From b64f2d4e4ff815d62ea0833c86aa7fb642f27222 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 11:32:23 -0600 Subject: [PATCH 01/11] Init --- .nvmrc | 2 +- package-lock.json | 604 ++++++++++++++++-- .../grid-toolbar/src/js/dist/bundle/index.js | 195 ++++++ plugins/grid-toolbar/src/js/package.json | 61 ++ .../src/js/src/GridToolbarMiddleware.tsx | 46 ++ .../src/js/src/GridToolbarPanelMiddleware.tsx | 51 ++ .../src/js/src/GridToolbarPlugin.ts | 21 + plugins/grid-toolbar/src/js/src/index.ts | 6 + .../src/js/src/middlewareTypes.ts | 40 ++ plugins/grid-toolbar/src/js/tsconfig.json | 13 + plugins/grid-toolbar/src/js/vite.config.ts | 29 + plugins/manifest.json | 5 + 12 files changed, 1006 insertions(+), 67 deletions(-) create mode 100644 plugins/grid-toolbar/src/js/dist/bundle/index.js create mode 100644 plugins/grid-toolbar/src/js/package.json create mode 100644 plugins/grid-toolbar/src/js/src/GridToolbarMiddleware.tsx create mode 100644 plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx create mode 100644 plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts create mode 100644 plugins/grid-toolbar/src/js/src/index.ts create mode 100644 plugins/grid-toolbar/src/js/src/middlewareTypes.ts create mode 100644 plugins/grid-toolbar/src/js/tsconfig.json create mode 100644 plugins/grid-toolbar/src/js/vite.config.ts diff --git a/.nvmrc b/.nvmrc index 78a26fa51..f5603339e 100644 --- a/.nvmrc +++ b/.nvmrc @@ -1 +1 @@ -v24.10.0 +v24.14.1 \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index c2a355a0b..9ed7d4f1e 100644 --- a/package-lock.json +++ b/package-lock.json @@ -208,7 +208,6 @@ "version": "7.26.10", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.26.2", @@ -759,7 +758,6 @@ "version": "7.26.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.25.9" }, @@ -1553,7 +1551,6 @@ "version": "7.25.9", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.25.9", "@babel/helper-module-imports": "^7.25.9", @@ -2062,6 +2059,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -3688,6 +3686,10 @@ "resolved": "plugins/dashboard-object-viewer/src/js", "link": true }, + "node_modules/@deephaven/js-plugin-grid-toolbar": { + "resolved": "plugins/grid-toolbar/src/js", + "link": true + }, "node_modules/@deephaven/js-plugin-matplotlib": { "resolved": "plugins/matplotlib/src/js", "link": true @@ -4828,7 +4830,6 @@ "node_modules/@dnd-kit/core": { "version": "6.3.1", "license": "MIT", - "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -4865,6 +4866,7 @@ "version": "4.1.0", "dev": true, "license": "MIT", + "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" @@ -5388,7 +5390,6 @@ "node_modules/@fortawesome/fontawesome-svg-core": { "version": "6.7.2", "license": "MIT", - "peer": true, "dependencies": { "@fortawesome/fontawesome-common-types": "6.7.2" }, @@ -5399,7 +5400,6 @@ "node_modules/@fortawesome/react-fontawesome": { "version": "0.2.2", "license": "MIT", - "peer": true, "dependencies": { "prop-types": "^15.8.1" }, @@ -6425,6 +6425,7 @@ "node_modules/@jridgewell/source-map": { "version": "0.3.6", "license": "MIT", + "peer": true, "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25" @@ -6446,6 +6447,7 @@ "version": "1.0.3", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "buffer": "^6.0.3" } @@ -7917,7 +7919,6 @@ "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@octokit/auth-token": "^4.0.0", "@octokit/graphql": "^7.1.0", @@ -8074,6 +8075,186 @@ "@octokit/openapi-types": "^24.2.0" } }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.5.1.tgz", + "integrity": "sha512-KF8+j9nNbUN8vzOFDpRMsaKBHZ/mcjEjMToVMJOhTozkDonQFFrRcfdLWn6yWKCmJKmdVxSgHiYvTCef4/qcBA==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.5.1.tgz", + "integrity": "sha512-eAzPv5osDmZyBhou8PoF4i6RQXAfeKL9tjb3QzYuccXFMQU0ruIc/POh30ePnaOyD1UXdlKguHBmsTs53tVoPw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.5.1.tgz", + "integrity": "sha512-1ZXDthrnNmwv10A0/3AJNZ9JGlzrF82i3gNQcWOzd7nJ8aj+ILyW1MTxVk35Db0u91oD5Nlk9MBiujMlwmeXZg==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.5.1.tgz", + "integrity": "sha512-SI4eljM7Flp9yPuKi8W0ird8TI/JK6CSxju3NojVI6BjHsTyK7zxA9urjVjEKJ5MBYC+bLmMcbAWlZ+rFkLpJQ==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.5.1.tgz", + "integrity": "sha512-RCdZlEyTs8geyBkkcnPWvtXLY44BCeZKmGYRtSgtwwnHR4dxfHRG3gR99XdMEdQ7KeiDdasJwwvNSF5jKtDwdA==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.5.1.tgz", + "integrity": "sha512-6E+m/Mm1t1yhB8X412stiKFG3XykmgdIOqhjWj+VL8oHkKABfu/gjFj8DvLrYVHSBNC+/u5PeNrujiSQ1zwd1Q==", + "cpu": [ + "arm" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.5.1.tgz", + "integrity": "sha512-LrGp+f02yU3BN9A+DGuY3v3bmnFUggAITBGriZHUREfNEzZh/GO06FF5u2kx8x+GBEUYfyTGamol4j3m9ANe8w==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.5.1.tgz", + "integrity": "sha512-cFOjABi92pMYRXS7AcQv9/M1YuKRw8SZniCDw0ssQb/noPkRzA+HBDkwmyOJYp5wXcsTrhxO0zq1U11cK9jsFg==", + "cpu": [ + "arm64" + ], + "dev": true, + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, "node_modules/@parcel/watcher-linux-x64-glibc": { "version": "2.5.1", "cpu": [ @@ -8112,6 +8293,69 @@ "url": "https://opencollective.com/parcel" } }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.5.1.tgz", + "integrity": "sha512-RFzklRvmc3PkjKjry3hLF9wD7ppR4AKcWNzH7kXR7GUe0Igb3Nz8fyPwtZCSquGrhU5HhUNDr/mKBqj7tqA2Vw==", + "cpu": [ + "arm64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-ia32": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-ia32/-/watcher-win32-ia32-2.5.1.tgz", + "integrity": "sha512-c2KkcVN+NJmuA7CGlaGD1qJh1cLfDnQsHjE89E60vUEMlqduHGCdCLJCID5geFVM0dOtA3ZiIO8BoEQmzQVfpQ==", + "cpu": [ + "ia32" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.5.1", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.5.1.tgz", + "integrity": "sha512-9lHBdJITeNR++EvSQVUcaZoWupyHfXe1jZvGZ06O/5MflPcuPLtEphScIBL+AiCWBO46tDSHzWyD0uDmmZqsgA==", + "cpu": [ + "x64" + ], + "dev": true, + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, "node_modules/@pkgjs/parseargs": { "version": "0.11.0", "dev": true, @@ -8125,6 +8369,7 @@ "version": "0.1.1", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": "^12.20.0 || ^14.18.0 || >=16.0.0" }, @@ -9912,7 +10157,6 @@ "node_modules/@react-spectrum/provider": { "version": "3.10.3", "license": "Apache-2.0", - "peer": true, "dependencies": { "@react-aria/i18n": "^3.12.7", "@react-aria/overlays": "^3.26.1", @@ -12206,6 +12450,7 @@ "node_modules/@types/eslint": { "version": "9.6.1", "license": "MIT", + "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -12214,6 +12459,7 @@ "node_modules/@types/eslint-scope": { "version": "3.7.7", "license": "MIT", + "peer": true, "dependencies": { "@types/eslint": "*", "@types/estree": "*" @@ -12417,7 +12663,6 @@ "node_modules/@types/node": { "version": "20.17.24", "license": "MIT", - "peer": true, "dependencies": { "undici-types": "~6.19.2" } @@ -12459,7 +12704,6 @@ "node_modules/@types/react": { "version": "17.0.83", "license": "MIT", - "peer": true, "dependencies": { "@types/prop-types": "*", "@types/scheduler": "^0.16", @@ -12616,7 +12860,6 @@ "version": "5.62.0", "dev": true, "license": "BSD-2-Clause", - "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.62.0", "@typescript-eslint/types": "5.62.0", @@ -12801,6 +13044,7 @@ "node_modules/@webassemblyjs/ast": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/helper-numbers": "1.13.2", "@webassemblyjs/helper-wasm-bytecode": "1.13.2" @@ -12808,19 +13052,23 @@ }, "node_modules/@webassemblyjs/floating-point-hex-parser": { "version": "1.13.2", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@webassemblyjs/helper-api-error": { "version": "1.13.2", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@webassemblyjs/helper-buffer": { "version": "1.14.1", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@webassemblyjs/helper-numbers": { "version": "1.13.2", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/floating-point-hex-parser": "1.13.2", "@webassemblyjs/helper-api-error": "1.13.2", @@ -12829,11 +13077,13 @@ }, "node_modules/@webassemblyjs/helper-wasm-bytecode": { "version": "1.13.2", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@webassemblyjs/helper-wasm-section": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -12844,6 +13094,7 @@ "node_modules/@webassemblyjs/ieee754": { "version": "1.13.2", "license": "MIT", + "peer": true, "dependencies": { "@xtuc/ieee754": "^1.2.0" } @@ -12851,17 +13102,20 @@ "node_modules/@webassemblyjs/leb128": { "version": "1.13.2", "license": "Apache-2.0", + "peer": true, "dependencies": { "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/utf8": { "version": "1.13.2", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/@webassemblyjs/wasm-edit": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -12876,6 +13130,7 @@ "node_modules/@webassemblyjs/wasm-gen": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", @@ -12887,6 +13142,7 @@ "node_modules/@webassemblyjs/wasm-opt": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -12897,6 +13153,7 @@ "node_modules/@webassemblyjs/wasm-parser": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-api-error": "1.13.2", @@ -12909,6 +13166,7 @@ "node_modules/@webassemblyjs/wast-printer": { "version": "1.14.1", "license": "MIT", + "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@xtuc/long": "4.2.2" @@ -12916,11 +13174,13 @@ }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", - "license": "BSD-3-Clause" + "license": "BSD-3-Clause", + "peer": true }, "node_modules/@xtuc/long": { "version": "4.2.2", - "license": "Apache-2.0" + "license": "Apache-2.0", + "peer": true }, "node_modules/@yarnpkg/lockfile": { "version": "1.1.0", @@ -12999,7 +13259,6 @@ "node_modules/acorn": { "version": "8.14.1", "license": "MIT", - "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -13164,6 +13423,7 @@ "node_modules/ajv-formats": { "version": "2.1.1", "license": "MIT", + "peer": true, "dependencies": { "ajv": "^8.0.0" }, @@ -13179,6 +13439,7 @@ "node_modules/ajv-formats/node_modules/ajv": { "version": "8.17.1", "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -13192,7 +13453,8 @@ }, "node_modules/ajv-formats/node_modules/json-schema-traverse": { "version": "1.0.0", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/almost-equal": { "version": "1.1.0", @@ -13487,6 +13749,7 @@ "version": "2.0.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -13996,7 +14259,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001688", "electron-to-chromium": "^1.5.73", @@ -14194,6 +14456,7 @@ "version": "1.8.9", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "hookified": "^1.7.1", "keyv": "^5.3.1" @@ -14203,6 +14466,7 @@ "version": "5.3.2", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@keyv/serialize": "^1.0.3" } @@ -14380,6 +14644,7 @@ "node_modules/chrome-trace-event": { "version": "1.0.4", "license": "MIT", + "peer": true, "engines": { "node": ">=6.0" } @@ -14612,7 +14877,8 @@ "node_modules/colord": { "version": "2.9.3", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/columnify": { "version": "1.6.0", @@ -15039,6 +15305,7 @@ "version": "3.2.3", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12 || >=16" } @@ -15098,6 +15365,7 @@ "version": "3.1.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "mdn-data": "2.12.2", "source-map-js": "^1.0.1" @@ -15825,6 +16093,29 @@ "dev": true, "license": "MIT" }, + "node_modules/encoding": { + "version": "0.1.13", + "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", + "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", + "license": "MIT", + "optional": true, + "dependencies": { + "iconv-lite": "^0.6.2" + } + }, + "node_modules/encoding/node_modules/iconv-lite": { + "version": "0.6.3", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", + "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", + "license": "MIT", + "optional": true, + "dependencies": { + "safer-buffer": ">= 2.1.2 < 3.0.0" + }, + "engines": { + "node": ">=0.10.0" + } + }, "node_modules/end-of-stream": { "version": "1.4.4", "license": "MIT", @@ -15835,6 +16126,7 @@ "node_modules/enhanced-resolve": { "version": "5.18.1", "license": "MIT", + "peer": true, "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" @@ -16024,7 +16316,8 @@ }, "node_modules/es-module-lexer": { "version": "1.6.0", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/es-object-atoms": { "version": "1.1.1", @@ -16565,7 +16858,6 @@ "version": "8.57.1", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -16658,7 +16950,6 @@ "version": "8.3.0", "dev": true, "license": "MIT", - "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -16716,6 +17007,7 @@ "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.5.0.tgz", "integrity": "sha512-DEfpfuk+O/T5e9HBZOxocmwMuUGkvQQd5WRiMJF9kKNT9amByqOyGlWoAZAQiv0SZSy4GMtG1clmnvQA/RzA0A==", "dev": true, + "peer": true, "dependencies": { "debug": "^4.3.4", "enhanced-resolve": "^5.10.0", @@ -16741,6 +17033,7 @@ "resolved": "https://registry.npmjs.org/globby/-/globby-13.2.2.tgz", "integrity": "sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==", "dev": true, + "peer": true, "dependencies": { "dir-glob": "^3.0.1", "fast-glob": "^3.3.0", @@ -16760,6 +17053,7 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", "dev": true, + "peer": true, "engines": { "node": ">=12" }, @@ -16772,6 +17066,7 @@ "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", "dev": true, + "peer": true, "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" @@ -16847,7 +17142,6 @@ "version": "2.31.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", "array-includes": "^3.1.8", @@ -16922,7 +17216,6 @@ "version": "6.10.2", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "aria-query": "^5.3.2", "array-includes": "^3.1.8", @@ -16989,7 +17282,6 @@ "version": "7.37.4", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", @@ -17021,7 +17313,6 @@ "version": "4.6.2", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=10" }, @@ -17102,6 +17393,7 @@ "version": "2.1.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "eslint-visitor-keys": "^1.1.0" }, @@ -17116,6 +17408,7 @@ "version": "1.3.0", "dev": true, "license": "Apache-2.0", + "peer": true, "engines": { "node": ">=4" } @@ -17375,7 +17668,8 @@ "node_modules/fast-diff": { "version": "1.3.0", "dev": true, - "license": "Apache-2.0" + "license": "Apache-2.0", + "peer": true }, "node_modules/fast-glob": { "version": "3.3.3", @@ -17436,12 +17730,14 @@ "url": "https://opencollective.com/fastify" } ], - "license": "BSD-3-Clause" + "license": "BSD-3-Clause", + "peer": true }, "node_modules/fastest-levenshtein": { "version": "1.0.16", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4.9.1" } @@ -18054,6 +18350,7 @@ "version": "4.10.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "resolve-pkg-maps": "^1.0.0" }, @@ -18240,12 +18537,14 @@ }, "node_modules/glob-to-regexp": { "version": "0.4.1", - "license": "BSD-2-Clause" + "license": "BSD-2-Clause", + "peer": true }, "node_modules/global-modules": { "version": "2.0.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "global-prefix": "^3.0.0" }, @@ -18257,6 +18556,7 @@ "version": "3.0.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "ini": "^1.3.5", "kind-of": "^6.0.2", @@ -18270,6 +18570,7 @@ "version": "1.3.1", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "isexe": "^2.0.0" }, @@ -18361,7 +18662,8 @@ "node_modules/globjoin": { "version": "0.1.4", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/glsl-inject-defines": { "version": "1.0.3", @@ -18831,7 +19133,8 @@ "node_modules/hookified": { "version": "1.8.1", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/hosted-git-info": { "version": "9.0.2", @@ -18879,6 +19182,7 @@ "version": "3.3.1", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" }, @@ -19529,6 +19833,7 @@ "version": "5.0.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -19860,7 +20165,6 @@ "version": "29.7.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@jest/core": "^29.7.0", "@jest/types": "^29.6.3", @@ -20904,8 +21208,7 @@ }, "node_modules/jquery": { "version": "3.7.1", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/js-cookie": { "version": "3.0.5", @@ -21226,7 +21529,8 @@ "node_modules/known-css-properties": { "version": "0.35.0", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/language-subtag-registry": { "version": "0.3.23", @@ -21842,6 +22146,7 @@ "node_modules/loader-runner": { "version": "4.3.0", "license": "MIT", + "peer": true, "engines": { "node": ">=6.11.5" } @@ -21909,7 +22214,8 @@ "node_modules/lodash.truncate": { "version": "4.4.2", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/log-symbols": { "version": "4.1.0", @@ -22194,6 +22500,7 @@ "version": "2.1.3", "dev": true, "license": "MIT", + "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" @@ -22415,7 +22722,8 @@ "node_modules/mdn-data": { "version": "2.12.2", "dev": true, - "license": "CC0-1.0" + "license": "CC0-1.0", + "peer": true }, "node_modules/memoize-one": { "version": "5.2.1", @@ -24362,7 +24670,6 @@ "dev": true, "hasInstallScript": true, "license": "MIT", - "peer": true, "dependencies": { "@napi-rs/wasm-runtime": "0.2.4", "@yarnpkg/lockfile": "^1.1.0", @@ -25526,7 +25833,6 @@ "node_modules/plotly.js": { "version": "2.35.3", "license": "MIT", - "peer": true, "dependencies": { "@plotly/d3": "3.8.2", "@plotly/d3-sankey": "0.7.2", @@ -25598,7 +25904,6 @@ "node_modules/popper.js": { "version": "1.16.1", "license": "MIT", - "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -25628,7 +25933,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -25714,7 +26018,8 @@ "node_modules/postcss-resolve-nested-selector": { "version": "0.1.6", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/postcss-safe-parser": { "version": "7.0.1", @@ -25734,6 +26039,7 @@ } ], "license": "MIT", + "peer": true, "engines": { "node": ">=18.0" }, @@ -25747,7 +26053,6 @@ "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -25792,7 +26097,6 @@ "version": "3.0.0", "dev": true, "license": "MIT", - "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -25807,6 +26111,7 @@ "version": "1.0.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-diff": "^1.1.2" }, @@ -26077,6 +26382,7 @@ "node_modules/randombytes": { "version": "2.1.0", "license": "MIT", + "peer": true, "dependencies": { "safe-buffer": "^5.1.0" } @@ -26084,7 +26390,6 @@ "node_modules/react": { "version": "17.0.2", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1" @@ -26211,7 +26516,6 @@ "node_modules/react-dom": { "version": "17.0.2", "license": "MIT", - "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -26306,7 +26610,6 @@ "node_modules/react-redux": { "version": "7.2.9", "license": "MIT", - "peer": true, "dependencies": { "@babel/runtime": "^7.15.4", "@types/react-redux": "^7.1.20", @@ -26670,7 +26973,6 @@ "node_modules/redux": { "version": "4.2.1", "license": "MIT", - "peer": true, "dependencies": { "@babel/runtime": "^7.9.2" } @@ -26755,6 +27057,7 @@ "version": "3.2.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" }, @@ -27228,6 +27531,7 @@ "node_modules/require-from-string": { "version": "2.0.2", "license": "MIT", + "peer": true, "engines": { "node": ">=0.10.0" } @@ -27285,6 +27589,7 @@ "version": "1.0.0", "dev": true, "license": "MIT", + "peer": true, "funding": { "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } @@ -27776,6 +28081,7 @@ "node_modules/schema-utils": { "version": "4.3.0", "license": "MIT", + "peer": true, "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", @@ -27808,6 +28114,7 @@ "node_modules/schema-utils/node_modules/ajv-keywords": { "version": "5.1.0", "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3" }, @@ -27817,7 +28124,8 @@ }, "node_modules/schema-utils/node_modules/json-schema-traverse": { "version": "1.0.0", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/semver": { "version": "6.3.1", @@ -27830,6 +28138,7 @@ "node_modules/serialize-javascript": { "version": "6.0.2", "license": "BSD-3-Clause", + "peer": true, "dependencies": { "randombytes": "^2.1.0" } @@ -28050,6 +28359,7 @@ "version": "4.0.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", @@ -28599,6 +28909,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3", @@ -28660,6 +28971,7 @@ } ], "license": "MIT-0", + "peer": true, "engines": { "node": ">=18" }, @@ -28670,12 +28982,14 @@ "node_modules/stylelint/node_modules/balanced-match": { "version": "2.0.0", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/stylelint/node_modules/cosmiconfig": { "version": "9.0.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", @@ -28701,6 +29015,7 @@ "version": "10.0.7", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "flat-cache": "^6.1.7" } @@ -28709,6 +29024,7 @@ "version": "6.1.7", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cacheable": "^1.8.9", "flatted": "^3.3.3", @@ -28719,6 +29035,7 @@ "version": "7.0.3", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">= 4" } @@ -28727,6 +29044,7 @@ "version": "13.2.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=18" }, @@ -28738,6 +29056,7 @@ "version": "5.0.0", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=8" } @@ -28746,6 +29065,7 @@ "version": "4.1.0", "dev": true, "license": "ISC", + "peer": true, "engines": { "node": ">=14" }, @@ -28757,6 +29077,7 @@ "version": "5.0.1", "dev": true, "license": "ISC", + "peer": true, "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" @@ -28795,6 +29116,7 @@ "version": "3.2.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "has-flag": "^4.0.0", "supports-color": "^7.0.0" @@ -28850,7 +29172,8 @@ }, "node_modules/svg-tags": { "version": "1.0.0", - "dev": true + "dev": true, + "peer": true }, "node_modules/symbol-tree": { "version": "3.2.4", @@ -28860,6 +29183,7 @@ "version": "0.9.2", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" @@ -28875,6 +29199,7 @@ "version": "6.9.0", "dev": true, "license": "BSD-3-Clause", + "peer": true, "dependencies": { "ajv": "^8.0.1", "lodash.truncate": "^4.4.2", @@ -28890,6 +29215,7 @@ "version": "8.17.1", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -28904,11 +29230,13 @@ "node_modules/table/node_modules/json-schema-traverse": { "version": "1.0.0", "dev": true, - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/tapable": { "version": "2.2.1", "license": "MIT", + "peer": true, "engines": { "node": ">=6" } @@ -29046,6 +29374,7 @@ "node_modules/terser-webpack-plugin": { "version": "5.3.14", "license": "MIT", + "peer": true, "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "jest-worker": "^27.4.5", @@ -29078,6 +29407,7 @@ "node_modules/terser-webpack-plugin/node_modules/jest-worker": { "version": "27.5.1", "license": "MIT", + "peer": true, "dependencies": { "@types/node": "*", "merge-stream": "^2.0.0", @@ -29090,6 +29420,7 @@ "node_modules/terser-webpack-plugin/node_modules/supports-color": { "version": "8.1.1", "license": "MIT", + "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -29103,6 +29434,7 @@ "node_modules/terser/node_modules/source-map-support": { "version": "0.5.21", "license": "MIT", + "peer": true, "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" @@ -29252,7 +29584,6 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12" }, @@ -29594,7 +29925,6 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, - "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -30070,7 +30400,6 @@ "version": "5.4.14", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -30172,6 +30501,7 @@ "node_modules/watchpack": { "version": "2.4.2", "license": "MIT", + "peer": true, "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" @@ -30264,13 +30594,15 @@ "node_modules/webpack-sources": { "version": "3.2.3", "license": "MIT", + "peer": true, "engines": { "node": ">=10.13.0" } }, "node_modules/webpack/node_modules/json-parse-even-better-errors": { "version": "2.3.1", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/whatwg-encoding": { "version": "2.0.0", @@ -31014,6 +31346,148 @@ "typescript": "^5.2.2" } }, + "plugins/grid-toolbar/src/js": { + "name": "@deephaven/js-plugin-grid-toolbar", + "version": "0.1.0", + "license": "Apache-2.0", + "dependencies": { + "@deephaven/components": "^0.106.0", + "@deephaven/icons": "^0.106.0", + "@deephaven/log": "^0.106.2", + "@deephaven/plugin": "^0.106.4" + }, + "devDependencies": { + "@types/react": "^17.0.2", + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "peerDependencies": { + "react": "^17.0.2 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.2 || ^18.0.0 || ^19.0.0" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/components": { + "version": "0.106.2", + "resolved": "https://registry.npmjs.org/@deephaven/components/-/components-0.106.2.tgz", + "integrity": "sha512-nQz3o2ty95SrT6+mm8BNaDAKK5jhPJdTOhxyzMUmMEJWTBSxb53hvfzP/760hpn9r5S25FqFLZc/heVZXVJ4Aw==", + "license": "Apache-2.0", + "dependencies": { + "@adobe/react-spectrum": "3.38.0", + "@deephaven/icons": "^0.106.0", + "@deephaven/log": "^0.106.2", + "@deephaven/react-hooks": "^0.106.2", + "@deephaven/utils": "^0.106.0", + "@fortawesome/fontawesome-svg-core": "^6.2.1", + "@fortawesome/react-fontawesome": "^0.2.0", + "@internationalized/date": "^3.5.5", + "@react-spectrum/theme-default": "^3.5.1", + "@react-spectrum/toast": "^3.0.0-beta.16", + "@react-spectrum/utils": "^3.11.5", + "@react-types/combobox": "3.13.1", + "@react-types/radio": "^3.8.1", + "@react-types/shared": "^3.22.1", + "@react-types/textfield": "^3.9.1", + "bootstrap": "4.6.2", + "classnames": "^2.3.1", + "event-target-shim": "^6.0.2", + "lodash.clamp": "^4.0.3", + "lodash.debounce": "^4.0.8", + "lodash.flatten": "^4.4.0", + "memoizee": "^0.4.15", + "nanoid": "^5.0.7", + "popper.js": "^1.16.1", + "prop-types": "^15.7.2", + "react-beautiful-dnd": "^13.1.0", + "react-transition-group": "^4.4.2", + "react-virtualized-auto-sizer": "1.0.6", + "react-window": "^1.8.6" + }, + "engines": { + "node": ">=10" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0", + "react-is": ">=16.8.0" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/components/node_modules/@react-types/combobox": { + "version": "3.13.1", + "resolved": "https://registry.npmjs.org/@react-types/combobox/-/combobox-3.13.1.tgz", + "integrity": "sha512-7xr+HknfhReN4QPqKff5tbKTe2kGZvH+DGzPYskAtb51FAAiZsKo+WvnNAvLwg3kRoC9Rkn4TAiVBp/HgymRDw==", + "license": "Apache-2.0", + "dependencies": { + "@react-types/shared": "^3.26.0" + }, + "peerDependencies": { + "react": "^16.8.0 || ^17.0.0-rc.1 || ^18.0.0 || ^19.0.0-rc.1" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/icons": { + "version": "0.106.0", + "resolved": "https://registry.npmjs.org/@deephaven/icons/-/icons-0.106.0.tgz", + "integrity": "sha512-I41Le5SkNrvg2v29ylBHWFsKeep+HxlfJ5fKvAaU67c8Z0J6PsXzOZ8WcwsPkbTdmOf2RIdKgozUMLSVjzk+YQ==", + "license": "Apache-2.0", + "dependencies": { + "@fortawesome/fontawesome-common-types": "^6.1.1" + }, + "peerDependencies": { + "@fortawesome/fontawesome-svg-core": "^6.2.1", + "@fortawesome/react-fontawesome": "^0.2.0" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/jsapi-types": { + "version": "1.0.0-dev0.40.9", + "resolved": "https://registry.npmjs.org/@deephaven/jsapi-types/-/jsapi-types-1.0.0-dev0.40.9.tgz", + "integrity": "sha512-NwMxFmNCnRV4/2+MdN/8vUGiEtXFgL1K/+iXTKKvi+Brje5JHOSCn2miCKR9tAn0LNb/UdmJq+DSIZqvz8cU/Q==", + "license": "Apache-2.0" + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/log": { + "version": "0.106.2", + "resolved": "https://registry.npmjs.org/@deephaven/log/-/log-0.106.2.tgz", + "integrity": "sha512-0yX5zrT51WDZnAKMlr4Lz4F/GYlsAb0YUq0sd3cSRclqD4OKmJrk57Ev8J4D23Rg4jQBwKunmQvdUatdTKcAHg==", + "license": "Apache-2.0", + "dependencies": { + "event-target-shim": "^6.0.2", + "jszip": "^3.10.1" + }, + "engines": { + "node": ">=16" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/plugin": { + "version": "0.106.4", + "resolved": "https://registry.npmjs.org/@deephaven/plugin/-/plugin-0.106.4.tgz", + "integrity": "sha512-yjnKaBbYJk2Jozv8nTb9UCPv9zAs31SglNeeX1CCRGbk0u3U5Mo8e2KgsLJPszOHqxxMBgrtCRnbE5w9BYAN1w==", + "license": "Apache-2.0", + "dependencies": { + "@deephaven/components": "^0.106.2", + "@deephaven/golden-layout": "^0.106.2", + "@deephaven/grid": "^0.106.3", + "@deephaven/icons": "^0.106.0", + "@deephaven/iris-grid": "^0.106.4", + "@deephaven/jsapi-types": "^1.0.0-dev0.37.2", + "@deephaven/log": "^0.106.2", + "@deephaven/react-hooks": "^0.106.2", + "@fortawesome/fontawesome-common-types": "^6.1.1", + "@fortawesome/react-fontawesome": "^0.2.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/utils": { + "version": "0.106.0", + "resolved": "https://registry.npmjs.org/@deephaven/utils/-/utils-0.106.0.tgz", + "integrity": "sha512-P5EsEl/rtA/KGZDQu8FDtovERRp/muRfJgrPunZdQy9stWSW0zYBFRHnLZCEbeETdduP/q902ZIOw77WSATqCw==", + "license": "Apache-2.0", + "engines": { + "node": ">=16" + } + }, "plugins/matplotlib/src/js": { "name": "@deephaven/js-plugin-matplotlib", "version": "0.5.0", @@ -32441,8 +32915,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "plugins/plotly-express/src/js/node_modules/@deephaven/dashboard": { "version": "1.17.1", @@ -32756,8 +33229,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "plugins/plotly-express/src/js/node_modules/@deephaven/dashboard-core-plugins/node_modules/@deephaven/jsapi-components": { "version": "1.17.0", @@ -33262,8 +33734,7 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT", - "peer": true + "license": "MIT" }, "plugins/plotly-express/src/js/node_modules/@deephaven/redux": { "version": "1.17.0", @@ -33486,7 +33957,8 @@ "version": "0.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT" + "license": "MIT", + "peer": true }, "plugins/plotly-express/src/js/node_modules/unist-util-find-after": { "version": "4.0.1", diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js new file mode 100644 index 000000000..c7c58819f --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/bundle/index.js @@ -0,0 +1,195 @@ +"use strict"; +Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); +const plugin = require("@deephaven/plugin"); +const require$$1 = require("react"); +const Log = require("@deephaven/log"); +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production_min = {}; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; +function toObject(val) { + if (val === null || val === void 0) { + throw new TypeError("Object.assign cannot be called with null or undefined"); + } + return Object(val); +} +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + var test1 = new String("abc"); + test1[5] = "de"; + if (Object.getOwnPropertyNames(test1)[0] === "5") { + return false; + } + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2["_" + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { + return test2[n2]; + }); + if (order2.join("") !== "0123456789") { + return false; + } + var test3 = {}; + "abcdefghijklmnopqrst".split("").forEach(function(letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { + return false; + } + return true; + } catch (err) { + return false; + } +} +shouldUseNative() ? Object.assign : function(target, source) { + var from; + var to = toObject(target); + var symbols; + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + return to; +}; +/** @license React v17.0.2 + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var f = require$$1, g = 60103; +reactJsxRuntime_production_min.Fragment = 60107; +if ("function" === typeof Symbol && Symbol.for) { + var h = Symbol.for; + g = h("react.element"); + reactJsxRuntime_production_min.Fragment = h("react.fragment"); +} +var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; +function q(c, a, k) { + var b, d = {}, e = null, l = null; + void 0 !== k && (e = "" + k); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (l = a.ref); + for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); + if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); + return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; +} +reactJsxRuntime_production_min.jsx = q; +reactJsxRuntime_production_min.jsxs = q; +{ + jsxRuntime.exports = reactJsxRuntime_production_min; +} +var jsxRuntimeExports = jsxRuntime.exports; +const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar"); +function GridToolbarMiddleware({ + Component, + ...props +}) { + const handleExport = require$$1.useCallback(() => { + log$1.info("Export clicked"); + }, []); + const handleResetFilters = require$$1.useCallback(() => { + log$1.info("[0] Reset Filters clicked", props, Component); + }, [props, Component]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleExport, + children: "Export" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) + ] }); +} +const log = Log.module("@deephaven/js-plugin-grid-toolbar"); +const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; +function GridToolbarPanelMiddleware({ + Component, + glEventHub, + ...props +}) { + const handleExport = require$$1.useCallback(() => { + log.info("Export clicked"); + }, []); + const handleResetFilters = require$$1.useCallback(() => { + log.info("[0] Reset Filters clicked", props, Component); + glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); + }, [glEventHub, props, Component]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleExport, + children: "Export" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { glEventHub, ...props }) }) + ] }); +} +const GridToolbarPlugin = { + name: "@deephaven/js-plugin-grid-toolbar", + type: plugin.PluginType.WIDGET_PLUGIN, + supportedTypes: [ + "Table", + "TreeTable", + "HierarchicalTable", + "PartitionedTable" + ], + component: GridToolbarMiddleware, + panelComponent: GridToolbarPanelMiddleware, + isMiddleware: true +}; +exports.GridToolbarMiddleware = GridToolbarMiddleware; +exports.GridToolbarPlugin = GridToolbarPlugin; +exports.default = GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/package.json b/plugins/grid-toolbar/src/js/package.json new file mode 100644 index 000000000..d535a52f3 --- /dev/null +++ b/plugins/grid-toolbar/src/js/package.json @@ -0,0 +1,61 @@ +{ + "name": "@deephaven/js-plugin-grid-toolbar", + "version": "0.1.0", + "description": "Deephaven Grid Toolbar middleware plugin - adds a toolbar to table widgets", + "keywords": [ + "Deephaven", + "plugin", + "deephaven-js-plugin", + "grid-toolbar", + "middleware" + ], + "author": "Deephaven Data Labs LLC", + "license": "Apache-2.0", + "main": "dist/bundle/index.js", + "repository": { + "type": "git", + "url": "git+https://github.com/deephaven/deephaven-plugins" + }, + "type": "module", + "exports": { + ".": { + "import": "./dist/index.js", + "require": "./dist/bundle/index.js", + "default": "./dist/bundle/index.js" + }, + "./*.js": "./dist/*.js", + "./*": "./dist/*.js" + }, + "types": "dist/index", + "bugs": { + "url": "https://github.com/deephaven/deephaven-plugins/issues" + }, + "homepage": "https://github.com/deephaven/deephaven-plugins", + "scripts": { + "start": "vite build --watch", + "build": "run-s build:*", + "build:transpile": "tsc", + "build:bundle": "vite build" + }, + "devDependencies": { + "@types/react": "^17.0.2", + "react": "^17.0.2", + "react-dom": "^17.0.2" + }, + "peerDependencies": { + "react": "^17.0.2 || ^18.0.0 || ^19.0.0", + "react-dom": "^17.0.2 || ^18.0.0 || ^19.0.0" + }, + "dependencies": { + "@deephaven/components": "^0.106.0", + "@deephaven/icons": "^0.106.0", + "@deephaven/log": "^0.106.2", + "@deephaven/plugin": "^0.106.4" + }, + "publishConfig": { + "access": "public" + }, + "files": [ + "dist" + ] +} diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarMiddleware.tsx new file mode 100644 index 000000000..690a19c48 --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/GridToolbarMiddleware.tsx @@ -0,0 +1,46 @@ +import { useCallback } from 'react'; +import Log from '@deephaven/log'; +// TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges +import type { WidgetMiddlewareComponentProps } from './middlewareTypes'; + +const log = Log.module('@deephaven/js-plugin-grid-toolbar'); + +export function GridToolbarMiddleware({ + Component, + ...props +}: WidgetMiddlewareComponentProps): JSX.Element { + const handleExport = useCallback(() => { + log.info('Export clicked'); + }, []); + + const handleResetFilters = useCallback(() => { + log.info('[0] Reset Filters clicked', props, Component); + }, [props, Component]); + + return ( +
+
+ + +
+
+ {/* eslint-disable-next-line react/jsx-props-no-spreading */} + +
+
+ ); +} + +export default GridToolbarMiddleware; diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx new file mode 100644 index 000000000..215fdf93b --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -0,0 +1,51 @@ +import { useCallback } from 'react'; +import Log from '@deephaven/log'; +// TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges +import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; + +const log = Log.module('@deephaven/js-plugin-grid-toolbar'); + +// Matches InputFilterEvent.CLEAR_ALL_FILTERS from @deephaven/dashboard-core-plugins +const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; + +export function GridToolbarPanelMiddleware({ + Component, + glEventHub, + ...props +}: WidgetMiddlewarePanelProps): JSX.Element { + const handleExport = useCallback(() => { + log.info('Export clicked'); + }, []); + + const handleResetFilters = useCallback(() => { + log.info('[0] Reset Filters clicked', props, Component); + glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); + }, [glEventHub, props, Component]); + + return ( +
+
+ + +
+
+ {/* eslint-disable-next-line react/jsx-props-no-spreading */} + +
+
+ ); +} + +export default GridToolbarPanelMiddleware; diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts b/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts new file mode 100644 index 000000000..49145d6f7 --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts @@ -0,0 +1,21 @@ +import { PluginType } from '@deephaven/plugin'; +// TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges +import type { WidgetMiddlewarePlugin } from './middlewareTypes'; +import { GridToolbarMiddleware } from './GridToolbarMiddleware'; +import { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; + +export const GridToolbarPlugin: WidgetMiddlewarePlugin = { + name: '@deephaven/js-plugin-grid-toolbar', + type: PluginType.WIDGET_PLUGIN, + supportedTypes: [ + 'Table', + 'TreeTable', + 'HierarchicalTable', + 'PartitionedTable', + ], + component: GridToolbarMiddleware, + panelComponent: GridToolbarPanelMiddleware, + isMiddleware: true, +}; + +export default GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/src/index.ts b/plugins/grid-toolbar/src/js/src/index.ts new file mode 100644 index 000000000..b2fde617c --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/index.ts @@ -0,0 +1,6 @@ +import { GridToolbarPlugin } from './GridToolbarPlugin'; + +export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPlugin } from './GridToolbarPlugin'; + +export default GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/src/middlewareTypes.ts b/plugins/grid-toolbar/src/js/src/middlewareTypes.ts new file mode 100644 index 000000000..342f8cee7 --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/middlewareTypes.ts @@ -0,0 +1,40 @@ +/** + * Local type definitions for middleware plugin types. + * + * TODO: Delete this file after deephaven/web-client-ui#2660 is merged and + * @deephaven/plugin is updated with WidgetMiddlewarePlugin types. + * Replace imports with: import { type WidgetMiddlewarePlugin, type WidgetMiddlewareComponentProps } from '@deephaven/plugin'; + */ +import type { + WidgetComponentProps, + WidgetPanelProps, + WidgetPlugin, +} from '@deephaven/plugin'; + +/** + * Props passed to middleware components that wrap a base widget. + */ +export interface WidgetMiddlewareComponentProps + extends WidgetComponentProps { + /** The next component in the middleware chain. */ + Component: React.ComponentType>; +} + +/** + * Props passed to middleware panel components that wrap a base panel. + */ +export interface WidgetMiddlewarePanelProps + extends WidgetPanelProps { + /** The next panel component in the middleware chain. */ + Component: React.ComponentType>; +} + +/** + * A middleware plugin that wraps and enhances another widget plugin. + */ +export interface WidgetMiddlewarePlugin + extends Omit, 'component' | 'panelComponent'> { + isMiddleware: true; + component: React.ComponentType>; + panelComponent?: React.ComponentType>; +} diff --git a/plugins/grid-toolbar/src/js/tsconfig.json b/plugins/grid-toolbar/src/js/tsconfig.json new file mode 100644 index 000000000..ece69655d --- /dev/null +++ b/plugins/grid-toolbar/src/js/tsconfig.json @@ -0,0 +1,13 @@ +{ + "extends": "@deephaven/tsconfig", + "compilerOptions": { + "composite": false, + "rootDir": "src/", + "outDir": "dist/", + "types": [], + "emitDeclarationOnly": false, + "noEmit": false + }, + "include": ["src/**/*.ts", "src/**/*.tsx"], + "exclude": ["**/node_modules/**/*", "src/**/*.test.*", "dist/**/*"] +} diff --git a/plugins/grid-toolbar/src/js/vite.config.ts b/plugins/grid-toolbar/src/js/vite.config.ts new file mode 100644 index 000000000..c6120d13a --- /dev/null +++ b/plugins/grid-toolbar/src/js/vite.config.ts @@ -0,0 +1,29 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { defineConfig } from 'vite'; +import react from '@vitejs/plugin-react-swc'; + +// https://vitejs.dev/config/ +export default defineConfig(({ mode }) => ({ + build: { + minify: false, + outDir: 'dist/bundle', + lib: { + entry: './src/index.ts', + fileName: () => 'index.js', + formats: ['cjs'], + }, + rollupOptions: { + external: [ + 'react', + 'react-dom', + '@deephaven/components', + '@deephaven/icons', + '@deephaven/log', + '@deephaven/plugin', + ], + }, + }, + define: + mode === 'production' ? { 'process.env.NODE_ENV': '"production"' } : {}, + plugins: [react()], +})); diff --git a/plugins/manifest.json b/plugins/manifest.json index eb078b74e..d13fe5588 100644 --- a/plugins/manifest.json +++ b/plugins/manifest.json @@ -40,6 +40,11 @@ "name": "pivot", "version": "0.0.0", "main": "src/js/dist/index.js" + }, + { + "name": "grid-toolbar", + "version": "0.0.0", + "main": "src/js/dist/bundle/index.js" } ] } From ed9aa145b2cd7dc48c69310d2f48cf6ae1c49091 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 12:00:14 -0600 Subject: [PATCH 02/11] Component replacement POC --- plans/chart-builder-proof-of-concept.md | 136 + .../src/js/dist/bundle/Chart-DElXbH_b.cjs | 90838 ++++++++++++++++ .../src/js/dist/bundle/index-nioU_Oes.cjs | 12476 +++ .../grid-toolbar/src/js/dist/bundle/index.js | 197 +- .../grid-toolbar/src/js/dist/bundle/style.css | 88 + plugins/grid-toolbar/src/js/package.json | 2 + .../src/js/src/GridToolbarPanelMiddleware.tsx | 70 +- plugins/grid-toolbar/src/js/vite.config.ts | 2 + 8 files changed, 103606 insertions(+), 203 deletions(-) create mode 100644 plans/chart-builder-proof-of-concept.md create mode 100644 plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs create mode 100644 plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs create mode 100644 plugins/grid-toolbar/src/js/dist/bundle/style.css diff --git a/plans/chart-builder-proof-of-concept.md b/plans/chart-builder-proof-of-concept.md new file mode 100644 index 000000000..d19601460 --- /dev/null +++ b/plans/chart-builder-proof-of-concept.md @@ -0,0 +1,136 @@ +# Chart Builder Proof of Concept + +## Description + +Add an in-panel Chart toggle button to the `grid-toolbar` middleware plugin. Clicking "Chart" replaces the grid view with a line chart built from the first two columns of the table. Clicking "Grid" toggles back. + +## Problem / Feature Gap + +The `grid-toolbar` middleware plugin currently only provides a Reset Filters button. This proof of concept demonstrates that a middleware plugin can replace the panel's content entirely — not just augment it — by rendering a chart model in place of the grid. + +## Scope + +**In scope:** +- Rename "Export" button to "Chart" (toggles to "Grid" when chart is shown) +- On click: fetch the table, build a `LINE` chart from the first two columns (col[0] = x-axis, col[1] = y-axis), render it in-panel +- Toggle back to grid view on second click +- Graceful no-op if the table has fewer than 2 columns + +**Out of scope:** +- Chart type selection UI +- Column picker UI +- Opening the chart in a new Golden Layout panel +- Persistence of the chart/grid toggle state across reloads + +**Risks:** +- `ChartModelFactory.makeModelFromSettings` is async — the button must be disabled while the model is building to prevent double-clicks +- `FigureChartModel` wraps a live Deephaven figure and must be cleaned up on unmount + +## Technical Design + +### Dependencies + +Add to `plugins/grid-toolbar/src/js/package.json` `dependencies`: +```json +"@deephaven/chart": "^0.106.0", +"@deephaven/jsapi-bootstrap": "^0.106.0" +``` + +Add both to `vite.config.ts` `rollupOptions.external` so they are loaded from the host app bundle, not re-bundled. + +### GridToolbarPanelMiddleware.tsx Changes + +**New imports:** +```ts +import { useState, useEffect, useCallback } from 'react'; +import { Chart, ChartModel, ChartModelFactory } from '@deephaven/chart'; +import { useApi } from '@deephaven/jsapi-bootstrap'; +``` + +**New state:** +```ts +const dh = useApi(); +const [view, setView] = useState<'grid' | 'chart'>('grid'); +const [chartModel, setChartModel] = useState(null); +const [isBuilding, setIsBuilding] = useState(false); +``` + +**`handleChart` handler (replaces `handleExport`):** +```ts +const handleChart = useCallback(async () => { + if (view === 'chart') { + setView('grid'); + return; + } + setIsBuilding(true); + try { + const table = await fetch(); + if (table.columns.length < 2) return; + const settings = { + type: 'LINE', + series: [table.columns[1].name], + xAxis: table.columns[0].name, + }; + const model = await ChartModelFactory.makeModelFromSettings(dh, settings, table); + setChartModel(model); + setView('chart'); + } finally { + setIsBuilding(false); + } +}, [dh, fetch, view]); +``` + +**Cleanup:** +```ts +useEffect(() => { + return () => { + chartModel?.close(); + }; +}, [chartModel]); +``` + +**Render:** +```tsx + + +
+ {view === 'chart' && chartModel != null + ? + : } +
+``` + +### Key References + +| Concern | Answer | +|---|---| +| dh API in middleware | `useApi()` from `@deephaven/jsapi-bootstrap` — context provided at dashboard root | +| Chart model creation | `ChartModelFactory.makeModelFromSettings(dh, settings, table)` from `@deephaven/chart` | +| `settings.type` | String key of `dh.plot.SeriesPlotStyle` — use `'LINE'`, not the enum value | +| `fetch` return type | `() => Promise` for grid widgets | +| Chart component | `Chart` from `@deephaven/chart` (lazy-loaded) | +| Model cleanup | `FigureChartModel` — call `chartModel.close()` on unmount | + +### Affected Files + +- `plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx` +- `plugins/grid-toolbar/src/js/package.json` +- `plugins/grid-toolbar/src/js/vite.config.ts` + +## Verification + +1. `npm run build` in `plugins/grid-toolbar/src/js` — no build errors +2. Rebuild plugin, reload browser +3. Open a table with ≥2 columns — "Chart" button appears in toolbar +4. Click "Chart" — grid replaced by a line chart; col[0] = x-axis, col[1] = y-axis +5. Click "Grid" — chart replaced by grid; Reset Filters still works +6. Open a table with <2 columns — clicking "Chart" is a no-op (button re-enables, view unchanged) +7. Close panel — no console errors from leaked chart model or figure subscription + +## Research Appendix + +- `IrisGridEvent.CREATE_CHART` (string: `'IrisGridevent.CREATE_CHART'`) is the GL event bus mechanism used by `IrisGridPanel` to open a chart in a **new** GL panel via `ChartBuilderPlugin`. This approach was considered but rejected — the proof of concept renders the chart in-panel instead, which is simpler and demonstrates middleware panel content replacement. +- `LayoutUtils.getIdFromContainer(glContainer)` is the functional-component equivalent of `LayoutUtils.getIdFromPanel(this)` for getting the current panel's ID (available in `WidgetPanelProps`). +- `@deephaven/jsapi-bootstrap` `useApi()` is already used by `plugins/pivot`, `plugins/ag-grid`, and `plugins/python-remote-file-source` — the pattern is well established in this repo. diff --git a/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs b/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs new file mode 100644 index 000000000..a46c05798 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs @@ -0,0 +1,90838 @@ +"use strict"; +Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); +const React = require("react"); +const index$3 = require("./index-nioU_Oes.cjs"); +const icons = require("@deephaven/icons"); +const Log = require("@deephaven/log"); +const components = require("@deephaven/components"); +function _defineProperty$6(obj, key, value2) { + key = _toPropertyKey$6(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$6(arg) { + var key = _toPrimitive$6(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$6(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class TableColumnFormatter { + /** + * Validates format object + * @param dh JSAPI instance + * @param format Format object + * @returns true for valid object + */ + static isValid(dh, format2) { + return true; + } + /** + * Check if the given formats match + * @param formatA format object to check + * @param formatB format object to check + * @returns True if the formats match + */ + static isSameFormat(formatA, formatB) { + throw new Error("isSameFormat not implemented"); + } + /** + * Create and return a Format object + * @param label The label of the format object + * @param formatString Format string to use for the format + * @param type The type of column to use for this format + * @returns A format object + */ + static makeFormat(label, formatString, type) { + return { + label, + formatString, + type + }; + } + /** + * @param value The value to format + * @param format Optional format object with value transformation options + * @returns String the formatted text string of the value passed in. + */ + format(value2, format2) { + return ""; + } +} +_defineProperty$6(TableColumnFormatter, "TYPE_GLOBAL", "type-global"); +_defineProperty$6(TableColumnFormatter, "TYPE_CONTEXT_PRESET", "type-context-preset"); +_defineProperty$6(TableColumnFormatter, "TYPE_CONTEXT_CUSTOM", "type-context-custom"); +class BooleanColumnFormatter extends TableColumnFormatter { + format(value2) { + switch (value2) { + case 1: + case true: + return "true"; + case 0: + case false: + return "false"; + default: + return ""; + } + } +} +class CharColumnFormatter extends TableColumnFormatter { + format(value2) { + return String.fromCharCode(value2); + } +} +function _defineProperty$5(obj, key, value2) { + key = _toPropertyKey$5(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$5(arg) { + var key = _toPrimitive$5(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$5(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +var log$3 = Log.module("DateTimeColumnFormatter"); +class DateTimeColumnFormatter extends TableColumnFormatter { + /** + * Validates format object + * @param dh JSAPI instance + * @param format Format object + * @returns true for valid object + */ + static isValid(dh, format2) { + if (format2.formatString == null) { + return false; + } + try { + dh.i18n.DateTimeFormat.format(format2.formatString, /* @__PURE__ */ new Date()); + return true; + } catch (e) { + return false; + } + } + static makeFormat(label, formatString) { + var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; + return { + label, + formatString, + type + }; + } + /** + * Check if the given formats match + * @param formatA format object to check + * @param formatB format object to check + * @returns True if the formats match + */ + static isSameFormat(formatA, formatB) { + return formatA === formatB || formatA !== null && formatB !== null && formatA.type === formatB.type && formatA.formatString === formatB.formatString; + } + static makeGlobalFormatStringMap(showTimeZone, showTSeparator) { + var separator = showTSeparator ? "'T'" : " "; + var tz = showTimeZone ? " z" : ""; + return /* @__PURE__ */ new Map([["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd".concat(separator, "HH:mm:ss").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSS").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSSSSSSSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSSSSSSSS").concat(tz)]]); + } + static getGlobalFormats(showTimeZone, showTSeparator) { + var formatStringMap = DateTimeColumnFormatter.makeGlobalFormatStringMap(showTimeZone, showTSeparator); + return [...formatStringMap.keys()]; + } + static makeFormatStringMap(showTimeZone, showTSeparator) { + var separator = showTSeparator !== void 0 && showTSeparator ? "'T'" : " "; + var tz = showTimeZone !== void 0 && showTimeZone ? " z" : ""; + return /* @__PURE__ */ new Map([["yyyy-MM-dd", "yyyy-MM-dd".concat(tz)], ["MM-dd-yyyy", "MM-dd-yyyy".concat(tz)], ["HH:mm:ss", "HH:mm:ss".concat(tz)], ["HH:mm:ss.SSS", "HH:mm:ss.SSS".concat(tz)], ["HH:mm:ss.SSSSSSSSS", "HH:mm:ss.SSSSSSSSS".concat(tz)], ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd".concat(separator, "HH:mm:ss").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSS").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSSSSSSSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSSSSSSSS").concat(tz)]]); + } + static getFormats(showTimeZone, showTSeparator) { + var formatStringMap = DateTimeColumnFormatter.makeFormatStringMap(showTimeZone, showTSeparator); + return [...formatStringMap.keys()]; + } + constructor(dh) { + var { + timeZone: timeZoneParam = "", + showTimeZone = true, + showTSeparator = false, + defaultDateTimeFormatString = DateTimeColumnFormatter.DEFAULT_DATETIME_FORMAT_STRING + } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + super(); + _defineProperty$5(this, "dh", void 0); + _defineProperty$5(this, "dhTimeZone", void 0); + _defineProperty$5(this, "defaultDateTimeFormatString", void 0); + _defineProperty$5(this, "showTimeZone", void 0); + _defineProperty$5(this, "showTSeparator", void 0); + _defineProperty$5(this, "formatStringMap", void 0); + var timeZone = timeZoneParam || DateTimeColumnFormatter.DEFAULT_TIME_ZONE_ID; + try { + this.dhTimeZone = dh.i18n.TimeZone.getTimeZone(timeZone); + } catch (e) { + log$3.error("Unsupported time zone id", timeZone); + this.dhTimeZone = dh.i18n.TimeZone.getTimeZone(DateTimeColumnFormatter.DEFAULT_TIME_ZONE_ID); + } + this.dh = dh; + this.defaultDateTimeFormatString = defaultDateTimeFormatString; + this.showTimeZone = showTimeZone; + this.showTSeparator = showTSeparator; + this.formatStringMap = DateTimeColumnFormatter.makeFormatStringMap(showTimeZone, showTSeparator); + } + getEffectiveFormatString(baseFormatString) { + var _this$formatStringMap; + return (_this$formatStringMap = this.formatStringMap.get(baseFormatString)) !== null && _this$formatStringMap !== void 0 ? _this$formatStringMap : baseFormatString; + } + format(value2) { + var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var baseFormatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultDateTimeFormatString; + var formatString = this.getEffectiveFormatString(baseFormatString); + try { + return this.dh.i18n.DateTimeFormat.format(formatString, value2, this.dhTimeZone); + } catch (e) { + log$3.error("Invalid format arguments"); + } + return ""; + } +} +_defineProperty$5(DateTimeColumnFormatter, "DEFAULT_DATETIME_FORMAT_STRING", "yyyy-MM-dd HH:mm:ss.SSS"); +_defineProperty$5(DateTimeColumnFormatter, "DEFAULT_TIME_ZONE_ID", "America/New_York"); +function _defineProperty$4(obj, key, value2) { + key = _toPropertyKey$4(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$4(arg) { + var key = _toPrimitive$4(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$4(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +var log$2 = Log.module("DecimalColumnFormatter"); +class DecimalColumnFormatter extends TableColumnFormatter { + /** + * Validates format object + * @param dh JSAPI instance + * @param format Format object + * @returns true for valid object + */ + static isValid(dh, format2) { + if (format2.formatString == null) { + return false; + } + try { + dh.i18n.NumberFormat.format(format2.formatString, 0); + return true; + } catch (e) { + return false; + } + } + /** + * Create a DecimalColumnFormat object with the parameters specified + * @param label Label for the format + * @param formatString Format string for the format + * @param multiplier Optional multiplier for the formatter + * @param type Type of format created + * @returns DecimalColumnFormat object + */ + static makeFormat(label, formatString) { + var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; + var multiplier = arguments.length > 3 ? arguments[3] : void 0; + return { + label, + type, + formatString, + multiplier + }; + } + /** + * Convenient function to create a DecimalFormatObject with Preset type set + * @param label Label for this format object + * @param formatString Format string to use + * @param multiplier Multiplier to use + * @returns DecimalColumnFormat object + */ + static makePresetFormat(label) { + var formatString = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ""; + var multiplier = arguments.length > 2 ? arguments[2] : void 0; + return DecimalColumnFormatter.makeFormat(label, formatString, TableColumnFormatter.TYPE_CONTEXT_PRESET, multiplier); + } + /** + * Convenient function to create a DecimalFormatObject with a default 'Custom Format' label and Custom type + * @param formatString Format string to use + * @param multiplier Multiplier to use + * @returns DecimalColumnFormat object + */ + static makeCustomFormat() { + var formatString = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; + var multiplier = arguments.length > 1 ? arguments[1] : void 0; + return DecimalColumnFormatter.makeFormat("Custom Format", formatString, TableColumnFormatter.TYPE_CONTEXT_CUSTOM, multiplier); + } + /** + * Check if the given formats match + * @param formatA format object to check + * @param formatB format object to check + * @returns True if the formats match + */ + static isSameFormat(formatA, formatB) { + return formatA === formatB || formatA != null && formatB != null && formatA.type === formatB.type && formatA.formatString === formatB.formatString && formatA.multiplier === formatB.multiplier; + } + constructor(dh) { + var { + defaultFormatString = DecimalColumnFormatter.DEFAULT_FORMAT_STRING + } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + super(); + _defineProperty$4(this, "defaultFormatString", void 0); + _defineProperty$4(this, "dh", void 0); + this.dh = dh; + this.defaultFormatString = defaultFormatString; + } + /** + * Format a value with the provided format object + * @param valueParam Value to format + * @param format Format object + * @returns Formatted string + */ + format(valueParam) { + var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var formatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultFormatString; + var value2 = format2.multiplier != null && format2.multiplier !== 0 ? valueParam * format2.multiplier : valueParam; + try { + return this.dh.i18n.NumberFormat.format(formatString, value2); + } catch (e) { + log$2.error("Invalid format arguments"); + } + return ""; + } +} +_defineProperty$4(DecimalColumnFormatter, "DEFAULT_FORMAT_STRING", "###,##0.0000"); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_PERCENT", DecimalColumnFormatter.makePresetFormat("Percent", "##0.00%")); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_BASIS_POINTS", DecimalColumnFormatter.makePresetFormat("Basis Points", "###,##0 bp", 1e4)); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_THOUSANDS", DecimalColumnFormatter.makePresetFormat("Thousands", "##0.000 k", 1e-3)); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_MILLIONS", DecimalColumnFormatter.makePresetFormat("Millions", "###,##0.000 mm", 1e-6)); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_SCIENTIFIC_NOTATION", DecimalColumnFormatter.makePresetFormat("Scientific Notation", "0.0000E0")); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND", DecimalColumnFormatter.makePresetFormat("Round", "###,##0")); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND_TWO_DECIMALS", DecimalColumnFormatter.makePresetFormat("0.00", "###,##0.00")); +_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND_FOUR_DECIMALS", DecimalColumnFormatter.makePresetFormat("0.0000", "###,##0.0000")); +class DefaultColumnFormatter extends TableColumnFormatter { + format(value2) { + return "".concat(value2); + } +} +function _defineProperty$3(obj, key, value2) { + key = _toPropertyKey$3(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$3(arg) { + var key = _toPrimitive$3(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$3(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +var log$1 = Log.module("IntegerColumnFormatter"); +class IntegerColumnFormatter extends TableColumnFormatter { + /** + * Validates format object + * @param dh JSAPI instance + * @param format Format object + * @returns true for valid object + */ + static isValid(dh, format2) { + if (format2.formatString == null) { + return false; + } + try { + dh.i18n.NumberFormat.format(format2.formatString, 0); + return true; + } catch (e) { + return false; + } + } + /** + * Create an IntegerColumnFormat object with the parameters specified + * @param label Label for the format + * @param formatString Format string for the format + * @param multiplier Optional multiplier for the formatter + * @param type Type of format created + * @returns IntegerColumnFormat object + */ + static makeFormat(label, formatString) { + var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; + var multiplier = arguments.length > 3 ? arguments[3] : void 0; + return { + label, + type, + formatString, + multiplier + }; + } + /** + * Convenient function to create a IntegerFormatObject with Preset type set + * @param label Label for this format object + * @param formatString Format string to use + * @param multiplier Multiplier to use + * @returns IntegerColumnFormat object + */ + static makePresetFormat(label) { + var formatString = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ""; + var multiplier = arguments.length > 2 ? arguments[2] : void 0; + return IntegerColumnFormatter.makeFormat(label, formatString, TableColumnFormatter.TYPE_CONTEXT_PRESET, multiplier); + } + /** + * Convenient function to create a IntegerFormatObject with a default 'Custom Format' label and Custom type + * @param formatString Format string to use + * @param multiplier Multiplier to use + * @returns IntegerColumnFormat object + */ + static makeCustomFormat() { + var formatString = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; + var multiplier = arguments.length > 1 ? arguments[1] : void 0; + return IntegerColumnFormatter.makeFormat("Custom Format", formatString, TableColumnFormatter.TYPE_CONTEXT_CUSTOM, multiplier); + } + /** + * Check if the given formats match + * @param formatA format object to check + * @param formatB format object to check + * @returns True if the formats match + */ + static isSameFormat(formatA, formatB) { + return formatA === formatB || formatA != null && formatB != null && formatA.type === formatB.type && formatA.formatString === formatB.formatString && formatA.multiplier === formatB.multiplier; + } + constructor(dh) { + var { + defaultFormatString = IntegerColumnFormatter.DEFAULT_FORMAT_STRING + } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + super(); + _defineProperty$3(this, "dh", void 0); + _defineProperty$3(this, "defaultFormatString", void 0); + this.dh = dh; + this.defaultFormatString = defaultFormatString; + } + /** + * Format a value with the provided format object + * @param valueParam Value to format + * @param format Format object + * @returns Formatted string + */ + format(valueParam) { + var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; + var formatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultFormatString; + var value2 = format2.multiplier != null && format2.multiplier !== 0 ? valueParam * format2.multiplier : valueParam; + try { + return this.dh.i18n.NumberFormat.format(formatString, value2); + } catch (e) { + log$1.error("Invalid format arguments"); + } + return ""; + } +} +_defineProperty$3(IntegerColumnFormatter, "DEFAULT_FORMAT_STRING", "###,##0"); +_defineProperty$3(IntegerColumnFormatter, "FORMAT_THOUSANDS", IntegerColumnFormatter.makePresetFormat("Thousands", "##0.000 k", 1e-3)); +_defineProperty$3(IntegerColumnFormatter, "FORMAT_MILLIONS", IntegerColumnFormatter.makePresetFormat("Millions", "###,##0.000 mm", 1e-6)); +_defineProperty$3(IntegerColumnFormatter, "FORMAT_SCIENTIFIC_NOTATION", IntegerColumnFormatter.makePresetFormat("Scientific Notation", "0.0000E0")); +class StringColumnFormatter extends TableColumnFormatter { + format(value2) { + return value2; + } +} +function _defineProperty$2(obj, key, value2) { + key = _toPropertyKey$2(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$2(arg) { + var key = _toPrimitive$2(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$2(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class Formatter { + /** + * Converts FormattingRule[] to Map + * @param columnFormattingRules Array or column formatting rules + * @returns Map of columnName-to-format Maps indexed by normalized dataType + */ + static makeColumnFormatMap(columnFormattingRules) { + if (columnFormattingRules == null) { + return /* @__PURE__ */ new Map(); + } + return columnFormattingRules.reduce((map2, next) => { + var dataType = index$3.TableUtils.getNormalizedType(next.columnType); + if (dataType === null) { + return map2; + } + if (!map2.has(dataType)) { + map2.set(dataType, /* @__PURE__ */ new Map()); + } + var formatMap = map2.get(dataType); + formatMap === null || formatMap === void 0 ? void 0 : formatMap.set(next.columnName, next.format); + return map2; + }, /* @__PURE__ */ new Map()); + } + /** + * Creates a column formatting rule + * @param columnType Normalized data type + * @param columnName Column name + * @param format Format object + */ + static makeColumnFormattingRule(columnType, columnName, format2) { + return { + columnType, + columnName, + format: format2 + }; + } + /** + * @param dh JSAPI instance + * @param columnFormattingRules Optional array of column formatting rules + * @param dateTimeOptions Optional object with DateTime configuration + * @param decimalFormatOptions Optional object with Decimal configuration + * @param integerFormatOptions Optional object with Integer configuration + * @param truncateNumbersWithPound Determine if numbers should be truncated w/ repeating # instead of ellipsis at the end + */ + constructor(dh) { + var columnFormattingRules = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : []; + var dateTimeOptions = arguments.length > 2 ? arguments[2] : void 0; + var decimalFormatOptions = arguments.length > 3 ? arguments[3] : void 0; + var integerFormatOptions = arguments.length > 4 ? arguments[4] : void 0; + var truncateNumbersWithPound = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false; + var showEmptyStrings = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : true; + var showNullStrings = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : true; + _defineProperty$2(this, "defaultColumnFormatter", void 0); + _defineProperty$2(this, "typeFormatterMap", void 0); + _defineProperty$2(this, "columnFormatMap", void 0); + _defineProperty$2(this, "truncateNumbersWithPound", void 0); + _defineProperty$2(this, "showEmptyStrings", void 0); + _defineProperty$2(this, "showNullStrings", void 0); + this.defaultColumnFormatter = new DefaultColumnFormatter(); + this.typeFormatterMap = /* @__PURE__ */ new Map([[index$3.TableUtils.dataType.BOOLEAN, new BooleanColumnFormatter()], [index$3.TableUtils.dataType.CHAR, new CharColumnFormatter()], [index$3.TableUtils.dataType.DATETIME, new DateTimeColumnFormatter(dh, dateTimeOptions)], [index$3.TableUtils.dataType.DECIMAL, new DecimalColumnFormatter(dh, decimalFormatOptions)], [index$3.TableUtils.dataType.INT, new IntegerColumnFormatter(dh, integerFormatOptions)], [index$3.TableUtils.dataType.STRING, new StringColumnFormatter()]]); + this.columnFormatMap = Formatter.makeColumnFormatMap(columnFormattingRules); + this.truncateNumbersWithPound = truncateNumbersWithPound; + this.showEmptyStrings = showEmptyStrings; + this.showNullStrings = showNullStrings; + } + /** + * Gets columnFormatMap indexed by name for a given column type, creates new Map entry if necessary + * @param columnType column type + * @param createIfNecessary create new entry if true + * @returns Map of format strings indexed by column name or undefined if it doesn't exist + */ + getColumnFormatMapForType(columnType) { + var createIfNecessary = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; + var dataType = index$3.TableUtils.getNormalizedType(columnType); + if (dataType === null) { + return void 0; + } + if (createIfNecessary && !this.columnFormatMap.has(dataType)) { + this.columnFormatMap.set(dataType, /* @__PURE__ */ new Map()); + } + return this.columnFormatMap.get(dataType); + } + /** + * Gets a column format object for a given column type and name + * @param columnType column type + * @param columnName column name + * @returns format object or null for Default + */ + getColumnFormat(columnType, columnName) { + var _columnFormatMap$get; + var columnFormatMap = this.getColumnFormatMapForType(columnType); + return (_columnFormatMap$get = columnFormatMap === null || columnFormatMap === void 0 ? void 0 : columnFormatMap.get(columnName)) !== null && _columnFormatMap$get !== void 0 ? _columnFormatMap$get : null; + } + getColumnTypeFormatter(columnType) { + var dataType = index$3.TableUtils.getNormalizedType(columnType); + var columnTypeFormatter = this.defaultColumnFormatter; + if (dataType) { + var _this$typeFormatterMa; + columnTypeFormatter = (_this$typeFormatterMa = this.typeFormatterMap.get(dataType)) !== null && _this$typeFormatterMa !== void 0 ? _this$typeFormatterMa : columnTypeFormatter; + } + return columnTypeFormatter; + } + /** + * Gets formatted string for a given value, column type and name + * @param value Value to format + * @param columnType Column type used to determine the formatting settings + * @param columnName Column name used to determine the formatting settings + * @param formatOverride Format object passed to the formatter in place of the format defined in columnFormatMap + */ + getFormattedString(value2, columnType) { + var columnName = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ""; + var formatOverride = arguments.length > 3 ? arguments[3] : void 0; + if (value2 == null) { + return ""; + } + var formatter = this.getColumnTypeFormatter(columnType); + var format2 = formatOverride || this.getColumnFormat(columnType, columnName); + return formatter.format(value2, format2 !== null && format2 !== void 0 ? format2 : void 0); + } + /** + * Gets the timeZone name + * @returns The time zone name E.g. America/New_York + */ + get timeZone() { + var formatter = this.typeFormatterMap.get(index$3.TableUtils.dataType.DATETIME); + index$3.assertInstanceOf(formatter, DateTimeColumnFormatter); + return formatter.dhTimeZone.id; + } +} +function createFormatterFromSettings(dh, settings) { + var columnRules = getColumnFormats(settings); + var dateTimeOptions = getDateTimeFormatterOptions(settings); + var { + defaultDecimalFormatOptions, + defaultIntegerFormatOptions, + truncateNumbersWithPound, + showEmptyStrings, + showNullStrings + } = settings !== null && settings !== void 0 ? settings : {}; + return new Formatter(dh, columnRules, dateTimeOptions, defaultDecimalFormatOptions, defaultIntegerFormatOptions, truncateNumbersWithPound, showEmptyStrings, showNullStrings); +} +function getColumnFormats(settings) { + if (settings && settings.formatter) { + var { + formatter + } = settings; + return formatter; + } + return void 0; +} +function getDateTimeFormatterOptions(settings) { + return { + timeZone: settings === null || settings === void 0 ? void 0 : settings.timeZone, + defaultDateTimeFormatString: settings === null || settings === void 0 ? void 0 : settings.defaultDateTimeFormat, + showTimeZone: settings === null || settings === void 0 ? void 0 : settings.showTimeZone, + showTSeparator: settings === null || settings === void 0 ? void 0 : settings.showTSeparator + }; +} +function isCustomColumnFormatDefined(formatter, columnName, columnType) { + var columnFormat = formatter.getColumnFormat(columnType, columnName); + return columnFormat != null && (columnFormat.type === TableColumnFormatter.TYPE_CONTEXT_PRESET || columnFormat.type === TableColumnFormatter.TYPE_CONTEXT_CUSTOM); +} +const FormatterUtils = { + createFormatterFromSettings, + getColumnFormats, + getDateTimeFormatterOptions, + isCustomColumnFormatDefined +}; +function _defineProperty$1(e, r, t) { + return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey$1(t) { + var i = _toPrimitive$1(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive$1(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +class DownsamplingError extends Error { + constructor() { + super(...arguments); + _defineProperty$1(this, "isDownsamplingError", true); + } +} +var ChartThemeContext = /* @__PURE__ */ React.createContext(null); +function useContextOrThrow(context2) { + var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "No value available in context. Was code wrapped in a provider?"; + var value2 = React.useContext(context2); + if (value2 == null) { + throw new Error(message); + } + return value2; +} +function mergeRefs() { + for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { + refs[_key] = arguments[_key]; + } + return (newRef) => { + refs.forEach((ref2) => { + if (ref2 != null) { + if (typeof ref2 === "function") { + ref2(newRef); + } else { + ref2.current = newRef; + } + } + }); + }; +} +function useChartTheme() { + return useContextOrThrow(ChartThemeContext, "No ChartThemeContext value found."); +} +var fastDeepEqual = function equal(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + if (a.constructor !== b.constructor) return false; + var length2, i, keys; + if (Array.isArray(a)) { + length2 = a.length; + if (length2 != b.length) return false; + for (i = length2; i-- !== 0; ) + if (!equal(a[i], b[i])) return false; + return true; + } + if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; + if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); + if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); + keys = Object.keys(a); + length2 = keys.length; + if (length2 !== Object.keys(b).length) return false; + for (i = length2; i-- !== 0; ) + if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; + for (i = length2; i-- !== 0; ) { + var key = keys[i]; + if (!equal(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; +}; +const deepEqual = /* @__PURE__ */ index$3.getDefaultExportFromCjs(fastDeepEqual); +var safeIsNaN = Number.isNaN || function ponyfill(value2) { + return typeof value2 === "number" && value2 !== value2; +}; +function isEqual(first, second2) { + if (first === second2) { + return true; + } + if (safeIsNaN(first) && safeIsNaN(second2)) { + return true; + } + return false; +} +function areInputsEqual(newInputs, lastInputs) { + if (newInputs.length !== lastInputs.length) { + return false; + } + for (var i = 0; i < newInputs.length; i++) { + if (!isEqual(newInputs[i], lastInputs[i])) { + return false; + } + } + return true; +} +function memoizeOne(resultFn, isEqual2) { + if (isEqual2 === void 0) { + isEqual2 = areInputsEqual; + } + var lastThis; + var lastArgs = []; + var lastResult; + var calledOnce = false; + function memoized() { + var newArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + newArgs[_i] = arguments[_i]; + } + if (calledOnce && lastThis === this && isEqual2(newArgs, lastArgs)) { + return lastResult; + } + lastResult = resultFn.apply(this, newArgs); + calledOnce = true; + lastThis = this; + lastArgs = newArgs; + return lastResult; + } + return memoized; +} +var factory = {}; +var propTypes = { exports: {} }; +var ReactPropTypesSecret$1 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; +var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; +var ReactPropTypesSecret = ReactPropTypesSecret_1; +function emptyFunction() { +} +function emptyFunctionWithReset() { +} +emptyFunctionWithReset.resetWarningCache = emptyFunction; +var factoryWithThrowingShims = function() { + function shim2(props, propName, componentName, location, propFullName, secret) { + if (secret === ReactPropTypesSecret) { + return; + } + var err = new Error( + "Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types" + ); + err.name = "Invariant Violation"; + throw err; + } + shim2.isRequired = shim2; + function getShim() { + return shim2; + } + var ReactPropTypes = { + array: shim2, + bigint: shim2, + bool: shim2, + func: shim2, + number: shim2, + object: shim2, + string: shim2, + symbol: shim2, + any: shim2, + arrayOf: getShim, + element: shim2, + elementType: shim2, + instanceOf: getShim, + node: shim2, + objectOf: getShim, + oneOf: getShim, + oneOfType: getShim, + shape: getShim, + exact: getShim, + checkPropTypes: emptyFunctionWithReset, + resetWarningCache: emptyFunction + }; + ReactPropTypes.PropTypes = ReactPropTypes; + return ReactPropTypes; +}; +{ + propTypes.exports = factoryWithThrowingShims(); +} +var propTypesExports = propTypes.exports; +(function(exports2) { + function _typeof(obj) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { + return typeof obj2; + } : function(obj2) { + return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }, _typeof(obj); + } + Object.defineProperty(exports2, "__esModule", { + value: true + }); + exports2["default"] = plotComponentFactory; + var _react = _interopRequireWildcard(React); + var _propTypes = _interopRequireDefault(propTypesExports); + function _interopRequireDefault(obj) { + return obj && obj.__esModule ? obj : { "default": obj }; + } + function _getRequireWildcardCache(nodeInterop) { + if (typeof WeakMap !== "function") return null; + var cacheBabelInterop = /* @__PURE__ */ new WeakMap(); + var cacheNodeInterop = /* @__PURE__ */ new WeakMap(); + return (_getRequireWildcardCache = function _getRequireWildcardCache2(nodeInterop2) { + return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop; + })(nodeInterop); + } + function _interopRequireWildcard(obj, nodeInterop) { + if (obj && obj.__esModule) { + return obj; + } + if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { + return { "default": obj }; + } + var cache2 = _getRequireWildcardCache(nodeInterop); + if (cache2 && cache2.has(obj)) { + return cache2.get(obj); + } + var newObj = {}; + var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; + for (var key in obj) { + if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { + var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; + if (desc && (desc.get || desc.set)) { + Object.defineProperty(newObj, key, desc); + } else { + newObj[key] = obj[key]; + } + } + } + newObj["default"] = obj; + if (cache2) { + cache2.set(obj, newObj); + } + return newObj; + } + function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } + } + function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } + } + function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + Object.defineProperty(Constructor, "prototype", { writable: false }); + return Constructor; + } + function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); + Object.defineProperty(subClass, "prototype", { writable: false }); + if (superClass) _setPrototypeOf(subClass, superClass); + } + function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { + o2.__proto__ = p2; + return o2; + }; + return _setPrototypeOf(o, p); + } + function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), result; + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + return _possibleConstructorReturn(this, result); + }; + } + function _possibleConstructorReturn(self2, call) { + if (call && (_typeof(call) === "object" || typeof call === "function")) { + return call; + } else if (call !== void 0) { + throw new TypeError("Derived constructors may only return object or undefined"); + } + return _assertThisInitialized(self2); + } + function _assertThisInitialized(self2) { + if (self2 === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + return self2; + } + function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { + })); + return true; + } catch (e) { + return false; + } + } + function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { + return o2.__proto__ || Object.getPrototypeOf(o2); + }; + return _getPrototypeOf(o); + } + var eventNames2 = ["AfterExport", "AfterPlot", "Animated", "AnimatingFrame", "AnimationInterrupted", "AutoSize", "BeforeExport", "BeforeHover", "ButtonClicked", "Click", "ClickAnnotation", "Deselect", "DoubleClick", "Framework", "Hover", "LegendClick", "LegendDoubleClick", "Relayout", "Relayouting", "Restyle", "Redraw", "Selected", "Selecting", "SliderChange", "SliderEnd", "SliderStart", "SunburstClick", "Transitioning", "TransitionInterrupted", "Unhover", "WebGlContextLost"]; + var updateEvents = ["plotly_restyle", "plotly_redraw", "plotly_relayout", "plotly_relayouting", "plotly_doubleclick", "plotly_animated", "plotly_sunburstclick"]; + var isBrowser2 = typeof window !== "undefined"; + function plotComponentFactory(Plotly2) { + var PlotlyComponent = /* @__PURE__ */ function(_Component) { + _inherits(PlotlyComponent2, _Component); + var _super = _createSuper(PlotlyComponent2); + function PlotlyComponent2(props) { + var _this; + _classCallCheck(this, PlotlyComponent2); + _this = _super.call(this, props); + _this.p = Promise.resolve(); + _this.resizeHandler = null; + _this.handlers = {}; + _this.syncWindowResize = _this.syncWindowResize.bind(_assertThisInitialized(_this)); + _this.syncEventHandlers = _this.syncEventHandlers.bind(_assertThisInitialized(_this)); + _this.attachUpdateEvents = _this.attachUpdateEvents.bind(_assertThisInitialized(_this)); + _this.getRef = _this.getRef.bind(_assertThisInitialized(_this)); + _this.handleUpdate = _this.handleUpdate.bind(_assertThisInitialized(_this)); + _this.figureCallback = _this.figureCallback.bind(_assertThisInitialized(_this)); + _this.updatePlotly = _this.updatePlotly.bind(_assertThisInitialized(_this)); + return _this; + } + _createClass(PlotlyComponent2, [{ + key: "updatePlotly", + value: function updatePlotly(shouldInvokeResizeHandler, figureCallbackFunction, shouldAttachUpdateEvents) { + var _this2 = this; + this.p = this.p.then(function() { + if (_this2.unmounting) { + return; + } + if (!_this2.el) { + throw new Error("Missing element reference"); + } + return Plotly2.react(_this2.el, { + data: _this2.props.data, + layout: _this2.props.layout, + config: _this2.props.config, + frames: _this2.props.frames + }); + }).then(function() { + if (_this2.unmounting) { + return; + } + _this2.syncWindowResize(shouldInvokeResizeHandler); + _this2.syncEventHandlers(); + _this2.figureCallback(figureCallbackFunction); + if (shouldAttachUpdateEvents) { + _this2.attachUpdateEvents(); + } + })["catch"](function(err) { + if (_this2.props.onError) { + _this2.props.onError(err); + } + }); + } + }, { + key: "componentDidMount", + value: function componentDidMount() { + this.unmounting = false; + this.updatePlotly(true, this.props.onInitialized, true); + } + }, { + key: "componentDidUpdate", + value: function componentDidUpdate(prevProps) { + this.unmounting = false; + var numPrevFrames = prevProps.frames && prevProps.frames.length ? prevProps.frames.length : 0; + var numNextFrames = this.props.frames && this.props.frames.length ? this.props.frames.length : 0; + var figureChanged = !(prevProps.layout === this.props.layout && prevProps.data === this.props.data && prevProps.config === this.props.config && numNextFrames === numPrevFrames); + var revisionDefined = prevProps.revision !== void 0; + var revisionChanged = prevProps.revision !== this.props.revision; + if (!figureChanged && (!revisionDefined || revisionDefined && !revisionChanged)) { + return; + } + this.updatePlotly(false, this.props.onUpdate, false); + } + }, { + key: "componentWillUnmount", + value: function componentWillUnmount() { + this.unmounting = true; + this.figureCallback(this.props.onPurge); + if (this.resizeHandler && isBrowser2) { + window.removeEventListener("resize", this.resizeHandler); + this.resizeHandler = null; + } + this.removeUpdateEvents(); + Plotly2.purge(this.el); + } + }, { + key: "attachUpdateEvents", + value: function attachUpdateEvents() { + var _this3 = this; + if (!this.el || !this.el.removeListener) { + return; + } + updateEvents.forEach(function(updateEvent) { + _this3.el.on(updateEvent, _this3.handleUpdate); + }); + } + }, { + key: "removeUpdateEvents", + value: function removeUpdateEvents() { + var _this4 = this; + if (!this.el || !this.el.removeListener) { + return; + } + updateEvents.forEach(function(updateEvent) { + _this4.el.removeListener(updateEvent, _this4.handleUpdate); + }); + } + }, { + key: "handleUpdate", + value: function handleUpdate() { + this.figureCallback(this.props.onUpdate); + } + }, { + key: "figureCallback", + value: function figureCallback(callback) { + if (typeof callback === "function") { + var _this$el = this.el, data = _this$el.data, layout = _this$el.layout; + var frames = this.el._transitionData ? this.el._transitionData._frames : null; + var figure = { + data, + layout, + frames + }; + callback(figure, this.el); + } + } + }, { + key: "syncWindowResize", + value: function syncWindowResize(invoke) { + var _this5 = this; + if (!isBrowser2) { + return; + } + if (this.props.useResizeHandler && !this.resizeHandler) { + this.resizeHandler = function() { + return Plotly2.Plots.resize(_this5.el); + }; + window.addEventListener("resize", this.resizeHandler); + if (invoke) { + this.resizeHandler(); + } + } else if (!this.props.useResizeHandler && this.resizeHandler) { + window.removeEventListener("resize", this.resizeHandler); + this.resizeHandler = null; + } + } + }, { + key: "getRef", + value: function getRef(el) { + this.el = el; + if (this.props.debug && isBrowser2) { + window.gd = this.el; + } + } + // Attach and remove event handlers as they're added or removed from props: + }, { + key: "syncEventHandlers", + value: function syncEventHandlers() { + var _this6 = this; + eventNames2.forEach(function(eventName) { + var prop = _this6.props["on" + eventName]; + var handler = _this6.handlers[eventName]; + var hasHandler = Boolean(handler); + if (prop && !hasHandler) { + _this6.addEventHandler(eventName, prop); + } else if (!prop && hasHandler) { + _this6.removeEventHandler(eventName); + } else if (prop && hasHandler && prop !== handler) { + _this6.removeEventHandler(eventName); + _this6.addEventHandler(eventName, prop); + } + }); + } + }, { + key: "addEventHandler", + value: function addEventHandler(eventName, prop) { + this.handlers[eventName] = prop; + this.el.on(this.getPlotlyEventName(eventName), this.handlers[eventName]); + } + }, { + key: "removeEventHandler", + value: function removeEventHandler(eventName) { + this.el.removeListener(this.getPlotlyEventName(eventName), this.handlers[eventName]); + delete this.handlers[eventName]; + } + }, { + key: "getPlotlyEventName", + value: function getPlotlyEventName(eventName) { + return "plotly_" + eventName.toLowerCase(); + } + }, { + key: "render", + value: function render() { + return /* @__PURE__ */ _react["default"].createElement("div", { + id: this.props.divId, + style: this.props.style, + ref: this.getRef, + className: this.props.className + }); + } + }]); + return PlotlyComponent2; + }(_react.Component); + PlotlyComponent.propTypes = { + data: _propTypes["default"].arrayOf(_propTypes["default"].object), + config: _propTypes["default"].object, + layout: _propTypes["default"].object, + frames: _propTypes["default"].arrayOf(_propTypes["default"].object), + revision: _propTypes["default"].number, + onInitialized: _propTypes["default"].func, + onPurge: _propTypes["default"].func, + onError: _propTypes["default"].func, + onUpdate: _propTypes["default"].func, + debug: _propTypes["default"].bool, + style: _propTypes["default"].object, + className: _propTypes["default"].string, + useResizeHandler: _propTypes["default"].bool, + divId: _propTypes["default"].string + }; + eventNames2.forEach(function(eventName) { + PlotlyComponent.propTypes["on" + eventName] = _propTypes["default"].func; + }); + PlotlyComponent.defaultProps = { + debug: false, + useResizeHandler: false, + data: [], + style: { + position: "relative", + display: "inline-block" + } + }; + return PlotlyComponent; + } +})(factory); +const createPlotlyComponent$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(factory); +const createPlotlyComponent = typeof createPlotlyComponent$1 === "function" ? createPlotlyComponent$1 : ( + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-ignore + createPlotlyComponent$1.default +); +var core$1 = {}; +var version$2 = {}; +version$2.version = "2.35.3"; +var npo_src = { exports: {} }; +/*! Native Promise Only + v0.8.1 (c) Kyle Simpson + MIT License: http://getify.mit-license.org +*/ +(function(module2) { + (function UMD(name2, context2, definition) { + context2[name2] = context2[name2] || definition(); + if (module2.exports) { + module2.exports = context2[name2]; + } + })("Promise", typeof index$3.commonjsGlobal != "undefined" ? index$3.commonjsGlobal : index$3.commonjsGlobal, function DEF() { + var builtInProp, cycle, scheduling_queue, ToString = Object.prototype.toString, timer = typeof setImmediate != "undefined" ? function timer2(fn) { + return setImmediate(fn); + } : setTimeout; + try { + Object.defineProperty({}, "x", {}); + builtInProp = function builtInProp2(obj, name2, val, config) { + return Object.defineProperty(obj, name2, { + value: val, + writable: true, + configurable: config !== false + }); + }; + } catch (err) { + builtInProp = function builtInProp2(obj, name2, val) { + obj[name2] = val; + return obj; + }; + } + scheduling_queue = /* @__PURE__ */ function Queue() { + var first, last, item; + function Item(fn, self2) { + this.fn = fn; + this.self = self2; + this.next = void 0; + } + return { + add: function add(fn, self2) { + item = new Item(fn, self2); + if (last) { + last.next = item; + } else { + first = item; + } + last = item; + item = void 0; + }, + drain: function drain() { + var f = first; + first = last = cycle = void 0; + while (f) { + f.fn.call(f.self); + f = f.next; + } + } + }; + }(); + function schedule(fn, self2) { + scheduling_queue.add(fn, self2); + if (!cycle) { + cycle = timer(scheduling_queue.drain); + } + } + function isThenable(o) { + var _then, o_type = typeof o; + if (o != null && (o_type == "object" || o_type == "function")) { + _then = o.then; + } + return typeof _then == "function" ? _then : false; + } + function notify() { + for (var i = 0; i < this.chain.length; i++) { + notifyIsolated( + this, + this.state === 1 ? this.chain[i].success : this.chain[i].failure, + this.chain[i] + ); + } + this.chain.length = 0; + } + function notifyIsolated(self2, cb, chain) { + var ret, _then; + try { + if (cb === false) { + chain.reject(self2.msg); + } else { + if (cb === true) { + ret = self2.msg; + } else { + ret = cb.call(void 0, self2.msg); + } + if (ret === chain.promise) { + chain.reject(TypeError("Promise-chain cycle")); + } else if (_then = isThenable(ret)) { + _then.call(ret, chain.resolve, chain.reject); + } else { + chain.resolve(ret); + } + } + } catch (err) { + chain.reject(err); + } + } + function resolve(msg2) { + var _then, self2 = this; + if (self2.triggered) { + return; + } + self2.triggered = true; + if (self2.def) { + self2 = self2.def; + } + try { + if (_then = isThenable(msg2)) { + schedule(function() { + var def_wrapper = new MakeDefWrapper(self2); + try { + _then.call( + msg2, + function $resolve$() { + resolve.apply(def_wrapper, arguments); + }, + function $reject$() { + reject.apply(def_wrapper, arguments); + } + ); + } catch (err) { + reject.call(def_wrapper, err); + } + }); + } else { + self2.msg = msg2; + self2.state = 1; + if (self2.chain.length > 0) { + schedule(notify, self2); + } + } + } catch (err) { + reject.call(new MakeDefWrapper(self2), err); + } + } + function reject(msg2) { + var self2 = this; + if (self2.triggered) { + return; + } + self2.triggered = true; + if (self2.def) { + self2 = self2.def; + } + self2.msg = msg2; + self2.state = 2; + if (self2.chain.length > 0) { + schedule(notify, self2); + } + } + function iteratePromises(Constructor, arr, resolver, rejecter) { + for (var idx = 0; idx < arr.length; idx++) { + (function IIFE(idx2) { + Constructor.resolve(arr[idx2]).then( + function $resolver$(msg2) { + resolver(idx2, msg2); + }, + rejecter + ); + })(idx); + } + } + function MakeDefWrapper(self2) { + this.def = self2; + this.triggered = false; + } + function MakeDef(self2) { + this.promise = self2; + this.state = 0; + this.triggered = false; + this.chain = []; + this.msg = void 0; + } + function Promise2(executor) { + if (typeof executor != "function") { + throw TypeError("Not a function"); + } + if (this.__NPO__ !== 0) { + throw TypeError("Not a promise"); + } + this.__NPO__ = 1; + var def = new MakeDef(this); + this["then"] = function then(success, failure) { + var o = { + success: typeof success == "function" ? success : true, + failure: typeof failure == "function" ? failure : false + }; + o.promise = new this.constructor(function extractChain(resolve2, reject2) { + if (typeof resolve2 != "function" || typeof reject2 != "function") { + throw TypeError("Not a function"); + } + o.resolve = resolve2; + o.reject = reject2; + }); + def.chain.push(o); + if (def.state !== 0) { + schedule(notify, def); + } + return o.promise; + }; + this["catch"] = function $catch$(failure) { + return this.then(void 0, failure); + }; + try { + executor.call( + void 0, + function publicResolve(msg2) { + resolve.call(def, msg2); + }, + function publicReject(msg2) { + reject.call(def, msg2); + } + ); + } catch (err) { + reject.call(def, err); + } + } + var PromisePrototype = builtInProp( + {}, + "constructor", + Promise2, + /*configurable=*/ + false + ); + Promise2.prototype = PromisePrototype; + builtInProp( + PromisePrototype, + "__NPO__", + 0, + /*configurable=*/ + false + ); + builtInProp(Promise2, "resolve", function Promise$resolve(msg2) { + var Constructor = this; + if (msg2 && typeof msg2 == "object" && msg2.__NPO__ === 1) { + return msg2; + } + return new Constructor(function executor(resolve2, reject2) { + if (typeof resolve2 != "function" || typeof reject2 != "function") { + throw TypeError("Not a function"); + } + resolve2(msg2); + }); + }); + builtInProp(Promise2, "reject", function Promise$reject(msg2) { + return new this(function executor(resolve2, reject2) { + if (typeof resolve2 != "function" || typeof reject2 != "function") { + throw TypeError("Not a function"); + } + reject2(msg2); + }); + }); + builtInProp(Promise2, "all", function Promise$all(arr) { + var Constructor = this; + if (ToString.call(arr) != "[object Array]") { + return Constructor.reject(TypeError("Not an array")); + } + if (arr.length === 0) { + return Constructor.resolve([]); + } + return new Constructor(function executor(resolve2, reject2) { + if (typeof resolve2 != "function" || typeof reject2 != "function") { + throw TypeError("Not a function"); + } + var len = arr.length, msgs = Array(len), count2 = 0; + iteratePromises(Constructor, arr, function resolver(idx, msg2) { + msgs[idx] = msg2; + if (++count2 === len) { + resolve2(msgs); + } + }, reject2); + }); + }); + builtInProp(Promise2, "race", function Promise$race(arr) { + var Constructor = this; + if (ToString.call(arr) != "[object Array]") { + return Constructor.reject(TypeError("Not an array")); + } + return new Constructor(function executor(resolve2, reject2) { + if (typeof resolve2 != "function" || typeof reject2 != "function") { + throw TypeError("Not a function"); + } + iteratePromises(Constructor, arr, function resolver(idx, msg2) { + resolve2(msg2); + }, reject2); + }); + }); + return Promise2; + }); +})(npo_src); +var lib$1 = { exports: {} }; +var d3$G = { exports: {} }; +(function(module2) { + !(function() { + var d32 = { + version: "3.8.2" + }; + var d3_arraySlice = [].slice, d3_array = function(list) { + return d3_arraySlice.call(list); + }; + var d3_document = self.document; + function d3_documentElement(node) { + return node && (node.ownerDocument || node.document || node).documentElement; + } + function d3_window(node) { + return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); + } + if (d3_document) { + try { + d3_array(d3_document.documentElement.childNodes)[0].nodeType; + } catch (e) { + d3_array = function(list) { + var i = list.length, array2 = new Array(i); + while (i--) array2[i] = list[i]; + return array2; + }; + } + } + if (!Date.now) Date.now = function() { + return +/* @__PURE__ */ new Date(); + }; + if (d3_document) { + try { + d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); + } catch (error) { + var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; + d3_element_prototype.setAttribute = function(name2, value2) { + d3_element_setAttribute.call(this, name2, value2 + ""); + }; + d3_element_prototype.setAttributeNS = function(space, local, value2) { + d3_element_setAttributeNS.call(this, space, local, value2 + ""); + }; + d3_style_prototype.setProperty = function(name2, value2, priority) { + d3_style_setProperty.call(this, name2, value2 + "", priority); + }; + } + } + d32.ascending = d3_ascending; + function d3_ascending(a, b) { + return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; + } + d32.descending = function(a, b) { + return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; + }; + d32.min = function(array2, f) { + var i = -1, n = array2.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array2[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array2[i]) != null && a > b) a = b; + } else { + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && a > b) a = b; + } + return a; + }; + d32.max = function(array2, f) { + var i = -1, n = array2.length, a, b; + if (arguments.length === 1) { + while (++i < n) if ((b = array2[i]) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = array2[i]) != null && b > a) a = b; + } else { + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { + a = b; + break; + } + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b > a) a = b; + } + return a; + }; + d32.extent = function(array2, f) { + var i = -1, n = array2.length, a, b, c; + if (arguments.length === 1) { + while (++i < n) if ((b = array2[i]) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = array2[i]) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } else { + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { + a = c = b; + break; + } + while (++i < n) if ((b = f.call(array2, array2[i], i)) != null) { + if (a > b) a = b; + if (c < b) c = b; + } + } + return [a, c]; + }; + function d3_number(x) { + return x === null ? NaN : +x; + } + function d3_numeric(x) { + return !isNaN(x); + } + d32.sum = function(array2, f) { + var s = 0, n = array2.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = +array2[i])) s += a; + } else { + while (++i < n) if (d3_numeric(a = +f.call(array2, array2[i], i))) s += a; + } + return s; + }; + d32.mean = function(array2, f) { + var s = 0, n = array2.length, a, i = -1, j = n; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array2[i]))) s += a; + else --j; + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) s += a; + else --j; + } + if (j) return s / j; + }; + d32.quantile = function(values, p) { + var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; + return e ? v + e * (values[h] - v) : v; + }; + d32.median = function(array2, f) { + var numbers = [], n = array2.length, a, i = -1; + if (arguments.length === 1) { + while (++i < n) if (d3_numeric(a = d3_number(array2[i]))) numbers.push(a); + } else { + while (++i < n) if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) numbers.push(a); + } + if (numbers.length) return d32.quantile(numbers.sort(d3_ascending), 0.5); + }; + d32.variance = function(array2, f) { + var n = array2.length, m = 0, a, d, s = 0, i = -1, j = 0; + if (arguments.length === 1) { + while (++i < n) { + if (d3_numeric(a = d3_number(array2[i]))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } else { + while (++i < n) { + if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) { + d = a - m; + m += d / ++j; + s += d * (a - m); + } + } + } + if (j > 1) return s / (j - 1); + }; + d32.deviation = function() { + var v = d32.variance.apply(this, arguments); + return v ? Math.sqrt(v) : v; + }; + function d3_bisector(compare) { + return { + left: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) < 0) lo = mid + 1; + else hi = mid; + } + return lo; + }, + right: function(a, x, lo, hi) { + if (arguments.length < 3) lo = 0; + if (arguments.length < 4) hi = a.length; + while (lo < hi) { + var mid = lo + hi >>> 1; + if (compare(a[mid], x) > 0) hi = mid; + else lo = mid + 1; + } + return lo; + } + }; + } + var d3_bisect = d3_bisector(d3_ascending); + d32.bisectLeft = d3_bisect.left; + d32.bisect = d32.bisectRight = d3_bisect.right; + d32.bisector = function(f) { + return d3_bisector(f.length === 1 ? function(d, x) { + return d3_ascending(f(d), x); + } : f); + }; + d32.shuffle = function(array2, i0, i1) { + if ((m = arguments.length) < 3) { + i1 = array2.length; + if (m < 2) i0 = 0; + } + var m = i1 - i0, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array2[m + i0], array2[m + i0] = array2[i + i0], array2[i + i0] = t; + } + return array2; + }; + d32.permute = function(array2, indexes) { + var i = indexes.length, permutes = new Array(i); + while (i--) permutes[i] = array2[indexes[i]]; + return permutes; + }; + d32.pairs = function(array2) { + var i = 0, n = array2.length - 1, p1 = array2[0], pairs = new Array(n < 0 ? 0 : n); + while (i < n) pairs[i] = [p1, p1 = array2[++i]]; + return pairs; + }; + d32.transpose = function(matrix2) { + if (!(n = matrix2.length)) return []; + for (var i = -1, m = d32.min(matrix2, d3_transposeLength), transpose2 = new Array(m); ++i < m; ) { + for (var j = -1, n, row = transpose2[i] = new Array(n); ++j < n; ) { + row[j] = matrix2[j][i]; + } + } + return transpose2; + }; + function d3_transposeLength(d) { + return d.length; + } + d32.zip = function() { + return d32.transpose(arguments); + }; + d32.keys = function(map2) { + var keys = []; + for (var key in map2) keys.push(key); + return keys; + }; + d32.values = function(map2) { + var values = []; + for (var key in map2) values.push(map2[key]); + return values; + }; + d32.entries = function(map2) { + var entries = []; + for (var key in map2) entries.push({ + key, + value: map2[key] + }); + return entries; + }; + d32.merge = function(arrays) { + var n = arrays.length, m, i = -1, j = 0, merged, array2; + while (++i < n) j += arrays[i].length; + merged = new Array(j); + while (--n >= 0) { + array2 = arrays[n]; + m = array2.length; + while (--m >= 0) { + merged[--j] = array2[m]; + } + } + return merged; + }; + var abs2 = Math.abs; + d32.range = function(start, stop, step) { + if (arguments.length < 3) { + step = 1; + if (arguments.length < 2) { + stop = start; + start = 0; + } + } + if ((stop - start) / step === Infinity) throw new Error("infinite range"); + var range = [], k = d3_range_integerScale(abs2(step)), i = -1, j; + start *= k, stop *= k, step *= k; + if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); + else while ((j = start + step * ++i) < stop) range.push(j / k); + return range; + }; + function d3_range_integerScale(x) { + var k = 1; + while (x * k % 1) k *= 10; + return k; + } + function d3_class(ctor, properties) { + for (var key in properties) { + Object.defineProperty(ctor.prototype, key, { + value: properties[key], + enumerable: false + }); + } + } + d32.map = function(object2, f) { + var map2 = new d3_Map(); + if (object2 instanceof d3_Map) { + object2.forEach(function(key2, value2) { + map2.set(key2, value2); + }); + } else if (Array.isArray(object2)) { + var i = -1, n = object2.length, o; + if (arguments.length === 1) while (++i < n) map2.set(i, object2[i]); + else while (++i < n) map2.set(f.call(object2, o = object2[i], i), o); + } else { + for (var key in object2) map2.set(key, object2[key]); + } + return map2; + }; + function d3_Map() { + this._ = /* @__PURE__ */ Object.create(null); + } + var d3_map_proto = "__proto__", d3_map_zero = "\0"; + d3_class(d3_Map, { + has: d3_map_has, + get: function(key) { + return this._[d3_map_escape(key)]; + }, + set: function(key, value2) { + return this._[d3_map_escape(key)] = value2; + }, + remove: d3_map_remove, + keys: d3_map_keys, + values: function() { + var values = []; + for (var key in this._) values.push(this._[key]); + return values; + }, + entries: function() { + var entries = []; + for (var key in this._) entries.push({ + key: d3_map_unescape(key), + value: this._[key] + }); + return entries; + }, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); + } + }); + function d3_map_escape(key) { + return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; + } + function d3_map_unescape(key) { + return (key += "")[0] === d3_map_zero ? key.slice(1) : key; + } + function d3_map_has(key) { + return d3_map_escape(key) in this._; + } + function d3_map_remove(key) { + return (key = d3_map_escape(key)) in this._ && delete this._[key]; + } + function d3_map_keys() { + var keys = []; + for (var key in this._) keys.push(d3_map_unescape(key)); + return keys; + } + function d3_map_size() { + var size = 0; + for (var key in this._) ++size; + return size; + } + function d3_map_empty() { + for (var key in this._) return false; + return true; + } + d32.nest = function() { + var nest = {}, keys = [], sortKeys = [], sortValues, rollup; + function map2(mapType, array2, depth) { + if (depth >= keys.length) return rollup ? rollup.call(nest, array2) : sortValues ? array2.sort(sortValues) : array2; + var i = -1, n = array2.length, key = keys[depth++], keyValue, object2, setter, valuesByKey = new d3_Map(), values; + while (++i < n) { + if (values = valuesByKey.get(keyValue = key(object2 = array2[i]))) { + values.push(object2); + } else { + valuesByKey.set(keyValue, [object2]); + } + } + if (mapType) { + object2 = mapType(); + setter = function(keyValue2, values2) { + object2.set(keyValue2, map2(mapType, values2, depth)); + }; + } else { + object2 = {}; + setter = function(keyValue2, values2) { + object2[keyValue2] = map2(mapType, values2, depth); + }; + } + valuesByKey.forEach(setter); + return object2; + } + function entries(map3, depth) { + if (depth >= keys.length) return map3; + var array2 = [], sortKey = sortKeys[depth++]; + map3.forEach(function(key, keyMap) { + array2.push({ + key, + values: entries(keyMap, depth) + }); + }); + return sortKey ? array2.sort(function(a, b) { + return sortKey(a.key, b.key); + }) : array2; + } + nest.map = function(array2, mapType) { + return map2(mapType, array2, 0); + }; + nest.entries = function(array2) { + return entries(map2(d32.map, array2, 0), 0); + }; + nest.key = function(d) { + keys.push(d); + return nest; + }; + nest.sortKeys = function(order) { + sortKeys[keys.length - 1] = order; + return nest; + }; + nest.sortValues = function(order) { + sortValues = order; + return nest; + }; + nest.rollup = function(f) { + rollup = f; + return nest; + }; + return nest; + }; + d32.set = function(array2) { + var set = new d3_Set(); + if (array2) for (var i = 0, n = array2.length; i < n; ++i) set.add(array2[i]); + return set; + }; + function d3_Set() { + this._ = /* @__PURE__ */ Object.create(null); + } + d3_class(d3_Set, { + has: d3_map_has, + add: function(key) { + this._[d3_map_escape(key += "")] = true; + return key; + }, + remove: d3_map_remove, + values: d3_map_keys, + size: d3_map_size, + empty: d3_map_empty, + forEach: function(f) { + for (var key in this._) f.call(this, d3_map_unescape(key)); + } + }); + d32.behavior = {}; + function d3_identity(d) { + return d; + } + d32.rebind = function(target, source) { + var i = 1, n = arguments.length, method; + while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); + return target; + }; + function d3_rebind(target, source, method) { + return function() { + var value2 = method.apply(source, arguments); + return value2 === source ? target : value2; + }; + } + function d3_vendorSymbol(object2, name2) { + if (name2 in object2) return name2; + name2 = name2.charAt(0).toUpperCase() + name2.slice(1); + for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { + var prefixName = d3_vendorPrefixes[i] + name2; + if (prefixName in object2) return prefixName; + } + } + var d3_vendorPrefixes = ["webkit", "ms", "moz", "Moz", "o", "O"]; + function d3_noop() { + } + d32.dispatch = function() { + var dispatch = new d3_dispatch(), i = -1, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + return dispatch; + }; + function d3_dispatch() { + } + d3_dispatch.prototype.on = function(type, listener) { + var i = type.indexOf("."), name2 = ""; + if (i >= 0) { + name2 = type.slice(i + 1); + type = type.slice(0, i); + } + if (type) return arguments.length < 2 ? this[type].on(name2) : this[type].on(name2, listener); + if (arguments.length === 2) { + if (listener == null) for (type in this) { + if (this.hasOwnProperty(type)) this[type].on(name2, null); + } + return this; + } + }; + function d3_dispatch_event(dispatch) { + var listeners2 = [], listenerByName = new d3_Map(); + function event() { + var z = listeners2, i = -1, n = z.length, l; + while (++i < n) if (l = z[i].on) l.apply(this, arguments); + return dispatch; + } + event.on = function(name2, listener) { + var l = listenerByName.get(name2), i; + if (arguments.length < 2) return l && l.on; + if (l) { + l.on = null; + listeners2 = listeners2.slice(0, i = listeners2.indexOf(l)).concat(listeners2.slice(i + 1)); + listenerByName.remove(name2); + } + if (listener) listeners2.push(listenerByName.set(name2, { + on: listener + })); + return dispatch; + }; + return event; + } + d32.event = null; + function d3_eventPreventDefault() { + d32.event.preventDefault(); + } + function d3_eventSource() { + var e = d32.event, s; + while (s = e.sourceEvent) e = s; + return e; + } + function d3_eventDispatch(target) { + var dispatch = new d3_dispatch(), i = 0, n = arguments.length; + while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); + dispatch.of = function(thiz, argumentz) { + return function(e1) { + try { + var e0 = e1.sourceEvent = d32.event; + e1.target = target; + d32.event = e1; + dispatch[e1.type].apply(thiz, argumentz); + } finally { + d32.event = e0; + } + }; + }; + return dispatch; + } + d32.requote = function(s) { + return s.replace(d3_requote_re, "\\$&"); + }; + var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; + var d3_subclass = {}.__proto__ ? function(object2, prototype) { + object2.__proto__ = prototype; + } : function(object2, prototype) { + for (var property in prototype) object2[property] = prototype[property]; + }; + function d3_selection(groups) { + d3_subclass(groups, d3_selectionPrototype); + return groups; + } + var d3_select = function(s, n) { + return n.querySelector(s); + }, d3_selectAll = function(s, n) { + return n.querySelectorAll(s); + }, d3_selectMatches = function(n, s) { + var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; + d3_selectMatches = function(n2, s2) { + return d3_selectMatcher.call(n2, s2); + }; + return d3_selectMatches(n, s); + }; + if (typeof Sizzle === "function") { + d3_select = function(s, n) { + return Sizzle(s, n)[0] || null; + }; + d3_selectAll = Sizzle; + d3_selectMatches = Sizzle.matchesSelector; + } + d32.selection = function() { + return d32.select(d3_document.documentElement); + }; + var d3_selectionPrototype = d32.selection.prototype = []; + d3_selectionPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, group, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(subnode = selector.call(node, node.__data__, i, j)); + if (subnode && "__data__" in node) subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selector(selector) { + return typeof selector === "function" ? selector : function() { + return d3_select(selector, this); + }; + } + d3_selectionPrototype.selectAll = function(selector) { + var subgroups = [], subgroup, node; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); + subgroup.parentNode = node; + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_selectorAll(selector) { + return typeof selector === "function" ? selector : function() { + return d3_selectAll(selector, this); + }; + } + var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; + var d3_nsPrefix = { + svg: "http://www.w3.org/2000/svg", + xhtml: d3_nsXhtml, + xlink: "http://www.w3.org/1999/xlink", + xml: "http://www.w3.org/XML/1998/namespace", + xmlns: "http://www.w3.org/2000/xmlns/" + }; + d32.ns = { + prefix: d3_nsPrefix, + qualify: function(name2) { + var i = name2.indexOf(":"), prefix = name2; + if (i >= 0 && (prefix = name2.slice(0, i)) !== "xmlns") name2 = name2.slice(i + 1); + return d3_nsPrefix.hasOwnProperty(prefix) ? { + space: d3_nsPrefix[prefix], + local: name2 + } : name2; + } + }; + d3_selectionPrototype.attr = function(name2, value2) { + if (arguments.length < 2) { + if (typeof name2 === "string") { + var node = this.node(); + name2 = d32.ns.qualify(name2); + return name2.local ? node.getAttributeNS(name2.space, name2.local) : node.getAttribute(name2); + } + for (value2 in name2) this.each(d3_selection_attr(value2, name2[value2])); + return this; + } + return this.each(d3_selection_attr(name2, value2)); + }; + function d3_selection_attr(name2, value2) { + name2 = d32.ns.qualify(name2); + function attrNull() { + this.removeAttribute(name2); + } + function attrNullNS() { + this.removeAttributeNS(name2.space, name2.local); + } + function attrConstant() { + this.setAttribute(name2, value2); + } + function attrConstantNS() { + this.setAttributeNS(name2.space, name2.local, value2); + } + function attrFunction() { + var x = value2.apply(this, arguments); + if (x == null) this.removeAttribute(name2); + else this.setAttribute(name2, x); + } + function attrFunctionNS() { + var x = value2.apply(this, arguments); + if (x == null) this.removeAttributeNS(name2.space, name2.local); + else this.setAttributeNS(name2.space, name2.local, x); + } + return value2 == null ? name2.local ? attrNullNS : attrNull : typeof value2 === "function" ? name2.local ? attrFunctionNS : attrFunction : name2.local ? attrConstantNS : attrConstant; + } + function d3_collapse(s) { + return s.trim().replace(/\s+/g, " "); + } + d3_selectionPrototype.classed = function(name2, value2) { + if (arguments.length < 2) { + if (typeof name2 === "string") { + var node = this.node(), n = (name2 = d3_selection_classes(name2)).length, i = -1; + if (value2 = node.classList) { + while (++i < n) if (!value2.contains(name2[i])) return false; + } else { + value2 = node.getAttribute("class"); + while (++i < n) if (!d3_selection_classedRe(name2[i]).test(value2)) return false; + } + return true; + } + for (value2 in name2) this.each(d3_selection_classed(value2, name2[value2])); + return this; + } + return this.each(d3_selection_classed(name2, value2)); + }; + function d3_selection_classedRe(name2) { + return new RegExp("(?:^|\\s+)" + d32.requote(name2) + "(?:\\s+|$)", "g"); + } + function d3_selection_classes(name2) { + return (name2 + "").trim().split(/^|\s+/); + } + function d3_selection_classed(name2, value2) { + name2 = d3_selection_classes(name2).map(d3_selection_classedName); + var n = name2.length; + function classedConstant() { + var i = -1; + while (++i < n) name2[i](this, value2); + } + function classedFunction() { + var i = -1, x = value2.apply(this, arguments); + while (++i < n) name2[i](this, x); + } + return typeof value2 === "function" ? classedFunction : classedConstant; + } + function d3_selection_classedName(name2) { + var re2 = d3_selection_classedRe(name2); + return function(node, value2) { + if (c = node.classList) return value2 ? c.add(name2) : c.remove(name2); + var c = node.getAttribute("class") || ""; + if (value2) { + re2.lastIndex = 0; + if (!re2.test(c)) node.setAttribute("class", d3_collapse(c + " " + name2)); + } else { + node.setAttribute("class", d3_collapse(c.replace(re2, " "))); + } + }; + } + d3_selectionPrototype.style = function(name2, value2, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name2 !== "string") { + if (n < 2) value2 = ""; + for (priority in name2) this.each(d3_selection_style(priority, name2[priority], value2)); + return this; + } + if (n < 2) { + var node = this.node(); + return d3_window(node).getComputedStyle(node, null).getPropertyValue(name2); + } + priority = ""; + } + return this.each(d3_selection_style(name2, value2, priority)); + }; + function d3_selection_style(name2, value2, priority) { + function styleNull() { + this.style.removeProperty(name2); + } + function styleConstant() { + this.style.setProperty(name2, value2, priority); + } + function styleFunction() { + var x = value2.apply(this, arguments); + if (x == null) this.style.removeProperty(name2); + else this.style.setProperty(name2, x, priority); + } + return value2 == null ? styleNull : typeof value2 === "function" ? styleFunction : styleConstant; + } + d3_selectionPrototype.property = function(name2, value2) { + if (arguments.length < 2) { + if (typeof name2 === "string") return this.node()[name2]; + for (value2 in name2) this.each(d3_selection_property(value2, name2[value2])); + return this; + } + return this.each(d3_selection_property(name2, value2)); + }; + function d3_selection_property(name2, value2) { + function propertyNull() { + delete this[name2]; + } + function propertyConstant() { + this[name2] = value2; + } + function propertyFunction() { + var x = value2.apply(this, arguments); + if (x == null) delete this[name2]; + else this[name2] = x; + } + return value2 == null ? propertyNull : typeof value2 === "function" ? propertyFunction : propertyConstant; + } + d3_selectionPrototype.text = function(value2) { + return arguments.length ? this.each(typeof value2 === "function" ? function() { + var v = value2.apply(this, arguments); + this.textContent = v == null ? "" : v; + } : value2 == null ? function() { + this.textContent = ""; + } : function() { + this.textContent = value2; + }) : this.node().textContent; + }; + d3_selectionPrototype.html = function(value2) { + return arguments.length ? this.each(typeof value2 === "function" ? function() { + var v = value2.apply(this, arguments); + this.innerHTML = v == null ? "" : v; + } : value2 == null ? function() { + this.innerHTML = ""; + } : function() { + this.innerHTML = value2; + }) : this.node().innerHTML; + }; + d3_selectionPrototype.append = function(name2) { + name2 = d3_selection_creator(name2); + return this.select(function() { + return this.appendChild(name2.apply(this, arguments)); + }); + }; + function d3_selection_creator(name2) { + function create2() { + var document2 = this.ownerDocument, namespace = this.namespaceURI; + return namespace === d3_nsXhtml && document2.documentElement.namespaceURI === d3_nsXhtml ? document2.createElement(name2) : document2.createElementNS(namespace, name2); + } + function createNS() { + return this.ownerDocument.createElementNS(name2.space, name2.local); + } + return typeof name2 === "function" ? name2 : (name2 = d32.ns.qualify(name2)).local ? createNS : create2; + } + d3_selectionPrototype.insert = function(name2, before) { + name2 = d3_selection_creator(name2); + before = d3_selection_selector(before); + return this.select(function() { + return this.insertBefore(name2.apply(this, arguments), before.apply(this, arguments) || null); + }); + }; + d3_selectionPrototype.remove = function() { + return this.each(d3_selectionRemove); + }; + function d3_selectionRemove() { + var parent = this.parentNode; + if (parent) parent.removeChild(this); + } + d3_selectionPrototype.data = function(value2, key) { + var i = -1, n = this.length, group, node; + if (!arguments.length) { + value2 = new Array(n = (group = this[0]).length); + while (++i < n) { + if (node = group[i]) { + value2[i] = node.__data__; + } + } + return value2; + } + function bind(group2, groupData) { + var i2, n2 = group2.length, m = groupData.length, n0 = Math.min(n2, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n2), node2, nodeData; + if (key) { + var nodeByKeyValue = new d3_Map(), keyValues = new Array(n2), keyValue; + for (i2 = -1; ++i2 < n2; ) { + if (node2 = group2[i2]) { + if (nodeByKeyValue.has(keyValue = key.call(node2, node2.__data__, i2))) { + exitNodes[i2] = node2; + } else { + nodeByKeyValue.set(keyValue, node2); + } + keyValues[i2] = keyValue; + } + } + for (i2 = -1; ++i2 < m; ) { + if (!(node2 = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i2], i2)))) { + enterNodes[i2] = d3_selection_dataNode(nodeData); + } else if (node2 !== true) { + updateNodes[i2] = node2; + node2.__data__ = nodeData; + } + nodeByKeyValue.set(keyValue, true); + } + for (i2 = -1; ++i2 < n2; ) { + if (i2 in keyValues && nodeByKeyValue.get(keyValues[i2]) !== true) { + exitNodes[i2] = group2[i2]; + } + } + } else { + for (i2 = -1; ++i2 < n0; ) { + node2 = group2[i2]; + nodeData = groupData[i2]; + if (node2) { + node2.__data__ = nodeData; + updateNodes[i2] = node2; + } else { + enterNodes[i2] = d3_selection_dataNode(nodeData); + } + } + for (; i2 < m; ++i2) { + enterNodes[i2] = d3_selection_dataNode(groupData[i2]); + } + for (; i2 < n2; ++i2) { + exitNodes[i2] = group2[i2]; + } + } + enterNodes.update = updateNodes; + enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group2.parentNode; + enter.push(enterNodes); + update2.push(updateNodes); + exit.push(exitNodes); + } + var enter = d3_selection_enter([]), update2 = d3_selection([]), exit = d3_selection([]); + if (typeof value2 === "function") { + while (++i < n) { + bind(group = this[i], value2.call(group, group.parentNode.__data__, i)); + } + } else { + while (++i < n) { + bind(group = this[i], value2); + } + } + update2.enter = function() { + return enter; + }; + update2.exit = function() { + return exit; + }; + return update2; + }; + function d3_selection_dataNode(data) { + return { + __data__: data + }; + } + d3_selectionPrototype.datum = function(value2) { + return arguments.length ? this.property("__data__", value2) : this.property("__data__"); + }; + d3_selectionPrototype.filter = function(filter2) { + var subgroups = [], subgroup, group, node; + if (typeof filter2 !== "function") filter2 = d3_selection_filter(filter2); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + subgroup.parentNode = (group = this[j]).parentNode; + for (var i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter2.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_selection(subgroups); + }; + function d3_selection_filter(selector) { + return function() { + return d3_selectMatches(this, selector); + }; + } + d3_selectionPrototype.order = function() { + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { + if (node = group[i]) { + if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); + next = node; + } + } + } + return this; + }; + d3_selectionPrototype.sort = function(comparator) { + comparator = d3_selection_sortComparator.apply(this, arguments); + for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); + return this.order(); + }; + function d3_selection_sortComparator(comparator) { + if (!arguments.length) comparator = d3_ascending; + return function(a, b) { + return a && b ? comparator(a.__data__, b.__data__) : !a - !b; + }; + } + d3_selectionPrototype.each = function(callback) { + return d3_selection_each(this, function(node, i, j) { + callback.call(node, node.__data__, i, j); + }); + }; + function d3_selection_each(groups, callback) { + for (var j = 0, m = groups.length; j < m; j++) { + for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { + if (node = group[i]) callback(node, i, j); + } + } + return groups; + } + d3_selectionPrototype.call = function(callback) { + var args = d3_array(arguments); + callback.apply(args[0] = this, args); + return this; + }; + d3_selectionPrototype.empty = function() { + return !this.node(); + }; + d3_selectionPrototype.node = function() { + for (var j = 0, m = this.length; j < m; j++) { + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + var node = group[i]; + if (node) return node; + } + } + return null; + }; + d3_selectionPrototype.size = function() { + var n = 0; + d3_selection_each(this, function() { + ++n; + }); + return n; + }; + function d3_selection_enter(selection) { + d3_subclass(selection, d3_selection_enterPrototype); + return selection; + } + var d3_selection_enterPrototype = []; + d32.selection.enter = d3_selection_enter; + d32.selection.enter.prototype = d3_selection_enterPrototype; + d3_selection_enterPrototype.append = d3_selectionPrototype.append; + d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; + d3_selection_enterPrototype.node = d3_selectionPrototype.node; + d3_selection_enterPrototype.call = d3_selectionPrototype.call; + d3_selection_enterPrototype.size = d3_selectionPrototype.size; + d3_selection_enterPrototype.select = function(selector) { + var subgroups = [], subgroup, subnode, upgroup, group, node; + for (var j = -1, m = this.length; ++j < m; ) { + upgroup = (group = this[j]).update; + subgroups.push(subgroup = []); + subgroup.parentNode = group.parentNode; + for (var i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); + subnode.__data__ = node.__data__; + } else { + subgroup.push(null); + } + } + } + return d3_selection(subgroups); + }; + d3_selection_enterPrototype.insert = function(name2, before) { + if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); + return d3_selectionPrototype.insert.call(this, name2, before); + }; + function d3_selection_enterInsertBefore(enter) { + var i0, j0; + return function(d, i, j) { + var group = enter[j].update, n = group.length, node; + if (j != j0) j0 = j, i0 = 0; + if (i >= i0) i0 = i + 1; + while (!(node = group[i0]) && ++i0 < n) ; + return node; + }; + } + d32.select = function(node) { + var group; + if (typeof node === "string") { + group = [d3_select(node, d3_document)]; + group.parentNode = d3_document.documentElement; + } else { + group = [node]; + group.parentNode = d3_documentElement(node); + } + return d3_selection([group]); + }; + d32.selectAll = function(nodes) { + var group; + if (typeof nodes === "string") { + group = d3_array(d3_selectAll(nodes, d3_document)); + group.parentNode = d3_document.documentElement; + } else { + group = d3_array(nodes); + group.parentNode = null; + } + return d3_selection([group]); + }; + d3_selectionPrototype.on = function(type, listener, capture) { + var n = arguments.length; + if (n < 3) { + if (typeof type !== "string") { + if (n < 2) listener = false; + for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); + return this; + } + if (n < 2) return (n = this.node()["__on" + type]) && n._; + capture = false; + } + return this.each(d3_selection_on(type, listener, capture)); + }; + function d3_selection_on(type, listener, capture) { + var name2 = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; + if (i > 0) type = type.slice(0, i); + var filter2 = d3_selection_onFilters.get(type); + if (filter2) type = filter2, wrap = d3_selection_onFilter; + function onRemove() { + var l = this[name2]; + if (l) { + this.removeEventListener(type, l, l.$); + delete this[name2]; + } + } + function onAdd() { + var l = wrap(listener, d3_array(arguments)); + onRemove.call(this); + this.addEventListener(type, this[name2] = l, l.$ = capture); + l._ = listener; + } + function removeAll() { + var re2 = new RegExp("^__on([^.]+)" + d32.requote(type) + "$"), match; + for (var name3 in this) { + if (match = name3.match(re2)) { + var l = this[name3]; + this.removeEventListener(match[1], l, l.$); + delete this[name3]; + } + } + } + return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; + } + var d3_selection_onFilters = d32.map({ + mouseenter: "mouseover", + mouseleave: "mouseout" + }); + if (d3_document) { + d3_selection_onFilters.forEach(function(k) { + if ("on" + k in d3_document) d3_selection_onFilters.remove(k); + }); + } + function d3_selection_onListener(listener, argumentz) { + return function(e) { + var o = d32.event; + d32.event = e; + argumentz[0] = this.__data__; + try { + listener.apply(this, argumentz); + } finally { + d32.event = o; + } + }; + } + function d3_selection_onFilter(listener, argumentz) { + var l = d3_selection_onListener(listener, argumentz); + return function(e) { + var target = this, related = e.relatedTarget; + if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { + l.call(target, e); + } + }; + } + var d3_event_dragSelect, d3_event_dragId = 0; + function d3_event_dragSuppress(node) { + var name2 = ".dragsuppress-" + ++d3_event_dragId, click3 = "click" + name2, w = d32.select(d3_window(node)).on("touchmove" + name2, d3_eventPreventDefault).on("dragstart" + name2, d3_eventPreventDefault).on("selectstart" + name2, d3_eventPreventDefault); + if (d3_event_dragSelect == null) { + d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); + } + if (d3_event_dragSelect) { + var style5 = d3_documentElement(node).style, select3 = style5[d3_event_dragSelect]; + style5[d3_event_dragSelect] = "none"; + } + return function(suppressClick) { + w.on(name2, null); + if (d3_event_dragSelect) style5[d3_event_dragSelect] = select3; + if (suppressClick) { + var off = function() { + w.on(click3, null); + }; + w.on(click3, function() { + d3_eventPreventDefault(); + off(); + }, true); + setTimeout(off, 0); + } + }; + } + d32.mouse = function(container) { + return d3_mousePoint(container, d3_eventSource()); + }; + var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; + function d3_mousePoint(container, e) { + if (e.changedTouches) e = e.changedTouches[0]; + var svg = container.ownerSVGElement || container; + if (svg.createSVGPoint) { + var point = svg.createSVGPoint(); + if (d3_mouse_bug44083 < 0) { + var window2 = d3_window(container); + if (window2.scrollX || window2.scrollY) { + svg = d32.select("body").append("svg").style({ + position: "absolute", + top: 0, + left: 0, + margin: 0, + padding: 0, + border: "none" + }, "important"); + var ctm = svg[0][0].getScreenCTM(); + d3_mouse_bug44083 = !(ctm.f || ctm.e); + svg.remove(); + } + } + if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; + else point.x = e.clientX, point.y = e.clientY; + point = point.matrixTransform(container.getScreenCTM().inverse()); + return [point.x, point.y]; + } + var rect2 = container.getBoundingClientRect(); + return [e.clientX - rect2.left - container.clientLeft, e.clientY - rect2.top - container.clientTop]; + } + d32.touch = function(container, touches, identifier) { + if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; + if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { + if ((touch = touches[i]).identifier === identifier) { + return d3_mousePoint(container, touch); + } + } + }; + d32.behavior.drag = function() { + var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d32.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d32.touch, d3_identity, "touchmove", "touchend"); + function drag() { + this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); + } + function dragstart(id, position, subject, move, end) { + return function() { + var that = this, target = d32.event.target.correspondingElement || d32.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d32.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); + if (origin) { + dragOffset = origin.apply(that, arguments); + dragOffset = [dragOffset.x - position0[0], dragOffset.y - position0[1]]; + } else { + dragOffset = [0, 0]; + } + dispatch({ + type: "dragstart" + }); + function moved() { + var position1 = position(parent, dragId), dx, dy; + if (!position1) return; + dx = position1[0] - position0[0]; + dy = position1[1] - position0[1]; + dragged |= dx | dy; + position0 = position1; + dispatch({ + type: "drag", + x: position1[0] + dragOffset[0], + y: position1[1] + dragOffset[1], + dx, + dy + }); + } + function ended() { + if (!position(parent, dragId)) return; + dragSubject.on(move + dragName, null).on(end + dragName, null); + dragRestore(dragged); + dispatch({ + type: "dragend" + }); + } + }; + } + drag.origin = function(x) { + if (!arguments.length) return origin; + origin = x; + return drag; + }; + return d32.rebind(drag, event, "on"); + }; + function d3_behavior_dragTouchId() { + return d32.event.changedTouches[0].identifier; + } + d32.touches = function(container, touches) { + if (arguments.length < 2) touches = d3_eventSource().touches; + return touches ? d3_array(touches).map(function(touch) { + var point = d3_mousePoint(container, touch); + point.identifier = touch.identifier; + return point; + }) : []; + }; + var ε = 1e-6, ε2 = ε * ε, π2 = Math.PI, τ = 2 * π2, τε = τ - ε, halfπ = π2 / 2, d3_radians = π2 / 180, d3_degrees = 180 / π2; + function d3_cross2d(a, b, c) { + return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); + } + function d3_asin(x) { + return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); + } + function d3_sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; + } + function d3_cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; + } + function d3_tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); + } + var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; + d32.interpolateZoom = function(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < ε2) { + S = Math.log(w1 / w0) / ρ; + i = function(t) { + return [ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S)]; + }; + } else { + var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); + S = (r1 - r0) / ρ; + i = function(t) { + var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); + return [ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0)]; + }; + } + i.duration = S * 1e3; + return i; + }; + d32.behavior.zoom = function() { + var view = { + x: 0, + y: 0, + k: 1 + }, translate0, center0, center, size = [960, 500], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom2, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; + if (!d3_behavior_zoomWheel) { + d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return -d32.event.deltaY * (d32.event.deltaMode ? 120 : 1); + }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { + return d32.event.wheelDelta; + }, "mousewheel") : (d3_behavior_zoomDelta = function() { + return -d32.event.detail; + }, "MozMousePixelScroll"); + } + function zoom2(g) { + g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); + } + zoom2.event = function(g) { + g.each(function() { + var dispatch = event.of(this, arguments), view1 = view; + if (d3_transitionInheritId) { + d32.select(this).transition().each("start.zoom", function() { + view = this.__chart__ || { + x: 0, + y: 0, + k: 1 + }; + zoomstarted(dispatch); + }).tween("zoom:zoom", function() { + var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d32.interpolateZoom([(cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k], [(cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k]); + return function(t) { + var l = i(t), k = dx / l[2]; + this.__chart__ = view = { + x: cx - l[0] * k, + y: cy - l[1] * k, + k + }; + zoomed(dispatch); + }; + }).each("interrupt.zoom", function() { + zoomended(dispatch); + }).each("end.zoom", function() { + zoomended(dispatch); + }); + } else { + this.__chart__ = view; + zoomstarted(dispatch); + zoomed(dispatch); + zoomended(dispatch); + } + }); + }; + zoom2.translate = function(_2) { + if (!arguments.length) return [view.x, view.y]; + view = { + x: +_2[0], + y: +_2[1], + k: view.k + }; + rescale(); + return zoom2; + }; + zoom2.scale = function(_2) { + if (!arguments.length) return view.k; + view = { + x: view.x, + y: view.y, + k: null + }; + scaleTo(+_2); + rescale(); + return zoom2; + }; + zoom2.scaleExtent = function(_2) { + if (!arguments.length) return scaleExtent; + scaleExtent = _2 == null ? d3_behavior_zoomInfinity : [+_2[0], +_2[1]]; + return zoom2; + }; + zoom2.center = function(_2) { + if (!arguments.length) return center; + center = _2 && [+_2[0], +_2[1]]; + return zoom2; + }; + zoom2.size = function(_2) { + if (!arguments.length) return size; + size = _2 && [+_2[0], +_2[1]]; + return zoom2; + }; + zoom2.duration = function(_2) { + if (!arguments.length) return duration; + duration = +_2; + return zoom2; + }; + zoom2.x = function(z) { + if (!arguments.length) return x1; + x1 = z; + x0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom2; + }; + zoom2.y = function(z) { + if (!arguments.length) return y1; + y1 = z; + y0 = z.copy(); + view = { + x: 0, + y: 0, + k: 1 + }; + return zoom2; + }; + function location(p) { + return [(p[0] - view.x) / view.k, (p[1] - view.y) / view.k]; + } + function point(l) { + return [l[0] * view.k + view.x, l[1] * view.k + view.y]; + } + function scaleTo(s) { + view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); + } + function translateTo(p, l) { + l = point(l); + view.x += p[0] - l[0]; + view.y += p[1] - l[1]; + } + function zoomTo(that, p, l, k) { + that.__chart__ = { + x: view.x, + y: view.y, + k: view.k + }; + scaleTo(Math.pow(2, k)); + translateTo(center0 = p, l); + that = d32.select(that); + if (duration > 0) that = that.transition().duration(duration); + that.call(zoom2.event); + } + function rescale() { + if (x1) x1.domain(x0.range().map(function(x) { + return (x - view.x) / view.k; + }).map(x0.invert)); + if (y1) y1.domain(y0.range().map(function(y) { + return (y - view.y) / view.k; + }).map(y0.invert)); + } + function zoomstarted(dispatch) { + if (!zooming++) dispatch({ + type: "zoomstart" + }); + } + function zoomed(dispatch) { + rescale(); + dispatch({ + type: "zoom", + scale: view.k, + translate: [view.x, view.y] + }); + } + function zoomended(dispatch) { + if (!--zooming) dispatch({ + type: "zoomend" + }), center0 = null; + } + function mousedowned() { + var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d32.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d32.mouse(that)), dragRestore = d3_event_dragSuppress(that); + d3_selection_interrupt.call(that); + zoomstarted(dispatch); + function moved() { + dragged = 1; + translateTo(d32.mouse(that), location0); + zoomed(dispatch); + } + function ended() { + subject.on(mousemove, null).on(mouseup, null); + dragRestore(dragged); + zoomended(dispatch); + } + } + function touchstarted() { + var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d32.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d32.select(that), dragRestore = d3_event_dragSuppress(that); + started(); + zoomstarted(dispatch); + subject.on(mousedown, null).on(touchstart, started); + function relocate() { + var touches = d32.touches(that); + scale0 = view.k; + touches.forEach(function(t) { + if (t.identifier in locations0) locations0[t.identifier] = location(t); + }); + return touches; + } + function started() { + var target = d32.event.target; + d32.select(target).on(touchmove, moved).on(touchend, ended); + targets.push(target); + var changed = d32.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + locations0[changed[i].identifier] = null; + } + var touches = relocate(), now = Date.now(); + if (touches.length === 1) { + if (now - touchtime < 500) { + var p = touches[0]; + zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); + d3_eventPreventDefault(); + } + touchtime = now; + } else if (touches.length > 1) { + var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; + distance0 = dx * dx + dy * dy; + } + } + function moved() { + var touches = d32.touches(that), p0, l0, p1, l1; + d3_selection_interrupt.call(that); + for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { + p1 = touches[i]; + if (l1 = locations0[p1.identifier]) { + if (l0) break; + p0 = p1, l0 = l1; + } + } + if (l1) { + var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); + p0 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2]; + l0 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2]; + scaleTo(scale1 * scale0); + } + touchtime = null; + translateTo(p0, l0); + zoomed(dispatch); + } + function ended() { + if (d32.event.touches.length) { + var changed = d32.event.changedTouches; + for (var i = 0, n = changed.length; i < n; ++i) { + delete locations0[changed[i].identifier]; + } + for (var identifier in locations0) { + return void relocate(); + } + } + d32.selectAll(targets).on(zoomName, null); + subject.on(mousedown, mousedowned).on(touchstart, touchstarted); + dragRestore(); + zoomended(dispatch); + } + } + function mousewheeled() { + var dispatch = event.of(this, arguments); + if (mousewheelTimer) clearTimeout(mousewheelTimer); + else d3_selection_interrupt.call(this), translate0 = location(center0 = center || d32.mouse(this)), zoomstarted(dispatch); + mousewheelTimer = setTimeout(function() { + mousewheelTimer = null; + zoomended(dispatch); + }, 50); + d3_eventPreventDefault(); + scaleTo(Math.pow(2, d3_behavior_zoomDelta() * 2e-3) * view.k); + translateTo(center0, translate0); + zoomed(dispatch); + } + function dblclicked() { + var p = d32.mouse(this), k = Math.log(view.k) / Math.LN2; + zoomTo(this, p, location(p), d32.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); + } + return d32.rebind(zoom2, event, "on"); + }; + var d3_behavior_zoomInfinity = [0, Infinity], d3_behavior_zoomDelta, d3_behavior_zoomWheel; + d32.color = d3_color; + function d3_color() { + } + d3_color.prototype.toString = function() { + return this.rgb() + ""; + }; + d32.hsl = d3_hsl; + function d3_hsl(h, s, l) { + return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); + } + var d3_hslPrototype = d3_hsl.prototype = new d3_color(); + d3_hslPrototype.brighter = function(k) { + k = Math.pow(0.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, this.l / k); + }; + d3_hslPrototype.darker = function(k) { + k = Math.pow(0.7, arguments.length ? k : 1); + return new d3_hsl(this.h, this.s, k * this.l); + }; + d3_hslPrototype.rgb = function() { + return d3_hsl_rgb(this.h, this.s, this.l); + }; + function d3_hsl_rgb(h, s, l) { + var m1, m2; + h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; + s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; + l = l < 0 ? 0 : l > 1 ? 1 : l; + m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s; + m1 = 2 * l - m2; + function v(h2) { + if (h2 > 360) h2 -= 360; + else if (h2 < 0) h2 += 360; + if (h2 < 60) return m1 + (m2 - m1) * h2 / 60; + if (h2 < 180) return m2; + if (h2 < 240) return m1 + (m2 - m1) * (240 - h2) / 60; + return m1; + } + function vv(h2) { + return Math.round(v(h2) * 255); + } + return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); + } + d32.hcl = d3_hcl; + function d3_hcl(h, c, l) { + return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d32.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); + } + var d3_hclPrototype = d3_hcl.prototype = new d3_color(); + d3_hclPrototype.brighter = function(k) { + return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.darker = function(k) { + return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); + }; + d3_hclPrototype.rgb = function() { + return d3_hcl_lab(this.h, this.c, this.l).rgb(); + }; + function d3_hcl_lab(h, c, l) { + if (isNaN(h)) h = 0; + if (isNaN(c)) c = 0; + return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); + } + d32.lab = d3_lab; + function d3_lab(l, a, b) { + return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); + } + var d3_lab_K = 18; + var d3_lab_X = 0.95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; + var d3_labPrototype = d3_lab.prototype = new d3_color(); + d3_labPrototype.brighter = function(k) { + return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.darker = function(k) { + return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); + }; + d3_labPrototype.rgb = function() { + return d3_lab_rgb(this.l, this.a, this.b); + }; + function d3_lab_rgb(l, a, b) { + var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; + x = d3_lab_xyz(x) * d3_lab_X; + y = d3_lab_xyz(y) * d3_lab_Y; + z = d3_lab_xyz(z) * d3_lab_Z; + return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), d3_xyz_rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), d3_xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z)); + } + function d3_lab_hcl(l, a, b) { + return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); + } + function d3_lab_xyz(x) { + return x > 0.206893034 ? x * x * x : (x - 4 / 29) / 7.787037; + } + function d3_xyz_lab(x) { + return x > 8856e-6 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; + } + function d3_xyz_rgb(r) { + return Math.round(255 * (r <= 304e-5 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - 0.055)); + } + d32.rgb = d3_rgb; + function d3_rgb(r, g, b) { + return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); + } + function d3_rgbNumber(value2) { + return new d3_rgb(value2 >> 16, value2 >> 8 & 255, value2 & 255); + } + function d3_rgbString(value2) { + return d3_rgbNumber(value2) + ""; + } + var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); + d3_rgbPrototype.brighter = function(k) { + k = Math.pow(0.7, arguments.length ? k : 1); + var r = this.r, g = this.g, b = this.b, i = 30; + if (!r && !g && !b) return new d3_rgb(i, i, i); + if (r && r < i) r = i; + if (g && g < i) g = i; + if (b && b < i) b = i; + return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); + }; + d3_rgbPrototype.darker = function(k) { + k = Math.pow(0.7, arguments.length ? k : 1); + return new d3_rgb(k * this.r, k * this.g, k * this.b); + }; + d3_rgbPrototype.hsl = function() { + return d3_rgb_hsl(this.r, this.g, this.b); + }; + d3_rgbPrototype.toString = function() { + return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); + }; + function d3_rgb_hex(v) { + return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); + } + function d3_rgb_parse(format2, rgb2, hsl2) { + var r = 0, g = 0, b = 0, m1, m2, color2; + m1 = /([a-z]+)\((.*)\)/.exec(format2 = format2.toLowerCase()); + if (m1) { + m2 = m1[2].split(","); + switch (m1[1]) { + case "hsl": { + return hsl2(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); + } + case "rgb": { + return rgb2(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); + } + } + } + if (color2 = d3_rgb_names.get(format2)) { + return rgb2(color2.r, color2.g, color2.b); + } + if (format2 != null && format2.charAt(0) === "#" && !isNaN(color2 = parseInt(format2.slice(1), 16))) { + if (format2.length === 4) { + r = (color2 & 3840) >> 4; + r = r >> 4 | r; + g = color2 & 240; + g = g >> 4 | g; + b = color2 & 15; + b = b << 4 | b; + } else if (format2.length === 7) { + r = (color2 & 16711680) >> 16; + g = (color2 & 65280) >> 8; + b = color2 & 255; + } + } + return rgb2(r, g, b); + } + function d3_rgb_hsl(r, g, b) { + var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; + if (d) { + s = l < 0.5 ? d / (max + min) : d / (2 - max - min); + if (r == max) h = (g - b) / d + (g < b ? 6 : 0); + else if (g == max) h = (b - r) / d + 2; + else h = (r - g) / d + 4; + h *= 60; + } else { + h = NaN; + s = l > 0 && l < 1 ? 0 : h; + } + return new d3_hsl(h, s, l); + } + function d3_rgb_lab(r, g, b) { + r = d3_rgb_xyz(r); + g = d3_rgb_xyz(g); + b = d3_rgb_xyz(b); + var x = d3_xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / d3_lab_X), y = d3_xyz_lab((0.2126729 * r + 0.7151522 * g + 0.072175 * b) / d3_lab_Y), z = d3_xyz_lab((0.0193339 * r + 0.119192 * g + 0.9503041 * b) / d3_lab_Z); + return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); + } + function d3_rgb_xyz(r) { + return (r /= 255) <= 0.04045 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4); + } + function d3_rgb_parseNumber(c) { + var f = parseFloat(c); + return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; + } + var d3_rgb_names = d32.map({ + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 + }); + d3_rgb_names.forEach(function(key, value2) { + d3_rgb_names.set(key, d3_rgbNumber(value2)); + }); + function d3_functor(v) { + return typeof v === "function" ? v : function() { + return v; + }; + } + d32.functor = d3_functor; + d32.xhr = d3_xhrType(d3_identity); + function d3_xhrType(response) { + return function(url, mimeType, callback) { + if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; + return d3_xhr(url, mimeType, response, callback); + }; + } + function d3_xhr(url, mimeType, response, callback) { + var xhr = {}, dispatch = d32.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; + if (self.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); + "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { + request.readyState > 3 && respond(); + }; + function respond() { + var status = request.status, result; + if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { + try { + result = response.call(xhr, request); + } catch (e) { + dispatch.error.call(xhr, e); + return; + } + dispatch.load.call(xhr, result); + } else { + dispatch.error.call(xhr, request); + } + } + request.onprogress = function(event) { + var o = d32.event; + d32.event = event; + try { + dispatch.progress.call(xhr, request); + } finally { + d32.event = o; + } + }; + xhr.header = function(name2, value2) { + name2 = (name2 + "").toLowerCase(); + if (arguments.length < 2) return headers[name2]; + if (value2 == null) delete headers[name2]; + else headers[name2] = value2 + ""; + return xhr; + }; + xhr.mimeType = function(value2) { + if (!arguments.length) return mimeType; + mimeType = value2 == null ? null : value2 + ""; + return xhr; + }; + xhr.responseType = function(value2) { + if (!arguments.length) return responseType; + responseType = value2; + return xhr; + }; + xhr.response = function(value2) { + response = value2; + return xhr; + }; + ["get", "post"].forEach(function(method) { + xhr[method] = function() { + return xhr.send.apply(xhr, [method].concat(d3_array(arguments))); + }; + }); + xhr.send = function(method, data, callback2) { + if (arguments.length === 2 && typeof data === "function") callback2 = data, data = null; + request.open(method, url, true); + if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; + if (request.setRequestHeader) for (var name2 in headers) request.setRequestHeader(name2, headers[name2]); + if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); + if (responseType != null) request.responseType = responseType; + if (callback2 != null) xhr.on("error", callback2).on("load", function(request2) { + callback2(null, request2); + }); + dispatch.beforesend.call(xhr, request); + request.send(data == null ? null : data); + return xhr; + }; + xhr.abort = function() { + request.abort(); + return xhr; + }; + d32.rebind(xhr, dispatch, "on"); + return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); + } + function d3_xhr_fixCallback(callback) { + return callback.length === 1 ? function(error, request) { + callback(error == null ? request : null); + } : callback; + } + function d3_xhrHasResponse(request) { + var type = request.responseType; + return type && type !== "text" ? request.response : request.responseText; + } + d32.dsv = function(delimiter, mimeType) { + var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); + function dsv(url, row, callback) { + if (arguments.length < 3) callback = row, row = null; + var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); + xhr.row = function(_2) { + return arguments.length ? xhr.response((row = _2) == null ? response : typedResponse(_2)) : row; + }; + return xhr; + } + function response(request) { + return dsv.parse(request.responseText); + } + function typedResponse(f) { + return function(request) { + return dsv.parse(request.responseText, f); + }; + } + dsv.parse = function(text, f) { + var o; + return dsv.parseRows(text, function(row, i) { + if (o) return o(row, i - 1); + var a = function(d) { + var obj = {}; + var len = row.length; + for (var k = 0; k < len; ++k) { + obj[row[k]] = d[k]; + } + return obj; + }; + o = f ? function(row2, i2) { + return f(a(row2), i2); + } : a; + }); + }; + dsv.parseRows = function(text, f) { + var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; + function token() { + if (I >= N) return EOF; + if (eol) return eol = false, EOL; + var j = I; + if (text.charCodeAt(j) === 34) { + var i = j; + while (i++ < N) { + if (text.charCodeAt(i) === 34) { + if (text.charCodeAt(i + 1) !== 34) break; + ++i; + } + } + I = i + 2; + var c = text.charCodeAt(i + 1); + if (c === 13) { + eol = true; + if (text.charCodeAt(i + 2) === 10) ++I; + } else if (c === 10) { + eol = true; + } + return text.slice(j + 1, i).replace(/""/g, '"'); + } + while (I < N) { + var c = text.charCodeAt(I++), k = 1; + if (c === 10) eol = true; + else if (c === 13) { + eol = true; + if (text.charCodeAt(I) === 10) ++I, ++k; + } else if (c !== delimiterCode) continue; + return text.slice(j, I - k); + } + return text.slice(j); + } + while ((t = token()) !== EOF) { + var a = []; + while (t !== EOL && t !== EOF) { + a.push(t); + t = token(); + } + if (f && (a = f(a, n++)) == null) continue; + rows.push(a); + } + return rows; + }; + dsv.format = function(rows) { + if (Array.isArray(rows[0])) return dsv.formatRows(rows); + var fieldSet = new d3_Set(), fields = []; + rows.forEach(function(row) { + for (var field in row) { + if (!fieldSet.has(field)) { + fields.push(fieldSet.add(field)); + } + } + }); + return [fields.map(formatValue2).join(delimiter)].concat(rows.map(function(row) { + return fields.map(function(field) { + return formatValue2(row[field]); + }).join(delimiter); + })).join("\n"); + }; + dsv.formatRows = function(rows) { + return rows.map(formatRow).join("\n"); + }; + function formatRow(row) { + return row.map(formatValue2).join(delimiter); + } + function formatValue2(text) { + return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; + } + return dsv; + }; + d32.csv = d32.dsv(",", "text/csv"); + d32.tsv = d32.dsv(" ", "text/tab-separated-values"); + var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { + setTimeout(callback, 17); + }; + d32.timer = function() { + d3_timer.apply(this, arguments); + }; + function d3_timer(callback, delay, then) { + var n = arguments.length; + if (n < 2) delay = 0; + if (n < 3) then = Date.now(); + var time = then + delay, timer = { + c: callback, + t: time, + n: null + }; + if (d3_timer_queueTail) d3_timer_queueTail.n = timer; + else d3_timer_queueHead = timer; + d3_timer_queueTail = timer; + if (!d3_timer_interval) { + d3_timer_timeout = clearTimeout(d3_timer_timeout); + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + return timer; + } + function d3_timer_step() { + var now = d3_timer_mark(), delay = d3_timer_sweep() - now; + if (delay > 24) { + if (isFinite(delay)) { + clearTimeout(d3_timer_timeout); + d3_timer_timeout = setTimeout(d3_timer_step, delay); + } + d3_timer_interval = 0; + } else { + d3_timer_interval = 1; + d3_timer_frame(d3_timer_step); + } + } + d32.timer.flush = function() { + d3_timer_mark(); + d3_timer_sweep(); + }; + function d3_timer_mark() { + var now = Date.now(), timer = d3_timer_queueHead; + while (timer) { + if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; + timer = timer.n; + } + return now; + } + function d3_timer_sweep() { + var t02, t12 = d3_timer_queueHead, time = Infinity; + while (t12) { + if (t12.c) { + if (t12.t < time) time = t12.t; + t12 = (t02 = t12).n; + } else { + t12 = t02 ? t02.n = t12.n : d3_timer_queueHead = t12.n; + } + } + d3_timer_queueTail = t02; + return time; + } + d32.round = function(x, n) { + return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); + }; + d32.geom = {}; + function d3_geom_pointX(d) { + return d[0]; + } + function d3_geom_pointY(d) { + return d[1]; + } + d32.geom.hull = function(vertices) { + var x = d3_geom_pointX, y = d3_geom_pointY; + if (arguments.length) return hull(vertices); + function hull(data) { + if (data.length < 3) return []; + var fx2 = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; + for (i = 0; i < n; i++) { + points.push([+fx2.call(this, data[i], i), +fy.call(this, data[i], i), i]); + } + points.sort(d3_geom_hullOrder); + for (i = 0; i < n; i++) flippedPoints.push([points[i][0], -points[i][1]]); + var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); + var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon2 = []; + for (i = upper.length - 1; i >= 0; --i) polygon2.push(data[points[upper[i]][2]]); + for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon2.push(data[points[lower[i]][2]]); + return polygon2; + } + hull.x = function(_2) { + return arguments.length ? (x = _2, hull) : x; + }; + hull.y = function(_2) { + return arguments.length ? (y = _2, hull) : y; + }; + return hull; + }; + function d3_geom_hullUpper(points) { + var n = points.length, hull = [0, 1], hs = 2; + for (var i = 2; i < n; i++) { + while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; + hull[hs++] = i; + } + return hull.slice(0, hs); + } + function d3_geom_hullOrder(a, b) { + return a[0] - b[0] || a[1] - b[1]; + } + d32.geom.polygon = function(coordinates) { + d3_subclass(coordinates, d3_geom_polygonPrototype); + return coordinates; + }; + var d3_geom_polygonPrototype = d32.geom.polygon.prototype = []; + d3_geom_polygonPrototype.area = function() { + var i = -1, n = this.length, a, b = this[n - 1], area2 = 0; + while (++i < n) { + a = b; + b = this[i]; + area2 += a[1] * b[0] - a[0] * b[1]; + } + return area2 * 0.5; + }; + d3_geom_polygonPrototype.centroid = function(k) { + var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; + if (!arguments.length) k = -1 / (6 * this.area()); + while (++i < n) { + a = b; + b = this[i]; + c = a[0] * b[1] - b[0] * a[1]; + x += (a[0] + b[0]) * c; + y += (a[1] + b[1]) * c; + } + return [x * k, y * k]; + }; + d3_geom_polygonPrototype.clip = function(subject) { + var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; + while (++i < n) { + input = subject.slice(); + subject.length = 0; + b = this[i]; + c = input[(m = input.length - closed) - 1]; + j = -1; + while (++j < m) { + d = input[j]; + if (d3_geom_polygonInside(d, a, b)) { + if (!d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + subject.push(d); + } else if (d3_geom_polygonInside(c, a, b)) { + subject.push(d3_geom_polygonIntersect(c, d, a, b)); + } + c = d; + } + if (closed) subject.push(subject[0]); + a = b; + } + return subject; + }; + function d3_geom_polygonInside(p, a, b) { + return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); + } + function d3_geom_polygonIntersect(c, d, a, b) { + var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); + return [x1 + ua * x21, y1 + ua * y21]; + } + function d3_geom_polygonClosed(coordinates) { + var a = coordinates[0], b = coordinates[coordinates.length - 1]; + return !(a[0] - b[0] || a[1] - b[1]); + } + var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; + function d3_geom_voronoiBeach() { + d3_geom_voronoiRedBlackNode(this); + this.edge = this.site = this.circle = null; + } + function d3_geom_voronoiCreateBeach(site) { + var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); + beach.site = site; + return beach; + } + function d3_geom_voronoiDetachBeach(beach) { + d3_geom_voronoiDetachCircle(beach); + d3_geom_voronoiBeaches.remove(beach); + d3_geom_voronoiBeachPool.push(beach); + d3_geom_voronoiRedBlackNode(beach); + } + function d3_geom_voronoiRemoveBeach(beach) { + var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { + x, + y + }, previous = beach.P, next = beach.N, disappearing = [beach]; + d3_geom_voronoiDetachBeach(beach); + var lArc = previous; + while (lArc.circle && abs2(x - lArc.circle.x) < ε && abs2(y - lArc.circle.cy) < ε) { + previous = lArc.P; + disappearing.unshift(lArc); + d3_geom_voronoiDetachBeach(lArc); + lArc = previous; + } + disappearing.unshift(lArc); + d3_geom_voronoiDetachCircle(lArc); + var rArc = next; + while (rArc.circle && abs2(x - rArc.circle.x) < ε && abs2(y - rArc.circle.cy) < ε) { + next = rArc.N; + disappearing.push(rArc); + d3_geom_voronoiDetachBeach(rArc); + rArc = next; + } + disappearing.push(rArc); + d3_geom_voronoiDetachCircle(rArc); + var nArcs = disappearing.length, iArc; + for (iArc = 1; iArc < nArcs; ++iArc) { + rArc = disappearing[iArc]; + lArc = disappearing[iArc - 1]; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); + } + lArc = disappearing[0]; + rArc = disappearing[nArcs - 1]; + rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiAddBeach(site) { + var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; + while (node) { + dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; + if (dxl > ε) node = node.L; + else { + dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); + if (dxr > ε) { + if (!node.R) { + lArc = node; + break; + } + node = node.R; + } else { + if (dxl > -1e-6) { + lArc = node.P; + rArc = node; + } else if (dxr > -1e-6) { + lArc = node; + rArc = node.N; + } else { + lArc = rArc = node; + } + break; + } + } + } + var newArc = d3_geom_voronoiCreateBeach(site); + d3_geom_voronoiBeaches.insert(lArc, newArc); + if (!lArc && !rArc) return; + if (lArc === rArc) { + d3_geom_voronoiDetachCircle(lArc); + rArc = d3_geom_voronoiCreateBeach(lArc.site); + d3_geom_voronoiBeaches.insert(newArc, rArc); + newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + return; + } + if (!rArc) { + newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); + return; + } + d3_geom_voronoiDetachCircle(lArc); + d3_geom_voronoiDetachCircle(rArc); + var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { + x: (cy * hb - by * hc) / d + ax, + y: (bx * hc - cx * hb) / d + ay + }; + d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); + newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); + rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); + d3_geom_voronoiAttachCircle(lArc); + d3_geom_voronoiAttachCircle(rArc); + } + function d3_geom_voronoiLeftBreakPoint(arc2, directrix) { + var site = arc2.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; + if (!pby2) return rfocx; + var lArc = arc2.P; + if (!lArc) return -Infinity; + site = lArc.site; + var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; + if (!plby2) return lfocx; + var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; + if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; + return (rfocx + lfocx) / 2; + } + function d3_geom_voronoiRightBreakPoint(arc2, directrix) { + var rArc = arc2.N; + if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); + var site = arc2.site; + return site.y === directrix ? site.x : Infinity; + } + function d3_geom_voronoiCell(site) { + this.site = site; + this.edges = []; + } + d3_geom_voronoiCell.prototype.prepare = function() { + var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; + while (iHalfEdge--) { + edge = halfEdges[iHalfEdge].edge; + if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); + } + halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); + return halfEdges.length; + }; + function d3_geom_voronoiCloseCells(extent2) { + var x0 = extent2[0][0], x1 = extent2[1][0], y0 = extent2[0][1], y1 = extent2[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; + while (iCell--) { + cell = cells[iCell]; + if (!cell || !cell.prepare()) continue; + halfEdges = cell.edges; + nHalfEdges = halfEdges.length; + iHalfEdge = 0; + while (iHalfEdge < nHalfEdges) { + end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; + start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; + if (abs2(x3 - x2) > ε || abs2(y3 - y2) > ε) { + halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs2(x3 - x0) < ε && y1 - y3 > ε ? { + x: x0, + y: abs2(x2 - x0) < ε ? y2 : y1 + } : abs2(y3 - y1) < ε && x1 - x3 > ε ? { + x: abs2(y2 - y1) < ε ? x2 : x1, + y: y1 + } : abs2(x3 - x1) < ε && y3 - y0 > ε ? { + x: x1, + y: abs2(x2 - x1) < ε ? y2 : y0 + } : abs2(y3 - y0) < ε && x3 - x0 > ε ? { + x: abs2(y2 - y0) < ε ? x2 : x0, + y: y0 + } : null), cell.site, null)); + ++nHalfEdges; + } + } + } + } + function d3_geom_voronoiHalfEdgeOrder(a, b) { + return b.angle - a.angle; + } + function d3_geom_voronoiCircle() { + d3_geom_voronoiRedBlackNode(this); + this.x = this.y = this.arc = this.site = this.cy = null; + } + function d3_geom_voronoiAttachCircle(arc2) { + var lArc = arc2.P, rArc = arc2.N; + if (!lArc || !rArc) return; + var lSite = lArc.site, cSite = arc2.site, rSite = rArc.site; + if (lSite === rSite) return; + var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; + var d = 2 * (ax * cy - ay * cx); + if (d >= -1e-12) return; + var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; + var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); + circle.arc = arc2; + circle.site = cSite; + circle.x = x + bx; + circle.y = cy + Math.sqrt(x * x + y * y); + circle.cy = cy; + arc2.circle = circle; + var before = null, node = d3_geom_voronoiCircles._; + while (node) { + if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { + if (node.L) node = node.L; + else { + before = node.P; + break; + } + } else { + if (node.R) node = node.R; + else { + before = node; + break; + } + } + } + d3_geom_voronoiCircles.insert(before, circle); + if (!before) d3_geom_voronoiFirstCircle = circle; + } + function d3_geom_voronoiDetachCircle(arc2) { + var circle = arc2.circle; + if (circle) { + if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; + d3_geom_voronoiCircles.remove(circle); + d3_geom_voronoiCirclePool.push(circle); + d3_geom_voronoiRedBlackNode(circle); + arc2.circle = null; + } + } + function d3_geom_clipLine(x0, y0, x1, y1) { + return function(line2) { + var a = line2.a, b = line2.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t02 = 0, t12 = 1, dx = bx - ax, dy = by - ay, r; + r = x0 - ax; + if (!dx && r > 0) return; + r /= dx; + if (dx < 0) { + if (r < t02) return; + if (r < t12) t12 = r; + } else if (dx > 0) { + if (r > t12) return; + if (r > t02) t02 = r; + } + r = x1 - ax; + if (!dx && r < 0) return; + r /= dx; + if (dx < 0) { + if (r > t12) return; + if (r > t02) t02 = r; + } else if (dx > 0) { + if (r < t02) return; + if (r < t12) t12 = r; + } + r = y0 - ay; + if (!dy && r > 0) return; + r /= dy; + if (dy < 0) { + if (r < t02) return; + if (r < t12) t12 = r; + } else if (dy > 0) { + if (r > t12) return; + if (r > t02) t02 = r; + } + r = y1 - ay; + if (!dy && r < 0) return; + r /= dy; + if (dy < 0) { + if (r > t12) return; + if (r > t02) t02 = r; + } else if (dy > 0) { + if (r < t02) return; + if (r < t12) t12 = r; + } + if (t02 > 0) line2.a = { + x: ax + t02 * dx, + y: ay + t02 * dy + }; + if (t12 < 1) line2.b = { + x: ax + t12 * dx, + y: ay + t12 * dy + }; + return line2; + }; + } + function d3_geom_voronoiClipEdges(extent2) { + var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent2[0][0], extent2[0][1], extent2[1][0], extent2[1][1]), i = edges.length, e; + while (i--) { + e = edges[i]; + if (!d3_geom_voronoiConnectEdge(e, extent2) || !clip(e) || abs2(e.a.x - e.b.x) < ε && abs2(e.a.y - e.b.y) < ε) { + e.a = e.b = null; + edges.splice(i, 1); + } + } + } + function d3_geom_voronoiConnectEdge(edge, extent2) { + var vb = edge.b; + if (vb) return true; + var va = edge.a, x0 = extent2[0][0], x1 = extent2[1][0], y0 = extent2[0][1], y1 = extent2[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx2 = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; + if (ry === ly) { + if (fx2 < x0 || fx2 >= x1) return; + if (lx > rx) { + if (!va) va = { + x: fx2, + y: y0 + }; + else if (va.y >= y1) return; + vb = { + x: fx2, + y: y1 + }; + } else { + if (!va) va = { + x: fx2, + y: y1 + }; + else if (va.y < y0) return; + vb = { + x: fx2, + y: y0 + }; + } + } else { + fm = (lx - rx) / (ry - ly); + fb = fy - fm * fx2; + if (fm < -1 || fm > 1) { + if (lx > rx) { + if (!va) va = { + x: (y0 - fb) / fm, + y: y0 + }; + else if (va.y >= y1) return; + vb = { + x: (y1 - fb) / fm, + y: y1 + }; + } else { + if (!va) va = { + x: (y1 - fb) / fm, + y: y1 + }; + else if (va.y < y0) return; + vb = { + x: (y0 - fb) / fm, + y: y0 + }; + } + } else { + if (ly < ry) { + if (!va) va = { + x: x0, + y: fm * x0 + fb + }; + else if (va.x >= x1) return; + vb = { + x: x1, + y: fm * x1 + fb + }; + } else { + if (!va) va = { + x: x1, + y: fm * x1 + fb + }; + else if (va.x < x0) return; + vb = { + x: x0, + y: fm * x0 + fb + }; + } + } + } + edge.a = va; + edge.b = vb; + return true; + } + function d3_geom_voronoiEdge(lSite, rSite) { + this.l = lSite; + this.r = rSite; + this.a = this.b = null; + } + function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, rSite); + d3_geom_voronoiEdges.push(edge); + if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); + if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); + d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); + d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); + return edge; + } + function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { + var edge = new d3_geom_voronoiEdge(lSite, null); + edge.a = va; + edge.b = vb; + d3_geom_voronoiEdges.push(edge); + return edge; + } + function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { + if (!edge.a && !edge.b) { + edge.a = vertex; + edge.l = lSite; + edge.r = rSite; + } else if (edge.l === rSite) { + edge.b = vertex; + } else { + edge.a = vertex; + } + } + function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { + var va = edge.a, vb = edge.b; + this.edge = edge; + this.site = lSite; + this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); + } + d3_geom_voronoiHalfEdge.prototype = { + start: function() { + return this.edge.l === this.site ? this.edge.a : this.edge.b; + }, + end: function() { + return this.edge.l === this.site ? this.edge.b : this.edge.a; + } + }; + function d3_geom_voronoiRedBlackTree() { + this._ = null; + } + function d3_geom_voronoiRedBlackNode(node) { + node.U = node.C = node.L = node.R = node.P = node.N = null; + } + d3_geom_voronoiRedBlackTree.prototype = { + insert: function(after, node) { + var parent, grandpa, uncle; + if (after) { + node.P = after; + node.N = after.N; + if (after.N) after.N.P = node; + after.N = node; + if (after.R) { + after = after.R; + while (after.L) after = after.L; + after.L = node; + } else { + after.R = node; + } + parent = after; + } else if (this._) { + after = d3_geom_voronoiRedBlackFirst(this._); + node.P = null; + node.N = after; + after.P = after.L = node; + parent = after; + } else { + node.P = node.N = null; + this._ = node; + parent = null; + } + node.L = node.R = null; + node.U = parent; + node.C = true; + after = node; + while (parent && parent.C) { + grandpa = parent.U; + if (parent === grandpa.L) { + uncle = grandpa.R; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.R) { + d3_geom_voronoiRedBlackRotateLeft(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateRight(this, grandpa); + } + } else { + uncle = grandpa.L; + if (uncle && uncle.C) { + parent.C = uncle.C = false; + grandpa.C = true; + after = grandpa; + } else { + if (after === parent.L) { + d3_geom_voronoiRedBlackRotateRight(this, parent); + after = parent; + parent = after.U; + } + parent.C = false; + grandpa.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, grandpa); + } + } + parent = after.U; + } + this._.C = false; + }, + remove: function(node) { + if (node.N) node.N.P = node.P; + if (node.P) node.P.N = node.N; + node.N = node.P = null; + var parent = node.U, sibling, left = node.L, right = node.R, next, red; + if (!left) next = right; + else if (!right) next = left; + else next = d3_geom_voronoiRedBlackFirst(right); + if (parent) { + if (parent.L === node) parent.L = next; + else parent.R = next; + } else { + this._ = next; + } + if (left && right) { + red = next.C; + next.C = node.C; + next.L = left; + left.U = next; + if (next !== right) { + parent = next.U; + next.U = node.U; + node = next.R; + parent.L = node; + next.R = right; + right.U = next; + } else { + next.U = parent; + parent = next; + node = next.R; + } + } else { + red = node.C; + node = next; + } + if (node) node.U = parent; + if (red) return; + if (node && node.C) { + node.C = false; + return; + } + do { + if (node === this._) break; + if (node === parent.L) { + sibling = parent.R; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + sibling = parent.R; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.R || !sibling.R.C) { + sibling.L.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateRight(this, sibling); + sibling = parent.R; + } + sibling.C = parent.C; + parent.C = sibling.R.C = false; + d3_geom_voronoiRedBlackRotateLeft(this, parent); + node = this._; + break; + } + } else { + sibling = parent.L; + if (sibling.C) { + sibling.C = false; + parent.C = true; + d3_geom_voronoiRedBlackRotateRight(this, parent); + sibling = parent.L; + } + if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { + if (!sibling.L || !sibling.L.C) { + sibling.R.C = false; + sibling.C = true; + d3_geom_voronoiRedBlackRotateLeft(this, sibling); + sibling = parent.L; + } + sibling.C = parent.C; + parent.C = sibling.L.C = false; + d3_geom_voronoiRedBlackRotateRight(this, parent); + node = this._; + break; + } + } + sibling.C = true; + node = parent; + parent = parent.U; + } while (!node.C); + if (node) node.C = false; + } + }; + function d3_geom_voronoiRedBlackRotateLeft(tree2, node) { + var p = node, q = node.R, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; + else parent.R = q; + } else { + tree2._ = q; + } + q.U = parent; + p.U = q; + p.R = q.L; + if (p.R) p.R.U = p; + q.L = p; + } + function d3_geom_voronoiRedBlackRotateRight(tree2, node) { + var p = node, q = node.L, parent = p.U; + if (parent) { + if (parent.L === p) parent.L = q; + else parent.R = q; + } else { + tree2._ = q; + } + q.U = parent; + p.U = q; + p.L = q.R; + if (p.L) p.L.U = p; + q.R = p; + } + function d3_geom_voronoiRedBlackFirst(node) { + while (node.L) node = node.L; + return node; + } + function d3_geom_voronoi(sites, bbox) { + var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; + d3_geom_voronoiEdges = []; + d3_geom_voronoiCells = new Array(sites.length); + d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); + d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); + while (true) { + circle = d3_geom_voronoiFirstCircle; + if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { + if (site.x !== x0 || site.y !== y0) { + d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); + d3_geom_voronoiAddBeach(site); + x0 = site.x, y0 = site.y; + } + site = sites.pop(); + } else if (circle) { + d3_geom_voronoiRemoveBeach(circle.arc); + } else { + break; + } + } + if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); + var diagram = { + cells: d3_geom_voronoiCells, + edges: d3_geom_voronoiEdges + }; + d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; + return diagram; + } + function d3_geom_voronoiVertexOrder(a, b) { + return b.y - a.y || b.x - a.x; + } + d32.geom.voronoi = function(points) { + var x = d3_geom_pointX, y = d3_geom_pointY, fx2 = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; + if (points) return voronoi(points); + function voronoi(data) { + var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; + d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { + var edges = cell.edges, site = cell.site, polygon2 = polygons[i] = edges.length ? edges.map(function(e) { + var s = e.start(); + return [s.x, s.y]; + }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [[x0, y1], [x1, y1], [x1, y0], [x0, y0]] : []; + polygon2.point = data[i]; + }); + return polygons; + } + function sites(data) { + return data.map(function(d, i) { + return { + x: Math.round(fx2(d, i) / ε) * ε, + y: Math.round(fy(d, i) / ε) * ε, + i + }; + }); + } + voronoi.links = function(data) { + return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { + return edge.l && edge.r; + }).map(function(edge) { + return { + source: data[edge.l.i], + target: data[edge.r.i] + }; + }); + }; + voronoi.triangles = function(data) { + var triangles = []; + d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { + var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; + while (++j < m) { + s0 = s1; + e1 = edges[j].edge; + s1 = e1.l === site ? e1.r : e1.l; + if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { + triangles.push([data[i], data[s0.i], data[s1.i]]); + } + } + }); + return triangles; + }; + voronoi.x = function(_2) { + return arguments.length ? (fx2 = d3_functor(x = _2), voronoi) : x; + }; + voronoi.y = function(_2) { + return arguments.length ? (fy = d3_functor(y = _2), voronoi) : y; + }; + voronoi.clipExtent = function(_2) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; + clipExtent = _2 == null ? d3_geom_voronoiClipExtent : _2; + return voronoi; + }; + voronoi.size = function(_2) { + if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; + return voronoi.clipExtent(_2 && [[0, 0], _2]); + }; + return voronoi; + }; + var d3_geom_voronoiClipExtent = [[-1e6, -1e6], [1e6, 1e6]]; + function d3_geom_voronoiTriangleArea(a, b, c) { + return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); + } + d32.geom.delaunay = function(vertices) { + return d32.geom.voronoi().triangles(vertices); + }; + d32.geom.quadtree = function(points, x1, y1, x2, y2) { + var x = d3_geom_pointX, y = d3_geom_pointY, compat; + if (compat = arguments.length) { + x = d3_geom_quadtreeCompatX; + y = d3_geom_quadtreeCompatY; + if (compat === 3) { + y2 = y1; + x2 = x1; + y1 = x1 = 0; + } + return quadtree(points); + } + function quadtree(data) { + var d, fx2 = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; + if (x1 != null) { + x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; + } else { + x2_ = y2_ = -(x1_ = y1_ = Infinity); + xs = [], ys = []; + n = data.length; + if (compat) for (i = 0; i < n; ++i) { + d = data[i]; + if (d.x < x1_) x1_ = d.x; + if (d.y < y1_) y1_ = d.y; + if (d.x > x2_) x2_ = d.x; + if (d.y > y2_) y2_ = d.y; + xs.push(d.x); + ys.push(d.y); + } + else for (i = 0; i < n; ++i) { + var x_ = +fx2(d = data[i], i), y_ = +fy(d, i); + if (x_ < x1_) x1_ = x_; + if (y_ < y1_) y1_ = y_; + if (x_ > x2_) x2_ = x_; + if (y_ > y2_) y2_ = y_; + xs.push(x_); + ys.push(y_); + } + } + var dx = x2_ - x1_, dy = y2_ - y1_; + if (dx > dy) y2_ = y1_ + dx; + else x2_ = x1_ + dy; + function insert(n2, d2, x3, y3, x12, y12, x22, y22) { + if (isNaN(x3) || isNaN(y3)) return; + if (n2.leaf) { + var nx = n2.x, ny = n2.y; + if (nx != null) { + if (abs2(nx - x3) + abs2(ny - y3) < 0.01) { + insertChild(n2, d2, x3, y3, x12, y12, x22, y22); + } else { + var nPoint = n2.point; + n2.x = n2.y = n2.point = null; + insertChild(n2, nPoint, nx, ny, x12, y12, x22, y22); + insertChild(n2, d2, x3, y3, x12, y12, x22, y22); + } + } else { + n2.x = x3, n2.y = y3, n2.point = d2; + } + } else { + insertChild(n2, d2, x3, y3, x12, y12, x22, y22); + } + } + function insertChild(n2, d2, x3, y3, x12, y12, x22, y22) { + var xm = (x12 + x22) * 0.5, ym = (y12 + y22) * 0.5, right = x3 >= xm, below = y3 >= ym, i2 = below << 1 | right; + n2.leaf = false; + n2 = n2.nodes[i2] || (n2.nodes[i2] = d3_geom_quadtreeNode()); + if (right) x12 = xm; + else x22 = xm; + if (below) y12 = ym; + else y22 = ym; + insert(n2, d2, x3, y3, x12, y12, x22, y22); + } + var root = d3_geom_quadtreeNode(); + root.add = function(d2) { + insert(root, d2, +fx2(d2, ++i), +fy(d2, i), x1_, y1_, x2_, y2_); + }; + root.visit = function(f) { + d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); + }; + root.find = function(point) { + return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); + }; + i = -1; + if (x1 == null) { + while (++i < n) { + insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); + } + --i; + } else data.forEach(root.add); + xs = ys = data = d = null; + return root; + } + quadtree.x = function(_2) { + return arguments.length ? (x = _2, quadtree) : x; + }; + quadtree.y = function(_2) { + return arguments.length ? (y = _2, quadtree) : y; + }; + quadtree.extent = function(_2) { + if (!arguments.length) return x1 == null ? null : [[x1, y1], [x2, y2]]; + if (_2 == null) x1 = y1 = x2 = y2 = null; + else x1 = +_2[0][0], y1 = +_2[0][1], x2 = +_2[1][0], y2 = +_2[1][1]; + return quadtree; + }; + quadtree.size = function(_2) { + if (!arguments.length) return x1 == null ? null : [x2 - x1, y2 - y1]; + if (_2 == null) x1 = y1 = x2 = y2 = null; + else x1 = y1 = 0, x2 = +_2[0], y2 = +_2[1]; + return quadtree; + }; + return quadtree; + }; + function d3_geom_quadtreeCompatX(d) { + return d.x; + } + function d3_geom_quadtreeCompatY(d) { + return d.y; + } + function d3_geom_quadtreeNode() { + return { + leaf: true, + nodes: [], + point: null, + x: null, + y: null + }; + } + function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { + if (!f(node, x1, y1, x2, y2)) { + var sx = (x1 + x2) * 0.5, sy = (y1 + y2) * 0.5, children = node.nodes; + if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); + if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); + if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); + if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); + } + } + function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { + var minDistance2 = Infinity, closestPoint; + (function find(node, x1, y1, x2, y2) { + if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; + if (point = node.point) { + var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; + if (distance2 < minDistance2) { + var distance = Math.sqrt(minDistance2 = distance2); + x0 = x - distance, y0 = y - distance; + x3 = x + distance, y3 = y + distance; + closestPoint = point; + } + } + var children = node.nodes, xm = (x1 + x2) * 0.5, ym = (y1 + y2) * 0.5, right = x >= xm, below = y >= ym; + for (var i = below << 1 | right, j = i + 4; i < j; ++i) { + if (node = children[i & 3]) switch (i & 3) { + case 0: + find(node, x1, y1, xm, ym); + break; + case 1: + find(node, xm, y1, x2, ym); + break; + case 2: + find(node, x1, ym, xm, y2); + break; + case 3: + find(node, xm, ym, x2, y2); + break; + } + } + })(root, x0, y0, x3, y3); + return closestPoint; + } + d32.interpolateRgb = d3_interpolateRgb; + function d3_interpolateRgb(a, b) { + a = d32.rgb(a); + b = d32.rgb(b); + var ar = a.r, ag = a.g, ab2 = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab2; + return function(t) { + return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab2 + bb * t)); + }; + } + d32.interpolateObject = d3_interpolateObject; + function d3_interpolateObject(a, b) { + var i = {}, c = {}, k; + for (k in a) { + if (k in b) { + i[k] = d3_interpolate(a[k], b[k]); + } else { + c[k] = a[k]; + } + } + for (k in b) { + if (!(k in a)) { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; + } + d32.interpolateNumber = d3_interpolateNumber; + function d3_interpolateNumber(a, b) { + a = +a, b = +b; + return function(t) { + return a * (1 - t) + b * t; + }; + } + d32.interpolateString = d3_interpolateString; + function d3_interpolateString(a, b) { + var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; + else s[++i] = bm; + } else { + s[++i] = null; + q.push({ + i, + x: d3_interpolateNumber(am, bm) + }); + } + bi = d3_interpolate_numberB.lastIndex; + } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { + return b(t) + ""; + }) : function() { + return b; + } : (b = q.length, function(t) { + for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t); + return s.join(""); + }); + } + var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); + d32.interpolate = d3_interpolate; + function d3_interpolate(a, b) { + var i = d32.interpolators.length, f; + while (--i >= 0 && !(f = d32.interpolators[i](a, b))) ; + return f; + } + d32.interpolators = [function(a, b) { + var t = typeof b; + return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); + }]; + d32.interpolateArray = d3_interpolateArray; + function d3_interpolateArray(a, b) { + var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; + for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); + for (; i < na; ++i) c[i] = a[i]; + for (; i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < n0; ++i) c[i] = x[i](t); + return c; + }; + } + var d3_ease_default = function() { + return d3_identity; + }; + var d3_ease = d32.map({ + linear: d3_ease_default, + poly: d3_ease_poly, + quad: function() { + return d3_ease_quad; + }, + cubic: function() { + return d3_ease_cubic; + }, + sin: function() { + return d3_ease_sin; + }, + exp: function() { + return d3_ease_exp; + }, + circle: function() { + return d3_ease_circle; + }, + elastic: d3_ease_elastic, + back: d3_ease_back, + bounce: function() { + return d3_ease_bounce; + } + }); + var d3_ease_mode = d32.map({ + "in": d3_identity, + out: d3_ease_reverse, + "in-out": d3_ease_reflect, + "out-in": function(f) { + return d3_ease_reflect(d3_ease_reverse(f)); + } + }); + d32.ease = function(name2) { + var i = name2.indexOf("-"), t = i >= 0 ? name2.slice(0, i) : name2, m = i >= 0 ? name2.slice(i + 1) : "in"; + t = d3_ease.get(t) || d3_ease_default; + m = d3_ease_mode.get(m) || d3_identity; + return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); + }; + function d3_ease_clamp(f) { + return function(t) { + return t <= 0 ? 0 : t >= 1 ? 1 : f(t); + }; + } + function d3_ease_reverse(f) { + return function(t) { + return 1 - f(1 - t); + }; + } + function d3_ease_reflect(f) { + return function(t) { + return 0.5 * (t < 0.5 ? f(2 * t) : 2 - f(2 - 2 * t)); + }; + } + function d3_ease_quad(t) { + return t * t; + } + function d3_ease_cubic(t) { + return t * t * t; + } + function d3_ease_cubicInOut(t) { + if (t <= 0) return 0; + if (t >= 1) return 1; + var t22 = t * t, t32 = t22 * t; + return 4 * (t < 0.5 ? t32 : 3 * (t - t22) + t32 - 0.75); + } + function d3_ease_poly(e) { + return function(t) { + return Math.pow(t, e); + }; + } + function d3_ease_sin(t) { + return 1 - Math.cos(t * halfπ); + } + function d3_ease_exp(t) { + return Math.pow(2, 10 * (t - 1)); + } + function d3_ease_circle(t) { + return 1 - Math.sqrt(1 - t * t); + } + function d3_ease_elastic(a, p) { + var s; + if (arguments.length < 2) p = 0.45; + if (arguments.length) s = p / τ * Math.asin(1 / a); + else a = 1, s = p / 4; + return function(t) { + return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); + }; + } + function d3_ease_back(s) { + if (!s) s = 1.70158; + return function(t) { + return t * t * ((s + 1) * t - s); + }; + } + function d3_ease_bounce(t) { + return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375 : 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375; + } + d32.interpolateHcl = d3_interpolateHcl; + function d3_interpolateHcl(a, b) { + a = d32.hcl(a); + b = d32.hcl(b); + var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; + if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; + else if (bh > 180) bh -= 360; + else if (bh < -180) bh += 360; + return function(t) { + return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; + }; + } + d32.interpolateHsl = d3_interpolateHsl; + function d3_interpolateHsl(a, b) { + a = d32.hsl(a); + b = d32.hsl(b); + var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; + if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; + if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; + else if (bh > 180) bh -= 360; + else if (bh < -180) bh += 360; + return function(t) { + return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; + }; + } + d32.interpolateLab = d3_interpolateLab; + function d3_interpolateLab(a, b) { + a = d32.lab(a); + b = d32.lab(b); + var al = a.l, aa = a.a, ab2 = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab2; + return function(t) { + return d3_lab_rgb(al + bl * t, aa + ba * t, ab2 + bb * t) + ""; + }; + } + d32.interpolateRound = d3_interpolateRound; + function d3_interpolateRound(a, b) { + b -= a; + return function(t) { + return Math.round(a + b * t); + }; + } + d32.transform = function(string2) { + var g = d3_document.createElementNS(d32.ns.prefix.svg, "g"); + return (d32.transform = function(string3) { + if (string3 != null) { + g.setAttribute("transform", string3); + var t = g.transform.baseVal.consolidate(); + } + return new d3_transform(t ? t.matrix : d3_transformIdentity); + })(string2); + }; + function d3_transform(m) { + var r0 = [m.a, m.b], r1 = [m.c, m.d], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; + if (r0[0] * r1[1] < r1[0] * r0[1]) { + r0[0] *= -1; + r0[1] *= -1; + kx *= -1; + kz *= -1; + } + this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; + this.translate = [m.e, m.f]; + this.scale = [kx, ky]; + this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; + } + d3_transform.prototype.toString = function() { + return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; + }; + function d3_transformDot(a, b) { + return a[0] * b[0] + a[1] * b[1]; + } + function d3_transformNormalize(a) { + var k = Math.sqrt(d3_transformDot(a, a)); + if (k) { + a[0] /= k; + a[1] /= k; + } + return k; + } + function d3_transformCombine(a, b, k) { + a[0] += k * b[0]; + a[1] += k * b[1]; + return a; + } + var d3_transformIdentity = { + a: 1, + b: 0, + c: 0, + d: 1, + e: 0, + f: 0 + }; + d32.interpolateTransform = d3_interpolateTransform; + function d3_interpolateTransformPop(s) { + return s.length ? s.pop() + "," : ""; + } + function d3_interpolateTranslate(ta, tb, s, q) { + if (ta[0] !== tb[0] || ta[1] !== tb[1]) { + var i = s.push("translate(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ta[0], tb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ta[1], tb[1]) + }); + } else if (tb[0] || tb[1]) { + s.push("translate(" + tb + ")"); + } + } + function d3_interpolateRotate(ra, rb, s, q) { + if (ra !== rb) { + if (ra - rb > 180) rb += 360; + else if (rb - ra > 180) ra += 360; + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, + x: d3_interpolateNumber(ra, rb) + }); + } else if (rb) { + s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); + } + } + function d3_interpolateSkew(wa, wb, s, q) { + if (wa !== wb) { + q.push({ + i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, + x: d3_interpolateNumber(wa, wb) + }); + } else if (wb) { + s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); + } + } + function d3_interpolateScale(ka, kb, s, q) { + if (ka[0] !== kb[0] || ka[1] !== kb[1]) { + var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); + q.push({ + i: i - 4, + x: d3_interpolateNumber(ka[0], kb[0]) + }, { + i: i - 2, + x: d3_interpolateNumber(ka[1], kb[1]) + }); + } else if (kb[0] !== 1 || kb[1] !== 1) { + s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); + } + } + function d3_interpolateTransform(a, b) { + var s = [], q = []; + a = d32.transform(a), b = d32.transform(b); + d3_interpolateTranslate(a.translate, b.translate, s, q); + d3_interpolateRotate(a.rotate, b.rotate, s, q); + d3_interpolateSkew(a.skew, b.skew, s, q); + d3_interpolateScale(a.scale, b.scale, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + } + function d3_uninterpolateNumber(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return (x - a) / b; + }; + } + function d3_uninterpolateClamp(a, b) { + b = (b -= a = +a) || 1 / b; + return function(x) { + return Math.max(0, Math.min(1, (x - a) / b)); + }; + } + d32.layout = {}; + d32.layout.bundle = function() { + return function(links) { + var paths = [], i = -1, n = links.length; + while (++i < n) paths.push(d3_layout_bundlePath(links[i])); + return paths; + }; + }; + function d3_layout_bundlePath(link) { + var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [start]; + while (start !== lca) { + start = start.parent; + points.push(start); + } + var k = points.length; + while (end !== lca) { + points.splice(k, 0, end); + end = end.parent; + } + return points; + } + function d3_layout_bundleAncestors(node) { + var ancestors = [], parent = node.parent; + while (parent != null) { + ancestors.push(node); + node = parent; + parent = parent.parent; + } + ancestors.push(node); + return ancestors; + } + function d3_layout_bundleLeastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; + while (aNode === bNode) { + sharedNode = aNode; + aNode = aNodes.pop(); + bNode = bNodes.pop(); + } + return sharedNode; + } + d32.layout.chord = function() { + var chord = {}, chords, groups, matrix2, n, padding = 0, sortGroups, sortSubgroups, sortChords; + function relayout() { + var subgroups = {}, groupSums = [], groupIndex = d32.range(n), subgroupIndex = [], k, x, x0, i, j; + chords = []; + groups = []; + k = 0, i = -1; + while (++i < n) { + x = 0, j = -1; + while (++j < n) { + x += matrix2[i][j]; + } + groupSums.push(x); + subgroupIndex.push(d32.range(n)); + k += x; + } + if (sortGroups) { + groupIndex.sort(function(a, b) { + return sortGroups(groupSums[a], groupSums[b]); + }); + } + if (sortSubgroups) { + subgroupIndex.forEach(function(d, i2) { + d.sort(function(a, b) { + return sortSubgroups(matrix2[i2][a], matrix2[i2][b]); + }); + }); + } + k = (τ - padding * n) / k; + x = 0, i = -1; + while (++i < n) { + x0 = x, j = -1; + while (++j < n) { + var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix2[di][dj], a0 = x, a1 = x += v * k; + subgroups[di + "-" + dj] = { + index: di, + subindex: dj, + startAngle: a0, + endAngle: a1, + value: v + }; + } + groups[di] = { + index: di, + startAngle: x0, + endAngle: x, + value: groupSums[di] + }; + x += padding; + } + i = -1; + while (++i < n) { + j = i - 1; + while (++j < n) { + var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; + if (source.value || target.value) { + chords.push(source.value < target.value ? { + source: target, + target: source + } : { + source, + target + }); + } + } + } + if (sortChords) resort(); + } + function resort() { + chords.sort(function(a, b) { + return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); + }); + } + chord.matrix = function(x) { + if (!arguments.length) return matrix2; + n = (matrix2 = x) && matrix2.length; + chords = groups = null; + return chord; + }; + chord.padding = function(x) { + if (!arguments.length) return padding; + padding = x; + chords = groups = null; + return chord; + }; + chord.sortGroups = function(x) { + if (!arguments.length) return sortGroups; + sortGroups = x; + chords = groups = null; + return chord; + }; + chord.sortSubgroups = function(x) { + if (!arguments.length) return sortSubgroups; + sortSubgroups = x; + chords = null; + return chord; + }; + chord.sortChords = function(x) { + if (!arguments.length) return sortChords; + sortChords = x; + if (chords) resort(); + return chord; + }; + chord.chords = function() { + if (!chords) relayout(); + return chords; + }; + chord.groups = function() { + if (!groups) relayout(); + return groups; + }; + return chord; + }; + d32.layout.force = function() { + var force = {}, event = d32.dispatch("start", "tick", "end"), timer, size = [1, 1], drag, alpha, friction = 0.9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = 0.1, theta2 = 0.64, nodes = [], links = [], distances, strengths, charges; + function repulse(node) { + return function(quad2, x1, _2, x2) { + if (quad2.point !== node) { + var dx = quad2.cx - node.x, dy = quad2.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; + if (dw * dw / theta2 < dn) { + if (dn < chargeDistance2) { + var k = quad2.charge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + return true; + } + if (quad2.point && dn && dn < chargeDistance2) { + var k = quad2.pointCharge / dn; + node.px -= dx * k; + node.py -= dy * k; + } + } + return !quad2.charge; + }; + } + force.tick = function() { + if ((alpha *= 0.99) < 5e-3) { + timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + return true; + } + var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; + for (i = 0; i < m; ++i) { + o = links[i]; + s = o.source; + t = o.target; + x = t.x - s.x; + y = t.y - s.y; + if (l = x * x + y * y) { + l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; + x *= l; + y *= l; + t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : 0.5); + t.y -= y * k; + s.x += x * (k = 1 - k); + s.y += y * k; + } + } + if (k = alpha * gravity) { + x = size[0] / 2; + y = size[1] / 2; + i = -1; + if (k) while (++i < n) { + o = nodes[i]; + o.x += (x - o.x) * k; + o.y += (y - o.y) * k; + } + } + if (charge) { + d3_layout_forceAccumulate(q = d32.geom.quadtree(nodes), alpha, charges); + i = -1; + while (++i < n) { + if (!(o = nodes[i]).fixed) { + q.visit(repulse(o)); + } + } + } + i = -1; + while (++i < n) { + o = nodes[i]; + if (o.fixed) { + o.x = o.px; + o.y = o.py; + } else { + o.x -= (o.px - (o.px = o.x)) * friction; + o.y -= (o.py - (o.py = o.y)) * friction; + } + } + event.tick({ + type: "tick", + alpha + }); + }; + force.nodes = function(x) { + if (!arguments.length) return nodes; + nodes = x; + return force; + }; + force.links = function(x) { + if (!arguments.length) return links; + links = x; + return force; + }; + force.size = function(x) { + if (!arguments.length) return size; + size = x; + return force; + }; + force.linkDistance = function(x) { + if (!arguments.length) return linkDistance; + linkDistance = typeof x === "function" ? x : +x; + return force; + }; + force.distance = force.linkDistance; + force.linkStrength = function(x) { + if (!arguments.length) return linkStrength; + linkStrength = typeof x === "function" ? x : +x; + return force; + }; + force.friction = function(x) { + if (!arguments.length) return friction; + friction = +x; + return force; + }; + force.charge = function(x) { + if (!arguments.length) return charge; + charge = typeof x === "function" ? x : +x; + return force; + }; + force.chargeDistance = function(x) { + if (!arguments.length) return Math.sqrt(chargeDistance2); + chargeDistance2 = x * x; + return force; + }; + force.gravity = function(x) { + if (!arguments.length) return gravity; + gravity = +x; + return force; + }; + force.theta = function(x) { + if (!arguments.length) return Math.sqrt(theta2); + theta2 = x * x; + return force; + }; + force.alpha = function(x) { + if (!arguments.length) return alpha; + x = +x; + if (alpha) { + if (x > 0) { + alpha = x; + } else { + timer.c = null, timer.t = NaN, timer = null; + event.end({ + type: "end", + alpha: alpha = 0 + }); + } + } else if (x > 0) { + event.start({ + type: "start", + alpha: alpha = x + }); + timer = d3_timer(force.tick); + } + return force; + }; + force.start = function() { + var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; + for (i = 0; i < n; ++i) { + (o = nodes[i]).index = i; + o.weight = 0; + } + for (i = 0; i < m; ++i) { + o = links[i]; + if (typeof o.source == "number") o.source = nodes[o.source]; + if (typeof o.target == "number") o.target = nodes[o.target]; + ++o.source.weight; + ++o.target.weight; + } + for (i = 0; i < n; ++i) { + o = nodes[i]; + if (isNaN(o.x)) o.x = position("x", w); + if (isNaN(o.y)) o.y = position("y", h); + if (isNaN(o.px)) o.px = o.x; + if (isNaN(o.py)) o.py = o.y; + } + distances = []; + if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); + else for (i = 0; i < m; ++i) distances[i] = linkDistance; + strengths = []; + if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); + else for (i = 0; i < m; ++i) strengths[i] = linkStrength; + charges = []; + if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); + else for (i = 0; i < n; ++i) charges[i] = charge; + function position(dimension, size2) { + if (!neighbors) { + neighbors = new Array(n); + for (j = 0; j < n; ++j) { + neighbors[j] = []; + } + for (j = 0; j < m; ++j) { + var o2 = links[j]; + neighbors[o2.source.index].push(o2.target); + neighbors[o2.target.index].push(o2.source); + } + } + var candidates = neighbors[i], j = -1, l = candidates.length, x; + while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; + return Math.random() * size2; + } + return force.resume(); + }; + force.resume = function() { + return force.alpha(0.1); + }; + force.stop = function() { + return force.alpha(0); + }; + force.drag = function() { + if (!drag) drag = d32.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); + if (!arguments.length) return drag; + this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); + }; + function dragmove(d) { + d.px = d32.event.x, d.py = d32.event.y; + force.resume(); + } + return d32.rebind(force, event, "on"); + }; + function d3_layout_forceDragstart(d) { + d.fixed |= 2; + } + function d3_layout_forceDragend(d) { + d.fixed &= -7; + } + function d3_layout_forceMouseover(d) { + d.fixed |= 4; + d.px = d.x, d.py = d.y; + } + function d3_layout_forceMouseout(d) { + d.fixed &= -5; + } + function d3_layout_forceAccumulate(quad2, alpha, charges) { + var cx = 0, cy = 0; + quad2.charge = 0; + if (!quad2.leaf) { + var nodes = quad2.nodes, n = nodes.length, i = -1, c; + while (++i < n) { + c = nodes[i]; + if (c == null) continue; + d3_layout_forceAccumulate(c, alpha, charges); + quad2.charge += c.charge; + cx += c.charge * c.cx; + cy += c.charge * c.cy; + } + } + if (quad2.point) { + if (!quad2.leaf) { + quad2.point.x += Math.random() - 0.5; + quad2.point.y += Math.random() - 0.5; + } + var k = alpha * charges[quad2.point.index]; + quad2.charge += quad2.pointCharge = k; + cx += k * quad2.point.x; + cy += k * quad2.point.y; + } + quad2.cx = cx / quad2.charge; + quad2.cy = cy / quad2.charge; + } + var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; + d32.layout.hierarchy = function() { + var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value2 = d3_layout_hierarchyValue; + function hierarchy2(root) { + var stack = [root], nodes = [], node; + root.depth = 0; + while ((node = stack.pop()) != null) { + nodes.push(node); + if ((childs = children.call(hierarchy2, node, node.depth)) && (n = childs.length)) { + var n, childs, child; + while (--n >= 0) { + stack.push(child = childs[n]); + child.parent = node; + child.depth = node.depth + 1; + } + if (value2) node.value = 0; + node.children = childs; + } else { + if (value2) node.value = +value2.call(hierarchy2, node, node.depth) || 0; + delete node.children; + } + } + d3_layout_hierarchyVisitAfter(root, function(node2) { + var childs2, parent; + if (sort && (childs2 = node2.children)) childs2.sort(sort); + if (value2 && (parent = node2.parent)) parent.value += node2.value; + }); + return nodes; + } + hierarchy2.sort = function(x) { + if (!arguments.length) return sort; + sort = x; + return hierarchy2; + }; + hierarchy2.children = function(x) { + if (!arguments.length) return children; + children = x; + return hierarchy2; + }; + hierarchy2.value = function(x) { + if (!arguments.length) return value2; + value2 = x; + return hierarchy2; + }; + hierarchy2.revalue = function(root) { + if (value2) { + d3_layout_hierarchyVisitBefore(root, function(node) { + if (node.children) node.value = 0; + }); + d3_layout_hierarchyVisitAfter(root, function(node) { + var parent; + if (!node.children) node.value = +value2.call(hierarchy2, node, node.depth) || 0; + if (parent = node.parent) parent.value += node.value; + }); + } + return root; + }; + return hierarchy2; + }; + function d3_layout_hierarchyRebind(object2, hierarchy2) { + d32.rebind(object2, hierarchy2, "sort", "children", "value"); + object2.nodes = object2; + object2.links = d3_layout_hierarchyLinks; + return object2; + } + function d3_layout_hierarchyVisitBefore(node, callback) { + var nodes = [node]; + while ((node = nodes.pop()) != null) { + callback(node); + if ((children = node.children) && (n = children.length)) { + var n, children; + while (--n >= 0) nodes.push(children[n]); + } + } + } + function d3_layout_hierarchyVisitAfter(node, callback) { + var nodes = [node], nodes2 = []; + while ((node = nodes.pop()) != null) { + nodes2.push(node); + if ((children = node.children) && (n = children.length)) { + var i = -1, n, children; + while (++i < n) nodes.push(children[i]); + } + } + while ((node = nodes2.pop()) != null) { + callback(node); + } + } + function d3_layout_hierarchyChildren(d) { + return d.children; + } + function d3_layout_hierarchyValue(d) { + return d.value; + } + function d3_layout_hierarchySort(a, b) { + return b.value - a.value; + } + function d3_layout_hierarchyLinks(nodes) { + return d32.merge(nodes.map(function(parent) { + return (parent.children || []).map(function(child) { + return { + source: parent, + target: child + }; + }); + })); + } + d32.layout.partition = function() { + var hierarchy2 = d32.layout.hierarchy(), size = [1, 1]; + function position(node, x, dx, dy) { + var children = node.children; + node.x = x; + node.y = node.depth * dy; + node.dx = dx; + node.dy = dy; + if (children && (n = children.length)) { + var i = -1, n, c, d; + dx = node.value ? dx / node.value : 0; + while (++i < n) { + position(c = children[i], x, d = c.value * dx, dy); + x += d; + } + } + } + function depth(node) { + var children = node.children, d = 0; + if (children && (n = children.length)) { + var i = -1, n; + while (++i < n) d = Math.max(d, depth(children[i])); + } + return 1 + d; + } + function partition3(d, i) { + var nodes = hierarchy2.call(this, d, i); + position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); + return nodes; + } + partition3.size = function(x) { + if (!arguments.length) return size; + size = x; + return partition3; + }; + return d3_layout_hierarchyRebind(partition3, hierarchy2); + }; + d32.layout.pie = function() { + var value2 = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; + function pie2(data) { + var n = data.length, values = data.map(function(d, i) { + return +value2.call(pie2, d, i); + }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d32.sum(values), k = sum ? (da - n * pa) / sum : 0, index2 = d32.range(n), arcs = [], v; + if (sort != null) index2.sort(sort === d3_layout_pieSortByValue ? function(i, j) { + return values[j] - values[i]; + } : function(i, j) { + return sort(data[i], data[j]); + }); + index2.forEach(function(i) { + arcs[i] = { + data: data[i], + value: v = values[i], + startAngle: a, + endAngle: a += v * k + pa, + padAngle: p + }; + }); + return arcs; + } + pie2.value = function(_2) { + if (!arguments.length) return value2; + value2 = _2; + return pie2; + }; + pie2.sort = function(_2) { + if (!arguments.length) return sort; + sort = _2; + return pie2; + }; + pie2.startAngle = function(_2) { + if (!arguments.length) return startAngle; + startAngle = _2; + return pie2; + }; + pie2.endAngle = function(_2) { + if (!arguments.length) return endAngle; + endAngle = _2; + return pie2; + }; + pie2.padAngle = function(_2) { + if (!arguments.length) return padAngle; + padAngle = _2; + return pie2; + }; + return pie2; + }; + var d3_layout_pieSortByValue = {}; + d32.layout.stack = function() { + var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; + function stack(data, index2) { + if (!(n = data.length)) return data; + var series = data.map(function(d, i2) { + return values.call(stack, d, i2); + }); + var points = series.map(function(d) { + return d.map(function(v, i2) { + return [x.call(stack, v, i2), y.call(stack, v, i2)]; + }); + }); + var orders = order.call(stack, points, index2); + series = d32.permute(series, orders); + points = d32.permute(points, orders); + var offsets = offset.call(stack, points, index2); + var m = series[0].length, n, i, j, o; + for (j = 0; j < m; ++j) { + out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); + for (i = 1; i < n; ++i) { + out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); + } + } + return data; + } + stack.values = function(x2) { + if (!arguments.length) return values; + values = x2; + return stack; + }; + stack.order = function(x2) { + if (!arguments.length) return order; + order = typeof x2 === "function" ? x2 : d3_layout_stackOrders.get(x2) || d3_layout_stackOrderDefault; + return stack; + }; + stack.offset = function(x2) { + if (!arguments.length) return offset; + offset = typeof x2 === "function" ? x2 : d3_layout_stackOffsets.get(x2) || d3_layout_stackOffsetZero; + return stack; + }; + stack.x = function(z) { + if (!arguments.length) return x; + x = z; + return stack; + }; + stack.y = function(z) { + if (!arguments.length) return y; + y = z; + return stack; + }; + stack.out = function(z) { + if (!arguments.length) return out; + out = z; + return stack; + }; + return stack; + }; + function d3_layout_stackX(d) { + return d.x; + } + function d3_layout_stackY(d) { + return d.y; + } + function d3_layout_stackOut(d, y0, y) { + d.y0 = y0; + d.y = y; + } + var d3_layout_stackOrders = d32.map({ + "inside-out": function(data) { + var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index2 = d32.range(n).sort(function(a, b) { + return max[a] - max[b]; + }), top = 0, bottom = 0, tops = [], bottoms = []; + for (i = 0; i < n; ++i) { + j = index2[i]; + if (top < bottom) { + top += sums[j]; + tops.push(j); + } else { + bottom += sums[j]; + bottoms.push(j); + } + } + return bottoms.reverse().concat(tops); + }, + reverse: function(data) { + return d32.range(data.length).reverse(); + }, + "default": d3_layout_stackOrderDefault + }); + var d3_layout_stackOffsets = d32.map({ + silhouette: function(data) { + var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o > max) max = o; + sums.push(o); + } + for (j = 0; j < m; ++j) { + y0[j] = (max - sums[j]) / 2; + } + return y0; + }, + wiggle: function(data) { + var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; + y0[0] = o = o0 = 0; + for (j = 1; j < m; ++j) { + for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; + for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { + for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { + s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; + } + s2 += s3 * data[i][j][1]; + } + y0[j] = o -= s1 ? s2 / s1 * dx : 0; + if (o < o0) o0 = o; + } + for (j = 0; j < m; ++j) y0[j] -= o0; + return y0; + }, + expand: function(data) { + var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; + for (j = 0; j < m; ++j) { + for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; + if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; + else for (i = 0; i < n; i++) data[i][j][1] = k; + } + for (j = 0; j < m; ++j) y0[j] = 0; + return y0; + }, + zero: d3_layout_stackOffsetZero + }); + function d3_layout_stackOrderDefault(data) { + return d32.range(data.length); + } + function d3_layout_stackOffsetZero(data) { + var j = -1, m = data[0].length, y0 = []; + while (++j < m) y0[j] = 0; + return y0; + } + function d3_layout_stackMaxIndex(array2) { + var i = 1, j = 0, v = array2[0][1], k, n = array2.length; + for (; i < n; ++i) { + if ((k = array2[i][1]) > v) { + j = i; + v = k; + } + } + return j; + } + function d3_layout_stackReduceSum(d) { + return d.reduce(d3_layout_stackSum, 0); + } + function d3_layout_stackSum(p, d) { + return p + d[1]; + } + d32.layout.histogram = function() { + var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; + function histogram2(data, i) { + var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; + while (++i < m) { + bin = bins[i] = []; + bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); + bin.y = 0; + } + if (m > 0) { + i = -1; + while (++i < n) { + x = values[i]; + if (x >= range[0] && x <= range[1]) { + bin = bins[d32.bisect(thresholds, x, 1, m) - 1]; + bin.y += k; + bin.push(data[i]); + } + } + } + return bins; + } + histogram2.value = function(x) { + if (!arguments.length) return valuer; + valuer = x; + return histogram2; + }; + histogram2.range = function(x) { + if (!arguments.length) return ranger; + ranger = d3_functor(x); + return histogram2; + }; + histogram2.bins = function(x) { + if (!arguments.length) return binner; + binner = typeof x === "number" ? function(range) { + return d3_layout_histogramBinFixed(range, x); + } : d3_functor(x); + return histogram2; + }; + histogram2.frequency = function(x) { + if (!arguments.length) return frequency; + frequency = !!x; + return histogram2; + }; + return histogram2; + }; + function d3_layout_histogramBinSturges(range, values) { + return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); + } + function d3_layout_histogramBinFixed(range, n) { + var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; + while (++x <= n) f[x] = m * x + b; + return f; + } + function d3_layout_histogramRange(values) { + return [d32.min(values), d32.max(values)]; + } + d32.layout.pack = function() { + var hierarchy2 = d32.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [1, 1], radius; + function pack(d, i) { + var nodes = hierarchy2.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { + return radius; + }; + root.x = root.y = 0; + d3_layout_hierarchyVisitAfter(root, function(d2) { + d2.r = +r(d2.value); + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + if (padding) { + var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; + d3_layout_hierarchyVisitAfter(root, function(d2) { + d2.r += dr; + }); + d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); + d3_layout_hierarchyVisitAfter(root, function(d2) { + d2.r -= dr; + }); + } + d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); + return nodes; + } + pack.size = function(_2) { + if (!arguments.length) return size; + size = _2; + return pack; + }; + pack.radius = function(_2) { + if (!arguments.length) return radius; + radius = _2 == null || typeof _2 === "function" ? _2 : +_2; + return pack; + }; + pack.padding = function(_2) { + if (!arguments.length) return padding; + padding = +_2; + return pack; + }; + return d3_layout_hierarchyRebind(pack, hierarchy2); + }; + function d3_layout_packSort(a, b) { + return a.value - b.value; + } + function d3_layout_packInsert(a, b) { + var c = a._pack_next; + a._pack_next = b; + b._pack_prev = a; + b._pack_next = c; + c._pack_prev = b; + } + function d3_layout_packSplice(a, b) { + a._pack_next = b; + b._pack_prev = a; + } + function d3_layout_packIntersects(a, b) { + var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; + return 0.999 * dr * dr > dx * dx + dy * dy; + } + function d3_layout_packSiblings(node) { + if (!(nodes = node.children) || !(n = nodes.length)) return; + var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; + function bound(node2) { + xMin = Math.min(node2.x - node2.r, xMin); + xMax = Math.max(node2.x + node2.r, xMax); + yMin = Math.min(node2.y - node2.r, yMin); + yMax = Math.max(node2.y + node2.r, yMax); + } + nodes.forEach(d3_layout_packLink); + a = nodes[0]; + a.x = -a.r; + a.y = 0; + bound(a); + if (n > 1) { + b = nodes[1]; + b.x = b.r; + b.y = 0; + bound(b); + if (n > 2) { + c = nodes[2]; + d3_layout_packPlace(a, b, c); + bound(c); + d3_layout_packInsert(a, c); + a._pack_prev = c; + d3_layout_packInsert(c, b); + b = a._pack_next; + for (i = 3; i < n; i++) { + d3_layout_packPlace(a, b, c = nodes[i]); + var isect = 0, s1 = 1, s2 = 1; + for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { + if (d3_layout_packIntersects(j, c)) { + isect = 1; + break; + } + } + if (isect == 1) { + for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { + if (d3_layout_packIntersects(k, c)) { + break; + } + } + } + if (isect) { + if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); + else d3_layout_packSplice(a = k, b); + i--; + } else { + d3_layout_packInsert(a, c); + b = c; + bound(c); + } + } + } + } + var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; + for (i = 0; i < n; i++) { + c = nodes[i]; + c.x -= cx; + c.y -= cy; + cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); + } + node.r = cr; + nodes.forEach(d3_layout_packUnlink); + } + function d3_layout_packLink(node) { + node._pack_next = node._pack_prev = node; + } + function d3_layout_packUnlink(node) { + delete node._pack_next; + delete node._pack_prev; + } + function d3_layout_packTransform(node, x, y, k) { + var children = node.children; + node.x = x += k * node.x; + node.y = y += k * node.y; + node.r *= k; + if (children) { + var i = -1, n = children.length; + while (++i < n) d3_layout_packTransform(children[i], x, y, k); + } + } + function d3_layout_packPlace(a, b, c) { + var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; + if (db && (dx || dy)) { + var da = b.r + c.r, dc = dx * dx + dy * dy; + da *= da; + db *= db; + var x = 0.5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); + c.x = a.x + x * dx + y * dy; + c.y = a.y + x * dy - y * dx; + } else { + c.x = a.x + db; + c.y = a.y; + } + } + d32.layout.tree = function() { + var hierarchy2 = d32.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = null; + function tree2(d, i) { + var nodes = hierarchy2.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); + d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; + d3_layout_hierarchyVisitBefore(root1, secondWalk); + if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); + else { + var left = root0, right = root0, bottom = root0; + d3_layout_hierarchyVisitBefore(root0, function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); + d3_layout_hierarchyVisitBefore(root0, function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); + } + return nodes; + } + function wrapTree(root0) { + var root1 = { + A: null, + children: [root0] + }, queue2 = [root1], node1; + while ((node1 = queue2.pop()) != null) { + for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { + queue2.push((children[i] = child = { + _: children[i], + parent: node1, + children: (child = children[i].children) && child.slice() || [], + A: null, + a: null, + z: 0, + m: 0, + c: 0, + s: 0, + t: null, + i + }).a = child); + } + } + return root1.children[0]; + } + function firstWalk(v) { + var children = v.children, siblings2 = v.parent.children, w = v.i ? siblings2[v.i - 1] : null; + if (children.length) { + d3_layout_treeShift(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; + } + } else if (w) { + v.z = w.z + separation(v._, w._); + } + v.parent.A = apportion(v, w, v.parent.A || siblings2[0]); + } + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; + } + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { + vom = d3_layout_treeLeft(vom); + vop = d3_layout_treeRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !d3_layout_treeRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !d3_layout_treeLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; + } + function sizeNode(node) { + node.x *= size[0]; + node.y = node.depth * size[1]; + } + tree2.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return tree2; + }; + tree2.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null ? sizeNode : null; + return tree2; + }; + tree2.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) == null ? null : sizeNode; + return tree2; + }; + return d3_layout_hierarchyRebind(tree2, hierarchy2); + }; + function d3_layout_treeSeparation(a, b) { + return a.parent == b.parent ? 1 : 2; + } + function d3_layout_treeLeft(v) { + var children = v.children; + return children.length ? children[0] : v.t; + } + function d3_layout_treeRight(v) { + var children = v.children, n; + return (n = children.length) ? children[n - 1] : v.t; + } + function d3_layout_treeMove(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; + } + function d3_layout_treeShift(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); + } + } + function d3_layout_treeAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; + } + d32.layout.cluster = function() { + var hierarchy2 = d32.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = false; + function cluster3(d, i) { + var nodes = hierarchy2.call(this, d, i), root = nodes[0], previousNode, x = 0; + d3_layout_hierarchyVisitAfter(root, function(node) { + var children = node.children; + if (children && children.length) { + node.x = d3_layout_clusterX(children); + node.y = d3_layout_clusterY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { + node.x = (node.x - root.x) * size[0]; + node.y = (root.y - node.y) * size[1]; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * size[0]; + node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; + }); + return nodes; + } + cluster3.separation = function(x) { + if (!arguments.length) return separation; + separation = x; + return cluster3; + }; + cluster3.size = function(x) { + if (!arguments.length) return nodeSize ? null : size; + nodeSize = (size = x) == null; + return cluster3; + }; + cluster3.nodeSize = function(x) { + if (!arguments.length) return nodeSize ? size : null; + nodeSize = (size = x) != null; + return cluster3; + }; + return d3_layout_hierarchyRebind(cluster3, hierarchy2); + }; + function d3_layout_clusterY(children) { + return 1 + d32.max(children, function(child) { + return child.y; + }); + } + function d3_layout_clusterX(children) { + return children.reduce(function(x, child) { + return x + child.x; + }, 0) / children.length; + } + function d3_layout_clusterLeft(node) { + var children = node.children; + return children && children.length ? d3_layout_clusterLeft(children[0]) : node; + } + function d3_layout_clusterRight(node) { + var children = node.children, n; + return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; + } + d32.layout.treemap = function() { + var hierarchy2 = d32.layout.hierarchy(), round2 = Math.round, size = [1, 1], padding = null, pad2 = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = 0.5 * (1 + Math.sqrt(5)); + function scale2(children, k) { + var i = -1, n = children.length, child, area2; + while (++i < n) { + area2 = (child = children[i]).value * (k < 0 ? 0 : k); + child.area = isNaN(area2) || area2 <= 0 ? 0 : area2; + } + } + function squarify2(node) { + var children = node.children; + if (children && children.length) { + var rect2 = pad2(node), row = [], remaining = children.slice(), child, best = Infinity, score2, u = mode === "slice" ? rect2.dx : mode === "dice" ? rect2.dy : mode === "slice-dice" ? node.depth & 1 ? rect2.dy : rect2.dx : Math.min(rect2.dx, rect2.dy), n; + scale2(remaining, rect2.dx * rect2.dy / node.value); + row.area = 0; + while ((n = remaining.length) > 0) { + row.push(child = remaining[n - 1]); + row.area += child.area; + if (mode !== "squarify" || (score2 = worst(row, u)) <= best) { + remaining.pop(); + best = score2; + } else { + row.area -= row.pop().area; + position(row, u, rect2, false); + u = Math.min(rect2.dx, rect2.dy); + row.length = row.area = 0; + best = Infinity; + } + } + if (row.length) { + position(row, u, rect2, true); + row.length = row.area = 0; + } + children.forEach(squarify2); + } + } + function stickify(node) { + var children = node.children; + if (children && children.length) { + var rect2 = pad2(node), remaining = children.slice(), child, row = []; + scale2(remaining, rect2.dx * rect2.dy / node.value); + row.area = 0; + while (child = remaining.pop()) { + row.push(child); + row.area += child.area; + if (child.z != null) { + position(row, child.z ? rect2.dx : rect2.dy, rect2, !remaining.length); + row.length = row.area = 0; + } + } + children.forEach(stickify); + } + } + function worst(row, u) { + var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; + while (++i < n) { + if (!(r = row[i].area)) continue; + if (r < rmin) rmin = r; + if (r > rmax) rmax = r; + } + s *= s; + u *= u; + return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; + } + function position(row, u, rect2, flush) { + var i = -1, n = row.length, x = rect2.x, y = rect2.y, v = u ? round2(row.area / u) : 0, o; + if (u == rect2.dx) { + if (flush || v > rect2.dy) v = rect2.dy; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dy = v; + x += o.dx = Math.min(rect2.x + rect2.dx - x, v ? round2(o.area / v) : 0); + } + o.z = true; + o.dx += rect2.x + rect2.dx - x; + rect2.y += v; + rect2.dy -= v; + } else { + if (flush || v > rect2.dx) v = rect2.dx; + while (++i < n) { + o = row[i]; + o.x = x; + o.y = y; + o.dx = v; + y += o.dy = Math.min(rect2.y + rect2.dy - y, v ? round2(o.area / v) : 0); + } + o.z = false; + o.dy += rect2.y + rect2.dy - y; + rect2.x += v; + rect2.dx -= v; + } + } + function treemap2(d) { + var nodes = stickies || hierarchy2(d), root = nodes[0]; + root.x = root.y = 0; + if (root.value) root.dx = size[0], root.dy = size[1]; + else root.dx = root.dy = 0; + if (stickies) hierarchy2.revalue(root); + scale2([root], root.dx * root.dy / root.value); + (stickies ? stickify : squarify2)(root); + if (sticky) stickies = nodes; + return nodes; + } + treemap2.size = function(x) { + if (!arguments.length) return size; + size = x; + return treemap2; + }; + treemap2.padding = function(x) { + if (!arguments.length) return padding; + function padFunction(node) { + var p = x.call(treemap2, node, node.depth); + return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p); + } + function padConstant(node) { + return d3_layout_treemapPad(node, x); + } + var type; + pad2 = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [x, x, x, x], padConstant) : padConstant; + return treemap2; + }; + treemap2.round = function(x) { + if (!arguments.length) return round2 != Number; + round2 = x ? Math.round : Number; + return treemap2; + }; + treemap2.sticky = function(x) { + if (!arguments.length) return sticky; + sticky = x; + stickies = null; + return treemap2; + }; + treemap2.ratio = function(x) { + if (!arguments.length) return ratio; + ratio = x; + return treemap2; + }; + treemap2.mode = function(x) { + if (!arguments.length) return mode; + mode = x + ""; + return treemap2; + }; + return d3_layout_hierarchyRebind(treemap2, hierarchy2); + }; + function d3_layout_treemapPadNull(node) { + return { + x: node.x, + y: node.y, + dx: node.dx, + dy: node.dy + }; + } + function d3_layout_treemapPad(node, padding) { + var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; + if (dx < 0) { + x += dx / 2; + dx = 0; + } + if (dy < 0) { + y += dy / 2; + dy = 0; + } + return { + x, + y, + dx, + dy + }; + } + d32.random = { + normal: function(mu, sigma) { + var n = arguments.length; + if (n < 2) sigma = 1; + if (n < 1) mu = 0; + return function() { + var x, y, r; + do { + x = Math.random() * 2 - 1; + y = Math.random() * 2 - 1; + r = x * x + y * y; + } while (!r || r > 1); + return mu + sigma * x * Math.sqrt(-2 * Math.log(r) / r); + }; + }, + logNormal: function() { + var random = d32.random.normal.apply(d32, arguments); + return function() { + return Math.exp(random()); + }; + }, + bates: function(m) { + var random = d32.random.irwinHall(m); + return function() { + return random() / m; + }; + }, + irwinHall: function(m) { + return function() { + for (var s = 0, j = 0; j < m; j++) s += Math.random(); + return s; + }; + } + }; + d32.scale = {}; + function d3_scaleExtent(domain2) { + var start = domain2[0], stop = domain2[domain2.length - 1]; + return start < stop ? [start, stop] : [stop, start]; + } + function d3_scaleRange(scale2) { + return scale2.rangeExtent ? scale2.rangeExtent() : d3_scaleExtent(scale2.range()); + } + function d3_scale_bilinear(domain2, range, uninterpolate, interpolate2) { + var u = uninterpolate(domain2[0], domain2[1]), i = interpolate2(range[0], range[1]); + return function(x) { + return i(u(x)); + }; + } + function d3_scale_nice(domain2, nice) { + var i0 = 0, i1 = domain2.length - 1, x0 = domain2[i0], x1 = domain2[i1], dx; + if (x1 < x0) { + dx = i0, i0 = i1, i1 = dx; + dx = x0, x0 = x1, x1 = dx; + } + domain2[i0] = nice.floor(x0); + domain2[i1] = nice.ceil(x1); + return domain2; + } + function d3_scale_niceStep(step) { + return step ? { + floor: function(x) { + return Math.floor(x / step) * step; + }, + ceil: function(x) { + return Math.ceil(x / step) * step; + } + } : d3_scale_niceIdentity; + } + var d3_scale_niceIdentity = { + floor: d3_identity, + ceil: d3_identity + }; + function d3_scale_polylinear(domain2, range, uninterpolate, interpolate2) { + var u = [], i = [], j = 0, k = Math.min(domain2.length, range.length) - 1; + if (domain2[k] < domain2[0]) { + domain2 = domain2.slice().reverse(); + range = range.slice().reverse(); + } + while (++j <= k) { + u.push(uninterpolate(domain2[j - 1], domain2[j])); + i.push(interpolate2(range[j - 1], range[j])); + } + return function(x) { + var j2 = d32.bisect(domain2, x, 1, k) - 1; + return i[j2](u[j2](x)); + }; + } + d32.scale.linear = function() { + return d3_scale_linear([0, 1], [0, 1], d3_interpolate, false); + }; + function d3_scale_linear(domain2, range, interpolate2, clamp2) { + var output, input; + function rescale() { + var linear2 = Math.min(domain2.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp2 ? d3_uninterpolateClamp : d3_uninterpolateNumber; + output = linear2(domain2, range, uninterpolate, interpolate2); + input = linear2(range, domain2, uninterpolate, d3_interpolate); + return scale2; + } + function scale2(x) { + return output(x); + } + scale2.invert = function(y) { + return input(y); + }; + scale2.domain = function(x) { + if (!arguments.length) return domain2; + domain2 = x.map(Number); + return rescale(); + }; + scale2.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale2.rangeRound = function(x) { + return scale2.range(x).interpolate(d3_interpolateRound); + }; + scale2.clamp = function(x) { + if (!arguments.length) return clamp2; + clamp2 = x; + return rescale(); + }; + scale2.interpolate = function(x) { + if (!arguments.length) return interpolate2; + interpolate2 = x; + return rescale(); + }; + scale2.ticks = function(m) { + return d3_scale_linearTicks(domain2, m); + }; + scale2.tickFormat = function(m, format2) { + return d3_scale_linearTickFormat(domain2, m, format2); + }; + scale2.nice = function(m) { + d3_scale_linearNice(domain2, m); + return rescale(); + }; + scale2.copy = function() { + return d3_scale_linear(domain2, range, interpolate2, clamp2); + }; + return rescale(); + } + function d3_scale_linearRebind(scale2, linear2) { + return d32.rebind(scale2, linear2, "range", "rangeRound", "interpolate", "clamp"); + } + function d3_scale_linearNice(domain2, m) { + d3_scale_nice(domain2, d3_scale_niceStep(d3_scale_linearTickRange(domain2, m)[2])); + d3_scale_nice(domain2, d3_scale_niceStep(d3_scale_linearTickRange(domain2, m)[2])); + return domain2; + } + function d3_scale_linearTickRange(domain2, m) { + if (m == null) m = 10; + var extent2 = d3_scaleExtent(domain2), span = extent2[1] - extent2[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; + if (err <= 0.15) step *= 10; + else if (err <= 0.35) step *= 5; + else if (err <= 0.75) step *= 2; + extent2[0] = Math.ceil(extent2[0] / step) * step; + extent2[1] = Math.floor(extent2[1] / step) * step + step * 0.5; + extent2[2] = step; + return extent2; + } + function d3_scale_linearTicks(domain2, m) { + return d32.range.apply(d32, d3_scale_linearTickRange(domain2, m)); + } + d32.scale.log = function() { + return d3_scale_log(d32.scale.linear().domain([0, 1]), 10, true, [1, 10]); + }; + function d3_scale_log(linear2, base, positive, domain2) { + function log3(x) { + return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); + } + function pow(x) { + return positive ? Math.pow(base, x) : -Math.pow(base, -x); + } + function scale2(x) { + return linear2(log3(x)); + } + scale2.invert = function(x) { + return pow(linear2.invert(x)); + }; + scale2.domain = function(x) { + if (!arguments.length) return domain2; + positive = x[0] >= 0; + linear2.domain((domain2 = x.map(Number)).map(log3)); + return scale2; + }; + scale2.base = function(_2) { + if (!arguments.length) return base; + base = +_2; + linear2.domain(domain2.map(log3)); + return scale2; + }; + scale2.nice = function() { + var niced = d3_scale_nice(domain2.map(log3), positive ? Math : d3_scale_logNiceNegative); + linear2.domain(niced); + domain2 = niced.map(pow); + return scale2; + }; + scale2.ticks = function() { + var extent2 = d3_scaleExtent(domain2), ticks2 = [], u = extent2[0], v = extent2[1], i = Math.floor(log3(u)), j = Math.ceil(log3(v)), n = base % 1 ? 2 : base; + if (isFinite(j - i)) { + if (positive) { + for (; i < j; i++) for (var k = 1; k < n; k++) ticks2.push(pow(i) * k); + ticks2.push(pow(i)); + } else { + ticks2.push(pow(i)); + for (; i++ < j; ) for (var k = n - 1; k > 0; k--) ticks2.push(pow(i) * k); + } + for (i = 0; ticks2[i] < u; i++) { + } + for (j = ticks2.length; ticks2[j - 1] > v; j--) { + } + ticks2 = ticks2.slice(i, j); + } + return ticks2; + }; + scale2.copy = function() { + return d3_scale_log(linear2.copy(), base, positive, domain2); + }; + return d3_scale_linearRebind(scale2, linear2); + } + var d3_scale_logNiceNegative = { + floor: function(x) { + return -Math.ceil(-x); + }, + ceil: function(x) { + return -Math.floor(-x); + } + }; + d32.scale.pow = function() { + return d3_scale_pow(d32.scale.linear(), 1, [0, 1]); + }; + function d3_scale_pow(linear2, exponent2, domain2) { + var powp = d3_scale_powPow(exponent2), powb = d3_scale_powPow(1 / exponent2); + function scale2(x) { + return linear2(powp(x)); + } + scale2.invert = function(x) { + return powb(linear2.invert(x)); + }; + scale2.domain = function(x) { + if (!arguments.length) return domain2; + linear2.domain((domain2 = x.map(Number)).map(powp)); + return scale2; + }; + scale2.ticks = function(m) { + return d3_scale_linearTicks(domain2, m); + }; + scale2.tickFormat = function(m, format2) { + return d3_scale_linearTickFormat(domain2, m, format2); + }; + scale2.nice = function(m) { + return scale2.domain(d3_scale_linearNice(domain2, m)); + }; + scale2.exponent = function(x) { + if (!arguments.length) return exponent2; + powp = d3_scale_powPow(exponent2 = x); + powb = d3_scale_powPow(1 / exponent2); + linear2.domain(domain2.map(powp)); + return scale2; + }; + scale2.copy = function() { + return d3_scale_pow(linear2.copy(), exponent2, domain2); + }; + return d3_scale_linearRebind(scale2, linear2); + } + function d3_scale_powPow(e) { + return function(x) { + return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); + }; + } + d32.scale.sqrt = function() { + return d32.scale.pow().exponent(0.5); + }; + d32.scale.ordinal = function() { + return d3_scale_ordinal([], { + t: "range", + a: [[]] + }); + }; + function d3_scale_ordinal(domain2, ranger) { + var index2, range, rangeBand; + function scale2(x) { + return range[((index2.get(x) || (ranger.t === "range" ? index2.set(x, domain2.push(x)) : NaN)) - 1) % range.length]; + } + function steps(start, step) { + return d32.range(domain2.length).map(function(i) { + return start + step * i; + }); + } + scale2.domain = function(x) { + if (!arguments.length) return domain2; + domain2 = []; + index2 = new d3_Map(); + var i = -1, n = x.length, xi; + while (++i < n) if (!index2.has(xi = x[i])) index2.set(xi, domain2.push(xi)); + return scale2[ranger.t].apply(scale2, ranger.a); + }; + scale2.range = function(x) { + if (!arguments.length) return range; + range = x; + rangeBand = 0; + ranger = { + t: "range", + a: arguments + }; + return scale2; + }; + scale2.rangePoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain2.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain2.length - 1 + padding); + range = steps(start + step * padding / 2, step); + rangeBand = 0; + ranger = { + t: "rangePoints", + a: arguments + }; + return scale2; + }; + scale2.rangeRoundPoints = function(x, padding) { + if (arguments.length < 2) padding = 0; + var start = x[0], stop = x[1], step = domain2.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain2.length - 1 + padding) | 0; + range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain2.length - 1 + padding) * step) / 2), step); + rangeBand = 0; + ranger = { + t: "rangeRoundPoints", + a: arguments + }; + return scale2; + }; + scale2.rangeBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain2.length - padding + 2 * outerPadding); + range = steps(start + step * outerPadding, step); + if (reverse) range.reverse(); + rangeBand = step * (1 - padding); + ranger = { + t: "rangeBands", + a: arguments + }; + return scale2; + }; + scale2.rangeRoundBands = function(x, padding, outerPadding) { + if (arguments.length < 2) padding = 0; + if (arguments.length < 3) outerPadding = padding; + var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain2.length - padding + 2 * outerPadding)); + range = steps(start + Math.round((stop - start - (domain2.length - padding) * step) / 2), step); + if (reverse) range.reverse(); + rangeBand = Math.round(step * (1 - padding)); + ranger = { + t: "rangeRoundBands", + a: arguments + }; + return scale2; + }; + scale2.rangeBand = function() { + return rangeBand; + }; + scale2.rangeExtent = function() { + return d3_scaleExtent(ranger.a[0]); + }; + scale2.copy = function() { + return d3_scale_ordinal(domain2, ranger); + }; + return scale2.domain(domain2); + } + d32.scale.category10 = function() { + return d32.scale.ordinal().range(d3_category10); + }; + d32.scale.category20 = function() { + return d32.scale.ordinal().range(d3_category20); + }; + d32.scale.category20b = function() { + return d32.scale.ordinal().range(d3_category20b); + }; + d32.scale.category20c = function() { + return d32.scale.ordinal().range(d3_category20c); + }; + var d3_category10 = [2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175].map(d3_rgbString); + var d3_category20 = [2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725].map(d3_rgbString); + var d3_category20b = [3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654].map(d3_rgbString); + var d3_category20c = [3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081].map(d3_rgbString); + d32.scale.quantile = function() { + return d3_scale_quantile([], []); + }; + function d3_scale_quantile(domain2, range) { + var thresholds; + function rescale() { + var k = 0, q = range.length; + thresholds = []; + while (++k < q) thresholds[k - 1] = d32.quantile(domain2, k / q); + return scale2; + } + function scale2(x) { + if (!isNaN(x = +x)) return range[d32.bisect(thresholds, x)]; + } + scale2.domain = function(x) { + if (!arguments.length) return domain2; + domain2 = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); + return rescale(); + }; + scale2.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale2.quantiles = function() { + return thresholds; + }; + scale2.invertExtent = function(y) { + y = range.indexOf(y); + return y < 0 ? [NaN, NaN] : [y > 0 ? thresholds[y - 1] : domain2[0], y < thresholds.length ? thresholds[y] : domain2[domain2.length - 1]]; + }; + scale2.copy = function() { + return d3_scale_quantile(domain2, range); + }; + return rescale(); + } + d32.scale.quantize = function() { + return d3_scale_quantize(0, 1, [0, 1]); + }; + function d3_scale_quantize(x0, x1, range) { + var kx, i; + function scale2(x) { + return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; + } + function rescale() { + kx = range.length / (x1 - x0); + i = range.length - 1; + return scale2; + } + scale2.domain = function(x) { + if (!arguments.length) return [x0, x1]; + x0 = +x[0]; + x1 = +x[x.length - 1]; + return rescale(); + }; + scale2.range = function(x) { + if (!arguments.length) return range; + range = x; + return rescale(); + }; + scale2.invertExtent = function(y) { + y = range.indexOf(y); + y = y < 0 ? NaN : y / kx + x0; + return [y, y + 1 / kx]; + }; + scale2.copy = function() { + return d3_scale_quantize(x0, x1, range); + }; + return rescale(); + } + d32.scale.threshold = function() { + return d3_scale_threshold([0.5], [0, 1]); + }; + function d3_scale_threshold(domain2, range) { + function scale2(x) { + if (x <= x) return range[d32.bisect(domain2, x)]; + } + scale2.domain = function(_2) { + if (!arguments.length) return domain2; + domain2 = _2; + return scale2; + }; + scale2.range = function(_2) { + if (!arguments.length) return range; + range = _2; + return scale2; + }; + scale2.invertExtent = function(y) { + y = range.indexOf(y); + return [domain2[y - 1], domain2[y]]; + }; + scale2.copy = function() { + return d3_scale_threshold(domain2, range); + }; + return scale2; + } + d32.scale.identity = function() { + return d3_scale_identity([0, 1]); + }; + function d3_scale_identity(domain2) { + function identity3(x) { + return +x; + } + identity3.invert = identity3; + identity3.domain = identity3.range = function(x) { + if (!arguments.length) return domain2; + domain2 = x.map(identity3); + return identity3; + }; + identity3.ticks = function(m) { + return d3_scale_linearTicks(domain2, m); + }; + identity3.tickFormat = function(m, format2) { + return d3_scale_linearTickFormat(domain2, m, format2); + }; + identity3.copy = function() { + return d3_scale_identity(domain2); + }; + return identity3; + } + d32.svg = {}; + function d3_zero() { + return 0; + } + d32.svg.arc = function() { + var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; + function arc2() { + var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; + if (r1 < r0) rc = r1, r1 = r0, r0 = rc; + if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; + var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; + if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { + rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); + if (!cw) p1 *= -1; + if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); + if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); + } + if (r1) { + x0 = r1 * Math.cos(a0 + p1); + y0 = r1 * Math.sin(a0 + p1); + x1 = r1 * Math.cos(a1 - p1); + y1 = r1 * Math.sin(a1 - p1); + var l1 = Math.abs(a1 - a0 - 2 * p1) <= π2 ? 0 : 1; + if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { + var h1 = (a0 + a1) / 2; + x0 = r1 * Math.cos(h1); + y0 = r1 * Math.sin(h1); + x1 = y1 = null; + } + } else { + x0 = y0 = 0; + } + if (r0) { + x2 = r0 * Math.cos(a1 - p0); + y2 = r0 * Math.sin(a1 - p0); + x3 = r0 * Math.cos(a0 + p0); + y3 = r0 * Math.sin(a0 + p0); + var l0 = Math.abs(a0 - a1 + 2 * p0) <= π2 ? 0 : 1; + if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { + var h0 = (a0 + a1) / 2; + x2 = r0 * Math.cos(h0); + y2 = r0 * Math.sin(h0); + x3 = y3 = null; + } + } else { + x2 = y2 = 0; + } + if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > 1e-3) { + cr = r0 < r1 ^ cw ? 0 : 1; + var rc1 = rc, rc0 = rc; + if (da < π2) { + var oc = x3 == null ? [x2, y2] : x1 == null ? [x0, y0] : d3_geom_polygonIntersect([x0, y0], [x3, y3], [x1, y1], [x2, y2]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); + rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); + rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); + } + if (x1 != null) { + var t30 = d3_svg_arcCornerTangents(x3 == null ? [x2, y2] : [x3, y3], [x0, y0], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([x1, y1], [x2, y2], r1, rc1, cw); + if (rc === rc1) { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); + } else { + path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); + } + } else { + path.push("M", x0, ",", y0); + } + if (x3 != null) { + var t03 = d3_svg_arcCornerTangents([x0, y0], [x3, y3], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([x2, y2], x1 == null ? [x0, y0] : [x1, y1], r0, -rc0, cw); + if (rc === rc0) { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } else { + path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); + } + } else { + path.push("L", x2, ",", y2); + } + } else { + path.push("M", x0, ",", y0); + if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); + path.push("L", x2, ",", y2); + if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); + } + path.push("Z"); + return path.join(""); + } + function circleSegment(r1, cw) { + return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; + } + arc2.innerRadius = function(v) { + if (!arguments.length) return innerRadius; + innerRadius = d3_functor(v); + return arc2; + }; + arc2.outerRadius = function(v) { + if (!arguments.length) return outerRadius; + outerRadius = d3_functor(v); + return arc2; + }; + arc2.cornerRadius = function(v) { + if (!arguments.length) return cornerRadius; + cornerRadius = d3_functor(v); + return arc2; + }; + arc2.padRadius = function(v) { + if (!arguments.length) return padRadius; + padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); + return arc2; + }; + arc2.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return arc2; + }; + arc2.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return arc2; + }; + arc2.padAngle = function(v) { + if (!arguments.length) return padAngle; + padAngle = d3_functor(v); + return arc2; + }; + arc2.centroid = function() { + var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; + return [Math.cos(a) * r, Math.sin(a) * r]; + }; + return arc2; + }; + var d3_svg_arcAuto = "auto"; + function d3_svg_arcInnerRadius(d) { + return d.innerRadius; + } + function d3_svg_arcOuterRadius(d) { + return d.outerRadius; + } + function d3_svg_arcStartAngle(d) { + return d.startAngle; + } + function d3_svg_arcEndAngle(d) { + return d.endAngle; + } + function d3_svg_arcPadAngle(d) { + return d && d.padAngle; + } + function d3_svg_arcSweep(x0, y0, x1, y1) { + return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; + } + function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { + var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D2 = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D2 * D2)), cx0 = (D2 * dy - dx * d) / d2, cy0 = (-D2 * dx - dy * d) / d2, cx1 = (D2 * dy + dx * d) / d2, cy1 = (-D2 * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; + if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; + return [[cx0 - ox, cy0 - oy], [cx0 * r1 / r, cy0 * r1 / r]]; + } + function d3_true() { + return true; + } + function d3_svg_line(projection) { + var x = d3_geom_pointX, y = d3_geom_pointY, defined3 = d3_true, interpolate2 = d3_svg_lineLinear, interpolateKey = interpolate2.key, tension = 0.7; + function line2(data) { + var segments = [], points = [], i = -1, n = data.length, d, fx2 = d3_functor(x), fy = d3_functor(y); + function segment2() { + segments.push("M", interpolate2(projection(points), tension)); + } + while (++i < n) { + if (defined3.call(this, d = data[i], i)) { + points.push([+fx2.call(this, d, i), +fy.call(this, d, i)]); + } else if (points.length) { + segment2(); + points = []; + } + } + if (points.length) segment2(); + return segments.length ? segments.join("") : null; + } + line2.x = function(_2) { + if (!arguments.length) return x; + x = _2; + return line2; + }; + line2.y = function(_2) { + if (!arguments.length) return y; + y = _2; + return line2; + }; + line2.defined = function(_2) { + if (!arguments.length) return defined3; + defined3 = _2; + return line2; + }; + line2.interpolate = function(_2) { + if (!arguments.length) return interpolateKey; + if (typeof _2 === "function") interpolateKey = interpolate2 = _2; + else interpolateKey = (interpolate2 = d3_svg_lineInterpolators.get(_2) || d3_svg_lineLinear).key; + return line2; + }; + line2.tension = function(_2) { + if (!arguments.length) return tension; + tension = _2; + return line2; + }; + return line2; + } + d32.svg.line = function() { + return d3_svg_line(d3_identity); + }; + var d3_svg_lineInterpolators = d32.map({ + linear: d3_svg_lineLinear, + "linear-closed": d3_svg_lineLinearClosed, + step: d3_svg_lineStep, + "step-before": d3_svg_lineStepBefore, + "step-after": d3_svg_lineStepAfter, + basis: d3_svg_lineBasis, + "basis-open": d3_svg_lineBasisOpen, + "basis-closed": d3_svg_lineBasisClosed, + bundle: d3_svg_lineBundle, + cardinal: d3_svg_lineCardinal, + "cardinal-open": d3_svg_lineCardinalOpen, + "cardinal-closed": d3_svg_lineCardinalClosed, + monotone: d3_svg_lineMonotone + }); + d3_svg_lineInterpolators.forEach(function(key, value2) { + value2.key = key; + value2.closed = /-closed$/.test(key); + }); + function d3_svg_lineLinear(points) { + return points.length > 1 ? points.join("L") : points + "Z"; + } + function d3_svg_lineLinearClosed(points) { + return points.join("L") + "Z"; + } + function d3_svg_lineStep(points) { + var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; + while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); + if (n > 1) path.push("H", p[0]); + return path.join(""); + } + function d3_svg_lineStepBefore(points) { + var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; + while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); + return path.join(""); + } + function d3_svg_lineStepAfter(points) { + var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; + while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); + return path.join(""); + } + function d3_svg_lineCardinalOpen(points, tension) { + return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineCardinalClosed(points, tension) { + return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([points[points.length - 2]].concat(points, [points[1]]), tension)); + } + function d3_svg_lineCardinal(points, tension) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); + } + function d3_svg_lineHermite(points, tangents) { + if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { + return d3_svg_lineLinear(points); + } + var quad2 = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t02 = tangents[0], t = t02, pi = 1; + if (quad2) { + path += "Q" + (p[0] - t02[0] * 2 / 3) + "," + (p[1] - t02[1] * 2 / 3) + "," + p[0] + "," + p[1]; + p0 = points[1]; + pi = 2; + } + if (tangents.length > 1) { + t = tangents[1]; + p = points[pi]; + pi++; + path += "C" + (p0[0] + t02[0]) + "," + (p0[1] + t02[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + for (var i = 2; i < tangents.length; i++, pi++) { + p = points[pi]; + t = tangents[i]; + path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; + } + } + if (quad2) { + var lp = points[pi]; + path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; + } + return path; + } + function d3_svg_lineCardinalTangents(points, tension) { + var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; + while (++i < n) { + p0 = p1; + p1 = p2; + p2 = points[i]; + tangents.push([a * (p2[0] - p0[0]), a * (p2[1] - p0[1])]); + } + return tangents; + } + function d3_svg_lineBasis(points) { + if (points.length < 3) return d3_svg_lineLinear(points); + var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px2 = [x0, x0, x0, (pi = points[1])[0]], py = [y0, y0, y0, pi[1]], path = [x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)]; + points.push(points[n - 1]); + while (++i <= n) { + pi = points[i]; + px2.shift(); + px2.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px2, py); + } + points.pop(); + path.push("L", pi); + return path.join(""); + } + function d3_svg_lineBasisOpen(points) { + if (points.length < 4) return d3_svg_lineLinear(points); + var path = [], i = -1, n = points.length, pi, px2 = [0], py = [0]; + while (++i < 3) { + pi = points[i]; + px2.push(pi[0]); + py.push(pi[1]); + } + path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); + --i; + while (++i < n) { + pi = points[i]; + px2.shift(); + px2.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px2, py); + } + return path.join(""); + } + function d3_svg_lineBasisClosed(points) { + var path, i = -1, n = points.length, m = n + 4, pi, px2 = [], py = []; + while (++i < 4) { + pi = points[i % n]; + px2.push(pi[0]); + py.push(pi[1]); + } + path = [d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)]; + --i; + while (++i < m) { + pi = points[i % n]; + px2.shift(); + px2.push(pi[0]); + py.shift(); + py.push(pi[1]); + d3_svg_lineBasisBezier(path, px2, py); + } + return path.join(""); + } + function d3_svg_lineBundle(points, tension) { + var n = points.length - 1; + if (n) { + var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; + while (++i <= n) { + p = points[i]; + t = i / n; + p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); + p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); + } + } + return d3_svg_lineBasis(points); + } + function d3_svg_lineDot4(a, b) { + return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; + } + var d3_svg_lineBasisBezier1 = [0, 2 / 3, 1 / 3, 0], d3_svg_lineBasisBezier2 = [0, 1 / 3, 2 / 3, 0], d3_svg_lineBasisBezier3 = [0, 1 / 6, 2 / 3, 1 / 6]; + function d3_svg_lineBasisBezier(path, x, y) { + path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); + } + function d3_svg_lineSlope(p0, p1) { + return (p1[1] - p0[1]) / (p1[0] - p0[0]); + } + function d3_svg_lineFiniteDifferences(points) { + var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); + while (++i < j) { + m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; + } + m[i] = d; + return m; + } + function d3_svg_lineMonotoneTangents(points) { + var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; + while (++i < j) { + d = d3_svg_lineSlope(points[i], points[i + 1]); + if (abs2(d) < ε) { + m[i] = m[i + 1] = 0; + } else { + a = m[i] / d; + b = m[i + 1] / d; + s = a * a + b * b; + if (s > 9) { + s = d * 3 / Math.sqrt(s); + m[i] = s * a; + m[i + 1] = s * b; + } + } + } + i = -1; + while (++i <= j) { + s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); + tangents.push([s || 0, m[i] * s || 0]); + } + return tangents; + } + function d3_svg_lineMonotone(points) { + return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); + } + d32.svg.line.radial = function() { + var line2 = d3_svg_line(d3_svg_lineRadial); + line2.radius = line2.x, delete line2.x; + line2.angle = line2.y, delete line2.y; + return line2; + }; + function d3_svg_lineRadial(points) { + var point, i = -1, n = points.length, r, a; + while (++i < n) { + point = points[i]; + r = point[0]; + a = point[1] - halfπ; + point[0] = r * Math.cos(a); + point[1] = r * Math.sin(a); + } + return points; + } + function d3_svg_area(projection) { + var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined3 = d3_true, interpolate2 = d3_svg_lineLinear, interpolateKey = interpolate2.key, interpolateReverse = interpolate2, L = "L", tension = 0.7; + function area2(data) { + var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { + return x; + } : d3_functor(x1), fy1 = y0 === y1 ? function() { + return y; + } : d3_functor(y1), x, y; + function segment2() { + segments.push("M", interpolate2(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); + } + while (++i < n) { + if (defined3.call(this, d = data[i], i)) { + points0.push([x = +fx0.call(this, d, i), y = +fy0.call(this, d, i)]); + points1.push([+fx1.call(this, d, i), +fy1.call(this, d, i)]); + } else if (points0.length) { + segment2(); + points0 = []; + points1 = []; + } + } + if (points0.length) segment2(); + return segments.length ? segments.join("") : null; + } + area2.x = function(_2) { + if (!arguments.length) return x1; + x0 = x1 = _2; + return area2; + }; + area2.x0 = function(_2) { + if (!arguments.length) return x0; + x0 = _2; + return area2; + }; + area2.x1 = function(_2) { + if (!arguments.length) return x1; + x1 = _2; + return area2; + }; + area2.y = function(_2) { + if (!arguments.length) return y1; + y0 = y1 = _2; + return area2; + }; + area2.y0 = function(_2) { + if (!arguments.length) return y0; + y0 = _2; + return area2; + }; + area2.y1 = function(_2) { + if (!arguments.length) return y1; + y1 = _2; + return area2; + }; + area2.defined = function(_2) { + if (!arguments.length) return defined3; + defined3 = _2; + return area2; + }; + area2.interpolate = function(_2) { + if (!arguments.length) return interpolateKey; + if (typeof _2 === "function") interpolateKey = interpolate2 = _2; + else interpolateKey = (interpolate2 = d3_svg_lineInterpolators.get(_2) || d3_svg_lineLinear).key; + interpolateReverse = interpolate2.reverse || interpolate2; + L = interpolate2.closed ? "M" : "L"; + return area2; + }; + area2.tension = function(_2) { + if (!arguments.length) return tension; + tension = _2; + return area2; + }; + return area2; + } + d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; + d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; + d32.svg.area = function() { + return d3_svg_area(d3_identity); + }; + d32.svg.area.radial = function() { + var area2 = d3_svg_area(d3_svg_lineRadial); + area2.radius = area2.x, delete area2.x; + area2.innerRadius = area2.x0, delete area2.x0; + area2.outerRadius = area2.x1, delete area2.x1; + area2.angle = area2.y, delete area2.y; + area2.startAngle = area2.y0, delete area2.y0; + area2.endAngle = area2.y1, delete area2.y1; + return area2; + }; + function d3_source(d) { + return d.source; + } + function d3_target(d) { + return d.target; + } + d32.svg.chord = function() { + var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; + function chord(d, i) { + var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); + return "M" + s.p0 + arc2(s.r, s.p1, s.a1 - s.a0) + (equals2(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc2(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; + } + function subgroup(self2, f, d, i) { + var subgroup2 = f.call(self2, d, i), r = radius.call(self2, subgroup2, i), a0 = startAngle.call(self2, subgroup2, i) - halfπ, a1 = endAngle.call(self2, subgroup2, i) - halfπ; + return { + r, + a0, + a1, + p0: [r * Math.cos(a0), r * Math.sin(a0)], + p1: [r * Math.cos(a1), r * Math.sin(a1)] + }; + } + function equals2(a, b) { + return a.a0 == b.a0 && a.a1 == b.a1; + } + function arc2(r, p, a) { + return "A" + r + "," + r + " 0 " + +(a > π2) + ",1 " + p; + } + function curve(r0, p0, r1, p1) { + return "Q 0,0 " + p1; + } + chord.radius = function(v) { + if (!arguments.length) return radius; + radius = d3_functor(v); + return chord; + }; + chord.source = function(v) { + if (!arguments.length) return source; + source = d3_functor(v); + return chord; + }; + chord.target = function(v) { + if (!arguments.length) return target; + target = d3_functor(v); + return chord; + }; + chord.startAngle = function(v) { + if (!arguments.length) return startAngle; + startAngle = d3_functor(v); + return chord; + }; + chord.endAngle = function(v) { + if (!arguments.length) return endAngle; + endAngle = d3_functor(v); + return chord; + }; + return chord; + }; + function d3_svg_chordRadius(d) { + return d.radius; + } + d32.svg.diagonal = function() { + var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; + function diagonal(d, i) { + var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [p0, { + x: p0.x, + y: m + }, { + x: p3.x, + y: m + }, p3]; + p = p.map(projection); + return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; + } + diagonal.source = function(x) { + if (!arguments.length) return source; + source = d3_functor(x); + return diagonal; + }; + diagonal.target = function(x) { + if (!arguments.length) return target; + target = d3_functor(x); + return diagonal; + }; + diagonal.projection = function(x) { + if (!arguments.length) return projection; + projection = x; + return diagonal; + }; + return diagonal; + }; + function d3_svg_diagonalProjection(d) { + return [d.x, d.y]; + } + d32.svg.diagonal.radial = function() { + var diagonal = d32.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; + diagonal.projection = function(x) { + return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; + }; + return diagonal; + }; + function d3_svg_diagonalRadialProjection(projection) { + return function() { + var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; + return [r * Math.cos(a), r * Math.sin(a)]; + }; + } + d32.svg.symbol = function() { + var type = d3_svg_symbolType, size = d3_svg_symbolSize; + function symbol(d, i) { + return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); + } + symbol.type = function(x) { + if (!arguments.length) return type; + type = d3_functor(x); + return symbol; + }; + symbol.size = function(x) { + if (!arguments.length) return size; + size = d3_functor(x); + return symbol; + }; + return symbol; + }; + function d3_svg_symbolSize() { + return 64; + } + function d3_svg_symbolType() { + return "circle"; + } + function d3_svg_symbolCircle(size) { + var r = Math.sqrt(size / π2); + return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; + } + var d3_svg_symbols = d32.map({ + circle: d3_svg_symbolCircle, + cross: function(size) { + var r = Math.sqrt(size / 5) / 2; + return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; + }, + diamond: function(size) { + var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; + return "M0," + -ry + "L" + rx + ",0 0," + ry + " " + -rx + ",0Z"; + }, + square: function(size) { + var r = Math.sqrt(size) / 2; + return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; + }, + "triangle-down": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; + }, + "triangle-up": function(size) { + var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; + return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; + } + }); + d32.svg.symbolTypes = d3_svg_symbols.keys(); + var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); + d3_selectionPrototype.transition = function(name2) { + var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name2), subgroups = [], subgroup, node, transition2 = d3_transitionInherit || { + time: Date.now(), + ease: d3_ease_cubicInOut, + delay: 0, + duration: 250 + }; + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) d3_transitionNode(node, i, ns, id, transition2); + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id); + }; + d3_selectionPrototype.interrupt = function(name2) { + return this.each(name2 == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name2))); + }; + var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); + function d3_selection_interruptNS(ns) { + return function() { + var lock, activeId, active; + if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { + active.timer.c = null; + active.timer.t = NaN; + if (--lock.count) delete lock[activeId]; + else delete this[ns]; + lock.active += 0.5; + active.event && active.event.interrupt.call(this, this.__data__, active.index); + } + }; + } + function d3_transition(groups, ns, id) { + d3_subclass(groups, d3_transitionPrototype); + groups.namespace = ns; + groups.id = id; + return groups; + } + var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; + d3_transitionPrototype.call = d3_selectionPrototype.call; + d3_transitionPrototype.empty = d3_selectionPrototype.empty; + d3_transitionPrototype.node = d3_selectionPrototype.node; + d3_transitionPrototype.size = d3_selectionPrototype.size; + d32.transition = function(selection, name2) { + return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name2) : selection : d32.selection().transition(selection); + }; + d32.transition.prototype = d3_transitionPrototype; + d3_transitionPrototype.select = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; + selector = d3_selection_selector(selector); + for (var j = -1, m = this.length; ++j < m; ) { + subgroups.push(subgroup = []); + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { + if ("__data__" in node) subnode.__data__ = node.__data__; + d3_transitionNode(subnode, i, ns, id, node[ns][id]); + subgroup.push(subnode); + } else { + subgroup.push(null); + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.selectAll = function(selector) { + var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition2; + selector = d3_selection_selectorAll(selector); + for (var j = -1, m = this.length; ++j < m; ) { + for (var group = this[j], i = -1, n = group.length; ++i < n; ) { + if (node = group[i]) { + transition2 = node[ns][id]; + subnodes = selector.call(node, node.__data__, i, j); + subgroups.push(subgroup = []); + for (var k = -1, o = subnodes.length; ++k < o; ) { + if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition2); + subgroup.push(subnode); + } + } + } + } + return d3_transition(subgroups, ns, id); + }; + d3_transitionPrototype.filter = function(filter2) { + var subgroups = [], subgroup, group, node; + if (typeof filter2 !== "function") filter2 = d3_selection_filter(filter2); + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if ((node = group[i]) && filter2.call(node, node.__data__, i, j)) { + subgroup.push(node); + } + } + } + return d3_transition(subgroups, this.namespace, this.id); + }; + d3_transitionPrototype.tween = function(name2, tween) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) return this.node()[ns][id].tween.get(name2); + return d3_selection_each(this, tween == null ? function(node) { + node[ns][id].tween.remove(name2); + } : function(node) { + node[ns][id].tween.set(name2, tween); + }); + }; + function d3_transition_tween(groups, name2, value2, tween) { + var id = groups.id, ns = groups.namespace; + return d3_selection_each(groups, typeof value2 === "function" ? function(node, i, j) { + node[ns][id].tween.set(name2, tween(value2.call(node, node.__data__, i, j))); + } : (value2 = tween(value2), function(node) { + node[ns][id].tween.set(name2, value2); + })); + } + d3_transitionPrototype.attr = function(nameNS, value2) { + if (arguments.length < 2) { + for (value2 in nameNS) this.attr(value2, nameNS[value2]); + return this; + } + var interpolate2 = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name2 = d32.ns.qualify(nameNS); + function attrNull() { + this.removeAttribute(name2); + } + function attrNullNS() { + this.removeAttributeNS(name2.space, name2.local); + } + function attrTween(b) { + return b == null ? attrNull : (b += "", function() { + var a = this.getAttribute(name2), i; + return a !== b && (i = interpolate2(a, b), function(t) { + this.setAttribute(name2, i(t)); + }); + }); + } + function attrTweenNS(b) { + return b == null ? attrNullNS : (b += "", function() { + var a = this.getAttributeNS(name2.space, name2.local), i; + return a !== b && (i = interpolate2(a, b), function(t) { + this.setAttributeNS(name2.space, name2.local, i(t)); + }); + }); + } + return d3_transition_tween(this, "attr." + nameNS, value2, name2.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.attrTween = function(nameNS, tween) { + var name2 = d32.ns.qualify(nameNS); + function attrTween(d, i) { + var f = tween.call(this, d, i, this.getAttribute(name2)); + return f && function(t) { + this.setAttribute(name2, f(t)); + }; + } + function attrTweenNS(d, i) { + var f = tween.call(this, d, i, this.getAttributeNS(name2.space, name2.local)); + return f && function(t) { + this.setAttributeNS(name2.space, name2.local, f(t)); + }; + } + return this.tween("attr." + nameNS, name2.local ? attrTweenNS : attrTween); + }; + d3_transitionPrototype.style = function(name2, value2, priority) { + var n = arguments.length; + if (n < 3) { + if (typeof name2 !== "string") { + if (n < 2) value2 = ""; + for (priority in name2) this.style(priority, name2[priority], value2); + return this; + } + priority = ""; + } + function styleNull() { + this.style.removeProperty(name2); + } + function styleString(b) { + return b == null ? styleNull : (b += "", function() { + var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name2), i; + return a !== b && (i = d3_interpolate(a, b), function(t) { + this.style.setProperty(name2, i(t), priority); + }); + }); + } + return d3_transition_tween(this, "style." + name2, value2, styleString); + }; + d3_transitionPrototype.styleTween = function(name2, tween, priority) { + if (arguments.length < 3) priority = ""; + function styleTween(d, i) { + var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name2)); + return f && function(t) { + this.style.setProperty(name2, f(t), priority); + }; + } + return this.tween("style." + name2, styleTween); + }; + d3_transitionPrototype.text = function(value2) { + return d3_transition_tween(this, "text", value2, d3_transition_text); + }; + function d3_transition_text(b) { + if (b == null) b = ""; + return function() { + this.textContent = b; + }; + } + d3_transitionPrototype.remove = function() { + var ns = this.namespace; + return this.each("end.transition", function() { + var p; + if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); + }); + }; + d3_transitionPrototype.ease = function(value2) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].ease; + if (typeof value2 !== "function") value2 = d32.ease.apply(d32, arguments); + return d3_selection_each(this, function(node) { + node[ns][id].ease = value2; + }); + }; + d3_transitionPrototype.delay = function(value2) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].delay; + return d3_selection_each(this, typeof value2 === "function" ? function(node, i, j) { + node[ns][id].delay = +value2.call(node, node.__data__, i, j); + } : (value2 = +value2, function(node) { + node[ns][id].delay = value2; + })); + }; + d3_transitionPrototype.duration = function(value2) { + var id = this.id, ns = this.namespace; + if (arguments.length < 1) return this.node()[ns][id].duration; + return d3_selection_each(this, typeof value2 === "function" ? function(node, i, j) { + node[ns][id].duration = Math.max(1, value2.call(node, node.__data__, i, j)); + } : (value2 = Math.max(1, value2), function(node) { + node[ns][id].duration = value2; + })); + }; + d3_transitionPrototype.each = function(type, listener) { + var id = this.id, ns = this.namespace; + if (arguments.length < 2) { + var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; + try { + d3_transitionInheritId = id; + d3_selection_each(this, function(node, i, j) { + d3_transitionInherit = node[ns][id]; + type.call(node, node.__data__, i, j); + }); + } finally { + d3_transitionInherit = inherit; + d3_transitionInheritId = inheritId; + } + } else { + d3_selection_each(this, function(node) { + var transition2 = node[ns][id]; + (transition2.event || (transition2.event = d32.dispatch("start", "end", "interrupt"))).on(type, listener); + }); + } + return this; + }; + d3_transitionPrototype.transition = function() { + var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition2; + for (var j = 0, m = this.length; j < m; j++) { + subgroups.push(subgroup = []); + for (var group = this[j], i = 0, n = group.length; i < n; i++) { + if (node = group[i]) { + transition2 = node[ns][id0]; + d3_transitionNode(node, i, ns, id1, { + time: transition2.time, + ease: transition2.ease, + delay: transition2.delay + transition2.duration, + duration: transition2.duration + }); + } + subgroup.push(node); + } + } + return d3_transition(subgroups, ns, id1); + }; + function d3_transitionNamespace(name2) { + return name2 == null ? "__transition__" : "__transition_" + name2 + "__"; + } + function d3_transitionNode(node, i, ns, id, inherit) { + var lock = node[ns] || (node[ns] = { + active: 0, + count: 0 + }), transition2 = lock[id], time, timer, duration, ease, tweens; + function schedule(elapsed) { + var delay = transition2.delay; + timer.t = delay + time; + if (delay <= elapsed) return start(elapsed - delay); + timer.c = start; + } + function start(elapsed) { + var activeId = lock.active, active = lock[activeId]; + if (active) { + active.timer.c = null; + active.timer.t = NaN; + --lock.count; + delete lock[activeId]; + active.event && active.event.interrupt.call(node, node.__data__, active.index); + } + for (var cancelId in lock) { + if (+cancelId < id) { + var cancel = lock[cancelId]; + cancel.timer.c = null; + cancel.timer.t = NaN; + --lock.count; + delete lock[cancelId]; + } + } + timer.c = tick; + d3_timer(function() { + if (timer.c && tick(elapsed || 1)) { + timer.c = null; + timer.t = NaN; + } + return 1; + }, 0, time); + lock.active = id; + transition2.event && transition2.event.start.call(node, node.__data__, i); + tweens = []; + transition2.tween.forEach(function(key, value2) { + if (value2 = value2.call(node, node.__data__, i)) { + tweens.push(value2); + } + }); + ease = transition2.ease; + duration = transition2.duration; + } + function tick(elapsed) { + var t = elapsed / duration, e = ease(t), n = tweens.length; + while (n > 0) { + tweens[--n].call(node, e); + } + if (t >= 1) { + transition2.event && transition2.event.end.call(node, node.__data__, i); + if (--lock.count) delete lock[id]; + else delete node[ns]; + return 1; + } + } + if (!transition2) { + time = inherit.time; + timer = d3_timer(schedule, 0, time); + transition2 = lock[id] = { + tween: new d3_Map(), + time, + timer, + delay: inherit.delay, + duration: inherit.duration, + ease: inherit.ease, + index: i + }; + inherit = null; + ++lock.count; + } + } + d32.svg.axis = function() { + var scale2 = d32.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [10], tickValues = null, tickFormat_; + function axis(g) { + g.each(function() { + var g2 = d32.select(this); + var scale0 = this.__chart__ || scale2, scale1 = this.__chart__ = scale2.copy(); + var ticks2 = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g2.selectAll(".tick").data(ticks2, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d32.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d32.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; + var range = d3_scaleRange(scale1), path = g2.selectAll(".domain").data([0]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d32.transition(path)); + tickEnter.append("line"); + tickEnter.append("text"); + var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign2 = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; + if (orient === "bottom" || orient === "top") { + tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; + text.attr("dy", sign2 < 0 ? "0em" : ".71em").style("text-anchor", "middle"); + pathUpdate.attr("d", "M" + range[0] + "," + sign2 * outerTickSize + "V0H" + range[1] + "V" + sign2 * outerTickSize); + } else { + tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; + text.attr("dy", ".32em").style("text-anchor", sign2 < 0 ? "end" : "start"); + pathUpdate.attr("d", "M" + sign2 * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign2 * outerTickSize); + } + lineEnter.attr(y2, sign2 * innerTickSize); + textEnter.attr(y1, sign2 * tickSpacing); + lineUpdate.attr(x2, 0).attr(y2, sign2 * innerTickSize); + textUpdate.attr(x1, 0).attr(y1, sign2 * tickSpacing); + if (scale1.rangeBand) { + var x = scale1, dx = x.rangeBand() / 2; + scale0 = scale1 = function(d) { + return x(d) + dx; + }; + } else if (scale0.rangeBand) { + scale0 = scale1; + } else { + tickExit.call(tickTransform, scale1, scale0); + } + tickEnter.call(tickTransform, scale0, scale1); + tickUpdate.call(tickTransform, scale1, scale1); + }); + } + axis.scale = function(x) { + if (!arguments.length) return scale2; + scale2 = x; + return axis; + }; + axis.orient = function(x) { + if (!arguments.length) return orient; + orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; + return axis; + }; + axis.ticks = function() { + if (!arguments.length) return tickArguments_; + tickArguments_ = d3_array(arguments); + return axis; + }; + axis.tickValues = function(x) { + if (!arguments.length) return tickValues; + tickValues = x; + return axis; + }; + axis.tickFormat = function(x) { + if (!arguments.length) return tickFormat_; + tickFormat_ = x; + return axis; + }; + axis.tickSize = function(x) { + var n = arguments.length; + if (!n) return innerTickSize; + innerTickSize = +x; + outerTickSize = +arguments[n - 1]; + return axis; + }; + axis.innerTickSize = function(x) { + if (!arguments.length) return innerTickSize; + innerTickSize = +x; + return axis; + }; + axis.outerTickSize = function(x) { + if (!arguments.length) return outerTickSize; + outerTickSize = +x; + return axis; + }; + axis.tickPadding = function(x) { + if (!arguments.length) return tickPadding; + tickPadding = +x; + return axis; + }; + axis.tickSubdivide = function() { + return arguments.length && axis; + }; + return axis; + }; + var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { + top: 1, + right: 1, + bottom: 1, + left: 1 + }; + function d3_svg_axisX(selection, x0, x1) { + selection.attr("transform", function(d) { + var v0 = x0(d); + return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; + }); + } + function d3_svg_axisY(selection, y0, y1) { + selection.attr("transform", function(d) { + var v0 = y0(d); + return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; + }); + } + d32.svg.brush = function() { + var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [0, 0], yExtent = [0, 0], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; + function brush(g) { + g.each(function() { + var g2 = d32.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); + var background2 = g2.selectAll(".background").data([0]); + background2.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); + g2.selectAll(".extent").data([0]).enter().append("rect").attr("class", "extent").style("cursor", "move"); + var resize2 = g2.selectAll(".resize").data(resizes, d3_identity); + resize2.exit().remove(); + resize2.enter().append("g").attr("class", function(d) { + return "resize " + d; + }).style("cursor", function(d) { + return d3_svg_brushCursor[d]; + }).append("rect").attr("x", function(d) { + return /[ew]$/.test(d) ? -3 : null; + }).attr("y", function(d) { + return /^[ns]/.test(d) ? -3 : null; + }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); + resize2.style("display", brush.empty() ? "none" : null); + var gUpdate = d32.transition(g2), backgroundUpdate = d32.transition(background2), range; + if (x) { + range = d3_scaleRange(x); + backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); + redrawX(gUpdate); + } + if (y) { + range = d3_scaleRange(y); + backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); + redrawY(gUpdate); + } + redraw(gUpdate); + }); + } + brush.event = function(g) { + g.each(function() { + var event_ = event.of(this, arguments), extent1 = { + x: xExtent, + y: yExtent, + i: xExtentDomain, + j: yExtentDomain + }, extent0 = this.__chart__ || extent1; + this.__chart__ = extent1; + if (d3_transitionInheritId) { + d32.select(this).transition().each("start.brush", function() { + xExtentDomain = extent0.i; + yExtentDomain = extent0.j; + xExtent = extent0.x; + yExtent = extent0.y; + event_({ + type: "brushstart" + }); + }).tween("brush:brush", function() { + var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); + xExtentDomain = yExtentDomain = null; + return function(t) { + xExtent = extent1.x = xi(t); + yExtent = extent1.y = yi(t); + event_({ + type: "brush", + mode: "resize" + }); + }; + }).each("end.brush", function() { + xExtentDomain = extent1.i; + yExtentDomain = extent1.j; + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + }); + } else { + event_({ + type: "brushstart" + }); + event_({ + type: "brush", + mode: "resize" + }); + event_({ + type: "brushend" + }); + } + }); + }; + function redraw(g) { + g.selectAll(".resize").attr("transform", function(d) { + return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; + }); + } + function redrawX(g) { + g.select(".extent").attr("x", xExtent[0]); + g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); + } + function redrawY(g) { + g.select(".extent").attr("y", yExtent[0]); + g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); + } + function brushstart() { + var target = this, eventTarget = d32.select(d32.event.target), event_ = event.of(target, arguments), g = d32.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d32.mouse(target), offset; + var w = d32.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); + if (d32.event.changedTouches) { + w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); + } else { + w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); + } + g.interrupt().selectAll("*").interrupt(); + if (dragging) { + origin[0] = xExtent[0] - origin[0]; + origin[1] = yExtent[0] - origin[1]; + } else if (resizing) { + var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); + offset = [xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1]]; + origin[0] = xExtent[ex]; + origin[1] = yExtent[ey]; + } else if (d32.event.altKey) center = origin.slice(); + g.style("pointer-events", "none").selectAll(".resize").style("display", null); + d32.select("body").style("cursor", eventTarget.style("cursor")); + event_({ + type: "brushstart" + }); + brushmove(); + function keydown() { + if (d32.event.keyCode == 32) { + if (!dragging) { + center = null; + origin[0] -= xExtent[1]; + origin[1] -= yExtent[1]; + dragging = 2; + } + d3_eventPreventDefault(); + } + } + function keyup() { + if (d32.event.keyCode == 32 && dragging == 2) { + origin[0] += xExtent[1]; + origin[1] += yExtent[1]; + dragging = 0; + d3_eventPreventDefault(); + } + } + function brushmove() { + var point = d32.mouse(target), moved = false; + if (offset) { + point[0] += offset[0]; + point[1] += offset[1]; + } + if (!dragging) { + if (d32.event.altKey) { + if (!center) center = [(xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2]; + origin[0] = xExtent[+(point[0] < center[0])]; + origin[1] = yExtent[+(point[1] < center[1])]; + } else center = null; + } + if (resizingX && move1(point, x, 0)) { + redrawX(g); + moved = true; + } + if (resizingY && move1(point, y, 1)) { + redrawY(g); + moved = true; + } + if (moved) { + redraw(g); + event_({ + type: "brush", + mode: dragging ? "move" : "resize" + }); + } + } + function move1(point, scale2, i) { + var range = d3_scaleRange(scale2), r0 = range[0], r1 = range[1], position = origin[i], extent2 = i ? yExtent : xExtent, size = extent2[1] - extent2[0], min, max; + if (dragging) { + r0 -= position; + r1 -= size + position; + } + min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; + if (dragging) { + max = (min += position) + size; + } else { + if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); + if (position < min) { + max = min; + min = position; + } else { + max = position; + } + } + if (extent2[0] != min || extent2[1] != max) { + if (i) yExtentDomain = null; + else xExtentDomain = null; + extent2[0] = min; + extent2[1] = max; + return true; + } + } + function brushend() { + brushmove(); + g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); + d32.select("body").style("cursor", null); + w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); + dragRestore(); + event_({ + type: "brushend" + }); + } + } + brush.x = function(z) { + if (!arguments.length) return x; + x = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.y = function(z) { + if (!arguments.length) return y; + y = z; + resizes = d3_svg_brushResizes[!x << 1 | !y]; + return brush; + }; + brush.clamp = function(z) { + if (!arguments.length) return x && y ? [xClamp, yClamp] : x ? xClamp : y ? yClamp : null; + if (x && y) xClamp = !!z[0], yClamp = !!z[1]; + else if (x) xClamp = !!z; + else if (y) yClamp = !!z; + return brush; + }; + brush.extent = function(z) { + var x0, x1, y0, y1, t; + if (!arguments.length) { + if (x) { + if (xExtentDomain) { + x0 = xExtentDomain[0], x1 = xExtentDomain[1]; + } else { + x0 = xExtent[0], x1 = xExtent[1]; + if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + } + } + if (y) { + if (yExtentDomain) { + y0 = yExtentDomain[0], y1 = yExtentDomain[1]; + } else { + y0 = yExtent[0], y1 = yExtent[1]; + if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + } + } + return x && y ? [[x0, y0], [x1, y1]] : x ? [x0, x1] : y && [y0, y1]; + } + if (x) { + x0 = z[0], x1 = z[1]; + if (y) x0 = x0[0], x1 = x1[0]; + xExtentDomain = [x0, x1]; + if (x.invert) x0 = x(x0), x1 = x(x1); + if (x1 < x0) t = x0, x0 = x1, x1 = t; + if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [x0, x1]; + } + if (y) { + y0 = z[0], y1 = z[1]; + if (x) y0 = y0[1], y1 = y1[1]; + yExtentDomain = [y0, y1]; + if (y.invert) y0 = y(y0), y1 = y(y1); + if (y1 < y0) t = y0, y0 = y1, y1 = t; + if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [y0, y1]; + } + return brush; + }; + brush.clear = function() { + if (!brush.empty()) { + xExtent = [0, 0], yExtent = [0, 0]; + xExtentDomain = yExtentDomain = null; + } + return brush; + }; + brush.empty = function() { + return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; + }; + return d32.rebind(brush, event, "on"); + }; + var d3_svg_brushCursor = { + n: "ns-resize", + e: "ew-resize", + s: "ns-resize", + w: "ew-resize", + nw: "nwse-resize", + ne: "nesw-resize", + se: "nwse-resize", + sw: "nesw-resize" + }; + var d3_svg_brushResizes = [["n", "e", "s", "w", "nw", "ne", "se", "sw"], ["e", "w"], ["n", "s"], []]; + d32.text = d3_xhrType(function(request) { + return request.responseText; + }); + d32.json = function(url, callback) { + return d3_xhr(url, "application/json", d3_json, callback); + }; + function d3_json(request) { + return JSON.parse(request.responseText); + } + d32.html = function(url, callback) { + return d3_xhr(url, "text/html", d3_html, callback); + }; + function d3_html(request) { + var range = d3_document.createRange(); + range.selectNode(d3_document.body); + return range.createContextualFragment(request.responseText); + } + d32.xml = d3_xhrType(function(request) { + return request.responseXML; + }); + if (module2.exports) module2.exports = d32; + else this.d3 = d32; + }).apply(self); +})(d3$G); +var d3Exports = d3$G.exports; +var t0$1 = /* @__PURE__ */ new Date(), t1$1 = /* @__PURE__ */ new Date(); +function newInterval(floori, offseti, count2, field) { + function interval(date2) { + return floori(date2 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date2)), date2; + } + interval.floor = function(date2) { + return floori(date2 = /* @__PURE__ */ new Date(+date2)), date2; + }; + interval.ceil = function(date2) { + return floori(date2 = new Date(date2 - 1)), offseti(date2, 1), floori(date2), date2; + }; + interval.round = function(date2) { + var d0 = interval(date2), d1 = interval.ceil(date2); + return date2 - d0 < d1 - date2 ? d0 : d1; + }; + interval.offset = function(date2, step) { + return offseti(date2 = /* @__PURE__ */ new Date(+date2), step == null ? 1 : Math.floor(step)), date2; + }; + interval.range = function(start, stop, step) { + var range = [], previous; + start = interval.ceil(start); + step = step == null ? 1 : Math.floor(step); + if (!(start < stop) || !(step > 0)) return range; + do + range.push(previous = /* @__PURE__ */ new Date(+start)), offseti(start, step), floori(start); + while (previous < start && start < stop); + return range; + }; + interval.filter = function(test) { + return newInterval(function(date2) { + if (date2 >= date2) while (floori(date2), !test(date2)) date2.setTime(date2 - 1); + }, function(date2, step) { + if (date2 >= date2) { + if (step < 0) while (++step <= 0) { + while (offseti(date2, -1), !test(date2)) { + } + } + else while (--step >= 0) { + while (offseti(date2, 1), !test(date2)) { + } + } + } + }); + }; + if (count2) { + interval.count = function(start, end) { + t0$1.setTime(+start), t1$1.setTime(+end); + floori(t0$1), floori(t1$1); + return Math.floor(count2(t0$1, t1$1)); + }; + interval.every = function(step) { + step = Math.floor(step); + return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? function(d) { + return field(d) % step === 0; + } : function(d) { + return interval.count(0, d) % step === 0; + }); + }; + } + return interval; +} +var millisecond = newInterval(function() { +}, function(date2, step) { + date2.setTime(+date2 + step); +}, function(start, end) { + return end - start; +}); +millisecond.every = function(k) { + k = Math.floor(k); + if (!isFinite(k) || !(k > 0)) return null; + if (!(k > 1)) return millisecond; + return newInterval(function(date2) { + date2.setTime(Math.floor(date2 / k) * k); + }, function(date2, step) { + date2.setTime(+date2 + step * k); + }, function(start, end) { + return (end - start) / k; + }); +}; +var milliseconds = millisecond.range; +var durationSecond = 1e3; +var durationMinute = 6e4; +var durationHour = 36e5; +var durationDay = 864e5; +var durationWeek = 6048e5; +var second = newInterval(function(date2) { + date2.setTime(date2 - date2.getMilliseconds()); +}, function(date2, step) { + date2.setTime(+date2 + step * durationSecond); +}, function(start, end) { + return (end - start) / durationSecond; +}, function(date2) { + return date2.getUTCSeconds(); +}); +var seconds = second.range; +var minute = newInterval(function(date2) { + date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond); +}, function(date2, step) { + date2.setTime(+date2 + step * durationMinute); +}, function(start, end) { + return (end - start) / durationMinute; +}, function(date2) { + return date2.getMinutes(); +}); +var minutes = minute.range; +var hour = newInterval(function(date2) { + date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond - date2.getMinutes() * durationMinute); +}, function(date2, step) { + date2.setTime(+date2 + step * durationHour); +}, function(start, end) { + return (end - start) / durationHour; +}, function(date2) { + return date2.getHours(); +}); +var hours = hour.range; +var day = newInterval(function(date2) { + date2.setHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setDate(date2.getDate() + step); +}, function(start, end) { + return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay; +}, function(date2) { + return date2.getDate() - 1; +}); +var days = day.range; +function weekday(i) { + return newInterval(function(date2) { + date2.setDate(date2.getDate() - (date2.getDay() + 7 - i) % 7); + date2.setHours(0, 0, 0, 0); + }, function(date2, step) { + date2.setDate(date2.getDate() + step * 7); + }, function(start, end) { + return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; + }); +} +var sunday = weekday(0); +var monday = weekday(1); +var tuesday = weekday(2); +var wednesday = weekday(3); +var thursday = weekday(4); +var friday = weekday(5); +var saturday = weekday(6); +var sundays = sunday.range; +var mondays = monday.range; +var tuesdays = tuesday.range; +var wednesdays = wednesday.range; +var thursdays = thursday.range; +var fridays = friday.range; +var saturdays = saturday.range; +var month = newInterval(function(date2) { + date2.setDate(1); + date2.setHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setMonth(date2.getMonth() + step); +}, function(start, end) { + return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; +}, function(date2) { + return date2.getMonth(); +}); +var months = month.range; +var year = newInterval(function(date2) { + date2.setMonth(0, 1); + date2.setHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setFullYear(date2.getFullYear() + step); +}, function(start, end) { + return end.getFullYear() - start.getFullYear(); +}, function(date2) { + return date2.getFullYear(); +}); +year.every = function(k) { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date2) { + date2.setFullYear(Math.floor(date2.getFullYear() / k) * k); + date2.setMonth(0, 1); + date2.setHours(0, 0, 0, 0); + }, function(date2, step) { + date2.setFullYear(date2.getFullYear() + step * k); + }); +}; +var years = year.range; +var utcMinute = newInterval(function(date2) { + date2.setUTCSeconds(0, 0); +}, function(date2, step) { + date2.setTime(+date2 + step * durationMinute); +}, function(start, end) { + return (end - start) / durationMinute; +}, function(date2) { + return date2.getUTCMinutes(); +}); +var utcMinutes = utcMinute.range; +var utcHour = newInterval(function(date2) { + date2.setUTCMinutes(0, 0, 0); +}, function(date2, step) { + date2.setTime(+date2 + step * durationHour); +}, function(start, end) { + return (end - start) / durationHour; +}, function(date2) { + return date2.getUTCHours(); +}); +var utcHours = utcHour.range; +var utcDay = newInterval(function(date2) { + date2.setUTCHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setUTCDate(date2.getUTCDate() + step); +}, function(start, end) { + return (end - start) / durationDay; +}, function(date2) { + return date2.getUTCDate() - 1; +}); +var utcDays = utcDay.range; +function utcWeekday(i) { + return newInterval(function(date2) { + date2.setUTCDate(date2.getUTCDate() - (date2.getUTCDay() + 7 - i) % 7); + date2.setUTCHours(0, 0, 0, 0); + }, function(date2, step) { + date2.setUTCDate(date2.getUTCDate() + step * 7); + }, function(start, end) { + return (end - start) / durationWeek; + }); +} +var utcSunday = utcWeekday(0); +var utcMonday = utcWeekday(1); +var utcTuesday = utcWeekday(2); +var utcWednesday = utcWeekday(3); +var utcThursday = utcWeekday(4); +var utcFriday = utcWeekday(5); +var utcSaturday = utcWeekday(6); +var utcSundays = utcSunday.range; +var utcMondays = utcMonday.range; +var utcTuesdays = utcTuesday.range; +var utcWednesdays = utcWednesday.range; +var utcThursdays = utcThursday.range; +var utcFridays = utcFriday.range; +var utcSaturdays = utcSaturday.range; +var utcMonth = newInterval(function(date2) { + date2.setUTCDate(1); + date2.setUTCHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setUTCMonth(date2.getUTCMonth() + step); +}, function(start, end) { + return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; +}, function(date2) { + return date2.getUTCMonth(); +}); +var utcMonths = utcMonth.range; +var utcYear = newInterval(function(date2) { + date2.setUTCMonth(0, 1); + date2.setUTCHours(0, 0, 0, 0); +}, function(date2, step) { + date2.setUTCFullYear(date2.getUTCFullYear() + step); +}, function(start, end) { + return end.getUTCFullYear() - start.getUTCFullYear(); +}, function(date2) { + return date2.getUTCFullYear(); +}); +utcYear.every = function(k) { + return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date2) { + date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / k) * k); + date2.setUTCMonth(0, 1); + date2.setUTCHours(0, 0, 0, 0); + }, function(date2, step) { + date2.setUTCFullYear(date2.getUTCFullYear() + step * k); + }); +}; +var utcYears = utcYear.range; +const src$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + timeDay: day, + timeDays: days, + timeFriday: friday, + timeFridays: fridays, + timeHour: hour, + timeHours: hours, + timeInterval: newInterval, + timeMillisecond: millisecond, + timeMilliseconds: milliseconds, + timeMinute: minute, + timeMinutes: minutes, + timeMonday: monday, + timeMondays: mondays, + timeMonth: month, + timeMonths: months, + timeSaturday: saturday, + timeSaturdays: saturdays, + timeSecond: second, + timeSeconds: seconds, + timeSunday: sunday, + timeSundays: sundays, + timeThursday: thursday, + timeThursdays: thursdays, + timeTuesday: tuesday, + timeTuesdays: tuesdays, + timeWednesday: wednesday, + timeWednesdays: wednesdays, + timeWeek: sunday, + timeWeeks: sundays, + timeYear: year, + timeYears: years, + utcDay, + utcDays, + utcFriday, + utcFridays, + utcHour, + utcHours, + utcMillisecond: millisecond, + utcMilliseconds: milliseconds, + utcMinute, + utcMinutes, + utcMonday, + utcMondays, + utcMonth, + utcMonths, + utcSaturday, + utcSaturdays, + utcSecond: second, + utcSeconds: seconds, + utcSunday, + utcSundays, + utcThursday, + utcThursdays, + utcTuesday, + utcTuesdays, + utcWednesday, + utcWednesdays, + utcWeek: utcSunday, + utcWeeks: utcSundays, + utcYear, + utcYears +}, Symbol.toStringTag, { value: "Module" })); +function localDate(d) { + if (0 <= d.y && d.y < 100) { + var date2 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); + date2.setFullYear(d.y); + return date2; + } + return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); +} +function utcDate(d) { + if (0 <= d.y && d.y < 100) { + var date2 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); + date2.setUTCFullYear(d.y); + return date2; + } + return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); +} +function newDate(y, m, d) { + return { y, m, d, H: 0, M: 0, S: 0, L: 0 }; +} +function formatLocale$2(locale2) { + var locale_dateTime = locale2.dateTime, locale_date = locale2.date, locale_time = locale2.time, locale_periods = locale2.periods, locale_weekdays = locale2.days, locale_shortWeekdays = locale2.shortDays, locale_months = locale2.months, locale_shortMonths = locale2.shortMonths; + var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths); + var formats = { + "a": formatShortWeekday, + "A": formatWeekday, + "b": formatShortMonth, + "B": formatMonth, + "c": null, + "d": formatDayOfMonth, + "e": formatDayOfMonth, + "f": formatMicroseconds, + "g": formatYearISO, + "G": formatFullYearISO, + "H": formatHour24, + "I": formatHour12, + "j": formatDayOfYear, + "L": formatMilliseconds, + "m": formatMonthNumber, + "M": formatMinutes, + "p": formatPeriod, + "q": formatQuarter, + "Q": formatUnixTimestamp, + "s": formatUnixTimestampSeconds, + "S": formatSeconds, + "u": formatWeekdayNumberMonday, + "U": formatWeekNumberSunday, + "V": formatWeekNumberISO, + "w": formatWeekdayNumberSunday, + "W": formatWeekNumberMonday, + "x": null, + "X": null, + "y": formatYear, + "Y": formatFullYear, + "Z": formatZone, + "%": formatLiteralPercent + }; + var utcFormats = { + "a": formatUTCShortWeekday, + "A": formatUTCWeekday, + "b": formatUTCShortMonth, + "B": formatUTCMonth, + "c": null, + "d": formatUTCDayOfMonth, + "e": formatUTCDayOfMonth, + "f": formatUTCMicroseconds, + "g": formatUTCYearISO, + "G": formatUTCFullYearISO, + "H": formatUTCHour24, + "I": formatUTCHour12, + "j": formatUTCDayOfYear, + "L": formatUTCMilliseconds, + "m": formatUTCMonthNumber, + "M": formatUTCMinutes, + "p": formatUTCPeriod, + "q": formatUTCQuarter, + "Q": formatUnixTimestamp, + "s": formatUnixTimestampSeconds, + "S": formatUTCSeconds, + "u": formatUTCWeekdayNumberMonday, + "U": formatUTCWeekNumberSunday, + "V": formatUTCWeekNumberISO, + "w": formatUTCWeekdayNumberSunday, + "W": formatUTCWeekNumberMonday, + "x": null, + "X": null, + "y": formatUTCYear, + "Y": formatUTCFullYear, + "Z": formatUTCZone, + "%": formatLiteralPercent + }; + var parses = { + "a": parseShortWeekday, + "A": parseWeekday, + "b": parseShortMonth, + "B": parseMonth, + "c": parseLocaleDateTime, + "d": parseDayOfMonth, + "e": parseDayOfMonth, + "f": parseMicroseconds, + "g": parseYear, + "G": parseFullYear, + "H": parseHour24, + "I": parseHour24, + "j": parseDayOfYear, + "L": parseMilliseconds, + "m": parseMonthNumber, + "M": parseMinutes, + "p": parsePeriod, + "q": parseQuarter, + "Q": parseUnixTimestamp, + "s": parseUnixTimestampSeconds, + "S": parseSeconds, + "u": parseWeekdayNumberMonday, + "U": parseWeekNumberSunday, + "V": parseWeekNumberISO, + "w": parseWeekdayNumberSunday, + "W": parseWeekNumberMonday, + "x": parseLocaleDate, + "X": parseLocaleTime, + "y": parseYear, + "Y": parseFullYear, + "Z": parseZone, + "%": parseLiteralPercent + }; + formats.x = newFormat(locale_date, formats); + formats.X = newFormat(locale_time, formats); + formats.c = newFormat(locale_dateTime, formats); + utcFormats.x = newFormat(locale_date, utcFormats); + utcFormats.X = newFormat(locale_time, utcFormats); + utcFormats.c = newFormat(locale_dateTime, utcFormats); + function newFormat(specifier, formats2) { + return function(date2) { + var string2 = [], i = -1, j = 0, n = specifier.length, c, pad2, format2; + if (!(date2 instanceof Date)) date2 = /* @__PURE__ */ new Date(+date2); + while (++i < n) { + if (specifier.charCodeAt(i) === 37) { + string2.push(specifier.slice(j, i)); + if ((pad2 = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i); + else pad2 = c === "e" ? " " : "0"; + if (format2 = formats2[c]) c = format2(date2, pad2); + string2.push(c); + j = i + 1; + } + } + string2.push(specifier.slice(j, i)); + return string2.join(""); + }; + } + function newParse(specifier, Z) { + return function(string2) { + var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string2 += "", 0), week, day$1; + if (i != string2.length) return null; + if ("Q" in d) return new Date(d.Q); + if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0)); + if (Z && !("Z" in d)) d.Z = 0; + if ("p" in d) d.H = d.H % 12 + d.p * 12; + if (d.m === void 0) d.m = "q" in d ? d.q : 0; + if ("V" in d) { + if (d.V < 1 || d.V > 53) return null; + if (!("w" in d)) d.w = 1; + if ("Z" in d) { + week = utcDate(newDate(d.y, 0, 1)), day$1 = week.getUTCDay(); + week = day$1 > 4 || day$1 === 0 ? utcMonday.ceil(week) : utcMonday(week); + week = utcDay.offset(week, (d.V - 1) * 7); + d.y = week.getUTCFullYear(); + d.m = week.getUTCMonth(); + d.d = week.getUTCDate() + (d.w + 6) % 7; + } else { + week = localDate(newDate(d.y, 0, 1)), day$1 = week.getDay(); + week = day$1 > 4 || day$1 === 0 ? monday.ceil(week) : monday(week); + week = day.offset(week, (d.V - 1) * 7); + d.y = week.getFullYear(); + d.m = week.getMonth(); + d.d = week.getDate() + (d.w + 6) % 7; + } + } else if ("W" in d || "U" in d) { + if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0; + day$1 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(); + d.m = 0; + d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day$1 + 5) % 7 : d.w + d.U * 7 - (day$1 + 6) % 7; + } + if ("Z" in d) { + d.H += d.Z / 100 | 0; + d.M += d.Z % 100; + return utcDate(d); + } + return localDate(d); + }; + } + function parseSpecifier(d, specifier, string2, j) { + var i = 0, n = specifier.length, m = string2.length, c, parse2; + while (i < n) { + if (j >= m) return -1; + c = specifier.charCodeAt(i++); + if (c === 37) { + c = specifier.charAt(i++); + parse2 = parses[c in pads ? specifier.charAt(i++) : c]; + if (!parse2 || (j = parse2(d, string2, j)) < 0) return -1; + } else if (c != string2.charCodeAt(j++)) { + return -1; + } + } + return j; + } + function parsePeriod(d, string2, i) { + var n = periodRe.exec(string2.slice(i)); + return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1; + } + function parseShortWeekday(d, string2, i) { + var n = shortWeekdayRe.exec(string2.slice(i)); + return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; + } + function parseWeekday(d, string2, i) { + var n = weekdayRe.exec(string2.slice(i)); + return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; + } + function parseShortMonth(d, string2, i) { + var n = shortMonthRe.exec(string2.slice(i)); + return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1; + } + function parseMonth(d, string2, i) { + var n = monthRe.exec(string2.slice(i)); + return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1; + } + function parseLocaleDateTime(d, string2, i) { + return parseSpecifier(d, locale_dateTime, string2, i); + } + function parseLocaleDate(d, string2, i) { + return parseSpecifier(d, locale_date, string2, i); + } + function parseLocaleTime(d, string2, i) { + return parseSpecifier(d, locale_time, string2, i); + } + function formatShortWeekday(d) { + return locale_shortWeekdays[d.getDay()]; + } + function formatWeekday(d) { + return locale_weekdays[d.getDay()]; + } + function formatShortMonth(d) { + return locale_shortMonths[d.getMonth()]; + } + function formatMonth(d) { + return locale_months[d.getMonth()]; + } + function formatPeriod(d) { + return locale_periods[+(d.getHours() >= 12)]; + } + function formatQuarter(d) { + return 1 + ~~(d.getMonth() / 3); + } + function formatUTCShortWeekday(d) { + return locale_shortWeekdays[d.getUTCDay()]; + } + function formatUTCWeekday(d) { + return locale_weekdays[d.getUTCDay()]; + } + function formatUTCShortMonth(d) { + return locale_shortMonths[d.getUTCMonth()]; + } + function formatUTCMonth(d) { + return locale_months[d.getUTCMonth()]; + } + function formatUTCPeriod(d) { + return locale_periods[+(d.getUTCHours() >= 12)]; + } + function formatUTCQuarter(d) { + return 1 + ~~(d.getUTCMonth() / 3); + } + return { + format: function(specifier) { + var f = newFormat(specifier += "", formats); + f.toString = function() { + return specifier; + }; + return f; + }, + parse: function(specifier) { + var p = newParse(specifier += "", false); + p.toString = function() { + return specifier; + }; + return p; + }, + utcFormat: function(specifier) { + var f = newFormat(specifier += "", utcFormats); + f.toString = function() { + return specifier; + }; + return f; + }, + utcParse: function(specifier) { + var p = newParse(specifier += "", true); + p.toString = function() { + return specifier; + }; + return p; + } + }; +} +var pads = { "-": "", "_": " ", "0": "0" }, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g; +function pad(value2, fill, width) { + var sign2 = value2 < 0 ? "-" : "", string2 = (sign2 ? -value2 : value2) + "", length2 = string2.length; + return sign2 + (length2 < width ? new Array(width - length2 + 1).join(fill) + string2 : string2); +} +function requote(s) { + return s.replace(requoteRe, "\\$&"); +} +function formatRe(names2) { + return new RegExp("^(?:" + names2.map(requote).join("|") + ")", "i"); +} +function formatLookup(names2) { + var map2 = {}, i = -1, n = names2.length; + while (++i < n) map2[names2[i].toLowerCase()] = i; + return map2; +} +function parseWeekdayNumberSunday(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 1)); + return n ? (d.w = +n[0], i + n[0].length) : -1; +} +function parseWeekdayNumberMonday(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 1)); + return n ? (d.u = +n[0], i + n[0].length) : -1; +} +function parseWeekNumberSunday(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.U = +n[0], i + n[0].length) : -1; +} +function parseWeekNumberISO(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.V = +n[0], i + n[0].length) : -1; +} +function parseWeekNumberMonday(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.W = +n[0], i + n[0].length) : -1; +} +function parseFullYear(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 4)); + return n ? (d.y = +n[0], i + n[0].length) : -1; +} +function parseYear(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1; +} +function parseZone(d, string2, i) { + var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string2.slice(i, i + 6)); + return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1; +} +function parseQuarter(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 1)); + return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1; +} +function parseMonthNumber(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.m = n[0] - 1, i + n[0].length) : -1; +} +function parseDayOfMonth(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.d = +n[0], i + n[0].length) : -1; +} +function parseDayOfYear(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 3)); + return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; +} +function parseHour24(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.H = +n[0], i + n[0].length) : -1; +} +function parseMinutes(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.M = +n[0], i + n[0].length) : -1; +} +function parseSeconds(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 2)); + return n ? (d.S = +n[0], i + n[0].length) : -1; +} +function parseMilliseconds(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 3)); + return n ? (d.L = +n[0], i + n[0].length) : -1; +} +function parseMicroseconds(d, string2, i) { + var n = numberRe.exec(string2.slice(i, i + 6)); + return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1; +} +function parseLiteralPercent(d, string2, i) { + var n = percentRe.exec(string2.slice(i, i + 1)); + return n ? i + n[0].length : -1; +} +function parseUnixTimestamp(d, string2, i) { + var n = numberRe.exec(string2.slice(i)); + return n ? (d.Q = +n[0], i + n[0].length) : -1; +} +function parseUnixTimestampSeconds(d, string2, i) { + var n = numberRe.exec(string2.slice(i)); + return n ? (d.s = +n[0], i + n[0].length) : -1; +} +function formatDayOfMonth(d, p) { + return pad(d.getDate(), p, 2); +} +function formatHour24(d, p) { + return pad(d.getHours(), p, 2); +} +function formatHour12(d, p) { + return pad(d.getHours() % 12 || 12, p, 2); +} +function formatDayOfYear(d, p) { + return pad(1 + day.count(year(d), d), p, 3); +} +function formatMilliseconds(d, p) { + return pad(d.getMilliseconds(), p, 3); +} +function formatMicroseconds(d, p) { + return formatMilliseconds(d, p) + "000"; +} +function formatMonthNumber(d, p) { + return pad(d.getMonth() + 1, p, 2); +} +function formatMinutes(d, p) { + return pad(d.getMinutes(), p, 2); +} +function formatSeconds(d, p) { + return pad(d.getSeconds(), p, 2); +} +function formatWeekdayNumberMonday(d) { + var day2 = d.getDay(); + return day2 === 0 ? 7 : day2; +} +function formatWeekNumberSunday(d, p) { + return pad(sunday.count(year(d) - 1, d), p, 2); +} +function dISO(d) { + var day2 = d.getDay(); + return day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d); +} +function formatWeekNumberISO(d, p) { + d = dISO(d); + return pad(thursday.count(year(d), d) + (year(d).getDay() === 4), p, 2); +} +function formatWeekdayNumberSunday(d) { + return d.getDay(); +} +function formatWeekNumberMonday(d, p) { + return pad(monday.count(year(d) - 1, d), p, 2); +} +function formatYear(d, p) { + return pad(d.getFullYear() % 100, p, 2); +} +function formatYearISO(d, p) { + d = dISO(d); + return pad(d.getFullYear() % 100, p, 2); +} +function formatFullYear(d, p) { + return pad(d.getFullYear() % 1e4, p, 4); +} +function formatFullYearISO(d, p) { + var day2 = d.getDay(); + d = day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d); + return pad(d.getFullYear() % 1e4, p, 4); +} +function formatZone(d) { + var z = d.getTimezoneOffset(); + return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2); +} +function formatUTCDayOfMonth(d, p) { + return pad(d.getUTCDate(), p, 2); +} +function formatUTCHour24(d, p) { + return pad(d.getUTCHours(), p, 2); +} +function formatUTCHour12(d, p) { + return pad(d.getUTCHours() % 12 || 12, p, 2); +} +function formatUTCDayOfYear(d, p) { + return pad(1 + utcDay.count(utcYear(d), d), p, 3); +} +function formatUTCMilliseconds(d, p) { + return pad(d.getUTCMilliseconds(), p, 3); +} +function formatUTCMicroseconds(d, p) { + return formatUTCMilliseconds(d, p) + "000"; +} +function formatUTCMonthNumber(d, p) { + return pad(d.getUTCMonth() + 1, p, 2); +} +function formatUTCMinutes(d, p) { + return pad(d.getUTCMinutes(), p, 2); +} +function formatUTCSeconds(d, p) { + return pad(d.getUTCSeconds(), p, 2); +} +function formatUTCWeekdayNumberMonday(d) { + var dow = d.getUTCDay(); + return dow === 0 ? 7 : dow; +} +function formatUTCWeekNumberSunday(d, p) { + return pad(utcSunday.count(utcYear(d) - 1, d), p, 2); +} +function UTCdISO(d) { + var day2 = d.getUTCDay(); + return day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d); +} +function formatUTCWeekNumberISO(d, p) { + d = UTCdISO(d); + return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2); +} +function formatUTCWeekdayNumberSunday(d) { + return d.getUTCDay(); +} +function formatUTCWeekNumberMonday(d, p) { + return pad(utcMonday.count(utcYear(d) - 1, d), p, 2); +} +function formatUTCYear(d, p) { + return pad(d.getUTCFullYear() % 100, p, 2); +} +function formatUTCYearISO(d, p) { + d = UTCdISO(d); + return pad(d.getUTCFullYear() % 100, p, 2); +} +function formatUTCFullYear(d, p) { + return pad(d.getUTCFullYear() % 1e4, p, 4); +} +function formatUTCFullYearISO(d, p) { + var day2 = d.getUTCDay(); + d = day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d); + return pad(d.getUTCFullYear() % 1e4, p, 4); +} +function formatUTCZone() { + return "+0000"; +} +function formatLiteralPercent() { + return "%"; +} +function formatUnixTimestamp(d) { + return +d; +} +function formatUnixTimestampSeconds(d) { + return Math.floor(+d / 1e3); +} +var locale$1; +var timeFormat; +var timeParse; +var utcFormat$2; +var utcParse; +defaultLocale$1({ + dateTime: "%x, %X", + date: "%-m/%-d/%Y", + time: "%-I:%M:%S %p", + periods: ["AM", "PM"], + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], + shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], + shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] +}); +function defaultLocale$1(definition) { + locale$1 = formatLocale$2(definition); + timeFormat = locale$1.format; + timeParse = locale$1.parse; + utcFormat$2 = locale$1.utcFormat; + utcParse = locale$1.utcParse; + return locale$1; +} +var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ"; +function formatIsoNative(date2) { + return date2.toISOString(); +} +var formatIso = Date.prototype.toISOString ? formatIsoNative : utcFormat$2(isoSpecifier); +function parseIsoNative(string2) { + var date2 = new Date(string2); + return isNaN(date2) ? null : date2; +} +var parseIso = +/* @__PURE__ */ new Date("2000-01-01T00:00:00.000Z") ? parseIsoNative : utcParse(isoSpecifier); +const src$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + isoFormat: formatIso, + isoParse: parseIso, + get timeFormat() { + return timeFormat; + }, + timeFormatDefaultLocale: defaultLocale$1, + timeFormatLocale: formatLocale$2, + get timeParse() { + return timeParse; + }, + get utcFormat() { + return utcFormat$2; + }, + get utcParse() { + return utcParse; + } +}, Symbol.toStringTag, { value: "Module" })); +const require$$1$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$3); +function formatDecimal(x) { + return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10); +} +function formatDecimalParts(x, p) { + if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; + var i, coefficient = x.slice(0, i); + return [ + coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, + +x.slice(i + 1) + ]; +} +function exponent(x) { + return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN; +} +function formatGroup(grouping, thousands) { + return function(value2, width) { + var i = value2.length, t = [], j = 0, g = grouping[0], length2 = 0; + while (i > 0 && g > 0) { + if (length2 + g + 1 > width) g = Math.max(1, width - length2); + t.push(value2.substring(i -= g, i + g)); + if ((length2 += g + 1) > width) break; + g = grouping[j = (j + 1) % grouping.length]; + } + return t.reverse().join(thousands); + }; +} +function formatNumerals(numerals) { + return function(value2) { + return value2.replace(/[0-9]/g, function(i) { + return numerals[+i]; + }); + }; +} +var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i; +function formatSpecifier(specifier) { + if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); + var match; + return new FormatSpecifier({ + fill: match[1], + align: match[2], + sign: match[3], + symbol: match[4], + zero: match[5], + width: match[6], + comma: match[7], + precision: match[8] && match[8].slice(1), + trim: match[9], + type: match[10] + }); +} +formatSpecifier.prototype = FormatSpecifier.prototype; +function FormatSpecifier(specifier) { + this.fill = specifier.fill === void 0 ? " " : specifier.fill + ""; + this.align = specifier.align === void 0 ? ">" : specifier.align + ""; + this.sign = specifier.sign === void 0 ? "-" : specifier.sign + ""; + this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + ""; + this.zero = !!specifier.zero; + this.width = specifier.width === void 0 ? void 0 : +specifier.width; + this.comma = !!specifier.comma; + this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision; + this.trim = !!specifier.trim; + this.type = specifier.type === void 0 ? "" : specifier.type + ""; +} +FormatSpecifier.prototype.toString = function() { + return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type; +}; +function formatTrim(s) { + out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { + switch (s[i]) { + case ".": + i0 = i1 = i; + break; + case "0": + if (i0 === 0) i0 = i; + i1 = i; + break; + default: + if (!+s[i]) break out; + if (i0 > 0) i0 = 0; + break; + } + } + return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; +} +var prefixExponent; +function formatPrefixAuto(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return x + ""; + var coefficient = d[0], exponent2 = d[1], i = exponent2 - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent2 / 3))) * 3) + 1, n = coefficient.length; + return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; +} +function formatRounded(x, p) { + var d = formatDecimalParts(x, p); + if (!d) return x + ""; + var coefficient = d[0], exponent2 = d[1]; + return exponent2 < 0 ? "0." + new Array(-exponent2).join("0") + coefficient : coefficient.length > exponent2 + 1 ? coefficient.slice(0, exponent2 + 1) + "." + coefficient.slice(exponent2 + 1) : coefficient + new Array(exponent2 - coefficient.length + 2).join("0"); +} +const formatTypes = { + "%": function(x, p) { + return (x * 100).toFixed(p); + }, + "b": function(x) { + return Math.round(x).toString(2); + }, + "c": function(x) { + return x + ""; + }, + "d": formatDecimal, + "e": function(x, p) { + return x.toExponential(p); + }, + "f": function(x, p) { + return x.toFixed(p); + }, + "g": function(x, p) { + return x.toPrecision(p); + }, + "o": function(x) { + return Math.round(x).toString(8); + }, + "p": function(x, p) { + return formatRounded(x * 100, p); + }, + "r": formatRounded, + "s": formatPrefixAuto, + "X": function(x) { + return Math.round(x).toString(16).toUpperCase(); + }, + "x": function(x) { + return Math.round(x).toString(16); + } +}; +function identity$5(x) { + return x; +} +var map = Array.prototype.map, prefixes = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"]; +function formatLocale$1(locale2) { + var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity$5 : formatGroup(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity$5 : formatNumerals(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "-" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + ""; + function newFormat(specifier) { + specifier = formatSpecifier(specifier); + var fill = specifier.fill, align3 = specifier.align, sign2 = specifier.sign, symbol = specifier.symbol, zero2 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type; + if (type === "n") comma = true, type = "g"; + else if (!formatTypes[type]) precision === void 0 && (precision = 12), trim = true, type = "g"; + if (zero2 || fill === "0" && align3 === "=") zero2 = true, fill = "0", align3 = "="; + var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : ""; + var formatType = formatTypes[type], maybeSuffix = /[defgprs%]/.test(type); + precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); + function format2(value2) { + var valuePrefix = prefix, valueSuffix = suffix, i, n, c; + if (type === "c") { + valueSuffix = formatType(value2) + valueSuffix; + value2 = ""; + } else { + value2 = +value2; + var valueNegative = value2 < 0 || 1 / value2 < 0; + value2 = isNaN(value2) ? nan : formatType(Math.abs(value2), precision); + if (trim) value2 = formatTrim(value2); + if (valueNegative && +value2 === 0 && sign2 !== "+") valueNegative = false; + valuePrefix = (valueNegative ? sign2 === "(" ? sign2 : minus : sign2 === "-" || sign2 === "(" ? "" : sign2) + valuePrefix; + valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign2 === "(" ? ")" : ""); + if (maybeSuffix) { + i = -1, n = value2.length; + while (++i < n) { + if (c = value2.charCodeAt(i), 48 > c || c > 57) { + valueSuffix = (c === 46 ? decimal + value2.slice(i + 1) : value2.slice(i)) + valueSuffix; + value2 = value2.slice(0, i); + break; + } + } + } + } + if (comma && !zero2) value2 = group(value2, Infinity); + var length2 = valuePrefix.length + value2.length + valueSuffix.length, padding = length2 < width ? new Array(width - length2 + 1).join(fill) : ""; + if (comma && zero2) value2 = group(padding + value2, padding.length ? width - valueSuffix.length : Infinity), padding = ""; + switch (align3) { + case "<": + value2 = valuePrefix + value2 + valueSuffix + padding; + break; + case "=": + value2 = valuePrefix + padding + value2 + valueSuffix; + break; + case "^": + value2 = padding.slice(0, length2 = padding.length >> 1) + valuePrefix + value2 + valueSuffix + padding.slice(length2); + break; + default: + value2 = padding + valuePrefix + value2 + valueSuffix; + break; + } + return numerals(value2); + } + format2.toString = function() { + return specifier + ""; + }; + return format2; + } + function formatPrefix2(specifier, value2) { + var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value2) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; + return function(value3) { + return f(k * value3) + prefix; + }; + } + return { + format: newFormat, + formatPrefix: formatPrefix2 + }; +} +var locale; +var format$2; +var formatPrefix; +defaultLocale({ + decimal: ".", + thousands: ",", + grouping: [3], + currency: ["$", ""], + minus: "-" +}); +function defaultLocale(definition) { + locale = formatLocale$1(definition); + format$2 = locale.format; + formatPrefix = locale.formatPrefix; + return locale; +} +function precisionFixed(step) { + return Math.max(0, -exponent(Math.abs(step))); +} +function precisionPrefix(step, value2) { + return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value2) / 3))) * 3 - exponent(Math.abs(step))); +} +function precisionRound(step, max) { + step = Math.abs(step), max = Math.abs(max) - step; + return Math.max(0, exponent(max) - exponent(step)) + 1; +} +const src$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + FormatSpecifier, + get format() { + return format$2; + }, + formatDefaultLocale: defaultLocale, + formatLocale: formatLocale$1, + get formatPrefix() { + return formatPrefix; + }, + formatSpecifier, + precisionFixed, + precisionPrefix, + precisionRound +}, Symbol.toStringTag, { value: "Module" })); +const require$$2$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$2); +var isStringBlank = function(str2) { + var l = str2.length, a; + for (var i = 0; i < l; i++) { + a = str2.charCodeAt(i); + if ((a < 9 || a > 13) && a !== 32 && a !== 133 && a !== 160 && a !== 5760 && a !== 6158 && (a < 8192 || a > 8205) && a !== 8232 && a !== 8233 && a !== 8239 && a !== 8287 && a !== 8288 && a !== 12288 && a !== 65279) { + return false; + } + } + return true; +}; +var allBlankCharCodes = isStringBlank; +var fastIsnumeric = function(n) { + var type = typeof n; + if (type === "string") { + var original = n; + n = +n; + if (n === 0 && allBlankCharCodes(original)) return false; + } else if (type !== "number") return false; + return n - n < 1; +}; +var numerical = { + /** + * Standardize all missing data in calcdata to use undefined + * never null or NaN. + * That way we can use !==undefined, or !== BADNUM, + * to test for real data + */ + BADNUM: void 0, + /* + * Limit certain operations to well below floating point max value + * to avoid glitches: Make sure that even when you multiply it by the + * number of pixels on a giant screen it still works + */ + FP_SAFE: Number.MAX_VALUE * 1e-4, + /* + * conversion of date units to milliseconds + * year and month constants are marked "AVG" + * to remind us that not all years and months + * have the same length + */ + ONEMAXYEAR: 316224e5, + // 366 * ONEDAY + ONEAVGYEAR: 315576e5, + // 365.25 days + ONEMINYEAR: 31536e6, + // 365 * ONEDAY + ONEMAXQUARTER: 79488e5, + // 92 * ONEDAY + ONEAVGQUARTER: 78894e5, + // 1/4 of ONEAVGYEAR + ONEMINQUARTER: 76896e5, + // 89 * ONEDAY + ONEMAXMONTH: 26784e5, + // 31 * ONEDAY + ONEAVGMONTH: 26298e5, + // 1/12 of ONEAVGYEAR + ONEMINMONTH: 24192e5, + // 28 * ONEDAY + ONEWEEK: 6048e5, + // 7 * ONEDAY + ONEDAY: 864e5, + // 24 * ONEHOUR + ONEHOUR: 36e5, + ONEMIN: 6e4, + ONESEC: 1e3, + ONEMILLI: 1, + ONEMICROSEC: 1e-3, + /* + * For fast conversion btwn world calendars and epoch ms, the Julian Day Number + * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD() + */ + EPOCHJD: 24405875e-1, + /* + * Are two values nearly equal? Compare to 1PPM + */ + ALMOST_EQUAL: 1 - 1e-6, + /* + * If we're asked to clip a non-positive log value, how far off-screen + * do we put it? + */ + LOG_CLIP: 10, + /* + * not a number, but for displaying numbers: the "minus sign" symbol is + * wider than the regular ascii dash "-" + */ + MINUS_SIGN: "−" +}; +var array$2 = {}; +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256); +for (var i$1 = 0; i$1 < chars.length; i$1++) { + lookup$1[chars.charCodeAt(i$1)] = i$1; +} +var encode = function(arraybuffer) { + var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; + for (i = 0; i < len; i += 3) { + base64 += chars[bytes[i] >> 2]; + base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; + base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; + base64 += chars[bytes[i + 2] & 63]; + } + if (len % 3 === 2) { + base64 = base64.substring(0, base64.length - 1) + "="; + } else if (len % 3 === 1) { + base64 = base64.substring(0, base64.length - 2) + "=="; + } + return base64; +}; +var decode = function(base64) { + var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; + if (base64[base64.length - 1] === "=") { + bufferLength--; + if (base64[base64.length - 2] === "=") { + bufferLength--; + } + } + var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); + for (i = 0; i < len; i += 4) { + encoded1 = lookup$1[base64.charCodeAt(i)]; + encoded2 = lookup$1[base64.charCodeAt(i + 1)]; + encoded3 = lookup$1[base64.charCodeAt(i + 2)]; + encoded4 = lookup$1[base64.charCodeAt(i + 3)]; + bytes[p++] = encoded1 << 2 | encoded2 >> 4; + bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; + bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; + } + return arraybuffer; +}; +const base64Arraybuffer_es5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + decode, + encode +}, Symbol.toStringTag, { value: "Module" })); +const require$$4$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(base64Arraybuffer_es5); +var is_plain_object = function isPlainObject(obj) { + if (window && window.process && window.process.versions) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } + return Object.prototype.toString.call(obj) === "[object Object]" && Object.getPrototypeOf(obj).hasOwnProperty("hasOwnProperty"); +}; +var b64decode = require$$4$1.decode; +var isPlainObject$6 = is_plain_object; +var isArray$2 = Array.isArray; +var ab = ArrayBuffer; +var dv = DataView; +function isTypedArray$1(a) { + return ab.isView(a) && !(a instanceof dv); +} +array$2.isTypedArray = isTypedArray$1; +function isArrayOrTypedArray$c(a) { + return isArray$2(a) || isTypedArray$1(a); +} +array$2.isArrayOrTypedArray = isArrayOrTypedArray$c; +function isArray1D(a) { + return !isArrayOrTypedArray$c(a[0]); +} +array$2.isArray1D = isArray1D; +array$2.ensureArray = function(out, n) { + if (!isArray$2(out)) out = []; + out.length = n; + return out; +}; +var typedArrays = { + u1c: typeof Uint8ClampedArray === "undefined" ? void 0 : Uint8ClampedArray, + // not supported in numpy? + i1: typeof Int8Array === "undefined" ? void 0 : Int8Array, + u1: typeof Uint8Array === "undefined" ? void 0 : Uint8Array, + i2: typeof Int16Array === "undefined" ? void 0 : Int16Array, + u2: typeof Uint16Array === "undefined" ? void 0 : Uint16Array, + i4: typeof Int32Array === "undefined" ? void 0 : Int32Array, + u4: typeof Uint32Array === "undefined" ? void 0 : Uint32Array, + f4: typeof Float32Array === "undefined" ? void 0 : Float32Array, + f8: typeof Float64Array === "undefined" ? void 0 : Float64Array + /* TODO: potentially add Big Int + + i8: typeof BigInt64Array === 'undefined' ? undefined : + BigInt64Array, + + u8: typeof BigUint64Array === 'undefined' ? undefined : + BigUint64Array, + */ +}; +typedArrays.uint8c = typedArrays.u1c; +typedArrays.uint8 = typedArrays.u1; +typedArrays.int8 = typedArrays.i1; +typedArrays.uint16 = typedArrays.u2; +typedArrays.int16 = typedArrays.i2; +typedArrays.uint32 = typedArrays.u4; +typedArrays.int32 = typedArrays.i4; +typedArrays.float32 = typedArrays.f4; +typedArrays.float64 = typedArrays.f8; +function isArrayBuffer(a) { + return a.constructor === ArrayBuffer; +} +array$2.isArrayBuffer = isArrayBuffer; +array$2.decodeTypedArraySpec = function(vIn) { + var out = []; + var v = coerceTypedArraySpec(vIn); + var dtype2 = v.dtype; + var T = typedArrays[dtype2]; + if (!T) throw new Error('Error in dtype: "' + dtype2 + '"'); + var BYTES_PER_ELEMENT = T.BYTES_PER_ELEMENT; + var buffer2 = v.bdata; + if (!isArrayBuffer(buffer2)) { + buffer2 = b64decode(buffer2); + } + var shape = v.shape === void 0 ? ( + // detect 1-d length + [buffer2.byteLength / BYTES_PER_ELEMENT] + ) : ( + // convert number to string and split to array + ("" + v.shape).split(",") + ); + shape.reverse(); + var ndim = shape.length; + var nj, j; + var ni = +shape[0]; + var rowBytes = BYTES_PER_ELEMENT * ni; + var pos = 0; + if (ndim === 1) { + out = new T(buffer2); + } else if (ndim === 2) { + nj = +shape[1]; + for (j = 0; j < nj; j++) { + out[j] = new T(buffer2, pos, ni); + pos += rowBytes; + } + } else if (ndim === 3) { + nj = +shape[1]; + var nk = +shape[2]; + for (var k = 0; k < nk; k++) { + out[k] = []; + for (j = 0; j < nj; j++) { + out[k][j] = new T(buffer2, pos, ni); + pos += rowBytes; + } + } + } else { + throw new Error("ndim: " + ndim + 'is not supported with the shape:"' + v.shape + '"'); + } + out.bdata = v.bdata; + out.dtype = v.dtype; + out.shape = shape.reverse().join(","); + vIn._inputArray = out; + return out; +}; +array$2.isTypedArraySpec = function(v) { + return isPlainObject$6(v) && v.hasOwnProperty("dtype") && typeof v.dtype === "string" && v.hasOwnProperty("bdata") && (typeof v.bdata === "string" || isArrayBuffer(v.bdata)) && (v.shape === void 0 || v.hasOwnProperty("shape") && (typeof v.shape === "string" || typeof v.shape === "number")); +}; +function coerceTypedArraySpec(v) { + return { + bdata: v.bdata, + dtype: v.dtype, + shape: v.shape + }; +} +array$2.concat = function() { + var args = []; + var allArray = true; + var totalLen = 0; + var _constructor, arg0, i, argi, posi, leni, out, j; + for (i = 0; i < arguments.length; i++) { + argi = arguments[i]; + leni = argi.length; + if (leni) { + if (arg0) args.push(argi); + else { + arg0 = argi; + posi = leni; + } + if (isArray$2(argi)) { + _constructor = false; + } else { + allArray = false; + if (!totalLen) { + _constructor = argi.constructor; + } else if (_constructor !== argi.constructor) { + _constructor = false; + } + } + totalLen += leni; + } + } + if (!totalLen) return []; + if (!args.length) return arg0; + if (allArray) return arg0.concat.apply(arg0, args); + if (_constructor) { + out = new _constructor(totalLen); + out.set(arg0); + for (i = 0; i < args.length; i++) { + argi = args[i]; + out.set(argi, posi); + posi += argi.length; + } + return out; + } + out = new Array(totalLen); + for (j = 0; j < arg0.length; j++) out[j] = arg0[j]; + for (i = 0; i < args.length; i++) { + argi = args[i]; + for (j = 0; j < argi.length; j++) out[posi + j] = argi[j]; + posi += j; + } + return out; +}; +array$2.maxRowLength = function(z) { + return _rowLength(z, Math.max, 0); +}; +array$2.minRowLength = function(z) { + return _rowLength(z, Math.min, Infinity); +}; +function _rowLength(z, fn, len0) { + if (isArrayOrTypedArray$c(z)) { + if (isArrayOrTypedArray$c(z[0])) { + var len = len0; + for (var i = 0; i < z.length; i++) { + len = fn(len, z[i].length); + } + return len; + } else { + return z.length; + } + } + return 0; +} +var isNumeric$B = fastIsnumeric; +var isArrayOrTypedArray$b = array$2.isArrayOrTypedArray; +var nested_property = function nestedProperty(container, propStr) { + if (isNumeric$B(propStr)) propStr = String(propStr); + else if (typeof propStr !== "string" || propStr.substr(propStr.length - 4) === "[-1]") { + throw "bad property string"; + } + var propParts = propStr.split("."); + var indexed; + var indices; + var i, j; + for (j = 0; j < propParts.length; j++) { + if (String(propParts[j]).slice(0, 2) === "__") { + throw "bad property string"; + } + } + j = 0; + while (j < propParts.length) { + indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/); + if (indexed) { + if (indexed[1]) propParts[j] = indexed[1]; + else if (j === 0) propParts.splice(0, 1); + else throw "bad property string"; + indices = indexed[2].substr(1, indexed[2].length - 2).split("]["); + for (i = 0; i < indices.length; i++) { + j++; + propParts.splice(j, 0, Number(indices[i])); + } + } + j++; + } + if (typeof container !== "object") { + return badContainer(container, propStr, propParts); + } + return { + set: npSet(container, propParts, propStr), + get: npGet(container, propParts), + astr: propStr, + parts: propParts, + obj: container + }; +}; +function npGet(cont, parts) { + return function() { + var curCont = cont; + var curPart; + var allSame; + var out; + var i; + var j; + for (i = 0; i < parts.length - 1; i++) { + curPart = parts[i]; + if (curPart === -1) { + allSame = true; + out = []; + for (j = 0; j < curCont.length; j++) { + out[j] = npGet(curCont[j], parts.slice(i + 1))(); + if (out[j] !== out[0]) allSame = false; + } + return allSame ? out[0] : out; + } + if (typeof curPart === "number" && !isArrayOrTypedArray$b(curCont)) { + return void 0; + } + curCont = curCont[curPart]; + if (typeof curCont !== "object" || curCont === null) { + return void 0; + } + } + if (typeof curCont !== "object" || curCont === null) return void 0; + out = curCont[parts[i]]; + if (out === null) return void 0; + return out; + }; +} +var ARGS_PATTERN = /(^|\.)args\[/; +function isDeletable(val, propStr) { + return val === void 0 || val === null && !propStr.match(ARGS_PATTERN); +} +function npSet(cont, parts, propStr) { + return function(val) { + var curCont = cont; + var propPart = ""; + var toDelete = isDeletable(val, propStr); + var curPart; + var i; + for (i = 0; i < parts.length - 1; i++) { + curPart = parts[i]; + if (typeof curPart === "number" && !isArrayOrTypedArray$b(curCont)) { + throw "array index but container is not an array"; + } + if (curPart === -1) { + toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr); + if (toDelete) break; + else return; + } + if (!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) { + break; + } + curCont = curCont[curPart]; + if (typeof curCont !== "object" || curCont === null) { + throw "container is not an object"; + } + propPart = joinPropStr(propPart, curPart); + } + if (toDelete) { + if (i === parts.length - 1) { + delete curCont[parts[i]]; + if (Array.isArray(curCont) && +parts[i] === curCont.length - 1) { + while (curCont.length && curCont[curCont.length - 1] === void 0) { + curCont.pop(); + } + } + } + } else curCont[parts[i]] = val; + }; +} +function joinPropStr(propStr, newPart) { + var toAdd = newPart; + if (isNumeric$B(newPart)) toAdd = "[" + newPart + "]"; + else if (propStr) toAdd = "." + newPart; + return propStr + toAdd; +} +function setArrayAll(containerArray, innerParts, val, propStr) { + var arrayVal = isArrayOrTypedArray$b(val); + var allSet = true; + var thisVal = val; + var thisPropStr = propStr.replace("-1", 0); + var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr); + var firstPart = innerParts[0]; + var i; + for (i = 0; i < containerArray.length; i++) { + thisPropStr = propStr.replace("-1", i); + if (arrayVal) { + thisVal = val[i % val.length]; + deleteThis = isDeletable(thisVal, thisPropStr); + } + if (deleteThis) allSet = false; + if (!checkNewContainer(containerArray, i, firstPart, deleteThis)) { + continue; + } + npSet(containerArray[i], innerParts, propStr.replace("-1", i))(thisVal); + } + return allSet; +} +function checkNewContainer(container, part, nextPart, toDelete) { + if (container[part] === void 0) { + if (toDelete) return false; + if (typeof nextPart === "number") container[part] = []; + else container[part] = {}; + } + return true; +} +function badContainer(container, propStr, propParts) { + return { + set: function() { + throw "bad container"; + }, + get: function() { + }, + astr: propStr, + parts: propParts, + obj: container + }; +} +var nestedProperty$1 = nested_property; +var SIMPLE_PROPERTY_REGEX$1 = /^\w*$/; +var NONE = 0; +var NAME = 1; +var VALUE = 2; +var BOTH = 3; +var UNSET = 4; +var keyed_container = function keyedContainer(baseObj, path, keyName, valueName) { + keyName = keyName || "name"; + valueName = valueName || "value"; + var i, arr, baseProp; + var changeTypes = {}; + if (path && path.length) { + baseProp = nestedProperty$1(baseObj, path); + arr = baseProp.get(); + } else { + arr = baseObj; + } + path = path || ""; + var indexLookup = {}; + if (arr) { + for (i = 0; i < arr.length; i++) { + indexLookup[arr[i][keyName]] = i; + } + } + var isSimpleValueProp = SIMPLE_PROPERTY_REGEX$1.test(valueName); + var obj = { + set: function(name2, value2) { + var changeType = value2 === null ? UNSET : NONE; + if (!arr) { + if (!baseProp || changeType === UNSET) return; + arr = []; + baseProp.set(arr); + } + var idx = indexLookup[name2]; + if (idx === void 0) { + if (changeType === UNSET) return; + changeType = changeType | BOTH; + idx = arr.length; + indexLookup[name2] = idx; + } else if (value2 !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty$1(arr[idx], valueName).get())) { + changeType = changeType | VALUE; + } + var newValue = arr[idx] = arr[idx] || {}; + newValue[keyName] = name2; + if (isSimpleValueProp) { + newValue[valueName] = value2; + } else { + nestedProperty$1(newValue, valueName).set(value2); + } + if (value2 !== null) { + changeType = changeType & -5; + } + changeTypes[idx] = changeTypes[idx] | changeType; + return obj; + }, + get: function(name2) { + if (!arr) return; + var idx = indexLookup[name2]; + if (idx === void 0) { + return void 0; + } else if (isSimpleValueProp) { + return arr[idx][valueName]; + } else { + return nestedProperty$1(arr[idx], valueName).get(); + } + }, + rename: function(name2, newName) { + var idx = indexLookup[name2]; + if (idx === void 0) return obj; + changeTypes[idx] = changeTypes[idx] | NAME; + indexLookup[newName] = idx; + delete indexLookup[name2]; + arr[idx][keyName] = newName; + return obj; + }, + remove: function(name2) { + var idx = indexLookup[name2]; + if (idx === void 0) return obj; + var object2 = arr[idx]; + if (Object.keys(object2).length > 2) { + changeTypes[idx] = changeTypes[idx] | VALUE; + return obj.set(name2, null); + } + if (isSimpleValueProp) { + for (i = idx; i < arr.length; i++) { + changeTypes[i] = changeTypes[i] | BOTH; + } + for (i = idx; i < arr.length; i++) { + indexLookup[arr[i][keyName]]--; + } + arr.splice(idx, 1); + delete indexLookup[name2]; + } else { + nestedProperty$1(object2, valueName).set(null); + changeTypes[idx] = changeTypes[idx] | VALUE | UNSET; + } + return obj; + }, + constructUpdate: function() { + var astr, idx; + var update2 = {}; + var changed = Object.keys(changeTypes); + for (var i2 = 0; i2 < changed.length; i2++) { + idx = changed[i2]; + astr = path + "[" + idx + "]"; + if (arr[idx]) { + if (changeTypes[idx] & NAME) { + update2[astr + "." + keyName] = arr[idx][keyName]; + } + if (changeTypes[idx] & VALUE) { + if (isSimpleValueProp) { + update2[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : arr[idx][valueName]; + } else { + update2[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : nestedProperty$1(arr[idx], valueName).get(); + } + } + } else { + update2[astr] = null; + } + } + return update2; + } + }; + return obj; +}; +var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/; +var SIMPLEATTR = /^[^\.\[\]]+$/; +var relative_attr = function(baseAttr, relativeAttr) { + while (relativeAttr) { + var match = baseAttr.match(ASCEND); + if (match) baseAttr = match[1]; + else if (baseAttr.match(SIMPLEATTR)) baseAttr = ""; + else throw new Error("bad relativeAttr call:" + [baseAttr, relativeAttr]); + if (relativeAttr.charAt(0) === "^") relativeAttr = relativeAttr.slice(1); + else break; + } + if (baseAttr && relativeAttr.charAt(0) !== "[") { + return baseAttr + "." + relativeAttr; + } + return baseAttr + relativeAttr; +}; +var isNumeric$A = fastIsnumeric; +var to_log_range = function toLogRange(val, range) { + if (val > 0) return Math.log(val) / Math.LN10; + var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10; + if (!isNumeric$A(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; + return newVal; +}; +var isArrayOrTypedArray$a = array$2.isArrayOrTypedArray; +var isPlainObject$5 = is_plain_object; +var relink_private = function relinkPrivateKeys(toContainer, fromContainer) { + for (var k in fromContainer) { + var fromVal = fromContainer[k]; + var toVal = toContainer[k]; + if (toVal === fromVal) continue; + if (k.charAt(0) === "_" || typeof fromVal === "function") { + if (k in toContainer) continue; + toContainer[k] = fromVal; + } else if (isArrayOrTypedArray$a(fromVal) && isArrayOrTypedArray$a(toVal) && isPlainObject$5(fromVal[0])) { + if (k === "customdata" || k === "ids") continue; + var minLen = Math.min(fromVal.length, toVal.length); + for (var j = 0; j < minLen; j++) { + if (toVal[j] !== fromVal[j] && isPlainObject$5(fromVal[j]) && isPlainObject$5(toVal[j])) { + relinkPrivateKeys(toVal[j], fromVal[j]); + } + } + } else if (isPlainObject$5(fromVal) && isPlainObject$5(toVal)) { + relinkPrivateKeys(toVal, fromVal); + if (!Object.keys(toVal).length) delete toContainer[k]; + } + } +}; +function mod$2(v, d) { + var out = v % d; + return out < 0 ? out + d : out; +} +function modHalf$1(v, d) { + return Math.abs(v) > d / 2 ? v - Math.round(v / d) * d : v; +} +var mod_1 = { + mod: mod$2, + modHalf: modHalf$1 +}; +var coerce$1 = {}; +var tinycolor$8 = { exports: {} }; +(function(module2, exports2) { + (function(global, factory2) { + module2.exports = factory2(); + })(index$3.commonjsGlobal, function() { + function _typeof(obj) { + "@babel/helpers - typeof"; + return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { + return typeof obj2; + } : function(obj2) { + return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; + }, _typeof(obj); + } + var trimLeft = /^\s+/; + var trimRight = /\s+$/; + function tinycolor2(color2, opts) { + color2 = color2 ? color2 : ""; + opts = opts || {}; + if (color2 instanceof tinycolor2) { + return color2; + } + if (!(this instanceof tinycolor2)) { + return new tinycolor2(color2, opts); + } + var rgb2 = inputToRGB(color2); + this._originalInput = color2, this._r = rgb2.r, this._g = rgb2.g, this._b = rgb2.b, this._a = rgb2.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb2.format; + this._gradientType = opts.gradientType; + if (this._r < 1) this._r = Math.round(this._r); + if (this._g < 1) this._g = Math.round(this._g); + if (this._b < 1) this._b = Math.round(this._b); + this._ok = rgb2.ok; + } + tinycolor2.prototype = { + isDark: function isDark() { + return this.getBrightness() < 128; + }, + isLight: function isLight() { + return !this.isDark(); + }, + isValid: function isValid() { + return this._ok; + }, + getOriginalInput: function getOriginalInput() { + return this._originalInput; + }, + getFormat: function getFormat() { + return this._format; + }, + getAlpha: function getAlpha() { + return this._a; + }, + getBrightness: function getBrightness() { + var rgb2 = this.toRgb(); + return (rgb2.r * 299 + rgb2.g * 587 + rgb2.b * 114) / 1e3; + }, + getLuminance: function getLuminance() { + var rgb2 = this.toRgb(); + var RsRGB, GsRGB, BsRGB, R2, G, B2; + RsRGB = rgb2.r / 255; + GsRGB = rgb2.g / 255; + BsRGB = rgb2.b / 255; + if (RsRGB <= 0.03928) R2 = RsRGB / 12.92; + else R2 = Math.pow((RsRGB + 0.055) / 1.055, 2.4); + if (GsRGB <= 0.03928) G = GsRGB / 12.92; + else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); + if (BsRGB <= 0.03928) B2 = BsRGB / 12.92; + else B2 = Math.pow((BsRGB + 0.055) / 1.055, 2.4); + return 0.2126 * R2 + 0.7152 * G + 0.0722 * B2; + }, + setAlpha: function setAlpha(value2) { + this._a = boundAlpha(value2); + this._roundA = Math.round(100 * this._a) / 100; + return this; + }, + toHsv: function toHsv() { + var hsv = rgbToHsv(this._r, this._g, this._b); + return { + h: hsv.h * 360, + s: hsv.s, + v: hsv.v, + a: this._a + }; + }, + toHsvString: function toHsvString() { + var hsv = rgbToHsv(this._r, this._g, this._b); + var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100); + return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; + }, + toHsl: function toHsl() { + var hsl2 = rgbToHsl(this._r, this._g, this._b); + return { + h: hsl2.h * 360, + s: hsl2.s, + l: hsl2.l, + a: this._a + }; + }, + toHslString: function toHslString() { + var hsl2 = rgbToHsl(this._r, this._g, this._b); + var h = Math.round(hsl2.h * 360), s = Math.round(hsl2.s * 100), l = Math.round(hsl2.l * 100); + return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; + }, + toHex: function toHex(allow3Char) { + return rgbToHex(this._r, this._g, this._b, allow3Char); + }, + toHexString: function toHexString(allow3Char) { + return "#" + this.toHex(allow3Char); + }, + toHex8: function toHex8(allow4Char) { + return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); + }, + toHex8String: function toHex8String(allow4Char) { + return "#" + this.toHex8(allow4Char); + }, + toRgb: function toRgb() { + return { + r: Math.round(this._r), + g: Math.round(this._g), + b: Math.round(this._b), + a: this._a + }; + }, + toRgbString: function toRgbString() { + return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; + }, + toPercentageRgb: function toPercentageRgb() { + return { + r: Math.round(bound01(this._r, 255) * 100) + "%", + g: Math.round(bound01(this._g, 255) * 100) + "%", + b: Math.round(bound01(this._b, 255) * 100) + "%", + a: this._a + }; + }, + toPercentageRgbString: function toPercentageRgbString() { + return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; + }, + toName: function toName() { + if (this._a === 0) { + return "transparent"; + } + if (this._a < 1) { + return false; + } + return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; + }, + toFilter: function toFilter(secondColor) { + var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); + var secondHex8String = hex8String; + var gradientType = this._gradientType ? "GradientType = 1, " : ""; + if (secondColor) { + var s = tinycolor2(secondColor); + secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); + } + return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; + }, + toString: function toString2(format2) { + var formatSet = !!format2; + format2 = format2 || this._format; + var formattedString = false; + var hasAlpha = this._a < 1 && this._a >= 0; + var needsAlphaFormat = !formatSet && hasAlpha && (format2 === "hex" || format2 === "hex6" || format2 === "hex3" || format2 === "hex4" || format2 === "hex8" || format2 === "name"); + if (needsAlphaFormat) { + if (format2 === "name" && this._a === 0) { + return this.toName(); + } + return this.toRgbString(); + } + if (format2 === "rgb") { + formattedString = this.toRgbString(); + } + if (format2 === "prgb") { + formattedString = this.toPercentageRgbString(); + } + if (format2 === "hex" || format2 === "hex6") { + formattedString = this.toHexString(); + } + if (format2 === "hex3") { + formattedString = this.toHexString(true); + } + if (format2 === "hex4") { + formattedString = this.toHex8String(true); + } + if (format2 === "hex8") { + formattedString = this.toHex8String(); + } + if (format2 === "name") { + formattedString = this.toName(); + } + if (format2 === "hsl") { + formattedString = this.toHslString(); + } + if (format2 === "hsv") { + formattedString = this.toHsvString(); + } + return formattedString || this.toHexString(); + }, + clone: function clone2() { + return tinycolor2(this.toString()); + }, + _applyModification: function _applyModification(fn, args) { + var color2 = fn.apply(null, [this].concat([].slice.call(args))); + this._r = color2._r; + this._g = color2._g; + this._b = color2._b; + this.setAlpha(color2._a); + return this; + }, + lighten: function lighten() { + return this._applyModification(_lighten, arguments); + }, + brighten: function brighten() { + return this._applyModification(_brighten, arguments); + }, + darken: function darken() { + return this._applyModification(_darken, arguments); + }, + desaturate: function desaturate() { + return this._applyModification(_desaturate, arguments); + }, + saturate: function saturate() { + return this._applyModification(_saturate, arguments); + }, + greyscale: function greyscale() { + return this._applyModification(_greyscale, arguments); + }, + spin: function spin() { + return this._applyModification(_spin, arguments); + }, + _applyCombination: function _applyCombination(fn, args) { + return fn.apply(null, [this].concat([].slice.call(args))); + }, + analogous: function analogous() { + return this._applyCombination(_analogous, arguments); + }, + complement: function complement() { + return this._applyCombination(_complement, arguments); + }, + monochromatic: function monochromatic() { + return this._applyCombination(_monochromatic, arguments); + }, + splitcomplement: function splitcomplement() { + return this._applyCombination(_splitcomplement, arguments); + }, + // Disabled until https://github.com/bgrins/TinyColor/issues/254 + // polyad: function (number) { + // return this._applyCombination(polyad, [number]); + // }, + triad: function triad() { + return this._applyCombination(polyad, [3]); + }, + tetrad: function tetrad() { + return this._applyCombination(polyad, [4]); + } + }; + tinycolor2.fromRatio = function(color2, opts) { + if (_typeof(color2) == "object") { + var newColor = {}; + for (var i in color2) { + if (color2.hasOwnProperty(i)) { + if (i === "a") { + newColor[i] = color2[i]; + } else { + newColor[i] = convertToPercentage(color2[i]); + } + } + } + color2 = newColor; + } + return tinycolor2(color2, opts); + }; + function inputToRGB(color2) { + var rgb2 = { + r: 0, + g: 0, + b: 0 + }; + var a = 1; + var s = null; + var v = null; + var l = null; + var ok = false; + var format2 = false; + if (typeof color2 == "string") { + color2 = stringInputToObject(color2); + } + if (_typeof(color2) == "object") { + if (isValidCSSUnit(color2.r) && isValidCSSUnit(color2.g) && isValidCSSUnit(color2.b)) { + rgb2 = rgbToRgb(color2.r, color2.g, color2.b); + ok = true; + format2 = String(color2.r).substr(-1) === "%" ? "prgb" : "rgb"; + } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.v)) { + s = convertToPercentage(color2.s); + v = convertToPercentage(color2.v); + rgb2 = hsvToRgb(color2.h, s, v); + ok = true; + format2 = "hsv"; + } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.l)) { + s = convertToPercentage(color2.s); + l = convertToPercentage(color2.l); + rgb2 = hslToRgb(color2.h, s, l); + ok = true; + format2 = "hsl"; + } + if (color2.hasOwnProperty("a")) { + a = color2.a; + } + } + a = boundAlpha(a); + return { + ok, + format: color2.format || format2, + r: Math.min(255, Math.max(rgb2.r, 0)), + g: Math.min(255, Math.max(rgb2.g, 0)), + b: Math.min(255, Math.max(rgb2.b, 0)), + a + }; + } + function rgbToRgb(r, g, b) { + return { + r: bound01(r, 255) * 255, + g: bound01(g, 255) * 255, + b: bound01(b, 255) * 255 + }; + } + function rgbToHsl(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, l = (max + min) / 2; + if (max == min) { + h = s = 0; + } else { + var d = max - min; + s = l > 0.5 ? d / (2 - max - min) : d / (max + min); + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h, + s, + l + }; + } + function hslToRgb(h, s, l) { + var r, g, b; + h = bound01(h, 360); + s = bound01(s, 100); + l = bound01(l, 100); + function hue2rgb(p2, q2, t) { + if (t < 0) t += 1; + if (t > 1) t -= 1; + if (t < 1 / 6) return p2 + (q2 - p2) * 6 * t; + if (t < 1 / 2) return q2; + if (t < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t) * 6; + return p2; + } + if (s === 0) { + r = g = b = l; + } else { + var q = l < 0.5 ? l * (1 + s) : l + s - l * s; + var p = 2 * l - q; + r = hue2rgb(p, q, h + 1 / 3); + g = hue2rgb(p, q, h); + b = hue2rgb(p, q, h - 1 / 3); + } + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + function rgbToHsv(r, g, b) { + r = bound01(r, 255); + g = bound01(g, 255); + b = bound01(b, 255); + var max = Math.max(r, g, b), min = Math.min(r, g, b); + var h, s, v = max; + var d = max - min; + s = max === 0 ? 0 : d / max; + if (max == min) { + h = 0; + } else { + switch (max) { + case r: + h = (g - b) / d + (g < b ? 6 : 0); + break; + case g: + h = (b - r) / d + 2; + break; + case b: + h = (r - g) / d + 4; + break; + } + h /= 6; + } + return { + h, + s, + v + }; + } + function hsvToRgb(h, s, v) { + h = bound01(h, 360) * 6; + s = bound01(s, 100); + v = bound01(v, 100); + var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod2 = i % 6, r = [v, q, p, p, t, v][mod2], g = [t, v, v, q, p, p][mod2], b = [p, p, t, v, v, q][mod2]; + return { + r: r * 255, + g: g * 255, + b: b * 255 + }; + } + function rgbToHex(r, g, b, allow3Char) { + var hex2 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + if (allow3Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1)) { + return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0); + } + return hex2.join(""); + } + function rgbaToHex(r, g, b, a, allow4Char) { + var hex2 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; + if (allow4Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1) && hex2[3].charAt(0) == hex2[3].charAt(1)) { + return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0) + hex2[3].charAt(0); + } + return hex2.join(""); + } + function rgbaToArgbHex(r, g, b, a) { + var hex2 = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; + return hex2.join(""); + } + tinycolor2.equals = function(color1, color2) { + if (!color1 || !color2) return false; + return tinycolor2(color1).toRgbString() == tinycolor2(color2).toRgbString(); + }; + tinycolor2.random = function() { + return tinycolor2.fromRatio({ + r: Math.random(), + g: Math.random(), + b: Math.random() + }); + }; + function _desaturate(color2, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl2 = tinycolor2(color2).toHsl(); + hsl2.s -= amount / 100; + hsl2.s = clamp01(hsl2.s); + return tinycolor2(hsl2); + } + function _saturate(color2, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl2 = tinycolor2(color2).toHsl(); + hsl2.s += amount / 100; + hsl2.s = clamp01(hsl2.s); + return tinycolor2(hsl2); + } + function _greyscale(color2) { + return tinycolor2(color2).desaturate(100); + } + function _lighten(color2, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl2 = tinycolor2(color2).toHsl(); + hsl2.l += amount / 100; + hsl2.l = clamp01(hsl2.l); + return tinycolor2(hsl2); + } + function _brighten(color2, amount) { + amount = amount === 0 ? 0 : amount || 10; + var rgb2 = tinycolor2(color2).toRgb(); + rgb2.r = Math.max(0, Math.min(255, rgb2.r - Math.round(255 * -(amount / 100)))); + rgb2.g = Math.max(0, Math.min(255, rgb2.g - Math.round(255 * -(amount / 100)))); + rgb2.b = Math.max(0, Math.min(255, rgb2.b - Math.round(255 * -(amount / 100)))); + return tinycolor2(rgb2); + } + function _darken(color2, amount) { + amount = amount === 0 ? 0 : amount || 10; + var hsl2 = tinycolor2(color2).toHsl(); + hsl2.l -= amount / 100; + hsl2.l = clamp01(hsl2.l); + return tinycolor2(hsl2); + } + function _spin(color2, amount) { + var hsl2 = tinycolor2(color2).toHsl(); + var hue2 = (hsl2.h + amount) % 360; + hsl2.h = hue2 < 0 ? 360 + hue2 : hue2; + return tinycolor2(hsl2); + } + function _complement(color2) { + var hsl2 = tinycolor2(color2).toHsl(); + hsl2.h = (hsl2.h + 180) % 360; + return tinycolor2(hsl2); + } + function polyad(color2, number2) { + if (isNaN(number2) || number2 <= 0) { + throw new Error("Argument to polyad must be a positive number"); + } + var hsl2 = tinycolor2(color2).toHsl(); + var result = [tinycolor2(color2)]; + var step = 360 / number2; + for (var i = 1; i < number2; i++) { + result.push(tinycolor2({ + h: (hsl2.h + i * step) % 360, + s: hsl2.s, + l: hsl2.l + })); + } + return result; + } + function _splitcomplement(color2) { + var hsl2 = tinycolor2(color2).toHsl(); + var h = hsl2.h; + return [tinycolor2(color2), tinycolor2({ + h: (h + 72) % 360, + s: hsl2.s, + l: hsl2.l + }), tinycolor2({ + h: (h + 216) % 360, + s: hsl2.s, + l: hsl2.l + })]; + } + function _analogous(color2, results, slices) { + results = results || 6; + slices = slices || 30; + var hsl2 = tinycolor2(color2).toHsl(); + var part = 360 / slices; + var ret = [tinycolor2(color2)]; + for (hsl2.h = (hsl2.h - (part * results >> 1) + 720) % 360; --results; ) { + hsl2.h = (hsl2.h + part) % 360; + ret.push(tinycolor2(hsl2)); + } + return ret; + } + function _monochromatic(color2, results) { + results = results || 6; + var hsv = tinycolor2(color2).toHsv(); + var h = hsv.h, s = hsv.s, v = hsv.v; + var ret = []; + var modification = 1 / results; + while (results--) { + ret.push(tinycolor2({ + h, + s, + v + })); + v = (v + modification) % 1; + } + return ret; + } + tinycolor2.mix = function(color1, color2, amount) { + amount = amount === 0 ? 0 : amount || 50; + var rgb1 = tinycolor2(color1).toRgb(); + var rgb2 = tinycolor2(color2).toRgb(); + var p = amount / 100; + var rgba3 = { + r: (rgb2.r - rgb1.r) * p + rgb1.r, + g: (rgb2.g - rgb1.g) * p + rgb1.g, + b: (rgb2.b - rgb1.b) * p + rgb1.b, + a: (rgb2.a - rgb1.a) * p + rgb1.a + }; + return tinycolor2(rgba3); + }; + tinycolor2.readability = function(color1, color2) { + var c1 = tinycolor2(color1); + var c2 = tinycolor2(color2); + return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05); + }; + tinycolor2.isReadable = function(color1, color2, wcag2) { + var readability = tinycolor2.readability(color1, color2); + var wcag2Parms, out; + out = false; + wcag2Parms = validateWCAG2Parms(wcag2); + switch (wcag2Parms.level + wcag2Parms.size) { + case "AAsmall": + case "AAAlarge": + out = readability >= 4.5; + break; + case "AAlarge": + out = readability >= 3; + break; + case "AAAsmall": + out = readability >= 7; + break; + } + return out; + }; + tinycolor2.mostReadable = function(baseColor, colorList, args) { + var bestColor = null; + var bestScore = 0; + var readability; + var includeFallbackColors, level, size; + args = args || {}; + includeFallbackColors = args.includeFallbackColors; + level = args.level; + size = args.size; + for (var i = 0; i < colorList.length; i++) { + readability = tinycolor2.readability(baseColor, colorList[i]); + if (readability > bestScore) { + bestScore = readability; + bestColor = tinycolor2(colorList[i]); + } + } + if (tinycolor2.isReadable(baseColor, bestColor, { + level, + size + }) || !includeFallbackColors) { + return bestColor; + } else { + args.includeFallbackColors = false; + return tinycolor2.mostReadable(baseColor, ["#fff", "#000"], args); + } + }; + var names2 = tinycolor2.names = { + aliceblue: "f0f8ff", + antiquewhite: "faebd7", + aqua: "0ff", + aquamarine: "7fffd4", + azure: "f0ffff", + beige: "f5f5dc", + bisque: "ffe4c4", + black: "000", + blanchedalmond: "ffebcd", + blue: "00f", + blueviolet: "8a2be2", + brown: "a52a2a", + burlywood: "deb887", + burntsienna: "ea7e5d", + cadetblue: "5f9ea0", + chartreuse: "7fff00", + chocolate: "d2691e", + coral: "ff7f50", + cornflowerblue: "6495ed", + cornsilk: "fff8dc", + crimson: "dc143c", + cyan: "0ff", + darkblue: "00008b", + darkcyan: "008b8b", + darkgoldenrod: "b8860b", + darkgray: "a9a9a9", + darkgreen: "006400", + darkgrey: "a9a9a9", + darkkhaki: "bdb76b", + darkmagenta: "8b008b", + darkolivegreen: "556b2f", + darkorange: "ff8c00", + darkorchid: "9932cc", + darkred: "8b0000", + darksalmon: "e9967a", + darkseagreen: "8fbc8f", + darkslateblue: "483d8b", + darkslategray: "2f4f4f", + darkslategrey: "2f4f4f", + darkturquoise: "00ced1", + darkviolet: "9400d3", + deeppink: "ff1493", + deepskyblue: "00bfff", + dimgray: "696969", + dimgrey: "696969", + dodgerblue: "1e90ff", + firebrick: "b22222", + floralwhite: "fffaf0", + forestgreen: "228b22", + fuchsia: "f0f", + gainsboro: "dcdcdc", + ghostwhite: "f8f8ff", + gold: "ffd700", + goldenrod: "daa520", + gray: "808080", + green: "008000", + greenyellow: "adff2f", + grey: "808080", + honeydew: "f0fff0", + hotpink: "ff69b4", + indianred: "cd5c5c", + indigo: "4b0082", + ivory: "fffff0", + khaki: "f0e68c", + lavender: "e6e6fa", + lavenderblush: "fff0f5", + lawngreen: "7cfc00", + lemonchiffon: "fffacd", + lightblue: "add8e6", + lightcoral: "f08080", + lightcyan: "e0ffff", + lightgoldenrodyellow: "fafad2", + lightgray: "d3d3d3", + lightgreen: "90ee90", + lightgrey: "d3d3d3", + lightpink: "ffb6c1", + lightsalmon: "ffa07a", + lightseagreen: "20b2aa", + lightskyblue: "87cefa", + lightslategray: "789", + lightslategrey: "789", + lightsteelblue: "b0c4de", + lightyellow: "ffffe0", + lime: "0f0", + limegreen: "32cd32", + linen: "faf0e6", + magenta: "f0f", + maroon: "800000", + mediumaquamarine: "66cdaa", + mediumblue: "0000cd", + mediumorchid: "ba55d3", + mediumpurple: "9370db", + mediumseagreen: "3cb371", + mediumslateblue: "7b68ee", + mediumspringgreen: "00fa9a", + mediumturquoise: "48d1cc", + mediumvioletred: "c71585", + midnightblue: "191970", + mintcream: "f5fffa", + mistyrose: "ffe4e1", + moccasin: "ffe4b5", + navajowhite: "ffdead", + navy: "000080", + oldlace: "fdf5e6", + olive: "808000", + olivedrab: "6b8e23", + orange: "ffa500", + orangered: "ff4500", + orchid: "da70d6", + palegoldenrod: "eee8aa", + palegreen: "98fb98", + paleturquoise: "afeeee", + palevioletred: "db7093", + papayawhip: "ffefd5", + peachpuff: "ffdab9", + peru: "cd853f", + pink: "ffc0cb", + plum: "dda0dd", + powderblue: "b0e0e6", + purple: "800080", + rebeccapurple: "663399", + red: "f00", + rosybrown: "bc8f8f", + royalblue: "4169e1", + saddlebrown: "8b4513", + salmon: "fa8072", + sandybrown: "f4a460", + seagreen: "2e8b57", + seashell: "fff5ee", + sienna: "a0522d", + silver: "c0c0c0", + skyblue: "87ceeb", + slateblue: "6a5acd", + slategray: "708090", + slategrey: "708090", + snow: "fffafa", + springgreen: "00ff7f", + steelblue: "4682b4", + tan: "d2b48c", + teal: "008080", + thistle: "d8bfd8", + tomato: "ff6347", + turquoise: "40e0d0", + violet: "ee82ee", + wheat: "f5deb3", + white: "fff", + whitesmoke: "f5f5f5", + yellow: "ff0", + yellowgreen: "9acd32" + }; + var hexNames = tinycolor2.hexNames = flip(names2); + function flip(o) { + var flipped = {}; + for (var i in o) { + if (o.hasOwnProperty(i)) { + flipped[o[i]] = i; + } + } + return flipped; + } + function boundAlpha(a) { + a = parseFloat(a); + if (isNaN(a) || a < 0 || a > 1) { + a = 1; + } + return a; + } + function bound01(n, max) { + if (isOnePointZero(n)) n = "100%"; + var processPercent = isPercentage(n); + n = Math.min(max, Math.max(0, parseFloat(n))); + if (processPercent) { + n = parseInt(n * max, 10) / 100; + } + if (Math.abs(n - max) < 1e-6) { + return 1; + } + return n % max / parseFloat(max); + } + function clamp01(val) { + return Math.min(1, Math.max(0, val)); + } + function parseIntFromHex(val) { + return parseInt(val, 16); + } + function isOnePointZero(n) { + return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; + } + function isPercentage(n) { + return typeof n === "string" && n.indexOf("%") != -1; + } + function pad2(c) { + return c.length == 1 ? "0" + c : "" + c; + } + function convertToPercentage(n) { + if (n <= 1) { + n = n * 100 + "%"; + } + return n; + } + function convertDecimalToHex(d) { + return Math.round(parseFloat(d) * 255).toString(16); + } + function convertHexToDecimal(h) { + return parseIntFromHex(h) / 255; + } + var matchers = function() { + var CSS_INTEGER = "[-\\+]?\\d+%?"; + var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; + var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; + var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; + return { + CSS_UNIT: new RegExp(CSS_UNIT), + rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), + rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), + hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), + hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), + hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), + hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), + hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, + hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, + hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ + }; + }(); + function isValidCSSUnit(color2) { + return !!matchers.CSS_UNIT.exec(color2); + } + function stringInputToObject(color2) { + color2 = color2.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); + var named2 = false; + if (names2[color2]) { + color2 = names2[color2]; + named2 = true; + } else if (color2 == "transparent") { + return { + r: 0, + g: 0, + b: 0, + a: 0, + format: "name" + }; + } + var match; + if (match = matchers.rgb.exec(color2)) { + return { + r: match[1], + g: match[2], + b: match[3] + }; + } + if (match = matchers.rgba.exec(color2)) { + return { + r: match[1], + g: match[2], + b: match[3], + a: match[4] + }; + } + if (match = matchers.hsl.exec(color2)) { + return { + h: match[1], + s: match[2], + l: match[3] + }; + } + if (match = matchers.hsla.exec(color2)) { + return { + h: match[1], + s: match[2], + l: match[3], + a: match[4] + }; + } + if (match = matchers.hsv.exec(color2)) { + return { + h: match[1], + s: match[2], + v: match[3] + }; + } + if (match = matchers.hsva.exec(color2)) { + return { + h: match[1], + s: match[2], + v: match[3], + a: match[4] + }; + } + if (match = matchers.hex8.exec(color2)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + a: convertHexToDecimal(match[4]), + format: named2 ? "name" : "hex8" + }; + } + if (match = matchers.hex6.exec(color2)) { + return { + r: parseIntFromHex(match[1]), + g: parseIntFromHex(match[2]), + b: parseIntFromHex(match[3]), + format: named2 ? "name" : "hex" + }; + } + if (match = matchers.hex4.exec(color2)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + a: convertHexToDecimal(match[4] + "" + match[4]), + format: named2 ? "name" : "hex8" + }; + } + if (match = matchers.hex3.exec(color2)) { + return { + r: parseIntFromHex(match[1] + "" + match[1]), + g: parseIntFromHex(match[2] + "" + match[2]), + b: parseIntFromHex(match[3] + "" + match[3]), + format: named2 ? "name" : "hex" + }; + } + return false; + } + function validateWCAG2Parms(parms) { + var level, size; + parms = parms || { + level: "AA", + size: "small" + }; + level = (parms.level || "AA").toUpperCase(); + size = (parms.size || "small").toLowerCase(); + if (level !== "AA" && level !== "AAA") { + level = "AA"; + } + if (size !== "small" && size !== "large") { + size = "small"; + } + return { + level, + size + }; + } + return tinycolor2; + }); +})(tinycolor$8); +var tinycolorExports = tinycolor$8.exports; +var extend$5 = {}; +var isPlainObject$4 = is_plain_object; +var isArray$1 = Array.isArray; +function primitivesLoopSplice(source, target) { + var i, value2; + for (i = 0; i < source.length; i++) { + value2 = source[i]; + if (value2 !== null && typeof value2 === "object") { + return false; + } + if (value2 !== void 0) { + target[i] = value2; + } + } + return true; +} +extend$5.extendFlat = function() { + return _extend(arguments, false, false, false); +}; +extend$5.extendDeep = function() { + return _extend(arguments, true, false, false); +}; +extend$5.extendDeepAll = function() { + return _extend(arguments, true, true, false); +}; +extend$5.extendDeepNoArrays = function() { + return _extend(arguments, true, false, true); +}; +function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { + var target = inputs[0]; + var length2 = inputs.length; + var input, key, src2, copy2, copyIsArray, clone2, allPrimitives; + if (length2 === 2 && isArray$1(target) && isArray$1(inputs[1]) && target.length === 0) { + allPrimitives = primitivesLoopSplice(inputs[1], target); + if (allPrimitives) { + return target; + } else { + target.splice(0, target.length); + } + } + for (var i = 1; i < length2; i++) { + input = inputs[i]; + for (key in input) { + src2 = target[key]; + copy2 = input[key]; + if (noArrayCopies && isArray$1(copy2)) { + target[key] = copy2; + } else if (isDeep && copy2 && (isPlainObject$4(copy2) || (copyIsArray = isArray$1(copy2)))) { + if (copyIsArray) { + copyIsArray = false; + clone2 = src2 && isArray$1(src2) ? src2 : []; + } else { + clone2 = src2 && isPlainObject$4(src2) ? src2 : {}; + } + target[key] = _extend([clone2, copy2], isDeep, keepAllKeys, noArrayCopies); + } else if (typeof copy2 !== "undefined" || keepAllKeys) { + target[key] = copy2; + } + } + } + return target; +} +var font_attributes = function(opts) { + var variantValues = opts.variantValues; + var editType = opts.editType; + var colorEditType = opts.colorEditType; + if (colorEditType === void 0) colorEditType = editType; + var weight = { + editType, + valType: "integer", + min: 1, + max: 1e3, + extras: ["normal", "bold"], + dflt: "normal", + description: [ + "Sets the weight (or boldness) of the font." + ].join(" ") + }; + if (opts.noNumericWeightValues) { + weight.valType = "enumerated"; + weight.values = weight.extras; + weight.extras = void 0; + weight.min = void 0; + weight.max = void 0; + } + var attrs2 = { + family: { + valType: "string", + noBlank: true, + strict: true, + editType, + description: [ + "HTML font family - the typeface that will be applied by the web browser.", + "The web browser will only be able to apply a font if it is available on the system", + "which it operates. Provide multiple font families, separated by commas, to indicate", + "the preference in which to apply fonts if they aren't available on the system.", + "The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server,", + "where only a select number of", + "fonts are installed and supported.", + "These include *Arial*, *Balto*, *Courier New*, *Droid Sans*, *Droid Serif*,", + "*Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*,", + "*PT Sans Narrow*, *Raleway*, *Times New Roman*." + ].join(" ") + }, + size: { + valType: "number", + min: 1, + editType + }, + color: { + valType: "color", + editType: colorEditType + }, + weight, + style: { + editType, + valType: "enumerated", + values: ["normal", "italic"], + dflt: "normal", + description: [ + "Sets whether a font should be styled with a normal or italic face from its family." + ].join(" ") + }, + variant: opts.noFontVariant ? void 0 : { + editType, + valType: "enumerated", + values: variantValues || [ + "normal", + "small-caps", + "all-small-caps", + "all-petite-caps", + "petite-caps", + "unicase" + ], + dflt: "normal", + description: [ + "Sets the variant of the font." + ].join(" ") + }, + textcase: opts.noFontTextcase ? void 0 : { + editType, + valType: "enumerated", + values: ["normal", "word caps", "upper", "lower"], + dflt: "normal", + description: [ + "Sets capitalization of text.", + "It can be used to make text appear in all-uppercase or all-lowercase,", + "or with each word capitalized." + ].join(" ") + }, + lineposition: opts.noFontLineposition ? void 0 : { + editType, + valType: "flaglist", + flags: ["under", "over", "through"], + extras: ["none"], + dflt: "none", + description: [ + "Sets the kind of decoration line(s) with text,", + "such as an *under*, *over* or *through*", + "as well as combinations e.g. *under+over*, etc." + ].join(" ") + }, + shadow: opts.noFontShadow ? void 0 : { + editType, + valType: "string", + dflt: opts.autoShadowDflt ? "auto" : "none", + description: [ + "Sets the shape and color of the shadow behind text.", + "*auto* places minimal shadow and applies contrast text font color.", + "See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options." + ].join(" ") + }, + editType, + // blank strings so compress_attributes can remove + // TODO - that's uber hacky... better solution? + description: "" + (opts.description || "") + }; + if (opts.autoSize) attrs2.size.dflt = "auto"; + if (opts.autoColor) attrs2.color.dflt = "auto"; + if (opts.arrayOk) { + attrs2.family.arrayOk = true; + attrs2.weight.arrayOk = true; + attrs2.style.arrayOk = true; + if (!opts.noFontVariant) { + attrs2.variant.arrayOk = true; + } + if (!opts.noFontTextcase) { + attrs2.textcase.arrayOk = true; + } + if (!opts.noFontLineposition) { + attrs2.lineposition.arrayOk = true; + } + if (!opts.noFontShadow) { + attrs2.shadow.arrayOk = true; + } + attrs2.size.arrayOk = true; + attrs2.color.arrayOk = true; + } + return attrs2; +}; +var constants$W = { + // hover labels for multiple horizontal bars get tilted by this angle + YANGLE: 60, + // size and display constants for hover text + // pixel size of hover arrows + HOVERARROWSIZE: 6, + // pixels padding around text + HOVERTEXTPAD: 3, + // hover font + HOVERFONTSIZE: 13, + HOVERFONT: "Arial, sans-serif", + // minimum time (msec) between hover calls + HOVERMINTIME: 50, + // ID suffix (with fullLayout._uid) for hover events in the throttle cache + HOVERID: "-hover" +}; +var constants$V = constants$W; +var fontAttrs$h = font_attributes; +var font = fontAttrs$h({ + editType: "none", + description: "Sets the default hover label font used by all traces on the graph." +}); +font.family.dflt = constants$V.HOVERFONT; +font.size.dflt = constants$V.HOVERFONTSIZE; +var layout_attributes$7 = { + clickmode: { + valType: "flaglist", + flags: ["event", "select"], + dflt: "event", + editType: "plot", + extras: ["none"], + description: [ + "Determines the mode of single click interactions.", + "*event* is the default value and emits the `plotly_click`", + "event. In addition this mode emits the `plotly_selected` event", + "in drag modes *lasso* and *select*, but with no event data attached", + "(kept for compatibility reasons).", + "The *select* flag enables selecting single", + "data points via click. This mode also supports persistent selections,", + "meaning that pressing Shift while clicking, adds to / subtracts from an", + "existing selection. *select* with `hovermode`: *x* can be confusing, consider", + "explicitly setting `hovermode`: *closest* when using this feature.", + "Selection events are sent accordingly as long as *event* flag is set as well.", + "When the *event* flag is missing, `plotly_click` and `plotly_selected`", + "events are not fired." + ].join(" ") + }, + dragmode: { + valType: "enumerated", + values: [ + "zoom", + "pan", + "select", + "lasso", + "drawclosedpath", + "drawopenpath", + "drawline", + "drawrect", + "drawcircle", + "orbit", + "turntable", + false + ], + dflt: "zoom", + editType: "modebar", + description: [ + "Determines the mode of drag interactions.", + "*select* and *lasso* apply only to scatter traces with", + "markers or text. *orbit* and *turntable* apply only to", + "3D scenes." + ].join(" ") + }, + hovermode: { + valType: "enumerated", + values: ["x", "y", "closest", false, "x unified", "y unified"], + dflt: "closest", + editType: "modebar", + description: [ + "Determines the mode of hover interactions.", + "If *closest*, a single hoverlabel will appear", + "for the *closest* point within the `hoverdistance`.", + "If *x* (or *y*), multiple hoverlabels will appear for multiple points", + "at the *closest* x- (or y-) coordinate within the `hoverdistance`,", + "with the caveat that no more than one hoverlabel will appear per trace.", + "If *x unified* (or *y unified*), a single hoverlabel will appear", + "multiple points at the closest x- (or y-) coordinate within the `hoverdistance`", + "with the caveat that no more than one hoverlabel will appear per trace.", + "In this mode, spikelines are enabled by default perpendicular to the specified axis.", + "If false, hover interactions are disabled." + ].join(" ") + }, + hoversubplots: { + valType: "enumerated", + values: ["single", "overlaying", "axis"], + dflt: "overlaying", + editType: "none", + description: [ + "Determines expansion of hover effects to other subplots", + "If *single* just the axis pair of the primary point is included without overlaying subplots.", + "If *overlaying* all subplots using the main axis and occupying the same space are included.", + "If *axis*, also include stacked subplots using the same axis", + "when `hovermode` is set to *x*, *x unified*, *y* or *y unified*." + ].join(" ") + }, + hoverdistance: { + valType: "integer", + min: -1, + dflt: 20, + editType: "none", + description: [ + "Sets the default distance (in pixels) to look for data", + "to add hover labels (-1 means no cutoff, 0 means no looking for data).", + "This is only a real distance for hovering on point-like objects,", + "like scatter points. For area-like objects (bars, scatter fills, etc)", + "hovering is on inside the area and off outside, but these objects", + "will not supersede hover on point-like objects in case of conflict." + ].join(" ") + }, + spikedistance: { + valType: "integer", + min: -1, + dflt: -1, + editType: "none", + description: [ + "Sets the default distance (in pixels) to look for data to draw", + "spikelines to (-1 means no cutoff, 0 means no looking for data).", + "As with hoverdistance, distance does not apply to area-like objects.", + "In addition, some objects can be hovered on but will not generate", + "spikelines, such as scatter fills." + ].join(" ") + }, + hoverlabel: { + bgcolor: { + valType: "color", + editType: "none", + description: [ + "Sets the background color of all hover labels on graph" + ].join(" ") + }, + bordercolor: { + valType: "color", + editType: "none", + description: [ + "Sets the border color of all hover labels on graph." + ].join(" ") + }, + font, + grouptitlefont: fontAttrs$h({ + editType: "none", + description: [ + "Sets the font for group titles in hover (unified modes).", + "Defaults to `hoverlabel.font`." + ].join(" ") + }), + align: { + valType: "enumerated", + values: ["left", "right", "auto"], + dflt: "auto", + editType: "none", + description: [ + "Sets the horizontal alignment of the text content within hover label box.", + "Has an effect only if the hover label text spans more two or more lines" + ].join(" ") + }, + namelength: { + valType: "integer", + min: -1, + dflt: 15, + editType: "none", + description: [ + "Sets the default length (in number of characters) of the trace name in", + "the hover labels for all traces. -1 shows the whole name", + "regardless of length. 0-3 shows the first 0-3 characters, and", + "an integer >3 will show the whole name if it is less than that", + "many characters, but if it is longer, will truncate to", + "`namelength - 3` characters and add an ellipsis." + ].join(" ") + }, + editType: "none" + }, + selectdirection: { + valType: "enumerated", + values: ["h", "v", "d", "any"], + dflt: "any", + description: [ + "When `dragmode` is set to *select*, this limits the selection of the drag to", + "horizontal, vertical or diagonal. *h* only allows horizontal selection,", + "*v* only vertical, *d* only diagonal and *any* sets no limit." + ].join(" "), + editType: "none" + } +}; +var fontAttrs$g = font_attributes; +var hoverLabelAttrs = layout_attributes$7.hoverlabel; +var extendFlat$l = extend$5.extendFlat; +var attributes$P = { + hoverlabel: { + bgcolor: extendFlat$l({}, hoverLabelAttrs.bgcolor, { + arrayOk: true, + description: "Sets the background color of the hover labels for this trace" + }), + bordercolor: extendFlat$l({}, hoverLabelAttrs.bordercolor, { + arrayOk: true, + description: "Sets the border color of the hover labels for this trace." + }), + font: fontAttrs$g({ + arrayOk: true, + editType: "none", + description: "Sets the font used in hover labels." + }), + align: extendFlat$l({}, hoverLabelAttrs.align, { arrayOk: true }), + namelength: extendFlat$l({}, hoverLabelAttrs.namelength, { arrayOk: true }), + editType: "none" + } +}; +var fontAttrs$f = font_attributes; +var fxAttrs$1 = attributes$P; +var attributes$O = { + type: { + valType: "enumerated", + values: [], + // listed dynamically + dflt: "scatter", + editType: "calc+clearAxisTypes", + _noTemplating: true + // we handle this at a higher level + }, + visible: { + valType: "enumerated", + values: [true, false, "legendonly"], + dflt: true, + editType: "calc", + description: [ + "Determines whether or not this trace is visible.", + "If *legendonly*, the trace is not drawn,", + "but can appear as a legend item", + "(provided that the legend itself is visible)." + ].join(" ") + }, + showlegend: { + valType: "boolean", + dflt: true, + editType: "style", + description: [ + "Determines whether or not an item corresponding to this", + "trace is shown in the legend." + ].join(" ") + }, + legend: { + valType: "subplotid", + dflt: "legend", + editType: "style", + description: [ + "Sets the reference to a legend to show this trace in.", + "References to these legends are *legend*, *legend2*, *legend3*, etc.", + "Settings for these legends are set in the layout, under", + "`layout.legend`, `layout.legend2`, etc." + ].join(" ") + }, + legendgroup: { + valType: "string", + dflt: "", + editType: "style", + description: [ + "Sets the legend group for this trace.", + "Traces and shapes part of the same legend group hide/show at the same time", + "when toggling legend items." + ].join(" ") + }, + legendgrouptitle: { + text: { + valType: "string", + dflt: "", + editType: "style", + description: [ + "Sets the title of the legend group." + ].join(" ") + }, + font: fontAttrs$f({ + editType: "style", + description: [ + "Sets this legend group's title font." + ].join(" ") + }), + editType: "style" + }, + legendrank: { + valType: "number", + dflt: 1e3, + editType: "style", + description: [ + "Sets the legend rank for this trace.", + "Items and groups with smaller ranks are presented on top/left side while", + "with *reversed* `legend.traceorder` they are on bottom/right side.", + "The default legendrank is 1000,", + "so that you can use ranks less than 1000 to place certain items before all unranked items,", + "and ranks greater than 1000 to go after all unranked items.", + "When having unranked or equal rank items shapes would be displayed after traces", + "i.e. according to their order in data and layout." + ].join(" ") + }, + legendwidth: { + valType: "number", + min: 0, + editType: "style", + description: "Sets the width (in px or fraction) of the legend for this trace." + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 1, + editType: "style", + description: "Sets the opacity of the trace." + }, + name: { + valType: "string", + editType: "style", + description: [ + "Sets the trace name.", + "The trace name appears as the legend item and on hover." + ].join(" ") + }, + uid: { + valType: "string", + editType: "plot", + anim: true, + description: [ + "Assign an id to this trace,", + "Use this to provide object constancy between traces during animations", + "and transitions." + ].join(" ") + }, + ids: { + valType: "data_array", + editType: "calc", + anim: true, + description: [ + "Assigns id labels to each datum.", + "These ids for object constancy of data points during animation.", + "Should be an array of strings, not numbers or any other type." + ].join(" ") + }, + customdata: { + valType: "data_array", + editType: "calc", + description: [ + "Assigns extra data each datum.", + "This may be useful when listening to hover, click and selection events.", + "Note that, *scatter* traces also appends customdata items in the markers", + "DOM elements" + ].join(" ") + }, + meta: { + valType: "any", + arrayOk: true, + editType: "plot", + description: [ + "Assigns extra meta information associated with this trace", + "that can be used in various text attributes.", + "Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text`", + "`rangeselector`, `updatemenues` and `sliders` `label` text", + "all support `meta`.", + "To access the trace `meta` values in an attribute in the same trace, simply use", + "`%{meta[i]}` where `i` is the index or key of the `meta`", + "item in question.", + "To access trace `meta` in layout attributes, use", + "`%{data[n[.meta[i]}` where `i` is the index or key of the `meta`", + "and `n` is the trace index." + ].join(" ") + }, + // N.B. these cannot be 'data_array' as they do not have the same length as + // other data arrays and arrayOk attributes in general + // + // Maybe add another valType: + // https://github.com/plotly/plotly.js/issues/1894 + selectedpoints: { + valType: "any", + editType: "calc", + description: [ + "Array containing integer indices of selected points.", + "Has an effect only for traces that support selections.", + "Note that an empty array means an empty selection where the `unselected`", + "are turned on for all points, whereas, any other non-array values means no", + "selection all where the `selected` and `unselected` styles have no effect." + ].join(" ") + }, + hoverinfo: { + valType: "flaglist", + flags: ["x", "y", "z", "text", "name"], + extras: ["all", "none", "skip"], + arrayOk: true, + dflt: "all", + editType: "none", + description: [ + "Determines which trace information appear on hover.", + "If `none` or `skip` are set, no information is displayed upon hovering.", + "But, if `none` is set, click and hover events are still fired." + ].join(" ") + }, + hoverlabel: fxAttrs$1.hoverlabel, + stream: { + token: { + valType: "string", + noBlank: true, + strict: true, + editType: "calc", + description: [ + "The stream id number links a data trace on a plot with a stream.", + "See https://chart-studio.plotly.com/settings for more details." + ].join(" ") + }, + maxpoints: { + valType: "number", + min: 0, + max: 1e4, + dflt: 500, + editType: "calc", + description: [ + "Sets the maximum number of points to keep on the plots from an", + "incoming stream.", + "If `maxpoints` is set to *50*, only the newest 50 points will", + "be displayed on the plot." + ].join(" ") + }, + editType: "calc" + }, + transforms: { + _isLinkedToArray: "transform", + editType: "calc", + description: [ + "WARNING: All transforms are deprecated and may be removed from the API in next major version.", + "An array of operations that manipulate the trace data,", + "for example filtering or sorting the data arrays." + ].join(" ") + }, + uirevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of some user-driven changes to the trace:", + "`constraintrange` in `parcoords` traces, as well as some", + "`editable: true` modifications such as `name` and `colorbar.title`.", + "Defaults to `layout.uirevision`.", + "Note that other user-driven trace attribute changes are controlled", + "by `layout` attributes:", + "`trace.visible` is controlled by `layout.legend.uirevision`,", + "`selectedpoints` is controlled by `layout.selectionrevision`,", + "and `colorbar.(x|y)` (accessible with `config: {editable: true}`)", + "is controlled by `layout.editrevision`.", + "Trace changes are tracked by `uid`, which only falls back on trace", + "index if no `uid` is provided. So if your app can add/remove traces", + "before the end of the `data` array, such that the same trace has a", + "different index, you can still preserve user-driven changes if you", + "give each trace a `uid` that stays with it as it moves." + ].join(" ") + } +}; +var tinycolor$7 = tinycolorExports; +var scales$2 = { + Greys: [ + [0, "rgb(0,0,0)"], + [1, "rgb(255,255,255)"] + ], + YlGnBu: [ + [0, "rgb(8,29,88)"], + [0.125, "rgb(37,52,148)"], + [0.25, "rgb(34,94,168)"], + [0.375, "rgb(29,145,192)"], + [0.5, "rgb(65,182,196)"], + [0.625, "rgb(127,205,187)"], + [0.75, "rgb(199,233,180)"], + [0.875, "rgb(237,248,217)"], + [1, "rgb(255,255,217)"] + ], + Greens: [ + [0, "rgb(0,68,27)"], + [0.125, "rgb(0,109,44)"], + [0.25, "rgb(35,139,69)"], + [0.375, "rgb(65,171,93)"], + [0.5, "rgb(116,196,118)"], + [0.625, "rgb(161,217,155)"], + [0.75, "rgb(199,233,192)"], + [0.875, "rgb(229,245,224)"], + [1, "rgb(247,252,245)"] + ], + YlOrRd: [ + [0, "rgb(128,0,38)"], + [0.125, "rgb(189,0,38)"], + [0.25, "rgb(227,26,28)"], + [0.375, "rgb(252,78,42)"], + [0.5, "rgb(253,141,60)"], + [0.625, "rgb(254,178,76)"], + [0.75, "rgb(254,217,118)"], + [0.875, "rgb(255,237,160)"], + [1, "rgb(255,255,204)"] + ], + Bluered: [ + [0, "rgb(0,0,255)"], + [1, "rgb(255,0,0)"] + ], + // modified RdBu based on + // http://www.kennethmoreland.com/color-maps/ + RdBu: [ + [0, "rgb(5,10,172)"], + [0.35, "rgb(106,137,247)"], + [0.5, "rgb(190,190,190)"], + [0.6, "rgb(220,170,132)"], + [0.7, "rgb(230,145,90)"], + [1, "rgb(178,10,28)"] + ], + // Scale for non-negative numeric values + Reds: [ + [0, "rgb(220,220,220)"], + [0.2, "rgb(245,195,157)"], + [0.4, "rgb(245,160,105)"], + [1, "rgb(178,10,28)"] + ], + // Scale for non-positive numeric values + Blues: [ + [0, "rgb(5,10,172)"], + [0.35, "rgb(40,60,190)"], + [0.5, "rgb(70,100,245)"], + [0.6, "rgb(90,120,245)"], + [0.7, "rgb(106,137,247)"], + [1, "rgb(220,220,220)"] + ], + Picnic: [ + [0, "rgb(0,0,255)"], + [0.1, "rgb(51,153,255)"], + [0.2, "rgb(102,204,255)"], + [0.3, "rgb(153,204,255)"], + [0.4, "rgb(204,204,255)"], + [0.5, "rgb(255,255,255)"], + [0.6, "rgb(255,204,255)"], + [0.7, "rgb(255,153,255)"], + [0.8, "rgb(255,102,204)"], + [0.9, "rgb(255,102,102)"], + [1, "rgb(255,0,0)"] + ], + Rainbow: [ + [0, "rgb(150,0,90)"], + [0.125, "rgb(0,0,200)"], + [0.25, "rgb(0,25,255)"], + [0.375, "rgb(0,152,255)"], + [0.5, "rgb(44,255,150)"], + [0.625, "rgb(151,255,0)"], + [0.75, "rgb(255,234,0)"], + [0.875, "rgb(255,111,0)"], + [1, "rgb(255,0,0)"] + ], + Portland: [ + [0, "rgb(12,51,131)"], + [0.25, "rgb(10,136,186)"], + [0.5, "rgb(242,211,56)"], + [0.75, "rgb(242,143,56)"], + [1, "rgb(217,30,30)"] + ], + Jet: [ + [0, "rgb(0,0,131)"], + [0.125, "rgb(0,60,170)"], + [0.375, "rgb(5,255,255)"], + [0.625, "rgb(255,255,0)"], + [0.875, "rgb(250,0,0)"], + [1, "rgb(128,0,0)"] + ], + Hot: [ + [0, "rgb(0,0,0)"], + [0.3, "rgb(230,0,0)"], + [0.6, "rgb(255,210,0)"], + [1, "rgb(255,255,255)"] + ], + Blackbody: [ + [0, "rgb(0,0,0)"], + [0.2, "rgb(230,0,0)"], + [0.4, "rgb(230,210,0)"], + [0.7, "rgb(255,255,255)"], + [1, "rgb(160,200,255)"] + ], + Earth: [ + [0, "rgb(0,0,130)"], + [0.1, "rgb(0,180,180)"], + [0.2, "rgb(40,210,40)"], + [0.4, "rgb(230,230,50)"], + [0.6, "rgb(120,70,20)"], + [1, "rgb(255,255,255)"] + ], + Electric: [ + [0, "rgb(0,0,0)"], + [0.15, "rgb(30,0,100)"], + [0.4, "rgb(120,0,100)"], + [0.6, "rgb(160,90,0)"], + [0.8, "rgb(230,200,0)"], + [1, "rgb(255,250,220)"] + ], + Viridis: [ + [0, "#440154"], + [0.06274509803921569, "#48186a"], + [0.12549019607843137, "#472d7b"], + [0.18823529411764706, "#424086"], + [0.25098039215686274, "#3b528b"], + [0.3137254901960784, "#33638d"], + [0.3764705882352941, "#2c728e"], + [0.4392156862745098, "#26828e"], + [0.5019607843137255, "#21918c"], + [0.5647058823529412, "#1fa088"], + [0.6274509803921569, "#28ae80"], + [0.6901960784313725, "#3fbc73"], + [0.7529411764705882, "#5ec962"], + [0.8156862745098039, "#84d44b"], + [0.8784313725490196, "#addc30"], + [0.9411764705882353, "#d8e219"], + [1, "#fde725"] + ], + Cividis: [ + [0, "rgb(0,32,76)"], + [0.058824, "rgb(0,42,102)"], + [0.117647, "rgb(0,52,110)"], + [0.176471, "rgb(39,63,108)"], + [0.235294, "rgb(60,74,107)"], + [0.294118, "rgb(76,85,107)"], + [0.352941, "rgb(91,95,109)"], + [0.411765, "rgb(104,106,112)"], + [0.470588, "rgb(117,117,117)"], + [0.529412, "rgb(131,129,120)"], + [0.588235, "rgb(146,140,120)"], + [0.647059, "rgb(161,152,118)"], + [0.705882, "rgb(176,165,114)"], + [0.764706, "rgb(192,177,109)"], + [0.823529, "rgb(209,191,102)"], + [0.882353, "rgb(225,204,92)"], + [0.941176, "rgb(243,219,79)"], + [1, "rgb(255,233,69)"] + ] +}; +var defaultScale = scales$2.RdBu; +function getScale(scl, dflt) { + if (!dflt) dflt = defaultScale; + if (!scl) return dflt; + function parseScale() { + try { + scl = scales$2[scl] || JSON.parse(scl); + } catch (e) { + scl = dflt; + } + } + if (typeof scl === "string") { + parseScale(); + if (typeof scl === "string") parseScale(); + } + if (!isValidScaleArray(scl)) return dflt; + return scl; +} +function isValidScaleArray(scl) { + var highestVal = 0; + if (!Array.isArray(scl) || scl.length < 2) return false; + if (!scl[0] || !scl[scl.length - 1]) return false; + if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false; + for (var i = 0; i < scl.length; i++) { + var si = scl[i]; + if (si.length !== 2 || +si[0] < highestVal || !tinycolor$7(si[1]).isValid()) { + return false; + } + highestVal = +si[0]; + } + return true; +} +function isValidScale$2(scl) { + if (scales$2[scl] !== void 0) return true; + else return isValidScaleArray(scl); +} +var scales_1 = { + scales: scales$2, + defaultScale, + get: getScale, + isValid: isValidScale$2 +}; +var color$2 = { exports: {} }; +var attributes$N = {}; +attributes$N.defaults = [ + "#1f77b4", + // muted blue + "#ff7f0e", + // safety orange + "#2ca02c", + // cooked asparagus green + "#d62728", + // brick red + "#9467bd", + // muted purple + "#8c564b", + // chestnut brown + "#e377c2", + // raspberry yogurt pink + "#7f7f7f", + // middle gray + "#bcbd22", + // curry yellow-green + "#17becf" + // blue-teal +]; +attributes$N.defaultLine = "#444"; +attributes$N.lightLine = "#eee"; +attributes$N.background = "#fff"; +attributes$N.borderLine = "#BEC8D9"; +attributes$N.lightFraction = 100 * (14 - 4) / (15 - 4); +var tinycolor$6 = tinycolorExports; +var isNumeric$z = fastIsnumeric; +var isTypedArray = array$2.isTypedArray; +var color$1 = color$2.exports = {}; +var colorAttrs$7 = attributes$N; +color$1.defaults = colorAttrs$7.defaults; +var defaultLine = color$1.defaultLine = colorAttrs$7.defaultLine; +color$1.lightLine = colorAttrs$7.lightLine; +var background = color$1.background = colorAttrs$7.background; +color$1.tinyRGB = function(tc) { + var c = tc.toRgb(); + return "rgb(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ")"; +}; +color$1.rgb = function(cstr) { + return color$1.tinyRGB(tinycolor$6(cstr)); +}; +color$1.opacity = function(cstr) { + return cstr ? tinycolor$6(cstr).getAlpha() : 0; +}; +color$1.addOpacity = function(cstr, op) { + var c = tinycolor$6(cstr).toRgb(); + return "rgba(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ", " + op + ")"; +}; +color$1.combine = function(front, back) { + var fc = tinycolor$6(front).toRgb(); + if (fc.a === 1) return tinycolor$6(front).toRgbString(); + var bc = tinycolor$6(back || background).toRgb(); + var bcflat = bc.a === 1 ? bc : { + r: 255 * (1 - bc.a) + bc.r * bc.a, + g: 255 * (1 - bc.a) + bc.g * bc.a, + b: 255 * (1 - bc.a) + bc.b * bc.a + }; + var fcflat = { + r: bcflat.r * (1 - fc.a) + fc.r * fc.a, + g: bcflat.g * (1 - fc.a) + fc.g * fc.a, + b: bcflat.b * (1 - fc.a) + fc.b * fc.a + }; + return tinycolor$6(fcflat).toRgbString(); +}; +color$1.interpolate = function(first, second2, factor) { + var fc = tinycolor$6(first).toRgb(); + var sc = tinycolor$6(second2).toRgb(); + var ic = { + r: factor * fc.r + (1 - factor) * sc.r, + g: factor * fc.g + (1 - factor) * sc.g, + b: factor * fc.b + (1 - factor) * sc.b + }; + return tinycolor$6(ic).toRgbString(); +}; +color$1.contrast = function(cstr, lightAmount, darkAmount) { + var tc = tinycolor$6(cstr); + if (tc.getAlpha() !== 1) tc = tinycolor$6(color$1.combine(cstr, background)); + var newColor = tc.isDark() ? lightAmount ? tc.lighten(lightAmount) : background : darkAmount ? tc.darken(darkAmount) : defaultLine; + return newColor.toString(); +}; +color$1.stroke = function(s, c) { + var tc = tinycolor$6(c); + s.style({ stroke: color$1.tinyRGB(tc), "stroke-opacity": tc.getAlpha() }); +}; +color$1.fill = function(s, c) { + var tc = tinycolor$6(c); + s.style({ + fill: color$1.tinyRGB(tc), + "fill-opacity": tc.getAlpha() + }); +}; +color$1.clean = function(container) { + if (!container || typeof container !== "object") return; + var keys = Object.keys(container); + var i, j, key, val; + for (i = 0; i < keys.length; i++) { + key = keys[i]; + val = container[key]; + if (key.substr(key.length - 5) === "color") { + if (Array.isArray(val)) { + for (j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); + } else container[key] = cleanOne(val); + } else if (key.substr(key.length - 10) === "colorscale" && Array.isArray(val)) { + for (j = 0; j < val.length; j++) { + if (Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); + } + } else if (Array.isArray(val)) { + var el0 = val[0]; + if (!Array.isArray(el0) && el0 && typeof el0 === "object") { + for (j = 0; j < val.length; j++) color$1.clean(val[j]); + } + } else if (val && typeof val === "object" && !isTypedArray(val)) color$1.clean(val); + } +}; +function cleanOne(val) { + if (isNumeric$z(val) || typeof val !== "string") return val; + var valTrim = val.trim(); + if (valTrim.substr(0, 3) !== "rgb") return val; + var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); + if (!match) return val; + var parts = match[1].trim().split(/\s*[\s,]\s*/); + var rgba3 = valTrim.charAt(3) === "a" && parts.length === 4; + if (!rgba3 && parts.length !== 3) return val; + for (var i = 0; i < parts.length; i++) { + if (!parts[i].length) return val; + parts[i] = Number(parts[i]); + if (!(parts[i] >= 0)) { + return val; + } + if (i === 3) { + if (parts[i] > 1) parts[i] = 1; + } else if (parts[i] >= 1) { + return val; + } + } + var rgbStr = Math.round(parts[0] * 255) + ", " + Math.round(parts[1] * 255) + ", " + Math.round(parts[2] * 255); + if (rgba3) return "rgba(" + rgbStr + ", " + parts[3] + ")"; + return "rgb(" + rgbStr + ")"; +} +var colorExports = color$2.exports; +var interactions = { + /** + * Timing information for interactive elements + */ + SHOW_PLACEHOLDER: 100, + HIDE_PLACEHOLDER: 1e3, + // opacity dimming fraction for points that are not in selection + DESELECTDIM: 0.2 +}; +var regex = {}; +regex.counter = function(head, tail, openEnded, matchBeginning) { + var fullTail = (tail || "") + (openEnded ? "" : "$"); + var startWithPrefix = matchBeginning === false ? "" : "^"; + if (head === "xy") { + return new RegExp(startWithPrefix + "x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?" + fullTail); + } + return new RegExp(startWithPrefix + head + "([2-9]|[1-9][0-9]+)?" + fullTail); +}; +(function(exports2) { + var isNumeric2 = fastIsnumeric; + var tinycolor2 = tinycolorExports; + var extendFlat2 = extend$5.extendFlat; + var baseTraceAttrs = attributes$O; + var colorscales = scales_1; + var Color2 = colorExports; + var DESELECTDIM2 = interactions.DESELECTDIM; + var nestedProperty3 = nested_property; + var counterRegex2 = regex.counter; + var modHalf2 = mod_1.modHalf; + var isArrayOrTypedArray2 = array$2.isArrayOrTypedArray; + var isTypedArraySpec2 = array$2.isTypedArraySpec; + var decodeTypedArraySpec2 = array$2.decodeTypedArraySpec; + exports2.valObjectMeta = { + data_array: { + // You can use *dflt=[] to force said array to exist though. + description: [ + "An {array} of data.", + "The value must represent an {array} or it will be ignored,", + "but this array can be provided in several forms:", + "(1) a regular {array} object", + "(2) a typed array (e.g. Float32Array)", + "(3) an object with keys dtype, bdata, and optionally shape.", + "In this 3rd form, dtype is one of", + "*f8*, *f4*.", + "*i4*, *u4*,", + "*i2*, *u2*,", + "*i1*, *u1* or *u1c* for Uint8ClampedArray.", + "In addition to shorthand `dtype` above one could also use the following forms:", + "*float64*, *float32*,", + "*int32*, *uint32*,", + "*int16*, *uint16*,", + "*int8*, *uint8* or *uint8c* for Uint8ClampedArray.", + "`bdata` is either a base64-encoded string or the ArrayBuffer of", + "an integer or float typed array.", + "For either multi-dimensional arrays you must also", + "provide its dimensions separated by comma via `shape`.", + "For example using `dtype`: *f4* and `shape`: *5,100* you can", + "declare a 2-D array that has 5 rows and 100 columns", + "containing float32 values i.e. 4 bits per value.", + "`shape` is optional for one dimensional arrays." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt"], + coerceFunction: function(v, propOut, dflt) { + propOut.set( + isArrayOrTypedArray2(v) ? v : isTypedArraySpec2(v) ? decodeTypedArraySpec2(v) : dflt + ); + } + }, + enumerated: { + description: [ + "Enumerated value type. The available values are listed", + "in `values`." + ].join(" "), + requiredOpts: ["values"], + otherOpts: ["dflt", "coerceNumber", "arrayOk"], + coerceFunction: function(v, propOut, dflt, opts) { + if (opts.coerceNumber) v = +v; + if (opts.values.indexOf(v) === -1) propOut.set(dflt); + else propOut.set(v); + }, + validateFunction: function(v, opts) { + if (opts.coerceNumber) v = +v; + var values = opts.values; + for (var i = 0; i < values.length; i++) { + var k = String(values[i]); + if (k.charAt(0) === "/" && k.charAt(k.length - 1) === "/") { + var regex2 = new RegExp(k.substr(1, k.length - 2)); + if (regex2.test(v)) return true; + } else if (v === values[i]) return true; + } + return false; + } + }, + boolean: { + description: "A boolean (true/false) value.", + requiredOpts: [], + otherOpts: ["dflt"], + coerceFunction: function(v, propOut, dflt) { + if (v === true || v === false) propOut.set(v); + else propOut.set(dflt); + } + }, + number: { + description: [ + "A number or a numeric value", + "(e.g. a number inside a string).", + "When applicable, values greater (less) than `max` (`min`)", + "are coerced to the `dflt`." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt", "min", "max", "arrayOk"], + coerceFunction: function(v, propOut, dflt, opts) { + if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); + if (!isNumeric2(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) { + propOut.set(dflt); + } else propOut.set(+v); + } + }, + integer: { + description: [ + "An integer or an integer inside a string.", + "When applicable, values greater (less) than `max` (`min`)", + "are coerced to the `dflt`." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt", "min", "max", "arrayOk", "extras"], + coerceFunction: function(v, propOut, dflt, opts) { + if ((opts.extras || []).indexOf(v) !== -1) { + propOut.set(v); + return; + } + if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); + if (v % 1 || !isNumeric2(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) { + propOut.set(dflt); + } else propOut.set(+v); + } + }, + string: { + description: [ + "A string value.", + "Numbers are converted to strings except for attributes with", + "`strict` set to true." + ].join(" "), + requiredOpts: [], + // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter) + otherOpts: ["dflt", "noBlank", "strict", "arrayOk", "values"], + coerceFunction: function(v, propOut, dflt, opts) { + if (typeof v !== "string") { + var okToCoerce = typeof v === "number"; + if (opts.strict === true || !okToCoerce) propOut.set(dflt); + else propOut.set(String(v)); + } else if (opts.noBlank && !v) propOut.set(dflt); + else propOut.set(v); + } + }, + color: { + description: [ + "A string describing color.", + "Supported formats:", + "- hex (e.g. '#d3d3d3')", + "- rgb (e.g. 'rgb(255, 0, 0)')", + "- rgba (e.g. 'rgb(255, 0, 0, 0.5)')", + "- hsl (e.g. 'hsl(0, 100%, 50%)')", + "- hsv (e.g. 'hsv(0, 100%, 100%)')", + "- named colors (full list: http://www.w3.org/TR/css3-color/#svg-color)" + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt", "arrayOk"], + coerceFunction: function(v, propOut, dflt) { + if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); + if (tinycolor2(v).isValid()) propOut.set(v); + else propOut.set(dflt); + } + }, + colorlist: { + description: [ + "A list of colors.", + "Must be an {array} containing valid colors." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt"], + coerceFunction: function(v, propOut, dflt) { + function isColor(color2) { + return tinycolor2(color2).isValid(); + } + if (!Array.isArray(v) || !v.length) propOut.set(dflt); + else if (v.every(isColor)) propOut.set(v); + else propOut.set(dflt); + } + }, + colorscale: { + description: [ + "A Plotly colorscale either picked by a name:", + "(any of", + Object.keys(colorscales.scales).join(", "), + ")", + "customized as an {array} of 2-element {arrays} where", + "the first element is the normalized color level value", + "(starting at *0* and ending at *1*),", + "and the second item is a valid color string." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt"], + coerceFunction: function(v, propOut, dflt) { + propOut.set(colorscales.get(v, dflt)); + } + }, + angle: { + description: [ + "A number (in degree) between -180 and 180." + ].join(" "), + requiredOpts: [], + otherOpts: ["dflt", "arrayOk"], + coerceFunction: function(v, propOut, dflt) { + if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); + if (v === "auto") propOut.set("auto"); + else if (!isNumeric2(v)) propOut.set(dflt); + else propOut.set(modHalf2(+v, 360)); + } + }, + subplotid: { + description: [ + "An id string of a subplot type (given by dflt), optionally", + "followed by an integer >1. e.g. if dflt='geo', we can have", + "'geo', 'geo2', 'geo3', ..." + ].join(" "), + requiredOpts: ["dflt"], + otherOpts: ["regex"], + coerceFunction: function(v, propOut, dflt, opts) { + var regex2 = opts.regex || counterRegex2(dflt); + if (typeof v === "string" && regex2.test(v)) { + propOut.set(v); + return; + } + propOut.set(dflt); + }, + validateFunction: function(v, opts) { + var dflt = opts.dflt; + if (v === dflt) return true; + if (typeof v !== "string") return false; + if (counterRegex2(dflt).test(v)) return true; + return false; + } + }, + flaglist: { + description: [ + "A string representing a combination of flags", + "(order does not matter here).", + "Combine any of the available `flags` with *+*.", + "(e.g. ('lines+markers')).", + "Values in `extras` cannot be combined." + ].join(" "), + requiredOpts: ["flags"], + otherOpts: ["dflt", "extras", "arrayOk"], + coerceFunction: function(v, propOut, dflt, opts) { + if ((opts.extras || []).indexOf(v) !== -1) { + propOut.set(v); + return; + } + if (typeof v !== "string") { + propOut.set(dflt); + return; + } + var vParts = v.split("+"); + var i = 0; + while (i < vParts.length) { + var vi = vParts[i]; + if (opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) { + vParts.splice(i, 1); + } else i++; + } + if (!vParts.length) propOut.set(dflt); + else propOut.set(vParts.join("+")); + } + }, + any: { + description: "Any type.", + requiredOpts: [], + otherOpts: ["dflt", "values", "arrayOk"], + coerceFunction: function(v, propOut, dflt) { + if (v === void 0) { + propOut.set(dflt); + } else { + propOut.set( + isTypedArraySpec2(v) ? decodeTypedArraySpec2(v) : v + ); + } + } + }, + info_array: { + description: [ + "An {array} of plot information." + ].join(" "), + requiredOpts: ["items"], + // set `dimensions=2` for a 2D array or '1-2' for either + // `items` may be a single object instead of an array, in which case + // `freeLength` must be true. + // if `dimensions='1-2'` and items is a 1D array, then the value can + // either be a matching 1D array or an array of such matching 1D arrays + otherOpts: ["dflt", "freeLength", "dimensions"], + coerceFunction: function(v, propOut, dflt, opts) { + function coercePart(v2, opts2, dflt2) { + var out; + var propPart = { set: function(v3) { + out = v3; + } }; + if (dflt2 === void 0) dflt2 = opts2.dflt; + exports2.valObjectMeta[opts2.valType].coerceFunction(v2, propPart, dflt2, opts2); + return out; + } + if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); + if (!isArrayOrTypedArray2(v)) { + propOut.set(dflt); + return; + } + var twoD = opts.dimensions === 2 || opts.dimensions === "1-2" && Array.isArray(v) && isArrayOrTypedArray2(v[0]); + var items = opts.items; + var vOut = []; + var arrayItems = Array.isArray(items); + var arrayItems2D = arrayItems && twoD && isArrayOrTypedArray2(items[0]); + var innerItemsOnly = twoD && arrayItems && !arrayItems2D; + var len = arrayItems && !innerItemsOnly ? items.length : v.length; + var i, j, row, item, len2, vNew; + dflt = Array.isArray(dflt) ? dflt : []; + if (twoD) { + for (i = 0; i < len; i++) { + vOut[i] = []; + row = isArrayOrTypedArray2(v[i]) ? v[i] : []; + if (innerItemsOnly) len2 = items.length; + else if (arrayItems) len2 = items[i].length; + else len2 = row.length; + for (j = 0; j < len2; j++) { + if (innerItemsOnly) item = items[j]; + else if (arrayItems) item = items[i][j]; + else item = items; + vNew = coercePart(row[j], item, (dflt[i] || [])[j]); + if (vNew !== void 0) vOut[i][j] = vNew; + } + } + } else { + for (i = 0; i < len; i++) { + vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]); + if (vNew !== void 0) vOut[i] = vNew; + } + } + propOut.set(vOut); + }, + validateFunction: function(v, opts) { + if (!isArrayOrTypedArray2(v)) return false; + var items = opts.items; + var arrayItems = Array.isArray(items); + var twoD = opts.dimensions === 2; + if (!opts.freeLength && v.length !== items.length) return false; + for (var i = 0; i < v.length; i++) { + if (twoD) { + if (!isArrayOrTypedArray2(v[i]) || !opts.freeLength && v[i].length !== items[i].length) { + return false; + } + for (var j = 0; j < v[i].length; j++) { + if (!validate3(v[i][j], arrayItems ? items[i][j] : items)) { + return false; + } + } + } else if (!validate3(v[i], arrayItems ? items[i] : items)) return false; + } + return true; + } + } + }; + exports2.coerce = function(containerIn, containerOut, attributes2, attribute, dflt) { + var opts = nestedProperty3(attributes2, attribute).get(); + var propIn = nestedProperty3(containerIn, attribute); + var propOut = nestedProperty3(containerOut, attribute); + var v = propIn.get(); + var template = containerOut._template; + if (v === void 0 && template) { + v = nestedProperty3(template, attribute).get(); + template = 0; + } + if (dflt === void 0) dflt = opts.dflt; + if (opts.arrayOk) { + if (isArrayOrTypedArray2(v)) { + propOut.set(v); + return v; + } else { + if (isTypedArraySpec2(v)) { + v = decodeTypedArraySpec2(v); + propOut.set(v); + return v; + } + } + } + var coerceFunction = exports2.valObjectMeta[opts.valType].coerceFunction; + coerceFunction(v, propOut, dflt, opts); + var out = propOut.get(); + if (template && out === dflt && !validate3(v, opts)) { + v = nestedProperty3(template, attribute).get(); + coerceFunction(v, propOut, dflt, opts); + out = propOut.get(); + } + return out; + }; + exports2.coerce2 = function(containerIn, containerOut, attributes2, attribute, dflt) { + var propIn = nestedProperty3(containerIn, attribute); + var propOut = exports2.coerce(containerIn, containerOut, attributes2, attribute, dflt); + var valIn = propIn.get(); + return valIn !== void 0 && valIn !== null ? propOut : false; + }; + exports2.coerceFont = function(coerce2, attr, dfltObj, opts) { + if (!opts) opts = {}; + dfltObj = extendFlat2({}, dfltObj); + dfltObj = extendFlat2(dfltObj, opts.overrideDflt || {}); + var out = { + family: coerce2(attr + ".family", dfltObj.family), + size: coerce2(attr + ".size", dfltObj.size), + color: coerce2(attr + ".color", dfltObj.color), + weight: coerce2(attr + ".weight", dfltObj.weight), + style: coerce2(attr + ".style", dfltObj.style) + }; + if (!opts.noFontVariant) out.variant = coerce2(attr + ".variant", dfltObj.variant); + if (!opts.noFontLineposition) out.lineposition = coerce2(attr + ".lineposition", dfltObj.lineposition); + if (!opts.noFontTextcase) out.textcase = coerce2(attr + ".textcase", dfltObj.textcase); + if (!opts.noFontShadow) { + var dfltShadow = dfltObj.shadow; + if (dfltShadow === "none" && opts.autoShadowDflt) { + dfltShadow = "auto"; + } + out.shadow = coerce2(attr + ".shadow", dfltShadow); + } + return out; + }; + exports2.coercePattern = function(coerce2, attr, markerColor, hasMarkerColorscale) { + var shape = coerce2(attr + ".shape"); + if (shape) { + coerce2(attr + ".solidity"); + coerce2(attr + ".size"); + var fillmode = coerce2(attr + ".fillmode"); + var isOverlay = fillmode === "overlay"; + if (!hasMarkerColorscale) { + var bgcolor = coerce2( + attr + ".bgcolor", + isOverlay ? markerColor : void 0 + ); + coerce2( + attr + ".fgcolor", + isOverlay ? Color2.contrast(bgcolor) : markerColor + ); + } + coerce2( + attr + ".fgopacity", + isOverlay ? 0.5 : 1 + ); + } + }; + exports2.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { + var moduleAttrs = traceOut._module.attributes; + var attrs2 = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs; + var valObj = attrs2.hoverinfo; + var dflt; + if (layoutOut._dataLength === 1) { + var flags = valObj.dflt === "all" ? valObj.flags.slice() : valObj.dflt.split("+"); + flags.splice(flags.indexOf("name"), 1); + dflt = flags.join("+"); + } + return exports2.coerce(traceIn, traceOut, attrs2, "hoverinfo", dflt); + }; + exports2.coerceSelectionMarkerOpacity = function(traceOut, coerce2) { + if (!traceOut.marker) return; + var mo = traceOut.marker.opacity; + if (mo === void 0) return; + var smoDflt; + var usmoDflt; + if (!isArrayOrTypedArray2(mo) && !traceOut.selected && !traceOut.unselected) { + smoDflt = mo; + usmoDflt = DESELECTDIM2 * mo; + } + coerce2("selected.marker.opacity", smoDflt); + coerce2("unselected.marker.opacity", usmoDflt); + }; + function validate3(value2, opts) { + var valObjectDef = exports2.valObjectMeta[opts.valType]; + if (opts.arrayOk && isArrayOrTypedArray2(value2)) return true; + if (valObjectDef.validateFunction) { + return valObjectDef.validateFunction(value2, opts); + } + var failed = {}; + var out = failed; + var propMock = { set: function(v) { + out = v; + } }; + valObjectDef.coerceFunction(value2, propMock, failed, opts); + return out !== failed; + } + exports2.validate = validate3; +})(coerce$1); +var dates = {}; +var loggers$2 = { exports: {} }; +var configAttributes = { + staticPlot: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether the graphs are interactive or not.", + "If *false*, no interactivity, for export or image generation." + ].join(" ") + }, + typesetMath: { + valType: "boolean", + dflt: true, + description: [ + "Determines whether math should be typeset or not,", + "when MathJax (either v2 or v3) is present on the page." + ].join(" ") + }, + plotlyServerURL: { + valType: "string", + dflt: "", + description: [ + "When set it determines base URL for", + "the 'Edit in Chart Studio' `showEditInChartStudio`/`showSendToCloud` mode bar button", + "and the showLink/sendData on-graph link.", + "To enable sending your data to Chart Studio Cloud, you need to", + "set both `plotlyServerURL` to 'https://chart-studio.plotly.com' and", + "also set `showSendToCloud` to true." + ].join(" ") + }, + editable: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether the graph is editable or not.", + "Sets all pieces of `edits`", + "unless a separate `edits` config item overrides individual parts." + ].join(" ") + }, + edits: { + annotationPosition: { + valType: "boolean", + dflt: false, + description: [ + "Determines if the main anchor of the annotation is editable.", + "The main anchor corresponds to the", + "text (if no arrow) or the arrow (which drags the whole thing leaving", + "the arrow length & direction unchanged)." + ].join(" ") + }, + annotationTail: { + valType: "boolean", + dflt: false, + description: [ + "Has only an effect for annotations with arrows.", + "Enables changing the length and direction of the arrow." + ].join(" ") + }, + annotationText: { + valType: "boolean", + dflt: false, + description: "Enables editing annotation text." + }, + axisTitleText: { + valType: "boolean", + dflt: false, + description: "Enables editing axis title text." + }, + colorbarPosition: { + valType: "boolean", + dflt: false, + description: "Enables moving colorbars." + }, + colorbarTitleText: { + valType: "boolean", + dflt: false, + description: "Enables editing colorbar title text." + }, + legendPosition: { + valType: "boolean", + dflt: false, + description: "Enables moving the legend." + }, + legendText: { + valType: "boolean", + dflt: false, + description: "Enables editing the trace name fields from the legend" + }, + shapePosition: { + valType: "boolean", + dflt: false, + description: "Enables moving shapes." + }, + titleText: { + valType: "boolean", + dflt: false, + description: "Enables editing the global layout title." + } + }, + editSelection: { + valType: "boolean", + dflt: true, + description: "Enables moving selections." + }, + autosizable: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether the graphs are plotted with respect to", + "layout.autosize:true and infer its container size." + ].join(" ") + }, + responsive: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether to change the layout size when window is resized.", + "In v3, this option will be removed and will always be true." + ].join(" ") + }, + fillFrame: { + valType: "boolean", + dflt: false, + description: [ + "When `layout.autosize` is turned on, determines whether the graph", + "fills the container (the default) or the screen (if set to *true*)." + ].join(" ") + }, + frameMargins: { + valType: "number", + dflt: 0, + min: 0, + max: 0.5, + description: [ + "When `layout.autosize` is turned on, set the frame margins", + "in fraction of the graph size." + ].join(" ") + }, + scrollZoom: { + valType: "flaglist", + flags: ["cartesian", "gl3d", "geo", "mapbox", "map"], + extras: [true, false], + dflt: "gl3d+geo+map", + description: [ + "Determines whether mouse wheel or two-finger scroll zooms is enable.", + "Turned on by default for gl3d, geo, mapbox and map subplots", + "(as these subplot types do not have zoombox via pan),", + "but turned off by default for cartesian subplots.", + "Set `scrollZoom` to *false* to disable scrolling for all subplots." + ].join(" ") + }, + doubleClick: { + valType: "enumerated", + values: [false, "reset", "autosize", "reset+autosize"], + dflt: "reset+autosize", + description: [ + "Sets the double click interaction mode.", + "Has an effect only in cartesian plots.", + "If *false*, double click is disable.", + "If *reset*, double click resets the axis ranges to their initial values.", + "If *autosize*, double click set the axis ranges to their autorange values.", + "If *reset+autosize*, the odd double clicks resets the axis ranges", + "to their initial values and even double clicks set the axis ranges", + "to their autorange values." + ].join(" ") + }, + doubleClickDelay: { + valType: "number", + dflt: 300, + min: 0, + description: [ + "Sets the delay for registering a double-click in ms.", + "This is the time interval (in ms) between first mousedown and", + "2nd mouseup to constitute a double-click.", + "This setting propagates to all on-subplot double clicks", + "(except for geo, mapbox and map) and on-legend double clicks." + ].join(" ") + }, + showAxisDragHandles: { + valType: "boolean", + dflt: true, + description: [ + "Set to *false* to omit cartesian axis pan/zoom drag handles." + ].join(" ") + }, + showAxisRangeEntryBoxes: { + valType: "boolean", + dflt: true, + description: [ + "Set to *false* to omit direct range entry at the pan/zoom drag points,", + "note that `showAxisDragHandles` must be enabled to have an effect." + ].join(" ") + }, + showTips: { + valType: "boolean", + dflt: true, + description: [ + "Determines whether or not tips are shown while interacting", + "with the resulting graphs." + ].join(" ") + }, + showLink: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether a link to Chart Studio Cloud is displayed", + "at the bottom right corner of resulting graphs.", + "Use with `sendData` and `linkText`." + ].join(" ") + }, + linkText: { + valType: "string", + dflt: "Edit chart", + noBlank: true, + description: [ + "Sets the text appearing in the `showLink` link." + ].join(" ") + }, + sendData: { + valType: "boolean", + dflt: true, + description: [ + "If *showLink* is true, does it contain data", + "just link to a Chart Studio Cloud file?" + ].join(" ") + }, + showSources: { + valType: "any", + dflt: false, + description: [ + "Adds a source-displaying function to show sources on", + "the resulting graphs." + ].join(" ") + }, + displayModeBar: { + valType: "enumerated", + values: ["hover", true, false], + dflt: "hover", + description: [ + "Determines the mode bar display mode.", + "If *true*, the mode bar is always visible.", + "If *false*, the mode bar is always hidden.", + "If *hover*, the mode bar is visible while the mouse cursor", + "is on the graph container." + ].join(" ") + }, + showSendToCloud: { + valType: "boolean", + dflt: false, + description: [ + 'Should we include a ModeBar button, labeled "Edit in Chart Studio",', + "that sends this chart to chart-studio.plotly.com (formerly plot.ly) or another plotly server", + "as specified by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0", + "this button was included by default, now it is opt-in using this flag.", + "Note that this button can (depending on `plotlyServerURL` being set) send your data", + "to an external server. However that server does not persist your data", + 'until you arrive at the Chart Studio and explicitly click "Save".' + ].join(" ") + }, + showEditInChartStudio: { + valType: "boolean", + dflt: false, + description: [ + "Same as `showSendToCloud`, but use a pencil icon instead of a floppy-disk.", + "Note that if both `showSendToCloud` and `showEditInChartStudio` are turned,", + "only `showEditInChartStudio` will be honored." + ].join(" ") + }, + modeBarButtonsToRemove: { + valType: "any", + dflt: [], + description: [ + "Remove mode bar buttons by name.", + "See ./components/modebar/buttons.js for the list of names." + ].join(" ") + }, + modeBarButtonsToAdd: { + valType: "any", + dflt: [], + description: [ + "Add mode bar button using config objects", + "See ./components/modebar/buttons.js for list of arguments.", + "To enable predefined modebar buttons e.g. shape drawing, hover and spikelines,", + "simply provide their string name(s). This could include:", + "*v1hovermode*, *hoverclosest*, *hovercompare*, *togglehover*, *togglespikelines*,", + "*drawline*, *drawopenpath*, *drawclosedpath*, *drawcircle*, *drawrect* and *eraseshape*.", + "Please note that these predefined buttons will only be shown if they are compatible", + "with all trace types used in a graph." + ].join(" ") + }, + modeBarButtons: { + valType: "any", + dflt: false, + description: [ + "Define fully custom mode bar buttons as nested array,", + "where the outer arrays represents button groups, and", + "the inner arrays have buttons config objects or names of default buttons", + "See ./components/modebar/buttons.js for more info." + ].join(" ") + }, + toImageButtonOptions: { + valType: "any", + dflt: {}, + description: [ + "Statically override options for toImage modebar button", + "allowed keys are format, filename, width, height, scale", + "see ../components/modebar/buttons.js" + ].join(" ") + }, + displaylogo: { + valType: "boolean", + dflt: true, + description: [ + "Determines whether or not the plotly logo is displayed", + "on the end of the mode bar." + ].join(" ") + }, + watermark: { + valType: "boolean", + dflt: false, + description: "watermark the images with the company's logo" + }, + plotGlPixelRatio: { + valType: "number", + dflt: 2, + min: 1, + max: 4, + description: [ + "Set the pixel ratio during WebGL image export.", + "This config option was formerly named `plot3dPixelRatio`", + "which is now deprecated." + ].join(" ") + }, + setBackground: { + valType: "any", + dflt: "transparent", + description: [ + "Set function to add the background color (i.e. `layout.paper_color`)", + "to a different container.", + "This function take the graph div as first argument and the current background", + "color as second argument.", + "Alternatively, set to string *opaque* to ensure there is white behind it." + ].join(" ") + }, + topojsonURL: { + valType: "string", + noBlank: true, + dflt: "https://cdn.plot.ly/", + description: [ + "Set the URL to topojson used in geo charts.", + "By default, the topojson files are fetched from cdn.plot.ly.", + "For example, set this option to:", + "/dist/topojson/", + "to render geographical feature using the topojson files", + "that ship with the plotly.js module." + ].join(" ") + }, + mapboxAccessToken: { + valType: "string", + dflt: null, + description: [ + "Mapbox access token (required to plot mapbox trace types)", + "If using an Mapbox Atlas server, set this option to ''", + "so that plotly.js won't attempt to authenticate to the public Mapbox server." + ].join(" ") + }, + logging: { + valType: "integer", + min: 0, + max: 2, + dflt: 1, + description: [ + "Turn all console logging on or off (errors will be thrown)", + "This should ONLY be set via Plotly.setPlotConfig", + "Available levels:", + "0: no logs", + "1: warnings and errors, but not informational messages", + "2: verbose logs" + ].join(" ") + }, + notifyOnLogging: { + valType: "integer", + min: 0, + max: 2, + dflt: 0, + description: [ + "Set on-graph logging (notifier) level", + "This should ONLY be set via Plotly.setPlotConfig", + "Available levels:", + "0: no on-graph logs", + "1: warnings and errors, but not informational messages", + "2: verbose logs" + ].join(" ") + }, + queueLength: { + valType: "integer", + min: 0, + dflt: 0, + description: "Sets the length of the undo/redo queue." + }, + globalTransforms: { + valType: "any", + dflt: [], + description: [ + "Set global transform to be applied to all traces with no", + "specification needed" + ].join(" ") + }, + locale: { + valType: "string", + dflt: "en-US", + description: [ + "Which localization should we use?", + "Should be a string like 'en' or 'en-US'." + ].join(" ") + }, + locales: { + valType: "any", + dflt: {}, + description: [ + "Localization definitions", + "Locales can be provided either here (specific to one chart) or globally", + "by registering them as modules.", + "Should be an object of objects {locale: {dictionary: {...}, format: {...}}}", + "{", + " da: {", + " dictionary: {'Reset axes': 'Nulstil aksler', ...},", + " format: {months: [...], shortMonths: [...]}", + " },", + " ...", + "}", + "All parts are optional. When looking for translation or format fields, we", + "look first for an exact match in a config locale, then in a registered", + "module. If those fail, we strip off any regionalization ('en-US' -> 'en')", + "and try each (config, registry) again. The final fallback for translation", + "is untranslated (which is US English) and for formats is the base English", + "(the only consequence being the last fallback date format %x is DD/MM/YYYY", + "instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored", + "for our automatic number formatting, but can be used in custom formats." + ].join(" ") + } +}; +var dfltConfig$4 = {}; +function crawl$1(src2, target) { + for (var k in src2) { + var obj = src2[k]; + if (obj.valType) { + target[k] = obj.dflt; + } else { + if (!target[k]) { + target[k] = {}; + } + crawl$1(obj, target[k]); + } + } +} +crawl$1(configAttributes, dfltConfig$4); +var plot_config = { + configAttributes, + dfltConfig: dfltConfig$4 +}; +var d3$F = d3Exports; +var isNumeric$y = fastIsnumeric; +var NOTEDATA = []; +var notifier$1 = function(text, displayLength) { + if (NOTEDATA.indexOf(text) !== -1) return; + NOTEDATA.push(text); + var ts = 1e3; + if (isNumeric$y(displayLength)) ts = displayLength; + else if (displayLength === "long") ts = 3e3; + var notifierContainer = d3$F.select("body").selectAll(".plotly-notifier").data([0]); + notifierContainer.enter().append("div").classed("plotly-notifier", true); + var notes = notifierContainer.selectAll(".notifier-note").data(NOTEDATA); + function killNote(transition2) { + transition2.duration(700).style("opacity", 0).each("end", function(thisText) { + var thisIndex = NOTEDATA.indexOf(thisText); + if (thisIndex !== -1) NOTEDATA.splice(thisIndex, 1); + d3$F.select(this).remove(); + }); + } + notes.enter().append("div").classed("notifier-note", true).style("opacity", 0).each(function(thisText) { + var note = d3$F.select(this); + note.append("button").classed("notifier-close", true).html("×").on("click", function() { + note.transition().call(killNote); + }); + var p = note.append("p"); + var lines = thisText.split(//g); + for (var i = 0; i < lines.length; i++) { + if (i) p.append("br"); + p.append("span").text(lines[i]); + } + if (displayLength === "stick") { + note.transition().duration(350).style("opacity", 1); + } else { + note.transition().duration(700).style("opacity", 1).transition().delay(ts).call(killNote); + } + }); +}; +var dfltConfig$3 = plot_config.dfltConfig; +var notifier = notifier$1; +var loggers$1 = loggers$2.exports = {}; +loggers$1.log = function() { + var i; + if (dfltConfig$3.logging > 1) { + var messages = ["LOG:"]; + for (i = 0; i < arguments.length; i++) { + messages.push(arguments[i]); + } + console.trace.apply(console, messages); + } + if (dfltConfig$3.notifyOnLogging > 1) { + var lines = []; + for (i = 0; i < arguments.length; i++) { + lines.push(arguments[i]); + } + notifier(lines.join("
"), "long"); + } +}; +loggers$1.warn = function() { + var i; + if (dfltConfig$3.logging > 0) { + var messages = ["WARN:"]; + for (i = 0; i < arguments.length; i++) { + messages.push(arguments[i]); + } + console.trace.apply(console, messages); + } + if (dfltConfig$3.notifyOnLogging > 0) { + var lines = []; + for (i = 0; i < arguments.length; i++) { + lines.push(arguments[i]); + } + notifier(lines.join("
"), "stick"); + } +}; +loggers$1.error = function() { + var i; + if (dfltConfig$3.logging > 0) { + var messages = ["ERROR:"]; + for (i = 0; i < arguments.length; i++) { + messages.push(arguments[i]); + } + console.error.apply(console, messages); + } + if (dfltConfig$3.notifyOnLogging > 0) { + var lines = []; + for (i = 0; i < arguments.length; i++) { + lines.push(arguments[i]); + } + notifier(lines.join("
"), "stick"); + } +}; +var loggersExports = loggers$2.exports; +var registry = {}; +var noop$2 = function noop() { +}; +var push_unique = function pushUnique(array2, item) { + if (item instanceof RegExp) { + var itemStr = item.toString(); + for (var i = 0; i < array2.length; i++) { + if (array2[i] instanceof RegExp && array2[i].toString() === itemStr) { + return array2; + } + } + array2.push(item); + } else if ((item || item === 0) && array2.indexOf(item) === -1) array2.push(item); + return array2; +}; +var matrix$1 = {}; +var create_1$1 = create; +function create() { + var out = new Float32Array(16); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var clone_1 = clone; +function clone(a) { + var out = new Float32Array(16); + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +var copy_1 = copy$1; +function copy$1(out, a) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +var identity_1 = identity$4; +function identity$4(out) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var transpose_1 = transpose; +function transpose(out, a) { + if (out === a) { + var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a01; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a02; + out[9] = a12; + out[11] = a[14]; + out[12] = a03; + out[13] = a13; + out[14] = a23; + } else { + out[0] = a[0]; + out[1] = a[4]; + out[2] = a[8]; + out[3] = a[12]; + out[4] = a[1]; + out[5] = a[5]; + out[6] = a[9]; + out[7] = a[13]; + out[8] = a[2]; + out[9] = a[6]; + out[10] = a[10]; + out[11] = a[14]; + out[12] = a[3]; + out[13] = a[7]; + out[14] = a[11]; + out[15] = a[15]; + } + return out; +} +var invert_1 = invert; +function invert(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; + if (!det) { + return null; + } + det = 1 / det; + out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; + out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; + out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; + out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; + out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; + out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; + out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; + out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; + out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; + out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; + out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; + out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; + out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; + out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; + out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; + out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; + return out; +} +var adjoint_1 = adjoint; +function adjoint(out, a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); + out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); + out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); + out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); + out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); + out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); + out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); + out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); + out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); + out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); + out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); + out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); + out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); + out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); + out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); + out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); + return out; +} +var determinant_1 = determinant; +function determinant(a) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32; + return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; +} +var multiply_1 = multiply; +function multiply(out, a, b) { + var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; + var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; + out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[4]; + b1 = b[5]; + b2 = b[6]; + b3 = b[7]; + out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[8]; + b1 = b[9]; + b2 = b[10]; + b3 = b[11]; + out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + b0 = b[12]; + b1 = b[13]; + b2 = b[14]; + b3 = b[15]; + out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; + out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; + out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; + out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; + return out; +} +var translate_1 = translate; +function translate(out, a, v) { + var x = v[0], y = v[1], z = v[2], a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23; + if (a === out) { + out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; + out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; + out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; + out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; + } else { + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + out[0] = a00; + out[1] = a01; + out[2] = a02; + out[3] = a03; + out[4] = a10; + out[5] = a11; + out[6] = a12; + out[7] = a13; + out[8] = a20; + out[9] = a21; + out[10] = a22; + out[11] = a23; + out[12] = a00 * x + a10 * y + a20 * z + a[12]; + out[13] = a01 * x + a11 * y + a21 * z + a[13]; + out[14] = a02 * x + a12 * y + a22 * z + a[14]; + out[15] = a03 * x + a13 * y + a23 * z + a[15]; + } + return out; +} +var scale_1 = scale; +function scale(out, a, v) { + var x = v[0], y = v[1], z = v[2]; + out[0] = a[0] * x; + out[1] = a[1] * x; + out[2] = a[2] * x; + out[3] = a[3] * x; + out[4] = a[4] * y; + out[5] = a[5] * y; + out[6] = a[6] * y; + out[7] = a[7] * y; + out[8] = a[8] * z; + out[9] = a[9] * z; + out[10] = a[10] * z; + out[11] = a[11] * z; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + return out; +} +var rotate_1 = rotate$2; +function rotate$2(out, a, rad, axis) { + var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22; + if (Math.abs(len) < 1e-6) { + return null; + } + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + a00 = a[0]; + a01 = a[1]; + a02 = a[2]; + a03 = a[3]; + a10 = a[4]; + a11 = a[5]; + a12 = a[6]; + a13 = a[7]; + a20 = a[8]; + a21 = a[9]; + a22 = a[10]; + a23 = a[11]; + b00 = x * x * t + c; + b01 = y * x * t + z * s; + b02 = z * x * t - y * s; + b10 = x * y * t - z * s; + b11 = y * y * t + c; + b12 = z * y * t + x * s; + b20 = x * z * t + y * s; + b21 = y * z * t - x * s; + b22 = z * z * t + c; + out[0] = a00 * b00 + a10 * b01 + a20 * b02; + out[1] = a01 * b00 + a11 * b01 + a21 * b02; + out[2] = a02 * b00 + a12 * b01 + a22 * b02; + out[3] = a03 * b00 + a13 * b01 + a23 * b02; + out[4] = a00 * b10 + a10 * b11 + a20 * b12; + out[5] = a01 * b10 + a11 * b11 + a21 * b12; + out[6] = a02 * b10 + a12 * b11 + a22 * b12; + out[7] = a03 * b10 + a13 * b11 + a23 * b12; + out[8] = a00 * b20 + a10 * b21 + a20 * b22; + out[9] = a01 * b20 + a11 * b21 + a21 * b22; + out[10] = a02 * b20 + a12 * b21 + a22 * b22; + out[11] = a03 * b20 + a13 * b21 + a23 * b22; + if (a !== out) { + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + return out; +} +var rotateX_1 = rotateX; +function rotateX(out, a, rad) { + var s = Math.sin(rad), c = Math.cos(rad), a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; + if (a !== out) { + out[0] = a[0]; + out[1] = a[1]; + out[2] = a[2]; + out[3] = a[3]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[4] = a10 * c + a20 * s; + out[5] = a11 * c + a21 * s; + out[6] = a12 * c + a22 * s; + out[7] = a13 * c + a23 * s; + out[8] = a20 * c - a10 * s; + out[9] = a21 * c - a11 * s; + out[10] = a22 * c - a12 * s; + out[11] = a23 * c - a13 * s; + return out; +} +var rotateY_1 = rotateY; +function rotateY(out, a, rad) { + var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; + if (a !== out) { + out[4] = a[4]; + out[5] = a[5]; + out[6] = a[6]; + out[7] = a[7]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[0] = a00 * c - a20 * s; + out[1] = a01 * c - a21 * s; + out[2] = a02 * c - a22 * s; + out[3] = a03 * c - a23 * s; + out[8] = a00 * s + a20 * c; + out[9] = a01 * s + a21 * c; + out[10] = a02 * s + a22 * c; + out[11] = a03 * s + a23 * c; + return out; +} +var rotateZ_1 = rotateZ; +function rotateZ(out, a, rad) { + var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; + if (a !== out) { + out[8] = a[8]; + out[9] = a[9]; + out[10] = a[10]; + out[11] = a[11]; + out[12] = a[12]; + out[13] = a[13]; + out[14] = a[14]; + out[15] = a[15]; + } + out[0] = a00 * c + a10 * s; + out[1] = a01 * c + a11 * s; + out[2] = a02 * c + a12 * s; + out[3] = a03 * c + a13 * s; + out[4] = a10 * c - a00 * s; + out[5] = a11 * c - a01 * s; + out[6] = a12 * c - a02 * s; + out[7] = a13 * c - a03 * s; + return out; +} +var fromRotation_1 = fromRotation; +function fromRotation(out, rad, axis) { + var s, c, t; + var x = axis[0]; + var y = axis[1]; + var z = axis[2]; + var len = Math.sqrt(x * x + y * y + z * z); + if (Math.abs(len) < 1e-6) { + return null; + } + len = 1 / len; + x *= len; + y *= len; + z *= len; + s = Math.sin(rad); + c = Math.cos(rad); + t = 1 - c; + out[0] = x * x * t + c; + out[1] = y * x * t + z * s; + out[2] = z * x * t - y * s; + out[3] = 0; + out[4] = x * y * t - z * s; + out[5] = y * y * t + c; + out[6] = z * y * t + x * s; + out[7] = 0; + out[8] = x * z * t + y * s; + out[9] = y * z * t - x * s; + out[10] = z * z * t + c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var fromRotationTranslation_1 = fromRotationTranslation; +function fromRotationTranslation(out, q, v) { + var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; + out[0] = 1 - (yy + zz); + out[1] = xy + wz; + out[2] = xz - wy; + out[3] = 0; + out[4] = xy - wz; + out[5] = 1 - (xx + zz); + out[6] = yz + wx; + out[7] = 0; + out[8] = xz + wy; + out[9] = yz - wx; + out[10] = 1 - (xx + yy); + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +var fromScaling_1 = fromScaling; +function fromScaling(out, v) { + out[0] = v[0]; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = v[1]; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = v[2]; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var fromTranslation_1 = fromTranslation; +function fromTranslation(out, v) { + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = v[0]; + out[13] = v[1]; + out[14] = v[2]; + out[15] = 1; + return out; +} +var fromXRotation_1 = fromXRotation; +function fromXRotation(out, rad) { + var s = Math.sin(rad), c = Math.cos(rad); + out[0] = 1; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = c; + out[6] = s; + out[7] = 0; + out[8] = 0; + out[9] = -s; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var fromYRotation_1 = fromYRotation; +function fromYRotation(out, rad) { + var s = Math.sin(rad), c = Math.cos(rad); + out[0] = c; + out[1] = 0; + out[2] = -s; + out[3] = 0; + out[4] = 0; + out[5] = 1; + out[6] = 0; + out[7] = 0; + out[8] = s; + out[9] = 0; + out[10] = c; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var fromZRotation_1 = fromZRotation; +function fromZRotation(out, rad) { + var s = Math.sin(rad), c = Math.cos(rad); + out[0] = c; + out[1] = s; + out[2] = 0; + out[3] = 0; + out[4] = -s; + out[5] = c; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 1; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var fromQuat_1 = fromQuat; +function fromQuat(out, q) { + var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; + out[0] = 1 - yy - zz; + out[1] = yx + wz; + out[2] = zx - wy; + out[3] = 0; + out[4] = yx - wz; + out[5] = 1 - xx - zz; + out[6] = zy + wx; + out[7] = 0; + out[8] = zx + wy; + out[9] = zy - wx; + out[10] = 1 - xx - yy; + out[11] = 0; + out[12] = 0; + out[13] = 0; + out[14] = 0; + out[15] = 1; + return out; +} +var frustum_1 = frustum; +function frustum(out, left, right, bottom, top, near, far) { + var rl = 1 / (right - left), tb = 1 / (top - bottom), nf = 1 / (near - far); + out[0] = near * 2 * rl; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = near * 2 * tb; + out[6] = 0; + out[7] = 0; + out[8] = (right + left) * rl; + out[9] = (top + bottom) * tb; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near * 2 * nf; + out[15] = 0; + return out; +} +var perspective_1 = perspective; +function perspective(out, fovy, aspect, near, far) { + var f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far); + out[0] = f / aspect; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = f; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = (far + near) * nf; + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = 2 * far * near * nf; + out[15] = 0; + return out; +} +var perspectiveFromFieldOfView_1 = perspectiveFromFieldOfView; +function perspectiveFromFieldOfView(out, fov, near, far) { + var upTan = Math.tan(fov.upDegrees * Math.PI / 180), downTan = Math.tan(fov.downDegrees * Math.PI / 180), leftTan = Math.tan(fov.leftDegrees * Math.PI / 180), rightTan = Math.tan(fov.rightDegrees * Math.PI / 180), xScale = 2 / (leftTan + rightTan), yScale = 2 / (upTan + downTan); + out[0] = xScale; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = yScale; + out[6] = 0; + out[7] = 0; + out[8] = -((leftTan - rightTan) * xScale * 0.5); + out[9] = (upTan - downTan) * yScale * 0.5; + out[10] = far / (near - far); + out[11] = -1; + out[12] = 0; + out[13] = 0; + out[14] = far * near / (near - far); + out[15] = 0; + return out; +} +var ortho_1 = ortho; +function ortho(out, left, right, bottom, top, near, far) { + var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far); + out[0] = -2 * lr; + out[1] = 0; + out[2] = 0; + out[3] = 0; + out[4] = 0; + out[5] = -2 * bt; + out[6] = 0; + out[7] = 0; + out[8] = 0; + out[9] = 0; + out[10] = 2 * nf; + out[11] = 0; + out[12] = (left + right) * lr; + out[13] = (top + bottom) * bt; + out[14] = (far + near) * nf; + out[15] = 1; + return out; +} +var identity$3 = identity_1; +var lookAt_1 = lookAt; +function lookAt(out, eye, center, up) { + var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2], centerx = center[0], centery = center[1], centerz = center[2]; + if (Math.abs(eyex - centerx) < 1e-6 && Math.abs(eyey - centery) < 1e-6 && Math.abs(eyez - centerz) < 1e-6) { + return identity$3(out); + } + z0 = eyex - centerx; + z1 = eyey - centery; + z2 = eyez - centerz; + len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); + z0 *= len; + z1 *= len; + z2 *= len; + x0 = upy * z2 - upz * z1; + x1 = upz * z0 - upx * z2; + x2 = upx * z1 - upy * z0; + len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); + if (!len) { + x0 = 0; + x1 = 0; + x2 = 0; + } else { + len = 1 / len; + x0 *= len; + x1 *= len; + x2 *= len; + } + y0 = z1 * x2 - z2 * x1; + y1 = z2 * x0 - z0 * x2; + y2 = z0 * x1 - z1 * x0; + len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); + if (!len) { + y0 = 0; + y1 = 0; + y2 = 0; + } else { + len = 1 / len; + y0 *= len; + y1 *= len; + y2 *= len; + } + out[0] = x0; + out[1] = y0; + out[2] = z0; + out[3] = 0; + out[4] = x1; + out[5] = y1; + out[6] = z1; + out[7] = 0; + out[8] = x2; + out[9] = y2; + out[10] = z2; + out[11] = 0; + out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); + out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); + out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); + out[15] = 1; + return out; +} +var str_1 = str; +function str(a) { + return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")"; +} +var glMat4 = { + create: create_1$1, + clone: clone_1, + copy: copy_1, + identity: identity_1, + transpose: transpose_1, + invert: invert_1, + adjoint: adjoint_1, + determinant: determinant_1, + multiply: multiply_1, + translate: translate_1, + scale: scale_1, + rotate: rotate_1, + rotateX: rotateX_1, + rotateY: rotateY_1, + rotateZ: rotateZ_1, + fromRotation: fromRotation_1, + fromRotationTranslation: fromRotationTranslation_1, + fromScaling: fromScaling_1, + fromTranslation: fromTranslation_1, + fromXRotation: fromXRotation_1, + fromYRotation: fromYRotation_1, + fromZRotation: fromZRotation_1, + fromQuat: fromQuat_1, + frustum: frustum_1, + perspective: perspective_1, + perspectiveFromFieldOfView: perspectiveFromFieldOfView_1, + ortho: ortho_1, + lookAt: lookAt_1, + str: str_1 +}; +(function(exports2) { + var mat4X42 = glMat4; + exports2.init2dArray = function(rowLength, colLength) { + var array2 = new Array(rowLength); + for (var i = 0; i < rowLength; i++) array2[i] = new Array(colLength); + return array2; + }; + exports2.transposeRagged = function(z) { + var maxlen = 0; + var zlen = z.length; + var i, j; + for (i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length); + var t = new Array(maxlen); + for (i = 0; i < maxlen; i++) { + t[i] = new Array(zlen); + for (j = 0; j < zlen; j++) t[i][j] = z[j][i]; + } + return t; + }; + exports2.dot = function(x, y) { + if (!(x.length && y.length) || x.length !== y.length) return null; + var len = x.length; + var out; + var i; + if (x[0].length) { + out = new Array(len); + for (i = 0; i < len; i++) out[i] = exports2.dot(x[i], y); + } else if (y[0].length) { + var yTranspose = exports2.transposeRagged(y); + out = new Array(yTranspose.length); + for (i = 0; i < yTranspose.length; i++) out[i] = exports2.dot(x, yTranspose[i]); + } else { + out = 0; + for (i = 0; i < len; i++) out += x[i] * y[i]; + } + return out; + }; + exports2.translationMatrix = function(x, y) { + return [[1, 0, x], [0, 1, y], [0, 0, 1]]; + }; + exports2.rotationMatrix = function(alpha) { + var a = alpha * Math.PI / 180; + return [ + [Math.cos(a), -Math.sin(a), 0], + [Math.sin(a), Math.cos(a), 0], + [0, 0, 1] + ]; + }; + exports2.rotationXYMatrix = function(a, x, y) { + return exports2.dot( + exports2.dot( + exports2.translationMatrix(x, y), + exports2.rotationMatrix(a) + ), + exports2.translationMatrix(-x, -y) + ); + }; + exports2.apply3DTransform = function(transform) { + return function() { + var args = arguments; + var xyz = arguments.length === 1 ? args[0] : [args[0], args[1], args[2] || 0]; + return exports2.dot(transform, [xyz[0], xyz[1], xyz[2], 1]).slice(0, 3); + }; + }; + exports2.apply2DTransform = function(transform) { + return function() { + var args = arguments; + if (args.length === 3) { + args = args[0]; + } + var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; + return exports2.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); + }; + }; + exports2.apply2DTransform2 = function(transform) { + var at = exports2.apply2DTransform(transform); + return function(xys) { + return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); + }; + }; + exports2.convertCssMatrix = function(m) { + if (m) { + var len = m.length; + if (len === 16) return m; + if (len === 6) { + return [ + m[0], + m[1], + 0, + 0, + m[2], + m[3], + 0, + 0, + 0, + 0, + 1, + 0, + m[4], + m[5], + 0, + 1 + ]; + } + } + return [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + }; + exports2.inverseTransformMatrix = function(m) { + var out = []; + mat4X42.invert(out, m); + return [ + [out[0], out[1], out[2], out[3]], + [out[4], out[5], out[6], out[7]], + [out[8], out[9], out[10], out[11]], + [out[12], out[13], out[14], out[15]] + ]; + }; +})(matrix$1); +var d3$E = d3Exports; +var loggers = loggersExports; +var matrix = matrix$1; +var mat4X4 = glMat4; +function getGraphDiv$2(gd) { + var gdElement; + if (typeof gd === "string") { + gdElement = document.getElementById(gd); + if (gdElement === null) { + throw new Error("No DOM element with id '" + gd + "' exists on the page."); + } + return gdElement; + } else if (gd === null || gd === void 0) { + throw new Error("DOM element provided is null or undefined"); + } + return gd; +} +function isPlotDiv(el) { + var el3 = d3$E.select(el); + return el3.node() instanceof HTMLElement && el3.size() && el3.classed("js-plotly-plot"); +} +function removeElement$1(el) { + var elParent = el && el.parentNode; + if (elParent) elParent.removeChild(el); +} +function addStyleRule(selector, styleString) { + addRelatedStyleRule("global", selector, styleString); +} +function addRelatedStyleRule(uid, selector, styleString) { + var id = "plotly.js-style-" + uid; + var style5 = document.getElementById(id); + if (!style5) { + style5 = document.createElement("style"); + style5.setAttribute("id", id); + style5.appendChild(document.createTextNode("")); + document.head.appendChild(style5); + } + var styleSheet = style5.sheet; + if (styleSheet.insertRule) { + styleSheet.insertRule(selector + "{" + styleString + "}", 0); + } else if (styleSheet.addRule) { + styleSheet.addRule(selector, styleString, 0); + } else loggers.warn("addStyleRule failed"); +} +function deleteRelatedStyleRule(uid) { + var id = "plotly.js-style-" + uid; + var style5 = document.getElementById(id); + if (style5) removeElement$1(style5); +} +function getFullTransformMatrix(element) { + var allElements = getElementAndAncestors(element); + var out = [ + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 1 + ]; + allElements.forEach(function(e) { + var t = getElementTransformMatrix(e); + if (t) { + var m = matrix.convertCssMatrix(t); + out = mat4X4.multiply(out, out, m); + } + }); + return out; +} +function getElementTransformMatrix(element) { + var style5 = window.getComputedStyle(element, null); + var transform = style5.getPropertyValue("-webkit-transform") || style5.getPropertyValue("-moz-transform") || style5.getPropertyValue("-ms-transform") || style5.getPropertyValue("-o-transform") || style5.getPropertyValue("transform"); + if (transform === "none") return null; + return transform.replace("matrix", "").replace("3d", "").slice(1, -1).split(",").map(function(n) { + return +n; + }); +} +function getElementAndAncestors(element) { + var allElements = []; + while (isTransformableElement(element)) { + allElements.push(element); + element = element.parentNode; + if (typeof ShadowRoot === "function" && element instanceof ShadowRoot) { + element = element.host; + } + } + return allElements; +} +function isTransformableElement(element) { + return element && (element instanceof Element || element instanceof HTMLElement); +} +function equalDomRects(a, b) { + return a && b && a.top === b.top && a.left === b.left && a.right === b.right && a.bottom === b.bottom; +} +var dom = { + getGraphDiv: getGraphDiv$2, + isPlotDiv, + removeElement: removeElement$1, + addStyleRule, + addRelatedStyleRule, + deleteRelatedStyleRule, + getFullTransformMatrix, + getElementTransformMatrix, + getElementAndAncestors, + equalDomRects +}; +var animation_attributes = { + mode: { + valType: "enumerated", + dflt: "afterall", + values: ["immediate", "next", "afterall"], + description: [ + "Describes how a new animate call interacts with currently-running", + "animations. If `immediate`, current animations are interrupted and", + "the new animation is started. If `next`, the current frame is allowed", + "to complete, after which the new animation is started. If `afterall`", + "all existing frames are animated to completion before the new animation", + "is started." + ].join(" ") + }, + direction: { + valType: "enumerated", + values: ["forward", "reverse"], + dflt: "forward", + description: [ + "The direction in which to play the frames triggered by the animation call" + ].join(" ") + }, + fromcurrent: { + valType: "boolean", + dflt: false, + description: [ + "Play frames starting at the current frame instead of the beginning." + ].join(" ") + }, + frame: { + duration: { + valType: "number", + min: 0, + dflt: 500, + description: [ + "The duration in milliseconds of each frame. If greater than the frame", + "duration, it will be limited to the frame duration." + ].join(" ") + }, + redraw: { + valType: "boolean", + dflt: true, + description: [ + "Redraw the plot at completion of the transition. This is desirable", + "for transitions that include properties that cannot be transitioned,", + "but may significantly slow down updates that do not require a full", + "redraw of the plot" + ].join(" ") + } + }, + transition: { + duration: { + valType: "number", + min: 0, + dflt: 500, + editType: "none", + description: [ + "The duration of the transition, in milliseconds. If equal to zero,", + "updates are synchronous." + ].join(" ") + }, + easing: { + valType: "enumerated", + dflt: "cubic-in-out", + values: [ + "linear", + "quad", + "cubic", + "sin", + "exp", + "circle", + "elastic", + "back", + "bounce", + "linear-in", + "quad-in", + "cubic-in", + "sin-in", + "exp-in", + "circle-in", + "elastic-in", + "back-in", + "bounce-in", + "linear-out", + "quad-out", + "cubic-out", + "sin-out", + "exp-out", + "circle-out", + "elastic-out", + "back-out", + "bounce-out", + "linear-in-out", + "quad-in-out", + "cubic-in-out", + "sin-in-out", + "exp-in-out", + "circle-in-out", + "elastic-in-out", + "back-in-out", + "bounce-in-out" + ], + editType: "none", + description: "The easing function used for the transition" + }, + ordering: { + valType: "enumerated", + values: ["layout first", "traces first"], + dflt: "layout first", + editType: "none", + description: [ + "Determines whether the figure's layout or traces smoothly transitions", + "during updates that make both traces and layout change." + ].join(" ") + } + } +}; +var extendFlat$k = extend$5.extendFlat; +var isPlainObject$3 = is_plain_object; +var traceOpts = { + valType: "flaglist", + extras: ["none"], + flags: ["calc", "clearAxisTypes", "plot", "style", "markerSize", "colorbars"], + description: [ + "trace attributes should include an `editType` string matching this flaglist.", + "*calc* is the most extensive: a full (re)plot starting by clearing `gd.calcdata`", + "to force it to be regenerated", + "*clearAxisTypes* resets the types of the axes this trace is on, because new data could", + "cause the automatic axis type detection to change. Log type will not be cleared, as that", + "is never automatically chosen so must have been user-specified.", + "*plot* (re)plots but without first clearing `gd.calcdata`.", + "*style* only calls `module.style` (or module.editStyle) for all trace modules and redraws the legend.", + "*markerSize* is like *style*, but propagate axis-range changes due to scatter `marker.size`", + "*colorbars* only redraws colorbars." + ].join(" ") +}; +var layoutOpts = { + valType: "flaglist", + extras: ["none"], + flags: [ + "calc", + "plot", + "legend", + "ticks", + "axrange", + "layoutstyle", + "modebar", + "camera", + "arraydraw", + "colorbars" + ], + description: [ + "layout attributes should include an `editType` string matching this flaglist.", + "*calc* is the most extensive: a full (re)plot starting by clearing `gd.calcdata`", + "to force it to be regenerated", + "*plot* (re)plots but without first clearing `gd.calcdata`.", + "*legend* only redraws the legend.", + "*ticks* only redraws axis ticks, labels, and gridlines.", + "*axrange* minimal sequence when updating axis ranges.", + "*layoutstyle* reapplies global and SVG cartesian axis styles.", + "*modebar* just updates the modebar.", + "*camera* just updates the camera settings for gl3d scenes.", + "*arraydraw* allows component arrays to invoke the redraw routines just for the", + "component(s) that changed.", + "*colorbars* only redraws colorbars." + ].join(" ") +}; +var traceEditTypeFlags = traceOpts.flags.slice().concat(["fullReplot"]); +var layoutEditTypeFlags = layoutOpts.flags.slice().concat("layoutReplot"); +var edit_types = { + traces: traceOpts, + layout: layoutOpts, + /* + * default (all false) edit flags for restyle (traces) + * creates a new object each call, so the caller can mutate freely + */ + traceFlags: function() { + return falseObj(traceEditTypeFlags); + }, + /* + * default (all false) edit flags for relayout + * creates a new object each call, so the caller can mutate freely + */ + layoutFlags: function() { + return falseObj(layoutEditTypeFlags); + }, + /* + * update `flags` with the `editType` values found in `attr` + */ + update: function(flags, attr) { + var editType = attr.editType; + if (editType && editType !== "none") { + var editTypeParts = editType.split("+"); + for (var i = 0; i < editTypeParts.length; i++) { + flags[editTypeParts[i]] = true; + } + } + }, + overrideAll: overrideAll$8 +}; +function falseObj(keys) { + var out = {}; + for (var i = 0; i < keys.length; i++) out[keys[i]] = false; + return out; +} +function overrideAll$8(attrs2, editTypeOverride, overrideContainers) { + var out = extendFlat$k({}, attrs2); + for (var key in out) { + var attr = out[key]; + if (isPlainObject$3(attr)) { + out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); + } + } + if (overrideContainers === "from-root") out.editType = editTypeOverride; + return out; +} +function overrideOne(attr, editTypeOverride, overrideContainers, key) { + if (attr.valType) { + var out = extendFlat$k({}, attr); + out.editType = editTypeOverride; + if (Array.isArray(attr.items)) { + out.items = new Array(attr.items.length); + for (var i = 0; i < attr.items.length; i++) { + out.items[i] = overrideOne(attr.items[i], editTypeOverride); + } + } + return out; + } else { + return overrideAll$8( + attr, + editTypeOverride, + key.charAt(0) === "_" ? "nested" : "from-root" + ); + } +} +var attributes$M = {}; +attributes$M.dash = { + valType: "string", + // string type usually doesn't take values... this one should really be + // a special type or at least a special coercion function, from the GUI + // you only get these values but elsewhere the user can supply a list of + // dash lengths in px, and it will be honored + values: ["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"], + dflt: "solid", + editType: "style", + description: [ + "Sets the dash style of lines. Set to a dash type string", + "(*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*)", + "or a dash length list in px (eg *5px,10px,2px,2px*)." + ].join(" ") +}; +attributes$M.pattern = { + shape: { + valType: "enumerated", + values: ["", "/", "\\", "x", "-", "|", "+", "."], + dflt: "", + arrayOk: true, + editType: "style", + description: [ + "Sets the shape of the pattern fill.", + "By default, no pattern is used for filling the area." + ].join(" ") + }, + fillmode: { + valType: "enumerated", + values: ["replace", "overlay"], + dflt: "replace", + editType: "style", + description: [ + "Determines whether `marker.color` should be used", + "as a default to `bgcolor` or a `fgcolor`." + ].join(" ") + }, + bgcolor: { + valType: "color", + arrayOk: true, + editType: "style", + description: [ + "When there is no colorscale sets the color of background pattern fill.", + "Defaults to a `marker.color` background when `fillmode` is *overlay*.", + "Otherwise, defaults to a transparent background." + ].join(" ") + }, + fgcolor: { + valType: "color", + arrayOk: true, + editType: "style", + description: [ + "When there is no colorscale sets the color of foreground pattern fill.", + "Defaults to a `marker.color` background when `fillmode` is *replace*.", + "Otherwise, defaults to dark grey or white", + "to increase contrast with the `bgcolor`." + ].join(" ") + }, + fgopacity: { + valType: "number", + editType: "style", + min: 0, + max: 1, + description: [ + "Sets the opacity of the foreground pattern fill.", + "Defaults to a 0.5 when `fillmode` is *overlay*.", + "Otherwise, defaults to 1." + ].join(" ") + }, + size: { + valType: "number", + min: 0, + dflt: 8, + arrayOk: true, + editType: "style", + description: [ + "Sets the size of unit squares of the pattern fill in pixels,", + "which corresponds to the interval of repetition of the pattern." + ].join(" ") + }, + solidity: { + valType: "number", + min: 0, + max: 1, + dflt: 0.3, + arrayOk: true, + editType: "style", + description: [ + "Sets the solidity of the pattern fill.", + "Solidity is roughly the fraction of the area filled by the pattern.", + "Solidity of 0 shows only the background color without pattern", + "and solidty of 1 shows only the foreground color without pattern." + ].join(" ") + }, + editType: "style", + description: [ + "Sets the pattern within the marker." + ].join(" ") +}; +var template_attributes = {}; +var docs$2 = { + FORMAT_LINK: "https://github.com/d3/d3-format/tree/v1.4.5#d3-format", + DATE_FORMAT_LINK: "https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format" +}; +var docs$1 = docs$2; +var FORMAT_LINK$1 = docs$1.FORMAT_LINK; +var DATE_FORMAT_LINK$1 = docs$1.DATE_FORMAT_LINK; +function templateFormatStringDescription(opts) { + var supportOther = opts && opts.supportOther; + return [ + "Variables are inserted using %{variable},", + 'for example "y: %{y}"' + (supportOther ? " as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, *xother* will be added to those with different x positions from the first point. An underscore before or after *(x|y)other* will add a space on that side, only when this field is shown." : "."), + `Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}".`, + FORMAT_LINK$1, + "for details on the formatting syntax.", + `Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".`, + DATE_FORMAT_LINK$1, + "for details on the date formatting syntax." + ].join(" "); +} +function shapeTemplateFormatStringDescription() { + return [ + "Variables are inserted using %{variable},", + 'for example "x0: %{x0}".', + `Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{x0:$.2f}". See`, + FORMAT_LINK$1, + "for details on the formatting syntax.", + `Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{x0|%m %b %Y}". See`, + DATE_FORMAT_LINK$1, + "for details on the date formatting syntax.", + "A single multiplication or division operation may be applied to numeric variables, and combined with", + 'd3 number formatting, for example "Length in cm: %{x0*2.54}", "%{slope*60:.1f} meters per second."', + "For log axes, variable values are given in log units.", + "For date axes, x/y coordinate variables and center variables use datetimes, while all other variable values use values in ms." + ].join(" "); +} +function describeVariables(extra) { + var descPart = extra.description ? " " + extra.description : ""; + var keys = extra.keys || []; + if (keys.length > 0) { + var quotedKeys = []; + for (var i = 0; i < keys.length; i++) { + quotedKeys[i] = "`" + keys[i] + "`"; + } + descPart = descPart + "Finally, the template string has access to "; + if (keys.length === 1) { + descPart = descPart + "variable " + quotedKeys[0]; + } else { + descPart = descPart + "variables " + quotedKeys.slice(0, -1).join(", ") + " and " + quotedKeys.slice(-1) + "."; + } + } + return descPart; +} +template_attributes.hovertemplateAttrs = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; + var descPart = describeVariables(extra); + var hovertemplate = { + valType: "string", + dflt: "", + editType: opts.editType || "none", + description: [ + "Template string used for rendering the information that appear on hover box.", + "Note that this will override `hoverinfo`.", + templateFormatStringDescription({ supportOther: true }), + "The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event-data.", + "Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available.", + descPart, + 'Anything contained in tag `` is displayed in the secondary box, for example "{fullData.name}".', + "To hide the secondary box completely, use an empty tag ``." + ].join(" ") + }; + if (opts.arrayOk !== false) { + hovertemplate.arrayOk = true; + } + return hovertemplate; +}; +template_attributes.texttemplateAttrs = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; + var descPart = describeVariables(extra); + var texttemplate = { + valType: "string", + dflt: "", + editType: opts.editType || "calc", + description: [ + "Template string used for rendering the information text that appear on points.", + "Note that this will override `textinfo`.", + templateFormatStringDescription(), + "Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available.", + descPart + ].join(" ") + }; + if (opts.arrayOk !== false) { + texttemplate.arrayOk = true; + } + return texttemplate; +}; +template_attributes.shapeTexttemplateAttrs = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; + var newStr = opts.newshape ? "new " : ""; + var descPart = describeVariables(extra); + var texttemplate = { + valType: "string", + dflt: "", + editType: opts.editType || "arraydraw", + description: [ + "Template string used for rendering the " + newStr + "shape's label.", + "Note that this will override `text`.", + shapeTemplateFormatStringDescription(), + descPart + ].join(" ") + }; + return texttemplate; +}; +function d2l(v, axis) { + return axis ? axis.d2l(v) : v; +} +function l2d(v, axis) { + return axis ? axis.l2d(v) : v; +} +function x0Fn(shape) { + return shape.x0; +} +function x1Fn(shape) { + return shape.x1; +} +function y0Fn(shape) { + return shape.y0; +} +function y1Fn(shape) { + return shape.y1; +} +function x0shiftFn(shape) { + return shape.x0shift || 0; +} +function x1shiftFn(shape) { + return shape.x1shift || 0; +} +function y0shiftFn(shape) { + return shape.y0shift || 0; +} +function y1shiftFn(shape) { + return shape.y1shift || 0; +} +function dxFn(shape, xa) { + return d2l(shape.x1, xa) + x1shiftFn(shape) - d2l(shape.x0, xa) - x0shiftFn(shape); +} +function dyFn(shape, xa, ya) { + return d2l(shape.y1, ya) + y1shiftFn(shape) - d2l(shape.y0, ya) - y0shiftFn(shape); +} +function widthFn(shape, xa) { + return Math.abs(dxFn(shape, xa)); +} +function heightFn(shape, xa, ya) { + return Math.abs(dyFn(shape, xa, ya)); +} +function lengthFn(shape, xa, ya) { + return shape.type !== "line" ? void 0 : Math.sqrt( + Math.pow(dxFn(shape, xa), 2) + Math.pow(dyFn(shape, xa, ya), 2) + ); +} +function xcenterFn(shape, xa) { + return l2d((d2l(shape.x1, xa) + x1shiftFn(shape) + d2l(shape.x0, xa) + x0shiftFn(shape)) / 2, xa); +} +function ycenterFn(shape, xa, ya) { + return l2d((d2l(shape.y1, ya) + y1shiftFn(shape) + d2l(shape.y0, ya) + y0shiftFn(shape)) / 2, ya); +} +function slopeFn(shape, xa, ya) { + return shape.type !== "line" ? void 0 : dyFn(shape, xa, ya) / dxFn(shape, xa); +} +var label_texttemplate = { + x0: x0Fn, + x1: x1Fn, + y0: y0Fn, + y1: y1Fn, + slope: slopeFn, + dx: dxFn, + dy: dyFn, + width: widthFn, + height: heightFn, + length: lengthFn, + xcenter: xcenterFn, + ycenter: ycenterFn +}; +var overrideAll$7 = edit_types.overrideAll; +var basePlotAttributes$1 = attributes$O; +var fontAttrs$e = font_attributes; +var dash$6 = attributes$M.dash; +var extendFlat$j = extend$5.extendFlat; +var shapeTexttemplateAttrs$1 = template_attributes.shapeTexttemplateAttrs; +var shapeLabelTexttemplateVars$2 = label_texttemplate; +var attributes$L = overrideAll$7({ + newshape: { + visible: extendFlat$j({}, basePlotAttributes$1.visible, { + description: [ + "Determines whether or not new shape is visible.", + "If *legendonly*, the shape is not drawn,", + "but can appear as a legend item", + "(provided that the legend itself is visible)." + ].join(" ") + }), + showlegend: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether or not new", + "shape is shown in the legend." + ].join(" ") + }, + legend: extendFlat$j({}, basePlotAttributes$1.legend, { + description: [ + "Sets the reference to a legend to show new shape in.", + "References to these legends are *legend*, *legend2*, *legend3*, etc.", + "Settings for these legends are set in the layout, under", + "`layout.legend`, `layout.legend2`, etc." + ].join(" ") + }), + legendgroup: extendFlat$j({}, basePlotAttributes$1.legendgroup, { + description: [ + "Sets the legend group for new shape.", + "Traces and shapes part of the same legend group hide/show at the same time", + "when toggling legend items." + ].join(" ") + }), + legendgrouptitle: { + text: extendFlat$j({}, basePlotAttributes$1.legendgrouptitle.text, {}), + font: fontAttrs$e({ + description: [ + "Sets this legend group's title font." + ].join(" ") + }) + }, + legendrank: extendFlat$j({}, basePlotAttributes$1.legendrank, { + description: [ + "Sets the legend rank for new shape.", + "Items and groups with smaller ranks are presented on top/left side while", + "with *reversed* `legend.traceorder` they are on bottom/right side.", + "The default legendrank is 1000,", + "so that you can use ranks less than 1000 to place certain items before all unranked items,", + "and ranks greater than 1000 to go after all unranked items." + ].join(" ") + }), + legendwidth: extendFlat$j({}, basePlotAttributes$1.legendwidth, { + description: "Sets the width (in px or fraction) of the legend for new shape." + }), + line: { + color: { + valType: "color", + description: [ + "Sets the line color.", + "By default uses either dark grey or white", + "to increase contrast with background color." + ].join(" ") + }, + width: { + valType: "number", + min: 0, + dflt: 4, + description: "Sets the line width (in px)." + }, + dash: extendFlat$j({}, dash$6, { + dflt: "solid" + }) + }, + fillcolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + description: [ + "Sets the color filling new shapes' interior.", + "Please note that if using a fillcolor with alpha greater than half,", + "drag inside the active shape starts moving the shape underneath,", + "otherwise a new shape could be started over." + ].join(" ") + }, + fillrule: { + valType: "enumerated", + values: ["evenodd", "nonzero"], + dflt: "evenodd", + description: [ + "Determines the path's interior.", + "For more info please visit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule" + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 1, + description: "Sets the opacity of new shapes." + }, + layer: { + valType: "enumerated", + values: ["below", "above", "between"], + dflt: "above", + description: [ + "Specifies whether new shapes are drawn below gridlines (*below*),", + "between gridlines and traces (*between*) or above traces (*above*)." + ].join(" ") + }, + drawdirection: { + valType: "enumerated", + values: ["ortho", "horizontal", "vertical", "diagonal"], + dflt: "diagonal", + description: [ + "When `dragmode` is set to *drawrect*, *drawline* or *drawcircle*", + "this limits the drag to be horizontal, vertical or diagonal.", + "Using *diagonal* there is no limit e.g. in drawing lines in any direction.", + "*ortho* limits the draw to be either horizontal or vertical.", + "*horizontal* allows horizontal extend.", + "*vertical* allows vertical extend." + ].join(" ") + }, + name: extendFlat$j({}, basePlotAttributes$1.name, { + description: [ + "Sets new shape name.", + "The name appears as the legend item." + ].join(" ") + }), + label: { + text: { + valType: "string", + dflt: "", + description: [ + "Sets the text to display with the new shape.", + "It is also used for legend item if `name` is not provided." + ].join(" ") + }, + texttemplate: shapeTexttemplateAttrs$1({ newshape: true }, { keys: Object.keys(shapeLabelTexttemplateVars$2) }), + font: fontAttrs$e({ + description: "Sets the new shape label text font." + }), + textposition: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right", + "start", + "middle", + "end" + ], + description: [ + "Sets the position of the label text relative to the new shape.", + "Supported values for rectangles, circles and paths are", + "*top left*, *top center*, *top right*, *middle left*,", + "*middle center*, *middle right*, *bottom left*, *bottom center*,", + "and *bottom right*.", + "Supported values for lines are *start*, *middle*, and *end*.", + "Default: *middle center* for rectangles, circles, and paths; *middle* for lines." + ].join(" ") + }, + textangle: { + valType: "angle", + dflt: "auto", + description: [ + "Sets the angle at which the label text is drawn", + "with respect to the horizontal. For lines, angle *auto*", + "is the same angle as the line. For all other shapes,", + "angle *auto* is horizontal." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "auto", + description: [ + "Sets the label's horizontal position anchor", + "This anchor binds the specified `textposition` to the *left*, *center*", + "or *right* of the label text.", + "For example, if `textposition` is set to *top right* and", + "`xanchor` to *right* then the right-most portion of the", + "label text lines up with the right-most edge of the", + "new shape." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + description: [ + "Sets the label's vertical position anchor", + "This anchor binds the specified `textposition` to the *top*, *middle*", + "or *bottom* of the label text.", + "For example, if `textposition` is set to *top right* and", + "`yanchor` to *top* then the top-most portion of the", + "label text lines up with the top-most edge of the", + "new shape." + ].join(" ") + }, + padding: { + valType: "number", + dflt: 3, + min: 0, + description: "Sets padding (in px) between edge of label and edge of new shape." + } + } + }, + activeshape: { + fillcolor: { + valType: "color", + dflt: "rgb(255,0,255)", + description: "Sets the color filling the active shape' interior." + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 0.5, + description: "Sets the opacity of the active shape." + } + } +}, "none", "from-root"); +var dash$5 = attributes$M.dash; +var extendFlat$i = extend$5.extendFlat; +var attributes$K = { + newselection: { + mode: { + valType: "enumerated", + values: ["immediate", "gradual"], + dflt: "immediate", + editType: "none", + description: [ + "Describes how a new selection is created.", + "If `immediate`, a new selection is created after first mouse up.", + "If `gradual`, a new selection is not created after first mouse.", + "By adding to and subtracting from the initial selection,", + "this option allows declaring extra outlines of the selection." + ].join(" ") + }, + line: { + color: { + valType: "color", + editType: "none", + description: [ + "Sets the line color.", + "By default uses either dark grey or white", + "to increase contrast with background color." + ].join(" ") + }, + width: { + valType: "number", + min: 1, + dflt: 1, + editType: "none", + description: "Sets the line width (in px)." + }, + dash: extendFlat$i({}, dash$5, { + dflt: "dot", + editType: "none" + }), + editType: "none" + }, + // no drawdirection here noting that layout.selectdirection is used instead. + editType: "none" + }, + activeselection: { + fillcolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + editType: "none", + description: "Sets the color filling the active selection' interior." + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 0.5, + editType: "none", + description: "Sets the opacity of the active selection." + }, + editType: "none" + } +}; +var pad_attributes = function(opts) { + var editType = opts.editType; + return { + t: { + valType: "number", + dflt: 0, + editType, + description: "The amount of padding (in px) along the top of the component." + }, + r: { + valType: "number", + dflt: 0, + editType, + description: "The amount of padding (in px) on the right side of the component." + }, + b: { + valType: "number", + dflt: 0, + editType, + description: "The amount of padding (in px) along the bottom of the component." + }, + l: { + valType: "number", + dflt: 0, + editType, + description: "The amount of padding (in px) on the left side of the component." + }, + editType + }; +}; +var fontAttrs$d = font_attributes; +var animationAttrs$2 = animation_attributes; +var colorAttrs$6 = attributes$N; +var drawNewShapeAttrs = attributes$L; +var drawNewSelectionAttrs = attributes$K; +var padAttrs$2 = pad_attributes; +var extendFlat$h = extend$5.extendFlat; +var globalFont = fontAttrs$d({ + editType: "calc", + description: [ + "Sets the global font.", + "Note that fonts used in traces and other", + "layout components inherit from the global font." + ].join(" ") +}); +globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; +globalFont.size.dflt = 12; +globalFont.color.dflt = colorAttrs$6.defaultLine; +var layout_attributes$6 = { + font: globalFont, + title: { + text: { + valType: "string", + editType: "layoutstyle", + description: [ + "Sets the plot's title.", + "Note that before the existence of `title.text`, the title's", + "contents used to be defined as the `title` attribute itself.", + "This behavior has been deprecated." + ].join(" ") + }, + font: fontAttrs$d({ + editType: "layoutstyle", + description: [ + "Sets the title font.", + "Note that the title's font used to be customized", + "by the now deprecated `titlefont` attribute." + ].join(" ") + }), + subtitle: { + text: { + valType: "string", + editType: "layoutstyle", + description: "Sets the plot's subtitle." + }, + font: fontAttrs$d({ + editType: "layoutstyle", + description: "Sets the subtitle font." + }), + editType: "layoutstyle" + }, + xref: { + valType: "enumerated", + dflt: "container", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `x` refers to.", + "*container* spans the entire `width` of the plot.", + "*paper* refers to the width of the plotting area only." + ].join(" ") + }, + yref: { + valType: "enumerated", + dflt: "container", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `y` refers to.", + "*container* spans the entire `height` of the plot.", + "*paper* refers to the height of the plotting area only." + ].join(" ") + }, + x: { + valType: "number", + min: 0, + max: 1, + dflt: 0.5, + editType: "layoutstyle", + description: [ + "Sets the x position with respect to `xref` in normalized", + "coordinates from *0* (left) to *1* (right)." + ].join(" ") + }, + y: { + valType: "number", + min: 0, + max: 1, + dflt: "auto", + editType: "layoutstyle", + description: [ + "Sets the y position with respect to `yref` in normalized", + "coordinates from *0* (bottom) to *1* (top).", + "*auto* places the baseline of the title onto the", + "vertical center of the top margin." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + dflt: "auto", + values: ["auto", "left", "center", "right"], + editType: "layoutstyle", + description: [ + "Sets the title's horizontal alignment with respect to its x position.", + "*left* means that the title starts at x,", + "*right* means that the title ends at x", + "and *center* means that the title's center is at x.", + "*auto* divides `xref` by three and calculates the `xanchor`", + "value automatically based on the value of `x`." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + dflt: "auto", + values: ["auto", "top", "middle", "bottom"], + editType: "layoutstyle", + description: [ + "Sets the title's vertical alignment with respect to its y position.", + "*top* means that the title's cap line is at y,", + "*bottom* means that the title's baseline is at y", + "and *middle* means that the title's midline is at y.", + "*auto* divides `yref` by three and calculates the `yanchor`", + "value automatically based on the value of `y`." + ].join(" ") + }, + pad: extendFlat$h(padAttrs$2({ editType: "layoutstyle" }), { + description: [ + "Sets the padding of the title.", + "Each padding value only applies when the corresponding", + "`xanchor`/`yanchor` value is set accordingly. E.g. for left", + "padding to take effect, `xanchor` must be set to *left*.", + "The same rule applies if `xanchor`/`yanchor` is determined automatically.", + "Padding is muted if the respective anchor value is *middle*/*center*." + ].join(" ") + }), + automargin: { + valType: "boolean", + dflt: false, + editType: "plot", + description: [ + "Determines whether the title can automatically push the figure margins.", + "If `yref='paper'` then the margin will expand to ensure that the title doesn’t", + "overlap with the edges of the container. If `yref='container'` then the margins", + "will ensure that the title doesn’t overlap with the plot area, tick labels,", + "and axis titles. If `automargin=true` and the margins need to be expanded,", + "then y will be set to a default 1 and yanchor will be set to an appropriate", + "default to ensure that minimal margin space is needed. Note that when `yref='paper'`,", + "only 1 or 0 are allowed y values. Invalid values will be reset to the default 1." + ].join(" ") + }, + editType: "layoutstyle" + }, + uniformtext: { + mode: { + valType: "enumerated", + values: [false, "hide", "show"], + dflt: false, + editType: "plot", + description: [ + "Determines how the font size for various text", + "elements are uniformed between each trace type.", + "If the computed text sizes were smaller than", + "the minimum size defined by `uniformtext.minsize`", + "using *hide* option hides the text; and", + "using *show* option shows the text without further downscaling.", + "Please note that if the size defined by `minsize` is greater than", + "the font size defined by trace, then the `minsize` is used." + ].join(" ") + }, + minsize: { + valType: "number", + min: 0, + dflt: 0, + editType: "plot", + description: [ + "Sets the minimum text size between traces of the same type." + ].join(" ") + }, + editType: "plot" + }, + autosize: { + valType: "boolean", + dflt: false, + // autosize, width, and height get special editType treatment in _relayout + // so we can handle noop resizes more efficiently + editType: "none", + description: [ + "Determines whether or not a layout width or height", + "that has been left undefined by the user", + "is initialized on each relayout.", + "Note that, regardless of this attribute,", + "an undefined layout width or height", + "is always initialized on the first call to plot." + ].join(" ") + }, + width: { + valType: "number", + min: 10, + dflt: 700, + editType: "plot", + description: [ + "Sets the plot's width (in px)." + ].join(" ") + }, + height: { + valType: "number", + min: 10, + dflt: 450, + editType: "plot", + description: [ + "Sets the plot's height (in px)." + ].join(" ") + }, + minreducedwidth: { + valType: "number", + min: 2, + dflt: 64, + editType: "plot", + description: "Minimum width of the plot with margin.automargin applied (in px)" + }, + minreducedheight: { + valType: "number", + min: 2, + dflt: 64, + editType: "plot", + description: "Minimum height of the plot with margin.automargin applied (in px)" + }, + margin: { + l: { + valType: "number", + min: 0, + dflt: 80, + editType: "plot", + description: "Sets the left margin (in px)." + }, + r: { + valType: "number", + min: 0, + dflt: 80, + editType: "plot", + description: "Sets the right margin (in px)." + }, + t: { + valType: "number", + min: 0, + dflt: 100, + editType: "plot", + description: "Sets the top margin (in px)." + }, + b: { + valType: "number", + min: 0, + dflt: 80, + editType: "plot", + description: "Sets the bottom margin (in px)." + }, + pad: { + valType: "number", + min: 0, + dflt: 0, + editType: "plot", + description: [ + "Sets the amount of padding (in px)", + "between the plotting area and the axis lines" + ].join(" ") + }, + autoexpand: { + valType: "boolean", + dflt: true, + editType: "plot", + description: [ + "Turns on/off margin expansion computations.", + "Legends, colorbars, updatemenus, sliders, axis rangeselector and rangeslider", + "are allowed to push the margins by defaults." + ].join(" ") + }, + editType: "plot" + }, + computed: { + valType: "any", + editType: "none", + description: [ + "Placeholder for exporting automargin-impacting values namely", + "`margin.t`, `margin.b`, `margin.l` and `margin.r` in *full-json* mode." + ].join(" ") + }, + paper_bgcolor: { + valType: "color", + dflt: colorAttrs$6.background, + editType: "plot", + description: "Sets the background color of the paper where the graph is drawn." + }, + plot_bgcolor: { + // defined here, but set in cartesian.supplyLayoutDefaults + // because it needs to know if there are (2D) axes or not + valType: "color", + dflt: colorAttrs$6.background, + editType: "layoutstyle", + description: [ + "Sets the background color of the plotting area in-between x and y axes." + ].join(" ") + }, + autotypenumbers: { + valType: "enumerated", + values: ["convert types", "strict"], + dflt: "convert types", + editType: "calc", + description: [ + "Using *strict* a numeric string in trace data is not converted to a number.", + "Using *convert types* a numeric string in trace data may be", + "treated as a number during automatic axis `type` detection.", + "This is the default value; however it could be overridden for individual axes." + ].join(" ") + }, + separators: { + valType: "string", + editType: "plot", + description: [ + "Sets the decimal and thousand separators.", + "For example, *. * puts a '.' before decimals and a space", + "between thousands. In English locales, dflt is *.,* but", + "other locales may alter this default." + ].join(" ") + }, + hidesources: { + valType: "boolean", + dflt: false, + editType: "plot", + description: [ + "Determines whether or not a text link citing the data source is", + "placed at the bottom-right cored of the figure.", + "Has only an effect only on graphs that have been generated via", + "forked graphs from the Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise)." + ].join(" ") + }, + showlegend: { + // handled in legend.supplyLayoutDefaults + // but included here because it's not in the legend object + valType: "boolean", + editType: "legend", + description: [ + "Determines whether or not a legend is drawn.", + "Default is `true` if there is a trace to show and any of these:", + "a) Two or more traces would by default be shown in the legend.", + "b) One pie trace is shown in the legend.", + "c) One trace is explicitly given with `showlegend: true`." + ].join(" ") + }, + colorway: { + valType: "colorlist", + dflt: colorAttrs$6.defaults, + editType: "calc", + description: "Sets the default trace colors." + }, + datarevision: { + valType: "any", + editType: "calc", + description: [ + "If provided, a changed value tells `Plotly.react` that", + "one or more data arrays has changed. This way you can modify", + "arrays in-place rather than making a complete new copy for an", + "incremental change.", + "If NOT provided, `Plotly.react` assumes that data arrays are", + "being treated as immutable, thus any data array with a", + "different identity from its predecessor contains new data." + ].join(" ") + }, + uirevision: { + valType: "any", + editType: "none", + description: [ + "Used to allow user interactions with the plot to persist after", + "`Plotly.react` calls that are unaware of these interactions.", + "If `uirevision` is omitted, or if it is given and it changed from", + "the previous `Plotly.react` call, the exact new figure is used.", + "If `uirevision` is truthy and did NOT change, any attribute", + "that has been affected by user interactions and did not receive a", + "different value in the new figure will keep the interaction value.", + "`layout.uirevision` attribute serves as the default for", + "`uirevision` attributes in various sub-containers. For finer", + "control you can set these sub-attributes directly. For example,", + "if your app separately controls the data on the x and y axes you", + "might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`.", + "Then if only the y data is changed, you can update", + "`yaxis.uirevision=*quantity*` and the y axis range will reset but", + "the x axis range will retain any user-driven zoom." + ].join(" ") + }, + editrevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of user-driven changes in `editable: true`", + "configuration, other than trace names and axis titles.", + "Defaults to `layout.uirevision`." + ].join(" ") + }, + selectionrevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of user-driven changes in selected points", + "from all traces." + ].join(" ") + }, + template: { + valType: "any", + editType: "calc", + description: [ + "Default attributes to be applied to the plot. Templates can be", + "created from existing plots using `Plotly.makeTemplate`, or", + "created manually. They should be objects with format:", + "`{layout: layoutTemplate, data: {[type]: [traceTemplate, ...]}, ...}`", + "`layoutTemplate` and `traceTemplate` are objects matching the", + "attribute structure of `layout` and a data trace. ", + "Trace templates are applied cyclically to traces of each type.", + "Container arrays (eg `annotations`) have special handling:", + "An object ending in `defaults` (eg `annotationdefaults`) is applied", + "to each array item. But if an item has a `templateitemname` key", + "we look in the template array for an item with matching `name` and", + "apply that instead. If no matching `name` is found we mark the item", + "invisible. Any named template item not referenced is appended to", + "the end of the array, so you can use this for a watermark annotation", + "or a logo image, for example. To omit one of these items on the plot,", + "make an item with matching `templateitemname` and `visible: false`." + ].join(" ") + }, + newshape: drawNewShapeAttrs.newshape, + activeshape: drawNewShapeAttrs.activeshape, + newselection: drawNewSelectionAttrs.newselection, + activeselection: drawNewSelectionAttrs.activeselection, + meta: { + valType: "any", + arrayOk: true, + editType: "plot", + description: [ + "Assigns extra meta information that can be used in various `text` attributes.", + "Attributes such as the graph, axis and colorbar `title.text`, annotation `text`", + "`trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text", + "all support `meta`. One can access `meta` fields using template strings:", + "`%{meta[i]}` where `i` is the index of the `meta`", + "item in question.", + "`meta` can also be an object for example `{key: value}` which can be accessed", + "%{meta[key]}." + ].join(" ") + }, + transition: extendFlat$h({}, animationAttrs$2.transition, { + description: [ + "Sets transition options used during Plotly.react updates." + ].join(" "), + editType: "none" + }), + _deprecated: { + title: { + valType: "string", + editType: "layoutstyle", + description: [ + "Value of `title` is no longer a simple *string* but a set of sub-attributes.", + "To set the contents of the title, please use `title.text` now." + ].join(" ") + }, + titlefont: fontAttrs$d({ + editType: "layoutstyle", + description: [ + "Former `titlefont` is now the sub-attribute `font` of `title`.", + "To customize title font properties, please use `title.font` now." + ].join(" ") + }) + } +}; +(function(exports2) { + var Loggers2 = loggersExports; + var noop3 = noop$2; + var pushUnique3 = push_unique; + var isPlainObject3 = is_plain_object; + var addStyleRule2 = dom.addStyleRule; + var ExtendModule = extend$5; + var basePlotAttributes2 = attributes$O; + var baseLayoutAttributes = layout_attributes$6; + var extendFlat2 = ExtendModule.extendFlat; + var extendDeepAll2 = ExtendModule.extendDeepAll; + exports2.modules = {}; + exports2.allCategories = {}; + exports2.allTypes = []; + exports2.subplotsRegistry = {}; + exports2.transformsRegistry = {}; + exports2.componentsRegistry = {}; + exports2.layoutArrayContainers = []; + exports2.layoutArrayRegexes = []; + exports2.traceLayoutAttributes = {}; + exports2.localeRegistry = {}; + exports2.apiMethodRegistry = {}; + exports2.collectableSubplotTypes = null; + exports2.register = function register(_modules) { + exports2.collectableSubplotTypes = null; + if (!_modules) { + throw new Error("No argument passed to Plotly.register."); + } else if (_modules && !Array.isArray(_modules)) { + _modules = [_modules]; + } + for (var i = 0; i < _modules.length; i++) { + var newModule = _modules[i]; + if (!newModule) { + throw new Error("Invalid module was attempted to be registered!"); + } + switch (newModule.moduleType) { + case "trace": + registerTraceModule(newModule); + break; + case "transform": + registerTransformModule(newModule); + break; + case "component": + registerComponentModule(newModule); + break; + case "locale": + registerLocale(newModule); + break; + case "apiMethod": + var name2 = newModule.name; + exports2.apiMethodRegistry[name2] = newModule.fn; + break; + default: + throw new Error("Invalid module was attempted to be registered!"); + } + } + }; + exports2.getModule = function(trace) { + var _module = exports2.modules[getTraceType(trace)]; + if (!_module) return false; + return _module._module; + }; + exports2.traceIs = function(traceType, category2) { + traceType = getTraceType(traceType); + if (traceType === "various") return false; + var _module = exports2.modules[traceType]; + if (!_module) { + if (traceType) { + Loggers2.log("Unrecognized trace type " + traceType + "."); + } + _module = exports2.modules[basePlotAttributes2.type.dflt]; + } + return !!_module.categories[category2]; + }; + exports2.getTransformIndices = function(data, type) { + var indices = []; + var transforms = data.transforms || []; + for (var i = 0; i < transforms.length; i++) { + if (transforms[i].type === type) { + indices.push(i); + } + } + return indices; + }; + exports2.hasTransform = function(data, type) { + var transforms = data.transforms || []; + for (var i = 0; i < transforms.length; i++) { + if (transforms[i].type === type) { + return true; + } + } + return false; + }; + exports2.getComponentMethod = function(name2, method) { + var _module = exports2.componentsRegistry[name2]; + if (!_module) return noop3; + return _module[method] || noop3; + }; + exports2.call = function() { + var name2 = arguments[0]; + var args = [].slice.call(arguments, 1); + return exports2.apiMethodRegistry[name2].apply(null, args); + }; + function registerTraceModule(_module) { + var thisType = _module.name; + var categoriesIn = _module.categories; + var meta = _module.meta; + if (exports2.modules[thisType]) { + Loggers2.log("Type " + thisType + " already registered"); + return; + } + if (!exports2.subplotsRegistry[_module.basePlotModule.name]) { + registerSubplot(_module.basePlotModule); + } + var categoryObj = {}; + for (var i = 0; i < categoriesIn.length; i++) { + categoryObj[categoriesIn[i]] = true; + exports2.allCategories[categoriesIn[i]] = true; + } + exports2.modules[thisType] = { + _module, + categories: categoryObj + }; + if (meta && Object.keys(meta).length) { + exports2.modules[thisType].meta = meta; + } + exports2.allTypes.push(thisType); + for (var componentName in exports2.componentsRegistry) { + mergeComponentAttrsToTrace(componentName, thisType); + } + if (_module.layoutAttributes) { + extendFlat2(exports2.traceLayoutAttributes, _module.layoutAttributes); + } + var basePlotModule = _module.basePlotModule; + var bpmName = basePlotModule.name; + if (bpmName === "mapbox") { + var styleRules = basePlotModule.constants.styleRules; + for (var k in styleRules) { + addStyleRule2(".js-plotly-plot .plotly .mapboxgl-" + k, styleRules[k]); + } + } + if ((bpmName === "geo" || bpmName === "mapbox" || bpmName === "map") && window.PlotlyGeoAssets === void 0) { + window.PlotlyGeoAssets = { topojson: {} }; + } + } + function registerSubplot(_module) { + var plotType = _module.name; + if (exports2.subplotsRegistry[plotType]) { + Loggers2.log("Plot type " + plotType + " already registered."); + return; + } + findArrayRegexps(_module); + exports2.subplotsRegistry[plotType] = _module; + for (var componentName in exports2.componentsRegistry) { + mergeComponentAttrsToSubplot(componentName, _module.name); + } + } + function registerComponentModule(_module) { + if (typeof _module.name !== "string") { + throw new Error("Component module *name* must be a string."); + } + var name2 = _module.name; + exports2.componentsRegistry[name2] = _module; + if (_module.layoutAttributes) { + if (_module.layoutAttributes._isLinkedToArray) { + pushUnique3(exports2.layoutArrayContainers, name2); + } + findArrayRegexps(_module); + } + for (var traceType in exports2.modules) { + mergeComponentAttrsToTrace(name2, traceType); + } + for (var subplotName in exports2.subplotsRegistry) { + mergeComponentAttrsToSubplot(name2, subplotName); + } + for (var transformType in exports2.transformsRegistry) { + mergeComponentAttrsToTransform(name2, transformType); + } + if (_module.schema && _module.schema.layout) { + extendDeepAll2(baseLayoutAttributes, _module.schema.layout); + } + } + function registerTransformModule(_module) { + if (typeof _module.name !== "string") { + throw new Error("Transform module *name* must be a string."); + } + var prefix = "Transform module " + _module.name; + var hasTransform = typeof _module.transform === "function"; + var hasCalcTransform = typeof _module.calcTransform === "function"; + if (!hasTransform && !hasCalcTransform) { + throw new Error(prefix + " is missing a *transform* or *calcTransform* method."); + } + if (hasTransform && hasCalcTransform) { + Loggers2.log([ + prefix + " has both a *transform* and *calcTransform* methods.", + "Please note that all *transform* methods are executed", + "before all *calcTransform* methods." + ].join(" ")); + } + if (!isPlainObject3(_module.attributes)) { + Loggers2.log(prefix + " registered without an *attributes* object."); + } + if (typeof _module.supplyDefaults !== "function") { + Loggers2.log(prefix + " registered without a *supplyDefaults* method."); + } + exports2.transformsRegistry[_module.name] = _module; + for (var componentName in exports2.componentsRegistry) { + mergeComponentAttrsToTransform(componentName, _module.name); + } + } + function registerLocale(_module) { + var locale2 = _module.name; + var baseLocale = locale2.split("-")[0]; + var newDict = _module.dictionary; + var newFormat = _module.format; + var hasDict = newDict && Object.keys(newDict).length; + var hasFormat = newFormat && Object.keys(newFormat).length; + var locales = exports2.localeRegistry; + var localeObj = locales[locale2]; + if (!localeObj) locales[locale2] = localeObj = {}; + if (baseLocale !== locale2) { + var baseLocaleObj = locales[baseLocale]; + if (!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {}; + if (hasDict && baseLocaleObj.dictionary === localeObj.dictionary) { + baseLocaleObj.dictionary = newDict; + } + if (hasFormat && baseLocaleObj.format === localeObj.format) { + baseLocaleObj.format = newFormat; + } + } + if (hasDict) localeObj.dictionary = newDict; + if (hasFormat) localeObj.format = newFormat; + } + function findArrayRegexps(_module) { + if (_module.layoutAttributes) { + var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; + if (arrayAttrRegexps) { + for (var i = 0; i < arrayAttrRegexps.length; i++) { + pushUnique3(exports2.layoutArrayRegexes, arrayAttrRegexps[i]); + } + } + } + } + function mergeComponentAttrsToTrace(componentName, traceType) { + var componentSchema = exports2.componentsRegistry[componentName].schema; + if (!componentSchema || !componentSchema.traces) return; + var traceAttrs = componentSchema.traces[traceType]; + if (traceAttrs) { + extendDeepAll2(exports2.modules[traceType]._module.attributes, traceAttrs); + } + } + function mergeComponentAttrsToTransform(componentName, transformType) { + var componentSchema = exports2.componentsRegistry[componentName].schema; + if (!componentSchema || !componentSchema.transforms) return; + var transformAttrs = componentSchema.transforms[transformType]; + if (transformAttrs) { + extendDeepAll2(exports2.transformsRegistry[transformType].attributes, transformAttrs); + } + } + function mergeComponentAttrsToSubplot(componentName, subplotName) { + var componentSchema = exports2.componentsRegistry[componentName].schema; + if (!componentSchema || !componentSchema.subplots) return; + var subplotModule = exports2.subplotsRegistry[subplotName]; + var subplotAttrs = subplotModule.layoutAttributes; + var subplotAttr = subplotModule.attr === "subplot" ? subplotModule.name : subplotModule.attr; + if (Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; + var componentLayoutAttrs = componentSchema.subplots[subplotAttr]; + if (subplotAttrs && componentLayoutAttrs) { + extendDeepAll2(subplotAttrs, componentLayoutAttrs); + } + } + function getTraceType(traceType) { + if (typeof traceType === "object") traceType = traceType.type; + return traceType; + } +})(registry); +(function(exports2) { + var timeFormat2 = require$$1$1.timeFormat; + var isNumeric2 = fastIsnumeric; + var Loggers2 = loggersExports; + var mod2 = mod_1.mod; + var constants2 = numerical; + var BADNUM2 = constants2.BADNUM; + var ONEDAY2 = constants2.ONEDAY; + var ONEHOUR2 = constants2.ONEHOUR; + var ONEMIN2 = constants2.ONEMIN; + var ONESEC2 = constants2.ONESEC; + var EPOCHJD = constants2.EPOCHJD; + var Registry2 = registry; + var utcFormat2 = require$$1$1.utcFormat; + var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m; + var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m; + var YFIRST = (/* @__PURE__ */ new Date()).getFullYear() - 70; + function isWorldCalendar(calendar) { + return calendar && Registry2.componentsRegistry.calendars && typeof calendar === "string" && calendar !== "gregorian"; + } + exports2.dateTick0 = function(calendar, dayOfWeek) { + var tick02 = _dateTick0(calendar, !!dayOfWeek); + if (dayOfWeek < 2) return tick02; + var v = exports2.dateTime2ms(tick02, calendar); + v += ONEDAY2 * (dayOfWeek - 1); + return exports2.ms2DateTime(v, 0, calendar); + }; + function _dateTick0(calendar, sunday2) { + if (isWorldCalendar(calendar)) { + return sunday2 ? Registry2.getComponentMethod("calendars", "CANONICAL_SUNDAY")[calendar] : Registry2.getComponentMethod("calendars", "CANONICAL_TICK")[calendar]; + } else { + return sunday2 ? "2000-01-02" : "2000-01-01"; + } + } + exports2.dfltRange = function(calendar) { + if (isWorldCalendar(calendar)) { + return Registry2.getComponentMethod("calendars", "DFLTRANGE")[calendar]; + } else { + return ["2000-01-01", "2001-01-01"]; + } + }; + exports2.isJSDate = function(v) { + return typeof v === "object" && v !== null && typeof v.getTime === "function"; + }; + var MIN_MS, MAX_MS; + exports2.dateTime2ms = function(s, calendar) { + if (exports2.isJSDate(s)) { + var tzOffset = s.getTimezoneOffset() * ONEMIN2; + var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN2 + (s.getUTCSeconds() - s.getSeconds()) * ONESEC2 + (s.getUTCMilliseconds() - s.getMilliseconds()); + if (offsetTweak) { + var comb = 3 * ONEMIN2; + tzOffset = tzOffset - comb / 2 + mod2(offsetTweak - tzOffset + comb / 2, comb); + } + s = Number(s) - tzOffset; + if (s >= MIN_MS && s <= MAX_MS) return s; + return BADNUM2; + } + if (typeof s !== "string" && typeof s !== "number") return BADNUM2; + s = String(s); + var isWorld = isWorldCalendar(calendar); + var s0 = s.charAt(0); + if (isWorld && (s0 === "G" || s0 === "g")) { + s = s.substr(1); + calendar = ""; + } + var isChinese = isWorld && calendar.substr(0, 7) === "chinese"; + var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); + if (!match) return BADNUM2; + var y = match[1]; + var m = match[3] || "1"; + var d = Number(match[5] || 1); + var H = Number(match[7] || 0); + var M = Number(match[9] || 0); + var S = Number(match[11] || 0); + if (isWorld) { + if (y.length === 2) return BADNUM2; + y = Number(y); + var cDate; + try { + var calInstance = Registry2.getComponentMethod("calendars", "getCal")(calendar); + if (isChinese) { + var isIntercalary = m.charAt(m.length - 1) === "i"; + m = parseInt(m, 10); + cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d); + } else { + cDate = calInstance.newDate(y, Number(m), d); + } + } catch (e) { + return BADNUM2; + } + if (!cDate) return BADNUM2; + return (cDate.toJD() - EPOCHJD) * ONEDAY2 + H * ONEHOUR2 + M * ONEMIN2 + S * ONESEC2; + } + if (y.length === 2) { + y = (Number(y) + 2e3 - YFIRST) % 100 + YFIRST; + } else y = Number(y); + m -= 1; + var date2 = new Date(Date.UTC(2e3, m, d, H, M)); + date2.setUTCFullYear(y); + if (date2.getUTCMonth() !== m) return BADNUM2; + if (date2.getUTCDate() !== d) return BADNUM2; + return date2.getTime() + S * ONESEC2; + }; + MIN_MS = exports2.MIN_MS = exports2.dateTime2ms("-9999"); + MAX_MS = exports2.MAX_MS = exports2.dateTime2ms("9999-12-31 23:59:59.9999"); + exports2.isDateTime = function(s, calendar) { + return exports2.dateTime2ms(s, calendar) !== BADNUM2; + }; + function lpad(val, digits) { + return String(val + Math.pow(10, digits)).substr(1); + } + var NINETYDAYS = 90 * ONEDAY2; + var THREEHOURS = 3 * ONEHOUR2; + var FIVEMIN = 5 * ONEMIN2; + exports2.ms2DateTime = function(ms, r, calendar) { + if (typeof ms !== "number" || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM2; + if (!r) r = 0; + var msecTenths = Math.floor(mod2(ms + 0.05, 1) * 10); + var msRounded = Math.round(ms - msecTenths / 10); + var dateStr, h, m, s, msec10, d; + if (isWorldCalendar(calendar)) { + var dateJD = Math.floor(msRounded / ONEDAY2) + EPOCHJD; + var timeMs = Math.floor(mod2(ms, ONEDAY2)); + try { + dateStr = Registry2.getComponentMethod("calendars", "getCal")(calendar).fromJD(dateJD).formatDate("yyyy-mm-dd"); + } catch (e) { + dateStr = utcFormat2("G%Y-%m-%d")(new Date(msRounded)); + } + if (dateStr.charAt(0) === "-") { + while (dateStr.length < 11) dateStr = "-0" + dateStr.substr(1); + } else { + while (dateStr.length < 10) dateStr = "0" + dateStr; + } + h = r < NINETYDAYS ? Math.floor(timeMs / ONEHOUR2) : 0; + m = r < NINETYDAYS ? Math.floor(timeMs % ONEHOUR2 / ONEMIN2) : 0; + s = r < THREEHOURS ? Math.floor(timeMs % ONEMIN2 / ONESEC2) : 0; + msec10 = r < FIVEMIN ? timeMs % ONESEC2 * 10 + msecTenths : 0; + } else { + d = new Date(msRounded); + dateStr = utcFormat2("%Y-%m-%d")(d); + h = r < NINETYDAYS ? d.getUTCHours() : 0; + m = r < NINETYDAYS ? d.getUTCMinutes() : 0; + s = r < THREEHOURS ? d.getUTCSeconds() : 0; + msec10 = r < FIVEMIN ? d.getUTCMilliseconds() * 10 + msecTenths : 0; + } + return includeTime(dateStr, h, m, s, msec10); + }; + exports2.ms2DateTimeLocal = function(ms) { + if (!(ms >= MIN_MS + ONEDAY2 && ms <= MAX_MS - ONEDAY2)) return BADNUM2; + var msecTenths = Math.floor(mod2(ms + 0.05, 1) * 10); + var d = new Date(Math.round(ms - msecTenths / 10)); + var dateStr = timeFormat2("%Y-%m-%d")(d); + var h = d.getHours(); + var m = d.getMinutes(); + var s = d.getSeconds(); + var msec10 = d.getUTCMilliseconds() * 10 + msecTenths; + return includeTime(dateStr, h, m, s, msec10); + }; + function includeTime(dateStr, h, m, s, msec10) { + if (h || m || s || msec10) { + dateStr += " " + lpad(h, 2) + ":" + lpad(m, 2); + if (s || msec10) { + dateStr += ":" + lpad(s, 2); + if (msec10) { + var digits = 4; + while (msec10 % 10 === 0) { + digits -= 1; + msec10 /= 10; + } + dateStr += "." + lpad(msec10, digits); + } + } + } + return dateStr; + } + exports2.cleanDate = function(v, dflt, calendar) { + if (v === BADNUM2) return dflt; + if (exports2.isJSDate(v) || typeof v === "number" && isFinite(v)) { + if (isWorldCalendar(calendar)) { + Loggers2.error("JS Dates and milliseconds are incompatible with world calendars", v); + return dflt; + } + v = exports2.ms2DateTimeLocal(+v); + if (!v && dflt !== void 0) return dflt; + } else if (!exports2.isDateTime(v, calendar)) { + Loggers2.error("unrecognized date", v); + return dflt; + } + return v; + }; + var fracMatch = /%\d?f/g; + var halfYearMatch = /%h/g; + var quarterToHalfYear = { + 1: "1", + 2: "1", + 3: "2", + 4: "2" + }; + function modDateFormat(fmt, x, formatter, calendar) { + fmt = fmt.replace(fracMatch, function(match) { + var digits = Math.min(+match.charAt(1) || 6, 6); + var fracSecs = (x / 1e3 % 1 + 2).toFixed(digits).substr(2).replace(/0+$/, "") || "0"; + return fracSecs; + }); + var d = new Date(Math.floor(x + 0.05)); + fmt = fmt.replace(halfYearMatch, function() { + return quarterToHalfYear[formatter("%q")(d)]; + }); + if (isWorldCalendar(calendar)) { + try { + fmt = Registry2.getComponentMethod("calendars", "worldCalFmt")(fmt, x, calendar); + } catch (e) { + return "Invalid"; + } + } + return formatter(fmt)(d); + } + var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; + function formatTime(x, tr) { + var timePart = mod2(x + 0.05, ONEDAY2); + var timeStr = lpad(Math.floor(timePart / ONEHOUR2), 2) + ":" + lpad(mod2(Math.floor(timePart / ONEMIN2), 60), 2); + if (tr !== "M") { + if (!isNumeric2(tr)) tr = 0; + var sec = Math.min(mod2(x / ONESEC2, 60), MAXSECONDS[tr]); + var secStr = (100 + sec).toFixed(tr).substr(1); + if (tr > 0) { + secStr = secStr.replace(/0+$/, "").replace(/[\.]$/, ""); + } + timeStr += ":" + secStr; + } + return timeStr; + } + exports2.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { + calendar = isWorldCalendar(calendar) && calendar; + if (!fmt) { + if (tr === "y") fmt = extraFormat.year; + else if (tr === "m") fmt = extraFormat.month; + else if (tr === "d") { + fmt = extraFormat.dayMonth + "\n" + extraFormat.year; + } else { + return formatTime(x, tr) + "\n" + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar); + } + } + return modDateFormat(fmt, x, formatter, calendar); + }; + var THREEDAYS = 3 * ONEDAY2; + exports2.incrementMonth = function(ms, dMonth, calendar) { + calendar = isWorldCalendar(calendar) && calendar; + var timeMs = mod2(ms, ONEDAY2); + ms = Math.round(ms - timeMs); + if (calendar) { + try { + var dateJD = Math.round(ms / ONEDAY2) + EPOCHJD; + var calInstance = Registry2.getComponentMethod("calendars", "getCal")(calendar); + var cDate = calInstance.fromJD(dateJD); + if (dMonth % 12) calInstance.add(cDate, dMonth, "m"); + else calInstance.add(cDate, dMonth / 12, "y"); + return (cDate.toJD() - EPOCHJD) * ONEDAY2 + timeMs; + } catch (e) { + Loggers2.error("invalid ms " + ms + " in calendar " + calendar); + } + } + var y = new Date(ms + THREEDAYS); + return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS; + }; + exports2.findExactDates = function(data, calendar) { + var exactYears = 0; + var exactMonths = 0; + var exactDays = 0; + var blankCount = 0; + var d; + var di; + var calInstance = isWorldCalendar(calendar) && Registry2.getComponentMethod("calendars", "getCal")(calendar); + for (var i = 0; i < data.length; i++) { + di = data[i]; + if (!isNumeric2(di)) { + blankCount++; + continue; + } + if (di % ONEDAY2) continue; + if (calInstance) { + try { + d = calInstance.fromJD(di / ONEDAY2 + EPOCHJD); + if (d.day() === 1) { + if (d.month() === 1) exactYears++; + else exactMonths++; + } else exactDays++; + } catch (e) { + } + } else { + d = new Date(di); + if (d.getUTCDate() === 1) { + if (d.getUTCMonth() === 0) exactYears++; + else exactMonths++; + } else exactDays++; + } + } + exactMonths += exactYears; + exactDays += exactMonths; + var dataCount = data.length - blankCount; + return { + exactYears: exactYears / dataCount, + exactMonths: exactMonths / dataCount, + exactDays: exactDays / dataCount + }; + }; +})(dates); +var search$1 = {}; +var identity$2 = function identity(d) { + return d; +}; +(function(exports2) { + var isNumeric2 = fastIsnumeric; + var loggers2 = loggersExports; + var identity3 = identity$2; + var BADNUM2 = numerical.BADNUM; + var roundingError = 1e-9; + exports2.findBin = function(val, bins, linelow) { + if (isNumeric2(bins.start)) { + return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError); + } else { + var n1 = 0; + var n2 = bins.length; + var c = 0; + var binSize = n2 > 1 ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1; + var n, test; + if (binSize >= 0) { + test = linelow ? lessThan : lessOrEqual2; + } else { + test = linelow ? greaterOrEqual2 : greaterThan; + } + val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1); + while (n1 < n2 && c++ < 100) { + n = Math.floor((n1 + n2) / 2); + if (test(bins[n], val)) n1 = n + 1; + else n2 = n; + } + if (c > 90) loggers2.log("Long binary search..."); + return n1 - 1; + } + }; + function lessThan(a, b) { + return a < b; + } + function lessOrEqual2(a, b) { + return a <= b; + } + function greaterThan(a, b) { + return a > b; + } + function greaterOrEqual2(a, b) { + return a >= b; + } + exports2.sorterAsc = function(a, b) { + return a - b; + }; + exports2.sorterDes = function(a, b) { + return b - a; + }; + exports2.distinctVals = function(valsIn) { + var vals = valsIn.slice(); + vals.sort(exports2.sorterAsc); + var last; + for (last = vals.length - 1; last > -1; last--) { + if (vals[last] !== BADNUM2) break; + } + var minDiff = vals[last] - vals[0] || 1; + var errDiff = minDiff / (last || 1) / 1e4; + var newVals = []; + var preV; + for (var i = 0; i <= last; i++) { + var v = vals[i]; + var diff = v - preV; + if (preV === void 0) { + newVals.push(v); + preV = v; + } else if (diff > errDiff) { + minDiff = Math.min(minDiff, diff); + newVals.push(v); + preV = v; + } + } + return { vals: newVals, minDiff }; + }; + exports2.roundUp = function(val, arrayIn, reverse) { + var low = 0; + var high = arrayIn.length - 1; + var mid; + var c = 0; + var dlow = reverse ? 0 : 1; + var dhigh = reverse ? 1 : 0; + var rounded = reverse ? Math.ceil : Math.floor; + while (low < high && c++ < 100) { + mid = rounded((low + high) / 2); + if (arrayIn[mid] <= val) low = mid + dlow; + else high = mid - dhigh; + } + return arrayIn[low]; + }; + exports2.sort = function(array2, sortFn) { + var notOrdered = 0; + var notReversed = 0; + for (var i = 1; i < array2.length; i++) { + var pairOrder = sortFn(array2[i], array2[i - 1]); + if (pairOrder < 0) notOrdered = 1; + else if (pairOrder > 0) notReversed = 1; + if (notOrdered && notReversed) return array2.sort(sortFn); + } + return notReversed ? array2 : array2.reverse(); + }; + exports2.findIndexOfMin = function(arr, fn) { + fn = fn || identity3; + var min = Infinity; + var ind; + for (var i = 0; i < arr.length; i++) { + var v = fn(arr[i]); + if (v < min) { + min = v; + ind = i; + } + } + return ind; + }; +})(search$1); +var sort_object_keys = function sortObjectKeys(obj) { + return Object.keys(obj).sort(); +}; +var stats = {}; +(function(exports2) { + var isNumeric2 = fastIsnumeric; + var isArrayOrTypedArray2 = array$2.isArrayOrTypedArray; + exports2.aggNums = function(f, v, a, len) { + var i, b; + if (!len || len > a.length) len = a.length; + if (!isNumeric2(v)) v = false; + if (isArrayOrTypedArray2(a[0])) { + b = new Array(len); + for (i = 0; i < len; i++) b[i] = exports2.aggNums(f, v, a[i]); + a = b; + } + for (i = 0; i < len; i++) { + if (!isNumeric2(v)) v = a[i]; + else if (isNumeric2(a[i])) v = f(+v, +a[i]); + } + return v; + }; + exports2.len = function(data) { + return exports2.aggNums(function(a) { + return a + 1; + }, 0, data); + }; + exports2.mean = function(data, len) { + if (!len) len = exports2.len(data); + return exports2.aggNums(function(a, b) { + return a + b; + }, 0, data) / len; + }; + exports2.geometricMean = function(data, len) { + if (!len) len = exports2.len(data); + return Math.pow(exports2.aggNums(function(a, b) { + return a * b; + }, 1, data), 1 / len); + }; + exports2.midRange = function(numArr) { + if (numArr === void 0 || numArr.length === 0) return void 0; + return (exports2.aggNums(Math.max, null, numArr) + exports2.aggNums(Math.min, null, numArr)) / 2; + }; + exports2.variance = function(data, len, mean) { + if (!len) len = exports2.len(data); + if (!isNumeric2(mean)) mean = exports2.mean(data, len); + return exports2.aggNums(function(a, b) { + return a + Math.pow(b - mean, 2); + }, 0, data) / len; + }; + exports2.stdev = function(data, len, mean) { + return Math.sqrt(exports2.variance(data, len, mean)); + }; + exports2.median = function(data) { + var b = data.slice().sort(); + return exports2.interp(b, 0.5); + }; + exports2.interp = function(arr, n) { + if (!isNumeric2(n)) throw "n should be a finite number"; + n = n * arr.length - 0.5; + if (n < 0) return arr[0]; + if (n > arr.length - 1) return arr[arr.length - 1]; + var frac = n % 1; + return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; + }; +})(stats); +var modModule$1 = mod_1; +var mod$1 = modModule$1.mod; +var modHalf = modModule$1.modHalf; +var PI = Math.PI; +var twoPI = 2 * PI; +function deg2rad(deg) { + return deg / 180 * PI; +} +function rad2deg(rad) { + return rad / PI * 180; +} +function isFullCircle(aBnds) { + return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-14; +} +function angleDelta(a, b) { + return modHalf(b - a, twoPI); +} +function angleDist(a, b) { + return Math.abs(angleDelta(a, b)); +} +function isAngleInsideSector(a, aBnds) { + if (isFullCircle(aBnds)) return true; + var s0, s1; + if (aBnds[0] < aBnds[1]) { + s0 = aBnds[0]; + s1 = aBnds[1]; + } else { + s0 = aBnds[1]; + s1 = aBnds[0]; + } + s0 = mod$1(s0, twoPI); + s1 = mod$1(s1, twoPI); + if (s0 > s1) s1 += twoPI; + var a0 = mod$1(a, twoPI); + var a1 = a0 + twoPI; + return a0 >= s0 && a0 <= s1 || a1 >= s0 && a1 <= s1; +} +function isPtInsideSector(r, a, rBnds, aBnds) { + if (!isAngleInsideSector(a, aBnds)) return false; + var r0, r1; + if (rBnds[0] < rBnds[1]) { + r0 = rBnds[0]; + r1 = rBnds[1]; + } else { + r0 = rBnds[1]; + r1 = rBnds[0]; + } + return r >= r0 && r <= r1; +} +function _path(r0, r1, a0, a1, cx, cy, isClosed) { + cx = cx || 0; + cy = cy || 0; + var isCircle = isFullCircle([a0, a1]); + var aStart, aMid, aEnd; + var rStart, rEnd; + if (isCircle) { + aStart = 0; + aMid = PI; + aEnd = twoPI; + } else { + if (a0 < a1) { + aStart = a0; + aEnd = a1; + } else { + aStart = a1; + aEnd = a0; + } + } + if (r0 < r1) { + rStart = r0; + rEnd = r1; + } else { + rStart = r1; + rEnd = r0; + } + function pt(r, a) { + return [r * Math.cos(a) + cx, cy - r * Math.sin(a)]; + } + var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1; + function arc2(r, a, cw) { + return "A" + [r, r] + " " + [0, largeArc, cw] + " " + pt(r, a); + } + var p; + if (isCircle) { + if (rStart === null) { + p = "M" + pt(rEnd, aStart) + arc2(rEnd, aMid, 0) + arc2(rEnd, aEnd, 0) + "Z"; + } else { + p = "M" + pt(rStart, aStart) + arc2(rStart, aMid, 0) + arc2(rStart, aEnd, 0) + "ZM" + pt(rEnd, aStart) + arc2(rEnd, aMid, 1) + arc2(rEnd, aEnd, 1) + "Z"; + } + } else { + if (rStart === null) { + p = "M" + pt(rEnd, aStart) + arc2(rEnd, aEnd, 0); + if (isClosed) p += "L0,0Z"; + } else { + p = "M" + pt(rStart, aStart) + "L" + pt(rEnd, aStart) + arc2(rEnd, aEnd, 0) + "L" + pt(rStart, aEnd) + arc2(rStart, aStart, 1) + "Z"; + } + } + return p; +} +function pathArc(r, a0, a1, cx, cy) { + return _path(null, r, a0, a1, cx, cy, 0); +} +function pathSector(r, a0, a1, cx, cy) { + return _path(null, r, a0, a1, cx, cy, 1); +} +function pathAnnulus(r0, r1, a0, a1, cx, cy) { + return _path(r0, r1, a0, a1, cx, cy, 1); +} +var angles = { + deg2rad, + rad2deg, + angleDelta, + angleDist, + isFullCircle, + isAngleInsideSector, + isPtInsideSector, + pathArc, + pathSector, + pathAnnulus +}; +var anchor_utils = {}; +anchor_utils.isLeftAnchor = function isLeftAnchor(opts) { + return opts.xanchor === "left" || opts.xanchor === "auto" && opts.x <= 1 / 3; +}; +anchor_utils.isCenterAnchor = function isCenterAnchor(opts) { + return opts.xanchor === "center" || opts.xanchor === "auto" && opts.x > 1 / 3 && opts.x < 2 / 3; +}; +anchor_utils.isRightAnchor = function isRightAnchor(opts) { + return opts.xanchor === "right" || opts.xanchor === "auto" && opts.x >= 2 / 3; +}; +anchor_utils.isTopAnchor = function isTopAnchor(opts) { + return opts.yanchor === "top" || opts.yanchor === "auto" && opts.y >= 2 / 3; +}; +anchor_utils.isMiddleAnchor = function isMiddleAnchor(opts) { + return opts.yanchor === "middle" || opts.yanchor === "auto" && opts.y > 1 / 3 && opts.y < 2 / 3; +}; +anchor_utils.isBottomAnchor = function isBottomAnchor(opts) { + return opts.yanchor === "bottom" || opts.yanchor === "auto" && opts.y <= 1 / 3; +}; +var geometry2d = {}; +var mod = mod_1.mod; +geometry2d.segmentsIntersect = segmentsIntersect$1; +function segmentsIntersect$1(x1, y1, x2, y2, x3, y3, x4, y4) { + var a = x2 - x1; + var b = x3 - x1; + var c = x4 - x3; + var d = y2 - y1; + var e = y3 - y1; + var f = y4 - y3; + var det = a * f - c * d; + if (det === 0) return null; + var t = (b * f - c * e) / det; + var u = (b * d - a * e) / det; + if (u < 0 || u > 1 || t < 0 || t > 1) return null; + return { x: x1 + a * t, y: y1 + d * t }; +} +geometry2d.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { + if (segmentsIntersect$1(x1, y1, x2, y2, x3, y3, x4, y4)) return 0; + var x12 = x2 - x1; + var y12 = y2 - y1; + var x34 = x4 - x3; + var y34 = y4 - y3; + var ll12 = x12 * x12 + y12 * y12; + var ll34 = x34 * x34 + y34 * y34; + var dist2 = Math.min( + perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1), + perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1), + perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3), + perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3) + ); + return Math.sqrt(dist2); +}; +function perpDistance2(xab, yab, llab, xac, yac) { + var fcAB = xac * xab + yac * yab; + if (fcAB < 0) { + return xac * xac + yac * yac; + } else if (fcAB > llab) { + var xbc = xac - xab; + var ybc = yac - yab; + return xbc * xbc + ybc * ybc; + } else { + var crossProduct = xac * yab - yac * xab; + return crossProduct * crossProduct / llab; + } +} +var locationCache, workingPath, workingTextWidth; +geometry2d.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { + if (path !== workingPath || textWidth !== workingTextWidth) { + locationCache = {}; + workingPath = path; + workingTextWidth = textWidth; + } + if (locationCache[positionOnPath]) { + return locationCache[positionOnPath]; + } + var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen)); + var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen)); + var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x)); + var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen)); + var x = (pCenter.x * 4 + p0.x + p1.x) / 6; + var y = (pCenter.y * 4 + p0.y + p1.y) / 6; + var out = { x, y, theta }; + locationCache[positionOnPath] = out; + return out; +}; +geometry2d.clearLocationCache = function() { + workingPath = null; +}; +geometry2d.getVisibleSegment = function getVisibleSegment(path, bounds, buffer2) { + var left = bounds.left; + var right = bounds.right; + var top = bounds.top; + var bottom = bounds.bottom; + var pMin = 0; + var pTotal = path.getTotalLength(); + var pMax = pTotal; + var pt0, ptTotal; + function getDistToPlot(len) { + var pt = path.getPointAtLength(len); + if (len === 0) pt0 = pt; + else if (len === pTotal) ptTotal = pt; + var dx = pt.x < left ? left - pt.x : pt.x > right ? pt.x - right : 0; + var dy = pt.y < top ? top - pt.y : pt.y > bottom ? pt.y - bottom : 0; + return Math.sqrt(dx * dx + dy * dy); + } + var distToPlot = getDistToPlot(pMin); + while (distToPlot) { + pMin += distToPlot + buffer2; + if (pMin > pMax) return; + distToPlot = getDistToPlot(pMin); + } + distToPlot = getDistToPlot(pMax); + while (distToPlot) { + pMax -= distToPlot + buffer2; + if (pMin > pMax) return; + distToPlot = getDistToPlot(pMax); + } + return { + min: pMin, + max: pMax, + len: pMax - pMin, + total: pTotal, + isClosed: pMin === 0 && pMax === pTotal && Math.abs(pt0.x - ptTotal.x) < 0.1 && Math.abs(pt0.y - ptTotal.y) < 0.1 + }; +}; +geometry2d.findPointOnPath = function findPointOnPath(path, val, coord, opts) { + opts = opts || {}; + var pathLength = opts.pathLength || path.getTotalLength(); + var tolerance = opts.tolerance || 1e-3; + var iterationLimit = opts.iterationLimit || 30; + var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1; + var i = 0; + var b0 = 0; + var b1 = pathLength; + var mid; + var pt; + var diff; + while (i < iterationLimit) { + mid = (b0 + b1) / 2; + pt = path.getPointAtLength(mid); + diff = pt[coord] - val; + if (Math.abs(diff) < tolerance) { + return pt; + } else { + if (mul * diff > 0) { + b1 = mid; + } else { + b0 = mid; + } + i++; + } + } + return pt; +}; +var throttle$2 = {}; +(function(exports2) { + var timerCache = {}; + exports2.throttle = function throttle2(id, minInterval, callback) { + var cache2 = timerCache[id]; + var now = Date.now(); + if (!cache2) { + for (var idi in timerCache) { + if (timerCache[idi].ts < now - 6e4) { + delete timerCache[idi]; + } + } + cache2 = timerCache[id] = { ts: 0, timer: null }; + } + _clearTimeout(cache2); + function exec() { + callback(); + cache2.ts = Date.now(); + if (cache2.onDone) { + cache2.onDone(); + cache2.onDone = null; + } + } + if (now > cache2.ts + minInterval) { + exec(); + return; + } + cache2.timer = setTimeout(function() { + exec(); + cache2.timer = null; + }, minInterval); + }; + exports2.done = function(id) { + var cache2 = timerCache[id]; + if (!cache2 || !cache2.timer) return Promise.resolve(); + return new Promise(function(resolve) { + var previousOnDone = cache2.onDone; + cache2.onDone = function onDone() { + if (previousOnDone) previousOnDone(); + resolve(); + cache2.onDone = null; + }; + }); + }; + exports2.clear = function(id) { + if (id) { + _clearTimeout(timerCache[id]); + delete timerCache[id]; + } else { + for (var idi in timerCache) exports2.clear(idi); + } + }; + function _clearTimeout(cache2) { + if (cache2 && cache2.timer !== null) { + clearTimeout(cache2.timer); + cache2.timer = null; + } + } +})(throttle$2); +var clear_responsive = function clearResponsive(gd) { + if (gd._responsiveChartHandler) { + window.removeEventListener("resize", gd._responsiveChartHandler); + delete gd._responsiveChartHandler; + } +}; +var isMobile$1 = { exports: {} }; +isMobile$1.exports = isMobile; +isMobile$1.exports.isMobile = isMobile; +isMobile$1.exports.default = isMobile; +const mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i; +const notMobileRE = /CrOS/; +const tabletRE = /android|ipad|playbook|silk/i; +function isMobile(opts) { + if (!opts) opts = {}; + let ua = opts.ua; + if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent; + if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") { + ua = ua.headers["user-agent"]; + } + if (typeof ua !== "string") return false; + let result = mobileRE.test(ua) && !notMobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua); + if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) { + result = true; + } + return result; +} +var isMobileExports = isMobile$1.exports; +var isNumeric$x = fastIsnumeric; +var isMobileOrTablet = isMobileExports; +var preserve_drawing_buffer = function preserveDrawingBuffer(opts) { + var ua; + if (opts && opts.hasOwnProperty("userAgent")) { + ua = opts.userAgent; + } else { + ua = getUserAgent(); + } + if (typeof ua !== "string") return true; + var enable2 = isMobileOrTablet({ + ua: { headers: { "user-agent": ua } }, + tablet: true, + featureDetect: false + }); + if (!enable2) { + var allParts = ua.split(" "); + for (var i = 1; i < allParts.length; i++) { + var part = allParts[i]; + if (part.indexOf("Safari") !== -1) { + for (var k = i - 1; k > -1; k--) { + var prevPart = allParts[k]; + if (prevPart.substr(0, 8) === "Version/") { + var v = prevPart.substr(8).split(".")[0]; + if (isNumeric$x(v)) v = +v; + if (v >= 13) return true; + } + } + } + } + } + return enable2; +}; +function getUserAgent() { + var ua; + if (typeof navigator !== "undefined") { + ua = navigator.userAgent; + } + if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") { + ua = ua.headers["user-agent"]; + } + return ua; +} +var d3$D = d3Exports; +var make_trace_groups = function makeTraceGroups(traceLayer, cdModule, cls) { + var traces = traceLayer.selectAll("g." + cls.replace(/\s/g, ".")).data(cdModule, function(cd) { + return cd[0].trace.uid; + }); + traces.exit().remove(); + traces.enter().append("g").attr("class", cls); + traces.order(); + var k = traceLayer.classed("rangeplot") ? "nodeRangePlot3" : "node3"; + traces.each(function(cd) { + cd[0][k] = d3$D.select(this); + }); + return traces; +}; +var Registry$O = registry; +var localize = function localize2(gd, s) { + var locale2 = gd._context.locale; + for (var i = 0; i < 2; i++) { + var locales = gd._context.locales; + for (var j = 0; j < 2; j++) { + var dict = (locales[locale2] || {}).dictionary; + if (dict) { + var out = dict[s]; + if (out) return out; + } + locales = Registry$O.localeRegistry; + } + var baseLocale = locale2.split("-")[0]; + if (baseLocale === locale2) break; + locale2 = baseLocale; + } + return s; +}; +var filter_unique = function filterUnique(array2) { + var seen = {}; + var out = []; + var j = 0; + for (var i = 0; i < array2.length; i++) { + var item = array2[i]; + if (seen[item] !== 1) { + seen[item] = 1; + out[j++] = item; + } + } + return out; +}; +var filter_visible = function filterVisible(container) { + var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; + var out = []; + for (var i = 0; i < container.length; i++) { + var item = container[i]; + if (filterFn(item)) out.push(item); + } + return out; +}; +function baseFilter(item) { + return item.visible === true; +} +function calcDataFilter(item) { + var trace = item[0].trace; + return trace.visible === true && trace._length !== 0; +} +function isCalcData(cont) { + return Array.isArray(cont) && Array.isArray(cont[0]) && cont[0][0] && cont[0][0].trace; +} +var increment = function incrementNumeric(x, delta2) { + if (!delta2) return x; + var scale2 = 1 / Math.abs(delta2); + var newX = scale2 > 1 ? (scale2 * x + scale2 * delta2) / scale2 : x + delta2; + var lenX1 = String(newX).length; + if (lenX1 > 16) { + var lenDt = String(delta2).length; + var lenX0 = String(x).length; + if (lenX1 >= lenX0 + lenDt) { + var s = parseFloat(newX).toPrecision(12); + if (s.indexOf("e+") === -1) newX = +s; + } + } + return newX; +}; +var isNumeric$w = fastIsnumeric; +var BADNUM$c = numerical.BADNUM; +var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; +var clean_number = function cleanNumber(v) { + if (typeof v === "string") { + v = v.replace(JUNK, ""); + } + if (isNumeric$w(v)) return Number(v); + return BADNUM$c; +}; +var d3$C = d3Exports; +var utcFormat$1 = require$$1$1.utcFormat; +var d3Format = require$$2$2.format; +var isNumeric$v = fastIsnumeric; +var numConstants$4 = numerical; +var MAX_SAFE = numConstants$4.FP_SAFE; +var MIN_SAFE = -MAX_SAFE; +var BADNUM$b = numConstants$4.BADNUM; +var lib = lib$1.exports = {}; +lib.adjustFormat = function adjustFormat(formatStr) { + if (!formatStr || /^\d[.]\df/.test(formatStr) || /[.]\d%/.test(formatStr)) return formatStr; + if (formatStr === "0.f") return "~f"; + if (/^\d%/.test(formatStr)) return "~%"; + if (/^\ds/.test(formatStr)) return "~s"; + if (!/^[~,.0$]/.test(formatStr) && /[&fps]/.test(formatStr)) return "~" + formatStr; + return formatStr; +}; +var seenBadFormats = {}; +lib.warnBadFormat = function(f) { + var key = String(f); + if (!seenBadFormats[key]) { + seenBadFormats[key] = 1; + lib.warn('encountered bad format: "' + key + '"'); + } +}; +lib.noFormat = function(value2) { + return String(value2); +}; +lib.numberFormat = function(formatStr) { + var fn; + try { + fn = d3Format(lib.adjustFormat(formatStr)); + } catch (e) { + lib.warnBadFormat(formatStr); + return lib.noFormat; + } + return fn; +}; +lib.nestedProperty = nested_property; +lib.keyedContainer = keyed_container; +lib.relativeAttr = relative_attr; +lib.isPlainObject = is_plain_object; +lib.toLogRange = to_log_range; +lib.relinkPrivateKeys = relink_private; +var arrayModule = array$2; +lib.isArrayBuffer = arrayModule.isArrayBuffer; +lib.isTypedArray = arrayModule.isTypedArray; +lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray; +lib.isArray1D = arrayModule.isArray1D; +lib.ensureArray = arrayModule.ensureArray; +lib.concat = arrayModule.concat; +lib.maxRowLength = arrayModule.maxRowLength; +lib.minRowLength = arrayModule.minRowLength; +var modModule = mod_1; +lib.mod = modModule.mod; +lib.modHalf = modModule.modHalf; +var coerceModule = coerce$1; +lib.valObjectMeta = coerceModule.valObjectMeta; +lib.coerce = coerceModule.coerce; +lib.coerce2 = coerceModule.coerce2; +lib.coerceFont = coerceModule.coerceFont; +lib.coercePattern = coerceModule.coercePattern; +lib.coerceHoverinfo = coerceModule.coerceHoverinfo; +lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity; +lib.validate = coerceModule.validate; +var datesModule = dates; +lib.dateTime2ms = datesModule.dateTime2ms; +lib.isDateTime = datesModule.isDateTime; +lib.ms2DateTime = datesModule.ms2DateTime; +lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal; +lib.cleanDate = datesModule.cleanDate; +lib.isJSDate = datesModule.isJSDate; +lib.formatDate = datesModule.formatDate; +lib.incrementMonth = datesModule.incrementMonth; +lib.dateTick0 = datesModule.dateTick0; +lib.dfltRange = datesModule.dfltRange; +lib.findExactDates = datesModule.findExactDates; +lib.MIN_MS = datesModule.MIN_MS; +lib.MAX_MS = datesModule.MAX_MS; +var searchModule = search$1; +lib.findBin = searchModule.findBin; +lib.sorterAsc = searchModule.sorterAsc; +lib.sorterDes = searchModule.sorterDes; +lib.distinctVals = searchModule.distinctVals; +lib.roundUp = searchModule.roundUp; +lib.sort = searchModule.sort; +lib.findIndexOfMin = searchModule.findIndexOfMin; +lib.sortObjectKeys = sort_object_keys; +var statsModule = stats; +lib.aggNums = statsModule.aggNums; +lib.len = statsModule.len; +lib.mean = statsModule.mean; +lib.geometricMean = statsModule.geometricMean; +lib.median = statsModule.median; +lib.midRange = statsModule.midRange; +lib.variance = statsModule.variance; +lib.stdev = statsModule.stdev; +lib.interp = statsModule.interp; +var matrixModule = matrix$1; +lib.init2dArray = matrixModule.init2dArray; +lib.transposeRagged = matrixModule.transposeRagged; +lib.dot = matrixModule.dot; +lib.translationMatrix = matrixModule.translationMatrix; +lib.rotationMatrix = matrixModule.rotationMatrix; +lib.rotationXYMatrix = matrixModule.rotationXYMatrix; +lib.apply3DTransform = matrixModule.apply3DTransform; +lib.apply2DTransform = matrixModule.apply2DTransform; +lib.apply2DTransform2 = matrixModule.apply2DTransform2; +lib.convertCssMatrix = matrixModule.convertCssMatrix; +lib.inverseTransformMatrix = matrixModule.inverseTransformMatrix; +var anglesModule = angles; +lib.deg2rad = anglesModule.deg2rad; +lib.rad2deg = anglesModule.rad2deg; +lib.angleDelta = anglesModule.angleDelta; +lib.angleDist = anglesModule.angleDist; +lib.isFullCircle = anglesModule.isFullCircle; +lib.isAngleInsideSector = anglesModule.isAngleInsideSector; +lib.isPtInsideSector = anglesModule.isPtInsideSector; +lib.pathArc = anglesModule.pathArc; +lib.pathSector = anglesModule.pathSector; +lib.pathAnnulus = anglesModule.pathAnnulus; +var anchorUtils = anchor_utils; +lib.isLeftAnchor = anchorUtils.isLeftAnchor; +lib.isCenterAnchor = anchorUtils.isCenterAnchor; +lib.isRightAnchor = anchorUtils.isRightAnchor; +lib.isTopAnchor = anchorUtils.isTopAnchor; +lib.isMiddleAnchor = anchorUtils.isMiddleAnchor; +lib.isBottomAnchor = anchorUtils.isBottomAnchor; +var geom2dModule = geometry2d; +lib.segmentsIntersect = geom2dModule.segmentsIntersect; +lib.segmentDistance = geom2dModule.segmentDistance; +lib.getTextLocation = geom2dModule.getTextLocation; +lib.clearLocationCache = geom2dModule.clearLocationCache; +lib.getVisibleSegment = geom2dModule.getVisibleSegment; +lib.findPointOnPath = geom2dModule.findPointOnPath; +var extendModule = extend$5; +lib.extendFlat = extendModule.extendFlat; +lib.extendDeep = extendModule.extendDeep; +lib.extendDeepAll = extendModule.extendDeepAll; +lib.extendDeepNoArrays = extendModule.extendDeepNoArrays; +var loggersModule = loggersExports; +lib.log = loggersModule.log; +lib.warn = loggersModule.warn; +lib.error = loggersModule.error; +var regexModule = regex; +lib.counterRegex = regexModule.counter; +var throttleModule = throttle$2; +lib.throttle = throttleModule.throttle; +lib.throttleDone = throttleModule.done; +lib.clearThrottle = throttleModule.clear; +var domModule = dom; +lib.getGraphDiv = domModule.getGraphDiv; +lib.isPlotDiv = domModule.isPlotDiv; +lib.removeElement = domModule.removeElement; +lib.addStyleRule = domModule.addStyleRule; +lib.addRelatedStyleRule = domModule.addRelatedStyleRule; +lib.deleteRelatedStyleRule = domModule.deleteRelatedStyleRule; +lib.getFullTransformMatrix = domModule.getFullTransformMatrix; +lib.getElementTransformMatrix = domModule.getElementTransformMatrix; +lib.getElementAndAncestors = domModule.getElementAndAncestors; +lib.equalDomRects = domModule.equalDomRects; +lib.clearResponsive = clear_responsive; +lib.preserveDrawingBuffer = preserve_drawing_buffer; +lib.makeTraceGroups = make_trace_groups; +lib._ = localize; +lib.notifier = notifier$1; +lib.filterUnique = filter_unique; +lib.filterVisible = filter_visible; +lib.pushUnique = push_unique; +lib.increment = increment; +lib.cleanNumber = clean_number; +lib.ensureNumber = function ensureNumber(v) { + if (!isNumeric$v(v)) return BADNUM$b; + v = Number(v); + return v > MAX_SAFE || v < MIN_SAFE ? BADNUM$b : v; +}; +lib.isIndex = function(v, len) { + if (len !== void 0 && v >= len) return false; + return isNumeric$v(v) && v >= 0 && v % 1 === 0; +}; +lib.noop = noop$2; +lib.identity = identity$2; +lib.repeat = function(v, cnt) { + var out = new Array(cnt); + for (var i = 0; i < cnt; i++) { + out[i] = v; + } + return out; +}; +lib.swapAttrs = function(cont, attrList, part1, part2) { + if (!part1) part1 = "x"; + if (!part2) part2 = "y"; + for (var i = 0; i < attrList.length; i++) { + var attr = attrList[i]; + var xp = lib.nestedProperty(cont, attr.replace("?", part1)); + var yp = lib.nestedProperty(cont, attr.replace("?", part2)); + var temp = xp.get(); + xp.set(yp.get()); + yp.set(temp); + } +}; +lib.raiseToTop = function raiseToTop(elem) { + elem.parentNode.appendChild(elem); +}; +lib.cancelTransition = function(selection) { + return selection.transition().duration(0); +}; +lib.constrain = function(v, v0, v1) { + if (v0 > v1) return Math.max(v1, Math.min(v0, v)); + return Math.max(v0, Math.min(v1, v)); +}; +lib.bBoxIntersect = function(a, b, pad2) { + pad2 = pad2 || 0; + return a.left <= b.right + pad2 && b.left <= a.right + pad2 && a.top <= b.bottom + pad2 && b.top <= a.bottom + pad2; +}; +lib.simpleMap = function(array2, func, x1, x2, opts) { + var len = array2.length; + var out = new Array(len); + for (var i = 0; i < len; i++) out[i] = func(array2[i], x1, x2, opts); + return out; +}; +lib.randstr = function randstr(existing, bits2, base, _recursion) { + if (!base) base = 16; + if (bits2 === void 0) bits2 = 24; + if (bits2 <= 0) return "0"; + var digits = Math.log(Math.pow(2, bits2)) / Math.log(base); + var res = ""; + var i, b, x; + for (i = 2; digits === Infinity; i *= 2) { + digits = Math.log(Math.pow(2, bits2 / i)) / Math.log(base) * i; + } + var rem = digits - Math.floor(digits); + for (i = 0; i < Math.floor(digits); i++) { + x = Math.floor(Math.random() * base).toString(base); + res = x + res; + } + if (rem) { + b = Math.pow(base, rem); + x = Math.floor(Math.random() * b).toString(base); + res = x + res; + } + var parsed = parseInt(res, base); + if (existing && existing[res] || parsed !== Infinity && parsed >= Math.pow(2, bits2)) { + if (_recursion > 10) { + lib.warn("randstr failed uniqueness"); + return res; + } + return randstr(existing, bits2, base, (_recursion || 0) + 1); + } else return res; +}; +lib.OptionControl = function(opt, optname) { + if (!opt) opt = {}; + if (!optname) optname = "opt"; + var self2 = {}; + self2.optionList = []; + self2._newoption = function(optObj) { + optObj[optname] = opt; + self2[optObj.name] = optObj; + self2.optionList.push(optObj); + }; + self2["_" + optname] = opt; + return self2; +}; +lib.smooth = function(arrayIn, FWHM) { + FWHM = Math.round(FWHM) || 0; + if (FWHM < 2) return arrayIn; + var alen = arrayIn.length; + var alen2 = 2 * alen; + var wlen = 2 * FWHM - 1; + var w = new Array(wlen); + var arrayOut = new Array(alen); + var i; + var j; + var k; + var v; + for (i = 0; i < wlen; i++) { + w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM); + } + for (i = 0; i < alen; i++) { + v = 0; + for (j = 0; j < wlen; j++) { + k = i + j + 1 - FWHM; + if (k < -alen) k -= alen2 * Math.round(k / alen2); + else if (k >= alen2) k -= alen2 * Math.floor(k / alen2); + if (k < 0) k = -1 - k; + else if (k >= alen) k = alen2 - 1 - k; + v += arrayIn[k] * w[j]; + } + arrayOut[i] = v; + } + return arrayOut; +}; +lib.syncOrAsync = function(sequence, arg, finalStep) { + var ret, fni; + function continueAsync() { + return lib.syncOrAsync(sequence, arg, finalStep); + } + while (sequence.length) { + fni = sequence.splice(0, 1)[0]; + ret = fni(arg); + if (ret && ret.then) { + return ret.then(continueAsync); + } + } + return finalStep && finalStep(arg); +}; +lib.stripTrailingSlash = function(str2) { + if (str2.substr(-1) === "/") return str2.substr(0, str2.length - 1); + return str2; +}; +lib.noneOrAll = function(containerIn, containerOut, attrList) { + if (!containerIn) return; + var hasAny = false; + var hasAll = true; + var i; + var val; + for (i = 0; i < attrList.length; i++) { + val = containerIn[attrList[i]]; + if (val !== void 0 && val !== null) hasAny = true; + else hasAll = false; + } + if (hasAny && !hasAll) { + for (i = 0; i < attrList.length; i++) { + containerIn[attrList[i]] = containerOut[attrList[i]]; + } + } +}; +lib.mergeArray = function(traceAttr, cd, cdAttr, fn) { + var hasFn = typeof fn === "function"; + if (lib.isArrayOrTypedArray(traceAttr)) { + var imax = Math.min(traceAttr.length, cd.length); + for (var i = 0; i < imax; i++) { + var v = traceAttr[i]; + cd[i][cdAttr] = hasFn ? fn(v) : v; + } + } +}; +lib.mergeArrayCastPositive = function(traceAttr, cd, cdAttr) { + return lib.mergeArray(traceAttr, cd, cdAttr, function(v) { + var w = +v; + return !isFinite(w) ? 0 : w > 0 ? w : 0; + }); +}; +lib.fillArray = function(traceAttr, cd, cdAttr, fn) { + fn = fn || lib.identity; + if (lib.isArrayOrTypedArray(traceAttr)) { + for (var i = 0; i < cd.length; i++) { + cd[i][cdAttr] = fn(traceAttr[i]); + } + } +}; +lib.castOption = function(trace, ptNumber, astr, fn) { + fn = fn || lib.identity; + var val = lib.nestedProperty(trace, astr).get(); + if (lib.isArrayOrTypedArray(val)) { + if (Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) { + return fn(val[ptNumber[0]][ptNumber[1]]); + } else { + return fn(val[ptNumber]); + } + } else { + return val; + } +}; +lib.extractOption = function(calcPt, trace, calcKey, traceKey) { + if (calcKey in calcPt) return calcPt[calcKey]; + var traceVal = lib.nestedProperty(trace, traceKey).get(); + if (!Array.isArray(traceVal)) return traceVal; +}; +function makePtIndex2PtNumber(indexToPoints) { + var ptIndex2ptNumber = {}; + for (var k in indexToPoints) { + var pts = indexToPoints[k]; + for (var j = 0; j < pts.length; j++) { + ptIndex2ptNumber[pts[j]] = +k; + } + } + return ptIndex2ptNumber; +} +lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) { + var selectedpoints = trace.selectedpoints; + var indexToPoints = trace._indexToPoints; + var ptIndex2ptNumber; + if (indexToPoints) { + ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints); + } + function isCdIndexValid(v) { + return v !== void 0 && v < calcTrace.length; + } + for (var i = 0; i < selectedpoints.length; i++) { + var ptIndex = selectedpoints[i]; + if (lib.isIndex(ptIndex) || lib.isArrayOrTypedArray(ptIndex) && lib.isIndex(ptIndex[0]) && lib.isIndex(ptIndex[1])) { + var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex; + var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber; + if (isCdIndexValid(cdIndex)) { + calcTrace[cdIndex].selected = 1; + } + } + } +}; +lib.selIndices2selPoints = function(trace) { + var selectedpoints = trace.selectedpoints; + var indexToPoints = trace._indexToPoints; + if (indexToPoints) { + var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints); + var out = []; + for (var i = 0; i < selectedpoints.length; i++) { + var ptIndex = selectedpoints[i]; + if (lib.isIndex(ptIndex)) { + var ptNumber = ptIndex2ptNumber[ptIndex]; + if (lib.isIndex(ptNumber)) { + out.push(ptNumber); + } + } + } + return out; + } else { + return selectedpoints; + } +}; +lib.getTargetArray = function(trace, transformOpts) { + var target = transformOpts.target; + if (typeof target === "string" && target) { + var array2 = lib.nestedProperty(trace, target).get(); + return lib.isArrayOrTypedArray(array2) ? array2 : false; + } else if (lib.isArrayOrTypedArray(target)) { + return target; + } + return false; +}; +function minExtend(obj1, obj2, opt) { + var objOut = {}; + if (typeof obj2 !== "object") obj2 = {}; + var arrayLen = opt === "pieLike" ? -1 : 3; + var keys = Object.keys(obj1); + var i, k, v; + for (i = 0; i < keys.length; i++) { + k = keys[i]; + v = obj1[k]; + if (k.charAt(0) === "_" || typeof v === "function") continue; + else if (k === "module") objOut[k] = v; + else if (Array.isArray(v)) { + if (k === "colorscale" || arrayLen === -1) { + objOut[k] = v.slice(); + } else { + objOut[k] = v.slice(0, arrayLen); + } + } else if (lib.isTypedArray(v)) { + if (arrayLen === -1) { + objOut[k] = v.subarray(); + } else { + objOut[k] = v.subarray(0, arrayLen); + } + } else if (v && typeof v === "object") objOut[k] = minExtend(obj1[k], obj2[k], opt); + else objOut[k] = v; + } + keys = Object.keys(obj2); + for (i = 0; i < keys.length; i++) { + k = keys[i]; + v = obj2[k]; + if (typeof v !== "object" || !(k in objOut) || typeof objOut[k] !== "object") { + objOut[k] = v; + } + } + return objOut; +} +lib.minExtend = minExtend; +lib.titleCase = function(s) { + return s.charAt(0).toUpperCase() + s.substr(1); +}; +lib.containsAny = function(s, fragments) { + for (var i = 0; i < fragments.length; i++) { + if (s.indexOf(fragments[i]) !== -1) return true; + } + return false; +}; +lib.isIE = function() { + return typeof window.navigator.msSaveBlob !== "undefined"; +}; +var IS_SAFARI_REGEX = /Version\/[\d\.]+.*Safari/; +lib.isSafari = function() { + return IS_SAFARI_REGEX.test(window.navigator.userAgent); +}; +var IS_IOS_REGEX = /iPad|iPhone|iPod/; +lib.isIOS = function() { + return IS_IOS_REGEX.test(window.navigator.userAgent); +}; +var FIREFOX_VERSION_REGEX = /Firefox\/(\d+)\.\d+/; +lib.getFirefoxVersion = function() { + var match = FIREFOX_VERSION_REGEX.exec(window.navigator.userAgent); + if (match && match.length === 2) { + var versionInt = parseInt(match[1]); + if (!isNaN(versionInt)) { + return versionInt; + } + } + return null; +}; +lib.isD3Selection = function(obj) { + return obj instanceof d3$C.selection; +}; +lib.ensureSingle = function(parent, nodeType, className, enterFn) { + var sel = parent.select(nodeType + (className ? "." + className : "")); + if (sel.size()) return sel; + var layer = parent.append(nodeType); + if (className) layer.classed(className, true); + if (enterFn) layer.call(enterFn); + return layer; +}; +lib.ensureSingleById = function(parent, nodeType, id, enterFn) { + var sel = parent.select(nodeType + "#" + id); + if (sel.size()) return sel; + var layer = parent.append(nodeType).attr("id", id); + if (enterFn) layer.call(enterFn); + return layer; +}; +lib.objectFromPath = function(path, value2) { + var keys = path.split("."); + var tmpObj; + var obj = tmpObj = {}; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var el = null; + var parts = keys[i].match(/(.*)\[([0-9]+)\]/); + if (parts) { + key = parts[1]; + el = parts[2]; + tmpObj = tmpObj[key] = []; + if (i === keys.length - 1) { + tmpObj[el] = value2; + } else { + tmpObj[el] = {}; + } + tmpObj = tmpObj[el]; + } else { + if (i === keys.length - 1) { + tmpObj[key] = value2; + } else { + tmpObj[key] = {}; + } + tmpObj = tmpObj[key]; + } + } + return obj; +}; +var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/; +var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/; +function notValid(prop) { + return prop.slice(0, 2) === "__"; +} +lib.expandObjectPaths = function(data) { + var match, key, prop, datum, idx, dest, trailingPath; + if (typeof data === "object" && !Array.isArray(data)) { + for (key in data) { + if (data.hasOwnProperty(key)) { + if (match = key.match(dottedPropertyRegex)) { + datum = data[key]; + prop = match[1]; + if (notValid(prop)) continue; + delete data[key]; + data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]); + } else if (match = key.match(indexedPropertyRegex)) { + datum = data[key]; + prop = match[1]; + if (notValid(prop)) continue; + idx = parseInt(match[2]); + delete data[key]; + data[prop] = data[prop] || []; + if (match[3] === ".") { + trailingPath = match[4]; + dest = data[prop][idx] = data[prop][idx] || {}; + lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum))); + } else { + if (notValid(prop)) continue; + data[prop][idx] = lib.expandObjectPaths(datum); + } + } else { + if (notValid(key)) continue; + data[key] = lib.expandObjectPaths(data[key]); + } + } + } + } + return data; +}; +lib.numSeparate = function(value2, separators, separatethousands) { + if (!separatethousands) separatethousands = false; + if (typeof separators !== "string" || separators.length === 0) { + throw new Error("Separator string required for formatting!"); + } + if (typeof value2 === "number") { + value2 = String(value2); + } + var thousandsRe = /(\d+)(\d{3})/; + var decimalSep = separators.charAt(0); + var thouSep = separators.charAt(1); + var x = value2.split("."); + var x1 = x[0]; + var x2 = x.length > 1 ? decimalSep + x[1] : ""; + if (thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) { + while (thousandsRe.test(x1)) { + x1 = x1.replace(thousandsRe, "$1" + thouSep + "$2"); + } + } + return x1 + x2; +}; +lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)([:|\|][^}]*)?}/g; +var SIMPLE_PROPERTY_REGEX = /^\w*$/; +lib.templateString = function(string2, obj) { + var getterCache = {}; + return string2.replace(lib.TEMPLATE_STRING_REGEX, function(dummy, key) { + var v; + if (SIMPLE_PROPERTY_REGEX.test(key)) { + v = obj[key]; + } else { + getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; + v = getterCache[key](); + } + return lib.isValidTextValue(v) ? v : ""; + }); +}; +var hovertemplateWarnings = { + max: 10, + count: 0, + name: "hovertemplate" +}; +lib.hovertemplateString = function() { + return templateFormatString.apply(hovertemplateWarnings, arguments); +}; +var texttemplateWarnings = { + max: 10, + count: 0, + name: "texttemplate" +}; +lib.texttemplateString = function() { + return templateFormatString.apply(texttemplateWarnings, arguments); +}; +var MULT_DIV_REGEX = /^(\S+)([\*\/])(-?\d+(\.\d+)?)$/; +function multDivParser(inputStr) { + var match = inputStr.match(MULT_DIV_REGEX); + if (match) return { key: match[1], op: match[2], number: Number(match[3]) }; + return { key: inputStr, op: null, number: null }; +} +var texttemplateWarningsForShapes = { + max: 10, + count: 0, + name: "texttemplate", + parseMultDiv: true +}; +lib.texttemplateStringForShapes = function() { + return templateFormatString.apply(texttemplateWarningsForShapes, arguments); +}; +var TEMPLATE_STRING_FORMAT_SEPARATOR = /^[:|\|]/; +function templateFormatString(string2, labels, d3locale) { + var opts = this; + var args = arguments; + if (!labels) labels = {}; + var getterCache = {}; + return string2.replace(lib.TEMPLATE_STRING_REGEX, function(match, rawKey, format2) { + var isOther = rawKey === "xother" || rawKey === "yother"; + var isSpaceOther = rawKey === "_xother" || rawKey === "_yother"; + var isSpaceOtherSpace = rawKey === "_xother_" || rawKey === "_yother_"; + var isOtherSpace = rawKey === "xother_" || rawKey === "yother_"; + var hasOther = isOther || isSpaceOther || isOtherSpace || isSpaceOtherSpace; + var key = rawKey; + if (isSpaceOther || isSpaceOtherSpace) key = key.substring(1); + if (isOtherSpace || isSpaceOtherSpace) key = key.substring(0, key.length - 1); + var parsedOp = null; + var parsedNumber = null; + if (opts.parseMultDiv) { + var _match = multDivParser(key); + key = _match.key; + parsedOp = _match.op; + parsedNumber = _match.number; + } + var value2; + if (hasOther) { + value2 = labels[key]; + if (value2 === void 0) return ""; + } else { + var obj, i; + for (i = 3; i < args.length; i++) { + obj = args[i]; + if (!obj) continue; + if (obj.hasOwnProperty(key)) { + value2 = obj[key]; + break; + } + if (!SIMPLE_PROPERTY_REGEX.test(key)) { + value2 = lib.nestedProperty(obj, key).get(); + value2 = getterCache[key] || lib.nestedProperty(obj, key).get(); + if (value2) getterCache[key] = value2; + } + if (value2 !== void 0) break; + } + } + if (value2 !== void 0) { + if (parsedOp === "*") value2 *= parsedNumber; + if (parsedOp === "/") value2 /= parsedNumber; + } + if (value2 === void 0 && opts) { + if (opts.count < opts.max) { + lib.warn("Variable '" + key + "' in " + opts.name + " could not be found!"); + value2 = match; + } + if (opts.count === opts.max) { + lib.warn("Too many " + opts.name + " warnings - additional warnings will be suppressed"); + } + opts.count++; + return match; + } + if (format2) { + var fmt; + if (format2[0] === ":") { + fmt = d3locale ? d3locale.numberFormat : lib.numberFormat; + if (value2 !== "") { + value2 = fmt(format2.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""))(value2); + } + } + if (format2[0] === "|") { + fmt = d3locale ? d3locale.timeFormat : utcFormat$1; + var ms = lib.dateTime2ms(value2); + value2 = lib.formatDate(ms, format2.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""), false, fmt); + } + } else { + var keyLabel = key + "Label"; + if (labels.hasOwnProperty(keyLabel)) value2 = labels[keyLabel]; + } + if (hasOther) { + value2 = "(" + value2 + ")"; + if (isSpaceOther || isSpaceOtherSpace) value2 = " " + value2; + if (isOtherSpace || isSpaceOtherSpace) value2 = value2 + " "; + } + return value2; + }); +} +var char0 = 48; +var char9 = 57; +lib.subplotSort = function(a, b) { + var l = Math.min(a.length, b.length) + 1; + var numA = 0; + var numB = 0; + for (var i = 0; i < l; i++) { + var charA = a.charCodeAt(i) || 0; + var charB = b.charCodeAt(i) || 0; + var isNumA = charA >= char0 && charA <= char9; + var isNumB = charB >= char0 && charB <= char9; + if (isNumA) numA = 10 * numA + charA - char0; + if (isNumB) numB = 10 * numB + charB - char0; + if (!isNumA || !isNumB) { + if (numA !== numB) return numA - numB; + if (charA !== charB) return charA - charB; + } + } + return numB - numA; +}; +var randSeed = 2e9; +lib.seedPseudoRandom = function() { + randSeed = 2e9; +}; +lib.pseudoRandom = function() { + var lastVal = randSeed; + randSeed = (69069 * randSeed + 1) % 4294967296; + if (Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom(); + return randSeed / 4294967296; +}; +lib.fillText = function(calcPt, trace, contOut) { + var fill = Array.isArray(contOut) ? function(v) { + contOut.push(v); + } : function(v) { + contOut.text = v; + }; + var htx = lib.extractOption(calcPt, trace, "htx", "hovertext"); + if (lib.isValidTextValue(htx)) return fill(htx); + var tx = lib.extractOption(calcPt, trace, "tx", "text"); + if (lib.isValidTextValue(tx)) return fill(tx); +}; +lib.isValidTextValue = function(v) { + return v || v === 0; +}; +lib.formatPercent = function(ratio, n) { + n = n || 0; + var str2 = (Math.round(100 * ratio * Math.pow(10, n)) * Math.pow(0.1, n)).toFixed(n) + "%"; + for (var i = 0; i < n; i++) { + if (str2.indexOf(".") !== -1) { + str2 = str2.replace("0%", "%"); + str2 = str2.replace(".%", "%"); + } + } + return str2; +}; +lib.isHidden = function(gd) { + var display = window.getComputedStyle(gd).display; + return !display || display === "none"; +}; +lib.strTranslate = function(x, y) { + return x || y ? "translate(" + x + "," + y + ")" : ""; +}; +lib.strRotate = function(a) { + return a ? "rotate(" + a + ")" : ""; +}; +lib.strScale = function(s) { + return s !== 1 ? "scale(" + s + ")" : ""; +}; +lib.getTextTransform = function(transform) { + var noCenter = transform.noCenter; + var textX = transform.textX; + var textY = transform.textY; + var targetX = transform.targetX; + var targetY = transform.targetY; + var anchorX = transform.anchorX || 0; + var anchorY = transform.anchorY || 0; + var rotate2 = transform.rotate; + var scale2 = transform.scale; + if (!scale2) scale2 = 0; + else if (scale2 > 1) scale2 = 1; + return lib.strTranslate( + targetX - scale2 * (textX + anchorX), + targetY - scale2 * (textY + anchorY) + ) + lib.strScale(scale2) + (rotate2 ? "rotate(" + rotate2 + (noCenter ? "" : " " + textX + " " + textY) + ")" : ""); +}; +lib.setTransormAndDisplay = function(s, transform) { + s.attr("transform", lib.getTextTransform(transform)); + s.style("display", transform.scale ? null : "none"); +}; +lib.ensureUniformFontSize = function(gd, baseFont) { + var out = lib.extendFlat({}, baseFont); + out.size = Math.max( + baseFont.size, + gd._fullLayout.uniformtext.minsize || 0 + ); + return out; +}; +lib.join2 = function(arr, mainSeparator, lastSeparator) { + var len = arr.length; + if (len > 1) { + return arr.slice(0, -1).join(mainSeparator) + lastSeparator + arr[len - 1]; + } + return arr.join(mainSeparator); +}; +lib.bigFont = function(size) { + return Math.round(1.2 * size); +}; +var firefoxVersion = lib.getFirefoxVersion(); +var isProblematicFirefox = firefoxVersion !== null && firefoxVersion < 86; +lib.getPositionFromD3Event = function() { + if (isProblematicFirefox) { + return [ + d3$C.event.layerX, + d3$C.event.layerY + ]; + } else { + return [ + d3$C.event.offsetX, + d3$C.event.offsetY + ]; + } +}; +var libExports = lib$1.exports; +var Lib$1Z = libExports; +var rules = { + "X,X div": 'direction:ltr;font-family:"Open Sans",verdana,arial,sans-serif;margin:0;padding:0;', + "X input,X button": 'font-family:"Open Sans",verdana,arial,sans-serif;', + "X input:focus,X button:focus": "outline:none;", + "X a": "text-decoration:none;", + "X a:hover": "text-decoration:none;", + "X .crisp": "shape-rendering:crispEdges;", + "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;", + "X svg": "overflow:hidden;", + "X svg a": "fill:#447adb;", + "X svg a:hover": "fill:#3c6dc5;", + "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;", + "X .main-svg .draglayer": "pointer-events:all;", + "X .cursor-default": "cursor:default;", + "X .cursor-pointer": "cursor:pointer;", + "X .cursor-crosshair": "cursor:crosshair;", + "X .cursor-move": "cursor:move;", + "X .cursor-col-resize": "cursor:col-resize;", + "X .cursor-row-resize": "cursor:row-resize;", + "X .cursor-ns-resize": "cursor:ns-resize;", + "X .cursor-ew-resize": "cursor:ew-resize;", + "X .cursor-sw-resize": "cursor:sw-resize;", + "X .cursor-s-resize": "cursor:s-resize;", + "X .cursor-se-resize": "cursor:se-resize;", + "X .cursor-w-resize": "cursor:w-resize;", + "X .cursor-e-resize": "cursor:e-resize;", + "X .cursor-nw-resize": "cursor:nw-resize;", + "X .cursor-n-resize": "cursor:n-resize;", + "X .cursor-ne-resize": "cursor:ne-resize;", + "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;", + "X .modebar": "position:absolute;top:2px;right:2px;", + "X .ease-bg": "-webkit-transition:background-color .3s ease 0s;-moz-transition:background-color .3s ease 0s;-ms-transition:background-color .3s ease 0s;-o-transition:background-color .3s ease 0s;transition:background-color .3s ease 0s;", + "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity .3s ease 0s;-moz-transition:opacity .3s ease 0s;-ms-transition:opacity .3s ease 0s;-o-transition:opacity .3s ease 0s;transition:opacity .3s ease 0s;", + "X:hover .modebar--hover .modebar-group": "opacity:1;", + "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", + "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;", + "X .modebar-btn svg": "position:relative;top:2px;", + "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;", + "X .modebar.vertical svg": "top:-1px;", + "X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;", + "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;", + "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;", + "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;", + "X [data-title]:before": 'content:"";position:absolute;background:rgba(0,0,0,0);border:6px solid rgba(0,0,0,0);z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;', + "X [data-title]:after": "content:attr(data-title);background:#69738a;color:#fff;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;", + "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;", + "X .vertical [data-title]:before": "border:6px solid rgba(0,0,0,0);border-left-color:#69738a;margin-top:8px;margin-right:-30px;", + Y: 'font-family:"Open Sans",verdana,arial,sans-serif;position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;', + "Y p": "margin:0;", + "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;", + "Y .notifier-close": "color:#fff;opacity:.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;", + "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;" +}; +for (var selector in rules) { + var fullSelector = selector.replace(/^,/, " ,").replace(/X/g, ".js-plotly-plot .plotly").replace(/Y/g, ".plotly-notifier"); + Lib$1Z.addStyleRule(fullSelector, rules[selector]); +} +var plot_api$1 = {}; +var plot_api = {}; +var client = true; +var isBrowser = client; +var hasHover$1; +if (typeof index$3.commonjsGlobal.matchMedia === "function") { + hasHover$1 = !index$3.commonjsGlobal.matchMedia("(hover: none)").matches; +} else { + hasHover$1 = isBrowser; +} +var hasHover_1 = hasHover$1; +var events$1 = { exports: {} }; +var R = typeof Reflect === "object" ? Reflect : null; +var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); +}; +var ReflectOwnKeys; +if (R && typeof R.ownKeys === "function") { + ReflectOwnKeys = R.ownKeys; +} else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); + }; +} else { + ReflectOwnKeys = function ReflectOwnKeys2(target) { + return Object.getOwnPropertyNames(target); + }; +} +function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); +} +var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value2) { + return value2 !== value2; +}; +function EventEmitter$3() { + EventEmitter$3.init.call(this); +} +events$1.exports = EventEmitter$3; +events$1.exports.once = once2; +EventEmitter$3.EventEmitter = EventEmitter$3; +EventEmitter$3.prototype._events = void 0; +EventEmitter$3.prototype._eventsCount = 0; +EventEmitter$3.prototype._maxListeners = void 0; +var defaultMaxListeners = 10; +function checkListener(listener) { + if (typeof listener !== "function") { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } +} +Object.defineProperty(EventEmitter$3, "defaultMaxListeners", { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); + } + defaultMaxListeners = arg; + } +}); +EventEmitter$3.init = function() { + if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } + this._maxListeners = this._maxListeners || void 0; +}; +EventEmitter$3.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); + } + this._maxListeners = n; + return this; +}; +function _getMaxListeners(that) { + if (that._maxListeners === void 0) + return EventEmitter$3.defaultMaxListeners; + return that._maxListeners; +} +EventEmitter$3.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); +}; +EventEmitter$3.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = type === "error"; + var events2 = this._events; + if (events2 !== void 0) + doError = doError && events2.error === void 0; + else if (!doError) + return false; + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + throw er; + } + var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); + err.context = er; + throw err; + } + var handler = events2[type]; + if (handler === void 0) + return false; + if (typeof handler === "function") { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners2 = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners2[i], this, args); + } + return true; +}; +function _addListener(target, type, listener, prepend) { + var m; + var events2; + var existing; + checkListener(listener); + events2 = target._events; + if (events2 === void 0) { + events2 = target._events = /* @__PURE__ */ Object.create(null); + target._eventsCount = 0; + } else { + if (events2.newListener !== void 0) { + target.emit( + "newListener", + type, + listener.listener ? listener.listener : listener + ); + events2 = target._events; + } + existing = events2[type]; + } + if (existing === void 0) { + existing = events2[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === "function") { + existing = events2[type] = prepend ? [listener, existing] : [existing, listener]; + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); + w.name = "MaxListenersExceededWarning"; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + return target; +} +EventEmitter$3.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); +}; +EventEmitter$3.prototype.on = EventEmitter$3.prototype.addListener; +EventEmitter$3.prototype.prependListener = function prependListener(type, listener) { + return _addListener(this, type, listener, true); +}; +function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } +} +function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: void 0, target, type, listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; +} +EventEmitter$3.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; +}; +EventEmitter$3.prototype.prependOnceListener = function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; +}; +EventEmitter$3.prototype.removeListener = function removeListener(type, listener) { + var list, events2, position, i, originalListener; + checkListener(listener); + events2 = this._events; + if (events2 === void 0) + return this; + list = events2[type]; + if (list === void 0) + return this; + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else { + delete events2[type]; + if (events2.removeListener) + this.emit("removeListener", type, list.listener || listener); + } + } else if (typeof list !== "function") { + position = -1; + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + if (position < 0) + return this; + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + if (list.length === 1) + events2[type] = list[0]; + if (events2.removeListener !== void 0) + this.emit("removeListener", type, originalListener || listener); + } + return this; +}; +EventEmitter$3.prototype.off = EventEmitter$3.prototype.removeListener; +EventEmitter$3.prototype.removeAllListeners = function removeAllListeners(type) { + var listeners2, events2, i; + events2 = this._events; + if (events2 === void 0) + return this; + if (events2.removeListener === void 0) { + if (arguments.length === 0) { + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + } else if (events2[type] !== void 0) { + if (--this._eventsCount === 0) + this._events = /* @__PURE__ */ Object.create(null); + else + delete events2[type]; + } + return this; + } + if (arguments.length === 0) { + var keys = Object.keys(events2); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === "removeListener") continue; + this.removeAllListeners(key); + } + this.removeAllListeners("removeListener"); + this._events = /* @__PURE__ */ Object.create(null); + this._eventsCount = 0; + return this; + } + listeners2 = events2[type]; + if (typeof listeners2 === "function") { + this.removeListener(type, listeners2); + } else if (listeners2 !== void 0) { + for (i = listeners2.length - 1; i >= 0; i--) { + this.removeListener(type, listeners2[i]); + } + } + return this; +}; +function _listeners(target, type, unwrap) { + var events2 = target._events; + if (events2 === void 0) + return []; + var evlistener = events2[type]; + if (evlistener === void 0) + return []; + if (typeof evlistener === "function") + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); +} +EventEmitter$3.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); +}; +EventEmitter$3.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); +}; +EventEmitter$3.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === "function") { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } +}; +EventEmitter$3.prototype.listenerCount = listenerCount; +function listenerCount(type) { + var events2 = this._events; + if (events2 !== void 0) { + var evlistener = events2[type]; + if (typeof evlistener === "function") { + return 1; + } else if (evlistener !== void 0) { + return evlistener.length; + } + } + return 0; +} +EventEmitter$3.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; +}; +function arrayClone(arr, n) { + var copy2 = new Array(n); + for (var i = 0; i < n; ++i) + copy2[i] = arr[i]; + return copy2; +} +function spliceOne(list, index2) { + for (; index2 + 1 < list.length; index2++) + list[index2] = list[index2 + 1]; + list.pop(); +} +function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; +} +function once2(emitter, name2) { + return new Promise(function(resolve, reject) { + function errorListener(err) { + emitter.removeListener(name2, resolver); + reject(err); + } + function resolver() { + if (typeof emitter.removeListener === "function") { + emitter.removeListener("error", errorListener); + } + resolve([].slice.call(arguments)); + } + eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); + if (name2 !== "error") { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); +} +function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === "function") { + eventTargetAgnosticAddListener(emitter, "error", handler, flags); + } +} +function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { + if (typeof emitter.on === "function") { + if (flags.once) { + emitter.once(name2, listener); + } else { + emitter.on(name2, listener); + } + } else if (typeof emitter.addEventListener === "function") { + emitter.addEventListener(name2, function wrapListener(arg) { + if (flags.once) { + emitter.removeEventListener(name2, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } +} +var eventsExports = events$1.exports; +var EventEmitter$2 = eventsExports.EventEmitter; +var Events$4 = { + init: function(plotObj) { + if (plotObj._ev instanceof EventEmitter$2) return plotObj; + var ev = new EventEmitter$2(); + var internalEv = new EventEmitter$2(); + plotObj._ev = ev; + plotObj._internalEv = internalEv; + plotObj.on = ev.on.bind(ev); + plotObj.once = ev.once.bind(ev); + plotObj.removeListener = ev.removeListener.bind(ev); + plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); + plotObj._internalOn = internalEv.on.bind(internalEv); + plotObj._internalOnce = internalEv.once.bind(internalEv); + plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); + plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); + plotObj.emit = function(event, data) { + if (typeof jQuery !== "undefined") { + jQuery(plotObj).trigger(event, data); + } + ev.emit(event, data); + internalEv.emit(event, data); + }; + return plotObj; + }, + /* + * This function behaves like jQuery's triggerHandler. It calls + * all handlers for a particular event and returns the return value + * of the LAST handler. This function also triggers jQuery's + * triggerHandler for backwards compatibility. + */ + triggerHandler: function(plotObj, event, data) { + var jQueryHandlerValue; + var nodeEventHandlerValue; + if (typeof jQuery !== "undefined") { + jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); + } + var ev = plotObj._ev; + if (!ev) return jQueryHandlerValue; + var handlers = ev._events[event]; + if (!handlers) return jQueryHandlerValue; + function apply(handler) { + if (handler.listener) { + ev.removeListener(event, handler.listener); + if (!handler.fired) { + handler.fired = true; + return handler.listener.apply(ev, [data]); + } + } else { + return handler.apply(ev, [data]); + } + } + handlers = Array.isArray(handlers) ? handlers : [handlers]; + var i; + for (i = 0; i < handlers.length - 1; i++) { + apply(handlers[i]); + } + nodeEventHandlerValue = apply(handlers[i]); + return jQueryHandlerValue !== void 0 ? jQueryHandlerValue : nodeEventHandlerValue; + }, + purge: function(plotObj) { + delete plotObj._ev; + delete plotObj.on; + delete plotObj.once; + delete plotObj.removeListener; + delete plotObj.removeAllListeners; + delete plotObj.emit; + delete plotObj._ev; + delete plotObj._internalEv; + delete plotObj._internalOn; + delete plotObj._internalOnce; + delete plotObj._removeInternalListener; + delete plotObj._removeAllInternalListeners; + return plotObj; + } +}; +var events = Events$4; +var Lib$1Y = libExports; +var dfltConfig$2 = plot_config.dfltConfig; +function copyArgArray(gd, args) { + var copy2 = []; + var arg; + for (var i = 0; i < args.length; i++) { + arg = args[i]; + if (arg === gd) copy2[i] = arg; + else if (typeof arg === "object") { + copy2[i] = Array.isArray(arg) ? Lib$1Y.extendDeep([], arg) : Lib$1Y.extendDeepAll({}, arg); + } else copy2[i] = arg; + } + return copy2; +} +var queue = {}; +queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { + var queueObj, queueIndex; + gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; + queueIndex = gd.undoQueue.index; + if (gd.autoplay) { + if (!gd.undoQueue.inSequence) gd.autoplay = false; + return; + } + if (!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { + queueObj = { undo: { calls: [], args: [] }, redo: { calls: [], args: [] } }; + gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); + gd.undoQueue.index += 1; + } else { + queueObj = gd.undoQueue.queue[queueIndex - 1]; + } + gd.undoQueue.beginSequence = false; + if (queueObj) { + queueObj.undo.calls.unshift(undoFunc); + queueObj.undo.args.unshift(undoArgs); + queueObj.redo.calls.push(redoFunc); + queueObj.redo.args.push(redoArgs); + } + if (gd.undoQueue.queue.length > dfltConfig$2.queueLength) { + gd.undoQueue.queue.shift(); + gd.undoQueue.index--; + } +}; +queue.startSequence = function(gd) { + gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; + gd.undoQueue.sequence = true; + gd.undoQueue.beginSequence = true; +}; +queue.stopSequence = function(gd) { + gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; + gd.undoQueue.sequence = false; + gd.undoQueue.beginSequence = false; +}; +queue.undo = function undo(gd) { + var queueObj, i; + if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index <= 0) { + return; + } + gd.undoQueue.index--; + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + gd.undoQueue.inSequence = true; + for (i = 0; i < queueObj.undo.calls.length; i++) { + queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; +}; +queue.redo = function redo(gd) { + var queueObj, i; + if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index >= gd.undoQueue.queue.length) { + return; + } + queueObj = gd.undoQueue.queue[gd.undoQueue.index]; + gd.undoQueue.inSequence = true; + for (i = 0; i < queueObj.redo.calls.length; i++) { + queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); + } + gd.undoQueue.inSequence = false; + gd.autoplay = false; + gd.undoQueue.index++; +}; +queue.plotDo = function(gd, func, args) { + gd.autoplay = true; + args = copyArgArray(gd, args); + func.apply(null, args); +}; +var queue_1 = queue; +var plot_schema = {}; +var frame_attributes = { + _isLinkedToArray: "frames_entry", + group: { + valType: "string", + description: [ + "An identifier that specifies the group to which the frame belongs,", + "used by animate to select a subset of frames." + ].join(" ") + }, + name: { + valType: "string", + description: "A label by which to identify the frame" + }, + traces: { + valType: "any", + description: [ + "A list of trace indices that identify the respective traces in the", + "data attribute" + ].join(" ") + }, + baseframe: { + valType: "string", + description: [ + "The name of the frame into which this frame's properties are merged", + "before applying. This is used to unify properties and avoid needing", + "to specify the same values for the same properties in multiple frames." + ].join(" ") + }, + data: { + valType: "any", + description: [ + "A list of traces this frame modifies. The format is identical to the", + "normal trace definition." + ].join(" ") + }, + layout: { + valType: "any", + description: [ + "Layout properties which this frame modifies. The format is identical", + "to the normal layout definition." + ].join(" ") + } +}; +(function(exports2) { + var Registry2 = registry; + var Lib2 = libExports; + var baseAttributes = attributes$O; + var baseLayoutAttributes = layout_attributes$6; + var frameAttributes = frame_attributes; + var animationAttributes = animation_attributes; + var configAttributes2 = plot_config.configAttributes; + var editTypes = edit_types; + var extendDeepAll2 = Lib2.extendDeepAll; + var isPlainObject3 = Lib2.isPlainObject; + var isArrayOrTypedArray2 = Lib2.isArrayOrTypedArray; + var nestedProperty3 = Lib2.nestedProperty; + var valObjectMeta = Lib2.valObjectMeta; + var IS_SUBPLOT_OBJ = "_isSubplotObj"; + var IS_LINKED_TO_ARRAY = "_isLinkedToArray"; + var ARRAY_ATTR_REGEXPS = "_arrayAttrRegexps"; + var DEPRECATED = "_deprecated"; + var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; + exports2.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; + exports2.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; + exports2.DEPRECATED = DEPRECATED; + exports2.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; + exports2.get = function() { + var traces = {}; + Registry2.allTypes.forEach(function(type) { + traces[type] = getTraceAttributes(type); + }); + var transforms = {}; + Object.keys(Registry2.transformsRegistry).forEach(function(type) { + transforms[type] = getTransformAttributes(type); + }); + return { + defs: { + valObjects: valObjectMeta, + metaKeys: UNDERSCORE_ATTRS.concat(["description", "role", "editType", "impliedEdits"]), + editType: { + traces: editTypes.traces, + layout: editTypes.layout + }, + impliedEdits: { + description: [ + "Sometimes when an attribute is changed, other attributes", + "must be altered as well in order to achieve the intended", + "result. For example, when `range` is specified, it is", + "important to set `autorange` to `false` or the new `range`", + "value would be lost in the redraw. `impliedEdits` is the", + "mechanism to do this: `impliedEdits: {autorange: false}`.", + "Each key is a relative paths to the attribute string to", + "change, using *^* to ascend into the parent container,", + "for example `range[0]` has `impliedEdits: {*^autorange*: false}`.", + "A value of `undefined` means that the attribute will not be", + "changed, but its previous value should be recorded in case", + "we want to reverse this change later. For example, `autorange`", + "has `impliedEdits: {*range[0]*: undefined, *range[1]*:undefined}", + "because the range will likely be changed by redraw." + ].join(" ") + } + }, + traces, + layout: getLayoutAttributes(), + transforms, + frames: getFramesAttributes(), + animation: formatAttributes(animationAttributes), + config: formatAttributes(configAttributes2) + }; + }; + exports2.crawl = function(attrs2, callback, specifiedLevel, attrString) { + var level = specifiedLevel || 0; + attrString = attrString || ""; + Object.keys(attrs2).forEach(function(attrName) { + var attr = attrs2[attrName]; + if (UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return; + var fullAttrString = (attrString ? attrString + "." : "") + attrName; + callback(attr, attrName, attrs2, level, fullAttrString); + if (exports2.isValObject(attr)) return; + if (isPlainObject3(attr) && attrName !== "impliedEdits") { + exports2.crawl(attr, callback, level + 1, fullAttrString); + } + }); + }; + exports2.isValObject = function(obj) { + return obj && obj.valType !== void 0; + }; + exports2.findArrayAttributes = function(trace) { + var arrayAttributes = []; + var stack = []; + var isArrayStack = []; + var baseContainer, baseAttrName; + function callback(attr, attrName, attrs2, level) { + stack = stack.slice(0, level).concat([attrName]); + isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]); + var splittableAttr = attr && (attr.valType === "data_array" || attr.arrayOk === true) && !(stack[level - 1] === "colorbar" && (attrName === "ticktext" || attrName === "tickvals")); + if (!splittableAttr) return; + crawlIntoTrace(baseContainer, 0, ""); + } + function crawlIntoTrace(container, i2, astrPartial) { + var item = container[stack[i2]]; + var newAstrPartial = astrPartial + stack[i2]; + if (i2 === stack.length - 1) { + if (isArrayOrTypedArray2(item)) { + arrayAttributes.push(baseAttrName + newAstrPartial); + } + } else { + if (isArrayStack[i2]) { + if (Array.isArray(item)) { + for (var j = 0; j < item.length; j++) { + if (isPlainObject3(item[j])) { + crawlIntoTrace(item[j], i2 + 1, newAstrPartial + "[" + j + "]."); + } + } + } + } else if (isPlainObject3(item)) { + crawlIntoTrace(item, i2 + 1, newAstrPartial + "."); + } + } + } + baseContainer = trace; + baseAttrName = ""; + exports2.crawl(baseAttributes, callback); + if (trace._module && trace._module.attributes) { + exports2.crawl(trace._module.attributes, callback); + } + var transforms = trace.transforms; + if (transforms) { + for (var i = 0; i < transforms.length; i++) { + var transform = transforms[i]; + var module2 = transform._module; + if (module2) { + baseAttrName = "transforms[" + i + "]."; + baseContainer = transform; + exports2.crawl(module2.attributes, callback); + } + } + } + return arrayAttributes; + }; + exports2.getTraceValObject = function(trace, parts) { + var head = parts[0]; + var i = 1; + var moduleAttrs, valObject; + if (head === "transforms") { + if (parts.length === 1) { + return baseAttributes.transforms; + } + var transforms = trace.transforms; + if (!Array.isArray(transforms) || !transforms.length) return false; + var tNum = parts[1]; + if (!isIndex(tNum) || tNum >= transforms.length) { + return false; + } + moduleAttrs = (Registry2.transformsRegistry[transforms[tNum].type] || {}).attributes; + valObject = moduleAttrs && moduleAttrs[parts[2]]; + i = 3; + } else { + var _module = trace._module; + if (!_module) _module = (Registry2.modules[trace.type || baseAttributes.type.dflt] || {})._module; + if (!_module) return false; + moduleAttrs = _module.attributes; + valObject = moduleAttrs && moduleAttrs[head]; + if (!valObject) { + var subplotModule = _module.basePlotModule; + if (subplotModule && subplotModule.attributes) { + valObject = subplotModule.attributes[head]; + } + } + if (!valObject) valObject = baseAttributes[head]; + } + return recurseIntoValObject(valObject, parts, i); + }; + exports2.getLayoutValObject = function(fullLayout, parts) { + var valObject = layoutHeadAttr(fullLayout, parts[0]); + return recurseIntoValObject(valObject, parts, 1); + }; + function layoutHeadAttr(fullLayout, head) { + var i, key, _module, attributes2; + var basePlotModules = fullLayout._basePlotModules; + if (basePlotModules) { + var out; + for (i = 0; i < basePlotModules.length; i++) { + _module = basePlotModules[i]; + if (_module.attrRegex && _module.attrRegex.test(head)) { + if (_module.layoutAttrOverrides) return _module.layoutAttrOverrides; + if (!out && _module.layoutAttributes) out = _module.layoutAttributes; + } + var baseOverrides = _module.baseLayoutAttrOverrides; + if (baseOverrides && head in baseOverrides) return baseOverrides[head]; + } + if (out) return out; + } + var modules2 = fullLayout._modules; + if (modules2) { + for (i = 0; i < modules2.length; i++) { + attributes2 = modules2[i].layoutAttributes; + if (attributes2 && head in attributes2) { + return attributes2[head]; + } + } + } + for (key in Registry2.componentsRegistry) { + _module = Registry2.componentsRegistry[key]; + if (_module.name === "colorscale" && head.indexOf("coloraxis") === 0) { + return _module.layoutAttributes[head]; + } else if (!_module.schema && head === _module.name) { + return _module.layoutAttributes; + } + } + if (head in baseLayoutAttributes) return baseLayoutAttributes[head]; + return false; + } + function recurseIntoValObject(valObject, parts, i) { + if (!valObject) return false; + if (valObject._isLinkedToArray) { + if (isIndex(parts[i])) i++; + else if (i < parts.length) return false; + } + for (; i < parts.length; i++) { + var newValObject = valObject[parts[i]]; + if (isPlainObject3(newValObject)) valObject = newValObject; + else break; + if (i === parts.length - 1) break; + if (valObject._isLinkedToArray) { + i++; + if (!isIndex(parts[i])) return false; + } else if (valObject.valType === "info_array") { + i++; + var index2 = parts[i]; + if (!isIndex(index2)) return false; + var items = valObject.items; + if (Array.isArray(items)) { + if (index2 >= items.length) return false; + if (valObject.dimensions === 2) { + i++; + if (parts.length === i) return valObject; + var index22 = parts[i]; + if (!isIndex(index22)) return false; + valObject = items[index2][index22]; + } else valObject = items[index2]; + } else { + valObject = items; + } + } + } + return valObject; + } + function isIndex(val) { + return val === Math.round(val) && val >= 0; + } + function getTraceAttributes(type) { + var _module, basePlotModule; + _module = Registry2.modules[type]._module, basePlotModule = _module.basePlotModule; + var attributes2 = {}; + attributes2.type = null; + var copyBaseAttributes = extendDeepAll2({}, baseAttributes); + var copyModuleAttributes = extendDeepAll2({}, _module.attributes); + exports2.crawl(copyModuleAttributes, function(attr, attrName, attrs2, level, fullAttrString) { + nestedProperty3(copyBaseAttributes, fullAttrString).set(void 0); + if (attr === void 0) nestedProperty3(copyModuleAttributes, fullAttrString).set(void 0); + }); + extendDeepAll2(attributes2, copyBaseAttributes); + if (Registry2.traceIs(type, "noOpacity")) { + delete attributes2.opacity; + } + if (!Registry2.traceIs(type, "showLegend")) { + delete attributes2.showlegend; + delete attributes2.legendgroup; + } + if (Registry2.traceIs(type, "noHover")) { + delete attributes2.hoverinfo; + delete attributes2.hoverlabel; + } + if (!_module.selectPoints) { + delete attributes2.selectedpoints; + } + extendDeepAll2(attributes2, copyModuleAttributes); + if (basePlotModule.attributes) { + extendDeepAll2(attributes2, basePlotModule.attributes); + } + attributes2.type = type; + var out = { + meta: _module.meta || {}, + categories: _module.categories || {}, + animatable: Boolean(_module.animatable), + type, + attributes: formatAttributes(attributes2) + }; + if (_module.layoutAttributes) { + var layoutAttributes2 = {}; + extendDeepAll2(layoutAttributes2, _module.layoutAttributes); + out.layoutAttributes = formatAttributes(layoutAttributes2); + } + if (!_module.animatable) { + exports2.crawl(out, function(attr) { + if (exports2.isValObject(attr) && "anim" in attr) { + delete attr.anim; + } + }); + } + return out; + } + function getLayoutAttributes() { + var layoutAttributes2 = {}; + var key, _module; + extendDeepAll2(layoutAttributes2, baseLayoutAttributes); + for (key in Registry2.subplotsRegistry) { + _module = Registry2.subplotsRegistry[key]; + if (!_module.layoutAttributes) continue; + if (Array.isArray(_module.attr)) { + for (var i = 0; i < _module.attr.length; i++) { + handleBasePlotModule(layoutAttributes2, _module, _module.attr[i]); + } + } else { + var astr = _module.attr === "subplot" ? _module.name : _module.attr; + handleBasePlotModule(layoutAttributes2, _module, astr); + } + } + for (key in Registry2.componentsRegistry) { + _module = Registry2.componentsRegistry[key]; + var schema = _module.schema; + if (schema && (schema.subplots || schema.layout)) { + var subplots = schema.subplots; + if (subplots && subplots.xaxis && !subplots.yaxis) { + for (var xkey in subplots.xaxis) { + delete layoutAttributes2.yaxis[xkey]; + } + } + delete layoutAttributes2.xaxis.shift; + delete layoutAttributes2.xaxis.autoshift; + } else if (_module.name === "colorscale") { + extendDeepAll2(layoutAttributes2, _module.layoutAttributes); + } else if (_module.layoutAttributes) { + insertAttrs(layoutAttributes2, _module.layoutAttributes, _module.name); + } + } + return { + layoutAttributes: formatAttributes(layoutAttributes2) + }; + } + function getTransformAttributes(type) { + var _module = Registry2.transformsRegistry[type]; + var attributes2 = extendDeepAll2({}, _module.attributes); + Object.keys(Registry2.componentsRegistry).forEach(function(k) { + var _module2 = Registry2.componentsRegistry[k]; + if (_module2.schema && _module2.schema.transforms && _module2.schema.transforms[type]) { + Object.keys(_module2.schema.transforms[type]).forEach(function(v) { + insertAttrs(attributes2, _module2.schema.transforms[type][v], v); + }); + } + }); + return { + attributes: formatAttributes(attributes2) + }; + } + function getFramesAttributes() { + var attrs2 = { + frames: extendDeepAll2({}, frameAttributes) + }; + formatAttributes(attrs2); + return attrs2.frames; + } + function formatAttributes(attrs2) { + mergeValTypeAndRole(attrs2); + formatArrayContainers(attrs2); + stringify2(attrs2); + return attrs2; + } + function mergeValTypeAndRole(attrs2) { + function makeSrcAttr(attrName) { + return { + valType: "string", + description: "Sets the source reference on Chart Studio Cloud for `" + attrName + "`.", + editType: "none" + }; + } + function callback(attr, attrName, attrs3) { + if (exports2.isValObject(attr)) { + if (attr.arrayOk === true || attr.valType === "data_array") { + attrs3[attrName + "src"] = makeSrcAttr(attrName); + } + } else if (isPlainObject3(attr)) { + attr.role = "object"; + } + } + exports2.crawl(attrs2, callback); + } + function formatArrayContainers(attrs2) { + function callback(attr, attrName, attrs3) { + if (!attr) return; + var itemName = attr[IS_LINKED_TO_ARRAY]; + if (!itemName) return; + delete attr[IS_LINKED_TO_ARRAY]; + attrs3[attrName] = { items: {} }; + attrs3[attrName].items[itemName] = attr; + attrs3[attrName].role = "object"; + } + exports2.crawl(attrs2, callback); + } + function stringify2(attrs2) { + function walk(attr) { + for (var k in attr) { + if (isPlainObject3(attr[k])) { + walk(attr[k]); + } else if (Array.isArray(attr[k])) { + for (var i = 0; i < attr[k].length; i++) { + walk(attr[k][i]); + } + } else { + if (attr[k] instanceof RegExp) { + attr[k] = attr[k].toString(); + } + } + } + } + walk(attrs2); + } + function handleBasePlotModule(layoutAttributes2, _module, astr) { + var np = nestedProperty3(layoutAttributes2, astr); + var attrs2 = extendDeepAll2({}, _module.layoutAttributes); + attrs2[IS_SUBPLOT_OBJ] = true; + np.set(attrs2); + } + function insertAttrs(baseAttrs2, newAttrs, astr) { + var np = nestedProperty3(baseAttrs2, astr); + np.set(extendDeepAll2(np.get() || {}, newAttrs)); + } +})(plot_schema); +var plots$2 = { exports: {} }; +var plot_template = {}; +var Lib$1X = libExports; +var plotAttributes$1 = attributes$O; +var TEMPLATEITEMNAME = "templateitemname"; +var templateAttrs = { + name: { + valType: "string", + editType: "none", + description: [ + "When used in a template, named items are created in the output figure", + "in addition to any items the figure already has in this array.", + "You can modify these items in the output figure by making your own", + "item with `templateitemname` matching this `name`", + "alongside your modifications (including `visible: false` or", + "`enabled: false` to hide it).", + "Has no effect outside of a template." + ].join(" ") + } +}; +templateAttrs[TEMPLATEITEMNAME] = { + valType: "string", + editType: "calc", + description: [ + "Used to refer to a named item in this array in the template. Named", + "items from the template will be created even without a matching item", + "in the input figure, but you can modify one by making an item with", + "`templateitemname` matching its `name`, alongside your modifications", + "(including `visible: false` or `enabled: false` to hide it).", + "If there is no template or no matching item, this item will be", + "hidden unless you explicitly show it with `visible: true`." + ].join(" ") +}; +plot_template.templatedArray = function(name2, attrs2) { + attrs2._isLinkedToArray = name2; + attrs2.name = templateAttrs.name; + attrs2[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME]; + return attrs2; +}; +plot_template.traceTemplater = function(dataTemplate) { + var traceCounts = {}; + var traceType, typeTemplates; + for (traceType in dataTemplate) { + typeTemplates = dataTemplate[traceType]; + if (Array.isArray(typeTemplates) && typeTemplates.length) { + traceCounts[traceType] = 0; + } + } + function newTrace(traceIn) { + traceType = Lib$1X.coerce(traceIn, {}, plotAttributes$1, "type"); + var traceOut = { type: traceType, _template: null }; + if (traceType in traceCounts) { + typeTemplates = dataTemplate[traceType]; + var typei = traceCounts[traceType] % typeTemplates.length; + traceCounts[traceType]++; + traceOut._template = typeTemplates[typei]; + } + return traceOut; + } + return { + newTrace + // TODO: function to figure out what's left & what didn't work + }; +}; +plot_template.newContainer = function(container, name2, baseName) { + var template = container._template; + var part = template && (template[name2] || baseName && template[baseName]); + if (!Lib$1X.isPlainObject(part)) part = null; + var out = container[name2] = { _template: part }; + return out; +}; +plot_template.arrayTemplater = function(container, name2, inclusionAttr) { + var template = container._template; + var defaultsTemplate = template && template[arrayDefaultKey(name2)]; + var templateItems = template && template[name2]; + if (!Array.isArray(templateItems) || !templateItems.length) { + templateItems = []; + } + var usedNames = {}; + function newItem(itemIn) { + var out = { name: itemIn.name, _input: itemIn }; + var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME]; + if (!validItemName(templateItemName)) { + out._template = defaultsTemplate; + return out; + } + for (var i = 0; i < templateItems.length; i++) { + var templateItem = templateItems[i]; + if (templateItem.name === templateItemName) { + usedNames[templateItemName] = 1; + out._template = templateItem; + return out; + } + } + out[inclusionAttr] = itemIn[inclusionAttr] || false; + out._template = false; + return out; + } + function defaultItems() { + var out = []; + for (var i = 0; i < templateItems.length; i++) { + var templateItem = templateItems[i]; + var name3 = templateItem.name; + if (validItemName(name3) && !usedNames[name3]) { + var outi = { + _template: templateItem, + name: name3, + _input: { _templateitemname: name3 } + }; + outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME]; + out.push(outi); + usedNames[name3] = 1; + } + } + return out; + } + return { + newItem, + defaultItems + }; +}; +function validItemName(name2) { + return name2 && typeof name2 === "string"; +} +function arrayDefaultKey(name2) { + var lastChar = name2.length - 1; + if (name2.charAt(lastChar) !== "s") { + Lib$1X.warn("bad argument to arrayDefaultKey: " + name2); + } + return name2.substr(0, name2.length - 1) + "defaults"; +} +plot_template.arrayDefaultKey = arrayDefaultKey; +plot_template.arrayEditor = function(parentIn, containerStr, itemOut) { + var lengthIn = (Lib$1X.nestedProperty(parentIn, containerStr).get() || []).length; + var index2 = itemOut._index; + var templateItemName = index2 >= lengthIn && (itemOut._input || {})._templateitemname; + if (templateItemName) index2 = lengthIn; + var itemStr = containerStr + "[" + index2 + "]"; + var update2; + function resetUpdate() { + update2 = {}; + if (templateItemName) { + update2[itemStr] = {}; + update2[itemStr][TEMPLATEITEMNAME] = templateItemName; + } + } + resetUpdate(); + function modifyBase(attr, value2) { + update2[attr] = value2; + } + function modifyItem(attr, value2) { + if (templateItemName) { + Lib$1X.nestedProperty(update2[itemStr], attr).set(value2); + } else { + update2[itemStr + "." + attr] = value2; + } + } + function getUpdateObj() { + var updateOut = update2; + resetUpdate(); + return updateOut; + } + function applyUpdate(attr, value2) { + if (attr) modifyItem(attr, value2); + var updateToApply = getUpdateObj(); + for (var key in updateToApply) { + Lib$1X.nestedProperty(parentIn, key).set(updateToApply[key]); + } + } + return { + modifyBase, + modifyItem, + getUpdateObj, + applyUpdate + }; +}; +var axis_ids = {}; +var counterRegex$2 = regex.counter; +var constants$U = { + idRegex: { + x: counterRegex$2("x", "( domain)?"), + y: counterRegex$2("y", "( domain)?") + }, + attrRegex: counterRegex$2("[xy]axis"), + // axis match regular expression + xAxisMatch: counterRegex$2("xaxis"), + yAxisMatch: counterRegex$2("yaxis"), + // pattern matching axis ids and names + // note that this is more permissive than counterRegex, as + // id2name, name2id, and cleanId accept "x1" etc + AX_ID_PATTERN: /^[xyz][0-9]*( domain)?$/, + AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/, + // and for 2D subplots + SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/, + HOUR_PATTERN: "hour", + WEEKDAY_PATTERN: "day of week", + // pixels to move mouse before you stop clamping to starting point + MINDRAG: 8, + // smallest dimension allowed for a zoombox + MINZOOM: 20, + // width of axis drag regions + DRAGGERSIZE: 20, + // delay before a redraw (relayout) after smooth panning and zooming + REDRAWDELAY: 50, + // last resort axis ranges for x and y axes if we have no data + DFLTRANGEX: [-1, 6], + DFLTRANGEY: [-1, 4], + // Layers to keep trace types in the right order + // N.B. each 'unique' plot method must have its own layer + traceLayerClasses: [ + "imagelayer", + "heatmaplayer", + "contourcarpetlayer", + "contourlayer", + "funnellayer", + "waterfalllayer", + "barlayer", + "carpetlayer", + "violinlayer", + "boxlayer", + "ohlclayer", + "scattercarpetlayer", + "scatterlayer" + ], + clipOnAxisFalseQuery: [ + ".scatterlayer", + ".barlayer", + ".funnellayer", + ".waterfalllayer" + ], + layerValue2layerClass: { + "above traces": "above", + "below traces": "below" + }, + zindexSeparator: "z" + // used for zindex of cartesian subplots e.g. xy, xyz2, xyz3, etc. +}; +(function(exports2) { + var Registry2 = registry; + var constants2 = constants$U; + exports2.id2name = function id2name2(id) { + if (typeof id !== "string" || !id.match(constants2.AX_ID_PATTERN)) return; + var axNum = id.split(" ")[0].substr(1); + if (axNum === "1") axNum = ""; + return id.charAt(0) + "axis" + axNum; + }; + exports2.name2id = function name2id(name2) { + if (!name2.match(constants2.AX_NAME_PATTERN)) return; + var axNum = name2.substr(5); + if (axNum === "1") axNum = ""; + return name2.charAt(0) + axNum; + }; + exports2.cleanId = function cleanId(id, axLetter, domainId) { + var domainTest = /( domain)$/.test(id); + if (typeof id !== "string" || !id.match(constants2.AX_ID_PATTERN)) return; + if (axLetter && id.charAt(0) !== axLetter) return; + if (domainTest && !domainId) return; + var axNum = id.split(" ")[0].substr(1).replace(/^0+/, ""); + if (axNum === "1") axNum = ""; + return id.charAt(0) + axNum + (domainTest && domainId ? " domain" : ""); + }; + exports2.list = function(gd, axLetter, only2d) { + var fullLayout = gd._fullLayout; + if (!fullLayout) return []; + var idList = exports2.listIds(gd, axLetter); + var out = new Array(idList.length); + var i; + for (i = 0; i < idList.length; i++) { + var idi = idList[i]; + out[i] = fullLayout[idi.charAt(0) + "axis" + idi.substr(1)]; + } + if (!only2d) { + var sceneIds3D = fullLayout._subplots.gl3d || []; + for (i = 0; i < sceneIds3D.length; i++) { + var scene = fullLayout[sceneIds3D[i]]; + if (axLetter) out.push(scene[axLetter + "axis"]); + else out.push(scene.xaxis, scene.yaxis, scene.zaxis); + } + } + return out; + }; + exports2.listIds = function(gd, axLetter) { + var fullLayout = gd._fullLayout; + if (!fullLayout) return []; + var subplotLists = fullLayout._subplots; + if (axLetter) return subplotLists[axLetter + "axis"]; + return subplotLists.xaxis.concat(subplotLists.yaxis); + }; + exports2.getFromId = function(gd, id, type) { + var fullLayout = gd._fullLayout; + id = id === void 0 || typeof id !== "string" ? id : id.replace(" domain", ""); + if (type === "x") id = id.replace(/y[0-9]*/, ""); + else if (type === "y") id = id.replace(/x[0-9]*/, ""); + return fullLayout[exports2.id2name(id)]; + }; + exports2.getFromTrace = function(gd, fullTrace, type) { + var fullLayout = gd._fullLayout; + var ax = null; + if (Registry2.traceIs(fullTrace, "gl3d")) { + var scene = fullTrace.scene; + if (scene.substr(0, 5) === "scene") { + ax = fullLayout[scene][type + "axis"]; + } + } else { + ax = exports2.getFromId(gd, fullTrace[type + "axis"] || type); + } + return ax; + }; + exports2.idSort = function(id1, id2) { + var letter1 = id1.charAt(0); + var letter2 = id2.charAt(0); + if (letter1 !== letter2) return letter1 > letter2 ? 1 : -1; + return +(id1.substr(1) || 1) - +(id2.substr(1) || 1); + }; + exports2.ref2id = function(ar) { + return /^[xyz]/.test(ar) ? ar.split(" ")[0] : false; + }; + function isFound(axId, list) { + if (list && list.length) { + for (var i = 0; i < list.length; i++) { + if (list[i][axId]) return true; + } + } + return false; + } + exports2.isLinked = function(fullLayout, axId) { + return isFound(axId, fullLayout._axisMatchGroups) || isFound(axId, fullLayout._axisConstraintGroups); + }; +})(axis_ids); +function clearOutlineControllers$3(gd) { + var zoomLayer = gd._fullLayout._zoomlayer; + if (zoomLayer) { + zoomLayer.selectAll(".outline-controllers").remove(); + } +} +function clearOutline$4(gd) { + var zoomLayer = gd._fullLayout._zoomlayer; + if (zoomLayer) { + zoomLayer.selectAll(".select-outline").remove(); + } + gd._fullLayout._outlining = false; +} +var handle_outline = { + clearOutlineControllers: clearOutlineControllers$3, + clearOutline: clearOutline$4 +}; +var layout_attributes$5 = { + scattermode: { + valType: "enumerated", + values: ["group", "overlay"], + dflt: "overlay", + editType: "calc", + description: [ + "Determines how scatter points at the same location coordinate", + "are displayed on the graph.", + "With *group*, the scatter points are plotted next to one another", + "centered around the shared location.", + "With *overlay*, the scatter points are plotted over one another,", + "you might need to reduce *opacity* to see multiple scatter points." + ].join(" ") + }, + scattergap: { + valType: "number", + min: 0, + max: 1, + editType: "calc", + description: [ + "Sets the gap (in plot fraction) between scatter points of", + "adjacent location coordinates.", + "Defaults to `bargap`." + ].join(" ") + } +}; +var get_data = {}; +var Registry$N = registry; +var SUBPLOT_PATTERN = constants$U.SUBPLOT_PATTERN; +get_data.getSubplotCalcData = function(calcData, type, subplotId) { + var basePlotModule = Registry$N.subplotsRegistry[type]; + if (!basePlotModule) return []; + var attr = basePlotModule.attr; + var subplotCalcData = []; + for (var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; + if (trace[attr] === subplotId) subplotCalcData.push(calcTrace); + } + return subplotCalcData; +}; +get_data.getModuleCalcData = function(calcdata, arg1, arg2) { + var moduleCalcData = []; + var remainingCalcData = []; + var plotMethod; + if (typeof arg1 === "string") { + plotMethod = Registry$N.getModule(arg1).plot; + } else if (typeof arg1 === "function") { + plotMethod = arg1; + } else { + plotMethod = arg1.plot; + } + if (!plotMethod) { + return [moduleCalcData, calcdata]; + } + var zorder = arg2; + for (var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + var filterByZ = trace.zorder !== void 0; + if (trace.visible !== true || trace._length === 0) continue; + if (trace._module && trace._module.plot === plotMethod && (!filterByZ || trace.zorder === zorder)) { + moduleCalcData.push(cd); + } else { + remainingCalcData.push(cd); + } + } + return [moduleCalcData, remainingCalcData]; +}; +get_data.getSubplotData = function getSubplotData(data, type, subplotId) { + if (!Registry$N.subplotsRegistry[type]) return []; + var attr = Registry$N.subplotsRegistry[type].attr; + var subplotData = []; + var trace, subplotX, subplotY; + if (type === "gl2d") { + var spmatch = subplotId.match(SUBPLOT_PATTERN); + subplotX = "x" + spmatch[1]; + subplotY = "y" + spmatch[2]; + } + for (var i = 0; i < data.length; i++) { + trace = data[i]; + if (type === "gl2d" && Registry$N.traceIs(trace, "gl2d")) { + if (trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { + subplotData.push(trace); + } + } else { + if (trace[attr] === subplotId) subplotData.push(trace); + } + } + return subplotData; +}; +var command = {}; +var hasRequiredCommand; +function requireCommand() { + if (hasRequiredCommand) return command; + hasRequiredCommand = 1; + (function(exports2) { + var Registry2 = registry; + var Lib2 = libExports; + exports2.manageCommandObserver = function(gd, container, commandList, onchange) { + var ret = {}; + var enabled = true; + if (container && container._commandObserver) { + ret = container._commandObserver; + } + if (!ret.cache) { + ret.cache = {}; + } + ret.lookupTable = {}; + var binding = exports2.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); + if (container && container._commandObserver) { + if (!binding) { + if (container._commandObserver.remove) { + container._commandObserver.remove(); + container._commandObserver = null; + return ret; + } + } else { + return ret; + } + } + if (binding) { + bindingValueHasChanged(gd, binding, ret.cache); + ret.check = function check() { + if (!enabled) return; + var update2 = bindingValueHasChanged(gd, binding, ret.cache); + if (update2.changed && onchange) { + if (ret.lookupTable[update2.value] !== void 0) { + ret.disable(); + Promise.resolve(onchange({ + value: update2.value, + type: binding.type, + prop: binding.prop, + traces: binding.traces, + index: ret.lookupTable[update2.value] + })).then(ret.enable, ret.enable); + } + } + return update2.changed; + }; + var checkEvents = [ + "plotly_relayout", + "plotly_redraw", + "plotly_restyle", + "plotly_update", + "plotly_animatingframe", + "plotly_afterplot" + ]; + for (var i = 0; i < checkEvents.length; i++) { + gd._internalOn(checkEvents[i], ret.check); + } + ret.remove = function() { + for (var i2 = 0; i2 < checkEvents.length; i2++) { + gd._removeInternalListener(checkEvents[i2], ret.check); + } + }; + } else { + Lib2.log("Unable to automatically bind plot updates to API command"); + ret.lookupTable = {}; + ret.remove = function() { + }; + } + ret.disable = function disable2() { + enabled = false; + }; + ret.enable = function enable2() { + enabled = true; + }; + if (container) { + container._commandObserver = ret; + } + return ret; + }; + exports2.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { + var i; + var n = commandList.length; + var refBinding; + for (i = 0; i < n; i++) { + var binding; + var command2 = commandList[i]; + var method = command2.method; + var args = command2.args; + if (!Array.isArray(args)) args = []; + if (!method) { + return false; + } + var bindings = exports2.computeAPICommandBindings(gd, method, args); + if (bindings.length !== 1) { + return false; + } + if (!refBinding) { + refBinding = bindings[0]; + if (Array.isArray(refBinding.traces)) { + refBinding.traces.sort(); + } + } else { + binding = bindings[0]; + if (binding.type !== refBinding.type) { + return false; + } + if (binding.prop !== refBinding.prop) { + return false; + } + if (Array.isArray(refBinding.traces)) { + if (Array.isArray(binding.traces)) { + binding.traces.sort(); + for (var j = 0; j < refBinding.traces.length; j++) { + if (refBinding.traces[j] !== binding.traces[j]) { + return false; + } + } + } else { + return false; + } + } else { + if (binding.prop !== refBinding.prop) { + return false; + } + } + } + binding = bindings[0]; + var value2 = binding.value; + if (Array.isArray(value2)) { + if (value2.length === 1) { + value2 = value2[0]; + } else { + return false; + } + } + if (bindingsByValue) { + bindingsByValue[value2] = i; + } + } + return refBinding; + }; + function bindingValueHasChanged(gd, binding, cache2) { + var container, value2, obj; + var changed = false; + if (binding.type === "data") { + container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0]; + } else if (binding.type === "layout") { + container = gd._fullLayout; + } else { + return false; + } + value2 = Lib2.nestedProperty(container, binding.prop).get(); + obj = cache2[binding.type] = cache2[binding.type] || {}; + if (obj.hasOwnProperty(binding.prop)) { + if (obj[binding.prop] !== value2) { + changed = true; + } + } + obj[binding.prop] = value2; + return { + changed, + value: value2 + }; + } + exports2.executeAPICommand = function(gd, method, args) { + if (method === "skip") return Promise.resolve(); + var _method = Registry2.apiMethodRegistry[method]; + var allArgs = [gd]; + if (!Array.isArray(args)) args = []; + for (var i = 0; i < args.length; i++) { + allArgs.push(args[i]); + } + return _method.apply(null, allArgs).catch(function(err) { + Lib2.warn("API call to Plotly." + method + " rejected.", err); + return Promise.reject(err); + }); + }; + exports2.computeAPICommandBindings = function(gd, method, args) { + var bindings; + if (!Array.isArray(args)) args = []; + switch (method) { + case "restyle": + bindings = computeDataBindings(gd, args); + break; + case "relayout": + bindings = computeLayoutBindings(gd, args); + break; + case "update": + bindings = computeDataBindings(gd, [args[0], args[2]]).concat(computeLayoutBindings(gd, [args[1]])); + break; + case "animate": + bindings = computeAnimateBindings(gd, args); + break; + default: + bindings = []; + } + return bindings; + }; + function computeAnimateBindings(gd, args) { + if (Array.isArray(args[0]) && args[0].length === 1 && ["string", "number"].indexOf(typeof args[0][0]) !== -1) { + return [{ type: "layout", prop: "_currentFrame", value: args[0][0].toString() }]; + } else { + return []; + } + } + function computeLayoutBindings(gd, args) { + var bindings = []; + var astr = args[0]; + var aobj = {}; + if (typeof astr === "string") { + aobj[astr] = args[1]; + } else if (Lib2.isPlainObject(astr)) { + aobj = astr; + } else { + return bindings; + } + crawl2(aobj, function(path, attrName, attr) { + bindings.push({ type: "layout", prop: path, value: attr }); + }, "", 0); + return bindings; + } + function computeDataBindings(gd, args) { + var traces, astr, val, aobj; + var bindings = []; + astr = args[0]; + val = args[1]; + traces = args[2]; + aobj = {}; + if (typeof astr === "string") { + aobj[astr] = val; + } else if (Lib2.isPlainObject(astr)) { + aobj = astr; + if (traces === void 0) { + traces = val; + } + } else { + return bindings; + } + if (traces === void 0) { + traces = null; + } + crawl2(aobj, function(path, attrName, _attr) { + var thisTraces; + var attr; + if (Array.isArray(_attr)) { + attr = _attr.slice(); + var nAttr = Math.min(attr.length, gd.data.length); + if (traces) { + nAttr = Math.min(nAttr, traces.length); + } + thisTraces = []; + for (var j = 0; j < nAttr; j++) { + thisTraces[j] = traces ? traces[j] : j; + } + } else { + attr = _attr; + thisTraces = traces ? traces.slice() : null; + } + if (thisTraces === null) { + if (Array.isArray(attr)) { + attr = attr[0]; + } + } else if (Array.isArray(thisTraces)) { + if (!Array.isArray(attr)) { + var tmp = attr; + attr = []; + for (var i = 0; i < thisTraces.length; i++) { + attr[i] = tmp; + } + } + attr.length = Math.min(thisTraces.length, attr.length); + } + bindings.push({ + type: "data", + prop: path, + traces: thisTraces, + value: attr + }); + }, "", 0); + return bindings; + } + function crawl2(attrs2, callback, path, depth) { + Object.keys(attrs2).forEach(function(attrName) { + var attr = attrs2[attrName]; + if (attrName[0] === "_") return; + var thisPath = path + (depth > 0 ? "." : "") + attrName; + if (Lib2.isPlainObject(attr)) { + crawl2(attr, callback, thisPath, depth + 1); + } else { + callback(thisPath, attrName, attr); + } + }); + } + })(command); + return command; +} +var d3$B = d3Exports; +var timeFormatLocale = require$$1$1.timeFormatLocale; +var formatLocale = require$$2$2.formatLocale; +var isNumeric$u = fastIsnumeric; +var b64encode = require$$4$1; +var Registry$M = registry; +var PlotSchema$2 = plot_schema; +var Template$9 = plot_template; +var Lib$1W = libExports; +var Color$L = colorExports; +var BADNUM$a = numerical.BADNUM; +var axisIDs$1 = axis_ids; +var clearOutline$3 = handle_outline.clearOutline; +var scatterAttrs$3 = layout_attributes$5; +var animationAttrs$1 = animation_attributes; +var frameAttrs = frame_attributes; +var getModuleCalcData$1 = get_data.getModuleCalcData; +var relinkPrivateKeys2 = Lib$1W.relinkPrivateKeys; +var _$2 = Lib$1W._; +var plots$1 = plots$2.exports = {}; +Lib$1W.extendFlat(plots$1, Registry$M); +plots$1.attributes = attributes$O; +plots$1.attributes.type.values = plots$1.allTypes; +plots$1.fontAttrs = font_attributes; +plots$1.layoutAttributes = layout_attributes$6; +var transformsRegistry = plots$1.transformsRegistry; +var commandModule = requireCommand(); +plots$1.executeAPICommand = commandModule.executeAPICommand; +plots$1.computeAPICommandBindings = commandModule.computeAPICommandBindings; +plots$1.manageCommandObserver = commandModule.manageCommandObserver; +plots$1.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings; +plots$1.redrawText = function(gd) { + gd = Lib$1W.getGraphDiv(gd); + return new Promise(function(resolve) { + setTimeout(function() { + if (!gd._fullLayout) return; + Registry$M.getComponentMethod("annotations", "draw")(gd); + Registry$M.getComponentMethod("legend", "draw")(gd); + Registry$M.getComponentMethod("colorbar", "draw")(gd); + resolve(plots$1.previousPromises(gd)); + }, 300); + }); +}; +plots$1.resize = function(gd) { + gd = Lib$1W.getGraphDiv(gd); + var resolveLastResize; + var p = new Promise(function(resolve, reject) { + if (!gd || Lib$1W.isHidden(gd)) { + reject(new Error("Resize must be passed a displayed plot div element.")); + } + if (gd._redrawTimer) clearTimeout(gd._redrawTimer); + if (gd._resolveResize) resolveLastResize = gd._resolveResize; + gd._resolveResize = resolve; + gd._redrawTimer = setTimeout(function() { + if (!gd.layout || gd.layout.width && gd.layout.height || Lib$1W.isHidden(gd)) { + resolve(gd); + return; + } + delete gd.layout.width; + delete gd.layout.height; + var oldchanged = gd.changed; + gd.autoplay = true; + Registry$M.call("relayout", gd, { autosize: true }).then(function() { + gd.changed = oldchanged; + if (gd._resolveResize === resolve) { + delete gd._resolveResize; + resolve(gd); + } + }); + }, 100); + }); + if (resolveLastResize) resolveLastResize(p); + return p; +}; +plots$1.previousPromises = function(gd) { + if ((gd._promises || []).length) { + return Promise.all(gd._promises).then(function() { + gd._promises = []; + }); + } +}; +plots$1.addLinks = function(gd) { + if (!gd._context.showLink && !gd._context.showSources) return; + var fullLayout = gd._fullLayout; + var linkContainer = Lib$1W.ensureSingle(fullLayout._paper, "text", "js-plot-link-container", function(s) { + s.style({ + "font-family": '"Open Sans", Arial, sans-serif', + "font-size": "12px", + fill: Color$L.defaultLine, + "pointer-events": "all" + }).each(function() { + var links = d3$B.select(this); + links.append("tspan").classed("js-link-to-tool", true); + links.append("tspan").classed("js-link-spacer", true); + links.append("tspan").classed("js-sourcelinks", true); + }); + }); + var text = linkContainer.node(); + var attrs2 = { y: fullLayout._paper.attr("height") - 9 }; + if (document.body.contains(text) && text.getComputedTextLength() >= fullLayout.width - 20) { + attrs2["text-anchor"] = "start"; + attrs2.x = 5; + } else { + attrs2["text-anchor"] = "end"; + attrs2.x = fullLayout._paper.attr("width") - 7; + } + linkContainer.attr(attrs2); + var toolspan = linkContainer.select(".js-link-to-tool"); + var spacespan = linkContainer.select(".js-link-spacer"); + var sourcespan = linkContainer.select(".js-sourcelinks"); + if (gd._context.showSources) gd._context.showSources(gd); + if (gd._context.showLink) positionPlayWithData(gd, toolspan); + spacespan.text(toolspan.text() && sourcespan.text() ? " - " : ""); +}; +function positionPlayWithData(gd, container) { + container.text(""); + var link = container.append("a").attr({ + "xlink:xlink:href": "#", + class: "link--impt link--embedview", + "font-weight": "bold" + }).text(gd._context.linkText + " " + String.fromCharCode(187)); + if (gd._context.sendData) { + link.on("click", function() { + plots$1.sendDataToCloud(gd); + }); + } else { + var path = window.location.pathname.split("/"); + var query = window.location.search; + link.attr({ + "xlink:xlink:show": "new", + "xlink:xlink:href": "/" + path[2].split(".")[0] + "/" + path[1] + query + }); + } +} +plots$1.sendDataToCloud = function(gd) { + var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL; + if (!baseUrl) return; + gd.emit("plotly_beforeexport"); + var hiddenformDiv = d3$B.select(gd).append("div").attr("id", "hiddenform").style("display", "none"); + var hiddenform = hiddenformDiv.append("form").attr({ + action: baseUrl + "/external", + method: "post", + target: "_blank" + }); + var hiddenformInput = hiddenform.append("input").attr({ + type: "text", + name: "data" + }); + hiddenformInput.node().value = plots$1.graphJson(gd, false, "keepdata"); + hiddenform.node().submit(); + hiddenformDiv.remove(); + gd.emit("plotly_afterexport"); + return false; +}; +var d3FormatKeys = [ + "days", + "shortDays", + "months", + "shortMonths", + "periods", + "dateTime", + "date", + "time", + "decimal", + "thousands", + "grouping", + "currency" +]; +var extraFormatKeys = [ + "year", + "month", + "dayMonth", + "dayMonthYear" +]; +plots$1.supplyDefaults = function(gd, opts) { + var skipUpdateCalc = opts && opts.skipUpdateCalc; + var oldFullLayout = gd._fullLayout || {}; + if (oldFullLayout._skipDefaults) { + delete oldFullLayout._skipDefaults; + return; + } + var newFullLayout = gd._fullLayout = {}; + var newLayout = gd.layout || {}; + var oldFullData = gd._fullData || []; + var newFullData = gd._fullData = []; + var newData = gd.data || []; + var oldCalcdata = gd.calcdata || []; + var context2 = gd._context || {}; + var i; + if (!gd._transitionData) plots$1.createTransitionData(gd); + newFullLayout._dfltTitle = { + plot: _$2(gd, "Click to enter Plot title"), + subtitle: _$2(gd, "Click to enter Plot subtitle"), + x: _$2(gd, "Click to enter X axis title"), + y: _$2(gd, "Click to enter Y axis title"), + colorbar: _$2(gd, "Click to enter Colorscale title"), + annotation: _$2(gd, "new text") + }; + newFullLayout._traceWord = _$2(gd, "trace"); + var formatObj = getFormatObj(gd, d3FormatKeys); + newFullLayout._mapboxAccessToken = context2.mapboxAccessToken; + if (oldFullLayout._initialAutoSizeIsDone) { + var oldWidth = oldFullLayout.width; + var oldHeight = oldFullLayout.height; + plots$1.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj); + if (!newLayout.width) newFullLayout.width = oldWidth; + if (!newLayout.height) newFullLayout.height = oldHeight; + plots$1.sanitizeMargins(newFullLayout); + } else { + plots$1.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj); + var missingWidthOrHeight = !newLayout.width || !newLayout.height; + var autosize = newFullLayout.autosize; + var autosizable = context2.autosizable; + var initialAutoSize = missingWidthOrHeight && (autosize || autosizable); + if (initialAutoSize) plots$1.plotAutoSize(gd, newLayout, newFullLayout); + else if (missingWidthOrHeight) plots$1.sanitizeMargins(newFullLayout); + if (!autosize && missingWidthOrHeight) { + newLayout.width = newFullLayout.width; + newLayout.height = newFullLayout.height; + } + } + newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators); + newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys); + newFullLayout._initialAutoSizeIsDone = true; + newFullLayout._dataLength = newData.length; + newFullLayout._modules = []; + newFullLayout._visibleModules = []; + newFullLayout._basePlotModules = []; + var subplots = newFullLayout._subplots = emptySubplotLists(); + var splomAxes = newFullLayout._splomAxes = { x: {}, y: {} }; + var splomSubplots = newFullLayout._splomSubplots = {}; + newFullLayout._splomGridDflt = {}; + newFullLayout._scatterStackOpts = {}; + newFullLayout._firstScatter = {}; + newFullLayout._alignmentOpts = {}; + newFullLayout._colorAxes = {}; + newFullLayout._requestRangeslider = {}; + newFullLayout._traceUids = getTraceUids(oldFullData, newData); + newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; + plots$1.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); + var splomXa = Object.keys(splomAxes.x); + var splomYa = Object.keys(splomAxes.y); + if (splomXa.length > 1 && splomYa.length > 1) { + Registry$M.getComponentMethod("grid", "sizeDefaults")(newLayout, newFullLayout); + for (i = 0; i < splomXa.length; i++) { + Lib$1W.pushUnique(subplots.xaxis, splomXa[i]); + } + for (i = 0; i < splomYa.length; i++) { + Lib$1W.pushUnique(subplots.yaxis, splomYa[i]); + } + for (var k in splomSubplots) { + Lib$1W.pushUnique(subplots.cartesian, k); + } + } + newFullLayout._has = plots$1._hasPlotType.bind(newFullLayout); + if (oldFullData.length === newFullData.length) { + for (i = 0; i < newFullData.length; i++) { + relinkPrivateKeys2(newFullData[i], oldFullData[i]); + } + } + plots$1.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); + var _modules = newFullLayout._visibleModules; + var crossTraceDefaultsFuncs = []; + for (i = 0; i < _modules.length; i++) { + var funci = _modules[i].crossTraceDefaults; + if (funci) Lib$1W.pushUnique(crossTraceDefaultsFuncs, funci); + } + for (i = 0; i < crossTraceDefaultsFuncs.length; i++) { + crossTraceDefaultsFuncs[i](newFullData, newFullLayout); + } + newFullLayout._hasOnlyLargeSploms = newFullLayout._basePlotModules.length === 1 && newFullLayout._basePlotModules[0].name === "splom" && splomXa.length > 15 && splomYa.length > 15 && newFullLayout.shapes.length === 0 && newFullLayout.images.length === 0; + plots$1.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); + plots$1.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); + var hadGL2D = !!(oldFullLayout._has && oldFullLayout._has("gl2d")); + var hasGL2D = !!(newFullLayout._has && newFullLayout._has("gl2d")); + var hadCartesian = !!(oldFullLayout._has && oldFullLayout._has("cartesian")); + var hasCartesian = !!(newFullLayout._has && newFullLayout._has("cartesian")); + var hadBgLayer = hadCartesian || hadGL2D; + var hasBgLayer = hasCartesian || hasGL2D; + if (hadBgLayer && !hasBgLayer) { + oldFullLayout._bgLayer.remove(); + } else if (hasBgLayer && !hadBgLayer) { + newFullLayout._shouldCreateBgLayer = true; + } + if (oldFullLayout._zoomlayer && !gd._dragging) { + clearOutline$3({ + // mock old gd + _fullLayout: oldFullLayout + }); + } + fillMetaTextHelpers(newFullData, newFullLayout); + relinkPrivateKeys2(newFullLayout, oldFullLayout); + Registry$M.getComponentMethod("colorscale", "crossTraceDefaults")(newFullData, newFullLayout); + if (!newFullLayout._preGUI) newFullLayout._preGUI = {}; + if (!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {}; + var tracePreGUI = newFullLayout._tracePreGUI; + var uids = {}; + var uid; + for (uid in tracePreGUI) uids[uid] = "old"; + for (i = 0; i < newFullData.length; i++) { + uid = newFullData[i]._fullInput.uid; + if (!uids[uid]) tracePreGUI[uid] = {}; + uids[uid] = "new"; + } + for (uid in uids) { + if (uids[uid] === "old") delete tracePreGUI[uid]; + } + initMargins(newFullLayout); + Registry$M.getComponentMethod("rangeslider", "makeData")(newFullLayout); + if (!skipUpdateCalc && oldCalcdata.length === newFullData.length) { + plots$1.supplyDefaultsUpdateCalc(oldCalcdata, newFullData); + } +}; +plots$1.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) { + for (var i = 0; i < newFullData.length; i++) { + var newTrace = newFullData[i]; + var cd0 = (oldCalcdata[i] || [])[0]; + if (cd0 && cd0.trace) { + var oldTrace = cd0.trace; + if (oldTrace._hasCalcTransform) { + var arrayAttrs = oldTrace._arrayAttrs; + var j, astr, oldArrayVal; + for (j = 0; j < arrayAttrs.length; j++) { + astr = arrayAttrs[j]; + oldArrayVal = Lib$1W.nestedProperty(oldTrace, astr).get().slice(); + Lib$1W.nestedProperty(newTrace, astr).set(oldArrayVal); + } + } + cd0.trace = newTrace; + } + } +}; +function getTraceUids(oldFullData, newData) { + var len = newData.length; + var oldFullInput = []; + var i, prevFullInput; + for (i = 0; i < oldFullData.length; i++) { + var thisFullInput = oldFullData[i]._fullInput; + if (thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput); + prevFullInput = thisFullInput; + } + var oldLen = oldFullInput.length; + var out = new Array(len); + var seenUids = {}; + function setUid(uid, i2) { + out[i2] = uid; + seenUids[uid] = 1; + } + function tryUid(uid, i2) { + if (uid && typeof uid === "string" && !seenUids[uid]) { + setUid(uid, i2); + return true; + } + } + for (i = 0; i < len; i++) { + var newUid = newData[i].uid; + if (typeof newUid === "number") newUid = String(newUid); + if (tryUid(newUid, i)) continue; + if (i < oldLen && tryUid(oldFullInput[i].uid, i)) continue; + setUid(Lib$1W.randstr(seenUids), i); + } + return out; +} +function emptySubplotLists() { + var collectableSubplotTypes = Registry$M.collectableSubplotTypes; + var out = {}; + var i, j; + if (!collectableSubplotTypes) { + collectableSubplotTypes = []; + var subplotsRegistry = Registry$M.subplotsRegistry; + for (var subplotType in subplotsRegistry) { + var subplotModule = subplotsRegistry[subplotType]; + var subplotAttr = subplotModule.attr; + if (subplotAttr) { + collectableSubplotTypes.push(subplotType); + if (Array.isArray(subplotAttr)) { + for (j = 0; j < subplotAttr.length; j++) { + Lib$1W.pushUnique(collectableSubplotTypes, subplotAttr[j]); + } + } + } + } + } + for (i = 0; i < collectableSubplotTypes.length; i++) { + out[collectableSubplotTypes[i]] = []; + } + return out; +} +function getFormatObj(gd, formatKeys) { + var locale2 = gd._context.locale; + if (!locale2) locale2 = "en-US"; + var formatDone = false; + var formatObj = {}; + function includeFormat(newFormat) { + var formatFinished = true; + for (var i2 = 0; i2 < formatKeys.length; i2++) { + var formatKey = formatKeys[i2]; + if (!formatObj[formatKey]) { + if (newFormat[formatKey]) { + formatObj[formatKey] = newFormat[formatKey]; + } else formatFinished = false; + } + } + if (formatFinished) formatDone = true; + } + for (var i = 0; i < 2; i++) { + var locales = gd._context.locales; + for (var j = 0; j < 2; j++) { + var formatj = (locales[locale2] || {}).format; + if (formatj) { + includeFormat(formatj); + if (formatDone) break; + } + locales = Registry$M.localeRegistry; + } + var baseLocale = locale2.split("-")[0]; + if (formatDone || baseLocale === locale2) break; + locale2 = baseLocale; + } + if (!formatDone) includeFormat(Registry$M.localeRegistry.en.format); + return formatObj; +} +function getFormatter(formatObj, separators) { + formatObj.decimal = separators.charAt(0); + formatObj.thousands = separators.charAt(1); + return { + numberFormat: function(formatStr) { + try { + formatStr = formatLocale(formatObj).format( + Lib$1W.adjustFormat(formatStr) + ); + } catch (e) { + Lib$1W.warnBadFormat(formatStr); + return Lib$1W.noFormat; + } + return formatStr; + }, + timeFormat: timeFormatLocale(formatObj).utcFormat + }; +} +function fillMetaTextHelpers(newFullData, newFullLayout) { + var _meta; + var meta4data = []; + if (newFullLayout.meta) { + _meta = newFullLayout._meta = { + meta: newFullLayout.meta, + layout: { meta: newFullLayout.meta } + }; + } + for (var i = 0; i < newFullData.length; i++) { + var trace = newFullData[i]; + if (trace.meta) { + meta4data[trace.index] = trace._meta = { meta: trace.meta }; + } else if (newFullLayout.meta) { + trace._meta = { meta: newFullLayout.meta }; + } + if (newFullLayout.meta) { + trace._meta.layout = { meta: newFullLayout.meta }; + } + } + if (meta4data.length) { + if (!_meta) { + _meta = newFullLayout._meta = {}; + } + _meta.data = meta4data; + } +} +plots$1.createTransitionData = function(gd) { + if (!gd._transitionData) { + gd._transitionData = {}; + } + if (!gd._transitionData._frames) { + gd._transitionData._frames = []; + } + if (!gd._transitionData._frameHash) { + gd._transitionData._frameHash = {}; + } + if (!gd._transitionData._counter) { + gd._transitionData._counter = 0; + } + if (!gd._transitionData._interruptCallbacks) { + gd._transitionData._interruptCallbacks = []; + } +}; +plots$1._hasPlotType = function(category2) { + var i; + var basePlotModules = this._basePlotModules || []; + for (i = 0; i < basePlotModules.length; i++) { + if (basePlotModules[i].name === category2) return true; + } + var modules2 = this._modules || []; + for (i = 0; i < modules2.length; i++) { + var name2 = modules2[i].name; + if (name2 === category2) return true; + var _module = Registry$M.modules[name2]; + if (_module && _module.categories[category2]) return true; + } + return false; +}; +plots$1.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var i, j; + var basePlotModules = oldFullLayout._basePlotModules || []; + for (i = 0; i < basePlotModules.length; i++) { + var _module = basePlotModules[i]; + if (_module.clean) { + _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); + } + } + var hadGl = oldFullLayout._has && oldFullLayout._has("gl"); + var hasGl = newFullLayout._has && newFullLayout._has("gl"); + if (hadGl && !hasGl) { + if (oldFullLayout._glcontainer !== void 0) { + oldFullLayout._glcontainer.selectAll(".gl-canvas").remove(); + oldFullLayout._glcontainer.selectAll(".no-webgl").remove(); + oldFullLayout._glcanvas = null; + } + } + var hasInfoLayer = !!oldFullLayout._infolayer; + oldLoop: + for (i = 0; i < oldFullData.length; i++) { + var oldTrace = oldFullData[i]; + var oldUid = oldTrace.uid; + for (j = 0; j < newFullData.length; j++) { + var newTrace = newFullData[j]; + if (oldUid === newTrace.uid) continue oldLoop; + } + if (hasInfoLayer) { + oldFullLayout._infolayer.select(".cb" + oldUid).remove(); + } + } +}; +plots$1.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var i, j; + var oldSubplots = oldFullLayout._plots || {}; + var newSubplots = newFullLayout._plots = {}; + var newSubplotList = newFullLayout._subplots; + var mockGd = { + _fullData: newFullData, + _fullLayout: newFullLayout + }; + var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []); + for (i = 0; i < ids.length; i++) { + var id = ids[i]; + var oldSubplot = oldSubplots[id]; + var xaxis = axisIDs$1.getFromId(mockGd, id, "x"); + var yaxis = axisIDs$1.getFromId(mockGd, id, "y"); + var plotinfo; + if (oldSubplot) { + plotinfo = newSubplots[id] = oldSubplot; + } else { + plotinfo = newSubplots[id] = {}; + plotinfo.id = id; + } + xaxis._counterAxes.push(yaxis._id); + yaxis._counterAxes.push(xaxis._id); + xaxis._subplotsWith.push(id); + yaxis._subplotsWith.push(id); + plotinfo.xaxis = xaxis; + plotinfo.yaxis = yaxis; + plotinfo._hasClipOnAxisFalse = false; + for (j = 0; j < newFullData.length; j++) { + var trace = newFullData[j]; + if (trace.xaxis === plotinfo.xaxis._id && trace.yaxis === plotinfo.yaxis._id && trace.cliponaxis === false) { + plotinfo._hasClipOnAxisFalse = true; + break; + } + } + } + var axList = axisIDs$1.list(mockGd, null, true); + var ax; + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + var mainAx = null; + if (ax.overlaying) { + mainAx = axisIDs$1.getFromId(mockGd, ax.overlaying); + if (mainAx && mainAx.overlaying) { + ax.overlaying = false; + mainAx = null; + } + } + ax._mainAxis = mainAx || ax; + if (mainAx) ax.domain = mainAx.domain.slice(); + ax._anchorAxis = ax.anchor === "free" ? null : axisIDs$1.getFromId(mockGd, ax.anchor); + } + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + ax._counterAxes.sort(axisIDs$1.idSort); + ax._subplotsWith.sort(Lib$1W.subplotSort); + ax._mainSubplot = findMainSubplot(ax, newFullLayout); + if (ax._counterAxes.length && (ax.spikemode && ax.spikemode.indexOf("across") !== -1 || ax.automargin && ax.mirror && ax.anchor !== "free" || Registry$M.getComponentMethod("rangeslider", "isVisible")(ax))) { + var min = 1; + var max = 0; + for (j = 0; j < ax._counterAxes.length; j++) { + var ax2 = axisIDs$1.getFromId(mockGd, ax._counterAxes[j]); + min = Math.min(min, ax2.domain[0]); + max = Math.max(max, ax2.domain[1]); + } + if (min < max) { + ax._counterDomainMin = min; + ax._counterDomainMax = max; + } + } + } +}; +function findMainSubplot(ax, fullLayout) { + var mockGd = { _fullLayout: fullLayout }; + var isX = ax._id.charAt(0) === "x"; + var anchorAx = ax._mainAxis._anchorAxis; + var mainSubplotID = ""; + var nextBestMainSubplotID = ""; + var anchorID = ""; + if (anchorAx) { + anchorID = anchorAx._mainAxis._id; + mainSubplotID = isX ? ax._id + anchorID : anchorID + ax._id; + } + if (!mainSubplotID || !fullLayout._plots[mainSubplotID]) { + mainSubplotID = ""; + var counterIDs = ax._counterAxes; + for (var j = 0; j < counterIDs.length; j++) { + var counterPart = counterIDs[j]; + var id = isX ? ax._id + counterPart : counterPart + ax._id; + if (!nextBestMainSubplotID) nextBestMainSubplotID = id; + var counterAx = axisIDs$1.getFromId(mockGd, counterPart); + if (anchorID && counterAx.overlaying === anchorID) { + mainSubplotID = id; + break; + } + } + } + return mainSubplotID || nextBestMainSubplotID; +} +plots$1.clearExpandedTraceDefaultColors = function(trace) { + var colorAttrs2, path, i; + function locateColorAttrs(attr, attrName, attrs2, level) { + path[level] = attrName; + path.length = level + 1; + if (attr.valType === "color" && attr.dflt === void 0) { + colorAttrs2.push(path.join(".")); + } + } + path = []; + colorAttrs2 = trace._module._colorAttrs; + if (!colorAttrs2) { + trace._module._colorAttrs = colorAttrs2 = []; + PlotSchema$2.crawl( + trace._module.attributes, + locateColorAttrs + ); + } + for (i = 0; i < colorAttrs2.length; i++) { + var origprop = Lib$1W.nestedProperty(trace, "_input." + colorAttrs2[i]); + if (!origprop.get()) { + Lib$1W.nestedProperty(trace, colorAttrs2[i]).set(null); + } + } +}; +plots$1.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { + var modules2 = fullLayout._modules; + var visibleModules = fullLayout._visibleModules; + var basePlotModules = fullLayout._basePlotModules; + var cnt = 0; + var colorCnt = 0; + var i, fullTrace, trace; + fullLayout._transformModules = []; + function pushModule(fullTrace2) { + dataOut.push(fullTrace2); + var _module = fullTrace2._module; + if (!_module) return; + Lib$1W.pushUnique(modules2, _module); + if (fullTrace2.visible === true) Lib$1W.pushUnique(visibleModules, _module); + Lib$1W.pushUnique(basePlotModules, fullTrace2._module.basePlotModule); + cnt++; + if (fullTrace2._input.visible !== false) colorCnt++; + } + var carpetIndex = {}; + var carpetDependents = []; + var dataTemplate = (layout.template || {}).data || {}; + var templater = Template$9.traceTemplater(dataTemplate); + for (i = 0; i < dataIn.length; i++) { + trace = dataIn[i]; + fullTrace = templater.newTrace(trace); + fullTrace.uid = fullLayout._traceUids[i]; + plots$1.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i); + fullTrace.index = i; + fullTrace._input = trace; + fullTrace._expandedIndex = cnt; + if (fullTrace.transforms && fullTrace.transforms.length) { + var sdInvisible = trace.visible !== false && fullTrace.visible === false; + var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout); + for (var j = 0; j < expandedTraces.length; j++) { + var expandedTrace = expandedTraces[j]; + var fullExpandedTrace = { + _template: fullTrace._template, + type: fullTrace.type, + // set uid using parent uid and expanded index + // to promote consistency between update calls + uid: fullTrace.uid + j + }; + if (sdInvisible && expandedTrace.visible === false) { + delete expandedTrace.visible; + } + plots$1.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i); + relinkPrivateKeys2(fullExpandedTrace, expandedTrace); + fullExpandedTrace.index = i; + fullExpandedTrace._input = trace; + fullExpandedTrace._fullInput = fullTrace; + fullExpandedTrace._expandedIndex = cnt; + fullExpandedTrace._expandedInput = expandedTrace; + pushModule(fullExpandedTrace); + } + } else { + fullTrace._fullInput = fullTrace; + fullTrace._expandedInput = fullTrace; + pushModule(fullTrace); + } + if (Registry$M.traceIs(fullTrace, "carpetAxis")) { + carpetIndex[fullTrace.carpet] = fullTrace; + } + if (Registry$M.traceIs(fullTrace, "carpetDependent")) { + carpetDependents.push(i); + } + } + for (i = 0; i < carpetDependents.length; i++) { + fullTrace = dataOut[carpetDependents[i]]; + if (!fullTrace.visible) continue; + var carpetAxis = carpetIndex[fullTrace.carpet]; + fullTrace._carpet = carpetAxis; + if (!carpetAxis || !carpetAxis.visible) { + fullTrace.visible = false; + continue; + } + fullTrace.xaxis = carpetAxis.xaxis; + fullTrace.yaxis = carpetAxis.yaxis; + } +}; +plots$1.supplyAnimationDefaults = function(opts) { + opts = opts || {}; + var i; + var optsOut = {}; + function coerce2(attr, dflt) { + return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1, attr, dflt); + } + coerce2("mode"); + coerce2("direction"); + coerce2("fromcurrent"); + if (Array.isArray(opts.frame)) { + optsOut.frame = []; + for (i = 0; i < opts.frame.length; i++) { + optsOut.frame[i] = plots$1.supplyAnimationFrameDefaults(opts.frame[i] || {}); + } + } else { + optsOut.frame = plots$1.supplyAnimationFrameDefaults(opts.frame || {}); + } + if (Array.isArray(opts.transition)) { + optsOut.transition = []; + for (i = 0; i < opts.transition.length; i++) { + optsOut.transition[i] = plots$1.supplyAnimationTransitionDefaults(opts.transition[i] || {}); + } + } else { + optsOut.transition = plots$1.supplyAnimationTransitionDefaults(opts.transition || {}); + } + return optsOut; +}; +plots$1.supplyAnimationFrameDefaults = function(opts) { + var optsOut = {}; + function coerce2(attr, dflt) { + return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1.frame, attr, dflt); + } + coerce2("duration"); + coerce2("redraw"); + return optsOut; +}; +plots$1.supplyAnimationTransitionDefaults = function(opts) { + var optsOut = {}; + function coerce2(attr, dflt) { + return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1.transition, attr, dflt); + } + coerce2("duration"); + coerce2("easing"); + return optsOut; +}; +plots$1.supplyFrameDefaults = function(frameIn) { + var frameOut = {}; + function coerce2(attr, dflt) { + return Lib$1W.coerce(frameIn, frameOut, frameAttrs, attr, dflt); + } + coerce2("group"); + coerce2("name"); + coerce2("traces"); + coerce2("baseframe"); + coerce2("data"); + coerce2("layout"); + return frameOut; +}; +plots$1.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) { + var colorway = layout.colorway || Color$L.defaults; + var defaultColor = colorway[colorIndex % colorway.length]; + var i; + function coerce2(attr, dflt) { + return Lib$1W.coerce(traceIn, traceOut, plots$1.attributes, attr, dflt); + } + var visible = coerce2("visible"); + coerce2("type"); + coerce2("name", layout._traceWord + " " + traceInIndex); + coerce2("uirevision", layout.uirevision); + var _module = plots$1.getModule(traceOut); + traceOut._module = _module; + if (_module) { + var basePlotModule = _module.basePlotModule; + var subplotAttr = basePlotModule.attr; + var subplotAttrs = basePlotModule.attributes; + if (subplotAttr && subplotAttrs) { + var subplots = layout._subplots; + var subplotId = ""; + if (visible || basePlotModule.name !== "gl2d") { + if (Array.isArray(subplotAttr)) { + for (i = 0; i < subplotAttr.length; i++) { + var attri = subplotAttr[i]; + var vali = Lib$1W.coerce(traceIn, traceOut, subplotAttrs, attri); + if (subplots[attri]) Lib$1W.pushUnique(subplots[attri], vali); + subplotId += vali; + } + } else { + subplotId = Lib$1W.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); + } + if (subplots[basePlotModule.name]) { + Lib$1W.pushUnique(subplots[basePlotModule.name], subplotId); + } + } + } + } + if (visible) { + coerce2("customdata"); + coerce2("ids"); + coerce2("meta"); + if (Registry$M.traceIs(traceOut, "showLegend")) { + Lib$1W.coerce( + traceIn, + traceOut, + _module.attributes.showlegend ? _module.attributes : plots$1.attributes, + "showlegend" + ); + coerce2("legend"); + coerce2("legendwidth"); + coerce2("legendgroup"); + coerce2("legendgrouptitle.text"); + coerce2("legendrank"); + traceOut._dfltShowLegend = true; + } else { + traceOut._dfltShowLegend = false; + } + if (_module) { + _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); + } + if (!Registry$M.traceIs(traceOut, "noOpacity")) { + coerce2("opacity"); + } + if (Registry$M.traceIs(traceOut, "notLegendIsolatable")) { + traceOut.visible = !!traceOut.visible; + } + if (!Registry$M.traceIs(traceOut, "noHover")) { + if (!traceOut.hovertemplate) Lib$1W.coerceHoverinfo(traceIn, traceOut, layout); + if (traceOut.type !== "parcats") { + Registry$M.getComponentMethod("fx", "supplyDefaults")(traceIn, traceOut, defaultColor, layout); + } + } + if (_module && _module.selectPoints) { + var selectedpoints = coerce2("selectedpoints"); + if (Lib$1W.isTypedArray(selectedpoints)) { + traceOut.selectedpoints = Array.from(selectedpoints); + } + } + plots$1.supplyTransformDefaults(traceIn, traceOut, layout); + } + return traceOut; +}; +function hasMakesDataTransform(trace) { + var transforms = trace.transforms; + if (Array.isArray(transforms) && transforms.length) { + for (var i = 0; i < transforms.length; i++) { + var ti = transforms[i]; + var _module = ti._module || transformsRegistry[ti.type]; + if (_module && _module.makesData) return true; + } + } + return false; +} +plots$1.hasMakesDataTransform = hasMakesDataTransform; +plots$1.supplyTransformDefaults = function(traceIn, traceOut, layout) { + if (!(traceOut._length || hasMakesDataTransform(traceIn))) return; + var globalTransforms = layout._globalTransforms || []; + var transformModules = layout._transformModules || []; + if (!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return; + var containerIn = traceIn.transforms || []; + var transformList = globalTransforms.concat(containerIn); + var containerOut = traceOut.transforms = []; + for (var i = 0; i < transformList.length; i++) { + var transformIn = transformList[i]; + var type = transformIn.type; + var _module = transformsRegistry[type]; + var transformOut; + var isFirstStage = !(transformIn._module && transformIn._module === _module); + var doLaterStages = _module && typeof _module.transform === "function"; + if (!_module) Lib$1W.warn("Unrecognized transform type " + type + "."); + if (_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { + transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); + transformOut.type = type; + transformOut._module = _module; + Lib$1W.pushUnique(transformModules, _module); + } else { + transformOut = Lib$1W.extendFlat({}, transformIn); + } + containerOut.push(transformOut); + } +}; +function applyTransforms(fullTrace, fullData, layout, fullLayout) { + var container = fullTrace.transforms; + var dataOut = [fullTrace]; + for (var i = 0; i < container.length; i++) { + var transform = container[i]; + var _module = transformsRegistry[transform.type]; + if (_module && _module.transform) { + dataOut = _module.transform(dataOut, { + transform, + fullTrace, + fullData, + layout, + fullLayout, + transformIndex: i + }); + } + } + return dataOut; +} +plots$1.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { + function coerce2(attr, dflt) { + return Lib$1W.coerce(layoutIn, layoutOut, plots$1.layoutAttributes, attr, dflt); + } + var template = layoutIn.template; + if (Lib$1W.isPlainObject(template)) { + layoutOut.template = template; + layoutOut._template = template.layout; + layoutOut._dataTemplate = template.data; + } + coerce2("autotypenumbers"); + var font2 = Lib$1W.coerceFont(coerce2, "font"); + var fontSize = font2.size; + Lib$1W.coerceFont(coerce2, "title.font", font2, { overrideDflt: { + size: Math.round(fontSize * 1.4) + } }); + coerce2("title.text", layoutOut._dfltTitle.plot); + coerce2("title.xref"); + var titleYref = coerce2("title.yref"); + coerce2("title.pad.t"); + coerce2("title.pad.r"); + coerce2("title.pad.b"); + coerce2("title.pad.l"); + var titleAutomargin = coerce2("title.automargin"); + coerce2("title.x"); + coerce2("title.xanchor"); + coerce2("title.y"); + coerce2("title.yanchor"); + coerce2("title.subtitle.text", layoutOut._dfltTitle.subtitle); + Lib$1W.coerceFont(coerce2, "title.subtitle.font", font2, { + overrideDflt: { + size: Math.round(layoutOut.title.font.size * 0.7) + } + }); + if (titleAutomargin) { + if (titleYref === "paper") { + if (layoutOut.title.y !== 0) layoutOut.title.y = 1; + if (layoutOut.title.yanchor === "auto") { + layoutOut.title.yanchor = layoutOut.title.y === 0 ? "top" : "bottom"; + } + } + if (titleYref === "container") { + if (layoutOut.title.y === "auto") layoutOut.title.y = 1; + if (layoutOut.title.yanchor === "auto") { + layoutOut.title.yanchor = layoutOut.title.y < 0.5 ? "bottom" : "top"; + } + } + } + var uniformtextMode = coerce2("uniformtext.mode"); + if (uniformtextMode) { + coerce2("uniformtext.minsize"); + } + coerce2("autosize", !(layoutIn.width && layoutIn.height)); + coerce2("width"); + coerce2("height"); + coerce2("minreducedwidth"); + coerce2("minreducedheight"); + coerce2("margin.l"); + coerce2("margin.r"); + coerce2("margin.t"); + coerce2("margin.b"); + coerce2("margin.pad"); + coerce2("margin.autoexpand"); + if (layoutIn.width && layoutIn.height) plots$1.sanitizeMargins(layoutOut); + Registry$M.getComponentMethod("grid", "sizeDefaults")(layoutIn, layoutOut); + coerce2("paper_bgcolor"); + coerce2("separators", formatObj.decimal + formatObj.thousands); + coerce2("hidesources"); + coerce2("colorway"); + coerce2("datarevision"); + var uirevision = coerce2("uirevision"); + coerce2("editrevision", uirevision); + coerce2("selectionrevision", uirevision); + Registry$M.getComponentMethod( + "modebar", + "supplyLayoutDefaults" + )(layoutIn, layoutOut); + Registry$M.getComponentMethod( + "shapes", + "supplyDrawNewShapeDefaults" + )(layoutIn, layoutOut, coerce2); + Registry$M.getComponentMethod( + "selections", + "supplyDrawNewSelectionDefaults" + )(layoutIn, layoutOut, coerce2); + coerce2("meta"); + if (Lib$1W.isPlainObject(layoutIn.transition)) { + coerce2("transition.duration"); + coerce2("transition.easing"); + coerce2("transition.ordering"); + } + Registry$M.getComponentMethod( + "calendars", + "handleDefaults" + )(layoutIn, layoutOut, "calendar"); + Registry$M.getComponentMethod( + "fx", + "supplyLayoutGlobalDefaults" + )(layoutIn, layoutOut, coerce2); + Lib$1W.coerce(layoutIn, layoutOut, scatterAttrs$3, "scattermode"); +}; +function getComputedSize(attr) { + return typeof attr === "string" && attr.substr(attr.length - 2) === "px" && parseFloat(attr); +} +plots$1.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { + var context2 = gd._context || {}; + var frameMargins = context2.frameMargins; + var newWidth; + var newHeight; + var isPlotDiv2 = Lib$1W.isPlotDiv(gd); + if (isPlotDiv2) gd.emit("plotly_autosize"); + if (context2.fillFrame) { + newWidth = window.innerWidth; + newHeight = window.innerHeight; + document.body.style.overflow = "hidden"; + } else { + var computedStyle = isPlotDiv2 ? window.getComputedStyle(gd) : {}; + newWidth = getComputedSize(computedStyle.width) || getComputedSize(computedStyle.maxWidth) || fullLayout.width; + newHeight = getComputedSize(computedStyle.height) || getComputedSize(computedStyle.maxHeight) || fullLayout.height; + if (isNumeric$u(frameMargins) && frameMargins > 0) { + var factor = 1 - 2 * frameMargins; + newWidth = Math.round(factor * newWidth); + newHeight = Math.round(factor * newHeight); + } + } + var minWidth = plots$1.layoutAttributes.width.min; + var minHeight = plots$1.layoutAttributes.height.min; + if (newWidth < minWidth) newWidth = minWidth; + if (newHeight < minHeight) newHeight = minHeight; + var widthHasChanged = !layout.width && Math.abs(fullLayout.width - newWidth) > 1; + var heightHasChanged = !layout.height && Math.abs(fullLayout.height - newHeight) > 1; + if (heightHasChanged || widthHasChanged) { + if (widthHasChanged) fullLayout.width = newWidth; + if (heightHasChanged) fullLayout.height = newHeight; + } + if (!gd._initialAutoSize) { + gd._initialAutoSize = { width: newWidth, height: newHeight }; + } + plots$1.sanitizeMargins(fullLayout); +}; +plots$1.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { + var componentsRegistry = Registry$M.componentsRegistry; + var basePlotModules = layoutOut._basePlotModules; + var component, i, _module; + var Cartesian = Registry$M.subplotsRegistry.cartesian; + for (component in componentsRegistry) { + _module = componentsRegistry[component]; + if (_module.includeBasePlot) { + _module.includeBasePlot(layoutIn, layoutOut); + } + } + if (!basePlotModules.length) { + basePlotModules.push(Cartesian); + } + if (layoutOut._has("cartesian")) { + Registry$M.getComponentMethod("grid", "contentDefaults")(layoutIn, layoutOut); + Cartesian.finalizeSubplots(layoutIn, layoutOut); + } + for (var subplotType in layoutOut._subplots) { + layoutOut._subplots[subplotType].sort(Lib$1W.subplotSort); + } + for (i = 0; i < basePlotModules.length; i++) { + _module = basePlotModules[i]; + if (_module.supplyLayoutDefaults) { + _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + } + } + var modules2 = layoutOut._modules; + for (i = 0; i < modules2.length; i++) { + _module = modules2[i]; + if (_module.supplyLayoutDefaults) { + _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + } + } + var transformModules = layoutOut._transformModules; + for (i = 0; i < transformModules.length; i++) { + _module = transformModules[i]; + if (_module.supplyLayoutDefaults) { + _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData); + } + } + for (component in componentsRegistry) { + _module = componentsRegistry[component]; + if (_module.supplyLayoutDefaults) { + _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); + } + } +}; +plots$1.purge = function(gd) { + var fullLayout = gd._fullLayout || {}; + if (fullLayout._glcontainer !== void 0) { + fullLayout._glcontainer.selectAll(".gl-canvas").remove(); + fullLayout._glcontainer.remove(); + fullLayout._glcanvas = null; + } + if (fullLayout._modeBar) fullLayout._modeBar.destroy(); + if (gd._transitionData) { + if (gd._transitionData._interruptCallbacks) { + gd._transitionData._interruptCallbacks.length = 0; + } + if (gd._transitionData._animationRaf) { + window.cancelAnimationFrame(gd._transitionData._animationRaf); + } + } + Lib$1W.clearThrottle(); + Lib$1W.clearResponsive(gd); + delete gd.data; + delete gd.layout; + delete gd._fullData; + delete gd._fullLayout; + delete gd.calcdata; + delete gd.empty; + delete gd.fid; + delete gd.undoqueue; + delete gd.undonum; + delete gd.autoplay; + delete gd.changed; + delete gd._promises; + delete gd._redrawTimer; + delete gd._hmlumcount; + delete gd._hmpixcount; + delete gd._transitionData; + delete gd._transitioning; + delete gd._initialAutoSize; + delete gd._transitioningWithDuration; + delete gd._dragging; + delete gd._dragged; + delete gd._dragdata; + delete gd._hoverdata; + delete gd._snapshotInProgress; + delete gd._editing; + delete gd._mouseDownTime; + delete gd._legendMouseDownTime; + if (gd.removeAllListeners) gd.removeAllListeners(); +}; +plots$1.style = function(gd) { + var _modules = gd._fullLayout._visibleModules; + var styleModules = []; + var i; + for (i = 0; i < _modules.length; i++) { + var _module = _modules[i]; + if (_module.style) { + Lib$1W.pushUnique(styleModules, _module.style); + } + } + for (i = 0; i < styleModules.length; i++) { + styleModules[i](gd); + } +}; +plots$1.sanitizeMargins = function(fullLayout) { + if (!fullLayout || !fullLayout.margin) return; + var width = fullLayout.width; + var height = fullLayout.height; + var margin = fullLayout.margin; + var plotWidth = width - (margin.l + margin.r); + var plotHeight = height - (margin.t + margin.b); + var correction; + if (plotWidth < 0) { + correction = (width - 1) / (margin.l + margin.r); + margin.l = Math.floor(correction * margin.l); + margin.r = Math.floor(correction * margin.r); + } + if (plotHeight < 0) { + correction = (height - 1) / (margin.t + margin.b); + margin.t = Math.floor(correction * margin.t); + margin.b = Math.floor(correction * margin.b); + } +}; +plots$1.clearAutoMarginIds = function(gd) { + gd._fullLayout._pushmarginIds = {}; +}; +plots$1.allowAutoMargin = function(gd, id) { + gd._fullLayout._pushmarginIds[id] = 1; +}; +function initMargins(fullLayout) { + var margin = fullLayout.margin; + if (!fullLayout._size) { + var gs = fullLayout._size = { + l: Math.round(margin.l), + r: Math.round(margin.r), + t: Math.round(margin.t), + b: Math.round(margin.b), + p: Math.round(margin.pad) + }; + gs.w = Math.round(fullLayout.width) - gs.l - gs.r; + gs.h = Math.round(fullLayout.height) - gs.t - gs.b; + } + if (!fullLayout._pushmargin) fullLayout._pushmargin = {}; + if (!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {}; + if (!fullLayout._reservedMargin) fullLayout._reservedMargin = {}; +} +var MIN_SPECIFIED_WIDTH = 2; +var MIN_SPECIFIED_HEIGHT = 2; +plots$1.autoMargin = function(gd, id, o) { + var fullLayout = gd._fullLayout; + var width = fullLayout.width; + var height = fullLayout.height; + var margin = fullLayout.margin; + var minreducedwidth = fullLayout.minreducedwidth; + var minreducedheight = fullLayout.minreducedheight; + var minFinalWidth = Lib$1W.constrain( + width - margin.l - margin.r, + MIN_SPECIFIED_WIDTH, + minreducedwidth + ); + var minFinalHeight = Lib$1W.constrain( + height - margin.t - margin.b, + MIN_SPECIFIED_HEIGHT, + minreducedheight + ); + var maxSpaceW = Math.max(0, width - minFinalWidth); + var maxSpaceH = Math.max(0, height - minFinalHeight); + var pushMargin = fullLayout._pushmargin; + var pushMarginIds = fullLayout._pushmarginIds; + if (margin.autoexpand !== false) { + if (!o) { + delete pushMargin[id]; + delete pushMarginIds[id]; + } else { + var pad2 = o.pad; + if (pad2 === void 0) { + pad2 = Math.min(12, margin.l, margin.r, margin.t, margin.b); + } + if (maxSpaceW) { + var rW = (o.l + o.r) / maxSpaceW; + if (rW > 1) { + o.l /= rW; + o.r /= rW; + } + } + if (maxSpaceH) { + var rH = (o.t + o.b) / maxSpaceH; + if (rH > 1) { + o.t /= rH; + o.b /= rH; + } + } + var xl = o.xl !== void 0 ? o.xl : o.x; + var xr = o.xr !== void 0 ? o.xr : o.x; + var yt = o.yt !== void 0 ? o.yt : o.y; + var yb = o.yb !== void 0 ? o.yb : o.y; + pushMargin[id] = { + l: { val: xl, size: o.l + pad2 }, + r: { val: xr, size: o.r + pad2 }, + b: { val: yb, size: o.b + pad2 }, + t: { val: yt, size: o.t + pad2 } + }; + pushMarginIds[id] = 1; + } + if (!fullLayout._replotting) { + return plots$1.doAutoMargin(gd); + } + } +}; +function needsRedrawForShift(gd) { + if ("_redrawFromAutoMarginCount" in gd._fullLayout) { + return false; + } + var axList = axisIDs$1.list(gd, "", true); + for (var ax in axList) { + if (axList[ax].autoshift || axList[ax].shift) return true; + } + return false; +} +plots$1.doAutoMargin = function(gd) { + var fullLayout = gd._fullLayout; + var width = fullLayout.width; + var height = fullLayout.height; + if (!fullLayout._size) fullLayout._size = {}; + initMargins(fullLayout); + var gs = fullLayout._size; + var margin = fullLayout.margin; + var reservedMargins = { t: 0, b: 0, l: 0, r: 0 }; + var oldMargins = Lib$1W.extendFlat({}, gs); + var ml = margin.l; + var mr = margin.r; + var mt = margin.t; + var mb = margin.b; + var pushMargin = fullLayout._pushmargin; + var pushMarginIds = fullLayout._pushmarginIds; + var minreducedwidth = fullLayout.minreducedwidth; + var minreducedheight = fullLayout.minreducedheight; + if (margin.autoexpand !== false) { + for (var k in pushMargin) { + if (!pushMarginIds[k]) delete pushMargin[k]; + } + var margins = gd._fullLayout._reservedMargin; + for (var key in margins) { + for (var side in margins[key]) { + var val = margins[key][side]; + reservedMargins[side] = Math.max(reservedMargins[side], val); + } + } + pushMargin.base = { + l: { val: 0, size: ml }, + r: { val: 1, size: mr }, + t: { val: 1, size: mt }, + b: { val: 0, size: mb } + }; + for (var s in reservedMargins) { + var autoMarginPush = 0; + for (var m in pushMargin) { + if (m !== "base") { + if (isNumeric$u(pushMargin[m][s].size)) { + autoMarginPush = pushMargin[m][s].size > autoMarginPush ? pushMargin[m][s].size : autoMarginPush; + } + } + } + var extraMargin = Math.max(0, margin[s] - autoMarginPush); + reservedMargins[s] = Math.max(0, reservedMargins[s] - extraMargin); + } + for (var k1 in pushMargin) { + var pushleft = pushMargin[k1].l || {}; + var pushbottom = pushMargin[k1].b || {}; + var fl = pushleft.val; + var pl = pushleft.size; + var fb = pushbottom.val; + var pb = pushbottom.size; + var availableWidth = width - reservedMargins.r - reservedMargins.l; + var availableHeight = height - reservedMargins.t - reservedMargins.b; + for (var k2 in pushMargin) { + if (isNumeric$u(pl) && pushMargin[k2].r) { + var fr = pushMargin[k2].r.val; + var pr = pushMargin[k2].r.size; + if (fr > fl) { + var newL = (pl * fr + (pr - availableWidth) * fl) / (fr - fl); + var newR = (pr * (1 - fl) + (pl - availableWidth) * (1 - fr)) / (fr - fl); + if (newL + newR > ml + mr) { + ml = newL; + mr = newR; + } + } + } + if (isNumeric$u(pb) && pushMargin[k2].t) { + var ft = pushMargin[k2].t.val; + var pt = pushMargin[k2].t.size; + if (ft > fb) { + var newB = (pb * ft + (pt - availableHeight) * fb) / (ft - fb); + var newT = (pt * (1 - fb) + (pb - availableHeight) * (1 - ft)) / (ft - fb); + if (newB + newT > mb + mt) { + mb = newB; + mt = newT; + } + } + } + } + } + } + var minFinalWidth = Lib$1W.constrain( + width - margin.l - margin.r, + MIN_SPECIFIED_WIDTH, + minreducedwidth + ); + var minFinalHeight = Lib$1W.constrain( + height - margin.t - margin.b, + MIN_SPECIFIED_HEIGHT, + minreducedheight + ); + var maxSpaceW = Math.max(0, width - minFinalWidth); + var maxSpaceH = Math.max(0, height - minFinalHeight); + if (maxSpaceW) { + var rW = (ml + mr) / maxSpaceW; + if (rW > 1) { + ml /= rW; + mr /= rW; + } + } + if (maxSpaceH) { + var rH = (mb + mt) / maxSpaceH; + if (rH > 1) { + mb /= rH; + mt /= rH; + } + } + gs.l = Math.round(ml) + reservedMargins.l; + gs.r = Math.round(mr) + reservedMargins.r; + gs.t = Math.round(mt) + reservedMargins.t; + gs.b = Math.round(mb) + reservedMargins.b; + gs.p = Math.round(margin.pad); + gs.w = Math.round(width) - gs.l - gs.r; + gs.h = Math.round(height) - gs.t - gs.b; + if (!fullLayout._replotting && (plots$1.didMarginChange(oldMargins, gs) || needsRedrawForShift(gd))) { + if ("_redrawFromAutoMarginCount" in fullLayout) { + fullLayout._redrawFromAutoMarginCount++; + } else { + fullLayout._redrawFromAutoMarginCount = 1; + } + var maxNumberOfRedraws = 3 * (1 + Object.keys(pushMarginIds).length); + if (fullLayout._redrawFromAutoMarginCount < maxNumberOfRedraws) { + return Registry$M.call("_doPlot", gd); + } else { + fullLayout._size = oldMargins; + Lib$1W.warn("Too many auto-margin redraws."); + } + } + refineTicks(gd); +}; +function refineTicks(gd) { + var axList = axisIDs$1.list(gd, "", true); + [ + "_adjustTickLabelsOverflow", + "_hideCounterAxisInsideTickLabels" + ].forEach(function(k) { + for (var i = 0; i < axList.length; i++) { + var hideFn = axList[i][k]; + if (hideFn) hideFn(); + } + }); +} +var marginKeys = ["l", "r", "t", "b", "p", "w", "h"]; +plots$1.didMarginChange = function(margin0, margin1) { + for (var i = 0; i < marginKeys.length; i++) { + var k = marginKeys[i]; + var m0 = margin0[k]; + var m1 = margin1[k]; + if (!isNumeric$u(m0) || Math.abs(m1 - m0) > 1) { + return true; + } + } + return false; +}; +plots$1.graphJson = function(gd, dataonly, mode, output, useDefaults, includeConfig) { + if (useDefaults && dataonly && !gd._fullData || useDefaults && !dataonly && !gd._fullLayout) { + plots$1.supplyDefaults(gd); + } + var data = useDefaults ? gd._fullData : gd.data; + var layout = useDefaults ? gd._fullLayout : gd.layout; + var frames = (gd._transitionData || {})._frames; + function stripObj(d, keepFunction) { + if (typeof d === "function") { + return keepFunction ? "_function_" : null; + } + if (Lib$1W.isPlainObject(d)) { + var o = {}; + var src2; + Object.keys(d).sort().forEach(function(v) { + if (["_", "["].indexOf(v.charAt(0)) !== -1) return; + if (typeof d[v] === "function") { + if (keepFunction) o[v] = "_function"; + return; + } + if (mode === "keepdata") { + if (v.substr(v.length - 3) === "src") { + return; + } + } else if (mode === "keepstream") { + src2 = d[v + "src"]; + if (typeof src2 === "string" && src2.indexOf(":") > 0) { + if (!Lib$1W.isPlainObject(d.stream)) { + return; + } + } + } else if (mode !== "keepall") { + src2 = d[v + "src"]; + if (typeof src2 === "string" && src2.indexOf(":") > 0) { + return; + } + } + o[v] = stripObj(d[v], keepFunction); + }); + return o; + } + var dIsArray = Array.isArray(d); + var dIsTypedArray = Lib$1W.isTypedArray(d); + if ((dIsArray || dIsTypedArray) && d.dtype && d.shape) { + var bdata = d.bdata; + return stripObj({ + dtype: d.dtype, + shape: d.shape, + bdata: ( + // case of ArrayBuffer + Lib$1W.isArrayBuffer(bdata) ? b64encode.encode(bdata) : ( + // case of b64 string + bdata + ) + ) + }, keepFunction); + } + if (dIsArray) { + return d.map(function(x) { + return stripObj(x, keepFunction); + }); + } + if (dIsTypedArray) { + return Lib$1W.simpleMap(d, Lib$1W.identity); + } + if (Lib$1W.isJSDate(d)) return Lib$1W.ms2DateTimeLocal(+d); + return d; + } + var obj = { + data: (data || []).map(function(v) { + var d = stripObj(v); + if (dataonly) { + delete d.fit; + } + return d; + }) + }; + if (!dataonly) { + obj.layout = stripObj(layout); + if (useDefaults) { + var gs = layout._size; + obj.layout.computed = { + margin: { + b: gs.b, + l: gs.l, + r: gs.r, + t: gs.t + } + }; + } + } + if (frames) obj.frames = stripObj(frames); + if (includeConfig) obj.config = stripObj(gd._context, true); + return output === "object" ? obj : JSON.stringify(obj); +}; +plots$1.modifyFrames = function(gd, operations) { + var i, op, frame; + var _frames = gd._transitionData._frames; + var _frameHash = gd._transitionData._frameHash; + for (i = 0; i < operations.length; i++) { + op = operations[i]; + switch (op.type) { + case "replace": + frame = op.value; + var oldName = (_frames[op.index] || {}).name; + var newName = frame.name; + _frames[op.index] = _frameHash[newName] = frame; + if (newName !== oldName) { + delete _frameHash[oldName]; + _frameHash[newName] = frame; + } + break; + case "insert": + frame = op.value; + _frameHash[frame.name] = frame; + _frames.splice(op.index, 0, frame); + break; + case "delete": + frame = _frames[op.index]; + delete _frameHash[frame.name]; + _frames.splice(op.index, 1); + break; + } + } + return Promise.resolve(); +}; +plots$1.computeFrame = function(gd, frameName) { + var frameLookup = gd._transitionData._frameHash; + var i, traceIndices, traceIndex, destIndex; + if (!frameName) { + throw new Error("computeFrame must be given a string frame name"); + } + var framePtr = frameLookup[frameName.toString()]; + if (!framePtr) { + return false; + } + var frameStack = [framePtr]; + var frameNameStack = [framePtr.name]; + while (framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) { + if (frameNameStack.indexOf(framePtr.name) !== -1) break; + frameStack.push(framePtr); + frameNameStack.push(framePtr.name); + } + var result = {}; + while (framePtr = frameStack.pop()) { + if (framePtr.layout) { + result.layout = plots$1.extendLayout(result.layout, framePtr.layout); + } + if (framePtr.data) { + if (!result.data) { + result.data = []; + } + traceIndices = framePtr.traces; + if (!traceIndices) { + traceIndices = []; + for (i = 0; i < framePtr.data.length; i++) { + traceIndices[i] = i; + } + } + if (!result.traces) { + result.traces = []; + } + for (i = 0; i < framePtr.data.length; i++) { + traceIndex = traceIndices[i]; + if (traceIndex === void 0 || traceIndex === null) { + continue; + } + destIndex = result.traces.indexOf(traceIndex); + if (destIndex === -1) { + destIndex = result.data.length; + result.traces[destIndex] = traceIndex; + } + result.data[destIndex] = plots$1.extendTrace(result.data[destIndex], framePtr.data[i]); + } + } + } + return result; +}; +plots$1.recomputeFrameHash = function(gd) { + var hash = gd._transitionData._frameHash = {}; + var frames = gd._transitionData._frames; + for (var i = 0; i < frames.length; i++) { + var frame = frames[i]; + if (frame && frame.name) { + hash[frame.name] = frame; + } + } +}; +plots$1.extendObjectWithContainers = function(dest, src2, containerPaths) { + var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; + var copy2 = Lib$1W.extendDeepNoArrays({}, src2 || {}); + var expandedObj = Lib$1W.expandObjectPaths(copy2); + var containerObj = {}; + if (containerPaths && containerPaths.length) { + for (i = 0; i < containerPaths.length; i++) { + containerProp = Lib$1W.nestedProperty(expandedObj, containerPaths[i]); + containerVal = containerProp.get(); + if (containerVal === void 0) { + Lib$1W.nestedProperty(containerObj, containerPaths[i]).set(null); + } else { + containerProp.set(null); + Lib$1W.nestedProperty(containerObj, containerPaths[i]).set(containerVal); + } + } + } + dest = Lib$1W.extendDeepNoArrays(dest || {}, expandedObj); + if (containerPaths && containerPaths.length) { + for (i = 0; i < containerPaths.length; i++) { + srcProp = Lib$1W.nestedProperty(containerObj, containerPaths[i]); + srcContainer = srcProp.get(); + if (!srcContainer) continue; + destProp = Lib$1W.nestedProperty(dest, containerPaths[i]); + destContainer = destProp.get(); + if (!Array.isArray(destContainer)) { + destContainer = []; + destProp.set(destContainer); + } + for (j = 0; j < srcContainer.length; j++) { + var srcObj = srcContainer[j]; + if (srcObj === null) destContainer[j] = null; + else { + destContainer[j] = plots$1.extendObjectWithContainers(destContainer[j], srcObj); + } + } + destProp.set(destContainer); + } + } + return dest; +}; +plots$1.dataArrayContainers = ["transforms", "dimensions"]; +plots$1.layoutArrayContainers = Registry$M.layoutArrayContainers; +plots$1.extendTrace = function(destTrace, srcTrace) { + return plots$1.extendObjectWithContainers(destTrace, srcTrace, plots$1.dataArrayContainers); +}; +plots$1.extendLayout = function(destLayout, srcLayout) { + return plots$1.extendObjectWithContainers(destLayout, srcLayout, plots$1.layoutArrayContainers); +}; +plots$1.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) { + var opts = { redraw: frameOpts.redraw }; + var transitionedTraces = {}; + var axEdits = []; + opts.prepareFn = function() { + var dataLength = Array.isArray(data) ? data.length : 0; + var traceIndices = traces.slice(0, dataLength); + for (var i = 0; i < traceIndices.length; i++) { + var traceIdx = traceIndices[i]; + var trace = gd._fullData[traceIdx]; + var _module = trace._module; + if (!_module) continue; + if (_module.animatable) { + var n = _module.basePlotModule.name; + if (!transitionedTraces[n]) transitionedTraces[n] = []; + transitionedTraces[n].push(traceIdx); + } + gd.data[traceIndices[i]] = plots$1.extendTrace(gd.data[traceIndices[i]], data[i]); + } + var layoutUpdate = Lib$1W.expandObjectPaths(Lib$1W.extendDeepNoArrays({}, layout)); + var axisAttrRe = /^[xy]axis[0-9]*$/; + for (var attr in layoutUpdate) { + if (!axisAttrRe.test(attr)) continue; + delete layoutUpdate[attr].range; + } + plots$1.extendLayout(gd.layout, layoutUpdate); + delete gd.calcdata; + plots$1.supplyDefaults(gd); + plots$1.doCalcdata(gd); + var newLayout = Lib$1W.expandObjectPaths(layout); + if (newLayout) { + var subplots = gd._fullLayout._plots; + for (var k in subplots) { + var plotinfo = subplots[k]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var xr0 = xa.range.slice(); + var yr0 = ya.range.slice(); + var xr1 = null; + var yr1 = null; + var editX = null; + var editY = null; + if (Array.isArray(newLayout[xa._name + ".range"])) { + xr1 = newLayout[xa._name + ".range"].slice(); + } else if (Array.isArray((newLayout[xa._name] || {}).range)) { + xr1 = newLayout[xa._name].range.slice(); + } + if (Array.isArray(newLayout[ya._name + ".range"])) { + yr1 = newLayout[ya._name + ".range"].slice(); + } else if (Array.isArray((newLayout[ya._name] || {}).range)) { + yr1 = newLayout[ya._name].range.slice(); + } + if (xr0 && xr1 && (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1]))) { + editX = { xr0, xr1 }; + } + if (yr0 && yr1 && (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1]))) { + editY = { yr0, yr1 }; + } + if (editX || editY) { + axEdits.push(Lib$1W.extendFlat({ plotinfo }, editX, editY)); + } + } + } + return Promise.resolve(); + }; + opts.runFn = function(makeCallback) { + var traceTransitionOpts; + var basePlotModules = gd._fullLayout._basePlotModules; + var hasAxisTransition = axEdits.length; + var i; + if (layout) { + for (i = 0; i < basePlotModules.length; i++) { + if (basePlotModules[i].transitionAxes) { + basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback); + } + } + } + if (hasAxisTransition) { + traceTransitionOpts = Lib$1W.extendFlat({}, transitionOpts); + traceTransitionOpts.duration = 0; + delete transitionedTraces.cartesian; + } else { + traceTransitionOpts = transitionOpts; + } + for (var n in transitionedTraces) { + var traceIndices = transitionedTraces[n]; + var _module = gd._fullData[traceIndices[0]]._module; + _module.basePlotModule.plot(gd, traceIndices, traceTransitionOpts, makeCallback); + } + }; + return _transition(gd, transitionOpts, opts); +}; +plots$1.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) { + var fullLayout = gd._fullLayout; + var transitionOpts = fullLayout.transition; + var opts = {}; + var axEdits = []; + opts.prepareFn = function() { + var subplots = fullLayout._plots; + opts.redraw = false; + if (restyleFlags.anim === "some") opts.redraw = true; + if (relayoutFlags.anim === "some") opts.redraw = true; + for (var k in subplots) { + var plotinfo = subplots[k]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var xr0 = oldFullLayout[xa._name].range.slice(); + var yr0 = oldFullLayout[ya._name].range.slice(); + var xr1 = xa.range.slice(); + var yr1 = ya.range.slice(); + xa.setScale(); + ya.setScale(); + var editX = null; + var editY = null; + if (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1])) { + editX = { xr0, xr1 }; + } + if (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1])) { + editY = { yr0, yr1 }; + } + if (editX || editY) { + axEdits.push(Lib$1W.extendFlat({ plotinfo }, editX, editY)); + } + } + return Promise.resolve(); + }; + opts.runFn = function(makeCallback) { + var fullData = gd._fullData; + var fullLayout2 = gd._fullLayout; + var basePlotModules = fullLayout2._basePlotModules; + var axisTransitionOpts; + var traceTransitionOpts; + var transitionedTraces; + var allTraceIndices = []; + for (var i = 0; i < fullData.length; i++) { + allTraceIndices.push(i); + } + function transitionAxes() { + if (!gd._fullLayout) return; + for (var j = 0; j < basePlotModules.length; j++) { + if (basePlotModules[j].transitionAxes) { + basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback); + } + } + } + function transitionTraces() { + if (!gd._fullLayout) return; + for (var j = 0; j < basePlotModules.length; j++) { + basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback); + } + } + if (axEdits.length && restyleFlags.anim) { + if (transitionOpts.ordering === "traces first") { + axisTransitionOpts = Lib$1W.extendFlat({}, transitionOpts, { duration: 0 }); + transitionedTraces = allTraceIndices; + traceTransitionOpts = transitionOpts; + setTimeout(transitionAxes, transitionOpts.duration); + transitionTraces(); + } else { + axisTransitionOpts = transitionOpts; + transitionedTraces = null; + traceTransitionOpts = Lib$1W.extendFlat({}, transitionOpts, { duration: 0 }); + setTimeout(transitionTraces, axisTransitionOpts.duration); + transitionAxes(); + } + } else if (axEdits.length) { + axisTransitionOpts = transitionOpts; + transitionAxes(); + } else if (restyleFlags.anim) { + transitionedTraces = allTraceIndices; + traceTransitionOpts = transitionOpts; + transitionTraces(); + } + }; + return _transition(gd, transitionOpts, opts); +}; +function _transition(gd, transitionOpts, opts) { + var aborted = false; + function executeCallbacks(list) { + var p = Promise.resolve(); + if (!list) return p; + while (list.length) { + p = p.then(list.shift()); + } + return p; + } + function flushCallbacks(list) { + if (!list) return; + while (list.length) { + list.shift(); + } + } + function executeTransitions() { + gd.emit("plotly_transitioning", []); + return new Promise(function(resolve) { + gd._transitioning = true; + if (transitionOpts.duration > 0) { + gd._transitioningWithDuration = true; + } + gd._transitionData._interruptCallbacks.push(function() { + aborted = true; + }); + if (opts.redraw) { + gd._transitionData._interruptCallbacks.push(function() { + return Registry$M.call("redraw", gd); + }); + } + gd._transitionData._interruptCallbacks.push(function() { + gd.emit("plotly_transitioninterrupted", []); + }); + var numCallbacks = 0; + var numCompleted = 0; + function makeCallback() { + numCallbacks++; + return function() { + numCompleted++; + if (!aborted && numCompleted === numCallbacks) { + completeTransition(resolve); + } + }; + } + opts.runFn(makeCallback); + setTimeout(makeCallback()); + }); + } + function completeTransition(callback) { + if (!gd._transitionData) return; + flushCallbacks(gd._transitionData._interruptCallbacks); + return Promise.resolve().then(function() { + if (opts.redraw) { + return Registry$M.call("redraw", gd); + } + }).then(function() { + gd._transitioning = false; + gd._transitioningWithDuration = false; + gd.emit("plotly_transitioned", []); + }).then(callback); + } + function interruptPreviousTransitions() { + if (!gd._transitionData) return; + gd._transitioning = false; + return executeCallbacks(gd._transitionData._interruptCallbacks); + } + var seq = [ + plots$1.previousPromises, + interruptPreviousTransitions, + opts.prepareFn, + plots$1.rehover, + plots$1.reselect, + executeTransitions + ]; + var transitionStarting = Lib$1W.syncOrAsync(seq, gd); + if (!transitionStarting || !transitionStarting.then) { + transitionStarting = Promise.resolve(); + } + return transitionStarting.then(function() { + return gd; + }); +} +plots$1.doCalcdata = function(gd, traces) { + var axList = axisIDs$1.list(gd); + var fullData = gd._fullData; + var fullLayout = gd._fullLayout; + var trace, _module, i, j; + var calcdata = new Array(fullData.length); + var oldCalcdata = (gd.calcdata || []).slice(); + gd.calcdata = calcdata; + fullLayout._numBoxes = 0; + fullLayout._numViolins = 0; + fullLayout._violinScaleGroupStats = {}; + gd._hmpixcount = 0; + gd._hmlumcount = 0; + fullLayout._piecolormap = {}; + fullLayout._sunburstcolormap = {}; + fullLayout._treemapcolormap = {}; + fullLayout._iciclecolormap = {}; + fullLayout._funnelareacolormap = {}; + for (i = 0; i < fullData.length; i++) { + if (Array.isArray(traces) && traces.indexOf(i) === -1) { + calcdata[i] = oldCalcdata[i]; + continue; + } + } + for (i = 0; i < fullData.length; i++) { + trace = fullData[i]; + trace._arrayAttrs = PlotSchema$2.findArrayAttributes(trace); + trace._extremes = {}; + } + var polarIds = fullLayout._subplots.polar || []; + for (i = 0; i < polarIds.length; i++) { + axList.push( + fullLayout[polarIds[i]].radialaxis, + fullLayout[polarIds[i]].angularaxis + ); + } + for (var k in fullLayout._colorAxes) { + var cOpts = fullLayout[k]; + if (cOpts.cauto !== false) { + delete cOpts.cmin; + delete cOpts.cmax; + } + } + var hasCalcTransform = false; + function transformCalci(i2) { + trace = fullData[i2]; + _module = trace._module; + if (trace.visible === true && trace.transforms) { + if (_module && _module.calc) { + var cdi = _module.calc(gd, trace); + if (cdi[0] && cdi[0].t && cdi[0].t._scene) { + delete cdi[0].t._scene.dirty; + } + } + for (j = 0; j < trace.transforms.length; j++) { + var transform = trace.transforms[j]; + _module = transformsRegistry[transform.type]; + if (_module && _module.calcTransform) { + trace._hasCalcTransform = true; + hasCalcTransform = true; + _module.calcTransform(gd, trace, transform); + } + } + } + } + function calci(i2, isContainer) { + trace = fullData[i2]; + _module = trace._module; + if (!!_module.isContainer !== isContainer) return; + var cd = []; + if (trace.visible === true && trace._length !== 0) { + delete trace._indexToPoints; + var transforms = trace.transforms || []; + for (j = transforms.length - 1; j >= 0; j--) { + if (transforms[j].enabled) { + trace._indexToPoints = transforms[j]._indexToPoints; + break; + } + } + if (_module && _module.calc) { + cd = _module.calc(gd, trace); + } + } + if (!Array.isArray(cd) || !cd[0]) { + cd = [{ x: BADNUM$a, y: BADNUM$a }]; + } + if (!cd[0].t) cd[0].t = {}; + cd[0].trace = trace; + calcdata[i2] = cd; + } + setupAxisCategories(axList, fullData, fullLayout); + for (i = 0; i < fullData.length; i++) calci(i, true); + for (i = 0; i < fullData.length; i++) transformCalci(i); + if (hasCalcTransform) setupAxisCategories(axList, fullData, fullLayout); + for (i = 0; i < fullData.length; i++) calci(i, true); + for (i = 0; i < fullData.length; i++) calci(i, false); + doCrossTraceCalc(gd); + var sorted = sortAxisCategoriesByValue(axList, gd); + if (sorted.length) { + fullLayout._numBoxes = 0; + fullLayout._numViolins = 0; + for (i = 0; i < sorted.length; i++) calci(sorted[i], true); + for (i = 0; i < sorted.length; i++) calci(sorted[i], false); + doCrossTraceCalc(gd); + } + Registry$M.getComponentMethod("fx", "calc")(gd); + Registry$M.getComponentMethod("errorbars", "calc")(gd); +}; +var sortAxisCategoriesByValueRegex = /(total|sum|min|max|mean|geometric mean|median) (ascending|descending)/; +function sortAxisCategoriesByValue(axList, gd) { + var affectedTraces = []; + var i, j, k, l, o; + function zMapCategory(type2, ax2, value3) { + var axLetter2 = ax2._id.charAt(0); + if (type2 === "histogram2dcontour") { + var counterAxLetter = ax2._counterAxes[0]; + var counterAx = axisIDs$1.getFromId(gd, counterAxLetter); + var xCategorical = axLetter2 === "x" || counterAxLetter === "x" && counterAx.type === "category"; + var yCategorical = axLetter2 === "y" || counterAxLetter === "y" && counterAx.type === "category"; + return function(o2, l2) { + if (o2 === 0 || l2 === 0) return -1; + if (xCategorical && o2 === value3[l2].length - 1) return -1; + if (yCategorical && l2 === value3.length - 1) return -1; + return (axLetter2 === "y" ? l2 : o2) - 1; + }; + } else { + return function(o2, l2) { + return axLetter2 === "y" ? l2 : o2; + }; + } + } + var aggFn = { + min: function(values) { + return Lib$1W.aggNums(Math.min, null, values); + }, + max: function(values) { + return Lib$1W.aggNums(Math.max, null, values); + }, + sum: function(values) { + return Lib$1W.aggNums(function(a, b) { + return a + b; + }, null, values); + }, + total: function(values) { + return Lib$1W.aggNums(function(a, b) { + return a + b; + }, null, values); + }, + mean: function(values) { + return Lib$1W.mean(values); + }, + "geometric mean": function(values) { + return Lib$1W.geometricMean(values); + }, + median: function(values) { + return Lib$1W.median(values); + } + }; + function sortAscending(a, b) { + return a[1] - b[1]; + } + function sortDescending(a, b) { + return b[1] - a[1]; + } + for (i = 0; i < axList.length; i++) { + var ax = axList[i]; + if (ax.type !== "category") continue; + var match = ax.categoryorder.match(sortAxisCategoriesByValueRegex); + if (match) { + var aggregator = match[1]; + var order = match[2]; + var axLetter = ax._id.charAt(0); + var isX = axLetter === "x"; + var categoriesValue = []; + for (j = 0; j < ax._categories.length; j++) { + categoriesValue.push([ax._categories[j], []]); + } + for (j = 0; j < ax._traceIndices.length; j++) { + var traceIndex = ax._traceIndices[j]; + var fullTrace = gd._fullData[traceIndex]; + if (fullTrace.visible !== true) continue; + var type = fullTrace.type; + if (Registry$M.traceIs(fullTrace, "histogram")) { + delete fullTrace._xautoBinFinished; + delete fullTrace._yautoBinFinished; + } + var isSplom = type === "splom"; + var isScattergl = type === "scattergl"; + var cd = gd.calcdata[traceIndex]; + for (k = 0; k < cd.length; k++) { + var cdi = cd[k]; + var catIndex, value2; + if (isSplom) { + var currentDimensionIndex = fullTrace._axesDim[ax._id]; + if (!isX) { + var associatedXAxisID = fullTrace._diag[currentDimensionIndex][0]; + if (associatedXAxisID) ax = gd._fullLayout[axisIDs$1.id2name(associatedXAxisID)]; + } + var categories = cdi.trace.dimensions[currentDimensionIndex].values; + for (l = 0; l < categories.length; l++) { + catIndex = ax._categoriesMap[categories[l]]; + for (o = 0; o < cdi.trace.dimensions.length; o++) { + if (o === currentDimensionIndex) continue; + var dimension = cdi.trace.dimensions[o]; + categoriesValue[catIndex][1].push(dimension.values[l]); + } + } + } else if (isScattergl) { + for (l = 0; l < cdi.t.x.length; l++) { + if (isX) { + catIndex = cdi.t.x[l]; + value2 = cdi.t.y[l]; + } else { + catIndex = cdi.t.y[l]; + value2 = cdi.t.x[l]; + } + categoriesValue[catIndex][1].push(value2); + } + if (cdi.t && cdi.t._scene) { + delete cdi.t._scene.dirty; + } + } else if (cdi.hasOwnProperty("z")) { + value2 = cdi.z; + var mapping = zMapCategory(fullTrace.type, ax, value2); + for (l = 0; l < value2.length; l++) { + for (o = 0; o < value2[l].length; o++) { + catIndex = mapping(o, l); + if (catIndex + 1) categoriesValue[catIndex][1].push(value2[l][o]); + } + } + } else { + catIndex = cdi.p; + if (catIndex === void 0) catIndex = cdi[axLetter]; + value2 = cdi.s; + if (value2 === void 0) value2 = cdi.v; + if (value2 === void 0) value2 = isX ? cdi.y : cdi.x; + if (!Array.isArray(value2)) { + if (value2 === void 0) value2 = []; + else value2 = [value2]; + } + for (l = 0; l < value2.length; l++) { + categoriesValue[catIndex][1].push(value2[l]); + } + } + } + } + ax._categoriesValue = categoriesValue; + var categoriesAggregatedValue = []; + for (j = 0; j < categoriesValue.length; j++) { + categoriesAggregatedValue.push([ + categoriesValue[j][0], + aggFn[aggregator](categoriesValue[j][1]) + ]); + } + categoriesAggregatedValue.sort(order === "descending" ? sortDescending : sortAscending); + ax._categoriesAggregatedValue = categoriesAggregatedValue; + ax._initialCategories = categoriesAggregatedValue.map(function(c) { + return c[0]; + }); + affectedTraces = affectedTraces.concat(ax.sortByInitialCategories()); + } + } + return affectedTraces; +} +function setupAxisCategories(axList, fullData, fullLayout) { + var axLookup = {}; + function setupOne(ax) { + ax.clearCalc(); + if (ax.type === "multicategory") { + ax.setupMultiCategory(fullData); + } + axLookup[ax._id] = 1; + } + Lib$1W.simpleMap(axList, setupOne); + var matchGroups = fullLayout._axisMatchGroups || []; + for (var i = 0; i < matchGroups.length; i++) { + for (var axId in matchGroups[i]) { + if (!axLookup[axId]) { + setupOne(fullLayout[axisIDs$1.id2name(axId)]); + } + } + } +} +function doCrossTraceCalc(gd) { + var fullLayout = gd._fullLayout; + var modules2 = fullLayout._visibleModules; + var hash = {}; + var i, j, k; + for (j = 0; j < modules2.length; j++) { + var _module = modules2[j]; + var fn = _module.crossTraceCalc; + if (fn) { + var spType = _module.basePlotModule.name; + if (hash[spType]) { + Lib$1W.pushUnique(hash[spType], fn); + } else { + hash[spType] = [fn]; + } + } + } + for (k in hash) { + var methods2 = hash[k]; + var subplots = fullLayout._subplots[k]; + if (Array.isArray(subplots)) { + for (i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + var spInfo = k === "cartesian" ? fullLayout._plots[sp] : fullLayout[sp]; + for (j = 0; j < methods2.length; j++) { + methods2[j](gd, spInfo, sp); + } + } + } else { + for (j = 0; j < methods2.length; j++) { + methods2[j](gd); + } + } + } +} +plots$1.rehover = function(gd) { + if (gd._fullLayout._rehover) { + gd._fullLayout._rehover(); + } +}; +plots$1.redrag = function(gd) { + if (gd._fullLayout._redrag) { + gd._fullLayout._redrag(); + } +}; +plots$1.reselect = function(gd) { + var fullLayout = gd._fullLayout; + var A2 = (gd.layout || {}).selections; + var B2 = fullLayout._previousSelections; + fullLayout._previousSelections = A2; + var mayEmitSelected = fullLayout._reselect || JSON.stringify(A2) !== JSON.stringify(B2); + Registry$M.getComponentMethod("selections", "reselect")(gd, mayEmitSelected); +}; +plots$1.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) { + var traceHashOld = subplot.traceHash; + var traceHash = {}; + var i; + for (i = 0; i < subplotCalcData.length; i++) { + var calcTraces = subplotCalcData[i]; + var trace = calcTraces[0].trace; + if (trace.visible) { + traceHash[trace.type] = traceHash[trace.type] || []; + traceHash[trace.type].push(calcTraces); + } + } + for (var moduleNameOld in traceHashOld) { + if (!traceHash[moduleNameOld]) { + var fakeCalcTrace = traceHashOld[moduleNameOld][0]; + var fakeTrace = fakeCalcTrace[0].trace; + fakeTrace.visible = false; + traceHash[moduleNameOld] = [fakeCalcTrace]; + } + } + for (var moduleName in traceHash) { + var moduleCalcData = traceHash[moduleName]; + var _module = moduleCalcData[0][0].trace._module; + _module.plot(gd, subplot, Lib$1W.filterVisible(moduleCalcData), subplotLayout); + } + subplot.traceHash = traceHash; +}; +plots$1.plotBasePlot = function(desiredType, gd, traces, transitionOpts, makeOnCompleteCallback) { + var _module = Registry$M.getModule(desiredType); + var cdmodule = getModuleCalcData$1(gd.calcdata, _module)[0]; + _module.plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback); +}; +plots$1.cleanBasePlot = function(desiredType, newFullData, newFullLayout, oldFullData, oldFullLayout) { + var had = oldFullLayout._has && oldFullLayout._has(desiredType); + var has = newFullLayout._has && newFullLayout._has(desiredType); + if (had && !has) { + oldFullLayout["_" + desiredType + "layer"].selectAll("g.trace").remove(); + } +}; +var plotsExports = plots$2.exports; +var axes$1 = { exports: {} }; +var svg_text_utils = {}; +var xmlns_namespaces = {}; +(function(exports2) { + exports2.xmlns = "http://www.w3.org/2000/xmlns/"; + exports2.svg = "http://www.w3.org/2000/svg"; + exports2.xlink = "http://www.w3.org/1999/xlink"; + exports2.svgAttrs = { + xmlns: exports2.svg, + "xmlns:xlink": exports2.xlink + }; +})(xmlns_namespaces); +var alignment$1 = { + // from bottom left: this is the origin of our paper-reference + // positioning system + FROM_BL: { + left: 0, + center: 0.5, + right: 1, + bottom: 0, + middle: 0.5, + top: 1 + }, + // from top left: this is the screen pixel positioning origin + FROM_TL: { + left: 0, + center: 0.5, + right: 1, + bottom: 1, + middle: 0.5, + top: 0 + }, + // from bottom right: sometimes you just need the opposite of ^^ + FROM_BR: { + left: 1, + center: 0.5, + right: 0, + bottom: 0, + middle: 0.5, + top: 1 + }, + // multiple of fontSize to get the vertical offset between lines + LINE_SPACING: 1.3, + // multiple of fontSize to shift from the baseline + // to the cap (captical letter) line + // (to use when we don't calculate this shift from Drawing.bBox) + // This is an approximation since in reality cap height can differ + // from font to font. However, according to Wikipedia + // an "average" font might have a cap height of 70% of the em + // https://en.wikipedia.org/wiki/Em_(typography)#History + CAP_SHIFT: 0.7, + // half the cap height (distance between baseline and cap line) + // of an "average" font (for more info see above). + MID_SHIFT: 0.35, + OPPOSITE_SIDE: { + left: "right", + right: "left", + top: "bottom", + bottom: "top" + } +}; +(function(exports2) { + var d32 = d3Exports; + var Lib2 = libExports; + var strTranslate2 = Lib2.strTranslate; + var xmlnsNamespaces2 = xmlns_namespaces; + var LINE_SPACING2 = alignment$1.LINE_SPACING; + var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; + exports2.convertToTspans = function(_context, gd, _callback) { + var str2 = _context.text(); + var tex = !_context.attr("data-notex") && gd && gd._context.typesetMath && typeof MathJax !== "undefined" && str2.match(FIND_TEX); + var parent = d32.select(_context.node().parentNode); + if (parent.empty()) return; + var svgClass = _context.attr("class") ? _context.attr("class").split(" ")[0] : "text"; + svgClass += "-math"; + parent.selectAll("svg." + svgClass).remove(); + parent.selectAll("g." + svgClass + "-group").remove(); + _context.style("display", null).attr({ + // some callers use data-unformatted *from the element* in 'cancel' + // so we need it here even if we're going to turn it into math + // these two (plus style and text-anchor attributes) form the key we're + // going to use for Drawing.bBox + "data-unformatted": str2, + "data-math": "N" + }); + function showText() { + if (!parent.empty()) { + svgClass = _context.attr("class") + "-math"; + parent.select("svg." + svgClass).remove(); + } + _context.text("").style("white-space", "pre"); + var hasLink = buildSVGText(_context.node(), str2); + if (hasLink) { + _context.style("pointer-events", "all"); + } + exports2.positionText(_context); + if (_callback) _callback.call(_context); + } + if (tex) { + (gd && gd._promises || []).push(new Promise(function(resolve) { + _context.style("display", "none"); + var fontSize = parseInt(_context.node().style.fontSize, 10); + var config = { fontSize }; + texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) { + parent.selectAll("svg." + svgClass).remove(); + parent.selectAll("g." + svgClass + "-group").remove(); + var newSvg = _svgEl && _svgEl.select("svg"); + if (!newSvg || !newSvg.node()) { + showText(); + resolve(); + return; + } + var mathjaxGroup = parent.append("g").classed(svgClass + "-group", true).attr({ + "pointer-events": "none", + "data-unformatted": str2, + "data-math": "Y" + }); + mathjaxGroup.node().appendChild(newSvg.node()); + if (_glyphDefs && _glyphDefs.node()) { + newSvg.node().insertBefore( + _glyphDefs.node().cloneNode(true), + newSvg.node().firstChild + ); + } + var w0 = _svgBBox.width; + var h0 = _svgBBox.height; + newSvg.attr({ + class: svgClass, + height: h0, + preserveAspectRatio: "xMinYMin meet" + }).style({ overflow: "visible", "pointer-events": "none" }); + var fill = _context.node().style.fill || "black"; + var g = newSvg.select("g"); + g.attr({ fill, stroke: fill }); + var bb = g.node().getBoundingClientRect(); + var w = bb.width; + var h = bb.height; + if (w > w0 || h > h0) { + newSvg.style("overflow", "hidden"); + bb = newSvg.node().getBoundingClientRect(); + w = bb.width; + h = bb.height; + } + var x = +_context.attr("x"); + var y = +_context.attr("y"); + var textHeight = fontSize || _context.node().getBoundingClientRect().height; + var dy = -textHeight / 4; + if (svgClass[0] === "y") { + mathjaxGroup.attr({ + transform: "rotate(" + [-90, x, y] + ")" + strTranslate2(-w / 2, dy - h / 2) + }); + } else if (svgClass[0] === "l") { + y = dy - h / 2; + } else if (svgClass[0] === "a" && svgClass.indexOf("atitle") !== 0) { + x = 0; + y = dy; + } else { + var anchor = _context.attr("text-anchor"); + x = x - w * (anchor === "middle" ? 0.5 : anchor === "end" ? 1 : 0); + y = y + dy - h / 2; + } + newSvg.attr({ + x, + y + }); + if (_callback) _callback.call(_context, mathjaxGroup); + resolve(mathjaxGroup); + }); + })); + } else showText(); + return _context; + }; + var LT_MATCH = /(<|<|<)/g; + var GT_MATCH = /(>|>|>)/g; + function cleanEscapesForTex(s) { + return s.replace(LT_MATCH, "\\lt ").replace(GT_MATCH, "\\gt "); + } + var inlineMath = [["$", "$"], ["\\(", "\\)"]]; + function texToSVG(_texString, _config, _callback) { + var MathJaxVersion = parseInt( + (MathJax.version || "").split(".")[0] + ); + if (MathJaxVersion !== 2 && MathJaxVersion !== 3) { + Lib2.warn("No MathJax version:", MathJax.version); + return; + } + var originalRenderer, originalConfig, originalProcessSectionDelay, tmpDiv; + var setConfig2 = function() { + originalConfig = Lib2.extendDeepAll({}, MathJax.Hub.config); + originalProcessSectionDelay = MathJax.Hub.processSectionDelay; + if (MathJax.Hub.processSectionDelay !== void 0) { + MathJax.Hub.processSectionDelay = 0; + } + return MathJax.Hub.Config({ + messageStyle: "none", + tex2jax: { + inlineMath + }, + displayAlign: "left" + }); + }; + var setConfig3 = function() { + originalConfig = Lib2.extendDeepAll({}, MathJax.config); + if (!MathJax.config.tex) { + MathJax.config.tex = {}; + } + MathJax.config.tex.inlineMath = inlineMath; + }; + var setRenderer2 = function() { + originalRenderer = MathJax.Hub.config.menuSettings.renderer; + if (originalRenderer !== "SVG") { + return MathJax.Hub.setRenderer("SVG"); + } + }; + var setRenderer3 = function() { + originalRenderer = MathJax.config.startup.output; + if (originalRenderer !== "svg") { + MathJax.config.startup.output = "svg"; + } + }; + var initiateMathJax = function() { + var randomID = "math-output-" + Lib2.randstr({}, 64); + tmpDiv = d32.select("body").append("div").attr({ id: randomID }).style({ + visibility: "hidden", + position: "absolute", + "font-size": _config.fontSize + "px" + }).text(cleanEscapesForTex(_texString)); + var tmpNode = tmpDiv.node(); + return MathJaxVersion === 2 ? MathJax.Hub.Typeset(tmpNode) : MathJax.typeset([tmpNode]); + }; + var finalizeMathJax = function() { + var sel = tmpDiv.select( + MathJaxVersion === 2 ? ".MathJax_SVG" : ".MathJax" + ); + var node = !sel.empty() && tmpDiv.select("svg").node(); + if (!node) { + Lib2.log("There was an error in the tex syntax.", _texString); + _callback(); + } else { + var nodeBBox = node.getBoundingClientRect(); + var glyphDefs; + if (MathJaxVersion === 2) { + glyphDefs = d32.select("body").select("#MathJax_SVG_glyphs"); + } else { + glyphDefs = sel.select("defs"); + } + _callback(sel, glyphDefs, nodeBBox); + } + tmpDiv.remove(); + }; + var resetRenderer2 = function() { + if (originalRenderer !== "SVG") { + return MathJax.Hub.setRenderer(originalRenderer); + } + }; + var resetRenderer3 = function() { + if (originalRenderer !== "svg") { + MathJax.config.startup.output = originalRenderer; + } + }; + var resetConfig2 = function() { + if (originalProcessSectionDelay !== void 0) { + MathJax.Hub.processSectionDelay = originalProcessSectionDelay; + } + return MathJax.Hub.Config(originalConfig); + }; + var resetConfig3 = function() { + MathJax.config = originalConfig; + }; + if (MathJaxVersion === 2) { + MathJax.Hub.Queue( + setConfig2, + setRenderer2, + initiateMathJax, + finalizeMathJax, + resetRenderer2, + resetConfig2 + ); + } else if (MathJaxVersion === 3) { + setConfig3(); + setRenderer3(); + MathJax.startup.defaultReady(); + MathJax.startup.promise.then(function() { + initiateMathJax(); + finalizeMathJax(); + resetRenderer3(); + resetConfig3(); + }); + } + } + var TAG_STYLES = { + // would like to use baseline-shift for sub/sup but FF doesn't support it + // so we need to use dy along with the uber hacky shift-back-to + // baseline below + sup: "font-size:70%", + sub: "font-size:70%", + s: "text-decoration:line-through", + u: "text-decoration:underline", + b: "font-weight:bold", + i: "font-style:italic", + a: "cursor:pointer", + span: "", + em: "font-style:italic;font-weight:bold" + }; + var SHIFT_DY = { + sub: "0.3em", + sup: "-0.6em" + }; + var RESET_DY = { + sub: "-0.21em", + sup: "0.42em" + }; + var ZERO_WIDTH_SPACE = "​"; + var PROTOCOLS = ["http:", "https:", "mailto:", "", void 0, ":"]; + var NEWLINES = exports2.NEWLINES = /(\r\n?|\n)/g; + var SPLIT_TAGS = /(<[^<>]*>)/; + var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i; + var BR_TAG = //i; + exports2.BR_TAG_ALL = //gi; + var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i; + var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i; + var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i; + var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i; + function getQuotedMatch(_str, re2) { + if (!_str) return null; + var match = _str.match(re2); + var result = match && (match[3] || match[4]); + return result && convertEntities(result); + } + var COLORMATCH = /(^|;)\s*color:/; + exports2.plainText = function(_str, opts) { + opts = opts || {}; + var len = opts.len !== void 0 && opts.len !== -1 ? opts.len : Infinity; + var allowedTags = opts.allowedTags !== void 0 ? opts.allowedTags : ["br"]; + var ellipsis = "..."; + var eLen = ellipsis.length; + var oldParts = _str.split(SPLIT_TAGS); + var newParts = []; + var prevTag = ""; + var l = 0; + for (var i = 0; i < oldParts.length; i++) { + var p = oldParts[i]; + var match = p.match(ONE_TAG); + var tagType = match && match[2].toLowerCase(); + if (tagType) { + if (allowedTags.indexOf(tagType) !== -1) { + newParts.push(p); + prevTag = tagType; + } + } else { + var pLen = p.length; + if (l + pLen < len) { + newParts.push(p); + l += pLen; + } else if (l < len) { + var pLen2 = len - l; + if (prevTag && (prevTag !== "br" || pLen2 <= eLen || pLen <= eLen)) { + newParts.pop(); + } + if (len > eLen) { + newParts.push(p.substr(0, pLen2 - eLen) + ellipsis); + } else { + newParts.push(p.substr(0, pLen2)); + } + break; + } + prevTag = ""; + } + } + return newParts.join(""); + }; + var entityToUnicode = { + mu: "μ", + amp: "&", + lt: "<", + gt: ">", + nbsp: " ", + times: "×", + plusmn: "±", + deg: "°" + }; + var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g; + function convertEntities(_str) { + return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) { + var outChar; + if (innerMatch.charAt(0) === "#") { + outChar = fromCodePoint( + innerMatch.charAt(1) === "x" ? parseInt(innerMatch.substr(2), 16) : parseInt(innerMatch.substr(1), 10) + ); + } else outChar = entityToUnicode[innerMatch]; + return outChar || fullMatch; + }); + } + exports2.convertEntities = convertEntities; + function fromCodePoint(code2) { + if (code2 > 1114111) return; + var stringFromCodePoint = String.fromCodePoint; + if (stringFromCodePoint) return stringFromCodePoint(code2); + var stringFromCharCode = String.fromCharCode; + if (code2 <= 65535) return stringFromCharCode(code2); + return stringFromCharCode( + (code2 >> 10) + 55232, + code2 % 1024 + 56320 + ); + } + function buildSVGText(containerNode, str2) { + str2 = str2.replace(NEWLINES, " "); + var hasLink = false; + var nodeStack = []; + var currentNode; + var currentLine = -1; + function newLine() { + currentLine++; + var lineNode = document.createElementNS(xmlnsNamespaces2.svg, "tspan"); + d32.select(lineNode).attr({ + class: "line", + dy: currentLine * LINE_SPACING2 + "em" + }); + containerNode.appendChild(lineNode); + currentNode = lineNode; + var oldNodeStack = nodeStack; + nodeStack = [{ node: lineNode }]; + if (oldNodeStack.length > 1) { + for (var i2 = 1; i2 < oldNodeStack.length; i2++) { + enterNode(oldNodeStack[i2]); + } + } + } + function enterNode(nodeSpec2) { + var type = nodeSpec2.type; + var nodeAttrs = {}; + var nodeType; + if (type === "a") { + nodeType = "a"; + var target = nodeSpec2.target; + var href2 = nodeSpec2.href; + var popup = nodeSpec2.popup; + if (href2) { + nodeAttrs = { + "xlink:xlink:show": target === "_blank" || target.charAt(0) !== "_" ? "new" : "replace", + target, + "xlink:xlink:href": href2 + }; + if (popup) { + nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' + popup + '");return false;'; + } + } + } else nodeType = "tspan"; + if (nodeSpec2.style) nodeAttrs.style = nodeSpec2.style; + var newNode = document.createElementNS(xmlnsNamespaces2.svg, nodeType); + if (type === "sup" || type === "sub") { + addTextNode(currentNode, ZERO_WIDTH_SPACE); + currentNode.appendChild(newNode); + var resetter = document.createElementNS(xmlnsNamespaces2.svg, "tspan"); + addTextNode(resetter, ZERO_WIDTH_SPACE); + d32.select(resetter).attr("dy", RESET_DY[type]); + nodeAttrs.dy = SHIFT_DY[type]; + currentNode.appendChild(newNode); + currentNode.appendChild(resetter); + } else { + currentNode.appendChild(newNode); + } + d32.select(newNode).attr(nodeAttrs); + currentNode = nodeSpec2.node = newNode; + nodeStack.push(nodeSpec2); + } + function addTextNode(node, text) { + node.appendChild(document.createTextNode(text)); + } + function exitNode(type) { + if (nodeStack.length === 1) { + Lib2.log("Ignoring unexpected end tag .", str2); + return; + } + var innerNode = nodeStack.pop(); + if (type !== innerNode.type) { + Lib2.log("Start tag <" + innerNode.type + "> doesnt match end tag <" + type + ">. Pretending it did match.", str2); + } + currentNode = nodeStack[nodeStack.length - 1].node; + } + var hasLines = BR_TAG.test(str2); + if (hasLines) newLine(); + else { + currentNode = containerNode; + nodeStack = [{ node: containerNode }]; + } + var parts = str2.split(SPLIT_TAGS); + for (var i = 0; i < parts.length; i++) { + var parti = parts[i]; + var match = parti.match(ONE_TAG); + var tagType = match && match[2].toLowerCase(); + var tagStyle = TAG_STYLES[tagType]; + if (tagType === "br") { + newLine(); + } else if (tagStyle === void 0) { + addTextNode(currentNode, convertEntities(parti)); + } else { + if (match[1]) { + exitNode(tagType); + } else { + var extra = match[4]; + var nodeSpec = { type: tagType }; + var css = getQuotedMatch(extra, STYLEMATCH); + if (css) { + css = css.replace(COLORMATCH, "$1 fill:"); + if (tagStyle) css += ";" + tagStyle; + } else if (tagStyle) css = tagStyle; + if (css) nodeSpec.style = css; + if (tagType === "a") { + hasLink = true; + var href = getQuotedMatch(extra, HREFMATCH); + if (href) { + var safeHref = sanitizeHref(href); + if (safeHref) { + nodeSpec.href = safeHref; + nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || "_blank"; + nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH); + } + } + } + enterNode(nodeSpec); + } + } + } + return hasLink; + } + function sanitizeHref(href) { + var decodedHref = encodeURI(decodeURI(href)); + var dummyAnchor1 = document.createElement("a"); + var dummyAnchor2 = document.createElement("a"); + dummyAnchor1.href = href; + dummyAnchor2.href = decodedHref; + var p1 = dummyAnchor1.protocol; + var p2 = dummyAnchor2.protocol; + if (PROTOCOLS.indexOf(p1) !== -1 && PROTOCOLS.indexOf(p2) !== -1) { + return decodedHref; + } else { + return ""; + } + } + exports2.sanitizeHTML = function sanitizeHTML(str2) { + str2 = str2.replace(NEWLINES, " "); + var rootNode = document.createElement("p"); + var currentNode = rootNode; + var nodeStack = []; + var parts = str2.split(SPLIT_TAGS); + for (var i = 0; i < parts.length; i++) { + var parti = parts[i]; + var match = parti.match(ONE_TAG); + var tagType = match && match[2].toLowerCase(); + if (tagType in TAG_STYLES) { + if (match[1]) { + if (nodeStack.length) { + currentNode = nodeStack.pop(); + } + } else { + var extra = match[4]; + var css = getQuotedMatch(extra, STYLEMATCH); + var nodeAttrs = css ? { style: css } : {}; + if (tagType === "a") { + var href = getQuotedMatch(extra, HREFMATCH); + if (href) { + var safeHref = sanitizeHref(href); + if (safeHref) { + nodeAttrs.href = safeHref; + var target = getQuotedMatch(extra, TARGETMATCH); + if (target) { + nodeAttrs.target = target; + } + } + } + } + var newNode = document.createElement(tagType); + currentNode.appendChild(newNode); + d32.select(newNode).attr(nodeAttrs); + currentNode = newNode; + nodeStack.push(newNode); + } + } else { + currentNode.appendChild( + document.createTextNode(convertEntities(parti)) + ); + } + } + var key = "innerHTML"; + return rootNode[key]; + }; + exports2.lineCount = function lineCount(s) { + return s.selectAll("tspan.line").size() || 1; + }; + exports2.positionText = function positionText(s, x, y) { + return s.each(function() { + var text = d32.select(this); + function setOrGet(attr, val) { + if (val === void 0) { + val = text.attr(attr); + if (val === null) { + text.attr(attr, 0); + val = 0; + } + } else text.attr(attr, val); + return val; + } + var thisX = setOrGet("x", x); + var thisY = setOrGet("y", y); + if (this.nodeName === "text") { + text.selectAll("tspan.line").attr({ x: thisX, y: thisY }); + } + }); + }; + function alignHTMLWith(_base, container, options) { + var alignH = options.horizontalAlign; + var alignV = options.verticalAlign || "top"; + var bRect = _base.node().getBoundingClientRect(); + var cRect = container.node().getBoundingClientRect(); + var thisRect; + var getTop; + var getLeft; + if (alignV === "bottom") { + getTop = function() { + return bRect.bottom - thisRect.height; + }; + } else if (alignV === "middle") { + getTop = function() { + return bRect.top + (bRect.height - thisRect.height) / 2; + }; + } else { + getTop = function() { + return bRect.top; + }; + } + if (alignH === "right") { + getLeft = function() { + return bRect.right - thisRect.width; + }; + } else if (alignH === "center") { + getLeft = function() { + return bRect.left + (bRect.width - thisRect.width) / 2; + }; + } else { + getLeft = function() { + return bRect.left; + }; + } + return function() { + thisRect = this.node().getBoundingClientRect(); + var x0 = getLeft() - cRect.left; + var y0 = getTop() - cRect.top; + var gd = options.gd || {}; + if (options.gd) { + gd._fullLayout._calcInverseTransform(gd); + var transformedCoords = Lib2.apply3DTransform(gd._fullLayout._invTransform)(x0, y0); + x0 = transformedCoords[0]; + y0 = transformedCoords[1]; + } + this.style({ + top: y0 + "px", + left: x0 + "px", + "z-index": 1e3 + }); + return this; + }; + } + var onePx = "1px "; + exports2.makeTextShadow = function(color2) { + var x = onePx; + var y = onePx; + var b = onePx; + return x + y + b + color2 + ", -" + x + "-" + y + b + color2 + ", " + x + "-" + y + b + color2 + ", -" + x + y + b + color2; + }; + exports2.makeEditable = function(context2, options) { + var gd = options.gd; + var _delegate = options.delegate; + var dispatch = d32.dispatch("edit", "input", "cancel"); + var handlerElement = _delegate || context2; + context2.style({ "pointer-events": _delegate ? "none" : "all" }); + if (context2.size() !== 1) throw new Error("boo"); + function handleClick3() { + appendEditable(); + context2.style({ opacity: 0 }); + var svgClass = handlerElement.attr("class"); + var mathjaxClass; + if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group"; + else mathjaxClass = "[class*=-math-group]"; + if (mathjaxClass) { + d32.select(context2.node().parentNode).select(mathjaxClass).style({ opacity: 0 }); + } + } + function selectElementContents(_el) { + var el = _el.node(); + var range = document.createRange(); + range.selectNodeContents(el); + var sel = window.getSelection(); + sel.removeAllRanges(); + sel.addRange(range); + el.focus(); + } + function appendEditable() { + var plotDiv = d32.select(gd); + var container = plotDiv.select(".svg-container"); + var div = container.append("div"); + var cStyle = context2.node().style; + var fontSize = parseFloat(cStyle.fontSize || 12); + var initialText = options.text; + if (initialText === void 0) initialText = context2.attr("data-unformatted"); + div.classed("plugin-editable editable", true).style({ + position: "absolute", + "font-family": cStyle.fontFamily || "Arial", + "font-size": fontSize, + color: options.fill || cStyle.fill || "black", + opacity: 1, + "background-color": options.background || "transparent", + outline: "#ffffff33 1px solid", + margin: [-fontSize / 8 + 1, 0, 0, -1].join("px ") + "px", + padding: "0", + "box-sizing": "border-box" + }).attr({ contenteditable: true }).text(initialText).call(alignHTMLWith(context2, container, options)).on("blur", function() { + gd._editing = false; + context2.text(this.textContent).style({ opacity: 1 }); + var svgClass = d32.select(this).attr("class"); + var mathjaxClass; + if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group"; + else mathjaxClass = "[class*=-math-group]"; + if (mathjaxClass) { + d32.select(context2.node().parentNode).select(mathjaxClass).style({ opacity: 0 }); + } + var text = this.textContent; + d32.select(this).transition().duration(0).remove(); + d32.select(document).on("mouseup", null); + dispatch.edit.call(context2, text); + }).on("focus", function() { + var editDiv = this; + gd._editing = true; + d32.select(document).on("mouseup", function() { + if (d32.event.target === editDiv) return false; + if (document.activeElement === div.node()) div.node().blur(); + }); + }).on("keyup", function() { + if (d32.event.which === 27) { + gd._editing = false; + context2.style({ opacity: 1 }); + d32.select(this).style({ opacity: 0 }).on("blur", function() { + return false; + }).transition().remove(); + dispatch.cancel.call(context2, this.textContent); + } else { + dispatch.input.call(context2, this.textContent); + d32.select(this).call(alignHTMLWith(context2, container, options)); + } + }).on("keydown", function() { + if (d32.event.which === 13) this.blur(); + }).call(selectElementContents); + } + if (options.immediate) handleClick3(); + else handlerElement.on("click", handleClick3); + return d32.rebind(context2, dispatch, "on"); + }; +})(svg_text_utils); +var drawing$1 = { exports: {} }; +var d3$A = d3Exports; +var tinycolor$5 = tinycolorExports; +var isNumeric$t = fastIsnumeric; +var Lib$1V = libExports; +var Color$K = colorExports; +var isValidScale$1 = scales_1.isValid; +function hasColorscale$7(trace, containerStr, colorKey) { + var container = containerStr ? Lib$1V.nestedProperty(trace, containerStr).get() || {} : trace; + var color2 = container[colorKey || "color"]; + if (color2 && color2._inputArray) color2 = color2._inputArray; + var isArrayWithOneNumber = false; + if (Lib$1V.isArrayOrTypedArray(color2)) { + for (var i = 0; i < color2.length; i++) { + if (isNumeric$t(color2[i])) { + isArrayWithOneNumber = true; + break; + } + } + } + return Lib$1V.isPlainObject(container) && (isArrayWithOneNumber || container.showscale === true || isNumeric$t(container.cmin) && isNumeric$t(container.cmax) || isValidScale$1(container.colorscale) || Lib$1V.isPlainObject(container.colorbar)); +} +var constantAttrs = ["showscale", "autocolorscale", "colorscale", "reversescale", "colorbar"]; +var letterAttrs = ["min", "max", "mid", "auto"]; +function extractOpts$3(cont) { + var colorAx = cont._colorAx; + var cont2 = colorAx ? colorAx : cont; + var out = {}; + var cLetter; + var i, k; + for (i = 0; i < constantAttrs.length; i++) { + k = constantAttrs[i]; + out[k] = cont2[k]; + } + if (colorAx) { + cLetter = "c"; + for (i = 0; i < letterAttrs.length; i++) { + k = letterAttrs[i]; + out[k] = cont2["c" + k]; + } + } else { + var k2; + for (i = 0; i < letterAttrs.length; i++) { + k = letterAttrs[i]; + k2 = "c" + k; + if (k2 in cont2) { + out[k] = cont2[k2]; + continue; + } + k2 = "z" + k; + if (k2 in cont2) { + out[k] = cont2[k2]; + } + } + cLetter = k2.charAt(0); + } + out._sync = function(k3, v) { + var k22 = letterAttrs.indexOf(k3) !== -1 ? cLetter + k3 : k3; + cont2[k22] = cont2["_" + k22] = v; + }; + return out; +} +function extractScale(cont) { + var cOpts = extractOpts$3(cont); + var cmin = cOpts.min; + var cmax = cOpts.max; + var scl = cOpts.reversescale ? flipScale$1(cOpts.colorscale) : cOpts.colorscale; + var N = scl.length; + var domain2 = new Array(N); + var range = new Array(N); + for (var i = 0; i < N; i++) { + var si = scl[i]; + domain2[i] = cmin + si[0] * (cmax - cmin); + range[i] = si[1]; + } + return { domain: domain2, range }; +} +function flipScale$1(scl) { + var N = scl.length; + var sclNew = new Array(N); + for (var i = N - 1, j = 0; i >= 0; i--, j++) { + var si = scl[i]; + sclNew[j] = [1 - si[0], si[1]]; + } + return sclNew; +} +function makeColorScaleFunc(specs, opts) { + opts = opts || {}; + var domain2 = specs.domain; + var range = specs.range; + var N = range.length; + var _range = new Array(N); + for (var i = 0; i < N; i++) { + var rgba3 = tinycolor$5(range[i]).toRgb(); + _range[i] = [rgba3.r, rgba3.g, rgba3.b, rgba3.a]; + } + var _sclFunc = d3$A.scale.linear().domain(domain2).range(_range).clamp(true); + var noNumericCheck = opts.noNumericCheck; + var returnArray = opts.returnArray; + var sclFunc; + if (noNumericCheck && returnArray) { + sclFunc = _sclFunc; + } else if (noNumericCheck) { + sclFunc = function(v) { + return colorArray2rbga(_sclFunc(v)); + }; + } else if (returnArray) { + sclFunc = function(v) { + if (isNumeric$t(v)) return _sclFunc(v); + else if (tinycolor$5(v).isValid()) return v; + else return Color$K.defaultLine; + }; + } else { + sclFunc = function(v) { + if (isNumeric$t(v)) return colorArray2rbga(_sclFunc(v)); + else if (tinycolor$5(v).isValid()) return v; + else return Color$K.defaultLine; + }; + } + sclFunc.domain = _sclFunc.domain; + sclFunc.range = function() { + return range; + }; + return sclFunc; +} +function makeColorScaleFuncFromTrace(trace, opts) { + return makeColorScaleFunc(extractScale(trace), opts); +} +function colorArray2rbga(colorArray) { + var colorObj = { + r: colorArray[0], + g: colorArray[1], + b: colorArray[2], + a: colorArray[3] + }; + return tinycolor$5(colorObj).toRgbString(); +} +var helpers$L = { + hasColorscale: hasColorscale$7, + extractOpts: extractOpts$3, + extractScale, + flipScale: flipScale$1, + makeColorScaleFunc, + makeColorScaleFuncFromTrace +}; +var docs = docs$2; +var FORMAT_LINK = docs.FORMAT_LINK; +var DATE_FORMAT_LINK = docs.DATE_FORMAT_LINK; +function axisHoverFormat$5(x, noDates) { + return { + valType: "string", + dflt: "", + editType: "none", + description: (noDates ? descriptionOnlyNumbers : descriptionWithDates$1)("hover text", x) + [ + "By default the values are formatted using " + (noDates ? "generic number format" : "`" + x + "axis.hoverformat`") + "." + ].join(" ") + }; +} +function descriptionOnlyNumbers(label, x) { + return [ + "Sets the " + label + " formatting rule" + (x ? "for `" + x + "` " : ""), + "using d3 formatting mini-languages", + "which are very similar to those in Python. For numbers, see: " + FORMAT_LINK + "." + ].join(" "); +} +function descriptionWithDates$1(label, x) { + return descriptionOnlyNumbers(label, x) + [ + " And for dates see: " + DATE_FORMAT_LINK + ".", + "We add two items to d3's date formatter:", + "*%h* for half of the year as a decimal number as well as", + "*%{n}f* for fractional seconds", + "with n digits. For example, *2016-10-13 09:15:23.456* with tickformat", + "*%H~%M~%S.%2f* would display *09~15~23.46*" + ].join(" "); +} +var axis_format_attributes = { + axisHoverFormat: axisHoverFormat$5, + descriptionWithDates: descriptionWithDates$1 +}; +var fontAttrs$c = font_attributes; +var colorAttrs$5 = attributes$N; +var dash$4 = attributes$M.dash; +var extendFlat$g = extend$5.extendFlat; +var templatedArray$8 = plot_template.templatedArray; +var descriptionWithDates = axis_format_attributes.descriptionWithDates; +var ONEDAY$3 = numerical.ONEDAY; +var constants$T = constants$U; +var HOUR$1 = constants$T.HOUR_PATTERN; +var DAY_OF_WEEK$1 = constants$T.WEEKDAY_PATTERN; +var minorTickmode = { + valType: "enumerated", + values: ["auto", "linear", "array"], + editType: "ticks", + impliedEdits: { tick0: void 0, dtick: void 0 }, + description: [ + "Sets the tick mode for this axis.", + "If *auto*, the number of ticks is set via `nticks`.", + "If *linear*, the placement of the ticks is determined by", + "a starting position `tick0` and a tick step `dtick`", + "(*linear* is the default value if `tick0` and `dtick` are provided).", + "If *array*, the placement of the ticks is set via `tickvals`", + "and the tick text is `ticktext`.", + "(*array* is the default value if `tickvals` is provided)." + ].join(" ") +}; +var tickmode = extendFlat$g({}, minorTickmode, { + values: minorTickmode.values.slice().concat(["sync"]), + description: [ + minorTickmode.description, + "If *sync*, the number of ticks will sync with the overlayed axis", + "set by `overlaying` property." + ].join(" ") +}); +function makeNticks(minor) { + return { + valType: "integer", + min: 0, + dflt: minor ? 5 : 0, + editType: "ticks", + description: [ + "Specifies the maximum number of ticks for the particular axis.", + "The actual number of ticks will be chosen automatically to be", + "less than or equal to `nticks`.", + "Has an effect only if `tickmode` is set to *auto*." + ].join(" ") + }; +} +var tick0 = { + valType: "any", + editType: "ticks", + impliedEdits: { tickmode: "linear" }, + description: [ + "Sets the placement of the first tick on this axis.", + "Use with `dtick`.", + "If the axis `type` is *log*, then you must take the log of your starting tick", + "(e.g. to set the starting tick to 100, set the `tick0` to 2)", + "except when `dtick`=*L* (see `dtick` for more info).", + "If the axis `type` is *date*, it should be a date string, like date data.", + "If the axis `type` is *category*, it should be a number, using the scale where", + "each category is assigned a serial number from zero in the order it appears." + ].join(" ") +}; +var dtick = { + valType: "any", + editType: "ticks", + impliedEdits: { tickmode: "linear" }, + description: [ + "Sets the step in-between ticks on this axis. Use with `tick0`.", + "Must be a positive number, or special strings available to *log* and *date* axes.", + "If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n", + "is the tick number. For example,", + "to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1.", + "To set tick marks at 1, 100, 10000, ... set dtick to 2.", + "To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433.", + "*log* has several special values; *L*, where `f` is a positive number,", + "gives ticks linearly spaced in value (but not position).", + "For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc.", + "To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5).", + "`tick0` is ignored for *D1* and *D2*.", + "If the axis `type` is *date*, then you must convert the time to milliseconds.", + "For example, to set the interval between ticks to one day,", + "set `dtick` to 86400000.0.", + "*date* also has special values *M* gives ticks spaced by a number of months.", + "`n` must be a positive integer.", + "To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*.", + "To set ticks every 4 years, set `dtick` to *M48*" + ].join(" ") +}; +var tickvals = { + valType: "data_array", + editType: "ticks", + description: [ + "Sets the values at which ticks on this axis appear.", + "Only has an effect if `tickmode` is set to *array*.", + "Used with `ticktext`." + ].join(" ") +}; +var ticks = { + valType: "enumerated", + values: ["outside", "inside", ""], + editType: "ticks", + description: [ + "Determines whether ticks are drawn or not.", + "If **, this axis' ticks are not drawn.", + "If *outside* (*inside*), this axis' are drawn outside (inside)", + "the axis lines." + ].join(" ") +}; +function makeTicklen(minor) { + var obj = { + valType: "number", + min: 0, + editType: "ticks", + description: "Sets the tick length (in px)." + }; + if (!minor) obj.dflt = 5; + return obj; +} +function makeTickwidth(minor) { + var obj = { + valType: "number", + min: 0, + editType: "ticks", + description: "Sets the tick width (in px)." + }; + if (!minor) obj.dflt = 1; + return obj; +} +var tickcolor = { + valType: "color", + dflt: colorAttrs$5.defaultLine, + editType: "ticks", + description: "Sets the tick color." +}; +var gridcolor = { + valType: "color", + dflt: colorAttrs$5.lightLine, + editType: "ticks", + description: "Sets the color of the grid lines." +}; +function makeGridwidth(minor) { + var obj = { + valType: "number", + min: 0, + editType: "ticks", + description: "Sets the width (in px) of the grid lines." + }; + if (!minor) obj.dflt = 1; + return obj; +} +var griddash = extendFlat$g({}, dash$4, { editType: "ticks" }); +var showgrid = { + valType: "boolean", + editType: "ticks", + description: [ + "Determines whether or not grid lines are drawn.", + "If *true*, the grid lines are drawn at every tick mark." + ].join(" ") +}; +var layout_attributes$4 = { + visible: { + valType: "boolean", + editType: "plot", + description: [ + "A single toggle to hide the axis while preserving interaction like dragging.", + "Default is true when a cheater plot is present on the axis, otherwise", + "false" + ].join(" ") + }, + color: { + valType: "color", + dflt: colorAttrs$5.defaultLine, + editType: "ticks", + description: [ + "Sets default for all colors associated with this axis", + "all at once: line, font, tick, and grid colors.", + "Grid color is lightened by blending this with the plot background", + "Individual pieces can override this." + ].join(" ") + }, + title: { + text: { + valType: "string", + editType: "ticks", + description: [ + "Sets the title of this axis.", + "Note that before the existence of `title.text`, the title's", + "contents used to be defined as the `title` attribute itself.", + "This behavior has been deprecated." + ].join(" ") + }, + font: fontAttrs$c({ + editType: "ticks", + description: [ + "Sets this axis' title font.", + "Note that the title's font used to be customized", + "by the now deprecated `titlefont` attribute." + ].join(" ") + }), + standoff: { + valType: "number", + min: 0, + editType: "ticks", + description: [ + "Sets the standoff distance (in px) between the axis labels and the title text", + "The default value is a function of the axis tick labels, the title `font.size`", + "and the axis `linewidth`.", + "Note that the axis title position is always constrained within the margins,", + "so the actual standoff distance is always less than the set or default value.", + "By setting `standoff` and turning on `automargin`, plotly.js will push the", + "margins to fit the axis title at given standoff distance." + ].join(" ") + }, + editType: "ticks" + }, + type: { + valType: "enumerated", + // '-' means we haven't yet run autotype or couldn't find any data + // it gets turned into linear in gd._fullLayout but not copied back + // to gd.data like the others are. + values: ["-", "linear", "log", "date", "category", "multicategory"], + dflt: "-", + editType: "calc", + // we forget when an axis has been autotyped, just writing the auto + // value back to the input - so it doesn't make sense to template this. + // Note: we do NOT prohibit this in `coerce`, so if someone enters a + // type in the template explicitly it will be honored as the default. + _noTemplating: true, + description: [ + "Sets the axis type.", + "By default, plotly attempts to determined the axis type", + "by looking into the data of the traces that referenced", + "the axis in question." + ].join(" ") + }, + autotypenumbers: { + valType: "enumerated", + values: ["convert types", "strict"], + dflt: "convert types", + editType: "calc", + description: [ + "Using *strict* a numeric string in trace data is not converted to a number.", + "Using *convert types* a numeric string in trace data may be", + "treated as a number during automatic axis `type` detection.", + "Defaults to layout.autotypenumbers." + ].join(" ") + }, + autorange: { + valType: "enumerated", + values: [true, false, "reversed", "min reversed", "max reversed", "min", "max"], + dflt: true, + editType: "axrange", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Determines whether or not the range of this axis is", + "computed in relation to the input data.", + "See `rangemode` for more info.", + "If `range` is provided and it has a value for both the", + "lower and upper bound, `autorange` is set to *false*.", + "Using *min* applies autorange only to set the minimum.", + "Using *max* applies autorange only to set the maximum.", + "Using *min reversed* applies autorange only to set the minimum on a reversed axis.", + "Using *max reversed* applies autorange only to set the maximum on a reversed axis.", + "Using *reversed* applies autorange on both ends and reverses the axis direction." + ].join(" ") + }, + autorangeoptions: { + minallowed: { + valType: "any", + editType: "plot", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Use this value exactly as autorange minimum." + ].join(" ") + }, + maxallowed: { + valType: "any", + editType: "plot", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Use this value exactly as autorange maximum." + ].join(" ") + }, + clipmin: { + valType: "any", + editType: "plot", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Clip autorange minimum if it goes beyond this value.", + "Has no effect when `autorangeoptions.minallowed` is provided." + ].join(" ") + }, + clipmax: { + valType: "any", + editType: "plot", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Clip autorange maximum if it goes beyond this value.", + "Has no effect when `autorangeoptions.maxallowed` is provided." + ].join(" ") + }, + include: { + valType: "any", + arrayOk: true, + editType: "plot", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Ensure this value is included in autorange." + ].join(" ") + }, + editType: "plot" + }, + rangemode: { + valType: "enumerated", + values: ["normal", "tozero", "nonnegative"], + dflt: "normal", + editType: "plot", + description: [ + "If *normal*, the range is computed in relation to the extrema", + "of the input data.", + "If *tozero*`, the range extends to 0,", + "regardless of the input data", + "If *nonnegative*, the range is non-negative,", + "regardless of the input data.", + "Applies only to linear axes." + ].join(" ") + }, + range: { + valType: "info_array", + items: [ + { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true }, + { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true } + ], + editType: "axrange", + impliedEdits: { autorange: false }, + anim: true, + description: [ + "Sets the range of this axis.", + "If the axis `type` is *log*, then you must take the log of your", + "desired range (e.g. to set the range from 1 to 100,", + "set the range from 0 to 2).", + "If the axis `type` is *date*, it should be date strings,", + "like date data, though Date objects and unix milliseconds", + "will be accepted and converted to strings.", + "If the axis `type` is *category*, it should be numbers,", + "using the scale where each category is assigned a serial", + "number from zero in the order it appears.", + "Leaving either or both elements `null` impacts the default `autorange`." + ].join(" ") + }, + minallowed: { + valType: "any", + editType: "plot", + impliedEdits: { "^autorange": false }, + description: [ + "Determines the minimum range of this axis." + ].join(" ") + }, + maxallowed: { + valType: "any", + editType: "plot", + impliedEdits: { "^autorange": false }, + description: [ + "Determines the maximum range of this axis." + ].join(" ") + }, + fixedrange: { + valType: "boolean", + dflt: false, + editType: "calc", + description: [ + "Determines whether or not this axis is zoom-able.", + "If true, then zoom is disabled." + ].join(" ") + }, + insiderange: { + valType: "info_array", + items: [ + { valType: "any", editType: "plot" }, + { valType: "any", editType: "plot" } + ], + editType: "plot", + description: [ + "Could be used to set the desired inside range of this axis", + "(excluding the labels) when `ticklabelposition` of", + "the anchored axis has *inside*.", + "Not implemented for axes with `type` *log*.", + "This would be ignored when `range` is provided." + ].join(" ") + }, + // scaleanchor: not used directly, just put here for reference + // values are any opposite-letter axis id, or `false`. + scaleanchor: { + valType: "enumerated", + values: [ + constants$T.idRegex.x.toString(), + constants$T.idRegex.y.toString(), + false + ], + editType: "plot", + description: [ + "If set to another axis id (e.g. `x2`, `y`), the range of this axis", + "changes together with the range of the corresponding axis", + "such that the scale of pixels per unit is in a constant ratio.", + "Both axes are still zoomable, but when you zoom one, the other will", + "zoom the same amount, keeping a fixed midpoint.", + "`constrain` and `constraintoward` determine how we enforce the constraint.", + "You can chain these, ie `yaxis: {scaleanchor: *x*}, xaxis2: {scaleanchor: *y*}`", + "but you can only link axes of the same `type`.", + "The linked axis can have the opposite letter (to constrain the aspect ratio)", + "or the same letter (to match scales across subplots).", + "Loops (`yaxis: {scaleanchor: *x*}, xaxis: {scaleanchor: *y*}` or longer) are redundant", + "and the last constraint encountered will be ignored to avoid possible", + "inconsistent constraints via `scaleratio`.", + "Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint", + "is currently forbidden.", + "Setting `false` allows to remove a default constraint (occasionally,", + "you may need to prevent a default `scaleanchor` constraint from", + 'being applied, eg. when having an image trace `yaxis: {scaleanchor: "x"}`', + "is set automatically in order for pixels to be rendered as squares,", + "setting `yaxis: {scaleanchor: false}` allows to remove the constraint)." + ].join(" ") + }, + scaleratio: { + valType: "number", + min: 0, + dflt: 1, + editType: "plot", + description: [ + "If this axis is linked to another by `scaleanchor`, this determines the pixel", + "to unit scale ratio. For example, if this value is 10, then every unit on", + "this axis spans 10 times the number of pixels as a unit on the linked axis.", + "Use this for example to create an elevation profile where the vertical scale", + "is exaggerated a fixed amount with respect to the horizontal." + ].join(" ") + }, + constrain: { + valType: "enumerated", + values: ["range", "domain"], + editType: "plot", + description: [ + "If this axis needs to be compressed (either due to its own `scaleanchor` and", + "`scaleratio` or those of the other axis), determines how that happens:", + "by increasing the *range*, or by decreasing the *domain*.", + "Default is *domain* for axes containing image traces, *range* otherwise." + ].join(" ") + }, + // constraintoward: not used directly, just put here for reference + constraintoward: { + valType: "enumerated", + values: ["left", "center", "right", "top", "middle", "bottom"], + editType: "plot", + description: [ + "If this axis needs to be compressed (either due to its own `scaleanchor` and", + "`scaleratio` or those of the other axis), determines which direction we push", + "the originally specified plot area. Options are *left*, *center* (default),", + "and *right* for x axes, and *top*, *middle* (default), and *bottom* for y axes." + ].join(" ") + }, + matches: { + valType: "enumerated", + values: [ + constants$T.idRegex.x.toString(), + constants$T.idRegex.y.toString() + ], + editType: "calc", + description: [ + "If set to another axis id (e.g. `x2`, `y`), the range of this axis", + "will match the range of the corresponding axis in data-coordinates space.", + "Moreover, matching axes share auto-range values, category lists and", + "histogram auto-bins.", + "Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint", + "is currently forbidden.", + "Moreover, note that matching axes must have the same `type`." + ].join(" ") + }, + rangebreaks: templatedArray$8("rangebreak", { + enabled: { + valType: "boolean", + dflt: true, + editType: "calc", + description: [ + "Determines whether this axis rangebreak is enabled or disabled.", + "Please note that `rangebreaks` only work for *date* axis type." + ].join(" ") + }, + bounds: { + valType: "info_array", + items: [ + { valType: "any", editType: "calc" }, + { valType: "any", editType: "calc" } + ], + editType: "calc", + description: [ + "Sets the lower and upper bounds of this axis rangebreak.", + "Can be used with `pattern`." + ].join(" ") + }, + pattern: { + valType: "enumerated", + values: [DAY_OF_WEEK$1, HOUR$1, ""], + editType: "calc", + description: [ + "Determines a pattern on the time line that generates breaks.", + "If *" + DAY_OF_WEEK$1 + "* - days of the week in English e.g. 'Sunday' or `sun`", + "(matching is case-insensitive and considers only the first three characters),", + "as well as Sunday-based integers between 0 and 6.", + "If *" + HOUR$1 + "* - hour (24-hour clock) as decimal numbers between 0 and 24.", + "for more info.", + "Examples:", + "- { pattern: '" + DAY_OF_WEEK$1 + "', bounds: [6, 1] }", + " or simply { bounds: ['sat', 'mon'] }", + " breaks from Saturday to Monday (i.e. skips the weekends).", + "- { pattern: '" + HOUR$1 + "', bounds: [17, 8] }", + " breaks from 5pm to 8am (i.e. skips non-work hours)." + ].join(" ") + }, + values: { + valType: "info_array", + freeLength: true, + editType: "calc", + items: { + valType: "any", + editType: "calc" + }, + description: [ + "Sets the coordinate values corresponding to the rangebreaks.", + "An alternative to `bounds`.", + "Use `dvalue` to set the size of the values along the axis." + ].join(" ") + }, + dvalue: { + // TODO could become 'any' to add support for 'months', 'years' + valType: "number", + editType: "calc", + min: 0, + dflt: ONEDAY$3, + description: [ + "Sets the size of each `values` item.", + "The default is one day in milliseconds." + ].join(" ") + }, + /* + gap: { + valType: 'number', + min: 0, + dflt: 0, // for *date* axes, maybe something else for *linear* + editType: 'calc', + description: [ + 'Sets the gap distance between the start and the end of this rangebreak.', + 'Use with `gapmode` to set the unit of measurement.' + ].join(' ') + }, + gapmode: { + valType: 'enumerated', + values: ['pixels', 'fraction'], + dflt: 'pixels', + editType: 'calc', + description: [ + 'Determines if the `gap` value corresponds to a pixel length', + 'or a fraction of the plot area.' + ].join(' ') + }, + */ + // To complete https://github.com/plotly/plotly.js/issues/4210 + // we additionally need `gap` and make this work on *linear*, and + // possibly all other cartesian axis types. We possibly would also need + // some style attributes controlling the zig-zag on the corresponding + // axis. + editType: "calc" + }), + // ticks + tickmode, + nticks: makeNticks(), + tick0, + dtick, + ticklabelstep: { + valType: "integer", + min: 1, + dflt: 1, + editType: "ticks", + description: [ + "Sets the spacing between tick labels as compared to the spacing between ticks.", + "A value of 1 (default) means each tick gets a label.", + "A value of 2 means shows every 2nd label.", + "A larger value n means only every nth tick is labeled.", + "`tick0` determines which labels are shown.", + "Not implemented for axes with `type` *log* or *multicategory*, or when `tickmode` is *array*." + ].join(" ") + }, + tickvals, + ticktext: { + valType: "data_array", + editType: "ticks", + description: [ + "Sets the text displayed at the ticks position via `tickvals`.", + "Only has an effect if `tickmode` is set to *array*.", + "Used with `tickvals`." + ].join(" ") + }, + ticks, + tickson: { + valType: "enumerated", + values: ["labels", "boundaries"], + dflt: "labels", + editType: "ticks", + description: [ + "Determines where ticks and grid lines are drawn with respect to their", + "corresponding tick labels.", + "Only has an effect for axes of `type` *category* or *multicategory*.", + "When set to *boundaries*, ticks and grid lines are drawn half a category", + "to the left/bottom of labels." + ].join(" ") + }, + ticklabelmode: { + valType: "enumerated", + values: ["instant", "period"], + dflt: "instant", + editType: "ticks", + description: [ + "Determines where tick labels are drawn with respect to their", + "corresponding ticks and grid lines.", + "Only has an effect for axes of `type` *date*", + "When set to *period*, tick labels are drawn in the middle of the period", + "between ticks." + ].join(" ") + }, + // ticklabelposition: not used directly, as values depend on direction (similar to side) + // left/right options are for x axes, and top/bottom options are for y axes + ticklabelposition: { + valType: "enumerated", + values: [ + "outside", + "inside", + "outside top", + "inside top", + "outside left", + "inside left", + "outside right", + "inside right", + "outside bottom", + "inside bottom" + ], + dflt: "outside", + editType: "calc", + description: [ + "Determines where tick labels are drawn with respect to the axis", + "Please note that", + "top or bottom has no effect on x axes or when `ticklabelmode` is set to *period*.", + "Similarly", + "left or right has no effect on y axes or when `ticklabelmode` is set to *period*.", + "Has no effect on *multicategory* axes or when `tickson` is set to *boundaries*.", + "When used on axes linked by `matches` or `scaleanchor`,", + "no extra padding for inside labels would be added by autorange,", + "so that the scales could match." + ].join(" ") + }, + ticklabeloverflow: { + valType: "enumerated", + values: [ + "allow", + "hide past div", + "hide past domain" + ], + editType: "calc", + description: [ + "Determines how we handle tick labels that would overflow either the graph div or the domain of the axis.", + "The default value for inside tick labels is *hide past domain*.", + "Otherwise on *category* and *multicategory* axes the default is *allow*.", + "In other cases the default is *hide past div*." + ].join(" ") + }, + ticklabelshift: { + valType: "integer", + dflt: 0, + editType: "ticks", + description: [ + "Shifts the tick labels by the specified number of pixels in parallel to the axis.", + "Positive values move the labels in the positive direction of the axis." + ].join(" ") + }, + ticklabelstandoff: { + valType: "integer", + dflt: 0, + editType: "ticks", + description: [ + "Sets the standoff distance (in px) between the axis tick labels and their default position.", + "A positive `ticklabelstandoff` moves the labels farther away from the plot area", + "if `ticklabelposition` is *outside*, and deeper into the plot area if", + "`ticklabelposition` is *inside*. A negative `ticklabelstandoff` works in the opposite", + "direction, moving outside ticks towards the plot area and inside ticks towards", + "the outside. If the negative value is large enough, inside ticks can even end up", + "outside and vice versa." + ].join(" ") + }, + ticklabelindex: { + // in the future maybe add `extras: ['all', 'minor']` to allow showing labels for all ticks + // or for all minor ticks. + valType: "integer", + arrayOk: true, + editType: "calc", + description: [ + "Only for axes with `type` *date* or *linear*.", + "Instead of drawing the major tick label, draw the label for the minor tick", + "that is n positions away from the major tick. E.g. to always draw the label for the", + "minor tick before each major tick, choose `ticklabelindex` -1. This is useful for date", + "axes with `ticklabelmode` *period* if you want to label the period that ends with each", + "major tick instead of the period that begins there." + ].join(" ") + }, + mirror: { + valType: "enumerated", + values: [true, "ticks", false, "all", "allticks"], + dflt: false, + editType: "ticks+layoutstyle", + description: [ + "Determines if the axis lines or/and ticks are mirrored to", + "the opposite side of the plotting area.", + "If *true*, the axis lines are mirrored.", + "If *ticks*, the axis lines and ticks are mirrored.", + "If *false*, mirroring is disable.", + "If *all*, axis lines are mirrored on all shared-axes subplots.", + "If *allticks*, axis lines and ticks are mirrored", + "on all shared-axes subplots." + ].join(" ") + }, + ticklen: makeTicklen(), + tickwidth: makeTickwidth(), + tickcolor, + showticklabels: { + valType: "boolean", + dflt: true, + editType: "ticks", + description: "Determines whether or not the tick labels are drawn." + }, + labelalias: { + valType: "any", + dflt: false, + editType: "ticks", + description: [ + "Replacement text for specific tick or hover labels.", + "For example using {US: 'USA', CA: 'Canada'} changes US to USA", + "and CA to Canada. The labels we would have shown must match", + "the keys exactly, after adding any tickprefix or ticksuffix.", + "For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash.", + "That means you need to use −1 instead of -1.", + "labelalias can be used with any axis type, and both keys (if needed)", + "and values (if desired) can include html-like tags or MathJax." + ].join(" ") + }, + automargin: { + valType: "flaglist", + flags: ["height", "width", "left", "right", "top", "bottom"], + extras: [true, false], + dflt: false, + editType: "ticks", + description: [ + "Determines whether long tick labels automatically grow the figure", + "margins." + ].join(" ") + }, + showspikes: { + valType: "boolean", + dflt: false, + editType: "modebar", + description: [ + "Determines whether or not spikes (aka droplines) are drawn for this axis.", + "Note: This only takes affect when hovermode = closest" + ].join(" ") + }, + spikecolor: { + valType: "color", + dflt: null, + editType: "none", + description: "Sets the spike color. If undefined, will use the series color" + }, + spikethickness: { + valType: "number", + dflt: 3, + editType: "none", + description: "Sets the width (in px) of the zero line." + }, + spikedash: extendFlat$g({}, dash$4, { dflt: "dash", editType: "none" }), + spikemode: { + valType: "flaglist", + flags: ["toaxis", "across", "marker"], + dflt: "toaxis", + editType: "none", + description: [ + "Determines the drawing mode for the spike line", + "If *toaxis*, the line is drawn from the data point to the axis the ", + "series is plotted on.", + "If *across*, the line is drawn across the entire plot area, and", + "supercedes *toaxis*.", + "If *marker*, then a marker dot is drawn on the axis the series is", + "plotted on" + ].join(" ") + }, + spikesnap: { + valType: "enumerated", + values: ["data", "cursor", "hovered data"], + dflt: "hovered data", + editType: "none", + description: "Determines whether spikelines are stuck to the cursor or to the closest datapoints." + }, + tickfont: fontAttrs$c({ + editType: "ticks", + description: "Sets the tick font." + }), + tickangle: { + valType: "angle", + dflt: "auto", + editType: "ticks", + description: [ + "Sets the angle of the tick labels with respect to the horizontal.", + "For example, a `tickangle` of -90 draws the tick labels", + "vertically." + ].join(" ") + }, + autotickangles: { + valType: "info_array", + freeLength: true, + items: { + valType: "angle" + }, + dflt: [0, 30, 90], + editType: "ticks", + description: [ + "When `tickangle` is set to *auto*, it will be set to the first", + "angle in this array that is large enough to prevent label", + "overlap." + ].join(" ") + }, + tickprefix: { + valType: "string", + dflt: "", + editType: "ticks", + description: "Sets a tick label prefix." + }, + showtickprefix: { + valType: "enumerated", + values: ["all", "first", "last", "none"], + dflt: "all", + editType: "ticks", + description: [ + "If *all*, all tick labels are displayed with a prefix.", + "If *first*, only the first tick is displayed with a prefix.", + "If *last*, only the last tick is displayed with a suffix.", + "If *none*, tick prefixes are hidden." + ].join(" ") + }, + ticksuffix: { + valType: "string", + dflt: "", + editType: "ticks", + description: "Sets a tick label suffix." + }, + showticksuffix: { + valType: "enumerated", + values: ["all", "first", "last", "none"], + dflt: "all", + editType: "ticks", + description: "Same as `showtickprefix` but for tick suffixes." + }, + showexponent: { + valType: "enumerated", + values: ["all", "first", "last", "none"], + dflt: "all", + editType: "ticks", + description: [ + "If *all*, all exponents are shown besides their significands.", + "If *first*, only the exponent of the first tick is shown.", + "If *last*, only the exponent of the last tick is shown.", + "If *none*, no exponents appear." + ].join(" ") + }, + exponentformat: { + valType: "enumerated", + values: ["none", "e", "E", "power", "SI", "B"], + dflt: "B", + editType: "ticks", + description: [ + "Determines a formatting rule for the tick exponents.", + "For example, consider the number 1,000,000,000.", + "If *none*, it appears as 1,000,000,000.", + "If *e*, 1e+9.", + "If *E*, 1E+9.", + "If *power*, 1x10^9 (with 9 in a super script).", + "If *SI*, 1G.", + "If *B*, 1B." + ].join(" ") + }, + minexponent: { + valType: "number", + dflt: 3, + min: 0, + editType: "ticks", + description: [ + "Hide SI prefix for 10^n if |n| is below this number.", + "This only has an effect when `tickformat` is *SI* or *B*." + ].join(" ") + }, + separatethousands: { + valType: "boolean", + dflt: false, + editType: "ticks", + description: [ + 'If "true", even 4-digit integers are separated' + ].join(" ") + }, + tickformat: { + valType: "string", + dflt: "", + editType: "ticks", + description: descriptionWithDates("tick label") + }, + tickformatstops: templatedArray$8("tickformatstop", { + enabled: { + valType: "boolean", + dflt: true, + editType: "ticks", + description: [ + "Determines whether or not this stop is used.", + "If `false`, this stop is ignored even within its `dtickrange`." + ].join(" ") + }, + dtickrange: { + valType: "info_array", + items: [ + { valType: "any", editType: "ticks" }, + { valType: "any", editType: "ticks" } + ], + editType: "ticks", + description: [ + "range [*min*, *max*], where *min*, *max* - dtick values", + "which describe some zoom level, it is possible to omit *min*", + "or *max* value by passing *null*" + ].join(" ") + }, + value: { + valType: "string", + dflt: "", + editType: "ticks", + description: [ + "string - dtickformat for described zoom level, the same as *tickformat*" + ].join(" ") + }, + editType: "ticks" + }), + hoverformat: { + valType: "string", + dflt: "", + editType: "none", + description: descriptionWithDates("hover text") + }, + // lines and grids + showline: { + valType: "boolean", + dflt: false, + editType: "ticks+layoutstyle", + description: [ + "Determines whether or not a line bounding this axis is drawn." + ].join(" ") + }, + linecolor: { + valType: "color", + dflt: colorAttrs$5.defaultLine, + editType: "layoutstyle", + description: "Sets the axis line color." + }, + linewidth: { + valType: "number", + min: 0, + dflt: 1, + editType: "ticks+layoutstyle", + description: "Sets the width (in px) of the axis line." + }, + showgrid, + gridcolor, + gridwidth: makeGridwidth(), + griddash, + zeroline: { + valType: "boolean", + editType: "ticks", + description: [ + "Determines whether or not a line is drawn at along the 0 value", + "of this axis.", + "If *true*, the zero line is drawn on top of the grid lines." + ].join(" ") + }, + zerolinecolor: { + valType: "color", + dflt: colorAttrs$5.defaultLine, + editType: "ticks", + description: "Sets the line color of the zero line." + }, + zerolinewidth: { + valType: "number", + dflt: 1, + editType: "ticks", + description: "Sets the width (in px) of the zero line." + }, + showdividers: { + valType: "boolean", + dflt: true, + editType: "ticks", + description: [ + "Determines whether or not a dividers are drawn", + "between the category levels of this axis.", + "Only has an effect on *multicategory* axes." + ].join(" ") + }, + dividercolor: { + valType: "color", + dflt: colorAttrs$5.defaultLine, + editType: "ticks", + description: [ + "Sets the color of the dividers", + "Only has an effect on *multicategory* axes." + ].join(" ") + }, + dividerwidth: { + valType: "number", + dflt: 1, + editType: "ticks", + description: [ + "Sets the width (in px) of the dividers", + "Only has an effect on *multicategory* axes." + ].join(" ") + }, + // TODO dividerlen: that would override "to label base" length? + // positioning attributes + // anchor: not used directly, just put here for reference + // values are any opposite-letter axis id + anchor: { + valType: "enumerated", + values: [ + "free", + constants$T.idRegex.x.toString(), + constants$T.idRegex.y.toString() + ], + editType: "plot", + description: [ + "If set to an opposite-letter axis id (e.g. `x2`, `y`), this axis is bound to", + "the corresponding opposite-letter axis.", + "If set to *free*, this axis' position is determined by `position`." + ].join(" ") + }, + // side: not used directly, as values depend on direction + // values are top, bottom for x axes, and left, right for y + side: { + valType: "enumerated", + values: ["top", "bottom", "left", "right"], + editType: "plot", + description: [ + "Determines whether a x (y) axis is positioned", + "at the *bottom* (*left*) or *top* (*right*)", + "of the plotting area." + ].join(" ") + }, + // overlaying: not used directly, just put here for reference + // values are false and any other same-letter axis id that's not + // itself overlaying anything + overlaying: { + valType: "enumerated", + values: [ + "free", + constants$T.idRegex.x.toString(), + constants$T.idRegex.y.toString() + ], + editType: "plot", + description: [ + "If set a same-letter axis id, this axis is overlaid on top of", + "the corresponding same-letter axis, with traces and axes visible for both", + "axes.", + "If *false*, this axis does not overlay any same-letter axes.", + "In this case, for axes with overlapping domains only the highest-numbered", + "axis will be visible." + ].join(" ") + }, + minor: { + tickmode: minorTickmode, + nticks: makeNticks("minor"), + tick0, + dtick, + tickvals, + ticks, + ticklen: makeTicklen("minor"), + tickwidth: makeTickwidth("minor"), + tickcolor, + gridcolor, + gridwidth: makeGridwidth("minor"), + griddash, + showgrid, + editType: "ticks" + }, + layer: { + valType: "enumerated", + values: ["above traces", "below traces"], + dflt: "above traces", + editType: "plot", + description: [ + "Sets the layer on which this axis is displayed.", + "If *above traces*, this axis is displayed above all the subplot's traces", + "If *below traces*, this axis is displayed below all the subplot's traces,", + "but above the grid lines.", + "Useful when used together with scatter-like traces with `cliponaxis`", + "set to *false* to show markers and/or text nodes above this axis." + ].join(" ") + }, + domain: { + valType: "info_array", + items: [ + { valType: "number", min: 0, max: 1, editType: "plot" }, + { valType: "number", min: 0, max: 1, editType: "plot" } + ], + dflt: [0, 1], + editType: "plot", + description: [ + "Sets the domain of this axis (in plot fraction)." + ].join(" ") + }, + position: { + valType: "number", + min: 0, + max: 1, + dflt: 0, + editType: "plot", + description: [ + "Sets the position of this axis in the plotting space", + "(in normalized coordinates).", + "Only has an effect if `anchor` is set to *free*." + ].join(" ") + }, + autoshift: { + valType: "boolean", + dflt: false, + editType: "plot", + description: [ + "Automatically reposition the axis to avoid", + "overlap with other axes with the same `overlaying` value.", + "This repositioning will account for any `shift` amount applied to other", + "axes on the same side with `autoshift` is set to true.", + "Only has an effect if `anchor` is set to *free*." + ].join(" ") + }, + shift: { + valType: "number", + editType: "plot", + description: [ + "Moves the axis a given number of pixels from where it would have been otherwise.", + "Accepts both positive and negative values, which will shift the axis either right", + "or left, respectively.", + "If `autoshift` is set to true, then this defaults to a padding of -3 if `side` is set to *left*.", + "and defaults to +3 if `side` is set to *right*. Defaults to 0 if `autoshift` is set to false.", + "Only has an effect if `anchor` is set to *free*." + ].join(" ") + }, + categoryorder: { + valType: "enumerated", + values: [ + "trace", + "category ascending", + "category descending", + "array", + "total ascending", + "total descending", + "min ascending", + "min descending", + "max ascending", + "max descending", + "sum ascending", + "sum descending", + "mean ascending", + "mean descending", + "geometric mean ascending", + "geometric mean descending", + "median ascending", + "median descending" + ], + dflt: "trace", + editType: "calc", + description: [ + "Specifies the ordering logic for the case of categorical variables.", + "By default, plotly uses *trace*, which specifies the order that is present in the data supplied.", + "Set `categoryorder` to *category ascending* or *category descending* if order should be determined by", + "the alphanumerical order of the category names.", + "Set `categoryorder` to *array* to derive the ordering from the attribute `categoryarray`. If a category", + "is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to", + "the *trace* mode. The unspecified categories will follow the categories in `categoryarray`.", + "Set `categoryorder` to *total ascending* or *total descending* if order should be determined by the", + "numerical order of the values.", + "Similarly, the order can be determined by the min, max, sum, mean, geometric mean or median of all the values." + ].join(" ") + }, + categoryarray: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the order in which categories on this axis appear.", + "Only has an effect if `categoryorder` is set to *array*.", + "Used with `categoryorder`." + ].join(" ") + }, + uirevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of user-driven changes in axis `range`,", + "`autorange`, and `title` if in `editable: true` configuration.", + "Defaults to `layout.uirevision`." + ].join(" ") + }, + editType: "calc", + _deprecated: { + autotick: { + valType: "boolean", + editType: "ticks", + description: [ + "Obsolete.", + "Set `tickmode` to *auto* for old `autotick` *true* behavior.", + "Set `tickmode` to *linear* for `autotick` *false*." + ].join(" ") + }, + title: { + valType: "string", + editType: "ticks", + description: [ + "Value of `title` is no longer a simple *string* but a set of sub-attributes.", + "To set the axis' title, please use `title.text` now." + ].join(" ") + }, + titlefont: fontAttrs$c({ + editType: "ticks", + description: [ + "Former `titlefont` is now the sub-attribute `font` of `title`.", + "To customize title font properties, please use `title.font` now." + ].join(" ") + }) + } +}; +var axesAttrs = layout_attributes$4; +var fontAttrs$b = font_attributes; +var extendFlat$f = extend$5.extendFlat; +var overrideAll$6 = edit_types.overrideAll; +var attributes$J = overrideAll$6({ + orientation: { + valType: "enumerated", + values: ["h", "v"], + dflt: "v", + description: "Sets the orientation of the colorbar." + }, + thicknessmode: { + valType: "enumerated", + values: ["fraction", "pixels"], + dflt: "pixels", + description: [ + "Determines whether this color bar's thickness", + "(i.e. the measure in the constant color direction)", + "is set in units of plot *fraction* or in *pixels*.", + "Use `thickness` to set the value." + ].join(" ") + }, + thickness: { + valType: "number", + min: 0, + dflt: 30, + description: [ + "Sets the thickness of the color bar", + "This measure excludes the size of the padding, ticks and labels." + ].join(" ") + }, + lenmode: { + valType: "enumerated", + values: ["fraction", "pixels"], + dflt: "fraction", + description: [ + "Determines whether this color bar's length", + "(i.e. the measure in the color variation direction)", + "is set in units of plot *fraction* or in *pixels.", + "Use `len` to set the value." + ].join(" ") + }, + len: { + valType: "number", + min: 0, + dflt: 1, + description: [ + "Sets the length of the color bar", + "This measure excludes the padding of both ends.", + "That is, the color bar length is this length minus the", + "padding on both ends." + ].join(" ") + }, + x: { + valType: "number", + description: [ + "Sets the x position with respect to `xref` of the color bar (in plot fraction).", + "When `xref` is *paper*, defaults to 1.02 when `orientation` is *v* and", + "0.5 when `orientation` is *h*.", + "When `xref` is *container*, defaults to *1* when `orientation` is *v* and", + "0.5 when `orientation` is *h*.", + "Must be between *0* and *1* if `xref` is *container*", + "and between *-2* and *3* if `xref` is *paper*." + ].join(" ") + }, + xref: { + valType: "enumerated", + dflt: "paper", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `x` refers to.", + "*container* spans the entire `width` of the plot.", + "*paper* refers to the width of the plotting area only." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["left", "center", "right"], + description: [ + "Sets this color bar's horizontal position anchor.", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the color bar.", + "Defaults to *left* when `orientation` is *v* and", + "*center* when `orientation` is *h*." + ].join(" ") + }, + xpad: { + valType: "number", + min: 0, + dflt: 10, + description: "Sets the amount of padding (in px) along the x direction." + }, + y: { + valType: "number", + description: [ + "Sets the y position with respect to `yref` of the color bar (in plot fraction).", + "When `yref` is *paper*, defaults to 0.5 when `orientation` is *v* and", + "1.02 when `orientation` is *h*.", + "When `yref` is *container*, defaults to 0.5 when `orientation` is *v* and", + "1 when `orientation` is *h*.", + "Must be between *0* and *1* if `yref` is *container*", + "and between *-2* and *3* if `yref` is *paper*." + ].join(" ") + }, + yref: { + valType: "enumerated", + dflt: "paper", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `y` refers to.", + "*container* spans the entire `height` of the plot.", + "*paper* refers to the height of the plotting area only." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + description: [ + "Sets this color bar's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the color bar.", + "Defaults to *middle* when `orientation` is *v* and", + "*bottom* when `orientation` is *h*." + ].join(" ") + }, + ypad: { + valType: "number", + min: 0, + dflt: 10, + description: "Sets the amount of padding (in px) along the y direction." + }, + // a possible line around the bar itself + outlinecolor: axesAttrs.linecolor, + outlinewidth: axesAttrs.linewidth, + // Should outlinewidth have {dflt: 0} ? + // another possible line outside the padding and tick labels + bordercolor: axesAttrs.linecolor, + borderwidth: { + valType: "number", + min: 0, + dflt: 0, + description: [ + "Sets the width (in px) or the border enclosing this color bar." + ].join(" ") + }, + bgcolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + description: "Sets the color of padded area." + }, + // tick and title properties named and function exactly as in axes + tickmode: axesAttrs.minor.tickmode, + nticks: axesAttrs.nticks, + tick0: axesAttrs.tick0, + dtick: axesAttrs.dtick, + tickvals: axesAttrs.tickvals, + ticktext: axesAttrs.ticktext, + ticks: extendFlat$f({}, axesAttrs.ticks, { dflt: "" }), + ticklabeloverflow: extendFlat$f({}, axesAttrs.ticklabeloverflow, { + description: [ + "Determines how we handle tick labels that would overflow either the graph div or the domain of the axis.", + "The default value for inside tick labels is *hide past domain*.", + "In other cases the default is *hide past div*." + ].join(" ") + }), + // ticklabelposition: not used directly, as values depend on orientation + // left/right options are for x axes, and top/bottom options are for y axes + ticklabelposition: { + valType: "enumerated", + values: [ + "outside", + "inside", + "outside top", + "inside top", + "outside left", + "inside left", + "outside right", + "inside right", + "outside bottom", + "inside bottom" + ], + dflt: "outside", + description: [ + "Determines where tick labels are drawn relative to the ticks.", + "Left and right options are used when `orientation` is *h*,", + "top and bottom when `orientation` is *v*." + ].join(" ") + }, + ticklen: axesAttrs.ticklen, + tickwidth: axesAttrs.tickwidth, + tickcolor: axesAttrs.tickcolor, + ticklabelstep: axesAttrs.ticklabelstep, + showticklabels: axesAttrs.showticklabels, + labelalias: axesAttrs.labelalias, + tickfont: fontAttrs$b({ + description: "Sets the color bar's tick label font" + }), + tickangle: axesAttrs.tickangle, + tickformat: axesAttrs.tickformat, + tickformatstops: axesAttrs.tickformatstops, + tickprefix: axesAttrs.tickprefix, + showtickprefix: axesAttrs.showtickprefix, + ticksuffix: axesAttrs.ticksuffix, + showticksuffix: axesAttrs.showticksuffix, + separatethousands: axesAttrs.separatethousands, + exponentformat: axesAttrs.exponentformat, + minexponent: axesAttrs.minexponent, + showexponent: axesAttrs.showexponent, + title: { + text: { + valType: "string", + description: [ + "Sets the title of the color bar.", + "Note that before the existence of `title.text`, the title's", + "contents used to be defined as the `title` attribute itself.", + "This behavior has been deprecated." + ].join(" ") + }, + font: fontAttrs$b({ + description: [ + "Sets this color bar's title font.", + "Note that the title's font used to be set", + "by the now deprecated `titlefont` attribute." + ].join(" ") + }), + side: { + valType: "enumerated", + values: ["right", "top", "bottom"], + description: [ + "Determines the location of color bar's title", + "with respect to the color bar.", + "Defaults to *top* when `orientation` if *v* and ", + "defaults to *right* when `orientation` if *h*.", + "Note that the title's location used to be set", + "by the now deprecated `titleside` attribute." + ].join(" ") + } + }, + _deprecated: { + title: { + valType: "string", + description: [ + "Deprecated in favor of color bar's `title.text`.", + "Note that value of color bar's `title` is no longer a simple", + "*string* but a set of sub-attributes." + ].join(" ") + }, + titlefont: fontAttrs$b({ + description: "Deprecated in favor of color bar's `title.font`." + }), + titleside: { + valType: "enumerated", + values: ["right", "top", "bottom"], + dflt: "top", + description: "Deprecated in favor of color bar's `title.side`." + } + } +}, "colorbars", "from-root"); +var colorbarAttrs = attributes$J; +var counterRegex$1 = regex.counter; +var sortObjectKeys$1 = sort_object_keys; +var palettes = scales_1.scales; +var paletteStr = sortObjectKeys$1(palettes); +function code$1(s) { + return "`" + s + "`"; +} +var attributes$I = function colorScaleAttrs(context2, opts) { + context2 = context2 || ""; + opts = opts || {}; + var cLetter = opts.cLetter || "c"; + var onlyIfNumerical = "onlyIfNumerical" in opts ? opts.onlyIfNumerical : Boolean(context2); + var noScale = "noScale" in opts ? opts.noScale : context2 === "marker.line"; + var showScaleDflt = "showScaleDflt" in opts ? opts.showScaleDflt : cLetter === "z"; + var colorscaleDflt = typeof opts.colorscaleDflt === "string" ? palettes[opts.colorscaleDflt] : null; + var editTypeOverride = opts.editTypeOverride || ""; + var contextHead = context2 ? context2 + "." : ""; + var colorAttr, colorAttrFull; + if ("colorAttr" in opts) { + colorAttr = opts.colorAttr; + colorAttrFull = opts.colorAttr; + } else { + colorAttr = { z: "z", c: "color" }[cLetter]; + colorAttrFull = "in " + code$1(contextHead + colorAttr); + } + var effectDesc = onlyIfNumerical ? " Has an effect only if " + colorAttrFull + " is set to a numerical array." : ""; + var auto = cLetter + "auto"; + var min = cLetter + "min"; + var max = cLetter + "max"; + var mid = cLetter + "mid"; + var autoFull = code$1(contextHead + auto); + var minFull = code$1(contextHead + min); + var maxFull = code$1(contextHead + max); + var minmaxFull = minFull + " and " + maxFull; + var autoImpliedEdits = {}; + autoImpliedEdits[min] = autoImpliedEdits[max] = void 0; + var minmaxImpliedEdits = {}; + minmaxImpliedEdits[auto] = false; + var attrs2 = {}; + if (colorAttr === "color") { + attrs2.color = { + valType: "color", + arrayOk: true, + editType: editTypeOverride || "style", + description: [ + "Sets the", + context2, + "color.", + "It accepts either a specific color", + "or an array of numbers that are mapped to the colorscale", + "relative to the max and min values of the array or relative to", + minmaxFull, + "if set." + ].join(" ") + }; + if (opts.anim) { + attrs2.color.anim = true; + } + } + attrs2[auto] = { + valType: "boolean", + dflt: true, + editType: "calc", + impliedEdits: autoImpliedEdits, + description: [ + "Determines whether or not the color domain is computed", + "with respect to the input data (here " + colorAttrFull + ") or the bounds set in", + minmaxFull + effectDesc, + "Defaults to `false` when", + minmaxFull, + "are set by the user." + ].join(" ") + }; + attrs2[min] = { + valType: "number", + dflt: null, + editType: editTypeOverride || "plot", + impliedEdits: minmaxImpliedEdits, + description: [ + "Sets the lower bound of the color domain." + effectDesc, + "Value should have the same units as", + colorAttrFull, + "and if set,", + maxFull, + "must be set as well." + ].join(" ") + }; + attrs2[max] = { + valType: "number", + dflt: null, + editType: editTypeOverride || "plot", + impliedEdits: minmaxImpliedEdits, + description: [ + "Sets the upper bound of the color domain." + effectDesc, + "Value should have the same units as", + colorAttrFull, + "and if set,", + minFull, + "must be set as well." + ].join(" ") + }; + attrs2[mid] = { + valType: "number", + dflt: null, + editType: "calc", + impliedEdits: autoImpliedEdits, + description: [ + "Sets the mid-point of the color domain by scaling", + minFull, + "and/or", + maxFull, + "to be equidistant to this point." + effectDesc, + "Value should have the same units as", + colorAttrFull + ".", + "Has no effect when", + autoFull, + "is `false`." + ].join(" ") + }; + attrs2.colorscale = { + valType: "colorscale", + editType: "calc", + dflt: colorscaleDflt, + impliedEdits: { autocolorscale: false }, + description: [ + "Sets the colorscale." + effectDesc, + "The colorscale must be an array containing", + "arrays mapping a normalized value to an", + "rgb, rgba, hex, hsl, hsv, or named color string.", + "At minimum, a mapping for the lowest (0) and highest (1)", + "values are required. For example,", + "`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.", + "To control the bounds of the colorscale in color space,", + "use", + minmaxFull + ".", + "Alternatively, `colorscale` may be a palette name string", + "of the following list: " + paletteStr + "." + ].join(" ") + }; + attrs2.autocolorscale = { + valType: "boolean", + // gets overrode in 'heatmap' & 'surface' for backwards comp. + dflt: opts.autoColorDflt === false ? false : true, + editType: "calc", + impliedEdits: { colorscale: void 0 }, + description: [ + "Determines whether the colorscale is a default palette (`autocolorscale: true`)", + "or the palette determined by", + code$1(contextHead + "colorscale") + "." + effectDesc, + "In case `colorscale` is unspecified or `autocolorscale` is true, the default", + "palette will be chosen according to whether numbers in the `color` array are", + "all positive, all negative or mixed." + ].join(" ") + }; + attrs2.reversescale = { + valType: "boolean", + dflt: false, + editType: "plot", + description: [ + "Reverses the color mapping if true." + effectDesc, + "If true,", + minFull, + "will correspond to the last color", + "in the array and", + maxFull, + "will correspond to the first color." + ].join(" ") + }; + if (!noScale) { + attrs2.showscale = { + valType: "boolean", + dflt: showScaleDflt, + editType: "calc", + description: [ + "Determines whether or not a colorbar is displayed for this trace." + effectDesc + ].join(" ") + }; + attrs2.colorbar = colorbarAttrs; + } + if (!opts.noColorAxis) { + attrs2.coloraxis = { + valType: "subplotid", + regex: counterRegex$1("coloraxis"), + dflt: null, + editType: "calc", + description: [ + "Sets a reference to a shared color axis.", + "References to these shared color axes are *coloraxis*, *coloraxis2*, *coloraxis3*, etc.", + "Settings for these shared color axes are set in the layout, under", + "`layout.coloraxis`, `layout.coloraxis2`, etc.", + "Note that multiple color scales can be linked to the same color axis." + ].join(" ") + }; + } + return attrs2; +}; +var extendFlat$e = extend$5.extendFlat; +var colorScaleAttrs$6 = attributes$I; +var scales$1 = scales_1.scales; +var msg = "Note that `autocolorscale` must be true for this attribute to work."; +var layout_attributes$3 = { + editType: "calc", + colorscale: { + editType: "calc", + sequential: { + valType: "colorscale", + dflt: scales$1.Reds, + editType: "calc", + description: [ + "Sets the default sequential colorscale for positive values.", + msg + ].join(" ") + }, + sequentialminus: { + valType: "colorscale", + dflt: scales$1.Blues, + editType: "calc", + description: [ + "Sets the default sequential colorscale for negative values.", + msg + ].join(" ") + }, + diverging: { + valType: "colorscale", + dflt: scales$1.RdBu, + editType: "calc", + description: [ + "Sets the default diverging colorscale.", + msg + ].join(" ") + } + }, + coloraxis: extendFlat$e({ + // not really a 'subplot' attribute container, + // but this is the flag we use to denote attributes that + // support yaxis, yaxis2, yaxis3, ... counters + _isSubplotObj: true, + editType: "calc", + description: [ + "" + ].join(" ") + }, colorScaleAttrs$6("", { + colorAttr: "corresponding trace color array(s)", + noColorAxis: true, + showScaleDflt: true + })) +}; +var Lib$1U = libExports; +var has_colorbar = function hasColorbar(container) { + return Lib$1U.isPlainObject(container.colorbar); +}; +var clean_ticks = {}; +var isNumeric$s = fastIsnumeric; +var Lib$1T = libExports; +var constants$S = numerical; +var ONEDAY$2 = constants$S.ONEDAY; +var ONEWEEK$3 = constants$S.ONEWEEK; +clean_ticks.dtick = function(dtick2, axType) { + var isLog = axType === "log"; + var isDate = axType === "date"; + var isCat = axType === "category"; + var dtickDflt = isDate ? ONEDAY$2 : 1; + if (!dtick2) return dtickDflt; + if (isNumeric$s(dtick2)) { + dtick2 = Number(dtick2); + if (dtick2 <= 0) return dtickDflt; + if (isCat) { + return Math.max(1, Math.round(dtick2)); + } + if (isDate) { + return Math.max(0.1, dtick2); + } + return dtick2; + } + if (typeof dtick2 !== "string" || !(isDate || isLog)) { + return dtickDflt; + } + var prefix = dtick2.charAt(0); + var dtickNum = dtick2.substr(1); + dtickNum = isNumeric$s(dtickNum) ? Number(dtickNum) : 0; + if (dtickNum <= 0 || !// "M" gives ticks every (integer) n months + (isDate && prefix === "M" && dtickNum === Math.round(dtickNum) || // "L" gives ticks linearly spaced in data (not in position) every (float) f + isLog && prefix === "L" || // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 + isLog && prefix === "D" && (dtickNum === 1 || dtickNum === 2))) { + return dtickDflt; + } + return dtick2; +}; +clean_ticks.tick0 = function(tick02, axType, calendar, dtick2) { + if (axType === "date") { + return Lib$1T.cleanDate( + tick02, + Lib$1T.dateTick0(calendar, dtick2 % ONEWEEK$3 === 0 ? 1 : 0) + ); + } + if (dtick2 === "D1" || dtick2 === "D2") { + return void 0; + } + return isNumeric$s(tick02) ? Number(tick02) : 0; +}; +var cleanTicks$1 = clean_ticks; +var isArrayOrTypedArray$9 = libExports.isArrayOrTypedArray; +var isTypedArraySpec$2 = array$2.isTypedArraySpec; +var decodeTypedArraySpec = array$2.decodeTypedArraySpec; +var tick_value_defaults = function handleTickValueDefaults(containerIn, containerOut, coerce2, axType, opts) { + if (!opts) opts = {}; + var isMinor = opts.isMinor; + var cIn = isMinor ? containerIn.minor || {} : containerIn; + var cOut = isMinor ? containerOut.minor : containerOut; + var prefix = isMinor ? "minor." : ""; + function readInput(attr) { + var v = cIn[attr]; + if (isTypedArraySpec$2(v)) v = decodeTypedArraySpec(v); + return v !== void 0 ? v : (cOut._template || {})[attr]; + } + var _tick0 = readInput("tick0"); + var _dtick = readInput("dtick"); + var _tickvals = readInput("tickvals"); + var tickmodeDefault = isArrayOrTypedArray$9(_tickvals) ? "array" : _dtick ? "linear" : "auto"; + var tickmode2 = coerce2(prefix + "tickmode", tickmodeDefault); + if (tickmode2 === "auto" || tickmode2 === "sync") { + coerce2(prefix + "nticks"); + } else if (tickmode2 === "linear") { + var dtick2 = cOut.dtick = cleanTicks$1.dtick( + _dtick, + axType + ); + cOut.tick0 = cleanTicks$1.tick0( + _tick0, + axType, + containerOut.calendar, + dtick2 + ); + } else if (axType !== "multicategory") { + var tickvals2 = coerce2(prefix + "tickvals"); + if (tickvals2 === void 0) cOut.tickmode = "auto"; + else if (!isMinor) coerce2("ticktext"); + } +}; +var Lib$1S = libExports; +var layoutAttributes$b = layout_attributes$4; +var tick_mark_defaults = function handleTickMarkDefaults(containerIn, containerOut, coerce2, options) { + var isMinor = options.isMinor; + var cIn = isMinor ? containerIn.minor || {} : containerIn; + var cOut = isMinor ? containerOut.minor : containerOut; + var lAttr = isMinor ? layoutAttributes$b.minor : layoutAttributes$b; + var prefix = isMinor ? "minor." : ""; + var tickLen = Lib$1S.coerce2(cIn, cOut, lAttr, "ticklen", isMinor ? (containerOut.ticklen || 5) * 0.6 : void 0); + var tickWidth = Lib$1S.coerce2(cIn, cOut, lAttr, "tickwidth", isMinor ? containerOut.tickwidth || 1 : void 0); + var tickColor = Lib$1S.coerce2(cIn, cOut, lAttr, "tickcolor", (isMinor ? containerOut.tickcolor : void 0) || cOut.color); + var showTicks = coerce2(prefix + "ticks", !isMinor && options.outerTicks || tickLen || tickWidth || tickColor ? "outside" : ""); + if (!showTicks) { + delete cOut.ticklen; + delete cOut.tickwidth; + delete cOut.tickcolor; + } +}; +var show_dflt = function getShowAttrDflt(containerIn) { + var showAttrsAll = ["showexponent", "showtickprefix", "showticksuffix"]; + var showAttrs = showAttrsAll.filter(function(a) { + return containerIn[a] !== void 0; + }); + var sameVal = function(a) { + return containerIn[a] === containerIn[showAttrs[0]]; + }; + if (showAttrs.every(sameVal) || showAttrs.length === 1) { + return containerIn[showAttrs[0]]; + } +}; +var Lib$1R = libExports; +var Template$8 = plot_template; +var array_container_defaults = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { + var name2 = opts.name; + var inclusionAttr = opts.inclusionAttr || "visible"; + var previousContOut = parentObjOut[name2]; + var contIn = Lib$1R.isArrayOrTypedArray(parentObjIn[name2]) ? parentObjIn[name2] : []; + var contOut = parentObjOut[name2] = []; + var templater = Template$8.arrayTemplater(parentObjOut, name2, inclusionAttr); + var i, itemOut; + for (i = 0; i < contIn.length; i++) { + var itemIn = contIn[i]; + if (!Lib$1R.isPlainObject(itemIn)) { + itemOut = templater.newItem({}); + itemOut[inclusionAttr] = false; + } else { + itemOut = templater.newItem(itemIn); + } + itemOut._index = i; + if (itemOut[inclusionAttr] !== false) { + opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts); + } + contOut.push(itemOut); + } + var defaultItems = templater.defaultItems(); + for (i = 0; i < defaultItems.length; i++) { + itemOut = defaultItems[i]; + itemOut._index = contOut.length; + opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {}); + contOut.push(itemOut); + } + if (Lib$1R.isArrayOrTypedArray(previousContOut)) { + var len = Math.min(previousContOut.length, contOut.length); + for (i = 0; i < len; i++) { + Lib$1R.relinkPrivateKeys(contOut[i], previousContOut[i]); + } + } + return contOut; +}; +var Lib$1Q = libExports; +var contrast = colorExports.contrast; +var layoutAttributes$a = layout_attributes$4; +var getShowAttrDflt$1 = show_dflt; +var handleArrayContainerDefaults$9 = array_container_defaults; +var tick_label_defaults = function handleTickLabelDefaults(containerIn, containerOut, coerce2, axType, options) { + if (!options) options = {}; + var labelalias = coerce2("labelalias"); + if (!Lib$1Q.isPlainObject(labelalias)) delete containerOut.labelalias; + var showAttrDflt = getShowAttrDflt$1(containerIn); + var showTickLabels = coerce2("showticklabels"); + if (showTickLabels) { + if (!options.noTicklabelshift) { + coerce2("ticklabelshift"); + } + if (!options.noTicklabelstandoff) { + coerce2("ticklabelstandoff"); + } + var font2 = options.font || {}; + var contColor = containerOut.color; + var position = containerOut.ticklabelposition || ""; + var dfltFontColor = position.indexOf("inside") !== -1 ? contrast(options.bgColor) : ( + // as with titlefont.color, inherit axis.color only if one was + // explicitly provided + contColor && contColor !== layoutAttributes$a.color.dflt ? contColor : font2.color + ); + Lib$1Q.coerceFont(coerce2, "tickfont", font2, { overrideDflt: { + color: dfltFontColor + } }); + if (!options.noTicklabelstep && axType !== "multicategory" && axType !== "log") { + coerce2("ticklabelstep"); + } + if (!options.noAng) { + var tickAngle = coerce2("tickangle"); + if (!options.noAutotickangles && tickAngle === "auto") { + coerce2("autotickangles"); + } + } + if (axType !== "category") { + var tickFormat = coerce2("tickformat"); + handleArrayContainerDefaults$9(containerIn, containerOut, { + name: "tickformatstops", + inclusionAttr: "enabled", + handleItemDefaults: tickformatstopDefaults + }); + if (!containerOut.tickformatstops.length) { + delete containerOut.tickformatstops; + } + if (!options.noExp && !tickFormat && axType !== "date") { + coerce2("showexponent", showAttrDflt); + coerce2("exponentformat"); + coerce2("minexponent"); + coerce2("separatethousands"); + } + } + } +}; +function tickformatstopDefaults(valueIn, valueOut) { + function coerce2(attr, dflt) { + return Lib$1Q.coerce(valueIn, valueOut, layoutAttributes$a.tickformatstops, attr, dflt); + } + var enabled = coerce2("enabled"); + if (enabled) { + coerce2("dtickrange"); + coerce2("value"); + } +} +var getShowAttrDflt2 = show_dflt; +var prefix_suffix_defaults = function handlePrefixSuffixDefaults(containerIn, containerOut, coerce2, axType, options) { + if (!options) options = {}; + var tickSuffixDflt = options.tickSuffixDflt; + var showAttrDflt = getShowAttrDflt2(containerIn); + var tickPrefix = coerce2("tickprefix"); + if (tickPrefix) coerce2("showtickprefix", showAttrDflt); + var tickSuffix = coerce2("ticksuffix", tickSuffixDflt); + if (tickSuffix) coerce2("showticksuffix", showAttrDflt); +}; +var Lib$1P = libExports; +var Template$7 = plot_template; +var handleTickValueDefaults$1 = tick_value_defaults; +var handleTickMarkDefaults$1 = tick_mark_defaults; +var handleTickLabelDefaults$1 = tick_label_defaults; +var handlePrefixSuffixDefaults$1 = prefix_suffix_defaults; +var attributes$H = attributes$J; +var defaults$o = function colorbarDefaults(containerIn, containerOut, layout) { + var colorbarOut = Template$7.newContainer(containerOut, "colorbar"); + var colorbarIn = containerIn.colorbar || {}; + function coerce2(attr, dflt) { + return Lib$1P.coerce(colorbarIn, colorbarOut, attributes$H, attr, dflt); + } + var margin = layout.margin || { t: 0, b: 0, l: 0, r: 0 }; + var w = layout.width - margin.l - margin.r; + var h = layout.height - margin.t - margin.b; + var orientation = coerce2("orientation"); + var isVertical2 = orientation === "v"; + var thicknessmode = coerce2("thicknessmode"); + coerce2( + "thickness", + thicknessmode === "fraction" ? 30 / (isVertical2 ? w : h) : 30 + ); + var lenmode = coerce2("lenmode"); + coerce2( + "len", + lenmode === "fraction" ? 1 : isVertical2 ? h : w + ); + var yref = coerce2("yref"); + var xref = coerce2("xref"); + var isPaperY = yref === "paper"; + var isPaperX = xref === "paper"; + var defaultX, defaultY, defaultYAnchor; + var defaultXAnchor = "left"; + if (isVertical2) { + defaultYAnchor = "middle"; + defaultXAnchor = isPaperX ? "left" : "right"; + defaultX = isPaperX ? 1.02 : 1; + defaultY = 0.5; + } else { + defaultYAnchor = isPaperY ? "bottom" : "top"; + defaultXAnchor = "center"; + defaultX = 0.5; + defaultY = isPaperY ? 1.02 : 1; + } + Lib$1P.coerce(colorbarIn, colorbarOut, { + x: { + valType: "number", + min: isPaperX ? -2 : 0, + max: isPaperX ? 3 : 1, + dflt: defaultX + } + }, "x"); + Lib$1P.coerce(colorbarIn, colorbarOut, { + y: { + valType: "number", + min: isPaperY ? -2 : 0, + max: isPaperY ? 3 : 1, + dflt: defaultY + } + }, "y"); + coerce2("xanchor", defaultXAnchor); + coerce2("xpad"); + coerce2("yanchor", defaultYAnchor); + coerce2("ypad"); + Lib$1P.noneOrAll(colorbarIn, colorbarOut, ["x", "y"]); + coerce2("outlinecolor"); + coerce2("outlinewidth"); + coerce2("bordercolor"); + coerce2("borderwidth"); + coerce2("bgcolor"); + var ticklabelposition = Lib$1P.coerce(colorbarIn, colorbarOut, { + ticklabelposition: { + valType: "enumerated", + dflt: "outside", + values: isVertical2 ? [ + "outside", + "inside", + "outside top", + "inside top", + "outside bottom", + "inside bottom" + ] : [ + "outside", + "inside", + "outside left", + "inside left", + "outside right", + "inside right" + ] + } + }, "ticklabelposition"); + coerce2("ticklabeloverflow", ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : "hide past div"); + handleTickValueDefaults$1(colorbarIn, colorbarOut, coerce2, "linear"); + var font2 = layout.font; + var opts = { + noAutotickangles: true, + noTicklabelshift: true, + noTicklabelstandoff: true, + font: font2 + }; + if (ticklabelposition.indexOf("inside") !== -1) { + opts.bgColor = "black"; + } + handlePrefixSuffixDefaults$1(colorbarIn, colorbarOut, coerce2, "linear", opts); + handleTickLabelDefaults$1(colorbarIn, colorbarOut, coerce2, "linear", opts); + handleTickMarkDefaults$1(colorbarIn, colorbarOut, coerce2, "linear"); + coerce2("title.text", layout._dfltTitle.colorbar); + var tickFont = colorbarOut.showticklabels ? colorbarOut.tickfont : font2; + var dfltTitleFont = Lib$1P.extendFlat({}, font2, { + family: tickFont.family, + size: Lib$1P.bigFont(tickFont.size) + }); + Lib$1P.coerceFont(coerce2, "title.font", dfltTitleFont); + coerce2("title.side", isVertical2 ? "top" : "right"); +}; +var isNumeric$r = fastIsnumeric; +var Lib$1O = libExports; +var hasColorbar2 = has_colorbar; +var colorbarDefaults2 = defaults$o; +var isValidScale = scales_1.isValid; +var traceIs$1 = registry.traceIs; +function npMaybe(parentCont, prefix) { + var containerStr = prefix.slice(0, prefix.length - 1); + return prefix ? Lib$1O.nestedProperty(parentCont, containerStr).get() || {} : parentCont; +} +var defaults$n = function colorScaleDefaults(parentContIn, parentContOut, layout, coerce2, opts) { + var prefix = opts.prefix; + var cLetter = opts.cLetter; + var inTrace = "_module" in parentContOut; + var containerIn = npMaybe(parentContIn, prefix); + var containerOut = npMaybe(parentContOut, prefix); + var template = npMaybe(parentContOut._template || {}, prefix) || {}; + var thisFn = function() { + delete parentContIn.coloraxis; + delete parentContOut.coloraxis; + return colorScaleDefaults(parentContIn, parentContOut, layout, coerce2, opts); + }; + if (inTrace) { + var colorAxes = layout._colorAxes || {}; + var colorAx = coerce2(prefix + "coloraxis"); + if (colorAx) { + var colorbarVisuals = traceIs$1(parentContOut, "contour") && Lib$1O.nestedProperty(parentContOut, "contours.coloring").get() || "heatmap"; + var stash = colorAxes[colorAx]; + if (stash) { + stash[2].push(thisFn); + if (stash[0] !== colorbarVisuals) { + stash[0] = false; + Lib$1O.warn([ + "Ignoring coloraxis:", + colorAx, + "setting", + "as it is linked to incompatible colorscales." + ].join(" ")); + } + } else { + colorAxes[colorAx] = [colorbarVisuals, parentContOut, [thisFn]]; + } + return; + } + } + var minIn = containerIn[cLetter + "min"]; + var maxIn = containerIn[cLetter + "max"]; + var validMinMax = isNumeric$r(minIn) && isNumeric$r(maxIn) && minIn < maxIn; + var auto = coerce2(prefix + cLetter + "auto", !validMinMax); + if (auto) { + coerce2(prefix + cLetter + "mid"); + } else { + coerce2(prefix + cLetter + "min"); + coerce2(prefix + cLetter + "max"); + } + var sclIn = containerIn.colorscale; + var sclTemplate = template.colorscale; + var autoColorscaleDflt; + if (sclIn !== void 0) autoColorscaleDflt = !isValidScale(sclIn); + if (sclTemplate !== void 0) autoColorscaleDflt = !isValidScale(sclTemplate); + coerce2(prefix + "autocolorscale", autoColorscaleDflt); + coerce2(prefix + "colorscale"); + coerce2(prefix + "reversescale"); + if (prefix !== "marker.line.") { + var showScaleDflt; + if (prefix && inTrace) showScaleDflt = hasColorbar2(containerIn); + var showScale = coerce2(prefix + "showscale", showScaleDflt); + if (showScale) { + if (prefix && template) containerOut._template = template; + colorbarDefaults2(containerIn, containerOut, layout); + } + } +}; +var Lib$1N = libExports; +var Template$6 = plot_template; +var colorScaleAttrs$5 = layout_attributes$3; +var colorScaleDefaults2 = defaults$n; +var layout_defaults$6 = function supplyLayoutDefaults(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$1N.coerce(layoutIn, layoutOut, colorScaleAttrs$5, attr, dflt); + } + coerce2("colorscale.sequential"); + coerce2("colorscale.sequentialminus"); + coerce2("colorscale.diverging"); + var colorAxes = layoutOut._colorAxes; + var colorAxIn, colorAxOut; + function coerceAx(attr, dflt) { + return Lib$1N.coerce(colorAxIn, colorAxOut, colorScaleAttrs$5.coloraxis, attr, dflt); + } + for (var k in colorAxes) { + var stash = colorAxes[k]; + if (stash[0]) { + colorAxIn = layoutIn[k] || {}; + colorAxOut = Template$6.newContainer(layoutOut, k, "coloraxis"); + colorAxOut._name = k; + colorScaleDefaults2(colorAxIn, colorAxOut, layoutOut, coerceAx, { prefix: "", cLetter: "c" }); + } else { + for (var i = 0; i < stash[2].length; i++) { + stash[2][i](); + } + delete layoutOut._colorAxes[k]; + } + } +}; +var Lib$1M = libExports; +var hasColorscale$6 = helpers$L.hasColorscale; +var extractOpts$2 = helpers$L.extractOpts; +var cross_trace_defaults$2 = function crossTraceDefaults(fullData, fullLayout) { + function replace(cont, k2) { + var val = cont["_" + k2]; + if (val !== void 0) { + cont[k2] = val; + } + } + function relinkColorAttrs(outerCont, cbOpt) { + var cont = cbOpt.container ? Lib$1M.nestedProperty(outerCont, cbOpt.container).get() : outerCont; + if (cont) { + if (cont.coloraxis) { + cont._colorAx = fullLayout[cont.coloraxis]; + } else { + var cOpts = extractOpts$2(cont); + var isAuto = cOpts.auto; + if (isAuto || cOpts.min === void 0) { + replace(cont, cbOpt.min); + } + if (isAuto || cOpts.max === void 0) { + replace(cont, cbOpt.max); + } + if (cOpts.autocolorscale) { + replace(cont, "colorscale"); + } + } + } + } + for (var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + var cbOpts = trace._module.colorbar; + if (cbOpts) { + if (Array.isArray(cbOpts)) { + for (var j = 0; j < cbOpts.length; j++) { + relinkColorAttrs(trace, cbOpts[j]); + } + } else { + relinkColorAttrs(trace, cbOpts); + } + } + if (hasColorscale$6(trace, "marker.line")) { + relinkColorAttrs(trace, { + container: "marker.line", + min: "cmin", + max: "cmax" + }); + } + } + for (var k in fullLayout._colorAxes) { + relinkColorAttrs(fullLayout[k], { min: "cmin", max: "cmax" }); + } +}; +var isNumeric$q = fastIsnumeric; +var Lib$1L = libExports; +var extractOpts$1 = helpers$L.extractOpts; +var calc$c = function calc(gd, trace, opts) { + var fullLayout = gd._fullLayout; + var vals = opts.vals; + var containerStr = opts.containerStr; + var container = containerStr ? Lib$1L.nestedProperty(trace, containerStr).get() : trace; + var cOpts = extractOpts$1(container); + var auto = cOpts.auto !== false; + var min = cOpts.min; + var max = cOpts.max; + var mid = cOpts.mid; + var minVal = function() { + return Lib$1L.aggNums(Math.min, null, vals); + }; + var maxVal = function() { + return Lib$1L.aggNums(Math.max, null, vals); + }; + if (min === void 0) { + min = minVal(); + } else if (auto) { + if (container._colorAx && isNumeric$q(min)) { + min = Math.min(min, minVal()); + } else { + min = minVal(); + } + } + if (max === void 0) { + max = maxVal(); + } else if (auto) { + if (container._colorAx && isNumeric$q(max)) { + max = Math.max(max, maxVal()); + } else { + max = maxVal(); + } + } + if (auto && mid !== void 0) { + if (max - mid > mid - min) { + min = mid - (max - mid); + } else if (max - mid < mid - min) { + max = mid + (mid - min); + } + } + if (min === max) { + min -= 0.5; + max += 0.5; + } + cOpts._sync("min", min); + cOpts._sync("max", max); + if (cOpts.autocolorscale) { + var scl; + if (min * max < 0) scl = fullLayout.colorscale.diverging; + else if (min >= 0) scl = fullLayout.colorscale.sequential; + else scl = fullLayout.colorscale.sequentialminus; + cOpts._sync("colorscale", scl); + } +}; +var scales = scales_1; +var helpers$K = helpers$L; +var colorscale = { + moduleType: "component", + name: "colorscale", + attributes: attributes$I, + layoutAttributes: layout_attributes$3, + supplyLayoutDefaults: layout_defaults$6, + handleDefaults: defaults$n, + crossTraceDefaults: cross_trace_defaults$2, + calc: calc$c, + // ./scales.js is required in lib/coerce.js ; + // it needs to be a separate module to avoid a circular dependency + scales: scales.scales, + defaultScale: scales.defaultScale, + getScale: scales.get, + isValidScale: scales.isValid, + hasColorscale: helpers$K.hasColorscale, + extractOpts: helpers$K.extractOpts, + extractScale: helpers$K.extractScale, + flipScale: helpers$K.flipScale, + makeColorScaleFunc: helpers$K.makeColorScaleFunc, + makeColorScaleFuncFromTrace: helpers$K.makeColorScaleFuncFromTrace +}; +var Lib$1K = libExports; +var isTypedArraySpec$1 = array$2.isTypedArraySpec; +var subtypes$3 = { + hasLines: function(trace) { + return trace.visible && trace.mode && trace.mode.indexOf("lines") !== -1; + }, + hasMarkers: function(trace) { + return trace.visible && (trace.mode && trace.mode.indexOf("markers") !== -1 || // until splom implements 'mode' + trace.type === "splom"); + }, + hasText: function(trace) { + return trace.visible && trace.mode && trace.mode.indexOf("text") !== -1; + }, + isBubble: function(trace) { + var marker2 = trace.marker; + return Lib$1K.isPlainObject(marker2) && (Lib$1K.isArrayOrTypedArray(marker2.size) || isTypedArraySpec$1(marker2.size)); + } +}; +var isNumeric$p = fastIsnumeric; +var make_bubble_size_func = function makeBubbleSizeFn(trace, factor) { + if (!factor) { + factor = 2; + } + var marker2 = trace.marker; + var sizeRef = marker2.sizeref || 1; + var sizeMin = marker2.sizemin || 0; + var baseFn = marker2.sizemode === "area" ? function(v) { + return Math.sqrt(v / sizeRef); + } : function(v) { + return v / sizeRef; + }; + return function(v) { + var baseSize = baseFn(v / factor); + return isNumeric$p(baseSize) && baseSize > 0 ? Math.max(baseSize, sizeMin) : 0; + }; +}; +var helpers$J = {}; +(function(exports2) { + var Lib2 = libExports; + exports2.getSubplot = function(trace) { + return trace.subplot || trace.xaxis + trace.yaxis || trace.geo; + }; + exports2.isTraceInSubplots = function(trace, subplots) { + if (trace.type === "splom") { + var xaxes = trace.xaxes || []; + var yaxes = trace.yaxes || []; + for (var i = 0; i < xaxes.length; i++) { + for (var j = 0; j < yaxes.length; j++) { + if (subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { + return true; + } + } + } + return false; + } + return subplots.indexOf(exports2.getSubplot(trace)) !== -1; + }; + exports2.flat = function(subplots, v) { + var out = new Array(subplots.length); + for (var i = 0; i < subplots.length; i++) { + out[i] = v; + } + return out; + }; + exports2.p2c = function(axArray, v) { + var out = new Array(axArray.length); + for (var i = 0; i < axArray.length; i++) { + out[i] = axArray[i].p2c(v); + } + return out; + }; + exports2.getDistanceFunction = function(mode, dx, dy, dxy) { + if (mode === "closest") return dxy || exports2.quadrature(dx, dy); + return mode.charAt(0) === "x" ? dx : dy; + }; + exports2.getClosest = function(cd, distfn, pointData) { + if (pointData.index !== false) { + if (pointData.index >= 0 && pointData.index < cd.length) { + pointData.distance = 0; + } else pointData.index = false; + } else { + for (var i = 0; i < cd.length; i++) { + var newDistance = distfn(cd[i]); + if (newDistance <= pointData.distance) { + pointData.index = i; + pointData.distance = newDistance; + } + } + } + return pointData; + }; + exports2.inbox = function(v0, v1, passVal) { + return v0 * v1 < 0 || v0 === 0 ? passVal : Infinity; + }; + exports2.quadrature = function(dx, dy) { + return function(di) { + var x = dx(di); + var y = dy(di); + return Math.sqrt(x * x + y * y); + }; + }; + exports2.makeEventData = function(pt, trace, cd) { + var pointNumber = "index" in pt ? pt.index : pt.pointNumber; + var out = { + data: trace._input, + fullData: trace, + curveNumber: trace.index, + pointNumber + }; + if (trace._indexToPoints) { + var pointIndices = trace._indexToPoints[pointNumber]; + if (pointIndices.length === 1) { + out.pointIndex = pointIndices[0]; + } else { + out.pointIndices = pointIndices; + } + } else { + out.pointIndex = pointNumber; + } + if (trace._module.eventData) { + out = trace._module.eventData(out, pt, trace, cd, pointNumber); + } else { + if ("xVal" in pt) out.x = pt.xVal; + else if ("x" in pt) out.x = pt.x; + if ("yVal" in pt) out.y = pt.yVal; + else if ("y" in pt) out.y = pt.y; + if (pt.xa) out.xaxis = pt.xa; + if (pt.ya) out.yaxis = pt.ya; + if (pt.zLabelVal !== void 0) out.z = pt.zLabelVal; + } + exports2.appendArrayPointValue(out, trace, pointNumber); + return out; + }; + exports2.appendArrayPointValue = function(pointData, trace, pointNumber) { + var arrayAttrs = trace._arrayAttrs; + if (!arrayAttrs) { + return; + } + for (var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + if (pointData[key] === void 0) { + var val = Lib2.nestedProperty(trace, astr).get(); + var pointVal = getPointData(val, pointNumber); + if (pointVal !== void 0) pointData[key] = pointVal; + } + } + }; + exports2.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { + var arrayAttrs = trace._arrayAttrs; + if (!arrayAttrs) { + return; + } + for (var i = 0; i < arrayAttrs.length; i++) { + var astr = arrayAttrs[i]; + var key = getPointKey(astr); + if (pointData[key] === void 0) { + var val = Lib2.nestedProperty(trace, astr).get(); + var keyVal = new Array(pointNumbers.length); + for (var j = 0; j < pointNumbers.length; j++) { + keyVal[j] = getPointData(val, pointNumbers[j]); + } + pointData[key] = keyVal; + } + } + }; + var pointKeyMap = { + ids: "id", + locations: "location", + labels: "label", + values: "value", + "marker.colors": "color", + parents: "parent" + }; + function getPointKey(astr) { + return pointKeyMap[astr] || astr; + } + function getPointData(val, pointNumber) { + if (Array.isArray(pointNumber)) { + if (Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { + return val[pointNumber[0]][pointNumber[1]]; + } + } else { + return val[pointNumber]; + } + } + var xyHoverMode = { + x: true, + y: true + }; + var unifiedHoverMode = { + "x unified": true, + "y unified": true + }; + exports2.isUnifiedHover = function(hovermode) { + if (typeof hovermode !== "string") return false; + return !!unifiedHoverMode[hovermode]; + }; + exports2.isXYhover = function(hovermode) { + if (typeof hovermode !== "string") return false; + return !!xyHoverMode[hovermode]; + }; +})(helpers$J); +var parseSvgPath = parse$5; +var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 }; +var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig; +function parse$5(path) { + var data = []; + path.replace(segment, function(_2, command2, args) { + var type = command2.toLowerCase(); + args = parseValues(args); + if (type == "m" && args.length > 2) { + data.push([command2].concat(args.splice(0, 2))); + type = "l"; + command2 = command2 == "m" ? "l" : "L"; + } + while (true) { + if (args.length == length[type]) { + args.unshift(command2); + return data.push(args); + } + if (args.length < length[type]) throw new Error("malformed path data"); + data.push([command2].concat(args.splice(0, length[type]))); + } + }); + return data; +} +var number$1 = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig; +function parseValues(args) { + var numbers = args.match(number$1); + return numbers ? numbers.map(Number) : []; +} +var symbol_defs; +var hasRequiredSymbol_defs; +function requireSymbol_defs() { + if (hasRequiredSymbol_defs) return symbol_defs; + hasRequiredSymbol_defs = 1; + var parseSvgPath$1 = parseSvgPath; + var round2 = d3Exports.round; + var emptyPath = "M0,0Z"; + var sqrt2 = Math.sqrt(2); + var sqrt3 = Math.sqrt(3); + var PI2 = Math.PI; + var cos2 = Math.cos; + var sin2 = Math.sin; + symbol_defs = { + circle: { + n: 0, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + var circle = "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"; + return standoff ? align3(angle, standoff, circle) : circle; + } + }, + square: { + n: 1, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); + } + }, + diamond: { + n: 2, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rd = round2(r * 1.3, 2); + return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "Z"); + } + }, + cross: { + n: 3, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rc = round2(r * 0.4, 2); + var rc2 = round2(r * 1.2, 2); + return align3(angle, standoff, "M" + rc2 + "," + rc + "H" + rc + "V" + rc2 + "H-" + rc + "V" + rc + "H-" + rc2 + "V-" + rc + "H-" + rc + "V-" + rc2 + "H" + rc + "V-" + rc + "H" + rc2 + "Z"); + } + }, + x: { + n: 4, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r * 0.8 / sqrt2, 2); + var ne = "l" + rx + "," + rx; + var se = "l" + rx + ",-" + rx; + var sw = "l-" + rx + ",-" + rx; + var nw = "l-" + rx + "," + rx; + return align3(angle, standoff, "M0," + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + "Z"); + } + }, + "triangle-up": { + n: 5, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rt = round2(r * 2 / sqrt3, 2); + var r2 = round2(r / 2, 2); + var rs = round2(r, 2); + return align3(angle, standoff, "M-" + rt + "," + r2 + "H" + rt + "L0,-" + rs + "Z"); + } + }, + "triangle-down": { + n: 6, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rt = round2(r * 2 / sqrt3, 2); + var r2 = round2(r / 2, 2); + var rs = round2(r, 2); + return align3(angle, standoff, "M-" + rt + ",-" + r2 + "H" + rt + "L0," + rs + "Z"); + } + }, + "triangle-left": { + n: 7, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rt = round2(r * 2 / sqrt3, 2); + var r2 = round2(r / 2, 2); + var rs = round2(r, 2); + return align3(angle, standoff, "M" + r2 + ",-" + rt + "V" + rt + "L-" + rs + ",0Z"); + } + }, + "triangle-right": { + n: 8, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rt = round2(r * 2 / sqrt3, 2); + var r2 = round2(r / 2, 2); + var rs = round2(r, 2); + return align3(angle, standoff, "M-" + r2 + ",-" + rt + "V" + rt + "L" + rs + ",0Z"); + } + }, + "triangle-ne": { + n: 9, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var r1 = round2(r * 0.6, 2); + var r2 = round2(r * 1.2, 2); + return align3(angle, standoff, "M-" + r2 + ",-" + r1 + "H" + r1 + "V" + r2 + "Z"); + } + }, + "triangle-se": { + n: 10, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var r1 = round2(r * 0.6, 2); + var r2 = round2(r * 1.2, 2); + return align3(angle, standoff, "M" + r1 + ",-" + r2 + "V" + r1 + "H-" + r2 + "Z"); + } + }, + "triangle-sw": { + n: 11, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var r1 = round2(r * 0.6, 2); + var r2 = round2(r * 1.2, 2); + return align3(angle, standoff, "M" + r2 + "," + r1 + "H-" + r1 + "V-" + r2 + "Z"); + } + }, + "triangle-nw": { + n: 12, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var r1 = round2(r * 0.6, 2); + var r2 = round2(r * 1.2, 2); + return align3(angle, standoff, "M-" + r1 + "," + r2 + "V-" + r1 + "H" + r2 + "Z"); + } + }, + pentagon: { + n: 13, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x1 = round2(r * 0.951, 2); + var x2 = round2(r * 0.588, 2); + var y0 = round2(-r, 2); + var y1 = round2(r * -0.309, 2); + var y2 = round2(r * 0.809, 2); + return align3(angle, standoff, "M" + x1 + "," + y1 + "L" + x2 + "," + y2 + "H-" + x2 + "L-" + x1 + "," + y1 + "L0," + y0 + "Z"); + } + }, + hexagon: { + n: 14, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var y0 = round2(r, 2); + var y1 = round2(r / 2, 2); + var x = round2(r * sqrt3 / 2, 2); + return align3(angle, standoff, "M" + x + ",-" + y1 + "V" + y1 + "L0," + y0 + "L-" + x + "," + y1 + "V-" + y1 + "L0,-" + y0 + "Z"); + } + }, + hexagon2: { + n: 15, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x0 = round2(r, 2); + var x1 = round2(r / 2, 2); + var y = round2(r * sqrt3 / 2, 2); + return align3(angle, standoff, "M-" + x1 + "," + y + "H" + x1 + "L" + x0 + ",0L" + x1 + ",-" + y + "H-" + x1 + "L-" + x0 + ",0Z"); + } + }, + octagon: { + n: 16, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var a = round2(r * 0.924, 2); + var b = round2(r * 0.383, 2); + return align3(angle, standoff, "M-" + b + ",-" + a + "H" + b + "L" + a + ",-" + b + "V" + b + "L" + b + "," + a + "H-" + b + "L-" + a + "," + b + "V-" + b + "Z"); + } + }, + star: { + n: 17, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = r * 1.4; + var x1 = round2(rs * 0.225, 2); + var x2 = round2(rs * 0.951, 2); + var x3 = round2(rs * 0.363, 2); + var x4 = round2(rs * 0.588, 2); + var y0 = round2(-rs, 2); + var y1 = round2(rs * -0.309, 2); + var y3 = round2(rs * 0.118, 2); + var y4 = round2(rs * 0.809, 2); + var y5 = round2(rs * 0.382, 2); + return align3(angle, standoff, "M" + x1 + "," + y1 + "H" + x2 + "L" + x3 + "," + y3 + "L" + x4 + "," + y4 + "L0," + y5 + "L-" + x4 + "," + y4 + "L-" + x3 + "," + y3 + "L-" + x2 + "," + y1 + "H-" + x1 + "L0," + y0 + "Z"); + } + }, + hexagram: { + n: 18, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var y = round2(r * 0.66, 2); + var x1 = round2(r * 0.38, 2); + var x2 = round2(r * 0.76, 2); + return align3(angle, standoff, "M-" + x2 + ",0l-" + x1 + ",-" + y + "h" + x2 + "l" + x1 + ",-" + y + "l" + x1 + "," + y + "h" + x2 + "l-" + x1 + "," + y + "l" + x1 + "," + y + "h-" + x2 + "l-" + x1 + "," + y + "l-" + x1 + ",-" + y + "h-" + x2 + "Z"); + } + }, + "star-triangle-up": { + n: 19, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * sqrt3 * 0.8, 2); + var y1 = round2(r * 0.8, 2); + var y2 = round2(r * 1.6, 2); + var rc = round2(r * 4, 2); + var aPart = "A " + rc + "," + rc + " 0 0 1 "; + return align3(angle, standoff, "M-" + x + "," + y1 + aPart + x + "," + y1 + aPart + "0,-" + y2 + aPart + "-" + x + "," + y1 + "Z"); + } + }, + "star-triangle-down": { + n: 20, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * sqrt3 * 0.8, 2); + var y1 = round2(r * 0.8, 2); + var y2 = round2(r * 1.6, 2); + var rc = round2(r * 4, 2); + var aPart = "A " + rc + "," + rc + " 0 0 1 "; + return align3(angle, standoff, "M" + x + ",-" + y1 + aPart + "-" + x + ",-" + y1 + aPart + "0," + y2 + aPart + x + ",-" + y1 + "Z"); + } + }, + "star-square": { + n: 21, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rp = round2(r * 1.1, 2); + var rc = round2(r * 2, 2); + var aPart = "A " + rc + "," + rc + " 0 0 1 "; + return align3(angle, standoff, "M-" + rp + ",-" + rp + aPart + "-" + rp + "," + rp + aPart + rp + "," + rp + aPart + rp + ",-" + rp + aPart + "-" + rp + ",-" + rp + "Z"); + } + }, + "star-diamond": { + n: 22, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rp = round2(r * 1.4, 2); + var rc = round2(r * 1.9, 2); + var aPart = "A " + rc + "," + rc + " 0 0 1 "; + return align3(angle, standoff, "M-" + rp + ",0" + aPart + "0," + rp + aPart + rp + ",0" + aPart + "0,-" + rp + aPart + "-" + rp + ",0Z"); + } + }, + "diamond-tall": { + n: 23, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * 0.7, 2); + var y = round2(r * 1.4, 2); + return align3(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z"); + } + }, + "diamond-wide": { + n: 24, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * 1.4, 2); + var y = round2(r * 0.7, 2); + return align3(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z"); + } + }, + hourglass: { + n: 25, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "L" + rs + ",-" + rs + "H-" + rs + "Z"); + }, + noDot: true + }, + bowtie: { + n: 26, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M" + rs + "," + rs + "V-" + rs + "L-" + rs + "," + rs + "V-" + rs + "Z"); + }, + noDot: true + }, + "circle-cross": { + n: 27, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"); + }, + needLine: true, + noDot: true + }, + "circle-x": { + n: 28, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + var rc = round2(r / sqrt2, 2); + return align3(angle, standoff, "M" + rc + "," + rc + "L-" + rc + ",-" + rc + "M" + rc + ",-" + rc + "L-" + rc + "," + rc + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"); + }, + needLine: true, + noDot: true + }, + "square-cross": { + n: 29, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); + }, + needLine: true, + noDot: true + }, + "square-x": { + n: 30, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rs = round2(r, 2); + return align3(angle, standoff, "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); + }, + needLine: true, + noDot: true + }, + "diamond-cross": { + n: 31, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rd = round2(r * 1.3, 2); + return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM0,-" + rd + "V" + rd + "M-" + rd + ",0H" + rd); + }, + needLine: true, + noDot: true + }, + "diamond-x": { + n: 32, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rd = round2(r * 1.3, 2); + var r2 = round2(r * 0.65, 2); + return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM-" + r2 + ",-" + r2 + "L" + r2 + "," + r2 + "M-" + r2 + "," + r2 + "L" + r2 + ",-" + r2); + }, + needLine: true, + noDot: true + }, + "cross-thin": { + n: 33, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rc = round2(r * 1.4, 2); + return align3(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc); + }, + needLine: true, + noDot: true, + noFill: true + }, + "x-thin": { + n: 34, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + return align3(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx + "M" + rx + ",-" + rx + "L-" + rx + "," + rx); + }, + needLine: true, + noDot: true, + noFill: true + }, + asterisk: { + n: 35, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rc = round2(r * 1.2, 2); + var rs = round2(r * 0.85, 2); + return align3(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc + "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs); + }, + needLine: true, + noDot: true, + noFill: true + }, + hash: { + n: 36, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var r1 = round2(r / 2, 2); + var r2 = round2(r, 2); + return align3(angle, standoff, "M" + r1 + "," + r2 + "V-" + r2 + "M" + (r1 - r2) + ",-" + r2 + "V" + r2 + "M" + r2 + "," + r1 + "H-" + r2 + "M-" + r2 + "," + (r1 - r2) + "H" + r2); + }, + needLine: true, + noFill: true + }, + "y-up": { + n: 37, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * 1.2, 2); + var y0 = round2(r * 1.6, 2); + var y1 = round2(r * 0.8, 2); + return align3(angle, standoff, "M-" + x + "," + y1 + "L0,0M" + x + "," + y1 + "L0,0M0,-" + y0 + "L0,0"); + }, + needLine: true, + noDot: true, + noFill: true + }, + "y-down": { + n: 38, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var x = round2(r * 1.2, 2); + var y0 = round2(r * 1.6, 2); + var y1 = round2(r * 0.8, 2); + return align3(angle, standoff, "M-" + x + ",-" + y1 + "L0,0M" + x + ",-" + y1 + "L0,0M0," + y0 + "L0,0"); + }, + needLine: true, + noDot: true, + noFill: true + }, + "y-left": { + n: 39, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var y = round2(r * 1.2, 2); + var x0 = round2(r * 1.6, 2); + var x1 = round2(r * 0.8, 2); + return align3(angle, standoff, "M" + x1 + "," + y + "L0,0M" + x1 + ",-" + y + "L0,0M-" + x0 + ",0L0,0"); + }, + needLine: true, + noDot: true, + noFill: true + }, + "y-right": { + n: 40, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var y = round2(r * 1.2, 2); + var x0 = round2(r * 1.6, 2); + var x1 = round2(r * 0.8, 2); + return align3(angle, standoff, "M-" + x1 + "," + y + "L0,0M-" + x1 + ",-" + y + "L0,0M" + x0 + ",0L0,0"); + }, + needLine: true, + noDot: true, + noFill: true + }, + "line-ew": { + n: 41, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rc = round2(r * 1.4, 2); + return align3(angle, standoff, "M" + rc + ",0H-" + rc); + }, + needLine: true, + noDot: true, + noFill: true + }, + "line-ns": { + n: 42, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rc = round2(r * 1.4, 2); + return align3(angle, standoff, "M0," + rc + "V-" + rc); + }, + needLine: true, + noDot: true, + noFill: true + }, + "line-ne": { + n: 43, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + return align3(angle, standoff, "M" + rx + ",-" + rx + "L-" + rx + "," + rx); + }, + needLine: true, + noDot: true, + noFill: true + }, + "line-nw": { + n: 44, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + return align3(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx); + }, + needLine: true, + noDot: true, + noFill: true + }, + "arrow-up": { + n: 45, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + var ry = round2(r * 2, 2); + return align3(angle, standoff, "M0,0L-" + rx + "," + ry + "H" + rx + "Z"); + }, + backoff: 1, + noDot: true + }, + "arrow-down": { + n: 46, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + var ry = round2(r * 2, 2); + return align3(angle, standoff, "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z"); + }, + noDot: true + }, + "arrow-left": { + n: 47, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r * 2, 2); + var ry = round2(r, 2); + return align3(angle, standoff, "M0,0L" + rx + ",-" + ry + "V" + ry + "Z"); + }, + noDot: true + }, + "arrow-right": { + n: 48, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r * 2, 2); + var ry = round2(r, 2); + return align3(angle, standoff, "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z"); + }, + noDot: true + }, + "arrow-bar-up": { + n: 49, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + var ry = round2(r * 2, 2); + return align3(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + "," + ry + "H" + rx + "Z"); + }, + backoff: 1, + needLine: true, + noDot: true + }, + "arrow-bar-down": { + n: 50, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r, 2); + var ry = round2(r * 2, 2); + return align3(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z"); + }, + needLine: true, + noDot: true + }, + "arrow-bar-left": { + n: 51, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r * 2, 2); + var ry = round2(r, 2); + return align3(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L" + rx + ",-" + ry + "V" + ry + "Z"); + }, + needLine: true, + noDot: true + }, + "arrow-bar-right": { + n: 52, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var rx = round2(r * 2, 2); + var ry = round2(r, 2); + return align3(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z"); + }, + needLine: true, + noDot: true + }, + arrow: { + n: 53, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var headAngle = PI2 / 2.5; + var x = 2 * r * cos2(headAngle); + var y = 2 * r * sin2(headAngle); + return align3( + angle, + standoff, + "M0,0L" + -x + "," + y + "L" + x + "," + y + "Z" + ); + }, + backoff: 0.9, + noDot: true + }, + "arrow-wide": { + n: 54, + f: function(r, angle, standoff) { + if (skipAngle(angle)) return emptyPath; + var headAngle = PI2 / 4; + var x = 2 * r * cos2(headAngle); + var y = 2 * r * sin2(headAngle); + return align3( + angle, + standoff, + "M0,0L" + -x + "," + y + "A " + 2 * r + "," + 2 * r + " 0 0 1 " + x + "," + y + "Z" + ); + }, + backoff: 0.4, + noDot: true + } + }; + function skipAngle(angle) { + return angle === null; + } + var lastPathIn, lastPathOut; + var lastAngle, lastStandoff; + function align3(angle, standoff, path) { + if ((!angle || angle % 360 === 0) && !standoff) return path; + if (lastAngle === angle && lastStandoff === standoff && lastPathIn === path) return lastPathOut; + lastAngle = angle; + lastStandoff = standoff; + lastPathIn = path; + function rotate2(t4, xy) { + var cosT = cos2(t4); + var sinT = sin2(t4); + var x2 = xy[0]; + var y2 = xy[1] + (standoff || 0); + return [ + x2 * cosT - y2 * sinT, + x2 * sinT + y2 * cosT + ]; + } + var t = angle / 180 * PI2; + var x = 0; + var y = 0; + var cmd = parseSvgPath$1(path); + var str2 = ""; + for (var i = 0; i < cmd.length; i++) { + var cmdI = cmd[i]; + var op = cmdI[0]; + var x0 = x; + var y0 = y; + if (op === "M" || op === "L") { + x = +cmdI[1]; + y = +cmdI[2]; + } else if (op === "m" || op === "l") { + x += +cmdI[1]; + y += +cmdI[2]; + } else if (op === "H") { + x = +cmdI[1]; + } else if (op === "h") { + x += +cmdI[1]; + } else if (op === "V") { + y = +cmdI[1]; + } else if (op === "v") { + y += +cmdI[1]; + } else if (op === "A") { + x = +cmdI[1]; + y = +cmdI[2]; + var E2 = rotate2(t, [+cmdI[6], +cmdI[7]]); + cmdI[6] = E2[0]; + cmdI[7] = E2[1]; + cmdI[3] = +cmdI[3] + angle; + } + if (op === "H" || op === "V") op = "L"; + if (op === "h" || op === "v") op = "l"; + if (op === "m" || op === "l") { + x -= x0; + y -= y0; + } + var B2 = rotate2(t, [x, y]); + if (op === "H" || op === "V") op = "L"; + if (op === "M" || op === "L" || op === "m" || op === "l") { + cmdI[1] = B2[0]; + cmdI[2] = B2[1]; + } + cmdI[0] = op; + str2 += cmdI[0] + cmdI.slice(1).join(","); + } + lastPathOut = str2; + return str2; + } + return symbol_defs; +} +var d3$z = d3Exports; +var Lib$1J = libExports; +var numberFormat$1 = Lib$1J.numberFormat; +var isNumeric$o = fastIsnumeric; +var tinycolor$4 = tinycolorExports; +var Registry$L = registry; +var Color$J = colorExports; +var Colorscale$2 = colorscale; +var strTranslate$c = Lib$1J.strTranslate; +var svgTextUtils$f = svg_text_utils; +var xmlnsNamespaces$3 = xmlns_namespaces; +var alignment = alignment$1; +var LINE_SPACING$7 = alignment.LINE_SPACING; +var DESELECTDIM$2 = interactions.DESELECTDIM; +var subTypes$a = subtypes$3; +var makeBubbleSizeFn$1 = make_bubble_size_func; +var appendArrayPointValue$3 = helpers$J.appendArrayPointValue; +var drawing = drawing$1.exports = {}; +drawing.font = function(s, font2) { + var variant = font2.variant; + var style5 = font2.style; + var weight = font2.weight; + var color2 = font2.color; + var size = font2.size; + var family = font2.family; + var shadow = font2.shadow; + var lineposition = font2.lineposition; + var textcase = font2.textcase; + if (family) s.style("font-family", family); + if (size + 1) s.style("font-size", size + "px"); + if (color2) s.call(Color$J.fill, color2); + if (weight) s.style("font-weight", weight); + if (style5) s.style("font-style", style5); + if (variant) s.style("font-variant", variant); + if (textcase) s.style("text-transform", dropNone(textcase2transform(textcase))); + if (shadow) s.style("text-shadow", shadow === "auto" ? svgTextUtils$f.makeTextShadow(Color$J.contrast(color2)) : dropNone(shadow)); + if (lineposition) s.style("text-decoration-line", dropNone(lineposition2decorationLine(lineposition))); +}; +function dropNone(a) { + return a === "none" ? void 0 : a; +} +var textcase2transformOptions = { + normal: "none", + lower: "lowercase", + upper: "uppercase", + "word caps": "capitalize" +}; +function textcase2transform(textcase) { + return textcase2transformOptions[textcase]; +} +function lineposition2decorationLine(lineposition) { + return lineposition.replace("under", "underline").replace("over", "overline").replace("through", "line-through").split("+").join(" "); +} +drawing.setPosition = function(s, x, y) { + s.attr("x", x).attr("y", y); +}; +drawing.setSize = function(s, w, h) { + s.attr("width", w).attr("height", h); +}; +drawing.setRect = function(s, x, y, w, h) { + s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); +}; +drawing.translatePoint = function(d, sel, xa, ya) { + var x = xa.c2p(d.x); + var y = ya.c2p(d.y); + if (isNumeric$o(x) && isNumeric$o(y) && sel.node()) { + if (sel.node().nodeName === "text") { + sel.attr("x", x).attr("y", y); + } else { + sel.attr("transform", strTranslate$c(x, y)); + } + } else { + return false; + } + return true; +}; +drawing.translatePoints = function(s, xa, ya) { + s.each(function(d) { + var sel = d3$z.select(this); + drawing.translatePoint(d, sel, xa, ya); + }); +}; +drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) { + sel.attr( + "display", + xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar) ? null : "none" + ); +}; +drawing.hideOutsideRangePoints = function(traceGroups, subplot) { + if (!subplot._hasClipOnAxisFalse) return; + var xa = subplot.xaxis; + var ya = subplot.yaxis; + traceGroups.each(function(d) { + var trace = d[0].trace; + var xcalendar = trace.xcalendar; + var ycalendar = trace.ycalendar; + var selector = Registry$L.traceIs(trace, "bar-like") ? ".bartext" : ".point,.textpoint"; + traceGroups.selectAll(selector).each(function(d2) { + drawing.hideOutsideRangePoint(d2, d3$z.select(this), xa, ya, xcalendar, ycalendar); + }); + }); +}; +drawing.crispRound = function(gd, lineWidth, dflt) { + if (!lineWidth || !isNumeric$o(lineWidth)) return dflt || 0; + if (gd._context.staticPlot) return lineWidth; + if (lineWidth < 1) return 1; + return Math.round(lineWidth); +}; +drawing.singleLineStyle = function(d, s, lw, lc, ld) { + s.style("fill", "none"); + var line2 = (((d || [])[0] || {}).trace || {}).line || {}; + var lw1 = lw || line2.width || 0; + var dash2 = ld || line2.dash || ""; + Color$J.stroke(s, lc || line2.color); + drawing.dashLine(s, dash2, lw1); +}; +drawing.lineGroupStyle = function(s, lw, lc, ld) { + s.style("fill", "none").each(function(d) { + var line2 = (((d || [])[0] || {}).trace || {}).line || {}; + var lw1 = lw || line2.width || 0; + var dash2 = ld || line2.dash || ""; + d3$z.select(this).call(Color$J.stroke, lc || line2.color).call(drawing.dashLine, dash2, lw1); + }); +}; +drawing.dashLine = function(s, dash2, lineWidth) { + lineWidth = +lineWidth || 0; + dash2 = drawing.dashStyle(dash2, lineWidth); + s.style({ + "stroke-dasharray": dash2, + "stroke-width": lineWidth + "px" + }); +}; +drawing.dashStyle = function(dash2, lineWidth) { + lineWidth = +lineWidth || 1; + var dlw = Math.max(lineWidth, 3); + if (dash2 === "solid") dash2 = ""; + else if (dash2 === "dot") dash2 = dlw + "px," + dlw + "px"; + else if (dash2 === "dash") dash2 = 3 * dlw + "px," + 3 * dlw + "px"; + else if (dash2 === "longdash") dash2 = 5 * dlw + "px," + 5 * dlw + "px"; + else if (dash2 === "dashdot") { + dash2 = 3 * dlw + "px," + dlw + "px," + dlw + "px," + dlw + "px"; + } else if (dash2 === "longdashdot") { + dash2 = 5 * dlw + "px," + 2 * dlw + "px," + dlw + "px," + 2 * dlw + "px"; + } + return dash2; +}; +function setFillStyle(sel, trace, gd, forLegend) { + var markerPattern = trace.fillpattern; + var fillgradient = trace.fillgradient; + var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, 0, ""); + if (patternShape) { + var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, 0, null); + var patternFGColor = drawing.getPatternAttr(markerPattern.fgcolor, 0, null); + var patternFGOpacity = markerPattern.fgopacity; + var patternSize = drawing.getPatternAttr(markerPattern.size, 0, 8); + var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, 0, 0.3); + var patternID = trace.uid; + drawing.pattern( + sel, + "point", + gd, + patternID, + patternShape, + patternSize, + patternSolidity, + void 0, + markerPattern.fillmode, + patternBGColor, + patternFGColor, + patternFGOpacity + ); + } else if (fillgradient && fillgradient.type !== "none") { + var direction = fillgradient.type; + var gradientID = "scatterfill-" + trace.uid; + if (forLegend) { + gradientID = "legendfill-" + trace.uid; + } + if (!forLegend && (fillgradient.start !== void 0 || fillgradient.stop !== void 0)) { + var start, stop; + if (direction === "horizontal") { + start = { + x: fillgradient.start, + y: 0 + }; + stop = { + x: fillgradient.stop, + y: 0 + }; + } else if (direction === "vertical") { + start = { + x: 0, + y: fillgradient.start + }; + stop = { + x: 0, + y: fillgradient.stop + }; + } + start.x = trace._xA.c2p( + start.x === void 0 ? trace._extremes.x.min[0].val : start.x, + true + ); + start.y = trace._yA.c2p( + start.y === void 0 ? trace._extremes.y.min[0].val : start.y, + true + ); + stop.x = trace._xA.c2p( + stop.x === void 0 ? trace._extremes.x.max[0].val : stop.x, + true + ); + stop.y = trace._yA.c2p( + stop.y === void 0 ? trace._extremes.y.max[0].val : stop.y, + true + ); + sel.call(gradientWithBounds, gd, gradientID, "linear", fillgradient.colorscale, "fill", start, stop, true, false); + } else { + if (direction === "horizontal") { + direction = direction + "reversed"; + } + sel.call(drawing.gradient, gd, gradientID, direction, fillgradient.colorscale, "fill"); + } + } else if (trace.fillcolor) { + sel.call(Color$J.fill, trace.fillcolor); + } +} +drawing.singleFillStyle = function(sel, gd) { + var node = d3$z.select(sel.node()); + var data = node.data(); + var trace = ((data[0] || [])[0] || {}).trace || {}; + setFillStyle(sel, trace, gd, false); +}; +drawing.fillGroupStyle = function(s, gd, forLegend) { + s.style("stroke-width", 0).each(function(d) { + var shape = d3$z.select(this); + if (d[0].trace) { + setFillStyle(shape, d[0].trace, gd, forLegend); + } + }); +}; +var SYMBOLDEFS = requireSymbol_defs(); +drawing.symbolNames = []; +drawing.symbolFuncs = []; +drawing.symbolBackOffs = []; +drawing.symbolNeedLines = {}; +drawing.symbolNoDot = {}; +drawing.symbolNoFill = {}; +drawing.symbolList = []; +Object.keys(SYMBOLDEFS).forEach(function(k) { + var symDef = SYMBOLDEFS[k]; + var n = symDef.n; + drawing.symbolList.push( + n, + String(n), + k, + n + 100, + String(n + 100), + k + "-open" + ); + drawing.symbolNames[n] = k; + drawing.symbolFuncs[n] = symDef.f; + drawing.symbolBackOffs[n] = symDef.backoff || 0; + if (symDef.needLine) { + drawing.symbolNeedLines[n] = true; + } + if (symDef.noDot) { + drawing.symbolNoDot[n] = true; + } else { + drawing.symbolList.push( + n + 200, + String(n + 200), + k + "-dot", + n + 300, + String(n + 300), + k + "-open-dot" + ); + } + if (symDef.noFill) { + drawing.symbolNoFill[n] = true; + } +}); +var MAXSYMBOL = drawing.symbolNames.length; +var DOTPATH = "M0,0.5L0.5,0L0,-0.5L-0.5,0Z"; +drawing.symbolNumber = function(v) { + if (isNumeric$o(v)) { + v = +v; + } else if (typeof v === "string") { + var vbase = 0; + if (v.indexOf("-open") > 0) { + vbase = 100; + v = v.replace("-open", ""); + } + if (v.indexOf("-dot") > 0) { + vbase += 200; + v = v.replace("-dot", ""); + } + v = drawing.symbolNames.indexOf(v); + if (v >= 0) { + v += vbase; + } + } + return v % 100 >= MAXSYMBOL || v >= 400 ? 0 : Math.floor(Math.max(v, 0)); +}; +function makePointPath(symbolNumber, r, t, s) { + var base = symbolNumber % 100; + return drawing.symbolFuncs[base](r, t, s) + (symbolNumber >= 200 ? DOTPATH : ""); +} +var stopFormatter = numberFormat$1("~f"); +var gradientInfo = { + radial: { type: "radial" }, + radialreversed: { type: "radial", reversed: true }, + horizontal: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 } }, + horizontalreversed: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 }, reversed: true }, + vertical: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 } }, + verticalreversed: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 }, reversed: true } +}; +drawing.gradient = function(sel, gd, gradientID, type, colorscale2, prop) { + var info = gradientInfo[type]; + return gradientWithBounds( + sel, + gd, + gradientID, + info.type, + colorscale2, + prop, + info.start, + info.stop, + false, + info.reversed + ); +}; +function gradientWithBounds(sel, gd, gradientID, type, colorscale2, prop, start, stop, inUserSpace, reversed) { + var len = colorscale2.length; + var info; + if (type === "linear") { + info = { + node: "linearGradient", + attrs: { + x1: start.x, + y1: start.y, + x2: stop.x, + y2: stop.y, + gradientUnits: inUserSpace ? "userSpaceOnUse" : "objectBoundingBox" + }, + reversed + }; + } else if (type === "radial") { + info = { + node: "radialGradient", + reversed + }; + } + var colorStops = new Array(len); + for (var i = 0; i < len; i++) { + if (info.reversed) { + colorStops[len - 1 - i] = [stopFormatter((1 - colorscale2[i][0]) * 100), colorscale2[i][1]]; + } else { + colorStops[i] = [stopFormatter(colorscale2[i][0] * 100), colorscale2[i][1]]; + } + } + var fullLayout = gd._fullLayout; + var fullID = "g" + fullLayout._uid + "-" + gradientID; + var gradient = fullLayout._defs.select(".gradients").selectAll("#" + fullID).data([type + colorStops.join(";")], Lib$1J.identity); + gradient.exit().remove(); + gradient.enter().append(info.node).each(function() { + var el = d3$z.select(this); + if (info.attrs) el.attr(info.attrs); + el.attr("id", fullID); + var stops = el.selectAll("stop").data(colorStops); + stops.exit().remove(); + stops.enter().append("stop"); + stops.each(function(d) { + var tc = tinycolor$4(d[1]); + d3$z.select(this).attr({ + offset: d[0] + "%", + "stop-color": Color$J.tinyRGB(tc), + "stop-opacity": tc.getAlpha() + }); + }); + }); + sel.style(prop, getFullUrl(fullID, gd)).style(prop + "-opacity", null); + sel.classed("gradient_filled", true); +} +drawing.pattern = function(sel, calledBy, gd, patternID, shape, size, solidity, mcc, fillmode, bgcolor, fgcolor, fgopacity) { + var isLegend = calledBy === "legend"; + if (mcc) { + if (fillmode === "overlay") { + bgcolor = mcc; + fgcolor = Color$J.contrast(bgcolor); + } else { + bgcolor = void 0; + fgcolor = mcc; + } + } + var fullLayout = gd._fullLayout; + var fullID = "p" + fullLayout._uid + "-" + patternID; + var width, height; + var linearFn = function(x, x0, x1, y0, y1) { + return y0 + (y1 - y0) * (x - x0) / (x1 - x0); + }; + var path, linewidth, radius; + var patternTag; + var patternAttrs = {}; + var fgC = tinycolor$4(fgcolor); + var fgRGB = Color$J.tinyRGB(fgC); + var fgAlpha = fgC.getAlpha(); + var opacity = fgopacity * fgAlpha; + switch (shape) { + case "/": + width = size * Math.sqrt(2); + height = size * Math.sqrt(2); + path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2; + linewidth = solidity * size; + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case "\\": + width = size * Math.sqrt(2); + height = size * Math.sqrt(2); + path = "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2; + linewidth = solidity * size; + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case "x": + width = size * Math.sqrt(2); + height = size * Math.sqrt(2); + path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2 + "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2; + linewidth = size - size * Math.sqrt(1 - solidity); + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case "|": + width = size; + height = size; + patternTag = "path"; + path = "M" + width / 2 + ",0L" + width / 2 + "," + height; + linewidth = solidity * size; + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case "-": + width = size; + height = size; + patternTag = "path"; + path = "M0," + height / 2 + "L" + width + "," + height / 2; + linewidth = solidity * size; + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case "+": + width = size; + height = size; + patternTag = "path"; + path = "M" + width / 2 + ",0L" + width / 2 + "," + height + "M0," + height / 2 + "L" + width + "," + height / 2; + linewidth = size - size * Math.sqrt(1 - solidity); + patternTag = "path"; + patternAttrs = { + d: path, + opacity, + stroke: fgRGB, + "stroke-width": linewidth + "px" + }; + break; + case ".": + width = size; + height = size; + if (solidity < Math.PI / 4) { + radius = Math.sqrt(solidity * size * size / Math.PI); + } else { + radius = linearFn(solidity, Math.PI / 4, 1, size / 2, size / Math.sqrt(2)); + } + patternTag = "circle"; + patternAttrs = { + cx: width / 2, + cy: height / 2, + r: radius, + opacity, + fill: fgRGB + }; + break; + } + var str2 = [ + shape || "noSh", + bgcolor || "noBg", + fgcolor || "noFg", + size, + solidity + ].join(";"); + var pattern2 = fullLayout._defs.select(".patterns").selectAll("#" + fullID).data([str2], Lib$1J.identity); + pattern2.exit().remove(); + pattern2.enter().append("pattern").each(function() { + var el = d3$z.select(this); + el.attr({ + id: fullID, + width: width + "px", + height: height + "px", + patternUnits: "userSpaceOnUse", + // for legends scale down patterns just a bit so that default size (i.e 8) nicely fit in small icons + patternTransform: isLegend ? "scale(0.8)" : "" + }); + if (bgcolor) { + var bgC = tinycolor$4(bgcolor); + var bgRGB = Color$J.tinyRGB(bgC); + var bgAlpha = bgC.getAlpha(); + var rects = el.selectAll("rect").data([0]); + rects.exit().remove(); + rects.enter().append("rect").attr({ + width: width + "px", + height: height + "px", + fill: bgRGB, + "fill-opacity": bgAlpha + }); + } + var patterns = el.selectAll(patternTag).data([0]); + patterns.exit().remove(); + patterns.enter().append(patternTag).attr(patternAttrs); + }); + sel.style("fill", getFullUrl(fullID, gd)).style("fill-opacity", null); + sel.classed("pattern_filled", true); +}; +drawing.initGradients = function(gd) { + var fullLayout = gd._fullLayout; + var gradientsGroup = Lib$1J.ensureSingle(fullLayout._defs, "g", "gradients"); + gradientsGroup.selectAll("linearGradient,radialGradient").remove(); + d3$z.select(gd).selectAll(".gradient_filled").classed("gradient_filled", false); +}; +drawing.initPatterns = function(gd) { + var fullLayout = gd._fullLayout; + var patternsGroup = Lib$1J.ensureSingle(fullLayout._defs, "g", "patterns"); + patternsGroup.selectAll("pattern").remove(); + d3$z.select(gd).selectAll(".pattern_filled").classed("pattern_filled", false); +}; +drawing.getPatternAttr = function(mp, i, dflt) { + if (mp && Lib$1J.isArrayOrTypedArray(mp)) { + return i < mp.length ? mp[i] : dflt; + } + return mp; +}; +drawing.pointStyle = function(s, trace, gd, pt) { + if (!s.size()) return; + var fns = drawing.makePointStyleFns(trace); + s.each(function(d) { + drawing.singlePointStyle(d, d3$z.select(this), trace, fns, gd, pt); + }); +}; +drawing.singlePointStyle = function(d, sel, trace, fns, gd, pt) { + var marker2 = trace.marker; + var markerLine2 = marker2.line; + if (pt && pt.i >= 0 && d.i === void 0) d.i = pt.i; + sel.style( + "opacity", + fns.selectedOpacityFn ? fns.selectedOpacityFn(d) : d.mo === void 0 ? marker2.opacity : d.mo + ); + if (fns.ms2mrc) { + var r; + if (d.ms === "various" || marker2.size === "various") { + r = 3; + } else { + r = fns.ms2mrc(d.ms); + } + d.mrc = r; + if (fns.selectedSizeFn) { + r = d.mrc = fns.selectedSizeFn(d); + } + var x = drawing.symbolNumber(d.mx || marker2.symbol) || 0; + d.om = x % 200 >= 100; + var angle = getMarkerAngle(d, trace); + var standoff = getMarkerStandoff(d, trace); + sel.attr("d", makePointPath(x, r, angle, standoff)); + } + var perPointGradient = false; + var fillColor, lineColor, lineWidth; + if (d.so) { + lineWidth = markerLine2.outlierwidth; + lineColor = markerLine2.outliercolor; + fillColor = marker2.outliercolor; + } else { + var markerLineWidth2 = (markerLine2 || {}).width; + lineWidth = (d.mlw + 1 || markerLineWidth2 + 1 || // TODO: we need the latter for legends... can we get rid of it? + (d.trace ? (d.trace.marker.line || {}).width : 0) + 1) - 1 || 0; + if ("mlc" in d) lineColor = d.mlcc = fns.lineScale(d.mlc); + else if (Lib$1J.isArrayOrTypedArray(markerLine2.color)) lineColor = Color$J.defaultLine; + else lineColor = markerLine2.color; + if (Lib$1J.isArrayOrTypedArray(marker2.color)) { + fillColor = Color$J.defaultLine; + perPointGradient = true; + } + if ("mc" in d) { + fillColor = d.mcc = fns.markerScale(d.mc); + } else { + fillColor = marker2.color || marker2.colors || "rgba(0,0,0,0)"; + } + if (fns.selectedColorFn) { + fillColor = fns.selectedColorFn(d); + } + } + if (d.om) { + sel.call(Color$J.stroke, fillColor).style({ + "stroke-width": (lineWidth || 1) + "px", + fill: "none" + }); + } else { + sel.style("stroke-width", (d.isBlank ? 0 : lineWidth) + "px"); + var markerGradient = marker2.gradient; + var gradientType = d.mgt; + if (gradientType) perPointGradient = true; + else gradientType = markerGradient && markerGradient.type; + if (Lib$1J.isArrayOrTypedArray(gradientType)) { + gradientType = gradientType[0]; + if (!gradientInfo[gradientType]) gradientType = 0; + } + var markerPattern = marker2.pattern; + var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, d.i, ""); + if (gradientType && gradientType !== "none") { + var gradientColor = d.mgc; + if (gradientColor) perPointGradient = true; + else gradientColor = markerGradient.color; + var gradientID = trace.uid; + if (perPointGradient) gradientID += "-" + d.i; + drawing.gradient( + sel, + gd, + gradientID, + gradientType, + [[0, gradientColor], [1, fillColor]], + "fill" + ); + } else if (patternShape) { + var perPointPattern = false; + var fgcolor = markerPattern.fgcolor; + if (!fgcolor && pt && pt.color) { + fgcolor = pt.color; + perPointPattern = true; + } + var patternFGColor = drawing.getPatternAttr(fgcolor, d.i, pt && pt.color || null); + var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, d.i, null); + var patternFGOpacity = markerPattern.fgopacity; + var patternSize = drawing.getPatternAttr(markerPattern.size, d.i, 8); + var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, d.i, 0.3); + perPointPattern = perPointPattern || d.mcc || Lib$1J.isArrayOrTypedArray(markerPattern.shape) || Lib$1J.isArrayOrTypedArray(markerPattern.bgcolor) || Lib$1J.isArrayOrTypedArray(markerPattern.fgcolor) || Lib$1J.isArrayOrTypedArray(markerPattern.size) || Lib$1J.isArrayOrTypedArray(markerPattern.solidity); + var patternID = trace.uid; + if (perPointPattern) patternID += "-" + d.i; + drawing.pattern( + sel, + "point", + gd, + patternID, + patternShape, + patternSize, + patternSolidity, + d.mcc, + markerPattern.fillmode, + patternBGColor, + patternFGColor, + patternFGOpacity + ); + } else { + Lib$1J.isArrayOrTypedArray(fillColor) ? Color$J.fill(sel, fillColor[d.i]) : Color$J.fill(sel, fillColor); + } + if (lineWidth) { + Color$J.stroke(sel, lineColor); + } + } +}; +drawing.makePointStyleFns = function(trace) { + var out = {}; + var marker2 = trace.marker; + out.markerScale = drawing.tryColorscale(marker2, ""); + out.lineScale = drawing.tryColorscale(marker2, "line"); + if (Registry$L.traceIs(trace, "symbols")) { + out.ms2mrc = subTypes$a.isBubble(trace) ? makeBubbleSizeFn$1(trace) : function() { + return (marker2.size || 6) / 2; + }; + } + if (trace.selectedpoints) { + Lib$1J.extendFlat(out, drawing.makeSelectedPointStyleFns(trace)); + } + return out; +}; +drawing.makeSelectedPointStyleFns = function(trace) { + var out = {}; + var selectedAttrs = trace.selected || {}; + var unselectedAttrs = trace.unselected || {}; + var marker2 = trace.marker || {}; + var selectedMarker = selectedAttrs.marker || {}; + var unselectedMarker = unselectedAttrs.marker || {}; + var mo = marker2.opacity; + var smo = selectedMarker.opacity; + var usmo = unselectedMarker.opacity; + var smoIsDefined = smo !== void 0; + var usmoIsDefined = usmo !== void 0; + if (Lib$1J.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) { + out.selectedOpacityFn = function(d) { + var base = d.mo === void 0 ? marker2.opacity : d.mo; + if (d.selected) { + return smoIsDefined ? smo : base; + } else { + return usmoIsDefined ? usmo : DESELECTDIM$2 * base; + } + }; + } + var mc = marker2.color; + var smc = selectedMarker.color; + var usmc = unselectedMarker.color; + if (smc || usmc) { + out.selectedColorFn = function(d) { + var base = d.mcc || mc; + if (d.selected) { + return smc || base; + } else { + return usmc || base; + } + }; + } + var ms = marker2.size; + var sms = selectedMarker.size; + var usms = unselectedMarker.size; + var smsIsDefined = sms !== void 0; + var usmsIsDefined = usms !== void 0; + if (Registry$L.traceIs(trace, "symbols") && (smsIsDefined || usmsIsDefined)) { + out.selectedSizeFn = function(d) { + var base = d.mrc || ms / 2; + if (d.selected) { + return smsIsDefined ? sms / 2 : base; + } else { + return usmsIsDefined ? usms / 2 : base; + } + }; + } + return out; +}; +drawing.makeSelectedTextStyleFns = function(trace) { + var out = {}; + var selectedAttrs = trace.selected || {}; + var unselectedAttrs = trace.unselected || {}; + var textFont = trace.textfont || {}; + var selectedTextFont = selectedAttrs.textfont || {}; + var unselectedTextFont = unselectedAttrs.textfont || {}; + var tc = textFont.color; + var stc = selectedTextFont.color; + var utc = unselectedTextFont.color; + out.selectedTextColorFn = function(d) { + var base = d.tc || tc; + if (d.selected) { + return stc || base; + } else { + if (utc) return utc; + else return stc ? base : Color$J.addOpacity(base, DESELECTDIM$2); + } + }; + return out; +}; +drawing.selectedPointStyle = function(s, trace) { + if (!s.size() || !trace.selectedpoints) return; + var fns = drawing.makeSelectedPointStyleFns(trace); + var marker2 = trace.marker || {}; + var seq = []; + if (fns.selectedOpacityFn) { + seq.push(function(pt, d) { + pt.style("opacity", fns.selectedOpacityFn(d)); + }); + } + if (fns.selectedColorFn) { + seq.push(function(pt, d) { + Color$J.fill(pt, fns.selectedColorFn(d)); + }); + } + if (fns.selectedSizeFn) { + seq.push(function(pt, d) { + var mx = d.mx || marker2.symbol || 0; + var mrc2 = fns.selectedSizeFn(d); + pt.attr("d", makePointPath(drawing.symbolNumber(mx), mrc2, getMarkerAngle(d, trace), getMarkerStandoff(d, trace))); + d.mrc2 = mrc2; + }); + } + if (seq.length) { + s.each(function(d) { + var pt = d3$z.select(this); + for (var i = 0; i < seq.length; i++) { + seq[i](pt, d); + } + }); + } +}; +drawing.tryColorscale = function(marker2, prefix) { + var cont = prefix ? Lib$1J.nestedProperty(marker2, prefix).get() : marker2; + if (cont) { + var colorArray = cont.color; + if ((cont.colorscale || cont._colorAx) && Lib$1J.isArrayOrTypedArray(colorArray)) { + return Colorscale$2.makeColorScaleFuncFromTrace(cont); + } + } + return Lib$1J.identity; +}; +var TEXTOFFSETSIGN$1 = { + start: 1, + end: -1, + middle: 0, + bottom: 1, + top: -1 +}; +function textPointPosition(s, textPosition, fontSize, markerRadius, dontTouchParent) { + var group = d3$z.select(s.node().parentNode); + var v = textPosition.indexOf("top") !== -1 ? "top" : textPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; + var h = textPosition.indexOf("left") !== -1 ? "end" : textPosition.indexOf("right") !== -1 ? "start" : "middle"; + var r = markerRadius ? markerRadius / 0.8 + 1 : 0; + var numLines = (svgTextUtils$f.lineCount(s) - 1) * LINE_SPACING$7 + 1; + var dx = TEXTOFFSETSIGN$1[h] * r; + var dy = fontSize * 0.75 + TEXTOFFSETSIGN$1[v] * r + (TEXTOFFSETSIGN$1[v] - 1) * numLines * fontSize / 2; + s.attr("text-anchor", h); + if (!dontTouchParent) { + group.attr("transform", strTranslate$c(dx, dy)); + } +} +function extracTextFontSize(d, trace) { + var fontSize = d.ts || trace.textfont.size; + return isNumeric$o(fontSize) && fontSize > 0 ? fontSize : 0; +} +drawing.textPointStyle = function(s, trace, gd) { + if (!s.size()) return; + var selectedTextColorFn; + if (trace.selectedpoints) { + var fns = drawing.makeSelectedTextStyleFns(trace); + selectedTextColorFn = fns.selectedTextColorFn; + } + var texttemplate = trace.texttemplate; + var fullLayout = gd._fullLayout; + s.each(function(d) { + var p = d3$z.select(this); + var text = texttemplate ? Lib$1J.extractOption(d, trace, "txt", "texttemplate") : Lib$1J.extractOption(d, trace, "tx", "text"); + if (!text && text !== 0) { + p.remove(); + return; + } + if (texttemplate) { + var fn = trace._module.formatLabels; + var labels = fn ? fn(d, trace, fullLayout) : {}; + var pointValues = {}; + appendArrayPointValue$3(pointValues, trace, d.i); + var meta = trace._meta || {}; + text = Lib$1J.texttemplateString(text, labels, fullLayout._d3locale, pointValues, d, meta); + } + var pos = d.tp || trace.textposition; + var fontSize = extracTextFontSize(d, trace); + var fontColor = selectedTextColorFn ? selectedTextColorFn(d) : d.tc || trace.textfont.color; + p.call(drawing.font, { + family: d.tf || trace.textfont.family, + weight: d.tw || trace.textfont.weight, + style: d.ty || trace.textfont.style, + variant: d.tv || trace.textfont.variant, + textcase: d.tC || trace.textfont.textcase, + lineposition: d.tE || trace.textfont.lineposition, + shadow: d.tS || trace.textfont.shadow, + size: fontSize, + color: fontColor + }).text(text).call(svgTextUtils$f.convertToTspans, gd).call(textPointPosition, pos, fontSize, d.mrc); + }); +}; +drawing.selectedTextStyle = function(s, trace) { + if (!s.size() || !trace.selectedpoints) return; + var fns = drawing.makeSelectedTextStyleFns(trace); + s.each(function(d) { + var tx = d3$z.select(this); + var tc = fns.selectedTextColorFn(d); + var tp = d.tp || trace.textposition; + var fontSize = extracTextFontSize(d, trace); + Color$J.fill(tx, tc); + var dontTouchParent = Registry$L.traceIs(trace, "bar-like"); + textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc, dontTouchParent); + }); +}; +var CatmullRomExp = 0.5; +drawing.smoothopen = function(pts, smoothness) { + if (pts.length < 3) { + return "M" + pts.join("L"); + } + var path = "M" + pts[0]; + var tangents = []; + var i; + for (i = 1; i < pts.length - 1; i++) { + tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness)); + } + path += "Q" + tangents[0][0] + " " + pts[1]; + for (i = 2; i < pts.length - 1; i++) { + path += "C" + tangents[i - 2][1] + " " + tangents[i - 1][0] + " " + pts[i]; + } + path += "Q" + tangents[pts.length - 3][1] + " " + pts[pts.length - 1]; + return path; +}; +drawing.smoothclosed = function(pts, smoothness) { + if (pts.length < 3) { + return "M" + pts.join("L") + "Z"; + } + var path = "M" + pts[0]; + var pLast = pts.length - 1; + var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)]; + var i; + for (i = 1; i < pLast; i++) { + tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness)); + } + tangents.push( + makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness) + ); + for (i = 1; i <= pLast; i++) { + path += "C" + tangents[i - 1][1] + " " + tangents[i][0] + " " + pts[i]; + } + path += "C" + tangents[pLast][1] + " " + tangents[0][0] + " " + pts[0] + "Z"; + return path; +}; +var lastDrawnX, lastDrawnY; +function roundEnd(pt, isY, isLastPoint) { + if (isLastPoint) pt = applyBackoff(pt); + return isY ? roundY(pt[1]) : roundX(pt[0]); +} +function roundX(p) { + var v = d3$z.round(p, 2); + lastDrawnX = v; + return v; +} +function roundY(p) { + var v = d3$z.round(p, 2); + lastDrawnY = v; + return v; +} +function makeTangent(prevpt, thispt, nextpt, smoothness) { + var d1x = prevpt[0] - thispt[0]; + var d1y = prevpt[1] - thispt[1]; + var d2x = nextpt[0] - thispt[0]; + var d2y = nextpt[1] - thispt[1]; + var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2); + var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2); + var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness; + var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness; + var denom1 = 3 * d2a * (d1a + d2a); + var denom2 = 3 * d1a * (d1a + d2a); + return [ + [ + roundX(thispt[0] + (denom1 && numx / denom1)), + roundY(thispt[1] + (denom1 && numy / denom1)) + ], + [ + roundX(thispt[0] - (denom2 && numx / denom2)), + roundY(thispt[1] - (denom2 && numy / denom2)) + ] + ]; +} +var STEPPATH = { + hv: function(p0, p1, isLastPoint) { + return "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint); + }, + vh: function(p0, p1, isLastPoint) { + return "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint); + }, + hvh: function(p0, p1, isLastPoint) { + return "H" + roundX((p0[0] + p1[0]) / 2) + "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint); + }, + vhv: function(p0, p1, isLastPoint) { + return "V" + roundY((p0[1] + p1[1]) / 2) + "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint); + } +}; +var STEPLINEAR = function(p0, p1, isLastPoint) { + return "L" + roundEnd(p1, 0, isLastPoint) + "," + roundEnd(p1, 1, isLastPoint); +}; +drawing.steps = function(shape) { + var onestep = STEPPATH[shape] || STEPLINEAR; + return function(pts) { + var path = "M" + roundX(pts[0][0]) + "," + roundY(pts[0][1]); + var len = pts.length; + for (var i = 1; i < len; i++) { + path += onestep(pts[i - 1], pts[i], i === len - 1); + } + return path; + }; +}; +function applyBackoff(pt, start) { + var backoff = pt.backoff; + var trace = pt.trace; + var d = pt.d; + var i = pt.i; + if (backoff && trace && trace.marker && trace.marker.angle % 360 === 0 && trace.line && trace.line.shape !== "spline") { + var arrayBackoff = Lib$1J.isArrayOrTypedArray(backoff); + var end = pt; + var x1 = start ? start[0] : lastDrawnX || 0; + var y1 = start ? start[1] : lastDrawnY || 0; + var x2 = end[0]; + var y2 = end[1]; + var dx = x2 - x1; + var dy = y2 - y1; + var t = Math.atan2(dy, dx); + var b = arrayBackoff ? backoff[i] : backoff; + if (b === "auto") { + var endI = end.i; + if (trace.type === "scatter") endI--; + var endMarker = end.marker; + var endMarkerSymbol = endMarker.symbol; + if (Lib$1J.isArrayOrTypedArray(endMarkerSymbol)) endMarkerSymbol = endMarkerSymbol[endI]; + var endMarkerSize = endMarker.size; + if (Lib$1J.isArrayOrTypedArray(endMarkerSize)) endMarkerSize = endMarkerSize[endI]; + b = endMarker ? drawing.symbolBackOffs[drawing.symbolNumber(endMarkerSymbol)] * endMarkerSize : 0; + b += drawing.getMarkerStandoff(d[endI], trace) || 0; + } + var x = x2 - b * Math.cos(t); + var y = y2 - b * Math.sin(t); + if ((x <= x2 && x >= x1 || x >= x2 && x <= x1) && (y <= y2 && y >= y1 || y >= y2 && y <= y1)) { + pt = [x, y]; + } + } + return pt; +} +drawing.applyBackoff = applyBackoff; +drawing.makeTester = function() { + var tester2 = Lib$1J.ensureSingleById(d3$z.select("body"), "svg", "js-plotly-tester", function(s) { + s.attr(xmlnsNamespaces$3.svgAttrs).style({ + position: "absolute", + left: "-10000px", + top: "-10000px", + width: "9000px", + height: "9000px", + "z-index": "1" + }); + }); + var testref = Lib$1J.ensureSingle(tester2, "path", "js-reference-point", function(s) { + s.attr("d", "M0,0H1V1H0Z").style({ + "stroke-width": 0, + fill: "black" + }); + }); + drawing.tester = tester2; + drawing.testref = testref; +}; +drawing.savedBBoxes = {}; +var savedBBoxesCount = 0; +var maxSavedBBoxes = 1e4; +drawing.bBox = function(node, inTester, hash) { + if (!hash) hash = nodeHash(node); + var out; + if (hash) { + out = drawing.savedBBoxes[hash]; + if (out) return Lib$1J.extendFlat({}, out); + } else if (node.childNodes.length === 1) { + var innerNode = node.childNodes[0]; + hash = nodeHash(innerNode); + if (hash) { + var x = +innerNode.getAttribute("x") || 0; + var y = +innerNode.getAttribute("y") || 0; + var transform = innerNode.getAttribute("transform"); + if (!transform) { + var innerBB = drawing.bBox(innerNode, false, hash); + if (x) { + innerBB.left += x; + innerBB.right += x; + } + if (y) { + innerBB.top += y; + innerBB.bottom += y; + } + return innerBB; + } + hash += "~" + x + "~" + y + "~" + transform; + out = drawing.savedBBoxes[hash]; + if (out) return Lib$1J.extendFlat({}, out); + } + } + var testNode, tester2; + if (inTester) { + testNode = node; + } else { + tester2 = drawing.tester.node(); + testNode = node.cloneNode(true); + tester2.appendChild(testNode); + } + d3$z.select(testNode).attr("transform", null).call(svgTextUtils$f.positionText, 0, 0); + var testRect = testNode.getBoundingClientRect(); + var refRect = drawing.testref.node().getBoundingClientRect(); + if (!inTester) tester2.removeChild(testNode); + var bb = { + height: testRect.height, + width: testRect.width, + left: testRect.left - refRect.left, + top: testRect.top - refRect.top, + right: testRect.right - refRect.left, + bottom: testRect.bottom - refRect.top + }; + if (savedBBoxesCount >= maxSavedBBoxes) { + drawing.savedBBoxes = {}; + savedBBoxesCount = 0; + } + if (hash) drawing.savedBBoxes[hash] = bb; + savedBBoxesCount++; + return Lib$1J.extendFlat({}, bb); +}; +function nodeHash(node) { + var inputText = node.getAttribute("data-unformatted"); + if (inputText === null) return; + return inputText + node.getAttribute("data-math") + node.getAttribute("text-anchor") + node.getAttribute("style"); +} +drawing.setClipUrl = function(s, localId, gd) { + s.attr("clip-path", getFullUrl(localId, gd)); +}; +function getFullUrl(localId, gd) { + if (!localId) return null; + var context2 = gd._context; + var baseUrl = context2._exportedPlot ? "" : context2._baseUrl || ""; + return baseUrl ? "url('" + baseUrl + "#" + localId + "')" : "url(#" + localId + ")"; +} +drawing.getTranslate = function(element) { + var re2 = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/; + var getter = element.attr ? "attr" : "getAttribute"; + var transform = element[getter]("transform") || ""; + var translate2 = transform.replace(re2, function(match, p1, p2) { + return [p1, p2].join(" "); + }).split(" "); + return { + x: +translate2[0] || 0, + y: +translate2[1] || 0 + }; +}; +drawing.setTranslate = function(element, x, y) { + var re2 = /(\btranslate\(.*?\);?)/; + var getter = element.attr ? "attr" : "getAttribute"; + var setter = element.attr ? "attr" : "setAttribute"; + var transform = element[getter]("transform") || ""; + x = x || 0; + y = y || 0; + transform = transform.replace(re2, "").trim(); + transform += strTranslate$c(x, y); + transform = transform.trim(); + element[setter]("transform", transform); + return transform; +}; +drawing.getScale = function(element) { + var re2 = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/; + var getter = element.attr ? "attr" : "getAttribute"; + var transform = element[getter]("transform") || ""; + var translate2 = transform.replace(re2, function(match, p1, p2) { + return [p1, p2].join(" "); + }).split(" "); + return { + x: +translate2[0] || 1, + y: +translate2[1] || 1 + }; +}; +drawing.setScale = function(element, x, y) { + var re2 = /(\bscale\(.*?\);?)/; + var getter = element.attr ? "attr" : "getAttribute"; + var setter = element.attr ? "attr" : "setAttribute"; + var transform = element[getter]("transform") || ""; + x = x || 1; + y = y || 1; + transform = transform.replace(re2, "").trim(); + transform += "scale(" + x + "," + y + ")"; + transform = transform.trim(); + element[setter]("transform", transform); + return transform; +}; +var SCALE_RE = /\s*sc.*/; +drawing.setPointGroupScale = function(selection, xScale, yScale) { + xScale = xScale || 1; + yScale = yScale || 1; + if (!selection) return; + var scale2 = xScale === 1 && yScale === 1 ? "" : "scale(" + xScale + "," + yScale + ")"; + selection.each(function() { + var t = (this.getAttribute("transform") || "").replace(SCALE_RE, ""); + t += scale2; + t = t.trim(); + this.setAttribute("transform", t); + }); +}; +var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/; +drawing.setTextPointsScale = function(selection, xScale, yScale) { + if (!selection) return; + selection.each(function() { + var transforms; + var el = d3$z.select(this); + var text = el.select("text"); + if (!text.node()) return; + var x = parseFloat(text.attr("x") || 0); + var y = parseFloat(text.attr("y") || 0); + var existingTransform = (el.attr("transform") || "").match(TEXT_POINT_LAST_TRANSLATION_RE); + if (xScale === 1 && yScale === 1) { + transforms = []; + } else { + transforms = [ + strTranslate$c(x, y), + "scale(" + xScale + "," + yScale + ")", + strTranslate$c(-x, -y) + ]; + } + if (existingTransform) { + transforms.push(existingTransform); + } + el.attr("transform", transforms.join("")); + }); +}; +function getMarkerStandoff(d, trace) { + var standoff; + if (d) standoff = d.mf; + if (standoff === void 0) { + standoff = trace.marker ? trace.marker.standoff || 0 : 0; + } + if (!trace._geo && !trace._xA) { + return -standoff; + } + return standoff; +} +drawing.getMarkerStandoff = getMarkerStandoff; +var atan2 = Math.atan2; +var cos = Math.cos; +var sin = Math.sin; +function rotate$1(t, xy) { + var x = xy[0]; + var y = xy[1]; + return [ + x * cos(t) - y * sin(t), + x * sin(t) + y * cos(t) + ]; +} +var previousLon; +var previousLat; +var previousX; +var previousY; +var previousI; +var previousTraceUid; +function getMarkerAngle(d, trace) { + var angle = d.ma; + if (angle === void 0) { + angle = trace.marker.angle; + if (!angle || Lib$1J.isArrayOrTypedArray(angle)) { + angle = 0; + } + } + var x, y; + var ref2 = trace.marker.angleref; + if (ref2 === "previous" || ref2 === "north") { + if (trace._geo) { + var p = trace._geo.project(d.lonlat); + x = p[0]; + y = p[1]; + } else { + var xa = trace._xA; + var ya = trace._yA; + if (xa && ya) { + x = xa.c2p(d.x); + y = ya.c2p(d.y); + } else { + return 90; + } + } + if (trace._geo) { + var lon = d.lonlat[0]; + var lat = d.lonlat[1]; + var north = trace._geo.project([ + lon, + lat + 1e-5 + // epsilon + ]); + var east = trace._geo.project([ + lon + 1e-5, + // epsilon + lat + ]); + var u = atan2( + east[1] - y, + east[0] - x + ); + var v = atan2( + north[1] - y, + north[0] - x + ); + var t; + if (ref2 === "north") { + t = angle / 180 * Math.PI; + } else if (ref2 === "previous") { + var lon1 = lon / 180 * Math.PI; + var lat1 = lat / 180 * Math.PI; + var lon2 = previousLon / 180 * Math.PI; + var lat2 = previousLat / 180 * Math.PI; + var dLon = lon2 - lon1; + var deltaY = cos(lat2) * sin(dLon); + var deltaX = sin(lat2) * cos(lat1) - cos(lat2) * sin(lat1) * cos(dLon); + t = -atan2( + deltaY, + deltaX + ) - Math.PI; + previousLon = lon; + previousLat = lat; + } + var A2 = rotate$1(u, [cos(t), 0]); + var B2 = rotate$1(v, [sin(t), 0]); + angle = atan2( + A2[1] + B2[1], + A2[0] + B2[0] + ) / Math.PI * 180; + if (ref2 === "previous" && !(previousTraceUid === trace.uid && d.i === previousI + 1)) { + angle = null; + } + } + if (ref2 === "previous" && !trace._geo) { + if (previousTraceUid === trace.uid && d.i === previousI + 1 && isNumeric$o(x) && isNumeric$o(y)) { + var dX = x - previousX; + var dY = y - previousY; + var shape = trace.line ? trace.line.shape || "" : ""; + var lastShapeChar = shape.slice(shape.length - 1); + if (lastShapeChar === "h") dY = 0; + if (lastShapeChar === "v") dX = 0; + angle += atan2(dY, dX) / Math.PI * 180 + 90; + } else { + angle = null; + } + } + } + previousX = x; + previousY = y; + previousI = d.i; + previousTraceUid = trace.uid; + return angle; +} +drawing.getMarkerAngle = getMarkerAngle; +var drawingExports = drawing$1.exports; +var d3$y = d3Exports; +var isNumeric$n = fastIsnumeric; +var Plots$c = plotsExports; +var Registry$K = registry; +var Lib$1I = libExports; +var strTranslate$b = Lib$1I.strTranslate; +var Drawing$u = drawingExports; +var Color$I = colorExports; +var svgTextUtils$e = svg_text_utils; +var interactConstants = interactions; +var OPPOSITE_SIDE$1 = alignment$1.OPPOSITE_SIDE; +var numStripRE = / [XY][0-9]* /; +var SUBTITLE_PADDING_MATHJAX_EM = 1.6; +var SUBTITLE_PADDING_EM = 1.6; +function draw$e(gd, titleClass, options) { + var fullLayout = gd._fullLayout; + var cont = options.propContainer; + var prop = options.propName; + var placeholder = options.placeholder; + var traceIndex = options.traceIndex; + var avoid = options.avoid || {}; + var attributes2 = options.attributes; + var transform = options.transform; + var group = options.containerGroup; + var opacity = 1; + var title = cont.title; + var txt = (title && title.text ? title.text : "").trim(); + var titleIsPlaceholder = false; + var font2 = title && title.font ? title.font : {}; + var fontFamily = font2.family; + var fontSize = font2.size; + var fontColor = font2.color; + var fontWeight = font2.weight; + var fontStyle = font2.style; + var fontVariant = font2.variant; + var fontTextcase = font2.textcase; + var fontLineposition = font2.lineposition; + var fontShadow = font2.shadow; + var subtitleProp = options.subtitlePropName; + var subtitleEnabled = !!subtitleProp; + var subtitlePlaceholder = options.subtitlePlaceholder; + var subtitle = (cont.title || {}).subtitle || { text: "", font: {} }; + var subtitleTxt = subtitle.text.trim(); + var subtitleIsPlaceholder = false; + var subtitleOpacity = 1; + var subtitleFont = subtitle.font; + var subFontFamily = subtitleFont.family; + var subFontSize = subtitleFont.size; + var subFontColor = subtitleFont.color; + var subFontWeight = subtitleFont.weight; + var subFontStyle = subtitleFont.style; + var subFontVariant = subtitleFont.variant; + var subFontTextcase = subtitleFont.textcase; + var subFontLineposition = subtitleFont.lineposition; + var subFontShadow = subtitleFont.shadow; + var editAttr; + if (prop === "title.text") editAttr = "titleText"; + else if (prop.indexOf("axis") !== -1) editAttr = "axisTitleText"; + else if (prop.indexOf("colorbar" !== -1)) editAttr = "colorbarTitleText"; + var editable = gd._context.edits[editAttr]; + function matchesPlaceholder(text, placeholder2) { + if (text === void 0 || placeholder2 === void 0) return false; + return text.replace(numStripRE, " % ") === placeholder2.replace(numStripRE, " % "); + } + if (txt === "") opacity = 0; + else if (matchesPlaceholder(txt, placeholder)) { + if (!editable) txt = ""; + opacity = 0.2; + titleIsPlaceholder = true; + } + if (subtitleEnabled) { + if (subtitleTxt === "") subtitleOpacity = 0; + else if (matchesPlaceholder(subtitleTxt, subtitlePlaceholder)) { + if (!editable) subtitleTxt = ""; + subtitleOpacity = 0.2; + subtitleIsPlaceholder = true; + } + } + if (options._meta) { + txt = Lib$1I.templateString(txt, options._meta); + } else if (fullLayout._meta) { + txt = Lib$1I.templateString(txt, fullLayout._meta); + } + var elShouldExist = txt || subtitleTxt || editable; + var hColorbarMoveTitle; + if (!group) { + group = Lib$1I.ensureSingle(fullLayout._infolayer, "g", "g-" + titleClass); + hColorbarMoveTitle = fullLayout._hColorbarMoveTitle; + } + var el = group.selectAll("text." + titleClass).data(elShouldExist ? [0] : []); + el.enter().append("text"); + el.text(txt).attr("class", titleClass); + el.exit().remove(); + var subtitleEl = null; + var subtitleClass = titleClass + "-subtitle"; + var subtitleElShouldExist = subtitleTxt || editable; + if (subtitleEnabled && subtitleElShouldExist) { + subtitleEl = group.selectAll("text." + subtitleClass).data(subtitleElShouldExist ? [0] : []); + subtitleEl.enter().append("text"); + subtitleEl.text(subtitleTxt).attr("class", subtitleClass); + subtitleEl.exit().remove(); + } + if (!elShouldExist) return group; + function titleLayout(titleEl, subtitleEl2) { + Lib$1I.syncOrAsync([drawTitle2, scootTitle], { title: titleEl, subtitle: subtitleEl2 }); + } + function drawTitle2(titleAndSubtitleEls) { + var titleEl = titleAndSubtitleEls.title; + var subtitleEl2 = titleAndSubtitleEls.subtitle; + var transformVal; + if (!transform && hColorbarMoveTitle) { + transform = {}; + } + if (transform) { + transformVal = ""; + if (transform.rotate) { + transformVal += "rotate(" + [transform.rotate, attributes2.x, attributes2.y] + ")"; + } + if (transform.offset || hColorbarMoveTitle) { + transformVal += strTranslate$b(0, (transform.offset || 0) - (hColorbarMoveTitle || 0)); + } + } else { + transformVal = null; + } + titleEl.attr("transform", transformVal); + function adjustSubtitlePosition(titleElMathGroup2) { + if (!titleElMathGroup2) return; + var subtitleElement = d3$y.select(titleElMathGroup2.node().parentNode).select("." + subtitleClass); + if (!subtitleElement.empty()) { + var titleElMathBbox2 = titleElMathGroup2.node().getBBox(); + if (titleElMathBbox2.height) { + var subtitleY3 = titleElMathBbox2.y + titleElMathBbox2.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize; + subtitleElement.attr("y", subtitleY3); + } + } + } + titleEl.style("opacity", opacity * Color$I.opacity(fontColor)).call(Drawing$u.font, { + color: Color$I.rgb(fontColor), + size: d3$y.round(fontSize, 2), + family: fontFamily, + weight: fontWeight, + style: fontStyle, + variant: fontVariant, + textcase: fontTextcase, + shadow: fontShadow, + lineposition: fontLineposition + }).attr(attributes2).call(svgTextUtils$e.convertToTspans, gd, adjustSubtitlePosition); + if (subtitleEl2) { + var titleElMathGroup = group.select("." + titleClass + "-math-group"); + var titleElBbox2 = titleEl.node().getBBox(); + var titleElMathBbox = titleElMathGroup.node() ? titleElMathGroup.node().getBBox() : void 0; + var subtitleY2 = titleElMathBbox ? titleElMathBbox.y + titleElMathBbox.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize : titleElBbox2.y + titleElBbox2.height + SUBTITLE_PADDING_EM * subFontSize; + var subtitleAttributes = Lib$1I.extendFlat({}, attributes2, { + y: subtitleY2 + }); + subtitleEl2.attr("transform", transformVal); + subtitleEl2.style("opacity", subtitleOpacity * Color$I.opacity(subFontColor)).call(Drawing$u.font, { + color: Color$I.rgb(subFontColor), + size: d3$y.round(subFontSize, 2), + family: subFontFamily, + weight: subFontWeight, + style: subFontStyle, + variant: subFontVariant, + textcase: subFontTextcase, + shadow: subFontShadow, + lineposition: subFontLineposition + }).attr(subtitleAttributes).call(svgTextUtils$e.convertToTspans, gd); + } + return Plots$c.previousPromises(gd); + } + function scootTitle(titleAndSubtitleEls) { + var titleElIn = titleAndSubtitleEls.title; + var titleGroup = d3$y.select(titleElIn.node().parentNode); + if (avoid && avoid.selection && avoid.side && txt) { + titleGroup.attr("transform", null); + var backside = OPPOSITE_SIDE$1[avoid.side]; + var shiftSign = avoid.side === "left" || avoid.side === "top" ? -1 : 1; + var pad2 = isNumeric$n(avoid.pad) ? avoid.pad : 2; + var titlebb = Drawing$u.bBox(titleGroup.node()); + var reservedMargins = { t: 0, b: 0, l: 0, r: 0 }; + var margins = gd._fullLayout._reservedMargin; + for (var key in margins) { + for (var side in margins[key]) { + var val = margins[key][side]; + reservedMargins[side] = Math.max(reservedMargins[side], val); + } + } + var paperbb = { + left: reservedMargins.l, + top: reservedMargins.t, + right: fullLayout.width - reservedMargins.r, + bottom: fullLayout.height - reservedMargins.b + }; + var maxshift = avoid.maxShift || shiftSign * (paperbb[avoid.side] - titlebb[avoid.side]); + var shift = 0; + if (maxshift < 0) { + shift = maxshift; + } else { + var offsetLeft = avoid.offsetLeft || 0; + var offsetTop = avoid.offsetTop || 0; + titlebb.left -= offsetLeft; + titlebb.right -= offsetLeft; + titlebb.top -= offsetTop; + titlebb.bottom -= offsetTop; + avoid.selection.each(function() { + var avoidbb = Drawing$u.bBox(this); + if (Lib$1I.bBoxIntersect(titlebb, avoidbb, pad2)) { + shift = Math.max(shift, shiftSign * (avoidbb[avoid.side] - titlebb[backside]) + pad2); + } + }); + shift = Math.min(maxshift, shift); + cont._titleScoot = Math.abs(shift); + } + if (shift > 0 || maxshift < 0) { + var shiftTemplate = { + left: [-shift, 0], + right: [shift, 0], + top: [0, -shift], + bottom: [0, shift] + }[avoid.side]; + titleGroup.attr("transform", strTranslate$b(shiftTemplate[0], shiftTemplate[1])); + } + } + } + el.call(titleLayout, subtitleEl); + function setPlaceholder(element, placeholderText) { + element.text(placeholderText).on("mouseover.opacity", function() { + d3$y.select(this).transition().duration(interactConstants.SHOW_PLACEHOLDER).style("opacity", 1); + }).on("mouseout.opacity", function() { + d3$y.select(this).transition().duration(interactConstants.HIDE_PLACEHOLDER).style("opacity", 0); + }); + } + if (editable) { + if (!txt) { + setPlaceholder(el, placeholder); + titleIsPlaceholder = true; + } else el.on(".opacity", null); + el.call(svgTextUtils$e.makeEditable, { gd }).on("edit", function(text) { + if (traceIndex !== void 0) { + Registry$K.call("_guiRestyle", gd, prop, text, traceIndex); + } else { + Registry$K.call("_guiRelayout", gd, prop, text); + } + }).on("cancel", function() { + this.text(this.attr("data-unformatted")).call(titleLayout); + }).on("input", function(d) { + this.text(d || " ").call(svgTextUtils$e.positionText, attributes2.x, attributes2.y); + }); + if (subtitleEnabled) { + if (subtitleEnabled && !txt) { + var titleElBbox = el.node().getBBox(); + var subtitleY = titleElBbox.y + titleElBbox.height + SUBTITLE_PADDING_EM * subFontSize; + subtitleEl.attr("y", subtitleY); + } + if (!subtitleTxt) { + setPlaceholder(subtitleEl, subtitlePlaceholder); + subtitleIsPlaceholder = true; + } else subtitleEl.on(".opacity", null); + subtitleEl.call(svgTextUtils$e.makeEditable, { gd }).on("edit", function(text) { + Registry$K.call("_guiRelayout", gd, "title.subtitle.text", text); + }).on("cancel", function() { + this.text(this.attr("data-unformatted")).call(titleLayout); + }).on("input", function(d) { + this.text(d || " ").call(svgTextUtils$e.positionText, subtitleEl.attr("x"), subtitleEl.attr("y")); + }); + } + } + el.classed("js-placeholder", titleIsPlaceholder); + if (subtitleEl) subtitleEl.classed("js-placeholder", subtitleIsPlaceholder); + return group; +} +var titles = { + draw: draw$e, + SUBTITLE_PADDING_EM, + SUBTITLE_PADDING_MATHJAX_EM +}; +var d3$x = d3Exports; +var utcFormat = require$$1$1.utcFormat; +var Lib$1H = libExports; +var numberFormat = Lib$1H.numberFormat; +var isNumeric$m = fastIsnumeric; +var cleanNumber$1 = Lib$1H.cleanNumber; +var ms2DateTime = Lib$1H.ms2DateTime; +var dateTime2ms$1 = Lib$1H.dateTime2ms; +var ensureNumber2 = Lib$1H.ensureNumber; +var isArrayOrTypedArray$8 = Lib$1H.isArrayOrTypedArray; +var numConstants$3 = numerical; +var FP_SAFE$1 = numConstants$3.FP_SAFE; +var BADNUM$9 = numConstants$3.BADNUM; +var LOG_CLIP$1 = numConstants$3.LOG_CLIP; +var ONEWEEK$2 = numConstants$3.ONEWEEK; +var ONEDAY$1 = numConstants$3.ONEDAY; +var ONEHOUR$1 = numConstants$3.ONEHOUR; +var ONEMIN$1 = numConstants$3.ONEMIN; +var ONESEC$1 = numConstants$3.ONESEC; +var axisIds$8 = axis_ids; +var constants$R = constants$U; +var HOUR_PATTERN = constants$R.HOUR_PATTERN; +var WEEKDAY_PATTERN = constants$R.WEEKDAY_PATTERN; +function fromLog(v) { + return Math.pow(10, v); +} +function isValidCategory(v) { + return v !== null && v !== void 0; +} +var set_convert = function setConvert(ax, fullLayout) { + fullLayout = fullLayout || {}; + var axId = ax._id || "x"; + var axLetter = axId.charAt(0); + function toLog(v, clip) { + if (v > 0) return Math.log(v) / Math.LN10; + else if (v <= 0 && clip && ax.range && ax.range.length === 2) { + var r0 = ax.range[0]; + var r1 = ax.range[1]; + return 0.5 * (r0 + r1 - 2 * LOG_CLIP$1 * Math.abs(r0 - r1)); + } else return BADNUM$9; + } + function dt2ms(v, _2, calendar, opts) { + if ((opts || {}).msUTC && isNumeric$m(v)) { + return +v; + } + var ms = dateTime2ms$1(v, calendar || ax.calendar); + if (ms === BADNUM$9) { + if (isNumeric$m(v)) { + v = +v; + var msecTenths = Math.floor(Lib$1H.mod(v + 0.05, 1) * 10); + var msRounded = Math.round(v - msecTenths / 10); + ms = dateTime2ms$1(new Date(msRounded)) + msecTenths / 10; + } else return BADNUM$9; + } + return ms; + } + function ms2dt(v, r, calendar) { + return ms2DateTime(v, r, calendar || ax.calendar); + } + function getCategoryName(v) { + return ax._categories[Math.round(v)]; + } + function setCategoryIndex(v) { + if (isValidCategory(v)) { + if (ax._categoriesMap === void 0) { + ax._categoriesMap = {}; + } + if (ax._categoriesMap[v] !== void 0) { + return ax._categoriesMap[v]; + } else { + ax._categories.push(typeof v === "number" ? String(v) : v); + var curLength = ax._categories.length - 1; + ax._categoriesMap[v] = curLength; + return curLength; + } + } + return BADNUM$9; + } + function setMultiCategoryIndex(arrayIn, len) { + var arrayOut = new Array(len); + for (var i = 0; i < len; i++) { + var v0 = (arrayIn[0] || [])[i]; + var v1 = (arrayIn[1] || [])[i]; + arrayOut[i] = getCategoryIndex([v0, v1]); + } + return arrayOut; + } + function getCategoryIndex(v) { + if (ax._categoriesMap) { + return ax._categoriesMap[v]; + } + } + function getCategoryPosition(v) { + var index2 = getCategoryIndex(v); + if (index2 !== void 0) return index2; + if (isNumeric$m(v)) return +v; + } + function getRangePosition(v) { + return isNumeric$m(v) ? +v : getCategoryIndex(v); + } + function _l2p(v, m, b) { + return d3$x.round(b + m * v, 2); + } + function _p2l(px2, m, b) { + return (px2 - b) / m; + } + var l2p = function l2p2(v) { + if (!isNumeric$m(v)) return BADNUM$9; + return _l2p(v, ax._m, ax._b); + }; + var p2l = function(px2) { + return _p2l(px2, ax._m, ax._b); + }; + if (ax.rangebreaks) { + var isY = axLetter === "y"; + l2p = function(v) { + if (!isNumeric$m(v)) return BADNUM$9; + var len = ax._rangebreaks.length; + if (!len) return _l2p(v, ax._m, ax._b); + var flip = isY; + if (ax.range[0] > ax.range[1]) flip = !flip; + var signAx = flip ? -1 : 1; + var pos = signAx * v; + var q = 0; + for (var i = 0; i < len; i++) { + var min = signAx * ax._rangebreaks[i].min; + var max = signAx * ax._rangebreaks[i].max; + if (pos < min) break; + if (pos > max) q = i + 1; + else { + q = pos < (min + max) / 2 ? i : i + 1; + break; + } + } + var b2 = ax._B[q] || 0; + if (!isFinite(b2)) return 0; + return _l2p(v, ax._m2, b2); + }; + p2l = function(px2) { + var len = ax._rangebreaks.length; + if (!len) return _p2l(px2, ax._m, ax._b); + var q = 0; + for (var i = 0; i < len; i++) { + if (px2 < ax._rangebreaks[i].pmin) break; + if (px2 > ax._rangebreaks[i].pmax) q = i + 1; + } + return _p2l(px2, ax._m2, ax._B[q]); + }; + } + ax.c2l = ax.type === "log" ? toLog : ensureNumber2; + ax.l2c = ax.type === "log" ? fromLog : ensureNumber2; + ax.l2p = l2p; + ax.p2l = p2l; + ax.c2p = ax.type === "log" ? function(v, clip) { + return l2p(toLog(v, clip)); + } : l2p; + ax.p2c = ax.type === "log" ? function(px2) { + return fromLog(p2l(px2)); + } : p2l; + if (["linear", "-"].indexOf(ax.type) !== -1) { + ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber$1; + ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber2; + ax.d2p = ax.r2p = function(v) { + return ax.l2p(cleanNumber$1(v)); + }; + ax.p2d = ax.p2r = p2l; + ax.cleanPos = ensureNumber2; + } else if (ax.type === "log") { + ax.d2r = ax.d2l = function(v, clip) { + return toLog(cleanNumber$1(v), clip); + }; + ax.r2d = ax.r2c = function(v) { + return fromLog(cleanNumber$1(v)); + }; + ax.d2c = ax.r2l = cleanNumber$1; + ax.c2d = ax.l2r = ensureNumber2; + ax.c2r = toLog; + ax.l2d = fromLog; + ax.d2p = function(v, clip) { + return ax.l2p(ax.d2r(v, clip)); + }; + ax.p2d = function(px2) { + return fromLog(p2l(px2)); + }; + ax.r2p = function(v) { + return ax.l2p(cleanNumber$1(v)); + }; + ax.p2r = p2l; + ax.cleanPos = ensureNumber2; + } else if (ax.type === "date") { + ax.d2r = ax.r2d = Lib$1H.identity; + ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; + ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; + ax.d2p = ax.r2p = function(v, _2, calendar) { + return ax.l2p(dt2ms(v, 0, calendar)); + }; + ax.p2d = ax.p2r = function(px2, r, calendar) { + return ms2dt(p2l(px2), r, calendar); + }; + ax.cleanPos = function(v) { + return Lib$1H.cleanDate(v, BADNUM$9, ax.calendar); + }; + } else if (ax.type === "category") { + ax.d2c = ax.d2l = setCategoryIndex; + ax.r2d = ax.c2d = ax.l2d = getCategoryName; + ax.d2r = ax.d2l_noadd = getCategoryPosition; + ax.r2c = function(v) { + var index2 = getRangePosition(v); + return index2 !== void 0 ? index2 : ax.fraction2r(0.5); + }; + ax.l2r = ax.c2r = ensureNumber2; + ax.r2l = getRangePosition; + ax.d2p = function(v) { + return ax.l2p(ax.r2c(v)); + }; + ax.p2d = function(px2) { + return getCategoryName(p2l(px2)); + }; + ax.r2p = ax.d2p; + ax.p2r = p2l; + ax.cleanPos = function(v) { + if (typeof v === "string" && v !== "") return v; + return ensureNumber2(v); + }; + } else if (ax.type === "multicategory") { + ax.r2d = ax.c2d = ax.l2d = getCategoryName; + ax.d2r = ax.d2l_noadd = getCategoryPosition; + ax.r2c = function(v) { + var index2 = getCategoryPosition(v); + return index2 !== void 0 ? index2 : ax.fraction2r(0.5); + }; + ax.r2c_just_indices = getCategoryIndex; + ax.l2r = ax.c2r = ensureNumber2; + ax.r2l = getCategoryPosition; + ax.d2p = function(v) { + return ax.l2p(ax.r2c(v)); + }; + ax.p2d = function(px2) { + return getCategoryName(p2l(px2)); + }; + ax.r2p = ax.d2p; + ax.p2r = p2l; + ax.cleanPos = function(v) { + if (Array.isArray(v) || typeof v === "string" && v !== "") return v; + return ensureNumber2(v); + }; + ax.setupMultiCategory = function(fullData) { + var traceIndices = ax._traceIndices; + var i, j; + var group = ax._matchGroup; + if (group && ax._categories.length === 0) { + for (var axId2 in group) { + if (axId2 !== axId) { + var ax2 = fullLayout[axisIds$8.id2name(axId2)]; + traceIndices = traceIndices.concat(ax2._traceIndices); + } + } + } + var seen = [[0, {}], [0, {}]]; + var list = []; + for (i = 0; i < traceIndices.length; i++) { + var trace = fullData[traceIndices[i]]; + if (axLetter in trace) { + var arrayIn = trace[axLetter]; + var len = trace._length || Lib$1H.minRowLength(arrayIn); + if (isArrayOrTypedArray$8(arrayIn[0]) && isArrayOrTypedArray$8(arrayIn[1])) { + for (j = 0; j < len; j++) { + var v0 = arrayIn[0][j]; + var v1 = arrayIn[1][j]; + if (isValidCategory(v0) && isValidCategory(v1)) { + list.push([v0, v1]); + if (!(v0 in seen[0][1])) { + seen[0][1][v0] = seen[0][0]++; + } + if (!(v1 in seen[1][1])) { + seen[1][1][v1] = seen[1][0]++; + } + } + } + } + } + } + list.sort(function(a, b) { + var ind0 = seen[0][1]; + var d = ind0[a[0]] - ind0[b[0]]; + if (d) return d; + var ind1 = seen[1][1]; + return ind1[a[1]] - ind1[b[1]]; + }); + for (i = 0; i < list.length; i++) { + setCategoryIndex(list[i]); + } + }; + } + ax.fraction2r = function(v) { + var rl0 = ax.r2l(ax.range[0]); + var rl1 = ax.r2l(ax.range[1]); + return ax.l2r(rl0 + v * (rl1 - rl0)); + }; + ax.r2fraction = function(v) { + var rl0 = ax.r2l(ax.range[0]); + var rl1 = ax.r2l(ax.range[1]); + return (ax.r2l(v) - rl0) / (rl1 - rl0); + }; + ax.limitRange = function(rangeAttr) { + var minallowed = ax.minallowed; + var maxallowed = ax.maxallowed; + if (minallowed === void 0 && maxallowed === void 0) return; + if (!rangeAttr) rangeAttr = "range"; + var range = Lib$1H.nestedProperty(ax, rangeAttr).get(); + var rng = Lib$1H.simpleMap(range, ax.r2l); + var axrev = rng[1] < rng[0]; + if (axrev) rng.reverse(); + var bounds = Lib$1H.simpleMap([minallowed, maxallowed], ax.r2l); + if (minallowed !== void 0 && rng[0] < bounds[0]) range[axrev ? 1 : 0] = minallowed; + if (maxallowed !== void 0 && rng[1] > bounds[1]) range[axrev ? 0 : 1] = maxallowed; + if (range[0] === range[1]) { + var minL = ax.l2r(minallowed); + var maxL = ax.l2r(maxallowed); + if (minallowed !== void 0) { + var _max = minL + 1; + if (maxallowed !== void 0) _max = Math.min(_max, maxL); + range[axrev ? 1 : 0] = _max; + } + if (maxallowed !== void 0) { + var _min = maxL + 1; + if (minallowed !== void 0) _min = Math.max(_min, minL); + range[axrev ? 0 : 1] = _min; + } + } + }; + ax.cleanRange = function(rangeAttr, opts) { + ax._cleanRange(rangeAttr, opts); + ax.limitRange(rangeAttr); + }; + ax._cleanRange = function(rangeAttr, opts) { + if (!opts) opts = {}; + if (!rangeAttr) rangeAttr = "range"; + var range = Lib$1H.nestedProperty(ax, rangeAttr).get(); + var i, dflt; + if (ax.type === "date") dflt = Lib$1H.dfltRange(ax.calendar); + else if (axLetter === "y") dflt = constants$R.DFLTRANGEY; + else if (ax._name === "realaxis") dflt = [0, 1]; + else dflt = opts.dfltRange || constants$R.DFLTRANGEX; + dflt = dflt.slice(); + if (ax.rangemode === "tozero" || ax.rangemode === "nonnegative") { + dflt[0] = 0; + } + if (!range || range.length !== 2) { + Lib$1H.nestedProperty(ax, rangeAttr).set(dflt); + return; + } + var nullRange0 = range[0] === null; + var nullRange1 = range[1] === null; + if (ax.type === "date" && !ax.autorange) { + range[0] = Lib$1H.cleanDate(range[0], BADNUM$9, ax.calendar); + range[1] = Lib$1H.cleanDate(range[1], BADNUM$9, ax.calendar); + } + for (i = 0; i < 2; i++) { + if (ax.type === "date") { + if (!Lib$1H.isDateTime(range[i], ax.calendar)) { + ax[rangeAttr] = dflt; + break; + } + if (ax.r2l(range[0]) === ax.r2l(range[1])) { + var linCenter = Lib$1H.constrain( + ax.r2l(range[0]), + Lib$1H.MIN_MS + 1e3, + Lib$1H.MAX_MS - 1e3 + ); + range[0] = ax.l2r(linCenter - 1e3); + range[1] = ax.l2r(linCenter + 1e3); + break; + } + } else { + if (!isNumeric$m(range[i])) { + if (!(nullRange0 || nullRange1) && isNumeric$m(range[1 - i])) { + range[i] = range[1 - i] * (i ? 10 : 0.1); + } else { + ax[rangeAttr] = dflt; + break; + } + } + if (range[i] < -FP_SAFE$1) range[i] = -FP_SAFE$1; + else if (range[i] > FP_SAFE$1) range[i] = FP_SAFE$1; + if (range[0] === range[1]) { + var inc = Math.max(1, Math.abs(range[0] * 1e-6)); + range[0] -= inc; + range[1] += inc; + } + } + } + }; + ax.setScale = function(usePrivateRange) { + var gs = fullLayout._size; + if (ax.overlaying) { + var ax2 = axisIds$8.getFromId({ _fullLayout: fullLayout }, ax.overlaying); + ax.domain = ax2.domain; + } + var rangeAttr = usePrivateRange && ax._r ? "_r" : "range"; + var calendar = ax.calendar; + ax.cleanRange(rangeAttr); + var rl0 = ax.r2l(ax[rangeAttr][0], calendar); + var rl1 = ax.r2l(ax[rangeAttr][1], calendar); + var isY2 = axLetter === "y"; + if (isY2) { + ax._offset = gs.t + (1 - ax.domain[1]) * gs.h; + ax._length = gs.h * (ax.domain[1] - ax.domain[0]); + ax._m = ax._length / (rl0 - rl1); + ax._b = -ax._m * rl1; + } else { + ax._offset = gs.l + ax.domain[0] * gs.w; + ax._length = gs.w * (ax.domain[1] - ax.domain[0]); + ax._m = ax._length / (rl1 - rl0); + ax._b = -ax._m * rl0; + } + ax._rangebreaks = []; + ax._lBreaks = 0; + ax._m2 = 0; + ax._B = []; + if (ax.rangebreaks) { + var i, brk; + ax._rangebreaks = ax.locateBreaks( + Math.min(rl0, rl1), + Math.max(rl0, rl1) + ); + if (ax._rangebreaks.length) { + for (i = 0; i < ax._rangebreaks.length; i++) { + brk = ax._rangebreaks[i]; + ax._lBreaks += Math.abs(brk.max - brk.min); + } + var flip = isY2; + if (rl0 > rl1) flip = !flip; + if (flip) ax._rangebreaks.reverse(); + var sign2 = flip ? -1 : 1; + ax._m2 = sign2 * ax._length / (Math.abs(rl1 - rl0) - ax._lBreaks); + ax._B.push(-ax._m2 * (isY2 ? rl1 : rl0)); + for (i = 0; i < ax._rangebreaks.length; i++) { + brk = ax._rangebreaks[i]; + ax._B.push( + ax._B[ax._B.length - 1] - sign2 * ax._m2 * (brk.max - brk.min) + ); + } + for (i = 0; i < ax._rangebreaks.length; i++) { + brk = ax._rangebreaks[i]; + brk.pmin = l2p(brk.min); + brk.pmax = l2p(brk.max); + } + } + } + if (!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) { + fullLayout._replotting = false; + throw new Error("Something went wrong with axis scaling"); + } + }; + ax.maskBreaks = function(v) { + var rangebreaksIn = ax.rangebreaks || []; + var bnds, b0, b1, vb, vDate; + if (!rangebreaksIn._cachedPatterns) { + rangebreaksIn._cachedPatterns = rangebreaksIn.map(function(brk2) { + return brk2.enabled && brk2.bounds ? Lib$1H.simpleMap( + brk2.bounds, + brk2.pattern ? cleanNumber$1 : ax.d2c + // case of pattern: '' + ) : null; + }); + } + if (!rangebreaksIn._cachedValues) { + rangebreaksIn._cachedValues = rangebreaksIn.map(function(brk2) { + return brk2.enabled && brk2.values ? Lib$1H.simpleMap(brk2.values, ax.d2c).sort(Lib$1H.sorterAsc) : null; + }); + } + for (var i = 0; i < rangebreaksIn.length; i++) { + var brk = rangebreaksIn[i]; + if (brk.enabled) { + if (brk.bounds) { + var pattern2 = brk.pattern; + bnds = rangebreaksIn._cachedPatterns[i]; + b0 = bnds[0]; + b1 = bnds[1]; + switch (pattern2) { + case WEEKDAY_PATTERN: + vDate = new Date(v); + vb = vDate.getUTCDay(); + if (b0 > b1) { + b1 += 7; + if (vb < b0) vb += 7; + } + break; + case HOUR_PATTERN: + vDate = new Date(v); + var hours2 = vDate.getUTCHours(); + var minutes2 = vDate.getUTCMinutes(); + var seconds2 = vDate.getUTCSeconds(); + var milliseconds2 = vDate.getUTCMilliseconds(); + vb = hours2 + (minutes2 / 60 + seconds2 / 3600 + milliseconds2 / 36e5); + if (b0 > b1) { + b1 += 24; + if (vb < b0) vb += 24; + } + break; + case "": + vb = v; + break; + } + if (vb >= b0 && vb < b1) return BADNUM$9; + } else { + var vals = rangebreaksIn._cachedValues[i]; + for (var j = 0; j < vals.length; j++) { + b0 = vals[j]; + b1 = b0 + brk.dvalue; + if (v >= b0 && v < b1) return BADNUM$9; + } + } + } + } + return v; + }; + ax.locateBreaks = function(r0, r1) { + var i, bnds, b0, b1; + var rangebreaksOut = []; + if (!ax.rangebreaks) return rangebreaksOut; + var rangebreaksIn = ax.rangebreaks.slice().sort(function(a, b) { + if (a.pattern === WEEKDAY_PATTERN && b.pattern === HOUR_PATTERN) return -1; + if (b.pattern === WEEKDAY_PATTERN && a.pattern === HOUR_PATTERN) return 1; + return 0; + }); + var addBreak = function(min, max) { + min = Lib$1H.constrain(min, r0, r1); + max = Lib$1H.constrain(max, r0, r1); + if (min === max) return; + var isNewBreak = true; + for (var j2 = 0; j2 < rangebreaksOut.length; j2++) { + var brkj = rangebreaksOut[j2]; + if (min < brkj.max && max >= brkj.min) { + if (min < brkj.min) { + brkj.min = min; + } + if (max > brkj.max) { + brkj.max = max; + } + isNewBreak = false; + } + } + if (isNewBreak) { + rangebreaksOut.push({ min, max }); + } + }; + for (i = 0; i < rangebreaksIn.length; i++) { + var brk = rangebreaksIn[i]; + if (brk.enabled) { + if (brk.bounds) { + var t02 = r0; + var t12 = r1; + if (brk.pattern) { + t02 = Math.floor(t02); + } + bnds = Lib$1H.simpleMap(brk.bounds, brk.pattern ? cleanNumber$1 : ax.r2l); + b0 = bnds[0]; + b1 = bnds[1]; + var t0Date = new Date(t02); + var bndDelta; + var step; + switch (brk.pattern) { + case WEEKDAY_PATTERN: + step = ONEWEEK$2; + bndDelta = ((b1 < b0 ? 7 : 0) + (b1 - b0)) * ONEDAY$1; + t02 += b0 * ONEDAY$1 - (t0Date.getUTCDay() * ONEDAY$1 + t0Date.getUTCHours() * ONEHOUR$1 + t0Date.getUTCMinutes() * ONEMIN$1 + t0Date.getUTCSeconds() * ONESEC$1 + t0Date.getUTCMilliseconds()); + break; + case HOUR_PATTERN: + step = ONEDAY$1; + bndDelta = ((b1 < b0 ? 24 : 0) + (b1 - b0)) * ONEHOUR$1; + t02 += b0 * ONEHOUR$1 - (t0Date.getUTCHours() * ONEHOUR$1 + t0Date.getUTCMinutes() * ONEMIN$1 + t0Date.getUTCSeconds() * ONESEC$1 + t0Date.getUTCMilliseconds()); + break; + default: + t02 = Math.min(bnds[0], bnds[1]); + t12 = Math.max(bnds[0], bnds[1]); + step = t12 - t02; + bndDelta = step; + } + for (var t = t02; t < t12; t += step) { + addBreak(t, t + bndDelta); + } + } else { + var vals = Lib$1H.simpleMap(brk.values, ax.d2c); + for (var j = 0; j < vals.length; j++) { + b0 = vals[j]; + b1 = b0 + brk.dvalue; + addBreak(b0, b1); + } + } + } + } + rangebreaksOut.sort(function(a, b) { + return a.min - b.min; + }); + return rangebreaksOut; + }; + ax.makeCalcdata = function(trace, axLetter2, opts) { + var arrayIn, arrayOut, i, len; + var axType = ax.type; + var cal = axType === "date" && trace[axLetter2 + "calendar"]; + if (axLetter2 in trace) { + arrayIn = trace[axLetter2]; + len = trace._length || Lib$1H.minRowLength(arrayIn); + if (Lib$1H.isTypedArray(arrayIn) && (axType === "linear" || axType === "log")) { + if (len === arrayIn.length) { + return arrayIn; + } else if (arrayIn.subarray) { + return arrayIn.subarray(0, len); + } + } + if (axType === "multicategory") { + return setMultiCategoryIndex(arrayIn, len); + } + arrayOut = new Array(len); + for (i = 0; i < len; i++) { + arrayOut[i] = ax.d2c(arrayIn[i], 0, cal, opts); + } + } else { + var v0 = axLetter2 + "0" in trace ? ax.d2c(trace[axLetter2 + "0"], 0, cal) : 0; + var dv2 = trace["d" + axLetter2] ? Number(trace["d" + axLetter2]) : 1; + arrayIn = trace[{ x: "y", y: "x" }[axLetter2]]; + len = trace._length || arrayIn.length; + arrayOut = new Array(len); + for (i = 0; i < len; i++) { + arrayOut[i] = v0 + i * dv2; + } + } + if (ax.rangebreaks) { + for (i = 0; i < len; i++) { + arrayOut[i] = ax.maskBreaks(arrayOut[i]); + } + } + return arrayOut; + }; + ax.isValidRange = function(range, nullOk) { + return Array.isArray(range) && range.length === 2 && (nullOk && range[0] === null || isNumeric$m(ax.r2l(range[0]))) && (nullOk && range[1] === null || isNumeric$m(ax.r2l(range[1]))); + }; + ax.getAutorangeDflt = function(range, options) { + var autorangeDflt = !ax.isValidRange(range, "nullOk"); + if (autorangeDflt && options && options.reverseDflt) autorangeDflt = "reversed"; + else if (range) { + if (range[0] === null && range[1] === null) { + autorangeDflt = true; + } else if (range[0] === null && range[1] !== null) { + autorangeDflt = "min"; + } else if (range[0] !== null && range[1] === null) { + autorangeDflt = "max"; + } + } + return autorangeDflt; + }; + ax.isReversed = function() { + var autorange2 = ax.autorange; + return autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; + }; + ax.isPtWithinRange = function(d, calendar) { + var coord = ax.c2l(d[axLetter], null, calendar); + var r0 = ax.r2l(ax.range[0]); + var r1 = ax.r2l(ax.range[1]); + if (r0 < r1) { + return r0 <= coord && coord <= r1; + } else { + return r1 <= coord && coord <= r0; + } + }; + ax._emptyCategories = function() { + ax._categories = []; + ax._categoriesMap = {}; + }; + ax.clearCalc = function() { + var group = ax._matchGroup; + if (group) { + var categories = null; + var categoriesMap = null; + for (var axId2 in group) { + var ax2 = fullLayout[axisIds$8.id2name(axId2)]; + if (ax2._categories) { + categories = ax2._categories; + categoriesMap = ax2._categoriesMap; + break; + } + } + if (categories && categoriesMap) { + ax._categories = categories; + ax._categoriesMap = categoriesMap; + } else { + ax._emptyCategories(); + } + } else { + ax._emptyCategories(); + } + if (ax._initialCategories) { + for (var j = 0; j < ax._initialCategories.length; j++) { + setCategoryIndex(ax._initialCategories[j]); + } + } + }; + ax.sortByInitialCategories = function() { + var affectedTraces = []; + ax._emptyCategories(); + if (ax._initialCategories) { + for (var j = 0; j < ax._initialCategories.length; j++) { + setCategoryIndex(ax._initialCategories[j]); + } + } + affectedTraces = affectedTraces.concat(ax._traceIndices); + var group = ax._matchGroup; + for (var axId2 in group) { + if (axId === axId2) continue; + var ax2 = fullLayout[axisIds$8.id2name(axId2)]; + ax2._categories = ax._categories; + ax2._categoriesMap = ax._categoriesMap; + affectedTraces = affectedTraces.concat(ax2._traceIndices); + } + return affectedTraces; + }; + var locale2 = fullLayout._d3locale; + if (ax.type === "date") { + ax._dateFormat = locale2 ? locale2.timeFormat : utcFormat; + ax._extraFormat = fullLayout._extraFormat; + } + ax._separators = fullLayout.separators; + ax._numFormat = locale2 ? locale2.numberFormat : numberFormat; + delete ax._minDtick; + delete ax._forceTick0; +}; +var isNumeric$l = fastIsnumeric; +var Lib$1G = libExports; +var BADNUM$8 = numerical.BADNUM; +var isArrayOrTypedArray$7 = Lib$1G.isArrayOrTypedArray; +var isDateTime = Lib$1G.isDateTime; +var cleanNumber2 = Lib$1G.cleanNumber; +var round$1 = Math.round; +var axis_autotype = function autoType(array2, calendar, opts) { + var a = array2; + var noMultiCategory = opts.noMultiCategory; + if (isArrayOrTypedArray$7(a) && !a.length) return "-"; + if (!noMultiCategory && multiCategory(a)) return "multicategory"; + if (noMultiCategory && Array.isArray(a[0])) { + var b = []; + for (var i = 0; i < a.length; i++) { + if (isArrayOrTypedArray$7(a[i])) { + for (var j = 0; j < a[i].length; j++) { + b.push(a[i][j]); + } + } + } + a = b; + } + if (moreDates(a, calendar)) return "date"; + var convertNumeric = opts.autotypenumbers !== "strict"; + if (category(a, convertNumeric)) return "category"; + if (linearOK(a, convertNumeric)) return "linear"; + return "-"; +}; +function hasTypeNumber(v, convertNumeric) { + return convertNumeric ? isNumeric$l(v) : typeof v === "number"; +} +function linearOK(a, convertNumeric) { + var len = a.length; + for (var i = 0; i < len; i++) { + if (hasTypeNumber(a[i], convertNumeric)) return true; + } + return false; +} +function moreDates(a, calendar) { + var len = a.length; + var inc = getIncrement(len); + var dats = 0; + var nums = 0; + var seen = {}; + for (var f = 0; f < len; f += inc) { + var i = round$1(f); + var ai = a[i]; + var stri = String(ai); + if (seen[stri]) continue; + seen[stri] = 1; + if (isDateTime(ai, calendar)) dats++; + if (isNumeric$l(ai)) nums++; + } + return dats > nums * 2; +} +function getIncrement(len) { + return Math.max(1, (len - 1) / 1e3); +} +function category(a, convertNumeric) { + var len = a.length; + var inc = getIncrement(len); + var nums = 0; + var cats = 0; + var seen = {}; + for (var f = 0; f < len; f += inc) { + var i = round$1(f); + var ai = a[i]; + var stri = String(ai); + if (seen[stri]) continue; + seen[stri] = 1; + var t = typeof ai; + if (t === "boolean") cats++; + else if (convertNumeric ? cleanNumber2(ai) !== BADNUM$8 : t === "number") nums++; + else if (t === "string") cats++; + } + return cats > nums * 2; +} +function multiCategory(a) { + return isArrayOrTypedArray$7(a[0]) && isArrayOrTypedArray$7(a[1]); +} +var d3$w = d3Exports; +var isNumeric$k = fastIsnumeric; +var Lib$1F = libExports; +var FP_SAFE = numerical.FP_SAFE; +var Registry$J = registry; +var Drawing$t = drawingExports; +var axIds = axis_ids; +var getFromId$1 = axIds.getFromId; +var isLinked$1 = axIds.isLinked; +var autorange$2 = { + applyAutorangeOptions, + getAutoRange, + makePadFn, + doAutoRange, + findExtremes: findExtremes$1, + concatExtremes +}; +function getAutoRange(gd, ax) { + var i, j; + var newRange = []; + var fullLayout = gd._fullLayout; + var getPadMin = makePadFn(fullLayout, ax, 0); + var getPadMax = makePadFn(fullLayout, ax, 1); + var extremes = concatExtremes(gd, ax); + var minArray = extremes.min; + var maxArray = extremes.max; + if (minArray.length === 0 || maxArray.length === 0) { + return Lib$1F.simpleMap(ax.range, ax.r2l); + } + var minmin = minArray[0].val; + var maxmax = maxArray[0].val; + for (i = 1; i < minArray.length; i++) { + if (minmin !== maxmax) break; + minmin = Math.min(minmin, minArray[i].val); + } + for (i = 1; i < maxArray.length; i++) { + if (minmin !== maxmax) break; + maxmax = Math.max(maxmax, maxArray[i].val); + } + var autorange2 = ax.autorange; + var axReverse = autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; + if (!axReverse && ax.range) { + var rng = Lib$1F.simpleMap(ax.range, ax.r2l); + axReverse = rng[1] < rng[0]; + } + if (ax.autorange === "reversed") { + ax.autorange = true; + } + var rangeMode = ax.rangemode; + var toZero = rangeMode === "tozero"; + var nonNegative = rangeMode === "nonnegative"; + var axLen = ax._length; + var minSpan = axLen / 10; + var mbest = 0; + var minpt, maxpt, minbest, maxbest, dp, dv2; + for (i = 0; i < minArray.length; i++) { + minpt = minArray[i]; + for (j = 0; j < maxArray.length; j++) { + maxpt = maxArray[j]; + dv2 = maxpt.val - minpt.val - calcBreaksLength(ax, minpt.val, maxpt.val); + if (dv2 > 0) { + dp = axLen - getPadMin(minpt) - getPadMax(maxpt); + if (dp > minSpan) { + if (dv2 / dp > mbest) { + minbest = minpt; + maxbest = maxpt; + mbest = dv2 / dp; + } + } else if (dv2 / axLen > mbest) { + minbest = { val: minpt.val, nopad: 1 }; + maxbest = { val: maxpt.val, nopad: 1 }; + mbest = dv2 / axLen; + } + } + } + } + function maximumPad(prev, pt) { + return Math.max(prev, getPadMax(pt)); + } + if (minmin === maxmax) { + var lower = minmin - 1; + var upper = minmin + 1; + if (toZero) { + if (minmin === 0) { + newRange = [0, 1]; + } else { + var maxPad = (minmin > 0 ? maxArray : minArray).reduce(maximumPad, 0); + var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen)); + newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0]; + } + } else if (nonNegative) { + newRange = [Math.max(0, lower), Math.max(1, upper)]; + } else { + newRange = [lower, upper]; + } + } else { + if (toZero) { + if (minbest.val >= 0) { + minbest = { val: 0, nopad: 1 }; + } + if (maxbest.val <= 0) { + maxbest = { val: 0, nopad: 1 }; + } + } else if (nonNegative) { + if (minbest.val - mbest * getPadMin(minbest) < 0) { + minbest = { val: 0, nopad: 1 }; + } + if (maxbest.val <= 0) { + maxbest = { val: 1, nopad: 1 }; + } + } + mbest = (maxbest.val - minbest.val - calcBreaksLength(ax, minpt.val, maxpt.val)) / (axLen - getPadMin(minbest) - getPadMax(maxbest)); + newRange = [ + minbest.val - mbest * getPadMin(minbest), + maxbest.val + mbest * getPadMax(maxbest) + ]; + } + newRange = applyAutorangeOptions(newRange, ax); + if (ax.limitRange) ax.limitRange(); + if (axReverse) newRange.reverse(); + return Lib$1F.simpleMap(newRange, ax.l2r || Number); +} +function calcBreaksLength(ax, v0, v1) { + var lBreaks = 0; + if (ax.rangebreaks) { + var rangebreaksOut = ax.locateBreaks(v0, v1); + for (var i = 0; i < rangebreaksOut.length; i++) { + var brk = rangebreaksOut[i]; + lBreaks += brk.max - brk.min; + } + } + return lBreaks; +} +function makePadFn(fullLayout, ax, max) { + var extrappad = 0.05 * ax._length; + var anchorAxis = ax._anchorAxis || {}; + if ((ax.ticklabelposition || "").indexOf("inside") !== -1 || (anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) { + var axReverse = ax.isReversed(); + if (!axReverse) { + var rng = Lib$1F.simpleMap(ax.range, ax.r2l); + axReverse = rng[1] < rng[0]; + } + if (axReverse) max = !max; + } + var zero2 = 0; + if (!isLinked$1(fullLayout, ax._id)) { + zero2 = padInsideLabelsOnAnchorAxis(fullLayout, ax, max); + } + extrappad = Math.max(zero2, extrappad); + if (ax.constrain === "domain" && ax._inputDomain) { + extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) / (ax.domain[1] - ax.domain[0]); + } + return function getPad(pt) { + if (pt.nopad) return 0; + return pt.pad + (pt.extrapad ? extrappad : zero2); + }; +} +var TEXTPAD$5 = 3; +function padInsideLabelsOnAnchorAxis(fullLayout, ax, max) { + var pad2 = 0; + var isX = ax._id.charAt(0) === "x"; + for (var subplot in fullLayout._plots) { + var plotinfo = fullLayout._plots[subplot]; + if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; + var anchorAxis = (isX ? plotinfo.yaxis : plotinfo.xaxis) || {}; + if ((anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) { + if (!max && (anchorAxis.side === "left" || anchorAxis.side === "bottom") || max && (anchorAxis.side === "top" || anchorAxis.side === "right")) { + if (anchorAxis._vals) { + var rad = Lib$1F.deg2rad(anchorAxis._tickAngles[anchorAxis._id + "tick"] || 0); + var cosA = Math.abs(Math.cos(rad)); + var sinA = Math.abs(Math.sin(rad)); + if (!anchorAxis._vals[0].bb) { + var cls = anchorAxis._id + "tick"; + var tickLabels = anchorAxis._selections[cls]; + tickLabels.each(function(d) { + var thisLabel = d3$w.select(this); + var mathjaxGroup = thisLabel.select(".text-math-group"); + if (mathjaxGroup.empty()) { + d.bb = Drawing$t.bBox(thisLabel.node()); + } + }); + } + for (var i = 0; i < anchorAxis._vals.length; i++) { + var t = anchorAxis._vals[i]; + var bb = t.bb; + if (bb) { + var w = 2 * TEXTPAD$5 + bb.width; + var h = 2 * TEXTPAD$5 + bb.height; + pad2 = Math.max( + pad2, + isX ? Math.max(w * cosA, h * sinA) : Math.max(h * cosA, w * sinA) + ); + } + } + } + if (anchorAxis.ticks === "inside" && anchorAxis.ticklabelposition === "inside") { + pad2 += anchorAxis.ticklen || 0; + } + } + } + } + return pad2; +} +function concatExtremes(gd, ax, noMatch) { + var axId = ax._id; + var fullData = gd._fullData; + var fullLayout = gd._fullLayout; + var minArray = []; + var maxArray = []; + var i, j, d; + function _concat(cont, indices) { + for (i = 0; i < indices.length; i++) { + var item = cont[indices[i]]; + var extremes = (item._extremes || {})[axId]; + if (item.visible === true && extremes) { + for (j = 0; j < extremes.min.length; j++) { + d = extremes.min[j]; + collapseMinArray(minArray, d.val, d.pad, { extrapad: d.extrapad }); + } + for (j = 0; j < extremes.max.length; j++) { + d = extremes.max[j]; + collapseMaxArray(maxArray, d.val, d.pad, { extrapad: d.extrapad }); + } + } + } + } + _concat(fullData, ax._traceIndices); + _concat(fullLayout.annotations || [], ax._annIndices || []); + _concat(fullLayout.shapes || [], ax._shapeIndices || []); + if (ax._matchGroup && !noMatch) { + for (var axId2 in ax._matchGroup) { + if (axId2 !== ax._id) { + var ax2 = getFromId$1(gd, axId2); + var extremes2 = concatExtremes(gd, ax2, true); + var lenRatio = ax._length / ax2._length; + for (j = 0; j < extremes2.min.length; j++) { + d = extremes2.min[j]; + collapseMinArray(minArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad }); + } + for (j = 0; j < extremes2.max.length; j++) { + d = extremes2.max[j]; + collapseMaxArray(maxArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad }); + } + } + } + } + return { min: minArray, max: maxArray }; +} +function doAutoRange(gd, ax, presetRange) { + ax.setScale(); + if (ax.autorange) { + ax.range = presetRange ? presetRange.slice() : getAutoRange(gd, ax); + ax._r = ax.range.slice(); + ax._rl = Lib$1F.simpleMap(ax._r, ax.r2l); + var axIn = ax._input; + var edits = {}; + edits[ax._attr + ".range"] = ax.range; + edits[ax._attr + ".autorange"] = ax.autorange; + Registry$J.call("_storeDirectGUIEdit", gd.layout, gd._fullLayout._preGUI, edits); + axIn.range = ax.range.slice(); + axIn.autorange = ax.autorange; + } + var anchorAx = ax._anchorAxis; + if (anchorAx && anchorAx.rangeslider) { + var axeRangeOpts = anchorAx.rangeslider[ax._name]; + if (axeRangeOpts) { + if (axeRangeOpts.rangemode === "auto") { + axeRangeOpts.range = getAutoRange(gd, ax); + } + } + anchorAx._input.rangeslider[ax._name] = Lib$1F.extendFlat({}, axeRangeOpts); + } +} +function findExtremes$1(ax, data, opts) { + if (!opts) opts = {}; + if (!ax._m) ax.setScale(); + var minArray = []; + var maxArray = []; + var len = data.length; + var extrapad = opts.padded || false; + var tozero = opts.tozero && (ax.type === "linear" || ax.type === "-"); + var isLog = ax.type === "log"; + var hasArrayOption = false; + var vpadLinearized = opts.vpadLinearized || false; + var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax; + function makePadAccessor(item) { + if (Array.isArray(item)) { + hasArrayOption = true; + return function(i2) { + return Math.max(Number(item[i2] || 0), 0); + }; + } else { + var v2 = Math.max(Number(item || 0), 0); + return function() { + return v2; + }; + } + } + var ppadplus = makePadAccessor((ax._m > 0 ? opts.ppadplus : opts.ppadminus) || opts.ppad || 0); + var ppadminus = makePadAccessor((ax._m > 0 ? opts.ppadminus : opts.ppadplus) || opts.ppad || 0); + var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad); + var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad); + if (!hasArrayOption) { + vmin = Infinity; + vmax = -Infinity; + if (isLog) { + for (i = 0; i < len; i++) { + v = data[i]; + if (v < vmin && v > 0) vmin = v; + if (v > vmax && v < FP_SAFE) vmax = v; + } + } else { + for (i = 0; i < len; i++) { + v = data[i]; + if (v < vmin && v > -FP_SAFE) vmin = v; + if (v > vmax && v < FP_SAFE) vmax = v; + } + } + data = [vmin, vmax]; + len = 2; + } + var collapseOpts = { tozero, extrapad }; + function addItem(i2) { + di = data[i2]; + if (!isNumeric$k(di)) return; + ppadiplus = ppadplus(i2); + ppadiminus = ppadminus(i2); + if (vpadLinearized) { + dmin = ax.c2l(di) - vpadminus(i2); + dmax = ax.c2l(di) + vpadplus(i2); + } else { + vmin = di - vpadminus(i2); + vmax = di + vpadplus(i2); + if (isLog && vmin < vmax / 10) vmin = vmax / 10; + dmin = ax.c2l(vmin); + dmax = ax.c2l(vmax); + } + if (tozero) { + dmin = Math.min(0, dmin); + dmax = Math.max(0, dmax); + } + if (goodNumber(dmin)) { + collapseMinArray(minArray, dmin, ppadiminus, collapseOpts); + } + if (goodNumber(dmax)) { + collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts); + } + } + var iMax = Math.min(6, len); + for (i = 0; i < iMax; i++) addItem(i); + for (i = len - 1; i >= iMax; i--) addItem(i); + return { + min: minArray, + max: maxArray, + opts + }; +} +function collapseMinArray(array2, newVal, newPad, opts) { + collapseArray(array2, newVal, newPad, opts, lessOrEqual); +} +function collapseMaxArray(array2, newVal, newPad, opts) { + collapseArray(array2, newVal, newPad, opts, greaterOrEqual); +} +function collapseArray(array2, newVal, newPad, opts, atLeastAsExtreme) { + var tozero = opts.tozero; + var extrapad = opts.extrapad; + var includeThis = true; + for (var j = 0; j < array2.length && includeThis; j++) { + var v = array2[j]; + if (atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) { + includeThis = false; + break; + } else if (atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) { + array2.splice(j, 1); + j--; + } + } + if (includeThis) { + var clipAtZero = tozero && newVal === 0; + array2.push({ + val: newVal, + pad: clipAtZero ? 0 : newPad, + extrapad: clipAtZero ? false : extrapad + }); + } +} +function goodNumber(v) { + return isNumeric$k(v) && Math.abs(v) < FP_SAFE; +} +function lessOrEqual(v0, v1) { + return v0 <= v1; +} +function greaterOrEqual(v0, v1) { + return v0 >= v1; +} +function applyAutorangeMinOptions(v, ax) { + var autorangeoptions = ax.autorangeoptions; + if (autorangeoptions && autorangeoptions.minallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) { + return autorangeoptions.minallowed; + } + if (autorangeoptions && autorangeoptions.clipmin !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) { + return Math.max(v, ax.d2l(autorangeoptions.clipmin)); + } + return v; +} +function applyAutorangeMaxOptions(v, ax) { + var autorangeoptions = ax.autorangeoptions; + if (autorangeoptions && autorangeoptions.maxallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) { + return autorangeoptions.maxallowed; + } + if (autorangeoptions && autorangeoptions.clipmax !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) { + return Math.min(v, ax.d2l(autorangeoptions.clipmax)); + } + return v; +} +function hasValidMinAndMax(ax, min, max) { + if (min !== void 0 && max !== void 0) { + min = ax.d2l(min); + max = ax.d2l(max); + return min < max; + } + return true; +} +function applyAutorangeOptions(range, ax) { + if (!ax || !ax.autorangeoptions) return range; + var min = range[0]; + var max = range[1]; + var include = ax.autorangeoptions.include; + if (include !== void 0) { + var lMin = ax.d2l(min); + var lMax = ax.d2l(max); + if (!Lib$1F.isArrayOrTypedArray(include)) include = [include]; + for (var i = 0; i < include.length; i++) { + var v = ax.d2l(include[i]); + if (lMin >= v) { + lMin = v; + min = v; + } + if (lMax <= v) { + lMax = v; + max = v; + } + } + } + min = applyAutorangeMinOptions(min, ax); + max = applyAutorangeMaxOptions(max, ax); + return [min, max]; +} +var d3$v = d3Exports; +var isNumeric$j = fastIsnumeric; +var Plots$b = plotsExports; +var Registry$I = registry; +var Lib$1E = libExports; +var strTranslate$a = Lib$1E.strTranslate; +var svgTextUtils$d = svg_text_utils; +var Titles$1 = titles; +var Color$H = colorExports; +var Drawing$s = drawingExports; +var axAttrs = layout_attributes$4; +var cleanTicks = clean_ticks; +var constants$Q = numerical; +var ONEMAXYEAR = constants$Q.ONEMAXYEAR; +var ONEAVGYEAR = constants$Q.ONEAVGYEAR; +var ONEMINYEAR = constants$Q.ONEMINYEAR; +var ONEMAXQUARTER = constants$Q.ONEMAXQUARTER; +var ONEAVGQUARTER = constants$Q.ONEAVGQUARTER; +var ONEMINQUARTER = constants$Q.ONEMINQUARTER; +var ONEMAXMONTH = constants$Q.ONEMAXMONTH; +var ONEAVGMONTH$1 = constants$Q.ONEAVGMONTH; +var ONEMINMONTH = constants$Q.ONEMINMONTH; +var ONEWEEK$1 = constants$Q.ONEWEEK; +var ONEDAY = constants$Q.ONEDAY; +var HALFDAY = ONEDAY / 2; +var ONEHOUR = constants$Q.ONEHOUR; +var ONEMIN = constants$Q.ONEMIN; +var ONESEC = constants$Q.ONESEC; +var ONEMILLI = constants$Q.ONEMILLI; +var ONEMICROSEC = constants$Q.ONEMICROSEC; +var MINUS_SIGN = constants$Q.MINUS_SIGN; +var BADNUM$7 = constants$Q.BADNUM; +var ZERO_PATH = { K: "zeroline" }; +var GRID_PATH = { K: "gridline", L: "path" }; +var MINORGRID_PATH = { K: "minor-gridline", L: "path" }; +var TICK_PATH = { K: "tick", L: "path" }; +var TICK_TEXT = { K: "tick", L: "text" }; +var MARGIN_MAPPING = { + width: ["x", "r", "l", "xl", "xr"], + height: ["y", "t", "b", "yt", "yb"], + right: ["r", "xr"], + left: ["l", "xl"], + top: ["t", "yt"], + bottom: ["b", "yb"] +}; +var alignmentConstants$4 = alignment$1; +var MID_SHIFT = alignmentConstants$4.MID_SHIFT; +var CAP_SHIFT = alignmentConstants$4.CAP_SHIFT; +var LINE_SPACING$6 = alignmentConstants$4.LINE_SPACING; +var OPPOSITE_SIDE = alignmentConstants$4.OPPOSITE_SIDE; +var TEXTPAD$4 = 3; +var axes = axes$1.exports = {}; +axes.setConvert = set_convert; +var autoType2 = axis_autotype; +var axisIds$7 = axis_ids; +var idSort = axisIds$7.idSort; +var isLinked = axisIds$7.isLinked; +axes.id2name = axisIds$7.id2name; +axes.name2id = axisIds$7.name2id; +axes.cleanId = axisIds$7.cleanId; +axes.list = axisIds$7.list; +axes.listIds = axisIds$7.listIds; +axes.getFromId = axisIds$7.getFromId; +axes.getFromTrace = axisIds$7.getFromTrace; +var autorange$1 = autorange$2; +axes.getAutoRange = autorange$1.getAutoRange; +axes.findExtremes = autorange$1.findExtremes; +var epsilon$2 = 1e-4; +function expandRange(range) { + var delta2 = (range[1] - range[0]) * epsilon$2; + return [ + range[0] - delta2, + range[1] + delta2 + ]; +} +axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) { + var axLetter = attr.charAt(attr.length - 1); + var axlist = gd._fullLayout._subplots[axLetter + "axis"]; + var refAttr = attr + "ref"; + var attrDef = {}; + if (!dflt) dflt = axlist[0] || (typeof extraOption === "string" ? extraOption : extraOption[0]); + if (!extraOption) extraOption = dflt; + axlist = axlist.concat(axlist.map(function(x) { + return x + " domain"; + })); + attrDef[refAttr] = { + valType: "enumerated", + values: axlist.concat(extraOption ? typeof extraOption === "string" ? [extraOption] : extraOption : []), + dflt + }; + return Lib$1E.coerce(containerIn, containerOut, attrDef, refAttr); +}; +axes.getRefType = function(ar) { + if (ar === void 0) { + return ar; + } + if (ar === "paper") { + return "paper"; + } + if (ar === "pixel") { + return "pixel"; + } + if (/( domain)$/.test(ar)) { + return "domain"; + } else { + return "range"; + } +}; +axes.coercePosition = function(containerOut, gd, coerce2, axRef, attr, dflt) { + var cleanPos, pos; + var axRefType = axes.getRefType(axRef); + if (axRefType !== "range") { + cleanPos = Lib$1E.ensureNumber; + pos = coerce2(attr, dflt); + } else { + var ax = axes.getFromId(gd, axRef); + dflt = ax.fraction2r(dflt); + pos = coerce2(attr, dflt); + cleanPos = ax.cleanPos; + } + containerOut[attr] = cleanPos(pos); +}; +axes.cleanPosition = function(pos, gd, axRef) { + var cleanPos = axRef === "paper" || axRef === "pixel" ? Lib$1E.ensureNumber : axes.getFromId(gd, axRef).cleanPos; + return cleanPos(pos); +}; +axes.redrawComponents = function(gd, axIds2) { + axIds2 = axIds2 ? axIds2 : axes.listIds(gd); + var fullLayout = gd._fullLayout; + function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) { + var method = Registry$I.getComponentMethod(moduleName, methodName); + var stash = {}; + for (var i = 0; i < axIds2.length; i++) { + var ax = fullLayout[axes.id2name(axIds2[i])]; + var indices = ax[stashName]; + for (var j = 0; j < indices.length; j++) { + var ind = indices[j]; + if (!stash[ind]) { + method(gd, ind); + stash[ind] = 1; + if (shortCircuit) return; + } + } + } + } + _redrawOneComp("annotations", "drawOne", "_annIndices"); + _redrawOneComp("shapes", "drawOne", "_shapeIndices"); + _redrawOneComp("images", "draw", "_imgIndices", true); + _redrawOneComp("selections", "drawOne", "_selectionIndices"); +}; +var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { + var ax; + var d2cTarget = target === "x" || target === "y" || target === "z" ? target : targetArray; + if (Lib$1E.isArrayOrTypedArray(d2cTarget)) { + ax = { + type: autoType2(targetArray, void 0, { + autotypenumbers: gd._fullLayout.autotypenumbers + }), + _categories: [] + }; + axes.setConvert(ax); + if (ax.type === "category") { + for (var i = 0; i < targetArray.length; i++) { + ax.d2c(targetArray[i]); + } + } + } else { + ax = axes.getFromTrace(gd, trace, d2cTarget); + } + if (ax) return { d2c: ax.d2c, c2d: ax.c2d }; + if (d2cTarget === "ids") return { d2c: toString$1, c2d: toString$1 }; + return { d2c: toNum, c2d: toNum }; +}; +function toNum(v) { + return +v; +} +function toString$1(v) { + return String(v); +} +axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { + return getDataConversions(gd, trace, target, targetArray).d2c; +}; +axes.counterLetter = function(id) { + var axLetter = id.charAt(0); + if (axLetter === "x") return "y"; + if (axLetter === "y") return "x"; +}; +axes.minDtick = function(ax, newDiff, newFirst, allow) { + if (["log", "category", "multicategory"].indexOf(ax.type) !== -1 || !allow) { + ax._minDtick = 0; + } else if (ax._minDtick === void 0) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } else if (ax._minDtick) { + if ((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && // existing minDtick is an integer multiple of newDiff + // (within rounding err) + // and forceTick0 can be shifted to newFirst + ((newFirst - ax._forceTick0) / newDiff % 1 + 1.000001) % 1 < 2e-6) { + ax._minDtick = newDiff; + ax._forceTick0 = newFirst; + } else if ((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || // if the converse is true (newDiff is a multiple of minDtick and + // newFirst can be shifted to forceTick0) then do nothing - same + // forcing stands. Otherwise, cancel forced minimum + ((newFirst - ax._forceTick0) / ax._minDtick % 1 + 1.000001) % 1 > 2e-6) { + ax._minDtick = 0; + } + } +}; +axes.saveRangeInitial = function(gd, overwrite) { + var axList = axes.list(gd, "", true); + var hasOneAxisChanged = false; + for (var i = 0; i < axList.length; i++) { + var ax = axList[i]; + var isNew = ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0; + var hasChanged = isNew || (ax.range[0] !== ax._rangeInitial0 || ax.range[1] !== ax._rangeInitial1); + var autorange2 = ax.autorange; + if (isNew && autorange2 !== true || overwrite && hasChanged) { + ax._rangeInitial0 = autorange2 === "min" || autorange2 === "max reversed" ? void 0 : ax.range[0]; + ax._rangeInitial1 = autorange2 === "max" || autorange2 === "min reversed" ? void 0 : ax.range[1]; + ax._autorangeInitial = autorange2; + hasOneAxisChanged = true; + } + } + return hasOneAxisChanged; +}; +axes.saveShowSpikeInitial = function(gd, overwrite) { + var axList = axes.list(gd, "", true); + var hasOneAxisChanged = false; + var allSpikesEnabled = "on"; + for (var i = 0; i < axList.length; i++) { + var ax = axList[i]; + var isNew = ax._showSpikeInitial === void 0; + var hasChanged = isNew || !(ax.showspikes === ax._showspikes); + if (isNew || overwrite && hasChanged) { + ax._showSpikeInitial = ax.showspikes; + hasOneAxisChanged = true; + } + if (allSpikesEnabled === "on" && !ax.showspikes) { + allSpikesEnabled = "off"; + } + } + gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + return hasOneAxisChanged; +}; +axes.autoBin = function(data, ax, nbins, is2d, calendar, size) { + var dataMin = Lib$1E.aggNums(Math.min, null, data); + var dataMax = Lib$1E.aggNums(Math.max, null, data); + if (ax.type === "category" || ax.type === "multicategory") { + return { + start: dataMin - 0.5, + end: dataMax + 0.5, + size: Math.max(1, Math.round(size) || 1), + _dataSpan: dataMax - dataMin + }; + } + if (!calendar) calendar = ax.calendar; + var dummyAx; + if (ax.type === "log") { + dummyAx = { + type: "linear", + range: [dataMin, dataMax] + }; + } else { + dummyAx = { + type: ax.type, + range: Lib$1E.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), + calendar + }; + } + axes.setConvert(dummyAx); + size = size && cleanTicks.dtick(size, dummyAx.type); + if (size) { + dummyAx.dtick = size; + dummyAx.tick0 = cleanTicks.tick0(void 0, dummyAx.type, calendar); + } else { + var size0; + if (nbins) size0 = (dataMax - dataMin) / nbins; + else { + var distinctData = Lib$1E.distinctVals(data); + var msexp = Math.pow(10, Math.floor( + Math.log(distinctData.minDiff) / Math.LN10 + )); + var minSize = msexp * Lib$1E.roundUp( + distinctData.minDiff / msexp, + [0.9, 1.9, 4.9, 9.9], + true + ); + size0 = Math.max(minSize, 2 * Lib$1E.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4)); + if (!isNumeric$j(size0)) size0 = 1; + } + axes.autoTicks(dummyAx, size0); + } + var finalSize = dummyAx.dtick; + var binStart = axes.tickIncrement( + axes.tickFirst(dummyAx), + finalSize, + "reverse", + calendar + ); + var binEnd, bincount; + if (typeof finalSize === "number") { + binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); + bincount = 1 + Math.floor((dataMax - binStart) / finalSize); + binEnd = binStart + bincount * finalSize; + } else { + if (dummyAx.dtick.charAt(0) === "M") { + binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar); + } + binEnd = binStart; + bincount = 0; + while (binEnd <= dataMax) { + binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar); + bincount++; + } + } + return { + start: ax.c2r(binStart, 0, calendar), + end: ax.c2r(binEnd, 0, calendar), + size: finalSize, + _dataSpan: dataMax - dataMin + }; +}; +function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { + var edgecount = 0; + var midcount = 0; + var intcount = 0; + var blankCount = 0; + function nearEdge(v) { + return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; + } + for (var i = 0; i < data.length; i++) { + if (data[i] % 1 === 0) intcount++; + else if (!isNumeric$j(data[i])) blankCount++; + if (nearEdge(data[i])) edgecount++; + if (nearEdge(data[i] + ax.dtick / 2)) midcount++; + } + var dataCount = data.length - blankCount; + if (intcount === dataCount && ax.type !== "date") { + if (ax.dtick < 1) { + binStart = dataMin - 0.5 * ax.dtick; + } else { + binStart -= 0.5; + if (binStart + ax.dtick < dataMin) binStart += ax.dtick; + } + } else if (midcount < dataCount * 0.1) { + if (edgecount > dataCount * 0.3 || nearEdge(dataMin) || nearEdge(dataMax)) { + var binshift = ax.dtick / 2; + binStart += binStart + binshift < dataMin ? binshift : -binshift; + } + } + return binStart; +} +function autoShiftMonthBins(binStart, data, dtick2, dataMin, calendar) { + var stats2 = Lib$1E.findExactDates(data, calendar); + var threshold = 0.8; + if (stats2.exactDays > threshold) { + var numMonths = Number(dtick2.substr(1)); + if (stats2.exactYears > threshold && numMonths % 12 === 0) { + binStart = axes.tickIncrement(binStart, "M6", "reverse") + ONEDAY * 1.5; + } else if (stats2.exactMonths > threshold) { + binStart = axes.tickIncrement(binStart, "M1", "reverse") + ONEDAY * 15.5; + } else { + binStart -= HALFDAY; + } + var nextBinStart = axes.tickIncrement(binStart, dtick2); + if (nextBinStart <= dataMin) return nextBinStart; + } + return binStart; +} +axes.prepMinorTicks = function(mockAx, ax, opts) { + if (!ax.minor.dtick) { + delete mockAx.dtick; + var hasMajor = ax.dtick && isNumeric$j(ax._tmin); + var mockMinorRange; + if (hasMajor) { + var tick2 = axes.tickIncrement(ax._tmin, ax.dtick, true); + mockMinorRange = [ax._tmin, tick2 * 0.99 + ax._tmin * 0.01]; + } else { + var rl = Lib$1E.simpleMap(ax.range, ax.r2l); + mockMinorRange = [rl[0], 0.8 * rl[0] + 0.2 * rl[1]]; + } + mockAx.range = Lib$1E.simpleMap(mockMinorRange, ax.l2r); + mockAx._isMinor = true; + axes.prepTicks(mockAx, opts); + if (hasMajor) { + var numericMajor = isNumeric$j(ax.dtick); + var numericMinor = isNumeric$j(mockAx.dtick); + var majorNum = numericMajor ? ax.dtick : +ax.dtick.substring(1); + var minorNum = numericMinor ? mockAx.dtick : +mockAx.dtick.substring(1); + if (numericMajor && numericMinor) { + if (!isMultiple(majorNum, minorNum)) { + if (majorNum === 2 * ONEWEEK$1 && minorNum === 3 * ONEDAY) { + mockAx.dtick = ONEWEEK$1; + } else if (majorNum === ONEWEEK$1 && !(ax._input.minor || {}).nticks) { + mockAx.dtick = ONEDAY; + } else if (isClose(majorNum / minorNum, 2.5)) { + mockAx.dtick = majorNum / 2; + } else { + mockAx.dtick = majorNum; + } + } else if (majorNum === 2 * ONEWEEK$1 && minorNum === 2 * ONEDAY) { + mockAx.dtick = ONEWEEK$1; + } + } else if (String(ax.dtick).charAt(0) === "M") { + if (numericMinor) { + mockAx.dtick = "M1"; + } else { + if (!isMultiple(majorNum, minorNum)) { + mockAx.dtick = ax.dtick; + } else if (majorNum >= 12 && minorNum === 2) { + mockAx.dtick = "M3"; + } + } + } else if (String(mockAx.dtick).charAt(0) === "L") { + if (String(ax.dtick).charAt(0) === "L") { + if (!isMultiple(majorNum, minorNum)) { + mockAx.dtick = isClose(majorNum / minorNum, 2.5) ? ax.dtick / 2 : ax.dtick; + } + } else { + mockAx.dtick = "D1"; + } + } else if (mockAx.dtick === "D2" && +ax.dtick > 1) { + mockAx.dtick = 1; + } + } + mockAx.range = ax.range; + } + if (ax.minor._tick0Init === void 0) { + mockAx.tick0 = ax.tick0; + } +}; +function isMultiple(bigger, smaller) { + return Math.abs((bigger / smaller + 0.5) % 1 - 0.5) < 1e-3; +} +function isClose(a, b) { + return Math.abs(a / b - 1) < 1e-3; +} +axes.prepTicks = function(ax, opts) { + var rng = Lib$1E.simpleMap(ax.range, ax.r2l, void 0, void 0, opts); + if (ax.tickmode === "auto" || !ax.dtick) { + var nt = ax.nticks; + var minPx; + if (!nt) { + if (ax.type === "category" || ax.type === "multicategory") { + minPx = ax.tickfont ? Lib$1E.bigFont(ax.tickfont.size || 12) : 15; + nt = ax._length / minPx; + } else { + minPx = ax._id.charAt(0) === "y" ? 40 : 80; + nt = Lib$1E.constrain(ax._length / minPx, 4, 9) + 1; + } + if (ax._name === "radialaxis") nt *= 2; + } + if (!(ax.minor && ax.minor.tickmode !== "array")) { + if (ax.tickmode === "array") nt *= 100; + } + ax._roughDTick = Math.abs(rng[1] - rng[0]) / nt; + axes.autoTicks(ax, ax._roughDTick); + if (ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) { + ax.dtick = ax._minDtick; + ax.tick0 = ax.l2r(ax._forceTick0); + } + } + if (ax.ticklabelmode === "period") { + adjustPeriodDelta(ax); + } + if (!ax.tick0) { + ax.tick0 = ax.type === "date" ? "2000-01-01" : 0; + } + if (ax.type === "date" && ax.dtick < 0.1) ax.dtick = 0.1; + autoTickRound(ax); +}; +function nMonths(dtick2) { + return +dtick2.substring(1); +} +function adjustPeriodDelta(ax) { + var definedDelta; + function mDate() { + return !(isNumeric$j(ax.dtick) || ax.dtick.charAt(0) !== "M"); + } + var isMDate = mDate(); + var tickformat = axes.getTickFormat(ax); + if (tickformat) { + var noDtick = ax._dtickInit !== ax.dtick; + if (!/%[fLQsSMX]/.test(tickformat)) { + if (/%[HI]/.test(tickformat)) { + definedDelta = ONEHOUR; + if (noDtick && !isMDate && ax.dtick < ONEHOUR) ax.dtick = ONEHOUR; + } else if (/%p/.test(tickformat)) { + definedDelta = HALFDAY; + if (noDtick && !isMDate && ax.dtick < HALFDAY) ax.dtick = HALFDAY; + } else if (/%[Aadejuwx]/.test(tickformat)) { + definedDelta = ONEDAY; + if (noDtick && !isMDate && ax.dtick < ONEDAY) ax.dtick = ONEDAY; + } else if (/%[UVW]/.test(tickformat)) { + definedDelta = ONEWEEK$1; + if (noDtick && !isMDate && ax.dtick < ONEWEEK$1) ax.dtick = ONEWEEK$1; + } else if (/%[Bbm]/.test(tickformat)) { + definedDelta = ONEAVGMONTH$1; + if (noDtick && (isMDate ? nMonths(ax.dtick) < 1 : ax.dtick < ONEMINMONTH)) ax.dtick = "M1"; + } else if (/%[q]/.test(tickformat)) { + definedDelta = ONEAVGQUARTER; + if (noDtick && (isMDate ? nMonths(ax.dtick) < 3 : ax.dtick < ONEMINQUARTER)) ax.dtick = "M3"; + } else if (/%[Yy]/.test(tickformat)) { + definedDelta = ONEAVGYEAR; + if (noDtick && (isMDate ? nMonths(ax.dtick) < 12 : ax.dtick < ONEMINYEAR)) ax.dtick = "M12"; + } + } + } + isMDate = mDate(); + if (isMDate && ax.tick0 === ax._dowTick0) { + ax.tick0 = ax._rawTick0; + } + ax._definedDelta = definedDelta; +} +function positionPeriodTicks(tickVals, ax, definedDelta) { + for (var i = 0; i < tickVals.length; i++) { + var v = tickVals[i].value; + var a = i; + var b = i + 1; + if (i < tickVals.length - 1) { + a = i; + b = i + 1; + } else if (i > 0) { + a = i - 1; + b = i; + } else { + a = i; + b = i; + } + var A2 = tickVals[a].value; + var B2 = tickVals[b].value; + var actualDelta = Math.abs(B2 - A2); + var delta2 = definedDelta || actualDelta; + var periodLength = 0; + if (delta2 >= ONEMINYEAR) { + if (actualDelta >= ONEMINYEAR && actualDelta <= ONEMAXYEAR) { + periodLength = actualDelta; + } else { + periodLength = ONEAVGYEAR; + } + } else if (definedDelta === ONEAVGQUARTER && delta2 >= ONEMINQUARTER) { + if (actualDelta >= ONEMINQUARTER && actualDelta <= ONEMAXQUARTER) { + periodLength = actualDelta; + } else { + periodLength = ONEAVGQUARTER; + } + } else if (delta2 >= ONEMINMONTH) { + if (actualDelta >= ONEMINMONTH && actualDelta <= ONEMAXMONTH) { + periodLength = actualDelta; + } else { + periodLength = ONEAVGMONTH$1; + } + } else if (definedDelta === ONEWEEK$1 && delta2 >= ONEWEEK$1) { + periodLength = ONEWEEK$1; + } else if (delta2 >= ONEDAY) { + periodLength = ONEDAY; + } else if (definedDelta === HALFDAY && delta2 >= HALFDAY) { + periodLength = HALFDAY; + } else if (definedDelta === ONEHOUR && delta2 >= ONEHOUR) { + periodLength = ONEHOUR; + } + var inBetween; + if (periodLength >= actualDelta) { + periodLength = actualDelta; + inBetween = true; + } + var endPeriod = v + periodLength; + if (ax.rangebreaks && periodLength > 0) { + var nAll = 84; + var n = 0; + for (var c = 0; c < nAll; c++) { + var r = (c + 0.5) / nAll; + if (ax.maskBreaks(v * (1 - r) + r * endPeriod) !== BADNUM$7) n++; + } + periodLength *= n / nAll; + if (!periodLength) { + tickVals[i].drop = true; + } + if (inBetween && actualDelta > ONEWEEK$1) periodLength = actualDelta; + } + if (periodLength > 0 || // not instant + i === 0) { + tickVals[i].periodX = v + periodLength / 2; + } + } +} +axes.calcTicks = function calcTicks(ax, opts) { + var type = ax.type; + var calendar = ax.calendar; + var ticklabelstep = ax.ticklabelstep; + var isPeriod = ax.ticklabelmode === "period"; + var isReversed2 = ax.range[0] > ax.range[1]; + var ticklabelIndex = !ax.ticklabelindex || Lib$1E.isArrayOrTypedArray(ax.ticklabelindex) ? ax.ticklabelindex : [ax.ticklabelindex]; + var rng = Lib$1E.simpleMap(ax.range, ax.r2l, void 0, void 0, opts); + var axrev = rng[1] < rng[0]; + var minRange = Math.min(rng[0], rng[1]); + var maxRange = Math.max(rng[0], rng[1]); + var maxTicks = Math.max(1e3, ax._length || 0); + var ticksOut = []; + var minorTicks = []; + var tickVals = []; + var minorTickVals = []; + var allTicklabelVals = []; + var hasMinor = ax.minor && (ax.minor.ticks || ax.minor.showgrid); + for (var major = 1; major >= (hasMinor ? 0 : 1); major--) { + var isMinor = !major; + if (major) { + ax._dtickInit = ax.dtick; + ax._tick0Init = ax.tick0; + } else { + ax.minor._dtickInit = ax.minor.dtick; + ax.minor._tick0Init = ax.minor.tick0; + } + var mockAx = major ? ax : Lib$1E.extendFlat({}, ax, ax.minor); + if (isMinor) { + axes.prepMinorTicks(mockAx, ax, opts); + } else { + axes.prepTicks(mockAx, opts); + } + if (mockAx.tickmode === "array") { + if (major) { + tickVals = []; + ticksOut = arrayTicks(ax, !isMinor); + } else { + minorTickVals = []; + minorTicks = arrayTicks(ax, !isMinor); + } + continue; + } + if (mockAx.tickmode === "sync") { + tickVals = []; + ticksOut = syncTicks(ax); + continue; + } + var exRng = expandRange(rng); + var startTick = exRng[0]; + var endTick = exRng[1]; + var numDtick = isNumeric$j(mockAx.dtick); + var isDLog = type === "log" && !(numDtick || mockAx.dtick.charAt(0) === "L"); + var x0 = axes.tickFirst(mockAx, opts); + if (major) { + ax._tmin = x0; + if (x0 < startTick !== axrev) break; + if (type === "category" || type === "multicategory") { + endTick = axrev ? Math.max(-0.5, endTick) : Math.min(ax._categories.length - 0.5, endTick); + } + } + var prevX = null; + var x = x0; + var majorId; + if (major) { + var _dTick; + if (numDtick) { + _dTick = ax.dtick; + } else { + if (type === "date") { + if (typeof ax.dtick === "string" && ax.dtick.charAt(0) === "M") { + _dTick = ONEAVGMONTH$1 * ax.dtick.substring(1); + } + } else { + _dTick = ax._roughDTick; + } + } + majorId = Math.round((ax.r2l(x) - ax.r2l(ax.tick0)) / _dTick) - 1; + } + var dtick2 = mockAx.dtick; + if (mockAx.rangebreaks && mockAx._tick0Init !== mockAx.tick0) { + x = moveOutsideBreak(x, ax); + if (!axrev) { + x = axes.tickIncrement(x, dtick2, !axrev, calendar); + } + } + if (major && isPeriod) { + x = axes.tickIncrement(x, dtick2, !axrev, calendar); + majorId--; + } + for (; axrev ? x >= endTick : x <= endTick; x = axes.tickIncrement( + x, + dtick2, + axrev, + calendar + )) { + if (major) majorId++; + if (mockAx.rangebreaks) { + if (!axrev) { + if (x < startTick) continue; + if (mockAx.maskBreaks(x) === BADNUM$7 && moveOutsideBreak(x, mockAx) >= maxRange) break; + } + } + if (tickVals.length > maxTicks || x === prevX) break; + prevX = x; + var obj = { value: x }; + if (major) { + if (isDLog && x !== (x | 0)) { + obj.simpleLabel = true; + } + if (ticklabelstep > 1 && majorId % ticklabelstep) { + obj.skipLabel = true; + } + tickVals.push(obj); + } else { + obj.minor = true; + minorTickVals.push(obj); + } + } + } + if (!minorTickVals || minorTickVals.length < 2) { + ticklabelIndex = false; + } else { + var diff = (minorTickVals[1].value - minorTickVals[0].value) * (isReversed2 ? -1 : 1); + if (!periodCompatibleWithTickformat(diff, ax.tickformat)) { + ticklabelIndex = false; + } + } + if (!ticklabelIndex) { + allTicklabelVals = tickVals; + } else { + var allTickVals = tickVals.concat(minorTickVals); + if (isPeriod && tickVals.length) { + allTickVals = allTickVals.slice(1); + } + allTickVals = allTickVals.sort(function(a, b) { + return a.value - b.value; + }).filter(function(tick, index2, self2) { + return index2 === 0 || tick.value !== self2[index2 - 1].value; + }); + var majorTickIndices = allTickVals.map(function(item, index2) { + return item.minor === void 0 && !item.skipLabel ? index2 : null; + }).filter(function(index2) { + return index2 !== null; + }); + majorTickIndices.forEach(function(majorIdx) { + ticklabelIndex.map(function(nextLabelIdx) { + var minorIdx = majorIdx + nextLabelIdx; + if (minorIdx >= 0 && minorIdx < allTickVals.length) { + Lib$1E.pushUnique(allTicklabelVals, allTickVals[minorIdx]); + } + }); + }); + } + if (hasMinor) { + var canOverlap = ax.minor.ticks === "inside" && ax.ticks === "outside" || ax.minor.ticks === "outside" && ax.ticks === "inside"; + if (!canOverlap) { + var majorValues = tickVals.map(function(d) { + return d.value; + }); + var list = []; + for (var k = 0; k < minorTickVals.length; k++) { + var T = minorTickVals[k]; + var v = T.value; + if (majorValues.indexOf(v) !== -1) { + continue; + } + var found = false; + for (var q = 0; !found && q < tickVals.length; q++) { + if ( + // add 10e6 to eliminate problematic digits + 1e7 + tickVals[q].value === 1e7 + v + ) { + found = true; + } + } + if (!found) list.push(T); + } + minorTickVals = list; + } + } + if (isPeriod) positionPeriodTicks(allTicklabelVals, ax, ax._definedDelta); + var i; + if (ax.rangebreaks) { + var flip = ax._id.charAt(0) === "y"; + var fontSize = 1; + if (ax.tickmode === "auto") { + fontSize = ax.tickfont ? ax.tickfont.size : 12; + } + var prevL = NaN; + for (i = tickVals.length - 1; i > -1; i--) { + if (tickVals[i].drop) { + tickVals.splice(i, 1); + continue; + } + tickVals[i].value = moveOutsideBreak(tickVals[i].value, ax); + var l = ax.c2p(tickVals[i].value); + if (flip ? prevL > l - fontSize : prevL < l + fontSize) { + tickVals.splice(axrev ? i + 1 : i, 1); + } else { + prevL = l; + } + } + } + if (isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) { + tickVals.pop(); + } + ax._tmax = (tickVals[tickVals.length - 1] || {}).value; + ax._prevDateHead = ""; + ax._inCalcTicks = true; + var lastVisibleHead; + var hideLabel = function(tick) { + tick.text = ""; + ax._prevDateHead = lastVisibleHead; + }; + tickVals = tickVals.concat(minorTickVals); + function setTickLabel(ax2, tickVal) { + var text = axes.tickText( + ax2, + tickVal.value, + false, + // hover + tickVal.simpleLabel + // noSuffixPrefix + ); + var p = tickVal.periodX; + if (p !== void 0) { + text.periodX = p; + if (p > maxRange || p < minRange) { + if (p > maxRange) text.periodX = maxRange; + if (p < minRange) text.periodX = minRange; + hideLabel(text); + } + } + return text; + } + var t; + for (i = 0; i < tickVals.length; i++) { + var _minor = tickVals[i].minor; + var _value = tickVals[i].value; + if (_minor) { + if (ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) !== -1) { + t = setTickLabel(ax, tickVals[i]); + } else { + t = { x: _value }; + } + t.minor = true; + minorTicks.push(t); + } else { + lastVisibleHead = ax._prevDateHead; + t = setTickLabel(ax, tickVals[i]); + if (tickVals[i].skipLabel || ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) === -1) { + hideLabel(t); + } + ticksOut.push(t); + } + } + ticksOut = ticksOut.concat(minorTicks); + ax._inCalcTicks = false; + if (isPeriod && ticksOut.length) { + ticksOut[0].noTick = true; + } + return ticksOut; +}; +function filterRangeBreaks(ax, ticksOut) { + if (ax.rangebreaks) { + ticksOut = ticksOut.filter(function(d) { + return ax.maskBreaks(d.x) !== BADNUM$7; + }); + } + return ticksOut; +} +function syncTicks(ax) { + var baseAxis = ax._mainAxis; + var ticksOut = []; + if (baseAxis._vals) { + for (var i = 0; i < baseAxis._vals.length; i++) { + if (baseAxis._vals[i].noTick) { + continue; + } + var pos = baseAxis.l2p(baseAxis._vals[i].x); + var vali = ax.p2l(pos); + var obj = axes.tickText(ax, vali); + if (baseAxis._vals[i].minor) { + obj.minor = true; + obj.text = ""; + } + ticksOut.push(obj); + } + } + ticksOut = filterRangeBreaks(ax, ticksOut); + return ticksOut; +} +function arrayTicks(ax, majorOnly) { + var rng = Lib$1E.simpleMap(ax.range, ax.r2l); + var exRng = expandRange(rng); + var tickMin = Math.min(exRng[0], exRng[1]); + var tickMax = Math.max(exRng[0], exRng[1]); + var tickVal2l = ax.type === "category" ? ax.d2l_noadd : ax.d2l; + if (ax.type === "log" && String(ax.dtick).charAt(0) !== "L") { + ax.dtick = "L" + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1); + } + var ticksOut = []; + for (var isMinor = 0; isMinor <= 1; isMinor++) { + if (majorOnly !== void 0 && (majorOnly && isMinor || majorOnly === false && !isMinor)) continue; + if (isMinor && !ax.minor) continue; + var vals = !isMinor ? ax.tickvals : ax.minor.tickvals; + var text = !isMinor ? ax.ticktext : []; + if (!vals) continue; + if (!Lib$1E.isArrayOrTypedArray(text)) text = []; + for (var i = 0; i < vals.length; i++) { + var vali = tickVal2l(vals[i]); + if (vali > tickMin && vali < tickMax) { + var obj = axes.tickText(ax, vali, false, String(text[i])); + if (isMinor) { + obj.minor = true; + obj.text = ""; + } + ticksOut.push(obj); + } + } + } + ticksOut = filterRangeBreaks(ax, ticksOut); + return ticksOut; +} +var roundBase10 = [2, 5, 10]; +var roundBase24 = [1, 2, 3, 6, 12]; +var roundBase60 = [1, 2, 5, 10, 15, 30]; +var roundDays = [1, 2, 3, 7, 14]; +var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1]; +var roundLog2 = [-0.301, 0, 0.301, 0.699, 1]; +var roundAngles = [15, 30, 45, 90, 180]; +function roundDTick(roughDTick, base, roundingSet) { + return base * Lib$1E.roundUp(roughDTick / base, roundingSet); +} +axes.autoTicks = function(ax, roughDTick, isMinor) { + var base; + function getBase(v) { + return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); + } + if (ax.type === "date") { + ax.tick0 = Lib$1E.dateTick0(ax.calendar, 0); + var roughX2 = 2 * roughDTick; + if (roughX2 > ONEAVGYEAR) { + roughDTick /= ONEAVGYEAR; + base = getBase(10); + ax.dtick = "M" + 12 * roundDTick(roughDTick, base, roundBase10); + } else if (roughX2 > ONEAVGMONTH$1) { + roughDTick /= ONEAVGMONTH$1; + ax.dtick = "M" + roundDTick(roughDTick, 1, roundBase24); + } else if (roughX2 > ONEDAY) { + ax.dtick = roundDTick(roughDTick, ONEDAY, ax._hasDayOfWeekBreaks ? [1, 2, 7, 14] : roundDays); + if (!isMinor) { + var tickformat = axes.getTickFormat(ax); + var isPeriod = ax.ticklabelmode === "period"; + if (isPeriod) ax._rawTick0 = ax.tick0; + if (/%[uVW]/.test(tickformat)) { + ax.tick0 = Lib$1E.dateTick0(ax.calendar, 2); + } else { + ax.tick0 = Lib$1E.dateTick0(ax.calendar, 1); + } + if (isPeriod) ax._dowTick0 = ax.tick0; + } + } else if (roughX2 > ONEHOUR) { + ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24); + } else if (roughX2 > ONEMIN) { + ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60); + } else if (roughX2 > ONESEC) { + ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60); + } else { + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); + } + } else if (ax.type === "log") { + ax.tick0 = 0; + var rng = Lib$1E.simpleMap(ax.range, ax.r2l); + if (ax._isMinor) { + roughDTick *= 1.5; + } + if (roughDTick > 0.7) { + ax.dtick = Math.ceil(roughDTick); + } else if (Math.abs(rng[1] - rng[0]) < 1) { + var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick); + roughDTick = Math.abs(Math.pow(10, rng[1]) - Math.pow(10, rng[0])) / nt; + base = getBase(10); + ax.dtick = "L" + roundDTick(roughDTick, base, roundBase10); + } else { + ax.dtick = roughDTick > 0.3 ? "D2" : "D1"; + } + } else if (ax.type === "category" || ax.type === "multicategory") { + ax.tick0 = 0; + ax.dtick = Math.ceil(Math.max(roughDTick, 1)); + } else if (isAngular(ax)) { + ax.tick0 = 0; + base = 1; + ax.dtick = roundDTick(roughDTick, base, roundAngles); + } else { + ax.tick0 = 0; + base = getBase(10); + ax.dtick = roundDTick(roughDTick, base, roundBase10); + } + if (ax.dtick === 0) ax.dtick = 1; + if (!isNumeric$j(ax.dtick) && typeof ax.dtick !== "string") { + var olddtick = ax.dtick; + ax.dtick = 1; + throw "ax.dtick error: " + String(olddtick); + } +}; +function autoTickRound(ax) { + var dtick2 = ax.dtick; + ax._tickexponent = 0; + if (!isNumeric$j(dtick2) && typeof dtick2 !== "string") { + dtick2 = 1; + } + if (ax.type === "category" || ax.type === "multicategory") { + ax._tickround = null; + } + if (ax.type === "date") { + var tick0ms = ax.r2l(ax.tick0); + var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ""); + var tick0len = tick0str.length; + if (String(dtick2).charAt(0) === "M") { + if (tick0len > 10 || tick0str.substr(5) !== "01-01") ax._tickround = "d"; + else ax._tickround = +dtick2.substr(1) % 12 === 0 ? "y" : "m"; + } else if (dtick2 >= ONEDAY && tick0len <= 10 || dtick2 >= ONEDAY * 15) ax._tickround = "d"; + else if (dtick2 >= ONEMIN && tick0len <= 16 || dtick2 >= ONEHOUR) ax._tickround = "M"; + else if (dtick2 >= ONESEC && tick0len <= 19 || dtick2 >= ONEMIN) ax._tickround = "S"; + else { + var tick1len = ax.l2r(tick0ms + dtick2).replace(/^-/, "").length; + ax._tickround = Math.max(tick0len, tick1len) - 20; + if (ax._tickround < 0) ax._tickround = 4; + } + } else if (isNumeric$j(dtick2) || dtick2.charAt(0) === "L") { + var rng = ax.range.map(ax.r2d || Number); + if (!isNumeric$j(dtick2)) dtick2 = Number(dtick2.substr(1)); + ax._tickround = 2 - Math.floor(Math.log(dtick2) / Math.LN10 + 0.01); + var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1])); + var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01); + var minexponent = ax.minexponent === void 0 ? 3 : ax.minexponent; + if (Math.abs(rangeexp) > minexponent) { + if (isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) { + ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3); + } else ax._tickexponent = rangeexp; + } + } else { + ax._tickround = null; + } +} +axes.tickIncrement = function(x, dtick2, axrev, calendar) { + var axSign = axrev ? -1 : 1; + if (isNumeric$j(dtick2)) return Lib$1E.increment(x, axSign * dtick2); + var tType = dtick2.charAt(0); + var dtSigned = axSign * Number(dtick2.substr(1)); + if (tType === "M") return Lib$1E.incrementMonth(x, dtSigned, calendar); + if (tType === "L") return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; + if (tType === "D") { + var tickset = dtick2 === "D2" ? roundLog2 : roundLog1; + var x2 = x + axSign * 0.01; + var frac = Lib$1E.roundUp(Lib$1E.mod(x2, 1), tickset, axrev); + return Math.floor(x2) + Math.log(d3$v.round(Math.pow(10, frac), 1)) / Math.LN10; + } + throw "unrecognized dtick " + String(dtick2); +}; +axes.tickFirst = function(ax, opts) { + var r2l = ax.r2l || Number; + var rng = Lib$1E.simpleMap(ax.range, r2l, void 0, void 0, opts); + var axrev = rng[1] < rng[0]; + var sRound = axrev ? Math.floor : Math.ceil; + var r0 = expandRange(rng)[0]; + var dtick2 = ax.dtick; + var tick02 = r2l(ax.tick0); + if (isNumeric$j(dtick2)) { + var tmin = sRound((r0 - tick02) / dtick2) * dtick2 + tick02; + if (ax.type === "category" || ax.type === "multicategory") { + tmin = Lib$1E.constrain(tmin, 0, ax._categories.length - 1); + } + return tmin; + } + var tType = dtick2.charAt(0); + var dtNum = Number(dtick2.substr(1)); + if (tType === "M") { + var cnt = 0; + var t02 = tick02; + var t12, mult, newDTick; + while (cnt < 10) { + t12 = axes.tickIncrement(t02, dtick2, axrev, ax.calendar); + if ((t12 - r0) * (t02 - r0) <= 0) { + if (axrev) return Math.min(t02, t12); + return Math.max(t02, t12); + } + mult = (r0 - (t02 + t12) / 2) / (t12 - t02); + newDTick = tType + (Math.abs(Math.round(mult)) || 1) * dtNum; + t02 = axes.tickIncrement(t02, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); + cnt++; + } + Lib$1E.error("tickFirst did not converge", ax); + return t02; + } else if (tType === "L") { + return Math.log(sRound( + (Math.pow(10, r0) - tick02) / dtNum + ) * dtNum + tick02) / Math.LN10; + } else if (tType === "D") { + var tickset = dtick2 === "D2" ? roundLog2 : roundLog1; + var frac = Lib$1E.roundUp(Lib$1E.mod(r0, 1), tickset, axrev); + return Math.floor(r0) + Math.log(d3$v.round(Math.pow(10, frac), 1)) / Math.LN10; + } else throw "unrecognized dtick " + String(dtick2); +}; +axes.tickText = function(ax, x, hover3, noSuffixPrefix) { + var out = tickTextObj(ax, x); + var arrayMode = ax.tickmode === "array"; + var extraPrecision = hover3 || arrayMode; + var axType = ax.type; + var tickVal2l = axType === "category" ? ax.d2l_noadd : ax.d2l; + var i; + var inbounds = function(v) { + var p = ax.l2p(v); + return p >= 0 && p <= ax._length ? v : null; + }; + if (arrayMode && Lib$1E.isArrayOrTypedArray(ax.ticktext)) { + var rng = Lib$1E.simpleMap(ax.range, ax.r2l); + var minDiff = (Math.abs(rng[1] - rng[0]) - (ax._lBreaks || 0)) / 1e4; + for (i = 0; i < ax.ticktext.length; i++) { + if (Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break; + } + if (i < ax.ticktext.length) { + out.text = String(ax.ticktext[i]); + out.xbnd = [ + inbounds(out.x - 0.5), + inbounds(out.x + ax.dtick - 0.5) + ]; + return out; + } + } + function isHidden(showAttr) { + if (showAttr === void 0) return true; + if (hover3) return showAttr === "none"; + var firstOrLast = { + first: ax._tmin, + last: ax._tmax + }[showAttr]; + return showAttr !== "all" && x !== firstOrLast; + } + var hideexp = hover3 ? "never" : ax.exponentformat !== "none" && isHidden(ax.showexponent) ? "hide" : ""; + if (axType === "date") formatDate(ax, out, hover3, extraPrecision); + else if (axType === "log") formatLog(ax, out, hover3, extraPrecision, hideexp); + else if (axType === "category") formatCategory(ax, out); + else if (axType === "multicategory") formatMultiCategory(ax, out, hover3); + else if (isAngular(ax)) formatAngle(ax, out, hover3, extraPrecision, hideexp); + else formatLinear(ax, out, hover3, extraPrecision, hideexp); + if (!noSuffixPrefix) { + if (ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; + if (ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; + } + if (ax.labelalias && ax.labelalias.hasOwnProperty(out.text)) { + var t = ax.labelalias[out.text]; + if (typeof t === "string") out.text = t; + } + if (ax.tickson === "boundaries" || ax.showdividers) { + out.xbnd = [ + inbounds(out.x - 0.5), + inbounds(out.x + ax.dtick - 0.5) + ]; + } + return out; +}; +axes.hoverLabelText = function(ax, values, hoverformat) { + if (hoverformat) ax = Lib$1E.extendFlat({}, ax, { hoverformat }); + var val = Lib$1E.isArrayOrTypedArray(values) ? values[0] : values; + var val2 = Lib$1E.isArrayOrTypedArray(values) ? values[1] : void 0; + if (val2 !== void 0 && val2 !== val) { + return axes.hoverLabelText(ax, val, hoverformat) + " - " + axes.hoverLabelText(ax, val2, hoverformat); + } + var logOffScale = ax.type === "log" && val <= 0; + var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), "hover").text; + if (logOffScale) { + return val === 0 ? "0" : MINUS_SIGN + tx; + } + return tx; +}; +function tickTextObj(ax, x, text) { + var tf = ax.tickfont || {}; + return { + x, + dx: 0, + dy: 0, + text: text || "", + fontSize: tf.size, + font: tf.family, + fontWeight: tf.weight, + fontStyle: tf.style, + fontVariant: tf.variant, + fontTextcase: tf.textcase, + fontLineposition: tf.lineposition, + fontShadow: tf.shadow, + fontColor: tf.color + }; +} +function formatDate(ax, out, hover3, extraPrecision) { + var tr = ax._tickround; + var fmt = hover3 && ax.hoverformat || axes.getTickFormat(ax); + extraPrecision = !fmt && extraPrecision; + if (extraPrecision) { + if (isNumeric$j(tr)) tr = 4; + else tr = { y: "m", m: "d", d: "M", M: "S", S: 4 }[tr]; + } + var dateStr = Lib$1E.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat); + var headStr; + var splitIndex = dateStr.indexOf("\n"); + if (splitIndex !== -1) { + headStr = dateStr.substr(splitIndex + 1); + dateStr = dateStr.substr(0, splitIndex); + } + if (extraPrecision) { + if (headStr !== void 0 && (dateStr === "00:00:00" || dateStr === "00:00")) { + dateStr = headStr; + headStr = ""; + } else if (dateStr.length === 8) { + dateStr = dateStr.replace(/:00$/, ""); + } + } + if (headStr) { + if (hover3) { + if (tr === "d") dateStr += ", " + headStr; + else dateStr = headStr + (dateStr ? ", " + dateStr : ""); + } else { + if (!ax._inCalcTicks || ax._prevDateHead !== headStr) { + ax._prevDateHead = headStr; + dateStr += "
" + headStr; + } else { + var isInside = insideTicklabelposition(ax); + var side = ax._trueSide || ax.side; + if (!isInside && side === "top" || isInside && side === "bottom") { + dateStr += "
"; + } + } + } + } + out.text = dateStr; +} +function formatLog(ax, out, hover3, extraPrecision, hideexp) { + var dtick2 = ax.dtick; + var x = out.x; + var tickformat = ax.tickformat; + var dtChar0 = typeof dtick2 === "string" && dtick2.charAt(0); + if (hideexp === "never") { + hideexp = ""; + } + if (extraPrecision && dtChar0 !== "L") { + dtick2 = "L3"; + dtChar0 = "L"; + } + if (tickformat || dtChar0 === "L") { + out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); + } else if (isNumeric$j(dtick2) || dtChar0 === "D" && Lib$1E.mod(x + 0.01, 1) < 0.1) { + var p = Math.round(x); + var absP = Math.abs(p); + var exponentFormat = ax.exponentformat; + if (exponentFormat === "power" || isSIFormat(exponentFormat) && beyondSI(p)) { + if (p === 0) out.text = 1; + else if (p === 1) out.text = "10"; + else out.text = "10" + (p > 1 ? "" : MINUS_SIGN) + absP + ""; + out.fontSize *= 1.25; + } else if ((exponentFormat === "e" || exponentFormat === "E") && absP > 2) { + out.text = "1" + exponentFormat + (p > 0 ? "+" : MINUS_SIGN) + absP; + } else { + out.text = numFormat(Math.pow(10, x), ax, "", "fakehover"); + if (dtick2 === "D1" && ax._id.charAt(0) === "y") { + out.dy -= out.fontSize / 6; + } + } + } else if (dtChar0 === "D") { + out.text = String(Math.round(Math.pow(10, Lib$1E.mod(x, 1)))); + out.fontSize *= 0.75; + } else throw "unrecognized dtick " + String(dtick2); + if (ax.dtick === "D1") { + var firstChar = String(out.text).charAt(0); + if (firstChar === "0" || firstChar === "1") { + if (ax._id.charAt(0) === "y") { + out.dx -= out.fontSize / 4; + } else { + out.dy += out.fontSize / 2; + out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) * out.fontSize * (x < 0 ? 0.5 : 0.25); + } + } + } +} +function formatCategory(ax, out) { + var tt = ax._categories[Math.round(out.x)]; + if (tt === void 0) tt = ""; + out.text = String(tt); +} +function formatMultiCategory(ax, out, hover3) { + var v = Math.round(out.x); + var cats = ax._categories[v] || []; + var tt = cats[1] === void 0 ? "" : String(cats[1]); + var tt2 = cats[0] === void 0 ? "" : String(cats[0]); + if (hover3) { + out.text = tt2 + " - " + tt; + } else { + out.text = tt; + out.text2 = tt2; + } +} +function formatLinear(ax, out, hover3, extraPrecision, hideexp) { + if (hideexp === "never") { + hideexp = ""; + } else if (ax.showexponent === "all" && Math.abs(out.x / ax.dtick) < 1e-6) { + hideexp = "hide"; + } + out.text = numFormat(out.x, ax, hideexp, extraPrecision); +} +function formatAngle(ax, out, hover3, extraPrecision, hideexp) { + if (ax.thetaunit === "radians" && !hover3) { + var num = out.x / 180; + if (num === 0) { + out.text = "0"; + } else { + var frac = num2frac(num); + if (frac[1] >= 100) { + out.text = numFormat(Lib$1E.deg2rad(out.x), ax, hideexp, extraPrecision); + } else { + var isNeg = out.x < 0; + if (frac[1] === 1) { + if (frac[0] === 1) out.text = "π"; + else out.text = frac[0] + "π"; + } else { + out.text = [ + "", + frac[0], + "", + "⁄", + "", + frac[1], + "", + "π" + ].join(""); + } + if (isNeg) out.text = MINUS_SIGN + out.text; + } + } + } else { + out.text = numFormat(out.x, ax, hideexp, extraPrecision); + } +} +function num2frac(num) { + function almostEq(a, b) { + return Math.abs(a - b) <= 1e-6; + } + function findGCD(a, b) { + return almostEq(b, 0) ? a : findGCD(b, a % b); + } + function findPrecision(n) { + var e = 1; + while (!almostEq(Math.round(n * e) / e, n)) { + e *= 10; + } + return e; + } + var precision = findPrecision(num); + var number2 = num * precision; + var gcd = Math.abs(findGCD(number2, precision)); + return [ + // numerator + Math.round(number2 / gcd), + // denominator + Math.round(precision / gcd) + ]; +} +var SIPREFIXES = ["f", "p", "n", "μ", "m", "", "k", "M", "G", "T"]; +function isSIFormat(exponentFormat) { + return exponentFormat === "SI" || exponentFormat === "B"; +} +function beyondSI(exponent2) { + return exponent2 > 14 || exponent2 < -15; +} +function numFormat(v, ax, fmtoverride, hover3) { + var isNeg = v < 0; + var tickRound = ax._tickround; + var exponentFormat = fmtoverride || ax.exponentformat || "B"; + var exponent2 = ax._tickexponent; + var tickformat = axes.getTickFormat(ax); + var separatethousands = ax.separatethousands; + if (hover3) { + var ah = { + exponentformat: exponentFormat, + minexponent: ax.minexponent, + dtick: ax.showexponent === "none" ? ax.dtick : isNumeric$j(v) ? Math.abs(v) || 1 : 1, + // if not showing any exponents, don't change the exponent + // from what we calculate + range: ax.showexponent === "none" ? ax.range.map(ax.r2d) : [0, v || 1] + }; + autoTickRound(ah); + tickRound = (Number(ah._tickround) || 0) + 4; + exponent2 = ah._tickexponent; + if (ax.hoverformat) tickformat = ax.hoverformat; + } + if (tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); + var e = Math.pow(10, -tickRound) / 2; + if (exponentFormat === "none") exponent2 = 0; + v = Math.abs(v); + if (v < e) { + v = "0"; + isNeg = false; + } else { + v += e; + if (exponent2) { + v *= Math.pow(10, -exponent2); + tickRound += exponent2; + } + if (tickRound === 0) v = String(Math.floor(v)); + else if (tickRound < 0) { + v = String(Math.round(v)); + v = v.substr(0, v.length + tickRound); + for (var i = tickRound; i < 0; i++) v += "0"; + } else { + v = String(v); + var dp = v.indexOf(".") + 1; + if (dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ""); + } + v = Lib$1E.numSeparate(v, ax._separators, separatethousands); + } + if (exponent2 && exponentFormat !== "hide") { + if (isSIFormat(exponentFormat) && beyondSI(exponent2)) exponentFormat = "power"; + var signedExponent; + if (exponent2 < 0) signedExponent = MINUS_SIGN + -exponent2; + else if (exponentFormat !== "power") signedExponent = "+" + exponent2; + else signedExponent = String(exponent2); + if (exponentFormat === "e" || exponentFormat === "E") { + v += exponentFormat + signedExponent; + } else if (exponentFormat === "power") { + v += "×10" + signedExponent + ""; + } else if (exponentFormat === "B" && exponent2 === 9) { + v += "B"; + } else if (isSIFormat(exponentFormat)) { + v += SIPREFIXES[exponent2 / 3 + 5]; + } + } + if (isNeg) return MINUS_SIGN + v; + return v; +} +axes.getTickFormat = function(ax) { + var i; + function convertToMs(dtick2) { + return typeof dtick2 !== "string" ? dtick2 : Number(dtick2.replace("M", "")) * ONEAVGMONTH$1; + } + function compareLogTicks(left, right) { + var priority = ["L", "D"]; + if (typeof left === typeof right) { + if (typeof left === "number") { + return left - right; + } else { + var leftPriority = priority.indexOf(left.charAt(0)); + var rightPriority = priority.indexOf(right.charAt(0)); + if (leftPriority === rightPriority) { + return Number(left.replace(/(L|D)/g, "")) - Number(right.replace(/(L|D)/g, "")); + } else { + return leftPriority - rightPriority; + } + } + } else { + return typeof left === "number" ? 1 : -1; + } + } + function isProperStop(dtick2, range, convert3) { + var convertFn = convert3 || function(x) { + return x; + }; + var leftDtick = range[0]; + var rightDtick = range[1]; + return (!leftDtick && typeof leftDtick !== "number" || convertFn(leftDtick) <= convertFn(dtick2)) && (!rightDtick && typeof rightDtick !== "number" || convertFn(rightDtick) >= convertFn(dtick2)); + } + function isProperLogStop(dtick2, range) { + var isLeftDtickNull = range[0] === null; + var isRightDtickNull = range[1] === null; + var isDtickInRangeLeft = compareLogTicks(dtick2, range[0]) >= 0; + var isDtickInRangeRight = compareLogTicks(dtick2, range[1]) <= 0; + return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight); + } + var tickstop, stopi; + if (ax.tickformatstops && ax.tickformatstops.length > 0) { + switch (ax.type) { + case "date": + case "linear": { + for (i = 0; i < ax.tickformatstops.length; i++) { + stopi = ax.tickformatstops[i]; + if (stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) { + tickstop = stopi; + break; + } + } + break; + } + case "log": { + for (i = 0; i < ax.tickformatstops.length; i++) { + stopi = ax.tickformatstops[i]; + if (stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) { + tickstop = stopi; + break; + } + } + break; + } + } + } + return tickstop ? tickstop.value : ax.tickformat; +}; +axes.getSubplots = function(gd, ax) { + var subplotObj = gd._fullLayout._subplots; + var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); + var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; + out.sort(function(a, b) { + var aParts = a.substr(1).split("y"); + var bParts = b.substr(1).split("y"); + if (aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; + return +aParts[0] - +bParts[0]; + }); + return out; +}; +axes.findSubplotsWithAxis = function(subplots, ax) { + var axMatch = new RegExp( + ax._id.charAt(0) === "x" ? "^" + ax._id + "y" : ax._id + "$" + ); + var subplotsWithAx = []; + for (var i = 0; i < subplots.length; i++) { + var sp = subplots[i]; + if (axMatch.test(sp)) subplotsWithAx.push(sp); + } + return subplotsWithAx; +}; +axes.makeClipPaths = function(gd) { + var fullLayout = gd._fullLayout; + if (fullLayout._hasOnlyLargeSploms) return; + var fullWidth = { _offset: 0, _length: fullLayout.width, _id: "" }; + var fullHeight = { _offset: 0, _length: fullLayout.height, _id: "" }; + var xaList = axes.list(gd, "x", true); + var yaList = axes.list(gd, "y", true); + var clipList = []; + var i, j; + for (i = 0; i < xaList.length; i++) { + clipList.push({ x: xaList[i], y: fullHeight }); + for (j = 0; j < yaList.length; j++) { + if (i === 0) clipList.push({ x: fullWidth, y: yaList[j] }); + clipList.push({ x: xaList[i], y: yaList[j] }); + } + } + var axClips = fullLayout._clips.selectAll(".axesclip").data(clipList, function(d) { + return d.x._id + d.y._id; + }); + axClips.enter().append("clipPath").classed("axesclip", true).attr("id", function(d) { + return "clip" + fullLayout._uid + d.x._id + d.y._id; + }).append("rect"); + axClips.exit().remove(); + axClips.each(function(d) { + d3$v.select(this).select("rect").attr({ + x: d.x._offset || 0, + y: d.y._offset || 0, + width: d.x._length || 1, + height: d.y._length || 1 + }); + }); +}; +axes.draw = function(gd, arg, opts) { + var fullLayout = gd._fullLayout; + if (arg === "redraw") { + fullLayout._paper.selectAll("g.subplot").each(function(d) { + var id = d[0]; + var plotinfo = fullLayout._plots[id]; + if (plotinfo) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + plotinfo.xaxislayer.selectAll("." + xa._id + "tick").remove(); + plotinfo.yaxislayer.selectAll("." + ya._id + "tick").remove(); + plotinfo.xaxislayer.selectAll("." + xa._id + "tick2").remove(); + plotinfo.yaxislayer.selectAll("." + ya._id + "tick2").remove(); + plotinfo.xaxislayer.selectAll("." + xa._id + "divider").remove(); + plotinfo.yaxislayer.selectAll("." + ya._id + "divider").remove(); + if (plotinfo.minorGridlayer) plotinfo.minorGridlayer.selectAll("path").remove(); + if (plotinfo.gridlayer) plotinfo.gridlayer.selectAll("path").remove(); + if (plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll("path").remove(); + fullLayout._infolayer.select(".g-" + xa._id + "title").remove(); + fullLayout._infolayer.select(".g-" + ya._id + "title").remove(); + } + }); + } + var axList = !arg || arg === "redraw" ? axes.listIds(gd) : arg; + var fullAxList = axes.list(gd); + var overlayingShiftedAx = fullAxList.filter(function(ax) { + return ax.autoshift; + }).map(function(ax) { + return ax.overlaying; + }); + axList.map(function(axId) { + var ax = axes.getFromId(gd, axId); + if (ax.tickmode === "sync" && ax.overlaying) { + var overlayingIndex = axList.findIndex(function(axis) { + return axis === ax.overlaying; + }); + if (overlayingIndex >= 0) { + axList.unshift(axList.splice(overlayingIndex, 1).shift()); + } + } + }); + var axShifts = { false: { left: 0, right: 0 } }; + return Lib$1E.syncOrAsync(axList.map(function(axId) { + return function() { + if (!axId) return; + var ax = axes.getFromId(gd, axId); + if (!opts) opts = {}; + opts.axShifts = axShifts; + opts.overlayingShiftedAx = overlayingShiftedAx; + var axDone = axes.drawOne(gd, ax, opts); + if (ax._shiftPusher) { + incrementShift(ax, ax._fullDepth || 0, axShifts, true); + } + ax._r = ax.range.slice(); + ax._rl = Lib$1E.simpleMap(ax._r, ax.r2l); + return axDone; + }; + })); +}; +axes.drawOne = function(gd, ax, opts) { + opts = opts || {}; + var axShifts = opts.axShifts || {}; + var overlayingShiftedAx = opts.overlayingShiftedAx || []; + var i, sp, plotinfo; + ax.setScale(); + var fullLayout = gd._fullLayout; + var axId = ax._id; + var axLetter = axId.charAt(0); + var counterLetter = axes.counterLetter(axId); + var mainPlotinfo = fullLayout._plots[ax._mainSubplot]; + if (!mainPlotinfo) return; + ax._shiftPusher = ax.autoshift || overlayingShiftedAx.indexOf(ax._id) !== -1 || overlayingShiftedAx.indexOf(ax.overlaying) !== -1; + if (ax._shiftPusher & ax.anchor === "free") { + var selfPush = ax.linewidth / 2 || 0; + if (ax.ticks === "inside") { + selfPush += ax.ticklen; + } + incrementShift(ax, selfPush, axShifts, true); + incrementShift(ax, ax.shift || 0, axShifts, false); + } + if (opts.skipTitle !== true || ax._shift === void 0) ax._shift = setShiftVal(ax, axShifts); + var mainAxLayer = mainPlotinfo[axLetter + "axislayer"]; + var mainLinePosition = ax._mainLinePosition; + var mainLinePositionShift = mainLinePosition += ax._shift; + var mainMirrorPosition = ax._mainMirrorPosition; + var vals = ax._vals = axes.calcTicks(ax); + var axInfo = [ax.mirror, mainLinePositionShift, mainMirrorPosition].join("_"); + for (i = 0; i < vals.length; i++) { + vals[i].axInfo = axInfo; + } + ax._selections = {}; + if (ax._tickAngles) ax._prevTickAngles = ax._tickAngles; + ax._tickAngles = {}; + ax._depth = null; + var llbboxes = {}; + function getLabelLevelBbox(suffix) { + var cls = axId + (suffix || "tick"); + if (!llbboxes[cls]) llbboxes[cls] = calcLabelLevelBbox(ax, cls, mainLinePositionShift); + return llbboxes[cls]; + } + if (!ax.visible) return; + var transTickFn = axes.makeTransTickFn(ax); + var transTickLabelFn = axes.makeTransTickLabelFn(ax); + var tickVals; + var valsClipped; + var insideTicks = ax.ticks === "inside"; + var outsideTicks = ax.ticks === "outside"; + if (ax.tickson === "boundaries") { + var boundaryVals = getBoundaryVals(ax, vals); + valsClipped = axes.clipEnds(ax, boundaryVals); + tickVals = insideTicks ? valsClipped : boundaryVals; + } else { + valsClipped = axes.clipEnds(ax, vals); + tickVals = insideTicks && ax.ticklabelmode !== "period" ? valsClipped : vals; + } + var gridVals = ax._gridVals = valsClipped; + var dividerVals = getDividerVals(ax, vals); + if (!fullLayout._hasOnlyLargeSploms) { + var subplotsWithAx = ax._subplotsWith; + var finishedGrids = {}; + for (i = 0; i < subplotsWithAx.length; i++) { + sp = subplotsWithAx[i]; + plotinfo = fullLayout._plots[sp]; + var counterAxis = plotinfo[counterLetter + "axis"]; + var mainCounterID = counterAxis._mainAxis._id; + if (finishedGrids[mainCounterID]) continue; + finishedGrids[mainCounterID] = 1; + var gridPath = axLetter === "x" ? "M0," + counterAxis._offset + "v" + counterAxis._length : "M" + counterAxis._offset + ",0h" + counterAxis._length; + axes.drawGrid(gd, ax, { + vals: gridVals, + counterAxis, + layer: plotinfo.gridlayer.select("." + axId), + minorLayer: plotinfo.minorGridlayer.select("." + axId), + path: gridPath, + transFn: transTickFn + }); + axes.drawZeroLine(gd, ax, { + counterAxis, + layer: plotinfo.zerolinelayer, + path: gridPath, + transFn: transTickFn + }); + } + } + var tickPath; + var majorTickSigns = axes.getTickSigns(ax); + var minorTickSigns = axes.getTickSigns(ax, "minor"); + if (ax.ticks || ax.minor && ax.minor.ticks) { + var majorTickPath = axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[2]); + var minorTickPath = axes.makeTickPath(ax, mainLinePositionShift, minorTickSigns[2], { minor: true }); + var mirrorMajorTickPath; + var mirrorMinorTickPath; + var fullMajorTickPath; + var fullMinorTickPath; + if (ax._anchorAxis && ax.mirror && ax.mirror !== true) { + mirrorMajorTickPath = axes.makeTickPath(ax, mainMirrorPosition, majorTickSigns[3]); + mirrorMinorTickPath = axes.makeTickPath(ax, mainMirrorPosition, minorTickSigns[3], { minor: true }); + fullMajorTickPath = majorTickPath + mirrorMajorTickPath; + fullMinorTickPath = minorTickPath + mirrorMinorTickPath; + } else { + mirrorMajorTickPath = ""; + mirrorMinorTickPath = ""; + fullMajorTickPath = majorTickPath; + fullMinorTickPath = minorTickPath; + } + if (ax.showdividers && outsideTicks && ax.tickson === "boundaries") { + var dividerLookup = {}; + for (i = 0; i < dividerVals.length; i++) { + dividerLookup[dividerVals[i].x] = 1; + } + tickPath = function(d) { + return dividerLookup[d.x] ? mirrorMajorTickPath : fullMajorTickPath; + }; + } else { + tickPath = function(d) { + return d.minor ? fullMinorTickPath : fullMajorTickPath; + }; + } + } + axes.drawTicks(gd, ax, { + vals: tickVals, + layer: mainAxLayer, + path: tickPath, + transFn: transTickFn + }); + if (ax.mirror === "allticks") { + var tickSubplots = Object.keys(ax._linepositions || {}); + for (i = 0; i < tickSubplots.length; i++) { + sp = tickSubplots[i]; + plotinfo = fullLayout._plots[sp]; + var linepositions = ax._linepositions[sp] || []; + var p0 = linepositions[0]; + var p1 = linepositions[1]; + var isMinor = linepositions[2]; + var spTickPath = axes.makeTickPath( + ax, + p0, + isMinor ? majorTickSigns[0] : minorTickSigns[0], + { minor: isMinor } + ) + axes.makeTickPath( + ax, + p1, + isMinor ? majorTickSigns[1] : minorTickSigns[1], + { minor: isMinor } + ); + axes.drawTicks(gd, ax, { + vals: tickVals, + layer: plotinfo[axLetter + "axislayer"], + path: spTickPath, + transFn: transTickFn + }); + } + } + var seq = []; + seq.push(function() { + return axes.drawLabels(gd, ax, { + vals, + layer: mainAxLayer, + plotinfo, + transFn: transTickLabelFn, + labelFns: axes.makeLabelFns(ax, mainLinePositionShift) + }); + }); + if (ax.type === "multicategory") { + var pad2 = { x: 2, y: 10 }[axLetter]; + seq.push(function() { + var bboxKey = { x: "height", y: "width" }[axLetter]; + var standoff = getLabelLevelBbox()[bboxKey] + pad2 + (ax._tickAngles[axId + "tick"] ? ax.tickfont.size * LINE_SPACING$6 : 0); + return axes.drawLabels(gd, ax, { + vals: getSecondaryLabelVals(ax, vals), + layer: mainAxLayer, + cls: axId + "tick2", + repositionOnUpdate: true, + secondary: true, + transFn: transTickFn, + labelFns: axes.makeLabelFns(ax, mainLinePositionShift + standoff * majorTickSigns[4]) + }); + }); + seq.push(function() { + ax._depth = majorTickSigns[4] * (getLabelLevelBbox("tick2")[ax.side] - mainLinePositionShift); + return drawDividers(gd, ax, { + vals: dividerVals, + layer: mainAxLayer, + path: axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[4], { len: ax._depth }), + transFn: transTickFn + }); + }); + } else if (ax.title.hasOwnProperty("standoff")) { + seq.push(function() { + ax._depth = majorTickSigns[4] * (getLabelLevelBbox()[ax.side] - mainLinePositionShift); + }); + } + var hasRangeSlider = Registry$I.getComponentMethod("rangeslider", "isVisible")(ax); + if (!opts.skipTitle && !(hasRangeSlider && ax.side === "bottom")) { + seq.push(function() { + return drawTitle(gd, ax); + }); + } + seq.push(function() { + var s = ax.side.charAt(0); + var sMirror = OPPOSITE_SIDE[ax.side].charAt(0); + var pos = axes.getPxPosition(gd, ax); + var outsideTickLen = outsideTicks ? ax.ticklen : 0; + var llbbox; + var push; + var mirrorPush; + var rangeSliderPush; + if (ax.automargin || hasRangeSlider || ax._shiftPusher) { + if (ax.type === "multicategory") { + llbbox = getLabelLevelBbox("tick2"); + } else { + llbbox = getLabelLevelBbox(); + if (axLetter === "x" && s === "b") { + ax._depth = Math.max(llbbox.width > 0 ? llbbox.bottom - pos : 0, outsideTickLen); + } + } + } + var axDepth = 0; + var titleDepth = 0; + if (ax._shiftPusher) { + axDepth = Math.max( + outsideTickLen, + llbbox.height > 0 ? s === "l" ? pos - llbbox.left : llbbox.right - pos : 0 + ); + if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { + titleDepth = (ax._titleStandoff || 0) + (ax._titleScoot || 0); + if (s === "l") { + titleDepth += approxTitleDepth(ax); + } + } + ax._fullDepth = Math.max(axDepth, titleDepth); + } + if (ax.automargin) { + push = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 }; + var domainIndices = [0, 1]; + var shift = typeof ax._shift === "number" ? ax._shift : 0; + if (axLetter === "x") { + if (s === "b") { + push[s] = ax._depth; + } else { + push[s] = ax._depth = Math.max(llbbox.width > 0 ? pos - llbbox.top : 0, outsideTickLen); + domainIndices.reverse(); + } + if (llbbox.width > 0) { + var rExtra = llbbox.right - (ax._offset + ax._length); + if (rExtra > 0) { + push.xr = 1; + push.r = rExtra; + } + var lExtra = ax._offset - llbbox.left; + if (lExtra > 0) { + push.xl = 0; + push.l = lExtra; + } + } + } else { + if (s === "l") { + ax._depth = Math.max(llbbox.height > 0 ? pos - llbbox.left : 0, outsideTickLen); + push[s] = ax._depth - shift; + } else { + ax._depth = Math.max(llbbox.height > 0 ? llbbox.right - pos : 0, outsideTickLen); + push[s] = ax._depth + shift; + domainIndices.reverse(); + } + if (llbbox.height > 0) { + var bExtra = llbbox.bottom - (ax._offset + ax._length); + if (bExtra > 0) { + push.yb = 0; + push.b = bExtra; + } + var tExtra = ax._offset - llbbox.top; + if (tExtra > 0) { + push.yt = 1; + push.t = tExtra; + } + } + } + push[counterLetter] = ax.anchor === "free" ? ax.position : ax._anchorAxis.domain[domainIndices[0]]; + if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { + push[s] += approxTitleDepth(ax) + (ax.title.standoff || 0); + } + if (ax.mirror && ax.anchor !== "free") { + mirrorPush = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 }; + mirrorPush[sMirror] = ax.linewidth; + if (ax.mirror && ax.mirror !== true) mirrorPush[sMirror] += outsideTickLen; + if (ax.mirror === true || ax.mirror === "ticks") { + mirrorPush[counterLetter] = ax._anchorAxis.domain[domainIndices[1]]; + } else if (ax.mirror === "all" || ax.mirror === "allticks") { + mirrorPush[counterLetter] = [ax._counterDomainMin, ax._counterDomainMax][domainIndices[1]]; + } + } + } + if (hasRangeSlider) { + rangeSliderPush = Registry$I.getComponentMethod("rangeslider", "autoMarginOpts")(gd, ax); + } + if (typeof ax.automargin === "string") { + filterPush(push, ax.automargin); + filterPush(mirrorPush, ax.automargin); + } + Plots$b.autoMargin(gd, axAutoMarginID(ax), push); + Plots$b.autoMargin(gd, axMirrorAutoMarginID(ax), mirrorPush); + Plots$b.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush); + }); + return Lib$1E.syncOrAsync(seq); +}; +function filterPush(push, automargin) { + if (!push) return; + var keepMargin = Object.keys(MARGIN_MAPPING).reduce(function(data, nextKey) { + if (automargin.indexOf(nextKey) !== -1) { + MARGIN_MAPPING[nextKey].forEach(function(key) { + data[key] = 1; + }); + } + return data; + }, {}); + Object.keys(push).forEach(function(key) { + if (!keepMargin[key]) { + if (key.length === 1) push[key] = 0; + else delete push[key]; + } + }); +} +function getBoundaryVals(ax, vals) { + var out = []; + var i; + var _push = function(d, bndIndex) { + var xb = d.xbnd[bndIndex]; + if (xb !== null) { + out.push(Lib$1E.extendFlat({}, d, { x: xb })); + } + }; + if (vals.length) { + for (i = 0; i < vals.length; i++) { + _push(vals[i], 0); + } + _push(vals[i - 1], 1); + } + return out; +} +function getSecondaryLabelVals(ax, vals) { + var out = []; + var lookup2 = {}; + for (var i = 0; i < vals.length; i++) { + var d = vals[i]; + if (lookup2[d.text2]) { + lookup2[d.text2].push(d.x); + } else { + lookup2[d.text2] = [d.x]; + } + } + for (var k in lookup2) { + out.push(tickTextObj(ax, Lib$1E.interp(lookup2[k], 0.5), k)); + } + return out; +} +function getDividerVals(ax, vals) { + var out = []; + var i, current; + var reversed = vals.length && vals[vals.length - 1].x < vals[0].x; + var _push = function(d2, bndIndex) { + var xb = d2.xbnd[bndIndex]; + if (xb !== null) { + out.push(Lib$1E.extendFlat({}, d2, { x: xb })); + } + }; + if (ax.showdividers && vals.length) { + for (i = 0; i < vals.length; i++) { + var d = vals[i]; + if (d.text2 !== current) { + _push(d, reversed ? 1 : 0); + } + current = d.text2; + } + _push(vals[i - 1], reversed ? 0 : 1); + } + return out; +} +function calcLabelLevelBbox(ax, cls, mainLinePositionShift) { + var top, bottom; + var left, right; + if (ax._selections[cls].size()) { + top = Infinity; + bottom = -Infinity; + left = Infinity; + right = -Infinity; + ax._selections[cls].each(function() { + var thisLabel = selectTickLabel(this); + var bb = Drawing$s.bBox(thisLabel.node().parentNode); + top = Math.min(top, bb.top); + bottom = Math.max(bottom, bb.bottom); + left = Math.min(left, bb.left); + right = Math.max(right, bb.right); + }); + } else { + var dummyCalc = axes.makeLabelFns(ax, mainLinePositionShift); + top = bottom = dummyCalc.yFn({ dx: 0, dy: 0, fontSize: 0 }); + left = right = dummyCalc.xFn({ dx: 0, dy: 0, fontSize: 0 }); + } + return { + top, + bottom, + left, + right, + height: bottom - top, + width: right - left + }; +} +axes.getTickSigns = function(ax, minor) { + var axLetter = ax._id.charAt(0); + var sideOpposite = { x: "top", y: "right" }[axLetter]; + var main2 = ax.side === sideOpposite ? 1 : -1; + var out = [-1, 1, main2, -main2]; + var ticks2 = minor ? (ax.minor || {}).ticks : ax.ticks; + if (ticks2 !== "inside" === (axLetter === "x")) { + out = out.map(function(v) { + return -v; + }); + } + if (ax.side) { + out.push({ l: -1, t: -1, r: 1, b: 1 }[ax.side.charAt(0)]); + } + return out; +}; +axes.makeTransTickFn = function(ax) { + return ax._id.charAt(0) === "x" ? function(d) { + return strTranslate$a(ax._offset + ax.l2p(d.x), 0); + } : function(d) { + return strTranslate$a(0, ax._offset + ax.l2p(d.x)); + }; +}; +axes.makeTransTickLabelFn = function(ax) { + var uv = getTickLabelUV(ax); + var shift = ax.ticklabelshift || 0; + var standoff = ax.ticklabelstandoff || 0; + var u = uv[0]; + var v = uv[1]; + var isReversed2 = ax.range[0] > ax.range[1]; + var labelsInside = ax.ticklabelposition && ax.ticklabelposition.indexOf("inside") !== -1; + var labelsOutside = !labelsInside; + if (shift) { + var shiftSign = isReversed2 ? -1 : 1; + shift = shift * shiftSign; + } + if (standoff) { + var side = ax.side; + var standoffSign = labelsInside && (side === "top" || side === "left") || labelsOutside && (side === "bottom" || side === "right") ? 1 : -1; + standoff = standoff * standoffSign; + } + return ax._id.charAt(0) === "x" ? function(d) { + return strTranslate$a( + u + ax._offset + ax.l2p(getPosX(d)) + shift, + v + standoff + ); + } : function(d) { + return strTranslate$a( + v + standoff, + u + ax._offset + ax.l2p(getPosX(d)) + shift + ); + }; +}; +function getPosX(d) { + return d.periodX !== void 0 ? d.periodX : d.x; +} +function getTickLabelUV(ax) { + var ticklabelposition = ax.ticklabelposition || ""; + var has = function(str2) { + return ticklabelposition.indexOf(str2) !== -1; + }; + var isTop = has("top"); + var isLeft = has("left"); + var isRight = has("right"); + var isBottom = has("bottom"); + var isInside = has("inside"); + var isAligned = isBottom || isLeft || isTop || isRight; + if (!isAligned && !isInside) return [0, 0]; + var side = ax.side; + var u = isAligned ? (ax.tickwidth || 0) / 2 : 0; + var v = TEXTPAD$4; + var fontSize = ax.tickfont ? ax.tickfont.size : 12; + if (isBottom || isTop) { + u += fontSize * CAP_SHIFT; + v += (ax.linewidth || 0) / 2; + } + if (isLeft || isRight) { + u += (ax.linewidth || 0) / 2; + v += TEXTPAD$4; + } + if (isInside && side === "top") { + v -= fontSize * (1 - CAP_SHIFT); + } + if (isLeft || isTop) u = -u; + if (side === "bottom" || side === "right") v = -v; + return [ + isAligned ? u : 0, + isInside ? v : 0 + ]; +} +axes.makeTickPath = function(ax, shift, sgn, opts) { + if (!opts) opts = {}; + var minor = opts.minor; + if (minor && !ax.minor) return ""; + var len = opts.len !== void 0 ? opts.len : minor ? ax.minor.ticklen : ax.ticklen; + var axLetter = ax._id.charAt(0); + var pad2 = (ax.linewidth || 1) / 2; + return axLetter === "x" ? "M0," + (shift + pad2 * sgn) + "v" + len * sgn : "M" + (shift + pad2 * sgn) + ",0h" + len * sgn; +}; +axes.makeLabelFns = function(ax, shift, angle) { + var ticklabelposition = ax.ticklabelposition || ""; + var has = function(str2) { + return ticklabelposition.indexOf(str2) !== -1; + }; + var isTop = has("top"); + var isLeft = has("left"); + var isRight = has("right"); + var isBottom = has("bottom"); + var isAligned = isBottom || isLeft || isTop || isRight; + var insideTickLabels = has("inside"); + var labelsOverTicks = ticklabelposition === "inside" && ax.ticks === "inside" || !insideTickLabels && ax.ticks === "outside" && ax.tickson !== "boundaries"; + var labelStandoff = 0; + var labelShift = 0; + var tickLen = labelsOverTicks ? ax.ticklen : 0; + if (insideTickLabels) { + tickLen *= -1; + } else if (isAligned) { + tickLen = 0; + } + if (labelsOverTicks) { + labelStandoff += tickLen; + if (angle) { + var rad = Lib$1E.deg2rad(angle); + labelStandoff = tickLen * Math.cos(rad) + 1; + labelShift = tickLen * Math.sin(rad); + } + } + if (ax.showticklabels && (labelsOverTicks || ax.showline)) { + labelStandoff += 0.2 * ax.tickfont.size; + } + labelStandoff += (ax.linewidth || 1) / 2 * (insideTickLabels ? -1 : 1); + var out = { + labelStandoff, + labelShift + }; + var x0, y0, ff, flipIt; + var xQ = 0; + var side = ax.side; + var axLetter = ax._id.charAt(0); + var tickangle = ax.tickangle; + var endSide; + if (axLetter === "x") { + endSide = !insideTickLabels && side === "bottom" || insideTickLabels && side === "top"; + flipIt = endSide ? 1 : -1; + if (insideTickLabels) flipIt *= -1; + x0 = labelShift * flipIt; + y0 = shift + labelStandoff * flipIt; + ff = endSide ? 1 : -0.2; + if (Math.abs(tickangle) === 90) { + if (insideTickLabels) { + ff += MID_SHIFT; + } else { + if (tickangle === -90 && side === "bottom") { + ff = CAP_SHIFT; + } else if (tickangle === 90 && side === "top") { + ff = MID_SHIFT; + } else { + ff = 0.5; + } + } + xQ = MID_SHIFT / 2 * (tickangle / 90); + } + out.xFn = function(d) { + return d.dx + x0 + xQ * d.fontSize; + }; + out.yFn = function(d) { + return d.dy + y0 + d.fontSize * ff; + }; + out.anchorFn = function(d, a) { + if (isAligned) { + if (isLeft) return "end"; + if (isRight) return "start"; + } + if (!isNumeric$j(a) || a === 0 || a === 180) { + return "middle"; + } + return a * flipIt < 0 !== insideTickLabels ? "end" : "start"; + }; + out.heightFn = function(d, a, h) { + return a < -60 || a > 60 ? -0.5 * h : ax.side === "top" !== insideTickLabels ? -h : 0; + }; + } else if (axLetter === "y") { + endSide = !insideTickLabels && side === "left" || insideTickLabels && side === "right"; + flipIt = endSide ? 1 : -1; + if (insideTickLabels) flipIt *= -1; + x0 = labelStandoff; + y0 = labelShift * flipIt; + ff = 0; + if (!insideTickLabels && Math.abs(tickangle) === 90) { + if (tickangle === -90 && side === "left" || tickangle === 90 && side === "right") { + ff = CAP_SHIFT; + } else { + ff = 0.5; + } + } + if (insideTickLabels) { + var ang = isNumeric$j(tickangle) ? +tickangle : 0; + if (ang !== 0) { + var rA = Lib$1E.deg2rad(ang); + xQ = Math.abs(Math.sin(rA)) * CAP_SHIFT * flipIt; + ff = 0; + } + } + out.xFn = function(d) { + return d.dx + shift - (x0 + d.fontSize * ff) * flipIt + xQ * d.fontSize; + }; + out.yFn = function(d) { + return d.dy + y0 + d.fontSize * MID_SHIFT; + }; + out.anchorFn = function(d, a) { + if (isNumeric$j(a) && Math.abs(a) === 90) { + return "middle"; + } + return endSide ? "end" : "start"; + }; + out.heightFn = function(d, a, h) { + if (ax.side === "right") a *= -1; + return a < -30 ? -h : a < 30 ? -0.5 * h : 0; + }; + } + return out; +}; +function tickDataFn(d) { + return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join("_"); +} +axes.drawTicks = function(gd, ax, opts) { + opts = opts || {}; + var cls = ax._id + "tick"; + var vals = [].concat( + ax.minor && ax.minor.ticks ? ( + // minor vals + opts.vals.filter(function(d) { + return d.minor && !d.noTick; + }) + ) : [] + ).concat( + ax.ticks ? ( + // major vals + opts.vals.filter(function(d) { + return !d.minor && !d.noTick; + }) + ) : [] + ); + var ticks2 = opts.layer.selectAll("path." + cls).data(vals, tickDataFn); + ticks2.exit().remove(); + ticks2.enter().append("path").classed(cls, 1).classed("ticks", 1).classed("crisp", opts.crisp !== false).each(function(d) { + return Color$H.stroke(d3$v.select(this), d.minor ? ax.minor.tickcolor : ax.tickcolor); + }).style("stroke-width", function(d) { + return Drawing$s.crispRound( + gd, + d.minor ? ax.minor.tickwidth : ax.tickwidth, + 1 + ) + "px"; + }).attr("d", opts.path).style("display", null); + hideCounterAxisInsideTickLabels(ax, [TICK_PATH]); + ticks2.attr("transform", opts.transFn); +}; +axes.drawGrid = function(gd, ax, opts) { + opts = opts || {}; + if (ax.tickmode === "sync") { + return; + } + var cls = ax._id + "grid"; + var hasMinor = ax.minor && ax.minor.showgrid; + var minorVals = hasMinor ? opts.vals.filter(function(d) { + return d.minor; + }) : []; + var majorVals = ax.showgrid ? opts.vals.filter(function(d) { + return !d.minor; + }) : []; + var counterAx = opts.counterAxis; + if (counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) { + var isArrayMode = ax.tickmode === "array"; + for (var i = 0; i < majorVals.length; i++) { + var xi = majorVals[i].x; + if (isArrayMode ? !xi : Math.abs(xi) < ax.dtick / 100) { + majorVals = majorVals.slice(0, i).concat(majorVals.slice(i + 1)); + if (isArrayMode) i--; + else break; + } + } + } + ax._gw = Drawing$s.crispRound(gd, ax.gridwidth, 1); + var wMinor = !hasMinor ? 0 : Drawing$s.crispRound(gd, ax.minor.gridwidth, 1); + var majorLayer = opts.layer; + var minorLayer = opts.minorLayer; + for (var major = 1; major >= 0; major--) { + var layer = major ? majorLayer : minorLayer; + if (!layer) continue; + var grid2 = layer.selectAll("path." + cls).data(major ? majorVals : minorVals, tickDataFn); + grid2.exit().remove(); + grid2.enter().append("path").classed(cls, 1).classed("crisp", opts.crisp !== false); + grid2.attr("transform", opts.transFn).attr("d", opts.path).each(function(d) { + return Color$H.stroke( + d3$v.select(this), + d.minor ? ax.minor.gridcolor : ax.gridcolor || "#ddd" + ); + }).style("stroke-dasharray", function(d) { + return Drawing$s.dashStyle( + d.minor ? ax.minor.griddash : ax.griddash, + d.minor ? ax.minor.gridwidth : ax.gridwidth + ); + }).style("stroke-width", function(d) { + return (d.minor ? wMinor : ax._gw) + "px"; + }).style("display", null); + if (typeof opts.path === "function") grid2.attr("d", opts.path); + } + hideCounterAxisInsideTickLabels(ax, [GRID_PATH, MINORGRID_PATH]); +}; +axes.drawZeroLine = function(gd, ax, opts) { + opts = opts || opts; + var cls = ax._id + "zl"; + var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis); + var zl = opts.layer.selectAll("path." + cls).data(show ? [{ x: 0, id: ax._id }] : []); + zl.exit().remove(); + zl.enter().append("path").classed(cls, 1).classed("zl", 1).classed("crisp", opts.crisp !== false).each(function() { + opts.layer.selectAll("path").sort(function(da, db) { + return idSort(da.id, db.id); + }); + }); + zl.attr("transform", opts.transFn).attr("d", opts.path).call(Color$H.stroke, ax.zerolinecolor || Color$H.defaultLine).style("stroke-width", Drawing$s.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + "px").style("display", null); + hideCounterAxisInsideTickLabels(ax, [ZERO_PATH]); +}; +axes.drawLabels = function(gd, ax, opts) { + opts = opts || {}; + var fullLayout = gd._fullLayout; + var axId = ax._id; + var cls = opts.cls || axId + "tick"; + var vals = opts.vals.filter(function(d) { + return d.text; + }); + var labelFns = opts.labelFns; + var tickAngle = opts.secondary ? 0 : ax.tickangle; + var prevAngle = (ax._prevTickAngles || {})[cls]; + var tickLabels = opts.layer.selectAll("g." + cls).data(ax.showticklabels ? vals : [], tickDataFn); + var labelsReady = []; + tickLabels.enter().append("g").classed(cls, 1).append("text").attr("text-anchor", "middle").each(function(d) { + var thisLabel = d3$v.select(this); + var newPromise = gd._promises.length; + thisLabel.call(svgTextUtils$d.positionText, labelFns.xFn(d), labelFns.yFn(d)).call(Drawing$s.font, { + family: d.font, + size: d.fontSize, + color: d.fontColor, + weight: d.fontWeight, + style: d.fontStyle, + variant: d.fontVariant, + textcase: d.fontTextcase, + lineposition: d.fontLineposition, + shadow: d.fontShadow + }).text(d.text).call(svgTextUtils$d.convertToTspans, gd); + if (gd._promises[newPromise]) { + labelsReady.push(gd._promises.pop().then(function() { + positionLabels(thisLabel, tickAngle); + })); + } else { + positionLabels(thisLabel, tickAngle); + } + }); + hideCounterAxisInsideTickLabels(ax, [TICK_TEXT]); + tickLabels.exit().remove(); + if (opts.repositionOnUpdate) { + tickLabels.each(function(d) { + d3$v.select(this).select("text").call(svgTextUtils$d.positionText, labelFns.xFn(d), labelFns.yFn(d)); + }); + } + function positionLabels(s, angle) { + s.each(function(d) { + var thisLabel = d3$v.select(this); + var mathjaxGroup = thisLabel.select(".text-math-group"); + var anchor = labelFns.anchorFn(d, angle); + var transform = opts.transFn.call(thisLabel.node(), d) + (isNumeric$j(angle) && +angle !== 0 ? " rotate(" + angle + "," + labelFns.xFn(d) + "," + (labelFns.yFn(d) - d.fontSize / 2) + ")" : ""); + var nLines = svgTextUtils$d.lineCount(thisLabel); + var lineHeight = LINE_SPACING$6 * d.fontSize; + var anchorHeight = labelFns.heightFn(d, isNumeric$j(angle) ? +angle : 0, (nLines - 1) * lineHeight); + if (anchorHeight) { + transform += strTranslate$a(0, anchorHeight); + } + if (mathjaxGroup.empty()) { + var thisText = thisLabel.select("text"); + thisText.attr({ + transform, + "text-anchor": anchor + }); + thisText.style("opacity", 1); + if (ax._adjustTickLabelsOverflow) { + ax._adjustTickLabelsOverflow(); + } + } else { + var mjWidth = Drawing$s.bBox(mathjaxGroup.node()).width; + var mjShift = mjWidth * { end: -0.5, start: 0.5 }[anchor]; + mathjaxGroup.attr("transform", transform + strTranslate$a(mjShift, 0)); + } + }); + } + ax._adjustTickLabelsOverflow = function() { + var ticklabeloverflow = ax.ticklabeloverflow; + if (!ticklabeloverflow || ticklabeloverflow === "allow") return; + var hideOverflow = ticklabeloverflow.indexOf("hide") !== -1; + var isX = ax._id.charAt(0) === "x"; + var p02 = 0; + var p12 = isX ? gd._fullLayout.width : gd._fullLayout.height; + if (ticklabeloverflow.indexOf("domain") !== -1) { + var rl = Lib$1E.simpleMap(ax.range, ax.r2l); + p02 = ax.l2p(rl[0]) + ax._offset; + p12 = ax.l2p(rl[1]) + ax._offset; + } + var min = Math.min(p02, p12); + var max = Math.max(p02, p12); + var side = ax.side; + var visibleLabelMin = Infinity; + var visibleLabelMax = -Infinity; + tickLabels.each(function(d) { + var thisLabel = d3$v.select(this); + var mathjaxGroup = thisLabel.select(".text-math-group"); + if (mathjaxGroup.empty()) { + var bb = Drawing$s.bBox(thisLabel.node()); + var adjust = 0; + if (isX) { + if (bb.right > max) adjust = 1; + else if (bb.left < min) adjust = 1; + } else { + if (bb.bottom > max) adjust = 1; + else if (bb.top + (ax.tickangle ? 0 : d.fontSize / 4) < min) adjust = 1; + } + var t = thisLabel.select("text"); + if (adjust) { + if (hideOverflow) t.style("opacity", 0); + } else { + t.style("opacity", 1); + if (side === "bottom" || side === "right") { + visibleLabelMin = Math.min(visibleLabelMin, isX ? bb.top : bb.left); + } else { + visibleLabelMin = -Infinity; + } + if (side === "top" || side === "left") { + visibleLabelMax = Math.max(visibleLabelMax, isX ? bb.bottom : bb.right); + } else { + visibleLabelMax = Infinity; + } + } + } + }); + for (var subplot in fullLayout._plots) { + var plotinfo = fullLayout._plots[subplot]; + if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; + var anchorAx2 = isX ? plotinfo.yaxis : plotinfo.xaxis; + if (anchorAx2) { + anchorAx2["_visibleLabelMin_" + ax._id] = visibleLabelMin; + anchorAx2["_visibleLabelMax_" + ax._id] = visibleLabelMax; + } + } + }; + ax._hideCounterAxisInsideTickLabels = function(partialOpts) { + var isX = ax._id.charAt(0) === "x"; + var anchoredAxes = []; + for (var subplot in fullLayout._plots) { + var plotinfo = fullLayout._plots[subplot]; + if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; + anchoredAxes.push(isX ? plotinfo.yaxis : plotinfo.xaxis); + } + anchoredAxes.forEach(function(anchorAx2, idx) { + if (anchorAx2 && insideTicklabelposition(anchorAx2)) { + (partialOpts || [ + ZERO_PATH, + MINORGRID_PATH, + GRID_PATH, + TICK_PATH, + TICK_TEXT + ]).forEach(function(e) { + var isPeriodLabel = e.K === "tick" && e.L === "text" && ax.ticklabelmode === "period"; + var mainPlotinfo = fullLayout._plots[ax._mainSubplot]; + var sel; + if (e.K === ZERO_PATH.K) sel = mainPlotinfo.zerolinelayer.selectAll("." + ax._id + "zl"); + else if (e.K === MINORGRID_PATH.K) sel = mainPlotinfo.minorGridlayer.selectAll("." + ax._id); + else if (e.K === GRID_PATH.K) sel = mainPlotinfo.gridlayer.selectAll("." + ax._id); + else sel = mainPlotinfo[ax._id.charAt(0) + "axislayer"]; + sel.each(function() { + var w = d3$v.select(this); + if (e.L) w = w.selectAll(e.L); + w.each(function(d) { + var q = ax.l2p( + isPeriodLabel ? getPosX(d) : d.x + ) + ax._offset; + var t = d3$v.select(this); + if (q < ax["_visibleLabelMax_" + anchorAx2._id] && q > ax["_visibleLabelMin_" + anchorAx2._id]) { + t.style("display", "none"); + } else if (e.K === "tick" && !idx) { + t.style("display", null); + } + }); + }); + }); + } + }); + }; + positionLabels(tickLabels, prevAngle + 1 ? prevAngle : tickAngle); + function allLabelsReady() { + return labelsReady.length && Promise.all(labelsReady); + } + var autoangle = null; + function fixLabelOverlaps() { + positionLabels(tickLabels, tickAngle); + if (vals.length && ax.autotickangles && (ax.type !== "log" || String(ax.dtick).charAt(0) !== "D")) { + autoangle = ax.autotickangles[0]; + var maxFontSize = 0; + var lbbArray = []; + var i; + var maxLines = 1; + tickLabels.each(function(d) { + maxFontSize = Math.max(maxFontSize, d.fontSize); + var x = ax.l2p(d.x); + var thisLabel = selectTickLabel(this); + var bb = Drawing$s.bBox(thisLabel.node()); + maxLines = Math.max(maxLines, svgTextUtils$d.lineCount(thisLabel)); + lbbArray.push({ + // ignore about y, just deal with x overlaps + top: 0, + bottom: 10, + height: 10, + left: x - bb.width / 2, + // impose a 2px gap + right: x + bb.width / 2 + 2, + width: bb.width + 2 + }); + }); + var preventOverlapWithTick = (ax.tickson === "boundaries" || ax.showdividers) && !opts.secondary; + var vLen = vals.length; + var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1); + var adjacent = preventOverlapWithTick ? tickSpacing / 2 : tickSpacing; + var opposite = preventOverlapWithTick ? ax.ticklen : maxFontSize * 1.25 * maxLines; + var hypotenuse = Math.sqrt(Math.pow(adjacent, 2) + Math.pow(opposite, 2)); + var maxCos = adjacent / hypotenuse; + var autoTickAnglesRadians = ax.autotickangles.map( + function(degrees2) { + return degrees2 * Math.PI / 180; + } + ); + var angleRadians = autoTickAnglesRadians.find( + function(angle) { + return Math.abs(Math.cos(angle)) <= maxCos; + } + ); + if (angleRadians === void 0) { + angleRadians = autoTickAnglesRadians.reduce( + function(currentMax, nextAngle) { + return Math.abs(Math.cos(currentMax)) < Math.abs(Math.cos(nextAngle)) ? currentMax : nextAngle; + }, + autoTickAnglesRadians[0] + ); + } + var newAngle = angleRadians * (180 / Math.PI); + if (preventOverlapWithTick) { + var gap = 2; + if (ax.ticks) gap += ax.tickwidth / 2; + for (i = 0; i < lbbArray.length; i++) { + var xbnd = vals[i].xbnd; + var lbb = lbbArray[i]; + if (xbnd[0] !== null && lbb.left - ax.l2p(xbnd[0]) < gap || xbnd[1] !== null && ax.l2p(xbnd[1]) - lbb.right < gap) { + autoangle = newAngle; + break; + } + } + } else { + var ticklabelposition = ax.ticklabelposition || ""; + var has = function(str2) { + return ticklabelposition.indexOf(str2) !== -1; + }; + var isTop = has("top"); + var isLeft = has("left"); + var isRight = has("right"); + var isBottom = has("bottom"); + var isAligned = isBottom || isLeft || isTop || isRight; + var pad2 = !isAligned ? 0 : (ax.tickwidth || 0) + 2 * TEXTPAD$4; + for (i = 0; i < lbbArray.length - 1; i++) { + if (Lib$1E.bBoxIntersect(lbbArray[i], lbbArray[i + 1], pad2)) { + autoangle = newAngle; + break; + } + } + } + if (autoangle) { + positionLabels(tickLabels, autoangle); + } + } + } + if (ax._selections) { + ax._selections[cls] = tickLabels; + } + var seq = [allLabelsReady]; + if (ax.automargin && fullLayout._redrawFromAutoMarginCount && prevAngle === 90) { + autoangle = prevAngle; + seq.push(function() { + positionLabels(tickLabels, prevAngle); + }); + } else { + seq.push(fixLabelOverlaps); + } + if (ax._tickAngles) { + seq.push(function() { + ax._tickAngles[cls] = autoangle === null ? isNumeric$j(tickAngle) ? tickAngle : 0 : autoangle; + }); + } + var computeTickLabelBoundingBoxes = function() { + var labelsMaxW = 0; + var labelsMaxH = 0; + tickLabels.each(function(d, i) { + var thisLabel = selectTickLabel(this); + var mathjaxGroup = thisLabel.select(".text-math-group"); + if (mathjaxGroup.empty()) { + var bb; + if (ax._vals[i]) { + bb = ax._vals[i].bb || Drawing$s.bBox(thisLabel.node()); + ax._vals[i].bb = bb; + } + labelsMaxW = Math.max(labelsMaxW, bb.width); + labelsMaxH = Math.max(labelsMaxH, bb.height); + } + }); + return { + labelsMaxW, + labelsMaxH + }; + }; + var anchorAx = ax._anchorAxis; + if (anchorAx && (anchorAx.autorange || anchorAx.insiderange) && insideTicklabelposition(ax) && !isLinked(fullLayout, ax._id)) { + if (!fullLayout._insideTickLabelsUpdaterange) { + fullLayout._insideTickLabelsUpdaterange = {}; + } + if (anchorAx.autorange) { + fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".autorange"] = anchorAx.autorange; + seq.push(computeTickLabelBoundingBoxes); + } + if (anchorAx.insiderange) { + var BBs = computeTickLabelBoundingBoxes(); + var move = ax._id.charAt(0) === "y" ? BBs.labelsMaxW : BBs.labelsMaxH; + move += 2 * TEXTPAD$4; + if (ax.ticklabelposition === "inside") { + move += ax.ticklen || 0; + } + var sgn = ax.side === "right" || ax.side === "top" ? 1 : -1; + var index2 = sgn === 1 ? 1 : 0; + var otherIndex = sgn === 1 ? 0 : 1; + var newRange = []; + newRange[otherIndex] = anchorAx.range[otherIndex]; + var anchorAxRange = anchorAx.range; + var p0 = anchorAx.r2p(anchorAxRange[index2]); + var p1 = anchorAx.r2p(anchorAxRange[otherIndex]); + var _tempNewRange = fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"]; + if (_tempNewRange) { + var q0 = anchorAx.r2p(_tempNewRange[index2]); + var q1 = anchorAx.r2p(_tempNewRange[otherIndex]); + var dir = sgn * (ax._id.charAt(0) === "y" ? 1 : -1); + if (dir * p0 < dir * q0) { + p0 = q0; + newRange[index2] = anchorAxRange[index2] = _tempNewRange[index2]; + } + if (dir * p1 > dir * q1) { + p1 = q1; + newRange[otherIndex] = anchorAxRange[otherIndex] = _tempNewRange[otherIndex]; + } + } + var dist2 = Math.abs(p1 - p0); + if (dist2 - move > 0) { + dist2 -= move; + move *= 1 + move / dist2; + } else { + move = 0; + } + if (ax._id.charAt(0) !== "y") move = -move; + newRange[index2] = anchorAx.p2r( + anchorAx.r2p(anchorAxRange[index2]) + sgn * move + ); + if (anchorAx.autorange === "min" || anchorAx.autorange === "max reversed") { + newRange[0] = null; + anchorAx._rangeInitial0 = void 0; + anchorAx._rangeInitial1 = void 0; + } else if (anchorAx.autorange === "max" || anchorAx.autorange === "min reversed") { + newRange[1] = null; + anchorAx._rangeInitial0 = void 0; + anchorAx._rangeInitial1 = void 0; + } + fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"] = newRange; + } + } + var done = Lib$1E.syncOrAsync(seq); + if (done && done.then) gd._promises.push(done); + return done; +}; +function drawDividers(gd, ax, opts) { + var cls = ax._id + "divider"; + var vals = opts.vals; + var dividers = opts.layer.selectAll("path." + cls).data(vals, tickDataFn); + dividers.exit().remove(); + dividers.enter().insert("path", ":first-child").classed(cls, 1).classed("crisp", 1).call(Color$H.stroke, ax.dividercolor).style("stroke-width", Drawing$s.crispRound(gd, ax.dividerwidth, 1) + "px"); + dividers.attr("transform", opts.transFn).attr("d", opts.path); +} +axes.getPxPosition = function(gd, ax) { + var gs = gd._fullLayout._size; + var axLetter = ax._id.charAt(0); + var side = ax.side; + var anchorAxis; + if (ax.anchor !== "free") { + anchorAxis = ax._anchorAxis; + } else if (axLetter === "x") { + anchorAxis = { + _offset: gs.t + (1 - (ax.position || 0)) * gs.h, + _length: 0 + }; + } else if (axLetter === "y") { + anchorAxis = { + _offset: gs.l + (ax.position || 0) * gs.w + ax._shift, + _length: 0 + }; + } + if (side === "top" || side === "left") { + return anchorAxis._offset; + } else if (side === "bottom" || side === "right") { + return anchorAxis._offset + anchorAxis._length; + } +}; +function approxTitleDepth(ax) { + var fontSize = ax.title.font.size; + var extraLines = (ax.title.text.match(svgTextUtils$d.BR_TAG_ALL) || []).length; + if (ax.title.hasOwnProperty("standoff")) { + return fontSize * (CAP_SHIFT + extraLines * LINE_SPACING$6); + } else { + return extraLines ? fontSize * (extraLines + 1) * LINE_SPACING$6 : fontSize; + } +} +function drawTitle(gd, ax) { + var fullLayout = gd._fullLayout; + var axId = ax._id; + var axLetter = axId.charAt(0); + var fontSize = ax.title.font.size; + var titleStandoff; + var extraLines = (ax.title.text.match(svgTextUtils$d.BR_TAG_ALL) || []).length; + if (ax.title.hasOwnProperty("standoff")) { + if (ax.side === "bottom" || ax.side === "right") { + titleStandoff = ax._depth + ax.title.standoff + fontSize * CAP_SHIFT; + } else if (ax.side === "top" || ax.side === "left") { + titleStandoff = ax._depth + ax.title.standoff + fontSize * (MID_SHIFT + extraLines * LINE_SPACING$6); + } + } else { + var isInside = insideTicklabelposition(ax); + if (ax.type === "multicategory") { + titleStandoff = ax._depth; + } else { + var offsetBase = 1.5 * fontSize; + if (isInside) { + offsetBase = 0.5 * fontSize; + if (ax.ticks === "outside") { + offsetBase += ax.ticklen; + } + } + titleStandoff = 10 + offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0); + } + if (!isInside) { + if (axLetter === "x") { + titleStandoff += ax.side === "top" ? fontSize * (ax.showticklabels ? 1 : 0) : fontSize * (ax.showticklabels ? 1.5 : 0.5); + } else { + titleStandoff += ax.side === "right" ? fontSize * (ax.showticklabels ? 1 : 0.5) : fontSize * (ax.showticklabels ? 0.5 : 0); + } + } + } + var pos = axes.getPxPosition(gd, ax); + var transform, x, y; + if (axLetter === "x") { + x = ax._offset + ax._length / 2; + y = ax.side === "top" ? pos - titleStandoff : pos + titleStandoff; + } else { + y = ax._offset + ax._length / 2; + x = ax.side === "right" ? pos + titleStandoff : pos - titleStandoff; + transform = { rotate: "-90", offset: 0 }; + } + var avoid; + if (ax.type !== "multicategory") { + var tickLabels = ax._selections[ax._id + "tick"]; + avoid = { + selection: tickLabels, + side: ax.side + }; + if (tickLabels && tickLabels.node() && tickLabels.node().parentNode) { + var translation = Drawing$s.getTranslate(tickLabels.node().parentNode); + avoid.offsetLeft = translation.x; + avoid.offsetTop = translation.y; + } + if (ax.title.hasOwnProperty("standoff")) { + avoid.pad = 0; + } + } + ax._titleStandoff = titleStandoff; + return Titles$1.draw(gd, axId + "title", { + propContainer: ax, + propName: ax._name + ".title.text", + placeholder: fullLayout._dfltTitle[axLetter], + avoid, + transform, + attributes: { x, y, "text-anchor": "middle" } + }); +} +axes.shouldShowZeroLine = function(gd, ax, counterAxis) { + var rng = Lib$1E.simpleMap(ax.range, ax.r2l); + return rng[0] * rng[1] <= 0 && ax.zeroline && (ax.type === "linear" || ax.type === "-") && !(ax.rangebreaks && ax.maskBreaks(0) === BADNUM$7) && (clipEnds(ax, 0) || !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) || hasBarsOrFill(gd, ax)); +}; +axes.clipEnds = function(ax, vals) { + return vals.filter(function(d) { + return clipEnds(ax, d.x); + }); +}; +function clipEnds(ax, l) { + var p = ax.l2p(l); + return p > 1 && p < ax._length - 1; +} +function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) { + var mainCounterAxis = counterAxis._mainAxis; + if (!mainCounterAxis) return; + var fullLayout = gd._fullLayout; + var axLetter = ax._id.charAt(0); + var counterLetter = axes.counterLetter(ax._id); + var zeroPosition = ax._offset + (Math.abs(rng[0]) < Math.abs(rng[1]) === (axLetter === "x") ? 0 : ax._length); + function lineNearZero(ax2) { + if (!ax2.showline || !ax2.linewidth) return false; + var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1); + function closeEnough(pos2) { + return typeof pos2 === "number" && Math.abs(pos2 - zeroPosition) < tolerance; + } + if (closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) { + return true; + } + var linePositions = ax2._linepositions || {}; + for (var k in linePositions) { + if (closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) { + return true; + } + } + } + var plotinfo = fullLayout._plots[counterAxis._mainSubplot]; + if (!(plotinfo.mainplotinfo || plotinfo).overlays.length) { + return lineNearZero(counterAxis); + } + var counterLetterAxes = axes.list(gd, counterLetter); + for (var i = 0; i < counterLetterAxes.length; i++) { + var counterAxis2 = counterLetterAxes[i]; + if (counterAxis2._mainAxis === mainCounterAxis && lineNearZero(counterAxis2)) { + return true; + } + } +} +function hasBarsOrFill(gd, ax) { + var fullData = gd._fullData; + var subplot = ax._mainSubplot; + var axLetter = ax._id.charAt(0); + for (var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if (trace.visible === true && trace.xaxis + trace.yaxis === subplot) { + if (Registry$I.traceIs(trace, "bar-like") && trace.orientation === { x: "h", y: "v" }[axLetter]) return true; + if (trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter) return true; + } + } + return false; +} +function selectTickLabel(gTick) { + var s = d3$v.select(gTick); + var mj = s.select(".text-math-group"); + return mj.empty() ? s.select("text") : mj; +} +axes.allowAutoMargin = function(gd) { + var axList = axes.list(gd, "", true); + for (var i = 0; i < axList.length; i++) { + var ax = axList[i]; + if (ax.automargin) { + Plots$b.allowAutoMargin(gd, axAutoMarginID(ax)); + if (ax.mirror) { + Plots$b.allowAutoMargin(gd, axMirrorAutoMarginID(ax)); + } + } + if (Registry$I.getComponentMethod("rangeslider", "isVisible")(ax)) { + Plots$b.allowAutoMargin(gd, rangeSliderAutoMarginID(ax)); + } + } +}; +function axAutoMarginID(ax) { + return ax._id + ".automargin"; +} +function axMirrorAutoMarginID(ax) { + return axAutoMarginID(ax) + ".mirror"; +} +function rangeSliderAutoMarginID(ax) { + return ax._id + ".rangeslider"; +} +axes.swap = function(gd, traces) { + var axGroups = makeAxisGroups(gd, traces); + for (var i = 0; i < axGroups.length; i++) { + swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); + } +}; +function makeAxisGroups(gd, traces) { + var groups = []; + var i, j; + for (i = 0; i < traces.length; i++) { + var groupsi = []; + var xi = gd._fullData[traces[i]].xaxis; + var yi = gd._fullData[traces[i]].yaxis; + if (!xi || !yi) continue; + for (j = 0; j < groups.length; j++) { + if (groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { + groupsi.push(j); + } + } + if (!groupsi.length) { + groups.push({ x: [xi], y: [yi] }); + continue; + } + var group0 = groups[groupsi[0]]; + var groupj; + if (groupsi.length > 1) { + for (j = 1; j < groupsi.length; j++) { + groupj = groups[groupsi[j]]; + mergeAxisGroups(group0.x, groupj.x); + mergeAxisGroups(group0.y, groupj.y); + } + } + mergeAxisGroups(group0.x, [xi]); + mergeAxisGroups(group0.y, [yi]); + } + return groups; +} +function mergeAxisGroups(intoSet, fromSet) { + for (var i = 0; i < fromSet.length; i++) { + if (intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); + } +} +function swapAxisGroup(gd, xIds, yIds) { + var xFullAxes = []; + var yFullAxes = []; + var layout = gd.layout; + var i, j; + for (i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i])); + for (i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i])); + var allAxKeys = Object.keys(axAttrs); + var noSwapAttrs = [ + "anchor", + "domain", + "overlaying", + "position", + "side", + "tickangle", + "editType" + ]; + var numericTypes = ["linear", "log"]; + for (i = 0; i < allAxKeys.length; i++) { + var keyi = allAxKeys[i]; + var xVal = xFullAxes[0][keyi]; + var yVal = yFullAxes[0][keyi]; + var allEqual = true; + var coerceLinearX = false; + var coerceLinearY = false; + if (keyi.charAt(0) === "_" || typeof xVal === "function" || noSwapAttrs.indexOf(keyi) !== -1) { + continue; + } + for (j = 1; j < xFullAxes.length && allEqual; j++) { + var xVali = xFullAxes[j][keyi]; + if (keyi === "type" && numericTypes.indexOf(xVal) !== -1 && numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) { + coerceLinearX = true; + } else if (xVali !== xVal) allEqual = false; + } + for (j = 1; j < yFullAxes.length && allEqual; j++) { + var yVali = yFullAxes[j][keyi]; + if (keyi === "type" && numericTypes.indexOf(yVal) !== -1 && numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) { + coerceLinearY = true; + } else if (yFullAxes[j][keyi] !== yVal) allEqual = false; + } + if (allEqual) { + if (coerceLinearX) layout[xFullAxes[0]._name].type = "linear"; + if (coerceLinearY) layout[yFullAxes[0]._name].type = "linear"; + swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle); + } + } + for (i = 0; i < gd._fullLayout.annotations.length; i++) { + var ann = gd._fullLayout.annotations[i]; + if (xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { + Lib$1E.swapAttrs(layout.annotations[i], ["?"]); + } + } +} +function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) { + var np = Lib$1E.nestedProperty; + var xVal = np(layout[xFullAxes[0]._name], key).get(); + var yVal = np(layout[yFullAxes[0]._name], key).get(); + var i; + if (key === "title") { + if (xVal && xVal.text === dfltTitle.x) { + xVal.text = dfltTitle.y; + } + if (yVal && yVal.text === dfltTitle.y) { + yVal.text = dfltTitle.x; + } + } + for (i = 0; i < xFullAxes.length; i++) { + np(layout, xFullAxes[i]._name + "." + key).set(yVal); + } + for (i = 0; i < yFullAxes.length; i++) { + np(layout, yFullAxes[i]._name + "." + key).set(xVal); + } +} +function isAngular(ax) { + return ax._id === "angularaxis"; +} +function moveOutsideBreak(v, ax) { + var len = ax._rangebreaks.length; + for (var k = 0; k < len; k++) { + var brk = ax._rangebreaks[k]; + if (v >= brk.min && v < brk.max) { + return brk.max; + } + } + return v; +} +function insideTicklabelposition(ax) { + return (ax.ticklabelposition || "").indexOf("inside") !== -1; +} +function hideCounterAxisInsideTickLabels(ax, opts) { + if (insideTicklabelposition(ax._anchorAxis || {})) { + if (ax._hideCounterAxisInsideTickLabels) { + ax._hideCounterAxisInsideTickLabels(opts); + } + } +} +function incrementShift(ax, shiftVal, axShifts, normalize3) { + var overlay = ax.anchor !== "free" && (ax.overlaying === void 0 || ax.overlaying === false) ? ax._id : ax.overlaying; + var shiftValAdj; + if (normalize3) { + shiftValAdj = ax.side === "right" ? shiftVal : -shiftVal; + } else { + shiftValAdj = shiftVal; + } + if (!(overlay in axShifts)) { + axShifts[overlay] = {}; + } + if (!(ax.side in axShifts[overlay])) { + axShifts[overlay][ax.side] = 0; + } + axShifts[overlay][ax.side] += shiftValAdj; +} +function setShiftVal(ax, axShifts) { + return ax.autoshift ? axShifts[ax.overlaying][ax.side] : ax.shift || 0; +} +function periodCompatibleWithTickformat(period, tickformat) { + return /%f/.test(tickformat) ? period >= ONEMICROSEC : /%L/.test(tickformat) ? period >= ONEMILLI : /%[SX]/.test(tickformat) ? period >= ONESEC : /%M/.test(tickformat) ? period >= ONEMIN : /%[HI]/.test(tickformat) ? period >= ONEHOUR : /%p/.test(tickformat) ? period >= HALFDAY : /%[Aadejuwx]/.test(tickformat) ? period >= ONEDAY : /%[UVW]/.test(tickformat) ? period >= ONEWEEK$1 : /%[Bbm]/.test(tickformat) ? period >= ONEMINMONTH : /%[q]/.test(tickformat) ? period >= ONEMINQUARTER : /%[Yy]/.test(tickformat) ? period >= ONEMINYEAR : true; +} +var axesExports = axes$1.exports; +var autorange_options_defaults = function handleAutorangeOptionsDefaults(coerce2, autorange2, range) { + var minRange, maxRange; + if (range) { + var isReversed2 = autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; + minRange = range[isReversed2 ? 1 : 0]; + maxRange = range[isReversed2 ? 0 : 1]; + } + var minallowed = coerce2("autorangeoptions.minallowed", maxRange === null ? minRange : void 0); + var maxallowed = coerce2("autorangeoptions.maxallowed", minRange === null ? maxRange : void 0); + if (minallowed === void 0) coerce2("autorangeoptions.clipmin"); + if (maxallowed === void 0) coerce2("autorangeoptions.clipmax"); + coerce2("autorangeoptions.include"); +}; +var handleAutorangeOptionsDefaults2 = autorange_options_defaults; +var range_defaults = function handleRangeDefaults(containerIn, containerOut, coerce2, options) { + var axTemplate = containerOut._template || {}; + var axType = containerOut.type || axTemplate.type || "-"; + coerce2("minallowed"); + coerce2("maxallowed"); + var range = coerce2("range"); + if (!range) { + var insiderange; + if (!options.noInsiderange && axType !== "log") { + insiderange = coerce2("insiderange"); + if (insiderange && (insiderange[0] === null || insiderange[1] === null)) { + containerOut.insiderange = false; + insiderange = void 0; + } + if (insiderange) range = coerce2("range", insiderange); + } + } + var autorangeDflt = containerOut.getAutorangeDflt(range, options); + var autorange2 = coerce2("autorange", autorangeDflt); + var shouldAutorange; + if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange2 === "reversed" || autorange2 === true) || range[0] !== null && (autorange2 === "min" || autorange2 === "max reversed") || range[1] !== null && (autorange2 === "max" || autorange2 === "min reversed"))) { + range = void 0; + delete containerOut.range; + containerOut.autorange = true; + shouldAutorange = true; + } + if (!shouldAutorange) { + autorangeDflt = containerOut.getAutorangeDflt(range, options); + autorange2 = coerce2("autorange", autorangeDflt); + } + if (autorange2) { + handleAutorangeOptionsDefaults2(coerce2, autorange2, range); + if (axType === "linear" || axType === "-") coerce2("rangemode"); + } + containerOut.cleanRange(); +}; +var graph_interact = {}; +var dragelement = { exports: {} }; +var rootPosition = { left: 0, top: 0 }; +var mouseEventOffset_1 = mouseEventOffset; +function mouseEventOffset(ev, target, out) { + target = target || ev.currentTarget || ev.srcElement; + if (!Array.isArray(out)) { + out = [0, 0]; + } + var cx = ev.clientX || 0; + var cy = ev.clientY || 0; + var rect2 = getBoundingClientOffset(target); + out[0] = cx - rect2.left; + out[1] = cy - rect2.top; + return out; +} +function getBoundingClientOffset(element) { + if (element === window || element === document || element === document.body) { + return rootPosition; + } else { + return element.getBoundingClientRect(); + } +} +function detect() { + var supported = false; + try { + var opts = Object.defineProperty({}, "passive", { + get: function() { + supported = true; + } + }); + window.addEventListener("test", null, opts); + window.removeEventListener("test", null, opts); + } catch (e) { + supported = false; + } + return supported; +} +var hasPassiveEvents = detect(); +var align = function align2(v, dv2, v0, v1, anchor) { + var vmin = (v - v0) / (v1 - v0); + var vmax = vmin + dv2 / (v1 - v0); + var vc = (vmin + vmax) / 2; + if (anchor === "left" || anchor === "bottom") return vmin; + if (anchor === "center" || anchor === "middle") return vc; + if (anchor === "right" || anchor === "top") return vmax; + if (vmin < 2 / 3 - vc) return vmin; + if (vmax > 4 / 3 - vc) return vmax; + return vc; +}; +var Lib$1D = libExports; +var cursorset = [ + ["sw-resize", "s-resize", "se-resize"], + ["w-resize", "move", "e-resize"], + ["nw-resize", "n-resize", "ne-resize"] +]; +var cursor = function getCursor(x, y, xanchor, yanchor) { + if (xanchor === "left") x = 0; + else if (xanchor === "center") x = 1; + else if (xanchor === "right") x = 2; + else x = Lib$1D.constrain(Math.floor(x * 3), 0, 2); + if (yanchor === "bottom") y = 0; + else if (yanchor === "middle") y = 1; + else if (yanchor === "top") y = 2; + else y = Lib$1D.constrain(Math.floor(y * 3), 0, 2); + return cursorset[y][x]; +}; +var unhover$2 = { exports: {} }; +var Events$3 = events; +var throttle$1 = throttle$2; +var getGraphDiv$1 = dom.getGraphDiv; +var hoverConstants = constants$W; +var unhover$1 = unhover$2.exports = {}; +unhover$1.wrapped = function(gd, evt, subplot) { + gd = getGraphDiv$1(gd); + if (gd._fullLayout) { + throttle$1.clear(gd._fullLayout._uid + hoverConstants.HOVERID); + } + unhover$1.raw(gd, evt, subplot); +}; +unhover$1.raw = function raw(gd, evt) { + var fullLayout = gd._fullLayout; + var oldhoverdata = gd._hoverdata; + if (!evt) evt = {}; + if (evt.target && !gd._dragged && Events$3.triggerHandler(gd, "plotly_beforehover", evt) === false) { + return; + } + fullLayout._hoverlayer.selectAll("g").remove(); + fullLayout._hoverlayer.selectAll("line").remove(); + fullLayout._hoverlayer.selectAll("circle").remove(); + gd._hoverdata = void 0; + if (evt.target && oldhoverdata) { + gd.emit("plotly_unhover", { + event: evt, + points: oldhoverdata + }); + } +}; +var unhoverExports = unhover$2.exports; +var mouseOffset = mouseEventOffset_1; +var hasHover = hasHover_1; +var supportsPassive = hasPassiveEvents; +var removeElement = libExports.removeElement; +var constants$P = constants$U; +var dragElement$7 = dragelement.exports = {}; +dragElement$7.align = align; +dragElement$7.getCursor = cursor; +var unhover = unhoverExports; +dragElement$7.unhover = unhover.wrapped; +dragElement$7.unhoverRaw = unhover.raw; +dragElement$7.init = function init(options) { + var gd = options.gd; + var numClicks = 1; + var doubleClickDelay = gd._context.doubleClickDelay; + var element = options.element; + var startX, startY, newMouseDownTime, cursor2, dragCover, initialEvent, initialTarget, rightClick; + if (!gd._mouseDownTime) gd._mouseDownTime = 0; + element.style.pointerEvents = "all"; + element.onmousedown = onStart; + if (!supportsPassive) { + element.ontouchstart = onStart; + } else { + if (element._ontouchstart) { + element.removeEventListener("touchstart", element._ontouchstart); + } + element._ontouchstart = onStart; + element.addEventListener("touchstart", onStart, { passive: false }); + } + function _clampFn(dx, dy, minDrag) { + if (Math.abs(dx) < minDrag) dx = 0; + if (Math.abs(dy) < minDrag) dy = 0; + return [dx, dy]; + } + var clampFn = options.clampFn || _clampFn; + function onStart(e) { + gd._dragged = false; + gd._dragging = true; + var offset = pointerOffset(e); + startX = offset[0]; + startY = offset[1]; + initialTarget = e.target; + initialEvent = e; + rightClick = e.buttons === 2 || e.ctrlKey; + if (typeof e.clientX === "undefined" && typeof e.clientY === "undefined") { + e.clientX = startX; + e.clientY = startY; + } + newMouseDownTime = (/* @__PURE__ */ new Date()).getTime(); + if (newMouseDownTime - gd._mouseDownTime < doubleClickDelay) { + numClicks += 1; + } else { + numClicks = 1; + gd._mouseDownTime = newMouseDownTime; + } + if (options.prepFn) options.prepFn(e, startX, startY); + if (hasHover && !rightClick) { + dragCover = coverSlip(); + dragCover.style.cursor = window.getComputedStyle(element).cursor; + } else if (!hasHover) { + dragCover = document; + cursor2 = window.getComputedStyle(document.documentElement).cursor; + document.documentElement.style.cursor = window.getComputedStyle(element).cursor; + } + document.addEventListener("mouseup", onDone); + document.addEventListener("touchend", onDone); + if (options.dragmode !== false) { + e.preventDefault(); + document.addEventListener("mousemove", onMove); + document.addEventListener("touchmove", onMove, { passive: false }); + } + return; + } + function onMove(e) { + e.preventDefault(); + var offset = pointerOffset(e); + var minDrag = options.minDrag || constants$P.MINDRAG; + var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); + var dx = dxdy[0]; + var dy = dxdy[1]; + if (dx || dy) { + gd._dragged = true; + dragElement$7.unhover(gd, e); + } + if (gd._dragged && options.moveFn && !rightClick) { + gd._dragdata = { + element, + dx, + dy + }; + options.moveFn(dx, dy); + } + return; + } + function onDone(e) { + delete gd._dragdata; + if (options.dragmode !== false) { + e.preventDefault(); + document.removeEventListener("mousemove", onMove); + document.removeEventListener("touchmove", onMove); + } + document.removeEventListener("mouseup", onDone); + document.removeEventListener("touchend", onDone); + if (hasHover) { + removeElement(dragCover); + } else if (cursor2) { + dragCover.documentElement.style.cursor = cursor2; + cursor2 = null; + } + if (!gd._dragging) { + gd._dragged = false; + return; + } + gd._dragging = false; + if ((/* @__PURE__ */ new Date()).getTime() - gd._mouseDownTime > doubleClickDelay) { + numClicks = Math.max(numClicks - 1, 1); + } + if (gd._dragged) { + if (options.doneFn) options.doneFn(); + } else { + if (options.clickFn) options.clickFn(numClicks, initialEvent); + if (!rightClick) { + var e2; + try { + e2 = new MouseEvent("click", e); + } catch (err) { + var offset = pointerOffset(e); + e2 = document.createEvent("MouseEvents"); + e2.initMouseEvent( + "click", + e.bubbles, + e.cancelable, + e.view, + e.detail, + e.screenX, + e.screenY, + offset[0], + offset[1], + e.ctrlKey, + e.altKey, + e.shiftKey, + e.metaKey, + e.button, + e.relatedTarget + ); + } + initialTarget.dispatchEvent(e2); + } + } + gd._dragging = false; + gd._dragged = false; + return; + } +}; +function coverSlip() { + var cover = document.createElement("div"); + cover.className = "dragcover"; + var cStyle = cover.style; + cStyle.position = "fixed"; + cStyle.left = 0; + cStyle.right = 0; + cStyle.top = 0; + cStyle.bottom = 0; + cStyle.zIndex = 999999999; + cStyle.background = "none"; + document.body.appendChild(cover); + return cover; +} +dragElement$7.coverSlip = coverSlip; +function pointerOffset(e) { + return mouseOffset( + e.changedTouches ? e.changedTouches[0] : e, + document.body + ); +} +var dragelementExports = dragelement.exports; +var hover$7 = {}; +var setcursor = function setCursor(el3, csr) { + (el3.attr("class") || "").split(" ").forEach(function(cls) { + if (cls.indexOf("cursor-") === 0) el3.classed(cls, false); + }); + if (csr) el3.classed("cursor-" + csr, true); +}; +var setCursor$3 = setcursor; +var STASHATTR = "data-savedcursor"; +var NO_CURSOR = "!!"; +var override_cursor = function overrideCursor(el3, csr) { + var savedCursor = el3.attr(STASHATTR); + if (csr) { + if (!savedCursor) { + var classes = (el3.attr("class") || "").split(" "); + for (var i = 0; i < classes.length; i++) { + var cls = classes[i]; + if (cls.indexOf("cursor-") === 0) { + el3.attr(STASHATTR, cls.substr(7)).classed(cls, false); + } + } + if (!el3.attr(STASHATTR)) { + el3.attr(STASHATTR, NO_CURSOR); + } + } + setCursor$3(el3, csr); + } else if (savedCursor) { + el3.attr(STASHATTR, null); + if (savedCursor === NO_CURSOR) setCursor$3(el3); + else setCursor$3(el3, savedCursor); + } +}; +var fontAttrs$a = font_attributes; +var colorAttrs$4 = attributes$N; +var attributes$G = { + // not really a 'subplot' attribute container, + // but this is the flag we use to denote attributes that + // support yaxis, yaxis2, yaxis3, ... counters + _isSubplotObj: true, + visible: { + valType: "boolean", + dflt: true, + editType: "legend", + description: [ + "Determines whether or not this legend is visible." + ].join(" ") + }, + bgcolor: { + valType: "color", + editType: "legend", + description: [ + "Sets the legend background color.", + "Defaults to `layout.paper_bgcolor`." + ].join(" ") + }, + bordercolor: { + valType: "color", + dflt: colorAttrs$4.defaultLine, + editType: "legend", + description: "Sets the color of the border enclosing the legend." + }, + borderwidth: { + valType: "number", + min: 0, + dflt: 0, + editType: "legend", + description: "Sets the width (in px) of the border enclosing the legend." + }, + font: fontAttrs$a({ + editType: "legend", + description: "Sets the font used to text the legend items." + }), + grouptitlefont: fontAttrs$a({ + editType: "legend", + description: [ + "Sets the font for group titles in legend.", + "Defaults to `legend.font` with its size increased about 10%." + ].join(" ") + }), + orientation: { + valType: "enumerated", + values: ["v", "h"], + dflt: "v", + editType: "legend", + description: "Sets the orientation of the legend." + }, + traceorder: { + valType: "flaglist", + flags: ["reversed", "grouped"], + extras: ["normal"], + editType: "legend", + description: [ + "Determines the order at which the legend items are displayed.", + "If *normal*, the items are displayed top-to-bottom in the same", + "order as the input data.", + "If *reversed*, the items are displayed in the opposite order", + "as *normal*.", + "If *grouped*, the items are displayed in groups", + "(when a trace `legendgroup` is provided).", + "if *grouped+reversed*, the items are displayed in the opposite order", + "as *grouped*." + ].join(" ") + }, + tracegroupgap: { + valType: "number", + min: 0, + dflt: 10, + editType: "legend", + description: [ + "Sets the amount of vertical space (in px) between legend groups." + ].join(" ") + }, + entrywidth: { + valType: "number", + min: 0, + editType: "legend", + description: [ + "Sets the width (in px or fraction) of the legend.", + "Use 0 to size the entry based on the text width,", + "when `entrywidthmode` is set to *pixels*." + ].join(" ") + }, + entrywidthmode: { + valType: "enumerated", + values: ["fraction", "pixels"], + dflt: "pixels", + editType: "legend", + description: "Determines what entrywidth means." + }, + indentation: { + valType: "number", + min: -15, + dflt: 0, + editType: "legend", + description: "Sets the indentation (in px) of the legend entries." + }, + itemsizing: { + valType: "enumerated", + values: ["trace", "constant"], + dflt: "trace", + editType: "legend", + description: [ + "Determines if the legend items symbols scale with their corresponding *trace* attributes", + "or remain *constant* independent of the symbol size on the graph." + ].join(" ") + }, + itemwidth: { + valType: "number", + min: 30, + dflt: 30, + editType: "legend", + description: "Sets the width (in px) of the legend item symbols (the part other than the title.text)." + }, + itemclick: { + valType: "enumerated", + values: ["toggle", "toggleothers", false], + dflt: "toggle", + editType: "legend", + description: [ + "Determines the behavior on legend item click.", + "*toggle* toggles the visibility of the item clicked on the graph.", + "*toggleothers* makes the clicked item the sole visible item on the graph.", + "*false* disables legend item click interactions." + ].join(" ") + }, + itemdoubleclick: { + valType: "enumerated", + values: ["toggle", "toggleothers", false], + dflt: "toggleothers", + editType: "legend", + description: [ + "Determines the behavior on legend item double-click.", + "*toggle* toggles the visibility of the item clicked on the graph.", + "*toggleothers* makes the clicked item the sole visible item on the graph.", + "*false* disables legend item double-click interactions." + ].join(" ") + }, + groupclick: { + valType: "enumerated", + values: ["toggleitem", "togglegroup"], + dflt: "togglegroup", + editType: "legend", + description: [ + "Determines the behavior on legend group item click.", + "*toggleitem* toggles the visibility of the individual item clicked on the graph.", + "*togglegroup* toggles the visibility of all items in the same legendgroup as the item clicked on the graph." + ].join(" ") + }, + x: { + valType: "number", + editType: "legend", + description: [ + "Sets the x position with respect to `xref` (in normalized coordinates) of the legend.", + "When `xref` is *paper*, defaults to *1.02* for vertical legends and", + "defaults to *0* for horizontal legends.", + "When `xref` is *container*, defaults to *1* for vertical legends and", + "defaults to *0* for horizontal legends.", + "Must be between *0* and *1* if `xref` is *container*.", + "and between *-2* and *3* if `xref` is *paper*." + ].join(" ") + }, + xref: { + valType: "enumerated", + dflt: "paper", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `x` refers to.", + "*container* spans the entire `width` of the plot.", + "*paper* refers to the width of the plotting area only." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "left", + editType: "legend", + description: [ + "Sets the legend's horizontal position anchor.", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the legend.", + "Value *auto* anchors legends to the right for `x` values greater than or equal to 2/3,", + "anchors legends to the left for `x` values less than or equal to 1/3 and", + "anchors legends with respect to their center otherwise." + ].join(" ") + }, + y: { + valType: "number", + editType: "legend", + description: [ + "Sets the y position with respect to `yref` (in normalized coordinates) of the legend.", + "When `yref` is *paper*, defaults to *1* for vertical legends,", + "defaults to *-0.1* for horizontal legends on graphs w/o range sliders and", + "defaults to *1.1* for horizontal legends on graph with one or multiple range sliders.", + "When `yref` is *container*, defaults to *1*.", + "Must be between *0* and *1* if `yref` is *container*", + "and between *-2* and *3* if `yref` is *paper*." + ].join(" ") + }, + yref: { + valType: "enumerated", + dflt: "paper", + values: ["container", "paper"], + editType: "layoutstyle", + description: [ + "Sets the container `y` refers to.", + "*container* spans the entire `height` of the plot.", + "*paper* refers to the height of the plotting area only." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + values: ["auto", "top", "middle", "bottom"], + editType: "legend", + description: [ + "Sets the legend's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the legend.", + "Value *auto* anchors legends at their bottom for `y` values less than or equal to 1/3,", + "anchors legends to at their top for `y` values greater than or equal to 2/3 and", + "anchors legends with respect to their middle otherwise." + ].join(" ") + }, + uirevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of legend-driven changes in trace and pie label", + "visibility. Defaults to `layout.uirevision`." + ].join(" ") + }, + valign: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + dflt: "middle", + editType: "legend", + description: [ + "Sets the vertical alignment of the symbols with respect to their associated text." + ].join(" ") + }, + title: { + text: { + valType: "string", + dflt: "", + editType: "legend", + description: [ + "Sets the title of the legend." + ].join(" ") + }, + font: fontAttrs$a({ + editType: "legend", + description: [ + "Sets this legend's title font.", + "Defaults to `legend.font` with its size increased about 20%." + ].join(" ") + }), + side: { + valType: "enumerated", + values: ["top", "left", "top left", "top center", "top right"], + editType: "legend", + description: [ + "Determines the location of legend's title", + "with respect to the legend items.", + "Defaulted to *top* with `orientation` is *h*.", + "Defaulted to *left* with `orientation` is *v*.", + "The *top left* options could be used to expand", + "top center and top right are for horizontal alignment", + "legend area in both x and y sides." + ].join(" ") + }, + editType: "legend" + }, + editType: "legend" +}; +var helpers$I = {}; +helpers$I.isGrouped = function isGrouped(legendLayout) { + return (legendLayout.traceorder || "").indexOf("grouped") !== -1; +}; +helpers$I.isVertical = function isVertical(legendLayout) { + return legendLayout.orientation !== "h"; +}; +helpers$I.isReversed = function isReversed(legendLayout) { + return (legendLayout.traceorder || "").indexOf("reversed") !== -1; +}; +var Registry$H = registry; +var Lib$1C = libExports; +var Template$5 = plot_template; +var plotsAttrs = attributes$O; +var attributes$F = attributes$G; +var basePlotLayoutAttributes = layout_attributes$6; +var helpers$H = helpers$I; +function groupDefaults(legendId, layoutIn, layoutOut, fullData) { + var containerIn = layoutIn[legendId] || {}; + var containerOut = Template$5.newContainer(layoutOut, legendId); + function coerce2(attr, dflt) { + return Lib$1C.coerce(containerIn, containerOut, attributes$F, attr, dflt); + } + var itemFont = Lib$1C.coerceFont(coerce2, "font", layoutOut.font); + coerce2("bgcolor", layoutOut.paper_bgcolor); + coerce2("bordercolor"); + var visible = coerce2("visible"); + if (!visible) return; + var trace; + var traceCoerce = function(attr, dflt) { + var traceIn = trace._input; + var traceOut = trace; + return Lib$1C.coerce(traceIn, traceOut, plotsAttrs, attr, dflt); + }; + var globalFont2 = layoutOut.font || {}; + var grouptitlefont = Lib$1C.coerceFont(coerce2, "grouptitlefont", globalFont2, { overrideDflt: { + size: Math.round(globalFont2.size * 1.1) + } }); + var legendTraceCount = 0; + var legendReallyHasATrace = false; + var defaultOrder = "normal"; + var shapesWithLegend = (layoutOut.shapes || []).filter(function(d) { + return d.showlegend; + }); + var allLegendItems = fullData.concat(shapesWithLegend).filter(function(d) { + return legendId === (d.legend || "legend"); + }); + for (var i = 0; i < allLegendItems.length; i++) { + trace = allLegendItems[i]; + if (!trace.visible) continue; + var isShape = trace._isShape; + if (trace.showlegend || trace._dfltShowLegend && !(trace._module && trace._module.attributes && trace._module.attributes.showlegend && trace._module.attributes.showlegend.dflt === false)) { + legendTraceCount++; + if (trace.showlegend) { + legendReallyHasATrace = true; + if (!isShape && Registry$H.traceIs(trace, "pie-like") || trace._input.showlegend === true) { + legendTraceCount++; + } + } + Lib$1C.coerceFont(traceCoerce, "legendgrouptitle.font", grouptitlefont); + } + if (!isShape && Registry$H.traceIs(trace, "bar") && layoutOut.barmode === "stack" || ["tonextx", "tonexty"].indexOf(trace.fill) !== -1) { + defaultOrder = helpers$H.isGrouped({ traceorder: defaultOrder }) ? "grouped+reversed" : "reversed"; + } + if (trace.legendgroup !== void 0 && trace.legendgroup !== "") { + defaultOrder = helpers$H.isReversed({ traceorder: defaultOrder }) ? "reversed+grouped" : "grouped"; + } + } + var showLegend = Lib$1C.coerce( + layoutIn, + layoutOut, + basePlotLayoutAttributes, + "showlegend", + legendReallyHasATrace && legendTraceCount > (legendId === "legend" ? 1 : 0) + ); + if (showLegend === false) layoutOut[legendId] = void 0; + if (showLegend === false && !containerIn.uirevision) return; + coerce2("uirevision", layoutOut.uirevision); + if (showLegend === false) return; + coerce2("borderwidth"); + var orientation = coerce2("orientation"); + var yref = coerce2("yref"); + var xref = coerce2("xref"); + var isHorizontal = orientation === "h"; + var isPaperY = yref === "paper"; + var isPaperX = xref === "paper"; + var defaultX, defaultY, defaultYAnchor; + var defaultXAnchor = "left"; + if (isHorizontal) { + defaultX = 0; + if (Registry$H.getComponentMethod("rangeslider", "isVisible")(layoutIn.xaxis)) { + if (isPaperY) { + defaultY = 1.1; + defaultYAnchor = "bottom"; + } else { + defaultY = 1; + defaultYAnchor = "top"; + } + } else { + if (isPaperY) { + defaultY = -0.1; + defaultYAnchor = "top"; + } else { + defaultY = 0; + defaultYAnchor = "bottom"; + } + } + } else { + defaultY = 1; + defaultYAnchor = "auto"; + if (isPaperX) { + defaultX = 1.02; + } else { + defaultX = 1; + defaultXAnchor = "right"; + } + } + Lib$1C.coerce(containerIn, containerOut, { + x: { + valType: "number", + editType: "legend", + min: isPaperX ? -2 : 0, + max: isPaperX ? 3 : 1, + dflt: defaultX + } + }, "x"); + Lib$1C.coerce(containerIn, containerOut, { + y: { + valType: "number", + editType: "legend", + min: isPaperY ? -2 : 0, + max: isPaperY ? 3 : 1, + dflt: defaultY + } + }, "y"); + coerce2("traceorder", defaultOrder); + if (helpers$H.isGrouped(layoutOut[legendId])) coerce2("tracegroupgap"); + coerce2("entrywidth"); + coerce2("entrywidthmode"); + coerce2("indentation"); + coerce2("itemsizing"); + coerce2("itemwidth"); + coerce2("itemclick"); + coerce2("itemdoubleclick"); + coerce2("groupclick"); + coerce2("xanchor", defaultXAnchor); + coerce2("yanchor", defaultYAnchor); + coerce2("valign"); + Lib$1C.noneOrAll(containerIn, containerOut, ["x", "y"]); + var titleText = coerce2("title.text"); + if (titleText) { + coerce2("title.side", isHorizontal ? "left" : "top"); + var dfltTitleFont = Lib$1C.extendFlat({}, itemFont, { + size: Lib$1C.bigFont(itemFont.size) + }); + Lib$1C.coerceFont(coerce2, "title.font", dfltTitleFont); + } +} +var defaults$m = function legendDefaults(layoutIn, layoutOut, fullData) { + var i; + var allLegendsData = fullData.slice(); + var shapes2 = layoutOut.shapes; + if (shapes2) { + for (i = 0; i < shapes2.length; i++) { + var shape = shapes2[i]; + if (!shape.showlegend) continue; + var mockTrace = { + _input: shape._input, + visible: shape.visible, + showlegend: shape.showlegend, + legend: shape.legend + }; + allLegendsData.push(mockTrace); + } + } + var legends = ["legend"]; + for (i = 0; i < allLegendsData.length; i++) { + Lib$1C.pushUnique(legends, allLegendsData[i].legend); + } + layoutOut._legends = []; + for (i = 0; i < legends.length; i++) { + var legendId = legends[i]; + groupDefaults(legendId, layoutIn, layoutOut, allLegendsData); + if (layoutOut[legendId] && layoutOut[legendId].visible) { + layoutOut[legendId]._id = legendId; + } + layoutOut._legends.push(legendId); + } +}; +var Registry$G = registry; +var Lib$1B = libExports; +var pushUnique$1 = Lib$1B.pushUnique; +var SHOWISOLATETIP = true; +var handle_click = function handleClick(g, gd, numClicks) { + var fullLayout = gd._fullLayout; + if (gd._dragged || gd._editing) return; + var itemClick = fullLayout.legend.itemclick; + var itemDoubleClick = fullLayout.legend.itemdoubleclick; + var groupClick = fullLayout.legend.groupclick; + if (numClicks === 1 && itemClick === "toggle" && itemDoubleClick === "toggleothers" && SHOWISOLATETIP && gd.data && gd._context.showTips) { + Lib$1B.notifier(Lib$1B._(gd, "Double-click on legend to isolate one trace"), "long"); + SHOWISOLATETIP = false; + } else { + SHOWISOLATETIP = false; + } + var mode; + if (numClicks === 1) mode = itemClick; + else if (numClicks === 2) mode = itemDoubleClick; + if (!mode) return; + var toggleGroup = groupClick === "togglegroup"; + var hiddenSlices = fullLayout.hiddenlabels ? fullLayout.hiddenlabels.slice() : []; + var legendItem = g.data()[0][0]; + if (legendItem.groupTitle && legendItem.noClick) return; + var fullData = gd._fullData; + var shapesWithLegend = (fullLayout.shapes || []).filter(function(d2) { + return d2.showlegend; + }); + var allLegendItems = fullData.concat(shapesWithLegend); + var fullTrace = legendItem.trace; + if (fullTrace._isShape) { + fullTrace = fullTrace._fullInput; + } + var legendgroup = fullTrace.legendgroup; + var i, j, kcont, key, keys, val; + var dataUpdate = {}; + var dataIndices = []; + var carrs = []; + var carrIdx = []; + function insertDataUpdate(traceIndex, value2) { + var attrIndex = dataIndices.indexOf(traceIndex); + var valueArray = dataUpdate.visible; + if (!valueArray) { + valueArray = dataUpdate.visible = []; + } + if (dataIndices.indexOf(traceIndex) === -1) { + dataIndices.push(traceIndex); + attrIndex = dataIndices.length - 1; + } + valueArray[attrIndex] = value2; + return attrIndex; + } + var updatedShapes = (fullLayout.shapes || []).map(function(d2) { + return d2._input; + }); + var shapesUpdated = false; + function insertShapesUpdate(shapeIndex, value2) { + updatedShapes[shapeIndex].visible = value2; + shapesUpdated = true; + } + function setVisibility(fullTrace2, visibility) { + if (legendItem.groupTitle && !toggleGroup) return; + var fullInput2 = fullTrace2._fullInput || fullTrace2; + var isShape2 = fullInput2._isShape; + var index2 = fullInput2.index; + if (index2 === void 0) index2 = fullInput2._index; + if (Registry$G.hasTransform(fullInput2, "groupby")) { + var kcont2 = carrs[index2]; + if (!kcont2) { + var groupbyIndices = Registry$G.getTransformIndices(fullInput2, "groupby"); + var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; + kcont2 = Lib$1B.keyedContainer(fullInput2, "transforms[" + lastGroupbyIndex + "].styles", "target", "value.visible"); + carrs[index2] = kcont2; + } + var curState = kcont2.get(fullTrace2._group); + if (curState === void 0) { + curState = true; + } + if (curState !== false) { + kcont2.set(fullTrace2._group, visibility); + } + carrIdx[index2] = insertDataUpdate(index2, fullInput2.visible === false ? false : true); + } else { + var nextVisibility2 = fullInput2.visible === false ? false : visibility; + if (isShape2) { + insertShapesUpdate(index2, nextVisibility2); + } else { + insertDataUpdate(index2, nextVisibility2); + } + } + } + var thisLegend = fullTrace.legend; + var fullInput = fullTrace._fullInput; + var isShape = fullInput && fullInput._isShape; + if (!isShape && Registry$G.traceIs(fullTrace, "pie-like")) { + var thisLabel = legendItem.label; + var thisLabelIndex = hiddenSlices.indexOf(thisLabel); + if (mode === "toggle") { + if (thisLabelIndex === -1) hiddenSlices.push(thisLabel); + else hiddenSlices.splice(thisLabelIndex, 1); + } else if (mode === "toggleothers") { + var changed = thisLabelIndex !== -1; + var unhideList = []; + for (i = 0; i < gd.calcdata.length; i++) { + var cdi = gd.calcdata[i]; + for (j = 0; j < cdi.length; j++) { + var d = cdi[j]; + var dLabel = d.label; + if (thisLegend === cdi[0].trace.legend) { + if (thisLabel !== dLabel) { + if (hiddenSlices.indexOf(dLabel) === -1) changed = true; + pushUnique$1(hiddenSlices, dLabel); + unhideList.push(dLabel); + } + } + } + } + if (!changed) { + for (var q = 0; q < unhideList.length; q++) { + var pos = hiddenSlices.indexOf(unhideList[q]); + if (pos !== -1) { + hiddenSlices.splice(pos, 1); + } + } + } + } + Registry$G.call("_guiRelayout", gd, "hiddenlabels", hiddenSlices); + } else { + var hasLegendgroup = legendgroup && legendgroup.length; + var traceIndicesInGroup = []; + var tracei; + if (hasLegendgroup) { + for (i = 0; i < allLegendItems.length; i++) { + tracei = allLegendItems[i]; + if (!tracei.visible) continue; + if (tracei.legendgroup === legendgroup) { + traceIndicesInGroup.push(i); + } + } + } + if (mode === "toggle") { + var nextVisibility; + switch (fullTrace.visible) { + case true: + nextVisibility = "legendonly"; + break; + case false: + nextVisibility = false; + break; + case "legendonly": + nextVisibility = true; + break; + } + if (hasLegendgroup) { + if (toggleGroup) { + for (i = 0; i < allLegendItems.length; i++) { + var item = allLegendItems[i]; + if (item.visible !== false && item.legendgroup === legendgroup) { + setVisibility(item, nextVisibility); + } + } + } else { + setVisibility(fullTrace, nextVisibility); + } + } else { + setVisibility(fullTrace, nextVisibility); + } + } else if (mode === "toggleothers") { + var isClicked, isInGroup, notInLegend, otherState, _item; + var isIsolated = true; + for (i = 0; i < allLegendItems.length; i++) { + _item = allLegendItems[i]; + isClicked = _item === fullTrace; + notInLegend = _item.showlegend !== true; + if (isClicked || notInLegend) continue; + isInGroup = hasLegendgroup && _item.legendgroup === legendgroup; + if (!isInGroup && _item.legend === thisLegend && _item.visible === true && !Registry$G.traceIs(_item, "notLegendIsolatable")) { + isIsolated = false; + break; + } + } + for (i = 0; i < allLegendItems.length; i++) { + _item = allLegendItems[i]; + if (_item.visible === false || _item.legend !== thisLegend) continue; + if (Registry$G.traceIs(_item, "notLegendIsolatable")) { + continue; + } + switch (fullTrace.visible) { + case "legendonly": + setVisibility(_item, true); + break; + case true: + otherState = isIsolated ? true : "legendonly"; + isClicked = _item === fullTrace; + notInLegend = _item.showlegend !== true && !_item.legendgroup; + isInGroup = isClicked || hasLegendgroup && _item.legendgroup === legendgroup; + setVisibility(_item, isInGroup || notInLegend ? true : otherState); + break; + } + } + } + for (i = 0; i < carrs.length; i++) { + kcont = carrs[i]; + if (!kcont) continue; + var update2 = kcont.constructUpdate(); + var updateKeys = Object.keys(update2); + for (j = 0; j < updateKeys.length; j++) { + key = updateKeys[j]; + val = dataUpdate[key] = dataUpdate[key] || []; + val[carrIdx[i]] = update2[key]; + } + } + keys = Object.keys(dataUpdate); + for (i = 0; i < keys.length; i++) { + key = keys[i]; + for (j = 0; j < dataIndices.length; j++) { + if (!dataUpdate[key].hasOwnProperty(j)) { + dataUpdate[key][j] = void 0; + } + } + } + if (shapesUpdated) { + Registry$G.call("_guiUpdate", gd, dataUpdate, { shapes: updatedShapes }, dataIndices); + } else { + Registry$G.call("_guiRestyle", gd, dataUpdate, dataIndices); + } + } +}; +var constants$O = { + scrollBarWidth: 6, + scrollBarMinHeight: 20, + scrollBarColor: "#808BA4", + scrollBarMargin: 4, + scrollBarEnterAttrs: { rx: 20, ry: 3, width: 0, height: 0 }, + // number of px between legend title and (left) side of legend (always in x direction and from inner border) + titlePad: 2, + // number of px between each legend item (x and/or y direction) + itemGap: 5 +}; +var Registry$F = registry; +var helpers$G = helpers$I; +var get_legend_data = function getLegendData(calcdata, opts, hasMultipleLegends) { + var inHover = opts._inHover; + var grouped = helpers$G.isGrouped(opts); + var reversed = helpers$G.isReversed(opts); + var lgroupToTraces = {}; + var lgroups = []; + var hasOneNonBlankGroup = false; + var slicesShown = {}; + var lgroupi = 0; + var maxNameLength = 0; + var i, j; + function addOneItem(legendId, legendGroup, legendItem) { + if (opts.visible === false) return; + if (hasMultipleLegends && legendId !== opts._id) return; + if (legendGroup === "" || !helpers$G.isGrouped(opts)) { + var uniqueGroup = "~~i" + lgroupi; + lgroups.push(uniqueGroup); + lgroupToTraces[uniqueGroup] = [legendItem]; + lgroupi++; + } else if (lgroups.indexOf(legendGroup) === -1) { + lgroups.push(legendGroup); + hasOneNonBlankGroup = true; + lgroupToTraces[legendGroup] = [legendItem]; + } else { + lgroupToTraces[legendGroup].push(legendItem); + } + } + for (i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var cd0 = cd[0]; + var trace = cd0.trace; + var lid = trace.legend; + var lgroup = trace.legendgroup; + if (!inHover && (!trace.visible || !trace.showlegend)) continue; + if (Registry$F.traceIs(trace, "pie-like")) { + if (!slicesShown[lgroup]) slicesShown[lgroup] = {}; + for (j = 0; j < cd.length; j++) { + var labelj = cd[j].label; + if (!slicesShown[lgroup][labelj]) { + addOneItem(lid, lgroup, { + label: labelj, + color: cd[j].color, + i: cd[j].i, + trace, + pts: cd[j].pts + }); + slicesShown[lgroup][labelj] = true; + maxNameLength = Math.max(maxNameLength, (labelj || "").length); + } + } + } else { + addOneItem(lid, lgroup, cd0); + maxNameLength = Math.max(maxNameLength, (trace.name || "").length); + } + } + if (!lgroups.length) return []; + var shouldCollapse = !hasOneNonBlankGroup || !grouped; + var legendData = []; + for (i = 0; i < lgroups.length; i++) { + var t = lgroupToTraces[lgroups[i]]; + if (shouldCollapse) { + legendData.push(t[0]); + } else { + legendData.push(t); + } + } + if (shouldCollapse) legendData = [legendData]; + for (i = 0; i < legendData.length; i++) { + var groupMinRank = Infinity; + for (j = 0; j < legendData[i].length; j++) { + var rank = legendData[i][j].trace.legendrank; + if (groupMinRank > rank) groupMinRank = rank; + } + legendData[i][0]._groupMinRank = groupMinRank; + legendData[i][0]._preGroupSort = i; + } + var orderFn1 = function(a, b) { + return a[0]._groupMinRank - b[0]._groupMinRank || a[0]._preGroupSort - b[0]._preGroupSort; + }; + var orderFn2 = function(a, b) { + return a.trace.legendrank - b.trace.legendrank || a._preSort - b._preSort; + }; + legendData.forEach(function(a, k) { + a[0]._preGroupSort = k; + }); + legendData.sort(orderFn1); + for (i = 0; i < legendData.length; i++) { + legendData[i].forEach(function(a, k) { + a._preSort = k; + }); + legendData[i].sort(orderFn2); + var firstItemTrace = legendData[i][0].trace; + var groupTitle = null; + for (j = 0; j < legendData[i].length; j++) { + var gt2 = legendData[i][j].trace.legendgrouptitle; + if (gt2 && gt2.text) { + groupTitle = gt2; + if (inHover) gt2.font = opts._groupTitleFont; + break; + } + } + if (reversed) legendData[i].reverse(); + if (groupTitle) { + var hasPieLike = false; + for (j = 0; j < legendData[i].length; j++) { + if (Registry$F.traceIs(legendData[i][j].trace, "pie-like")) { + hasPieLike = true; + break; + } + } + legendData[i].unshift({ + i: -1, + groupTitle, + noClick: hasPieLike, + trace: { + showlegend: firstItemTrace.showlegend, + legendgroup: firstItemTrace.legendgroup, + visible: opts.groupclick === "toggleitem" ? true : firstItemTrace.visible + } + }); + } + for (j = 0; j < legendData[i].length; j++) { + legendData[i][j] = [ + legendData[i][j] + ]; + } + } + opts._lgroupsLength = legendData.length; + opts._maxNameLength = maxNameLength; + return legendData; +}; +var helpers$F = {}; +(function(exports2) { + var Lib2 = libExports; + function format2(vRounded) { + return vRounded.indexOf("e") !== -1 ? vRounded.replace(/[.]?0+e/, "e") : vRounded.indexOf(".") !== -1 ? vRounded.replace(/[.]?0+$/, "") : vRounded; + } + exports2.formatPiePercent = function formatPiePercent(v, separators) { + var vRounded = format2((v * 100).toPrecision(3)); + return Lib2.numSeparate(vRounded, separators) + "%"; + }; + exports2.formatPieValue = function formatPieValue(v, separators) { + var vRounded = format2(v.toPrecision(10)); + return Lib2.numSeparate(vRounded, separators); + }; + exports2.getFirstFilled = function getFirstFilled(array2, indices) { + if (!Lib2.isArrayOrTypedArray(array2)) return; + for (var i = 0; i < indices.length; i++) { + var v = array2[indices[i]]; + if (v || v === 0 || v === "") return v; + } + }; + exports2.castOption = function castOption2(item, indices) { + if (Lib2.isArrayOrTypedArray(item)) return exports2.getFirstFilled(item, indices); + else if (item) return item; + }; + exports2.getRotationAngle = function(rotation) { + return (rotation === "auto" ? 0 : rotation) * Math.PI / 180; + }; +})(helpers$F); +var Drawing$r = drawingExports; +var Color$G = colorExports; +var fill_one$1 = function fillOne(s, pt, trace, gd) { + var pattern2 = trace.marker.pattern; + if (pattern2 && pattern2.shape) { + Drawing$r.pointStyle(s, trace, gd, pt); + } else { + Color$G.fill(s, pt.color); + } +}; +var Color$F = colorExports; +var castOption = helpers$F.castOption; +var fillOne$2 = fill_one$1; +var style_one = function styleOne(s, pt, trace, gd) { + var line2 = trace.marker.line; + var lineColor = castOption(line2.color, pt.pts) || Color$F.defaultLine; + var lineWidth = castOption(line2.width, pt.pts) || 0; + s.call(fillOne$2, pt, trace, gd).style("stroke-width", lineWidth).call(Color$F.stroke, lineColor); +}; +var d3$u = d3Exports; +var Registry$E = registry; +var Lib$1A = libExports; +var strTranslate$9 = Lib$1A.strTranslate; +var Drawing$q = drawingExports; +var Color$E = colorExports; +var extractOpts = helpers$L.extractOpts; +var subTypes$9 = subtypes$3; +var stylePie = style_one; +var pieCastOption = helpers$F.castOption; +var constants$N = constants$O; +var CST_MARKER_SIZE = 12; +var CST_LINE_WIDTH = 5; +var CST_MARKER_LINE_WIDTH = 2; +var MAX_LINE_WIDTH = 10; +var MAX_MARKER_LINE_WIDTH = 5; +var style$8 = function style(s, gd, legend2) { + var fullLayout = gd._fullLayout; + if (!legend2) legend2 = fullLayout.legend; + var constantItemSizing = legend2.itemsizing === "constant"; + var itemWidth = legend2.itemwidth; + var centerPos = (itemWidth + constants$N.itemGap * 2) / 2; + var centerTransform = strTranslate$9(centerPos, 0); + var boundLineWidth = function(mlw, cont, max, cst) { + var v; + if (mlw + 1) { + v = mlw; + } else if (cont && cont.width > 0) { + v = cont.width; + } else { + return 0; + } + return constantItemSizing ? cst : Math.min(v, max); + }; + s.each(function(d) { + var traceGroup = d3$u.select(this); + var layers = Lib$1A.ensureSingle(traceGroup, "g", "layers"); + layers.style("opacity", d[0].trace.opacity); + var indentation = legend2.indentation; + var valign = legend2.valign; + var lineHeight = d[0].lineHeight; + var height = d[0].height; + if (valign === "middle" && indentation === 0 || !lineHeight || !height) { + layers.attr("transform", null); + } else { + var factor = { top: 1, bottom: -1 }[valign]; + var markerOffsetY = factor * (0.5 * (lineHeight - height + 3)) || 0; + var markerOffsetX = legend2.indentation; + layers.attr("transform", strTranslate$9(markerOffsetX, markerOffsetY)); + } + var fill = layers.selectAll("g.legendfill").data([d]); + fill.enter().append("g").classed("legendfill", true); + var line2 = layers.selectAll("g.legendlines").data([d]); + line2.enter().append("g").classed("legendlines", true); + var symbol = layers.selectAll("g.legendsymbols").data([d]); + symbol.enter().append("g").classed("legendsymbols", true); + symbol.selectAll("g.legendpoints").data([d]).enter().append("g").classed("legendpoints", true); + }).each(styleSpatial).each(styleWaterfalls).each(styleFunnels).each(styleBars).each(styleBoxes).each(styleFunnelareas).each(stylePies).each(styleLines).each(stylePoints2).each(styleCandles).each(styleOHLC); + function styleLines(d) { + var styleGuide = getStyleGuide(d); + var showFill = styleGuide.showFill; + var showLine = styleGuide.showLine; + var showGradientLine = styleGuide.showGradientLine; + var showGradientFill = styleGuide.showGradientFill; + var anyFill = styleGuide.anyFill; + var anyLine = styleGuide.anyLine; + var d0 = d[0]; + var trace = d0.trace; + var dMod, tMod; + var cOpts = extractOpts(trace); + var colorscale2 = cOpts.colorscale; + var reversescale = cOpts.reversescale; + var fillStyle = function(s2) { + if (s2.size()) { + if (showFill) { + Drawing$q.fillGroupStyle(s2, gd, true); + } else { + var gradientID = "legendfill-" + trace.uid; + Drawing$q.gradient( + s2, + gd, + gradientID, + getGradientDirection(reversescale), + colorscale2, + "fill" + ); + } + } + }; + var lineGradient = function(s2) { + if (s2.size()) { + var gradientID = "legendline-" + trace.uid; + Drawing$q.lineGroupStyle(s2); + Drawing$q.gradient( + s2, + gd, + gradientID, + getGradientDirection(reversescale), + colorscale2, + "stroke" + ); + } + }; + var pathStart = subTypes$9.hasMarkers(trace) || !anyFill ? "M5,0" : ( + // with a line leave it slightly below center, to leave room for the + // line thickness and because the line is usually more prominent + anyLine ? "M5,-2" : "M5,-3" + ); + var this3 = d3$u.select(this); + var fill = this3.select(".legendfill").selectAll("path").data(showFill || showGradientFill ? [d] : []); + fill.enter().append("path").classed("js-fill", true); + fill.exit().remove(); + fill.attr("d", pathStart + "h" + itemWidth + "v6h-" + itemWidth + "z").call(fillStyle); + if (showLine || showGradientLine) { + var lw = boundLineWidth(void 0, trace.line, MAX_LINE_WIDTH, CST_LINE_WIDTH); + tMod = Lib$1A.minExtend(trace, { line: { width: lw } }); + dMod = [Lib$1A.minExtend(d0, { trace: tMod })]; + } + var line2 = this3.select(".legendlines").selectAll("path").data(showLine || showGradientLine ? [dMod] : []); + line2.enter().append("path").classed("js-line", true); + line2.exit().remove(); + line2.attr("d", pathStart + (showGradientLine ? "l" + itemWidth + ",0.0001" : "h" + itemWidth)).call(showLine ? Drawing$q.lineGroupStyle : lineGradient); + } + function stylePoints2(d) { + var styleGuide = getStyleGuide(d); + var anyFill = styleGuide.anyFill; + var anyLine = styleGuide.anyLine; + var showLine = styleGuide.showLine; + var showMarker = styleGuide.showMarker; + var d0 = d[0]; + var trace = d0.trace; + var showText = !showMarker && !anyLine && !anyFill && subTypes$9.hasText(trace); + var dMod, tMod; + function boundVal(attrIn, arrayToValFn, bounds, cst) { + var valIn = Lib$1A.nestedProperty(trace, attrIn).get(); + var valToBound = Lib$1A.isArrayOrTypedArray(valIn) && arrayToValFn ? arrayToValFn(valIn) : valIn; + if (constantItemSizing && valToBound && cst !== void 0) { + valToBound = cst; + } + if (bounds) { + if (valToBound < bounds[0]) return bounds[0]; + else if (valToBound > bounds[1]) return bounds[1]; + } + return valToBound; + } + function pickFirst(array2) { + if (d0._distinct && d0.index && array2[d0.index]) return array2[d0.index]; + return array2[0]; + } + if (showMarker || showText || showLine) { + var dEdit = {}; + var tEdit = {}; + if (showMarker) { + dEdit.mc = boundVal("marker.color", pickFirst); + dEdit.mx = boundVal("marker.symbol", pickFirst); + dEdit.mo = boundVal("marker.opacity", Lib$1A.mean, [0.2, 1]); + dEdit.mlc = boundVal("marker.line.color", pickFirst); + dEdit.mlw = boundVal("marker.line.width", Lib$1A.mean, [0, 5], CST_MARKER_LINE_WIDTH); + tEdit.marker = { + sizeref: 1, + sizemin: 1, + sizemode: "diameter" + }; + var ms = boundVal("marker.size", Lib$1A.mean, [2, 16], CST_MARKER_SIZE); + dEdit.ms = ms; + tEdit.marker.size = ms; + } + if (showLine) { + tEdit.line = { + width: boundVal("line.width", pickFirst, [0, 10], CST_LINE_WIDTH) + }; + } + if (showText) { + dEdit.tx = "Aa"; + dEdit.tp = boundVal("textposition", pickFirst); + dEdit.ts = 10; + dEdit.tc = boundVal("textfont.color", pickFirst); + dEdit.tf = boundVal("textfont.family", pickFirst); + dEdit.tw = boundVal("textfont.weight", pickFirst); + dEdit.ty = boundVal("textfont.style", pickFirst); + dEdit.tv = boundVal("textfont.variant", pickFirst); + dEdit.tC = boundVal("textfont.textcase", pickFirst); + dEdit.tE = boundVal("textfont.lineposition", pickFirst); + dEdit.tS = boundVal("textfont.shadow", pickFirst); + } + dMod = [Lib$1A.minExtend(d0, dEdit)]; + tMod = Lib$1A.minExtend(trace, tEdit); + tMod.selectedpoints = null; + tMod.texttemplate = null; + } + var ptgroup = d3$u.select(this).select("g.legendpoints"); + var pts = ptgroup.selectAll("path.scatterpts").data(showMarker ? dMod : []); + pts.enter().insert("path", ":first-child").classed("scatterpts", true).attr("transform", centerTransform); + pts.exit().remove(); + pts.call(Drawing$q.pointStyle, tMod, gd); + if (showMarker) dMod[0].mrc = 3; + var txt = ptgroup.selectAll("g.pointtext").data(showText ? dMod : []); + txt.enter().append("g").classed("pointtext", true).append("text").attr("transform", centerTransform); + txt.exit().remove(); + txt.selectAll("text").call(Drawing$q.textPointStyle, tMod, gd); + } + function styleWaterfalls(d) { + var trace = d[0].trace; + var isWaterfall = trace.type === "waterfall"; + if (d[0]._distinct && isWaterfall) { + var cont = d[0].trace[d[0].dir].marker; + d[0].mc = cont.color; + d[0].mlw = cont.line.width; + d[0].mlc = cont.line.color; + return styleBarLike(d, this, "waterfall"); + } + var ptsData = []; + if (trace.visible && isWaterfall) { + ptsData = d[0].hasTotals ? [["increasing", "M-6,-6V6H0Z"], ["totals", "M6,6H0L-6,-6H-0Z"], ["decreasing", "M6,6V-6H0Z"]] : [["increasing", "M-6,-6V6H6Z"], ["decreasing", "M6,6V-6H-6Z"]]; + } + var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendwaterfall").data(ptsData); + pts.enter().append("path").classed("legendwaterfall", true).attr("transform", centerTransform).style("stroke-miterlimit", 1); + pts.exit().remove(); + pts.each(function(dd) { + var pt = d3$u.select(this); + var cont2 = trace[dd[0]].marker; + var lw = boundLineWidth(void 0, cont2.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + pt.attr("d", dd[1]).style("stroke-width", lw + "px").call(Color$E.fill, cont2.color); + if (lw) { + pt.call(Color$E.stroke, cont2.line.color); + } + }); + } + function styleBars(d) { + styleBarLike(d, this); + } + function styleFunnels(d) { + styleBarLike(d, this, "funnel"); + } + function styleBarLike(d, lThis, desiredType) { + var trace = d[0].trace; + var marker2 = trace.marker || {}; + var markerLine2 = marker2.line || {}; + var pathStr = marker2.cornerradius ? "M6,3a3,3,0,0,1-3,3H-3a3,3,0,0,1-3-3V-3a3,3,0,0,1,3-3H3a3,3,0,0,1,3,3Z" : ( + // Square with rounded corners + "M6,6H-6V-6H6Z" + ); + var isVisible2 = !desiredType ? Registry$E.traceIs(trace, "bar") : trace.visible && trace.type === desiredType; + var barpath = d3$u.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible2 ? [d] : []); + barpath.enter().append("path").classed("legend" + desiredType, true).attr("d", pathStr).attr("transform", centerTransform); + barpath.exit().remove(); + barpath.each(function(d2) { + var p = d3$u.select(this); + var d0 = d2[0]; + var w = boundLineWidth(d0.mlw, marker2.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + p.style("stroke-width", w + "px"); + var mcc = d0.mcc; + if (!legend2._inHover && "mc" in d0) { + var cOpts = extractOpts(marker2); + var mid = cOpts.mid; + if (mid === void 0) mid = (cOpts.max + cOpts.min) / 2; + mcc = Drawing$q.tryColorscale(marker2, "")(mid); + } + var fillColor = mcc || d0.mc || marker2.color; + var markerPattern = marker2.pattern; + var patternShape = markerPattern && Drawing$q.getPatternAttr(markerPattern.shape, 0, ""); + if (patternShape) { + var patternBGColor = Drawing$q.getPatternAttr(markerPattern.bgcolor, 0, null); + var patternFGColor = Drawing$q.getPatternAttr(markerPattern.fgcolor, 0, null); + var patternFGOpacity = markerPattern.fgopacity; + var patternSize = dimAttr(markerPattern.size, 8, 10); + var patternSolidity = dimAttr(markerPattern.solidity, 0.5, 1); + var patternID = "legend-" + trace.uid; + p.call( + Drawing$q.pattern, + "legend", + gd, + patternID, + patternShape, + patternSize, + patternSolidity, + mcc, + markerPattern.fillmode, + patternBGColor, + patternFGColor, + patternFGOpacity + ); + } else { + p.call(Color$E.fill, fillColor); + } + if (w) Color$E.stroke(p, d0.mlc || markerLine2.color); + }); + } + function styleBoxes(d) { + var trace = d[0].trace; + var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendbox").data(trace.visible && Registry$E.traceIs(trace, "box-violin") ? [d] : []); + pts.enter().append("path").classed("legendbox", true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform); + pts.exit().remove(); + pts.each(function() { + var p = d3$u.select(this); + if ((trace.boxpoints === "all" || trace.points === "all") && Color$E.opacity(trace.fillcolor) === 0 && Color$E.opacity((trace.line || {}).color) === 0) { + var tMod = Lib$1A.minExtend(trace, { + marker: { + size: constantItemSizing ? CST_MARKER_SIZE : Lib$1A.constrain(trace.marker.size, 2, 16), + sizeref: 1, + sizemin: 1, + sizemode: "diameter" + } + }); + pts.call(Drawing$q.pointStyle, tMod, gd); + } else { + var w = boundLineWidth(void 0, trace.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + p.style("stroke-width", w + "px").call(Color$E.fill, trace.fillcolor); + if (w) Color$E.stroke(p, trace.line.color); + } + }); + } + function styleCandles(d) { + var trace = d[0].trace; + var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendcandle").data(trace.visible && trace.type === "candlestick" ? [d, d] : []); + pts.enter().append("path").classed("legendcandle", true).attr("d", function(_2, i) { + if (i) return "M-15,0H-8M-8,6V-6H8Z"; + return "M15,0H8M8,-6V6H-8Z"; + }).attr("transform", centerTransform).style("stroke-miterlimit", 1); + pts.exit().remove(); + pts.each(function(_2, i) { + var p = d3$u.select(this); + var cont = trace[i ? "increasing" : "decreasing"]; + var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + p.style("stroke-width", w + "px").call(Color$E.fill, cont.fillcolor); + if (w) Color$E.stroke(p, cont.line.color); + }); + } + function styleOHLC(d) { + var trace = d[0].trace; + var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendohlc").data(trace.visible && trace.type === "ohlc" ? [d, d] : []); + pts.enter().append("path").classed("legendohlc", true).attr("d", function(_2, i) { + if (i) return "M-15,0H0M-8,-6V0"; + return "M15,0H0M8,6V0"; + }).attr("transform", centerTransform).style("stroke-miterlimit", 1); + pts.exit().remove(); + pts.each(function(_2, i) { + var p = d3$u.select(this); + var cont = trace[i ? "increasing" : "decreasing"]; + var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + p.style("fill", "none").call(Drawing$q.dashLine, cont.line.dash, w); + if (w) Color$E.stroke(p, cont.line.color); + }); + } + function stylePies(d) { + stylePieLike(d, this, "pie"); + } + function styleFunnelareas(d) { + stylePieLike(d, this, "funnelarea"); + } + function stylePieLike(d, lThis, desiredType) { + var d0 = d[0]; + var trace = d0.trace; + var isVisible2 = !desiredType ? Registry$E.traceIs(trace, desiredType) : trace.visible && trace.type === desiredType; + var pts = d3$u.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible2 ? [d] : []); + pts.enter().append("path").classed("legend" + desiredType, true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform); + pts.exit().remove(); + if (pts.size()) { + var cont = trace.marker || {}; + var lw = boundLineWidth(pieCastOption(cont.line.width, d0.pts), cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); + var opt = "pieLike"; + var tMod = Lib$1A.minExtend(trace, { marker: { line: { width: lw } } }, opt); + var d0Mod = Lib$1A.minExtend(d0, { trace: tMod }, opt); + stylePie(pts, d0Mod, tMod, gd); + } + } + function styleSpatial(d) { + var trace = d[0].trace; + var useGradient; + var ptsData = []; + if (trace.visible) { + switch (trace.type) { + case "histogram2d": + case "heatmap": + ptsData = [ + ["M-15,-2V4H15V-2Z"] + // similar to contour + ]; + useGradient = true; + break; + case "choropleth": + case "choroplethmapbox": + case "choroplethmap": + ptsData = [ + ["M-6,-6V6H6V-6Z"] + ]; + useGradient = true; + break; + case "densitymapbox": + case "densitymap": + ptsData = [ + ["M-6,0 a6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0"] + ]; + useGradient = "radial"; + break; + case "cone": + ptsData = [ + ["M-6,2 A2,2 0 0,0 -6,6 V6L6,4Z"], + ["M-6,-6 A2,2 0 0,0 -6,-2 L6,-4Z"], + ["M-6,-2 A2,2 0 0,0 -6,2 L6,0Z"] + ]; + useGradient = false; + break; + case "streamtube": + ptsData = [ + ["M-6,2 A2,2 0 0,0 -6,6 H6 A2,2 0 0,1 6,2 Z"], + ["M-6,-6 A2,2 0 0,0 -6,-2 H6 A2,2 0 0,1 6,-6 Z"], + ["M-6,-2 A2,2 0 0,0 -6,2 H6 A2,2 0 0,1 6,-2 Z"] + ]; + useGradient = false; + break; + case "surface": + ptsData = [ + ["M-6,-6 A2,3 0 0,0 -6,0 H6 A2,3 0 0,1 6,-6 Z"], + ["M-6,1 A2,3 0 0,1 -6,6 H6 A2,3 0 0,0 6,0 Z"] + ]; + useGradient = true; + break; + case "mesh3d": + ptsData = [ + ["M-6,6H0L-6,-6Z"], + ["M6,6H0L6,-6Z"], + ["M-6,-6H6L0,6Z"] + ]; + useGradient = false; + break; + case "volume": + ptsData = [ + ["M-6,6H0L-6,-6Z"], + ["M6,6H0L6,-6Z"], + ["M-6,-6H6L0,6Z"] + ]; + useGradient = true; + break; + case "isosurface": + ptsData = [ + ["M-6,6H0L-6,-6Z"], + ["M6,6H0L6,-6Z"], + ["M-6,-6 A12,24 0 0,0 6,-6 L0,6Z"] + ]; + useGradient = false; + break; + } + } + var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legend3dandfriends").data(ptsData); + pts.enter().append("path").classed("legend3dandfriends", true).attr("transform", centerTransform).style("stroke-miterlimit", 1); + pts.exit().remove(); + pts.each(function(dd, i) { + var pt = d3$u.select(this); + var cOpts = extractOpts(trace); + var colorscale2 = cOpts.colorscale; + var reversescale = cOpts.reversescale; + var fillGradient = function(s2) { + if (s2.size()) { + var gradientID = "legendfill-" + trace.uid; + Drawing$q.gradient( + s2, + gd, + gradientID, + getGradientDirection(reversescale, useGradient === "radial"), + colorscale2, + "fill" + ); + } + }; + var fillColor; + if (!colorscale2) { + var color2 = trace.vertexcolor || trace.facecolor || trace.color; + fillColor = Lib$1A.isArrayOrTypedArray(color2) ? color2[i] || color2[0] : color2; + } else { + if (!useGradient) { + var len = colorscale2.length; + fillColor = i === 0 ? colorscale2[reversescale ? len - 1 : 0][1] : ( + // minimum + i === 1 ? colorscale2[reversescale ? 0 : len - 1][1] : ( + // maximum + colorscale2[Math.floor((len - 1) / 2)][1] + ) + ); + } + } + pt.attr("d", dd[0]); + if (fillColor) { + pt.call(Color$E.fill, fillColor); + } else { + pt.call(fillGradient); + } + }); + } +}; +function getGradientDirection(reversescale, isRadial) { + var str2 = isRadial ? "radial" : "horizontal"; + return str2 + (reversescale ? "" : "reversed"); +} +function getStyleGuide(d) { + var trace = d[0].trace; + var contours = trace.contours; + var showLine = subTypes$9.hasLines(trace); + var showMarker = subTypes$9.hasMarkers(trace); + var showFill = trace.visible && trace.fill && trace.fill !== "none"; + var showGradientLine = false; + var showGradientFill = false; + if (contours) { + var coloring = contours.coloring; + if (coloring === "lines") { + showGradientLine = true; + } else { + showLine = coloring === "none" || coloring === "heatmap" || contours.showlines; + } + if (contours.type === "constraint") { + showFill = contours._operation !== "="; + } else if (coloring === "fill" || coloring === "heatmap") { + showGradientFill = true; + } + } + return { + showMarker, + showLine, + showFill, + showGradientLine, + showGradientFill, + anyLine: showLine || showGradientLine, + anyFill: showFill || showGradientFill + }; +} +function dimAttr(v, dflt, max) { + if (v && Lib$1A.isArrayOrTypedArray(v)) return dflt; + if (v > max) return max; + return v; +} +var d3$t = d3Exports; +var Lib$1z = libExports; +var Plots$a = plotsExports; +var Registry$D = registry; +var Events$2 = events; +var dragElement$6 = dragelementExports; +var Drawing$p = drawingExports; +var Color$D = colorExports; +var svgTextUtils$c = svg_text_utils; +var handleClick2 = handle_click; +var constants$M = constants$O; +var alignmentConstants$3 = alignment$1; +var LINE_SPACING$5 = alignmentConstants$3.LINE_SPACING; +var FROM_TL$4 = alignmentConstants$3.FROM_TL; +var FROM_BR$3 = alignmentConstants$3.FROM_BR; +var getLegendData2 = get_legend_data; +var style$7 = style$8; +var helpers$E = helpers$I; +var MAIN_TITLE = 1; +var LEGEND_PATTERN = /^legend[0-9]*$/; +var draw$d = function draw(gd, opts) { + if (opts) { + drawOne$3(gd, opts); + } else { + var fullLayout = gd._fullLayout; + var newLegends = fullLayout._legends; + var oldLegends = fullLayout._infolayer.selectAll('[class^="legend"]'); + oldLegends.each(function() { + var el = d3$t.select(this); + var classes = el.attr("class"); + var cls = classes.split(" ")[0]; + if (cls.match(LEGEND_PATTERN) && newLegends.indexOf(cls) === -1) { + el.remove(); + } + }); + for (var i = 0; i < newLegends.length; i++) { + var legendId = newLegends[i]; + var legendObj = gd._fullLayout[legendId]; + drawOne$3(gd, legendObj); + } + } +}; +function horizontalAlignTitle(titleEl, legendObj, bw) { + if (legendObj.title.side !== "top center" && legendObj.title.side !== "top right") return; + var font2 = legendObj.title.font; + var lineHeight = font2.size * LINE_SPACING$5; + var titleOffset = 0; + var textNode = titleEl.node(); + var width = Drawing$p.bBox(textNode).width; + if (legendObj.title.side === "top center") { + titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants$M.titlePad - width); + } else if (legendObj.title.side === "top right") { + titleOffset = legendObj._width - 2 * bw - 2 * constants$M.titlePad - width; + } + svgTextUtils$c.positionText( + titleEl, + bw + constants$M.titlePad + titleOffset, + bw + lineHeight + ); +} +function drawOne$3(gd, opts) { + var legendObj = opts || {}; + var fullLayout = gd._fullLayout; + var legendId = getId(legendObj); + var clipId, layer; + var inHover = legendObj._inHover; + if (inHover) { + layer = legendObj.layer; + clipId = "hover"; + } else { + layer = fullLayout._infolayer; + clipId = legendId; + } + if (!layer) return; + clipId += fullLayout._uid; + if (!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; + var legendData; + if (!inHover) { + var calcdata = (gd.calcdata || []).slice(); + var shapes2 = fullLayout.shapes; + for (var i = 0; i < shapes2.length; i++) { + var shape = shapes2[i]; + if (!shape.showlegend) continue; + var shapeLegend = { + _isShape: true, + _fullInput: shape, + index: shape._index, + name: shape.name || shape.label.text || "shape " + shape._index, + legend: shape.legend, + legendgroup: shape.legendgroup, + legendgrouptitle: shape.legendgrouptitle, + legendrank: shape.legendrank, + legendwidth: shape.legendwidth, + showlegend: shape.showlegend, + visible: shape.visible, + opacity: shape.opacity, + mode: shape.type === "line" ? "lines" : "markers", + line: shape.line, + marker: { + line: shape.line, + color: shape.fillcolor, + size: 12, + symbol: shape.type === "rect" ? "square" : shape.type === "circle" ? "circle" : ( + // case of path + "hexagon2" + ) + } + }; + calcdata.push([{ trace: shapeLegend }]); + } + legendData = fullLayout.showlegend && getLegendData2(calcdata, legendObj, fullLayout._legends.length > 1); + } else { + if (!legendObj.entries) return; + legendData = getLegendData2(legendObj.entries, legendObj); + } + var hiddenSlices = fullLayout.hiddenlabels || []; + if (!inHover && (!fullLayout.showlegend || !legendData.length)) { + layer.selectAll("." + legendId).remove(); + fullLayout._topdefs.select("#" + clipId).remove(); + return Plots$a.autoMargin(gd, legendId); + } + var legend2 = Lib$1z.ensureSingle(layer, "g", legendId, function(s) { + if (!inHover) s.attr("pointer-events", "all"); + }); + var clipPath = Lib$1z.ensureSingleById(fullLayout._topdefs, "clipPath", clipId, function(s) { + s.append("rect"); + }); + var bg = Lib$1z.ensureSingle(legend2, "rect", "bg", function(s) { + s.attr("shape-rendering", "crispEdges"); + }); + bg.call(Color$D.stroke, legendObj.bordercolor).call(Color$D.fill, legendObj.bgcolor).style("stroke-width", legendObj.borderwidth + "px"); + var scrollBox = Lib$1z.ensureSingle(legend2, "g", "scrollbox"); + var title = legendObj.title; + legendObj._titleWidth = 0; + legendObj._titleHeight = 0; + var titleEl; + if (title.text) { + titleEl = Lib$1z.ensureSingle(scrollBox, "text", legendId + "titletext"); + titleEl.attr("text-anchor", "start").call(Drawing$p.font, title.font).text(title.text); + textLayout(titleEl, scrollBox, gd, legendObj, MAIN_TITLE); + } else { + scrollBox.selectAll("." + legendId + "titletext").remove(); + } + var scrollBar = Lib$1z.ensureSingle(legend2, "rect", "scrollbar", function(s) { + s.attr(constants$M.scrollBarEnterAttrs).call(Color$D.fill, constants$M.scrollBarColor); + }); + var groups = scrollBox.selectAll("g.groups").data(legendData); + groups.enter().append("g").attr("class", "groups"); + groups.exit().remove(); + var traces = groups.selectAll("g.traces").data(Lib$1z.identity); + traces.enter().append("g").attr("class", "traces"); + traces.exit().remove(); + traces.style("opacity", function(d) { + var trace = d[0].trace; + if (Registry$D.traceIs(trace, "pie-like")) { + return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; + } else { + return trace.visible === "legendonly" ? 0.5 : 1; + } + }).each(function() { + d3$t.select(this).call(drawTexts, gd, legendObj); + }).call(style$7, gd, legendObj).each(function() { + if (!inHover) d3$t.select(this).call(setupTraceToggle, gd, legendId); + }); + Lib$1z.syncOrAsync([ + Plots$a.previousPromises, + function() { + return computeLegendDimensions(gd, groups, traces, legendObj); + }, + function() { + var gs = fullLayout._size; + var bw = legendObj.borderwidth; + var isPaperX = legendObj.xref === "paper"; + var isPaperY = legendObj.yref === "paper"; + if (title.text) { + horizontalAlignTitle(titleEl, legendObj, bw); + } + if (!inHover) { + var lx, ly; + if (isPaperX) { + lx = gs.l + gs.w * legendObj.x - FROM_TL$4[getXanchor(legendObj)] * legendObj._width; + } else { + lx = fullLayout.width * legendObj.x - FROM_TL$4[getXanchor(legendObj)] * legendObj._width; + } + if (isPaperY) { + ly = gs.t + gs.h * (1 - legendObj.y) - FROM_TL$4[getYanchor(legendObj)] * legendObj._effHeight; + } else { + ly = fullLayout.height * (1 - legendObj.y) - FROM_TL$4[getYanchor(legendObj)] * legendObj._effHeight; + } + var expMargin = expandMargin(gd, legendId, lx, ly); + if (expMargin) return; + if (fullLayout.margin.autoexpand) { + var lx0 = lx; + var ly0 = ly; + lx = isPaperX ? Lib$1z.constrain(lx, 0, fullLayout.width - legendObj._width) : lx0; + ly = isPaperY ? Lib$1z.constrain(ly, 0, fullLayout.height - legendObj._effHeight) : ly0; + if (lx !== lx0) { + Lib$1z.log("Constrain " + legendId + ".x to make legend fit inside graph"); + } + if (ly !== ly0) { + Lib$1z.log("Constrain " + legendId + ".y to make legend fit inside graph"); + } + } + Drawing$p.setTranslate(legend2, lx, ly); + } + scrollBar.on(".drag", null); + legend2.on("wheel", null); + if (inHover || legendObj._height <= legendObj._maxHeight || gd._context.staticPlot) { + var height = legendObj._effHeight; + if (inHover) height = legendObj._height; + bg.attr({ + width: legendObj._width - bw, + height: height - bw, + x: bw / 2, + y: bw / 2 + }); + Drawing$p.setTranslate(scrollBox, 0, 0); + clipPath.select("rect").attr({ + width: legendObj._width - 2 * bw, + height: height - 2 * bw, + x: bw, + y: bw + }); + Drawing$p.setClipUrl(scrollBox, clipId, gd); + Drawing$p.setRect(scrollBar, 0, 0, 0, 0); + delete legendObj._scrollY; + } else { + var scrollBarHeight = Math.max( + constants$M.scrollBarMinHeight, + legendObj._effHeight * legendObj._effHeight / legendObj._height + ); + var scrollBarYMax = legendObj._effHeight - scrollBarHeight - 2 * constants$M.scrollBarMargin; + var scrollBoxYMax = legendObj._height - legendObj._effHeight; + var scrollRatio = scrollBarYMax / scrollBoxYMax; + var scrollBoxY = Math.min(legendObj._scrollY || 0, scrollBoxYMax); + bg.attr({ + width: legendObj._width - 2 * bw + constants$M.scrollBarWidth + constants$M.scrollBarMargin, + height: legendObj._effHeight - bw, + x: bw / 2, + y: bw / 2 + }); + clipPath.select("rect").attr({ + width: legendObj._width - 2 * bw + constants$M.scrollBarWidth + constants$M.scrollBarMargin, + height: legendObj._effHeight - 2 * bw, + x: bw, + y: bw + scrollBoxY + }); + Drawing$p.setClipUrl(scrollBox, clipId, gd); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + legend2.on("wheel", function() { + scrollBoxY = Lib$1z.constrain( + legendObj._scrollY + d3$t.event.deltaY / scrollBarYMax * scrollBoxYMax, + 0, + scrollBoxYMax + ); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + if (scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { + d3$t.event.preventDefault(); + } + }); + var eventY0, eventY1, scrollBoxY0; + var getScrollBarDragY = function(scrollBoxY02, eventY02, eventY12) { + var y = (eventY12 - eventY02) / scrollRatio + scrollBoxY02; + return Lib$1z.constrain(y, 0, scrollBoxYMax); + }; + var getNaturalDragY = function(scrollBoxY02, eventY02, eventY12) { + var y = (eventY02 - eventY12) / scrollRatio + scrollBoxY02; + return Lib$1z.constrain(y, 0, scrollBoxYMax); + }; + var scrollBarDrag = d3$t.behavior.drag().on("dragstart", function() { + var e = d3$t.event.sourceEvent; + if (e.type === "touchstart") { + eventY0 = e.changedTouches[0].clientY; + } else { + eventY0 = e.clientY; + } + scrollBoxY0 = scrollBoxY; + }).on("drag", function() { + var e = d3$t.event.sourceEvent; + if (e.buttons === 2 || e.ctrlKey) return; + if (e.type === "touchmove") { + eventY1 = e.changedTouches[0].clientY; + } else { + eventY1 = e.clientY; + } + scrollBoxY = getScrollBarDragY(scrollBoxY0, eventY0, eventY1); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + }); + scrollBar.call(scrollBarDrag); + var scrollBoxTouchDrag = d3$t.behavior.drag().on("dragstart", function() { + var e = d3$t.event.sourceEvent; + if (e.type === "touchstart") { + eventY0 = e.changedTouches[0].clientY; + scrollBoxY0 = scrollBoxY; + } + }).on("drag", function() { + var e = d3$t.event.sourceEvent; + if (e.type === "touchmove") { + eventY1 = e.changedTouches[0].clientY; + scrollBoxY = getNaturalDragY(scrollBoxY0, eventY0, eventY1); + scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); + } + }); + scrollBox.call(scrollBoxTouchDrag); + } + function scrollHandler(scrollBoxY2, scrollBarHeight2, scrollRatio2) { + legendObj._scrollY = gd._fullLayout[legendId]._scrollY = scrollBoxY2; + Drawing$p.setTranslate(scrollBox, 0, -scrollBoxY2); + Drawing$p.setRect( + scrollBar, + legendObj._width, + constants$M.scrollBarMargin + scrollBoxY2 * scrollRatio2, + constants$M.scrollBarWidth, + scrollBarHeight2 + ); + clipPath.select("rect").attr("y", bw + scrollBoxY2); + } + if (gd._context.edits.legendPosition) { + var xf, yf, x0, y0; + legend2.classed("cursor-move", true); + dragElement$6.init({ + element: legend2.node(), + gd, + prepFn: function(e) { + if (e.target === scrollBar.node()) { + return; + } + var transform = Drawing$p.getTranslate(legend2); + x0 = transform.x; + y0 = transform.y; + }, + moveFn: function(dx, dy) { + if (x0 !== void 0 && y0 !== void 0) { + var newX = x0 + dx; + var newY = y0 + dy; + Drawing$p.setTranslate(legend2, newX, newY); + xf = dragElement$6.align(newX, legendObj._width, gs.l, gs.l + gs.w, legendObj.xanchor); + yf = dragElement$6.align(newY + legendObj._height, -legendObj._height, gs.t + gs.h, gs.t, legendObj.yanchor); + } + }, + doneFn: function() { + if (xf !== void 0 && yf !== void 0) { + var obj = {}; + obj[legendId + ".x"] = xf; + obj[legendId + ".y"] = yf; + Registry$D.call("_guiRelayout", gd, obj); + } + }, + clickFn: function(numClicks, e) { + var clickedTrace = layer.selectAll("g.traces").filter(function() { + var bbox = this.getBoundingClientRect(); + return e.clientX >= bbox.left && e.clientX <= bbox.right && e.clientY >= bbox.top && e.clientY <= bbox.bottom; + }); + if (clickedTrace.size() > 0) { + clickOrDoubleClick(gd, legend2, clickedTrace, numClicks, e); + } + } + }); + } + } + ], gd); +} +function getTraceWidth(d, legendObj, textGap) { + var legendItem = d[0]; + var legendWidth = legendItem.width; + var mode = legendObj.entrywidthmode; + var traceLegendWidth = legendItem.trace.legendwidth || legendObj.entrywidth; + if (mode === "fraction") return legendObj._maxWidth * traceLegendWidth; + return textGap + (traceLegendWidth || legendWidth); +} +function clickOrDoubleClick(gd, legend2, legendItem, numClicks, evt) { + var trace = legendItem.data()[0][0].trace; + var evtData = { + event: evt, + node: legendItem.node(), + curveNumber: trace.index, + expandedIndex: trace._expandedIndex, + data: gd.data, + layout: gd.layout, + frames: gd._transitionData._frames, + config: gd._context, + fullData: gd._fullData, + fullLayout: gd._fullLayout + }; + if (trace._group) { + evtData.group = trace._group; + } + if (Registry$D.traceIs(trace, "pie-like")) { + evtData.label = legendItem.datum()[0].label; + } + var clickVal = Events$2.triggerHandler(gd, "plotly_legendclick", evtData); + if (numClicks === 1) { + if (clickVal === false) return; + legend2._clickTimeout = setTimeout(function() { + if (!gd._fullLayout) return; + handleClick2(legendItem, gd, numClicks); + }, gd._context.doubleClickDelay); + } else if (numClicks === 2) { + if (legend2._clickTimeout) clearTimeout(legend2._clickTimeout); + gd._legendMouseDownTime = 0; + var dblClickVal = Events$2.triggerHandler(gd, "plotly_legenddoubleclick", evtData); + if (dblClickVal !== false && clickVal !== false) handleClick2(legendItem, gd, numClicks); + } +} +function drawTexts(g, gd, legendObj) { + var legendId = getId(legendObj); + var legendItem = g.data()[0][0]; + var trace = legendItem.trace; + var isPieLike = Registry$D.traceIs(trace, "pie-like"); + var isEditable = !legendObj._inHover && gd._context.edits.legendText && !isPieLike; + var maxNameLength = legendObj._maxNameLength; + var name2, font2; + if (legendItem.groupTitle) { + name2 = legendItem.groupTitle.text; + font2 = legendItem.groupTitle.font; + } else { + font2 = legendObj.font; + if (!legendObj.entries) { + name2 = isPieLike ? legendItem.label : trace.name; + if (trace._meta) { + name2 = Lib$1z.templateString(name2, trace._meta); + } + } else { + name2 = legendItem.text; + } + } + var textEl = Lib$1z.ensureSingle(g, "text", legendId + "text"); + textEl.attr("text-anchor", "start").call(Drawing$p.font, font2).text(isEditable ? ensureLength(name2, maxNameLength) : name2); + var textGap = legendObj.indentation + legendObj.itemwidth + constants$M.itemGap * 2; + svgTextUtils$c.positionText(textEl, textGap, 0); + if (isEditable) { + textEl.call(svgTextUtils$c.makeEditable, { gd, text: name2 }).call(textLayout, g, gd, legendObj).on("edit", function(newName) { + this.text(ensureLength(newName, maxNameLength)).call(textLayout, g, gd, legendObj); + var fullInput = legendItem.trace._fullInput || {}; + var update2 = {}; + if (Registry$D.hasTransform(fullInput, "groupby")) { + var groupbyIndices = Registry$D.getTransformIndices(fullInput, "groupby"); + var _index = groupbyIndices[groupbyIndices.length - 1]; + var kcont = Lib$1z.keyedContainer(fullInput, "transforms[" + _index + "].styles", "target", "value.name"); + kcont.set(legendItem.trace._group, newName); + update2 = kcont.constructUpdate(); + } else { + update2.name = newName; + } + if (fullInput._isShape) { + return Registry$D.call("_guiRelayout", gd, "shapes[" + trace.index + "].name", update2.name); + } else { + return Registry$D.call("_guiRestyle", gd, update2, trace.index); + } + }); + } else { + textLayout(textEl, g, gd, legendObj); + } +} +function ensureLength(str2, maxLength) { + var targetLength = Math.max(4, maxLength); + if (str2 && str2.trim().length >= targetLength / 2) return str2; + str2 = str2 || ""; + for (var i = targetLength - str2.length; i > 0; i--) str2 += " "; + return str2; +} +function setupTraceToggle(g, gd, legendId) { + var doubleClickDelay = gd._context.doubleClickDelay; + var newMouseDownTime; + var numClicks = 1; + var traceToggle = Lib$1z.ensureSingle(g, "rect", legendId + "toggle", function(s) { + if (!gd._context.staticPlot) { + s.style("cursor", "pointer").attr("pointer-events", "all"); + } + s.call(Color$D.fill, "rgba(0,0,0,0)"); + }); + if (gd._context.staticPlot) return; + traceToggle.on("mousedown", function() { + newMouseDownTime = (/* @__PURE__ */ new Date()).getTime(); + if (newMouseDownTime - gd._legendMouseDownTime < doubleClickDelay) { + numClicks += 1; + } else { + numClicks = 1; + gd._legendMouseDownTime = newMouseDownTime; + } + }); + traceToggle.on("mouseup", function() { + if (gd._dragged || gd._editing) return; + var legend2 = gd._fullLayout[legendId]; + if ((/* @__PURE__ */ new Date()).getTime() - gd._legendMouseDownTime > doubleClickDelay) { + numClicks = Math.max(numClicks - 1, 1); + } + clickOrDoubleClick(gd, legend2, g, numClicks, d3$t.event); + }); +} +function textLayout(s, g, gd, legendObj, aTitle) { + if (legendObj._inHover) s.attr("data-notex", true); + svgTextUtils$c.convertToTspans(s, gd, function() { + computeTextDimensions(g, gd, legendObj, aTitle); + }); +} +function computeTextDimensions(g, gd, legendObj, aTitle) { + var legendItem = g.data()[0][0]; + if (!legendObj._inHover && legendItem && !legendItem.trace.showlegend) { + g.remove(); + return; + } + var mathjaxGroup = g.select("g[class*=math-group]"); + var mathjaxNode = mathjaxGroup.node(); + var legendId = getId(legendObj); + if (!legendObj) { + legendObj = gd._fullLayout[legendId]; + } + var bw = legendObj.borderwidth; + var font2; + if (aTitle === MAIN_TITLE) { + font2 = legendObj.title.font; + } else if (legendItem.groupTitle) { + font2 = legendItem.groupTitle.font; + } else { + font2 = legendObj.font; + } + var lineHeight = font2.size * LINE_SPACING$5; + var height, width; + if (mathjaxNode) { + var mathjaxBB = Drawing$p.bBox(mathjaxNode); + height = mathjaxBB.height; + width = mathjaxBB.width; + if (aTitle === MAIN_TITLE) { + Drawing$p.setTranslate(mathjaxGroup, bw, bw + height * 0.75); + } else { + Drawing$p.setTranslate(mathjaxGroup, 0, height * 0.25); + } + } else { + var cls = "." + legendId + (aTitle === MAIN_TITLE ? "title" : "") + "text"; + var textEl = g.select(cls); + var textLines = svgTextUtils$c.lineCount(textEl); + var textNode = textEl.node(); + height = lineHeight * textLines; + width = textNode ? Drawing$p.bBox(textNode).width : 0; + if (aTitle === MAIN_TITLE) { + if (legendObj.title.side === "left") { + width += constants$M.itemGap * 2; + } + svgTextUtils$c.positionText( + textEl, + bw + constants$M.titlePad, + bw + lineHeight + ); + } else { + var x = constants$M.itemGap * 2 + legendObj.indentation + legendObj.itemwidth; + if (legendItem.groupTitle) { + x = constants$M.itemGap; + width -= legendObj.indentation + legendObj.itemwidth; + } + svgTextUtils$c.positionText( + textEl, + x, + -lineHeight * ((textLines - 1) / 2 - 0.3) + ); + } + } + if (aTitle === MAIN_TITLE) { + legendObj._titleWidth = width; + legendObj._titleHeight = height; + } else { + legendItem.lineHeight = lineHeight; + legendItem.height = Math.max(height, 16) + 3; + legendItem.width = width; + } +} +function getTitleSize(legendObj) { + var w = 0; + var h = 0; + var side = legendObj.title.side; + if (side) { + if (side.indexOf("left") !== -1) { + w = legendObj._titleWidth; + } + if (side.indexOf("top") !== -1) { + h = legendObj._titleHeight; + } + } + return [w, h]; +} +function computeLegendDimensions(gd, groups, traces, legendObj) { + var fullLayout = gd._fullLayout; + var legendId = getId(legendObj); + if (!legendObj) { + legendObj = fullLayout[legendId]; + } + var gs = fullLayout._size; + var isVertical2 = helpers$E.isVertical(legendObj); + var isGrouped2 = helpers$E.isGrouped(legendObj); + var isFraction = legendObj.entrywidthmode === "fraction"; + var bw = legendObj.borderwidth; + var bw2 = 2 * bw; + var itemGap = constants$M.itemGap; + var textGap = legendObj.indentation + legendObj.itemwidth + itemGap * 2; + var endPad = 2 * (bw + itemGap); + var yanchor = getYanchor(legendObj); + var isBelowPlotArea = legendObj.y < 0 || legendObj.y === 0 && yanchor === "top"; + var isAbovePlotArea = legendObj.y > 1 || legendObj.y === 1 && yanchor === "bottom"; + var traceGroupGap = legendObj.tracegroupgap; + var legendGroupWidths = {}; + legendObj._maxHeight = Math.max( + isBelowPlotArea || isAbovePlotArea ? fullLayout.height / 2 : gs.h, + 30 + ); + var toggleRectWidth = 0; + legendObj._width = 0; + legendObj._height = 0; + var titleSize = getTitleSize(legendObj); + if (isVertical2) { + traces.each(function(d) { + var h = d[0].height; + Drawing$p.setTranslate( + this, + bw + titleSize[0], + bw + titleSize[1] + legendObj._height + h / 2 + itemGap + ); + legendObj._height += h; + legendObj._width = Math.max(legendObj._width, d[0].width); + }); + toggleRectWidth = textGap + legendObj._width; + legendObj._width += itemGap + textGap + bw2; + legendObj._height += endPad; + if (isGrouped2) { + groups.each(function(d, i) { + Drawing$p.setTranslate(this, 0, i * legendObj.tracegroupgap); + }); + legendObj._height += (legendObj._lgroupsLength - 1) * legendObj.tracegroupgap; + } + } else { + var xanchor = getXanchor(legendObj); + var isLeftOfPlotArea = legendObj.x < 0 || legendObj.x === 0 && xanchor === "right"; + var isRightOfPlotArea = legendObj.x > 1 || legendObj.x === 1 && xanchor === "left"; + var isBeyondPlotAreaY = isAbovePlotArea || isBelowPlotArea; + var hw = fullLayout.width / 2; + legendObj._maxWidth = Math.max( + isLeftOfPlotArea ? isBeyondPlotAreaY && xanchor === "left" ? gs.l + gs.w : hw : isRightOfPlotArea ? isBeyondPlotAreaY && xanchor === "right" ? gs.r + gs.w : hw : gs.w, + 2 * textGap + ); + var maxItemWidth = 0; + var combinedItemWidth = 0; + traces.each(function(d) { + var w = getTraceWidth(d, legendObj, textGap); + maxItemWidth = Math.max(maxItemWidth, w); + combinedItemWidth += w; + }); + toggleRectWidth = null; + var maxRowWidth = 0; + if (isGrouped2) { + var maxGroupHeightInRow = 0; + var groupOffsetX = 0; + var groupOffsetY = 0; + groups.each(function() { + var maxWidthInGroup = 0; + var offsetY2 = 0; + d3$t.select(this).selectAll("g.traces").each(function(d) { + var w = getTraceWidth(d, legendObj, textGap); + var h = d[0].height; + Drawing$p.setTranslate( + this, + titleSize[0], + titleSize[1] + bw + itemGap + h / 2 + offsetY2 + ); + offsetY2 += h; + maxWidthInGroup = Math.max(maxWidthInGroup, w); + legendGroupWidths[d[0].trace.legendgroup] = maxWidthInGroup; + }); + var next = maxWidthInGroup + itemGap; + if ( + // not on the first column already + groupOffsetX > 0 && // goes beyound limit + next + bw + groupOffsetX > legendObj._maxWidth + ) { + maxRowWidth = Math.max(maxRowWidth, groupOffsetX); + groupOffsetX = 0; + groupOffsetY += maxGroupHeightInRow + traceGroupGap; + maxGroupHeightInRow = offsetY2; + } else { + maxGroupHeightInRow = Math.max(maxGroupHeightInRow, offsetY2); + } + Drawing$p.setTranslate(this, groupOffsetX, groupOffsetY); + groupOffsetX += next; + }); + legendObj._width = Math.max(maxRowWidth, groupOffsetX) + bw; + legendObj._height = groupOffsetY + maxGroupHeightInRow + endPad; + } else { + var nTraces = traces.size(); + var oneRowLegend = combinedItemWidth + bw2 + (nTraces - 1) * itemGap < legendObj._maxWidth; + var maxItemHeightInRow = 0; + var offsetX = 0; + var offsetY = 0; + var rowWidth = 0; + traces.each(function(d) { + var h = d[0].height; + var w = getTraceWidth(d, legendObj, textGap); + var next = oneRowLegend ? w : maxItemWidth; + if (!isFraction) { + next += itemGap; + } + if (next + bw + offsetX - itemGap >= legendObj._maxWidth) { + maxRowWidth = Math.max(maxRowWidth, rowWidth); + offsetX = 0; + offsetY += maxItemHeightInRow; + legendObj._height += maxItemHeightInRow; + maxItemHeightInRow = 0; + } + Drawing$p.setTranslate( + this, + titleSize[0] + bw + offsetX, + titleSize[1] + bw + offsetY + h / 2 + itemGap + ); + rowWidth = offsetX + w + itemGap; + offsetX += next; + maxItemHeightInRow = Math.max(maxItemHeightInRow, h); + }); + if (oneRowLegend) { + legendObj._width = offsetX + bw2; + legendObj._height = maxItemHeightInRow + endPad; + } else { + legendObj._width = Math.max(maxRowWidth, rowWidth) + bw2; + legendObj._height += maxItemHeightInRow + endPad; + } + } + } + legendObj._width = Math.ceil( + Math.max( + legendObj._width + titleSize[0], + legendObj._titleWidth + 2 * (bw + constants$M.titlePad) + ) + ); + legendObj._height = Math.ceil( + Math.max( + legendObj._height + titleSize[1], + legendObj._titleHeight + 2 * (bw + constants$M.itemGap) + ) + ); + legendObj._effHeight = Math.min(legendObj._height, legendObj._maxHeight); + var edits = gd._context.edits; + var isEditable = edits.legendText || edits.legendPosition; + traces.each(function(d) { + var traceToggle = d3$t.select(this).select("." + legendId + "toggle"); + var h = d[0].height; + var legendgroup = d[0].trace.legendgroup; + var traceWidth = getTraceWidth(d, legendObj, textGap); + if (isGrouped2 && legendgroup !== "") { + traceWidth = legendGroupWidths[legendgroup]; + } + var w = isEditable ? textGap : toggleRectWidth || traceWidth; + if (!isVertical2 && !isFraction) { + w += itemGap / 2; + } + Drawing$p.setRect(traceToggle, 0, -h / 2, w, h); + }); +} +function expandMargin(gd, legendId, lx, ly) { + var fullLayout = gd._fullLayout; + var legendObj = fullLayout[legendId]; + var xanchor = getXanchor(legendObj); + var yanchor = getYanchor(legendObj); + var isPaperX = legendObj.xref === "paper"; + var isPaperY = legendObj.yref === "paper"; + gd._fullLayout._reservedMargin[legendId] = {}; + var sideY = legendObj.y < 0.5 ? "b" : "t"; + var sideX = legendObj.x < 0.5 ? "l" : "r"; + var possibleReservedMargins = { + r: fullLayout.width - lx, + l: lx + legendObj._width, + b: fullLayout.height - ly, + t: ly + legendObj._effHeight + }; + if (isPaperX && isPaperY) { + return Plots$a.autoMargin(gd, legendId, { + x: legendObj.x, + y: legendObj.y, + l: legendObj._width * FROM_TL$4[xanchor], + r: legendObj._width * FROM_BR$3[xanchor], + b: legendObj._effHeight * FROM_BR$3[yanchor], + t: legendObj._effHeight * FROM_TL$4[yanchor] + }); + } else if (isPaperX) { + gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY]; + } else if (isPaperY) { + gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX]; + } else { + if (legendObj.orientation === "v") { + gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX]; + } else { + gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY]; + } + } +} +function getXanchor(legendObj) { + return Lib$1z.isRightAnchor(legendObj) ? "right" : Lib$1z.isCenterAnchor(legendObj) ? "center" : "left"; +} +function getYanchor(legendObj) { + return Lib$1z.isBottomAnchor(legendObj) ? "bottom" : Lib$1z.isMiddleAnchor(legendObj) ? "middle" : "top"; +} +function getId(legendObj) { + return legendObj._id || "legend"; +} +var d3$s = d3Exports; +var isNumeric$i = fastIsnumeric; +var tinycolor$3 = tinycolorExports; +var Lib$1y = libExports; +var pushUnique2 = Lib$1y.pushUnique; +var strTranslate$8 = Lib$1y.strTranslate; +var strRotate$1 = Lib$1y.strRotate; +var Events$1 = events; +var svgTextUtils$b = svg_text_utils; +var overrideCursor2 = override_cursor; +var Drawing$o = drawingExports; +var Color$C = colorExports; +var dragElement$5 = dragelementExports; +var Axes$l = axesExports; +var zindexSeparator$1 = constants$U.zindexSeparator; +var Registry$C = registry; +var helpers$D = helpers$J; +var constants$L = constants$W; +var legendSupplyDefaults = defaults$m; +var legendDraw = draw$d; +var YANGLE = constants$L.YANGLE; +var YA_RADIANS = Math.PI * YANGLE / 180; +var YFACTOR = 1 / Math.sin(YA_RADIANS); +var YSHIFTX = Math.cos(YA_RADIANS); +var YSHIFTY = Math.sin(YA_RADIANS); +var HOVERARROWSIZE = constants$L.HOVERARROWSIZE; +var HOVERTEXTPAD = constants$L.HOVERTEXTPAD; +var multipleHoverPoints = { + box: true, + ohlc: true, + violin: true, + candlestick: true +}; +var cartesianScatterPoints = { + scatter: true, + scattergl: true, + splom: true +}; +function distanceSort(a, b) { + return a.distance - b.distance; +} +hover$7.hover = function hover(gd, evt, subplot, noHoverEvent) { + gd = Lib$1y.getGraphDiv(gd); + var eventTarget = evt.target; + Lib$1y.throttle( + gd._fullLayout._uid + constants$L.HOVERID, + constants$L.HOVERMINTIME, + function() { + _hover(gd, evt, subplot, noHoverEvent, eventTarget); + } + ); +}; +hover$7.loneHover = function loneHover(hoverItems, opts) { + var multiHover = true; + if (!Array.isArray(hoverItems)) { + multiHover = false; + hoverItems = [hoverItems]; + } + var gd = opts.gd; + var gTop = getTopOffset(gd); + var gLeft = getLeftOffset(gd); + var pointsData = hoverItems.map(function(hoverItem) { + var _x0 = hoverItem._x0 || hoverItem.x0 || hoverItem.x || 0; + var _x1 = hoverItem._x1 || hoverItem.x1 || hoverItem.x || 0; + var _y0 = hoverItem._y0 || hoverItem.y0 || hoverItem.y || 0; + var _y1 = hoverItem._y1 || hoverItem.y1 || hoverItem.y || 0; + var eventData5 = hoverItem.eventData; + if (eventData5) { + var x0 = Math.min(_x0, _x1); + var x1 = Math.max(_x0, _x1); + var y0 = Math.min(_y0, _y1); + var y1 = Math.max(_y0, _y1); + var trace = hoverItem.trace; + if (Registry$C.traceIs(trace, "gl3d")) { + var container = gd._fullLayout[trace.scene]._scene.container; + var dx = container.offsetLeft; + var dy = container.offsetTop; + x0 += dx; + x1 += dx; + y0 += dy; + y1 += dy; + } + eventData5.bbox = { + x0: x0 + gLeft, + x1: x1 + gLeft, + y0: y0 + gTop, + y1: y1 + gTop + }; + if (opts.inOut_bbox) { + opts.inOut_bbox.push(eventData5.bbox); + } + } else { + eventData5 = false; + } + return { + color: hoverItem.color || Color$C.defaultLine, + x0: hoverItem.x0 || hoverItem.x || 0, + x1: hoverItem.x1 || hoverItem.x || 0, + y0: hoverItem.y0 || hoverItem.y || 0, + y1: hoverItem.y1 || hoverItem.y || 0, + xLabel: hoverItem.xLabel, + yLabel: hoverItem.yLabel, + zLabel: hoverItem.zLabel, + text: hoverItem.text, + name: hoverItem.name, + idealAlign: hoverItem.idealAlign, + // optional extra bits of styling + borderColor: hoverItem.borderColor, + fontFamily: hoverItem.fontFamily, + fontSize: hoverItem.fontSize, + fontColor: hoverItem.fontColor, + fontWeight: hoverItem.fontWeight, + fontStyle: hoverItem.fontStyle, + fontVariant: hoverItem.fontVariant, + nameLength: hoverItem.nameLength, + textAlign: hoverItem.textAlign, + // filler to make createHoverText happy + trace: hoverItem.trace || { + index: 0, + hoverinfo: "" + }, + xa: { _offset: 0 }, + ya: { _offset: 0 }, + index: 0, + hovertemplate: hoverItem.hovertemplate || false, + hovertemplateLabels: hoverItem.hovertemplateLabels || false, + eventData: eventData5 + }; + }); + var rotateLabels = false; + var hoverText = createHoverText(pointsData, { + gd, + hovermode: "closest", + rotateLabels, + bgColor: opts.bgColor || Color$C.background, + container: d3$s.select(opts.container), + outerContainer: opts.outerContainer || opts.container + }); + var hoverLabel = hoverText.hoverLabels; + var tooltipSpacing = 5; + var lastBottomY = 0; + var anchor = 0; + hoverLabel.sort(function(a, b) { + return a.y0 - b.y0; + }).each(function(d, i) { + var topY = d.y0 - d.by / 2; + if (topY - tooltipSpacing < lastBottomY) { + d.offset = lastBottomY - topY + tooltipSpacing; + } else { + d.offset = 0; + } + lastBottomY = topY + d.by + d.offset; + if (i === opts.anchorIndex || 0) anchor = d.offset; + }).each(function(d) { + d.offset -= anchor; + }); + var scaleX = gd._fullLayout._invScaleX; + var scaleY = gd._fullLayout._invScaleY; + alignHoverText(hoverLabel, rotateLabels, scaleX, scaleY); + return multiHover ? hoverLabel : hoverLabel.node(); +}; +function _hover(gd, evt, subplot, noHoverEvent, eventTarget) { + if (!subplot) subplot = "xy"; + if (typeof subplot === "string") { + subplot = subplot.split(zindexSeparator$1)[0]; + } + var subplots = Array.isArray(subplot) ? subplot : [subplot]; + var spId; + var fullLayout = gd._fullLayout; + var hoversubplots = fullLayout.hoversubplots; + var plots2 = fullLayout._plots || []; + var plotinfo = plots2[subplot]; + var hasCartesian = fullLayout._has("cartesian"); + var hovermode = evt.hovermode || fullLayout.hovermode; + var hovermodeHasX = (hovermode || "").charAt(0) === "x"; + var hovermodeHasY = (hovermode || "").charAt(0) === "y"; + var firstXaxis; + var firstYaxis; + if (hasCartesian && (hovermodeHasX || hovermodeHasY) && hoversubplots === "axis") { + var subplotsLength = subplots.length; + for (var p = 0; p < subplotsLength; p++) { + spId = subplots[p]; + if (plots2[spId]) { + firstXaxis = Axes$l.getFromId(gd, spId, "x"); + firstYaxis = Axes$l.getFromId(gd, spId, "y"); + var subplotsWith = (hovermodeHasX ? firstXaxis : firstYaxis)._subplotsWith; + if (subplotsWith && subplotsWith.length) { + for (var q = 0; q < subplotsWith.length; q++) { + pushUnique2(subplots, subplotsWith[q]); + } + } + } + } + } + if (plotinfo && hoversubplots !== "single") { + var overlayedSubplots = plotinfo.overlays.map(function(pi) { + return pi.id; + }); + subplots = subplots.concat(overlayedSubplots); + } + var len = subplots.length; + var xaArray = new Array(len); + var yaArray = new Array(len); + var supportsCompare = false; + for (var i = 0; i < len; i++) { + spId = subplots[i]; + if (plots2[spId]) { + supportsCompare = true; + xaArray[i] = plots2[spId].xaxis; + yaArray[i] = plots2[spId].yaxis; + } else if (fullLayout[spId] && fullLayout[spId]._subplot) { + var _subplot = fullLayout[spId]._subplot; + xaArray[i] = _subplot.xaxis; + yaArray[i] = _subplot.yaxis; + } else { + Lib$1y.warn("Unrecognized subplot: " + spId); + return; + } + } + if (hovermode && !supportsCompare) hovermode = "closest"; + if (["x", "y", "closest", "x unified", "y unified"].indexOf(hovermode) === -1 || !gd.calcdata || gd.querySelector(".zoombox") || gd._dragging) { + return dragElement$5.unhoverRaw(gd, evt); + } + var hoverdistance = fullLayout.hoverdistance; + if (hoverdistance === -1) hoverdistance = Infinity; + var spikedistance = fullLayout.spikedistance; + if (spikedistance === -1) spikedistance = Infinity; + var hoverData = []; + var searchData = []; + var xvalArray, yvalArray; + var itemnum, curvenum, cd, trace, subplotId, subploti, _mode, xval, yval, pointData, closedataPreviousLength; + var spikePoints = { + hLinePoint: null, + vLinePoint: null + }; + var hasOneHorizontalTrace = false; + if (Array.isArray(evt)) { + hovermode = "array"; + for (itemnum = 0; itemnum < evt.length; itemnum++) { + cd = gd.calcdata[evt[itemnum].curveNumber || 0]; + if (cd) { + trace = cd[0].trace; + if (cd[0].trace.hoverinfo !== "skip") { + searchData.push(cd); + if (trace.orientation === "h") { + hasOneHorizontalTrace = true; + } + } + } + } + } else { + var zorderedCalcdata = gd.calcdata.slice(); + zorderedCalcdata.sort(function(a, b) { + var aZorder = a[0].trace.zorder || 0; + var bZorder = b[0].trace.zorder || 0; + return aZorder - bZorder; + }); + for (curvenum = 0; curvenum < zorderedCalcdata.length; curvenum++) { + cd = zorderedCalcdata[curvenum]; + trace = cd[0].trace; + if (trace.hoverinfo !== "skip" && helpers$D.isTraceInSubplots(trace, subplots)) { + searchData.push(cd); + if (trace.orientation === "h") { + hasOneHorizontalTrace = true; + } + } + } + var hasUserCalledHover = !eventTarget; + var xpx, ypx; + if (hasUserCalledHover) { + if ("xpx" in evt) xpx = evt.xpx; + else xpx = xaArray[0]._length / 2; + if ("ypx" in evt) ypx = evt.ypx; + else ypx = yaArray[0]._length / 2; + } else { + if (Events$1.triggerHandler(gd, "plotly_beforehover", evt) === false) { + return; + } + var dbb = eventTarget.getBoundingClientRect(); + xpx = evt.clientX - dbb.left; + ypx = evt.clientY - dbb.top; + fullLayout._calcInverseTransform(gd); + var transformedCoords = Lib$1y.apply3DTransform(fullLayout._invTransform)(xpx, ypx); + xpx = transformedCoords[0]; + ypx = transformedCoords[1]; + if (xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) { + return dragElement$5.unhoverRaw(gd, evt); + } + } + evt.pointerX = xpx + xaArray[0]._offset; + evt.pointerY = ypx + yaArray[0]._offset; + if ("xval" in evt) xvalArray = helpers$D.flat(subplots, evt.xval); + else xvalArray = helpers$D.p2c(xaArray, xpx); + if ("yval" in evt) yvalArray = helpers$D.flat(subplots, evt.yval); + else yvalArray = helpers$D.p2c(yaArray, ypx); + if (!isNumeric$i(xvalArray[0]) || !isNumeric$i(yvalArray[0])) { + Lib$1y.warn("Fx.hover failed", evt, gd); + return dragElement$5.unhoverRaw(gd, evt); + } + } + var distance = Infinity; + function findHoverPoints(customXVal, customYVal) { + for (curvenum = 0; curvenum < searchData.length; curvenum++) { + cd = searchData[curvenum]; + if (!cd || !cd[0] || !cd[0].trace) continue; + trace = cd[0].trace; + if (trace.visible !== true || trace._length === 0) continue; + if (["carpet", "contourcarpet"].indexOf(trace._module.name) !== -1) continue; + _mode = hovermode; + if (helpers$D.isUnifiedHover(_mode)) { + _mode = _mode.charAt(0); + } + if (trace.type === "splom") { + subploti = 0; + subplotId = subplots[subploti]; + } else { + subplotId = helpers$D.getSubplot(trace); + subploti = subplots.indexOf(subplotId); + } + pointData = { + // trace properties + cd, + trace, + xa: xaArray[subploti], + ya: yaArray[subploti], + // max distances for hover and spikes - for points that want to show but do not + // want to override other points, set distance/spikeDistance equal to max*Distance + // and it will not get filtered out but it will be guaranteed to have a greater + // distance than any point that calculated a real distance. + maxHoverDistance: hoverdistance, + maxSpikeDistance: spikedistance, + // point properties - override all of these + index: false, + // point index in trace - only used by plotly.js hoverdata consumers + distance: Math.min(distance, hoverdistance), + // pixel distance or pseudo-distance + // distance/pseudo-distance for spikes. This distance should always be calculated + // as if in "closest" mode, and should only be set if this point should + // generate a spike. + spikeDistance: Infinity, + // in some cases the spikes have different positioning from the hover label + // they don't need x0/x1, just one position + xSpike: void 0, + ySpike: void 0, + // where and how to display the hover label + color: Color$C.defaultLine, + // trace color + name: trace.name, + x0: void 0, + x1: void 0, + y0: void 0, + y1: void 0, + xLabelVal: void 0, + yLabelVal: void 0, + zLabelVal: void 0, + text: void 0 + }; + if (fullLayout[subplotId]) { + pointData.subplot = fullLayout[subplotId]._subplot; + } + if (fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) { + pointData.scene = fullLayout._splomScenes[trace.uid]; + } + if (_mode === "array") { + var selection = evt[curvenum]; + if ("pointNumber" in selection) { + pointData.index = selection.pointNumber; + _mode = "closest"; + } else { + _mode = ""; + if ("xval" in selection) { + xval = selection.xval; + _mode = "x"; + } + if ("yval" in selection) { + yval = selection.yval; + _mode = _mode ? "closest" : "y"; + } + } + } else if (customXVal !== void 0 && customYVal !== void 0) { + xval = customXVal; + yval = customYVal; + } else { + xval = xvalArray[subploti]; + yval = yvalArray[subploti]; + } + closedataPreviousLength = hoverData.length; + if (hoverdistance !== 0) { + if (trace._module && trace._module.hoverPoints) { + var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, { + finiteRange: true, + hoverLayer: fullLayout._hoverlayer, + // options for splom when hovering on same axis + hoversubplots, + gd + }); + if (newPoints) { + var newPoint; + for (var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { + newPoint = newPoints[newPointNum]; + if (isNumeric$i(newPoint.x0) && isNumeric$i(newPoint.y0)) { + hoverData.push(cleanPoint(newPoint, hovermode)); + } + } + } + } else { + Lib$1y.log("Unrecognized trace type in hover:", trace); + } + } + if (hovermode === "closest" && hoverData.length > closedataPreviousLength) { + hoverData.splice(0, closedataPreviousLength); + distance = hoverData[0].distance; + } + if (hasCartesian && spikedistance !== 0) { + if (hoverData.length === 0) { + pointData.distance = spikedistance; + pointData.index = false; + var closestPoints = trace._module.hoverPoints(pointData, xval, yval, "closest", { + hoverLayer: fullLayout._hoverlayer + }); + if (closestPoints) { + closestPoints = closestPoints.filter(function(point) { + return point.spikeDistance <= spikedistance; + }); + } + if (closestPoints && closestPoints.length) { + var tmpPoint; + var closestVPoints = closestPoints.filter(function(point) { + return point.xa.showspikes && point.xa.spikesnap !== "hovered data"; + }); + if (closestVPoints.length) { + var closestVPt = closestVPoints[0]; + if (isNumeric$i(closestVPt.x0) && isNumeric$i(closestVPt.y0)) { + tmpPoint = fillSpikePoint(closestVPt); + if (!spikePoints.vLinePoint || spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance) { + spikePoints.vLinePoint = tmpPoint; + } + } + } + var closestHPoints = closestPoints.filter(function(point) { + return point.ya.showspikes && point.ya.spikesnap !== "hovered data"; + }); + if (closestHPoints.length) { + var closestHPt = closestHPoints[0]; + if (isNumeric$i(closestHPt.x0) && isNumeric$i(closestHPt.y0)) { + tmpPoint = fillSpikePoint(closestHPt); + if (!spikePoints.hLinePoint || spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance) { + spikePoints.hLinePoint = tmpPoint; + } + } + } + } + } + } + } + } + findHoverPoints(); + function selectClosestPoint(pointsData, spikedistance2, spikeOnWinning2) { + var resultPoint = null; + var minDistance = Infinity; + var thisSpikeDistance; + for (var i2 = 0; i2 < pointsData.length; i2++) { + if (firstXaxis && firstXaxis._id !== pointsData[i2].xa._id) continue; + if (firstYaxis && firstYaxis._id !== pointsData[i2].ya._id) continue; + thisSpikeDistance = pointsData[i2].spikeDistance; + if (spikeOnWinning2 && i2 === 0) thisSpikeDistance = -Infinity; + if (thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance2) { + resultPoint = pointsData[i2]; + minDistance = thisSpikeDistance; + } + } + return resultPoint; + } + function fillSpikePoint(point) { + if (!point) return null; + return { + xa: point.xa, + ya: point.ya, + x: point.xSpike !== void 0 ? point.xSpike : (point.x0 + point.x1) / 2, + y: point.ySpike !== void 0 ? point.ySpike : (point.y0 + point.y1) / 2, + distance: point.distance, + spikeDistance: point.spikeDistance, + curveNumber: point.trace.index, + color: point.color, + pointNumber: point.index + }; + } + var spikelineOpts = { + fullLayout, + container: fullLayout._hoverlayer, + event: evt + }; + gd._spikepoints; + var newspikepoints = { + vLinePoint: spikePoints.vLinePoint, + hLinePoint: spikePoints.hLinePoint + }; + gd._spikepoints = newspikepoints; + var sortHoverData = function() { + var hoverDataInSubplot = hoverData.filter(function(a) { + return firstXaxis && firstXaxis._id === a.xa._id && (firstYaxis && firstYaxis._id === a.ya._id); + }); + var hoverDataOutSubplot = hoverData.filter(function(a) { + return !(firstXaxis && firstXaxis._id === a.xa._id && (firstYaxis && firstYaxis._id === a.ya._id)); + }); + hoverDataInSubplot.sort(distanceSort); + hoverDataOutSubplot.sort(distanceSort); + hoverData = hoverDataInSubplot.concat(hoverDataOutSubplot); + hoverData = orderRangePoints(hoverData, hovermode); + }; + sortHoverData(); + var axLetter = hovermode.charAt(0); + var spikeOnWinning = (axLetter === "x" || axLetter === "y") && hoverData[0] && cartesianScatterPoints[hoverData[0].trace.type]; + if (hasCartesian && spikedistance !== 0) { + if (hoverData.length !== 0) { + var tmpHPointData = hoverData.filter(function(point) { + return point.ya.showspikes; + }); + var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance, spikeOnWinning); + spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); + var tmpVPointData = hoverData.filter(function(point) { + return point.xa.showspikes; + }); + var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance, spikeOnWinning); + spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); + } + } + if (hoverData.length === 0) { + var result = dragElement$5.unhoverRaw(gd, evt); + if (hasCartesian && (spikePoints.hLinePoint !== null || spikePoints.vLinePoint !== null)) { + if (spikesChanged()) { + createSpikelines(gd, spikePoints, spikelineOpts); + } + } + return result; + } + if (hasCartesian) { + if (spikesChanged()) { + createSpikelines(gd, spikePoints, spikelineOpts); + } + } + if (helpers$D.isXYhover(_mode) && hoverData[0].length !== 0 && hoverData[0].trace.type !== "splom") { + var winningPoint = hoverData[0]; + if (multipleHoverPoints[winningPoint.trace.type]) { + hoverData = hoverData.filter(function(d) { + return d.trace.index === winningPoint.trace.index; + }); + } else { + hoverData = [winningPoint]; + } + var initLen = hoverData.length; + var winX = getCoord("x", winningPoint, fullLayout); + var winY = getCoord("y", winningPoint, fullLayout); + findHoverPoints(winX, winY); + var finalPoints = []; + var seen = {}; + var id = 0; + var insert = function(newHd) { + var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index; + if (!seen[key]) { + id++; + seen[key] = id; + finalPoints.push(newHd); + } else { + var oldId = seen[key] - 1; + var oldHd = finalPoints[oldId]; + if (oldId > 0 && Math.abs(newHd.distance) < Math.abs(oldHd.distance)) { + finalPoints[oldId] = newHd; + } + } + }; + var k; + for (k = 0; k < initLen; k++) { + insert(hoverData[k]); + } + for (k = hoverData.length - 1; k > initLen - 1; k--) { + insert(hoverData[k]); + } + hoverData = finalPoints; + sortHoverData(); + } + var oldhoverdata = gd._hoverdata; + var newhoverdata = []; + var gTop = getTopOffset(gd); + var gLeft = getLeftOffset(gd); + for (itemnum = 0; itemnum < hoverData.length; itemnum++) { + var pt = hoverData[itemnum]; + var eventData5 = helpers$D.makeEventData(pt, pt.trace, pt.cd); + if (pt.hovertemplate !== false) { + var ht = false; + if (pt.cd[pt.index] && pt.cd[pt.index].ht) { + ht = pt.cd[pt.index].ht; + } + pt.hovertemplate = ht || pt.trace.hovertemplate || false; + } + if (pt.xa && pt.ya) { + var _x0 = pt.x0 + pt.xa._offset; + var _x1 = pt.x1 + pt.xa._offset; + var _y0 = pt.y0 + pt.ya._offset; + var _y1 = pt.y1 + pt.ya._offset; + var x0 = Math.min(_x0, _x1); + var x1 = Math.max(_x0, _x1); + var y0 = Math.min(_y0, _y1); + var y1 = Math.max(_y0, _y1); + eventData5.bbox = { + x0: x0 + gLeft, + x1: x1 + gLeft, + y0: y0 + gTop, + y1: y1 + gTop + }; + } + pt.eventData = [eventData5]; + newhoverdata.push(eventData5); + } + gd._hoverdata = newhoverdata; + var rotateLabels = hovermode === "y" && (searchData.length > 1 || hoverData.length > 1) || hovermode === "closest" && hasOneHorizontalTrace && hoverData.length > 1; + var bgColor = Color$C.combine( + fullLayout.plot_bgcolor || Color$C.background, + fullLayout.paper_bgcolor + ); + var hoverText = createHoverText(hoverData, { + gd, + hovermode, + rotateLabels, + bgColor, + container: fullLayout._hoverlayer, + outerContainer: fullLayout._paper.node(), + commonLabelOpts: fullLayout.hoverlabel, + hoverdistance: fullLayout.hoverdistance + }); + var hoverLabels = hoverText.hoverLabels; + if (!helpers$D.isUnifiedHover(hovermode)) { + hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, hoverText.commonLabelBoundingBox); + alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY); + } + if (eventTarget && eventTarget.tagName) { + var hasClickToShow2 = Registry$C.getComponentMethod("annotations", "hasClickToShow")(gd, newhoverdata); + overrideCursor2(d3$s.select(eventTarget), hasClickToShow2 ? "pointer" : ""); + } + if (!eventTarget || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; + if (oldhoverdata) { + gd.emit("plotly_unhover", { + event: evt, + points: oldhoverdata + }); + } + gd.emit("plotly_hover", { + event: evt, + points: gd._hoverdata, + xaxes: xaArray, + yaxes: yaArray, + xvals: xvalArray, + yvals: yvalArray + }); +} +function hoverDataKey(d) { + return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa ? d.xa._id : "", d.ya ? d.ya._id : ""].join(","); +} +var EXTRA_STRING_REGEX = /([\s\S]*)<\/extra>/; +function createHoverText(hoverData, opts) { + var gd = opts.gd; + var fullLayout = gd._fullLayout; + var hovermode = opts.hovermode; + var rotateLabels = opts.rotateLabels; + var bgColor = opts.bgColor; + var container = opts.container; + var outerContainer = opts.outerContainer; + var commonLabelOpts = opts.commonLabelOpts || {}; + if (hoverData.length === 0) return [[]]; + var fontFamily = opts.fontFamily || constants$L.HOVERFONT; + var fontSize = opts.fontSize || constants$L.HOVERFONTSIZE; + var fontWeight = opts.fontWeight || fullLayout.font.weight; + var fontStyle = opts.fontStyle || fullLayout.font.style; + var fontVariant = opts.fontVariant || fullLayout.font.variant; + var fontTextcase = opts.fontTextcase || fullLayout.font.textcase; + var fontLineposition = opts.fontLineposition || fullLayout.font.lineposition; + var fontShadow = opts.fontShadow || fullLayout.font.shadow; + var c0 = hoverData[0]; + var xa = c0.xa; + var ya = c0.ya; + var axLetter = hovermode.charAt(0); + var axLabel = axLetter + "Label"; + var t02 = c0[axLabel]; + if (t02 === void 0 && xa.type === "multicategory") { + for (var q = 0; q < hoverData.length; q++) { + t02 = hoverData[q][axLabel]; + if (t02 !== void 0) break; + } + } + var outerContainerBB = getBoundingClientRect(gd, outerContainer); + var outerTop = outerContainerBB.top; + var outerWidth = outerContainerBB.width; + var outerHeight = outerContainerBB.height; + var showCommonLabel = t02 !== void 0 && c0.distance <= opts.hoverdistance && (hovermode === "x" || hovermode === "y"); + if (showCommonLabel) { + var allHaveZ = true; + var i, traceHoverinfo; + for (i = 0; i < hoverData.length; i++) { + if (allHaveZ && hoverData[i].zLabel === void 0) allHaveZ = false; + traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; + if (traceHoverinfo) { + var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split("+"); + if (parts.indexOf("all") === -1 && parts.indexOf(hovermode) === -1) { + showCommonLabel = false; + break; + } + } + } + if (allHaveZ) showCommonLabel = false; + } + var commonLabel = container.selectAll("g.axistext").data(showCommonLabel ? [0] : []); + commonLabel.enter().append("g").classed("axistext", true); + commonLabel.exit().remove(); + var commonLabelRect = { + minX: 0, + maxX: 0, + minY: 0, + maxY: 0 + }; + commonLabel.each(function() { + var label = d3$s.select(this); + var lpath = Lib$1y.ensureSingle(label, "path", "", function(s) { + s.style({ "stroke-width": "1px" }); + }); + var ltext = Lib$1y.ensureSingle(label, "text", "", function(s) { + s.attr("data-notex", 1); + }); + var commonBgColor = commonLabelOpts.bgcolor || Color$C.defaultLine; + var commonStroke = commonLabelOpts.bordercolor || Color$C.contrast(commonBgColor); + var contrastColor = Color$C.contrast(commonBgColor); + var commonLabelOptsFont = commonLabelOpts.font; + var commonLabelFont = { + weight: commonLabelOptsFont.weight || fontWeight, + style: commonLabelOptsFont.style || fontStyle, + variant: commonLabelOptsFont.variant || fontVariant, + textcase: commonLabelOptsFont.textcase || fontTextcase, + lineposition: commonLabelOptsFont.lineposition || fontLineposition, + shadow: commonLabelOptsFont.shadow || fontShadow, + family: commonLabelOptsFont.family || fontFamily, + size: commonLabelOptsFont.size || fontSize, + color: commonLabelOptsFont.color || contrastColor + }; + lpath.style({ + fill: commonBgColor, + stroke: commonStroke + }); + ltext.text(t02).call(Drawing$o.font, commonLabelFont).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); + label.attr("transform", ""); + var tbb2 = getBoundingClientRect(gd, ltext.node()); + var lx2, ly2; + if (hovermode === "x") { + var topsign = xa.side === "top" ? "-" : ""; + ltext.attr("text-anchor", "middle").call(svgTextUtils$b.positionText, 0, xa.side === "top" ? outerTop - tbb2.bottom - HOVERARROWSIZE - HOVERTEXTPAD : outerTop - tbb2.top + HOVERARROWSIZE + HOVERTEXTPAD); + lx2 = xa._offset + (c0.x0 + c0.x1) / 2; + ly2 = ya._offset + (xa.side === "top" ? 0 : ya._length); + var halfWidth = tbb2.width / 2 + HOVERTEXTPAD; + var tooltipMidX = lx2; + if (lx2 < halfWidth) { + tooltipMidX = halfWidth; + } else if (lx2 > fullLayout.width - halfWidth) { + tooltipMidX = fullLayout.width - halfWidth; + } + lpath.attr("d", "M" + (lx2 - tooltipMidX) + ",0L" + (lx2 - tooltipMidX + HOVERARROWSIZE) + "," + topsign + HOVERARROWSIZE + "H" + halfWidth + "v" + topsign + (HOVERTEXTPAD * 2 + tbb2.height) + "H" + -halfWidth + "V" + topsign + HOVERARROWSIZE + "H" + (lx2 - tooltipMidX - HOVERARROWSIZE) + "Z"); + lx2 = tooltipMidX; + commonLabelRect.minX = lx2 - halfWidth; + commonLabelRect.maxX = lx2 + halfWidth; + if (xa.side === "top") { + commonLabelRect.minY = ly2 - (HOVERTEXTPAD * 2 + tbb2.height); + commonLabelRect.maxY = ly2 - HOVERTEXTPAD; + } else { + commonLabelRect.minY = ly2 + HOVERTEXTPAD; + commonLabelRect.maxY = ly2 + (HOVERTEXTPAD * 2 + tbb2.height); + } + } else { + var anchor; + var sgn; + var leftsign; + if (ya.side === "right") { + anchor = "start"; + sgn = 1; + leftsign = ""; + lx2 = xa._offset + xa._length; + } else { + anchor = "end"; + sgn = -1; + leftsign = "-"; + lx2 = xa._offset; + } + ly2 = ya._offset + (c0.y0 + c0.y1) / 2; + ltext.attr("text-anchor", anchor); + lpath.attr("d", "M0,0L" + leftsign + HOVERARROWSIZE + "," + HOVERARROWSIZE + "V" + (HOVERTEXTPAD + tbb2.height / 2) + "h" + leftsign + (HOVERTEXTPAD * 2 + tbb2.width) + "V-" + (HOVERTEXTPAD + tbb2.height / 2) + "H" + leftsign + HOVERARROWSIZE + "V-" + HOVERARROWSIZE + "Z"); + commonLabelRect.minY = ly2 - (HOVERTEXTPAD + tbb2.height / 2); + commonLabelRect.maxY = ly2 + (HOVERTEXTPAD + tbb2.height / 2); + if (ya.side === "right") { + commonLabelRect.minX = lx2 + HOVERARROWSIZE; + commonLabelRect.maxX = lx2 + HOVERARROWSIZE + (HOVERTEXTPAD * 2 + tbb2.width); + } else { + commonLabelRect.minX = lx2 - HOVERARROWSIZE - (HOVERTEXTPAD * 2 + tbb2.width); + commonLabelRect.maxX = lx2 - HOVERARROWSIZE; + } + var halfHeight = tbb2.height / 2; + var lty = outerTop - tbb2.top - halfHeight; + var clipId = "clip" + fullLayout._uid + "commonlabel" + ya._id; + var clipPath; + if (lx2 < tbb2.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE) { + clipPath = "M-" + (HOVERARROWSIZE + HOVERTEXTPAD) + "-" + halfHeight + "h-" + (tbb2.width - HOVERTEXTPAD) + "V" + halfHeight + "h" + (tbb2.width - HOVERTEXTPAD) + "Z"; + var ltx = tbb2.width - lx2 + HOVERTEXTPAD; + svgTextUtils$b.positionText(ltext, ltx, lty); + if (anchor === "end") { + ltext.selectAll("tspan").each(function() { + var s = d3$s.select(this); + var dummy = Drawing$o.tester.append("text").text(s.text()).call(Drawing$o.font, commonLabelFont); + var dummyBB = getBoundingClientRect(gd, dummy.node()); + if (Math.round(dummyBB.width) < Math.round(tbb2.width)) { + s.attr("x", ltx - dummyBB.width); + } + dummy.remove(); + }); + } + } else { + svgTextUtils$b.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty); + clipPath = null; + } + var textClip = fullLayout._topclips.selectAll("#" + clipId).data(clipPath ? [0] : []); + textClip.enter().append("clipPath").attr("id", clipId).append("path"); + textClip.exit().remove(); + textClip.select("path").attr("d", clipPath); + Drawing$o.setClipUrl(ltext, clipPath ? clipId : null, gd); + } + label.attr("transform", strTranslate$8(lx2, ly2)); + }); + if (helpers$D.isUnifiedHover(hovermode)) { + container.selectAll("g.hovertext").remove(); + var groupedHoverData = hoverData.filter(function(data) { + return data.hoverinfo !== "none"; + }); + if (groupedHoverData.length === 0) return []; + var hoverlabel = fullLayout.hoverlabel; + var font2 = hoverlabel.font; + var mockLayoutIn = { + showlegend: true, + legend: { + title: { text: t02, font: font2 }, + font: font2, + bgcolor: hoverlabel.bgcolor, + bordercolor: hoverlabel.bordercolor, + borderwidth: 1, + tracegroupgap: 7, + traceorder: fullLayout.legend ? fullLayout.legend.traceorder : void 0, + orientation: "v" + } + }; + var mockLayoutOut = { + font: font2 + }; + legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData); + var mockLegend = mockLayoutOut.legend; + mockLegend.entries = []; + for (var j = 0; j < groupedHoverData.length; j++) { + var pt = groupedHoverData[j]; + if (pt.hoverinfo === "none") continue; + var texts = getHoverLabelText(pt, true, hovermode, fullLayout, t02); + var text = texts[0]; + var name2 = texts[1]; + pt.name = name2; + if (name2 !== "") { + pt.text = name2 + " : " + text; + } else { + pt.text = text; + } + var cd = pt.cd[pt.index]; + if (cd) { + if (cd.mc) pt.mc = cd.mc; + if (cd.mcc) pt.mc = cd.mcc; + if (cd.mlc) pt.mlc = cd.mlc; + if (cd.mlcc) pt.mlc = cd.mlcc; + if (cd.mlw) pt.mlw = cd.mlw; + if (cd.mrc) pt.mrc = cd.mrc; + if (cd.dir) pt.dir = cd.dir; + } + pt._distinct = true; + mockLegend.entries.push([pt]); + } + mockLegend.entries.sort(function(a, b) { + return a[0].trace.index - b[0].trace.index; + }); + mockLegend.layer = container; + mockLegend._inHover = true; + mockLegend._groupTitleFont = hoverlabel.grouptitlefont; + legendDraw(gd, mockLegend); + var legendContainer = container.select("g.legend"); + var tbb = getBoundingClientRect(gd, legendContainer.node()); + var tWidth = tbb.width + 2 * HOVERTEXTPAD; + var tHeight = tbb.height + 2 * HOVERTEXTPAD; + var winningPoint = groupedHoverData[0]; + var avgX = (winningPoint.x0 + winningPoint.x1) / 2; + var avgY = (winningPoint.y0 + winningPoint.y1) / 2; + var pointWon = !(Registry$C.traceIs(winningPoint.trace, "bar-like") || Registry$C.traceIs(winningPoint.trace, "box-violin")); + var lyBottom, lyTop; + if (axLetter === "y") { + if (pointWon) { + lyTop = avgY - HOVERTEXTPAD; + lyBottom = avgY + HOVERTEXTPAD; + } else { + lyTop = Math.min.apply(null, groupedHoverData.map(function(c) { + return Math.min(c.y0, c.y1); + })); + lyBottom = Math.max.apply(null, groupedHoverData.map(function(c) { + return Math.max(c.y0, c.y1); + })); + } + } else { + lyTop = lyBottom = Lib$1y.mean(groupedHoverData.map(function(c) { + return (c.y0 + c.y1) / 2; + })) - tHeight / 2; + } + var lxRight, lxLeft; + if (axLetter === "x") { + if (pointWon) { + lxRight = avgX + HOVERTEXTPAD; + lxLeft = avgX - HOVERTEXTPAD; + } else { + lxRight = Math.max.apply(null, groupedHoverData.map(function(c) { + return Math.max(c.x0, c.x1); + })); + lxLeft = Math.min.apply(null, groupedHoverData.map(function(c) { + return Math.min(c.x0, c.x1); + })); + } + } else { + lxRight = lxLeft = Lib$1y.mean(groupedHoverData.map(function(c) { + return (c.x0 + c.x1) / 2; + })) - tWidth / 2; + } + var xOffset = xa._offset; + var yOffset = ya._offset; + lyBottom += yOffset; + lxRight += xOffset; + lxLeft += xOffset - tWidth; + lyTop += yOffset - tHeight; + var lx, ly; + if (lxRight + tWidth < outerWidth && lxRight >= 0) { + lx = lxRight; + } else if (lxLeft + tWidth < outerWidth && lxLeft >= 0) { + lx = lxLeft; + } else if (xOffset + tWidth < outerWidth) { + lx = xOffset; + } else { + if (lxRight - avgX < avgX - lxLeft + tWidth) { + lx = outerWidth - tWidth; + } else { + lx = 0; + } + } + lx += HOVERTEXTPAD; + if (lyBottom + tHeight < outerHeight && lyBottom >= 0) { + ly = lyBottom; + } else if (lyTop + tHeight < outerHeight && lyTop >= 0) { + ly = lyTop; + } else if (yOffset + tHeight < outerHeight) { + ly = yOffset; + } else { + if (lyBottom - avgY < avgY - lyTop + tHeight) { + ly = outerHeight - tHeight; + } else { + ly = 0; + } + } + ly += HOVERTEXTPAD; + legendContainer.attr("transform", strTranslate$8(lx - 1, ly - 1)); + return legendContainer; + } + var hoverLabels = container.selectAll("g.hovertext").data(hoverData, function(d) { + return hoverDataKey(d); + }); + hoverLabels.enter().append("g").classed("hovertext", true).each(function() { + var g = d3$s.select(this); + g.append("rect").call(Color$C.fill, Color$C.addOpacity(bgColor, 0.8)); + g.append("text").classed("name", true); + g.append("path").style("stroke-width", "1px"); + g.append("text").classed("nums", true).call(Drawing$o.font, { + weight: fontWeight, + style: fontStyle, + variant: fontVariant, + textcase: fontTextcase, + lineposition: fontLineposition, + shadow: fontShadow, + family: fontFamily, + size: fontSize + }); + }); + hoverLabels.exit().remove(); + hoverLabels.each(function(d) { + var g = d3$s.select(this).attr("transform", ""); + var dColor = d.color; + if (Array.isArray(dColor)) { + dColor = dColor[d.eventData[0].pointNumber]; + } + var color0 = d.bgcolor || dColor; + var numsColor = Color$C.combine( + Color$C.opacity(color0) ? color0 : Color$C.defaultLine, + bgColor + ); + var nameColor = Color$C.combine( + Color$C.opacity(dColor) ? dColor : Color$C.defaultLine, + bgColor + ); + var contrastColor = d.borderColor || Color$C.contrast(numsColor); + var texts2 = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g); + var text2 = texts2[0]; + var name3 = texts2[1]; + var tx = g.select("text.nums").call(Drawing$o.font, { + family: d.fontFamily || fontFamily, + size: d.fontSize || fontSize, + color: d.fontColor || contrastColor, + weight: d.fontWeight || fontWeight, + style: d.fontStyle || fontStyle, + variant: d.fontVariant || fontVariant, + textcase: d.fontTextcase || fontTextcase, + lineposition: d.fontLineposition || fontLineposition, + shadow: d.fontShadow || fontShadow + }).text(text2).attr("data-notex", 1).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); + var tx2 = g.select("text.name"); + var tx2width = 0; + var tx2height = 0; + if (name3 && name3 !== text2) { + tx2.call(Drawing$o.font, { + family: d.fontFamily || fontFamily, + size: d.fontSize || fontSize, + color: nameColor, + weight: d.fontWeight || fontWeight, + style: d.fontStyle || fontStyle, + variant: d.fontVariant || fontVariant, + textcase: d.fontTextcase || fontTextcase, + lineposition: d.fontLineposition || fontLineposition, + shadow: d.fontShadow || fontShadow + }).text(name3).attr("data-notex", 1).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); + var t2bb = getBoundingClientRect(gd, tx2.node()); + tx2width = t2bb.width + 2 * HOVERTEXTPAD; + tx2height = t2bb.height + 2 * HOVERTEXTPAD; + } else { + tx2.remove(); + g.select("rect").remove(); + } + g.select("path").style({ + fill: numsColor, + stroke: contrastColor + }); + var htx = d.xa._offset + (d.x0 + d.x1) / 2; + var hty = d.ya._offset + (d.y0 + d.y1) / 2; + var dx = Math.abs(d.x1 - d.x0); + var dy = Math.abs(d.y1 - d.y0); + var tbb2 = getBoundingClientRect(gd, tx.node()); + var tbbWidth = tbb2.width / fullLayout._invScaleX; + var tbbHeight = tbb2.height / fullLayout._invScaleY; + d.ty0 = (outerTop - tbb2.top) / fullLayout._invScaleY; + d.bx = tbbWidth + 2 * HOVERTEXTPAD; + d.by = Math.max(tbbHeight + 2 * HOVERTEXTPAD, tx2height); + d.anchor = "start"; + d.txwidth = tbbWidth; + d.tx2width = tx2width; + d.offset = 0; + var txTotalWidth = (tbbWidth + HOVERARROWSIZE + HOVERTEXTPAD + tx2width) * fullLayout._invScaleX; + var anchorStartOK, anchorEndOK; + if (rotateLabels) { + d.pos = htx; + anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; + anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; + if ((d.idealAlign === "top" || !anchorStartOK) && anchorEndOK) { + hty -= dy / 2; + d.anchor = "end"; + } else if (anchorStartOK) { + hty += dy / 2; + d.anchor = "start"; + } else { + d.anchor = "middle"; + } + d.crossPos = hty; + } else { + d.pos = hty; + anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; + anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; + if ((d.idealAlign === "left" || !anchorStartOK) && anchorEndOK) { + htx -= dx / 2; + d.anchor = "end"; + } else if (anchorStartOK) { + htx += dx / 2; + d.anchor = "start"; + } else { + d.anchor = "middle"; + var txHalfWidth = txTotalWidth / 2; + var overflowR = htx + txHalfWidth - outerWidth; + var overflowL = htx - txHalfWidth; + if (overflowR > 0) htx -= overflowR; + if (overflowL < 0) htx += -overflowL; + } + d.crossPos = htx; + } + tx.attr("text-anchor", d.anchor); + if (tx2width) tx2.attr("text-anchor", d.anchor); + g.attr("transform", strTranslate$8(htx, hty) + (rotateLabels ? strRotate$1(YANGLE) : "")); + }); + return { + hoverLabels, + commonLabelBoundingBox: commonLabelRect + }; +} +function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g) { + var name2 = ""; + var text = ""; + if (d.nameOverride !== void 0) d.name = d.nameOverride; + if (d.name) { + if (d.trace._meta) { + d.name = Lib$1y.templateString(d.name, d.trace._meta); + } + name2 = plainText(d.name, d.nameLength); + } + var h0 = hovermode.charAt(0); + var h1 = h0 === "x" ? "y" : "x"; + if (d.zLabel !== void 0) { + if (d.xLabel !== void 0) text += "x: " + d.xLabel + "
"; + if (d.yLabel !== void 0) text += "y: " + d.yLabel + "
"; + if (d.trace.type !== "choropleth" && d.trace.type !== "choroplethmapbox" && d.trace.type !== "choroplethmap") { + text += (text ? "z: " : "") + d.zLabel; + } + } else if (showCommonLabel && d[h0 + "Label"] === t02) { + text = d[h1 + "Label"] || ""; + } else if (d.xLabel === void 0) { + if (d.yLabel !== void 0 && d.trace.type !== "scattercarpet") { + text = d.yLabel; + } + } else if (d.yLabel === void 0) text = d.xLabel; + else text = "(" + d.xLabel + ", " + d.yLabel + ")"; + if ((d.text || d.text === 0) && !Array.isArray(d.text)) { + text += (text ? "
" : "") + d.text; + } + if (d.extraText !== void 0) text += (text ? "
" : "") + d.extraText; + if (g && text === "" && !d.hovertemplate) { + if (name2 === "") g.remove(); + text = name2; + } + var hovertemplate = d.hovertemplate || false; + if (hovertemplate) { + var labels = d.hovertemplateLabels || d; + if (d[h0 + "Label"] !== t02) { + labels[h0 + "other"] = labels[h0 + "Val"]; + labels[h0 + "otherLabel"] = labels[h0 + "Label"]; + } + text = Lib$1y.hovertemplateString( + hovertemplate, + labels, + fullLayout._d3locale, + d.eventData[0] || {}, + d.trace._meta + ); + text = text.replace(EXTRA_STRING_REGEX, function(match, extra) { + name2 = plainText(extra, d.nameLength); + return ""; + }); + } + return [text, name2]; +} +function hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, commonLabelBoundingBox) { + var axKey = rotateLabels ? "xa" : "ya"; + var crossAxKey = rotateLabels ? "ya" : "xa"; + var nummoves = 0; + var axSign = 1; + var nLabels = hoverLabels.size(); + var pointgroups = new Array(nLabels); + var k = 0; + var axisLabelMinX = commonLabelBoundingBox.minX; + var axisLabelMaxX = commonLabelBoundingBox.maxX; + var axisLabelMinY = commonLabelBoundingBox.minY; + var axisLabelMaxY = commonLabelBoundingBox.maxY; + var pX = function(x) { + return x * fullLayout._invScaleX; + }; + var pY = function(y) { + return y * fullLayout._invScaleY; + }; + hoverLabels.each(function(d) { + var ax = d[axKey]; + var crossAx = d[crossAxKey]; + var axIsX = ax._id.charAt(0) === "x"; + var rng = ax.range; + if (k === 0 && rng && rng[0] > rng[1] !== axIsX) { + axSign = -1; + } + var pmin = 0; + var pmax = axIsX ? fullLayout.width : fullLayout.height; + if (fullLayout.hovermode === "x" || fullLayout.hovermode === "y") { + var offsets = getHoverLabelOffsets(d, rotateLabels); + var anchor = d.anchor; + var horzSign = anchor === "end" ? -1 : 1; + var labelMin; + var labelMax; + if (anchor === "middle") { + labelMin = d.crossPos + (axIsX ? pY(offsets.y - d.by / 2) : pX(d.bx / 2 + d.tx2width / 2)); + labelMax = labelMin + (axIsX ? pY(d.by) : pX(d.bx)); + } else { + if (axIsX) { + labelMin = d.crossPos + pY(HOVERARROWSIZE + offsets.y) - pY(d.by / 2 - HOVERARROWSIZE); + labelMax = labelMin + pY(d.by); + } else { + var startX = pX(horzSign * HOVERARROWSIZE + offsets.x); + var endX = startX + pX(horzSign * d.bx); + labelMin = d.crossPos + Math.min(startX, endX); + labelMax = d.crossPos + Math.max(startX, endX); + } + } + if (axIsX) { + if (axisLabelMinY !== void 0 && axisLabelMaxY !== void 0 && Math.min(labelMax, axisLabelMaxY) - Math.max(labelMin, axisLabelMinY) > 1) { + if (crossAx.side === "left") { + pmin = crossAx._mainLinePosition; + pmax = fullLayout.width; + } else { + pmax = crossAx._mainLinePosition; + } + } + } else { + if (axisLabelMinX !== void 0 && axisLabelMaxX !== void 0 && Math.min(labelMax, axisLabelMaxX) - Math.max(labelMin, axisLabelMinX) > 1) { + if (crossAx.side === "top") { + pmin = crossAx._mainLinePosition; + pmax = fullLayout.height; + } else { + pmax = crossAx._mainLinePosition; + } + } + } + } + pointgroups[k++] = [{ + datum: d, + traceIndex: d.trace.index, + dp: 0, + pos: d.pos, + posref: d.posref, + size: d.by * (axIsX ? YFACTOR : 1) / 2, + pmin, + pmax + }]; + }); + pointgroups.sort(function(a, b) { + return a[0].posref - b[0].posref || // for equal positions, sort trace indices increasing or decreasing + // depending on whether the axis is reversed or not... so stacked + // traces will generally keep their order even if one trace adds + // nothing to the stack. + axSign * (b[0].traceIndex - a[0].traceIndex); + }); + var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp; + function constrainGroup(grp2) { + var minPt = grp2[0]; + var maxPt = grp2[grp2.length - 1]; + topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; + bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; + if (topOverlap > 0.01) { + for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp += topOverlap; + donepositioning = false; + } + if (bottomOverlap < 0.01) return; + if (topOverlap < -0.01) { + for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap; + donepositioning = false; + } + if (!donepositioning) return; + var deleteCount = 0; + for (i = 0; i < grp2.length; i++) { + pti = grp2[i]; + if (pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; + } + for (i = grp2.length - 1; i >= 0; i--) { + if (deleteCount <= 0) break; + pti = grp2[i]; + if (pti.pos > minPt.pmax - 1) { + pti.del = true; + deleteCount--; + } + } + for (i = 0; i < grp2.length; i++) { + if (deleteCount <= 0) break; + pti = grp2[i]; + if (pti.pos < minPt.pmin + 1) { + pti.del = true; + deleteCount--; + bottomOverlap = pti.size * 2; + for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap; + } + } + for (i = grp2.length - 1; i >= 0; i--) { + if (deleteCount <= 0) break; + pti = grp2[i]; + if (pti.pos + pti.dp + pti.size > minPt.pmax) { + pti.del = true; + deleteCount--; + } + } + } + while (!donepositioning && nummoves <= nLabels) { + nummoves++; + donepositioning = true; + i = 0; + while (i < pointgroups.length - 1) { + var g0 = pointgroups[i]; + var g1 = pointgroups[i + 1]; + var p0 = g0[g0.length - 1]; + var p1 = g1[0]; + topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; + if (topOverlap > 0.01) { + for (j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; + g0.push.apply(g0, g1); + pointgroups.splice(i + 1, 1); + sumdp = 0; + for (j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; + bottomOverlap = sumdp / g0.length; + for (j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; + donepositioning = false; + } else i++; + } + pointgroups.forEach(constrainGroup); + } + for (i = pointgroups.length - 1; i >= 0; i--) { + var grp = pointgroups[i]; + for (j = grp.length - 1; j >= 0; j--) { + var pt = grp[j]; + var hoverPt = pt.datum; + hoverPt.offset = pt.dp; + hoverPt.del = pt.del; + } + } +} +function getHoverLabelOffsets(hoverLabel, rotateLabels) { + var offsetX = 0; + var offsetY = hoverLabel.offset; + if (rotateLabels) { + offsetY *= -YSHIFTY; + offsetX = hoverLabel.offset * YSHIFTX; + } + return { + x: offsetX, + y: offsetY + }; +} +function getTextShiftX(hoverLabel) { + var alignShift = { start: 1, end: -1, middle: 0 }[hoverLabel.anchor]; + var textShiftX = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD); + var text2ShiftX = textShiftX + alignShift * (hoverLabel.txwidth + HOVERTEXTPAD); + var isMiddle = hoverLabel.anchor === "middle"; + if (isMiddle) { + textShiftX -= hoverLabel.tx2width / 2; + text2ShiftX += hoverLabel.txwidth / 2 + HOVERTEXTPAD; + } + return { + alignShift, + textShiftX, + text2ShiftX + }; +} +function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) { + var pX = function(x) { + return x * scaleX; + }; + var pY = function(y) { + return y * scaleY; + }; + hoverLabels.each(function(d) { + var g = d3$s.select(this); + if (d.del) return g.remove(); + var tx = g.select("text.nums"); + var anchor = d.anchor; + var horzSign = anchor === "end" ? -1 : 1; + var shiftX = getTextShiftX(d); + var offsets = getHoverLabelOffsets(d, rotateLabels); + var offsetX = offsets.x; + var offsetY = offsets.y; + var isMiddle = anchor === "middle"; + g.select("path").attr("d", isMiddle ? ( + // middle aligned: rect centered on data + "M-" + pX(d.bx / 2 + d.tx2width / 2) + "," + pY(offsetY - d.by / 2) + "h" + pX(d.bx) + "v" + pY(d.by) + "h-" + pX(d.bx) + "Z" + ) : ( + // left or right aligned: side rect with arrow to data + "M0,0L" + pX(horzSign * HOVERARROWSIZE + offsetX) + "," + pY(HOVERARROWSIZE + offsetY) + "v" + pY(d.by / 2 - HOVERARROWSIZE) + "h" + pX(horzSign * d.bx) + "v-" + pY(d.by) + "H" + pX(horzSign * HOVERARROWSIZE + offsetX) + "V" + pY(offsetY - HOVERARROWSIZE) + "Z" + )); + var posX = offsetX + shiftX.textShiftX; + var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD; + var textAlign = d.textAlign || "auto"; + if (textAlign !== "auto") { + if (textAlign === "left" && anchor !== "start") { + tx.attr("text-anchor", "start"); + posX = isMiddle ? -d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD : -d.bx - HOVERTEXTPAD; + } else if (textAlign === "right" && anchor !== "end") { + tx.attr("text-anchor", "end"); + posX = isMiddle ? d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD : d.bx + HOVERTEXTPAD; + } + } + tx.call(svgTextUtils$b.positionText, pX(posX), pY(posY)); + if (d.tx2width) { + g.select("text.name").call( + svgTextUtils$b.positionText, + pX(shiftX.text2ShiftX + shiftX.alignShift * HOVERTEXTPAD + offsetX), + pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD) + ); + g.select("rect").call( + Drawing$o.setRect, + pX(shiftX.text2ShiftX + (shiftX.alignShift - 1) * d.tx2width / 2 + offsetX), + pY(offsetY - d.by / 2 - 1), + pX(d.tx2width), + pY(d.by + 2) + ); + } + }); +} +function cleanPoint(d, hovermode) { + var index2 = d.index; + var trace = d.trace || {}; + var cd0 = d.cd[0]; + var cd = d.cd[index2] || {}; + function pass(v) { + return v || isNumeric$i(v) && v === 0; + } + var getVal = Array.isArray(index2) ? function(calcKey, traceKey) { + var v = Lib$1y.castOption(cd0, index2, calcKey); + return pass(v) ? v : Lib$1y.extractOption({}, trace, "", traceKey); + } : function(calcKey, traceKey) { + return Lib$1y.extractOption(cd, trace, calcKey, traceKey); + }; + function fill(key, calcKey, traceKey) { + var val = getVal(calcKey, traceKey); + if (pass(val)) d[key] = val; + } + fill("hoverinfo", "hi", "hoverinfo"); + fill("bgcolor", "hbg", "hoverlabel.bgcolor"); + fill("borderColor", "hbc", "hoverlabel.bordercolor"); + fill("fontFamily", "htf", "hoverlabel.font.family"); + fill("fontSize", "hts", "hoverlabel.font.size"); + fill("fontColor", "htc", "hoverlabel.font.color"); + fill("fontWeight", "htw", "hoverlabel.font.weight"); + fill("fontStyle", "hty", "hoverlabel.font.style"); + fill("fontVariant", "htv", "hoverlabel.font.variant"); + fill("nameLength", "hnl", "hoverlabel.namelength"); + fill("textAlign", "hta", "hoverlabel.align"); + d.posref = hovermode === "y" || hovermode === "closest" && trace.orientation === "h" ? d.xa._offset + (d.x0 + d.x1) / 2 : d.ya._offset + (d.y0 + d.y1) / 2; + d.x0 = Lib$1y.constrain(d.x0, 0, d.xa._length); + d.x1 = Lib$1y.constrain(d.x1, 0, d.xa._length); + d.y0 = Lib$1y.constrain(d.y0, 0, d.ya._length); + d.y1 = Lib$1y.constrain(d.y1, 0, d.ya._length); + if (d.xLabelVal !== void 0) { + d.xLabel = "xLabel" in d ? d.xLabel : Axes$l.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat); + d.xVal = d.xa.c2d(d.xLabelVal); + } + if (d.yLabelVal !== void 0) { + d.yLabel = "yLabel" in d ? d.yLabel : Axes$l.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat); + d.yVal = d.ya.c2d(d.yLabelVal); + } + if (d.zLabelVal !== void 0 && d.zLabel === void 0) { + d.zLabel = String(d.zLabelVal); + } + if (!isNaN(d.xerr) && !(d.xa.type === "log" && d.xerr <= 0)) { + var xeText = Axes$l.tickText(d.xa, d.xa.c2l(d.xerr), "hover").text; + if (d.xerrneg !== void 0) { + d.xLabel += " +" + xeText + " / -" + Axes$l.tickText(d.xa, d.xa.c2l(d.xerrneg), "hover").text; + } else d.xLabel += " ± " + xeText; + if (hovermode === "x") d.distance += 1; + } + if (!isNaN(d.yerr) && !(d.ya.type === "log" && d.yerr <= 0)) { + var yeText = Axes$l.tickText(d.ya, d.ya.c2l(d.yerr), "hover").text; + if (d.yerrneg !== void 0) { + d.yLabel += " +" + yeText + " / -" + Axes$l.tickText(d.ya, d.ya.c2l(d.yerrneg), "hover").text; + } else d.yLabel += " ± " + yeText; + if (hovermode === "y") d.distance += 1; + } + var infomode = d.hoverinfo || d.trace.hoverinfo; + if (infomode && infomode !== "all") { + infomode = Array.isArray(infomode) ? infomode : infomode.split("+"); + if (infomode.indexOf("x") === -1) d.xLabel = void 0; + if (infomode.indexOf("y") === -1) d.yLabel = void 0; + if (infomode.indexOf("z") === -1) d.zLabel = void 0; + if (infomode.indexOf("text") === -1) d.text = void 0; + if (infomode.indexOf("name") === -1) d.name = void 0; + } + return d; +} +function createSpikelines(gd, closestPoints, opts) { + var container = opts.container; + var fullLayout = opts.fullLayout; + var gs = fullLayout._size; + var evt = opts.event; + var showY = !!closestPoints.hLinePoint; + var showX = !!closestPoints.vLinePoint; + var xa, ya; + container.selectAll(".spikeline").remove(); + if (!(showX || showY)) return; + var contrastColor = Color$C.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); + if (showY) { + var hLinePoint = closestPoints.hLinePoint; + var hLinePointX, hLinePointY; + xa = hLinePoint && hLinePoint.xa; + ya = hLinePoint && hLinePoint.ya; + var ySnap = ya.spikesnap; + if (ySnap === "cursor") { + hLinePointX = evt.pointerX; + hLinePointY = evt.pointerY; + } else { + hLinePointX = xa._offset + hLinePoint.x; + hLinePointY = ya._offset + hLinePoint.y; + } + var dfltHLineColor = tinycolor$3.readability(hLinePoint.color, contrastColor) < 1.5 ? Color$C.contrast(contrastColor) : hLinePoint.color; + var yMode = ya.spikemode; + var yThickness = ya.spikethickness; + var yColor = ya.spikecolor || dfltHLineColor; + var xEdge = Axes$l.getPxPosition(gd, ya); + var xBase, xEndSpike; + if (yMode.indexOf("toaxis") !== -1 || yMode.indexOf("across") !== -1) { + if (yMode.indexOf("toaxis") !== -1) { + xBase = xEdge; + xEndSpike = hLinePointX; + } + if (yMode.indexOf("across") !== -1) { + var xAcross0 = ya._counterDomainMin; + var xAcross1 = ya._counterDomainMax; + if (ya.anchor === "free") { + xAcross0 = Math.min(xAcross0, ya.position); + xAcross1 = Math.max(xAcross1, ya.position); + } + xBase = gs.l + xAcross0 * gs.w; + xEndSpike = gs.l + xAcross1 * gs.w; + } + container.insert("line", ":first-child").attr({ + x1: xBase, + x2: xEndSpike, + y1: hLinePointY, + y2: hLinePointY, + "stroke-width": yThickness, + stroke: yColor, + "stroke-dasharray": Drawing$o.dashStyle(ya.spikedash, yThickness) + }).classed("spikeline", true).classed("crisp", true); + container.insert("line", ":first-child").attr({ + x1: xBase, + x2: xEndSpike, + y1: hLinePointY, + y2: hLinePointY, + "stroke-width": yThickness + 2, + stroke: contrastColor + }).classed("spikeline", true).classed("crisp", true); + } + if (yMode.indexOf("marker") !== -1) { + container.insert("circle", ":first-child").attr({ + cx: xEdge + (ya.side !== "right" ? yThickness : -yThickness), + cy: hLinePointY, + r: yThickness, + fill: yColor + }).classed("spikeline", true); + } + } + if (showX) { + var vLinePoint = closestPoints.vLinePoint; + var vLinePointX, vLinePointY; + xa = vLinePoint && vLinePoint.xa; + ya = vLinePoint && vLinePoint.ya; + var xSnap = xa.spikesnap; + if (xSnap === "cursor") { + vLinePointX = evt.pointerX; + vLinePointY = evt.pointerY; + } else { + vLinePointX = xa._offset + vLinePoint.x; + vLinePointY = ya._offset + vLinePoint.y; + } + var dfltVLineColor = tinycolor$3.readability(vLinePoint.color, contrastColor) < 1.5 ? Color$C.contrast(contrastColor) : vLinePoint.color; + var xMode = xa.spikemode; + var xThickness = xa.spikethickness; + var xColor = xa.spikecolor || dfltVLineColor; + var yEdge = Axes$l.getPxPosition(gd, xa); + var yBase, yEndSpike; + if (xMode.indexOf("toaxis") !== -1 || xMode.indexOf("across") !== -1) { + if (xMode.indexOf("toaxis") !== -1) { + yBase = yEdge; + yEndSpike = vLinePointY; + } + if (xMode.indexOf("across") !== -1) { + var yAcross0 = xa._counterDomainMin; + var yAcross1 = xa._counterDomainMax; + if (xa.anchor === "free") { + yAcross0 = Math.min(yAcross0, xa.position); + yAcross1 = Math.max(yAcross1, xa.position); + } + yBase = gs.t + (1 - yAcross1) * gs.h; + yEndSpike = gs.t + (1 - yAcross0) * gs.h; + } + container.insert("line", ":first-child").attr({ + x1: vLinePointX, + x2: vLinePointX, + y1: yBase, + y2: yEndSpike, + "stroke-width": xThickness, + stroke: xColor, + "stroke-dasharray": Drawing$o.dashStyle(xa.spikedash, xThickness) + }).classed("spikeline", true).classed("crisp", true); + container.insert("line", ":first-child").attr({ + x1: vLinePointX, + x2: vLinePointX, + y1: yBase, + y2: yEndSpike, + "stroke-width": xThickness + 2, + stroke: contrastColor + }).classed("spikeline", true).classed("crisp", true); + } + if (xMode.indexOf("marker") !== -1) { + container.insert("circle", ":first-child").attr({ + cx: vLinePointX, + cy: yEdge - (xa.side !== "top" ? xThickness : -xThickness), + r: xThickness, + fill: xColor + }).classed("spikeline", true); + } + } +} +function hoverChanged(gd, evt, oldhoverdata) { + if (!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; + for (var i = oldhoverdata.length - 1; i >= 0; i--) { + var oldPt = oldhoverdata[i]; + var newPt = gd._hoverdata[i]; + if (oldPt.curveNumber !== newPt.curveNumber || String(oldPt.pointNumber) !== String(newPt.pointNumber) || String(oldPt.pointNumbers) !== String(newPt.pointNumbers)) { + return true; + } + } + return false; +} +function spikesChanged(gd, oldspikepoints) { + return true; +} +function plainText(s, len) { + return svgTextUtils$b.plainText(s || "", { + len, + allowedTags: ["br", "sub", "sup", "b", "i", "em", "s", "u"] + }); +} +function orderRangePoints(hoverData, hovermode) { + var axLetter = hovermode.charAt(0); + var first = []; + var second2 = []; + var last = []; + for (var i = 0; i < hoverData.length; i++) { + var d = hoverData[i]; + if (Registry$C.traceIs(d.trace, "bar-like") || Registry$C.traceIs(d.trace, "box-violin")) { + last.push(d); + } else if (d.trace[axLetter + "period"]) { + second2.push(d); + } else { + first.push(d); + } + } + return first.concat(second2).concat(last); +} +function getCoord(axLetter, winningPoint, fullLayout) { + var ax = winningPoint[axLetter + "a"]; + var val = winningPoint[axLetter + "Val"]; + var cd0 = winningPoint.cd[0]; + if (ax.type === "category" || ax.type === "multicategory") val = ax._categoriesMap[val]; + else if (ax.type === "date") { + var periodalignment = winningPoint.trace[axLetter + "periodalignment"]; + if (periodalignment) { + var d = winningPoint.cd[winningPoint.index]; + var start = d[axLetter + "Start"]; + if (start === void 0) start = d[axLetter]; + var end = d[axLetter + "End"]; + if (end === void 0) end = d[axLetter]; + var diff = end - start; + if (periodalignment === "end") { + val += diff; + } else if (periodalignment === "middle") { + val += diff / 2; + } + } + val = ax.d2c(val); + } + if (cd0 && cd0.t && cd0.t.posLetter === ax._id) { + if (fullLayout.boxmode === "group" || fullLayout.violinmode === "group") { + val += cd0.t.dPos; + } + } + return val; +} +function getTopOffset(gd) { + return gd.offsetTop + gd.clientTop; +} +function getLeftOffset(gd) { + return gd.offsetLeft + gd.clientLeft; +} +function getBoundingClientRect(gd, node) { + var fullLayout = gd._fullLayout; + var rect2 = node.getBoundingClientRect(); + var x0 = rect2.left; + var y0 = rect2.top; + var x1 = x0 + rect2.width; + var y1 = y0 + rect2.height; + var A2 = Lib$1y.apply3DTransform(fullLayout._invTransform)(x0, y0); + var B2 = Lib$1y.apply3DTransform(fullLayout._invTransform)(x1, y1); + var Ax = A2[0]; + var Ay = A2[1]; + var Bx = B2[0]; + var By = B2[1]; + return { + x: Ax, + y: Ay, + width: Bx - Ax, + height: By - Ay, + top: Math.min(Ay, By), + left: Math.min(Ax, Bx), + right: Math.max(Ax, Bx), + bottom: Math.max(Ay, By) + }; +} +var Lib$1x = libExports; +var Color$B = colorExports; +var isUnifiedHover$1 = helpers$J.isUnifiedHover; +var hoverlabel_defaults = function handleHoverLabelDefaults(contIn, contOut, coerce2, opts) { + opts = opts || {}; + var hasLegend = contOut.legend; + function inheritFontAttr(attr) { + if (!opts.font[attr]) { + opts.font[attr] = hasLegend ? contOut.legend.font[attr] : contOut.font[attr]; + } + } + if (contOut && isUnifiedHover$1(contOut.hovermode)) { + if (!opts.font) opts.font = {}; + inheritFontAttr("size"); + inheritFontAttr("family"); + inheritFontAttr("color"); + inheritFontAttr("weight"); + inheritFontAttr("style"); + inheritFontAttr("variant"); + if (hasLegend) { + if (!opts.bgcolor) opts.bgcolor = Color$B.combine(contOut.legend.bgcolor, contOut.paper_bgcolor); + if (!opts.bordercolor) opts.bordercolor = contOut.legend.bordercolor; + } else { + if (!opts.bgcolor) opts.bgcolor = contOut.paper_bgcolor; + } + } + coerce2("hoverlabel.bgcolor", opts.bgcolor); + coerce2("hoverlabel.bordercolor", opts.bordercolor); + coerce2("hoverlabel.namelength", opts.namelength); + Lib$1x.coerceFont(coerce2, "hoverlabel.font", opts.font); + coerce2("hoverlabel.align", opts.align); +}; +var Lib$1w = libExports; +var handleHoverLabelDefaults$2 = hoverlabel_defaults; +var layoutAttributes$9 = layout_attributes$7; +var layout_global_defaults = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$1w.coerce(layoutIn, layoutOut, layoutAttributes$9, attr, dflt); + } + handleHoverLabelDefaults$2(layoutIn, layoutOut, coerce2); +}; +var Lib$1v = libExports; +var attributes$E = attributes$P; +var handleHoverLabelDefaults$1 = hoverlabel_defaults; +var defaults$l = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$1v.coerce(traceIn, traceOut, attributes$E, attr, dflt); + } + var opts = Lib$1v.extendFlat({}, layout.hoverlabel); + if (traceOut.hovertemplate) opts.namelength = -1; + handleHoverLabelDefaults$1(traceIn, traceOut, coerce2, opts); +}; +var Lib$1u = libExports; +var layoutAttributes$8 = layout_attributes$7; +var hovermode_defaults = function handleHoverModeDefaults(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + if (layoutOut[attr] !== void 0) return layoutOut[attr]; + return Lib$1u.coerce(layoutIn, layoutOut, layoutAttributes$8, attr, dflt); + } + coerce2("clickmode"); + coerce2("hoversubplots"); + return coerce2("hovermode"); +}; +var Lib$1t = libExports; +var layoutAttributes$7 = layout_attributes$7; +var handleHoverModeDefaults2 = hovermode_defaults; +var handleHoverLabelDefaults2 = hoverlabel_defaults; +var layout_defaults$5 = function supplyLayoutDefaults2(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$1t.coerce(layoutIn, layoutOut, layoutAttributes$7, attr, dflt); + } + var hoverMode = handleHoverModeDefaults2(layoutIn, layoutOut); + if (hoverMode) { + coerce2("hoverdistance"); + coerce2("spikedistance"); + } + var dragMode = coerce2("dragmode"); + if (dragMode === "select") coerce2("selectdirection"); + var hasMapbox = layoutOut._has("mapbox"); + var hasMap = layoutOut._has("map"); + var hasGeo = layoutOut._has("geo"); + var len = layoutOut._basePlotModules.length; + if (layoutOut.dragmode === "zoom" && ((hasMapbox || hasMap || hasGeo) && len === 1 || (hasMapbox || hasMap) && hasGeo && len === 2)) { + layoutOut.dragmode = "pan"; + } + handleHoverLabelDefaults2(layoutIn, layoutOut, coerce2); + Lib$1t.coerceFont(coerce2, "hoverlabel.grouptitlefont", layoutOut.hoverlabel.font); +}; +var Lib$1s = libExports; +var Registry$B = registry; +var calc$b = function calc2(gd) { + var calcdata = gd.calcdata; + var fullLayout = gd._fullLayout; + function makeCoerceHoverInfo(trace2) { + return function(val) { + return Lib$1s.coerceHoverinfo({ hoverinfo: val }, { _module: trace2._module }, fullLayout); + }; + } + for (var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var trace = cd[0].trace; + if (Registry$B.traceIs(trace, "pie-like")) continue; + var fillFn = Registry$B.traceIs(trace, "2dMap") ? paste : Lib$1s.fillArray; + fillFn(trace.hoverinfo, cd, "hi", makeCoerceHoverInfo(trace)); + if (trace.hovertemplate) fillFn(trace.hovertemplate, cd, "ht"); + if (!trace.hoverlabel) continue; + fillFn(trace.hoverlabel.bgcolor, cd, "hbg"); + fillFn(trace.hoverlabel.bordercolor, cd, "hbc"); + fillFn(trace.hoverlabel.font.size, cd, "hts"); + fillFn(trace.hoverlabel.font.color, cd, "htc"); + fillFn(trace.hoverlabel.font.family, cd, "htf"); + fillFn(trace.hoverlabel.font.weight, cd, "htw"); + fillFn(trace.hoverlabel.font.style, cd, "hty"); + fillFn(trace.hoverlabel.font.variant, cd, "htv"); + fillFn(trace.hoverlabel.namelength, cd, "hnl"); + fillFn(trace.hoverlabel.align, cd, "hta"); + } +}; +function paste(traceAttr, cd, cdAttr, fn) { + fn = fn || Lib$1s.identity; + if (Array.isArray(traceAttr)) { + cd[0][cdAttr] = fn(traceAttr); + } +} +var Registry$A = registry; +var hover$6 = hover$7.hover; +var click$1 = function click(gd, evt, subplot) { + var annotationsDone = Registry$A.getComponentMethod("annotations", "onClick")(gd, gd._hoverdata); + if (subplot !== void 0) { + hover$6(gd, evt, subplot, true); + } + function emitClick() { + gd.emit("plotly_click", { points: gd._hoverdata, event: evt }); + } + if (gd._hoverdata && evt && evt.target) { + if (annotationsDone && annotationsDone.then) { + annotationsDone.then(emitClick); + } else emitClick(); + if (evt.stopImmediatePropagation) evt.stopImmediatePropagation(); + } +}; +var d3$r = d3Exports; +var Lib$1r = libExports; +var dragElement$4 = dragelementExports; +var helpers$C = helpers$J; +var layoutAttributes$6 = layout_attributes$7; +var hoverModule = hover$7; +var fx$1 = { + moduleType: "component", + name: "fx", + constants: constants$W, + schema: { + layout: layoutAttributes$6 + }, + attributes: attributes$P, + layoutAttributes: layoutAttributes$6, + supplyLayoutGlobalDefaults: layout_global_defaults, + supplyDefaults: defaults$l, + supplyLayoutDefaults: layout_defaults$5, + calc: calc$b, + getDistanceFunction: helpers$C.getDistanceFunction, + getClosest: helpers$C.getClosest, + inbox: helpers$C.inbox, + quadrature: helpers$C.quadrature, + appendArrayPointValue: helpers$C.appendArrayPointValue, + castHoverOption, + castHoverinfo, + hover: hoverModule.hover, + unhover: dragElement$4.unhover, + loneHover: hoverModule.loneHover, + loneUnhover, + click: click$1 +}; +function loneUnhover(containerOrSelection) { + var selection = Lib$1r.isD3Selection(containerOrSelection) ? containerOrSelection : d3$r.select(containerOrSelection); + selection.selectAll("g.hovertext").remove(); + selection.selectAll(".spikeline").remove(); +} +function castHoverOption(trace, ptNumber, attr) { + return Lib$1r.castOption(trace, ptNumber, "hoverlabel." + attr); +} +function castHoverinfo(trace, fullLayout, ptNumber) { + function _coerce(val) { + return Lib$1r.coerceHoverinfo({ hoverinfo: val }, { _module: trace._module }, fullLayout); + } + return Lib$1r.castOption(trace, ptNumber, "hoverinfo", _coerce); +} +var helpers$B = {}; +(function(exports2) { + exports2.selectMode = function(dragmode) { + return dragmode === "lasso" || dragmode === "select"; + }; + exports2.drawMode = function(dragmode) { + return dragmode === "drawclosedpath" || dragmode === "drawopenpath" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle"; + }; + exports2.openMode = function(dragmode) { + return dragmode === "drawline" || dragmode === "drawopenpath"; + }; + exports2.rectMode = function(dragmode) { + return dragmode === "select" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle"; + }; + exports2.freeMode = function(dragmode) { + return dragmode === "lasso" || dragmode === "drawclosedpath" || dragmode === "drawopenpath"; + }; + exports2.selectingOrDrawing = function(dragmode) { + return exports2.freeMode(dragmode) || exports2.rectMode(dragmode); + }; +})(helpers$B); +var clear_gl_canvases = function clearGlCanvases(gd) { + var fullLayout = gd._fullLayout; + if (fullLayout._glcanvas && fullLayout._glcanvas.size()) { + fullLayout._glcanvas.each(function(d) { + if (d.regl) d.regl.clear({ color: true, depth: true }); + }); + } +}; +var subroutines = {}; +var buttons = { exports: {} }; +var ploticon = { + undo: { + width: 857.1, + height: 1e3, + path: "m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z", + transform: "matrix(1 0 0 -1 0 850)" + }, + home: { + width: 928.6, + height: 1e3, + path: "m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z", + transform: "matrix(1 0 0 -1 0 850)" + }, + "camera-retro": { + width: 1e3, + height: 1e3, + path: "m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z", + transform: "matrix(1 0 0 -1 0 850)" + }, + zoombox: { + width: 1e3, + height: 1e3, + path: "m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z", + transform: "matrix(1 0 0 -1 0 850)" + }, + pan: { + width: 1e3, + height: 1e3, + path: "m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z", + transform: "matrix(1 0 0 -1 0 850)" + }, + zoom_plus: { + width: 875, + height: 1e3, + path: "m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z", + transform: "matrix(1 0 0 -1 0 850)" + }, + zoom_minus: { + width: 875, + height: 1e3, + path: "m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z", + transform: "matrix(1 0 0 -1 0 850)" + }, + autoscale: { + width: 1e3, + height: 1e3, + path: "m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z", + transform: "matrix(1 0 0 -1 0 850)" + }, + tooltip_basic: { + width: 1500, + height: 1e3, + path: "m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z", + transform: "matrix(1 0 0 -1 0 850)" + }, + tooltip_compare: { + width: 1125, + height: 1e3, + path: "m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z", + transform: "matrix(1 0 0 -1 0 850)" + }, + plotlylogo: { + width: 1542, + height: 1e3, + path: "m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z", + transform: "matrix(1 0 0 -1 0 850)" + }, + "z-axis": { + width: 1e3, + height: 1e3, + path: "m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z", + transform: "matrix(1 0 0 -1 0 850)" + }, + "3d_rotate": { + width: 1e3, + height: 1e3, + path: "m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z", + transform: "matrix(1 0 0 -1 0 850)" + }, + camera: { + width: 1e3, + height: 1e3, + path: "m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z", + transform: "matrix(1 0 0 -1 0 850)" + }, + movie: { + width: 1e3, + height: 1e3, + path: "m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z", + transform: "matrix(1 0 0 -1 0 850)" + }, + question: { + width: 857.1, + height: 1e3, + path: "m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z", + transform: "matrix(1 0 0 -1 0 850)" + }, + disk: { + width: 857.1, + height: 1e3, + path: "m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z", + transform: "matrix(1 0 0 -1 0 850)" + }, + drawopenpath: { + width: 70, + height: 70, + path: "M33.21,85.65a7.31,7.31,0,0,1-2.59-.48c-8.16-3.11-9.27-19.8-9.88-41.3-.1-3.58-.19-6.68-.35-9-.15-2.1-.67-3.48-1.43-3.79-2.13-.88-7.91,2.32-12,5.86L3,32.38c1.87-1.64,11.55-9.66,18.27-6.9,2.13.87,4.75,3.14,5.17,9,.17,2.43.26,5.59.36,9.25a224.17,224.17,0,0,0,1.5,23.4c1.54,10.76,4,12.22,4.48,12.4.84.32,2.79-.46,5.76-3.59L43,80.07C41.53,81.57,37.68,85.64,33.21,85.65ZM74.81,69a11.34,11.34,0,0,0,6.09-6.72L87.26,44.5,74.72,32,56.9,38.35c-2.37.86-5.57,3.42-6.61,6L38.65,72.14l8.42,8.43ZM55,46.27a7.91,7.91,0,0,1,3.64-3.17l14.8-5.3,8,8L76.11,60.6l-.06.19a6.37,6.37,0,0,1-3,3.43L48.25,74.59,44.62,71Zm16.57,7.82A6.9,6.9,0,1,0,64.64,61,6.91,6.91,0,0,0,71.54,54.09Zm-4.05,0a2.85,2.85,0,1,1-2.85-2.85A2.86,2.86,0,0,1,67.49,54.09Zm-4.13,5.22L60.5,56.45,44.26,72.7l2.86,2.86ZM97.83,35.67,84.14,22l-8.57,8.57L89.26,44.24Zm-13.69-8,8,8-2.85,2.85-8-8Z", + transform: "matrix(1 0 0 1 -15 -15)" + }, + drawclosedpath: { + width: 90, + height: 90, + path: "M88.41,21.12a26.56,26.56,0,0,0-36.18,0l-2.07,2-2.07-2a26.57,26.57,0,0,0-36.18,0,23.74,23.74,0,0,0,0,34.8L48,90.12a3.22,3.22,0,0,0,4.42,0l36-34.21a23.73,23.73,0,0,0,0-34.79ZM84,51.24,50.16,83.35,16.35,51.25a17.28,17.28,0,0,1,0-25.47,20,20,0,0,1,27.3,0l4.29,4.07a3.23,3.23,0,0,0,4.44,0l4.29-4.07a20,20,0,0,1,27.3,0,17.27,17.27,0,0,1,0,25.46ZM66.76,47.68h-33v6.91h33ZM53.35,35H46.44V68h6.91Z", + transform: "matrix(1 0 0 1 -5 -5)" + }, + lasso: { + width: 1031, + height: 1e3, + path: "m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z", + transform: "matrix(1 0 0 -1 0 850)" + }, + selectbox: { + width: 1e3, + height: 1e3, + path: "m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z", + transform: "matrix(1 0 0 -1 0 850)" + }, + drawline: { + width: 70, + height: 70, + path: "M60.64,62.3a11.29,11.29,0,0,0,6.09-6.72l6.35-17.72L60.54,25.31l-17.82,6.4c-2.36.86-5.57,3.41-6.6,6L24.48,65.5l8.42,8.42ZM40.79,39.63a7.89,7.89,0,0,1,3.65-3.17l14.79-5.31,8,8L61.94,54l-.06.19a6.44,6.44,0,0,1-3,3.43L34.07,68l-3.62-3.63Zm16.57,7.81a6.9,6.9,0,1,0-6.89,6.9A6.9,6.9,0,0,0,57.36,47.44Zm-4,0a2.86,2.86,0,1,1-2.85-2.85A2.86,2.86,0,0,1,53.32,47.44Zm-4.13,5.22L46.33,49.8,30.08,66.05l2.86,2.86ZM83.65,29,70,15.34,61.4,23.9,75.09,37.59ZM70,21.06l8,8-2.84,2.85-8-8ZM87,80.49H10.67V87H87Z", + transform: "matrix(1 0 0 1 -15 -15)" + }, + drawrect: { + width: 80, + height: 80, + path: "M78,22V79H21V22H78m9-9H12V88H87V13ZM68,46.22H31V54H68ZM53,32H45.22V69H53Z", + transform: "matrix(1 0 0 1 -10 -10)" + }, + drawcircle: { + width: 80, + height: 80, + path: "M50,84.72C26.84,84.72,8,69.28,8,50.3S26.84,15.87,50,15.87,92,31.31,92,50.3,73.16,84.72,50,84.72Zm0-60.59c-18.6,0-33.74,11.74-33.74,26.17S31.4,76.46,50,76.46,83.74,64.72,83.74,50.3,68.6,24.13,50,24.13Zm17.15,22h-34v7.11h34Zm-13.8-13H46.24v34h7.11Z", + transform: "matrix(1 0 0 1 -10 -10)" + }, + eraseshape: { + width: 80, + height: 80, + path: "M82.77,78H31.85L6,49.57,31.85,21.14H82.77a8.72,8.72,0,0,1,8.65,8.77V69.24A8.72,8.72,0,0,1,82.77,78ZM35.46,69.84H82.77a.57.57,0,0,0,.49-.6V29.91a.57.57,0,0,0-.49-.61H35.46L17,49.57Zm32.68-34.7-24,24,5,5,24-24Zm-19,.53-5,5,24,24,5-5Z", + transform: "matrix(1 0 0 1 -10 -10)" + }, + spikeline: { + width: 1e3, + height: 1e3, + path: "M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z", + transform: "matrix(1.5 0 0 -1.5 0 850)" + }, + pencil: { + width: 1792, + height: 1792, + path: "M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z", + transform: "matrix(1 0 0 1 0 1)" + }, + newplotlylogo: { + name: "newplotlylogo", + svg: [ + "", + "", + " ", + "", + " plotly-logomark", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + " ", + "" + ].join("") + } +}; +var helpers$A = {}; +var CIRCLE_SIDES = 32; +var constants$K = { + CIRCLE_SIDES, + i000: 0, + i090: CIRCLE_SIDES / 4, + i180: CIRCLE_SIDES / 2, + i270: CIRCLE_SIDES / 4 * 3, + cos45: Math.cos(Math.PI / 4), + sin45: Math.sin(Math.PI / 4), + SQRT2: Math.sqrt(2) +}; +var strTranslate$7 = libExports.strTranslate; +function p2r$2(ax, v) { + switch (ax.type) { + case "log": + return ax.p2d(v); + case "date": + return ax.p2r(v, 0, ax.calendar); + default: + return ax.p2r(v); + } +} +function r2p$1(ax, v) { + switch (ax.type) { + case "log": + return ax.d2p(v); + case "date": + return ax.r2p(v, 0, ax.calendar); + default: + return ax.r2p(v); + } +} +function axValue$1(ax) { + var index2 = ax._id.charAt(0) === "y" ? 1 : 0; + return function(v) { + return p2r$2(ax, v[index2]); + }; +} +function getTransform$1(plotinfo) { + return strTranslate$7( + plotinfo.xaxis._offset, + plotinfo.yaxis._offset + ); +} +var helpers$z = { + p2r: p2r$2, + r2p: r2p$1, + axValue: axValue$1, + getTransform: getTransform$1 +}; +(function(exports2) { + var parseSvgPath$1 = parseSvgPath; + var constants2 = constants$K; + var CIRCLE_SIDES2 = constants2.CIRCLE_SIDES; + var SQRT2 = constants2.SQRT2; + var cartesianHelpers2 = helpers$z; + var p2r2 = cartesianHelpers2.p2r; + var r2p2 = cartesianHelpers2.r2p; + var iC = [0, 3, 4, 5, 6, 1, 2]; + var iQS = [0, 3, 4, 1, 2]; + exports2.writePaths = function(polygons) { + var nI = polygons.length; + if (!nI) return "M0,0Z"; + var str2 = ""; + for (var i = 0; i < nI; i++) { + var nJ = polygons[i].length; + for (var j = 0; j < nJ; j++) { + var w = polygons[i][j][0]; + if (w === "Z") { + str2 += "Z"; + } else { + var nK = polygons[i][j].length; + for (var k = 0; k < nK; k++) { + var realK = k; + if (w === "Q" || w === "S") { + realK = iQS[k]; + } else if (w === "C") { + realK = iC[k]; + } + str2 += polygons[i][j][realK]; + if (k > 0 && k < nK - 1) { + str2 += ","; + } + } + } + } + } + return str2; + }; + exports2.readPaths = function(str2, gd, plotinfo, isActiveShape) { + var cmd = parseSvgPath$1(str2); + var polys = []; + var n = -1; + var newPoly = function() { + n++; + polys[n] = []; + }; + var k; + var x = 0; + var y = 0; + var initX; + var initY; + var recStart = function() { + initX = x; + initY = y; + }; + recStart(); + for (var i = 0; i < cmd.length; i++) { + var newPos = []; + var x1, x2, y1, y2; + var c = cmd[i][0]; + var w = c; + switch (c) { + case "M": + newPoly(); + x = +cmd[i][1]; + y = +cmd[i][2]; + newPos.push([w, x, y]); + recStart(); + break; + case "Q": + case "S": + x1 = +cmd[i][1]; + y1 = +cmd[i][2]; + x = +cmd[i][3]; + y = +cmd[i][4]; + newPos.push([w, x, y, x1, y1]); + break; + case "C": + x1 = +cmd[i][1]; + y1 = +cmd[i][2]; + x2 = +cmd[i][3]; + y2 = +cmd[i][4]; + x = +cmd[i][5]; + y = +cmd[i][6]; + newPos.push([w, x, y, x1, y1, x2, y2]); + break; + case "T": + case "L": + x = +cmd[i][1]; + y = +cmd[i][2]; + newPos.push([w, x, y]); + break; + case "H": + w = "L"; + x = +cmd[i][1]; + newPos.push([w, x, y]); + break; + case "V": + w = "L"; + y = +cmd[i][1]; + newPos.push([w, x, y]); + break; + case "A": + w = "L"; + var rx = +cmd[i][1]; + var ry = +cmd[i][2]; + if (!+cmd[i][4]) { + rx = -rx; + ry = -ry; + } + var cenX = x - rx; + var cenY = y; + for (k = 1; k <= CIRCLE_SIDES2 / 2; k++) { + var t = 2 * Math.PI * k / CIRCLE_SIDES2; + newPos.push([ + w, + cenX + rx * Math.cos(t), + cenY + ry * Math.sin(t) + ]); + } + break; + case "Z": + if (x !== initX || y !== initY) { + x = initX; + y = initY; + newPos.push([w, x, y]); + } + break; + } + var domain2 = (plotinfo || {}).domain; + var size = gd._fullLayout._size; + var xPixelSized = plotinfo && plotinfo.xsizemode === "pixel"; + var yPixelSized = plotinfo && plotinfo.ysizemode === "pixel"; + var noOffset = isActiveShape === false; + for (var j = 0; j < newPos.length; j++) { + for (k = 0; k + 2 < 7; k += 2) { + var _x = newPos[j][k + 1]; + var _y = newPos[j][k + 2]; + if (_x === void 0 || _y === void 0) continue; + x = _x; + y = _y; + if (plotinfo) { + if (plotinfo.xaxis && plotinfo.xaxis.p2r) { + if (noOffset) _x -= plotinfo.xaxis._offset; + if (xPixelSized) { + _x = r2p2(plotinfo.xaxis, plotinfo.xanchor) + _x; + } else { + _x = p2r2(plotinfo.xaxis, _x); + } + } else { + if (noOffset) _x -= size.l; + if (domain2) _x = domain2.x[0] + _x / size.w; + else _x = _x / size.w; + } + if (plotinfo.yaxis && plotinfo.yaxis.p2r) { + if (noOffset) _y -= plotinfo.yaxis._offset; + if (yPixelSized) { + _y = r2p2(plotinfo.yaxis, plotinfo.yanchor) - _y; + } else { + _y = p2r2(plotinfo.yaxis, _y); + } + } else { + if (noOffset) _y -= size.t; + if (domain2) _y = domain2.y[1] - _y / size.h; + else _y = 1 - _y / size.h; + } + } + newPos[j][k + 1] = _x; + newPos[j][k + 2] = _y; + } + polys[n].push( + newPos[j].slice() + ); + } + } + return polys; + }; + function almostEq(a, b) { + return Math.abs(a - b) <= 1e-6; + } + function dist2(a, b) { + var dx = b[1] - a[1]; + var dy = b[2] - a[2]; + return Math.sqrt( + dx * dx + dy * dy + ); + } + exports2.pointsOnRectangle = function(cell) { + var len = cell.length; + if (len !== 5) return false; + for (var j = 1; j < 3; j++) { + var e01 = cell[0][j] - cell[1][j]; + var e32 = cell[3][j] - cell[2][j]; + if (!almostEq(e01, e32)) return false; + var e03 = cell[0][j] - cell[3][j]; + var e12 = cell[1][j] - cell[2][j]; + if (!almostEq(e03, e12)) return false; + } + if (!almostEq(cell[0][1], cell[1][1]) && !almostEq(cell[0][1], cell[3][1])) return false; + return !!(dist2(cell[0], cell[1]) * dist2(cell[0], cell[3])); + }; + exports2.pointsOnEllipse = function(cell) { + var len = cell.length; + if (len !== CIRCLE_SIDES2 + 1) return false; + len = CIRCLE_SIDES2; + for (var i = 0; i < len; i++) { + var k = (len * 2 - i) % len; + var k2 = (len / 2 + k) % len; + var i2 = (len / 2 + i) % len; + if (!almostEq( + dist2(cell[i], cell[i2]), + dist2(cell[k], cell[k2]) + )) return false; + } + return true; + }; + exports2.handleEllipse = function(isEllipse, start, end) { + if (!isEllipse) return [start, end]; + var pos = exports2.ellipseOver({ + x0: start[0], + y0: start[1], + x1: end[0], + y1: end[1] + }); + var cx = (pos.x1 + pos.x0) / 2; + var cy = (pos.y1 + pos.y0) / 2; + var rx = (pos.x1 - pos.x0) / 2; + var ry = (pos.y1 - pos.y0) / 2; + if (!rx) rx = ry = ry / SQRT2; + if (!ry) ry = rx = rx / SQRT2; + var cell = []; + for (var i = 0; i < CIRCLE_SIDES2; i++) { + var t = i * 2 * Math.PI / CIRCLE_SIDES2; + cell.push([ + cx + rx * Math.cos(t), + cy + ry * Math.sin(t) + ]); + } + return cell; + }; + exports2.ellipseOver = function(pos) { + var x0 = pos.x0; + var y0 = pos.y0; + var x1 = pos.x1; + var y1 = pos.y1; + var dx = x1 - x0; + var dy = y1 - y0; + x0 -= dx; + y0 -= dy; + var cx = (x0 + x1) / 2; + var cy = (y0 + y1) / 2; + var scale2 = SQRT2; + dx *= scale2; + dy *= scale2; + return { + x0: cx - dx, + y0: cy - dy, + x1: cx + dx, + y1: cy + dy + }; + }; + exports2.fixDatesForPaths = function(polygons, xaxis, yaxis) { + var xIsDate = xaxis.type === "date"; + var yIsDate = yaxis.type === "date"; + if (!xIsDate && !yIsDate) return polygons; + for (var i = 0; i < polygons.length; i++) { + for (var j = 0; j < polygons[i].length; j++) { + for (var k = 0; k + 2 < polygons[i][j].length; k += 2) { + if (xIsDate) polygons[i][j][k + 1] = polygons[i][j][k + 1].replace(" ", "_"); + if (yIsDate) polygons[i][j][k + 2] = polygons[i][j][k + 2].replace(" ", "_"); + } + } + } + return polygons; + }; +})(helpers$A); +var dragHelpers$3 = helpers$B; +var drawMode$2 = dragHelpers$3.drawMode; +var openMode$1 = dragHelpers$3.openMode; +var constants$J = constants$K; +var i000$1 = constants$J.i000; +var i090$1 = constants$J.i090; +var i180$1 = constants$J.i180; +var i270$1 = constants$J.i270; +var cos45 = constants$J.cos45; +var sin45 = constants$J.sin45; +var cartesianHelpers = helpers$z; +var p2r$1 = cartesianHelpers.p2r; +var r2p = cartesianHelpers.r2p; +var handleOutline$2 = handle_outline; +var clearOutline$2 = handleOutline$2.clearOutline; +var helpers$y = helpers$A; +var readPaths$5 = helpers$y.readPaths; +var writePaths$2 = helpers$y.writePaths; +var ellipseOver = helpers$y.ellipseOver; +var fixDatesForPaths$1 = helpers$y.fixDatesForPaths; +function newShapes$2(outlines, dragOptions) { + if (!outlines.length) return; + var e = outlines[0][0]; + if (!e) return; + var gd = dragOptions.gd; + var isActiveShape = dragOptions.isActiveShape; + var dragmode = dragOptions.dragmode; + var shapes2 = (gd.layout || {}).shapes || []; + if (!drawMode$2(dragmode) && isActiveShape !== void 0) { + var id = gd._fullLayout._activeShapeIndex; + if (id < shapes2.length) { + switch (gd._fullLayout.shapes[id].type) { + case "rect": + dragmode = "drawrect"; + break; + case "circle": + dragmode = "drawcircle"; + break; + case "line": + dragmode = "drawline"; + break; + case "path": + var path = shapes2[id].path || ""; + if (path[path.length - 1] === "Z") { + dragmode = "drawclosedpath"; + } else { + dragmode = "drawopenpath"; + } + break; + } + } + } + var newShape = createShapeObj$1(outlines, dragOptions, dragmode); + clearOutline$2(gd); + var editHelpers = dragOptions.editHelpers; + var modifyItem = (editHelpers || {}).modifyItem; + var allShapes = []; + for (var q = 0; q < shapes2.length; q++) { + var beforeEdit = gd._fullLayout.shapes[q]; + allShapes[q] = beforeEdit._input; + if (isActiveShape !== void 0 && q === gd._fullLayout._activeShapeIndex) { + var afterEdit = newShape; + switch (beforeEdit.type) { + case "line": + case "rect": + case "circle": + modifyItem("x0", afterEdit.x0 - (beforeEdit.x0shift || 0)); + modifyItem("x1", afterEdit.x1 - (beforeEdit.x1shift || 0)); + modifyItem("y0", afterEdit.y0 - (beforeEdit.y0shift || 0)); + modifyItem("y1", afterEdit.y1 - (beforeEdit.y1shift || 0)); + break; + case "path": + modifyItem("path", afterEdit.path); + break; + } + } + } + if (isActiveShape === void 0) { + allShapes.push(newShape); + return allShapes; + } + return editHelpers ? editHelpers.getUpdateObj() : {}; +} +function createShapeObj$1(outlines, dragOptions, dragmode) { + var e = outlines[0][0]; + var gd = dragOptions.gd; + var d = e.getAttribute("d"); + var newStyle = gd._fullLayout.newshape; + var plotinfo = dragOptions.plotinfo; + var isActiveShape = dragOptions.isActiveShape; + var xaxis = plotinfo.xaxis; + var yaxis = plotinfo.yaxis; + var xPaper = !!plotinfo.domain || !plotinfo.xaxis; + var yPaper = !!plotinfo.domain || !plotinfo.yaxis; + var isOpenMode = openMode$1(dragmode); + var polygons = readPaths$5(d, gd, plotinfo, isActiveShape); + var newShape = { + editable: true, + visible: newStyle.visible, + name: newStyle.name, + showlegend: newStyle.showlegend, + legend: newStyle.legend, + legendwidth: newStyle.legendwidth, + legendgroup: newStyle.legendgroup, + legendgrouptitle: { + text: newStyle.legendgrouptitle.text, + font: newStyle.legendgrouptitle.font + }, + legendrank: newStyle.legendrank, + label: newStyle.label, + xref: xPaper ? "paper" : xaxis._id, + yref: yPaper ? "paper" : yaxis._id, + layer: newStyle.layer, + opacity: newStyle.opacity, + line: { + color: newStyle.line.color, + width: newStyle.line.width, + dash: newStyle.line.dash + } + }; + if (!isOpenMode) { + newShape.fillcolor = newStyle.fillcolor; + newShape.fillrule = newStyle.fillrule; + } + var cell; + if (polygons.length === 1) cell = polygons[0]; + if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect + dragmode === "drawrect") { + newShape.type = "rect"; + newShape.x0 = cell[0][1]; + newShape.y0 = cell[0][2]; + newShape.x1 = cell[2][1]; + newShape.y1 = cell[2][2]; + } else if (cell && dragmode === "drawline") { + newShape.type = "line"; + newShape.x0 = cell[0][1]; + newShape.y0 = cell[0][2]; + newShape.x1 = cell[1][1]; + newShape.y1 = cell[1][2]; + } else if (cell && dragmode === "drawcircle") { + newShape.type = "circle"; + var xA = cell[i000$1][1]; + var xB = cell[i090$1][1]; + var xC = cell[i180$1][1]; + var xD = cell[i270$1][1]; + var yA = cell[i000$1][2]; + var yB = cell[i090$1][2]; + var yC = cell[i180$1][2]; + var yD = cell[i270$1][2]; + var xDateOrLog = plotinfo.xaxis && (plotinfo.xaxis.type === "date" || plotinfo.xaxis.type === "log"); + var yDateOrLog = plotinfo.yaxis && (plotinfo.yaxis.type === "date" || plotinfo.yaxis.type === "log"); + if (xDateOrLog) { + xA = r2p(plotinfo.xaxis, xA); + xB = r2p(plotinfo.xaxis, xB); + xC = r2p(plotinfo.xaxis, xC); + xD = r2p(plotinfo.xaxis, xD); + } + if (yDateOrLog) { + yA = r2p(plotinfo.yaxis, yA); + yB = r2p(plotinfo.yaxis, yB); + yC = r2p(plotinfo.yaxis, yC); + yD = r2p(plotinfo.yaxis, yD); + } + var x0 = (xB + xD) / 2; + var y0 = (yA + yC) / 2; + var rx = (xD - xB + xC - xA) / 2; + var ry = (yD - yB + yC - yA) / 2; + var pos = ellipseOver({ + x0, + y0, + x1: x0 + rx * cos45, + y1: y0 + ry * sin45 + }); + if (xDateOrLog) { + pos.x0 = p2r$1(plotinfo.xaxis, pos.x0); + pos.x1 = p2r$1(plotinfo.xaxis, pos.x1); + } + if (yDateOrLog) { + pos.y0 = p2r$1(plotinfo.yaxis, pos.y0); + pos.y1 = p2r$1(plotinfo.yaxis, pos.y1); + } + newShape.x0 = pos.x0; + newShape.y0 = pos.y0; + newShape.x1 = pos.x1; + newShape.y1 = pos.y1; + } else { + newShape.type = "path"; + if (xaxis && yaxis) fixDatesForPaths$1(polygons, xaxis, yaxis); + newShape.path = writePaths$2(polygons); + cell = null; + } + return newShape; +} +var newshapes = { + newShapes: newShapes$2, + createShapeObj: createShapeObj$1 +}; +var dragHelpers$2 = helpers$B; +var selectMode$3 = dragHelpers$2.selectMode; +var handleOutline$1 = handle_outline; +var clearOutline$1 = handleOutline$1.clearOutline; +var helpers$x = helpers$A; +var readPaths$4 = helpers$x.readPaths; +var writePaths$1 = helpers$x.writePaths; +var fixDatesForPaths = helpers$x.fixDatesForPaths; +var newselections = function newSelections(outlines, dragOptions) { + if (!outlines.length) return; + var e = outlines[0][0]; + if (!e) return; + var d = e.getAttribute("d"); + var gd = dragOptions.gd; + var newStyle = gd._fullLayout.newselection; + var plotinfo = dragOptions.plotinfo; + var xaxis = plotinfo.xaxis; + var yaxis = plotinfo.yaxis; + var isActiveSelection = dragOptions.isActiveSelection; + var dragmode = dragOptions.dragmode; + var selections2 = (gd.layout || {}).selections || []; + if (!selectMode$3(dragmode) && isActiveSelection !== void 0) { + var id = gd._fullLayout._activeSelectionIndex; + if (id < selections2.length) { + switch (gd._fullLayout.selections[id].type) { + case "rect": + dragmode = "select"; + break; + case "path": + dragmode = "lasso"; + break; + } + } + } + var polygons = readPaths$4(d, gd, plotinfo, isActiveSelection); + var newSelection = { + xref: xaxis._id, + yref: yaxis._id, + opacity: newStyle.opacity, + line: { + color: newStyle.line.color, + width: newStyle.line.width, + dash: newStyle.line.dash + } + }; + var cell; + if (polygons.length === 1) cell = polygons[0]; + if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect + dragmode === "select") { + newSelection.type = "rect"; + newSelection.x0 = cell[0][1]; + newSelection.y0 = cell[0][2]; + newSelection.x1 = cell[2][1]; + newSelection.y1 = cell[2][2]; + } else { + newSelection.type = "path"; + if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis); + newSelection.path = writePaths$1(polygons); + cell = null; + } + clearOutline$1(gd); + var editHelpers = dragOptions.editHelpers; + var modifyItem = (editHelpers || {}).modifyItem; + var allSelections = []; + for (var q = 0; q < selections2.length; q++) { + var beforeEdit = gd._fullLayout.selections[q]; + if (!beforeEdit) { + allSelections[q] = beforeEdit; + continue; + } + allSelections[q] = beforeEdit._input; + if (isActiveSelection !== void 0 && q === gd._fullLayout._activeSelectionIndex) { + var afterEdit = newSelection; + switch (beforeEdit.type) { + case "rect": + modifyItem("x0", afterEdit.x0); + modifyItem("x1", afterEdit.x1); + modifyItem("y0", afterEdit.y0); + modifyItem("y1", afterEdit.y1); + break; + case "path": + modifyItem("path", afterEdit.path); + break; + } + } + } + if (isActiveSelection === void 0) { + allSelections.push(newSelection); + return allSelections; + } + return editHelpers ? editHelpers.getUpdateObj() : {}; +}; +var helpers$w = {}; +var constants$I = { + segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, + paramRE: /[^\s,]+/g, + // which numbers in each path segment are x (or y) values + // drawn is which param is a drawn point, as opposed to a + // control point (which doesn't count toward autorange. + // TODO: this means curved paths could extend beyond the + // autorange bounds. This is a bit tricky to get right + // unless we revert to bounding boxes, but perhaps there's + // a calculation we could do...) + paramIsX: { + M: { 0: true, drawn: 0 }, + L: { 0: true, drawn: 0 }, + H: { 0: true, drawn: 0 }, + V: {}, + Q: { 0: true, 2: true, drawn: 2 }, + C: { 0: true, 2: true, 4: true, drawn: 4 }, + T: { 0: true, drawn: 0 }, + S: { 0: true, 2: true, drawn: 2 }, + // A: {0: true, 5: true}, + Z: {} + }, + paramIsY: { + M: { 1: true, drawn: 1 }, + L: { 1: true, drawn: 1 }, + H: {}, + V: { 0: true, drawn: 0 }, + Q: { 1: true, 3: true, drawn: 3 }, + C: { 1: true, 3: true, 5: true, drawn: 5 }, + T: { 1: true, drawn: 1 }, + S: { 1: true, 3: true, drawn: 5 }, + // A: {1: true, 6: true}, + Z: {} + }, + numParams: { + M: 2, + L: 2, + H: 1, + V: 1, + Q: 4, + C: 6, + T: 2, + S: 4, + // A: 7, + Z: 0 + } +}; +(function(exports2) { + var constants2 = constants$I; + var Lib2 = libExports; + var Axes2 = axesExports; + exports2.rangeToShapePosition = function(ax) { + return ax.type === "log" ? ax.r2d : function(v) { + return v; + }; + }; + exports2.shapePositionToRange = function(ax) { + return ax.type === "log" ? ax.d2r : function(v) { + return v; + }; + }; + exports2.decodeDate = function(convertToPx) { + return function(v) { + if (v.replace) v = v.replace("_", " "); + return convertToPx(v); + }; + }; + exports2.encodeDate = function(convertToDate) { + return function(v) { + return convertToDate(v).replace(" ", "_"); + }; + }; + exports2.extractPathCoords = function(path, paramsToUse, isRaw) { + var extractedCoordinates = []; + var segments = path.match(constants2.segmentRE); + segments.forEach(function(segment2) { + var relevantParamIdx = paramsToUse[segment2.charAt(0)].drawn; + if (relevantParamIdx === void 0) return; + var params = segment2.substr(1).match(constants2.paramRE); + if (!params || params.length < relevantParamIdx) return; + var str2 = params[relevantParamIdx]; + var pos = isRaw ? str2 : Lib2.cleanNumber(str2); + extractedCoordinates.push(pos); + }); + return extractedCoordinates; + }; + exports2.getDataToPixel = function(gd, axis, shift, isVertical2, refType) { + var gs = gd._fullLayout._size; + var dataToPixel; + if (axis) { + if (refType === "domain") { + dataToPixel = function(v) { + return axis._length * (isVertical2 ? 1 - v : v) + axis._offset; + }; + } else { + var d2r = exports2.shapePositionToRange(axis); + dataToPixel = function(v) { + var shiftPixels = getPixelShift(axis, shift); + return axis._offset + axis.r2p(d2r(v, true)) + shiftPixels; + }; + if (axis.type === "date") dataToPixel = exports2.decodeDate(dataToPixel); + } + } else if (isVertical2) { + dataToPixel = function(v) { + return gs.t + gs.h * (1 - v); + }; + } else { + dataToPixel = function(v) { + return gs.l + gs.w * v; + }; + } + return dataToPixel; + }; + exports2.getPixelToData = function(gd, axis, isVertical2, opt) { + var gs = gd._fullLayout._size; + var pixelToData; + if (axis) { + if (opt === "domain") { + pixelToData = function(p) { + var q = (p - axis._offset) / axis._length; + return isVertical2 ? 1 - q : q; + }; + } else { + var r2d = exports2.rangeToShapePosition(axis); + pixelToData = function(p) { + return r2d(axis.p2r(p - axis._offset)); + }; + } + } else if (isVertical2) { + pixelToData = function(p) { + return 1 - (p - gs.t) / gs.h; + }; + } else { + pixelToData = function(p) { + return (p - gs.l) / gs.w; + }; + } + return pixelToData; + }; + exports2.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) { + var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1; + var posValAsInt = Math.round(pos); + return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt; + }; + exports2.makeShapesOptionsAndPlotinfo = function(gd, index2) { + var options = gd._fullLayout.shapes[index2] || {}; + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + var hasPlotinfo = !!plotinfo; + if (hasPlotinfo) { + plotinfo._hadPlotinfo = true; + } else { + plotinfo = {}; + if (options.xref && options.xref !== "paper") plotinfo.xaxis = gd._fullLayout[options.xref + "axis"]; + if (options.yref && options.yref !== "paper") plotinfo.yaxis = gd._fullLayout[options.yref + "axis"]; + } + plotinfo.xsizemode = options.xsizemode; + plotinfo.ysizemode = options.ysizemode; + plotinfo.xanchor = options.xanchor; + plotinfo.yanchor = options.yanchor; + return { + options, + plotinfo + }; + }; + exports2.makeSelectionsOptionsAndPlotinfo = function(gd, index2) { + var options = gd._fullLayout.selections[index2] || {}; + var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; + var hasPlotinfo = !!plotinfo; + if (hasPlotinfo) { + plotinfo._hadPlotinfo = true; + } else { + plotinfo = {}; + if (options.xref) plotinfo.xaxis = gd._fullLayout[options.xref + "axis"]; + if (options.yref) plotinfo.yaxis = gd._fullLayout[options.yref + "axis"]; + } + return { + options, + plotinfo + }; + }; + exports2.getPathString = function(gd, options) { + var type = options.type; + var xRefType = Axes2.getRefType(options.xref); + var yRefType = Axes2.getRefType(options.yref); + var xa = Axes2.getFromId(gd, options.xref); + var ya = Axes2.getFromId(gd, options.yref); + var gs = gd._fullLayout._size; + var x2r, x2p, y2r, y2p; + var xShiftStart = getPixelShift(xa, options.x0shift); + var xShiftEnd = getPixelShift(xa, options.x1shift); + var yShiftStart = getPixelShift(ya, options.y0shift); + var yShiftEnd = getPixelShift(ya, options.y1shift); + var x0, x1, y0, y1; + if (xa) { + if (xRefType === "domain") { + x2p = function(v) { + return xa._offset + xa._length * v; + }; + } else { + x2r = exports2.shapePositionToRange(xa); + x2p = function(v) { + return xa._offset + xa.r2p(x2r(v, true)); + }; + } + } else { + x2p = function(v) { + return gs.l + gs.w * v; + }; + } + if (ya) { + if (yRefType === "domain") { + y2p = function(v) { + return ya._offset + ya._length * (1 - v); + }; + } else { + y2r = exports2.shapePositionToRange(ya); + y2p = function(v) { + return ya._offset + ya.r2p(y2r(v, true)); + }; + } + } else { + y2p = function(v) { + return gs.t + gs.h * (1 - v); + }; + } + if (type === "path") { + if (xa && xa.type === "date") x2p = exports2.decodeDate(x2p); + if (ya && ya.type === "date") y2p = exports2.decodeDate(y2p); + return convertPath(options, x2p, y2p); + } + if (options.xsizemode === "pixel") { + var xAnchorPos = x2p(options.xanchor); + x0 = xAnchorPos + options.x0 + xShiftStart; + x1 = xAnchorPos + options.x1 + xShiftEnd; + } else { + x0 = x2p(options.x0) + xShiftStart; + x1 = x2p(options.x1) + xShiftEnd; + } + if (options.ysizemode === "pixel") { + var yAnchorPos = y2p(options.yanchor); + y0 = yAnchorPos - options.y0 + yShiftStart; + y1 = yAnchorPos - options.y1 + yShiftEnd; + } else { + y0 = y2p(options.y0) + yShiftStart; + y1 = y2p(options.y1) + yShiftEnd; + } + if (type === "line") return "M" + x0 + "," + y0 + "L" + x1 + "," + y1; + if (type === "rect") return "M" + x0 + "," + y0 + "H" + x1 + "V" + y1 + "H" + x0 + "Z"; + var cx = (x0 + x1) / 2; + var cy = (y0 + y1) / 2; + var rx = Math.abs(cx - x0); + var ry = Math.abs(cy - y0); + var rArc = "A" + rx + "," + ry; + var rightPt = cx + rx + "," + cy; + var topPt = cx + "," + (cy - ry); + return "M" + rightPt + rArc + " 0 1,1 " + topPt + rArc + " 0 0,1 " + rightPt + "Z"; + }; + function convertPath(options, x2p, y2p) { + var pathIn = options.path; + var xSizemode = options.xsizemode; + var ySizemode = options.ysizemode; + var xAnchor = options.xanchor; + var yAnchor = options.yanchor; + return pathIn.replace(constants2.segmentRE, function(segment2) { + var paramNumber = 0; + var segmentType = segment2.charAt(0); + var xParams = constants2.paramIsX[segmentType]; + var yParams = constants2.paramIsY[segmentType]; + var nParams = constants2.numParams[segmentType]; + var paramString = segment2.substr(1).replace(constants2.paramRE, function(param) { + if (xParams[paramNumber]) { + if (xSizemode === "pixel") param = x2p(xAnchor) + Number(param); + else param = x2p(param); + } else if (yParams[paramNumber]) { + if (ySizemode === "pixel") param = y2p(yAnchor) - Number(param); + else param = y2p(param); + } + paramNumber++; + if (paramNumber > nParams) param = "X"; + return param; + }); + if (paramNumber > nParams) { + paramString = paramString.replace(/[\s,]*X.*/, ""); + Lib2.log("Ignoring extra params in segment " + segment2); + } + return segmentType + paramString; + }); + } + function getPixelShift(axis, shift) { + shift = shift || 0; + var shiftPixels = 0; + if (shift && axis && (axis.type === "category" || axis.type === "multicategory")) { + shiftPixels = (axis.r2p(1) - axis.r2p(0)) * shift; + } + return shiftPixels; + } +})(helpers$w); +var Lib$1q = libExports; +var Axes$k = axesExports; +var svgTextUtils$a = svg_text_utils; +var Drawing$n = drawingExports; +var readPaths$3 = helpers$A.readPaths; +var helpers$v = helpers$w; +var getPathString$2 = helpers$v.getPathString; +var shapeLabelTexttemplateVars$1 = label_texttemplate; +var FROM_TL$3 = alignment$1.FROM_TL; +var display_labels = function drawLabel(gd, index2, options, shapeGroup) { + shapeGroup.selectAll(".shape-label").remove(); + if (!(options.label.text || options.label.texttemplate)) return; + var text; + if (options.label.texttemplate) { + var templateValues = {}; + if (options.type !== "path") { + var _xa = Axes$k.getFromId(gd, options.xref); + var _ya = Axes$k.getFromId(gd, options.yref); + for (var key in shapeLabelTexttemplateVars$1) { + var val = shapeLabelTexttemplateVars$1[key](options, _xa, _ya); + if (val !== void 0) templateValues[key] = val; + } + } + text = Lib$1q.texttemplateStringForShapes( + options.label.texttemplate, + {}, + gd._fullLayout._d3locale, + templateValues + ); + } else { + text = options.label.text; + } + var labelGroupAttrs = { + "data-index": index2 + }; + var font2 = options.label.font; + var labelTextAttrs = { + "data-notex": 1 + }; + var labelGroup = shapeGroup.append("g").attr(labelGroupAttrs).classed("shape-label", true); + var labelText = labelGroup.append("text").attr(labelTextAttrs).classed("shape-label-text", true).text(text); + var shapex0, shapex1, shapey0, shapey1; + if (options.path) { + var d = getPathString$2(gd, options); + var polygons = readPaths$3(d, gd); + shapex0 = Infinity; + shapey0 = Infinity; + shapex1 = -Infinity; + shapey1 = -Infinity; + for (var i = 0; i < polygons.length; i++) { + for (var j = 0; j < polygons[i].length; j++) { + var p = polygons[i][j]; + for (var k = 1; k < p.length; k += 2) { + var _x = p[k]; + var _y = p[k + 1]; + shapex0 = Math.min(shapex0, _x); + shapex1 = Math.max(shapex1, _x); + shapey0 = Math.min(shapey0, _y); + shapey1 = Math.max(shapey1, _y); + } + } + } + } else { + var xa = Axes$k.getFromId(gd, options.xref); + var xShiftStart = options.x0shift; + var xShiftEnd = options.x1shift; + var xRefType = Axes$k.getRefType(options.xref); + var ya = Axes$k.getFromId(gd, options.yref); + var yShiftStart = options.y0shift; + var yShiftEnd = options.y1shift; + var yRefType = Axes$k.getRefType(options.yref); + var x2p = function(v, shift) { + var dataToPixel = helpers$v.getDataToPixel(gd, xa, shift, false, xRefType); + return dataToPixel(v); + }; + var y2p = function(v, shift) { + var dataToPixel = helpers$v.getDataToPixel(gd, ya, shift, true, yRefType); + return dataToPixel(v); + }; + shapex0 = x2p(options.x0, xShiftStart); + shapex1 = x2p(options.x1, xShiftEnd); + shapey0 = y2p(options.y0, yShiftStart); + shapey1 = y2p(options.y1, yShiftEnd); + } + var textangle = options.label.textangle; + if (textangle === "auto") { + if (options.type === "line") { + textangle = calcTextAngle(shapex0, shapey0, shapex1, shapey1); + } else { + textangle = 0; + } + } + labelText.call(function(s) { + s.call(Drawing$n.font, font2).attr({}); + svgTextUtils$a.convertToTspans(s, gd); + return s; + }); + var textBB = Drawing$n.bBox(labelText.node()); + var textPos = calcTextPosition(shapex0, shapey0, shapex1, shapey1, options, textangle, textBB); + var textx = textPos.textx; + var texty = textPos.texty; + var xanchor = textPos.xanchor; + labelText.attr({ + "text-anchor": { + left: "start", + center: "middle", + right: "end" + }[xanchor], + y: texty, + x: textx, + transform: "rotate(" + textangle + "," + textx + "," + texty + ")" + }).call(svgTextUtils$a.positionText, textx, texty); +}; +function calcTextAngle(shapex0, shapey0, shapex1, shapey1) { + var dy, dx; + dx = Math.abs(shapex1 - shapex0); + if (shapex1 >= shapex0) { + dy = shapey0 - shapey1; + } else { + dy = shapey1 - shapey0; + } + return -180 / Math.PI * Math.atan2(dy, dx); +} +function calcTextPosition(shapex0, shapey0, shapex1, shapey1, shapeOptions, actualTextAngle, textBB) { + var textPosition = shapeOptions.label.textposition; + var textAngle = shapeOptions.label.textangle; + var textPadding = shapeOptions.label.padding; + var shapeType = shapeOptions.type; + var textAngleRad = Math.PI / 180 * actualTextAngle; + var sinA = Math.sin(textAngleRad); + var cosA = Math.cos(textAngleRad); + var xanchor = shapeOptions.label.xanchor; + var yanchor = shapeOptions.label.yanchor; + var textx, texty, paddingX, paddingY; + if (shapeType === "line") { + if (textPosition === "start") { + textx = shapex0; + texty = shapey0; + } else if (textPosition === "end") { + textx = shapex1; + texty = shapey1; + } else { + textx = (shapex0 + shapex1) / 2; + texty = (shapey0 + shapey1) / 2; + } + if (xanchor === "auto") { + if (textPosition === "start") { + if (textAngle === "auto") { + if (shapex1 > shapex0) xanchor = "left"; + else if (shapex1 < shapex0) xanchor = "right"; + else xanchor = "center"; + } else { + if (shapex1 > shapex0) xanchor = "right"; + else if (shapex1 < shapex0) xanchor = "left"; + else xanchor = "center"; + } + } else if (textPosition === "end") { + if (textAngle === "auto") { + if (shapex1 > shapex0) xanchor = "right"; + else if (shapex1 < shapex0) xanchor = "left"; + else xanchor = "center"; + } else { + if (shapex1 > shapex0) xanchor = "left"; + else if (shapex1 < shapex0) xanchor = "right"; + else xanchor = "center"; + } + } else { + xanchor = "center"; + } + } + var paddingConstantsX = { left: 1, center: 0, right: -1 }; + var paddingConstantsY = { bottom: -1, middle: 0, top: 1 }; + if (textAngle === "auto") { + var paddingDirection = paddingConstantsY[yanchor]; + paddingX = -textPadding * sinA * paddingDirection; + paddingY = textPadding * cosA * paddingDirection; + } else { + var paddingDirectionX = paddingConstantsX[xanchor]; + var paddingDirectionY = paddingConstantsY[yanchor]; + paddingX = textPadding * paddingDirectionX; + paddingY = textPadding * paddingDirectionY; + } + textx = textx + paddingX; + texty = texty + paddingY; + } else { + paddingX = textPadding + 3; + if (textPosition.indexOf("right") !== -1) { + textx = Math.max(shapex0, shapex1) - paddingX; + if (xanchor === "auto") xanchor = "right"; + } else if (textPosition.indexOf("left") !== -1) { + textx = Math.min(shapex0, shapex1) + paddingX; + if (xanchor === "auto") xanchor = "left"; + } else { + textx = (shapex0 + shapex1) / 2; + if (xanchor === "auto") xanchor = "center"; + } + if (textPosition.indexOf("top") !== -1) { + texty = Math.min(shapey0, shapey1); + } else if (textPosition.indexOf("bottom") !== -1) { + texty = Math.max(shapey0, shapey1); + } else { + texty = (shapey0 + shapey1) / 2; + } + paddingY = textPadding; + if (yanchor === "bottom") { + texty = texty - paddingY; + } else if (yanchor === "top") { + texty = texty + paddingY; + } + } + var shiftFraction = FROM_TL$3[yanchor]; + var baselineAdjust = shapeOptions.label.font.size; + var textHeight = textBB.height; + var xshift = (textHeight * shiftFraction - baselineAdjust) * sinA; + var yshift = -(textHeight * shiftFraction - baselineAdjust) * cosA; + return { textx: textx + xshift, texty: texty + yshift, xanchor }; +} +var Lib$1p = libExports; +var strTranslate$6 = Lib$1p.strTranslate; +var dragElement$3 = dragelementExports; +var dragHelpers$1 = helpers$B; +var drawMode$1 = dragHelpers$1.drawMode; +var selectMode$2 = dragHelpers$1.selectMode; +var Registry$z = registry; +var Color$A = colorExports; +var constants$H = constants$K; +var i000 = constants$H.i000; +var i090 = constants$H.i090; +var i180 = constants$H.i180; +var i270 = constants$H.i270; +var handleOutline = handle_outline; +var clearOutlineControllers$2 = handleOutline.clearOutlineControllers; +var helpers$u = helpers$A; +var pointsOnRectangle = helpers$u.pointsOnRectangle; +var pointsOnEllipse = helpers$u.pointsOnEllipse; +var writePaths = helpers$u.writePaths; +var newShapes$1 = newshapes.newShapes; +var createShapeObj = newshapes.createShapeObj; +var newSelections$1 = newselections; +var drawLabel$2 = display_labels; +var display_outlines = function displayOutlines(polygons, outlines, dragOptions, nCalls) { + if (!nCalls) nCalls = 0; + var gd = dragOptions.gd; + function redraw() { + displayOutlines(polygons, outlines, dragOptions, nCalls++); + if (pointsOnEllipse(polygons[0]) || dragOptions.hasText) { + update2({ redrawing: true }); + } + } + function update2(opts) { + var updateObject = {}; + if (dragOptions.isActiveShape !== void 0) { + dragOptions.isActiveShape = false; + updateObject = newShapes$1(outlines, dragOptions); + } + if (dragOptions.isActiveSelection !== void 0) { + dragOptions.isActiveSelection = false; + updateObject = newSelections$1(outlines, dragOptions); + gd._fullLayout._reselect = true; + } + if (Object.keys(updateObject).length) { + Registry$z.call((opts || {}).redrawing ? "relayout" : "_guiRelayout", gd, updateObject); + } + } + var fullLayout = gd._fullLayout; + var zoomLayer = fullLayout._zoomlayer; + var dragmode = dragOptions.dragmode; + var isDrawMode = drawMode$1(dragmode); + var isSelectMode = selectMode$2(dragmode); + if (isDrawMode || isSelectMode) { + gd._fullLayout._outlining = true; + } + clearOutlineControllers$2(gd); + outlines.attr("d", writePaths(polygons)); + var vertexDragOptions; + var groupDragOptions; + var indexI; + var indexJ; + var copyPolygons; + if (!nCalls && (dragOptions.isActiveShape || dragOptions.isActiveSelection)) { + copyPolygons = recordPositions([], polygons); + var g = zoomLayer.append("g").attr("class", "outline-controllers"); + addVertexControllers(g); + addGroupControllers(); + } + if (isDrawMode && dragOptions.hasText) { + var shapeGroup = zoomLayer.select(".label-temp"); + var shapeOptions = createShapeObj(outlines, dragOptions, dragOptions.dragmode); + drawLabel$2(gd, "label-temp", shapeOptions, shapeGroup); + } + function startDragVertex(evt) { + indexI = +evt.srcElement.getAttribute("data-i"); + indexJ = +evt.srcElement.getAttribute("data-j"); + vertexDragOptions[indexI][indexJ].moveFn = moveVertexController; + } + function moveVertexController(dx, dy) { + if (!polygons.length) return; + var x0 = copyPolygons[indexI][indexJ][1]; + var y0 = copyPolygons[indexI][indexJ][2]; + var cell = polygons[indexI]; + var len = cell.length; + if (pointsOnRectangle(cell)) { + var _dx = dx; + var _dy = dy; + if (dragOptions.isActiveSelection) { + var nextPoint = getNextPoint(cell, indexJ); + if (nextPoint[1] === cell[indexJ][1]) { + _dy = 0; + } else { + _dx = 0; + } + } + for (var q = 0; q < len; q++) { + if (q === indexJ) continue; + var pos = cell[q]; + if (pos[1] === cell[indexJ][1]) { + pos[1] = x0 + _dx; + } + if (pos[2] === cell[indexJ][2]) { + pos[2] = y0 + _dy; + } + } + cell[indexJ][1] = x0 + _dx; + cell[indexJ][2] = y0 + _dy; + if (!pointsOnRectangle(cell)) { + for (var j = 0; j < len; j++) { + for (var k = 0; k < cell[j].length; k++) { + cell[j][k] = copyPolygons[indexI][j][k]; + } + } + } + } else { + cell[indexJ][1] = x0 + dx; + cell[indexJ][2] = y0 + dy; + } + redraw(); + } + function endDragVertexController() { + update2(); + } + function removeVertex() { + if (!polygons.length) return; + if (!polygons[indexI]) return; + if (!polygons[indexI].length) return; + var newPolygon = []; + for (var j = 0; j < polygons[indexI].length; j++) { + if (j !== indexJ) { + newPolygon.push( + polygons[indexI][j] + ); + } + } + if (newPolygon.length > 1 && !(newPolygon.length === 2 && newPolygon[1][0] === "Z")) { + if (indexJ === 0) { + newPolygon[0][0] = "M"; + } + polygons[indexI] = newPolygon; + redraw(); + update2(); + } + } + function clickVertexController(numClicks, evt) { + if (numClicks === 2) { + indexI = +evt.srcElement.getAttribute("data-i"); + indexJ = +evt.srcElement.getAttribute("data-j"); + var cell = polygons[indexI]; + if (!pointsOnRectangle(cell) && !pointsOnEllipse(cell)) { + removeVertex(); + } + } + } + function addVertexControllers(g2) { + vertexDragOptions = []; + for (var i = 0; i < polygons.length; i++) { + var cell = polygons[i]; + var onRect = pointsOnRectangle(cell); + var onEllipse = !onRect && pointsOnEllipse(cell); + vertexDragOptions[i] = []; + var len = cell.length; + for (var j = 0; j < len; j++) { + if (cell[j][0] === "Z") continue; + if (onEllipse && j !== i000 && j !== i090 && j !== i180 && j !== i270) { + continue; + } + var rectSelection = onRect && dragOptions.isActiveSelection; + var nextPoint; + if (rectSelection) nextPoint = getNextPoint(cell, j); + var x = cell[j][1]; + var y = cell[j][2]; + var vertex = g2.append(rectSelection ? "rect" : "circle").attr("data-i", i).attr("data-j", j).style({ + fill: Color$A.background, + stroke: Color$A.defaultLine, + "stroke-width": 1, + "shape-rendering": "crispEdges" + }); + if (rectSelection) { + var dx = nextPoint[1] - x; + var dy = nextPoint[2] - y; + var width = dy ? 5 : Math.max(Math.min(25, Math.abs(dx) - 5), 5); + var height = dx ? 5 : Math.max(Math.min(25, Math.abs(dy) - 5), 5); + vertex.classed(dy ? "cursor-ew-resize" : "cursor-ns-resize", true).attr("width", width).attr("height", height).attr("x", x - width / 2).attr("y", y - height / 2).attr("transform", strTranslate$6(dx / 2, dy / 2)); + } else { + vertex.classed("cursor-grab", true).attr("r", 5).attr("cx", x).attr("cy", y); + } + vertexDragOptions[i][j] = { + element: vertex.node(), + gd, + prepFn: startDragVertex, + doneFn: endDragVertexController, + clickFn: clickVertexController + }; + dragElement$3.init(vertexDragOptions[i][j]); + } + } + } + function moveGroup(dx, dy) { + if (!polygons.length) return; + for (var i = 0; i < polygons.length; i++) { + for (var j = 0; j < polygons[i].length; j++) { + for (var k = 0; k + 2 < polygons[i][j].length; k += 2) { + polygons[i][j][k + 1] = copyPolygons[i][j][k + 1] + dx; + polygons[i][j][k + 2] = copyPolygons[i][j][k + 2] + dy; + } + } + } + } + function moveGroupController(dx, dy) { + moveGroup(dx, dy); + redraw(); + } + function startDragGroupController(evt) { + indexI = +evt.srcElement.getAttribute("data-i"); + if (!indexI) indexI = 0; + groupDragOptions[indexI].moveFn = moveGroupController; + } + function endDragGroupController() { + update2(); + } + function clickGroupController(numClicks) { + if (numClicks === 2) { + eraseActiveSelection(gd); + } + } + function addGroupControllers() { + groupDragOptions = []; + if (!polygons.length) return; + var i = 0; + groupDragOptions[i] = { + element: outlines[0][0], + gd, + prepFn: startDragGroupController, + doneFn: endDragGroupController, + clickFn: clickGroupController + }; + dragElement$3.init(groupDragOptions[i]); + } +}; +function recordPositions(polygonsOut, polygonsIn) { + for (var i = 0; i < polygonsIn.length; i++) { + var cell = polygonsIn[i]; + polygonsOut[i] = []; + for (var j = 0; j < cell.length; j++) { + polygonsOut[i][j] = []; + for (var k = 0; k < cell[j].length; k++) { + polygonsOut[i][j][k] = cell[j][k]; + } + } + } + return polygonsOut; +} +function getNextPoint(cell, j) { + var x = cell[j][1]; + var y = cell[j][2]; + var len = cell.length; + var nextJ, nextX, nextY; + nextJ = (j + 1) % len; + nextX = cell[nextJ][1]; + nextY = cell[nextJ][2]; + if (nextX === x && nextY === y) { + nextJ = (j + 2) % len; + nextX = cell[nextJ][1]; + nextY = cell[nextJ][2]; + } + return [nextJ, nextX, nextY]; +} +function eraseActiveSelection(gd) { + if (!selectMode$2(gd._fullLayout.dragmode)) return; + clearOutlineControllers$2(gd); + var id = gd._fullLayout._activeSelectionIndex; + var selections2 = (gd.layout || {}).selections || []; + if (id < selections2.length) { + var list = []; + for (var q = 0; q < selections2.length; q++) { + if (q !== id) { + list.push(selections2[q]); + } + } + delete gd._fullLayout._activeSelectionIndex; + var erasedSelection = gd._fullLayout.selections[id]; + gd._fullLayout._deselect = { + xref: erasedSelection.xref, + yref: erasedSelection.yref + }; + Registry$z.call("_guiRelayout", gd, { + selections: list + }); + } +} +var d3$q = d3Exports; +var Registry$y = registry; +var Lib$1o = libExports; +var Axes$j = axesExports; +var readPaths$2 = helpers$A.readPaths; +var displayOutlines$2 = display_outlines; +var drawLabel$1 = display_labels; +var clearOutlineControllers$1 = handle_outline.clearOutlineControllers; +var Color$z = colorExports; +var Drawing$m = drawingExports; +var arrayEditor$5 = plot_template.arrayEditor; +var dragElement$2 = dragelementExports; +var setCursor$2 = setcursor; +var constants$G = constants$I; +var helpers$t = helpers$w; +var getPathString$1 = helpers$t.getPathString; +var draw_1$3 = { + draw: draw$c, + drawOne: drawOne$2, + eraseActiveShape: eraseActiveShape$2 +}; +function draw$c(gd) { + var fullLayout = gd._fullLayout; + fullLayout._shapeUpperLayer.selectAll("path").remove(); + fullLayout._shapeLowerLayer.selectAll("path").remove(); + fullLayout._shapeUpperLayer.selectAll("text").remove(); + fullLayout._shapeLowerLayer.selectAll("text").remove(); + for (var k in fullLayout._plots) { + var shapelayer = fullLayout._plots[k].shapelayer; + if (shapelayer) { + shapelayer.selectAll("path").remove(); + shapelayer.selectAll("text").remove(); + } + } + for (var i = 0; i < fullLayout.shapes.length; i++) { + if (fullLayout.shapes[i].visible === true) { + drawOne$2(gd, i); + } + } +} +function shouldSkipEdits(gd) { + return !!gd._fullLayout._outlining; +} +function couldHaveActiveShape(gd) { + return !gd._context.edits.shapePosition; +} +function drawOne$2(gd, index2) { + gd._fullLayout._paperdiv.selectAll('.shapelayer [data-index="' + index2 + '"]').remove(); + var o = helpers$t.makeShapesOptionsAndPlotinfo(gd, index2); + var options = o.options; + var plotinfo = o.plotinfo; + if (!options._input || options.visible !== true) return; + if (options.layer === "above") { + drawShape(gd._fullLayout._shapeUpperLayer); + } else if (options.xref === "paper" || options.yref === "paper") { + drawShape(gd._fullLayout._shapeLowerLayer); + } else if (options.layer === "between") { + drawShape(plotinfo.shapelayerBetween); + } else { + if (plotinfo._hadPlotinfo) { + var mainPlot = plotinfo.mainplotinfo || plotinfo; + drawShape(mainPlot.shapelayer); + } else { + drawShape(gd._fullLayout._shapeLowerLayer); + } + } + function drawShape(shapeLayer) { + var d = getPathString$1(gd, options); + var attrs2 = { + "data-index": index2, + "fill-rule": options.fillrule, + d + }; + var opacity = options.opacity; + var fillColor = options.fillcolor; + var lineColor = options.line.width ? options.line.color : "rgba(0,0,0,0)"; + var lineWidth = options.line.width; + var lineDash = options.line.dash; + if (!lineWidth && options.editable === true) { + lineWidth = 5; + lineDash = "solid"; + } + var isOpen = d[d.length - 1] !== "Z"; + var isActiveShape = couldHaveActiveShape(gd) && options.editable && gd._fullLayout._activeShapeIndex === index2; + if (isActiveShape) { + fillColor = isOpen ? "rgba(0,0,0,0)" : gd._fullLayout.activeshape.fillcolor; + opacity = gd._fullLayout.activeshape.opacity; + } + var shapeGroup = shapeLayer.append("g").classed("shape-group", true).attr({ "data-index": index2 }); + var path = shapeGroup.append("path").attr(attrs2).style("opacity", opacity).call(Color$z.stroke, lineColor).call(Color$z.fill, fillColor).call(Drawing$m.dashLine, lineDash, lineWidth); + setClipPath$1(shapeGroup, gd, options); + drawLabel$1(gd, index2, options, shapeGroup); + var editHelpers; + if (isActiveShape || gd._context.edits.shapePosition) editHelpers = arrayEditor$5(gd.layout, "shapes", options); + if (isActiveShape) { + path.style({ + cursor: "move" + }); + var dragOptions = { + element: path.node(), + plotinfo, + gd, + editHelpers, + hasText: options.label.text || options.label.texttemplate, + isActiveShape: true + // i.e. to enable controllers + }; + var polygons = readPaths$2(d, gd); + displayOutlines$2(polygons, path, dragOptions); + } else { + if (gd._context.edits.shapePosition) { + setupDragElement(gd, path, options, index2, shapeLayer, editHelpers); + } else if (options.editable === true) { + path.style( + "pointer-events", + isOpen || Color$z.opacity(fillColor) * opacity <= 0.5 ? "stroke" : "all" + ); + } + } + path.node().addEventListener("click", function() { + return activateShape(gd, path); + }); + } +} +function setClipPath$1(shapePath, gd, shapeOptions) { + var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, "").replace(/[xyz][1-9]* *domain/g, ""); + Drawing$m.setClipUrl( + shapePath, + clipAxes ? "clip" + gd._fullLayout._uid + clipAxes : null, + gd + ); +} +function setupDragElement(gd, shapePath, shapeOptions, index2, shapeLayer, editHelpers) { + var MINWIDTH = 10; + var MINHEIGHT = 10; + var xPixelSized = shapeOptions.xsizemode === "pixel"; + var yPixelSized = shapeOptions.ysizemode === "pixel"; + var isLine = shapeOptions.type === "line"; + var isPath2 = shapeOptions.type === "path"; + var modifyItem = editHelpers.modifyItem; + var x0, y0, x1, y1, xAnchor, yAnchor; + var n0, s0, w0, e0, optN, optS, optW, optE; + var pathIn; + var shapeGroup = d3$q.select(shapePath.node().parentNode); + var xa = Axes$j.getFromId(gd, shapeOptions.xref); + var xRefType = Axes$j.getRefType(shapeOptions.xref); + var ya = Axes$j.getFromId(gd, shapeOptions.yref); + var yRefType = Axes$j.getRefType(shapeOptions.yref); + var shiftXStart = shapeOptions.x0shift; + var shiftXEnd = shapeOptions.x1shift; + var shiftYStart = shapeOptions.y0shift; + var shiftYEnd = shapeOptions.y1shift; + var x2p = function(v, shift) { + var dataToPixel = helpers$t.getDataToPixel(gd, xa, shift, false, xRefType); + return dataToPixel(v); + }; + var y2p = function(v, shift) { + var dataToPixel = helpers$t.getDataToPixel(gd, ya, shift, true, yRefType); + return dataToPixel(v); + }; + var p2x = helpers$t.getPixelToData(gd, xa, false, xRefType); + var p2y = helpers$t.getPixelToData(gd, ya, true, yRefType); + var sensoryElement = obtainSensoryElement(); + var dragOptions = { + element: sensoryElement.node(), + gd, + prepFn: startDrag, + doneFn: endDrag, + clickFn: abortDrag + }; + var dragMode; + dragElement$2.init(dragOptions); + sensoryElement.node().onmousemove = updateDragMode; + function obtainSensoryElement() { + return isLine ? createLineDragHandles() : shapePath; + } + function createLineDragHandles() { + var minSensoryWidth = 10; + var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth); + var g = shapeLayer.append("g").attr("data-index", index2).attr("drag-helper", true); + g.append("path").attr("d", shapePath.attr("d")).style({ + cursor: "move", + "stroke-width": sensoryWidth, + "stroke-opacity": "0" + // ensure not visible + }); + var circleStyle = { + "fill-opacity": "0" + // ensure not visible + }; + var circleRadius = Math.max(sensoryWidth / 2, minSensoryWidth); + g.append("circle").attr({ + "data-line-point": "start-point", + cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0, shiftXStart), + cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0, shiftYStart), + r: circleRadius + }).style(circleStyle).classed("cursor-grab", true); + g.append("circle").attr({ + "data-line-point": "end-point", + cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1, shiftXEnd), + cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1, shiftYEnd), + r: circleRadius + }).style(circleStyle).classed("cursor-grab", true); + return g; + } + function updateDragMode(evt) { + if (shouldSkipEdits(gd)) { + dragMode = null; + return; + } + if (isLine) { + if (evt.target.tagName === "path") { + dragMode = "move"; + } else { + dragMode = evt.target.attributes["data-line-point"].value === "start-point" ? "resize-over-start-point" : "resize-over-end-point"; + } + } else { + var dragBBox = dragOptions.element.getBoundingClientRect(); + var w = dragBBox.right - dragBBox.left; + var h = dragBBox.bottom - dragBBox.top; + var x = evt.clientX - dragBBox.left; + var y = evt.clientY - dragBBox.top; + var cursor2 = !isPath2 && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey ? dragElement$2.getCursor(x / w, 1 - y / h) : "move"; + setCursor$2(shapePath, cursor2); + dragMode = cursor2.split("-")[0]; + } + } + function startDrag(evt) { + if (shouldSkipEdits(gd)) return; + if (xPixelSized) { + xAnchor = x2p(shapeOptions.xanchor); + } + if (yPixelSized) { + yAnchor = y2p(shapeOptions.yanchor); + } + if (shapeOptions.type === "path") { + pathIn = shapeOptions.path; + } else { + x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0); + y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0); + x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1); + y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1); + } + if (x0 < x1) { + w0 = x0; + optW = "x0"; + e0 = x1; + optE = "x1"; + } else { + w0 = x1; + optW = "x1"; + e0 = x0; + optE = "x0"; + } + if (!yPixelSized && y0 < y1 || yPixelSized && y0 > y1) { + n0 = y0; + optN = "y0"; + s0 = y1; + optS = "y1"; + } else { + n0 = y1; + optN = "y1"; + s0 = y0; + optS = "y0"; + } + updateDragMode(evt); + renderVisualCues(shapeLayer, shapeOptions); + deactivateClipPathTemporarily(shapePath, shapeOptions, gd); + dragOptions.moveFn = dragMode === "move" ? moveShape : resizeShape; + dragOptions.altKey = evt.altKey; + } + function endDrag() { + if (shouldSkipEdits(gd)) return; + setCursor$2(shapePath); + removeVisualCues(shapeLayer); + setClipPath$1(shapePath, gd, shapeOptions); + Registry$y.call("_guiRelayout", gd, editHelpers.getUpdateObj()); + } + function abortDrag() { + if (shouldSkipEdits(gd)) return; + removeVisualCues(shapeLayer); + } + function moveShape(dx, dy) { + if (shapeOptions.type === "path") { + var noOp = function(coord) { + return coord; + }; + var moveX = noOp; + var moveY = noOp; + if (xPixelSized) { + modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); + } else { + moveX = function moveX2(x) { + return p2x(x2p(x) + dx); + }; + if (xa && xa.type === "date") moveX = helpers$t.encodeDate(moveX); + } + if (yPixelSized) { + modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); + } else { + moveY = function moveY2(y) { + return p2y(y2p(y) + dy); + }; + if (ya && ya.type === "date") moveY = helpers$t.encodeDate(moveY); + } + modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY)); + } else { + if (xPixelSized) { + modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); + } else { + modifyItem("x0", shapeOptions.x0 = p2x(x0 + dx)); + modifyItem("x1", shapeOptions.x1 = p2x(x1 + dx)); + } + if (yPixelSized) { + modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); + } else { + modifyItem("y0", shapeOptions.y0 = p2y(y0 + dy)); + modifyItem("y1", shapeOptions.y1 = p2y(y1 + dy)); + } + } + shapePath.attr("d", getPathString$1(gd, shapeOptions)); + renderVisualCues(shapeLayer, shapeOptions); + drawLabel$1(gd, index2, shapeOptions, shapeGroup); + } + function resizeShape(dx, dy) { + if (isPath2) { + var noOp = function(coord) { + return coord; + }; + var moveX = noOp; + var moveY = noOp; + if (xPixelSized) { + modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); + } else { + moveX = function moveX2(x) { + return p2x(x2p(x) + dx); + }; + if (xa && xa.type === "date") moveX = helpers$t.encodeDate(moveX); + } + if (yPixelSized) { + modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); + } else { + moveY = function moveY2(y) { + return p2y(y2p(y) + dy); + }; + if (ya && ya.type === "date") moveY = helpers$t.encodeDate(moveY); + } + modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY)); + } else if (isLine) { + if (dragMode === "resize-over-start-point") { + var newX0 = x0 + dx; + var newY0 = yPixelSized ? y0 - dy : y0 + dy; + modifyItem("x0", shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0)); + modifyItem("y0", shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0)); + } else if (dragMode === "resize-over-end-point") { + var newX1 = x1 + dx; + var newY1 = yPixelSized ? y1 - dy : y1 + dy; + modifyItem("x1", shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1)); + modifyItem("y1", shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1)); + } + } else { + var has = function(str2) { + return dragMode.indexOf(str2) !== -1; + }; + var hasN = has("n"); + var hasS = has("s"); + var hasW = has("w"); + var hasE = has("e"); + var newN = hasN ? n0 + dy : n0; + var newS = hasS ? s0 + dy : s0; + var newW = hasW ? w0 + dx : w0; + var newE = hasE ? e0 + dx : e0; + if (yPixelSized) { + if (hasN) newN = n0 - dy; + if (hasS) newS = s0 - dy; + } + if (!yPixelSized && newS - newN > MINHEIGHT || yPixelSized && newN - newS > MINHEIGHT) { + modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN)); + modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS)); + } + if (newE - newW > MINWIDTH) { + modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW)); + modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE)); + } + } + shapePath.attr("d", getPathString$1(gd, shapeOptions)); + renderVisualCues(shapeLayer, shapeOptions); + drawLabel$1(gd, index2, shapeOptions, shapeGroup); + } + function renderVisualCues(shapeLayer2, shapeOptions2) { + if (xPixelSized || yPixelSized) { + renderAnchor(); + } + function renderAnchor() { + var isNotPath = shapeOptions2.type !== "path"; + var visualCues = shapeLayer2.selectAll(".visual-cue").data([0]); + var strokeWidth = 1; + visualCues.enter().append("path").attr({ + fill: "#fff", + "fill-rule": "evenodd", + stroke: "#000", + "stroke-width": strokeWidth + }).classed("visual-cue", true); + var posX = x2p( + xPixelSized ? shapeOptions2.xanchor : Lib$1o.midRange( + isNotPath ? [shapeOptions2.x0, shapeOptions2.x1] : helpers$t.extractPathCoords(shapeOptions2.path, constants$G.paramIsX) + ) + ); + var posY = y2p( + yPixelSized ? shapeOptions2.yanchor : Lib$1o.midRange( + isNotPath ? [shapeOptions2.y0, shapeOptions2.y1] : helpers$t.extractPathCoords(shapeOptions2.path, constants$G.paramIsY) + ) + ); + posX = helpers$t.roundPositionForSharpStrokeRendering(posX, strokeWidth); + posY = helpers$t.roundPositionForSharpStrokeRendering(posY, strokeWidth); + if (xPixelSized && yPixelSized) { + var crossPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z"; + visualCues.attr("d", crossPath); + } else if (xPixelSized) { + var vBarPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 9 - strokeWidth) + "v18 h2 v-18 Z"; + visualCues.attr("d", vBarPath); + } else { + var hBarPath = "M" + (posX - 9 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h18 v2 h-18 Z"; + visualCues.attr("d", hBarPath); + } + } + } + function removeVisualCues(shapeLayer2) { + shapeLayer2.selectAll(".visual-cue").remove(); + } + function deactivateClipPathTemporarily(shapePath2, shapeOptions2, gd2) { + var xref = shapeOptions2.xref; + var yref = shapeOptions2.yref; + var xa2 = Axes$j.getFromId(gd2, xref); + var ya2 = Axes$j.getFromId(gd2, yref); + var clipAxes = ""; + if (xref !== "paper" && !xa2.autorange) clipAxes += xref; + if (yref !== "paper" && !ya2.autorange) clipAxes += yref; + Drawing$m.setClipUrl( + shapePath2, + clipAxes ? "clip" + gd2._fullLayout._uid + clipAxes : null, + gd2 + ); + } +} +function movePath(pathIn, moveX, moveY) { + return pathIn.replace(constants$G.segmentRE, function(segment2) { + var paramNumber = 0; + var segmentType = segment2.charAt(0); + var xParams = constants$G.paramIsX[segmentType]; + var yParams = constants$G.paramIsY[segmentType]; + var nParams = constants$G.numParams[segmentType]; + var paramString = segment2.substr(1).replace(constants$G.paramRE, function(param) { + if (paramNumber >= nParams) return param; + if (xParams[paramNumber]) param = moveX(param); + else if (yParams[paramNumber]) param = moveY(param); + paramNumber++; + return param; + }); + return segmentType + paramString; + }); +} +function activateShape(gd, path) { + if (!couldHaveActiveShape(gd)) return; + var element = path.node(); + var id = +element.getAttribute("data-index"); + if (id >= 0) { + if (id === gd._fullLayout._activeShapeIndex) { + deactivateShape(gd); + return; + } + gd._fullLayout._activeShapeIndex = id; + gd._fullLayout._deactivateShape = deactivateShape; + draw$c(gd); + } +} +function deactivateShape(gd) { + if (!couldHaveActiveShape(gd)) return; + var id = gd._fullLayout._activeShapeIndex; + if (id >= 0) { + clearOutlineControllers$1(gd); + delete gd._fullLayout._activeShapeIndex; + draw$c(gd); + } +} +function eraseActiveShape$2(gd) { + if (!couldHaveActiveShape(gd)) return; + clearOutlineControllers$1(gd); + var id = gd._fullLayout._activeShapeIndex; + var shapes2 = (gd.layout || {}).shapes || []; + if (id < shapes2.length) { + var list = []; + for (var q = 0; q < shapes2.length; q++) { + if (q !== id) { + list.push(shapes2[q]); + } + } + delete gd._fullLayout._activeShapeIndex; + return Registry$y.call("_guiRelayout", gd, { + shapes: list + }); + } +} +var Registry$x = registry; +var Plots$9 = plotsExports; +var axisIds$6 = axis_ids; +var Icons$1 = ploticon; +var eraseActiveShape$1 = draw_1$3.eraseActiveShape; +var Lib$1n = libExports; +var _$1 = Lib$1n._; +var modeBarButtons$2 = buttons.exports = {}; +modeBarButtons$2.toImage = { + name: "toImage", + title: function(gd) { + var opts = gd._context.toImageButtonOptions || {}; + var format2 = opts.format || "png"; + return format2 === "png" ? _$1(gd, "Download plot as a png") : ( + // legacy text + _$1(gd, "Download plot") + ); + }, + icon: Icons$1.camera, + click: function(gd) { + var toImageButtonOptions = gd._context.toImageButtonOptions; + var opts = { format: toImageButtonOptions.format || "png" }; + Lib$1n.notifier(_$1(gd, "Taking snapshot - this may take a few seconds"), "long"); + if (opts.format !== "svg" && Lib$1n.isIE()) { + Lib$1n.notifier(_$1(gd, "IE only supports svg. Changing format to svg."), "long"); + opts.format = "svg"; + } + ["filename", "width", "height", "scale"].forEach(function(key) { + if (key in toImageButtonOptions) { + opts[key] = toImageButtonOptions[key]; + } + }); + Registry$x.call("downloadImage", gd, opts).then(function(filename) { + Lib$1n.notifier(_$1(gd, "Snapshot succeeded") + " - " + filename, "long"); + }).catch(function() { + Lib$1n.notifier(_$1(gd, "Sorry, there was a problem downloading your snapshot!"), "long"); + }); + } +}; +modeBarButtons$2.sendDataToCloud = { + name: "sendDataToCloud", + title: function(gd) { + return _$1(gd, "Edit in Chart Studio"); + }, + icon: Icons$1.disk, + click: function(gd) { + Plots$9.sendDataToCloud(gd); + } +}; +modeBarButtons$2.editInChartStudio = { + name: "editInChartStudio", + title: function(gd) { + return _$1(gd, "Edit in Chart Studio"); + }, + icon: Icons$1.pencil, + click: function(gd) { + Plots$9.sendDataToCloud(gd); + } +}; +modeBarButtons$2.zoom2d = { + name: "zoom2d", + _cat: "zoom", + title: function(gd) { + return _$1(gd, "Zoom"); + }, + attr: "dragmode", + val: "zoom", + icon: Icons$1.zoombox, + click: handleCartesian +}; +modeBarButtons$2.pan2d = { + name: "pan2d", + _cat: "pan", + title: function(gd) { + return _$1(gd, "Pan"); + }, + attr: "dragmode", + val: "pan", + icon: Icons$1.pan, + click: handleCartesian +}; +modeBarButtons$2.select2d = { + name: "select2d", + _cat: "select", + title: function(gd) { + return _$1(gd, "Box Select"); + }, + attr: "dragmode", + val: "select", + icon: Icons$1.selectbox, + click: handleCartesian +}; +modeBarButtons$2.lasso2d = { + name: "lasso2d", + _cat: "lasso", + title: function(gd) { + return _$1(gd, "Lasso Select"); + }, + attr: "dragmode", + val: "lasso", + icon: Icons$1.lasso, + click: handleCartesian +}; +modeBarButtons$2.drawclosedpath = { + name: "drawclosedpath", + title: function(gd) { + return _$1(gd, "Draw closed freeform"); + }, + attr: "dragmode", + val: "drawclosedpath", + icon: Icons$1.drawclosedpath, + click: handleCartesian +}; +modeBarButtons$2.drawopenpath = { + name: "drawopenpath", + title: function(gd) { + return _$1(gd, "Draw open freeform"); + }, + attr: "dragmode", + val: "drawopenpath", + icon: Icons$1.drawopenpath, + click: handleCartesian +}; +modeBarButtons$2.drawline = { + name: "drawline", + title: function(gd) { + return _$1(gd, "Draw line"); + }, + attr: "dragmode", + val: "drawline", + icon: Icons$1.drawline, + click: handleCartesian +}; +modeBarButtons$2.drawrect = { + name: "drawrect", + title: function(gd) { + return _$1(gd, "Draw rectangle"); + }, + attr: "dragmode", + val: "drawrect", + icon: Icons$1.drawrect, + click: handleCartesian +}; +modeBarButtons$2.drawcircle = { + name: "drawcircle", + title: function(gd) { + return _$1(gd, "Draw circle"); + }, + attr: "dragmode", + val: "drawcircle", + icon: Icons$1.drawcircle, + click: handleCartesian +}; +modeBarButtons$2.eraseshape = { + name: "eraseshape", + title: function(gd) { + return _$1(gd, "Erase active shape"); + }, + icon: Icons$1.eraseshape, + click: eraseActiveShape$1 +}; +modeBarButtons$2.zoomIn2d = { + name: "zoomIn2d", + _cat: "zoomin", + title: function(gd) { + return _$1(gd, "Zoom in"); + }, + attr: "zoom", + val: "in", + icon: Icons$1.zoom_plus, + click: handleCartesian +}; +modeBarButtons$2.zoomOut2d = { + name: "zoomOut2d", + _cat: "zoomout", + title: function(gd) { + return _$1(gd, "Zoom out"); + }, + attr: "zoom", + val: "out", + icon: Icons$1.zoom_minus, + click: handleCartesian +}; +modeBarButtons$2.autoScale2d = { + name: "autoScale2d", + _cat: "autoscale", + title: function(gd) { + return _$1(gd, "Autoscale"); + }, + attr: "zoom", + val: "auto", + icon: Icons$1.autoscale, + click: handleCartesian +}; +modeBarButtons$2.resetScale2d = { + name: "resetScale2d", + _cat: "resetscale", + title: function(gd) { + return _$1(gd, "Reset axes"); + }, + attr: "zoom", + val: "reset", + icon: Icons$1.home, + click: handleCartesian +}; +modeBarButtons$2.hoverClosestCartesian = { + name: "hoverClosestCartesian", + _cat: "hoverclosest", + title: function(gd) { + return _$1(gd, "Show closest data on hover"); + }, + attr: "hovermode", + val: "closest", + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: handleCartesian +}; +modeBarButtons$2.hoverCompareCartesian = { + name: "hoverCompareCartesian", + _cat: "hoverCompare", + title: function(gd) { + return _$1(gd, "Compare data on hover"); + }, + attr: "hovermode", + val: function(gd) { + return gd._fullLayout._isHoriz ? "y" : "x"; + }, + icon: Icons$1.tooltip_compare, + gravity: "ne", + click: handleCartesian +}; +function handleCartesian(gd, ev) { + var button = ev.currentTarget; + var astr = button.getAttribute("data-attr"); + var val = button.getAttribute("data-val") || true; + var fullLayout = gd._fullLayout; + var aobj = {}; + var axList = axisIds$6.list(gd, null, true); + var allSpikesEnabled = fullLayout._cartesianSpikesEnabled; + var ax, i; + if (astr === "zoom") { + var mag = val === "in" ? 0.5 : 2; + var r0 = (1 + mag) / 2; + var r1 = (1 - mag) / 2; + var axName; + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + if (!ax.fixedrange) { + axName = ax._name; + if (val === "auto") { + aobj[axName + ".autorange"] = true; + } else if (val === "reset") { + if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) { + aobj[axName + ".autorange"] = true; + } else if (ax._rangeInitial0 === void 0) { + aobj[axName + ".autorange"] = ax._autorangeInitial; + aobj[axName + ".range"] = [null, ax._rangeInitial1]; + } else if (ax._rangeInitial1 === void 0) { + aobj[axName + ".range"] = [ax._rangeInitial0, null]; + aobj[axName + ".autorange"] = ax._autorangeInitial; + } else { + aobj[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1]; + } + if (ax._showSpikeInitial !== void 0) { + aobj[axName + ".showspikes"] = ax._showSpikeInitial; + if (allSpikesEnabled === "on" && !ax._showSpikeInitial) { + allSpikesEnabled = "off"; + } + } + } else { + var rangeNow = [ + ax.r2l(ax.range[0]), + ax.r2l(ax.range[1]) + ]; + var rangeNew = [ + r0 * rangeNow[0] + r1 * rangeNow[1], + r0 * rangeNow[1] + r1 * rangeNow[0] + ]; + aobj[axName + ".range[0]"] = ax.l2r(rangeNew[0]); + aobj[axName + ".range[1]"] = ax.l2r(rangeNew[1]); + } + } + } + } else { + if (astr === "hovermode" && (val === "x" || val === "y")) { + val = fullLayout._isHoriz ? "y" : "x"; + button.setAttribute("data-val", val); + } + aobj[astr] = val; + } + fullLayout._cartesianSpikesEnabled = allSpikesEnabled; + Registry$x.call("_guiRelayout", gd, aobj); +} +modeBarButtons$2.zoom3d = { + name: "zoom3d", + _cat: "zoom", + title: function(gd) { + return _$1(gd, "Zoom"); + }, + attr: "scene.dragmode", + val: "zoom", + icon: Icons$1.zoombox, + click: handleDrag3d +}; +modeBarButtons$2.pan3d = { + name: "pan3d", + _cat: "pan", + title: function(gd) { + return _$1(gd, "Pan"); + }, + attr: "scene.dragmode", + val: "pan", + icon: Icons$1.pan, + click: handleDrag3d +}; +modeBarButtons$2.orbitRotation = { + name: "orbitRotation", + title: function(gd) { + return _$1(gd, "Orbital rotation"); + }, + attr: "scene.dragmode", + val: "orbit", + icon: Icons$1["3d_rotate"], + click: handleDrag3d +}; +modeBarButtons$2.tableRotation = { + name: "tableRotation", + title: function(gd) { + return _$1(gd, "Turntable rotation"); + }, + attr: "scene.dragmode", + val: "turntable", + icon: Icons$1["z-axis"], + click: handleDrag3d +}; +function handleDrag3d(gd, ev) { + var button = ev.currentTarget; + var attr = button.getAttribute("data-attr"); + var val = button.getAttribute("data-val") || true; + var sceneIds = gd._fullLayout._subplots.gl3d || []; + var layoutUpdate = {}; + var parts = attr.split("."); + for (var i = 0; i < sceneIds.length; i++) { + layoutUpdate[sceneIds[i] + "." + parts[1]] = val; + } + var val2d = val === "pan" ? val : "zoom"; + layoutUpdate.dragmode = val2d; + Registry$x.call("_guiRelayout", gd, layoutUpdate); +} +modeBarButtons$2.resetCameraDefault3d = { + name: "resetCameraDefault3d", + _cat: "resetCameraDefault", + title: function(gd) { + return _$1(gd, "Reset camera to default"); + }, + attr: "resetDefault", + icon: Icons$1.home, + click: handleCamera3d +}; +modeBarButtons$2.resetCameraLastSave3d = { + name: "resetCameraLastSave3d", + _cat: "resetCameraLastSave", + title: function(gd) { + return _$1(gd, "Reset camera to last save"); + }, + attr: "resetLastSave", + icon: Icons$1.movie, + click: handleCamera3d +}; +function handleCamera3d(gd, ev) { + var button = ev.currentTarget; + var attr = button.getAttribute("data-attr"); + var resetLastSave = attr === "resetLastSave"; + var resetDefault = attr === "resetDefault"; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d || []; + var aobj = {}; + for (var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i]; + var camera = sceneId + ".camera"; + var aspectratio = sceneId + ".aspectratio"; + var aspectmode = sceneId + ".aspectmode"; + var scene = fullLayout[sceneId]._scene; + var didUpdate; + if (resetLastSave) { + aobj[camera + ".up"] = scene.viewInitial.up; + aobj[camera + ".eye"] = scene.viewInitial.eye; + aobj[camera + ".center"] = scene.viewInitial.center; + didUpdate = true; + } else if (resetDefault) { + aobj[camera + ".up"] = null; + aobj[camera + ".eye"] = null; + aobj[camera + ".center"] = null; + didUpdate = true; + } + if (didUpdate) { + aobj[aspectratio + ".x"] = scene.viewInitial.aspectratio.x; + aobj[aspectratio + ".y"] = scene.viewInitial.aspectratio.y; + aobj[aspectratio + ".z"] = scene.viewInitial.aspectratio.z; + aobj[aspectmode] = scene.viewInitial.aspectmode; + } + } + Registry$x.call("_guiRelayout", gd, aobj); +} +modeBarButtons$2.hoverClosest3d = { + name: "hoverClosest3d", + _cat: "hoverclosest", + title: function(gd) { + return _$1(gd, "Toggle show closest data on hover"); + }, + attr: "hovermode", + val: null, + toggle: true, + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: handleHover3d +}; +function getNextHover3d(gd, ev) { + var button = ev.currentTarget; + var val = button._previousVal; + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d || []; + var axes2 = ["xaxis", "yaxis", "zaxis"]; + var currentSpikes = {}; + var layoutUpdate = {}; + if (val) { + layoutUpdate = val; + button._previousVal = null; + } else { + for (var i = 0; i < sceneIds.length; i++) { + var sceneId = sceneIds[i]; + var sceneLayout = fullLayout[sceneId]; + var hovermodeAStr = sceneId + ".hovermode"; + currentSpikes[hovermodeAStr] = sceneLayout.hovermode; + layoutUpdate[hovermodeAStr] = false; + for (var j = 0; j < 3; j++) { + var axis = axes2[j]; + var spikeAStr = sceneId + "." + axis + ".showspikes"; + layoutUpdate[spikeAStr] = false; + currentSpikes[spikeAStr] = sceneLayout[axis].showspikes; + } + } + button._previousVal = currentSpikes; + } + return layoutUpdate; +} +function handleHover3d(gd, ev) { + var layoutUpdate = getNextHover3d(gd, ev); + Registry$x.call("_guiRelayout", gd, layoutUpdate); +} +modeBarButtons$2.zoomInGeo = { + name: "zoomInGeo", + _cat: "zoomin", + title: function(gd) { + return _$1(gd, "Zoom in"); + }, + attr: "zoom", + val: "in", + icon: Icons$1.zoom_plus, + click: handleGeo +}; +modeBarButtons$2.zoomOutGeo = { + name: "zoomOutGeo", + _cat: "zoomout", + title: function(gd) { + return _$1(gd, "Zoom out"); + }, + attr: "zoom", + val: "out", + icon: Icons$1.zoom_minus, + click: handleGeo +}; +modeBarButtons$2.resetGeo = { + name: "resetGeo", + _cat: "reset", + title: function(gd) { + return _$1(gd, "Reset"); + }, + attr: "reset", + val: null, + icon: Icons$1.autoscale, + click: handleGeo +}; +modeBarButtons$2.hoverClosestGeo = { + name: "hoverClosestGeo", + _cat: "hoverclosest", + title: function(gd) { + return _$1(gd, "Toggle show closest data on hover"); + }, + attr: "hovermode", + val: null, + toggle: true, + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: toggleHover +}; +function handleGeo(gd, ev) { + var button = ev.currentTarget; + var attr = button.getAttribute("data-attr"); + var val = button.getAttribute("data-val") || true; + var fullLayout = gd._fullLayout; + var geoIds = fullLayout._subplots.geo || []; + for (var i = 0; i < geoIds.length; i++) { + var id = geoIds[i]; + var geoLayout = fullLayout[id]; + if (attr === "zoom") { + var scale2 = geoLayout.projection.scale; + var newScale = val === "in" ? 2 * scale2 : 0.5 * scale2; + Registry$x.call("_guiRelayout", gd, id + ".projection.scale", newScale); + } + } + if (attr === "reset") { + resetView(gd, "geo"); + } +} +modeBarButtons$2.hoverClosestGl2d = { + name: "hoverClosestGl2d", + _cat: "hoverclosest", + title: function(gd) { + return _$1(gd, "Toggle show closest data on hover"); + }, + attr: "hovermode", + val: null, + toggle: true, + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: toggleHover +}; +modeBarButtons$2.hoverClosestPie = { + name: "hoverClosestPie", + _cat: "hoverclosest", + title: function(gd) { + return _$1(gd, "Toggle show closest data on hover"); + }, + attr: "hovermode", + val: "closest", + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: toggleHover +}; +function getNextHover(gd) { + var fullLayout = gd._fullLayout; + if (fullLayout.hovermode) return false; + if (fullLayout._has("cartesian")) { + return fullLayout._isHoriz ? "y" : "x"; + } + return "closest"; +} +function toggleHover(gd) { + var newHover = getNextHover(gd); + Registry$x.call("_guiRelayout", gd, "hovermode", newHover); +} +modeBarButtons$2.resetViewSankey = { + name: "resetSankeyGroup", + title: function(gd) { + return _$1(gd, "Reset view"); + }, + icon: Icons$1.home, + click: function(gd) { + var aObj = { + "node.groups": [], + "node.x": [], + "node.y": [] + }; + for (var i = 0; i < gd._fullData.length; i++) { + var viewInitial = gd._fullData[i]._viewInitial; + aObj["node.groups"].push(viewInitial.node.groups.slice()); + aObj["node.x"].push(viewInitial.node.x.slice()); + aObj["node.y"].push(viewInitial.node.y.slice()); + } + Registry$x.call("restyle", gd, aObj); + } +}; +modeBarButtons$2.toggleHover = { + name: "toggleHover", + title: function(gd) { + return _$1(gd, "Toggle show closest data on hover"); + }, + attr: "hovermode", + val: null, + toggle: true, + icon: Icons$1.tooltip_basic, + gravity: "ne", + click: function(gd, ev) { + var layoutUpdate = getNextHover3d(gd, ev); + layoutUpdate.hovermode = getNextHover(gd); + Registry$x.call("_guiRelayout", gd, layoutUpdate); + } +}; +modeBarButtons$2.resetViews = { + name: "resetViews", + title: function(gd) { + return _$1(gd, "Reset views"); + }, + icon: Icons$1.home, + click: function(gd, ev) { + var button = ev.currentTarget; + button.setAttribute("data-attr", "zoom"); + button.setAttribute("data-val", "reset"); + handleCartesian(gd, ev); + button.setAttribute("data-attr", "resetLastSave"); + handleCamera3d(gd, ev); + resetView(gd, "geo"); + resetView(gd, "mapbox"); + resetView(gd, "map"); + } +}; +modeBarButtons$2.toggleSpikelines = { + name: "toggleSpikelines", + title: function(gd) { + return _$1(gd, "Toggle Spike Lines"); + }, + icon: Icons$1.spikeline, + attr: "_cartesianSpikesEnabled", + val: "on", + click: function(gd) { + var fullLayout = gd._fullLayout; + var allSpikesEnabled = fullLayout._cartesianSpikesEnabled; + fullLayout._cartesianSpikesEnabled = allSpikesEnabled === "on" ? "off" : "on"; + Registry$x.call("_guiRelayout", gd, setSpikelineVisibility(gd)); + } +}; +function setSpikelineVisibility(gd) { + var fullLayout = gd._fullLayout; + var areSpikesOn = fullLayout._cartesianSpikesEnabled === "on"; + var axList = axisIds$6.list(gd, null, true); + var aobj = {}; + for (var i = 0; i < axList.length; i++) { + var ax = axList[i]; + aobj[ax._name + ".showspikes"] = areSpikesOn ? true : ax._showSpikeInitial; + } + return aobj; +} +modeBarButtons$2.resetViewMapbox = { + name: "resetViewMapbox", + _cat: "resetView", + title: function(gd) { + return _$1(gd, "Reset view"); + }, + attr: "reset", + icon: Icons$1.home, + click: function(gd) { + resetView(gd, "mapbox"); + } +}; +modeBarButtons$2.resetViewMap = { + name: "resetViewMap", + _cat: "resetView", + title: function(gd) { + return _$1(gd, "Reset view"); + }, + attr: "reset", + icon: Icons$1.home, + click: function(gd) { + resetView(gd, "map"); + } +}; +modeBarButtons$2.zoomInMapbox = { + name: "zoomInMapbox", + _cat: "zoomin", + title: function(gd) { + return _$1(gd, "Zoom in"); + }, + attr: "zoom", + val: "in", + icon: Icons$1.zoom_plus, + click: handleMapboxZoom +}; +modeBarButtons$2.zoomInMap = { + name: "zoomInMap", + _cat: "zoomin", + title: function(gd) { + return _$1(gd, "Zoom in"); + }, + attr: "zoom", + val: "in", + icon: Icons$1.zoom_plus, + click: handleMapZoom +}; +modeBarButtons$2.zoomOutMapbox = { + name: "zoomOutMapbox", + _cat: "zoomout", + title: function(gd) { + return _$1(gd, "Zoom out"); + }, + attr: "zoom", + val: "out", + icon: Icons$1.zoom_minus, + click: handleMapboxZoom +}; +modeBarButtons$2.zoomOutMap = { + name: "zoomOutMap", + _cat: "zoomout", + title: function(gd) { + return _$1(gd, "Zoom out"); + }, + attr: "zoom", + val: "out", + icon: Icons$1.zoom_minus, + click: handleMapZoom +}; +function handleMapboxZoom(gd, ev) { + _handleMapZoom(gd, ev, "mapbox"); +} +function handleMapZoom(gd, ev) { + _handleMapZoom(gd, ev, "map"); +} +function _handleMapZoom(gd, ev, mapType) { + var button = ev.currentTarget; + var val = button.getAttribute("data-val"); + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[mapType] || []; + var scalar = 1.05; + var aObj = {}; + for (var i = 0; i < subplotIds.length; i++) { + var id = subplotIds[i]; + var current = fullLayout[id].zoom; + var next = val === "in" ? scalar * current : current / scalar; + aObj[id + ".zoom"] = next; + } + Registry$x.call("_guiRelayout", gd, aObj); +} +function resetView(gd, subplotType) { + var fullLayout = gd._fullLayout; + var subplotIds = fullLayout._subplots[subplotType] || []; + var aObj = {}; + for (var i = 0; i < subplotIds.length; i++) { + var id = subplotIds[i]; + var subplotObj = fullLayout[id]._subplot; + var viewInitial = subplotObj.viewInitial; + var viewKeys = Object.keys(viewInitial); + for (var j = 0; j < viewKeys.length; j++) { + var key = viewKeys[j]; + aObj[id + "." + key] = viewInitial[key]; + } + } + Registry$x.call("_guiRelayout", gd, aObj); +} +var buttonsExports = buttons.exports; +var modeBarButtons$1 = buttonsExports; +var buttonList = Object.keys(modeBarButtons$1); +var DRAW_MODES$1 = [ + "drawline", + "drawopenpath", + "drawclosedpath", + "drawcircle", + "drawrect", + "eraseshape" +]; +var backButtons = [ + "v1hovermode", + "hoverclosest", + "hovercompare", + "togglehover", + "togglespikelines" +].concat(DRAW_MODES$1); +var foreButtons = []; +var addToForeButtons = function(b) { + if (backButtons.indexOf(b._cat || b.name) !== -1) return; + var name2 = b.name; + var _cat = (b._cat || b.name).toLowerCase(); + if (foreButtons.indexOf(name2) === -1) foreButtons.push(name2); + if (foreButtons.indexOf(_cat) === -1) foreButtons.push(_cat); +}; +buttonList.forEach(function(k) { + addToForeButtons(modeBarButtons$1[k]); +}); +foreButtons.sort(); +var constants$F = { + DRAW_MODES: DRAW_MODES$1, + backButtons, + foreButtons +}; +var constants$E = constants$F; +var attributes$D = { + editType: "modebar", + orientation: { + valType: "enumerated", + values: ["v", "h"], + dflt: "h", + editType: "modebar", + description: "Sets the orientation of the modebar." + }, + bgcolor: { + valType: "color", + editType: "modebar", + description: "Sets the background color of the modebar." + }, + color: { + valType: "color", + editType: "modebar", + description: "Sets the color of the icons in the modebar." + }, + activecolor: { + valType: "color", + editType: "modebar", + description: "Sets the color of the active or hovered on icons in the modebar." + }, + uirevision: { + valType: "any", + editType: "none", + description: [ + "Controls persistence of user-driven changes related to the modebar,", + "including `hovermode`, `dragmode`, and `showspikes` at both the", + "root level and inside subplots. Defaults to `layout.uirevision`." + ].join(" ") + }, + add: { + valType: "string", + arrayOk: true, + dflt: "", + editType: "modebar", + description: [ + "Determines which predefined modebar buttons to add.", + "Please note that these buttons will only be shown if they are", + "compatible with all trace types used in a graph.", + "Similar to `config.modeBarButtonsToAdd` option.", + "This may include *" + constants$E.backButtons.join("*, *") + "*." + ].join(" ") + }, + remove: { + valType: "string", + arrayOk: true, + dflt: "", + editType: "modebar", + description: [ + "Determines which predefined modebar buttons to remove.", + "Similar to `config.modeBarButtonsToRemove` option.", + "This may include *" + constants$E.foreButtons.join("*, *") + "*." + ].join(" ") + } +}; +var Lib$1m = libExports; +var Color$y = colorExports; +var Template$4 = plot_template; +var attributes$C = attributes$D; +var defaults$k = function supplyLayoutDefaults3(layoutIn, layoutOut) { + var containerIn = layoutIn.modebar || {}; + var containerOut = Template$4.newContainer(layoutOut, "modebar"); + function coerce2(attr, dflt) { + return Lib$1m.coerce(containerIn, containerOut, attributes$C, attr, dflt); + } + coerce2("orientation"); + coerce2("bgcolor", Color$y.addOpacity(layoutOut.paper_bgcolor, 0.5)); + var defaultColor = Color$y.contrast(Color$y.rgb(layoutOut.modebar.bgcolor)); + coerce2("color", Color$y.addOpacity(defaultColor, 0.3)); + coerce2("activecolor", Color$y.addOpacity(defaultColor, 0.7)); + coerce2("uirevision", layoutOut.uirevision); + coerce2("add"); + coerce2("remove"); +}; +var d3$p = d3Exports; +var isNumeric$h = fastIsnumeric; +var Lib$1l = libExports; +var Icons = ploticon; +var version$1 = version$2.version; +var Parser = new DOMParser(); +function ModeBar(opts) { + this.container = opts.container; + this.element = document.createElement("div"); + this.update(opts.graphInfo, opts.buttons); + this.container.appendChild(this.element); +} +var proto = ModeBar.prototype; +proto.update = function(graphInfo, buttons2) { + this.graphInfo = graphInfo; + var context2 = this.graphInfo._context; + var fullLayout = this.graphInfo._fullLayout; + var modeBarId = "modebar-" + fullLayout._uid; + this.element.setAttribute("id", modeBarId); + this._uid = modeBarId; + this.element.className = "modebar"; + if (context2.displayModeBar === "hover") this.element.className += " modebar--hover ease-bg"; + if (fullLayout.modebar.orientation === "v") { + this.element.className += " vertical"; + buttons2 = buttons2.reverse(); + } + var style5 = fullLayout.modebar; + var bgSelector = context2.displayModeBar === "hover" ? ".js-plotly-plot .plotly:hover " : ""; + Lib$1l.deleteRelatedStyleRule(modeBarId); + Lib$1l.addRelatedStyleRule(modeBarId, bgSelector + "#" + modeBarId + " .modebar-group", "background-color: " + style5.bgcolor); + Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn .icon path", "fill: " + style5.color); + Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn:hover .icon path", "fill: " + style5.activecolor); + Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn.active .icon path", "fill: " + style5.activecolor); + var needsNewButtons = !this.hasButtons(buttons2); + var needsNewLogo = this.hasLogo !== context2.displaylogo; + var needsNewLocale = this.locale !== context2.locale; + this.locale = context2.locale; + if (needsNewButtons || needsNewLogo || needsNewLocale) { + this.removeAllButtons(); + this.updateButtons(buttons2); + if (context2.watermark || context2.displaylogo) { + var logoGroup = this.getLogo(); + if (context2.watermark) { + logoGroup.className = logoGroup.className + " watermark"; + } + if (fullLayout.modebar.orientation === "v") { + this.element.insertBefore(logoGroup, this.element.childNodes[0]); + } else { + this.element.appendChild(logoGroup); + } + this.hasLogo = true; + } + } + this.updateActiveButton(); +}; +proto.updateButtons = function(buttons2) { + var _this = this; + this.buttons = buttons2; + this.buttonElements = []; + this.buttonsNames = []; + this.buttons.forEach(function(buttonGroup) { + var group = _this.createGroup(); + buttonGroup.forEach(function(buttonConfig) { + var buttonName = buttonConfig.name; + if (!buttonName) { + throw new Error("must provide button 'name' in button config"); + } + if (_this.buttonsNames.indexOf(buttonName) !== -1) { + throw new Error("button name '" + buttonName + "' is taken"); + } + _this.buttonsNames.push(buttonName); + var button = _this.createButton(buttonConfig); + _this.buttonElements.push(button); + group.appendChild(button); + }); + _this.element.appendChild(group); + }); +}; +proto.createGroup = function() { + var group = document.createElement("div"); + group.className = "modebar-group"; + return group; +}; +proto.createButton = function(config) { + var _this = this; + var button = document.createElement("a"); + button.setAttribute("rel", "tooltip"); + button.className = "modebar-btn"; + var title = config.title; + if (title === void 0) title = config.name; + else if (typeof title === "function") title = title(this.graphInfo); + if (title || title === 0) button.setAttribute("data-title", title); + if (config.attr !== void 0) button.setAttribute("data-attr", config.attr); + var val = config.val; + if (val !== void 0) { + if (typeof val === "function") val = val(this.graphInfo); + button.setAttribute("data-val", val); + } + var click3 = config.click; + if (typeof click3 !== "function") { + throw new Error("must provide button 'click' function in button config"); + } else { + button.addEventListener("click", function(ev) { + config.click(_this.graphInfo, ev); + _this.updateActiveButton(ev.currentTarget); + }); + } + button.setAttribute("data-toggle", config.toggle || false); + if (config.toggle) d3$p.select(button).classed("active", true); + var icon = config.icon; + if (typeof icon === "function") { + button.appendChild(icon()); + } else { + button.appendChild(this.createIcon(icon || Icons.question)); + } + button.setAttribute("data-gravity", config.gravity || "n"); + return button; +}; +proto.createIcon = function(thisIcon) { + var iconHeight = isNumeric$h(thisIcon.height) ? Number(thisIcon.height) : thisIcon.ascent - thisIcon.descent; + var svgNS = "http://www.w3.org/2000/svg"; + var icon; + if (thisIcon.path) { + icon = document.createElementNS(svgNS, "svg"); + icon.setAttribute("viewBox", [0, 0, thisIcon.width, iconHeight].join(" ")); + icon.setAttribute("class", "icon"); + var path = document.createElementNS(svgNS, "path"); + path.setAttribute("d", thisIcon.path); + if (thisIcon.transform) { + path.setAttribute("transform", thisIcon.transform); + } else if (thisIcon.ascent !== void 0) { + path.setAttribute("transform", "matrix(1 0 0 -1 0 " + thisIcon.ascent + ")"); + } + icon.appendChild(path); + } + if (thisIcon.svg) { + var svgDoc = Parser.parseFromString(thisIcon.svg, "application/xml"); + icon = svgDoc.childNodes[0]; + } + icon.setAttribute("height", "1em"); + icon.setAttribute("width", "1em"); + return icon; +}; +proto.updateActiveButton = function(buttonClicked) { + var fullLayout = this.graphInfo._fullLayout; + var dataAttrClicked = buttonClicked !== void 0 ? buttonClicked.getAttribute("data-attr") : null; + this.buttonElements.forEach(function(button) { + var thisval = button.getAttribute("data-val") || true; + var dataAttr = button.getAttribute("data-attr"); + var isToggleButton = button.getAttribute("data-toggle") === "true"; + var button3 = d3$p.select(button); + if (isToggleButton) { + if (dataAttr === dataAttrClicked) { + button3.classed("active", !button3.classed("active")); + } + } else { + var val = dataAttr === null ? dataAttr : Lib$1l.nestedProperty(fullLayout, dataAttr).get(); + button3.classed("active", val === thisval); + } + }); +}; +proto.hasButtons = function(buttons2) { + var currentButtons = this.buttons; + if (!currentButtons) return false; + if (buttons2.length !== currentButtons.length) return false; + for (var i = 0; i < buttons2.length; ++i) { + if (buttons2[i].length !== currentButtons[i].length) return false; + for (var j = 0; j < buttons2[i].length; j++) { + if (buttons2[i][j].name !== currentButtons[i][j].name) return false; + } + } + return true; +}; +function jsVersion(str2) { + return str2 + " (v" + version$1 + ")"; +} +proto.getLogo = function() { + var group = this.createGroup(); + var a = document.createElement("a"); + a.href = "https://plotly.com/"; + a.target = "_blank"; + a.setAttribute("data-title", jsVersion(Lib$1l._(this.graphInfo, "Produced with Plotly.js"))); + a.className = "modebar-btn plotlyjsicon modebar-btn--logo"; + a.appendChild(this.createIcon(Icons.newplotlylogo)); + group.appendChild(a); + return group; +}; +proto.removeAllButtons = function() { + while (this.element.firstChild) { + this.element.removeChild(this.element.firstChild); + } + this.hasLogo = false; +}; +proto.destroy = function() { + Lib$1l.removeElement(this.container.querySelector(".modebar")); + Lib$1l.deleteRelatedStyleRule(this._uid); +}; +function createModeBar$1(gd, buttons2) { + var fullLayout = gd._fullLayout; + var modeBar = new ModeBar({ + graphInfo: gd, + container: fullLayout._modebardiv.node(), + buttons: buttons2 + }); + if (fullLayout._privateplot) { + d3$p.select(modeBar.element).append("span").classed("badge-private float--left", true).text("PRIVATE"); + } + return modeBar; +} +var modebar$1 = createModeBar$1; +var axisIds$5 = axis_ids; +var scatterSubTypes = subtypes$3; +var Registry$w = registry; +var isUnifiedHover = helpers$J.isUnifiedHover; +var createModeBar = modebar$1; +var modeBarButtons = buttonsExports; +var DRAW_MODES = constants$F.DRAW_MODES; +var extendDeep$1 = libExports.extendDeep; +var manage = function manageModeBar(gd) { + var fullLayout = gd._fullLayout; + var context2 = gd._context; + var modeBar = fullLayout._modeBar; + if (!context2.displayModeBar && !context2.watermark) { + if (modeBar) { + modeBar.destroy(); + delete fullLayout._modeBar; + } + return; + } + if (!Array.isArray(context2.modeBarButtonsToRemove)) { + throw new Error([ + "*modeBarButtonsToRemove* configuration options", + "must be an array." + ].join(" ")); + } + if (!Array.isArray(context2.modeBarButtonsToAdd)) { + throw new Error([ + "*modeBarButtonsToAdd* configuration options", + "must be an array." + ].join(" ")); + } + var customButtons = context2.modeBarButtons; + var buttonGroups; + if (Array.isArray(customButtons) && customButtons.length) { + buttonGroups = fillCustomButton(customButtons); + } else if (!context2.displayModeBar && context2.watermark) { + buttonGroups = []; + } else { + buttonGroups = getButtonGroups(gd); + } + if (modeBar) modeBar.update(gd, buttonGroups); + else fullLayout._modeBar = createModeBar(gd, buttonGroups); +}; +function getButtonGroups(gd) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; + var context2 = gd._context; + function match(name2, B2) { + if (typeof B2 === "string") { + if (B2.toLowerCase() === name2.toLowerCase()) return true; + } else { + var v0 = B2.name; + var v1 = B2._cat || B2.name; + if (v0 === name2 || v1 === name2.toLowerCase()) return true; + } + return false; + } + var layoutAdd = fullLayout.modebar.add; + if (typeof layoutAdd === "string") layoutAdd = [layoutAdd]; + var layoutRemove = fullLayout.modebar.remove; + if (typeof layoutRemove === "string") layoutRemove = [layoutRemove]; + var buttonsToAdd = context2.modeBarButtonsToAdd.concat( + layoutAdd.filter(function(e) { + for (var i2 = 0; i2 < context2.modeBarButtonsToRemove.length; i2++) { + if (match(e, context2.modeBarButtonsToRemove[i2])) return false; + } + return true; + }) + ); + var buttonsToRemove = context2.modeBarButtonsToRemove.concat( + layoutRemove.filter(function(e) { + for (var i2 = 0; i2 < context2.modeBarButtonsToAdd.length; i2++) { + if (match(e, context2.modeBarButtonsToAdd[i2])) return false; + } + return true; + }) + ); + var hasCartesian = fullLayout._has("cartesian"); + var hasGL3D = fullLayout._has("gl3d"); + var hasGeo = fullLayout._has("geo"); + var hasPie = fullLayout._has("pie"); + var hasFunnelarea = fullLayout._has("funnelarea"); + var hasGL2D = fullLayout._has("gl2d"); + var hasTernary = fullLayout._has("ternary"); + var hasMapbox = fullLayout._has("mapbox"); + var hasMap = fullLayout._has("map"); + var hasPolar = fullLayout._has("polar"); + var hasSmith = fullLayout._has("smith"); + var hasSankey = fullLayout._has("sankey"); + var allAxesFixed = areAllAxesFixed(fullLayout); + var hasUnifiedHoverLabel = isUnifiedHover(fullLayout.hovermode); + var groups = []; + function addGroup(newGroup) { + if (!newGroup.length) return; + var out = []; + for (var i2 = 0; i2 < newGroup.length; i2++) { + var name2 = newGroup[i2]; + var B2 = modeBarButtons[name2]; + var v0 = B2.name.toLowerCase(); + var v1 = (B2._cat || B2.name).toLowerCase(); + var found = false; + for (var q = 0; q < buttonsToRemove.length; q++) { + var t = buttonsToRemove[q].toLowerCase(); + if (t === v0 || t === v1) { + found = true; + break; + } + } + if (found) continue; + out.push(modeBarButtons[name2]); + } + groups.push(out); + } + var commonGroup = ["toImage"]; + if (context2.showEditInChartStudio) commonGroup.push("editInChartStudio"); + else if (context2.showSendToCloud) commonGroup.push("sendDataToCloud"); + addGroup(commonGroup); + var zoomGroup = []; + var hoverGroup = []; + var resetGroup = []; + var dragModeGroup = []; + if ((hasCartesian || hasGL2D || hasPie || hasFunnelarea || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasMap + hasPolar + hasSmith > 1) { + hoverGroup = ["toggleHover"]; + resetGroup = ["resetViews"]; + } else if (hasGeo) { + zoomGroup = ["zoomInGeo", "zoomOutGeo"]; + hoverGroup = ["hoverClosestGeo"]; + resetGroup = ["resetGeo"]; + } else if (hasGL3D) { + hoverGroup = ["hoverClosest3d"]; + resetGroup = ["resetCameraDefault3d", "resetCameraLastSave3d"]; + } else if (hasMapbox) { + zoomGroup = ["zoomInMapbox", "zoomOutMapbox"]; + hoverGroup = ["toggleHover"]; + resetGroup = ["resetViewMapbox"]; + } else if (hasMap) { + zoomGroup = ["zoomInMap", "zoomOutMap"]; + hoverGroup = ["toggleHover"]; + resetGroup = ["resetViewMap"]; + } else if (hasGL2D) { + hoverGroup = ["hoverClosestGl2d"]; + } else if (hasPie) { + hoverGroup = ["hoverClosestPie"]; + } else if (hasSankey) { + hoverGroup = ["hoverClosestCartesian", "hoverCompareCartesian"]; + resetGroup = ["resetViewSankey"]; + } else { + hoverGroup = ["toggleHover"]; + } + if (hasCartesian) { + hoverGroup.push("toggleSpikelines", "hoverClosestCartesian", "hoverCompareCartesian"); + } + if (hasNoHover(fullData) || hasUnifiedHoverLabel) { + hoverGroup = []; + } + if ((hasCartesian || hasGL2D) && !allAxesFixed) { + zoomGroup = ["zoomIn2d", "zoomOut2d", "autoScale2d"]; + if (resetGroup[0] !== "resetViews") resetGroup = ["resetScale2d"]; + } + if (hasGL3D) { + dragModeGroup = ["zoom3d", "pan3d", "orbitRotation", "tableRotation"]; + } else if ((hasCartesian || hasGL2D) && !allAxesFixed || hasTernary) { + dragModeGroup = ["zoom2d", "pan2d"]; + } else if (hasMapbox || hasMap || hasGeo) { + dragModeGroup = ["pan2d"]; + } else if (hasPolar) { + dragModeGroup = ["zoom2d"]; + } + if (isSelectable(fullData)) { + dragModeGroup.push("select2d", "lasso2d"); + } + var enabledHoverGroup = []; + var enableHover = function(a) { + if (enabledHoverGroup.indexOf(a) !== -1) return; + if (hoverGroup.indexOf(a) !== -1) { + enabledHoverGroup.push(a); + } + }; + if (Array.isArray(buttonsToAdd)) { + var newList = []; + for (var i = 0; i < buttonsToAdd.length; i++) { + var b = buttonsToAdd[i]; + if (typeof b === "string") { + b = b.toLowerCase(); + if (DRAW_MODES.indexOf(b) !== -1) { + if (fullLayout._has("mapbox") || fullLayout._has("map") || // draw shapes in paper coordinate (could be improved in future to support data coordinate, when there is no pitch) + fullLayout._has("cartesian")) { + dragModeGroup.push(b); + } + } else if (b === "togglespikelines") { + enableHover("toggleSpikelines"); + } else if (b === "togglehover") { + enableHover("toggleHover"); + } else if (b === "hovercompare") { + enableHover("hoverCompareCartesian"); + } else if (b === "hoverclosest") { + enableHover("hoverClosestCartesian"); + enableHover("hoverClosestGeo"); + enableHover("hoverClosest3d"); + enableHover("hoverClosestGl2d"); + enableHover("hoverClosestPie"); + } else if (b === "v1hovermode") { + enableHover("hoverClosestCartesian"); + enableHover("hoverCompareCartesian"); + enableHover("hoverClosestGeo"); + enableHover("hoverClosest3d"); + enableHover("hoverClosestGl2d"); + enableHover("hoverClosestPie"); + } + } else newList.push(b); + } + buttonsToAdd = newList; + } + addGroup(dragModeGroup); + addGroup(zoomGroup.concat(resetGroup)); + addGroup(enabledHoverGroup); + return appendButtonsToGroups(groups, buttonsToAdd); +} +function areAllAxesFixed(fullLayout) { + var axList = axisIds$5.list({ _fullLayout: fullLayout }, null, true); + for (var i = 0; i < axList.length; i++) { + if (!axList[i].fixedrange) { + return false; + } + } + return true; +} +function isSelectable(fullData) { + var selectable = false; + for (var i = 0; i < fullData.length; i++) { + if (selectable) break; + var trace = fullData[i]; + if (!trace._module || !trace._module.selectPoints) continue; + if (Registry$w.traceIs(trace, "scatter-like")) { + if (scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) { + selectable = true; + } + } else if (Registry$w.traceIs(trace, "box-violin")) { + if (trace.boxpoints === "all" || trace.points === "all") { + selectable = true; + } + } else { + selectable = true; + } + } + return selectable; +} +function hasNoHover(fullData) { + for (var i = 0; i < fullData.length; i++) { + if (!Registry$w.traceIs(fullData[i], "noHover")) return false; + } + return true; +} +function appendButtonsToGroups(groups, buttons2) { + if (buttons2.length) { + if (Array.isArray(buttons2[0])) { + for (var i = 0; i < buttons2.length; i++) { + groups.push(buttons2[i]); + } + } else groups.push(buttons2); + } + return groups; +} +function fillCustomButton(originalModeBarButtons) { + var customButtons = extendDeep$1([], originalModeBarButtons); + for (var i = 0; i < customButtons.length; i++) { + var buttonGroup = customButtons[i]; + for (var j = 0; j < buttonGroup.length; j++) { + var button = buttonGroup[j]; + if (typeof button === "string") { + if (modeBarButtons[button] !== void 0) { + customButtons[i][j] = modeBarButtons[button]; + } else { + throw new Error([ + "*modeBarButtons* configuration options", + "invalid button name" + ].join(" ")); + } + } + } + } + return customButtons; +} +var modebar = { + moduleType: "component", + name: "modebar", + layoutAttributes: attributes$D, + supplyLayoutDefaults: defaults$k, + manage +}; +var constraints = {}; +var FROM_BL$1 = alignment$1.FROM_BL; +var scale_zoom = function scaleZoom(ax, factor, centerFraction) { + if (centerFraction === void 0) { + centerFraction = FROM_BL$1[ax.constraintoward || "center"]; + } + var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; + var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; + ax.range = ax._input.range = [ + ax.l2r(center + (rangeLinear[0] - center) * factor), + ax.l2r(center + (rangeLinear[1] - center) * factor) + ]; + ax.setScale(); +}; +var Lib$1k = libExports; +var autorange = autorange$2; +var id2name = axis_ids.id2name; +var layoutAttributes$5 = layout_attributes$4; +var scaleZoom2 = scale_zoom; +var setConvert$1 = set_convert; +var ALMOST_EQUAL = numerical.ALMOST_EQUAL; +var FROM_BL = alignment$1.FROM_BL; +constraints.handleDefaults = function(layoutIn, layoutOut, opts) { + var axIds2 = opts.axIds; + var axHasImage = opts.axHasImage; + var constraintGroups = layoutOut._axisConstraintGroups = []; + var matchGroups = layoutOut._axisMatchGroups = []; + var i, group, axId, axName, axIn, axOut, attr, val; + for (i = 0; i < axIds2.length; i++) { + axName = id2name(axIds2[i]); + axIn = layoutIn[axName]; + axOut = layoutOut[axName]; + handleOneAxDefaults(axIn, axOut, { + axIds: axIds2, + layoutOut, + hasImage: axHasImage[axName] + }); + } + function stash(groups, stashAttr) { + for (i = 0; i < groups.length; i++) { + group = groups[i]; + for (axId in group) { + layoutOut[id2name(axId)][stashAttr] = group; + } + } + } + stash(matchGroups, "_matchGroup"); + for (i = 0; i < constraintGroups.length; i++) { + group = constraintGroups[i]; + for (axId in group) { + axOut = layoutOut[id2name(axId)]; + if (axOut.fixedrange) { + for (var axId2 in group) { + var axName2 = id2name(axId2); + if ((layoutIn[axName2] || {}).fixedrange === false) { + Lib$1k.warn( + "fixedrange was specified as false for axis " + axName2 + " but was overridden because another axis in its constraint group has fixedrange true" + ); + } + layoutOut[axName2].fixedrange = true; + } + break; + } + } + } + i = 0; + while (i < constraintGroups.length) { + group = constraintGroups[i]; + for (axId in group) { + axOut = layoutOut[id2name(axId)]; + if (axOut._matchGroup && Object.keys(axOut._matchGroup).length === Object.keys(group).length) { + constraintGroups.splice(i, 1); + i--; + } + break; + } + i++; + } + stash(constraintGroups, "_constraintGroup"); + var matchAttrs = [ + "constrain", + "range", + "autorange", + "rangemode", + "rangebreaks", + "categoryorder", + "categoryarray" + ]; + var hasRange = false; + var hasDayOfWeekBreaks = false; + function setAttrVal() { + val = axOut[attr]; + if (attr === "rangebreaks") { + hasDayOfWeekBreaks = axOut._hasDayOfWeekBreaks; + } + } + for (i = 0; i < matchGroups.length; i++) { + group = matchGroups[i]; + for (var j = 0; j < matchAttrs.length; j++) { + attr = matchAttrs[j]; + val = null; + var baseAx; + for (axId in group) { + axName = id2name(axId); + axIn = layoutIn[axName]; + axOut = layoutOut[axName]; + if (!(attr in axOut)) { + continue; + } + if (!axOut.matches) { + baseAx = axOut; + if (attr in axIn) { + setAttrVal(); + break; + } + } + if (val === null && attr in axIn) { + setAttrVal(); + } + } + if (attr === "range" && val && axIn.range && axIn.range.length === 2 && axIn.range[0] !== null && axIn.range[1] !== null) { + hasRange = true; + } + if (attr === "autorange" && val === null && hasRange) { + val = false; + } + if (val === null && attr in baseAx) { + val = baseAx[attr]; + } + if (val !== null) { + for (axId in group) { + axOut = layoutOut[id2name(axId)]; + axOut[attr] = attr === "range" ? val.slice() : val; + if (attr === "rangebreaks") { + axOut._hasDayOfWeekBreaks = hasDayOfWeekBreaks; + setConvert$1(axOut, layoutOut); + } + } + } + } + } +}; +function handleOneAxDefaults(axIn, axOut, opts) { + var axIds2 = opts.axIds; + var layoutOut = opts.layoutOut; + var hasImage = opts.hasImage; + var constraintGroups = layoutOut._axisConstraintGroups; + var matchGroups = layoutOut._axisMatchGroups; + var axId = axOut._id; + var axLetter = axId.charAt(0); + var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {}; + var thisID = axOut._id; + var isX = thisID.charAt(0) === "x"; + axOut._matchGroup = null; + axOut._constraintGroup = null; + function coerce2(attr, dflt) { + return Lib$1k.coerce(axIn, axOut, layoutAttributes$5, attr, dflt); + } + coerce2("constrain", hasImage ? "domain" : "range"); + Lib$1k.coerce(axIn, axOut, { + constraintoward: { + valType: "enumerated", + values: isX ? ["left", "center", "right"] : ["bottom", "middle", "top"], + dflt: isX ? "center" : "middle" + } + }, "constraintoward"); + var thisType = axOut.type; + var i, idi; + var linkableAxes = []; + for (i = 0; i < axIds2.length; i++) { + idi = axIds2[i]; + if (idi === thisID) continue; + var axi = layoutOut[id2name(idi)]; + if (axi.type === thisType) { + linkableAxes.push(idi); + } + } + var thisGroup = getConstraintGroup(constraintGroups, thisID); + if (thisGroup) { + var linkableAxesNoLoops = []; + for (i = 0; i < linkableAxes.length; i++) { + idi = linkableAxes[i]; + if (!thisGroup[idi]) linkableAxesNoLoops.push(idi); + } + linkableAxes = linkableAxesNoLoops; + } + var canLink = linkableAxes.length; + var matches, scaleanchor; + if (canLink && (axIn.matches || splomStash.matches)) { + matches = Lib$1k.coerce(axIn, axOut, { + matches: { + valType: "enumerated", + values: linkableAxes, + dflt: linkableAxes.indexOf(splomStash.matches) !== -1 ? splomStash.matches : void 0 + } + }, "matches"); + } + var scaleanchorDflt = hasImage && !isX ? axOut.anchor : void 0; + if (canLink && !matches && (axIn.scaleanchor || scaleanchorDflt)) { + scaleanchor = Lib$1k.coerce(axIn, axOut, { + scaleanchor: { + valType: "enumerated", + values: linkableAxes.concat([false]) + } + }, "scaleanchor", scaleanchorDflt); + } + if (matches) { + axOut._matchGroup = updateConstraintGroups(matchGroups, thisID, matches, 1); + var matchedAx = layoutOut[id2name(matches)]; + var matchRatio = extent(layoutOut, axOut) / extent(layoutOut, matchedAx); + if (isX !== (matches.charAt(0) === "x")) { + matchRatio = (isX ? "x" : "y") + matchRatio; + } + updateConstraintGroups(constraintGroups, thisID, matches, matchRatio); + } else if (axIn.matches && axIds2.indexOf(axIn.matches) !== -1) { + Lib$1k.warn("ignored " + axOut._name + '.matches: "' + axIn.matches + '" to avoid an infinite loop'); + } + if (scaleanchor) { + var scaleratio = coerce2("scaleratio"); + if (!scaleratio) scaleratio = axOut.scaleratio = 1; + updateConstraintGroups(constraintGroups, thisID, scaleanchor, scaleratio); + } else if (axIn.scaleanchor && axIds2.indexOf(axIn.scaleanchor) !== -1) { + Lib$1k.warn("ignored " + axOut._name + '.scaleanchor: "' + axIn.scaleanchor + '" to avoid either an infinite loop and possibly inconsistent scaleratios, or because this axis declares a *matches* constraint.'); + } +} +function extent(layoutOut, ax) { + var domain2 = ax.domain; + if (!domain2) { + domain2 = layoutOut[id2name(ax.overlaying)].domain; + } + return domain2[1] - domain2[0]; +} +function getConstraintGroup(groups, thisID) { + for (var i = 0; i < groups.length; i++) { + if (groups[i][thisID]) { + return groups[i]; + } + } + return null; +} +function updateConstraintGroups(constraintGroups, thisID, thatID, scaleratio) { + var i, j, groupi, keyj, thisGroupIndex; + var thisGroup = getConstraintGroup(constraintGroups, thisID); + if (thisGroup === null) { + thisGroup = {}; + thisGroup[thisID] = 1; + thisGroupIndex = constraintGroups.length; + constraintGroups.push(thisGroup); + } else { + thisGroupIndex = constraintGroups.indexOf(thisGroup); + } + var thisGroupKeys = Object.keys(thisGroup); + for (i = 0; i < constraintGroups.length; i++) { + groupi = constraintGroups[i]; + if (i !== thisGroupIndex && groupi[thatID]) { + var baseScale = groupi[thatID]; + for (j = 0; j < thisGroupKeys.length; j++) { + keyj = thisGroupKeys[j]; + groupi[keyj] = multiplyScales(baseScale, multiplyScales(scaleratio, thisGroup[keyj])); + } + constraintGroups.splice(thisGroupIndex, 1); + return; + } + } + if (scaleratio !== 1) { + for (j = 0; j < thisGroupKeys.length; j++) { + var key = thisGroupKeys[j]; + thisGroup[key] = multiplyScales(scaleratio, thisGroup[key]); + } + } + thisGroup[thatID] = 1; +} +function multiplyScales(a, b) { + var aPrefix = ""; + var bPrefix = ""; + var aLen, bLen; + if (typeof a === "string") { + aPrefix = a.match(/^[xy]*/)[0]; + aLen = aPrefix.length; + a = +a.substr(aLen); + } + if (typeof b === "string") { + bPrefix = b.match(/^[xy]*/)[0]; + bLen = bPrefix.length; + b = +b.substr(bLen); + } + var c = a * b; + if (!aLen && !bLen) { + return c; + } + if (!aLen || !bLen || aPrefix.charAt(0) === bPrefix.charAt(0)) { + return aPrefix + bPrefix + a * b; + } + if (aLen === bLen) { + return c; + } + return (aLen > bLen ? aPrefix.substr(bLen) : bPrefix.substr(aLen)) + c; +} +function finalRatios(group, fullLayout) { + var size = fullLayout._size; + var yRatio = size.h / size.w; + var out = {}; + var keys = Object.keys(group); + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + var val = group[key]; + if (typeof val === "string") { + var prefix = val.match(/^[xy]*/)[0]; + var pLen = prefix.length; + val = +val.substr(pLen); + var mult = prefix.charAt(0) === "y" ? yRatio : 1 / yRatio; + for (var j = 0; j < pLen; j++) { + val *= mult; + } + } + out[key] = val; + } + return out; +} +constraints.enforce = function enforce(gd) { + var fullLayout = gd._fullLayout; + var constraintGroups = fullLayout._axisConstraintGroups || []; + var i, j, group, axisID, ax, normScale, mode, factor; + for (i = 0; i < constraintGroups.length; i++) { + group = finalRatios(constraintGroups[i], fullLayout); + var axisIDs2 = Object.keys(group); + var minScale = Infinity; + var maxScale = 0; + var matchScale = Infinity; + var normScales = {}; + var axes2 = {}; + var hasAnyDomainConstraint = false; + for (j = 0; j < axisIDs2.length; j++) { + axisID = axisIDs2[j]; + axes2[axisID] = ax = fullLayout[id2name(axisID)]; + if (ax._inputDomain) ax.domain = ax._inputDomain.slice(); + else ax._inputDomain = ax.domain.slice(); + if (!ax._inputRange) ax._inputRange = ax.range.slice(); + ax.setScale(); + normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID]; + minScale = Math.min(minScale, normScale); + if (ax.constrain === "domain" || !ax._constraintShrinkable) { + matchScale = Math.min(matchScale, normScale); + } + delete ax._constraintShrinkable; + maxScale = Math.max(maxScale, normScale); + if (ax.constrain === "domain") hasAnyDomainConstraint = true; + } + if (minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; + for (j = 0; j < axisIDs2.length; j++) { + axisID = axisIDs2[j]; + normScale = normScales[axisID]; + ax = axes2[axisID]; + mode = ax.constrain; + if (normScale !== matchScale || mode === "domain") { + factor = normScale / matchScale; + if (mode === "range") { + scaleZoom2(ax, factor); + } else { + var inputDomain = ax._inputDomain; + var domainShrunk = (ax.domain[1] - ax.domain[0]) / (inputDomain[1] - inputDomain[0]); + var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) / (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0])); + factor /= domainShrunk; + if (factor * rangeShrunk < 1) { + ax.domain = ax._input.domain = inputDomain.slice(); + scaleZoom2(ax, factor); + continue; + } + if (rangeShrunk < 1) { + ax.range = ax._input.range = ax._inputRange.slice(); + factor *= rangeShrunk; + } + if (ax.autorange) { + var rl0 = ax.r2l(ax.range[0]); + var rl1 = ax.r2l(ax.range[1]); + var rangeCenter = (rl0 + rl1) / 2; + var rangeMin = rangeCenter; + var rangeMax = rangeCenter; + var halfRange = Math.abs(rl1 - rangeCenter); + var outerMin = rangeCenter - halfRange * factor * 1.0001; + var outerMax = rangeCenter + halfRange * factor * 1.0001; + var getPadMin = autorange.makePadFn(fullLayout, ax, 0); + var getPadMax = autorange.makePadFn(fullLayout, ax, 1); + updateDomain(ax, factor); + var m = Math.abs(ax._m); + var extremes = autorange.concatExtremes(gd, ax); + var minArray = extremes.min; + var maxArray = extremes.max; + var newVal; + var k; + for (k = 0; k < minArray.length; k++) { + newVal = minArray[k].val - getPadMin(minArray[k]) / m; + if (newVal > outerMin && newVal < rangeMin) { + rangeMin = newVal; + } + } + for (k = 0; k < maxArray.length; k++) { + newVal = maxArray[k].val + getPadMax(maxArray[k]) / m; + if (newVal < outerMax && newVal > rangeMax) { + rangeMax = newVal; + } + } + var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); + factor /= domainExpand; + rangeMin = ax.l2r(rangeMin); + rangeMax = ax.l2r(rangeMax); + ax.range = ax._input.range = rl0 < rl1 ? [rangeMin, rangeMax] : [rangeMax, rangeMin]; + } + updateDomain(ax, factor); + } + } + } + } +}; +constraints.getAxisGroup = function getAxisGroup(fullLayout, axId) { + var matchGroups = fullLayout._axisMatchGroups; + for (var i = 0; i < matchGroups.length; i++) { + var group = matchGroups[i]; + if (group[axId]) return "g" + i; + } + return axId; +}; +constraints.clean = function clean(gd, ax) { + if (ax._inputDomain) { + var isConstrained = false; + var axId = ax._id; + var constraintGroups = gd._fullLayout._axisConstraintGroups; + for (var j = 0; j < constraintGroups.length; j++) { + if (constraintGroups[j][axId]) { + isConstrained = true; + break; + } + } + if (!isConstrained || ax.constrain !== "domain") { + ax._input.domain = ax.domain = ax._inputDomain; + delete ax._inputDomain; + } + } +}; +function updateDomain(ax, factor) { + var inputDomain = ax._inputDomain; + var centerFraction = FROM_BL[ax.constraintoward]; + var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; + ax.domain = ax._input.domain = [ + center + (inputDomain[0] - center) / factor, + center + (inputDomain[1] - center) / factor + ]; + ax.setScale(); +} +(function(exports2) { + var d32 = d3Exports; + var Registry2 = registry; + var Plots2 = plotsExports; + var Lib2 = libExports; + var svgTextUtils2 = svg_text_utils; + var clearGlCanvases3 = clear_gl_canvases; + var Color2 = colorExports; + var Drawing2 = drawingExports; + var Titles2 = titles; + var ModeBar2 = modebar; + var Axes2 = axesExports; + var alignmentConstants2 = alignment$1; + var axisConstraints = constraints; + var enforceAxisConstraints = axisConstraints.enforce; + var cleanAxisConstraints = axisConstraints.clean; + var doAutoRange2 = autorange$2.doAutoRange; + var SVG_TEXT_ANCHOR_START = "start"; + var SVG_TEXT_ANCHOR_MIDDLE = "middle"; + var SVG_TEXT_ANCHOR_END = "end"; + var zindexSeparator2 = constants$U.zindexSeparator; + exports2.layoutStyles = function(gd) { + return Lib2.syncOrAsync([Plots2.doAutoMargin, lsInner], gd); + }; + function overlappingDomain(xDomain, yDomain, domains) { + for (var i = 0; i < domains.length; i++) { + var existingX = domains[i][0]; + var existingY = domains[i][1]; + if (existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) { + continue; + } + if (existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) { + return true; + } + } + return false; + } + function lsInner(gd) { + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var pad2 = gs.p; + var axList = Axes2.list(gd, "", true); + var i, subplot, plotinfo, ax, xa, ya; + fullLayout._paperdiv.style({ + width: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width ? "100%" : fullLayout.width + "px", + height: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height ? "100%" : fullLayout.height + "px" + }).selectAll(".main-svg").call(Drawing2.setSize, fullLayout.width, fullLayout.height); + gd._context.setBackground(gd, fullLayout.paper_bgcolor); + exports2.drawMainTitle(gd); + ModeBar2.manage(gd); + if (!fullLayout._has("cartesian")) { + return Plots2.previousPromises(gd); + } + function getLinePosition(ax2, counterAx2, side) { + var lwHalf = ax2._lw / 2; + if (ax2._id.charAt(0) === "x") { + if (!counterAx2) return gs.t + gs.h * (1 - (ax2.position || 0)) + lwHalf % 1; + else if (side === "top") return counterAx2._offset - pad2 - lwHalf; + return counterAx2._offset + counterAx2._length + pad2 + lwHalf; + } + if (!counterAx2) return gs.l + gs.w * (ax2.position || 0) + lwHalf % 1; + else if (side === "right") return counterAx2._offset + counterAx2._length + pad2 + lwHalf; + return counterAx2._offset - pad2 - lwHalf; + } + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + var counterAx = ax._anchorAxis; + ax._linepositions = {}; + ax._lw = Drawing2.crispRound(gd, ax.linewidth, 1); + ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side); + ax._mainMirrorPosition = ax.mirror && counterAx ? getLinePosition( + ax, + counterAx, + alignmentConstants2.OPPOSITE_SIDE[ax.side] + ) : null; + } + var lowerBackgroundIDs = []; + var backgroundIds = []; + var lowerDomains = []; + var noNeedForBg = Color2.opacity(fullLayout.paper_bgcolor) === 1 && Color2.opacity(fullLayout.plot_bgcolor) === 1 && fullLayout.paper_bgcolor === fullLayout.plot_bgcolor; + for (subplot in fullLayout._plots) { + plotinfo = fullLayout._plots[subplot]; + if (plotinfo.mainplot) { + if (plotinfo.bg) { + plotinfo.bg.remove(); + } + plotinfo.bg = void 0; + } else { + var xDomain = plotinfo.xaxis.domain; + var yDomain = plotinfo.yaxis.domain; + var plotgroup = plotinfo.plotgroup; + if (overlappingDomain(xDomain, yDomain, lowerDomains) && subplot.indexOf(zindexSeparator2) === -1) { + var pgNode = plotgroup.node(); + var plotgroupBg = plotinfo.bg = Lib2.ensureSingle(plotgroup, "rect", "bg"); + pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); + backgroundIds.push(subplot); + } else { + plotgroup.select("rect.bg").remove(); + lowerDomains.push([xDomain, yDomain]); + if (!noNeedForBg) { + lowerBackgroundIDs.push(subplot); + backgroundIds.push(subplot); + } + } + } + } + var lowerBackgrounds = fullLayout._bgLayer.selectAll(".bg").data(lowerBackgroundIDs); + lowerBackgrounds.enter().append("rect").classed("bg", true); + lowerBackgrounds.exit().remove(); + lowerBackgrounds.each(function(subplot2) { + fullLayout._plots[subplot2].bg = d32.select(this); + }); + for (i = 0; i < backgroundIds.length; i++) { + plotinfo = fullLayout._plots[backgroundIds[i]]; + xa = plotinfo.xaxis; + ya = plotinfo.yaxis; + if (plotinfo.bg && xa._offset !== void 0 && ya._offset !== void 0) { + plotinfo.bg.call( + Drawing2.setRect, + xa._offset - pad2, + ya._offset - pad2, + xa._length + 2 * pad2, + ya._length + 2 * pad2 + ).call(Color2.fill, fullLayout.plot_bgcolor).style("stroke-width", 0); + } + } + if (!fullLayout._hasOnlyLargeSploms) { + for (subplot in fullLayout._plots) { + plotinfo = fullLayout._plots[subplot]; + xa = plotinfo.xaxis; + ya = plotinfo.yaxis; + var clipId = plotinfo.clipId = "clip" + fullLayout._uid + subplot + "plot"; + var plotClip = Lib2.ensureSingleById(fullLayout._clips, "clipPath", clipId, function(s) { + s.classed("plotclip", true).append("rect"); + }); + plotinfo.clipRect = plotClip.select("rect").attr({ + width: xa._length, + height: ya._length + }); + Drawing2.setTranslate(plotinfo.plot, xa._offset, ya._offset); + var plotClipId; + var layerClipId; + if (plotinfo._hasClipOnAxisFalse) { + plotClipId = null; + layerClipId = clipId; + } else { + plotClipId = clipId; + layerClipId = null; + } + Drawing2.setClipUrl(plotinfo.plot, plotClipId, gd); + plotinfo.layerClipId = layerClipId; + } + } + var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop, leftYLineWidth, rightYLineWidth; + var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight, connectYBottom, connectYTop; + var extraSubplot; + function xLinePath(y) { + return "M" + xLinesXLeft + "," + y + "H" + xLinesXRight; + } + function xLinePathFree(y) { + return "M" + xa._offset + "," + y + "h" + xa._length; + } + function yLinePath(x) { + return "M" + x + "," + yLinesYTop + "V" + yLinesYBottom; + } + function yLinePathFree(x) { + if (ya._shift !== void 0) { + x += ya._shift; + } + return "M" + x + "," + ya._offset + "v" + ya._length; + } + function mainPath(ax2, pathFn, pathFnFree) { + if (!ax2.showline || subplot !== ax2._mainSubplot) return ""; + if (!ax2._anchorAxis) return pathFnFree(ax2._mainLinePosition); + var out = pathFn(ax2._mainLinePosition); + if (ax2.mirror) out += pathFn(ax2._mainMirrorPosition); + return out; + } + for (subplot in fullLayout._plots) { + plotinfo = fullLayout._plots[subplot]; + xa = plotinfo.xaxis; + ya = plotinfo.yaxis; + var xPath = "M0,0"; + if (shouldShowLinesOrTicks(xa, subplot)) { + leftYLineWidth = findCounterAxisLineWidth(xa, "left", ya, axList); + xLinesXLeft = xa._offset - (leftYLineWidth ? pad2 + leftYLineWidth : 0); + rightYLineWidth = findCounterAxisLineWidth(xa, "right", ya, axList); + xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? pad2 + rightYLineWidth : 0); + xLinesYBottom = getLinePosition(xa, ya, "bottom"); + xLinesYTop = getLinePosition(xa, ya, "top"); + extraSubplot = !xa._anchorAxis || subplot !== xa._mainSubplot; + if (extraSubplot && (xa.mirror === "allticks" || xa.mirror === "all")) { + xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop]; + } + xPath = mainPath(xa, xLinePath, xLinePathFree); + if (extraSubplot && xa.showline && (xa.mirror === "all" || xa.mirror === "allticks")) { + xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop); + } + plotinfo.xlines.style("stroke-width", xa._lw + "px").call(Color2.stroke, xa.showline ? xa.linecolor : "rgba(0,0,0,0)"); + } + plotinfo.xlines.attr("d", xPath); + var yPath = "M0,0"; + if (shouldShowLinesOrTicks(ya, subplot)) { + connectYBottom = findCounterAxisLineWidth(ya, "bottom", xa, axList); + yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad2 : 0); + connectYTop = findCounterAxisLineWidth(ya, "top", xa, axList); + yLinesYTop = ya._offset - (connectYTop ? pad2 : 0); + yLinesXLeft = getLinePosition(ya, xa, "left"); + yLinesXRight = getLinePosition(ya, xa, "right"); + extraSubplot = !ya._anchorAxis || subplot !== ya._mainSubplot; + if (extraSubplot && (ya.mirror === "allticks" || ya.mirror === "all")) { + ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight]; + } + yPath = mainPath(ya, yLinePath, yLinePathFree); + if (extraSubplot && ya.showline && (ya.mirror === "all" || ya.mirror === "allticks")) { + yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight); + } + plotinfo.ylines.style("stroke-width", ya._lw + "px").call(Color2.stroke, ya.showline ? ya.linecolor : "rgba(0,0,0,0)"); + } + plotinfo.ylines.attr("d", yPath); + } + Axes2.makeClipPaths(gd); + return Plots2.previousPromises(gd); + } + function shouldShowLinesOrTicks(ax, subplot) { + return (ax.ticks || ax.showline) && (subplot === ax._mainSubplot || ax.mirror === "all" || ax.mirror === "allticks"); + } + function shouldShowLineThisSide(ax, side, counterAx) { + if (!counterAx.showline || !counterAx._lw) return false; + if (counterAx.mirror === "all" || counterAx.mirror === "allticks") return true; + var anchorAx = counterAx._anchorAxis; + if (!anchorAx) return false; + var sideIndex = alignmentConstants2.FROM_BL[side]; + if (counterAx.side === side) { + return anchorAx.domain[sideIndex] === ax.domain[sideIndex]; + } + return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex]; + } + function findCounterAxisLineWidth(ax, side, counterAx, axList) { + if (shouldShowLineThisSide(ax, side, counterAx)) { + return counterAx._lw; + } + for (var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if (axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) { + return axi._lw; + } + } + return 0; + } + exports2.drawMainTitle = function(gd) { + var title = gd._fullLayout.title; + var fullLayout = gd._fullLayout; + var textAnchor = getMainTitleTextAnchor(fullLayout); + var dy = getMainTitleDy(fullLayout); + var y = getMainTitleY(fullLayout, dy); + var x = getMainTitleX(fullLayout, textAnchor); + Titles2.draw(gd, "gtitle", { + propContainer: fullLayout, + propName: "title.text", + subtitlePropName: "title.subtitle.text", + placeholder: fullLayout._dfltTitle.plot, + subtitlePlaceholder: fullLayout._dfltTitle.subtitle, + attributes: { + x, + y, + "text-anchor": textAnchor, + dy + } + }); + if (title.text && title.automargin) { + var titleObj = d32.selectAll(".gtitle"); + var titleHeight = Drawing2.bBox(d32.selectAll(".g-gtitle").node()).height; + var pushMargin = needsMarginPush(gd, title, titleHeight); + if (pushMargin > 0) { + applyTitleAutoMargin(gd, y, pushMargin, titleHeight); + titleObj.attr({ + x, + y, + "text-anchor": textAnchor, + dy: getMainTitleDyAdj(title.yanchor) + }).call(svgTextUtils2.positionText, x, y); + var extraLines = (title.text.match(svgTextUtils2.BR_TAG_ALL) || []).length; + if (extraLines) { + var delta2 = alignmentConstants2.LINE_SPACING * extraLines + alignmentConstants2.MID_SHIFT; + if (title.y === 0) { + delta2 = -delta2; + } + titleObj.selectAll(".line").each(function() { + var newDy = +this.getAttribute("dy").slice(0, -2) - delta2 + "em"; + this.setAttribute("dy", newDy); + }); + } + var subtitleObj = d32.selectAll(".gtitle-subtitle"); + if (subtitleObj.node()) { + var titleBB = titleObj.node().getBBox(); + var titleBottom = titleBB.y + titleBB.height; + var subtitleY = titleBottom + Titles2.SUBTITLE_PADDING_EM * title.subtitle.font.size; + subtitleObj.attr({ + x, + y: subtitleY, + "text-anchor": textAnchor, + dy: getMainTitleDyAdj(title.yanchor) + }).call(svgTextUtils2.positionText, x, subtitleY); + } + } + } + }; + function isOutsideContainer(gd, title, position, y, titleHeight) { + var plotHeight = title.yref === "paper" ? gd._fullLayout._size.h : gd._fullLayout.height; + var yPosTop = Lib2.isTopAnchor(title) ? y : y - titleHeight; + var yPosRel = position === "b" ? plotHeight - yPosTop : yPosTop; + if (Lib2.isTopAnchor(title) && position === "t" || Lib2.isBottomAnchor(title) && position === "b") { + return false; + } else { + return yPosRel < titleHeight; + } + } + function containerPushVal(position, titleY, titleYanchor, height, titleDepth) { + var push = 0; + if (titleYanchor === "middle") { + push += titleDepth / 2; + } + if (position === "t") { + if (titleYanchor === "top") { + push += titleDepth; + } + push += height - titleY * height; + } else { + if (titleYanchor === "bottom") { + push += titleDepth; + } + push += titleY * height; + } + return push; + } + function needsMarginPush(gd, title, titleHeight) { + var titleY = title.y; + var titleYanchor = title.yanchor; + var position = titleY > 0.5 ? "t" : "b"; + var curMargin = gd._fullLayout.margin[position]; + var pushMargin = 0; + if (title.yref === "paper") { + pushMargin = titleHeight + title.pad.t + title.pad.b; + } else if (title.yref === "container") { + pushMargin = containerPushVal(position, titleY, titleYanchor, gd._fullLayout.height, titleHeight) + title.pad.t + title.pad.b; + } + if (pushMargin > curMargin) { + return pushMargin; + } + return 0; + } + function applyTitleAutoMargin(gd, y, pushMargin, titleHeight) { + var titleID = "title.automargin"; + var title = gd._fullLayout.title; + var position = title.y > 0.5 ? "t" : "b"; + var push = { + x: title.x, + y: title.y, + t: 0, + b: 0 + }; + var reservedPush = {}; + if (title.yref === "paper" && isOutsideContainer(gd, title, position, y, titleHeight)) { + push[position] = pushMargin; + } else if (title.yref === "container") { + reservedPush[position] = pushMargin; + gd._fullLayout._reservedMargin[titleID] = reservedPush; + } + Plots2.allowAutoMargin(gd, titleID); + Plots2.autoMargin(gd, titleID, push); + } + function getMainTitleX(fullLayout, textAnchor) { + var title = fullLayout.title; + var gs = fullLayout._size; + var hPadShift = 0; + if (textAnchor === SVG_TEXT_ANCHOR_START) { + hPadShift = title.pad.l; + } else if (textAnchor === SVG_TEXT_ANCHOR_END) { + hPadShift = -title.pad.r; + } + switch (title.xref) { + case "paper": + return gs.l + gs.w * title.x + hPadShift; + case "container": + default: + return fullLayout.width * title.x + hPadShift; + } + } + function getMainTitleY(fullLayout, dy) { + var title = fullLayout.title; + var gs = fullLayout._size; + var vPadShift = 0; + if (dy === "0em" || !dy) { + vPadShift = -title.pad.b; + } else if (dy === alignmentConstants2.CAP_SHIFT + "em") { + vPadShift = title.pad.t; + } + if (title.y === "auto") { + return gs.t / 2; + } else { + switch (title.yref) { + case "paper": + return gs.t + gs.h - gs.h * title.y + vPadShift; + case "container": + default: + return fullLayout.height - fullLayout.height * title.y + vPadShift; + } + } + } + function getMainTitleDyAdj(yanchor) { + if (yanchor === "top") { + return alignmentConstants2.CAP_SHIFT + 0.3 + "em"; + } else if (yanchor === "bottom") { + return "-0.3em"; + } else { + return alignmentConstants2.MID_SHIFT + "em"; + } + } + function getMainTitleTextAnchor(fullLayout) { + var title = fullLayout.title; + var textAnchor = SVG_TEXT_ANCHOR_MIDDLE; + if (Lib2.isRightAnchor(title)) { + textAnchor = SVG_TEXT_ANCHOR_END; + } else if (Lib2.isLeftAnchor(title)) { + textAnchor = SVG_TEXT_ANCHOR_START; + } + return textAnchor; + } + function getMainTitleDy(fullLayout) { + var title = fullLayout.title; + var dy = "0em"; + if (Lib2.isTopAnchor(title)) { + dy = alignmentConstants2.CAP_SHIFT + "em"; + } else if (Lib2.isMiddleAnchor(title)) { + dy = alignmentConstants2.MID_SHIFT + "em"; + } + return dy; + } + exports2.doTraceStyle = function(gd) { + var calcdata = gd.calcdata; + var editStyleCalls = []; + var i; + for (i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var cd0 = cd[0] || {}; + var trace = cd0.trace || {}; + var _module = trace._module || {}; + var arraysToCalcdata4 = _module.arraysToCalcdata; + if (arraysToCalcdata4) arraysToCalcdata4(cd, trace); + var editStyle = _module.editStyle; + if (editStyle) editStyleCalls.push({ fn: editStyle, cd0 }); + } + if (editStyleCalls.length) { + for (i = 0; i < editStyleCalls.length; i++) { + var edit = editStyleCalls[i]; + edit.fn(gd, edit.cd0); + } + clearGlCanvases3(gd); + exports2.redrawReglTraces(gd); + } + Plots2.style(gd); + Registry2.getComponentMethod("legend", "draw")(gd); + return Plots2.previousPromises(gd); + }; + exports2.doColorBars = function(gd) { + Registry2.getComponentMethod("colorbar", "draw")(gd); + return Plots2.previousPromises(gd); + }; + exports2.layoutReplot = function(gd) { + var layout = gd.layout; + gd.layout = void 0; + return Registry2.call("_doPlot", gd, "", layout); + }; + exports2.doLegend = function(gd) { + Registry2.getComponentMethod("legend", "draw")(gd); + return Plots2.previousPromises(gd); + }; + exports2.doTicksRelayout = function(gd) { + Axes2.draw(gd, "redraw"); + if (gd._fullLayout._hasOnlyLargeSploms) { + Registry2.subplotsRegistry.splom.updateGrid(gd); + clearGlCanvases3(gd); + exports2.redrawReglTraces(gd); + } + exports2.drawMainTitle(gd); + return Plots2.previousPromises(gd); + }; + exports2.doModeBar = function(gd) { + var fullLayout = gd._fullLayout; + ModeBar2.manage(gd); + for (var i = 0; i < fullLayout._basePlotModules.length; i++) { + var updateFx = fullLayout._basePlotModules[i].updateFx; + if (updateFx) updateFx(gd); + } + return Plots2.previousPromises(gd); + }; + exports2.doCamera = function(gd) { + var fullLayout = gd._fullLayout; + var sceneIds = fullLayout._subplots.gl3d; + for (var i = 0; i < sceneIds.length; i++) { + var sceneLayout = fullLayout[sceneIds[i]]; + var scene = sceneLayout._scene; + scene.setViewport(sceneLayout); + } + }; + exports2.drawData = function(gd) { + var fullLayout = gd._fullLayout; + clearGlCanvases3(gd); + var basePlotModules = fullLayout._basePlotModules; + for (var i = 0; i < basePlotModules.length; i++) { + basePlotModules[i].plot(gd); + } + exports2.redrawReglTraces(gd); + Plots2.style(gd); + Registry2.getComponentMethod("selections", "draw")(gd); + Registry2.getComponentMethod("shapes", "draw")(gd); + Registry2.getComponentMethod("annotations", "draw")(gd); + Registry2.getComponentMethod("images", "draw")(gd); + fullLayout._replotting = false; + return Plots2.previousPromises(gd); + }; + exports2.redrawReglTraces = function(gd) { + var fullLayout = gd._fullLayout; + if (fullLayout._has("regl")) { + var fullData = gd._fullData; + var cartesianIds = []; + var polarIds = []; + var i, sp; + if (fullLayout._hasOnlyLargeSploms) { + fullLayout._splomGrid.draw(); + } + for (i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if (trace.visible === true && trace._length !== 0) { + if (trace.type === "splom") { + fullLayout._splomScenes[trace.uid].draw(); + } else if (trace.type === "scattergl") { + Lib2.pushUnique(cartesianIds, trace.xaxis + trace.yaxis); + } else if (trace.type === "scatterpolargl") { + Lib2.pushUnique(polarIds, trace.subplot); + } + } + } + for (i = 0; i < cartesianIds.length; i++) { + sp = fullLayout._plots[cartesianIds[i]]; + if (sp._scene) sp._scene.draw(); + } + for (i = 0; i < polarIds.length; i++) { + sp = fullLayout[polarIds[i]]._subplot; + if (sp._scene) sp._scene.draw(); + } + } + }; + exports2.doAutoRangeAndConstraints = function(gd) { + var axList = Axes2.list(gd, "", true); + var ax; + var autoRangeDone = {}; + for (var i = 0; i < axList.length; i++) { + ax = axList[i]; + if (!autoRangeDone[ax._id]) { + autoRangeDone[ax._id] = 1; + cleanAxisConstraints(gd, ax); + doAutoRange2(gd, ax); + var matchGroup = ax._matchGroup; + if (matchGroup) { + for (var id2 in matchGroup) { + var ax2 = Axes2.getFromId(gd, id2); + doAutoRange2(gd, ax2, ax.range); + autoRangeDone[id2] = 1; + } + } + } + } + enforceAxisConstraints(gd); + }; + exports2.finalDraw = function(gd) { + Registry2.getComponentMethod("rangeslider", "draw")(gd); + Registry2.getComponentMethod("rangeselector", "draw")(gd); + }; + exports2.drawMarginPushers = function(gd) { + Registry2.getComponentMethod("legend", "draw")(gd); + Registry2.getComponentMethod("rangeselector", "draw")(gd); + Registry2.getComponentMethod("sliders", "draw")(gd); + Registry2.getComponentMethod("updatemenus", "draw")(gd); + Registry2.getComponentMethod("colorbar", "draw")(gd); + }; +})(subroutines); +var readPaths$1 = helpers$A.readPaths; +var displayOutlines$1 = display_outlines; +var clearOutlineControllers = handle_outline.clearOutlineControllers; +var Color$x = colorExports; +var Drawing$l = drawingExports; +var arrayEditor$4 = plot_template.arrayEditor; +var helpers$s = helpers$w; +var getPathString = helpers$s.getPathString; +var draw_1$2 = { + draw: draw$b, + drawOne: drawOne$1, + activateLastSelection: activateLastSelection$1 +}; +function draw$b(gd) { + var fullLayout = gd._fullLayout; + clearOutlineControllers(gd); + fullLayout._selectionLayer.selectAll("path").remove(); + for (var k in fullLayout._plots) { + var selectionLayer = fullLayout._plots[k].selectionLayer; + if (selectionLayer) selectionLayer.selectAll("path").remove(); + } + for (var i = 0; i < fullLayout.selections.length; i++) { + drawOne$1(gd, i); + } +} +function couldHaveActiveSelection(gd) { + return gd._context.editSelection; +} +function drawOne$1(gd, index2) { + gd._fullLayout._paperdiv.selectAll('.selectionlayer [data-index="' + index2 + '"]').remove(); + var o = helpers$s.makeSelectionsOptionsAndPlotinfo(gd, index2); + var options = o.options; + var plotinfo = o.plotinfo; + if (!options._input) return; + drawSelection(gd._fullLayout._selectionLayer); + function drawSelection(selectionLayer) { + var d = getPathString(gd, options); + var attrs2 = { + "data-index": index2, + "fill-rule": "evenodd", + d + }; + var opacity = options.opacity; + var fillColor = "rgba(0,0,0,0)"; + var lineColor = options.line.color || Color$x.contrast(gd._fullLayout.plot_bgcolor); + var lineWidth = options.line.width; + var lineDash = options.line.dash; + if (!lineWidth) { + lineWidth = 5; + lineDash = "solid"; + } + var isActiveSelection = couldHaveActiveSelection(gd) && gd._fullLayout._activeSelectionIndex === index2; + if (isActiveSelection) { + fillColor = gd._fullLayout.activeselection.fillcolor; + opacity = gd._fullLayout.activeselection.opacity; + } + var allPaths = []; + for (var sensory = 1; sensory >= 0; sensory--) { + var path = selectionLayer.append("path").attr(attrs2).style("opacity", sensory ? 0.1 : opacity).call(Color$x.stroke, lineColor).call(Color$x.fill, fillColor).call( + Drawing$l.dashLine, + sensory ? "solid" : lineDash, + sensory ? 4 + lineWidth : lineWidth + ); + setClipPath(path, gd, options); + if (isActiveSelection) { + var editHelpers = arrayEditor$4(gd.layout, "selections", options); + path.style({ + cursor: "move" + }); + var dragOptions = { + element: path.node(), + plotinfo, + gd, + editHelpers, + isActiveSelection: true + // i.e. to enable controllers + }; + var polygons = readPaths$1(d, gd); + displayOutlines$1(polygons, path, dragOptions); + } else { + path.style("pointer-events", sensory ? "all" : "none"); + } + allPaths[sensory] = path; + } + var forePath = allPaths[0]; + var backPath = allPaths[1]; + backPath.node().addEventListener("click", function() { + return activateSelection(gd, forePath); + }); + } +} +function setClipPath(selectionPath, gd, selectionOptions) { + var clipAxes = selectionOptions.xref + selectionOptions.yref; + Drawing$l.setClipUrl( + selectionPath, + "clip" + gd._fullLayout._uid + clipAxes, + gd + ); +} +function activateSelection(gd, path) { + if (!couldHaveActiveSelection(gd)) return; + var element = path.node(); + var id = +element.getAttribute("data-index"); + if (id >= 0) { + if (id === gd._fullLayout._activeSelectionIndex) { + deactivateSelection(gd); + return; + } + gd._fullLayout._activeSelectionIndex = id; + gd._fullLayout._deactivateSelection = deactivateSelection; + draw$b(gd); + } +} +function activateLastSelection$1(gd) { + if (!couldHaveActiveSelection(gd)) return; + var id = gd._fullLayout.selections.length - 1; + gd._fullLayout._activeSelectionIndex = id; + gd._fullLayout._deactivateSelection = deactivateSelection; + draw$b(gd); +} +function deactivateSelection(gd) { + if (!couldHaveActiveSelection(gd)) return; + var id = gd._fullLayout._activeSelectionIndex; + if (id >= 0) { + clearOutlineControllers(gd); + delete gd._fullLayout._activeSelectionIndex; + draw$b(gd); + } +} +function BuildLog$1() { + var my; + var nextSegmentId = 0; + var curVert = false; + function push(type, data) { + my.list.push({ + type, + data: data ? JSON.parse(JSON.stringify(data)) : void 0 + }); + return my; + } + my = { + list: [], + segmentId: function() { + return nextSegmentId++; + }, + checkIntersection: function(seg1, seg2) { + return push("check", { seg1, seg2 }); + }, + segmentChop: function(seg, end) { + push("div_seg", { seg, pt: end }); + return push("chop", { seg, pt: end }); + }, + statusRemove: function(seg) { + return push("pop_seg", { seg }); + }, + segmentUpdate: function(seg) { + return push("seg_update", { seg }); + }, + segmentNew: function(seg, primary) { + return push("new_seg", { seg, primary }); + }, + segmentRemove: function(seg) { + return push("rem_seg", { seg }); + }, + tempStatus: function(seg, above, below) { + return push("temp_status", { seg, above, below }); + }, + rewind: function(seg) { + return push("rewind", { seg }); + }, + status: function(seg, above, below) { + return push("status", { seg, above, below }); + }, + vert: function(x) { + if (x === curVert) + return my; + curVert = x; + return push("vert", { x }); + }, + log: function(data) { + if (typeof data !== "string") + data = JSON.stringify(data, false, " "); + return push("log", { txt: data }); + }, + reset: function() { + return push("reset"); + }, + selected: function(segs) { + return push("selected", { segs }); + }, + chainStart: function(seg) { + return push("chain_start", { seg }); + }, + chainRemoveHead: function(index2, pt) { + return push("chain_rem_head", { index: index2, pt }); + }, + chainRemoveTail: function(index2, pt) { + return push("chain_rem_tail", { index: index2, pt }); + }, + chainNew: function(pt1, pt2) { + return push("chain_new", { pt1, pt2 }); + }, + chainMatch: function(index2) { + return push("chain_match", { index: index2 }); + }, + chainClose: function(index2) { + return push("chain_close", { index: index2 }); + }, + chainAddHead: function(index2, pt) { + return push("chain_add_head", { index: index2, pt }); + }, + chainAddTail: function(index2, pt) { + return push("chain_add_tail", { index: index2, pt }); + }, + chainConnect: function(index1, index2) { + return push("chain_con", { index1, index2 }); + }, + chainReverse: function(index2) { + return push("chain_rev", { index: index2 }); + }, + chainJoin: function(index1, index2) { + return push("chain_join", { index1, index2 }); + }, + done: function() { + return push("done"); + } + }; + return my; +} +var buildLog$1 = BuildLog$1; +function Epsilon$1(eps) { + if (typeof eps !== "number") + eps = 1e-10; + var my = { + epsilon: function(v) { + if (typeof v === "number") + eps = v; + return eps; + }, + pointAboveOrOnLine: function(pt, left, right) { + var Ax = left[0]; + var Ay = left[1]; + var Bx = right[0]; + var By = right[1]; + var Cx = pt[0]; + var Cy = pt[1]; + return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; + }, + pointBetween: function(p, left, right) { + var d_py_ly = p[1] - left[1]; + var d_rx_lx = right[0] - left[0]; + var d_px_lx = p[0] - left[0]; + var d_ry_ly = right[1] - left[1]; + var dot2 = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; + if (dot2 < eps) + return false; + var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; + if (dot2 - sqlen > -eps) + return false; + return true; + }, + pointsSameX: function(p1, p2) { + return Math.abs(p1[0] - p2[0]) < eps; + }, + pointsSameY: function(p1, p2) { + return Math.abs(p1[1] - p2[1]) < eps; + }, + pointsSame: function(p1, p2) { + return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); + }, + pointsCompare: function(p1, p2) { + if (my.pointsSameX(p1, p2)) + return my.pointsSameY(p1, p2) ? 0 : p1[1] < p2[1] ? -1 : 1; + return p1[0] < p2[0] ? -1 : 1; + }, + pointsCollinear: function(pt1, pt2, pt3) { + var dx1 = pt1[0] - pt2[0]; + var dy1 = pt1[1] - pt2[1]; + var dx2 = pt2[0] - pt3[0]; + var dy2 = pt2[1] - pt3[1]; + return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; + }, + linesIntersect: function(a0, a1, b0, b1) { + var adx = a1[0] - a0[0]; + var ady = a1[1] - a0[1]; + var bdx = b1[0] - b0[0]; + var bdy = b1[1] - b0[1]; + var axb = adx * bdy - ady * bdx; + if (Math.abs(axb) < eps) + return false; + var dx = a0[0] - b0[0]; + var dy = a0[1] - b0[1]; + var A2 = (bdx * dy - bdy * dx) / axb; + var B2 = (adx * dy - ady * dx) / axb; + var ret = { + alongA: 0, + alongB: 0, + pt: [ + a0[0] + A2 * adx, + a0[1] + A2 * ady + ] + }; + if (A2 <= -eps) + ret.alongA = -2; + else if (A2 < eps) + ret.alongA = -1; + else if (A2 - 1 <= -eps) + ret.alongA = 0; + else if (A2 - 1 < eps) + ret.alongA = 1; + else + ret.alongA = 2; + if (B2 <= -eps) + ret.alongB = -2; + else if (B2 < eps) + ret.alongB = -1; + else if (B2 - 1 <= -eps) + ret.alongB = 0; + else if (B2 - 1 < eps) + ret.alongB = 1; + else + ret.alongB = 2; + return ret; + }, + pointInsideRegion: function(pt, region) { + var x = pt[0]; + var y = pt[1]; + var last_x = region[region.length - 1][0]; + var last_y = region[region.length - 1][1]; + var inside = false; + for (var i = 0; i < region.length; i++) { + var curr_x = region[i][0]; + var curr_y = region[i][1]; + if (curr_y - y > eps != last_y - y > eps && (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) + inside = !inside; + last_x = curr_x; + last_y = curr_y; + } + return inside; + } + }; + return my; +} +var epsilon$1 = Epsilon$1; +var LinkedList$1 = { + create: function() { + var my = { + root: { root: true, next: null }, + exists: function(node) { + if (node === null || node === my.root) + return false; + return true; + }, + isEmpty: function() { + return my.root.next === null; + }, + getHead: function() { + return my.root.next; + }, + insertBefore: function(node, check) { + var last = my.root; + var here = my.root.next; + while (here !== null) { + if (check(here)) { + node.prev = here.prev; + node.next = here; + here.prev.next = node; + here.prev = node; + return; + } + last = here; + here = here.next; + } + last.next = node; + node.prev = last; + node.next = null; + }, + findTransition: function(check) { + var prev = my.root; + var here = my.root.next; + while (here !== null) { + if (check(here)) + break; + prev = here; + here = here.next; + } + return { + before: prev === my.root ? null : prev, + after: here, + insert: function(node) { + node.prev = prev; + node.next = here; + prev.next = node; + if (here !== null) + here.prev = node; + return node; + } + }; + } + }; + return my; + }, + node: function(data) { + data.prev = null; + data.next = null; + data.remove = function() { + data.prev.next = data.next; + if (data.next) + data.next.prev = data.prev; + data.prev = null; + data.next = null; + }; + return data; + } +}; +var linkedList$1 = LinkedList$1; +var LinkedList = linkedList$1; +function Intersecter$1(selfIntersection, eps, buildLog2) { + function segmentNew(start, end) { + return { + id: buildLog2 ? buildLog2.segmentId() : -1, + start, + end, + myFill: { + above: null, + // is there fill above us? + below: null + // is there fill below us? + }, + otherFill: null + }; + } + function segmentCopy(start, end, seg) { + return { + id: buildLog2 ? buildLog2.segmentId() : -1, + start, + end, + myFill: { + above: seg.myFill.above, + below: seg.myFill.below + }, + otherFill: null + }; + } + var event_root = LinkedList.create(); + function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2) { + var comp = eps.pointsCompare(p1_1, p2_1); + if (comp !== 0) + return comp; + if (eps.pointsSame(p1_2, p2_2)) + return 0; + if (p1_isStart !== p2_isStart) + return p1_isStart ? 1 : -1; + return eps.pointAboveOrOnLine( + p1_2, + p2_isStart ? p2_1 : p2_2, + // order matters + p2_isStart ? p2_2 : p2_1 + ) ? 1 : -1; + } + function eventAdd(ev, other_pt) { + event_root.insertBefore(ev, function(here) { + var comp = eventCompare( + ev.isStart, + ev.pt, + other_pt, + here.isStart, + here.pt, + here.other.pt + ); + return comp < 0; + }); + } + function eventAddSegmentStart(seg, primary) { + var ev_start = LinkedList.node({ + isStart: true, + pt: seg.start, + seg, + primary, + other: null, + status: null + }); + eventAdd(ev_start, seg.end); + return ev_start; + } + function eventAddSegmentEnd(ev_start, seg, primary) { + var ev_end = LinkedList.node({ + isStart: false, + pt: seg.end, + seg, + primary, + other: ev_start, + status: null + }); + ev_start.other = ev_end; + eventAdd(ev_end, ev_start.pt); + } + function eventAddSegment(seg, primary) { + var ev_start = eventAddSegmentStart(seg, primary); + eventAddSegmentEnd(ev_start, seg, primary); + return ev_start; + } + function eventUpdateEnd(ev, end) { + if (buildLog2) + buildLog2.segmentChop(ev.seg, end); + ev.other.remove(); + ev.seg.end = end; + ev.other.pt = end; + eventAdd(ev.other, ev.pt); + } + function eventDivide(ev, pt) { + var ns = segmentCopy(pt, ev.seg.end, ev.seg); + eventUpdateEnd(ev, pt); + return eventAddSegment(ns, ev.primary); + } + function calculate(primaryPolyInverted, secondaryPolyInverted) { + var status_root = LinkedList.create(); + function statusCompare(ev1, ev2) { + var a1 = ev1.seg.start; + var a2 = ev1.seg.end; + var b1 = ev2.seg.start; + var b2 = ev2.seg.end; + if (eps.pointsCollinear(a1, b1, b2)) { + if (eps.pointsCollinear(a2, b1, b2)) + return 1; + return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; + } + return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; + } + function statusFindSurrounding(ev2) { + return status_root.findTransition(function(here) { + var comp = statusCompare(ev2, here.ev); + return comp > 0; + }); + } + function checkIntersection(ev1, ev2) { + var seg1 = ev1.seg; + var seg2 = ev2.seg; + var a1 = seg1.start; + var a2 = seg1.end; + var b1 = seg2.start; + var b2 = seg2.end; + if (buildLog2) + buildLog2.checkIntersection(seg1, seg2); + var i = eps.linesIntersect(a1, a2, b1, b2); + if (i === false) { + if (!eps.pointsCollinear(a1, a2, b1)) + return false; + if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) + return false; + var a1_equ_b1 = eps.pointsSame(a1, b1); + var a2_equ_b2 = eps.pointsSame(a2, b2); + if (a1_equ_b1 && a2_equ_b2) + return ev2; + var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); + var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); + if (a1_equ_b1) { + if (a2_between) { + eventDivide(ev2, a2); + } else { + eventDivide(ev1, b2); + } + return ev2; + } else if (a1_between) { + if (!a2_equ_b2) { + if (a2_between) { + eventDivide(ev2, a2); + } else { + eventDivide(ev1, b2); + } + } + eventDivide(ev2, a1); + } + } else { + if (i.alongA === 0) { + if (i.alongB === -1) + eventDivide(ev1, b1); + else if (i.alongB === 0) + eventDivide(ev1, i.pt); + else if (i.alongB === 1) + eventDivide(ev1, b2); + } + if (i.alongB === 0) { + if (i.alongA === -1) + eventDivide(ev2, a1); + else if (i.alongA === 0) + eventDivide(ev2, i.pt); + else if (i.alongA === 1) + eventDivide(ev2, a2); + } + } + return false; + } + var segments = []; + while (!event_root.isEmpty()) { + var ev = event_root.getHead(); + if (buildLog2) + buildLog2.vert(ev.pt[0]); + if (ev.isStart) { + let checkBothIntersections = function() { + if (above) { + var eve2 = checkIntersection(ev, above); + if (eve2) + return eve2; + } + if (below) + return checkIntersection(ev, below); + return false; + }; + if (buildLog2) + buildLog2.segmentNew(ev.seg, ev.primary); + var surrounding = statusFindSurrounding(ev); + var above = surrounding.before ? surrounding.before.ev : null; + var below = surrounding.after ? surrounding.after.ev : null; + if (buildLog2) { + buildLog2.tempStatus( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + var eve = checkBothIntersections(); + if (eve) { + if (selfIntersection) { + var toggle; + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + if (toggle) + eve.seg.myFill.above = !eve.seg.myFill.above; + } else { + eve.seg.otherFill = ev.seg.myFill; + } + if (buildLog2) + buildLog2.segmentUpdate(eve.seg); + ev.other.remove(); + ev.remove(); + } + if (event_root.getHead() !== ev) { + if (buildLog2) + buildLog2.rewind(ev.seg); + continue; + } + if (selfIntersection) { + var toggle; + if (ev.seg.myFill.below === null) + toggle = true; + else + toggle = ev.seg.myFill.above !== ev.seg.myFill.below; + if (!below) { + ev.seg.myFill.below = primaryPolyInverted; + } else { + ev.seg.myFill.below = below.seg.myFill.above; + } + if (toggle) + ev.seg.myFill.above = !ev.seg.myFill.below; + else + ev.seg.myFill.above = ev.seg.myFill.below; + } else { + if (ev.seg.otherFill === null) { + var inside; + if (!below) { + inside = ev.primary ? secondaryPolyInverted : primaryPolyInverted; + } else { + if (ev.primary === below.primary) + inside = below.seg.otherFill.above; + else + inside = below.seg.myFill.above; + } + ev.seg.otherFill = { + above: inside, + below: inside + }; + } + } + if (buildLog2) { + buildLog2.status( + ev.seg, + above ? above.seg : false, + below ? below.seg : false + ); + } + ev.other.status = surrounding.insert(LinkedList.node({ ev })); + } else { + var st = ev.status; + if (st === null) { + throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large"); + } + if (status_root.exists(st.prev) && status_root.exists(st.next)) + checkIntersection(st.prev.ev, st.next.ev); + if (buildLog2) + buildLog2.statusRemove(st.ev.seg); + st.remove(); + if (!ev.primary) { + var s = ev.seg.myFill; + ev.seg.myFill = ev.seg.otherFill; + ev.seg.otherFill = s; + } + segments.push(ev.seg); + } + event_root.getHead().remove(); + } + if (buildLog2) + buildLog2.done(); + return segments; + } + if (!selfIntersection) { + return { + calculate: function(segments1, inverted1, segments2, inverted2) { + segments1.forEach(function(seg) { + eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); + }); + segments2.forEach(function(seg) { + eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); + }); + return calculate(inverted1, inverted2); + } + }; + } + return { + addRegion: function(region) { + var pt1; + var pt2 = region[region.length - 1]; + for (var i = 0; i < region.length; i++) { + pt1 = pt2; + pt2 = region[i]; + var forward = eps.pointsCompare(pt1, pt2); + if (forward === 0) + continue; + eventAddSegment( + segmentNew( + forward < 0 ? pt1 : pt2, + forward < 0 ? pt2 : pt1 + ), + true + ); + } + }, + calculate: function(inverted) { + return calculate(inverted, false); + } + }; +} +var intersecter = Intersecter$1; +function SegmentChainer$1(segments, eps, buildLog2) { + var chains = []; + var regions = []; + segments.forEach(function(seg) { + var pt1 = seg.start; + var pt2 = seg.end; + if (eps.pointsSame(pt1, pt2)) { + console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large"); + return; + } + if (buildLog2) + buildLog2.chainStart(seg); + var first_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var second_match = { + index: 0, + matches_head: false, + matches_pt1: false + }; + var next_match = first_match; + function setMatch(index3, matches_head, matches_pt1) { + next_match.index = index3; + next_match.matches_head = matches_head; + next_match.matches_pt1 = matches_pt1; + if (next_match === first_match) { + next_match = second_match; + return false; + } + next_match = null; + return true; + } + for (var i = 0; i < chains.length; i++) { + var chain = chains[i]; + var head = chain[0]; + chain[1]; + var tail = chain[chain.length - 1]; + chain[chain.length - 2]; + if (eps.pointsSame(head, pt1)) { + if (setMatch(i, true, true)) + break; + } else if (eps.pointsSame(head, pt2)) { + if (setMatch(i, true, false)) + break; + } else if (eps.pointsSame(tail, pt1)) { + if (setMatch(i, false, true)) + break; + } else if (eps.pointsSame(tail, pt2)) { + if (setMatch(i, false, false)) + break; + } + } + if (next_match === first_match) { + chains.push([pt1, pt2]); + if (buildLog2) + buildLog2.chainNew(pt1, pt2); + return; + } + if (next_match === second_match) { + if (buildLog2) + buildLog2.chainMatch(first_match.index); + var index2 = first_match.index; + var pt = first_match.matches_pt1 ? pt2 : pt1; + var addToHead = first_match.matches_head; + var chain = chains[index2]; + var grow = addToHead ? chain[0] : chain[chain.length - 1]; + var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; + var oppo = addToHead ? chain[chain.length - 1] : chain[0]; + var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; + if (eps.pointsCollinear(grow2, grow, pt)) { + if (addToHead) { + if (buildLog2) + buildLog2.chainRemoveHead(first_match.index, pt); + chain.shift(); + } else { + if (buildLog2) + buildLog2.chainRemoveTail(first_match.index, pt); + chain.pop(); + } + grow = grow2; + } + if (eps.pointsSame(oppo, pt)) { + chains.splice(index2, 1); + if (eps.pointsCollinear(oppo2, oppo, grow)) { + if (addToHead) { + if (buildLog2) + buildLog2.chainRemoveTail(first_match.index, grow); + chain.pop(); + } else { + if (buildLog2) + buildLog2.chainRemoveHead(first_match.index, grow); + chain.shift(); + } + } + if (buildLog2) + buildLog2.chainClose(first_match.index); + regions.push(chain); + return; + } + if (addToHead) { + if (buildLog2) + buildLog2.chainAddHead(first_match.index, pt); + chain.unshift(pt); + } else { + if (buildLog2) + buildLog2.chainAddTail(first_match.index, pt); + chain.push(pt); + } + return; + } + function reverseChain(index3) { + if (buildLog2) + buildLog2.chainReverse(index3); + chains[index3].reverse(); + } + function appendChain(index1, index22) { + var chain1 = chains[index1]; + var chain2 = chains[index22]; + var tail2 = chain1[chain1.length - 1]; + var tail22 = chain1[chain1.length - 2]; + var head2 = chain2[0]; + var head22 = chain2[1]; + if (eps.pointsCollinear(tail22, tail2, head2)) { + if (buildLog2) + buildLog2.chainRemoveTail(index1, tail2); + chain1.pop(); + tail2 = tail22; + } + if (eps.pointsCollinear(tail2, head2, head22)) { + if (buildLog2) + buildLog2.chainRemoveHead(index22, head2); + chain2.shift(); + } + if (buildLog2) + buildLog2.chainJoin(index1, index22); + chains[index1] = chain1.concat(chain2); + chains.splice(index22, 1); + } + var F = first_match.index; + var S = second_match.index; + if (buildLog2) + buildLog2.chainConnect(F, S); + var reverseF = chains[F].length < chains[S].length; + if (first_match.matches_head) { + if (second_match.matches_head) { + if (reverseF) { + reverseChain(F); + appendChain(F, S); + } else { + reverseChain(S); + appendChain(S, F); + } + } else { + appendChain(S, F); + } + } else { + if (second_match.matches_head) { + appendChain(F, S); + } else { + if (reverseF) { + reverseChain(F); + appendChain(S, F); + } else { + reverseChain(S); + appendChain(F, S); + } + } + } + }); + return regions; +} +var segmentChainer = SegmentChainer$1; +function select$6(segments, selection, buildLog2) { + var result = []; + segments.forEach(function(seg) { + var index2 = (seg.myFill.above ? 8 : 0) + (seg.myFill.below ? 4 : 0) + (seg.otherFill && seg.otherFill.above ? 2 : 0) + (seg.otherFill && seg.otherFill.below ? 1 : 0); + if (selection[index2] !== 0) { + result.push({ + id: buildLog2 ? buildLog2.segmentId() : -1, + start: seg.start, + end: seg.end, + myFill: { + above: selection[index2] === 1, + // 1 if filled above + below: selection[index2] === 2 + // 2 if filled below + }, + otherFill: null + }); + } + }); + if (buildLog2) + buildLog2.selected(result); + return result; +} +var SegmentSelector$1 = { + union: function(segments, buildLog2) { + return select$6(segments, [ + 0, + 2, + 1, + 0, + 2, + 2, + 0, + 0, + 1, + 0, + 1, + 0, + 0, + 0, + 0, + 0 + ], buildLog2); + }, + intersect: function(segments, buildLog2) { + return select$6(segments, [ + 0, + 0, + 0, + 0, + 0, + 2, + 0, + 2, + 0, + 0, + 1, + 1, + 0, + 2, + 1, + 0 + ], buildLog2); + }, + difference: function(segments, buildLog2) { + return select$6(segments, [ + 0, + 0, + 0, + 0, + 2, + 0, + 2, + 0, + 1, + 1, + 0, + 0, + 0, + 1, + 2, + 0 + ], buildLog2); + }, + differenceRev: function(segments, buildLog2) { + return select$6(segments, [ + 0, + 2, + 1, + 0, + 0, + 0, + 1, + 1, + 0, + 2, + 0, + 2, + 0, + 0, + 0, + 0 + ], buildLog2); + }, + xor: function(segments, buildLog2) { + return select$6(segments, [ + 0, + 2, + 1, + 0, + 2, + 0, + 0, + 1, + 1, + 0, + 0, + 2, + 0, + 1, + 2, + 0 + ], buildLog2); + } +}; +var segmentSelector = SegmentSelector$1; +var GeoJSON$1 = { + // convert a GeoJSON object to a PolyBool polygon + toPolygon: function(PolyBool2, geojson2) { + function GeoPoly(coords) { + if (coords.length <= 0) + return PolyBool2.segments({ inverted: false, regions: [] }); + function LineString(ls) { + var reg2 = ls.slice(0, ls.length - 1); + return PolyBool2.segments({ inverted: false, regions: [reg2] }); + } + var out2 = LineString(coords[0]); + for (var i2 = 1; i2 < coords.length; i2++) + out2 = PolyBool2.selectDifference(PolyBool2.combine(out2, LineString(coords[i2]))); + return out2; + } + if (geojson2.type === "Polygon") { + return PolyBool2.polygon(GeoPoly(geojson2.coordinates)); + } else if (geojson2.type === "MultiPolygon") { + var out = PolyBool2.segments({ inverted: false, regions: [] }); + for (var i = 0; i < geojson2.coordinates.length; i++) + out = PolyBool2.selectUnion(PolyBool2.combine(out, GeoPoly(geojson2.coordinates[i]))); + return PolyBool2.polygon(out); + } + throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon"); + }, + // convert a PolyBool polygon to a GeoJSON object + fromPolygon: function(PolyBool2, eps, poly) { + poly = PolyBool2.polygon(PolyBool2.segments(poly)); + function regionInsideRegion(r1, r2) { + return eps.pointInsideRegion([ + (r1[0][0] + r1[1][0]) * 0.5, + (r1[0][1] + r1[1][1]) * 0.5 + ], r2); + } + function newNode(region2) { + return { + region: region2, + children: [] + }; + } + var roots = newNode(null); + function addChild(root, region2) { + for (var i2 = 0; i2 < root.children.length; i2++) { + var child = root.children[i2]; + if (regionInsideRegion(region2, child.region)) { + addChild(child, region2); + return; + } + } + var node = newNode(region2); + for (var i2 = 0; i2 < root.children.length; i2++) { + var child = root.children[i2]; + if (regionInsideRegion(child.region, region2)) { + node.children.push(child); + root.children.splice(i2, 1); + i2--; + } + } + root.children.push(node); + } + for (var i = 0; i < poly.regions.length; i++) { + var region = poly.regions[i]; + if (region.length < 3) + continue; + addChild(roots, region); + } + function forceWinding(region2, clockwise) { + var winding = 0; + var last_x = region2[region2.length - 1][0]; + var last_y = region2[region2.length - 1][1]; + var copy2 = []; + for (var i2 = 0; i2 < region2.length; i2++) { + var curr_x = region2[i2][0]; + var curr_y = region2[i2][1]; + copy2.push([curr_x, curr_y]); + winding += curr_y * last_x - curr_x * last_y; + last_x = curr_x; + last_y = curr_y; + } + var isclockwise = winding < 0; + if (isclockwise !== clockwise) + copy2.reverse(); + copy2.push([copy2[0][0], copy2[0][1]]); + return copy2; + } + var geopolys = []; + function addExterior(node) { + var poly2 = [forceWinding(node.region, false)]; + geopolys.push(poly2); + for (var i2 = 0; i2 < node.children.length; i2++) + poly2.push(getInterior(node.children[i2])); + } + function getInterior(node) { + for (var i2 = 0; i2 < node.children.length; i2++) + addExterior(node.children[i2]); + return forceWinding(node.region, true); + } + for (var i = 0; i < roots.children.length; i++) + addExterior(roots.children[i]); + if (geopolys.length <= 0) + return { type: "Polygon", coordinates: [] }; + if (geopolys.length == 1) + return { type: "Polygon", coordinates: geopolys[0] }; + return { + // otherwise, use a GeoJSON MultiPolygon + type: "MultiPolygon", + coordinates: geopolys + }; + } +}; +var geojson = GeoJSON$1; +/* + * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc + * @license MIT + * @preserve Project Home: https://github.com/voidqk/polybooljs + */ +var BuildLog = buildLog$1; +var Epsilon = epsilon$1; +var Intersecter = intersecter; +var SegmentChainer = segmentChainer; +var SegmentSelector = segmentSelector; +var GeoJSON = geojson; +var buildLog = false; +var epsilon = Epsilon(); +var PolyBool; +PolyBool = { + // getter/setter for buildLog + buildLog: function(bl) { + if (bl === true) + buildLog = BuildLog(); + else if (bl === false) + buildLog = false; + return buildLog === false ? false : buildLog.list; + }, + // getter/setter for epsilon + epsilon: function(v) { + return epsilon.epsilon(v); + }, + // core API + segments: function(poly) { + var i = Intersecter(true, epsilon, buildLog); + poly.regions.forEach(i.addRegion); + return { + segments: i.calculate(poly.inverted), + inverted: poly.inverted + }; + }, + combine: function(segments1, segments2) { + var i3 = Intersecter(false, epsilon, buildLog); + return { + combined: i3.calculate( + segments1.segments, + segments1.inverted, + segments2.segments, + segments2.inverted + ), + inverted1: segments1.inverted, + inverted2: segments2.inverted + }; + }, + selectUnion: function(combined) { + return { + segments: SegmentSelector.union(combined.combined, buildLog), + inverted: combined.inverted1 || combined.inverted2 + }; + }, + selectIntersect: function(combined) { + return { + segments: SegmentSelector.intersect(combined.combined, buildLog), + inverted: combined.inverted1 && combined.inverted2 + }; + }, + selectDifference: function(combined) { + return { + segments: SegmentSelector.difference(combined.combined, buildLog), + inverted: combined.inverted1 && !combined.inverted2 + }; + }, + selectDifferenceRev: function(combined) { + return { + segments: SegmentSelector.differenceRev(combined.combined, buildLog), + inverted: !combined.inverted1 && combined.inverted2 + }; + }, + selectXor: function(combined) { + return { + segments: SegmentSelector.xor(combined.combined, buildLog), + inverted: combined.inverted1 !== combined.inverted2 + }; + }, + polygon: function(segments) { + return { + regions: SegmentChainer(segments.segments, epsilon, buildLog), + inverted: segments.inverted + }; + }, + // GeoJSON converters + polygonFromGeoJSON: function(geojson2) { + return GeoJSON.toPolygon(PolyBool, geojson2); + }, + polygonToGeoJSON: function(poly) { + return GeoJSON.fromPolygon(PolyBool, epsilon, poly); + }, + // helper functions for common operations + union: function(poly1, poly2) { + return operate(poly1, poly2, PolyBool.selectUnion); + }, + intersect: function(poly1, poly2) { + return operate(poly1, poly2, PolyBool.selectIntersect); + }, + difference: function(poly1, poly2) { + return operate(poly1, poly2, PolyBool.selectDifference); + }, + differenceRev: function(poly1, poly2) { + return operate(poly1, poly2, PolyBool.selectDifferenceRev); + }, + xor: function(poly1, poly2) { + return operate(poly1, poly2, PolyBool.selectXor); + } +}; +function operate(poly1, poly2, selector) { + var seg1 = PolyBool.segments(poly1); + var seg2 = PolyBool.segments(poly2); + var comb = PolyBool.combine(seg1, seg2); + var seg3 = selector(comb); + return PolyBool.polygon(seg3); +} +if (typeof window === "object") + window.PolyBool = PolyBool; +var polybooljs = PolyBool; +var nested = function pointInPolygonNested(point, vs, start, end) { + var x = point[0], y = point[1]; + var inside = false; + if (start === void 0) start = 0; + if (end === void 0) end = vs.length; + var len = end - start; + for (var i = 0, j = len - 1; i < len; j = i++) { + var xi = vs[i + start][0], yi = vs[i + start][1]; + var xj = vs[j + start][0], yj = vs[j + start][1]; + var intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; + if (intersect) inside = !inside; + } + return inside; +}; +var polygon$1 = { exports: {} }; +var dot = matrix$1.dot; +var BADNUM$6 = numerical.BADNUM; +var polygon = polygon$1.exports = {}; +polygon.tester = function tester(ptsIn) { + var pts = ptsIn.slice(); + var xmin = pts[0][0]; + var xmax = xmin; + var ymin = pts[0][1]; + var ymax = ymin; + var i; + if (pts[pts.length - 1][0] !== pts[0][0] || pts[pts.length - 1][1] !== pts[0][1]) { + pts.push(pts[0]); + } + for (i = 1; i < pts.length; i++) { + xmin = Math.min(xmin, pts[i][0]); + xmax = Math.max(xmax, pts[i][0]); + ymin = Math.min(ymin, pts[i][1]); + ymax = Math.max(ymax, pts[i][1]); + } + var isRect = false; + var rectFirstEdgeTest; + if (pts.length === 5) { + if (pts[0][0] === pts[1][0]) { + if (pts[2][0] === pts[3][0] && pts[0][1] === pts[3][1] && pts[1][1] === pts[2][1]) { + isRect = true; + rectFirstEdgeTest = function(pt) { + return pt[0] === pts[0][0]; + }; + } + } else if (pts[0][1] === pts[1][1]) { + if (pts[2][1] === pts[3][1] && pts[0][0] === pts[3][0] && pts[1][0] === pts[2][0]) { + isRect = true; + rectFirstEdgeTest = function(pt) { + return pt[1] === pts[0][1]; + }; + } + } + } + function rectContains(pt, omitFirstEdge) { + var x = pt[0]; + var y = pt[1]; + if (x === BADNUM$6 || x < xmin || x > xmax || y === BADNUM$6 || y < ymin || y > ymax) { + return false; + } + if (omitFirstEdge && rectFirstEdgeTest(pt)) return false; + return true; + } + function contains(pt, omitFirstEdge) { + var x = pt[0]; + var y = pt[1]; + if (x === BADNUM$6 || x < xmin || x > xmax || y === BADNUM$6 || y < ymin || y > ymax) { + return false; + } + var imax = pts.length; + var x1 = pts[0][0]; + var y1 = pts[0][1]; + var crossings = 0; + var i2; + var x0; + var y0; + var xmini; + var ycross; + for (i2 = 1; i2 < imax; i2++) { + x0 = x1; + y0 = y1; + x1 = pts[i2][0]; + y1 = pts[i2][1]; + xmini = Math.min(x0, x1); + if (x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { + continue; + } else if (y < Math.min(y0, y1)) { + if (x !== xmini) crossings++; + } else { + if (x1 === x0) ycross = y; + else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); + if (y === ycross) { + if (i2 === 1 && omitFirstEdge) return false; + return true; + } + if (y <= ycross && x !== xmini) crossings++; + } + } + return crossings % 2 === 1; + } + var degenerate = true; + var lastPt = pts[0]; + for (i = 1; i < pts.length; i++) { + if (lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { + degenerate = false; + break; + } + } + return { + xmin, + xmax, + ymin, + ymax, + pts, + contains: isRect ? rectContains : contains, + isRect, + degenerate + }; +}; +polygon.isSegmentBent = function isSegmentBent(pts, start, end, tolerance) { + var startPt = pts[start]; + var segment2 = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]]; + var segmentSquared = dot(segment2, segment2); + var segmentLen = Math.sqrt(segmentSquared); + var unitPerp = [-segment2[1] / segmentLen, segment2[0] / segmentLen]; + var i; + var part; + var partParallel; + for (i = start + 1; i < end; i++) { + part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; + partParallel = dot(part, segment2); + if (partParallel < 0 || partParallel > segmentSquared || Math.abs(dot(part, unitPerp)) > tolerance) return true; + } + return false; +}; +polygon.filter = function filter(pts, tolerance) { + var ptsFiltered = [pts[0]]; + var doneRawIndex = 0; + var doneFilteredIndex = 0; + function addPt(pt) { + pts.push(pt); + var prevFilterLen = ptsFiltered.length; + var iLast = doneRawIndex; + ptsFiltered.splice(doneFilteredIndex + 1); + for (var i = iLast + 1; i < pts.length; i++) { + if (i === pts.length - 1 || polygon.isSegmentBent(pts, iLast, i + 1, tolerance)) { + ptsFiltered.push(pts[i]); + if (ptsFiltered.length < prevFilterLen - 2) { + doneRawIndex = i; + doneFilteredIndex = ptsFiltered.length - 1; + } + iLast = i; + } + } + } + if (pts.length > 1) { + var lastPt = pts.pop(); + addPt(lastPt); + } + return { + addPt, + raw: pts, + filtered: ptsFiltered + }; +}; +var polygonExports = polygon$1.exports; +var constants$D = { + // max pixels off straight before a lasso select line counts as bent + BENDPX: 1.5, + // smallest dimension allowed for a select box + MINSELECT: 12, + // throttling limit (ms) for selectPoints calls + SELECTDELAY: 100, + // cache ID suffix for throttle + SELECTID: "-select" +}; +var polybool = polybooljs; +var pointInPolygon = nested; +var Registry$v = registry; +var dashStyle = drawingExports.dashStyle; +var Color$w = colorExports; +var Fx$6 = fx$1; +var makeEventData$1 = helpers$J.makeEventData; +var dragHelpers = helpers$B; +var freeMode = dragHelpers.freeMode; +var rectMode = dragHelpers.rectMode; +var drawMode = dragHelpers.drawMode; +var openMode = dragHelpers.openMode; +var selectMode$1 = dragHelpers.selectMode; +var shapeHelpers = helpers$w; +var shapeConstants = constants$I; +var displayOutlines2 = display_outlines; +var clearOutline = handle_outline.clearOutline; +var newShapeHelpers = helpers$A; +var handleEllipse = newShapeHelpers.handleEllipse; +var readPaths = newShapeHelpers.readPaths; +var newShapes = newshapes.newShapes; +var newSelections2 = newselections; +var activateLastSelection = draw_1$2.activateLastSelection; +var Lib$1j = libExports; +var ascending = Lib$1j.sorterAsc; +var libPolygon = polygonExports; +var throttle = throttle$2; +var getFromId = axis_ids.getFromId; +var clearGlCanvases2 = clear_gl_canvases; +var redrawReglTraces = subroutines.redrawReglTraces; +var constants$C = constants$D; +var MINSELECT = constants$C.MINSELECT; +var filteredPolygon = libPolygon.filter; +var polygonTester$1 = libPolygon.tester; +var helpers$r = helpers$z; +var p2r = helpers$r.p2r; +var axValue = helpers$r.axValue; +var getTransform = helpers$r.getTransform; +function hasSubplot(dragOptions) { + return dragOptions.subplot !== void 0; +} +function prepSelect(evt, startX, startY, dragOptions, mode) { + var isCartesian = !hasSubplot(dragOptions); + var isFreeMode = freeMode(mode); + var isRectMode = rectMode(mode); + var isOpenMode = openMode(mode); + var isDrawMode = drawMode(mode); + var isSelectMode = selectMode$1(mode); + var isLine = mode === "drawline"; + var isEllipse = mode === "drawcircle"; + var isLineOrEllipse = isLine || isEllipse; + var gd = dragOptions.gd; + var fullLayout = gd._fullLayout; + var immediateSelect = isSelectMode && fullLayout.newselection.mode === "immediate" && isCartesian; + var zoomLayer = fullLayout._zoomlayer; + var dragBBox = dragOptions.element.getBoundingClientRect(); + var plotinfo = dragOptions.plotinfo; + var transform = getTransform(plotinfo); + var x0 = startX - dragBBox.left; + var y0 = startY - dragBBox.top; + fullLayout._calcInverseTransform(gd); + var transformedCoords = Lib$1j.apply3DTransform(fullLayout._invTransform)(x0, y0); + x0 = transformedCoords[0]; + y0 = transformedCoords[1]; + var scaleX = fullLayout._invScaleX; + var scaleY = fullLayout._invScaleY; + var x1 = x0; + var y1 = y0; + var path0 = "M" + x0 + "," + y0; + var xAxis = dragOptions.xaxes[0]; + var yAxis = dragOptions.yaxes[0]; + var pw = xAxis._length; + var ph = yAxis._length; + var subtract = evt.altKey && !(drawMode(mode) && isOpenMode); + var filterPoly, selectionTesters, mergedPolygons, currentPolygon; + var i, searchInfo, eventData5; + coerceSelectionsCache(evt, gd, dragOptions); + if (isFreeMode) { + filterPoly = filteredPolygon([[x0, y0]], constants$C.BENDPX); + } + var outlines = zoomLayer.selectAll("path.select-outline-" + plotinfo.id).data([1]); + var newStyle = isDrawMode ? fullLayout.newshape : fullLayout.newselection; + if (isDrawMode) { + dragOptions.hasText = newStyle.label.text || newStyle.label.texttemplate; + } + var fillC = isDrawMode && !isOpenMode ? newStyle.fillcolor : "rgba(0,0,0,0)"; + var strokeC = newStyle.line.color || (isCartesian ? Color$w.contrast(gd._fullLayout.plot_bgcolor) : "#7f7f7f"); + outlines.enter().append("path").attr("class", "select-outline select-outline-" + plotinfo.id).style({ + opacity: isDrawMode ? newStyle.opacity / 2 : 1, + "stroke-dasharray": dashStyle(newStyle.line.dash, newStyle.line.width), + "stroke-width": newStyle.line.width + "px", + "shape-rendering": "crispEdges" + }).call(Color$w.stroke, strokeC).call(Color$w.fill, fillC).attr("fill-rule", "evenodd").classed("cursor-move", isDrawMode ? true : false).attr("transform", transform).attr("d", path0 + "Z"); + var corners = zoomLayer.append("path").attr("class", "zoombox-corners").style({ + fill: Color$w.background, + stroke: Color$w.defaultLine, + "stroke-width": 1 + }).attr("transform", transform).attr("d", "M0,0Z"); + if (isDrawMode && dragOptions.hasText) { + var shapeGroup = zoomLayer.select(".label-temp"); + if (shapeGroup.empty()) { + shapeGroup = zoomLayer.append("g").classed("label-temp", true).classed("select-outline", true).style({ opacity: 0.8 }); + } + } + var throttleID = fullLayout._uid + constants$C.SELECTID; + var selection = []; + var searchTraces = determineSearchTraces( + gd, + dragOptions.xaxes, + dragOptions.yaxes, + dragOptions.subplot + ); + if (immediateSelect && !evt.shiftKey) { + dragOptions._clearSubplotSelections = function() { + if (!isCartesian) return; + var xRef = xAxis._id; + var yRef = yAxis._id; + deselectSubplot(gd, xRef, yRef, searchTraces); + var selections2 = (gd.layout || {}).selections || []; + var list = []; + var selectionErased = false; + for (var q = 0; q < selections2.length; q++) { + var s = fullLayout.selections[q]; + if (s.xref !== xRef || s.yref !== yRef) { + list.push(selections2[q]); + } else { + selectionErased = true; + } + } + if (selectionErased) { + gd._fullLayout._noEmitSelectedAtStart = true; + Registry$v.call("_guiRelayout", gd, { + selections: list + }); + } + }; + } + var fillRangeItems = getFillRangeItems(dragOptions); + dragOptions.moveFn = function(dx0, dy0) { + if (dragOptions._clearSubplotSelections) { + dragOptions._clearSubplotSelections(); + dragOptions._clearSubplotSelections = void 0; + } + x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0)); + y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0)); + var dx = Math.abs(x1 - x0); + var dy = Math.abs(y1 - y0); + if (isRectMode) { + var direction; + var start, end; + if (isSelectMode) { + var q = fullLayout.selectdirection; + if (q === "any") { + if (dy < Math.min(dx * 0.6, MINSELECT)) { + direction = "h"; + } else if (dx < Math.min(dy * 0.6, MINSELECT)) { + direction = "v"; + } else { + direction = "d"; + } + } else { + direction = q; + } + switch (direction) { + case "h": + start = isEllipse ? ph / 2 : 0; + end = ph; + break; + case "v": + start = isEllipse ? pw / 2 : 0; + end = pw; + break; + } + } + if (isDrawMode) { + switch (fullLayout.newshape.drawdirection) { + case "vertical": + direction = "h"; + start = isEllipse ? ph / 2 : 0; + end = ph; + break; + case "horizontal": + direction = "v"; + start = isEllipse ? pw / 2 : 0; + end = pw; + break; + case "ortho": + if (dx < dy) { + direction = "h"; + start = y0; + end = y1; + } else { + direction = "v"; + start = x0; + end = x1; + } + break; + default: + direction = "d"; + } + } + if (direction === "h") { + currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x1, start], [x1, end]) : ( + // using x1 instead of x0 allows adjusting the line while drawing + [[x0, start], [x0, end], [x1, end], [x1, start]] + ); + currentPolygon.xmin = isLineOrEllipse ? x1 : Math.min(x0, x1); + currentPolygon.xmax = isLineOrEllipse ? x1 : Math.max(x0, x1); + currentPolygon.ymin = Math.min(start, end); + currentPolygon.ymax = Math.max(start, end); + corners.attr("d", "M" + currentPolygon.xmin + "," + (y0 - MINSELECT) + "h-4v" + 2 * MINSELECT + "h4ZM" + (currentPolygon.xmax - 1) + "," + (y0 - MINSELECT) + "h4v" + 2 * MINSELECT + "h-4Z"); + } else if (direction === "v") { + currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [start, y1], [end, y1]) : ( + // using y1 instead of y0 allows adjusting the line while drawing + [[start, y0], [start, y1], [end, y1], [end, y0]] + ); + currentPolygon.xmin = Math.min(start, end); + currentPolygon.xmax = Math.max(start, end); + currentPolygon.ymin = isLineOrEllipse ? y1 : Math.min(y0, y1); + currentPolygon.ymax = isLineOrEllipse ? y1 : Math.max(y0, y1); + corners.attr("d", "M" + (x0 - MINSELECT) + "," + currentPolygon.ymin + "v-4h" + 2 * MINSELECT + "v4ZM" + (x0 - MINSELECT) + "," + (currentPolygon.ymax - 1) + "v4h" + 2 * MINSELECT + "v-4Z"); + } else if (direction === "d") { + currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x0, y0], [x1, y1]) : [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]; + currentPolygon.xmin = Math.min(x0, x1); + currentPolygon.xmax = Math.max(x0, x1); + currentPolygon.ymin = Math.min(y0, y1); + currentPolygon.ymax = Math.max(y0, y1); + corners.attr("d", "M0,0Z"); + } + } else if (isFreeMode) { + filterPoly.addPt([x1, y1]); + currentPolygon = filterPoly.filtered; + } + if (dragOptions.selectionDefs && dragOptions.selectionDefs.length) { + mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); + currentPolygon.subtract = subtract; + selectionTesters = multiTester(dragOptions.selectionDefs.concat([currentPolygon])); + } else { + mergedPolygons = [currentPolygon]; + selectionTesters = polygonTester$1(currentPolygon); + } + displayOutlines2(convertPoly(mergedPolygons, isOpenMode), outlines, dragOptions); + if (isSelectMode) { + var _res = reselect(gd, false); + var extraPoints = _res.eventData ? _res.eventData.points.slice() : []; + _res = reselect(gd, false, selectionTesters, searchTraces, dragOptions); + selectionTesters = _res.selectionTesters; + eventData5 = _res.eventData; + var poly; + if (filterPoly) { + poly = filterPoly.filtered; + } else { + poly = castMultiPolygon(mergedPolygons); + } + throttle.throttle( + throttleID, + constants$C.SELECTDELAY, + function() { + selection = _doSelect(selectionTesters, searchTraces); + var newPoints = selection.slice(); + for (var w = 0; w < extraPoints.length; w++) { + var p = extraPoints[w]; + var found = false; + for (var u = 0; u < newPoints.length; u++) { + if (newPoints[u].curveNumber === p.curveNumber && newPoints[u].pointNumber === p.pointNumber) { + found = true; + break; + } + } + if (!found) newPoints.push(p); + } + if (newPoints.length) { + if (!eventData5) eventData5 = {}; + eventData5.points = newPoints; + } + fillRangeItems(eventData5, poly); + emitSelecting(gd, eventData5); + } + ); + } + }; + dragOptions.clickFn = function(numClicks, evt2) { + corners.remove(); + if (gd._fullLayout._activeShapeIndex >= 0) { + gd._fullLayout._deactivateShape(gd); + return; + } + if (isDrawMode) return; + var clickmode = fullLayout.clickmode; + throttle.done(throttleID).then(function() { + throttle.clear(throttleID); + if (numClicks === 2) { + outlines.remove(); + for (i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + searchInfo._module.selectPoints(searchInfo, false); + } + updateSelectedState(gd, searchTraces); + clearSelectionsCache(dragOptions); + emitDeselect(gd); + if (searchTraces.length) { + var clickedXaxis = searchTraces[0].xaxis; + var clickedYaxis = searchTraces[0].yaxis; + if (clickedXaxis && clickedYaxis) { + var subSelections = []; + var allSelections = gd._fullLayout.selections; + for (var k = 0; k < allSelections.length; k++) { + var s = allSelections[k]; + if (!s) continue; + if (s.xref !== clickedXaxis._id || s.yref !== clickedYaxis._id) { + subSelections.push(s); + } + } + if (subSelections.length < allSelections.length) { + gd._fullLayout._noEmitSelectedAtStart = true; + Registry$v.call("_guiRelayout", gd, { + selections: subSelections + }); + } + } + } + } else { + if (clickmode.indexOf("select") > -1) { + selectOnClick( + evt2, + gd, + dragOptions.xaxes, + dragOptions.yaxes, + dragOptions.subplot, + dragOptions, + outlines + ); + } + if (clickmode === "event") { + emitSelected(gd, void 0); + } + } + Fx$6.click(gd, evt2, plotinfo.id); + }).catch(Lib$1j.error); + }; + dragOptions.doneFn = function() { + corners.remove(); + throttle.done(throttleID).then(function() { + throttle.clear(throttleID); + if (!immediateSelect && currentPolygon && dragOptions.selectionDefs) { + currentPolygon.subtract = subtract; + dragOptions.selectionDefs.push(currentPolygon); + dragOptions.mergedPolygons.length = 0; + [].push.apply(dragOptions.mergedPolygons, mergedPolygons); + } + if (immediateSelect || isDrawMode) { + clearSelectionsCache(dragOptions, immediateSelect); + } + if (dragOptions.doneFnCompleted) { + dragOptions.doneFnCompleted(selection); + } + if (isSelectMode) { + emitSelected(gd, eventData5); + } + }).catch(Lib$1j.error); + }; +} +function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) { + var hoverData = gd._hoverdata; + var fullLayout = gd._fullLayout; + var clickmode = fullLayout.clickmode; + var sendEvents = clickmode.indexOf("event") > -1; + var selection = []; + var searchTraces, searchInfo, currentSelectionDef, selectionTesters, traceSelection; + var thisTracesSelection, pointOrBinSelected, subtract, eventData5, i; + if (isHoverDataSet(hoverData)) { + coerceSelectionsCache(evt, gd, dragOptions); + searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot); + var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces); + var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0; + if (isBinnedTrace ? isOnlyThisBinSelected(searchTraces, clickedPtInfo) : isOnlyOnePointSelected(searchTraces) && (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo))) { + if (polygonOutlines) polygonOutlines.remove(); + for (i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + searchInfo._module.selectPoints(searchInfo, false); + } + updateSelectedState(gd, searchTraces); + clearSelectionsCache(dragOptions); + if (sendEvents) { + emitDeselect(gd); + } + } else { + subtract = evt.shiftKey && (pointOrBinSelected !== void 0 ? pointOrBinSelected : isPointOrBinSelected(clickedPtInfo)); + currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract); + var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]); + selectionTesters = multiTester(allSelectionDefs); + for (i = 0; i < searchTraces.length; i++) { + traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTesters); + thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]); + if (selection.length) { + for (var j = 0; j < thisTracesSelection.length; j++) { + selection.push(thisTracesSelection[j]); + } + } else selection = thisTracesSelection; + } + eventData5 = { points: selection }; + updateSelectedState(gd, searchTraces, eventData5); + if (currentSelectionDef && dragOptions) { + dragOptions.selectionDefs.push(currentSelectionDef); + } + if (polygonOutlines) { + var polygons = dragOptions.mergedPolygons; + var isOpenMode = openMode(dragOptions.dragmode); + displayOutlines2(convertPoly(polygons, isOpenMode), polygonOutlines, dragOptions); + } + if (sendEvents) { + emitSelected(gd, eventData5); + } + } + } +} +function newPointSelectionDef(pointNumber, searchInfo, subtract) { + return { + pointNumber, + searchInfo, + subtract: !!subtract + }; +} +function isPointSelectionDef(o) { + return "pointNumber" in o && "searchInfo" in o; +} +function newPointNumTester(pointSelectionDef) { + return { + xmin: 0, + xmax: 0, + ymin: 0, + ymax: 0, + pts: [], + contains: function(pt, omitFirstEdge, pointNumber, searchInfo) { + var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex; + var idxActualTrace = searchInfo.cd[0].trace._expandedIndex; + return idxActualTrace === idxWantedTrace && pointNumber === pointSelectionDef.pointNumber; + }, + isRect: false, + degenerate: false, + subtract: !!pointSelectionDef.subtract + }; +} +function multiTester(list) { + if (!list.length) return; + var testers = []; + var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0]; + var xmax = xmin; + var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1]; + var ymax = ymin; + for (var i = 0; i < list.length; i++) { + if (isPointSelectionDef(list[i])) { + testers.push(newPointNumTester(list[i])); + } else { + var tester2 = polygonTester$1(list[i]); + tester2.subtract = !!list[i].subtract; + testers.push(tester2); + xmin = Math.min(xmin, tester2.xmin); + xmax = Math.max(xmax, tester2.xmax); + ymin = Math.min(ymin, tester2.ymin); + ymax = Math.max(ymax, tester2.ymax); + } + } + function contains(pt, arg, pointNumber, searchInfo) { + var contained = false; + for (var i2 = 0; i2 < testers.length; i2++) { + if (testers[i2].contains(pt, arg, pointNumber, searchInfo)) { + contained = !testers[i2].subtract; + } + } + return contained; + } + return { + xmin, + xmax, + ymin, + ymax, + pts: [], + contains, + isRect: false, + degenerate: false + }; +} +function coerceSelectionsCache(evt, gd, dragOptions) { + var fullLayout = gd._fullLayout; + var plotinfo = dragOptions.plotinfo; + var dragmode = dragOptions.dragmode; + var selectingOnSameSubplot = fullLayout._lastSelectedSubplot && fullLayout._lastSelectedSubplot === plotinfo.id; + var hasModifierKey = (evt.shiftKey || evt.altKey) && !(drawMode(dragmode) && openMode(dragmode)); + if (selectingOnSameSubplot && hasModifierKey && plotinfo.selection && plotinfo.selection.selectionDefs && !dragOptions.selectionDefs) { + dragOptions.selectionDefs = plotinfo.selection.selectionDefs; + dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; + } else if (!hasModifierKey || !plotinfo.selection) { + clearSelectionsCache(dragOptions); + } + if (!selectingOnSameSubplot) { + clearOutline(gd); + fullLayout._lastSelectedSubplot = plotinfo.id; + } +} +function hasActiveShape(gd) { + return gd._fullLayout._activeShapeIndex >= 0; +} +function hasActiveSelection(gd) { + return gd._fullLayout._activeSelectionIndex >= 0; +} +function clearSelectionsCache(dragOptions, immediateSelect) { + var dragmode = dragOptions.dragmode; + var plotinfo = dragOptions.plotinfo; + var gd = dragOptions.gd; + if (hasActiveShape(gd)) { + gd._fullLayout._deactivateShape(gd); + } + if (hasActiveSelection(gd)) { + gd._fullLayout._deactivateSelection(gd); + } + var fullLayout = gd._fullLayout; + var zoomLayer = fullLayout._zoomlayer; + var isDrawMode = drawMode(dragmode); + var isSelectMode = selectMode$1(dragmode); + if (isDrawMode || isSelectMode) { + var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id); + if (outlines && gd._fullLayout._outlining) { + var shapes2; + if (isDrawMode) { + shapes2 = newShapes(outlines, dragOptions); + } + if (shapes2) { + Registry$v.call("_guiRelayout", gd, { + shapes: shapes2 + }); + } + var selections2; + if (isSelectMode && !hasSubplot(dragOptions)) { + selections2 = newSelections2(outlines, dragOptions); + } + if (selections2) { + gd._fullLayout._noEmitSelectedAtStart = true; + Registry$v.call("_guiRelayout", gd, { + selections: selections2 + }).then(function() { + if (immediateSelect) { + activateLastSelection(gd); + } + }); + } + gd._fullLayout._outlining = false; + } + } + plotinfo.selection = {}; + plotinfo.selection.selectionDefs = dragOptions.selectionDefs = []; + plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; +} +function getAxId(ax) { + return ax._id; +} +function determineSearchTraces(gd, xAxes, yAxes, subplot) { + if (!gd.calcdata) return []; + var searchTraces = []; + var xAxisIds = xAxes.map(getAxId); + var yAxisIds = yAxes.map(getAxId); + var cd, trace, i; + for (i = 0; i < gd.calcdata.length; i++) { + cd = gd.calcdata[i]; + trace = cd[0].trace; + if (trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; + if (hasSubplot({ subplot }) && (trace.subplot === subplot || trace.geo === subplot)) { + searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0])); + } else if (trace.type === "splom") { + if (trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]) { + var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]); + info.scene = gd._fullLayout._splomScenes[trace.uid]; + searchTraces.push(info); + } + } else if (trace.type === "sankey") { + var sankeyInfo = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]); + searchTraces.push(sankeyInfo); + } else { + if (xAxisIds.indexOf(trace.xaxis) === -1 && (!trace._xA || !trace._xA.overlaying)) continue; + if (yAxisIds.indexOf(trace.yaxis) === -1 && (!trace._yA || !trace._yA.overlaying)) continue; + searchTraces.push(createSearchInfo( + trace._module, + cd, + getFromId(gd, trace.xaxis), + getFromId(gd, trace.yaxis) + )); + } + } + return searchTraces; +} +function createSearchInfo(module2, calcData, xaxis, yaxis) { + return { + _module: module2, + cd: calcData, + xaxis, + yaxis + }; +} +function isHoverDataSet(hoverData) { + return hoverData && Array.isArray(hoverData) && hoverData[0].hoverOnBox !== true; +} +function extractClickedPtInfo(hoverData, searchTraces) { + var hoverDatum = hoverData[0]; + var pointNumber = -1; + var pointNumbers = []; + var searchInfo, i; + for (i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + if (hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) { + if (hoverDatum.hoverOnBox === true) { + break; + } + if (hoverDatum.pointNumber !== void 0) { + pointNumber = hoverDatum.pointNumber; + } else if (hoverDatum.binNumber !== void 0) { + pointNumber = hoverDatum.binNumber; + pointNumbers = hoverDatum.pointNumbers; + } + break; + } + } + return { + pointNumber, + pointNumbers, + searchInfo + }; +} +function isPointOrBinSelected(clickedPtInfo) { + var trace = clickedPtInfo.searchInfo.cd[0].trace; + var ptNum = clickedPtInfo.pointNumber; + var ptNums = clickedPtInfo.pointNumbers; + var ptNumsSet = ptNums.length > 0; + var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum; + return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false; +} +function isOnlyThisBinSelected(searchTraces, clickedPtInfo) { + var tracesWithSelectedPts = []; + var searchInfo, trace, isSameTrace, i; + for (i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + if (searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) { + tracesWithSelectedPts.push(searchInfo); + } + } + if (tracesWithSelectedPts.length === 1) { + isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo; + if (isSameTrace) { + trace = clickedPtInfo.searchInfo.cd[0].trace; + if (trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) { + for (i = 0; i < clickedPtInfo.pointNumbers.length; i++) { + if (trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) { + return false; + } + } + return true; + } + } + } + return false; +} +function isOnlyOnePointSelected(searchTraces) { + var len = 0; + var searchInfo, trace, i; + for (i = 0; i < searchTraces.length; i++) { + searchInfo = searchTraces[i]; + trace = searchInfo.cd[0].trace; + if (trace.selectedpoints) { + if (trace.selectedpoints.length > 1) return false; + len += trace.selectedpoints.length; + if (len > 1) return false; + } + } + return len === 1; +} +function updateSelectedState(gd, searchTraces, eventData5) { + var i; + for (i = 0; i < searchTraces.length; i++) { + var fullInputTrace = searchTraces[i].cd[0].trace._fullInput; + var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid] || {}; + if (tracePreGUI.selectedpoints === void 0) { + tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null; + } + } + var trace; + if (eventData5) { + var pts = eventData5.points || []; + for (i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + trace._input.selectedpoints = trace._fullInput.selectedpoints = []; + if (trace._fullInput !== trace) trace.selectedpoints = []; + } + for (var k = 0; k < pts.length; k++) { + var pt = pts[k]; + var data = pt.data; + var fullData = pt.fullData; + var pointIndex = pt.pointIndex; + var pointIndices = pt.pointIndices; + if (pointIndices) { + [].push.apply(data.selectedpoints, pointIndices); + if (trace._fullInput !== trace) { + [].push.apply(fullData.selectedpoints, pointIndices); + } + } else { + data.selectedpoints.push(pointIndex); + if (trace._fullInput !== trace) { + fullData.selectedpoints.push(pointIndex); + } + } + } + } else { + for (i = 0; i < searchTraces.length; i++) { + trace = searchTraces[i].cd[0].trace; + delete trace.selectedpoints; + delete trace._input.selectedpoints; + if (trace._fullInput !== trace) { + delete trace._fullInput.selectedpoints; + } + } + } + updateReglSelectedState(gd, searchTraces); +} +function updateReglSelectedState(gd, searchTraces) { + var hasRegl = false; + for (var i = 0; i < searchTraces.length; i++) { + var searchInfo = searchTraces[i]; + var cd = searchInfo.cd; + if (Registry$v.traceIs(cd[0].trace, "regl")) { + hasRegl = true; + } + var _module = searchInfo._module; + var fn = _module.styleOnSelect || _module.style; + if (fn) { + fn(gd, cd, cd[0].node3); + if (cd[0].nodeRangePlot3) fn(gd, cd, cd[0].nodeRangePlot3); + } + } + if (hasRegl) { + clearGlCanvases2(gd); + redrawReglTraces(gd); + } +} +function mergePolygons(list, poly, subtract) { + var fn = subtract ? polybool.difference : polybool.union; + var res = fn({ + regions: list + }, { + regions: [poly] + }); + var allPolygons = res.regions.reverse(); + for (var i = 0; i < allPolygons.length; i++) { + var polygon2 = allPolygons[i]; + polygon2.subtract = getSubtract(polygon2, allPolygons.slice(0, i)); + } + return allPolygons; +} +function fillSelectionItem(selection, searchInfo) { + if (Array.isArray(selection)) { + var cd = searchInfo.cd; + var trace = searchInfo.cd[0].trace; + for (var i = 0; i < selection.length; i++) { + selection[i] = makeEventData$1(selection[i], trace, cd); + } + } + return selection; +} +function convertPoly(polygonsIn, isOpenMode) { + var polygonsOut = []; + for (var i = 0; i < polygonsIn.length; i++) { + polygonsOut[i] = []; + for (var j = 0; j < polygonsIn[i].length; j++) { + polygonsOut[i][j] = []; + polygonsOut[i][j][0] = j ? "L" : "M"; + for (var k = 0; k < polygonsIn[i][j].length; k++) { + polygonsOut[i][j].push( + polygonsIn[i][j][k] + ); + } + } + if (!isOpenMode) { + polygonsOut[i].push([ + "Z", + polygonsOut[i][0][1], + // initial x + polygonsOut[i][0][2] + // initial y + ]); + } + } + return polygonsOut; +} +function _doSelect(selectionTesters, searchTraces) { + var allSelections = []; + var thisSelection; + var traceSelection; + for (var i = 0; i < searchTraces.length; i++) { + var searchInfo = searchTraces[i]; + traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTesters); + thisSelection = fillSelectionItem(traceSelection, searchInfo); + allSelections = allSelections.concat(thisSelection); + } + return allSelections; +} +function reselect(gd, mayEmitSelected, selectionTesters, searchTraces, dragOptions) { + var hadSearchTraces = !!searchTraces; + var plotinfo, xRef, yRef; + if (dragOptions) { + plotinfo = dragOptions.plotinfo; + xRef = dragOptions.xaxes[0]._id; + yRef = dragOptions.yaxes[0]._id; + } + var allSelections = []; + var allSearchTraces = []; + var layoutPolygons = getLayoutPolygons(gd); + var fullLayout = gd._fullLayout; + if (plotinfo) { + var zoomLayer = fullLayout._zoomlayer; + var mode = fullLayout.dragmode; + var isDrawMode = drawMode(mode); + var isSelectMode = selectMode$1(mode); + if (isDrawMode || isSelectMode) { + var xaxis = getFromId(gd, xRef, "x"); + var yaxis = getFromId(gd, yRef, "y"); + if (xaxis && yaxis) { + var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id); + if (outlines && gd._fullLayout._outlining) { + if (outlines.length) { + var e = outlines[0][0]; + var d = e.getAttribute("d"); + var outlinePolys = readPaths(d, gd, plotinfo); + var draftPolygons = []; + for (var u = 0; u < outlinePolys.length; u++) { + var p = outlinePolys[u]; + var polygon2 = []; + for (var t = 0; t < p.length; t++) { + polygon2.push([ + convert$3(xaxis, p[t][1]), + convert$3(yaxis, p[t][2]) + ]); + } + polygon2.xref = xRef; + polygon2.yref = yRef; + polygon2.subtract = getSubtract(polygon2, draftPolygons); + draftPolygons.push(polygon2); + } + layoutPolygons = layoutPolygons.concat(draftPolygons); + } + } + } + } + } + var subplots = xRef && yRef ? [xRef + yRef] : fullLayout._subplots.cartesian; + epmtySplomSelectionBatch(gd); + var seenSplom = {}; + for (var i = 0; i < subplots.length; i++) { + var subplot = subplots[i]; + var yAt = subplot.indexOf("y"); + var _xRef = subplot.slice(0, yAt); + var _yRef = subplot.slice(yAt); + var _selectionTesters = xRef && yRef ? selectionTesters : void 0; + _selectionTesters = addTester(layoutPolygons, _xRef, _yRef, _selectionTesters); + if (_selectionTesters) { + var _searchTraces = searchTraces; + if (!hadSearchTraces) { + var _xA = getFromId(gd, _xRef, "x"); + var _yA = getFromId(gd, _yRef, "y"); + _searchTraces = determineSearchTraces( + gd, + [_xA], + [_yA], + subplot + ); + for (var w = 0; w < _searchTraces.length; w++) { + var s = _searchTraces[w]; + var cd0 = s.cd[0]; + var trace = cd0.trace; + if (s._module.name === "scattergl" && !cd0.t.xpx) { + var x = trace.x; + var y = trace.y; + var len = trace._length; + cd0.t.xpx = []; + cd0.t.ypx = []; + for (var j = 0; j < len; j++) { + cd0.t.xpx[j] = _xA.c2p(x[j]); + cd0.t.ypx[j] = _yA.c2p(y[j]); + } + } + if (s._module.name === "splom") { + if (!seenSplom[trace.uid]) { + seenSplom[trace.uid] = true; + } + } + } + } + var selection = _doSelect(_selectionTesters, _searchTraces); + allSelections = allSelections.concat(selection); + allSearchTraces = allSearchTraces.concat(_searchTraces); + } + } + var eventData5 = { points: allSelections }; + updateSelectedState(gd, allSearchTraces, eventData5); + var clickmode = fullLayout.clickmode; + var sendEvents = clickmode.indexOf("event") > -1 && mayEmitSelected; + if (!plotinfo && // get called from plot_api & plots + mayEmitSelected) { + var activePolygons = getLayoutPolygons(gd, true); + if (activePolygons.length) { + var xref = activePolygons[0].xref; + var yref = activePolygons[0].yref; + if (xref && yref) { + var poly = castMultiPolygon(activePolygons); + var fillRangeItems = makeFillRangeItems([ + getFromId(gd, xref, "x"), + getFromId(gd, yref, "y") + ]); + fillRangeItems(eventData5, poly); + } + } + if (gd._fullLayout._noEmitSelectedAtStart) { + gd._fullLayout._noEmitSelectedAtStart = false; + } else { + if (sendEvents) emitSelected(gd, eventData5); + } + fullLayout._reselect = false; + } + if (!plotinfo && // get called from plot_api & plots + fullLayout._deselect) { + var deselect = fullLayout._deselect; + xRef = deselect.xref; + yRef = deselect.yref; + if (!subplotSelected(xRef, yRef, allSearchTraces)) { + deselectSubplot(gd, xRef, yRef, searchTraces); + } + if (sendEvents) { + if (eventData5.points.length) { + emitSelected(gd, eventData5); + } else { + emitDeselect(gd); + } + } + fullLayout._deselect = false; + } + return { + eventData: eventData5, + selectionTesters + }; +} +function epmtySplomSelectionBatch(gd) { + var cd = gd.calcdata; + if (!cd) return; + for (var i = 0; i < cd.length; i++) { + var cd0 = cd[i][0]; + var trace = cd0.trace; + var splomScenes = gd._fullLayout._splomScenes; + if (splomScenes) { + var scene = splomScenes[trace.uid]; + if (scene) { + scene.selectBatch = []; + } + } + } +} +function subplotSelected(xRef, yRef, searchTraces) { + for (var i = 0; i < searchTraces.length; i++) { + var s = searchTraces[i]; + if (s.xaxis && s.xaxis._id === xRef && (s.yaxis && s.yaxis._id === yRef)) { + return true; + } + } + return false; +} +function deselectSubplot(gd, xRef, yRef, searchTraces) { + searchTraces = determineSearchTraces( + gd, + [getFromId(gd, xRef, "x")], + [getFromId(gd, yRef, "y")], + xRef + yRef + ); + for (var k = 0; k < searchTraces.length; k++) { + var searchInfo = searchTraces[k]; + searchInfo._module.selectPoints(searchInfo, false); + } + updateSelectedState(gd, searchTraces); +} +function addTester(layoutPolygons, xRef, yRef, selectionTesters) { + var mergedPolygons; + for (var i = 0; i < layoutPolygons.length; i++) { + var currentPolygon = layoutPolygons[i]; + if (xRef !== currentPolygon.xref || yRef !== currentPolygon.yref) continue; + if (mergedPolygons) { + var subtract = !!currentPolygon.subtract; + mergedPolygons = mergePolygons(mergedPolygons, currentPolygon, subtract); + selectionTesters = multiTester(mergedPolygons); + } else { + mergedPolygons = [currentPolygon]; + selectionTesters = polygonTester$1(currentPolygon); + } + } + return selectionTesters; +} +function getLayoutPolygons(gd, onlyActiveOnes) { + var allPolygons = []; + var fullLayout = gd._fullLayout; + var allSelections = fullLayout.selections; + var len = allSelections.length; + for (var i = 0; i < len; i++) { + if (onlyActiveOnes && i !== fullLayout._activeSelectionIndex) continue; + var selection = allSelections[i]; + if (!selection) continue; + var xref = selection.xref; + var yref = selection.yref; + var xaxis = getFromId(gd, xref, "x"); + var yaxis = getFromId(gd, yref, "y"); + var xmin, xmax, ymin, ymax; + var polygon2; + if (selection.type === "rect") { + polygon2 = []; + var x0 = convert$3(xaxis, selection.x0); + var x1 = convert$3(xaxis, selection.x1); + var y0 = convert$3(yaxis, selection.y0); + var y1 = convert$3(yaxis, selection.y1); + polygon2 = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]; + xmin = Math.min(x0, x1); + xmax = Math.max(x0, x1); + ymin = Math.min(y0, y1); + ymax = Math.max(y0, y1); + polygon2.xmin = xmin; + polygon2.xmax = xmax; + polygon2.ymin = ymin; + polygon2.ymax = ymax; + polygon2.xref = xref; + polygon2.yref = yref; + polygon2.subtract = false; + polygon2.isRect = true; + allPolygons.push(polygon2); + } else if (selection.type === "path") { + var segments = selection.path.split("Z"); + var multiPolygons = []; + for (var j = 0; j < segments.length; j++) { + var path = segments[j]; + if (!path) continue; + path += "Z"; + var allX = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsX, "raw"); + var allY = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsY, "raw"); + xmin = Infinity; + xmax = -Infinity; + ymin = Infinity; + ymax = -Infinity; + polygon2 = []; + for (var k = 0; k < allX.length; k++) { + var x = convert$3(xaxis, allX[k]); + var y = convert$3(yaxis, allY[k]); + polygon2.push([x, y]); + xmin = Math.min(x, xmin); + xmax = Math.max(x, xmax); + ymin = Math.min(y, ymin); + ymax = Math.max(y, ymax); + } + polygon2.xmin = xmin; + polygon2.xmax = xmax; + polygon2.ymin = ymin; + polygon2.ymax = ymax; + polygon2.xref = xref; + polygon2.yref = yref; + polygon2.subtract = getSubtract(polygon2, multiPolygons); + multiPolygons.push(polygon2); + allPolygons.push(polygon2); + } + } + } + return allPolygons; +} +function getSubtract(polygon2, previousPolygons) { + var subtract = false; + for (var i = 0; i < previousPolygons.length; i++) { + var previousPolygon = previousPolygons[i]; + for (var k = 0; k < polygon2.length; k++) { + if (pointInPolygon(polygon2[k], previousPolygon)) { + subtract = !subtract; + break; + } + } + } + return subtract; +} +function convert$3(ax, d) { + if (ax.type === "date") d = d.replace("_", " "); + return ax.type === "log" ? ax.c2p(d) : ax.r2p(d, null, ax.calendar); +} +function castMultiPolygon(allPolygons) { + var len = allPolygons.length; + var p = []; + for (var i = 0; i < len; i++) { + var polygon2 = allPolygons[i]; + p = p.concat(polygon2); + p = p.concat([polygon2[0]]); + } + return computeRectAndRanges(p); +} +function computeRectAndRanges(poly) { + poly.isRect = poly.length === 5 && poly[0][0] === poly[4][0] && poly[0][1] === poly[4][1] && (poly[0][0] === poly[1][0] && poly[2][0] === poly[3][0] && poly[0][1] === poly[3][1] && poly[1][1] === poly[2][1]) || poly[0][1] === poly[1][1] && poly[2][1] === poly[3][1] && poly[0][0] === poly[3][0] && poly[1][0] === poly[2][0]; + if (poly.isRect) { + poly.xmin = Math.min(poly[0][0], poly[2][0]); + poly.xmax = Math.max(poly[0][0], poly[2][0]); + poly.ymin = Math.min(poly[0][1], poly[2][1]); + poly.ymax = Math.max(poly[0][1], poly[2][1]); + } + return poly; +} +function makeFillRangeItems(allAxes) { + return function(eventData5, poly) { + var range; + var lassoPoints; + for (var i = 0; i < allAxes.length; i++) { + var ax = allAxes[i]; + var id = ax._id; + var axLetter = id.charAt(0); + if (poly.isRect) { + if (!range) range = {}; + var min = poly[axLetter + "min"]; + var max = poly[axLetter + "max"]; + if (min !== void 0 && max !== void 0) { + range[id] = [ + p2r(ax, min), + p2r(ax, max) + ].sort(ascending); + } + } else { + if (!lassoPoints) lassoPoints = {}; + lassoPoints[id] = poly.map(axValue(ax)); + } + } + if (range) { + eventData5.range = range; + } + if (lassoPoints) { + eventData5.lassoPoints = lassoPoints; + } + }; +} +function getFillRangeItems(dragOptions) { + var plotinfo = dragOptions.plotinfo; + return plotinfo.fillRangeItems || // allow subplots (i.e. geo, mapbox, map, sankey) to override fillRangeItems routine + makeFillRangeItems(dragOptions.xaxes.concat(dragOptions.yaxes)); +} +function emitSelecting(gd, eventData5) { + gd.emit("plotly_selecting", eventData5); +} +function emitSelected(gd, eventData5) { + if (eventData5) { + eventData5.selections = (gd.layout || {}).selections || []; + } + gd.emit("plotly_selected", eventData5); +} +function emitDeselect(gd) { + gd.emit("plotly_deselect", null); +} +var select$5 = { + reselect, + prepSelect, + clearOutline, + clearSelectionsCache, + selectOnClick +}; +var arrow_paths = [ + // no arrow + { + path: "", + backoff: 0 + }, + // wide with flat back + { + path: "M-2.4,-3V3L0.6,0Z", + backoff: 0.6 + }, + // narrower with flat back + { + path: "M-3.7,-2.5V2.5L1.3,0Z", + backoff: 1.3 + }, + // barbed + { + path: "M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z", + backoff: 1.55 + }, + // wide line-drawn + { + path: "M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z", + backoff: 1.6 + }, + // narrower line-drawn + { + path: "M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z", + backoff: 2 + }, + // circle + { + path: "M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z", + backoff: 0, + noRotate: true + }, + // square + { + path: "M2,2V-2H-2V2Z", + backoff: 0, + noRotate: true + } +]; +var axis_placeable_objects = { + axisRefDescription: function(axisname, lower, upper) { + return [ + "If set to a", + axisname, + "axis id (e.g. *" + axisname + "* or", + "*" + axisname + "2*), the `" + axisname + "` position refers to a", + axisname, + "coordinate. If set to *paper*, the `" + axisname + "`", + "position refers to the distance from the", + lower, + "of the plotting", + "area in normalized coordinates where *0* (*1*) corresponds to the", + lower, + "(" + upper + "). If set to a", + axisname, + "axis ID followed by", + "*domain* (separated by a space), the position behaves like for", + "*paper*, but refers to the distance in fractions of the domain", + "length from the", + lower, + "of the domain of that axis: e.g.,", + "*" + axisname + "2 domain* refers to the domain of the second", + axisname, + " axis and a", + axisname, + "position of 0.5 refers to the", + "point between the", + lower, + "and the", + upper, + "of the domain of the", + "second", + axisname, + "axis." + ].join(" "); + } +}; +var ARROWPATHS$1 = arrow_paths; +var fontAttrs$9 = font_attributes; +var cartesianConstants$1 = constants$U; +var templatedArray$7 = plot_template.templatedArray; +var axisPlaceableObjs$3 = axis_placeable_objects; +function arrowAxisRefDescription(axis) { + return [ + "In order for absolute positioning of the arrow to work, *a" + axis + "ref* must be exactly the same as *" + axis + "ref*, otherwise *a" + axis + "ref* will revert to *pixel* (explained next).", + "For relative positioning, *a" + axis + "ref* can be set to *pixel*,", + "in which case the *a" + axis + "* value is specified in pixels", + "relative to *" + axis + "*.", + "Absolute positioning is useful", + "for trendline annotations which should continue to indicate", + "the correct trend when zoomed. Relative positioning is useful", + "for specifying the text offset for an annotated point." + ].join(" "); +} +function arrowCoordinateDescription(axis, lower, upper) { + return [ + "Sets the", + axis, + "component of the arrow tail about the arrow head.", + "If `a" + axis + "ref` is `pixel`, a positive (negative)", + "component corresponds to an arrow pointing", + "from", + upper, + "to", + lower, + "(" + lower, + "to", + upper + ").", + "If `a" + axis + "ref` is not `pixel` and is exactly the same as `" + axis + "ref`,", + "this is an absolute value on that axis,", + "like `" + axis + "`, specified in the same coordinates as `" + axis + "ref`." + ].join(" "); +} +var attributes$B = templatedArray$7("annotation", { + visible: { + valType: "boolean", + dflt: true, + editType: "calc+arraydraw", + description: [ + "Determines whether or not this annotation is visible." + ].join(" ") + }, + text: { + valType: "string", + editType: "calc+arraydraw", + description: [ + "Sets the text associated with this annotation.", + "Plotly uses a subset of HTML tags to do things like", + "newline (
), bold (), italics (),", + "hyperlinks (). Tags , , , , ", + " are also supported." + ].join(" ") + }, + textangle: { + valType: "angle", + dflt: 0, + editType: "calc+arraydraw", + description: [ + "Sets the angle at which the `text` is drawn", + "with respect to the horizontal." + ].join(" ") + }, + font: fontAttrs$9({ + editType: "calc+arraydraw", + colorEditType: "arraydraw", + description: "Sets the annotation text font." + }), + width: { + valType: "number", + min: 1, + dflt: null, + editType: "calc+arraydraw", + description: [ + "Sets an explicit width for the text box. null (default) lets the", + "text set the box width. Wider text will be clipped.", + "There is no automatic wrapping; use
to start a new line." + ].join(" ") + }, + height: { + valType: "number", + min: 1, + dflt: null, + editType: "calc+arraydraw", + description: [ + "Sets an explicit height for the text box. null (default) lets the", + "text set the box height. Taller text will be clipped." + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 1, + editType: "arraydraw", + description: "Sets the opacity of the annotation (text + arrow)." + }, + align: { + valType: "enumerated", + values: ["left", "center", "right"], + dflt: "center", + editType: "arraydraw", + description: [ + "Sets the horizontal alignment of the `text` within the box.", + "Has an effect only if `text` spans two or more lines", + "(i.e. `text` contains one or more
HTML tags) or if an", + "explicit width is set to override the text width." + ].join(" ") + }, + valign: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + dflt: "middle", + editType: "arraydraw", + description: [ + "Sets the vertical alignment of the `text` within the box.", + "Has an effect only if an explicit height is set to override", + "the text height." + ].join(" ") + }, + bgcolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + editType: "arraydraw", + description: "Sets the background color of the annotation." + }, + bordercolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + editType: "arraydraw", + description: [ + "Sets the color of the border enclosing the annotation `text`." + ].join(" ") + }, + borderpad: { + valType: "number", + min: 0, + dflt: 1, + editType: "calc+arraydraw", + description: [ + "Sets the padding (in px) between the `text`", + "and the enclosing border." + ].join(" ") + }, + borderwidth: { + valType: "number", + min: 0, + dflt: 1, + editType: "calc+arraydraw", + description: [ + "Sets the width (in px) of the border enclosing", + "the annotation `text`." + ].join(" ") + }, + // arrow + showarrow: { + valType: "boolean", + dflt: true, + editType: "calc+arraydraw", + description: [ + "Determines whether or not the annotation is drawn with an arrow.", + "If *true*, `text` is placed near the arrow's tail.", + "If *false*, `text` lines up with the `x` and `y` provided." + ].join(" ") + }, + arrowcolor: { + valType: "color", + editType: "arraydraw", + description: "Sets the color of the annotation arrow." + }, + arrowhead: { + valType: "integer", + min: 0, + max: ARROWPATHS$1.length, + dflt: 1, + editType: "arraydraw", + description: "Sets the end annotation arrow head style." + }, + startarrowhead: { + valType: "integer", + min: 0, + max: ARROWPATHS$1.length, + dflt: 1, + editType: "arraydraw", + description: "Sets the start annotation arrow head style." + }, + arrowside: { + valType: "flaglist", + flags: ["end", "start"], + extras: ["none"], + dflt: "end", + editType: "arraydraw", + description: "Sets the annotation arrow head position." + }, + arrowsize: { + valType: "number", + min: 0.3, + dflt: 1, + editType: "calc+arraydraw", + description: [ + "Sets the size of the end annotation arrow head, relative to `arrowwidth`.", + "A value of 1 (default) gives a head about 3x as wide as the line." + ].join(" ") + }, + startarrowsize: { + valType: "number", + min: 0.3, + dflt: 1, + editType: "calc+arraydraw", + description: [ + "Sets the size of the start annotation arrow head, relative to `arrowwidth`.", + "A value of 1 (default) gives a head about 3x as wide as the line." + ].join(" ") + }, + arrowwidth: { + valType: "number", + min: 0.1, + editType: "calc+arraydraw", + description: "Sets the width (in px) of annotation arrow line." + }, + standoff: { + valType: "number", + min: 0, + dflt: 0, + editType: "calc+arraydraw", + description: [ + "Sets a distance, in pixels, to move the end arrowhead away from the", + "position it is pointing at, for example to point at the edge of", + "a marker independent of zoom. Note that this shortens the arrow", + "from the `ax` / `ay` vector, in contrast to `xshift` / `yshift`", + "which moves everything by this amount." + ].join(" ") + }, + startstandoff: { + valType: "number", + min: 0, + dflt: 0, + editType: "calc+arraydraw", + description: [ + "Sets a distance, in pixels, to move the start arrowhead away from the", + "position it is pointing at, for example to point at the edge of", + "a marker independent of zoom. Note that this shortens the arrow", + "from the `ax` / `ay` vector, in contrast to `xshift` / `yshift`", + "which moves everything by this amount." + ].join(" ") + }, + ax: { + valType: "any", + editType: "calc+arraydraw", + description: [ + arrowCoordinateDescription("x", "left", "right") + ].join(" ") + }, + ay: { + valType: "any", + editType: "calc+arraydraw", + description: [ + arrowCoordinateDescription("y", "top", "bottom") + ].join(" ") + }, + axref: { + valType: "enumerated", + dflt: "pixel", + values: [ + "pixel", + cartesianConstants$1.idRegex.x.toString() + ], + editType: "calc", + description: [ + "Indicates in what coordinates the tail of the", + "annotation (ax,ay) is specified.", + axisPlaceableObjs$3.axisRefDescription("x", "left", "right"), + arrowAxisRefDescription("x") + ].join(" ") + }, + ayref: { + valType: "enumerated", + dflt: "pixel", + values: [ + "pixel", + cartesianConstants$1.idRegex.y.toString() + ], + editType: "calc", + description: [ + "Indicates in what coordinates the tail of the", + "annotation (ax,ay) is specified.", + axisPlaceableObjs$3.axisRefDescription("y", "bottom", "top"), + arrowAxisRefDescription("y") + ].join(" ") + }, + // positioning + xref: { + valType: "enumerated", + values: [ + "paper", + cartesianConstants$1.idRegex.x.toString() + ], + editType: "calc", + description: [ + "Sets the annotation's x coordinate axis.", + axisPlaceableObjs$3.axisRefDescription("x", "left", "right") + ].join(" ") + }, + x: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the annotation's x position.", + "If the axis `type` is *log*, then you must take the", + "log of your desired range.", + "If the axis `type` is *date*, it should be date strings,", + "like date data, though Date objects and unix milliseconds", + "will be accepted and converted to strings.", + "If the axis `type` is *category*, it should be numbers,", + "using the scale where each category is assigned a serial", + "number from zero in the order it appears." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "auto", + editType: "calc+arraydraw", + description: [ + "Sets the text box's horizontal position anchor", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the annotation.", + "For example, if `x` is set to 1, `xref` to *paper* and", + "`xanchor` to *right* then the right-most portion of the", + "annotation lines up with the right-most edge of the", + "plotting area.", + "If *auto*, the anchor is equivalent to *center* for", + "data-referenced annotations or if there is an arrow,", + "whereas for paper-referenced with no arrow, the anchor picked", + "corresponds to the closest side." + ].join(" ") + }, + xshift: { + valType: "number", + dflt: 0, + editType: "calc+arraydraw", + description: [ + "Shifts the position of the whole annotation and arrow to the", + "right (positive) or left (negative) by this many pixels." + ].join(" ") + }, + yref: { + valType: "enumerated", + values: [ + "paper", + cartesianConstants$1.idRegex.y.toString() + ], + editType: "calc", + description: [ + "Sets the annotation's y coordinate axis.", + axisPlaceableObjs$3.axisRefDescription("y", "bottom", "top") + ].join(" ") + }, + y: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the annotation's y position.", + "If the axis `type` is *log*, then you must take the", + "log of your desired range.", + "If the axis `type` is *date*, it should be date strings,", + "like date data, though Date objects and unix milliseconds", + "will be accepted and converted to strings.", + "If the axis `type` is *category*, it should be numbers,", + "using the scale where each category is assigned a serial", + "number from zero in the order it appears." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + values: ["auto", "top", "middle", "bottom"], + dflt: "auto", + editType: "calc+arraydraw", + description: [ + "Sets the text box's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the annotation.", + "For example, if `y` is set to 1, `yref` to *paper* and", + "`yanchor` to *top* then the top-most portion of the", + "annotation lines up with the top-most edge of the", + "plotting area.", + "If *auto*, the anchor is equivalent to *middle* for", + "data-referenced annotations or if there is an arrow,", + "whereas for paper-referenced with no arrow, the anchor picked", + "corresponds to the closest side." + ].join(" ") + }, + yshift: { + valType: "number", + dflt: 0, + editType: "calc+arraydraw", + description: [ + "Shifts the position of the whole annotation and arrow up", + "(positive) or down (negative) by this many pixels." + ].join(" ") + }, + clicktoshow: { + valType: "enumerated", + values: [false, "onoff", "onout"], + dflt: false, + editType: "arraydraw", + description: [ + "Makes this annotation respond to clicks on the plot.", + "If you click a data point that exactly matches the `x` and `y`", + "values of this annotation, and it is hidden (visible: false),", + "it will appear. In *onoff* mode, you must click the same point", + "again to make it disappear, so if you click multiple points,", + "you can show multiple annotations. In *onout* mode, a click", + "anywhere else in the plot (on another data point or not) will", + "hide this annotation.", + "If you need to show/hide this annotation in response to different", + "`x` or `y` values, you can set `xclick` and/or `yclick`. This is", + "useful for example to label the side of a bar. To label markers", + "though, `standoff` is preferred over `xclick` and `yclick`." + ].join(" ") + }, + xclick: { + valType: "any", + editType: "arraydraw", + description: [ + "Toggle this annotation when clicking a data point whose `x` value", + "is `xclick` rather than the annotation's `x` value." + ].join(" ") + }, + yclick: { + valType: "any", + editType: "arraydraw", + description: [ + "Toggle this annotation when clicking a data point whose `y` value", + "is `yclick` rather than the annotation's `y` value." + ].join(" ") + }, + hovertext: { + valType: "string", + editType: "arraydraw", + description: [ + "Sets text to appear when hovering over this annotation.", + "If omitted or blank, no hover label will appear." + ].join(" ") + }, + hoverlabel: { + bgcolor: { + valType: "color", + editType: "arraydraw", + description: [ + "Sets the background color of the hover label.", + "By default uses the annotation's `bgcolor` made opaque,", + "or white if it was transparent." + ].join(" ") + }, + bordercolor: { + valType: "color", + editType: "arraydraw", + description: [ + "Sets the border color of the hover label.", + "By default uses either dark grey or white, for maximum", + "contrast with `hoverlabel.bgcolor`." + ].join(" ") + }, + font: fontAttrs$9({ + editType: "arraydraw", + description: [ + "Sets the hover label text font.", + "By default uses the global hover font and size,", + "with color from `hoverlabel.bordercolor`." + ].join(" ") + }), + editType: "arraydraw" + }, + captureevents: { + valType: "boolean", + editType: "arraydraw", + description: [ + "Determines whether the annotation text box captures mouse move", + "and click events, or allows those events to pass through to data", + "points in the plot that may be behind the annotation. By default", + "`captureevents` is *false* unless `hovertext` is provided.", + "If you use the event `plotly_clickannotation` without `hovertext`", + "you must explicitly enable `captureevents`." + ].join(" ") + }, + editType: "calc", + _deprecated: { + ref: { + valType: "string", + editType: "calc", + description: [ + "Obsolete. Set `xref` and `yref` separately instead." + ].join(" ") + } + } +}); +var constants$B = { + PTS_LINESONLY: 20, + // fixed parameters of clustering and clipping algorithms + // fraction of clustering tolerance "so close we don't even consider it a new point" + minTolerance: 0.2, + // how fast does clustering tolerance increase as you get away from the visible region + toleranceGrowth: 10, + // number of viewport sizes away from the visible region + // at which we clip all lines to the perimeter + maxScreensAway: 20, + eventDataKeys: [] +}; +var fillcolor_attribute = function makeFillcolorAttr(hasFillgradient) { + return { + valType: "color", + editType: "style", + anim: true, + description: [ + "Sets the fill color.", + "Defaults to a half-transparent variant of the line color,", + "marker color, or marker line color, whichever is available." + (hasFillgradient ? " If fillgradient is specified, fillcolor is ignored except for setting the background color of the hover label, if any." : "") + ].join(" ") + }; +}; +var axisHoverFormat$4 = axis_format_attributes.axisHoverFormat; +var texttemplateAttrs$5 = template_attributes.texttemplateAttrs; +var hovertemplateAttrs$5 = template_attributes.hovertemplateAttrs; +var colorScaleAttrs$4 = attributes$I; +var fontAttrs$8 = font_attributes; +var dash$3 = attributes$M.dash; +var pattern$4 = attributes$M.pattern; +var Drawing$k = drawingExports; +var constants$A = constants$B; +var extendFlat$d = extend$5.extendFlat; +var makeFillcolorAttr$1 = fillcolor_attribute; +function axisPeriod(axis) { + return { + valType: "any", + dflt: 0, + editType: "calc", + description: [ + "Only relevant when the axis `type` is *date*.", + "Sets the period positioning in milliseconds or *M* on the " + axis + " axis.", + "Special values in the form of *M* could be used to declare", + "the number of months. In this case `n` must be a positive integer." + ].join(" ") + }; +} +function axisPeriod0(axis) { + return { + valType: "any", + editType: "calc", + description: [ + "Only relevant when the axis `type` is *date*.", + "Sets the base for period positioning in milliseconds or date string on the " + axis + " axis.", + "When `" + axis + "period` is round number of weeks,", + "the `" + axis + "period0` by default would be on a Sunday i.e. 2000-01-02,", + "otherwise it would be at 2000-01-01." + ].join(" ") + }; +} +function axisPeriodAlignment(axis) { + return { + valType: "enumerated", + values: [ + "start", + "middle", + "end" + ], + dflt: "middle", + editType: "calc", + description: [ + "Only relevant when the axis `type` is *date*.", + "Sets the alignment of data points on the " + axis + " axis." + ].join(" ") + }; +} +var attributes$A = { + x: { + valType: "data_array", + editType: "calc+clearAxisTypes", + anim: true, + description: "Sets the x coordinates." + }, + x0: { + valType: "any", + dflt: 0, + editType: "calc+clearAxisTypes", + anim: true, + description: [ + "Alternate to `x`.", + "Builds a linear space of x coordinates.", + "Use with `dx`", + "where `x0` is the starting coordinate and `dx` the step." + ].join(" ") + }, + dx: { + valType: "number", + dflt: 1, + editType: "calc", + anim: true, + description: [ + "Sets the x coordinate step.", + "See `x0` for more info." + ].join(" ") + }, + y: { + valType: "data_array", + editType: "calc+clearAxisTypes", + anim: true, + description: "Sets the y coordinates." + }, + y0: { + valType: "any", + dflt: 0, + editType: "calc+clearAxisTypes", + anim: true, + description: [ + "Alternate to `y`.", + "Builds a linear space of y coordinates.", + "Use with `dy`", + "where `y0` is the starting coordinate and `dy` the step." + ].join(" ") + }, + dy: { + valType: "number", + dflt: 1, + editType: "calc", + anim: true, + description: [ + "Sets the y coordinate step.", + "See `y0` for more info." + ].join(" ") + }, + xperiod: axisPeriod("x"), + yperiod: axisPeriod("y"), + xperiod0: axisPeriod0("x0"), + yperiod0: axisPeriod0("y0"), + xperiodalignment: axisPeriodAlignment("x"), + yperiodalignment: axisPeriodAlignment("y"), + xhoverformat: axisHoverFormat$4("x"), + yhoverformat: axisHoverFormat$4("y"), + offsetgroup: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "Set several traces linked to the same position axis", + "or matching axes to the same", + "offsetgroup where bars of the same position coordinate will line up." + ].join(" ") + }, + alignmentgroup: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "Set several traces linked to the same position axis", + "or matching axes to the same", + "alignmentgroup. This controls whether bars compute their positional", + "range dependently or independently." + ].join(" ") + }, + stackgroup: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "Set several scatter traces (on the same subplot) to the same", + "stackgroup in order to add their y values (or their x values if", + "`orientation` is *h*). If blank or omitted this trace will not be", + "stacked. Stacking also turns `fill` on by default, using *tonexty*", + "(*tonextx*) if `orientation` is *h* (*v*) and sets the default", + "`mode` to *lines* irrespective of point count.", + "You can only stack on a numeric (linear or log) axis.", + "Traces in a `stackgroup` will only fill to (or be filled to) other", + "traces in the same group. With multiple `stackgroup`s or some", + "traces stacked and some not, if fill-linked traces are not already", + "consecutive, the later ones will be pushed down in the drawing order." + ].join(" ") + }, + orientation: { + valType: "enumerated", + values: ["v", "h"], + editType: "calc", + description: [ + "Only relevant in the following cases:", + "1. when `scattermode` is set to *group*.", + "2. when `stackgroup` is used, and only the first", + "`orientation` found in the `stackgroup` will be used - including", + "if `visible` is *legendonly* but not if it is `false`. Sets the", + "stacking direction. With *v* (*h*), the y (x) values of subsequent", + "traces are added. Also affects the default value of `fill`." + ].join(" ") + }, + groupnorm: { + valType: "enumerated", + values: ["", "fraction", "percent"], + dflt: "", + editType: "calc", + description: [ + "Only relevant when `stackgroup` is used, and only the first", + "`groupnorm` found in the `stackgroup` will be used - including", + "if `visible` is *legendonly* but not if it is `false`.", + "Sets the normalization for the sum of this `stackgroup`.", + "With *fraction*, the value of each trace at each location is", + "divided by the sum of all trace values at that location.", + "*percent* is the same but multiplied by 100 to show percentages.", + "If there are multiple subplots, or multiple `stackgroup`s on one", + "subplot, each will be normalized within its own set." + ].join(" ") + }, + stackgaps: { + valType: "enumerated", + values: ["infer zero", "interpolate"], + dflt: "infer zero", + editType: "calc", + description: [ + "Only relevant when `stackgroup` is used, and only the first", + "`stackgaps` found in the `stackgroup` will be used - including", + "if `visible` is *legendonly* but not if it is `false`.", + "Determines how we handle locations at which other traces in this", + "group have data but this one does not.", + "With *infer zero* we insert a zero at these locations.", + "With *interpolate* we linearly interpolate between existing", + "values, and extrapolate a constant beyond the existing values." + // TODO - implement interrupt mode + // '*interrupt* omits this trace from the stack at this location by', + // 'dropping abruptly, midway between the existing and missing locations.' + ].join(" ") + }, + text: { + valType: "string", + dflt: "", + arrayOk: true, + editType: "calc", + description: [ + "Sets text elements associated with each (x,y) pair.", + "If a single string, the same string appears over", + "all the data points.", + "If an array of string, the items are mapped in order to the", + "this trace's (x,y) coordinates.", + "If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,", + "these elements will be seen in the hover labels." + ].join(" ") + }, + texttemplate: texttemplateAttrs$5({}, {}), + hovertext: { + valType: "string", + dflt: "", + arrayOk: true, + editType: "style", + description: [ + "Sets hover text elements associated with each (x,y) pair.", + "If a single string, the same string appears over", + "all the data points.", + "If an array of string, the items are mapped in order to the", + "this trace's (x,y) coordinates.", + "To be seen, trace `hoverinfo` must contain a *text* flag." + ].join(" ") + }, + mode: { + valType: "flaglist", + flags: ["lines", "markers", "text"], + extras: ["none"], + editType: "calc", + description: [ + "Determines the drawing mode for this scatter trace.", + "If the provided `mode` includes *text* then the `text` elements", + "appear at the coordinates. Otherwise, the `text` elements", + "appear on hover.", + "If there are less than " + constants$A.PTS_LINESONLY + " points", + "and the trace is not stacked", + "then the default is *lines+markers*. Otherwise, *lines*." + ].join(" ") + }, + hoveron: { + valType: "flaglist", + flags: ["points", "fills"], + editType: "style", + description: [ + "Do the hover effects highlight individual points (markers or", + "line points) or do they highlight filled regions?", + "If the fill is *toself* or *tonext* and there are no markers", + "or text, then the default is *fills*, otherwise it is *points*." + ].join(" ") + }, + hovertemplate: hovertemplateAttrs$5({}, { + keys: constants$A.eventDataKeys + }), + line: { + color: { + valType: "color", + editType: "style", + anim: true, + description: "Sets the line color." + }, + width: { + valType: "number", + min: 0, + dflt: 2, + editType: "style", + anim: true, + description: "Sets the line width (in px)." + }, + shape: { + valType: "enumerated", + values: ["linear", "spline", "hv", "vh", "hvh", "vhv"], + dflt: "linear", + editType: "plot", + description: [ + "Determines the line shape.", + "With *spline* the lines are drawn using spline interpolation.", + "The other available values correspond to step-wise line shapes." + ].join(" ") + }, + smoothing: { + valType: "number", + min: 0, + max: 1.3, + dflt: 1, + editType: "plot", + description: [ + "Has an effect only if `shape` is set to *spline*", + "Sets the amount of smoothing.", + "*0* corresponds to no smoothing (equivalent to a *linear* shape)." + ].join(" ") + }, + dash: extendFlat$d({}, dash$3, { editType: "style" }), + backoff: { + // we want to have a similar option for the start of the line + valType: "number", + min: 0, + dflt: "auto", + arrayOk: true, + editType: "plot", + description: [ + "Sets the line back off from the end point of the nth line segment (in px).", + "This option is useful e.g. to avoid overlap with arrowhead markers.", + "With *auto* the lines would trim before markers if `marker.angleref` is set to *previous*." + ].join(" ") + }, + simplify: { + valType: "boolean", + dflt: true, + editType: "plot", + description: [ + "Simplifies lines by removing nearly-collinear points. When transitioning", + "lines, it may be desirable to disable this so that the number of points", + "along the resulting SVG path is unaffected." + ].join(" ") + }, + editType: "plot" + }, + connectgaps: { + valType: "boolean", + dflt: false, + editType: "calc", + description: [ + "Determines whether or not gaps", + "(i.e. {nan} or missing values)", + "in the provided data arrays are connected." + ].join(" ") + }, + cliponaxis: { + valType: "boolean", + dflt: true, + editType: "plot", + description: [ + "Determines whether or not markers and text nodes", + "are clipped about the subplot axes.", + "To show markers and text nodes above axis lines and tick labels,", + "make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + ].join(" ") + }, + fill: { + valType: "enumerated", + values: ["none", "tozeroy", "tozerox", "tonexty", "tonextx", "toself", "tonext"], + editType: "calc", + description: [ + "Sets the area to fill with a solid color.", + "Defaults to *none* unless this trace is stacked, then it gets", + "*tonexty* (*tonextx*) if `orientation` is *v* (*h*)", + "Use with `fillcolor` if not *none*.", + "*tozerox* and *tozeroy* fill to x=0 and y=0 respectively.", + "*tonextx* and *tonexty* fill between the endpoints of this", + "trace and the endpoints of the trace before it, connecting those", + "endpoints with straight lines (to make a stacked area graph);", + "if there is no trace before it, they behave like *tozerox* and", + "*tozeroy*.", + "*toself* connects the endpoints of the trace (or each segment", + "of the trace if it has gaps) into a closed shape.", + "*tonext* fills the space between two traces if one completely", + "encloses the other (eg consecutive contour lines), and behaves like", + "*toself* if there is no trace before it. *tonext* should not be", + "used if one trace does not enclose the other.", + "Traces in a `stackgroup` will only fill to (or be filled to) other", + "traces in the same group. With multiple `stackgroup`s or some", + "traces stacked and some not, if fill-linked traces are not already", + "consecutive, the later ones will be pushed down in the drawing order." + ].join(" ") + }, + fillcolor: makeFillcolorAttr$1(true), + fillgradient: extendFlat$d({ + type: { + valType: "enumerated", + values: ["radial", "horizontal", "vertical", "none"], + dflt: "none", + editType: "calc", + description: [ + "Sets the type/orientation of the color gradient for the fill.", + "Defaults to *none*." + ].join(" ") + }, + start: { + valType: "number", + editType: "calc", + description: [ + "Sets the gradient start value.", + "It is given as the absolute position on the axis determined by", + "the orientiation. E.g., if orientation is *horizontal*, the", + "gradient will be horizontal and start from the x-position", + "given by start. If omitted, the gradient starts at the lowest", + "value of the trace along the respective axis.", + "Ignored if orientation is *radial*." + ].join(" ") + }, + stop: { + valType: "number", + editType: "calc", + description: [ + "Sets the gradient end value.", + "It is given as the absolute position on the axis determined by", + "the orientiation. E.g., if orientation is *horizontal*, the", + "gradient will be horizontal and end at the x-position", + "given by end. If omitted, the gradient ends at the highest", + "value of the trace along the respective axis.", + "Ignored if orientation is *radial*." + ].join(" ") + }, + colorscale: { + valType: "colorscale", + editType: "style", + description: [ + "Sets the fill gradient colors as a color scale.", + "The color scale is interpreted as a gradient", + "applied in the direction specified by *orientation*,", + "from the lowest to the highest value of the scatter", + "plot along that axis, or from the center to the most", + "distant point from it, if orientation is *radial*." + ].join(" ") + }, + editType: "calc", + description: [ + "Sets a fill gradient.", + "If not specified, the fillcolor is used instead." + ].join(" ") + }), + fillpattern: pattern$4, + marker: extendFlat$d( + { + symbol: { + valType: "enumerated", + values: Drawing$k.symbolList, + dflt: "circle", + arrayOk: true, + editType: "style", + description: [ + "Sets the marker symbol type.", + "Adding 100 is equivalent to appending *-open* to a symbol name.", + "Adding 200 is equivalent to appending *-dot* to a symbol name.", + "Adding 300 is equivalent to appending *-open-dot*", + "or *dot-open* to a symbol name." + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + arrayOk: true, + editType: "style", + anim: true, + description: "Sets the marker opacity." + }, + angle: { + valType: "angle", + dflt: 0, + arrayOk: true, + editType: "plot", + anim: false, + // TODO: possibly set to true in future + description: [ + "Sets the marker angle in respect to `angleref`." + ].join(" ") + }, + angleref: { + valType: "enumerated", + values: ["previous", "up"], + dflt: "up", + editType: "plot", + anim: false, + description: [ + "Sets the reference for marker angle.", + "With *previous*, angle 0 points along the line from the previous point to this one.", + "With *up*, angle 0 points toward the top of the screen." + ].join(" ") + }, + standoff: { + valType: "number", + min: 0, + dflt: 0, + arrayOk: true, + editType: "plot", + anim: true, + description: [ + "Moves the marker away from the data point in the direction of `angle` (in px).", + "This can be useful for example if you have another marker at this", + "location and you want to point an arrowhead marker at it." + ].join(" ") + }, + size: { + valType: "number", + min: 0, + dflt: 6, + arrayOk: true, + editType: "calc", + anim: true, + description: "Sets the marker size (in px)." + }, + maxdisplayed: { + valType: "number", + min: 0, + dflt: 0, + editType: "plot", + description: [ + "Sets a maximum number of points to be drawn on the graph.", + "*0* corresponds to no limit." + ].join(" ") + }, + sizeref: { + valType: "number", + dflt: 1, + editType: "calc", + description: [ + "Has an effect only if `marker.size` is set to a numerical array.", + "Sets the scale factor used to determine the rendered size of", + "marker points. Use with `sizemin` and `sizemode`." + ].join(" ") + }, + sizemin: { + valType: "number", + min: 0, + dflt: 0, + editType: "calc", + description: [ + "Has an effect only if `marker.size` is set to a numerical array.", + "Sets the minimum size (in px) of the rendered marker points." + ].join(" ") + }, + sizemode: { + valType: "enumerated", + values: ["diameter", "area"], + dflt: "diameter", + editType: "calc", + description: [ + "Has an effect only if `marker.size` is set to a numerical array.", + "Sets the rule for which the data in `size` is converted", + "to pixels." + ].join(" ") + }, + line: extendFlat$d( + { + width: { + valType: "number", + min: 0, + arrayOk: true, + editType: "style", + anim: true, + description: "Sets the width (in px) of the lines bounding the marker points." + }, + editType: "calc" + }, + colorScaleAttrs$4("marker.line", { anim: true }) + ), + gradient: { + type: { + valType: "enumerated", + values: ["radial", "horizontal", "vertical", "none"], + arrayOk: true, + dflt: "none", + editType: "calc", + description: [ + "Sets the type of gradient used to fill the markers" + ].join(" ") + }, + color: { + valType: "color", + arrayOk: true, + editType: "calc", + description: [ + "Sets the final color of the gradient fill:", + "the center color for radial, the right for horizontal,", + "or the bottom for vertical." + ].join(" ") + }, + editType: "calc" + }, + editType: "calc" + }, + colorScaleAttrs$4("marker", { anim: true }) + ), + selected: { + marker: { + opacity: { + valType: "number", + min: 0, + max: 1, + editType: "style", + description: "Sets the marker opacity of selected points." + }, + color: { + valType: "color", + editType: "style", + description: "Sets the marker color of selected points." + }, + size: { + valType: "number", + min: 0, + editType: "style", + description: "Sets the marker size of selected points." + }, + editType: "style" + }, + textfont: { + color: { + valType: "color", + editType: "style", + description: "Sets the text font color of selected points." + }, + editType: "style" + }, + editType: "style" + }, + unselected: { + marker: { + opacity: { + valType: "number", + min: 0, + max: 1, + editType: "style", + description: "Sets the marker opacity of unselected points, applied only when a selection exists." + }, + color: { + valType: "color", + editType: "style", + description: "Sets the marker color of unselected points, applied only when a selection exists." + }, + size: { + valType: "number", + min: 0, + editType: "style", + description: "Sets the marker size of unselected points, applied only when a selection exists." + }, + editType: "style" + }, + textfont: { + color: { + valType: "color", + editType: "style", + description: "Sets the text font color of unselected points, applied only when a selection exists." + }, + editType: "style" + }, + editType: "style" + }, + textposition: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + dflt: "middle center", + arrayOk: true, + editType: "calc", + description: [ + "Sets the positions of the `text` elements", + "with respects to the (x,y) coordinates." + ].join(" ") + }, + textfont: fontAttrs$8({ + editType: "calc", + colorEditType: "style", + arrayOk: true, + description: "Sets the text font." + }), + zorder: { + valType: "integer", + dflt: 0, + editType: "plot", + description: [ + "Sets the layer on which this trace is displayed, relative to", + "other SVG traces on the same subplot. SVG traces with higher `zorder`", + "appear in front of those with lower `zorder`." + ].join(" ") + } +}; +var annAttrs$2 = attributes$B; +var scatterLineAttrs$2 = attributes$A.line; +var dash$2 = attributes$M.dash; +var extendFlat$c = extend$5.extendFlat; +var overrideAll$5 = edit_types.overrideAll; +var templatedArray$6 = plot_template.templatedArray; +var axisPlaceableObjs$2 = axis_placeable_objects; +var attributes$z = overrideAll$5(templatedArray$6("selection", { + type: { + valType: "enumerated", + values: ["rect", "path"], + description: [ + "Specifies the selection type to be drawn.", + "If *rect*, a rectangle is drawn linking", + "(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`) and (`x0`,`y1`).", + "If *path*, draw a custom SVG path using `path`." + ].join(" ") + }, + xref: extendFlat$c({}, annAttrs$2.xref, { + description: [ + "Sets the selection's x coordinate axis.", + axisPlaceableObjs$2.axisRefDescription("x", "left", "right") + ].join(" ") + }), + yref: extendFlat$c({}, annAttrs$2.yref, { + description: [ + "Sets the selection's x coordinate axis.", + axisPlaceableObjs$2.axisRefDescription("y", "bottom", "top") + ].join(" ") + }), + x0: { + valType: "any", + description: "Sets the selection's starting x position." + }, + x1: { + valType: "any", + description: "Sets the selection's end x position." + }, + y0: { + valType: "any", + description: "Sets the selection's starting y position." + }, + y1: { + valType: "any", + description: "Sets the selection's end y position." + }, + path: { + valType: "string", + editType: "arraydraw", + description: [ + "For `type` *path* - a valid SVG path similar to `shapes.path` in data coordinates.", + "Allowed segments are: M, L and Z." + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 0.7, + editType: "arraydraw", + description: "Sets the opacity of the selection." + }, + line: { + color: scatterLineAttrs$2.color, + width: extendFlat$c({}, scatterLineAttrs$2.width, { + min: 1, + dflt: 1 + }), + dash: extendFlat$c({}, dash$2, { + dflt: "dot" + }) + } +}), "arraydraw", "from-root"); +var Lib$1i = libExports; +var Axes$i = axesExports; +var handleArrayContainerDefaults$8 = array_container_defaults; +var attributes$y = attributes$z; +var helpers$q = helpers$w; +var defaults$j = function supplyLayoutDefaults4(layoutIn, layoutOut) { + handleArrayContainerDefaults$8(layoutIn, layoutOut, { + name: "selections", + handleItemDefaults: handleSelectionDefaults + }); + var selections2 = layoutOut.selections; + for (var i = 0; i < selections2.length; i++) { + var selection = selections2[i]; + if (!selection) continue; + if (selection.path === void 0) { + if (selection.x0 === void 0 || selection.x1 === void 0 || selection.y0 === void 0 || selection.y1 === void 0) { + layoutOut.selections[i] = null; + } + } + } +}; +function handleSelectionDefaults(selectionIn, selectionOut, fullLayout) { + function coerce2(attr, dflt) { + return Lib$1i.coerce(selectionIn, selectionOut, attributes$y, attr, dflt); + } + var path = coerce2("path"); + var dfltType = path ? "path" : "rect"; + var selectionType = coerce2("type", dfltType); + var noPath = selectionType !== "path"; + if (noPath) delete selectionOut.path; + coerce2("opacity"); + coerce2("line.color"); + coerce2("line.width"); + coerce2("line.dash"); + var axLetters2 = ["x", "y"]; + for (var i = 0; i < 2; i++) { + var axLetter = axLetters2[i]; + var gdMock = { _fullLayout: fullLayout }; + var ax; + var pos2r; + var r2pos; + var axRef = Axes$i.coerceRef(selectionIn, selectionOut, gdMock, axLetter); + ax = Axes$i.getFromId(gdMock, axRef); + ax._selectionIndices.push(selectionOut._index); + r2pos = helpers$q.rangeToShapePosition(ax); + pos2r = helpers$q.shapePositionToRange(ax); + if (noPath) { + var attr0 = axLetter + "0"; + var attr1 = axLetter + "1"; + var in0 = selectionIn[attr0]; + var in1 = selectionIn[attr1]; + selectionIn[attr0] = pos2r(selectionIn[attr0], true); + selectionIn[attr1] = pos2r(selectionIn[attr1], true); + Axes$i.coercePosition(selectionOut, gdMock, coerce2, axRef, attr0); + Axes$i.coercePosition(selectionOut, gdMock, coerce2, axRef, attr1); + var p0 = selectionOut[attr0]; + var p1 = selectionOut[attr1]; + if (p0 !== void 0 && p1 !== void 0) { + selectionOut[attr0] = r2pos(p0); + selectionOut[attr1] = r2pos(p1); + selectionIn[attr0] = in0; + selectionIn[attr1] = in1; + } + } + } + if (noPath) { + Lib$1i.noneOrAll(selectionIn, selectionOut, ["x0", "x1", "y0", "y1"]); + } +} +var defaults$i = function supplyDrawNewSelectionDefaults(layoutIn, layoutOut, coerce2) { + coerce2("newselection.mode"); + var newselectionLineWidth = coerce2("newselection.line.width"); + if (newselectionLineWidth) { + coerce2("newselection.line.color"); + coerce2("newselection.line.dash"); + } + coerce2("activeselection.fillcolor"); + coerce2("activeselection.opacity"); +}; +var Registry$u = registry; +var Lib$1h = libExports; +var axisIds$4 = axis_ids; +var include_components = function makeIncludeComponents(containerArrayName) { + return function includeComponents(layoutIn, layoutOut) { + var array2 = layoutIn[containerArrayName]; + if (!Array.isArray(array2)) return; + var Cartesian = Registry$u.subplotsRegistry.cartesian; + var idRegex2 = Cartesian.idRegex; + var subplots = layoutOut._subplots; + var xaList = subplots.xaxis; + var yaList = subplots.yaxis; + var cartesianList = subplots.cartesian; + var hasCartesianOrGL2D = layoutOut._has("cartesian") || layoutOut._has("gl2d"); + for (var i = 0; i < array2.length; i++) { + var itemi = array2[i]; + if (!Lib$1h.isPlainObject(itemi)) continue; + var xref = axisIds$4.cleanId(itemi.xref, "x", false); + var yref = axisIds$4.cleanId(itemi.yref, "y", false); + var hasXref = idRegex2.x.test(xref); + var hasYref = idRegex2.y.test(yref); + if (hasXref || hasYref) { + if (!hasCartesianOrGL2D) Lib$1h.pushUnique(layoutOut._basePlotModules, Cartesian); + var newAxis = false; + if (hasXref && xaList.indexOf(xref) === -1) { + xaList.push(xref); + newAxis = true; + } + if (hasYref && yaList.indexOf(yref) === -1) { + yaList.push(yref); + newAxis = true; + } + if (newAxis && hasXref && hasYref) { + cartesianList.push(xref + yref); + } + } + } + }; +}; +var drawModule$2 = draw_1$2; +var select$4 = select$5; +var selections = { + moduleType: "component", + name: "selections", + layoutAttributes: attributes$z, + supplyLayoutDefaults: defaults$j, + supplyDrawNewSelectionDefaults: defaults$i, + includeBasePlot: include_components("selections"), + draw: drawModule$2.draw, + drawOne: drawModule$2.drawOne, + reselect: select$4.reselect, + prepSelect: select$4.prepSelect, + clearOutline: select$4.clearOutline, + clearSelectionsCache: select$4.clearSelectionsCache, + selectOnClick: select$4.selectOnClick +}; +var dragbox; +var hasRequiredDragbox; +function requireDragbox() { + if (hasRequiredDragbox) return dragbox; + hasRequiredDragbox = 1; + var d32 = d3Exports; + var Lib2 = libExports; + var numberFormat2 = Lib2.numberFormat; + var tinycolor2 = tinycolorExports; + var supportsPassive2 = hasPassiveEvents; + var Registry2 = registry; + var strTranslate2 = Lib2.strTranslate; + var svgTextUtils2 = svg_text_utils; + var Color2 = colorExports; + var Drawing2 = drawingExports; + var Fx2 = fx$1; + var Axes2 = axesExports; + var setCursor3 = setcursor; + var dragElement2 = dragelementExports; + var helpers2 = helpers$B; + var selectingOrDrawing = helpers2.selectingOrDrawing; + var freeMode2 = helpers2.freeMode; + var FROM_TL2 = alignment$1.FROM_TL; + var clearGlCanvases3 = clear_gl_canvases; + var redrawReglTraces2 = subroutines.redrawReglTraces; + var Plots2 = plotsExports; + var getFromId2 = axis_ids.getFromId; + var prepSelect2 = selections.prepSelect; + var clearOutline2 = selections.clearOutline; + var selectOnClick2 = selections.selectOnClick; + var scaleZoom3 = scale_zoom; + var constants2 = constants$U; + var MINDRAG = constants2.MINDRAG; + var MINZOOM = constants2.MINZOOM; + var SHOWZOOMOUTTIP = true; + function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { + var zoomlayer = gd._fullLayout._zoomlayer; + var isMainDrag = ns + ew === "nsew"; + var singleEnd = (ns + ew).length === 1; + var xa0, ya0; + var xaHash, yaHash; + var xaxes, yaxes; + var xs, ys; + var pw, ph; + var links; + var matches; + var xActive, yActive; + var allFixedRanges; + var editX, editY; + var hasScatterGl, hasSplom, hasSVG; + var updates; + var scaleX; + var scaleY; + x += plotinfo.yaxis._shift; + function recomputeAxisLists() { + xa0 = plotinfo.xaxis; + ya0 = plotinfo.yaxis; + pw = xa0._length; + ph = ya0._length; + xs = xa0._offset; + ys = ya0._offset; + xaHash = {}; + xaHash[xa0._id] = xa0; + yaHash = {}; + yaHash[ya0._id] = ya0; + if (ns && ew) { + var overlays = plotinfo.overlays; + for (var i = 0; i < overlays.length; i++) { + var xa = overlays[i].xaxis; + xaHash[xa._id] = xa; + var ya = overlays[i].yaxis; + yaHash[ya._id] = ya; + } + } + xaxes = hashValues(xaHash); + yaxes = hashValues(yaHash); + xActive = isDirectionActive(xaxes, ew); + yActive = isDirectionActive(yaxes, ns); + allFixedRanges = !yActive && !xActive; + matches = calcLinks(gd, gd._fullLayout._axisMatchGroups, xaHash, yaHash); + links = calcLinks(gd, gd._fullLayout._axisConstraintGroups, xaHash, yaHash, matches); + var spConstrained = links.isSubplotConstrained || matches.isSubplotConstrained; + editX = ew || spConstrained; + editY = ns || spConstrained; + var fullLayout = gd._fullLayout; + hasScatterGl = fullLayout._has("scattergl"); + hasSplom = fullLayout._has("splom"); + hasSVG = fullLayout._has("svg"); + } + recomputeAxisLists(); + var cursor2 = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); + var dragger = makeRectDragger(plotinfo, ns + ew + "drag", cursor2, x, y, w, h); + if (allFixedRanges && !isMainDrag) { + dragger.onmousedown = null; + dragger.style.pointerEvents = "none"; + return dragger; + } + var dragOptions = { + element: dragger, + gd, + plotinfo + }; + dragOptions.prepFn = function(e, startX, startY) { + var dragModePrev = dragOptions.dragmode; + var dragModeNow = gd._fullLayout.dragmode; + if (dragModeNow !== dragModePrev) { + dragOptions.dragmode = dragModeNow; + } + recomputeAxisLists(); + scaleX = gd._fullLayout._invScaleX; + scaleY = gd._fullLayout._invScaleY; + if (!allFixedRanges) { + if (isMainDrag) { + if (e.shiftKey) { + if (dragModeNow === "pan") dragModeNow = "zoom"; + else if (!selectingOrDrawing(dragModeNow)) dragModeNow = "pan"; + } else if (e.ctrlKey) { + dragModeNow = "pan"; + } + } else { + dragModeNow = "pan"; + } + } + if (freeMode2(dragModeNow)) dragOptions.minDrag = 1; + else dragOptions.minDrag = void 0; + if (selectingOrDrawing(dragModeNow)) { + dragOptions.xaxes = xaxes; + dragOptions.yaxes = yaxes; + prepSelect2(e, startX, startY, dragOptions, dragModeNow); + } else { + dragOptions.clickFn = clickFn; + if (selectingOrDrawing(dragModePrev)) { + clearAndResetSelect(); + } + if (!allFixedRanges) { + if (dragModeNow === "zoom") { + dragOptions.moveFn = zoomMove; + dragOptions.doneFn = zoomDone; + dragOptions.minDrag = 1; + zoomPrep(e, startX, startY); + } else if (dragModeNow === "pan") { + dragOptions.moveFn = plotDrag; + dragOptions.doneFn = dragTail; + } + } + } + gd._fullLayout._redrag = function() { + var dragDataNow = gd._dragdata; + if (dragDataNow && dragDataNow.element === dragger) { + var dragModeNow2 = gd._fullLayout.dragmode; + if (!selectingOrDrawing(dragModeNow2)) { + recomputeAxisLists(); + updateSubplots([0, 0, pw, ph]); + dragOptions.moveFn(dragDataNow.dx, dragDataNow.dy); + } + } + }; + }; + function clearAndResetSelect() { + dragOptions.plotinfo.selection = false; + clearOutline2(gd); + } + function clickFn(numClicks, evt) { + var gd2 = dragOptions.gd; + if (gd2._fullLayout._activeShapeIndex >= 0) { + gd2._fullLayout._deactivateShape(gd2); + return; + } + var clickmode = gd2._fullLayout.clickmode; + removeZoombox(gd2); + if (numClicks === 2 && !singleEnd) doubleClick(); + if (isMainDrag) { + if (clickmode.indexOf("select") > -1) { + selectOnClick2(evt, gd2, xaxes, yaxes, plotinfo.id, dragOptions); + } + if (clickmode.indexOf("event") > -1) { + Fx2.click(gd2, evt, plotinfo.id); + } + } else if (numClicks === 1 && singleEnd) { + var ax = ns ? ya0 : xa0; + var end = ns === "s" || ew === "w" ? 0 : 1; + var attrStr = ax._name + ".range[" + end + "]"; + var initialText = getEndText(ax, end); + var hAlign = "left"; + var vAlign = "middle"; + if (ax.fixedrange) return; + if (ns) { + vAlign = ns === "n" ? "top" : "bottom"; + if (ax.side === "right") hAlign = "right"; + } else if (ew === "e") hAlign = "right"; + if (gd2._context.showAxisRangeEntryBoxes) { + d32.select(dragger).call(svgTextUtils2.makeEditable, { + gd: gd2, + immediate: true, + background: gd2._fullLayout.paper_bgcolor, + text: String(initialText), + fill: ax.tickfont ? ax.tickfont.color : "#444", + horizontalAlign: hAlign, + verticalAlign: vAlign + }).on("edit", function(text) { + var v = ax.d2r(text); + if (v !== void 0) { + Registry2.call("_guiRelayout", gd2, attrStr, v); + } + }); + } + } + } + dragElement2.init(dragOptions); + var x0, y0; + var box; + var lum; + var path0; + var dimmed; + var zoomMode; + var zb; + var corners; + var zoomDragged; + function zoomPrep(e, startX, startY) { + var dragBBox = dragger.getBoundingClientRect(); + x0 = startX - dragBBox.left; + y0 = startY - dragBBox.top; + gd._fullLayout._calcInverseTransform(gd); + var transformedCoords = Lib2.apply3DTransform(gd._fullLayout._invTransform)(x0, y0); + x0 = transformedCoords[0]; + y0 = transformedCoords[1]; + box = { l: x0, r: x0, w: 0, t: y0, b: y0, h: 0 }; + lum = gd._hmpixcount ? gd._hmlumcount / gd._hmpixcount : tinycolor2(gd._fullLayout.plot_bgcolor).getLuminance(); + path0 = "M0,0H" + pw + "V" + ph + "H0V0"; + dimmed = false; + zoomMode = "xy"; + zoomDragged = false; + zb = makeZoombox(zoomlayer, lum, xs, ys, path0); + corners = makeCorners(zoomlayer, xs, ys); + } + function zoomMove(dx0, dy0) { + if (gd._transitioningWithDuration) { + return false; + } + var x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0)); + var y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0)); + var dx = Math.abs(x1 - x0); + var dy = Math.abs(y1 - y0); + box.l = Math.min(x0, x1); + box.r = Math.max(x0, x1); + box.t = Math.min(y0, y1); + box.b = Math.max(y0, y1); + function noZoom() { + zoomMode = ""; + box.r = box.l; + box.t = box.b; + corners.attr("d", "M0,0Z"); + } + if (links.isSubplotConstrained) { + if (dx > MINZOOM || dy > MINZOOM) { + zoomMode = "xy"; + if (dx / pw > dy / ph) { + dy = dx * ph / pw; + if (y0 > y1) box.t = y0 - dy; + else box.b = y0 + dy; + } else { + dx = dy * pw / ph; + if (x0 > x1) box.l = x0 - dx; + else box.r = x0 + dx; + } + corners.attr("d", xyCorners(box)); + } else { + noZoom(); + } + } else if (matches.isSubplotConstrained) { + if (dx > MINZOOM || dy > MINZOOM) { + zoomMode = "xy"; + var r0 = Math.min(box.l / pw, (ph - box.b) / ph); + var r1 = Math.max(box.r / pw, (ph - box.t) / ph); + box.l = r0 * pw; + box.r = r1 * pw; + box.b = (1 - r0) * ph; + box.t = (1 - r1) * ph; + corners.attr("d", xyCorners(box)); + } else { + noZoom(); + } + } else if (!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { + if (dx < MINDRAG || !xActive) { + noZoom(); + } else { + box.t = 0; + box.b = ph; + zoomMode = "x"; + corners.attr("d", xCorners(box, y0)); + } + } else if (!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { + box.l = 0; + box.r = pw; + zoomMode = "y"; + corners.attr("d", yCorners(box, x0)); + } else { + zoomMode = "xy"; + corners.attr("d", xyCorners(box)); + } + box.w = box.r - box.l; + box.h = box.b - box.t; + if (zoomMode) zoomDragged = true; + gd._dragged = zoomDragged; + updateZoombox(zb, corners, box, path0, dimmed, lum); + computeZoomUpdates(); + gd.emit("plotly_relayouting", updates); + dimmed = true; + } + function computeZoomUpdates() { + updates = {}; + if (zoomMode === "xy" || zoomMode === "x") { + zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); + updateMatchedAxRange("x", updates); + } + if (zoomMode === "xy" || zoomMode === "y") { + zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); + updateMatchedAxRange("y", updates); + } + } + function zoomDone() { + computeZoomUpdates(); + removeZoombox(gd); + dragTail(); + showDoubleClickNotifier(gd); + } + var scrollViewBox = [0, 0, pw, ph]; + var redrawTimer = null; + var REDRAWDELAY = constants2.REDRAWDELAY; + var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; + function zoomWheel(e) { + if (!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) { + return; + } + clearAndResetSelect(); + if (gd._transitioningWithDuration) { + e.preventDefault(); + e.stopPropagation(); + return; + } + recomputeAxisLists(); + clearTimeout(redrawTimer); + var wheelDelta = -e.deltaY; + if (!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; + if (!isFinite(wheelDelta)) { + Lib2.log("Did not find wheel motion attributes: ", e); + return; + } + var zoom2 = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200); + var gbb = mainplot.draglayer.select(".nsewdrag").node().getBoundingClientRect(); + var xfrac = (e.clientX - gbb.left) / gbb.width; + var yfrac = (gbb.bottom - e.clientY) / gbb.height; + var i; + function zoomWheelOneAxis(ax, centerFraction, zoom3) { + if (ax.fixedrange) return; + var axRange = Lib2.simpleMap(ax.range, ax.r2l); + var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; + function doZoom(v) { + return ax.l2r(v0 + (v - v0) * zoom3); + } + ax.range = axRange.map(doZoom); + } + if (editX) { + if (!ew) xfrac = 0.5; + for (i = 0; i < xaxes.length; i++) { + zoomWheelOneAxis(xaxes[i], xfrac, zoom2); + } + updateMatchedAxRange("x"); + scrollViewBox[2] *= zoom2; + scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom2 - 1); + } + if (editY) { + if (!ns) yfrac = 0.5; + for (i = 0; i < yaxes.length; i++) { + zoomWheelOneAxis(yaxes[i], yfrac, zoom2); + } + updateMatchedAxRange("y"); + scrollViewBox[3] *= zoom2; + scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom2 - 1); + } + updateSubplots(scrollViewBox); + ticksAndAnnotations(); + gd.emit("plotly_relayouting", updates); + redrawTimer = setTimeout(function() { + if (!gd._fullLayout) return; + scrollViewBox = [0, 0, pw, ph]; + dragTail(); + }, REDRAWDELAY); + e.preventDefault(); + return; + } + if (ns.length * ew.length !== 1) { + attachWheelEventHandler(dragger, zoomWheel); + } + function plotDrag(dx, dy) { + dx = dx * scaleX; + dy = dy * scaleY; + if (gd._transitioningWithDuration) { + return; + } + gd._fullLayout._replotting = true; + if (xActive === "ew" || yActive === "ns") { + var spDx = xActive ? -dx : 0; + var spDy = yActive ? -dy : 0; + if (matches.isSubplotConstrained) { + if (xActive && yActive) { + var frac = (dx / pw - dy / ph) / 2; + dx = frac * pw; + dy = -frac * ph; + spDx = -dx; + spDy = -dy; + } + if (yActive) { + spDx = -spDy * pw / ph; + } else { + spDy = -spDx * ph / pw; + } + } + if (xActive) { + dragAxList(xaxes, dx); + updateMatchedAxRange("x"); + } + if (yActive) { + dragAxList(yaxes, dy); + updateMatchedAxRange("y"); + } + updateSubplots([spDx, spDy, pw, ph]); + ticksAndAnnotations(); + gd.emit("plotly_relayouting", updates); + return; + } + function dz(axArray, end, d) { + var otherEnd = 1 - end; + var movedAx; + var newLinearizedEnd; + for (var i2 = 0; i2 < axArray.length; i2++) { + var axi = axArray[i2]; + if (axi.fixedrange) continue; + movedAx = axi; + newLinearizedEnd = axi._rl[otherEnd] + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); + var newEnd = axi.l2r(newLinearizedEnd); + if (newEnd !== false && newEnd !== void 0) axi.range[end] = newEnd; + } + return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / (movedAx._rl[end] - movedAx._rl[otherEnd]); + } + var dxySign = xActive === "w" === (yActive === "n") ? 1 : -1; + if (xActive && yActive && (links.isSubplotConstrained || matches.isSubplotConstrained)) { + var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; + dx = dxyFraction * pw; + dy = dxySign * dxyFraction * ph; + } + var xStart, yStart; + if (xActive === "w") dx = dz(xaxes, 0, dx); + else if (xActive === "e") dx = dz(xaxes, 1, -dx); + else if (!xActive) dx = 0; + if (yActive === "n") dy = dz(yaxes, 1, dy); + else if (yActive === "s") dy = dz(yaxes, 0, -dy); + else if (!yActive) dy = 0; + xStart = xActive === "w" ? dx : 0; + yStart = yActive === "n" ? dy : 0; + if (links.isSubplotConstrained && !matches.isSubplotConstrained || // NW or SE on matching axes - create a symmetric zoom + matches.isSubplotConstrained && xActive && yActive && dxySign > 0) { + var i; + if (matches.isSubplotConstrained || !xActive && yActive.length === 1) { + for (i = 0; i < xaxes.length; i++) { + xaxes[i].range = xaxes[i]._r.slice(); + scaleZoom3(xaxes[i], 1 - dy / ph); + } + dx = dy * pw / ph; + xStart = dx / 2; + } + if (matches.isSubplotConstrained || !yActive && xActive.length === 1) { + for (i = 0; i < yaxes.length; i++) { + yaxes[i].range = yaxes[i]._r.slice(); + scaleZoom3(yaxes[i], 1 - dx / pw); + } + dy = dx * ph / pw; + yStart = dy / 2; + } + } + if (!matches.isSubplotConstrained || !yActive) { + updateMatchedAxRange("x"); + } + if (!matches.isSubplotConstrained || !xActive) { + updateMatchedAxRange("y"); + } + var xSize = pw - dx; + var ySize = ph - dy; + if (matches.isSubplotConstrained && !(xActive && yActive)) { + if (xActive) { + yStart = xStart ? 0 : dx * ph / pw; + ySize = xSize * ph / pw; + } else { + xStart = yStart ? 0 : dy * pw / ph; + xSize = ySize * pw / ph; + } + } + updateSubplots([xStart, yStart, xSize, ySize]); + ticksAndAnnotations(); + gd.emit("plotly_relayouting", updates); + } + function updateMatchedAxRange(axLetter, out) { + var matchedAxes = matches.isSubplotConstrained ? { x: yaxes, y: xaxes }[axLetter] : matches[axLetter + "axes"]; + var constrainedAxes = matches.isSubplotConstrained ? { x: xaxes, y: yaxes }[axLetter] : []; + for (var i = 0; i < matchedAxes.length; i++) { + var ax = matchedAxes[i]; + var axId = ax._id; + var axId2 = matches.xLinks[axId] || matches.yLinks[axId]; + var ax2 = constrainedAxes[0] || xaHash[axId2] || yaHash[axId2]; + if (ax2) { + if (out) { + out[ax._name + ".range[0]"] = out[ax2._name + ".range[0]"]; + out[ax._name + ".range[1]"] = out[ax2._name + ".range[1]"]; + } else { + ax.range = ax2.range.slice(); + } + } + } + } + function ticksAndAnnotations() { + var activeAxIds = []; + var i; + function pushActiveAxIds(axList) { + for (i = 0; i < axList.length; i++) { + if (!axList[i].fixedrange) activeAxIds.push(axList[i]._id); + } + } + function pushActiveAxIdsSynced(axList, axisType) { + for (i = 0; i < axList.length; i++) { + var axListI = axList[i]; + var axListIType = axListI[axisType]; + if (!axListI.fixedrange && axListIType.tickmode === "sync") activeAxIds.push(axListIType._id); + } + } + if (editX) { + pushActiveAxIds(xaxes); + pushActiveAxIds(links.xaxes); + pushActiveAxIds(matches.xaxes); + pushActiveAxIdsSynced(plotinfo.overlays, "xaxis"); + } + if (editY) { + pushActiveAxIds(yaxes); + pushActiveAxIds(links.yaxes); + pushActiveAxIds(matches.yaxes); + pushActiveAxIdsSynced(plotinfo.overlays, "yaxis"); + } + updates = {}; + for (i = 0; i < activeAxIds.length; i++) { + var axId = activeAxIds[i]; + var ax = getFromId2(gd, axId); + Axes2.drawOne(gd, ax, { skipTitle: true }); + updates[ax._name + ".range[0]"] = ax.range[0]; + updates[ax._name + ".range[1]"] = ax.range[1]; + } + Axes2.redrawComponents(gd, activeAxIds); + } + function doubleClick() { + if (gd._transitioningWithDuration) return; + var doubleClickConfig = gd._context.doubleClick; + var axList = []; + if (xActive) axList = axList.concat(xaxes); + if (yActive) axList = axList.concat(yaxes); + if (matches.xaxes) axList = axList.concat(matches.xaxes); + if (matches.yaxes) axList = axList.concat(matches.yaxes); + var attrs2 = {}; + var ax, i; + if (doubleClickConfig === "reset+autosize") { + doubleClickConfig = "autosize"; + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + var r0 = ax._rangeInitial0; + var r1 = ax._rangeInitial1; + var hasRangeInitial = r0 !== void 0 || r1 !== void 0; + if (hasRangeInitial && (r0 !== void 0 && r0 !== ax.range[0] || r1 !== void 0 && r1 !== ax.range[1]) || !hasRangeInitial && ax.autorange !== true) { + doubleClickConfig = "reset"; + break; + } + } + } + if (doubleClickConfig === "autosize") { + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + if (!ax.fixedrange) attrs2[ax._name + ".autorange"] = true; + } + } else if (doubleClickConfig === "reset") { + if (xActive || links.isSubplotConstrained) axList = axList.concat(links.xaxes); + if (yActive && !links.isSubplotConstrained) axList = axList.concat(links.yaxes); + if (links.isSubplotConstrained) { + if (!xActive) axList = axList.concat(xaxes); + else if (!yActive) axList = axList.concat(yaxes); + } + for (i = 0; i < axList.length; i++) { + ax = axList[i]; + if (!ax.fixedrange) { + var axName = ax._name; + var autorangeInitial = ax._autorangeInitial; + if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) { + attrs2[axName + ".autorange"] = true; + } else if (ax._rangeInitial0 === void 0) { + attrs2[axName + ".autorange"] = autorangeInitial; + attrs2[axName + ".range"] = [null, ax._rangeInitial1]; + } else if (ax._rangeInitial1 === void 0) { + attrs2[axName + ".range"] = [ax._rangeInitial0, null]; + attrs2[axName + ".autorange"] = autorangeInitial; + } else { + attrs2[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1]; + } + } + } + } + gd.emit("plotly_doubleclick", null); + Registry2.call("_guiRelayout", gd, attrs2); + } + function dragTail() { + updateSubplots([0, 0, pw, ph]); + Lib2.syncOrAsync([ + Plots2.previousPromises, + function() { + gd._fullLayout._replotting = false; + Registry2.call("_guiRelayout", gd, updates); + } + ], gd); + } + function updateSubplots(viewBox) { + var fullLayout = gd._fullLayout; + var plotinfos = fullLayout._plots; + var subplots = fullLayout._subplots.cartesian; + var i, sp, xa, ya; + if (hasSplom) { + Registry2.subplotsRegistry.splom.drag(gd); + } + if (hasScatterGl) { + for (i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + if (sp._scene) { + if (xa.limitRange) xa.limitRange(); + if (ya.limitRange) ya.limitRange(); + var xrng = Lib2.simpleMap(xa.range, xa.r2l); + var yrng = Lib2.simpleMap(ya.range, ya.r2l); + sp._scene.update({ range: [xrng[0], yrng[0], xrng[1], yrng[1]] }); + } + } + } + if (hasSplom || hasScatterGl) { + clearGlCanvases3(gd); + redrawReglTraces2(gd); + } + if (hasSVG) { + var xScaleFactor = viewBox[2] / xa0._length; + var yScaleFactor = viewBox[3] / ya0._length; + for (i = 0; i < subplots.length; i++) { + sp = plotinfos[subplots[i]]; + xa = sp.xaxis; + ya = sp.yaxis; + var editX2 = (editX || matches.isSubplotConstrained) && !xa.fixedrange && xaHash[xa._id]; + var editY2 = (editY || matches.isSubplotConstrained) && !ya.fixedrange && yaHash[ya._id]; + var xScaleFactor2, yScaleFactor2; + var clipDx, clipDy; + if (editX2) { + xScaleFactor2 = xScaleFactor; + clipDx = ew || matches.isSubplotConstrained ? viewBox[0] : getShift(xa, xScaleFactor2); + } else if (matches.xaHash[xa._id]) { + xScaleFactor2 = xScaleFactor; + clipDx = viewBox[0] * xa._length / xa0._length; + } else if (matches.yaHash[xa._id]) { + xScaleFactor2 = yScaleFactor; + clipDx = yActive === "ns" ? -viewBox[1] * xa._length / ya0._length : getShift(xa, xScaleFactor2, { n: "top", s: "bottom" }[yActive]); + } else { + xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); + clipDx = scaleAndGetShift(xa, xScaleFactor2); + } + if (xScaleFactor2 > 1 && (xa.maxallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "e" : "w") || xa.minallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "w" : "e"))) { + xScaleFactor2 = 1; + clipDx = 0; + } + if (editY2) { + yScaleFactor2 = yScaleFactor; + clipDy = ns || matches.isSubplotConstrained ? viewBox[1] : getShift(ya, yScaleFactor2); + } else if (matches.yaHash[ya._id]) { + yScaleFactor2 = yScaleFactor; + clipDy = viewBox[1] * ya._length / ya0._length; + } else if (matches.xaHash[ya._id]) { + yScaleFactor2 = xScaleFactor; + clipDy = xActive === "ew" ? -viewBox[0] * ya._length / xa0._length : getShift(ya, yScaleFactor2, { e: "right", w: "left" }[xActive]); + } else { + yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); + clipDy = scaleAndGetShift(ya, yScaleFactor2); + } + if (yScaleFactor2 > 1 && (ya.maxallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "n" : "s") || ya.minallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "s" : "n"))) { + yScaleFactor2 = 1; + clipDy = 0; + } + if (!xScaleFactor2 && !yScaleFactor2) { + continue; + } + if (!xScaleFactor2) xScaleFactor2 = 1; + if (!yScaleFactor2) yScaleFactor2 = 1; + var plotDx = xa._offset - clipDx / xScaleFactor2; + var plotDy = ya._offset - clipDy / yScaleFactor2; + sp.clipRect.call(Drawing2.setTranslate, clipDx, clipDy).call(Drawing2.setScale, xScaleFactor2, yScaleFactor2); + sp.plot.call(Drawing2.setTranslate, plotDx, plotDy).call(Drawing2.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); + if (xScaleFactor2 !== sp.xScaleFactor || yScaleFactor2 !== sp.yScaleFactor) { + Drawing2.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2); + Drawing2.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2); + } + Drawing2.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp); + sp.xScaleFactor = xScaleFactor2; + sp.yScaleFactor = yScaleFactor2; + } + } + } + function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { + if (ax.fixedrange) return 0; + if (editX && links.xaHash[ax._id]) { + return xScaleFactor; + } + if (editY && (links.isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { + return yScaleFactor; + } + return 0; + } + function scaleAndGetShift(ax, scaleFactor) { + if (scaleFactor) { + ax.range = ax._r.slice(); + scaleZoom3(ax, scaleFactor); + return getShift(ax, scaleFactor); + } + return 0; + } + function getShift(ax, scaleFactor, from) { + return ax._length * (1 - scaleFactor) * FROM_TL2[from || ax.constraintoward || "middle"]; + } + return dragger; + } + function makeDragger(plotinfo, nodeName, dragClass, cursor2) { + var dragger3 = Lib2.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { + s.classed("drag", true).style({ fill: "transparent", "stroke-width": 0 }).attr("data-subplot", plotinfo.id); + }); + dragger3.call(setCursor3, cursor2); + return dragger3.node(); + } + function makeRectDragger(plotinfo, dragClass, cursor2, x, y, w, h) { + var dragger = makeDragger(plotinfo, "rect", dragClass, cursor2); + d32.select(dragger).call(Drawing2.setRect, x, y, w, h); + return dragger; + } + function isDirectionActive(axList, activeVal) { + for (var i = 0; i < axList.length; i++) { + if (!axList[i].fixedrange) return activeVal; + } + return ""; + } + function getEndText(ax, end) { + var initialVal = ax.range[end]; + var diff = Math.abs(initialVal - ax.range[1 - end]); + var dig; + if (ax.type === "date") { + return initialVal; + } else if (ax.type === "log") { + dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; + return numberFormat2("." + dig + "g")(Math.pow(10, initialVal)); + } else { + dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - Math.floor(Math.log(diff) / Math.LN10) + 4; + return numberFormat2("." + String(dig) + "g")(initialVal); + } + } + function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { + for (var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if (axi.fixedrange) continue; + if (axi.rangebreaks) { + var isY = axi._id.charAt(0) === "y"; + var r0F = isY ? 1 - r0Fraction : r0Fraction; + var r1F = isY ? 1 - r1Fraction : r1Fraction; + updates[axi._name + ".range[0]"] = axi.l2r(axi.p2l(r0F * axi._length)); + updates[axi._name + ".range[1]"] = axi.l2r(axi.p2l(r1F * axi._length)); + } else { + var axRangeLinear0 = axi._rl[0]; + var axRangeLinearSpan = axi._rl[1] - axRangeLinear0; + updates[axi._name + ".range[0]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction); + updates[axi._name + ".range[1]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction); + } + } + if (linkedAxes && linkedAxes.length) { + var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; + zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates, []); + } + } + function dragAxList(axList, pix) { + for (var i = 0; i < axList.length; i++) { + var axi = axList[i]; + if (!axi.fixedrange) { + if (axi.rangebreaks) { + var p0 = 0; + var p1 = axi._length; + var d0 = axi.p2l(p0 + pix) - axi.p2l(p0); + var d1 = axi.p2l(p1 + pix) - axi.p2l(p1); + var delta2 = (d0 + d1) / 2; + axi.range = [ + axi.l2r(axi._rl[0] - delta2), + axi.l2r(axi._rl[1] - delta2) + ]; + } else { + axi.range = [ + axi.l2r(axi._rl[0] - pix / axi._m), + axi.l2r(axi._rl[1] - pix / axi._m) + ]; + } + if (axi.limitRange) axi.limitRange(); + } + } + } + function dZoom(d) { + return 1 - (d >= 0 ? Math.min(d, 0.9) : 1 / (1 / Math.max(d, -0.3) + 3.222)); + } + function getDragCursor(nsew, dragmode, isMainDrag) { + if (!nsew) return "pointer"; + if (nsew === "nsew") { + if (isMainDrag) return ""; + if (dragmode === "pan") return "move"; + return "crosshair"; + } + return nsew.toLowerCase() + "-resize"; + } + function makeZoombox(zoomlayer, lum, xs, ys, path0) { + return zoomlayer.append("path").attr("class", "zoombox").style({ + fill: lum > 0.2 ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)", + "stroke-width": 0 + }).attr("transform", strTranslate2(xs, ys)).attr("d", path0 + "Z"); + } + function makeCorners(zoomlayer, xs, ys) { + return zoomlayer.append("path").attr("class", "zoombox-corners").style({ + fill: Color2.background, + stroke: Color2.defaultLine, + "stroke-width": 1, + opacity: 0 + }).attr("transform", strTranslate2(xs, ys)).attr("d", "M0,0Z"); + } + function updateZoombox(zb, corners, box, path0, dimmed, lum) { + zb.attr( + "d", + path0 + "M" + box.l + "," + box.t + "v" + box.h + "h" + box.w + "v-" + box.h + "h-" + box.w + "Z" + ); + transitionZoombox(zb, corners, dimmed, lum); + } + function transitionZoombox(zb, corners, dimmed, lum) { + if (!dimmed) { + zb.transition().style("fill", lum > 0.2 ? "rgba(0,0,0,0.4)" : "rgba(255,255,255,0.3)").duration(200); + corners.transition().style("opacity", 1).duration(200); + } + } + function removeZoombox(gd) { + d32.select(gd).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove(); + } + function showDoubleClickNotifier(gd) { + if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { + Lib2.notifier(Lib2._(gd, "Double-click to zoom back out"), "long"); + SHOWZOOMOUTTIP = false; + } + } + function xCorners(box, y0) { + return "M" + (box.l - 0.5) + "," + (y0 - MINZOOM - 0.5) + "h-3v" + (2 * MINZOOM + 1) + "h3ZM" + (box.r + 0.5) + "," + (y0 - MINZOOM - 0.5) + "h3v" + (2 * MINZOOM + 1) + "h-3Z"; + } + function yCorners(box, x0) { + return "M" + (x0 - MINZOOM - 0.5) + "," + (box.t - 0.5) + "v-3h" + (2 * MINZOOM + 1) + "v3ZM" + (x0 - MINZOOM - 0.5) + "," + (box.b + 0.5) + "v3h" + (2 * MINZOOM + 1) + "v-3Z"; + } + function xyCorners(box) { + var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); + return "M" + (box.l - 3.5) + "," + (box.t - 0.5 + clen) + "h3v" + -clen + "h" + clen + "v-3h-" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.t - 0.5 + clen) + "h-3v" + -clen + "h" + -clen + "v-3h" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.b + 0.5 - clen) + "h-3v" + clen + "h" + -clen + "v3h" + (clen + 3) + "ZM" + (box.l - 3.5) + "," + (box.b + 0.5 - clen) + "h3v" + clen + "h" + clen + "v3h-" + (clen + 3) + "Z"; + } + function calcLinks(gd, groups, xaHash, yaHash, exclude) { + var isSubplotConstrained = false; + var xLinks = {}; + var yLinks = {}; + var xID, yID, xLinkID, yLinkID; + var xExclude = (exclude || {}).xaHash; + var yExclude = (exclude || {}).yaHash; + for (var i = 0; i < groups.length; i++) { + var group = groups[i]; + for (xID in xaHash) { + if (group[xID]) { + for (xLinkID in group) { + if (!(exclude && (xExclude[xLinkID] || yExclude[xLinkID])) && !(xLinkID.charAt(0) === "x" ? xaHash : yaHash)[xLinkID]) { + xLinks[xLinkID] = xID; + } + } + for (yID in yaHash) { + if (!(exclude && (xExclude[yID] || yExclude[yID])) && group[yID]) { + isSubplotConstrained = true; + } + } + } + } + for (yID in yaHash) { + if (group[yID]) { + for (yLinkID in group) { + if (!(exclude && (xExclude[yLinkID] || yExclude[yLinkID])) && !(yLinkID.charAt(0) === "x" ? xaHash : yaHash)[yLinkID]) { + yLinks[yLinkID] = yID; + } + } + } + } + } + if (isSubplotConstrained) { + Lib2.extendFlat(xLinks, yLinks); + yLinks = {}; + } + var xaHashLinked = {}; + var xaxesLinked = []; + for (xLinkID in xLinks) { + var xa = getFromId2(gd, xLinkID); + xaxesLinked.push(xa); + xaHashLinked[xa._id] = xa; + } + var yaHashLinked = {}; + var yaxesLinked = []; + for (yLinkID in yLinks) { + var ya = getFromId2(gd, yLinkID); + yaxesLinked.push(ya); + yaHashLinked[ya._id] = ya; + } + return { + xaHash: xaHashLinked, + yaHash: yaHashLinked, + xaxes: xaxesLinked, + yaxes: yaxesLinked, + xLinks, + yLinks, + isSubplotConstrained + }; + } + function attachWheelEventHandler(element, handler) { + if (!supportsPassive2) { + if (element.onwheel !== void 0) element.onwheel = handler; + else if (element.onmousewheel !== void 0) element.onmousewheel = handler; + else if (!element.isAddedWheelEvent) { + element.isAddedWheelEvent = true; + element.addEventListener("wheel", handler, { passive: false }); + } + } else { + var wheelEventName = element.onwheel !== void 0 ? "wheel" : "mousewheel"; + if (element._onwheel) { + element.removeEventListener(wheelEventName, element._onwheel); + } + element._onwheel = handler; + element.addEventListener(wheelEventName, handler, { passive: false }); + } + } + function hashValues(hash) { + var out = []; + for (var k in hash) out.push(hash[k]); + return out; + } + dragbox = { + makeDragBox, + makeDragger, + makeRectDragger, + makeZoombox, + makeCorners, + updateZoombox, + xyCorners, + transitionZoombox, + removeZoombox, + showDoubleClickNotifier, + attachWheelEventHandler + }; + return dragbox; +} +var hasRequiredGraph_interact; +function requireGraph_interact() { + if (hasRequiredGraph_interact) return graph_interact; + hasRequiredGraph_interact = 1; + (function(exports2) { + var d32 = d3Exports; + var Fx2 = fx$1; + var dragElement2 = dragelementExports; + var setCursor3 = setcursor; + var makeDragBox = requireDragbox().makeDragBox; + var DRAGGERSIZE = constants$U.DRAGGERSIZE; + exports2.initInteractions = function initInteractions(gd) { + var fullLayout = gd._fullLayout; + if (gd._context.staticPlot) { + d32.select(gd).selectAll(".drag").remove(); + return; + } + if (!fullLayout._has("cartesian") && !fullLayout._has("splom")) return; + var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) { + if ((fullLayout._plots[a].mainplot && true) === (fullLayout._plots[b].mainplot && true)) { + var aParts = a.split("y"); + var bParts = b.split("y"); + return aParts[0] === bParts[0] ? Number(aParts[1] || 1) - Number(bParts[1] || 1) : Number(aParts[0] || 1) - Number(bParts[0] || 1); + } + return fullLayout._plots[a].mainplot ? 1 : -1; + }); + subplots.forEach(function(subplot) { + var plotinfo = fullLayout._plots[subplot]; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + if (!plotinfo.mainplot) { + var maindrag = makeDragBox( + gd, + plotinfo, + xa._offset, + ya._offset, + xa._length, + ya._length, + "ns", + "ew" + ); + maindrag.onmousemove = function(evt) { + gd._fullLayout._rehover = function() { + if (gd._fullLayout._hoversubplot === subplot && gd._fullLayout._plots[subplot]) { + Fx2.hover(gd, evt, subplot); + } + }; + Fx2.hover(gd, evt, subplot); + gd._fullLayout._lasthover = maindrag; + gd._fullLayout._hoversubplot = subplot; + }; + maindrag.onmouseout = function(evt) { + if (gd._dragging) return; + gd._fullLayout._hoversubplot = null; + dragElement2.unhover(gd, evt); + }; + if (gd._context.showAxisDragHandles) { + makeDragBox( + gd, + plotinfo, + xa._offset - DRAGGERSIZE, + ya._offset - DRAGGERSIZE, + DRAGGERSIZE, + DRAGGERSIZE, + "n", + "w" + ); + makeDragBox( + gd, + plotinfo, + xa._offset + xa._length, + ya._offset - DRAGGERSIZE, + DRAGGERSIZE, + DRAGGERSIZE, + "n", + "e" + ); + makeDragBox( + gd, + plotinfo, + xa._offset - DRAGGERSIZE, + ya._offset + ya._length, + DRAGGERSIZE, + DRAGGERSIZE, + "s", + "w" + ); + makeDragBox( + gd, + plotinfo, + xa._offset + xa._length, + ya._offset + ya._length, + DRAGGERSIZE, + DRAGGERSIZE, + "s", + "e" + ); + } + } + if (gd._context.showAxisDragHandles) { + if (subplot === xa._mainSubplot) { + var y0 = xa._mainLinePosition; + if (xa.side === "top") y0 -= DRAGGERSIZE; + makeDragBox( + gd, + plotinfo, + xa._offset + xa._length * 0.1, + y0, + xa._length * 0.8, + DRAGGERSIZE, + "", + "ew" + ); + makeDragBox( + gd, + plotinfo, + xa._offset, + y0, + xa._length * 0.1, + DRAGGERSIZE, + "", + "w" + ); + makeDragBox( + gd, + plotinfo, + xa._offset + xa._length * 0.9, + y0, + xa._length * 0.1, + DRAGGERSIZE, + "", + "e" + ); + } + if (subplot === ya._mainSubplot) { + var x0 = ya._mainLinePosition; + if (ya.side !== "right") x0 -= DRAGGERSIZE; + makeDragBox( + gd, + plotinfo, + x0, + ya._offset + ya._length * 0.1, + DRAGGERSIZE, + ya._length * 0.8, + "ns", + "" + ); + makeDragBox( + gd, + plotinfo, + x0, + ya._offset + ya._length * 0.9, + DRAGGERSIZE, + ya._length * 0.1, + "s", + "" + ); + makeDragBox( + gd, + plotinfo, + x0, + ya._offset, + DRAGGERSIZE, + ya._length * 0.1, + "n", + "" + ); + } + } + }); + var hoverLayer = fullLayout._hoverlayer.node(); + hoverLayer.onmousemove = function(evt) { + evt.target = gd._fullLayout._lasthover; + Fx2.hover(gd, evt, fullLayout._hoversubplot); + }; + hoverLayer.onclick = function(evt) { + evt.target = gd._fullLayout._lasthover; + Fx2.click(gd, evt); + }; + hoverLayer.onmousedown = function(evt) { + gd._fullLayout._lasthover.onmousedown(evt); + }; + exports2.updateFx(gd); + }; + exports2.updateFx = function(gd) { + var fullLayout = gd._fullLayout; + var cursor2 = fullLayout.dragmode === "pan" ? "move" : "crosshair"; + setCursor3(fullLayout._draggers, cursor2); + }; + })(graph_interact); + return graph_interact; +} +var manage_arrays = {}; +var Registry$t = registry; +var container_array_match = function containerArrayMatch(astr) { + var rootContainers = Registry$t.layoutArrayContainers; + var regexpContainers = Registry$t.layoutArrayRegexes; + var rootPart = astr.split("[")[0]; + var arrayStr; + var match; + for (var i = 0; i < regexpContainers.length; i++) { + match = astr.match(regexpContainers[i]); + if (match && match.index === 0) { + arrayStr = match[0]; + break; + } + } + if (!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)]; + if (!arrayStr) return false; + var tail = astr.substr(arrayStr.length); + if (!tail) return { array: arrayStr, index: "", property: "" }; + match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/); + if (!match) return false; + return { array: arrayStr, index: Number(match[1]), property: match[3] || "" }; +}; +var isPlainObject$2 = is_plain_object; +var noop$1 = noop$2; +var Loggers = loggersExports; +var sorterAsc = search$1.sorterAsc; +var Registry$s = registry; +manage_arrays.containerArrayMatch = container_array_match; +var isAddVal = manage_arrays.isAddVal = function isAddVal2(val) { + return val === "add" || isPlainObject$2(val); +}; +var isRemoveVal = manage_arrays.isRemoveVal = function isRemoveVal2(val) { + return val === null || val === "remove"; +}; +manage_arrays.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) { + var componentType = np.astr; + var supplyComponentDefaults = Registry$s.getComponentMethod(componentType, "supplyLayoutDefaults"); + var draw8 = Registry$s.getComponentMethod(componentType, "draw"); + var drawOne2 = Registry$s.getComponentMethod(componentType, "drawOne"); + var replotLater = flags.replot || flags.recalc || supplyComponentDefaults === noop$1 || draw8 === noop$1; + var layout = gd.layout; + var fullLayout = gd._fullLayout; + if (edits[""]) { + if (Object.keys(edits).length > 1) { + Loggers.warn( + "Full array edits are incompatible with other edits", + componentType + ); + } + var fullVal = edits[""][""]; + if (isRemoveVal(fullVal)) np.set(null); + else if (Array.isArray(fullVal)) np.set(fullVal); + else { + Loggers.warn("Unrecognized full array edit value", componentType, fullVal); + return true; + } + if (replotLater) return false; + supplyComponentDefaults(layout, fullLayout); + draw8(gd); + return true; + } + var componentNums = Object.keys(edits).map(Number).sort(sorterAsc); + var componentArrayIn = np.get(); + var componentArray = componentArrayIn || []; + var componentArrayFull = _nestedProperty(fullLayout, componentType).get(); + var deletes = []; + var firstIndexChange = -1; + var maxIndex = componentArray.length; + var i; + var j; + var componentNum; + var objEdits; + var objKeys; + var objVal; + var adding, prefix; + for (i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + objEdits = edits[componentNum]; + objKeys = Object.keys(objEdits); + objVal = objEdits[""], adding = isAddVal(objVal); + if (componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { + Loggers.warn("index out of range", componentType, componentNum); + continue; + } + if (objVal !== void 0) { + if (objKeys.length > 1) { + Loggers.warn( + "Insertion & removal are incompatible with edits to the same index.", + componentType, + componentNum + ); + } + if (isRemoveVal(objVal)) { + deletes.push(componentNum); + } else if (adding) { + if (objVal === "add") objVal = {}; + componentArray.splice(componentNum, 0, objVal); + if (componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); + } else { + Loggers.warn( + "Unrecognized full object edit value", + componentType, + componentNum, + objVal + ); + } + if (firstIndexChange === -1) firstIndexChange = componentNum; + } else { + for (j = 0; j < objKeys.length; j++) { + prefix = componentType + "[" + componentNum + "]."; + _nestedProperty(componentArray[componentNum], objKeys[j], prefix).set(objEdits[objKeys[j]]); + } + } + } + for (i = deletes.length - 1; i >= 0; i--) { + componentArray.splice(deletes[i], 1); + if (componentArrayFull) componentArrayFull.splice(deletes[i], 1); + } + if (!componentArray.length) np.set(null); + else if (!componentArrayIn) np.set(componentArray); + if (replotLater) return false; + supplyComponentDefaults(layout, fullLayout); + if (drawOne2 !== noop$1) { + var indicesToDraw; + if (firstIndexChange === -1) { + indicesToDraw = componentNums; + } else { + maxIndex = Math.max(componentArray.length, maxIndex); + indicesToDraw = []; + for (i = 0; i < componentNums.length; i++) { + componentNum = componentNums[i]; + if (componentNum >= firstIndexChange) break; + indicesToDraw.push(componentNum); + } + for (i = firstIndexChange; i < maxIndex; i++) { + indicesToDraw.push(i); + } + } + for (i = 0; i < indicesToDraw.length; i++) { + drawOne2(gd, indicesToDraw[i]); + } + } else draw8(gd); + return true; +}; +var helpers$p = {}; +(function(exports2) { + var isNumeric2 = fastIsnumeric; + var m4FromQuat = fromQuat_1; + var Registry2 = registry; + var Lib2 = libExports; + var Plots2 = plotsExports; + var AxisIds = axis_ids; + var Color2 = colorExports; + var cleanId = AxisIds.cleanId; + var getFromTrace = AxisIds.getFromTrace; + var traceIs2 = Registry2.traceIs; + exports2.clearPromiseQueue = function(gd) { + if (Array.isArray(gd._promises) && gd._promises.length > 0) { + Lib2.log("Clearing previous rejected promises from queue."); + } + gd._promises = []; + }; + exports2.cleanLayout = function(layout) { + var i, j; + if (!layout) layout = {}; + if (layout.xaxis1) { + if (!layout.xaxis) layout.xaxis = layout.xaxis1; + delete layout.xaxis1; + } + if (layout.yaxis1) { + if (!layout.yaxis) layout.yaxis = layout.yaxis1; + delete layout.yaxis1; + } + if (layout.scene1) { + if (!layout.scene) layout.scene = layout.scene1; + delete layout.scene1; + } + var axisAttrRegex = (Plots2.subplotsRegistry.cartesian || {}).attrRegex; + var polarAttrRegex = (Plots2.subplotsRegistry.polar || {}).attrRegex; + var ternaryAttrRegex = (Plots2.subplotsRegistry.ternary || {}).attrRegex; + var sceneAttrRegex = (Plots2.subplotsRegistry.gl3d || {}).attrRegex; + var keys = Object.keys(layout); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + if (axisAttrRegex && axisAttrRegex.test(key)) { + var ax = layout[key]; + if (ax.anchor && ax.anchor !== "free") { + ax.anchor = cleanId(ax.anchor); + } + if (ax.overlaying) ax.overlaying = cleanId(ax.overlaying); + if (!ax.type) { + if (ax.isdate) ax.type = "date"; + else if (ax.islog) ax.type = "log"; + else if (ax.isdate === false && ax.islog === false) ax.type = "linear"; + } + if (ax.autorange === "withzero" || ax.autorange === "tozero") { + ax.autorange = true; + ax.rangemode = "tozero"; + } + if (ax.insiderange) delete ax.range; + delete ax.islog; + delete ax.isdate; + delete ax.categories; + if (emptyContainer(ax, "domain")) delete ax.domain; + if (ax.autotick !== void 0) { + if (ax.tickmode === void 0) { + ax.tickmode = ax.autotick ? "auto" : "linear"; + } + delete ax.autotick; + } + cleanTitle(ax); + } else if (polarAttrRegex && polarAttrRegex.test(key)) { + var polar = layout[key]; + cleanTitle(polar.radialaxis); + } else if (ternaryAttrRegex && ternaryAttrRegex.test(key)) { + var ternary = layout[key]; + cleanTitle(ternary.aaxis); + cleanTitle(ternary.baxis); + cleanTitle(ternary.caxis); + } else if (sceneAttrRegex && sceneAttrRegex.test(key)) { + var scene = layout[key]; + var cameraposition = scene.cameraposition; + if (Array.isArray(cameraposition) && cameraposition[0].length === 4) { + var rotation = cameraposition[0]; + var center = cameraposition[1]; + var radius = cameraposition[2]; + var mat = m4FromQuat([], rotation); + var eye = []; + for (j = 0; j < 3; ++j) { + eye[j] = center[j] + radius * mat[2 + 4 * j]; + } + scene.camera = { + eye: { x: eye[0], y: eye[1], z: eye[2] }, + center: { x: center[0], y: center[1], z: center[2] }, + up: { x: 0, y: 0, z: 1 } + // we just ignore calculating camera z up in this case + }; + delete scene.cameraposition; + } + cleanTitle(scene.xaxis); + cleanTitle(scene.yaxis); + cleanTitle(scene.zaxis); + } + } + var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; + for (i = 0; i < annotationsLen; i++) { + var ann = layout.annotations[i]; + if (!Lib2.isPlainObject(ann)) continue; + if (ann.ref) { + if (ann.ref === "paper") { + ann.xref = "paper"; + ann.yref = "paper"; + } else if (ann.ref === "data") { + ann.xref = "x"; + ann.yref = "y"; + } + delete ann.ref; + } + cleanAxRef(ann, "xref"); + cleanAxRef(ann, "yref"); + } + var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; + for (i = 0; i < shapesLen; i++) { + var shape = layout.shapes[i]; + if (!Lib2.isPlainObject(shape)) continue; + cleanAxRef(shape, "xref"); + cleanAxRef(shape, "yref"); + } + var imagesLen = Array.isArray(layout.images) ? layout.images.length : 0; + for (i = 0; i < imagesLen; i++) { + var image = layout.images[i]; + if (!Lib2.isPlainObject(image)) continue; + cleanAxRef(image, "xref"); + cleanAxRef(image, "yref"); + } + var legend2 = layout.legend; + if (legend2) { + if (legend2.x > 3) { + legend2.x = 1.02; + legend2.xanchor = "left"; + } else if (legend2.x < -2) { + legend2.x = -0.02; + legend2.xanchor = "right"; + } + if (legend2.y > 3) { + legend2.y = 1.02; + legend2.yanchor = "bottom"; + } else if (legend2.y < -2) { + legend2.y = -0.02; + legend2.yanchor = "top"; + } + } + cleanTitle(layout); + if (layout.dragmode === "rotate") layout.dragmode = "orbit"; + Color2.clean(layout); + if (layout.template && layout.template.layout) { + exports2.cleanLayout(layout.template.layout); + } + return layout; + }; + function cleanAxRef(container, attr) { + var valIn = container[attr]; + var axLetter = attr.charAt(0); + if (valIn && valIn !== "paper") { + container[attr] = cleanId(valIn, axLetter, true); + } + } + function cleanTitle(titleContainer) { + if (titleContainer) { + if (typeof titleContainer.title === "string" || typeof titleContainer.title === "number") { + titleContainer.title = { + text: titleContainer.title + }; + } + rewireAttr("titlefont", "font"); + rewireAttr("titleposition", "position"); + rewireAttr("titleside", "side"); + rewireAttr("titleoffset", "offset"); + } + function rewireAttr(oldAttrName, newAttrName) { + var oldAttrSet = titleContainer[oldAttrName]; + var newAttrSet = titleContainer.title && titleContainer.title[newAttrName]; + if (oldAttrSet && !newAttrSet) { + if (!titleContainer.title) { + titleContainer.title = {}; + } + titleContainer.title[newAttrName] = titleContainer[oldAttrName]; + delete titleContainer[oldAttrName]; + } + } + } + exports2.cleanData = function(data) { + for (var tracei = 0; tracei < data.length; tracei++) { + var trace = data[tracei]; + var i; + if (trace.type === "histogramy" && "xbins" in trace && !("ybins" in trace)) { + trace.ybins = trace.xbins; + delete trace.xbins; + } + if (trace.error_y && "opacity" in trace.error_y) { + var dc = Color2.defaults; + var yeColor = trace.error_y.color || (traceIs2(trace, "bar") ? Color2.defaultLine : dc[tracei % dc.length]); + trace.error_y.color = Color2.addOpacity( + Color2.rgb(yeColor), + Color2.opacity(yeColor) * trace.error_y.opacity + ); + delete trace.error_y.opacity; + } + if ("bardir" in trace) { + if (trace.bardir === "h" && (traceIs2(trace, "bar") || trace.type.substr(0, 9) === "histogram")) { + trace.orientation = "h"; + exports2.swapXYData(trace); + } + delete trace.bardir; + } + if (trace.type === "histogramy") exports2.swapXYData(trace); + if (trace.type === "histogramx" || trace.type === "histogramy") { + trace.type = "histogram"; + } + if ("scl" in trace && !("colorscale" in trace)) { + trace.colorscale = trace.scl; + delete trace.scl; + } + if ("reversescl" in trace && !("reversescale" in trace)) { + trace.reversescale = trace.reversescl; + delete trace.reversescl; + } + if (trace.xaxis) trace.xaxis = cleanId(trace.xaxis, "x"); + if (trace.yaxis) trace.yaxis = cleanId(trace.yaxis, "y"); + if (traceIs2(trace, "gl3d") && trace.scene) { + trace.scene = Plots2.subplotsRegistry.gl3d.cleanId(trace.scene); + } + if (!traceIs2(trace, "pie-like") && !traceIs2(trace, "bar-like")) { + if (Array.isArray(trace.textposition)) { + for (i = 0; i < trace.textposition.length; i++) { + trace.textposition[i] = cleanTextPosition(trace.textposition[i]); + } + } else if (trace.textposition) { + trace.textposition = cleanTextPosition(trace.textposition); + } + } + var _module = Registry2.getModule(trace); + if (_module && _module.colorbar) { + var containerName = _module.colorbar.container; + var container = containerName ? trace[containerName] : trace; + if (container && container.colorscale) { + if (container.colorscale === "YIGnBu") container.colorscale = "YlGnBu"; + if (container.colorscale === "YIOrRd") container.colorscale = "YlOrRd"; + } + } + if (trace.type === "surface" && Lib2.isPlainObject(trace.contours)) { + var dims = ["x", "y", "z"]; + for (i = 0; i < dims.length; i++) { + var opts = trace.contours[dims[i]]; + if (!Lib2.isPlainObject(opts)) continue; + if (opts.highlightColor) { + opts.highlightcolor = opts.highlightColor; + delete opts.highlightColor; + } + if (opts.highlightWidth) { + opts.highlightwidth = opts.highlightWidth; + delete opts.highlightWidth; + } + } + } + if (trace.type === "candlestick" || trace.type === "ohlc") { + var increasingShowlegend = (trace.increasing || {}).showlegend !== false; + var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; + var increasingName = cleanFinanceDir(trace.increasing); + var decreasingName = cleanFinanceDir(trace.decreasing); + if (increasingName !== false && decreasingName !== false) { + var newName = commonPrefix( + increasingName, + decreasingName, + increasingShowlegend, + decreasingShowlegend + ); + if (newName) trace.name = newName; + } else if ((increasingName || decreasingName) && !trace.name) { + trace.name = increasingName || decreasingName; + } + } + if (Array.isArray(trace.transforms)) { + var transforms = trace.transforms; + for (i = 0; i < transforms.length; i++) { + var transform = transforms[i]; + if (!Lib2.isPlainObject(transform)) continue; + switch (transform.type) { + case "filter": + if (transform.filtersrc) { + transform.target = transform.filtersrc; + delete transform.filtersrc; + } + if (transform.calendar) { + if (!transform.valuecalendar) { + transform.valuecalendar = transform.calendar; + } + delete transform.calendar; + } + break; + case "groupby": + transform.styles = transform.styles || transform.style; + if (transform.styles && !Array.isArray(transform.styles)) { + var prevStyles = transform.styles; + var styleKeys = Object.keys(prevStyles); + transform.styles = []; + for (var j = 0; j < styleKeys.length; j++) { + transform.styles.push({ + target: styleKeys[j], + value: prevStyles[styleKeys[j]] + }); + } + } + break; + } + } + } + if (emptyContainer(trace, "line")) delete trace.line; + if ("marker" in trace) { + if (emptyContainer(trace.marker, "line")) delete trace.marker.line; + if (emptyContainer(trace, "marker")) delete trace.marker; + } + Color2.clean(trace); + if (trace.autobinx) { + delete trace.autobinx; + delete trace.xbins; + } + if (trace.autobiny) { + delete trace.autobiny; + delete trace.ybins; + } + cleanTitle(trace); + if (trace.colorbar) cleanTitle(trace.colorbar); + if (trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar); + if (trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar); + if (trace.aaxis) cleanTitle(trace.aaxis); + if (trace.baxis) cleanTitle(trace.baxis); + } + }; + function cleanFinanceDir(dirContainer) { + if (!Lib2.isPlainObject(dirContainer)) return false; + var dirName = dirContainer.name; + delete dirContainer.name; + delete dirContainer.showlegend; + return (typeof dirName === "string" || typeof dirName === "number") && String(dirName); + } + function commonPrefix(name1, name2, show1, show2) { + if (show1 && !show2) return name1; + if (show2 && !show1) return name2; + if (!name1.trim()) return name2; + if (!name2.trim()) return name1; + var minLen = Math.min(name1.length, name2.length); + var i; + for (i = 0; i < minLen; i++) { + if (name1.charAt(i) !== name2.charAt(i)) break; + } + var out = name1.substr(0, i); + return out.trim(); + } + function cleanTextPosition(textposition) { + var posY = "middle"; + var posX = "center"; + if (typeof textposition === "string") { + if (textposition.indexOf("top") !== -1) posY = "top"; + else if (textposition.indexOf("bottom") !== -1) posY = "bottom"; + if (textposition.indexOf("left") !== -1) posX = "left"; + else if (textposition.indexOf("right") !== -1) posX = "right"; + } + return posY + " " + posX; + } + function emptyContainer(outer, innerStr) { + return innerStr in outer && typeof outer[innerStr] === "object" && Object.keys(outer[innerStr]).length === 0; + } + exports2.swapXYData = function(trace) { + var i; + Lib2.swapAttrs(trace, ["?", "?0", "d?", "?bins", "nbins?", "autobin?", "?src", "error_?"]); + if (Array.isArray(trace.z) && Array.isArray(trace.z[0])) { + if (trace.transpose) delete trace.transpose; + else trace.transpose = true; + } + if (trace.error_x && trace.error_y) { + var errorY = trace.error_y; + var copyYstyle = "copy_ystyle" in errorY ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width); + Lib2.swapAttrs(trace, ["error_?.copy_ystyle"]); + if (copyYstyle) { + Lib2.swapAttrs(trace, ["error_?.color", "error_?.thickness", "error_?.width"]); + } + } + if (typeof trace.hoverinfo === "string") { + var hoverInfoParts = trace.hoverinfo.split("+"); + for (i = 0; i < hoverInfoParts.length; i++) { + if (hoverInfoParts[i] === "x") hoverInfoParts[i] = "y"; + else if (hoverInfoParts[i] === "y") hoverInfoParts[i] = "x"; + } + trace.hoverinfo = hoverInfoParts.join("+"); + } + }; + exports2.coerceTraceIndices = function(gd, traceIndices) { + if (isNumeric2(traceIndices)) { + return [traceIndices]; + } else if (!Array.isArray(traceIndices) || !traceIndices.length) { + return gd.data.map(function(_2, i2) { + return i2; + }); + } else if (Array.isArray(traceIndices)) { + var traceIndicesOut = []; + for (var i = 0; i < traceIndices.length; i++) { + if (Lib2.isIndex(traceIndices[i], gd.data.length)) { + traceIndicesOut.push(traceIndices[i]); + } else { + Lib2.warn("trace index (", traceIndices[i], ") is not a number or is out of bounds"); + } + } + return traceIndicesOut; + } + return traceIndices; + }; + exports2.manageArrayContainers = function(np, newVal, undoit) { + var obj = np.obj; + var parts = np.parts; + var pLength = parts.length; + var pLast = parts[pLength - 1]; + var pLastIsNumber = isNumeric2(pLast); + if (pLastIsNumber && newVal === null) { + var contPath = parts.slice(0, pLength - 1).join("."); + var cont = Lib2.nestedProperty(obj, contPath).get(); + cont.splice(pLast, 1); + } else if (pLastIsNumber && np.get() === void 0) { + if (np.get() === void 0) undoit[np.astr] = null; + np.set(newVal); + } else { + np.set(newVal); + } + }; + var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; + function getParent(attr) { + var tail = attr.search(ATTR_TAIL_RE); + if (tail > 0) return attr.substr(0, tail); + } + exports2.hasParent = function(aobj, attr) { + var attrParent = getParent(attr); + while (attrParent) { + if (attrParent in aobj) return true; + attrParent = getParent(attrParent); + } + return false; + }; + var axLetters2 = ["x", "y", "z"]; + exports2.clearAxisTypes = function(gd, traces, layoutUpdate) { + for (var i = 0; i < traces.length; i++) { + var trace = gd._fullData[i]; + for (var j = 0; j < 3; j++) { + var ax = getFromTrace(gd, trace, axLetters2[j]); + if (ax && ax.type !== "log") { + var axAttr = ax._name; + var sceneName = ax._id.substr(1); + if (sceneName.substr(0, 5) === "scene") { + if (layoutUpdate[sceneName] !== void 0) continue; + axAttr = sceneName + "." + axAttr; + } + var typeAttr = axAttr + ".type"; + if (layoutUpdate[axAttr] === void 0 && layoutUpdate[typeAttr] === void 0) { + Lib2.nestedProperty(gd.layout, typeAttr).set(null); + } + } + } + } + }; +})(helpers$p); +(function(exports2) { + var d32 = d3Exports; + var isNumeric2 = fastIsnumeric; + var hasHover2 = hasHover_1; + var Lib2 = libExports; + var nestedProperty3 = Lib2.nestedProperty; + var Events2 = events; + var Queue = queue_1; + var Registry2 = registry; + var PlotSchema2 = plot_schema; + var Plots2 = plotsExports; + var Axes2 = axesExports; + var handleRangeDefaults3 = range_defaults; + var cartesianLayoutAttributes = layout_attributes$4; + var Drawing2 = drawingExports; + var Color2 = colorExports; + var initInteractions = requireGraph_interact().initInteractions; + var xmlnsNamespaces2 = xmlns_namespaces; + var clearOutline2 = selections.clearOutline; + var dfltConfig2 = plot_config.dfltConfig; + var manageArrays = manage_arrays; + var helpers2 = helpers$p; + var subroutines$1 = subroutines; + var editTypes = edit_types; + var AX_NAME_PATTERN = constants$U.AX_NAME_PATTERN; + var numericNameWarningCount = 0; + var numericNameWarningCountLimit = 5; + function _doPlot(gd, data, layout, config) { + var frames; + gd = Lib2.getGraphDiv(gd); + Events2.init(gd); + if (Lib2.isPlainObject(data)) { + var obj = data; + data = obj.data; + layout = obj.layout; + config = obj.config; + frames = obj.frames; + } + var okToPlot = Events2.triggerHandler(gd, "plotly_beforeplot", [data, layout, config]); + if (okToPlot === false) return Promise.reject(); + if (!data && !layout && !Lib2.isPlotDiv(gd)) { + Lib2.warn("Calling _doPlot as if redrawing but this container doesn't yet have a plot.", gd); + } + function addFrames2() { + if (frames) { + return exports2.addFrames(gd, frames); + } + } + setPlotContext(gd, config); + if (!layout) layout = {}; + d32.select(gd).classed("js-plotly-plot", true); + Drawing2.makeTester(); + if (!Array.isArray(gd._promises)) gd._promises = []; + var graphWasEmpty = (gd.data || []).length === 0 && Array.isArray(data); + if (Array.isArray(data)) { + helpers2.cleanData(data); + if (graphWasEmpty) gd.data = data; + else gd.data.push.apply(gd.data, data); + gd.empty = false; + } + if (!gd.layout || graphWasEmpty) { + gd.layout = helpers2.cleanLayout(layout); + } + Plots2.supplyDefaults(gd); + var fullLayout = gd._fullLayout; + var hasCartesian = fullLayout._has("cartesian"); + fullLayout._replotting = true; + if (graphWasEmpty || fullLayout._shouldCreateBgLayer) { + makePlotFramework(gd); + if (fullLayout._shouldCreateBgLayer) { + delete fullLayout._shouldCreateBgLayer; + } + } + Drawing2.initGradients(gd); + Drawing2.initPatterns(gd); + if (graphWasEmpty) Axes2.saveShowSpikeInitial(gd); + var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; + if (recalc) Plots2.doCalcdata(gd); + for (var i = 0; i < gd.calcdata.length; i++) { + gd.calcdata[i][0].trace = gd._fullData[i]; + } + if (gd._context.responsive) { + if (!gd._responsiveChartHandler) { + gd._responsiveChartHandler = function() { + if (!Lib2.isHidden(gd)) Plots2.resize(gd); + }; + window.addEventListener("resize", gd._responsiveChartHandler); + } + } else { + Lib2.clearResponsive(gd); + } + var oldMargins = Lib2.extendFlat({}, fullLayout._size); + var drawFrameworkCalls = 0; + function drawFramework() { + var basePlotModules = fullLayout._basePlotModules; + for (var i2 = 0; i2 < basePlotModules.length; i2++) { + if (basePlotModules[i2].drawFramework) { + basePlotModules[i2].drawFramework(gd); + } + } + if (!fullLayout._glcanvas && fullLayout._has("gl")) { + fullLayout._glcanvas = fullLayout._glcontainer.selectAll(".gl-canvas").data([{ + key: "contextLayer", + context: true, + pick: false + }, { + key: "focusLayer", + context: false, + pick: false + }, { + key: "pickLayer", + context: false, + pick: true + }], function(d) { + return d.key; + }); + fullLayout._glcanvas.enter().append("canvas").attr("class", function(d) { + return "gl-canvas gl-canvas-" + d.key.replace("Layer", ""); + }).style({ + position: "absolute", + top: 0, + left: 0, + overflow: "visible", + "pointer-events": "none" + }); + } + var plotGlPixelRatio = gd._context.plotGlPixelRatio; + if (fullLayout._glcanvas) { + fullLayout._glcanvas.attr("width", fullLayout.width * plotGlPixelRatio).attr("height", fullLayout.height * plotGlPixelRatio).style("width", fullLayout.width + "px").style("height", fullLayout.height + "px"); + var regl = fullLayout._glcanvas.data()[0].regl; + if (regl) { + if (Math.floor(fullLayout.width * plotGlPixelRatio) !== regl._gl.drawingBufferWidth || Math.floor(fullLayout.height * plotGlPixelRatio) !== regl._gl.drawingBufferHeight) { + var msg2 = "WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug."; + if (drawFrameworkCalls) { + Lib2.error(msg2); + } else { + Lib2.log(msg2 + " Clearing graph and plotting again."); + Plots2.cleanPlot([], {}, gd._fullData, fullLayout); + Plots2.supplyDefaults(gd); + fullLayout = gd._fullLayout; + Plots2.doCalcdata(gd); + drawFrameworkCalls++; + return drawFramework(); + } + } + } + } + if (fullLayout.modebar.orientation === "h") { + fullLayout._modebardiv.style("height", null).style("width", "100%"); + } else { + fullLayout._modebardiv.style("width", null).style("height", fullLayout.height + "px"); + } + return Plots2.previousPromises(gd); + } + function marginPushers() { + Plots2.clearAutoMarginIds(gd); + subroutines$1.drawMarginPushers(gd); + Axes2.allowAutoMargin(gd); + if (gd._fullLayout.title.text && gd._fullLayout.title.automargin) Plots2.allowAutoMargin(gd, "title.automargin"); + if (fullLayout._has("pie")) { + var fullData = gd._fullData; + for (var i2 = 0; i2 < fullData.length; i2++) { + var trace = fullData[i2]; + if (trace.type === "pie" && trace.automargin) { + Plots2.allowAutoMargin(gd, "pie." + trace.uid + ".automargin"); + } + } + } + Plots2.doAutoMargin(gd); + return Plots2.previousPromises(gd); + } + function marginPushersAgain() { + if (!Plots2.didMarginChange(oldMargins, fullLayout._size)) return; + return Lib2.syncOrAsync([ + marginPushers, + subroutines$1.layoutStyles + ], gd); + } + function positionAndAutorange() { + if (!recalc) { + doAutoRangeAndConstraints(); + return; + } + return Lib2.syncOrAsync([ + Registry2.getComponentMethod("shapes", "calcAutorange"), + Registry2.getComponentMethod("annotations", "calcAutorange"), + doAutoRangeAndConstraints + ], gd); + } + function doAutoRangeAndConstraints() { + if (gd._transitioning) return; + subroutines$1.doAutoRangeAndConstraints(gd); + if (graphWasEmpty) Axes2.saveRangeInitial(gd); + Registry2.getComponentMethod("rangeslider", "calcAutorange")(gd); + } + function drawAxes() { + return Axes2.draw(gd, graphWasEmpty ? "" : "redraw"); + } + var seq = [ + Plots2.previousPromises, + addFrames2, + drawFramework, + marginPushers, + marginPushersAgain + ]; + if (hasCartesian) seq.push(positionAndAutorange); + seq.push(subroutines$1.layoutStyles); + if (hasCartesian) { + seq.push( + drawAxes, + function insideTickLabelsAutorange(gd2) { + var insideTickLabelsUpdaterange = gd2._fullLayout._insideTickLabelsUpdaterange; + if (insideTickLabelsUpdaterange) { + gd2._fullLayout._insideTickLabelsUpdaterange = void 0; + return relayout(gd2, insideTickLabelsUpdaterange).then(function() { + Axes2.saveRangeInitial(gd2, true); + }); + } + } + ); + } + seq.push( + subroutines$1.drawData, + subroutines$1.finalDraw, + initInteractions, + Plots2.addLinks, + Plots2.rehover, + Plots2.redrag, + Plots2.reselect, + // TODO: doAutoMargin is only needed here for axis automargin, which + // happens outside of marginPushers where all the other automargins are + // calculated. Would be much better to separate margin calculations from + // component drawing - see https://github.com/plotly/plotly.js/issues/2704 + Plots2.doAutoMargin, + Plots2.previousPromises + ); + var plotDone = Lib2.syncOrAsync(seq, gd); + if (!plotDone || !plotDone.then) plotDone = Promise.resolve(); + return plotDone.then(function() { + emitAfterPlot(gd); + return gd; + }); + } + function emitAfterPlot(gd) { + var fullLayout = gd._fullLayout; + if (fullLayout._redrawFromAutoMarginCount) { + fullLayout._redrawFromAutoMarginCount--; + } else { + gd.emit("plotly_afterplot"); + } + } + function setPlotConfig(obj) { + return Lib2.extendFlat(dfltConfig2, obj); + } + function setBackground(gd, bgColor) { + try { + gd._fullLayout._paper.style("background", bgColor); + } catch (e) { + Lib2.error(e); + } + } + function opaqueSetBackground(gd, bgColor) { + var blend = Color2.combine(bgColor, "white"); + setBackground(gd, blend); + } + function setPlotContext(gd, config) { + if (!gd._context) { + gd._context = Lib2.extendDeep({}, dfltConfig2); + var base = d32.select("base"); + gd._context._baseUrl = base.size() && base.attr("href") ? window.location.href.split("#")[0] : ""; + } + var context2 = gd._context; + var i, keys, key; + if (config) { + keys = Object.keys(config); + for (i = 0; i < keys.length; i++) { + key = keys[i]; + if (key === "editable" || key === "edits") continue; + if (key in context2) { + if (key === "setBackground" && config[key] === "opaque") { + context2[key] = opaqueSetBackground; + } else { + context2[key] = config[key]; + } + } + } + if (config.plot3dPixelRatio && !context2.plotGlPixelRatio) { + context2.plotGlPixelRatio = context2.plot3dPixelRatio; + } + var editable = config.editable; + if (editable !== void 0) { + context2.editable = editable; + keys = Object.keys(context2.edits); + for (i = 0; i < keys.length; i++) { + context2.edits[keys[i]] = editable; + } + } + if (config.edits) { + keys = Object.keys(config.edits); + for (i = 0; i < keys.length; i++) { + key = keys[i]; + if (key in context2.edits) { + context2.edits[key] = config.edits[key]; + } + } + } + context2._exportedPlot = config._exportedPlot; + } + if (context2.staticPlot) { + context2.editable = false; + context2.edits = {}; + context2.autosizable = false; + context2.scrollZoom = false; + context2.doubleClick = false; + context2.showTips = false; + context2.showLink = false; + context2.displayModeBar = false; + } + if (context2.displayModeBar === "hover" && !hasHover2) { + context2.displayModeBar = true; + } + if (context2.setBackground === "transparent" || typeof context2.setBackground !== "function") { + context2.setBackground = setBackground; + } + context2._hasZeroHeight = context2._hasZeroHeight || gd.clientHeight === 0; + context2._hasZeroWidth = context2._hasZeroWidth || gd.clientWidth === 0; + var szIn = context2.scrollZoom; + var szOut = context2._scrollZoom = {}; + if (szIn === true) { + szOut.cartesian = 1; + szOut.gl3d = 1; + szOut.geo = 1; + szOut.mapbox = 1; + szOut.map = 1; + } else if (typeof szIn === "string") { + var parts = szIn.split("+"); + for (i = 0; i < parts.length; i++) { + szOut[parts[i]] = 1; + } + } else if (szIn !== false) { + szOut.gl3d = 1; + szOut.geo = 1; + szOut.mapbox = 1; + szOut.map = 1; + } + } + function redraw(gd) { + gd = Lib2.getGraphDiv(gd); + if (!Lib2.isPlotDiv(gd)) { + throw new Error("This element is not a Plotly plot: " + gd); + } + helpers2.cleanData(gd.data); + helpers2.cleanLayout(gd.layout); + gd.calcdata = void 0; + return exports2._doPlot(gd).then(function() { + gd.emit("plotly_redraw"); + return gd; + }); + } + function newPlot(gd, data, layout, config) { + gd = Lib2.getGraphDiv(gd); + Plots2.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}); + Plots2.purge(gd); + return exports2._doPlot(gd, data, layout, config); + } + function positivifyIndices(indices, maxIndex) { + var parentLength = maxIndex + 1; + var positiveIndices = []; + var i; + var index2; + for (i = 0; i < indices.length; i++) { + index2 = indices[i]; + if (index2 < 0) { + positiveIndices.push(parentLength + index2); + } else { + positiveIndices.push(index2); + } + } + return positiveIndices; + } + function assertIndexArray(gd, indices, arrayName) { + var i, index2; + for (i = 0; i < indices.length; i++) { + index2 = indices[i]; + if (index2 !== parseInt(index2, 10)) { + throw new Error("all values in " + arrayName + " must be integers"); + } + if (index2 >= gd.data.length || index2 < -gd.data.length) { + throw new Error(arrayName + " must be valid indices for gd.data."); + } + if (indices.indexOf(index2, i + 1) > -1 || index2 >= 0 && indices.indexOf(-gd.data.length + index2) > -1 || index2 < 0 && indices.indexOf(gd.data.length + index2) > -1) { + throw new Error("each index in " + arrayName + " must be unique."); + } + } + } + function checkMoveTracesArgs(gd, currentIndices, newIndices) { + if (!Array.isArray(gd.data)) { + throw new Error("gd.data must be an array."); + } + if (typeof currentIndices === "undefined") { + throw new Error("currentIndices is a required argument."); + } else if (!Array.isArray(currentIndices)) { + currentIndices = [currentIndices]; + } + assertIndexArray(gd, currentIndices, "currentIndices"); + if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) { + newIndices = [newIndices]; + } + if (typeof newIndices !== "undefined") { + assertIndexArray(gd, newIndices, "newIndices"); + } + if (typeof newIndices !== "undefined" && currentIndices.length !== newIndices.length) { + throw new Error("current and new indices must be of equal length."); + } + } + function checkAddTracesArgs(gd, traces, newIndices) { + var i, value2; + if (!Array.isArray(gd.data)) { + throw new Error("gd.data must be an array."); + } + if (typeof traces === "undefined") { + throw new Error("traces must be defined."); + } + if (!Array.isArray(traces)) { + traces = [traces]; + } + for (i = 0; i < traces.length; i++) { + value2 = traces[i]; + if (typeof value2 !== "object" || (Array.isArray(value2) || value2 === null)) { + throw new Error("all values in traces array must be non-array objects"); + } + } + if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) { + newIndices = [newIndices]; + } + if (typeof newIndices !== "undefined" && newIndices.length !== traces.length) { + throw new Error( + "if indices is specified, traces.length must equal indices.length" + ); + } + } + function assertExtendTracesArgs(gd, update3, indices, maxPoints) { + var maxPointsIsObject = Lib2.isPlainObject(maxPoints); + if (!Array.isArray(gd.data)) { + throw new Error("gd.data must be an array"); + } + if (!Lib2.isPlainObject(update3)) { + throw new Error("update must be a key:value object"); + } + if (typeof indices === "undefined") { + throw new Error("indices must be an integer or array of integers"); + } + assertIndexArray(gd, indices, "indices"); + for (var key in update3) { + if (!Array.isArray(update3[key]) || update3[key].length !== indices.length) { + throw new Error("attribute " + key + " must be an array of length equal to indices array length"); + } + if (maxPointsIsObject && (!(key in maxPoints) || !Array.isArray(maxPoints[key]) || maxPoints[key].length !== update3[key].length)) { + throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object"); + } + } + } + function getExtendProperties(gd, update3, indices, maxPoints) { + var maxPointsIsObject = Lib2.isPlainObject(maxPoints); + var updateProps = []; + var trace, target, prop, insert, maxp; + if (!Array.isArray(indices)) indices = [indices]; + indices = positivifyIndices(indices, gd.data.length - 1); + for (var key in update3) { + for (var j = 0; j < indices.length; j++) { + trace = gd.data[indices[j]]; + prop = nestedProperty3(trace, key); + target = prop.get(); + insert = update3[key][j]; + if (!Lib2.isArrayOrTypedArray(insert)) { + throw new Error("attribute: " + key + " index: " + j + " must be an array"); + } + if (!Lib2.isArrayOrTypedArray(target)) { + throw new Error("cannot extend missing or non-array attribute: " + key); + } + if (target.constructor !== insert.constructor) { + throw new Error("cannot extend array with an array of a different type: " + key); + } + maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; + if (!isNumeric2(maxp)) maxp = -1; + updateProps.push({ + prop, + target, + insert, + maxp: Math.floor(maxp) + }); + } + } + return updateProps; + } + function spliceTraces(gd, update3, indices, maxPoints, updateArray) { + assertExtendTracesArgs(gd, update3, indices, maxPoints); + var updateProps = getExtendProperties(gd, update3, indices, maxPoints); + var undoUpdate = {}; + var undoPoints = {}; + for (var i = 0; i < updateProps.length; i++) { + var prop = updateProps[i].prop; + var maxp = updateProps[i].maxp; + var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp); + prop.set(out[0]); + if (!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = []; + undoUpdate[prop.astr].push(out[1]); + if (!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = []; + undoPoints[prop.astr].push(updateProps[i].target.length); + } + return { update: undoUpdate, maxPoints: undoPoints }; + } + function concatTypedArray(arr0, arr1) { + var arr2 = new arr0.constructor(arr0.length + arr1.length); + arr2.set(arr0); + arr2.set(arr1, arr0.length); + return arr2; + } + function extendTraces(gd, update3, indices, maxPoints) { + gd = Lib2.getGraphDiv(gd); + function updateArray(target, insert, maxp) { + var newArray, remainder; + if (Lib2.isTypedArray(target)) { + if (maxp < 0) { + var none = new target.constructor(0); + var both = concatTypedArray(target, insert); + if (maxp < 0) { + newArray = both; + remainder = none; + } else { + newArray = none; + remainder = both; + } + } else { + newArray = new target.constructor(maxp); + remainder = new target.constructor(target.length + insert.length - maxp); + if (maxp === insert.length) { + newArray.set(insert); + remainder.set(target); + } else if (maxp < insert.length) { + var numberOfItemsFromInsert = insert.length - maxp; + newArray.set(insert.subarray(numberOfItemsFromInsert)); + remainder.set(target); + remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length); + } else { + var numberOfItemsFromTarget = maxp - insert.length; + var targetBegin = target.length - numberOfItemsFromTarget; + newArray.set(target.subarray(targetBegin)); + newArray.set(insert, numberOfItemsFromTarget); + remainder.set(target.subarray(0, targetBegin)); + } + } + } else { + newArray = target.concat(insert); + remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(0, newArray.length - maxp) : []; + } + return [newArray, remainder]; + } + var undo2 = spliceTraces(gd, update3, indices, maxPoints, updateArray); + var promise = exports2.redraw(gd); + var undoArgs = [gd, undo2.update, indices, undo2.maxPoints]; + Queue.add(gd, exports2.prependTraces, undoArgs, extendTraces, arguments); + return promise; + } + function prependTraces(gd, update3, indices, maxPoints) { + gd = Lib2.getGraphDiv(gd); + function updateArray(target, insert, maxp) { + var newArray, remainder; + if (Lib2.isTypedArray(target)) { + if (maxp <= 0) { + var none = new target.constructor(0); + var both = concatTypedArray(insert, target); + if (maxp < 0) { + newArray = both; + remainder = none; + } else { + newArray = none; + remainder = both; + } + } else { + newArray = new target.constructor(maxp); + remainder = new target.constructor(target.length + insert.length - maxp); + if (maxp === insert.length) { + newArray.set(insert); + remainder.set(target); + } else if (maxp < insert.length) { + var numberOfItemsFromInsert = insert.length - maxp; + newArray.set(insert.subarray(0, numberOfItemsFromInsert)); + remainder.set(insert.subarray(numberOfItemsFromInsert)); + remainder.set(target, numberOfItemsFromInsert); + } else { + var numberOfItemsFromTarget = maxp - insert.length; + newArray.set(insert); + newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length); + remainder.set(target.subarray(numberOfItemsFromTarget)); + } + } + } else { + newArray = insert.concat(target); + remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(maxp, newArray.length) : []; + } + return [newArray, remainder]; + } + var undo2 = spliceTraces(gd, update3, indices, maxPoints, updateArray); + var promise = exports2.redraw(gd); + var undoArgs = [gd, undo2.update, indices, undo2.maxPoints]; + Queue.add(gd, exports2.extendTraces, undoArgs, prependTraces, arguments); + return promise; + } + function addTraces(gd, traces, newIndices) { + gd = Lib2.getGraphDiv(gd); + var currentIndices = []; + var undoFunc = exports2.deleteTraces; + var redoFunc = addTraces; + var undoArgs = [gd, currentIndices]; + var redoArgs = [gd, traces]; + var i; + var promise; + checkAddTracesArgs(gd, traces, newIndices); + if (!Array.isArray(traces)) { + traces = [traces]; + } + traces = traces.map(function(trace) { + return Lib2.extendFlat({}, trace); + }); + helpers2.cleanData(traces); + for (i = 0; i < traces.length; i++) { + gd.data.push(traces[i]); + } + for (i = 0; i < traces.length; i++) { + currentIndices.push(-traces.length + i); + } + if (typeof newIndices === "undefined") { + promise = exports2.redraw(gd); + Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + return promise; + } + if (!Array.isArray(newIndices)) { + newIndices = [newIndices]; + } + try { + checkMoveTracesArgs(gd, currentIndices, newIndices); + } catch (error) { + gd.data.splice(gd.data.length - traces.length, traces.length); + throw error; + } + Queue.startSequence(gd); + Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + promise = exports2.moveTraces(gd, currentIndices, newIndices); + Queue.stopSequence(gd); + return promise; + } + function deleteTraces(gd, indices) { + gd = Lib2.getGraphDiv(gd); + var traces = []; + var undoFunc = exports2.addTraces; + var redoFunc = deleteTraces; + var undoArgs = [gd, traces, indices]; + var redoArgs = [gd, indices]; + var i; + var deletedTrace; + if (typeof indices === "undefined") { + throw new Error("indices must be an integer or array of integers."); + } else if (!Array.isArray(indices)) { + indices = [indices]; + } + assertIndexArray(gd, indices, "indices"); + indices = positivifyIndices(indices, gd.data.length - 1); + indices.sort(Lib2.sorterDes); + for (i = 0; i < indices.length; i += 1) { + deletedTrace = gd.data.splice(indices[i], 1)[0]; + traces.push(deletedTrace); + } + var promise = exports2.redraw(gd); + Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + return promise; + } + function moveTraces(gd, currentIndices, newIndices) { + gd = Lib2.getGraphDiv(gd); + var newData = []; + var movingTraceMap = []; + var undoFunc = moveTraces; + var redoFunc = moveTraces; + var undoArgs = [gd, newIndices, currentIndices]; + var redoArgs = [gd, currentIndices, newIndices]; + var i; + checkMoveTracesArgs(gd, currentIndices, newIndices); + currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices]; + if (typeof newIndices === "undefined") { + newIndices = []; + for (i = 0; i < currentIndices.length; i++) { + newIndices.push(-currentIndices.length + i); + } + } + newIndices = Array.isArray(newIndices) ? newIndices : [newIndices]; + currentIndices = positivifyIndices(currentIndices, gd.data.length - 1); + newIndices = positivifyIndices(newIndices, gd.data.length - 1); + for (i = 0; i < gd.data.length; i++) { + if (currentIndices.indexOf(i) === -1) { + newData.push(gd.data[i]); + } + } + for (i = 0; i < currentIndices.length; i++) { + movingTraceMap.push({ newIndex: newIndices[i], trace: gd.data[currentIndices[i]] }); + } + movingTraceMap.sort(function(a, b) { + return a.newIndex - b.newIndex; + }); + for (i = 0; i < movingTraceMap.length; i += 1) { + newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace); + } + gd.data = newData; + var promise = exports2.redraw(gd); + Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + return promise; + } + function restyle(gd, astr, val, _traces) { + gd = Lib2.getGraphDiv(gd); + helpers2.clearPromiseQueue(gd); + var aobj = {}; + if (typeof astr === "string") aobj[astr] = val; + else if (Lib2.isPlainObject(astr)) { + aobj = Lib2.extendFlat({}, astr); + if (_traces === void 0) _traces = val; + } else { + Lib2.warn("Restyle fail.", astr, val, _traces); + return Promise.reject(); + } + if (Object.keys(aobj).length) gd.changed = true; + var traces = helpers2.coerceTraceIndices(gd, _traces); + var specs = _restyle(gd, aobj, traces); + var flags = specs.flags; + if (flags.calc) gd.calcdata = void 0; + if (flags.clearAxisTypes) helpers2.clearAxisTypes(gd, traces, {}); + var seq = []; + if (flags.fullReplot) { + seq.push(exports2._doPlot); + } else { + seq.push(Plots2.previousPromises); + Plots2.supplyDefaults(gd); + if (flags.markerSize) { + Plots2.doCalcdata(gd); + addAxRangeSequence(seq); + } + if (flags.style) seq.push(subroutines$1.doTraceStyle); + if (flags.colorbars) seq.push(subroutines$1.doColorBars); + seq.push(emitAfterPlot); + } + seq.push( + Plots2.rehover, + Plots2.redrag, + Plots2.reselect + ); + Queue.add( + gd, + restyle, + [gd, specs.undoit, specs.traces], + restyle, + [gd, specs.redoit, specs.traces] + ); + var plotDone = Lib2.syncOrAsync(seq, gd); + if (!plotDone || !plotDone.then) plotDone = Promise.resolve(); + return plotDone.then(function() { + gd.emit("plotly_restyle", specs.eventData); + return gd; + }); + } + function undefinedToNull(val) { + if (val === void 0) return null; + return val; + } + function makeNP(preGUI, guiEditFlag) { + if (!guiEditFlag) return nestedProperty3; + return function(container, attr, prefix) { + var np = nestedProperty3(container, attr); + var npSet2 = np.set; + np.set = function(val) { + var fullAttr = (prefix || "") + attr; + storeCurrent(fullAttr, np.get(), val, preGUI); + npSet2(val); + }; + return np; + }; + } + function storeCurrent(attr, val, newVal, preGUI) { + if (Array.isArray(val) || Array.isArray(newVal)) { + var arrayVal = Array.isArray(val) ? val : []; + var arrayNew = Array.isArray(newVal) ? newVal : []; + var maxLen = Math.max(arrayVal.length, arrayNew.length); + for (var i = 0; i < maxLen; i++) { + storeCurrent(attr + "[" + i + "]", arrayVal[i], arrayNew[i], preGUI); + } + } else if (Lib2.isPlainObject(val) || Lib2.isPlainObject(newVal)) { + var objVal = Lib2.isPlainObject(val) ? val : {}; + var objNew = Lib2.isPlainObject(newVal) ? newVal : {}; + var objBoth = Lib2.extendFlat({}, objVal, objNew); + for (var key in objBoth) { + storeCurrent(attr + "." + key, objVal[key], objNew[key], preGUI); + } + } else if (preGUI[attr] === void 0) { + preGUI[attr] = undefinedToNull(val); + } + } + function _storeDirectGUIEdit(container, preGUI, edits) { + for (var attr in edits) { + var np = nestedProperty3(container, attr); + storeCurrent(attr, np.get(), edits[attr], preGUI); + } + } + function _restyle(gd, aobj, traces) { + var fullLayout = gd._fullLayout; + var fullData = gd._fullData; + var data = gd.data; + var guiEditFlag = fullLayout._guiEditing; + var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); + var eventData5 = Lib2.extendDeepAll({}, aobj); + var i; + cleanDeprecatedAttributeKeys(aobj); + var flags = editTypes.traceFlags(); + var redoit = {}; + var undoit = {}; + var axlist; + function a0() { + return traces.map(function() { + return void 0; + }); + } + function addToAxlist(axid) { + var axName = Axes2.id2name(axid); + if (axlist.indexOf(axName) === -1) axlist.push(axName); + } + function autorangeAttr(axName) { + return "LAYOUT" + axName + ".autorange"; + } + function rangeAttr(axName) { + return "LAYOUT" + axName + ".range"; + } + function getFullTrace(traceIndex) { + for (var j = traceIndex; j < fullData.length; j++) { + if (fullData[j]._input === data[traceIndex]) return fullData[j]; + } + } + function doextra(attr, val, i2) { + if (Array.isArray(attr)) { + attr.forEach(function(a) { + doextra(a, val, i2); + }); + return; + } + if (attr in aobj || helpers2.hasParent(aobj, attr)) return; + var extraparam; + if (attr.substr(0, 6) === "LAYOUT") { + extraparam = layoutNP(gd.layout, attr.replace("LAYOUT", "")); + } else { + var tracei = traces[i2]; + var preGUI2 = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid]; + extraparam = makeNP(preGUI2, guiEditFlag)(data[tracei], attr); + } + if (!(attr in undoit)) { + undoit[attr] = a0(); + } + if (undoit[attr][i2] === void 0) { + undoit[attr][i2] = undefinedToNull(extraparam.get()); + } + if (val !== void 0) { + extraparam.set(val); + } + } + function allBins(binAttr) { + return function(j) { + return fullData[j][binAttr]; + }; + } + function arrayBins(binAttr) { + return function(vij, j) { + return vij === false ? fullData[traces[j]][binAttr] : null; + }; + } + for (var ai in aobj) { + if (helpers2.hasParent(aobj, ai)) { + throw new Error("cannot set " + ai + " and a parent attribute simultaneously"); + } + var vi = aobj[ai]; + var cont; + var contFull; + var param; + var oldVal; + var newVal; + var valObject; + if (ai === "autobinx" || ai === "autobiny") { + ai = ai.charAt(ai.length - 1) + "bins"; + if (Array.isArray(vi)) vi = vi.map(arrayBins(ai)); + else if (vi === false) vi = traces.map(allBins(ai)); + else vi = null; + } + redoit[ai] = vi; + if (ai.substr(0, 6) === "LAYOUT") { + param = layoutNP(gd.layout, ai.replace("LAYOUT", "")); + undoit[ai] = [undefinedToNull(param.get())]; + param.set(Array.isArray(vi) ? vi[0] : vi); + flags.calc = true; + continue; + } + undoit[ai] = a0(); + for (i = 0; i < traces.length; i++) { + cont = data[traces[i]]; + contFull = getFullTrace(traces[i]); + var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid]; + param = makeNP(preGUI, guiEditFlag)(cont, ai); + oldVal = param.get(); + newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; + if (newVal === void 0) continue; + var finalPart = param.parts[param.parts.length - 1]; + var prefix = ai.substr(0, ai.length - finalPart.length - 1); + var prefixDot = prefix ? prefix + "." : ""; + var innerContFull = prefix ? nestedProperty3(contFull, prefix).get() : contFull; + valObject = PlotSchema2.getTraceValObject(contFull, param.parts); + if (valObject && valObject.impliedEdits && newVal !== null) { + for (var impliedKey in valObject.impliedEdits) { + doextra(Lib2.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); + } + } else if ((finalPart === "thicknessmode" || finalPart === "lenmode") && oldVal !== newVal && (newVal === "fraction" || newVal === "pixels") && innerContFull) { + var gs = fullLayout._size; + var orient = innerContFull.orient; + var topOrBottom = orient === "top" || orient === "bottom"; + if (finalPart === "thicknessmode") { + var thicknorm = topOrBottom ? gs.h : gs.w; + doextra(prefixDot + "thickness", innerContFull.thickness * (newVal === "fraction" ? 1 / thicknorm : thicknorm), i); + } else { + var lennorm = topOrBottom ? gs.w : gs.h; + doextra(prefixDot + "len", innerContFull.len * (newVal === "fraction" ? 1 / lennorm : lennorm), i); + } + } else if (ai === "type" && (newVal === "pie" !== (oldVal === "pie") || newVal === "funnelarea" !== (oldVal === "funnelarea"))) { + var labelsTo = "x"; + var valuesTo = "y"; + if ((newVal === "bar" || oldVal === "bar") && cont.orientation === "h") { + labelsTo = "y"; + valuesTo = "x"; + } + Lib2.swapAttrs(cont, ["?", "?src"], "labels", labelsTo); + Lib2.swapAttrs(cont, ["d?", "?0"], "label", labelsTo); + Lib2.swapAttrs(cont, ["?", "?src"], "values", valuesTo); + if (oldVal === "pie" || oldVal === "funnelarea") { + nestedProperty3(cont, "marker.color").set(nestedProperty3(cont, "marker.colors").get()); + fullLayout._pielayer.selectAll("g.trace").remove(); + } else if (Registry2.traceIs(cont, "cartesian")) { + nestedProperty3(cont, "marker.colors").set(nestedProperty3(cont, "marker.color").get()); + } + } + undoit[ai][i] = undefinedToNull(oldVal); + var swapAttrs = [ + "swapxy", + "swapxyaxes", + "orientation", + "orientationaxes" + ]; + if (swapAttrs.indexOf(ai) !== -1) { + if (ai === "orientation") { + param.set(newVal); + var defaultOrientation = cont.x && !cont.y ? "h" : "v"; + if ((param.get() || defaultOrientation) === contFull.orientation) { + continue; + } + } else if (ai === "orientationaxes") { + cont.orientation = { v: "h", h: "v" }[contFull.orientation]; + } + helpers2.swapXYData(cont); + flags.calc = flags.clearAxisTypes = true; + } else if (Plots2.dataArrayContainers.indexOf(param.parts[0]) !== -1) { + helpers2.manageArrayContainers(param, newVal, undoit); + flags.calc = true; + } else { + if (valObject) { + if (valObject.arrayOk && !Registry2.traceIs(contFull, "regl") && (Lib2.isArrayOrTypedArray(newVal) || Lib2.isArrayOrTypedArray(oldVal))) { + flags.calc = true; + } else editTypes.update(flags, valObject); + } else { + flags.calc = true; + } + param.set(newVal); + } + } + if (["swapxyaxes", "orientationaxes"].indexOf(ai) !== -1) { + Axes2.swap(gd, traces); + } + if (ai === "orientationaxes") { + var hovermode = nestedProperty3(gd.layout, "hovermode"); + var h = hovermode.get(); + if (h === "x") { + hovermode.set("y"); + } else if (h === "y") { + hovermode.set("x"); + } else if (h === "x unified") { + hovermode.set("y unified"); + } else if (h === "y unified") { + hovermode.set("x unified"); + } + } + if (["orientation", "type"].indexOf(ai) !== -1) { + axlist = []; + for (i = 0; i < traces.length; i++) { + var trace = data[traces[i]]; + if (Registry2.traceIs(trace, "cartesian")) { + addToAxlist(trace.xaxis || "x"); + addToAxlist(trace.yaxis || "y"); + } + } + doextra(axlist.map(autorangeAttr), true, 0); + doextra(axlist.map(rangeAttr), [0, 1], 0); + } + } + if (flags.calc || flags.plot) { + flags.fullReplot = true; + } + return { + flags, + undoit, + redoit, + traces, + eventData: Lib2.extendDeepNoArrays([], [eventData5, traces]) + }; + } + function cleanDeprecatedAttributeKeys(aobj) { + var oldAxisTitleRegex = Lib2.counterRegex("axis", ".title", false, false); + var colorbarRegex = /colorbar\.title$/; + var keys = Object.keys(aobj); + var i, key, value2; + for (i = 0; i < keys.length; i++) { + key = keys[i]; + value2 = aobj[key]; + if ((key === "title" || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) && (typeof value2 === "string" || typeof value2 === "number")) { + replace(key, key.replace("title", "title.text")); + } else if (key.indexOf("titlefont") > -1 && key.indexOf("grouptitlefont") === -1) { + replace(key, key.replace("titlefont", "title.font")); + } else if (key.indexOf("titleposition") > -1) { + replace(key, key.replace("titleposition", "title.position")); + } else if (key.indexOf("titleside") > -1) { + replace(key, key.replace("titleside", "title.side")); + } else if (key.indexOf("titleoffset") > -1) { + replace(key, key.replace("titleoffset", "title.offset")); + } + } + function replace(oldAttrStr, newAttrStr) { + aobj[newAttrStr] = aobj[oldAttrStr]; + delete aobj[oldAttrStr]; + } + } + function relayout(gd, astr, val) { + gd = Lib2.getGraphDiv(gd); + helpers2.clearPromiseQueue(gd); + var aobj = {}; + if (typeof astr === "string") { + aobj[astr] = val; + } else if (Lib2.isPlainObject(astr)) { + aobj = Lib2.extendFlat({}, astr); + } else { + Lib2.warn("Relayout fail.", astr, val); + return Promise.reject(); + } + if (Object.keys(aobj).length) gd.changed = true; + var specs = _relayout(gd, aobj); + var flags = specs.flags; + if (flags.calc) gd.calcdata = void 0; + var seq = [Plots2.previousPromises]; + if (flags.layoutReplot) { + seq.push(subroutines$1.layoutReplot); + } else if (Object.keys(aobj).length) { + axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots2.supplyDefaults(gd); + if (flags.legend) seq.push(subroutines$1.doLegend); + if (flags.layoutstyle) seq.push(subroutines$1.layoutStyles); + if (flags.axrange) addAxRangeSequence(seq, specs.rangesAltered); + if (flags.ticks) seq.push(subroutines$1.doTicksRelayout); + if (flags.modebar) seq.push(subroutines$1.doModeBar); + if (flags.camera) seq.push(subroutines$1.doCamera); + if (flags.colorbars) seq.push(subroutines$1.doColorBars); + seq.push(emitAfterPlot); + } + seq.push( + Plots2.rehover, + Plots2.redrag, + Plots2.reselect + ); + Queue.add( + gd, + relayout, + [gd, specs.undoit], + relayout, + [gd, specs.redoit] + ); + var plotDone = Lib2.syncOrAsync(seq, gd); + if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); + return plotDone.then(function() { + gd.emit("plotly_relayout", specs.eventData); + return gd; + }); + } + function axRangeSupplyDefaultsByPass(gd, flags, specs) { + var fullLayout = gd._fullLayout; + if (!flags.axrange) return false; + for (var k in flags) { + if (k !== "axrange" && flags[k]) return false; + } + var axIn, axOut; + var coerce2 = function(attr, dflt) { + return Lib2.coerce(axIn, axOut, cartesianLayoutAttributes, attr, dflt); + }; + var options = {}; + for (var axId in specs.rangesAltered) { + var axName = Axes2.id2name(axId); + axIn = gd.layout[axName]; + axOut = fullLayout[axName]; + handleRangeDefaults3(axIn, axOut, coerce2, options); + if (axOut._matchGroup) { + for (var axId2 in axOut._matchGroup) { + if (axId2 !== axId) { + var ax2 = fullLayout[Axes2.id2name(axId2)]; + ax2.autorange = axOut.autorange; + ax2.range = axOut.range.slice(); + ax2._input.range = axOut.range.slice(); + } + } + } + } + return true; + } + function addAxRangeSequence(seq, rangesAltered) { + var drawAxes = rangesAltered ? function(gd) { + var axIds2 = []; + var skipTitle = true; + for (var id in rangesAltered) { + var ax = Axes2.getFromId(gd, id); + axIds2.push(id); + if ((ax.ticklabelposition || "").indexOf("inside") !== -1) { + if (ax._anchorAxis) { + axIds2.push(ax._anchorAxis._id); + } + } + if (ax._matchGroup) { + for (var id2 in ax._matchGroup) { + if (!rangesAltered[id2]) { + axIds2.push(id2); + } + } + } + } + return Axes2.draw(gd, axIds2, { skipTitle }); + } : function(gd) { + return Axes2.draw(gd, "redraw"); + }; + seq.push( + clearOutline2, + subroutines$1.doAutoRangeAndConstraints, + drawAxes, + subroutines$1.drawData, + subroutines$1.finalDraw + ); + } + var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/; + var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/; + var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/; + function _relayout(gd, aobj) { + var layout = gd.layout; + var fullLayout = gd._fullLayout; + var guiEditFlag = fullLayout._guiEditing; + var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); + var keys = Object.keys(aobj); + var axes2 = Axes2.list(gd); + var eventData5 = Lib2.extendDeepAll({}, aobj); + var arrayEdits = {}; + var arrayStr, i, j; + cleanDeprecatedAttributeKeys(aobj); + keys = Object.keys(aobj); + for (i = 0; i < keys.length; i++) { + if (keys[i].indexOf("allaxes") === 0) { + for (j = 0; j < axes2.length; j++) { + var scene = axes2[j]._id.substr(1); + var axisAttr = scene.indexOf("scene") !== -1 ? scene + "." : ""; + var newkey = keys[i].replace("allaxes", axisAttr + axes2[j]._name); + if (!aobj[newkey]) aobj[newkey] = aobj[keys[i]]; + } + delete aobj[keys[i]]; + } + } + var flags = editTypes.layoutFlags(); + var redoit = {}; + var undoit = {}; + function doextra(attr, val) { + if (Array.isArray(attr)) { + attr.forEach(function(a) { + doextra(a, val); + }); + return; + } + if (attr in aobj || helpers2.hasParent(aobj, attr)) return; + var p2 = layoutNP(layout, attr); + if (!(attr in undoit)) { + undoit[attr] = undefinedToNull(p2.get()); + } + if (val !== void 0) p2.set(val); + } + var rangesAltered = {}; + var ax; + function recordAlteredAxis(pleafPlus2) { + var axId2 = Axes2.name2id(pleafPlus2.split(".")[0]); + rangesAltered[axId2] = 1; + return axId2; + } + for (var ai in aobj) { + if (helpers2.hasParent(aobj, ai)) { + throw new Error("cannot set " + ai + " and a parent attribute simultaneously"); + } + var p = layoutNP(layout, ai); + var vi = aobj[ai]; + var plen = p.parts.length; + var pend = plen - 1; + while (pend > 0 && typeof p.parts[pend] !== "string") pend--; + var pleaf = p.parts[pend]; + var pleafPlus = p.parts[pend - 1] + "." + pleaf; + var ptrunk = p.parts.slice(0, pend).join("."); + var parentIn = nestedProperty3(gd.layout, ptrunk).get(); + var parentFull = nestedProperty3(fullLayout, ptrunk).get(); + var vOld = p.get(); + if (vi === void 0) continue; + redoit[ai] = vi; + undoit[ai] = pleaf === "reverse" ? vi : undefinedToNull(vOld); + var valObject = PlotSchema2.getLayoutValObject(fullLayout, p.parts); + if (valObject && valObject.impliedEdits && vi !== null) { + for (var impliedKey in valObject.impliedEdits) { + doextra(Lib2.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); + } + } + if (["width", "height"].indexOf(ai) !== -1) { + if (vi) { + doextra("autosize", null); + var oppositeAttr = ai === "height" ? "width" : "height"; + doextra(oppositeAttr, fullLayout[oppositeAttr]); + } else { + fullLayout[ai] = gd._initialAutoSize[ai]; + } + } else if (ai === "autosize") { + doextra("width", vi ? null : fullLayout.width); + doextra("height", vi ? null : fullLayout.height); + } else if (pleafPlus.match(AX_RANGE_RE)) { + recordAlteredAxis(pleafPlus); + nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); + } else if (pleafPlus.match(AX_AUTORANGE_RE)) { + recordAlteredAxis(pleafPlus); + nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); + var axFull = nestedProperty3(fullLayout, ptrunk).get(); + if (axFull._inputDomain) { + axFull._input.domain = axFull._inputDomain.slice(); + } + } else if (pleafPlus.match(AX_DOMAIN_RE)) { + nestedProperty3(fullLayout, ptrunk + "._inputDomain").set(null); + } + if (pleaf === "type") { + ax = parentIn; + var toLog = parentFull.type === "linear" && vi === "log"; + var fromLog2 = parentFull.type === "log" && vi === "linear"; + if (toLog || fromLog2) { + if (!ax || !ax.range) { + doextra(ptrunk + ".autorange", true); + } else if (!parentFull.autorange) { + var r0 = ax.range[0]; + var r1 = ax.range[1]; + if (toLog) { + if (r0 <= 0 && r1 <= 0) { + doextra(ptrunk + ".autorange", true); + } + if (r0 <= 0) r0 = r1 / 1e6; + else if (r1 <= 0) r1 = r0 / 1e6; + doextra(ptrunk + ".range[0]", Math.log(r0) / Math.LN10); + doextra(ptrunk + ".range[1]", Math.log(r1) / Math.LN10); + } else { + doextra(ptrunk + ".range[0]", Math.pow(10, r0)); + doextra(ptrunk + ".range[1]", Math.pow(10, r1)); + } + } else if (toLog) { + ax.range = ax.range[1] > ax.range[0] ? [1, 2] : [2, 1]; + } + if (Array.isArray(fullLayout._subplots.polar) && fullLayout._subplots.polar.length && fullLayout[p.parts[0]] && p.parts[1] === "radialaxis") { + delete fullLayout[p.parts[0]]._subplot.viewInitial["radialaxis.range"]; + } + Registry2.getComponentMethod("annotations", "convertCoords")(gd, parentFull, vi, doextra); + Registry2.getComponentMethod("images", "convertCoords")(gd, parentFull, vi, doextra); + } else { + doextra(ptrunk + ".autorange", true); + doextra(ptrunk + ".range", null); + } + nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); + } else if (pleaf.match(AX_NAME_PATTERN)) { + var fullProp = nestedProperty3(fullLayout, ai).get(); + var newType = (vi || {}).type; + if (!newType || newType === "-") newType = "linear"; + Registry2.getComponentMethod("annotations", "convertCoords")(gd, fullProp, newType, doextra); + Registry2.getComponentMethod("images", "convertCoords")(gd, fullProp, newType, doextra); + } + var containerArrayMatch2 = manageArrays.containerArrayMatch(ai); + if (containerArrayMatch2) { + arrayStr = containerArrayMatch2.array; + i = containerArrayMatch2.index; + var propStr = containerArrayMatch2.property; + var updateValObject = valObject || { editType: "calc" }; + if (i !== "" && propStr === "") { + if (manageArrays.isAddVal(vi)) { + undoit[ai] = null; + } else if (manageArrays.isRemoveVal(vi)) { + undoit[ai] = (nestedProperty3(layout, arrayStr).get() || [])[i]; + } else { + Lib2.warn("unrecognized full object value", aobj); + } + } + editTypes.update(flags, updateValObject); + if (!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; + var objEdits = arrayEdits[arrayStr][i]; + if (!objEdits) objEdits = arrayEdits[arrayStr][i] = {}; + objEdits[propStr] = vi; + delete aobj[ai]; + } else if (pleaf === "reverse") { + if (parentIn.range) parentIn.range.reverse(); + else { + doextra(ptrunk + ".autorange", true); + parentIn.range = [1, 0]; + } + if (parentFull.autorange) flags.calc = true; + else flags.plot = true; + } else { + if (ai === "dragmode" && (vi === false && vOld !== false || vi !== false && vOld === false)) { + flags.plot = true; + } else if (fullLayout._has("scatter-like") && fullLayout._has("regl") && (ai === "dragmode" && (vi === "lasso" || vi === "select") && !(vOld === "lasso" || vOld === "select"))) { + flags.plot = true; + } else if (fullLayout._has("gl2d")) { + flags.plot = true; + } else if (valObject) editTypes.update(flags, valObject); + else flags.calc = true; + p.set(vi); + } + } + for (arrayStr in arrayEdits) { + var finished = manageArrays.applyContainerArrayChanges( + gd, + layoutNP(layout, arrayStr), + arrayEdits[arrayStr], + flags, + layoutNP + ); + if (!finished) flags.plot = true; + } + for (var axId in rangesAltered) { + ax = Axes2.getFromId(gd, axId); + var group = ax && ax._constraintGroup; + if (group) { + flags.calc = true; + for (var groupAxId in group) { + if (!rangesAltered[groupAxId]) { + Axes2.getFromId(gd, groupAxId)._constraintShrinkable = true; + } + } + } + } + if (updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true; + var shapes2 = fullLayout.shapes; + for (i = 0; i < shapes2.length; i++) { + if (shapes2[i].showlegend) { + flags.calc = true; + break; + } + } + if (flags.plot || flags.calc) { + flags.layoutReplot = true; + } + return { + flags, + rangesAltered, + undoit, + redoit, + eventData: eventData5 + }; + } + function updateAutosize(gd) { + var fullLayout = gd._fullLayout; + var oldWidth = fullLayout.width; + var oldHeight = fullLayout.height; + if (gd.layout.autosize) Plots2.plotAutoSize(gd, gd.layout, fullLayout); + return fullLayout.width !== oldWidth || fullLayout.height !== oldHeight; + } + function update2(gd, traceUpdate, layoutUpdate, _traces) { + gd = Lib2.getGraphDiv(gd); + helpers2.clearPromiseQueue(gd); + if (!Lib2.isPlainObject(traceUpdate)) traceUpdate = {}; + if (!Lib2.isPlainObject(layoutUpdate)) layoutUpdate = {}; + if (Object.keys(traceUpdate).length) gd.changed = true; + if (Object.keys(layoutUpdate).length) gd.changed = true; + var traces = helpers2.coerceTraceIndices(gd, _traces); + var restyleSpecs = _restyle(gd, Lib2.extendFlat({}, traceUpdate), traces); + var restyleFlags = restyleSpecs.flags; + var relayoutSpecs = _relayout(gd, Lib2.extendFlat({}, layoutUpdate)); + var relayoutFlags = relayoutSpecs.flags; + if (restyleFlags.calc || relayoutFlags.calc) gd.calcdata = void 0; + if (restyleFlags.clearAxisTypes) helpers2.clearAxisTypes(gd, traces, layoutUpdate); + var seq = []; + if (relayoutFlags.layoutReplot) { + seq.push(subroutines$1.layoutReplot); + } else if (restyleFlags.fullReplot) { + seq.push(exports2._doPlot); + } else { + seq.push(Plots2.previousPromises); + axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots2.supplyDefaults(gd); + if (restyleFlags.style) seq.push(subroutines$1.doTraceStyle); + if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines$1.doColorBars); + if (relayoutFlags.legend) seq.push(subroutines$1.doLegend); + if (relayoutFlags.layoutstyle) seq.push(subroutines$1.layoutStyles); + if (relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered); + if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); + if (relayoutFlags.modebar) seq.push(subroutines$1.doModeBar); + if (relayoutFlags.camera) seq.push(subroutines$1.doCamera); + seq.push(emitAfterPlot); + } + seq.push( + Plots2.rehover, + Plots2.redrag, + Plots2.reselect + ); + Queue.add( + gd, + update2, + [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], + update2, + [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] + ); + var plotDone = Lib2.syncOrAsync(seq, gd); + if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); + return plotDone.then(function() { + gd.emit("plotly_update", { + data: restyleSpecs.eventData, + layout: relayoutSpecs.eventData + }); + return gd; + }); + } + function guiEdit(func) { + return function wrappedEdit(gd) { + gd._fullLayout._guiEditing = true; + var p = func.apply(null, arguments); + gd._fullLayout._guiEditing = false; + return p; + }; + } + var layoutUIControlPatterns = [ + { pattern: /^hiddenlabels/, attr: "legend.uirevision" }, + { pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/ }, + // showspikes and modes include those nested inside scenes + { pattern: /axis\d*\.showspikes$/, attr: "modebar.uirevision" }, + { pattern: /(hover|drag)mode$/, attr: "modebar.uirevision" }, + { pattern: /^(scene\d*)\.camera/ }, + { pattern: /^(geo\d*)\.(projection|center|fitbounds)/ }, + { pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/ }, + { pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/ }, + { pattern: /^(polar\d*\.angularaxis)\.rotation/ }, + { pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/ }, + { pattern: /^(map\d*)\.(center|zoom|bearing|pitch)/ }, + { pattern: /^legend\.(x|y)$/, attr: "editrevision" }, + { pattern: /^(shapes|annotations)/, attr: "editrevision" }, + { pattern: /^title\.text$/, attr: "editrevision" } + ]; + var traceUIControlPatterns = [ + { pattern: /^selectedpoints$/, attr: "selectionrevision" }, + // "visible" includes trace.transforms[i].styles[j].value.visible + { pattern: /(^|value\.)visible$/, attr: "legend.uirevision" }, + { pattern: /^dimensions\[\d+\]\.constraintrange/ }, + { pattern: /^node\.(x|y|groups)/ }, + // for Sankey nodes + { pattern: /^level$/ }, + // for Sunburst, Treemap and Icicle traces + // below this you must be in editable: true mode + // TODO: I still put name and title with `trace.uirevision` + // reasonable or should these be `editrevision`? + // Also applies to axis titles up in the layout section + // "name" also includes transform.styles + { pattern: /(^|value\.)name$/ }, + // including nested colorbar attributes (ie marker.colorbar) + { pattern: /colorbar\.title\.text$/ }, + { pattern: /colorbar\.(x|y)$/, attr: "editrevision" } + ]; + function findUIPattern(key, patternSpecs) { + for (var i = 0; i < patternSpecs.length; i++) { + var spec = patternSpecs[i]; + var match = key.match(spec.pattern); + if (match) { + var head = match[1] || ""; + return { head, tail: key.substr(head.length + 1), attr: spec.attr }; + } + } + } + function getNewRev(revAttr, container) { + var newRev = nestedProperty3(container, revAttr).get(); + if (newRev !== void 0) return newRev; + var parts = revAttr.split("."); + parts.pop(); + while (parts.length > 1) { + parts.pop(); + newRev = nestedProperty3(container, parts.join(".") + ".uirevision").get(); + if (newRev !== void 0) return newRev; + } + return container.uirevision; + } + function getFullTraceIndexFromUid(uid, fullData) { + for (var i = 0; i < fullData.length; i++) { + if (fullData[i]._fullInput.uid === uid) return i; + } + return -1; + } + function getTraceIndexFromUid(uid, data, tracei) { + for (var i = 0; i < data.length; i++) { + if (data[i].uid === uid) return i; + } + return !data[tracei] || data[tracei].uid ? -1 : tracei; + } + function valsMatch(v1, v2) { + var v1IsObj = Lib2.isPlainObject(v1); + var v1IsArray = Array.isArray(v1); + if (v1IsObj || v1IsArray) { + return (v1IsObj && Lib2.isPlainObject(v2) || v1IsArray && Array.isArray(v2)) && JSON.stringify(v1) === JSON.stringify(v2); + } + return v1 === v2; + } + function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { + var layoutPreGUI = oldFullLayout._preGUI; + var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal, head, tail; + var bothInheritAutorange = []; + var newAutorangeIn = {}; + var newRangeAccepted = {}; + for (key in layoutPreGUI) { + match = findUIPattern(key, layoutUIControlPatterns); + if (match) { + head = match.head; + tail = match.tail; + revAttr = match.attr || head + ".uirevision"; + oldRev = nestedProperty3(oldFullLayout, revAttr).get(); + newRev = oldRev && getNewRev(revAttr, layout); + if (newRev && newRev === oldRev) { + preGUIVal = layoutPreGUI[key]; + if (preGUIVal === null) preGUIVal = void 0; + newNP = nestedProperty3(layout, key); + newVal = newNP.get(); + if (valsMatch(newVal, preGUIVal)) { + if (newVal === void 0 && tail === "autorange") { + bothInheritAutorange.push(head); + } + newNP.set(undefinedToNull(nestedProperty3(oldFullLayout, key).get())); + continue; + } else if (tail === "autorange" || tail.substr(0, 6) === "range[") { + var pre0 = layoutPreGUI[head + ".range[0]"]; + var pre1 = layoutPreGUI[head + ".range[1]"]; + var preAuto = layoutPreGUI[head + ".autorange"]; + if (preAuto || preAuto === null && pre0 === null && pre1 === null) { + if (!(head in newAutorangeIn)) { + var newContainer = nestedProperty3(layout, head).get(); + newAutorangeIn[head] = newContainer && (newContainer.autorange || newContainer.autorange !== false && (!newContainer.range || newContainer.range.length !== 2)); + } + if (newAutorangeIn[head]) { + newNP.set(undefinedToNull(nestedProperty3(oldFullLayout, key).get())); + continue; + } + } + } + } + } else { + Lib2.warn("unrecognized GUI edit: " + key); + } + delete layoutPreGUI[key]; + if (match && match.tail.substr(0, 6) === "range[") { + newRangeAccepted[match.head] = 1; + } + } + for (var i = 0; i < bothInheritAutorange.length; i++) { + var axAttr = bothInheritAutorange[i]; + if (newRangeAccepted[axAttr]) { + var newAx = nestedProperty3(layout, axAttr).get(); + if (newAx) delete newAx.autorange; + } + } + var allTracePreGUI = oldFullLayout._tracePreGUI; + for (var uid in allTracePreGUI) { + var tracePreGUI = allTracePreGUI[uid]; + var newTrace = null; + var fullInput; + for (key in tracePreGUI) { + if (!newTrace) { + var fulli = getFullTraceIndexFromUid(uid, oldFullData); + if (fulli < 0) { + delete allTracePreGUI[uid]; + break; + } + var fullTrace = oldFullData[fulli]; + fullInput = fullTrace._fullInput; + var newTracei = getTraceIndexFromUid(uid, data, fullInput.index); + if (newTracei < 0) { + delete allTracePreGUI[uid]; + break; + } + newTrace = data[newTracei]; + } + match = findUIPattern(key, traceUIControlPatterns); + if (match) { + if (match.attr) { + oldRev = nestedProperty3(oldFullLayout, match.attr).get(); + newRev = oldRev && getNewRev(match.attr, layout); + } else { + oldRev = fullInput.uirevision; + newRev = newTrace.uirevision; + if (newRev === void 0) newRev = layout.uirevision; + } + if (newRev && newRev === oldRev) { + preGUIVal = tracePreGUI[key]; + if (preGUIVal === null) preGUIVal = void 0; + newNP = nestedProperty3(newTrace, key); + newVal = newNP.get(); + if (valsMatch(newVal, preGUIVal)) { + newNP.set(undefinedToNull(nestedProperty3(fullInput, key).get())); + continue; + } + } + } else { + Lib2.warn("unrecognized GUI edit: " + key + " in trace uid " + uid); + } + delete tracePreGUI[key]; + } + } + } + function react(gd, data, layout, config) { + var frames, plotDone; + function addFrames2() { + return exports2.addFrames(gd, frames); + } + gd = Lib2.getGraphDiv(gd); + helpers2.clearPromiseQueue(gd); + var oldFullData = gd._fullData; + var oldFullLayout = gd._fullLayout; + if (!Lib2.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { + plotDone = exports2.newPlot(gd, data, layout, config); + } else { + if (Lib2.isPlainObject(data)) { + var obj = data; + data = obj.data; + layout = obj.layout; + config = obj.config; + frames = obj.frames; + } + var configChanged = false; + if (config) { + var oldConfig = Lib2.extendDeep({}, gd._context); + gd._context = void 0; + setPlotContext(gd, config); + configChanged = diffConfig(oldConfig, gd._context); + } + gd.data = data || []; + helpers2.cleanData(gd.data); + gd.layout = layout || {}; + helpers2.cleanLayout(gd.layout); + applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout); + Plots2.supplyDefaults(gd, { skipUpdateCalc: true }); + var newFullData = gd._fullData; + var newFullLayout = gd._fullLayout; + var immutable = newFullLayout.datarevision === void 0; + var transition2 = newFullLayout.transition; + var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition2); + var newDataRevision = relayoutFlags.newDataRevision; + var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition2, newDataRevision); + if (updateAutosize(gd)) relayoutFlags.layoutReplot = true; + if (restyleFlags.calc || relayoutFlags.calc) { + gd.calcdata = void 0; + var allNames = Object.getOwnPropertyNames(newFullLayout); + for (var q = 0; q < allNames.length; q++) { + var name2 = allNames[q]; + var start = name2.substring(0, 5); + if (start === "xaxis" || start === "yaxis") { + var emptyCategories = newFullLayout[name2]._emptyCategories; + if (emptyCategories) emptyCategories(); + } + } + } else { + Plots2.supplyDefaultsUpdateCalc(gd.calcdata, newFullData); + } + var seq = []; + if (frames) { + gd._transitionData = {}; + Plots2.createTransitionData(gd); + seq.push(addFrames2); + } + if (newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) { + if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); + Plots2.doCalcdata(gd); + subroutines$1.doAutoRangeAndConstraints(gd); + seq.push(function() { + return Plots2.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout); + }); + } else if (restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { + gd._fullLayout._skipDefaults = true; + seq.push(exports2._doPlot); + } else { + for (var componentType in relayoutFlags.arrays) { + var indices = relayoutFlags.arrays[componentType]; + if (indices.length) { + var drawOne2 = Registry2.getComponentMethod(componentType, "drawOne"); + if (drawOne2 !== Lib2.noop) { + for (var i = 0; i < indices.length; i++) { + drawOne2(gd, indices[i]); + } + } else { + var draw8 = Registry2.getComponentMethod(componentType, "draw"); + if (draw8 === Lib2.noop) { + throw new Error("cannot draw components: " + componentType); + } + draw8(gd); + } + } + } + seq.push(Plots2.previousPromises); + if (restyleFlags.style) seq.push(subroutines$1.doTraceStyle); + if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines$1.doColorBars); + if (relayoutFlags.legend) seq.push(subroutines$1.doLegend); + if (relayoutFlags.layoutstyle) seq.push(subroutines$1.layoutStyles); + if (relayoutFlags.axrange) addAxRangeSequence(seq); + if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); + if (relayoutFlags.modebar) seq.push(subroutines$1.doModeBar); + if (relayoutFlags.camera) seq.push(subroutines$1.doCamera); + seq.push(emitAfterPlot); + } + seq.push( + Plots2.rehover, + Plots2.redrag, + Plots2.reselect + ); + plotDone = Lib2.syncOrAsync(seq, gd); + if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); + } + return plotDone.then(function() { + gd.emit("plotly_react", { + data, + layout + }); + return gd; + }); + } + function diffData(gd, oldFullData, newFullData, immutable, transition2, newDataRevision) { + var sameTraceLength = oldFullData.length === newFullData.length; + if (!transition2 && !sameTraceLength) { + return { + fullReplot: true, + calc: true + }; + } + var flags = editTypes.traceFlags(); + flags.arrays = {}; + flags.nChanges = 0; + flags.nChangesAnim = 0; + var i, trace; + function getTraceValObject(parts) { + var out = PlotSchema2.getTraceValObject(trace, parts); + if (!trace._module.animatable && out.anim) { + out.anim = false; + } + return out; + } + var diffOpts = { + getValObject: getTraceValObject, + flags, + immutable, + transition: transition2, + newDataRevision, + gd + }; + var seenUIDs = {}; + for (i = 0; i < oldFullData.length; i++) { + if (newFullData[i]) { + trace = newFullData[i]._fullInput; + if (Plots2.hasMakesDataTransform(trace)) trace = newFullData[i]; + if (seenUIDs[trace.uid]) continue; + seenUIDs[trace.uid] = 1; + getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts); + } + } + if (flags.calc || flags.plot) { + flags.fullReplot = true; + } + if (transition2 && flags.nChanges && flags.nChangesAnim) { + flags.anim = flags.nChanges === flags.nChangesAnim && sameTraceLength ? "all" : "some"; + } + return flags; + } + function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition2) { + var flags = editTypes.layoutFlags(); + flags.arrays = {}; + flags.rangesAltered = {}; + flags.nChanges = 0; + flags.nChangesAnim = 0; + function getLayoutValObject(parts) { + return PlotSchema2.getLayoutValObject(newFullLayout, parts); + } + var diffOpts = { + getValObject: getLayoutValObject, + flags, + immutable, + transition: transition2, + gd + }; + getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts); + if (flags.plot || flags.calc) { + flags.layoutReplot = true; + } + if (transition2 && flags.nChanges && flags.nChangesAnim) { + flags.anim = flags.nChanges === flags.nChangesAnim ? "all" : "some"; + } + return flags; + } + function getDiffFlags(oldContainer, newContainer, outerparts, opts) { + var valObject, key, astr; + var getValObject = opts.getValObject; + var flags = opts.flags; + var immutable = opts.immutable; + var inArray = opts.inArray; + var arrayIndex = opts.arrayIndex; + function changed() { + var editType = valObject.editType; + if (inArray && editType.indexOf("arraydraw") !== -1) { + Lib2.pushUnique(flags.arrays[inArray], arrayIndex); + return; + } + editTypes.update(flags, valObject); + if (editType !== "none") { + flags.nChanges++; + } + if (opts.transition && valObject.anim) { + flags.nChangesAnim++; + } + if (AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) { + flags.rangesAltered[outerparts[0]] = 1; + } + if (AX_DOMAIN_RE.test(astr)) { + nestedProperty3(newContainer, "_inputDomain").set(null); + } + if (key === "datarevision") { + flags.newDataRevision = 1; + } + } + function valObjectCanBeDataArray(valObject2) { + return valObject2.valType === "data_array" || valObject2.arrayOk; + } + for (key in oldContainer) { + if (flags.calc && !opts.transition) return; + var oldVal = oldContainer[key]; + var newVal = newContainer[key]; + var parts = outerparts.concat(key); + astr = parts.join("."); + if (key.charAt(0) === "_" || typeof oldVal === "function" || oldVal === newVal) continue; + if ((key === "tick0" || key === "dtick") && outerparts[0] !== "geo") { + var tickMode = newContainer.tickmode; + if (tickMode === "auto" || tickMode === "array" || !tickMode) continue; + } + if (key === "range" && newContainer.autorange) continue; + if ((key === "zmin" || key === "zmax") && newContainer.type === "contourcarpet") continue; + valObject = getValObject(parts); + if (!valObject) continue; + if (valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue; + var valType = valObject.valType; + var i; + var canBeDataArray = valObjectCanBeDataArray(valObject); + var wasArray = Array.isArray(oldVal); + var nowArray = Array.isArray(newVal); + if (wasArray && nowArray) { + var inputKey = "_input_" + key; + var oldValIn = oldContainer[inputKey]; + var newValIn = newContainer[inputKey]; + if (Array.isArray(oldValIn) && oldValIn === newValIn) continue; + } + if (newVal === void 0) { + if (canBeDataArray && wasArray) flags.calc = true; + else changed(); + } else if (valObject._isLinkedToArray) { + var arrayEditIndices = []; + var extraIndices = false; + if (!inArray) flags.arrays[key] = arrayEditIndices; + var minLen = Math.min(oldVal.length, newVal.length); + var maxLen = Math.max(oldVal.length, newVal.length); + if (minLen !== maxLen) { + if (valObject.editType === "arraydraw") { + extraIndices = true; + } else { + changed(); + continue; + } + } + for (i = 0; i < minLen; i++) { + getDiffFlags( + oldVal[i], + newVal[i], + parts.concat(i), + // add array indices, but not if we're already in an array + Lib2.extendFlat({ inArray: key, arrayIndex: i }, opts) + ); + } + if (extraIndices) { + for (i = minLen; i < maxLen; i++) { + arrayEditIndices.push(i); + } + } + } else if (!valType && Lib2.isPlainObject(oldVal)) { + getDiffFlags(oldVal, newVal, parts, opts); + } else if (canBeDataArray) { + if (wasArray && nowArray) { + if (immutable) { + flags.calc = true; + } + if (immutable || opts.newDataRevision) { + changed(); + } + } else if (wasArray !== nowArray) { + flags.calc = true; + } else changed(); + } else if (wasArray && nowArray) { + if (oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) { + changed(); + } + } else { + changed(); + } + } + for (key in newContainer) { + if (!(key in oldContainer || key.charAt(0) === "_" || typeof newContainer[key] === "function")) { + valObject = getValObject(outerparts.concat(key)); + if (valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) { + flags.calc = true; + return; + } else changed(); + } + } + } + function diffConfig(oldConfig, newConfig) { + var key; + for (key in oldConfig) { + if (key.charAt(0) === "_") continue; + var oldVal = oldConfig[key]; + var newVal = newConfig[key]; + if (oldVal !== newVal) { + if (Lib2.isPlainObject(oldVal) && Lib2.isPlainObject(newVal)) { + if (diffConfig(oldVal, newVal)) { + return true; + } + } else if (Array.isArray(oldVal) && Array.isArray(newVal)) { + if (oldVal.length !== newVal.length) { + return true; + } + for (var i = 0; i < oldVal.length; i++) { + if (oldVal[i] !== newVal[i]) { + if (Lib2.isPlainObject(oldVal[i]) && Lib2.isPlainObject(newVal[i])) { + if (diffConfig(oldVal[i], newVal[i])) { + return true; + } + } else { + return true; + } + } + } + } else { + return true; + } + } + } + } + function animate(gd, frameOrGroupNameOrFrameList, animationOpts) { + gd = Lib2.getGraphDiv(gd); + if (!Lib2.isPlotDiv(gd)) { + throw new Error( + "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before animating it. For more details, see https://plotly.com/javascript/animations/" + ); + } + var trans = gd._transitionData; + if (!trans._frameQueue) { + trans._frameQueue = []; + } + animationOpts = Plots2.supplyAnimationDefaults(animationOpts); + var transitionOpts = animationOpts.transition; + var frameOpts = animationOpts.frame; + if (trans._frameWaitingCnt === void 0) { + trans._frameWaitingCnt = 0; + } + function getTransitionOpts(i) { + if (Array.isArray(transitionOpts)) { + if (i >= transitionOpts.length) { + return transitionOpts[0]; + } else { + return transitionOpts[i]; + } + } else { + return transitionOpts; + } + } + function getFrameOpts(i) { + if (Array.isArray(frameOpts)) { + if (i >= frameOpts.length) { + return frameOpts[0]; + } else { + return frameOpts[i]; + } + } else { + return frameOpts; + } + } + function callbackOnNthTime(cb, n) { + var cnt = 0; + return function() { + if (cb && ++cnt === n) { + return cb(); + } + }; + } + return new Promise(function(resolve, reject) { + function discardExistingFrames() { + if (trans._frameQueue.length === 0) { + return; + } + while (trans._frameQueue.length) { + var next = trans._frameQueue.pop(); + if (next.onInterrupt) { + next.onInterrupt(); + } + } + gd.emit("plotly_animationinterrupted", []); + } + function queueFrames(frameList2) { + if (frameList2.length === 0) return; + for (var i2 = 0; i2 < frameList2.length; i2++) { + var computedFrame; + if (frameList2[i2].type === "byname") { + computedFrame = Plots2.computeFrame(gd, frameList2[i2].name); + } else { + computedFrame = frameList2[i2].data; + } + var frameOpts2 = getFrameOpts(i2); + var transitionOpts2 = getTransitionOpts(i2); + transitionOpts2.duration = Math.min(transitionOpts2.duration, frameOpts2.duration); + var nextFrame2 = { + frame: computedFrame, + name: frameList2[i2].name, + frameOpts: frameOpts2, + transitionOpts: transitionOpts2 + }; + if (i2 === frameList2.length - 1) { + nextFrame2.onComplete = callbackOnNthTime(resolve, 2); + nextFrame2.onInterrupt = reject; + } + trans._frameQueue.push(nextFrame2); + } + if (animationOpts.mode === "immediate") { + trans._lastFrameAt = -Infinity; + } + if (!trans._animationRaf) { + beginAnimationLoop(); + } + } + function stopAnimationLoop() { + gd.emit("plotly_animated"); + window.cancelAnimationFrame(trans._animationRaf); + trans._animationRaf = null; + } + function nextFrame() { + if (trans._currentFrame && trans._currentFrame.onComplete) { + trans._currentFrame.onComplete(); + } + var newFrame = trans._currentFrame = trans._frameQueue.shift(); + if (newFrame) { + var stringName = newFrame.name ? newFrame.name.toString() : null; + gd._fullLayout._currentFrame = stringName; + trans._lastFrameAt = Date.now(); + trans._timeToNext = newFrame.frameOpts.duration; + Plots2.transition( + gd, + newFrame.frame.data, + newFrame.frame.layout, + helpers2.coerceTraceIndices(gd, newFrame.frame.traces), + newFrame.frameOpts, + newFrame.transitionOpts + ).then(function() { + if (newFrame.onComplete) { + newFrame.onComplete(); + } + }); + gd.emit("plotly_animatingframe", { + name: stringName, + frame: newFrame.frame, + animation: { + frame: newFrame.frameOpts, + transition: newFrame.transitionOpts + } + }); + } else { + stopAnimationLoop(); + } + } + function beginAnimationLoop() { + gd.emit("plotly_animating"); + trans._lastFrameAt = -Infinity; + trans._timeToNext = 0; + trans._runningTransitions = 0; + trans._currentFrame = null; + var doFrame = function() { + trans._animationRaf = window.requestAnimationFrame(doFrame); + if (Date.now() - trans._lastFrameAt > trans._timeToNext) { + nextFrame(); + } + }; + doFrame(); + } + var configCounter = 0; + function setTransitionConfig(frame2) { + if (Array.isArray(transitionOpts)) { + if (configCounter >= transitionOpts.length) { + frame2.transitionOpts = transitionOpts[configCounter]; + } else { + frame2.transitionOpts = transitionOpts[0]; + } + } else { + frame2.transitionOpts = transitionOpts; + } + configCounter++; + return frame2; + } + var i, frame; + var frameList = []; + var allFrames = frameOrGroupNameOrFrameList === void 0 || frameOrGroupNameOrFrameList === null; + var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); + var isSingleFrame = !allFrames && !isFrameArray && Lib2.isPlainObject(frameOrGroupNameOrFrameList); + if (isSingleFrame) { + frameList.push({ + type: "object", + data: setTransitionConfig(Lib2.extendFlat({}, frameOrGroupNameOrFrameList)) + }); + } else if (allFrames || ["string", "number"].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { + for (i = 0; i < trans._frames.length; i++) { + frame = trans._frames[i]; + if (!frame) continue; + if (allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) { + frameList.push({ + type: "byname", + name: String(frame.name), + data: setTransitionConfig({ name: frame.name }) + }); + } + } + } else if (isFrameArray) { + for (i = 0; i < frameOrGroupNameOrFrameList.length; i++) { + var frameOrName = frameOrGroupNameOrFrameList[i]; + if (["number", "string"].indexOf(typeof frameOrName) !== -1) { + frameOrName = String(frameOrName); + frameList.push({ + type: "byname", + name: frameOrName, + data: setTransitionConfig({ name: frameOrName }) + }); + } else if (Lib2.isPlainObject(frameOrName)) { + frameList.push({ + type: "object", + data: setTransitionConfig(Lib2.extendFlat({}, frameOrName)) + }); + } + } + } + for (i = 0; i < frameList.length; i++) { + frame = frameList[i]; + if (frame.type === "byname" && !trans._frameHash[frame.data.name]) { + Lib2.warn('animate failure: frame not found: "' + frame.data.name + '"'); + reject(); + return; + } + } + if (["next", "immediate"].indexOf(animationOpts.mode) !== -1) { + discardExistingFrames(); + } + if (animationOpts.direction === "reverse") { + frameList.reverse(); + } + var currentFrame = gd._fullLayout._currentFrame; + if (currentFrame && animationOpts.fromcurrent) { + var idx = -1; + for (i = 0; i < frameList.length; i++) { + frame = frameList[i]; + if (frame.type === "byname" && frame.name === currentFrame) { + idx = i; + break; + } + } + if (idx > 0 && idx < frameList.length - 1) { + var filteredFrameList = []; + for (i = 0; i < frameList.length; i++) { + frame = frameList[i]; + if (frameList[i].type !== "byname" || i > idx) { + filteredFrameList.push(frame); + } + } + frameList = filteredFrameList; + } + } + if (frameList.length > 0) { + queueFrames(frameList); + } else { + gd.emit("plotly_animated"); + resolve(); + } + }); + } + function addFrames(gd, frameList, indices) { + gd = Lib2.getGraphDiv(gd); + if (frameList === null || frameList === void 0) { + return Promise.resolve(); + } + if (!Lib2.isPlotDiv(gd)) { + throw new Error( + "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before adding frames. For more details, see https://plotly.com/javascript/animations/" + ); + } + var i, frame, j, idx; + var _frames = gd._transitionData._frames; + var _frameHash = gd._transitionData._frameHash; + if (!Array.isArray(frameList)) { + throw new Error("addFrames failure: frameList must be an Array of frame definitions" + frameList); + } + var bigIndex = _frames.length + frameList.length * 2; + var insertions = []; + var _frameHashLocal = {}; + for (i = frameList.length - 1; i >= 0; i--) { + if (!Lib2.isPlainObject(frameList[i])) continue; + var lookupName = frameList[i].name; + var name2 = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name; + var newName = frameList[i].name; + var collisionPresent = _frameHash[name2] || _frameHashLocal[name2]; + if (name2 && newName && typeof newName === "number" && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { + numericNameWarningCount++; + Lib2.warn('addFrames: overwriting frame "' + (_frameHash[name2] || _frameHashLocal[name2]).name + '" with a frame whose name of type "number" also equates to "' + name2 + '". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'); + if (numericNameWarningCount === numericNameWarningCountLimit) { + Lib2.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed."); + } + } + _frameHashLocal[lookupName] = { name: lookupName }; + insertions.push({ + frame: Plots2.supplyFrameDefaults(frameList[i]), + index: indices && indices[i] !== void 0 && indices[i] !== null ? indices[i] : bigIndex + i + }); + } + insertions.sort(function(a, b) { + if (a.index > b.index) return -1; + if (a.index < b.index) return 1; + return 0; + }); + var ops = []; + var revops = []; + var frameCount = _frames.length; + for (i = insertions.length - 1; i >= 0; i--) { + frame = insertions[i].frame; + if (typeof frame.name === "number") { + Lib2.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"); + } + if (!frame.name) { + while (_frameHash[frame.name = "frame " + gd._transitionData._counter++]) ; + } + if (_frameHash[frame.name]) { + for (j = 0; j < _frames.length; j++) { + if ((_frames[j] || {}).name === frame.name) break; + } + ops.push({ type: "replace", index: j, value: frame }); + revops.unshift({ type: "replace", index: j, value: _frames[j] }); + } else { + idx = Math.max(0, Math.min(insertions[i].index, frameCount)); + ops.push({ type: "insert", index: idx, value: frame }); + revops.unshift({ type: "delete", index: idx }); + frameCount++; + } + } + var undoFunc = Plots2.modifyFrames; + var redoFunc = Plots2.modifyFrames; + var undoArgs = [gd, revops]; + var redoArgs = [gd, ops]; + if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + return Plots2.modifyFrames(gd, ops); + } + function deleteFrames(gd, frameList) { + gd = Lib2.getGraphDiv(gd); + if (!Lib2.isPlotDiv(gd)) { + throw new Error("This element is not a Plotly plot: " + gd); + } + var i, idx; + var _frames = gd._transitionData._frames; + var ops = []; + var revops = []; + if (!frameList) { + frameList = []; + for (i = 0; i < _frames.length; i++) { + frameList.push(i); + } + } + frameList = frameList.slice(); + frameList.sort(); + for (i = frameList.length - 1; i >= 0; i--) { + idx = frameList[i]; + ops.push({ type: "delete", index: idx }); + revops.unshift({ type: "insert", index: idx, value: _frames[idx] }); + } + var undoFunc = Plots2.modifyFrames; + var redoFunc = Plots2.modifyFrames; + var undoArgs = [gd, revops]; + var redoArgs = [gd, ops]; + if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); + return Plots2.modifyFrames(gd, ops); + } + function purge(gd) { + gd = Lib2.getGraphDiv(gd); + var fullLayout = gd._fullLayout || {}; + var fullData = gd._fullData || []; + Plots2.cleanPlot([], {}, fullData, fullLayout); + Plots2.purge(gd); + Events2.purge(gd); + if (fullLayout._container) fullLayout._container.remove(); + delete gd._context; + return gd; + } + function calcInverseTransform(gd) { + var fullLayout = gd._fullLayout; + var newBBox = gd.getBoundingClientRect(); + if (Lib2.equalDomRects(newBBox, fullLayout._lastBBox)) return; + var m = fullLayout._invTransform = Lib2.inverseTransformMatrix(Lib2.getFullTransformMatrix(gd)); + fullLayout._invScaleX = Math.sqrt(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]); + fullLayout._invScaleY = Math.sqrt(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]); + fullLayout._lastBBox = newBBox; + } + function makePlotFramework(gd) { + var gd3 = d32.select(gd); + var fullLayout = gd._fullLayout; + fullLayout._calcInverseTransform = calcInverseTransform; + fullLayout._calcInverseTransform(gd); + fullLayout._container = gd3.selectAll(".plot-container").data([0]); + fullLayout._container.enter().insert("div", ":first-child").classed("plot-container", true).classed("plotly", true).style({ + width: "100%", + height: "100%" + }); + fullLayout._paperdiv = fullLayout._container.selectAll(".svg-container").data([0]); + fullLayout._paperdiv.enter().append("div").classed("user-select-none", true).classed("svg-container", true).style("position", "relative"); + fullLayout._glcontainer = fullLayout._paperdiv.selectAll(".gl-container").data([{}]); + fullLayout._glcontainer.enter().append("div").classed("gl-container", true); + fullLayout._paperdiv.selectAll(".main-svg").remove(); + fullLayout._paperdiv.select(".modebar-container").remove(); + fullLayout._paper = fullLayout._paperdiv.insert("svg", ":first-child").classed("main-svg", true); + fullLayout._toppaper = fullLayout._paperdiv.append("svg").classed("main-svg", true); + fullLayout._modebardiv = fullLayout._paperdiv.append("div"); + delete fullLayout._modeBar; + fullLayout._hoverpaper = fullLayout._paperdiv.append("svg").classed("main-svg", true); + if (!fullLayout._uid) { + var otherUids = {}; + d32.selectAll("defs").each(function() { + if (this.id) otherUids[this.id.split("-")[1]] = 1; + }); + fullLayout._uid = Lib2.randstr(otherUids); + } + fullLayout._paperdiv.selectAll(".main-svg").attr(xmlnsNamespaces2.svgAttrs); + fullLayout._defs = fullLayout._paper.append("defs").attr("id", "defs-" + fullLayout._uid); + fullLayout._clips = fullLayout._defs.append("g").classed("clips", true); + fullLayout._topdefs = fullLayout._toppaper.append("defs").attr("id", "topdefs-" + fullLayout._uid); + fullLayout._topclips = fullLayout._topdefs.append("g").classed("clips", true); + fullLayout._bgLayer = fullLayout._paper.append("g").classed("bglayer", true); + fullLayout._draggers = fullLayout._paper.append("g").classed("draglayer", true); + var layerBelow = fullLayout._paper.append("g").classed("layer-below", true); + fullLayout._imageLowerLayer = layerBelow.append("g").classed("imagelayer", true); + fullLayout._shapeLowerLayer = layerBelow.append("g").classed("shapelayer", true); + fullLayout._cartesianlayer = fullLayout._paper.append("g").classed("cartesianlayer", true); + fullLayout._polarlayer = fullLayout._paper.append("g").classed("polarlayer", true); + fullLayout._smithlayer = fullLayout._paper.append("g").classed("smithlayer", true); + fullLayout._ternarylayer = fullLayout._paper.append("g").classed("ternarylayer", true); + fullLayout._geolayer = fullLayout._paper.append("g").classed("geolayer", true); + fullLayout._funnelarealayer = fullLayout._paper.append("g").classed("funnelarealayer", true); + fullLayout._pielayer = fullLayout._paper.append("g").classed("pielayer", true); + fullLayout._iciclelayer = fullLayout._paper.append("g").classed("iciclelayer", true); + fullLayout._treemaplayer = fullLayout._paper.append("g").classed("treemaplayer", true); + fullLayout._sunburstlayer = fullLayout._paper.append("g").classed("sunburstlayer", true); + fullLayout._indicatorlayer = fullLayout._toppaper.append("g").classed("indicatorlayer", true); + fullLayout._glimages = fullLayout._paper.append("g").classed("glimages", true); + var layerAbove = fullLayout._toppaper.append("g").classed("layer-above", true); + fullLayout._imageUpperLayer = layerAbove.append("g").classed("imagelayer", true); + fullLayout._shapeUpperLayer = layerAbove.append("g").classed("shapelayer", true); + fullLayout._selectionLayer = fullLayout._toppaper.append("g").classed("selectionlayer", true); + fullLayout._infolayer = fullLayout._toppaper.append("g").classed("infolayer", true); + fullLayout._menulayer = fullLayout._toppaper.append("g").classed("menulayer", true); + fullLayout._zoomlayer = fullLayout._toppaper.append("g").classed("zoomlayer", true); + fullLayout._hoverlayer = fullLayout._hoverpaper.append("g").classed("hoverlayer", true); + fullLayout._modebardiv.classed("modebar-container", true).style("position", "absolute").style("top", "0px").style("right", "0px"); + gd.emit("plotly_framework"); + } + exports2.animate = animate; + exports2.addFrames = addFrames; + exports2.deleteFrames = deleteFrames; + exports2.addTraces = addTraces; + exports2.deleteTraces = deleteTraces; + exports2.extendTraces = extendTraces; + exports2.moveTraces = moveTraces; + exports2.prependTraces = prependTraces; + exports2.newPlot = newPlot; + exports2._doPlot = _doPlot; + exports2.purge = purge; + exports2.react = react; + exports2.redraw = redraw; + exports2.relayout = relayout; + exports2.restyle = restyle; + exports2.setPlotConfig = setPlotConfig; + exports2.update = update2; + exports2._guiRelayout = guiEdit(relayout); + exports2._guiRestyle = guiEdit(restyle); + exports2._guiUpdate = guiEdit(update2); + exports2._storeDirectGUIEdit = _storeDirectGUIEdit; +})(plot_api); +var helpers$o = {}; +var Registry$r = registry; +helpers$o.getDelay = function(fullLayout) { + if (!fullLayout._has) return 0; + return fullLayout._has("gl3d") || fullLayout._has("gl2d") || fullLayout._has("mapbox") || fullLayout._has("map") ? 500 : 0; +}; +helpers$o.getRedrawFunc = function(gd) { + return function() { + Registry$r.getComponentMethod("colorbar", "draw")(gd); + }; +}; +helpers$o.encodeSVG = function(svg) { + return "data:image/svg+xml," + encodeURIComponent(svg); +}; +helpers$o.encodeJSON = function(json) { + return "data:application/json," + encodeURIComponent(json); +}; +var DOM_URL = window.URL || window.webkitURL; +helpers$o.createObjectURL = function(blob) { + return DOM_URL.createObjectURL(blob); +}; +helpers$o.revokeObjectURL = function(url) { + return DOM_URL.revokeObjectURL(url); +}; +helpers$o.createBlob = function(url, format2) { + if (format2 === "svg") { + return new window.Blob([url], { type: "image/svg+xml;charset=utf-8" }); + } else if (format2 === "full-json") { + return new window.Blob([url], { type: "application/json;charset=utf-8" }); + } else { + var binary2 = fixBinary(window.atob(url)); + return new window.Blob([binary2], { type: "image/" + format2 }); + } +}; +helpers$o.octetStream = function(s) { + document.location.href = "data:application/octet-stream" + s; +}; +function fixBinary(b) { + var len = b.length; + var buf = new ArrayBuffer(len); + var arr = new Uint8Array(buf); + for (var i = 0; i < len; i++) { + arr[i] = b.charCodeAt(i); + } + return buf; +} +helpers$o.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/; +helpers$o.MSG_IE_BAD_FORMAT = "Sorry IE does not support downloading from canvas. Try {format:'svg'} instead."; +var d3$o = d3Exports; +var Lib$1g = libExports; +var Drawing$j = drawingExports; +var Color$v = colorExports; +var xmlnsNamespaces$2 = xmlns_namespaces; +var DOUBLEQUOTE_REGEX = /"/g; +var DUMMY_SUB = "TOBESTRIPPED"; +var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ")|(" + DUMMY_SUB + '")', "g"); +function htmlEntityDecode(s) { + var hiddenDiv = d3$o.select("body").append("div").style({ display: "none" }).html(""); + var replaced = s.replace(/(&[^;]*;)/gi, function(d) { + if (d === "<") { + return "<"; + } + if (d === "&rt;") { + return ">"; + } + if (d.indexOf("<") !== -1 || d.indexOf(">") !== -1) { + return ""; + } + return hiddenDiv.html(d).text(); + }); + hiddenDiv.remove(); + return replaced; +} +function xmlEntityEncode(str2) { + return str2.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, "&"); +} +var tosvg = function toSVG(gd, format2, scale2) { + var fullLayout = gd._fullLayout; + var svg = fullLayout._paper; + var toppaper = fullLayout._toppaper; + var width = fullLayout.width; + var height = fullLayout.height; + var i; + svg.insert("rect", ":first-child").call(Drawing$j.setRect, 0, 0, width, height).call(Color$v.fill, fullLayout.paper_bgcolor); + var basePlotModules = fullLayout._basePlotModules || []; + for (i = 0; i < basePlotModules.length; i++) { + var _module = basePlotModules[i]; + if (_module.toSVG) _module.toSVG(gd); + } + if (toppaper) { + var nodes = toppaper.node().childNodes; + var topGroups = Array.prototype.slice.call(nodes); + for (i = 0; i < topGroups.length; i++) { + var topGroup = topGroups[i]; + if (topGroup.childNodes.length) svg.node().appendChild(topGroup); + } + } + if (fullLayout._draggers) { + fullLayout._draggers.remove(); + } + svg.node().style.background = ""; + svg.selectAll("text").attr({ "data-unformatted": null, "data-math": null }).each(function() { + var txt = d3$o.select(this); + if (this.style.visibility === "hidden" || this.style.display === "none") { + txt.remove(); + return; + } else { + txt.style({ visibility: null, display: null }); + } + var ff = this.style.fontFamily; + if (ff && ff.indexOf('"') !== -1) { + txt.style("font-family", ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); + } + var fw = this.style.fontWeight; + if (fw && (fw === "normal" || fw === "400")) { + txt.style("font-weight", void 0); + } + var fs = this.style.fontStyle; + if (fs && fs === "normal") { + txt.style("font-style", void 0); + } + var fv = this.style.fontVariant; + if (fv && fv === "normal") { + txt.style("font-variant", void 0); + } + }); + svg.selectAll(".gradient_filled,.pattern_filled").each(function() { + var pt = d3$o.select(this); + var fill = this.style.fill; + if (fill && fill.indexOf("url(") !== -1) { + pt.style("fill", fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); + } + var stroke = this.style.stroke; + if (stroke && stroke.indexOf("url(") !== -1) { + pt.style("stroke", stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); + } + }); + if (format2 === "pdf" || format2 === "eps") { + svg.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width", 0); + } + svg.node().setAttributeNS(xmlnsNamespaces$2.xmlns, "xmlns", xmlnsNamespaces$2.svg); + svg.node().setAttributeNS(xmlnsNamespaces$2.xmlns, "xmlns:xlink", xmlnsNamespaces$2.xlink); + if (format2 === "svg" && scale2) { + svg.attr("width", scale2 * width); + svg.attr("height", scale2 * height); + svg.attr("viewBox", "0 0 " + width + " " + height); + } + var s = new window.XMLSerializer().serializeToString(svg.node()); + s = htmlEntityDecode(s); + s = xmlEntityEncode(s); + s = s.replace(DUMMY_REGEX, "'"); + if (Lib$1g.isIE()) { + s = s.replace(/"/gi, "'"); + s = s.replace(/(\('#)([^']*)('\))/gi, '("#$2")'); + s = s.replace(/(\\')/gi, '"'); + } + return s; +}; +var Lib$1f = libExports; +var EventEmitter$1 = eventsExports.EventEmitter; +var helpers$n = helpers$o; +function svgToImg$2(opts) { + var ev = opts.emitter || new EventEmitter$1(); + var promise = new Promise(function(resolve, reject) { + var Image2 = window.Image; + var svg = opts.svg; + var format2 = opts.format || "png"; + if (Lib$1f.isIE() && format2 !== "svg") { + var ieSvgError = new Error(helpers$n.MSG_IE_BAD_FORMAT); + reject(ieSvgError); + if (!opts.promise) { + return ev.emit("error", ieSvgError); + } else { + return promise; + } + } + var canvas2 = opts.canvas; + var scale2 = opts.scale || 1; + var w0 = opts.width || 300; + var h0 = opts.height || 150; + var w1 = scale2 * w0; + var h1 = scale2 * h0; + var ctx2 = canvas2.getContext("2d", { willReadFrequently: true }); + var img = new Image2(); + var svgBlob, url; + if (format2 === "svg" || Lib$1f.isSafari()) { + url = helpers$n.encodeSVG(svg); + } else { + svgBlob = helpers$n.createBlob(svg, "svg"); + url = helpers$n.createObjectURL(svgBlob); + } + canvas2.width = w1; + canvas2.height = h1; + img.onload = function() { + var imgData; + svgBlob = null; + helpers$n.revokeObjectURL(url); + if (format2 !== "svg") { + ctx2.drawImage(img, 0, 0, w1, h1); + } + switch (format2) { + case "jpeg": + imgData = canvas2.toDataURL("image/jpeg"); + break; + case "png": + imgData = canvas2.toDataURL("image/png"); + break; + case "webp": + imgData = canvas2.toDataURL("image/webp"); + break; + case "svg": + imgData = url; + break; + default: + var errorMsg = "Image format is not jpeg, png, svg or webp."; + reject(new Error(errorMsg)); + if (!opts.promise) { + return ev.emit("error", errorMsg); + } + } + resolve(imgData); + if (!opts.promise) { + ev.emit("success", imgData); + } + }; + img.onerror = function(err) { + svgBlob = null; + helpers$n.revokeObjectURL(url); + reject(err); + if (!opts.promise) { + return ev.emit("error", err); + } + }; + img.src = url; + }); + if (opts.promise) { + return promise; + } + return ev; +} +var svgtoimg = svgToImg$2; +var isNumeric$g = fastIsnumeric; +var plotApi = plot_api; +var plots = plotsExports; +var Lib$1e = libExports; +var helpers$m = helpers$o; +var toSVG$1 = tosvg; +var svgToImg$1 = svgtoimg; +var version = version$2.version; +var attrs$2 = { + format: { + valType: "enumerated", + values: ["png", "jpeg", "webp", "svg", "full-json"], + dflt: "png", + description: "Sets the format of exported image." + }, + width: { + valType: "number", + min: 1, + description: [ + "Sets the exported image width.", + "Defaults to the value found in `layout.width`", + "If set to *null*, the exported image width will match the current graph width." + ].join(" ") + }, + height: { + valType: "number", + min: 1, + description: [ + "Sets the exported image height.", + "Defaults to the value found in `layout.height`", + "If set to *null*, the exported image height will match the current graph height." + ].join(" ") + }, + scale: { + valType: "number", + min: 0, + dflt: 1, + description: [ + "Sets a scaling for the generated image.", + "If set, all features of a graphs (e.g. text, line width)", + "are scaled, unlike simply setting", + "a bigger *width* and *height*." + ].join(" ") + }, + setBackground: { + valType: "any", + dflt: false, + description: [ + "Sets the image background mode.", + "By default, the image background is determined by `layout.paper_bgcolor`,", + "the *transparent* mode.", + "One might consider setting `setBackground` to *opaque*", + "when exporting a *jpeg* image as JPEGs do not support opacity." + ].join(" ") + }, + imageDataOnly: { + valType: "boolean", + dflt: false, + description: [ + "Determines whether or not the return value is prefixed by", + "the image format's corresponding 'data:image;' spec." + ].join(" ") + } +}; +function toImage$2(gd, opts) { + opts = opts || {}; + var data; + var layout; + var config; + var fullLayout; + if (Lib$1e.isPlainObject(gd)) { + data = gd.data || []; + layout = gd.layout || {}; + config = gd.config || {}; + fullLayout = {}; + } else { + gd = Lib$1e.getGraphDiv(gd); + data = Lib$1e.extendDeep([], gd.data); + layout = Lib$1e.extendDeep({}, gd.layout); + config = gd._context; + fullLayout = gd._fullLayout || {}; + } + function isImpliedOrValid(attr) { + return !(attr in opts) || Lib$1e.validate(opts[attr], attrs$2[attr]); + } + if (!isImpliedOrValid("width") && opts.width !== null || !isImpliedOrValid("height") && opts.height !== null) { + throw new Error("Height and width should be pixel values."); + } + if (!isImpliedOrValid("format")) { + throw new Error("Export format is not " + Lib$1e.join2(attrs$2.format.values, ", ", " or ") + "."); + } + var fullOpts = {}; + function coerce2(attr, dflt) { + return Lib$1e.coerce(opts, fullOpts, attrs$2, attr, dflt); + } + var format2 = coerce2("format"); + var width = coerce2("width"); + var height = coerce2("height"); + var scale2 = coerce2("scale"); + var setBackground = coerce2("setBackground"); + var imageDataOnly = coerce2("imageDataOnly"); + var clonedGd = document.createElement("div"); + clonedGd.style.position = "absolute"; + clonedGd.style.left = "-5000px"; + document.body.appendChild(clonedGd); + var layoutImage = Lib$1e.extendFlat({}, layout); + if (width) { + layoutImage.width = width; + } else if (opts.width === null && isNumeric$g(fullLayout.width)) { + layoutImage.width = fullLayout.width; + } + if (height) { + layoutImage.height = height; + } else if (opts.height === null && isNumeric$g(fullLayout.height)) { + layoutImage.height = fullLayout.height; + } + var configImage = Lib$1e.extendFlat({}, config, { + _exportedPlot: true, + staticPlot: true, + setBackground + }); + var redrawFunc = helpers$m.getRedrawFunc(clonedGd); + function wait() { + return new Promise(function(resolve) { + setTimeout(resolve, helpers$m.getDelay(clonedGd._fullLayout)); + }); + } + function convert3() { + return new Promise(function(resolve, reject) { + var svg = toSVG$1(clonedGd, format2, scale2); + var width2 = clonedGd._fullLayout.width; + var height2 = clonedGd._fullLayout.height; + function cleanup() { + plotApi.purge(clonedGd); + document.body.removeChild(clonedGd); + } + if (format2 === "full-json") { + var json = plots.graphJson(clonedGd, false, "keepdata", "object", true, true); + json.version = version; + json = JSON.stringify(json); + cleanup(); + if (imageDataOnly) { + return resolve(json); + } else { + return resolve(helpers$m.encodeJSON(json)); + } + } + cleanup(); + if (format2 === "svg") { + if (imageDataOnly) { + return resolve(svg); + } else { + return resolve(helpers$m.encodeSVG(svg)); + } + } + var canvas2 = document.createElement("canvas"); + canvas2.id = Lib$1e.randstr(); + svgToImg$1({ + format: format2, + width: width2, + height: height2, + scale: scale2, + canvas: canvas2, + svg, + // ask svgToImg to return a Promise + // rather than EventEmitter + // leave EventEmitter for backward + // compatibility + promise: true + }).then(resolve).catch(reject); + }); + } + function urlToImageData(url) { + if (imageDataOnly) { + return url.replace(helpers$m.IMAGE_URL_PREFIX, ""); + } else { + return url; + } + } + return new Promise(function(resolve, reject) { + plotApi.newPlot(clonedGd, data, layoutImage, configImage).then(redrawFunc).then(wait).then(convert3).then(function(url) { + resolve(urlToImageData(url)); + }).catch(function(err) { + reject(err); + }); + }); +} +var to_image = toImage$2; +var Lib$1d = libExports; +var Plots$8 = plotsExports; +var PlotSchema$1 = plot_schema; +var dfltConfig$1 = plot_config.dfltConfig; +var isPlainObject$1 = Lib$1d.isPlainObject; +var isArray = Array.isArray; +var isArrayOrTypedArray$6 = Lib$1d.isArrayOrTypedArray; +var validate = function validate2(data, layout) { + if (data === void 0) data = []; + if (layout === void 0) layout = {}; + var schema = PlotSchema$1.get(); + var errorList = []; + var gd = { _context: Lib$1d.extendFlat({}, dfltConfig$1) }; + var dataIn, layoutIn; + if (isArray(data)) { + gd.data = Lib$1d.extendDeep([], data); + dataIn = data; + } else { + gd.data = []; + dataIn = []; + errorList.push(format$1("array", "data")); + } + if (isPlainObject$1(layout)) { + gd.layout = Lib$1d.extendDeep({}, layout); + layoutIn = layout; + } else { + gd.layout = {}; + layoutIn = {}; + if (arguments.length > 1) { + errorList.push(format$1("object", "layout")); + } + } + Plots$8.supplyDefaults(gd); + var dataOut = gd._fullData; + var len = dataIn.length; + for (var i = 0; i < len; i++) { + var traceIn = dataIn[i]; + var base = ["data", i]; + if (!isPlainObject$1(traceIn)) { + errorList.push(format$1("object", base)); + continue; + } + var traceOut = dataOut[i]; + var traceType = traceOut.type; + var traceSchema = schema.traces[traceType].attributes; + traceSchema.type = { + valType: "enumerated", + values: [traceType] + }; + if (traceOut.visible === false && traceIn.visible !== false) { + errorList.push(format$1("invisible", base)); + } + crawl(traceIn, traceOut, traceSchema, errorList, base); + var transformsIn = traceIn.transforms; + var transformsOut = traceOut.transforms; + if (transformsIn) { + if (!isArray(transformsIn)) { + errorList.push(format$1("array", base, ["transforms"])); + } + base.push("transforms"); + for (var j = 0; j < transformsIn.length; j++) { + var path = ["transforms", j]; + var transformType = transformsIn[j].type; + if (!isPlainObject$1(transformsIn[j])) { + errorList.push(format$1("object", base, path)); + continue; + } + var transformSchema = schema.transforms[transformType] ? schema.transforms[transformType].attributes : {}; + transformSchema.type = { + valType: "enumerated", + values: Object.keys(schema.transforms) + }; + crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); + } + } + } + var layoutOut = gd._fullLayout; + var layoutSchema = fillLayoutSchema(schema, dataOut); + crawl(layoutIn, layoutOut, layoutSchema, errorList, "layout"); + return errorList.length === 0 ? void 0 : errorList; +}; +function crawl(objIn, objOut, schema, list, base, path) { + path = path || []; + var keys = Object.keys(objIn); + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + if (k === "transforms") continue; + var p = path.slice(); + p.push(k); + var valIn = objIn[k]; + var valOut = objOut[k]; + var nestedSchema = getNestedSchema(schema, k); + var nestedValType = (nestedSchema || {}).valType; + var isInfoArray = nestedValType === "info_array"; + var isColorscale = nestedValType === "colorscale"; + var items = (nestedSchema || {}).items; + if (!isInSchema(schema, k)) { + list.push(format$1("schema", base, p)); + } else if (isPlainObject$1(valIn) && isPlainObject$1(valOut) && nestedValType !== "any") { + crawl(valIn, valOut, nestedSchema, list, base, p); + } else if (isInfoArray && isArray(valIn)) { + if (valIn.length > valOut.length) { + list.push(format$1("unused", base, p.concat(valOut.length))); + } + var len = valOut.length; + var arrayItems = Array.isArray(items); + if (arrayItems) len = Math.min(len, items.length); + var m, n, item, valInPart, valOutPart; + if (nestedSchema.dimensions === 2) { + for (n = 0; n < len; n++) { + if (isArray(valIn[n])) { + if (valIn[n].length > valOut[n].length) { + list.push(format$1("unused", base, p.concat(n, valOut[n].length))); + } + var len2 = valOut[n].length; + for (m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) { + item = arrayItems ? items[n][m] : items; + valInPart = valIn[n][m]; + valOutPart = valOut[n][m]; + if (!Lib$1d.validate(valInPart, item)) { + list.push(format$1("value", base, p.concat(n, m), valInPart)); + } else if (valOutPart !== valInPart && valOutPart !== +valInPart) { + list.push(format$1("dynamic", base, p.concat(n, m), valInPart, valOutPart)); + } + } + } else { + list.push(format$1("array", base, p.concat(n), valIn[n])); + } + } + } else { + for (n = 0; n < len; n++) { + item = arrayItems ? items[n] : items; + valInPart = valIn[n]; + valOutPart = valOut[n]; + if (!Lib$1d.validate(valInPart, item)) { + list.push(format$1("value", base, p.concat(n), valInPart)); + } else if (valOutPart !== valInPart && valOutPart !== +valInPart) { + list.push(format$1("dynamic", base, p.concat(n), valInPart, valOutPart)); + } + } + } + } else if (nestedSchema.items && !isInfoArray && isArray(valIn)) { + var _nestedSchema = items[Object.keys(items)[0]]; + var indexList = []; + var j, _p; + for (j = 0; j < valOut.length; j++) { + var _index = valOut[j]._index || j; + _p = p.slice(); + _p.push(_index); + if (isPlainObject$1(valIn[_index]) && isPlainObject$1(valOut[j])) { + indexList.push(_index); + var valInj = valIn[_index]; + var valOutj = valOut[j]; + if (isPlainObject$1(valInj) && valInj.visible !== false && valOutj.visible === false) { + list.push(format$1("invisible", base, _p)); + } else crawl(valInj, valOutj, _nestedSchema, list, base, _p); + } + } + for (j = 0; j < valIn.length; j++) { + _p = p.slice(); + _p.push(j); + if (!isPlainObject$1(valIn[j])) { + list.push(format$1("object", base, _p, valIn[j])); + } else if (indexList.indexOf(j) === -1) { + list.push(format$1("unused", base, _p)); + } + } + } else if (!isPlainObject$1(valIn) && isPlainObject$1(valOut)) { + list.push(format$1("object", base, p, valIn)); + } else if (!isArrayOrTypedArray$6(valIn) && isArrayOrTypedArray$6(valOut) && !isInfoArray && !isColorscale) { + list.push(format$1("array", base, p, valIn)); + } else if (!(k in objOut)) { + list.push(format$1("unused", base, p, valIn)); + } else if (!Lib$1d.validate(valIn, nestedSchema)) { + list.push(format$1("value", base, p, valIn)); + } else if (nestedSchema.valType === "enumerated" && (nestedSchema.coerceNumber && valIn !== +valOut || valIn !== valOut)) { + list.push(format$1("dynamic", base, p, valIn, valOut)); + } + } + return list; +} +function fillLayoutSchema(schema, dataOut) { + var layoutSchema = schema.layout.layoutAttributes; + for (var i = 0; i < dataOut.length; i++) { + var traceOut = dataOut[i]; + var traceSchema = schema.traces[traceOut.type]; + var traceLayoutAttr = traceSchema.layoutAttributes; + if (traceLayoutAttr) { + if (traceOut.subplot) { + Lib$1d.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr); + } else { + Lib$1d.extendFlat(layoutSchema, traceLayoutAttr); + } + } + } + return layoutSchema; +} +var code2msgFunc = { + object: function(base, astr) { + var prefix; + if (base === "layout" && astr === "") prefix = "The layout argument"; + else if (base[0] === "data" && astr === "") { + prefix = "Trace " + base[1] + " in the data argument"; + } else prefix = inBase(base) + "key " + astr; + return prefix + " must be linked to an object container"; + }, + array: function(base, astr) { + var prefix; + if (base === "data") prefix = "The data argument"; + else prefix = inBase(base) + "key " + astr; + return prefix + " must be linked to an array container"; + }, + schema: function(base, astr) { + return inBase(base) + "key " + astr + " is not part of the schema"; + }, + unused: function(base, astr, valIn) { + var target = isPlainObject$1(valIn) ? "container" : "key"; + return inBase(base) + target + " " + astr + " did not get coerced"; + }, + dynamic: function(base, astr, valIn, valOut) { + return [ + inBase(base) + "key", + astr, + "(set to '" + valIn + "')", + "got reset to", + "'" + valOut + "'", + "during defaults." + ].join(" "); + }, + invisible: function(base, astr) { + return (astr ? inBase(base) + "item " + astr : "Trace " + base[1]) + " got defaulted to be not visible"; + }, + value: function(base, astr, valIn) { + return [ + inBase(base) + "key " + astr, + "is set to an invalid value (" + valIn + ")" + ].join(" "); + } +}; +function inBase(base) { + if (isArray(base)) return "In data trace " + base[1] + ", "; + return "In " + base + ", "; +} +function format$1(code2, base, path, valIn, valOut) { + path = path || ""; + var container, trace; + if (isArray(base)) { + container = base[0]; + trace = base[1]; + } else { + container = base; + trace = null; + } + var astr = convertPathToAttributeString(path); + var msg2 = code2msgFunc[code2](base, astr, valIn, valOut); + Lib$1d.log(msg2); + return { + code: code2, + container, + trace, + path, + astr, + msg: msg2 + }; +} +function isInSchema(schema, key) { + var parts = splitKey(key); + var keyMinusId = parts.keyMinusId; + var id = parts.id; + if (keyMinusId in schema && schema[keyMinusId]._isSubplotObj && id) { + return true; + } + return key in schema; +} +function getNestedSchema(schema, key) { + if (key in schema) return schema[key]; + var parts = splitKey(key); + return schema[parts.keyMinusId]; +} +var idRegex = Lib$1d.counterRegex("([a-z]+)"); +function splitKey(key) { + var idMatch = key.match(idRegex); + return { + keyMinusId: idMatch && idMatch[1], + id: idMatch && idMatch[2] + }; +} +function convertPathToAttributeString(path) { + if (!isArray(path)) return String(path); + var astr = ""; + for (var i = 0; i < path.length; i++) { + var p = path[i]; + if (typeof p === "number") { + astr = astr.substr(0, astr.length - 1) + "[" + p + "]"; + } else { + astr += p; + } + if (i < path.length - 1) astr += "."; + } + return astr; +} +var Lib$1c = libExports; +var helpers$l = helpers$o; +function fileSaver$1(url, name2, format2) { + var saveLink = document.createElement("a"); + var canUseSaveLink = "download" in saveLink; + var promise = new Promise(function(resolve, reject) { + var blob; + var objectUrl; + if (Lib$1c.isIE()) { + blob = helpers$l.createBlob(url, "svg"); + window.navigator.msSaveBlob(blob, name2); + blob = null; + return resolve(name2); + } + if (canUseSaveLink) { + blob = helpers$l.createBlob(url, format2); + objectUrl = helpers$l.createObjectURL(blob); + saveLink.href = objectUrl; + saveLink.download = name2; + document.body.appendChild(saveLink); + saveLink.click(); + document.body.removeChild(saveLink); + helpers$l.revokeObjectURL(objectUrl); + blob = null; + return resolve(name2); + } + if (Lib$1c.isSafari()) { + var prefix = format2 === "svg" ? "," : ";base64,"; + helpers$l.octetStream(prefix + encodeURIComponent(url)); + return resolve(name2); + } + reject(new Error("download error")); + }); + return promise; +} +var filesaver = fileSaver$1; +var Lib$1b = libExports; +var toImage$1 = to_image; +var fileSaver = filesaver; +var helpers$k = helpers$o; +function downloadImage(gd, opts) { + var _gd; + if (!Lib$1b.isPlainObject(gd)) _gd = Lib$1b.getGraphDiv(gd); + opts = opts || {}; + opts.format = opts.format || "png"; + opts.width = opts.width || null; + opts.height = opts.height || null; + opts.imageDataOnly = true; + return new Promise(function(resolve, reject) { + if (_gd && _gd._snapshotInProgress) { + reject(new Error("Snapshotting already in progress.")); + } + if (Lib$1b.isIE() && opts.format !== "svg") { + reject(new Error(helpers$k.MSG_IE_BAD_FORMAT)); + } + if (_gd) _gd._snapshotInProgress = true; + var promise = toImage$1(gd, opts); + var filename = opts.filename || gd.fn || "newplot"; + filename += "." + opts.format.replace("-", "."); + promise.then(function(result) { + if (_gd) _gd._snapshotInProgress = false; + return fileSaver(result, filename, opts.format); + }).then(function(name2) { + resolve(name2); + }).catch(function(err) { + if (_gd) _gd._snapshotInProgress = false; + reject(err); + }); + }); +} +var download = downloadImage; +var template_api = {}; +var Lib$1a = libExports; +var isPlainObject2 = Lib$1a.isPlainObject; +var PlotSchema = plot_schema; +var Plots$7 = plotsExports; +var plotAttributes = attributes$O; +var Template$3 = plot_template; +var dfltConfig = plot_config.dfltConfig; +template_api.makeTemplate = function(figure) { + figure = Lib$1a.isPlainObject(figure) ? figure : Lib$1a.getGraphDiv(figure); + figure = Lib$1a.extendDeep({ _context: dfltConfig }, { data: figure.data, layout: figure.layout }); + Plots$7.supplyDefaults(figure); + var data = figure.data || []; + var layout = figure.layout || {}; + layout._basePlotModules = figure._fullLayout._basePlotModules; + layout._modules = figure._fullLayout._modules; + var template = { + data: {}, + layout: {} + }; + data.forEach(function(trace) { + var traceTemplate = {}; + walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace)); + var traceType2 = Lib$1a.coerce(trace, {}, plotAttributes, "type"); + var typeTemplates2 = template.data[traceType2]; + if (!typeTemplates2) typeTemplates2 = template.data[traceType2] = []; + typeTemplates2.push(traceTemplate); + }); + walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout)); + delete template.layout.template; + var oldTemplate = layout.template; + if (isPlainObject2(oldTemplate)) { + var oldLayoutTemplate = oldTemplate.layout; + var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen; + if (isPlainObject2(oldLayoutTemplate)) { + mergeTemplates(oldLayoutTemplate, template.layout); + } + var oldDataTemplate = oldTemplate.data; + if (isPlainObject2(oldDataTemplate)) { + for (traceType in template.data) { + oldTypeTemplates = oldDataTemplate[traceType]; + if (Array.isArray(oldTypeTemplates)) { + typeTemplates = template.data[traceType]; + typeLen = typeTemplates.length; + oldTypeLen = oldTypeTemplates.length; + for (i = 0; i < typeLen; i++) { + mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]); + } + for (i = typeLen; i < oldTypeLen; i++) { + typeTemplates.push(Lib$1a.extendDeep({}, oldTypeTemplates[i])); + } + } + } + for (traceType in oldDataTemplate) { + if (!(traceType in template.data)) { + template.data[traceType] = Lib$1a.extendDeep([], oldDataTemplate[traceType]); + } + } + } + } + return template; +}; +function mergeTemplates(oldTemplate, newTemplate) { + oldTemplate = Lib$1a.extendDeep({}, oldTemplate); + var oldKeys = Object.keys(oldTemplate).sort(); + var i, j; + function mergeOne(oldVal2, newVal, key3) { + if (isPlainObject2(newVal) && isPlainObject2(oldVal2)) { + mergeTemplates(oldVal2, newVal); + } else if (Array.isArray(newVal) && Array.isArray(oldVal2)) { + var templater = Template$3.arrayTemplater({ _template: oldTemplate }, key3); + for (j = 0; j < newVal.length; j++) { + var item = newVal[j]; + var oldItem = templater.newItem(item)._template; + if (oldItem) mergeTemplates(oldItem, item); + } + var defaultItems = templater.defaultItems(); + for (j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template); + for (j = 0; j < newVal.length; j++) delete newVal[j].templateitemname; + } + } + for (i = 0; i < oldKeys.length; i++) { + var key = oldKeys[i]; + var oldVal = oldTemplate[key]; + if (key in newTemplate) { + mergeOne(oldVal, newTemplate[key], key); + } else newTemplate[key] = oldVal; + if (getBaseKey(key) === key) { + for (var key2 in newTemplate) { + var baseKey2 = getBaseKey(key2); + if (key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) { + mergeOne(oldVal, newTemplate[key2], key); + } + } + } + } +} +function getBaseKey(key) { + return key.replace(/[0-9]+$/, ""); +} +function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) { + var pathAttr = basePath && getAttributeInfo(basePath); + for (var key in parent) { + var child = parent[key]; + var nextPath = getNextPath(parent, key, path); + var nextBasePath = getNextPath(parent, key, basePath); + var attr = getAttributeInfo(nextBasePath); + if (!attr) { + var baseKey = getBaseKey(key); + if (baseKey !== key) { + nextBasePath = getNextPath(parent, baseKey, basePath); + attr = getAttributeInfo(nextBasePath); + } + } + if (pathAttr && pathAttr === attr) continue; + if (!attr || attr._noTemplating || attr.valType === "data_array" || attr.arrayOk && Array.isArray(child)) { + continue; + } + if (!attr.valType && isPlainObject2(child)) { + walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath); + } else if (attr._isLinkedToArray && Array.isArray(child)) { + var dfltDone = false; + var namedIndex = 0; + var usedNames = {}; + for (var i = 0; i < child.length; i++) { + var item = child[i]; + if (isPlainObject2(item)) { + var name2 = item.name; + if (name2) { + if (!usedNames[name2]) { + walkStyleKeys( + item, + templateOut, + getAttributeInfo, + getNextPath(child, namedIndex, nextPath), + getNextPath(child, namedIndex, nextBasePath) + ); + namedIndex++; + usedNames[name2] = 1; + } + } else if (!dfltDone) { + var dfltKey = Template$3.arrayDefaultKey(key); + var dfltPath = getNextPath(parent, dfltKey, path); + var pathInArray = getNextPath(child, namedIndex, nextPath); + walkStyleKeys( + item, + templateOut, + getAttributeInfo, + pathInArray, + getNextPath(child, namedIndex, nextBasePath) + ); + var itemPropInArray = Lib$1a.nestedProperty(templateOut, pathInArray); + var dfltProp = Lib$1a.nestedProperty(templateOut, dfltPath); + dfltProp.set(itemPropInArray.get()); + itemPropInArray.set(null); + dfltDone = true; + } + } + } + } else { + var templateProp = Lib$1a.nestedProperty(templateOut, nextPath); + templateProp.set(child); + } + } +} +function getLayoutInfo(layout, path) { + return PlotSchema.getLayoutValObject( + layout, + Lib$1a.nestedProperty({}, path).parts + ); +} +function getTraceInfo(trace, path) { + return PlotSchema.getTraceValObject( + trace, + Lib$1a.nestedProperty({}, path).parts + ); +} +function getNextPath(parent, key, path) { + var nextPath; + if (!path) nextPath = key; + else if (Array.isArray(parent)) nextPath = path + "[" + key + "]"; + else nextPath = path + "." + key; + return nextPath; +} +template_api.validateTemplate = function(figureIn, template) { + var figure = Lib$1a.extendDeep({}, { + _context: dfltConfig, + data: figureIn.data, + layout: figureIn.layout + }); + var layout = figure.layout || {}; + if (!isPlainObject2(template)) template = layout.template || {}; + var layoutTemplate = template.layout; + var dataTemplate = template.data; + var errorList = []; + figure.layout = layout; + figure.layout.template = template; + Plots$7.supplyDefaults(figure); + var fullLayout = figure._fullLayout; + var fullData = figure._fullData; + var layoutPaths = {}; + function crawlLayoutForContainers(obj, paths) { + for (var key in obj) { + if (key.charAt(0) !== "_" && isPlainObject2(obj[key])) { + var baseKey = getBaseKey(key); + var nextPaths = []; + var i2; + for (i2 = 0; i2 < paths.length; i2++) { + nextPaths.push(getNextPath(obj, key, paths[i2])); + if (baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i2])); + } + for (i2 = 0; i2 < nextPaths.length; i2++) { + layoutPaths[nextPaths[i2]] = 1; + } + crawlLayoutForContainers(obj[key], nextPaths); + } + } + } + function crawlLayoutTemplateForContainers(obj, path) { + for (var key in obj) { + if (key.indexOf("defaults") === -1 && isPlainObject2(obj[key])) { + var nextPath = getNextPath(obj, key, path); + if (layoutPaths[nextPath]) { + crawlLayoutTemplateForContainers(obj[key], nextPath); + } else { + errorList.push({ code: "unused", path: nextPath }); + } + } + } + } + if (!isPlainObject2(layoutTemplate)) { + errorList.push({ code: "layout" }); + } else { + crawlLayoutForContainers(fullLayout, ["layout"]); + crawlLayoutTemplateForContainers(layoutTemplate, "layout"); + } + if (!isPlainObject2(dataTemplate)) { + errorList.push({ code: "data" }); + } else { + var typeCount = {}; + var traceType; + for (var i = 0; i < fullData.length; i++) { + var fullTrace = fullData[i]; + traceType = fullTrace.type; + typeCount[traceType] = (typeCount[traceType] || 0) + 1; + if (!fullTrace._fullInput._template) { + errorList.push({ + code: "missing", + index: fullTrace._fullInput.index, + traceType + }); + } + } + for (traceType in dataTemplate) { + var templateCount = dataTemplate[traceType].length; + var dataCount = typeCount[traceType] || 0; + if (templateCount > dataCount) { + errorList.push({ + code: "unused", + traceType, + templateCount, + dataCount + }); + } else if (dataCount > templateCount) { + errorList.push({ + code: "reused", + traceType, + templateCount, + dataCount + }); + } + } + } + function crawlForMissingTemplates(obj, path) { + for (var key in obj) { + if (key.charAt(0) === "_") continue; + var val = obj[key]; + var nextPath = getNextPath(obj, key, path); + if (isPlainObject2(val)) { + if (Array.isArray(obj) && val._template === false && val.templateitemname) { + errorList.push({ + code: "missing", + path: nextPath, + templateitemname: val.templateitemname + }); + } + crawlForMissingTemplates(val, nextPath); + } else if (Array.isArray(val) && hasPlainObject(val)) { + crawlForMissingTemplates(val, nextPath); + } + } + } + crawlForMissingTemplates({ data: fullData, layout: fullLayout }, ""); + if (errorList.length) return errorList.map(format); +}; +function hasPlainObject(arr) { + for (var i = 0; i < arr.length; i++) { + if (isPlainObject2(arr[i])) return true; + } +} +function format(opts) { + var msg2; + switch (opts.code) { + case "data": + msg2 = "The template has no key data."; + break; + case "layout": + msg2 = "The template has no key layout."; + break; + case "missing": + if (opts.path) { + msg2 = "There are no templates for item " + opts.path + " with name " + opts.templateitemname; + } else { + msg2 = "There are no templates for trace " + opts.index + ", of type " + opts.traceType + "."; + } + break; + case "unused": + if (opts.path) { + msg2 = "The template item at " + opts.path + " was not used in constructing the plot."; + } else if (opts.dataCount) { + msg2 = "Some of the templates of type " + opts.traceType + " were not used. The template has " + opts.templateCount + " traces, the data only has " + opts.dataCount + " of this type."; + } else { + msg2 = "The template has " + opts.templateCount + " traces of type " + opts.traceType + " but there are none in the data."; + } + break; + case "reused": + msg2 = "Some of the templates of type " + opts.traceType + " were used more than once. The template has " + opts.templateCount + " traces, the data has " + opts.dataCount + " of this type."; + break; + } + opts.msg = msg2; + return opts; +} +var main = plot_api; +plot_api$1._doPlot = main._doPlot; +plot_api$1.newPlot = main.newPlot; +plot_api$1.restyle = main.restyle; +plot_api$1.relayout = main.relayout; +plot_api$1.redraw = main.redraw; +plot_api$1.update = main.update; +plot_api$1._guiRestyle = main._guiRestyle; +plot_api$1._guiRelayout = main._guiRelayout; +plot_api$1._guiUpdate = main._guiUpdate; +plot_api$1._storeDirectGUIEdit = main._storeDirectGUIEdit; +plot_api$1.react = main.react; +plot_api$1.extendTraces = main.extendTraces; +plot_api$1.prependTraces = main.prependTraces; +plot_api$1.addTraces = main.addTraces; +plot_api$1.deleteTraces = main.deleteTraces; +plot_api$1.moveTraces = main.moveTraces; +plot_api$1.purge = main.purge; +plot_api$1.addFrames = main.addFrames; +plot_api$1.deleteFrames = main.deleteFrames; +plot_api$1.animate = main.animate; +plot_api$1.setPlotConfig = main.setPlotConfig; +var getGraphDiv = dom.getGraphDiv; +var eraseActiveShape = draw_1$3.eraseActiveShape; +plot_api$1.deleteActiveShape = function(gd) { + return eraseActiveShape(getGraphDiv(gd)); +}; +plot_api$1.toImage = to_image; +plot_api$1.validate = validate; +plot_api$1.downloadImage = download; +var templateApi = template_api; +plot_api$1.makeTemplate = templateApi.makeTemplate; +plot_api$1.validateTemplate = templateApi.validateTemplate; +var Lib$19 = libExports; +var Registry$q = registry; +var xy_defaults = function handleXYDefaults(traceIn, traceOut, layout, coerce2) { + var x = coerce2("x"); + var y = coerce2("y"); + var len; + var handleCalendarDefaults = Registry$q.getComponentMethod("calendars", "handleTraceDefaults"); + handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout); + if (x) { + var xlen = Lib$19.minRowLength(x); + if (y) { + len = Math.min(xlen, Lib$19.minRowLength(y)); + } else { + len = xlen; + coerce2("y0"); + coerce2("dy"); + } + } else { + if (!y) return 0; + len = Lib$19.minRowLength(y); + coerce2("x0"); + coerce2("dx"); + } + traceOut._length = len; + return len; +}; +var dateTick0 = libExports.dateTick0; +var numConstants$2 = numerical; +var ONEWEEK = numConstants$2.ONEWEEK; +function getPeriod0Dflt(period, calendar) { + if (period % ONEWEEK === 0) { + return dateTick0(calendar, 1); + } + return dateTick0(calendar, 0); +} +var period_defaults = function handlePeriodDefaults(traceIn, traceOut, layout, coerce2, opts) { + if (!opts) { + opts = { + x: true, + y: true + }; + } + if (opts.x) { + var xperiod = coerce2("xperiod"); + if (xperiod) { + coerce2("xperiod0", getPeriod0Dflt(xperiod, traceOut.xcalendar)); + coerce2("xperiodalignment"); + } + } + if (opts.y) { + var yperiod = coerce2("yperiod"); + if (yperiod) { + coerce2("yperiod0", getPeriod0Dflt(yperiod, traceOut.ycalendar)); + coerce2("yperiodalignment"); + } + } +}; +var perStackAttrs = ["orientation", "groupnorm", "stackgaps"]; +var stack_defaults = function handleStackDefaults(traceIn, traceOut, layout, coerce2) { + var stackOpts = layout._scatterStackOpts; + var stackGroup = coerce2("stackgroup"); + if (stackGroup) { + var subplot = traceOut.xaxis + traceOut.yaxis; + var subplotStackOpts = stackOpts[subplot]; + if (!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {}; + var groupOpts = subplotStackOpts[stackGroup]; + var firstTrace = false; + if (groupOpts) { + groupOpts.traces.push(traceOut); + } else { + groupOpts = subplotStackOpts[stackGroup] = { + // keep track of trace indices for use during stacking calculations + // this will be filled in during `calc` and used during `crossTraceCalc` + // so it's OK if we don't recreate it during a non-calc edit + traceIndices: [], + // Hold on to the whole set of prior traces + // First one is most important, so we can clear defaults + // there if we find explicit values only in later traces. + // We're only going to *use* the values stored in groupOpts, + // but for the editor and validate we want things self-consistent + // The full set of traces is used only to fix `fill` default if + // we find `orientation: 'h'` beyond the first trace + traces: [traceOut] + }; + firstTrace = true; + } + var dflts = { + orientation: traceOut.x && !traceOut.y ? "h" : "v" + }; + for (var i = 0; i < perStackAttrs.length; i++) { + var attr = perStackAttrs[i]; + var attrFound = attr + "Found"; + if (!groupOpts[attrFound]) { + var traceHasAttr = traceIn[attr] !== void 0; + var isOrientation = attr === "orientation"; + if (traceHasAttr || firstTrace) { + groupOpts[attr] = coerce2(attr, dflts[attr]); + if (isOrientation) { + groupOpts.fillDflt = groupOpts[attr] === "h" ? "tonextx" : "tonexty"; + } + if (traceHasAttr) { + groupOpts[attrFound] = true; + if (!firstTrace) { + delete groupOpts.traces[0][attr]; + if (isOrientation) { + for (var j = 0; j < groupOpts.traces.length - 1; j++) { + var trace2 = groupOpts.traces[j]; + if (trace2._input.fill !== trace2.fill) { + trace2.fill = groupOpts.fillDflt; + } + } + } + } + } + } + } + } + return groupOpts; + } +}; +var Color$u = colorExports; +var hasColorscale$5 = helpers$L.hasColorscale; +var colorscaleDefaults$3 = defaults$n; +var subTypes$8 = subtypes$3; +var marker_defaults = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce2, opts) { + var isBubble = subTypes$8.isBubble(traceIn); + var lineColor = (traceIn.line || {}).color; + var defaultMLC; + opts = opts || {}; + if (lineColor) defaultColor = lineColor; + coerce2("marker.symbol"); + coerce2("marker.opacity", isBubble ? 0.7 : 1); + coerce2("marker.size"); + if (!opts.noAngle) { + coerce2("marker.angle"); + if (!opts.noAngleRef) { + coerce2("marker.angleref"); + } + if (!opts.noStandOff) { + coerce2("marker.standoff"); + } + } + coerce2("marker.color", defaultColor); + if (hasColorscale$5(traceIn, "marker")) { + colorscaleDefaults$3(traceIn, traceOut, layout, coerce2, { prefix: "marker.", cLetter: "c" }); + } + if (!opts.noSelect) { + coerce2("selected.marker.color"); + coerce2("unselected.marker.color"); + coerce2("selected.marker.size"); + coerce2("unselected.marker.size"); + } + if (!opts.noLine) { + if (lineColor && !Array.isArray(lineColor) && traceOut.marker.color !== lineColor) { + defaultMLC = lineColor; + } else if (isBubble) defaultMLC = Color$u.background; + else defaultMLC = Color$u.defaultLine; + coerce2("marker.line.color", defaultMLC); + if (hasColorscale$5(traceIn, "marker.line")) { + colorscaleDefaults$3(traceIn, traceOut, layout, coerce2, { prefix: "marker.line.", cLetter: "c" }); + } + coerce2("marker.line.width", isBubble ? 1 : 0); + } + if (isBubble) { + coerce2("marker.sizeref"); + coerce2("marker.sizemin"); + coerce2("marker.sizemode"); + } + if (opts.gradient) { + var gradientType = coerce2("marker.gradient.type"); + if (gradientType !== "none") { + coerce2("marker.gradient.color"); + } + } +}; +var isArrayOrTypedArray$5 = libExports.isArrayOrTypedArray; +var hasColorscale$4 = helpers$L.hasColorscale; +var colorscaleDefaults$2 = defaults$n; +var line_defaults = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce2, opts) { + if (!opts) opts = {}; + var markerColor = (traceIn.marker || {}).color; + if (markerColor && markerColor._inputArray) markerColor = markerColor._inputArray; + coerce2("line.color", defaultColor); + if (hasColorscale$4(traceIn, "line")) { + colorscaleDefaults$2(traceIn, traceOut, layout, coerce2, { prefix: "line.", cLetter: "c" }); + } else { + var lineColorDflt = (isArrayOrTypedArray$5(markerColor) ? false : markerColor) || defaultColor; + coerce2("line.color", lineColorDflt); + } + coerce2("line.width"); + if (!opts.noDash) coerce2("line.dash"); + if (opts.backoff) coerce2("line.backoff"); +}; +var line_shape_defaults = function handleLineShapeDefaults(traceIn, traceOut, coerce2) { + var shape = coerce2("line.shape"); + if (shape === "spline") coerce2("line.smoothing"); +}; +var Lib$18 = libExports; +var text_defaults = function(traceIn, traceOut, layout, coerce2, opts) { + opts = opts || {}; + coerce2("textposition"); + Lib$18.coerceFont(coerce2, "textfont", opts.font || layout.font, opts); + if (!opts.noSelect) { + coerce2("selected.textfont.color"); + coerce2("unselected.textfont.color"); + } +}; +var Color$t = colorExports; +var isArrayOrTypedArray$4 = libExports.isArrayOrTypedArray; +function averageColors(colorscale2) { + var color2 = Color$t.interpolate(colorscale2[0][1], colorscale2[1][1], 0.5); + for (var i = 2; i < colorscale2.length; i++) { + var averageColorI = Color$t.interpolate(colorscale2[i - 1][1], colorscale2[i][1], 0.5); + color2 = Color$t.interpolate(color2, averageColorI, colorscale2[i - 1][0] / colorscale2[i][0]); + } + return color2; +} +var fillcolor_defaults = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce2, opts) { + if (!opts) opts = {}; + var inheritColorFromMarker = false; + if (traceOut.marker) { + var markerColor = traceOut.marker.color; + var markerLineColor = (traceOut.marker.line || {}).color; + if (markerColor && !isArrayOrTypedArray$4(markerColor)) { + inheritColorFromMarker = markerColor; + } else if (markerLineColor && !isArrayOrTypedArray$4(markerLineColor)) { + inheritColorFromMarker = markerLineColor; + } + } + var averageGradientColor; + if (opts.moduleHasFillgradient) { + var gradientOrientation = coerce2("fillgradient.type"); + if (gradientOrientation !== "none") { + coerce2("fillgradient.start"); + coerce2("fillgradient.stop"); + var gradientColorscale = coerce2("fillgradient.colorscale"); + if (gradientColorscale) { + averageGradientColor = averageColors(gradientColorscale); + } + } + } + coerce2("fillcolor", Color$t.addOpacity( + (traceOut.line || {}).color || inheritColorFromMarker || averageGradientColor || defaultColor, + 0.5 + )); +}; +var Lib$17 = libExports; +var Registry$p = registry; +var attributes$x = attributes$A; +var constants$z = constants$B; +var subTypes$7 = subtypes$3; +var handleXYDefaults$2 = xy_defaults; +var handlePeriodDefaults$3 = period_defaults; +var handleStackDefaults2 = stack_defaults; +var handleMarkerDefaults$3 = marker_defaults; +var handleLineDefaults$1 = line_defaults; +var handleLineShapeDefaults2 = line_shape_defaults; +var handleTextDefaults$1 = text_defaults; +var handleFillColorDefaults$1 = fillcolor_defaults; +var coercePattern$2 = libExports.coercePattern; +var defaults$h = function supplyDefaults2(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$17.coerce(traceIn, traceOut, attributes$x, attr, dflt); + } + var len = handleXYDefaults$2(traceIn, traceOut, layout, coerce2); + if (!len) traceOut.visible = false; + if (!traceOut.visible) return; + handlePeriodDefaults$3(traceIn, traceOut, layout, coerce2); + coerce2("xhoverformat"); + coerce2("yhoverformat"); + coerce2("zorder"); + var stackGroupOpts = handleStackDefaults2(traceIn, traceOut, layout, coerce2); + if (layout.scattermode === "group" && traceOut.orientation === void 0) { + coerce2("orientation", "v"); + } + var defaultMode = !stackGroupOpts && len < constants$z.PTS_LINESONLY ? "lines+markers" : "lines"; + coerce2("text"); + coerce2("hovertext"); + coerce2("mode", defaultMode); + if (subTypes$7.hasMarkers(traceOut)) { + handleMarkerDefaults$3(traceIn, traceOut, defaultColor, layout, coerce2, { gradient: true }); + } + if (subTypes$7.hasLines(traceOut)) { + handleLineDefaults$1(traceIn, traceOut, defaultColor, layout, coerce2, { backoff: true }); + handleLineShapeDefaults2(traceIn, traceOut, coerce2); + coerce2("connectgaps"); + coerce2("line.simplify"); + } + if (subTypes$7.hasText(traceOut)) { + coerce2("texttemplate"); + handleTextDefaults$1(traceIn, traceOut, layout, coerce2); + } + var dfltHoverOn = []; + if (subTypes$7.hasMarkers(traceOut) || subTypes$7.hasText(traceOut)) { + coerce2("cliponaxis"); + coerce2("marker.maxdisplayed"); + dfltHoverOn.push("points"); + } + coerce2("fill", stackGroupOpts ? stackGroupOpts.fillDflt : "none"); + if (traceOut.fill !== "none") { + handleFillColorDefaults$1(traceIn, traceOut, defaultColor, coerce2, { + moduleHasFillgradient: true + }); + if (!subTypes$7.hasLines(traceOut)) handleLineShapeDefaults2(traceIn, traceOut, coerce2); + coercePattern$2(coerce2, "fillpattern", traceOut.fillcolor, false); + } + var lineColor = (traceOut.line || {}).color; + var markerColor = (traceOut.marker || {}).color; + if (traceOut.fill === "tonext" || traceOut.fill === "toself") { + dfltHoverOn.push("fills"); + } + coerce2("hoveron", dfltHoverOn.join("+") || "points"); + if (traceOut.hoveron !== "fills") coerce2("hovertemplate"); + var errorBarsSupplyDefaults = Registry$p.getComponentMethod("errorbars", "supplyDefaults"); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" }); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" }); + Lib$17.coerceSelectionMarkerOpacity(traceOut, coerce2); +}; +var getAxisGroup$2 = constraints.getAxisGroup; +var grouping_defaults = function handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce2) { + var orientation = traceOut.orientation; + var posAxId = traceOut[{ v: "x", h: "y" }[orientation] + "axis"]; + var groupId = getAxisGroup$2(fullLayout, posAxId) + orientation; + var alignmentOpts = fullLayout._alignmentOpts || {}; + var alignmentgroup = coerce2("alignmentgroup"); + var alignmentGroups = alignmentOpts[groupId]; + if (!alignmentGroups) alignmentGroups = alignmentOpts[groupId] = {}; + var alignmentGroupOpts = alignmentGroups[alignmentgroup]; + if (alignmentGroupOpts) { + alignmentGroupOpts.traces.push(traceOut); + } else { + alignmentGroupOpts = alignmentGroups[alignmentgroup] = { + traces: [traceOut], + alignmentIndex: Object.keys(alignmentGroups).length, + offsetGroups: {} + }; + } + var offsetgroup = coerce2("offsetgroup"); + var offsetGroups = alignmentGroupOpts.offsetGroups; + var offsetGroupOpts = offsetGroups[offsetgroup]; + if (offsetgroup) { + if (!offsetGroupOpts) { + offsetGroupOpts = offsetGroups[offsetgroup] = { + offsetIndex: Object.keys(offsetGroups).length + }; + } + traceOut._offsetIndex = offsetGroupOpts.offsetIndex; + } +}; +var Lib$16 = libExports; +var handleGroupingDefaults$2 = grouping_defaults; +var attributes$w = attributes$A; +var cross_trace_defaults$1 = function crossTraceDefaults2(fullData, fullLayout) { + var traceIn, traceOut, i; + function coerce2(attr) { + return Lib$16.coerce(traceOut._input, traceOut, attributes$w, attr); + } + if (fullLayout.scattermode === "group") { + for (i = 0; i < fullData.length; i++) { + traceOut = fullData[i]; + if (traceOut.type === "scatter") { + traceIn = traceOut._input; + handleGroupingDefaults$2(traceIn, traceOut, fullLayout, coerce2); + } + } + } + for (i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; + if (tracei.type !== "scatter") continue; + var filli = tracei.fill; + if (filli === "none" || filli === "toself") continue; + tracei.opacity = void 0; + if (filli === "tonexty" || filli === "tonextx") { + for (var j = i - 1; j >= 0; j--) { + var tracej = fullData[j]; + if (tracej.type === "scatter" && tracej.xaxis === tracei.xaxis && tracej.yaxis === tracei.yaxis) { + tracej.opacity = void 0; + break; + } + } + } + } +}; +var Lib$15 = libExports; +var layoutAttributes$4 = layout_attributes$5; +var layout_defaults$4 = function(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$15.coerce(layoutIn, layoutOut, layoutAttributes$4, attr, dflt); + } + var groupBarmode = layoutOut.barmode === "group"; + if (layoutOut.scattermode === "group") { + coerce2("scattergap", groupBarmode ? layoutOut.bargap : 0.2); + } +}; +var isNumeric$f = fastIsnumeric; +var Lib$14 = libExports; +var dateTime2ms = Lib$14.dateTime2ms; +var incrementMonth = Lib$14.incrementMonth; +var constants$y = numerical; +var ONEAVGMONTH = constants$y.ONEAVGMONTH; +var align_period = function alignPeriod(trace, ax, axLetter, vals) { + if (ax.type !== "date") return { vals }; + var alignment2 = trace[axLetter + "periodalignment"]; + if (!alignment2) return { vals }; + var period = trace[axLetter + "period"]; + var mPeriod; + if (isNumeric$f(period)) { + period = +period; + if (period <= 0) return { vals }; + } else if (typeof period === "string" && period.charAt(0) === "M") { + var n = +period.substring(1); + if (n > 0 && Math.round(n) === n) { + mPeriod = n; + } else return { vals }; + } + var calendar = ax.calendar; + var isStart = "start" === alignment2; + var isEnd = "end" === alignment2; + var period0 = trace[axLetter + "period0"]; + var base = dateTime2ms(period0, calendar) || 0; + var newVals = []; + var starts = []; + var ends = []; + var len = vals.length; + for (var i = 0; i < len; i++) { + var v = vals[i]; + var nEstimated, startTime, endTime; + if (mPeriod) { + nEstimated = Math.round((v - base) / (mPeriod * ONEAVGMONTH)); + endTime = incrementMonth(base, mPeriod * nEstimated, calendar); + while (endTime > v) { + endTime = incrementMonth(endTime, -mPeriod, calendar); + } + while (endTime <= v) { + endTime = incrementMonth(endTime, mPeriod, calendar); + } + startTime = incrementMonth(endTime, -mPeriod, calendar); + } else { + nEstimated = Math.round((v - base) / period); + endTime = base + nEstimated * period; + while (endTime > v) { + endTime -= period; + } + while (endTime <= v) { + endTime += period; + } + startTime = endTime - period; + } + newVals[i] = isStart ? startTime : isEnd ? endTime : (startTime + endTime) / 2; + starts[i] = startTime; + ends[i] = endTime; + } + return { + vals: newVals, + starts, + ends + }; +}; +var hasColorscale$3 = helpers$L.hasColorscale; +var calcColorscale$2 = calc$c; +var subTypes$6 = subtypes$3; +var colorscale_calc = function calcMarkerColorscale(gd, trace) { + if (subTypes$6.hasLines(trace) && hasColorscale$3(trace, "line")) { + calcColorscale$2(gd, trace, { + vals: trace.line.color, + containerStr: "line" + }); + } + if (subTypes$6.hasMarkers(trace)) { + if (hasColorscale$3(trace, "marker")) { + calcColorscale$2(gd, trace, { + vals: trace.marker.color, + containerStr: "marker" + }); + } + if (hasColorscale$3(trace, "marker.line")) { + calcColorscale$2(gd, trace, { + vals: trace.marker.line.color, + containerStr: "marker.line" + }); + } + } +}; +var Lib$13 = libExports; +var arrays_to_calcdata$1 = function arraysToCalcdata(cd, trace) { + for (var i = 0; i < cd.length; i++) cd[i].i = i; + Lib$13.mergeArray(trace.text, cd, "tx"); + Lib$13.mergeArray(trace.texttemplate, cd, "txt"); + Lib$13.mergeArray(trace.hovertext, cd, "htx"); + Lib$13.mergeArray(trace.customdata, cd, "data"); + Lib$13.mergeArray(trace.textposition, cd, "tp"); + if (trace.textfont) { + Lib$13.mergeArrayCastPositive(trace.textfont.size, cd, "ts"); + Lib$13.mergeArray(trace.textfont.color, cd, "tc"); + Lib$13.mergeArray(trace.textfont.family, cd, "tf"); + Lib$13.mergeArray(trace.textfont.weight, cd, "tw"); + Lib$13.mergeArray(trace.textfont.style, cd, "ty"); + Lib$13.mergeArray(trace.textfont.variant, cd, "tv"); + Lib$13.mergeArray(trace.textfont.textcase, cd, "tC"); + Lib$13.mergeArray(trace.textfont.lineposition, cd, "tE"); + Lib$13.mergeArray(trace.textfont.shadow, cd, "tS"); + } + var marker2 = trace.marker; + if (marker2) { + Lib$13.mergeArrayCastPositive(marker2.size, cd, "ms"); + Lib$13.mergeArrayCastPositive(marker2.opacity, cd, "mo"); + Lib$13.mergeArray(marker2.symbol, cd, "mx"); + Lib$13.mergeArray(marker2.angle, cd, "ma"); + Lib$13.mergeArray(marker2.standoff, cd, "mf"); + Lib$13.mergeArray(marker2.color, cd, "mc"); + var markerLine2 = marker2.line; + if (marker2.line) { + Lib$13.mergeArray(markerLine2.color, cd, "mlc"); + Lib$13.mergeArrayCastPositive(markerLine2.width, cd, "mlw"); + } + var markerGradient = marker2.gradient; + if (markerGradient && markerGradient.type !== "none") { + Lib$13.mergeArray(markerGradient.type, cd, "mgt"); + Lib$13.mergeArray(markerGradient.color, cd, "mgc"); + } + } +}; +var Lib$12 = libExports; +var calc_selection = function calcSelection(cd, trace) { + if (Lib$12.isArrayOrTypedArray(trace.selectedpoints)) { + Lib$12.tagSelected(cd, trace); + } +}; +var isNumeric$e = fastIsnumeric; +var Lib$11 = libExports; +var Axes$h = axesExports; +var alignPeriod$3 = align_period; +var BADNUM$5 = numerical.BADNUM; +var subTypes$5 = subtypes$3; +var calcColorscale$1 = colorscale_calc; +var arraysToCalcdata$2 = arrays_to_calcdata$1; +var calcSelection$1 = calc_selection; +function calc$a(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = trace._xA = Axes$h.getFromId(gd, trace.xaxis || "x", "x"); + var ya = trace._yA = Axes$h.getFromId(gd, trace.yaxis || "y", "y"); + var origX = xa.makeCalcdata(trace, "x"); + var origY = ya.makeCalcdata(trace, "y"); + var xObj = alignPeriod$3(trace, xa, "x", origX); + var yObj = alignPeriod$3(trace, ya, "y", origY); + var x = xObj.vals; + var y = yObj.vals; + var serieslen = trace._length; + var cd = new Array(serieslen); + var ids = trace.ids; + var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya); + var interpolateGaps = false; + var isV, i, j, k, interpolate2, vali; + setFirstScatter$1(fullLayout, trace); + var xAttr = "x"; + var yAttr = "y"; + var posAttr; + if (stackGroupOpts) { + Lib$11.pushUnique(stackGroupOpts.traceIndices, trace._expandedIndex); + isV = stackGroupOpts.orientation === "v"; + if (isV) { + yAttr = "s"; + posAttr = "x"; + } else { + xAttr = "s"; + posAttr = "y"; + } + interpolate2 = stackGroupOpts.stackgaps === "interpolate"; + } else { + var ppad = calcMarkerSize$1(trace, serieslen); + calcAxisExpansion$2(gd, trace, xa, ya, x, y, ppad); + } + var hasPeriodX = !!trace.xperiodalignment; + var hasPeriodY = !!trace.yperiodalignment; + for (i = 0; i < serieslen; i++) { + var cdi = cd[i] = {}; + var xValid = isNumeric$e(x[i]); + var yValid = isNumeric$e(y[i]); + if (xValid && yValid) { + cdi[xAttr] = x[i]; + cdi[yAttr] = y[i]; + if (hasPeriodX) { + cdi.orig_x = origX[i]; + cdi.xEnd = xObj.ends[i]; + cdi.xStart = xObj.starts[i]; + } + if (hasPeriodY) { + cdi.orig_y = origY[i]; + cdi.yEnd = yObj.ends[i]; + cdi.yStart = yObj.starts[i]; + } + } else if (stackGroupOpts && (isV ? xValid : yValid)) { + cdi[posAttr] = isV ? x[i] : y[i]; + cdi.gap = true; + if (interpolate2) { + cdi.s = BADNUM$5; + interpolateGaps = true; + } else { + cdi.s = 0; + } + } else { + cdi[xAttr] = cdi[yAttr] = BADNUM$5; + } + if (ids) { + cdi.id = String(ids[i]); + } + } + arraysToCalcdata$2(cd, trace); + calcColorscale$1(gd, trace); + calcSelection$1(cd, trace); + if (stackGroupOpts) { + i = 0; + while (i < cd.length) { + if (cd[i][posAttr] === BADNUM$5) { + cd.splice(i, 1); + } else i++; + } + Lib$11.sort(cd, function(a, b) { + return a[posAttr] - b[posAttr] || a.i - b.i; + }); + if (interpolateGaps) { + i = 0; + while (i < cd.length - 1 && cd[i].gap) { + i++; + } + vali = cd[i].s; + if (!vali) vali = cd[i].s = 0; + for (j = 0; j < i; j++) { + cd[j].s = vali; + } + k = cd.length - 1; + while (k > i && cd[k].gap) { + k--; + } + vali = cd[k].s; + for (j = cd.length - 1; j > k; j--) { + cd[j].s = vali; + } + while (i < k) { + i++; + if (cd[i].gap) { + j = i + 1; + while (cd[j].gap) { + j++; + } + var pos0 = cd[i - 1][posAttr]; + var size0 = cd[i - 1].s; + var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0); + while (i < j) { + cd[i].s = size0 + (cd[i][posAttr] - pos0) * m; + i++; + } + } + } + } + } + return cd; +} +function calcAxisExpansion$2(gd, trace, xa, ya, x, y, ppad) { + var serieslen = trace._length; + var fullLayout = gd._fullLayout; + var xId = xa._id; + var yId = ya._id; + var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid; + var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation; + var fill = trace.fill; + xa._minDtick = 0; + ya._minDtick = 0; + var xOptions = { padded: true }; + var yOptions = { padded: true }; + if (ppad) { + xOptions.ppad = yOptions.ppad = ppad; + } + var openEnded = serieslen < 2 || x[0] !== x[serieslen - 1] || y[0] !== y[serieslen - 1]; + if (openEnded && (fill === "tozerox" || fill === "tonextx" && (firstScatter || stackOrientation === "h"))) { + xOptions.tozero = true; + } else if (!(trace.error_y || {}).visible && // if no error bars, markers or text, or fill to y=0 remove x padding + (fill === "tonexty" || fill === "tozeroy" || !subTypes$5.hasMarkers(trace) && !subTypes$5.hasText(trace))) { + xOptions.padded = false; + xOptions.ppad = 0; + } + if (openEnded && (fill === "tozeroy" || fill === "tonexty" && (firstScatter || stackOrientation === "v"))) { + yOptions.tozero = true; + } else if (fill === "tonextx" || fill === "tozerox") { + yOptions.padded = false; + } + if (xId) trace._extremes[xId] = Axes$h.findExtremes(xa, x, xOptions); + if (yId) trace._extremes[yId] = Axes$h.findExtremes(ya, y, yOptions); +} +function calcMarkerSize$1(trace, serieslen) { + if (!subTypes$5.hasMarkers(trace)) return; + var marker2 = trace.marker; + var sizeref = 1.6 * (trace.marker.sizeref || 1); + var markerTrans; + if (trace.marker.sizemode === "area") { + markerTrans = function(v) { + return Math.max(Math.sqrt((v || 0) / sizeref), 3); + }; + } else { + markerTrans = function(v) { + return Math.max((v || 0) / sizeref, 3); + }; + } + if (Lib$11.isArrayOrTypedArray(marker2.size)) { + var ax = { type: "linear" }; + Axes$h.setConvert(ax); + var s = ax.makeCalcdata(trace.marker, "size"); + var sizeOut = new Array(serieslen); + for (var i = 0; i < serieslen; i++) { + sizeOut[i] = markerTrans(s[i]); + } + return sizeOut; + } else { + return markerTrans(marker2.size); + } +} +function setFirstScatter$1(fullLayout, trace) { + var group = firstScatterGroup(trace); + var firstScatter = fullLayout._firstScatter; + if (!firstScatter[group]) firstScatter[group] = trace.uid; +} +function firstScatterGroup(trace) { + var stackGroup = trace.stackgroup; + return trace.xaxis + trace.yaxis + trace.type + (stackGroup ? "-" + stackGroup : ""); +} +function getStackOpts(trace, fullLayout, xa, ya) { + var stackGroup = trace.stackgroup; + if (!stackGroup) return; + var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup]; + var stackAx = stackOpts.orientation === "v" ? ya : xa; + if (stackAx.type === "linear" || stackAx.type === "log") return stackOpts; +} +var calc_1$3 = { + calc: calc$a, + calcMarkerSize: calcMarkerSize$1, + calcAxisExpansion: calcAxisExpansion$2, + setFirstScatter: setFirstScatter$1, + getStackOpts +}; +var sieve = Sieve$1; +var distinctVals = libExports.distinctVals; +function Sieve$1(traces, opts) { + this.traces = traces; + this.sepNegVal = opts.sepNegVal; + this.overlapNoMerge = opts.overlapNoMerge; + var width1 = Infinity; + var axLetter = opts.posAxis._id.charAt(0); + var positions = []; + for (var i = 0; i < traces.length; i++) { + var trace = traces[i]; + for (var j = 0; j < trace.length; j++) { + var bar2 = trace[j]; + var pos = bar2.p; + if (pos === void 0) { + pos = bar2[axLetter]; + } + if (pos !== void 0) positions.push(pos); + } + if (trace[0] && trace[0].width1) { + width1 = Math.min(trace[0].width1, width1); + } + } + this.positions = positions; + var dv2 = distinctVals(positions); + this.distinctPositions = dv2.vals; + if (dv2.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; + else this.minDiff = Math.min(dv2.minDiff, width1); + var type = (opts.posAxis || {}).type; + if (type === "category" || type === "multicategory") { + this.minDiff = 1; + } + this.binWidth = this.minDiff; + this.bins = {}; +} +Sieve$1.prototype.put = function put(position, value2) { + var label = this.getLabel(position, value2); + var oldValue = this.bins[label] || 0; + this.bins[label] = oldValue + value2; + return oldValue; +}; +Sieve$1.prototype.get = function get(position, value2) { + var label = this.getLabel(position, value2); + return this.bins[label] || 0; +}; +Sieve$1.prototype.getLabel = function getLabel(position, value2) { + var prefix = value2 < 0 && this.sepNegVal ? "v" : "^"; + var label = this.overlapNoMerge ? position : Math.round(position / this.binWidth); + return prefix + label; +}; +var isNumeric$d = fastIsnumeric; +var isArrayOrTypedArray$3 = libExports.isArrayOrTypedArray; +var BADNUM$4 = numerical.BADNUM; +var Registry$o = registry; +var Axes$g = axesExports; +var getAxisGroup$1 = constraints.getAxisGroup; +var Sieve = sieve; +function crossTraceCalc$1(gd, plotinfo) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var fullLayout = gd._fullLayout; + var fullTraces = gd._fullData; + var calcTraces = gd.calcdata; + var calcTracesHorz = []; + var calcTracesVert = []; + for (var i = 0; i < fullTraces.length; i++) { + var fullTrace = fullTraces[i]; + if (fullTrace.visible === true && Registry$o.traceIs(fullTrace, "bar") && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) { + if (fullTrace.orientation === "h") { + calcTracesHorz.push(calcTraces[i]); + } else { + calcTracesVert.push(calcTraces[i]); + } + if (fullTrace._computePh) { + var cd = gd.calcdata[i]; + for (var j = 0; j < cd.length; j++) { + if (typeof cd[j].ph0 === "function") cd[j].ph0 = cd[j].ph0(); + if (typeof cd[j].ph1 === "function") cd[j].ph1 = cd[j].ph1(); + } + } + } + } + var opts = { + xCat: xa.type === "category" || xa.type === "multicategory", + yCat: ya.type === "category" || ya.type === "multicategory", + mode: fullLayout.barmode, + norm: fullLayout.barnorm, + gap: fullLayout.bargap, + groupgap: fullLayout.bargroupgap + }; + setGroupPositions$1(gd, xa, ya, calcTracesVert, opts); + setGroupPositions$1(gd, ya, xa, calcTracesHorz, opts); +} +function setGroupPositions$1(gd, pa, sa, calcTraces, opts) { + if (!calcTraces.length) return; + var excluded; + var included; + var i, calcTrace, fullTrace; + initBase(sa, calcTraces); + switch (opts.mode) { + case "overlay": + setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts); + break; + case "group": + excluded = []; + included = []; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + if (fullTrace.offset === void 0) included.push(calcTrace); + else excluded.push(calcTrace); + } + if (included.length) { + setGroupPositionsInGroupMode(gd, pa, sa, included, opts); + } + if (excluded.length) { + setGroupPositionsInOverlayMode(pa, sa, excluded, opts); + } + break; + case "stack": + case "relative": + excluded = []; + included = []; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + if (fullTrace.base === void 0) included.push(calcTrace); + else excluded.push(calcTrace); + } + standardizeCornerradius(included); + if (included.length) { + setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included, opts); + } + if (excluded.length) { + setGroupPositionsInOverlayMode(pa, sa, excluded, opts); + } + break; + } + setCornerradius(calcTraces); + collectExtents(calcTraces, pa); +} +function setCornerradius(calcTraces) { + var i, calcTrace, fullTrace, t, cr, crValue, crForm; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + t = calcTrace[0].t; + if (t.cornerradiusvalue === void 0) { + cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0; + if (cr !== void 0) { + crValue = isNumeric$d(cr) ? +cr : +cr.slice(0, -1); + crForm = isNumeric$d(cr) ? "px" : "%"; + t.cornerradiusvalue = crValue; + t.cornerradiusform = crForm; + } + } + } +} +function standardizeCornerradius(calcTraces) { + if (calcTraces.length < 2) return; + var i, calcTrace, fullTrace, t; + var cr, crValue, crForm; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0; + if (cr !== void 0) break; + } + if (cr !== void 0) { + crValue = isNumeric$d(cr) ? +cr : +cr.slice(0, -1); + crForm = isNumeric$d(cr) ? "px" : "%"; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + t = calcTrace[0].t; + t.cornerradiusvalue = crValue; + t.cornerradiusform = crForm; + } + } +} +function initBase(sa, calcTraces) { + var i, j; + for (i = 0; i < calcTraces.length; i++) { + var cd = calcTraces[i]; + var trace = cd[0].trace; + var base = trace.type === "funnel" ? trace._base : trace.base; + var b; + var scalendar = trace.orientation === "h" ? trace.xcalendar : trace.ycalendar; + var d2c = sa.type === "category" || sa.type === "multicategory" ? function() { + return null; + } : sa.d2c; + if (isArrayOrTypedArray$3(base)) { + for (j = 0; j < Math.min(base.length, cd.length); j++) { + b = d2c(base[j], 0, scalendar); + if (isNumeric$d(b)) { + cd[j].b = +b; + cd[j].hasB = 1; + } else cd[j].b = 0; + } + for (; j < cd.length; j++) { + cd[j].b = 0; + } + } else { + b = d2c(base, 0, scalendar); + var hasBase = isNumeric$d(b); + b = hasBase ? b : 0; + for (j = 0; j < cd.length; j++) { + cd[j].b = b; + if (hasBase) cd[j].hasB = 1; + } + } + } +} +function setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts) { + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var sieve2 = new Sieve([calcTrace], { + posAxis: pa, + sepNegVal: false, + overlapNoMerge: !opts.norm + }); + setOffsetAndWidth(pa, sieve2, opts); + if (opts.norm) { + sieveBars(sieve2); + normalizeBars(sa, sieve2, opts); + } else { + setBaseAndTop(sa, sieve2); + } + } +} +function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces, opts) { + var sieve2 = new Sieve(calcTraces, { + posAxis: pa, + sepNegVal: false, + overlapNoMerge: !opts.norm + }); + setOffsetAndWidthInGroupMode(gd, pa, sieve2, opts); + unhideBarsWithinTrace(sieve2, pa); + if (opts.norm) { + sieveBars(sieve2); + normalizeBars(sa, sieve2, opts); + } else { + setBaseAndTop(sa, sieve2); + } +} +function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces, opts) { + var sieve2 = new Sieve(calcTraces, { + posAxis: pa, + sepNegVal: opts.mode === "relative", + overlapNoMerge: !(opts.norm || opts.mode === "stack" || opts.mode === "relative") + }); + setOffsetAndWidth(pa, sieve2, opts); + stackBars(sa, sieve2, opts); + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + if (bar2.s !== BADNUM$4) { + var isOutmostBar = bar2.b + bar2.s === sieve2.get(bar2.p, bar2.s); + if (isOutmostBar) bar2._outmost = true; + } + } + } + if (opts.norm) normalizeBars(sa, sieve2, opts); +} +function setOffsetAndWidth(pa, sieve2, opts) { + var minDiff = sieve2.minDiff; + var calcTraces = sieve2.traces; + var barGroupWidth = minDiff * (1 - opts.gap); + var barWidthPlusGap = barGroupWidth; + var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0)); + var offsetFromCenter = -barWidth / 2; + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var t = calcTrace[0].t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; + } + sieve2.binWidth = calcTraces[0][0].t.barwidth / 100; + applyAttributes(sieve2); + setBarCenterAndWidth(pa, sieve2); + updatePositionAxis(pa, sieve2); +} +function setOffsetAndWidthInGroupMode(gd, pa, sieve2, opts) { + var fullLayout = gd._fullLayout; + var positions = sieve2.positions; + var distinctPositions = sieve2.distinctPositions; + var minDiff = sieve2.minDiff; + var calcTraces = sieve2.traces; + var nTraces = calcTraces.length; + var overlap = positions.length !== distinctPositions.length; + var barGroupWidth = minDiff * (1 - opts.gap); + var groupId = getAxisGroup$1(fullLayout, pa._id) + calcTraces[0][0].trace.orientation; + var alignmentGroups = fullLayout._alignmentOpts[groupId] || {}; + for (var i = 0; i < nTraces; i++) { + var calcTrace = calcTraces[i]; + var trace = calcTrace[0].trace; + var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {}; + var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length; + var barWidthPlusGap; + if (nOffsetGroups) { + barWidthPlusGap = barGroupWidth / nOffsetGroups; + } else { + barWidthPlusGap = overlap ? barGroupWidth / nTraces : barGroupWidth; + } + var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0)); + var offsetFromCenter; + if (nOffsetGroups) { + offsetFromCenter = ((2 * trace._offsetIndex + 1 - nOffsetGroups) * barWidthPlusGap - barWidth) / 2; + } else { + offsetFromCenter = overlap ? ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : -barWidth / 2; + } + var t = calcTrace[0].t; + t.barwidth = barWidth; + t.poffset = offsetFromCenter; + t.bargroupwidth = barGroupWidth; + t.bardelta = minDiff; + } + sieve2.binWidth = calcTraces[0][0].t.barwidth / 100; + applyAttributes(sieve2); + setBarCenterAndWidth(pa, sieve2); + updatePositionAxis(pa, sieve2, overlap); +} +function applyAttributes(sieve2) { + var calcTraces = sieve2.traces; + var i, j; + for (i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var calcTrace0 = calcTrace[0]; + var fullTrace = calcTrace0.trace; + var t = calcTrace0.t; + var offset = fullTrace._offset || fullTrace.offset; + var initialPoffset = t.poffset; + var newPoffset; + if (isArrayOrTypedArray$3(offset)) { + newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length); + for (j = 0; j < newPoffset.length; j++) { + if (!isNumeric$d(newPoffset[j])) { + newPoffset[j] = initialPoffset; + } + } + for (j = newPoffset.length; j < calcTrace.length; j++) { + newPoffset.push(initialPoffset); + } + t.poffset = newPoffset; + } else if (offset !== void 0) { + t.poffset = offset; + } + var width = fullTrace._width || fullTrace.width; + var initialBarwidth = t.barwidth; + if (isArrayOrTypedArray$3(width)) { + var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length); + for (j = 0; j < newBarwidth.length; j++) { + if (!isNumeric$d(newBarwidth[j])) newBarwidth[j] = initialBarwidth; + } + for (j = newBarwidth.length; j < calcTrace.length; j++) { + newBarwidth.push(initialBarwidth); + } + t.barwidth = newBarwidth; + if (offset === void 0) { + newPoffset = []; + for (j = 0; j < calcTrace.length; j++) { + newPoffset.push( + initialPoffset + (initialBarwidth - newBarwidth[j]) / 2 + ); + } + t.poffset = newPoffset; + } + } else if (width !== void 0) { + t.barwidth = width; + if (offset === void 0) { + t.poffset = initialPoffset + (initialBarwidth - width) / 2; + } + } + } +} +function setBarCenterAndWidth(pa, sieve2) { + var calcTraces = sieve2.traces; + var pLetter = getAxisLetter(pa); + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var t = calcTrace[0].t; + var poffset = t.poffset; + var poffsetIsArray = isArrayOrTypedArray$3(poffset); + var barwidth = t.barwidth; + var barwidthIsArray = isArrayOrTypedArray$3(barwidth); + for (var j = 0; j < calcTrace.length; j++) { + var calcBar = calcTrace[j]; + var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth; + if (calcBar.p === void 0) { + calcBar.p = calcBar[pLetter]; + calcBar["orig_" + pLetter] = calcBar[pLetter]; + } + var delta2 = (poffsetIsArray ? poffset[j] : poffset) + width / 2; + calcBar[pLetter] = calcBar.p + delta2; + } + } +} +function updatePositionAxis(pa, sieve2, allowMinDtick) { + var calcTraces = sieve2.traces; + var minDiff = sieve2.minDiff; + var vpad = minDiff / 2; + Axes$g.minDtick(pa, sieve2.minDiff, sieve2.distinctPositions[0], allowMinDtick); + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var calcTrace0 = calcTrace[0]; + var fullTrace = calcTrace0.trace; + var pts = []; + var bar2, l, r, j; + for (j = 0; j < calcTrace.length; j++) { + bar2 = calcTrace[j]; + l = bar2.p - vpad; + r = bar2.p + vpad; + pts.push(l, r); + } + if (fullTrace.width || fullTrace.offset) { + var t = calcTrace0.t; + var poffset = t.poffset; + var barwidth = t.barwidth; + var poffsetIsArray = isArrayOrTypedArray$3(poffset); + var barwidthIsArray = isArrayOrTypedArray$3(barwidth); + for (j = 0; j < calcTrace.length; j++) { + bar2 = calcTrace[j]; + var calcBarOffset = poffsetIsArray ? poffset[j] : poffset; + var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth; + l = bar2.p + calcBarOffset; + r = l + calcBarWidth; + pts.push(l, r); + } + } + fullTrace._extremes[pa._id] = Axes$g.findExtremes(pa, pts, { padded: false }); + } +} +function setBaseAndTop(sa, sieve2) { + var calcTraces = sieve2.traces; + var sLetter = getAxisLetter(sa); + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var fullTrace = calcTrace[0].trace; + var isScatter = fullTrace.type === "scatter"; + var isVertical2 = fullTrace.orientation === "v"; + var pts = []; + var tozero = false; + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + var base = isScatter ? 0 : bar2.b; + var top = isScatter ? isVertical2 ? bar2.y : bar2.x : base + bar2.s; + bar2[sLetter] = top; + pts.push(top); + if (bar2.hasB) pts.push(base); + if (!bar2.hasB || !bar2.b) { + tozero = true; + } + } + fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { + tozero, + padded: true + }); + } +} +function stackBars(sa, sieve2, opts) { + var sLetter = getAxisLetter(sa); + var calcTraces = sieve2.traces; + var calcTrace; + var fullTrace; + var isFunnel; + var i, j; + var bar2; + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + if (fullTrace.type === "funnel") { + for (j = 0; j < calcTrace.length; j++) { + bar2 = calcTrace[j]; + if (bar2.s !== BADNUM$4) { + sieve2.put(bar2.p, -0.5 * bar2.s); + } + } + } + } + for (i = 0; i < calcTraces.length; i++) { + calcTrace = calcTraces[i]; + fullTrace = calcTrace[0].trace; + isFunnel = fullTrace.type === "funnel"; + var pts = []; + for (j = 0; j < calcTrace.length; j++) { + bar2 = calcTrace[j]; + if (bar2.s !== BADNUM$4) { + var value2; + if (isFunnel) { + value2 = bar2.s; + } else { + value2 = bar2.s + bar2.b; + } + var base = sieve2.put(bar2.p, value2); + var top = base + value2; + bar2.b = base; + bar2[sLetter] = top; + if (!opts.norm) { + pts.push(top); + if (bar2.hasB) { + pts.push(base); + } + } + } + } + if (!opts.norm) { + fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { + // N.B. we don't stack base with 'base', + // so set tozero:true always! + tozero: true, + padded: true + }); + } + } +} +function sieveBars(sieve2) { + var calcTraces = sieve2.traces; + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + if (bar2.s !== BADNUM$4) { + sieve2.put(bar2.p, bar2.b + bar2.s); + } + } + } +} +function unhideBarsWithinTrace(sieve2, pa) { + var calcTraces = sieve2.traces; + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var fullTrace = calcTrace[0].trace; + if (fullTrace.base === void 0) { + var inTraceSieve = new Sieve([calcTrace], { + posAxis: pa, + sepNegVal: true, + overlapNoMerge: true + }); + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + if (bar2.p !== BADNUM$4) { + var base = inTraceSieve.put(bar2.p, bar2.b + bar2.s); + if (base) bar2.b = base; + } + } + } + } +} +function normalizeBars(sa, sieve2, opts) { + var calcTraces = sieve2.traces; + var sLetter = getAxisLetter(sa); + var sTop = opts.norm === "fraction" ? 1 : 100; + var sTiny = sTop / 1e9; + var sMin = sa.l2c(sa.c2l(0)); + var sMax = opts.mode === "stack" ? sTop : sMin; + function needsPadding(v) { + return isNumeric$d(sa.c2l(v)) && (v < sMin - sTiny || v > sMax + sTiny || !isNumeric$d(sMin)); + } + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + var fullTrace = calcTrace[0].trace; + var pts = []; + var tozero = false; + var padded = false; + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + if (bar2.s !== BADNUM$4) { + var scale2 = Math.abs(sTop / sieve2.get(bar2.p, bar2.s)); + bar2.b *= scale2; + bar2.s *= scale2; + var base = bar2.b; + var top = base + bar2.s; + bar2[sLetter] = top; + pts.push(top); + padded = padded || needsPadding(top); + if (bar2.hasB) { + pts.push(base); + padded = padded || needsPadding(base); + } + if (!bar2.hasB || !bar2.b) { + tozero = true; + } + } + } + fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { + tozero, + padded + }); + } +} +function setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa) { + var pLetter = getAxisLetter(pa); + for (var i = 0; i < calcTraces.length; i++) { + var calcTrace = calcTraces[i]; + for (var j = 0; j < calcTrace.length; j++) { + var bar2 = calcTrace[j]; + var pos = bar2[pLetter]; + bar2._sMin = sMinByPos[pos]; + bar2._sMax = sMaxByPos[pos]; + } + } +} +function collectExtents(calcTraces, pa) { + var pLetter = getAxisLetter(pa); + var extents = {}; + var i, j, cd; + var pMin = Infinity; + var pMax = -Infinity; + for (i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + for (j = 0; j < cd.length; j++) { + var p = cd[j].p; + if (isNumeric$d(p)) { + pMin = Math.min(pMin, p); + pMax = Math.max(pMax, p); + } + } + } + var roundFactor = 1e4 / (pMax - pMin); + var round2 = extents.round = function(p2) { + return String(Math.round(roundFactor * (p2 - pMin))); + }; + var sMinByPos = {}; + var sMaxByPos = {}; + var anyTraceHasCornerradius = calcTraces.some(function(x) { + var trace = x[0].trace; + return "marker" in trace && trace.marker.cornerradius; + }); + for (i = 0; i < calcTraces.length; i++) { + cd = calcTraces[i]; + cd[0].t.extents = extents; + var poffset = cd[0].t.poffset; + var poffsetIsArray = isArrayOrTypedArray$3(poffset); + for (j = 0; j < cd.length; j++) { + var di = cd[j]; + var p0 = di[pLetter] - di.w / 2; + if (isNumeric$d(p0)) { + var p1 = di[pLetter] + di.w / 2; + var pVal = round2(di.p); + if (extents[pVal]) { + extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])]; + } else { + extents[pVal] = [p0, p1]; + } + } + di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset); + di.p1 = di.p0 + di.w; + di.s0 = di.b; + di.s1 = di.s0 + di.s; + if (anyTraceHasCornerradius) { + var sMin = Math.min(di.s0, di.s1) || 0; + var sMax = Math.max(di.s0, di.s1) || 0; + var pos = di[pLetter]; + sMinByPos[pos] = pos in sMinByPos ? Math.min(sMinByPos[pos], sMin) : sMin; + sMaxByPos[pos] = pos in sMaxByPos ? Math.max(sMaxByPos[pos], sMax) : sMax; + } + } + } + if (anyTraceHasCornerradius) { + setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa); + } +} +function getAxisLetter(ax) { + return ax._id.charAt(0); +} +var cross_trace_calc$1 = { + crossTraceCalc: crossTraceCalc$1, + setGroupPositions: setGroupPositions$1 +}; +var calc$9 = calc_1$3; +var setGroupPositions = cross_trace_calc$1.setGroupPositions; +function groupCrossTraceCalc(gd, plotinfo) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var fullLayout = gd._fullLayout; + var fullTraces = gd._fullData; + var calcTraces = gd.calcdata; + var calcTracesHorz = []; + var calcTracesVert = []; + for (var i = 0; i < fullTraces.length; i++) { + var fullTrace = fullTraces[i]; + if (fullTrace.visible === true && fullTrace.type === "scatter" && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) { + if (fullTrace.orientation === "h") { + calcTracesHorz.push(calcTraces[i]); + } else if (fullTrace.orientation === "v") { + calcTracesVert.push(calcTraces[i]); + } + } + } + var opts = { + mode: fullLayout.scattermode, + gap: fullLayout.scattergap + }; + setGroupPositions(gd, xa, ya, calcTracesVert, opts); + setGroupPositions(gd, ya, xa, calcTracesHorz, opts); +} +var cross_trace_calc = function crossTraceCalc(gd, plotinfo) { + if (gd._fullLayout.scattermode === "group") { + groupCrossTraceCalc(gd, plotinfo); + } + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var subplot = xa._id + ya._id; + var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot]; + if (!subplotStackOpts) return; + var calcTraces = gd.calcdata; + var i, j, k, i2, cd, cd0, posj, sumj, norm2; + var groupOpts, interpolate2, groupnorm, posAttr, valAttr; + var hasAnyBlanks; + for (var stackGroup in subplotStackOpts) { + groupOpts = subplotStackOpts[stackGroup]; + var indices = groupOpts.traceIndices; + if (!indices.length) continue; + interpolate2 = groupOpts.stackgaps === "interpolate"; + groupnorm = groupOpts.groupnorm; + if (groupOpts.orientation === "v") { + posAttr = "x"; + valAttr = "y"; + } else { + posAttr = "y"; + valAttr = "x"; + } + hasAnyBlanks = new Array(indices.length); + for (i = 0; i < hasAnyBlanks.length; i++) { + hasAnyBlanks[i] = false; + } + cd0 = calcTraces[indices[0]]; + var allPositions = new Array(cd0.length); + for (i = 0; i < cd0.length; i++) { + allPositions[i] = cd0[i][posAttr]; + } + for (i = 1; i < indices.length; i++) { + cd = calcTraces[indices[i]]; + for (j = k = 0; j < cd.length; j++) { + posj = cd[j][posAttr]; + for (; posj > allPositions[k] && k < allPositions.length; k++) { + insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate2, posAttr); + j++; + } + if (posj !== allPositions[k]) { + for (i2 = 0; i2 < i; i2++) { + insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate2, posAttr); + } + allPositions.splice(k, 0, posj); + } + k++; + } + for (; k < allPositions.length; k++) { + insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate2, posAttr); + j++; + } + } + var serieslen = allPositions.length; + for (j = 0; j < cd0.length; j++) { + sumj = cd0[j][valAttr] = cd0[j].s; + for (i = 1; i < indices.length; i++) { + cd = calcTraces[indices[i]]; + cd[0].trace._rawLength = cd[0].trace._length; + cd[0].trace._length = serieslen; + sumj += cd[j].s; + cd[j][valAttr] = sumj; + } + if (groupnorm) { + norm2 = (groupnorm === "fraction" ? sumj : sumj / 100) || 1; + for (i = 0; i < indices.length; i++) { + var cdj = calcTraces[indices[i]][j]; + cdj[valAttr] /= norm2; + cdj.sNorm = cdj.s / norm2; + } + } + } + for (i = 0; i < indices.length; i++) { + cd = calcTraces[indices[i]]; + var trace = cd[0].trace; + var ppad = calc$9.calcMarkerSize(trace, trace._rawLength); + var arrayPad = Array.isArray(ppad); + if (ppad && hasAnyBlanks[i] || arrayPad) { + var ppadRaw = ppad; + ppad = new Array(serieslen); + for (j = 0; j < serieslen; j++) { + ppad[j] = cd[j].gap ? 0 : arrayPad ? ppadRaw[cd[j].i] : ppadRaw; + } + } + var x = new Array(serieslen); + var y = new Array(serieslen); + for (j = 0; j < serieslen; j++) { + x[j] = cd[j].x; + y[j] = cd[j].y; + } + calc$9.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + cd[0].t.orientation = groupOpts.orientation; + } + } +}; +function insertBlank(calcTrace, index2, position, traceIndex, hasAnyBlanks, interpolate2, posAttr) { + hasAnyBlanks[traceIndex] = true; + var newEntry = { + i: null, + gap: true, + s: 0 + }; + newEntry[posAttr] = position; + calcTrace.splice(index2, 0, newEntry); + if (index2 && position === calcTrace[index2 - 1][posAttr]) { + var prevEntry = calcTrace[index2 - 1]; + newEntry.s = prevEntry.s; + newEntry.i = prevEntry.i; + newEntry.gap = prevEntry.gap; + } else if (interpolate2) { + newEntry.s = getInterp(calcTrace, index2, position, posAttr); + } + if (!index2) { + calcTrace[0].t = calcTrace[1].t; + calcTrace[0].trace = calcTrace[1].trace; + delete calcTrace[1].t; + delete calcTrace[1].trace; + } +} +function getInterp(calcTrace, index2, position, posAttr) { + var pt0 = calcTrace[index2 - 1]; + var pt1 = calcTrace[index2 + 1]; + if (!pt1) return pt0.s; + if (!pt0) return pt1.s; + return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]); +} +var Drawing$i = drawingExports; +var numConstants$1 = numerical; +var BADNUM$3 = numConstants$1.BADNUM; +var LOG_CLIP = numConstants$1.LOG_CLIP; +var LOG_CLIP_PLUS = LOG_CLIP + 0.5; +var LOG_CLIP_MINUS = LOG_CLIP - 0.5; +var Lib$10 = libExports; +var segmentsIntersect = Lib$10.segmentsIntersect; +var constrain = Lib$10.constrain; +var constants$x = constants$B; +var line_points = function linePoints(d, opts) { + var trace = opts.trace || {}; + var xa = opts.xaxis; + var ya = opts.yaxis; + var xLog = xa.type === "log"; + var yLog = ya.type === "log"; + var xLen = xa._length; + var yLen = ya._length; + var backoff = opts.backoff; + var marker2 = trace.marker; + var connectGaps = opts.connectGaps; + var baseTolerance = opts.baseTolerance; + var shape = opts.shape; + var linear2 = shape === "linear"; + var fill = trace.fill && trace.fill !== "none"; + var segments = []; + var minTolerance = constants$x.minTolerance; + var len = d.length; + var pts = new Array(len); + var pti = 0; + var i; + var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt; + var thisPt; + var clusterHighFirst; + var clusterUnitVector; + var thisVector; + var clusterRefDist, clusterHighVal, clusterLowVal, thisVal; + var clusterMinDeviation, clusterMaxDeviation, thisDeviation; + function getPt(index2) { + var di = d[index2]; + if (!di) return false; + var x = opts.linearized ? xa.l2p(di.x) : xa.c2p(di.x); + var y = opts.linearized ? ya.l2p(di.y) : ya.c2p(di.y); + if (x === BADNUM$3) { + if (xLog) x = xa.c2p(di.x, true); + if (x === BADNUM$3) return false; + if (yLog && y === BADNUM$3) { + x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) / (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS))); + } + x *= 1e3; + } + if (y === BADNUM$3) { + if (yLog) y = ya.c2p(di.y, true); + if (y === BADNUM$3) return false; + y *= 1e3; + } + return [x, y]; + } + function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) { + var dx = xFrac1 - xFrac0; + var dy = yFrac1 - yFrac0; + var dx0 = 0.5 - xFrac0; + var dy0 = 0.5 - yFrac0; + var norm2 = dx * dx + dy * dy; + var dot2 = dx * dx0 + dy * dy0; + if (dot2 > 0 && dot2 < norm2) { + var cross = dx0 * dy - dy0 * dx; + if (cross * cross < norm2) return true; + } + } + var latestXFrac, latestYFrac; + function getTolerance(pt, nextPt2) { + var xFrac = pt[0] / xLen; + var yFrac = pt[1] / yLen; + var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1); + if (offScreenFraction && latestXFrac !== void 0 && crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)) { + offScreenFraction = 0; + } + if (offScreenFraction && nextPt2 && crossesViewport(xFrac, yFrac, nextPt2[0] / xLen, nextPt2[1] / yLen)) { + offScreenFraction = 0; + } + return (1 + constants$x.toleranceGrowth * offScreenFraction) * baseTolerance; + } + function ptDist(pt1, pt2) { + var dx = pt1[0] - pt2[0]; + var dy = pt1[1] - pt2[1]; + return Math.sqrt(dx * dx + dy * dy); + } + var maxScreensAway = constants$x.maxScreensAway; + var xEdge0 = -xLen * maxScreensAway; + var xEdge1 = xLen * (1 + maxScreensAway); + var yEdge0 = -yLen * maxScreensAway; + var yEdge1 = yLen * (1 + maxScreensAway); + var edges = [ + [xEdge0, yEdge0, xEdge1, yEdge0], + [xEdge1, yEdge0, xEdge1, yEdge1], + [xEdge1, yEdge1, xEdge0, yEdge1], + [xEdge0, yEdge1, xEdge0, yEdge0] + ]; + var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt; + function getLinearEdgeIntersections(pt1, pt2) { + var out = []; + var ptCount = 0; + for (var i2 = 0; i2 < 4; i2++) { + var edge = edges[i2]; + var ptInt = segmentsIntersect( + pt1[0], + pt1[1], + pt2[0], + pt2[1], + edge[0], + edge[1], + edge[2], + edge[3] + ); + if (ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || Math.abs(ptInt.y - out[0][1]) > 1)) { + ptInt = [ptInt.x, ptInt.y]; + if (ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt); + else out.push(ptInt); + ptCount++; + } + } + return out; + } + function onlyConstrainedPoint(pt) { + if (pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) { + return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)]; + } + } + function sameEdge(pt1, pt2) { + if (pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true; + if (pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true; + } + function getHVEdgeIntersections(pt1, pt2) { + var out = []; + var ptInt1 = onlyConstrainedPoint(pt1); + var ptInt2 = onlyConstrainedPoint(pt2); + if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out; + if (ptInt1) out.push(ptInt1); + if (ptInt2) out.push(ptInt2); + return out; + } + function getABAEdgeIntersections(dim, limit0, limit1) { + return function(pt1, pt2) { + var ptInt1 = onlyConstrainedPoint(pt1); + var ptInt2 = onlyConstrainedPoint(pt2); + var out = []; + if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out; + if (ptInt1) out.push(ptInt1); + if (ptInt2) out.push(ptInt2); + var midShift = 2 * Lib$10.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); + if (midShift) { + var ptToAlter; + if (ptInt1 && ptInt2) { + ptToAlter = midShift > 0 === ptInt1[dim] > ptInt2[dim] ? ptInt1 : ptInt2; + } else ptToAlter = ptInt1 || ptInt2; + ptToAlter[dim] += midShift; + } + return out; + }; + } + var getEdgeIntersections; + if (shape === "linear" || shape === "spline") { + getEdgeIntersections = getLinearEdgeIntersections; + } else if (shape === "hv" || shape === "vh") { + getEdgeIntersections = getHVEdgeIntersections; + } else if (shape === "hvh") getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1); + else if (shape === "vhv") getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1); + function getClosestCorner(pt1, pt2) { + var dx = pt2[0] - pt1[0]; + var m = (pt2[1] - pt1[1]) / dx; + var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx; + if (b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1]; + else return [m > 0 ? xEdge1 : xEdge0, yEdge0]; + } + function updateEdge(pt) { + var x = pt[0]; + var y = pt[1]; + var xSame = x === pts[pti - 1][0]; + var ySame = y === pts[pti - 1][1]; + if (xSame && ySame) return; + if (pti > 1) { + var xSame2 = x === pts[pti - 2][0]; + var ySame2 = y === pts[pti - 2][1]; + if (xSame && (x === xEdge0 || x === xEdge1) && xSame2) { + if (ySame2) pti--; + else pts[pti - 1] = pt; + } else if (ySame && (y === yEdge0 || y === yEdge1) && ySame2) { + if (xSame2) pti--; + else pts[pti - 1] = pt; + } else pts[pti++] = pt; + } else pts[pti++] = pt; + } + function updateEdgesForReentry(pt) { + if (pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) { + updateEdge([lastXEdge, lastYEdge]); + } + updateEdge(pt); + lastFarPt = null; + lastXEdge = lastYEdge = 0; + } + var arrayMarker = Lib$10.isArrayOrTypedArray(marker2); + function addPt(pt) { + if (pt && backoff) { + pt.i = i; + pt.d = d; + pt.trace = trace; + pt.marker = arrayMarker ? marker2[pt.i] : marker2; + pt.backoff = backoff; + } + latestXFrac = pt[0] / xLen; + latestYFrac = pt[1] / yLen; + xEdge = pt[0] < xEdge0 ? xEdge0 : pt[0] > xEdge1 ? xEdge1 : 0; + yEdge = pt[1] < yEdge0 ? yEdge0 : pt[1] > yEdge1 ? yEdge1 : 0; + if (xEdge || yEdge) { + if (!pti) { + pts[pti++] = [xEdge || pt[0], yEdge || pt[1]]; + } else if (lastFarPt) { + var intersections = getEdgeIntersections(lastFarPt, pt); + if (intersections.length > 1) { + updateEdgesForReentry(intersections[0]); + pts[pti++] = intersections[1]; + } + } else { + edgePt = getEdgeIntersections(pts[pti - 1], pt)[0]; + pts[pti++] = edgePt; + } + var lastPt = pts[pti - 1]; + if (xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) { + if (lastFarPt) { + if (lastXEdge !== xEdge && lastYEdge !== yEdge) { + if (lastXEdge && lastYEdge) { + updateEdge(getClosestCorner(lastFarPt, pt)); + } else { + updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]); + } + } else if (lastXEdge && lastYEdge) { + updateEdge([lastXEdge, lastYEdge]); + } + } + updateEdge([xEdge, yEdge]); + } else if (lastXEdge - xEdge && lastYEdge - yEdge) { + updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]); + } + lastFarPt = pt; + lastXEdge = xEdge; + lastYEdge = yEdge; + } else { + if (lastFarPt) { + updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]); + } + pts[pti++] = pt; + } + } + for (i = 0; i < len; i++) { + clusterStartPt = getPt(i); + if (!clusterStartPt) continue; + pti = 0; + lastFarPt = null; + addPt(clusterStartPt); + for (i++; i < len; i++) { + clusterHighPt = getPt(i); + if (!clusterHighPt) { + if (connectGaps) continue; + else break; + } + if (!linear2 || !opts.simplify) { + addPt(clusterHighPt); + continue; + } + var nextPt = getPt(i + 1); + clusterRefDist = ptDist(clusterHighPt, clusterStartPt); + if (!(fill && (pti === 0 || pti === len - 1)) && clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue; + clusterUnitVector = [ + (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist, + (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist + ]; + clusterLowPt = clusterStartPt; + clusterHighVal = clusterRefDist; + clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0; + clusterHighFirst = false; + clusterEndPt = clusterHighPt; + for (i++; i < d.length; i++) { + thisPt = nextPt; + nextPt = getPt(i + 1); + if (!thisPt) { + if (connectGaps) continue; + else break; + } + thisVector = [ + thisPt[0] - clusterStartPt[0], + thisPt[1] - clusterStartPt[1] + ]; + thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0]; + clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation); + clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation); + if (clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break; + clusterEndPt = thisPt; + thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1]; + if (thisVal > clusterHighVal) { + clusterHighVal = thisVal; + clusterHighPt = thisPt; + clusterHighFirst = false; + } else if (thisVal < clusterLowVal) { + clusterLowVal = thisVal; + clusterLowPt = thisPt; + clusterHighFirst = true; + } + } + if (clusterHighFirst) { + addPt(clusterHighPt); + if (clusterEndPt !== clusterLowPt) addPt(clusterLowPt); + } else { + if (clusterLowPt !== clusterStartPt) addPt(clusterLowPt); + if (clusterEndPt !== clusterHighPt) addPt(clusterHighPt); + } + addPt(clusterEndPt); + if (i >= d.length || !thisPt) break; + addPt(thisPt); + clusterStartPt = thisPt; + } + if (lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]); + segments.push(pts.slice(0, pti)); + } + var lastShapeChar = shape.slice(shape.length - 1); + if (backoff && lastShapeChar !== "h" && lastShapeChar !== "v") { + var trimmed = false; + var n = -1; + var newSegments = []; + for (var j = 0; j < segments.length; j++) { + for (var k = 0; k < segments[j].length - 1; k++) { + var start = segments[j][k]; + var end = segments[j][k + 1]; + var xy = Drawing$i.applyBackoff(end, start); + if (xy[0] !== end[0] || xy[1] !== end[1]) { + trimmed = true; + } + if (!newSegments[n + 1]) { + n++; + newSegments[n] = [ + start, + [xy[0], xy[1]] + ]; + } + } + } + return trimmed ? newSegments : segments; + } + return segments; +}; +var LINKEDFILLS = { tonextx: 1, tonexty: 1, tonext: 1 }; +var link_traces = function linkTraces(gd, plotinfo, cdscatter) { + var trace, i, group, prevtrace, groupIndex; + var groupIndices = {}; + var needsSort = false; + var prevGroupIndex = -1; + var nextGroupIndex = 0; + var prevUnstackedGroupIndex = -1; + for (i = 0; i < cdscatter.length; i++) { + trace = cdscatter[i][0].trace; + group = trace.stackgroup || ""; + if (group) { + if (group in groupIndices) { + groupIndex = groupIndices[group]; + } else { + groupIndex = groupIndices[group] = nextGroupIndex; + nextGroupIndex++; + } + } else if (trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) { + groupIndex = prevUnstackedGroupIndex; + } else { + groupIndex = prevUnstackedGroupIndex = nextGroupIndex; + nextGroupIndex++; + } + if (groupIndex < prevGroupIndex) needsSort = true; + trace._groupIndex = prevGroupIndex = groupIndex; + } + var cdscatterSorted = cdscatter.slice(); + if (needsSort) { + cdscatterSorted.sort(function(a, b) { + var traceA = a[0].trace; + var traceB = b[0].trace; + return traceA._groupIndex - traceB._groupIndex || traceA.index - traceB.index; + }); + } + var prevtraces = {}; + for (i = 0; i < cdscatterSorted.length; i++) { + trace = cdscatterSorted[i][0].trace; + group = trace.stackgroup || ""; + if (trace.visible === true) { + trace._nexttrace = null; + if (trace.fill in LINKEDFILLS) { + prevtrace = prevtraces[group]; + trace._prevtrace = prevtrace || null; + if (prevtrace) { + prevtrace._nexttrace = trace; + } + } + trace._ownfill = trace.fill && (trace.fill.substr(0, 6) === "tozero" || trace.fill === "toself" || trace.fill.substr(0, 2) === "to" && !trace._prevtrace); + prevtraces[group] = trace; + } else { + trace._prevtrace = trace._nexttrace = trace._ownfill = null; + } + } + return cdscatterSorted; +}; +var d3$n = d3Exports; +var Registry$n = registry; +var Lib$$ = libExports; +var ensureSingle$1 = Lib$$.ensureSingle; +var identity$1 = Lib$$.identity; +var Drawing$h = drawingExports; +var subTypes$4 = subtypes$3; +var linePoints2 = line_points; +var linkTraces$1 = link_traces; +var polygonTester = polygonExports.tester; +var plot$7 = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) { + var join, onComplete; + var isFullReplot = !transitionOpts; + var hasTransition2 = !!transitionOpts && transitionOpts.duration > 0; + var cdscatterSorted = linkTraces$1(gd, plotinfo, cdscatter); + join = scatterLayer.selectAll("g.trace").data(cdscatterSorted, function(d) { + return d[0].trace.uid; + }); + join.enter().append("g").attr("class", function(d) { + return "trace scatter trace" + d[0].trace.uid; + }).style("stroke-miterlimit", 2); + join.order(); + createFills(gd, join, plotinfo); + if (hasTransition2) { + if (makeOnCompleteCallback) { + onComplete = makeOnCompleteCallback(); + } + var transition2 = d3$n.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { + onComplete && onComplete(); + }).each("interrupt", function() { + onComplete && onComplete(); + }); + transition2.each(function() { + scatterLayer.selectAll("g.trace").each(function(d, i) { + plotOne$2(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts); + }); + }); + } else { + join.each(function(d, i) { + plotOne$2(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts); + }); + } + if (isFullReplot) { + join.exit().remove(); + } + scatterLayer.selectAll("path:not([d])").remove(); +}; +function createFills(gd, traceJoin, plotinfo) { + traceJoin.each(function(d) { + var fills = ensureSingle$1(d3$n.select(this), "g", "fills"); + Drawing$h.setClipUrl(fills, plotinfo.layerClipId, gd); + var trace = d[0].trace; + var fillData = []; + if (trace._ownfill) fillData.push("_ownFill"); + if (trace._nexttrace) fillData.push("_nextFill"); + var fillJoin = fills.selectAll("g").data(fillData, identity$1); + fillJoin.enter().append("g"); + fillJoin.exit().each(function(d2) { + trace[d2] = null; + }).remove(); + fillJoin.order().each(function(d2) { + trace[d2] = ensureSingle$1(d3$n.select(this), "path", "js-fill"); + }); + }); +} +function plotOne$2(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { + var isStatic = gd._context.staticPlot; + var i; + selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll); + var hasTransition2 = !!transitionOpts && transitionOpts.duration > 0; + function transition2(selection) { + return hasTransition2 ? selection.transition() : selection; + } + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var trace = cdscatter[0].trace; + var line2 = trace.line; + var tr = d3$n.select(element); + var errorBarGroup = ensureSingle$1(tr, "g", "errorbars"); + var lines = ensureSingle$1(tr, "g", "lines"); + var points = ensureSingle$1(tr, "g", "points"); + var text = ensureSingle$1(tr, "g", "text"); + Registry$n.getComponentMethod("errorbars", "plot")(gd, errorBarGroup, plotinfo, transitionOpts); + if (trace.visible !== true) return; + transition2(tr).style("opacity", trace.opacity); + var ownFillEl3, tonext; + var ownFillDir = trace.fill.charAt(trace.fill.length - 1); + if (ownFillDir !== "x" && ownFillDir !== "y") ownFillDir = ""; + var fillAxisIndex, fillAxisZero; + if (ownFillDir === "y") { + fillAxisIndex = 1; + fillAxisZero = ya.c2p(0, true); + } else if (ownFillDir === "x") { + fillAxisIndex = 0; + fillAxisZero = xa.c2p(0, true); + } + cdscatter[0][plotinfo.isRangePlot ? "nodeRangePlot3" : "node3"] = tr; + var prevRevpath = ""; + var prevPolygons = []; + var prevtrace = trace._prevtrace; + var prevFillsegments = null; + var prevFillElement = null; + if (prevtrace) { + prevRevpath = prevtrace._prevRevpath || ""; + tonext = prevtrace._nextFill; + prevPolygons = prevtrace._ownPolygons; + prevFillsegments = prevtrace._fillsegments; + prevFillElement = prevtrace._fillElement; + } + var thispath; + var thisrevpath; + var fullpath = ""; + var revpath = ""; + var pathfn, revpathbase, revpathfn; + var pt0, lastSegment, pt1; + var thisPolygons = []; + trace._polygons = []; + var fillsegments = []; + var segments = []; + var makeUpdate = Lib$$.noop; + ownFillEl3 = trace._ownFill; + if (subTypes$4.hasLines(trace) || trace.fill !== "none") { + if (tonext) { + tonext.datum(cdscatter); + } + if (["hv", "vh", "hvh", "vhv"].indexOf(line2.shape) !== -1) { + pathfn = Drawing$h.steps(line2.shape); + revpathbase = Drawing$h.steps( + line2.shape.split("").reverse().join("") + ); + } else if (line2.shape === "spline") { + pathfn = revpathbase = function(pts2) { + var pLast = pts2[pts2.length - 1]; + if (pts2.length > 1 && pts2[0][0] === pLast[0] && pts2[0][1] === pLast[1]) { + return Drawing$h.smoothclosed(pts2.slice(1), line2.smoothing); + } else { + return Drawing$h.smoothopen(pts2, line2.smoothing); + } + }; + } else { + pathfn = revpathbase = function(pts2) { + return "M" + pts2.join("L"); + }; + } + revpathfn = function(pts2) { + return revpathbase(pts2.reverse()); + }; + segments = linePoints2(cdscatter, { + xaxis: xa, + yaxis: ya, + trace, + connectGaps: trace.connectgaps, + baseTolerance: Math.max(line2.width || 1, 3) / 4, + shape: line2.shape, + backoff: line2.backoff, + simplify: line2.simplify, + fill: trace.fill + }); + fillsegments = new Array(segments.length); + var fillsegmentCount = 0; + for (i = 0; i < segments.length; i++) { + var curpoints; + var pts = segments[i]; + if (!curpoints || !ownFillDir) { + curpoints = pts.slice(); + fillsegments[fillsegmentCount] = curpoints; + fillsegmentCount++; + } else { + curpoints.push.apply(curpoints, pts); + } + } + trace._fillElement = null; + trace._fillExclusionElement = prevFillElement; + trace._fillsegments = fillsegments.slice(0, fillsegmentCount); + fillsegments = trace._fillsegments; + if (segments.length) { + pt0 = segments[0][0].slice(); + lastSegment = segments[segments.length - 1]; + pt1 = lastSegment[lastSegment.length - 1].slice(); + } + makeUpdate = function(isEnter) { + return function(pts2) { + thispath = pathfn(pts2); + thisrevpath = revpathfn(pts2); + if (!fullpath) { + fullpath = thispath; + revpath = thisrevpath; + } else if (ownFillDir) { + fullpath += "L" + thispath.substr(1); + revpath = thisrevpath + ("L" + revpath.substr(1)); + } else { + fullpath += "Z" + thispath; + revpath = thisrevpath + "Z" + revpath; + } + if (subTypes$4.hasLines(trace)) { + var el = d3$n.select(this); + el.datum(cdscatter); + if (isEnter) { + transition2(el.style("opacity", 0).attr("d", thispath).call(Drawing$h.lineGroupStyle)).style("opacity", 1); + } else { + var sel = transition2(el); + sel.attr("d", thispath); + Drawing$h.singleLineStyle(cdscatter, sel); + } + } + }; + }; + } + var lineJoin = lines.selectAll(".js-line").data(segments); + transition2(lineJoin.exit()).style("opacity", 0).remove(); + lineJoin.each(makeUpdate(false)); + lineJoin.enter().append("path").classed("js-line", true).style("vector-effect", isStatic ? "none" : "non-scaling-stroke").call(Drawing$h.lineGroupStyle).each(makeUpdate(true)); + Drawing$h.setClipUrl(lineJoin, plotinfo.layerClipId, gd); + function clearFill(selection) { + transition2(selection).attr("d", "M0,0Z"); + } + var makeSelfPolygons = function() { + var polygons = new Array(fillsegments.length); + for (i = 0; i < fillsegments.length; i++) { + polygons[i] = polygonTester(fillsegments[i]); + } + return polygons; + }; + var makePolygonsToPrevious = function(prevFillsegments2) { + var polygons, i2; + if (!prevFillsegments2 || prevFillsegments2.length === 0) { + polygons = new Array(fillsegments.length); + for (i2 = 0; i2 < fillsegments.length; i2++) { + var pt02 = fillsegments[i2][0].slice(); + var pt12 = fillsegments[i2][fillsegments[i2].length - 1].slice(); + pt02[fillAxisIndex] = pt12[fillAxisIndex] = fillAxisZero; + var zeropoints = [pt12, pt02]; + var polypoints = zeropoints.concat(fillsegments[i2]); + polygons[i2] = polygonTester(polypoints); + } + } else { + polygons = new Array(prevFillsegments2.length - 1 + fillsegments.length); + for (i2 = 0; i2 < prevFillsegments2.length - 1; i2++) { + polygons[i2] = polygonTester(prevFillsegments2[i2]); + } + var reversedPrevFillsegment = prevFillsegments2[prevFillsegments2.length - 1].slice(); + reversedPrevFillsegment.reverse(); + for (i2 = 0; i2 < fillsegments.length; i2++) { + polygons[prevFillsegments2.length - 1 + i2] = polygonTester(fillsegments[i2].concat(reversedPrevFillsegment)); + } + } + return polygons; + }; + if (segments.length) { + if (ownFillEl3) { + ownFillEl3.datum(cdscatter); + if (pt0 && pt1) { + if (ownFillDir) { + pt0[fillAxisIndex] = pt1[fillAxisIndex] = fillAxisZero; + transition2(ownFillEl3).attr("d", "M" + pt1 + "L" + pt0 + "L" + fullpath.substr(1)).call(Drawing$h.singleFillStyle, gd); + thisPolygons = makePolygonsToPrevious(null); + } else { + transition2(ownFillEl3).attr("d", fullpath + "Z").call(Drawing$h.singleFillStyle, gd); + thisPolygons = makeSelfPolygons(); + } + } + trace._polygons = thisPolygons; + trace._fillElement = ownFillEl3; + } else if (tonext) { + if (trace.fill.substr(0, 6) === "tonext" && fullpath && prevRevpath) { + if (trace.fill === "tonext") { + transition2(tonext).attr("d", fullpath + "Z" + prevRevpath + "Z").call(Drawing$h.singleFillStyle, gd); + thisPolygons = makeSelfPolygons(); + trace._polygons = thisPolygons.concat(prevPolygons); + } else { + transition2(tonext).attr("d", fullpath + "L" + prevRevpath.substr(1) + "Z").call(Drawing$h.singleFillStyle, gd); + thisPolygons = makePolygonsToPrevious(prevFillsegments); + trace._polygons = thisPolygons; + } + trace._fillElement = tonext; + } else { + clearFill(tonext); + } + } + trace._prevRevpath = revpath; + } else { + if (ownFillEl3) clearFill(ownFillEl3); + else if (tonext) clearFill(tonext); + trace._prevRevpath = null; + } + trace._ownPolygons = thisPolygons; + function visFilter(d) { + return d.filter(function(v) { + return !v.gap && v.vis; + }); + } + function visFilterWithGaps(d) { + return d.filter(function(v) { + return v.vis; + }); + } + function gapFilter(d) { + return d.filter(function(v) { + return !v.gap; + }); + } + function keyFunc2(d) { + return d.id; + } + function getKeyFunc2(trace2) { + if (trace2.ids) { + return keyFunc2; + } + } + function hideFilter() { + return false; + } + function makePoints(points2, text2, cdscatter2) { + var join, selection, hasNode; + var trace2 = cdscatter2[0].trace; + var showMarkers = subTypes$4.hasMarkers(trace2); + var showText = subTypes$4.hasText(trace2); + var keyFunc3 = getKeyFunc2(trace2); + var markerFilter = hideFilter; + var textFilter = hideFilter; + if (showMarkers || showText) { + var showFilter = identity$1; + var stackGroup = trace2.stackgroup; + var isInferZero = stackGroup && gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === "infer zero"; + if (trace2.marker.maxdisplayed || trace2._needsCull) { + showFilter = isInferZero ? visFilterWithGaps : visFilter; + } else if (stackGroup && !isInferZero) { + showFilter = gapFilter; + } + if (showMarkers) markerFilter = showFilter; + if (showText) textFilter = showFilter; + } + selection = points2.selectAll("path.point"); + join = selection.data(markerFilter, keyFunc3); + var enter = join.enter().append("path").classed("point", true); + if (hasTransition2) { + enter.call(Drawing$h.pointStyle, trace2, gd).call(Drawing$h.translatePoints, xa, ya).style("opacity", 0).transition().style("opacity", 1); + } + join.order(); + var styleFns; + if (showMarkers) { + styleFns = Drawing$h.makePointStyleFns(trace2); + } + join.each(function(d) { + var el = d3$n.select(this); + var sel = transition2(el); + hasNode = Drawing$h.translatePoint(d, sel, xa, ya); + if (hasNode) { + Drawing$h.singlePointStyle(d, sel, trace2, styleFns, gd); + if (plotinfo.layerClipId) { + Drawing$h.hideOutsideRangePoint(d, sel, xa, ya, trace2.xcalendar, trace2.ycalendar); + } + if (trace2.customdata) { + el.classed("plotly-customdata", d.data !== null && d.data !== void 0); + } + } else { + sel.remove(); + } + }); + if (hasTransition2) { + join.exit().transition().style("opacity", 0).remove(); + } else { + join.exit().remove(); + } + selection = text2.selectAll("g"); + join = selection.data(textFilter, keyFunc3); + join.enter().append("g").classed("textpoint", true).append("text"); + join.order(); + join.each(function(d) { + var g = d3$n.select(this); + var sel = transition2(g.select("text")); + hasNode = Drawing$h.translatePoint(d, sel, xa, ya); + if (hasNode) { + if (plotinfo.layerClipId) { + Drawing$h.hideOutsideRangePoint(d, g, xa, ya, trace2.xcalendar, trace2.ycalendar); + } + } else { + g.remove(); + } + }); + join.selectAll("text").call(Drawing$h.textPointStyle, trace2, gd).each(function(d) { + var x = xa.c2p(d.x); + var y = ya.c2p(d.y); + d3$n.select(this).selectAll("tspan.line").each(function() { + transition2(d3$n.select(this)).attr({ x, y }); + }); + }); + join.exit().remove(); + } + points.datum(cdscatter); + text.datum(cdscatter); + makePoints(points, text, cdscatter); + var hasClipOnAxisFalse = trace.cliponaxis === false; + var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId; + Drawing$h.setClipUrl(points, clipUrl, gd); + Drawing$h.setClipUrl(text, clipUrl, gd); +} +function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var xr = d3$n.extent(Lib$$.simpleMap(xa.range, xa.r2c)); + var yr = d3$n.extent(Lib$$.simpleMap(ya.range, ya.r2c)); + var trace = cdscatter[0].trace; + if (!subTypes$4.hasMarkers(trace)) return; + var mnum = trace.marker.maxdisplayed; + if (mnum === 0) return; + var cd = cdscatter.filter(function(v) { + return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; + }); + var inc = Math.ceil(cd.length / mnum); + var tnum = 0; + cdscatterAll.forEach(function(cdj, j) { + var tracei = cdj[0].trace; + if (subTypes$4.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { + tnum++; + } + }); + var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); + cdscatter.forEach(function(v) { + delete v.vis; + }); + cd.forEach(function(v, i) { + if (Math.round((i + i0) % inc) === 0) v.vis = true; + }); +} +var marker_colorbar = { + container: "marker", + min: "cmin", + max: "cmax" +}; +var Axes$f = axesExports; +var format_labels$1 = function formatLabels(cdi, trace, fullLayout) { + var labels = {}; + var mockGd = { _fullLayout: fullLayout }; + var xa = Axes$f.getFromTrace(mockGd, trace, "x"); + var ya = Axes$f.getFromTrace(mockGd, trace, "y"); + var x = cdi.orig_x; + if (x === void 0) x = cdi.x; + var y = cdi.orig_y; + if (y === void 0) y = cdi.y; + labels.xLabel = Axes$f.tickText(xa, xa.c2l(x), true).text; + labels.yLabel = Axes$f.tickText(ya, ya.c2l(y), true).text; + return labels; +}; +var d3$m = d3Exports; +var Drawing$g = drawingExports; +var Registry$m = registry; +function style$6(gd) { + var s = d3$m.select(gd).selectAll("g.trace.scatter"); + s.style("opacity", function(d) { + return d[0].trace.opacity; + }); + s.selectAll("g.points").each(function(d) { + var sel = d3$m.select(this); + var trace = d.trace || d[0].trace; + stylePoints$1(sel, trace, gd); + }); + s.selectAll("g.text").each(function(d) { + var sel = d3$m.select(this); + var trace = d.trace || d[0].trace; + styleText(sel, trace, gd); + }); + s.selectAll("g.trace path.js-line").call(Drawing$g.lineGroupStyle); + s.selectAll("g.trace path.js-fill").call(Drawing$g.fillGroupStyle, gd, false); + Registry$m.getComponentMethod("errorbars", "style")(s); +} +function stylePoints$1(sel, trace, gd) { + Drawing$g.pointStyle(sel.selectAll("path.point"), trace, gd); +} +function styleText(sel, trace, gd) { + Drawing$g.textPointStyle(sel.selectAll("text"), trace, gd); +} +function styleOnSelect$1(gd, cd, sel) { + var trace = cd[0].trace; + if (trace.selectedpoints) { + Drawing$g.selectedPointStyle(sel.selectAll("path.point"), trace); + Drawing$g.selectedTextStyle(sel.selectAll("text"), trace); + } else { + stylePoints$1(sel, trace, gd); + styleText(sel, trace, gd); + } +} +var style_1$3 = { + style: style$6, + styleOnSelect: styleOnSelect$1 +}; +var Color$s = colorExports; +var subtypes$2 = subtypes$3; +var get_trace_color = function getTraceColor(trace, di) { + var lc, tc; + if (trace.mode === "lines") { + lc = trace.line.color; + return lc && Color$s.opacity(lc) ? lc : trace.fillcolor; + } else if (trace.mode === "none") { + return trace.fill ? trace.fillcolor : ""; + } else { + var mc = di.mcc || (trace.marker || {}).color; + var mlc = di.mlcc || ((trace.marker || {}).line || {}).color; + tc = mc && Color$s.opacity(mc) ? mc : mlc && Color$s.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width) ? mlc : ""; + if (tc) { + if (Color$s.opacity(tc) < 0.3) { + return Color$s.addOpacity(tc, 0.3); + } else return tc; + } else { + lc = (trace.line || {}).color; + return lc && Color$s.opacity(lc) && subtypes$2.hasLines(trace) && trace.line.width ? lc : trace.fillcolor; + } + } +}; +var Lib$_ = libExports; +var Fx$5 = fx$1; +var Registry$l = registry; +var getTraceColor$2 = get_trace_color; +var Color$r = colorExports; +var fillText$2 = Lib$_.fillText; +var hover$5 = function hoverPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + var xa = pointData.xa; + var ya = pointData.ya; + var xpx = xa.c2p(xval); + var ypx = ya.c2p(yval); + var pt = [xpx, ypx]; + var hoveron = trace.hoveron || ""; + var minRad = trace.mode.indexOf("markers") !== -1 ? 3 : 0.5; + var xPeriod = !!trace.xperiodalignment; + var yPeriod = !!trace.yperiodalignment; + if (hoveron.indexOf("points") !== -1) { + var dx = function(di2) { + if (xPeriod) { + var x0 = xa.c2p(di2.xStart); + var x1 = xa.c2p(di2.xEnd); + return xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity; + } + var rad2 = Math.max(3, di2.mrc || 0); + var kink = 1 - 1 / rad2; + var dxRaw = Math.abs(xa.c2p(di2.x) - xpx); + return dxRaw < rad2 ? kink * dxRaw / rad2 : dxRaw - rad2 + kink; + }; + var dy = function(di2) { + if (yPeriod) { + var y0 = ya.c2p(di2.yStart); + var y1 = ya.c2p(di2.yEnd); + return ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity; + } + var rad2 = Math.max(3, di2.mrc || 0); + var kink = 1 - 1 / rad2; + var dyRaw = Math.abs(ya.c2p(di2.y) - ypx); + return dyRaw < rad2 ? kink * dyRaw / rad2 : dyRaw - rad2 + kink; + }; + var dxy = function(di2) { + var rad2 = Math.max(minRad, di2.mrc || 0); + var dx2 = xa.c2p(di2.x) - xpx; + var dy2 = ya.c2p(di2.y) - ypx; + return Math.max(Math.sqrt(dx2 * dx2 + dy2 * dy2) - rad2, 1 - minRad / rad2); + }; + var distfn = Fx$5.getDistanceFunction(hovermode, dx, dy, dxy); + Fx$5.getClosest(cd, distfn, pointData); + if (pointData.index !== false) { + var di = cd[pointData.index]; + var xc = xa.c2p(di.x, true); + var yc = ya.c2p(di.y, true); + var rad = di.mrc || 1; + pointData.index = di.i; + var orientation = cd[0].t.orientation; + var sizeVal = orientation && (di.sNorm || di.s); + var xLabelVal = orientation === "h" ? sizeVal : di.orig_x !== void 0 ? di.orig_x : di.x; + var yLabelVal = orientation === "v" ? sizeVal : di.orig_y !== void 0 ? di.orig_y : di.y; + Lib$_.extendFlat(pointData, { + color: getTraceColor$2(trace, di), + x0: xc - rad, + x1: xc + rad, + xLabelVal, + y0: yc - rad, + y1: yc + rad, + yLabelVal, + spikeDistance: dxy(di), + hovertemplate: trace.hovertemplate + }); + fillText$2(di, trace, pointData); + Registry$l.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData); + return [pointData]; + } + } + function isHoverPointInFillElement(el) { + if (!el) { + return false; + } + var svgElement = el.node(); + try { + var domPoint = new DOMPoint(pt[0], pt[1]); + return svgElement.isPointInFill(domPoint); + } catch (TypeError2) { + var svgPoint = svgElement.ownerSVGElement.createSVGPoint(); + svgPoint.x = pt[0]; + svgPoint.y = pt[1]; + return svgElement.isPointInFill(svgPoint); + } + } + function getHoverLabelPosition(polygons) { + var i; + var polygonsIn = []; + var xmin = Infinity; + var xmax = -Infinity; + var ymin = Infinity; + var ymax = -Infinity; + var yPos; + for (i = 0; i < polygons.length; i++) { + var polygon2 = polygons[i]; + if (polygon2.contains(pt)) { + polygonsIn.push(polygon2); + ymin = Math.min(ymin, polygon2.ymin); + ymax = Math.max(ymax, polygon2.ymax); + } + } + if (polygonsIn.length === 0) { + return null; + } + ymin = Math.max(ymin, 0); + ymax = Math.min(ymax, ya._length); + yPos = (ymin + ymax) / 2; + var j, pts, xAtYPos, x0, x1, y0, y1; + for (i = 0; i < polygonsIn.length; i++) { + pts = polygonsIn[i].pts; + for (j = 1; j < pts.length; j++) { + y0 = pts[j - 1][1]; + y1 = pts[j][1]; + if (y0 > yPos !== y1 >= yPos) { + x0 = pts[j - 1][0]; + x1 = pts[j][0]; + if (y1 - y0) { + xAtYPos = x0 + (x1 - x0) * (yPos - y0) / (y1 - y0); + xmin = Math.min(xmin, xAtYPos); + xmax = Math.max(xmax, xAtYPos); + } + } + } + } + xmin = Math.max(xmin, 0); + xmax = Math.min(xmax, xa._length); + return { + x0: xmin, + x1: xmax, + y0: yPos, + y1: yPos + }; + } + if (hoveron.indexOf("fills") !== -1 && trace._fillElement) { + var inside = isHoverPointInFillElement(trace._fillElement) && !isHoverPointInFillElement(trace._fillExclusionElement); + if (inside) { + var hoverLabelCoords = getHoverLabelPosition(trace._polygons); + if (hoverLabelCoords === null) { + hoverLabelCoords = { + x0: pt[0], + x1: pt[0], + y0: pt[1], + y1: pt[1] + }; + } + var color2 = Color$r.defaultLine; + if (Color$r.opacity(trace.fillcolor)) color2 = trace.fillcolor; + else if (Color$r.opacity((trace.line || {}).color)) { + color2 = trace.line.color; + } + Lib$_.extendFlat(pointData, { + // never let a 2D override 1D type as closest point + // also: no spikeDistance, it's not allowed for fills + distance: pointData.maxHoverDistance, + x0: hoverLabelCoords.x0, + x1: hoverLabelCoords.x1, + y0: hoverLabelCoords.y0, + y1: hoverLabelCoords.y1, + color: color2, + hovertemplate: false + }); + delete pointData.index; + if (trace.text && !Lib$_.isArrayOrTypedArray(trace.text)) { + pointData.text = String(trace.text); + } else pointData.text = trace.name; + return [pointData]; + } + } +}; +var subtypes$1 = subtypes$3; +var select$3 = function selectPoints(searchInfo, selectionTester) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var trace = cd[0].trace; + var i; + var di; + var x; + var y; + var hasOnlyLines = !subtypes$1.hasMarkers(trace) && !subtypes$1.hasText(trace); + if (hasOnlyLines) return []; + if (selectionTester === false) { + for (i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for (i = 0; i < cd.length; i++) { + di = cd[i]; + x = xa.c2p(di.x); + y = ya.c2p(di.y); + if (di.i !== null && selectionTester.contains([x, y], false, i, searchInfo)) { + selection.push({ + pointNumber: di.i, + x: xa.c2d(di.x), + y: ya.c2d(di.y) + }); + di.selected = 1; + } else { + di.selected = 0; + } + } + } + return selection; +}; +var cartesian = {}; +var attributes$v; +var hasRequiredAttributes; +function requireAttributes() { + if (hasRequiredAttributes) return attributes$v; + hasRequiredAttributes = 1; + attributes$v = { + xaxis: { + valType: "subplotid", + dflt: "x", + editType: "calc+clearAxisTypes", + description: [ + "Sets a reference between this trace's x coordinates and", + "a 2D cartesian x axis.", + "If *x* (the default value), the x coordinates refer to", + "`layout.xaxis`.", + "If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." + ].join(" ") + }, + yaxis: { + valType: "subplotid", + dflt: "y", + editType: "calc+clearAxisTypes", + description: [ + "Sets a reference between this trace's y coordinates and", + "a 2D cartesian y axis.", + "If *y* (the default value), the y coordinates refer to", + "`layout.yaxis`.", + "If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." + ].join(" ") + } + }; + return attributes$v; +} +var type_defaults; +var hasRequiredType_defaults; +function requireType_defaults() { + if (hasRequiredType_defaults) return type_defaults; + hasRequiredType_defaults = 1; + var traceIs2 = registry.traceIs; + var autoType3 = axis_autotype; + type_defaults = function handleTypeDefaults(containerIn, containerOut, coerce2, options) { + coerce2("autotypenumbers", options.autotypenumbersDflt); + var axType = coerce2("type", (options.splomStash || {}).type); + if (axType === "-") { + setAutoType(containerOut, options.data); + if (containerOut.type === "-") { + containerOut.type = "linear"; + } else { + containerIn.type = containerOut.type; + } + } + }; + function setAutoType(ax, data) { + if (ax.type !== "-") return; + var id = ax._id; + var axLetter = id.charAt(0); + var i; + if (id.indexOf("scene") !== -1) id = axLetter; + var d0 = getFirstNonEmptyTrace(data, id, axLetter); + if (!d0) return; + if (d0.type === "histogram" && axLetter === { v: "y", h: "x" }[d0.orientation || "v"]) { + ax.type = "linear"; + return; + } + var calAttr = axLetter + "calendar"; + var calendar = d0[calAttr]; + var opts = { noMultiCategory: !traceIs2(d0, "cartesian") || traceIs2(d0, "noMultiCategory") }; + if (d0.type === "box" && d0._hasPreCompStats && axLetter === { h: "x", v: "y" }[d0.orientation || "v"]) { + opts.noMultiCategory = true; + } + opts.autotypenumbers = ax.autotypenumbers; + if (isBoxWithoutPositionCoords(d0, axLetter)) { + var posLetter = getBoxPosLetter(d0); + var boxPositions = []; + for (i = 0; i < data.length; i++) { + var trace = data[i]; + if (!traceIs2(trace, "box-violin") || (trace[axLetter + "axis"] || axLetter) !== id) continue; + if (trace[posLetter] !== void 0) boxPositions.push(trace[posLetter][0]); + else if (trace.name !== void 0) boxPositions.push(trace.name); + else boxPositions.push("text"); + if (trace[calAttr] !== calendar) calendar = void 0; + } + ax.type = autoType3(boxPositions, calendar, opts); + } else if (d0.type === "splom") { + var dimensions = d0.dimensions; + var dim = dimensions[d0._axesDim[id]]; + if (dim.visible) ax.type = autoType3(dim.values, calendar, opts); + } else { + ax.type = autoType3(d0[axLetter] || [d0[axLetter + "0"]], calendar, opts); + } + } + function getFirstNonEmptyTrace(data, id, axLetter) { + for (var i = 0; i < data.length; i++) { + var trace = data[i]; + if (trace.type === "splom" && trace._length > 0 && (trace["_" + axLetter + "axes"] || {})[id]) { + return trace; + } + if ((trace[axLetter + "axis"] || axLetter) === id) { + if (isBoxWithoutPositionCoords(trace, axLetter)) { + return trace; + } else if ((trace[axLetter] || []).length || trace[axLetter + "0"]) { + return trace; + } + } + } + } + function getBoxPosLetter(trace) { + return { v: "x", h: "y" }[trace.orientation || "v"]; + } + function isBoxWithoutPositionCoords(trace, axLetter) { + var posLetter = getBoxPosLetter(trace); + var isBox = traceIs2(trace, "box-violin"); + var isCandlestick = traceIs2(trace._fullInput || {}, "candlestick"); + return isBox && !isCandlestick && axLetter === posLetter && trace[posLetter] === void 0 && trace[posLetter + "0"] === void 0; + } + return type_defaults; +} +var isTypedArraySpec = array$2.isTypedArraySpec; +function findCategories(ax, opts) { + var dataAttr = opts.dataAttr || ax._id.charAt(0); + var lookup2 = {}; + var axData; + var i, j; + if (opts.axData) { + axData = opts.axData; + } else { + axData = []; + for (i = 0; i < opts.data.length; i++) { + var trace = opts.data[i]; + if (trace[dataAttr + "axis"] === ax._id) { + axData.push(trace); + } + } + } + for (i = 0; i < axData.length; i++) { + var vals = axData[i][dataAttr]; + for (j = 0; j < vals.length; j++) { + var v = vals[j]; + if (v !== null && v !== void 0) { + lookup2[v] = 1; + } + } + } + return Object.keys(lookup2); +} +var category_order_defaults = function handleCategoryOrderDefaults(containerIn, containerOut, coerce2, opts) { + if (containerOut.type !== "category") return; + var arrayIn = containerIn.categoryarray; + var isValidArray = Array.isArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn); + var orderDefault; + if (isValidArray) orderDefault = "array"; + var order = coerce2("categoryorder", orderDefault); + var array2; + if (order === "array") { + array2 = coerce2("categoryarray"); + } + if (!isValidArray && order === "array") { + order = containerOut.categoryorder = "trace"; + } + if (order === "trace") { + containerOut._initialCategories = []; + } else if (order === "array") { + containerOut._initialCategories = array2.slice(); + } else { + array2 = findCategories(containerOut, opts).sort(); + if (order === "category ascending") { + containerOut._initialCategories = array2; + } else if (order === "category descending") { + containerOut._initialCategories = array2.reverse(); + } + } +}; +var colorMix = tinycolorExports.mix; +var colorAttrs$3 = attributes$N; +var Lib$Z = libExports; +var line_grid_defaults = function handleLineGridDefaults(containerIn, containerOut, coerce2, opts) { + opts = opts || {}; + var dfltColor = opts.dfltColor; + function coerce22(attr, dflt) { + return Lib$Z.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); + } + var lineColor = coerce22("linecolor", dfltColor); + var lineWidth = coerce22("linewidth"); + var showLine = coerce2("showline", opts.showLine || !!lineColor || !!lineWidth); + if (!showLine) { + delete containerOut.linecolor; + delete containerOut.linewidth; + } + var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || colorAttrs$3.lightFraction).toRgbString(); + var gridColor = coerce22("gridcolor", gridColorDflt); + var gridWidth = coerce22("gridwidth"); + var gridDash = coerce22("griddash"); + var showGridLines = coerce2( + "showgrid", + opts.showGrid || !!gridColor || !!gridWidth || !!gridDash + ); + if (!showGridLines) { + delete containerOut.gridcolor; + delete containerOut.gridwidth; + delete containerOut.griddash; + } + if (opts.hasMinor) { + var minorGridColorDflt = colorMix(containerOut.gridcolor, opts.bgColor, 67).toRgbString(); + var minorGridColor = coerce22("minor.gridcolor", minorGridColorDflt); + var minorGridWidth = coerce22("minor.gridwidth", containerOut.gridwidth || 1); + var minorGridDash = coerce22("minor.griddash", containerOut.griddash || "solid"); + var minorShowGridLines = coerce2( + "minor.showgrid", + !!minorGridColor || !!minorGridWidth || !!minorGridDash + ); + if (!minorShowGridLines) { + delete containerOut.minor.gridcolor; + delete containerOut.minor.gridwidth; + delete containerOut.minor.griddash; + } + } + if (!opts.noZeroLine) { + var zeroLineColor = coerce22("zerolinecolor", dfltColor); + var zeroLineWidth = coerce22("zerolinewidth"); + var showZeroLine = coerce2("zeroline", opts.showGrid || !!zeroLineColor || !!zeroLineWidth); + if (!showZeroLine) { + delete containerOut.zerolinecolor; + delete containerOut.zerolinewidth; + } + } +}; +var isNumeric$c = fastIsnumeric; +var Registry$k = registry; +var Lib$Y = libExports; +var Template$2 = plot_template; +var handleArrayContainerDefaults$7 = array_container_defaults; +var layoutAttributes$3 = layout_attributes$4; +var handleTickValueDefaults2 = tick_value_defaults; +var handleTickMarkDefaults2 = tick_mark_defaults; +var handleTickLabelDefaults2 = tick_label_defaults; +var handlePrefixSuffixDefaults2 = prefix_suffix_defaults; +var handleCategoryOrderDefaults2 = category_order_defaults; +var handleLineGridDefaults2 = line_grid_defaults; +var handleRangeDefaults2 = range_defaults; +var setConvert2 = set_convert; +var DAY_OF_WEEK = constants$U.WEEKDAY_PATTERN; +var HOUR = constants$U.HOUR_PATTERN; +var axis_defaults = function handleAxisDefaults(containerIn, containerOut, coerce2, options, layoutOut) { + var letter = options.letter; + var font2 = options.font || {}; + var splomStash = options.splomStash || {}; + var visible = coerce2("visible", !options.visibleDflt); + var axTemplate = containerOut._template || {}; + var axType = containerOut.type || axTemplate.type || "-"; + var ticklabelmode; + if (axType === "date") { + var handleCalendarDefaults = Registry$k.getComponentMethod("calendars", "handleDefaults"); + handleCalendarDefaults(containerIn, containerOut, "calendar", options.calendar); + if (!options.noTicklabelmode) { + ticklabelmode = coerce2("ticklabelmode"); + } + } + if (!options.noTicklabelindex && (axType === "date" || axType === "linear")) { + coerce2("ticklabelindex"); + } + var ticklabelposition = ""; + if (!options.noTicklabelposition || axType === "multicategory") { + ticklabelposition = Lib$Y.coerce(containerIn, containerOut, { + ticklabelposition: { + valType: "enumerated", + dflt: "outside", + values: ticklabelmode === "period" ? ["outside", "inside"] : letter === "x" ? [ + "outside", + "inside", + "outside left", + "inside left", + "outside right", + "inside right" + ] : [ + "outside", + "inside", + "outside top", + "inside top", + "outside bottom", + "inside bottom" + ] + } + }, "ticklabelposition"); + } + if (!options.noTicklabeloverflow) { + coerce2( + "ticklabeloverflow", + ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : axType === "category" || axType === "multicategory" ? "allow" : "hide past div" + ); + } + setConvert2(containerOut, layoutOut); + handleRangeDefaults2(containerIn, containerOut, coerce2, options); + handleCategoryOrderDefaults2(containerIn, containerOut, coerce2, options); + if (axType !== "category" && !options.noHover) coerce2("hoverformat"); + var dfltColor = coerce2("color"); + var dfltFontColor = dfltColor !== layoutAttributes$3.color.dflt ? dfltColor : font2.color; + var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter]; + handlePrefixSuffixDefaults2(containerIn, containerOut, coerce2, axType, options); + if (!visible) return containerOut; + coerce2("title.text", dfltTitle); + Lib$Y.coerceFont(coerce2, "title.font", font2, { overrideDflt: { + size: Lib$Y.bigFont(font2.size), + color: dfltFontColor + } }); + handleTickValueDefaults2(containerIn, containerOut, coerce2, axType); + var hasMinor = options.hasMinor; + if (hasMinor) { + Template$2.newContainer(containerOut, "minor"); + handleTickValueDefaults2(containerIn, containerOut, coerce2, axType, { isMinor: true }); + } + handleTickLabelDefaults2(containerIn, containerOut, coerce2, axType, options); + handleTickMarkDefaults2(containerIn, containerOut, coerce2, options); + if (hasMinor) { + var keepIsMinor = options.isMinor; + options.isMinor = true; + handleTickMarkDefaults2(containerIn, containerOut, coerce2, options); + options.isMinor = keepIsMinor; + } + handleLineGridDefaults2(containerIn, containerOut, coerce2, { + dfltColor, + bgColor: options.bgColor, + showGrid: options.showGrid, + hasMinor, + attributes: layoutAttributes$3 + }); + if (hasMinor && !containerOut.minor.ticks && !containerOut.minor.showgrid) { + delete containerOut.minor; + } + if (containerOut.showline || containerOut.ticks) coerce2("mirror"); + var isMultiCategory = axType === "multicategory"; + if (!options.noTickson && (axType === "category" || isMultiCategory) && (containerOut.ticks || containerOut.showgrid)) { + var ticksonDflt; + if (isMultiCategory) ticksonDflt = "boundaries"; + var tickson = coerce2("tickson", ticksonDflt); + if (tickson === "boundaries") { + delete containerOut.ticklabelposition; + } + } + if (isMultiCategory) { + var showDividers = coerce2("showdividers"); + if (showDividers) { + coerce2("dividercolor"); + coerce2("dividerwidth"); + } + } + if (axType === "date") { + handleArrayContainerDefaults$7(containerIn, containerOut, { + name: "rangebreaks", + inclusionAttr: "enabled", + handleItemDefaults: rangebreaksDefaults + }); + if (!containerOut.rangebreaks.length) { + delete containerOut.rangebreaks; + } else { + for (var k = 0; k < containerOut.rangebreaks.length; k++) { + if (containerOut.rangebreaks[k].pattern === DAY_OF_WEEK) { + containerOut._hasDayOfWeekBreaks = true; + break; + } + } + setConvert2(containerOut, layoutOut); + if (layoutOut._has("scattergl") || layoutOut._has("splom")) { + for (var i = 0; i < options.data.length; i++) { + var trace = options.data[i]; + if (trace.type === "scattergl" || trace.type === "splom") { + trace.visible = false; + Lib$Y.warn(trace.type + " traces do not work on axes with rangebreaks. Setting trace " + trace.index + " to `visible: false`."); + } + } + } + } + } + return containerOut; +}; +function rangebreaksDefaults(itemIn, itemOut, containerOut) { + function coerce2(attr, dflt) { + return Lib$Y.coerce(itemIn, itemOut, layoutAttributes$3.rangebreaks, attr, dflt); + } + var enabled = coerce2("enabled"); + if (enabled) { + var bnds = coerce2("bounds"); + if (bnds && bnds.length >= 2) { + var dfltPattern = ""; + var i, q; + if (bnds.length === 2) { + for (i = 0; i < 2; i++) { + q = indexOfDay(bnds[i]); + if (q) { + dfltPattern = DAY_OF_WEEK; + break; + } + } + } + var pattern2 = coerce2("pattern", dfltPattern); + if (pattern2 === DAY_OF_WEEK) { + for (i = 0; i < 2; i++) { + q = indexOfDay(bnds[i]); + if (q) { + itemOut.bounds[i] = bnds[i] = q - 1; + } + } + } + if (pattern2) { + for (i = 0; i < 2; i++) { + q = bnds[i]; + switch (pattern2) { + case DAY_OF_WEEK: + if (!isNumeric$c(q)) { + itemOut.enabled = false; + return; + } + q = +q; + if (q !== Math.floor(q) || // don't accept fractional days for mow + q < 0 || q >= 7) { + itemOut.enabled = false; + return; + } + itemOut.bounds[i] = bnds[i] = q; + break; + case HOUR: + if (!isNumeric$c(q)) { + itemOut.enabled = false; + return; + } + q = +q; + if (q < 0 || q > 24) { + itemOut.enabled = false; + return; + } + itemOut.bounds[i] = bnds[i] = q; + break; + } + } + } + if (containerOut.autorange === false) { + var rng = containerOut.range; + if (rng[0] < rng[1]) { + if (bnds[0] < rng[0] && bnds[1] > rng[1]) { + itemOut.enabled = false; + return; + } + } else if (bnds[0] > rng[0] && bnds[1] < rng[1]) { + itemOut.enabled = false; + return; + } + } + } else { + var values = coerce2("values"); + if (values && values.length) { + coerce2("dvalue"); + } else { + itemOut.enabled = false; + return; + } + } + } +} +var dayStrToNum = { + sun: 1, + mon: 2, + tue: 3, + wed: 4, + thu: 5, + fri: 6, + sat: 7 +}; +function indexOfDay(v) { + if (typeof v !== "string") return; + return dayStrToNum[v.substr(0, 3).toLowerCase()]; +} +var isNumeric$b = fastIsnumeric; +var Lib$X = libExports; +var position_defaults = function handlePositionDefaults(containerIn, containerOut, coerce2, options) { + var counterAxes = options.counterAxes || []; + var overlayableAxes = options.overlayableAxes || []; + var letter = options.letter; + var grid2 = options.grid; + var overlayingDomain = options.overlayingDomain; + var dfltAnchor, dfltDomain, dfltSide, dfltPosition, dfltShift, dfltAutomargin; + if (grid2) { + dfltDomain = grid2._domains[letter][grid2._axisMap[containerOut._id]]; + dfltAnchor = grid2._anchors[containerOut._id]; + if (dfltDomain) { + dfltSide = grid2[letter + "side"].split(" ")[0]; + dfltPosition = grid2.domain[letter][dfltSide === "right" || dfltSide === "top" ? 1 : 0]; + } + } + dfltDomain = dfltDomain || [0, 1]; + dfltAnchor = dfltAnchor || (isNumeric$b(containerIn.position) ? "free" : counterAxes[0] || "free"); + dfltSide = dfltSide || (letter === "x" ? "bottom" : "left"); + dfltPosition = dfltPosition || 0; + dfltShift = 0; + dfltAutomargin = false; + var anchor = Lib$X.coerce(containerIn, containerOut, { + anchor: { + valType: "enumerated", + values: ["free"].concat(counterAxes), + dflt: dfltAnchor + } + }, "anchor"); + var side = Lib$X.coerce(containerIn, containerOut, { + side: { + valType: "enumerated", + values: letter === "x" ? ["bottom", "top"] : ["left", "right"], + dflt: dfltSide + } + }, "side"); + if (anchor === "free") { + if (letter === "y") { + var autoshift = coerce2("autoshift"); + if (autoshift) { + dfltPosition = side === "left" ? overlayingDomain[0] : overlayingDomain[1]; + dfltAutomargin = containerOut.automargin ? containerOut.automargin : true; + dfltShift = side === "left" ? -3 : 3; + } + coerce2("shift", dfltShift); + } + coerce2("position", dfltPosition); + } + coerce2("automargin", dfltAutomargin); + var overlaying = false; + if (overlayableAxes.length) { + overlaying = Lib$X.coerce(containerIn, containerOut, { + overlaying: { + valType: "enumerated", + values: [false].concat(overlayableAxes), + dflt: false + } + }, "overlaying"); + } + if (!overlaying) { + var domain2 = coerce2("domain", dfltDomain); + if (domain2[0] > domain2[1] - 1 / 4096) containerOut.domain = dfltDomain; + Lib$X.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); + if (containerOut.tickmode === "sync") { + containerOut.tickmode = "auto"; + } + } + coerce2("layer"); + return containerOut; +}; +var layout_defaults$3; +var hasRequiredLayout_defaults; +function requireLayout_defaults() { + if (hasRequiredLayout_defaults) return layout_defaults$3; + hasRequiredLayout_defaults = 1; + var Lib2 = libExports; + var Color2 = colorExports; + var isUnifiedHover2 = helpers$J.isUnifiedHover; + var handleHoverModeDefaults3 = hovermode_defaults; + var Template2 = plot_template; + var basePlotLayoutAttributes2 = layout_attributes$6; + var layoutAttributes2 = layout_attributes$4; + var handleTypeDefaults = requireType_defaults(); + var handleAxisDefaults3 = axis_defaults; + var constraints$1 = constraints; + var handlePositionDefaults2 = position_defaults; + var axisIds2 = axis_ids; + var id2name2 = axisIds2.id2name; + var name2id = axisIds2.name2id; + var AX_ID_PATTERN = constants$U.AX_ID_PATTERN; + var Registry2 = registry; + var traceIs2 = Registry2.traceIs; + var getComponentMethod = Registry2.getComponentMethod; + function appendList(cont, k, item) { + if (Array.isArray(cont[k])) cont[k].push(item); + else cont[k] = [item]; + } + layout_defaults$3 = function supplyLayoutDefaults10(layoutIn, layoutOut, fullData) { + var autotypenumbersDflt = layoutOut.autotypenumbers; + var ax2traces = {}; + var xaMayHide = {}; + var yaMayHide = {}; + var xaMustDisplay = {}; + var yaMustDisplay = {}; + var yaMustNotReverse = {}; + var yaMayReverse = {}; + var axHasImage = {}; + var outerTicks = {}; + var noGrids = {}; + var i, j; + for (i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if (!traceIs2(trace, "cartesian") && !traceIs2(trace, "gl2d")) continue; + var xaName; + if (trace.xaxis) { + xaName = id2name2(trace.xaxis); + appendList(ax2traces, xaName, trace); + } else if (trace.xaxes) { + for (j = 0; j < trace.xaxes.length; j++) { + appendList(ax2traces, id2name2(trace.xaxes[j]), trace); + } + } + var yaName; + if (trace.yaxis) { + yaName = id2name2(trace.yaxis); + appendList(ax2traces, yaName, trace); + } else if (trace.yaxes) { + for (j = 0; j < trace.yaxes.length; j++) { + appendList(ax2traces, id2name2(trace.yaxes[j]), trace); + } + } + if (trace.type === "funnel") { + if (trace.orientation === "h") { + if (xaName) xaMayHide[xaName] = true; + if (yaName) yaMayReverse[yaName] = true; + } else { + if (yaName) yaMayHide[yaName] = true; + } + } else if (trace.type === "image") { + if (yaName) axHasImage[yaName] = true; + if (xaName) axHasImage[xaName] = true; + } else { + if (yaName) { + yaMustDisplay[yaName] = true; + yaMustNotReverse[yaName] = true; + } + if (!traceIs2(trace, "carpet") || trace.type === "carpet" && !trace._cheater) { + if (xaName) xaMustDisplay[xaName] = true; + } + } + if (trace.type === "carpet" && trace._cheater) { + if (xaName) xaMayHide[xaName] = true; + } + if (traceIs2(trace, "2dMap")) { + outerTicks[xaName] = true; + outerTicks[yaName] = true; + } + if (traceIs2(trace, "oriented")) { + var positionAxis = trace.orientation === "h" ? yaName : xaName; + noGrids[positionAxis] = true; + } + } + var subplots = layoutOut._subplots; + var xIds = subplots.xaxis; + var yIds = subplots.yaxis; + var xNames = Lib2.simpleMap(xIds, id2name2); + var yNames = Lib2.simpleMap(yIds, id2name2); + var axNames = xNames.concat(yNames); + var plotBgColor = Color2.background; + if (xIds.length && yIds.length) { + plotBgColor = Lib2.coerce(layoutIn, layoutOut, basePlotLayoutAttributes2, "plot_bgcolor"); + } + var bgColor = Color2.combine(plotBgColor, layoutOut.paper_bgcolor); + var axName; + var axId; + var axLetter; + var axLayoutIn; + var axLayoutOut; + function newAxLayoutOut() { + var traces = ax2traces[axName] || []; + axLayoutOut._traceIndices = traces.map(function(t) { + return t._expandedIndex; + }); + axLayoutOut._annIndices = []; + axLayoutOut._shapeIndices = []; + axLayoutOut._selectionIndices = []; + axLayoutOut._imgIndices = []; + axLayoutOut._subplotsWith = []; + axLayoutOut._counterAxes = []; + axLayoutOut._name = axLayoutOut._attr = axName; + axLayoutOut._id = axId; + } + function coerce2(attr, dflt) { + return Lib2.coerce(axLayoutIn, axLayoutOut, layoutAttributes2, attr, dflt); + } + function coerce22(attr, dflt) { + return Lib2.coerce2(axLayoutIn, axLayoutOut, layoutAttributes2, attr, dflt); + } + function getCounterAxes(axLetter2) { + return axLetter2 === "x" ? yIds : xIds; + } + function getOverlayableAxes(axLetter2, axName2) { + var list = axLetter2 === "x" ? xNames : yNames; + var out = []; + for (var j2 = 0; j2 < list.length; j2++) { + var axName22 = list[j2]; + if (axName22 !== axName2 && !(layoutIn[axName22] || {}).overlaying) { + out.push(name2id(axName22)); + } + } + return out; + } + var counterAxes = { x: getCounterAxes("x"), y: getCounterAxes("y") }; + var allAxisIds = counterAxes.x.concat(counterAxes.y); + var missingMatchedAxisIdsLookup = {}; + var missingMatchedAxisIds = []; + function addMissingMatchedAxis() { + var matchesIn = axLayoutIn.matches; + if (AX_ID_PATTERN.test(matchesIn) && allAxisIds.indexOf(matchesIn) === -1) { + missingMatchedAxisIdsLookup[matchesIn] = axLayoutIn.type; + missingMatchedAxisIds = Object.keys(missingMatchedAxisIdsLookup); + } + } + var hovermode = handleHoverModeDefaults3(layoutIn, layoutOut); + var unifiedHover = isUnifiedHover2(hovermode); + for (i = 0; i < axNames.length; i++) { + axName = axNames[i]; + axId = name2id(axName); + axLetter = axName.charAt(0); + if (!Lib2.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } + axLayoutIn = layoutIn[axName]; + axLayoutOut = Template2.newContainer(layoutOut, axName, axLetter + "axis"); + newAxLayoutOut(); + var visibleDflt = axLetter === "x" && !xaMustDisplay[axName] && xaMayHide[axName] || axLetter === "y" && !yaMustDisplay[axName] && yaMayHide[axName]; + var reverseDflt = axLetter === "y" && (!yaMustNotReverse[axName] && yaMayReverse[axName] || axHasImage[axName]); + var defaultOptions = { + hasMinor: true, + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: ax2traces[axName] || [], + bgColor, + calendar: layoutOut.calendar, + automargin: true, + visibleDflt, + reverseDflt, + autotypenumbersDflt, + splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId], + noAutotickangles: axLetter === "y" + }; + coerce2("uirevision", layoutOut.uirevision); + handleTypeDefaults(axLayoutIn, axLayoutOut, coerce2, defaultOptions); + handleAxisDefaults3(axLayoutIn, axLayoutOut, coerce2, defaultOptions, layoutOut); + var unifiedSpike = unifiedHover && axLetter === hovermode.charAt(0); + var spikecolor = coerce22("spikecolor", unifiedHover ? axLayoutOut.color : void 0); + var spikethickness = coerce22("spikethickness", unifiedHover ? 1.5 : void 0); + var spikedash = coerce22("spikedash", unifiedHover ? "dot" : void 0); + var spikemode = coerce22("spikemode", unifiedHover ? "across" : void 0); + var spikesnap = coerce22("spikesnap"); + var showSpikes = coerce2("showspikes", !!unifiedSpike || !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); + if (!showSpikes) { + delete axLayoutOut.spikecolor; + delete axLayoutOut.spikethickness; + delete axLayoutOut.spikedash; + delete axLayoutOut.spikemode; + delete axLayoutOut.spikesnap; + } + var overlayingAxis = id2name2(axLayoutIn.overlaying); + var overlayingAnchorDomain = [0, 1]; + if (layoutOut[overlayingAxis] !== void 0) { + var overlayingAnchor = id2name2(layoutOut[overlayingAxis].anchor); + if (layoutOut[overlayingAnchor] !== void 0) { + overlayingAnchorDomain = layoutOut[overlayingAnchor].domain; + } + } + handlePositionDefaults2(axLayoutIn, axLayoutOut, coerce2, { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: getOverlayableAxes(axLetter, axName), + grid: layoutOut.grid, + overlayingDomain: overlayingAnchorDomain + }); + coerce2("title.standoff"); + addMissingMatchedAxis(); + axLayoutOut._input = axLayoutIn; + } + i = 0; + while (i < missingMatchedAxisIds.length) { + axId = missingMatchedAxisIds[i++]; + axName = id2name2(axId); + axLetter = axName.charAt(0); + if (!Lib2.isPlainObject(layoutIn[axName])) { + layoutIn[axName] = {}; + } + axLayoutIn = layoutIn[axName]; + axLayoutOut = Template2.newContainer(layoutOut, axName, axLetter + "axis"); + newAxLayoutOut(); + var defaultOptions2 = { + letter: axLetter, + font: layoutOut.font, + outerTicks: outerTicks[axName], + showGrid: !noGrids[axName], + data: [], + bgColor, + calendar: layoutOut.calendar, + automargin: true, + visibleDflt: false, + reverseDflt: false, + autotypenumbersDflt, + splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId] + }; + coerce2("uirevision", layoutOut.uirevision); + axLayoutOut.type = missingMatchedAxisIdsLookup[axId] || "linear"; + handleAxisDefaults3(axLayoutIn, axLayoutOut, coerce2, defaultOptions2, layoutOut); + handlePositionDefaults2(axLayoutIn, axLayoutOut, coerce2, { + letter: axLetter, + counterAxes: counterAxes[axLetter], + overlayableAxes: getOverlayableAxes(axLetter, axName), + grid: layoutOut.grid + }); + coerce2("fixedrange"); + addMissingMatchedAxis(); + axLayoutOut._input = axLayoutIn; + } + var rangeSliderDefaults = getComponentMethod("rangeslider", "handleDefaults"); + var rangeSelectorDefaults = getComponentMethod("rangeselector", "handleDefaults"); + for (i = 0; i < xNames.length; i++) { + axName = xNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + rangeSliderDefaults(layoutIn, layoutOut, axName); + if (axLayoutOut.type === "date") { + rangeSelectorDefaults( + axLayoutIn, + axLayoutOut, + layoutOut, + yNames, + axLayoutOut.calendar + ); + } + coerce2("fixedrange"); + } + for (i = 0; i < yNames.length; i++) { + axName = yNames[i]; + axLayoutIn = layoutIn[axName]; + axLayoutOut = layoutOut[axName]; + var anchoredAxis = layoutOut[id2name2(axLayoutOut.anchor)]; + var fixedRangeDflt = getComponentMethod("rangeslider", "isVisible")(anchoredAxis); + coerce2("fixedrange", fixedRangeDflt); + } + constraints$1.handleDefaults(layoutIn, layoutOut, { + axIds: allAxisIds.concat(missingMatchedAxisIds).sort(axisIds2.idSort), + axHasImage + }); + }; + return layout_defaults$3; +} +var transition_axes; +var hasRequiredTransition_axes; +function requireTransition_axes() { + if (hasRequiredTransition_axes) return transition_axes; + hasRequiredTransition_axes = 1; + var d32 = d3Exports; + var Registry2 = registry; + var Lib2 = libExports; + var Drawing2 = drawingExports; + var Axes2 = axesExports; + transition_axes = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + if (edits.length === 0) { + Axes2.redrawComponents(gd); + return; + } + function unsetSubplotTransform(subplot) { + var xa = subplot.xaxis; + var ya = subplot.yaxis; + fullLayout._defs.select("#" + subplot.clipId + "> rect").call(Drawing2.setTranslate, 0, 0).call(Drawing2.setScale, 1, 1); + subplot.plot.call(Drawing2.setTranslate, xa._offset, ya._offset).call(Drawing2.setScale, 1, 1); + var traceGroups = subplot.plot.selectAll(".scatterlayer .trace"); + traceGroups.selectAll(".point").call(Drawing2.setPointGroupScale, 1, 1); + traceGroups.selectAll(".textpoint").call(Drawing2.setTextPointsScale, 1, 1); + traceGroups.call(Drawing2.hideOutsideRangePoints, subplot); + } + function updateSubplot(edit, progress) { + var plotinfo = edit.plotinfo; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var xlen = xa._length; + var ylen = ya._length; + var editX = !!edit.xr1; + var editY = !!edit.yr1; + var viewBox = []; + if (editX) { + var xr0 = Lib2.simpleMap(edit.xr0, xa.r2l); + var xr1 = Lib2.simpleMap(edit.xr1, xa.r2l); + var dx0 = xr0[1] - xr0[0]; + var dx1 = xr1[1] - xr1[0]; + viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen; + viewBox[2] = xlen * (1 - progress + progress * dx1 / dx0); + xa.range[0] = xa.l2r(xr0[0] * (1 - progress) + progress * xr1[0]); + xa.range[1] = xa.l2r(xr0[1] * (1 - progress) + progress * xr1[1]); + } else { + viewBox[0] = 0; + viewBox[2] = xlen; + } + if (editY) { + var yr0 = Lib2.simpleMap(edit.yr0, ya.r2l); + var yr1 = Lib2.simpleMap(edit.yr1, ya.r2l); + var dy0 = yr0[1] - yr0[0]; + var dy1 = yr1[1] - yr1[0]; + viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen; + viewBox[3] = ylen * (1 - progress + progress * dy1 / dy0); + ya.range[0] = xa.l2r(yr0[0] * (1 - progress) + progress * yr1[0]); + ya.range[1] = ya.l2r(yr0[1] * (1 - progress) + progress * yr1[1]); + } else { + viewBox[1] = 0; + viewBox[3] = ylen; + } + Axes2.drawOne(gd, xa, { skipTitle: true }); + Axes2.drawOne(gd, ya, { skipTitle: true }); + Axes2.redrawComponents(gd, [xa._id, ya._id]); + var xScaleFactor = editX ? xlen / viewBox[2] : 1; + var yScaleFactor = editY ? ylen / viewBox[3] : 1; + var clipDx = editX ? viewBox[0] : 0; + var clipDy = editY ? viewBox[1] : 0; + var fracDx = editX ? viewBox[0] / viewBox[2] * xlen : 0; + var fracDy = editY ? viewBox[1] / viewBox[3] * ylen : 0; + var plotDx = xa._offset - fracDx; + var plotDy = ya._offset - fracDy; + plotinfo.clipRect.call(Drawing2.setTranslate, clipDx, clipDy).call(Drawing2.setScale, 1 / xScaleFactor, 1 / yScaleFactor); + plotinfo.plot.call(Drawing2.setTranslate, plotDx, plotDy).call(Drawing2.setScale, xScaleFactor, yScaleFactor); + Drawing2.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor); + Drawing2.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor); + } + var onComplete; + if (makeOnCompleteCallback) { + onComplete = makeOnCompleteCallback(); + } + function transitionComplete() { + var aobj = {}; + for (var i = 0; i < edits.length; i++) { + var edit = edits[i]; + var xa = edit.plotinfo.xaxis; + var ya = edit.plotinfo.yaxis; + if (edit.xr1) aobj[xa._name + ".range"] = edit.xr1.slice(); + if (edit.yr1) aobj[ya._name + ".range"] = edit.yr1.slice(); + } + onComplete && onComplete(); + return Registry2.call("relayout", gd, aobj).then(function() { + for (var i2 = 0; i2 < edits.length; i2++) { + unsetSubplotTransform(edits[i2].plotinfo); + } + }); + } + function transitionInterrupt() { + var aobj = {}; + for (var i = 0; i < edits.length; i++) { + var edit = edits[i]; + var xa = edit.plotinfo.xaxis; + var ya = edit.plotinfo.yaxis; + if (edit.xr0) aobj[xa._name + ".range"] = edit.xr0.slice(); + if (edit.yr0) aobj[ya._name + ".range"] = edit.yr0.slice(); + } + return Registry2.call("relayout", gd, aobj).then(function() { + for (var i2 = 0; i2 < edits.length; i2++) { + unsetSubplotTransform(edits[i2].plotinfo); + } + }); + } + var t12, t22, raf; + var easeFn = d32.ease(transitionOpts.easing); + gd._transitionData._interruptCallbacks.push(function() { + window.cancelAnimationFrame(raf); + raf = null; + return transitionInterrupt(); + }); + function doFrame() { + t22 = Date.now(); + var tInterp = Math.min(1, (t22 - t12) / transitionOpts.duration); + var progress = easeFn(tInterp); + for (var i = 0; i < edits.length; i++) { + updateSubplot(edits[i], progress); + } + if (t22 - t12 > transitionOpts.duration) { + transitionComplete(); + raf = window.cancelAnimationFrame(doFrame); + } else { + raf = window.requestAnimationFrame(doFrame); + } + } + t12 = Date.now(); + raf = window.requestAnimationFrame(doFrame); + return Promise.resolve(); + }; + return transition_axes; +} +var d3$l = d3Exports; +var Registry$j = registry; +var Lib$W = libExports; +var Plots$6 = plotsExports; +var Drawing$f = drawingExports; +var getModuleCalcData = get_data.getModuleCalcData; +var axisIds$3 = axis_ids; +var constants$w = constants$U; +var xmlnsNamespaces$1 = xmlns_namespaces; +var ensureSingle = Lib$W.ensureSingle; +function ensureSingleAndAddDatum(parent, nodeType, className) { + return Lib$W.ensureSingle(parent, nodeType, className, function(s) { + s.datum(className); + }); +} +var zindexSeparator = constants$w.zindexSeparator; +cartesian.name = "cartesian"; +cartesian.attr = ["xaxis", "yaxis"]; +cartesian.idRoot = ["x", "y"]; +cartesian.idRegex = constants$w.idRegex; +cartesian.attrRegex = constants$w.attrRegex; +cartesian.attributes = requireAttributes(); +cartesian.layoutAttributes = layout_attributes$4; +cartesian.supplyLayoutDefaults = requireLayout_defaults(); +cartesian.transitionAxes = requireTransition_axes(); +cartesian.finalizeSubplots = function(layoutIn, layoutOut) { + var subplots = layoutOut._subplots; + var xList = subplots.xaxis; + var yList = subplots.yaxis; + var spSVG = subplots.cartesian; + var spAll = spSVG.concat(subplots.gl2d || []); + var allX = {}; + var allY = {}; + var i, xi, yi; + for (i = 0; i < spAll.length; i++) { + var parts = spAll[i].split("y"); + allX[parts[0]] = 1; + allY["y" + parts[1]] = 1; + } + for (i = 0; i < xList.length; i++) { + xi = xList[i]; + if (!allX[xi]) { + yi = (layoutIn[axisIds$3.id2name(xi)] || {}).anchor; + if (!constants$w.idRegex.y.test(yi)) yi = "y"; + spSVG.push(xi + yi); + spAll.push(xi + yi); + if (!allY[yi]) { + allY[yi] = 1; + Lib$W.pushUnique(yList, yi); + } + } + } + for (i = 0; i < yList.length; i++) { + yi = yList[i]; + if (!allY[yi]) { + xi = (layoutIn[axisIds$3.id2name(yi)] || {}).anchor; + if (!constants$w.idRegex.x.test(xi)) xi = "x"; + spSVG.push(xi + yi); + spAll.push(xi + yi); + if (!allX[xi]) { + allX[xi] = 1; + Lib$W.pushUnique(xList, xi); + } + } + } + if (!spAll.length) { + xi = ""; + yi = ""; + for (var ki in layoutIn) { + if (constants$w.attrRegex.test(ki)) { + var axLetter = ki.charAt(0); + if (axLetter === "x") { + if (!xi || +ki.substr(5) < +xi.substr(5)) { + xi = ki; + } + } else if (!yi || +ki.substr(5) < +yi.substr(5)) { + yi = ki; + } + } + } + xi = xi ? axisIds$3.name2id(xi) : "x"; + yi = yi ? axisIds$3.name2id(yi) : "y"; + xList.push(xi); + yList.push(yi); + spSVG.push(xi + yi); + } +}; +cartesian.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var subplots = fullLayout._subplots.cartesian; + var calcdata = gd.calcdata; + var i; + if (!Array.isArray(traces)) { + traces = []; + for (i = 0; i < calcdata.length; i++) traces.push(i); + } + var zindices = fullLayout._zindices; + for (var z = 0; z < zindices.length; z++) { + var zorder = zindices[z]; + for (i = 0; i < subplots.length; i++) { + var subplot = subplots[i]; + var subplotInfo = fullLayout._plots[subplot]; + if (z > 0) { + var idWithZ = subplotInfo.id; + if (idWithZ.indexOf(zindexSeparator) !== -1) continue; + idWithZ += zindexSeparator + (z + 1); + subplotInfo = Lib$W.extendFlat({}, subplotInfo, { + id: idWithZ, + plot: fullLayout._cartesianlayer.selectAll(".subplot").select("." + idWithZ) + }); + } + var cdSubplot = []; + var pcd; + for (var j = 0; j < calcdata.length; j++) { + var cd = calcdata[j]; + var trace = cd[0].trace; + if (zorder !== (trace.zorder || 0)) continue; + if (trace.xaxis + trace.yaxis === subplot) { + if (traces.indexOf(trace.index) !== -1 || trace.carpet) { + if (pcd && pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && ["tonextx", "tonexty", "tonext"].indexOf(trace.fill) !== -1 && cdSubplot.indexOf(pcd) === -1) { + cdSubplot.push(pcd); + } + cdSubplot.push(cd); + } + pcd = cd; + } + } + plotOne$1(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); + } + } +}; +function plotOne$1(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { + var traceLayerClasses = constants$w.traceLayerClasses; + var fullLayout = gd._fullLayout; + var zindices = fullLayout._zindices; + var modules2 = fullLayout._modules; + var _module, cdModuleAndOthers, cdModule; + var layerData = []; + var zoomScaleQueryParts = []; + for (var z = 0; z < zindices.length; z++) { + var zorder = zindices[z]; + for (var i = 0; i < modules2.length; i++) { + _module = modules2[i]; + var name2 = _module.name; + var categories = Registry$j.modules[name2].categories; + if (categories.svg) { + var classBaseName = _module.layerName || name2 + "layer"; + var className = classBaseName + (z ? Number(z) + 1 : ""); + var plotMethod = _module.plot; + cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod, zorder); + cdModule = cdModuleAndOthers[0]; + cdSubplot = cdModuleAndOthers[1]; + if (cdModule.length) { + layerData.push({ + i: traceLayerClasses.indexOf(classBaseName), + zindex: z, + className, + plotMethod, + cdModule + }); + } + if (categories.zoomScale) { + zoomScaleQueryParts.push("." + className); + } + } + } + } + layerData.sort(function(a, b) { + return (a.zindex || 0) - (b.zindex || 0) || a.i - b.i; + }); + var layers = plotinfo.plot.selectAll("g.mlayer").data(layerData, function(d) { + return d.className; + }); + layers.enter().append("g").attr("class", function(d) { + return d.className; + }).classed("mlayer", true).classed("rangeplot", plotinfo.isRangePlot); + layers.exit().remove(); + layers.order(); + layers.each(function(d) { + var sel = d3$l.select(this); + var className2 = d.className; + d.plotMethod( + gd, + plotinfo, + d.cdModule, + sel, + transitionOpts, + makeOnCompleteCallback + ); + if (constants$w.clipOnAxisFalseQuery.indexOf("." + className2) === -1) { + Drawing$f.setClipUrl(sel, plotinfo.layerClipId, gd); + } + }); + if (fullLayout._has("scattergl")) { + _module = Registry$j.getModule("scattergl"); + cdModule = getModuleCalcData(cdSubplot, _module)[0]; + _module.plot(gd, plotinfo, cdModule); + } + if (!gd._context.staticPlot) { + if (plotinfo._hasClipOnAxisFalse) { + plotinfo.clipOnAxisFalseTraces = plotinfo.plot.selectAll(constants$w.clipOnAxisFalseQuery.join(",")).selectAll(".trace"); + } + if (zoomScaleQueryParts.length) { + var traces = plotinfo.plot.selectAll(zoomScaleQueryParts.join(",")).selectAll(".trace"); + plotinfo.zoomScalePts = traces.selectAll("path.point"); + plotinfo.zoomScaleTxt = traces.selectAll(".textpoint"); + } + } +} +cartesian.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + var oldPlots = oldFullLayout._plots || {}; + var newPlots = newFullLayout._plots || {}; + var oldSubplotList = oldFullLayout._subplots || {}; + var plotinfo; + var i, k; + if (oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { + for (k in oldPlots) { + plotinfo = oldPlots[k]; + if (plotinfo.plotgroup) plotinfo.plotgroup.remove(); + } + } + var hadGl = oldFullLayout._has && oldFullLayout._has("gl"); + var hasGl = newFullLayout._has && newFullLayout._has("gl"); + if (hadGl && !hasGl) { + for (k in oldPlots) { + plotinfo = oldPlots[k]; + if (plotinfo._scene) plotinfo._scene.destroy(); + } + } + if (oldSubplotList.xaxis && oldSubplotList.yaxis) { + var oldAxIDs = axisIds$3.listIds({ _fullLayout: oldFullLayout }); + for (i = 0; i < oldAxIDs.length; i++) { + var oldAxId = oldAxIDs[i]; + if (!newFullLayout[axisIds$3.id2name(oldAxId)]) { + oldFullLayout._infolayer.selectAll(".g-" + oldAxId + "title").remove(); + } + } + } + var hadCartesian = oldFullLayout._has && oldFullLayout._has("cartesian"); + var hasCartesian = newFullLayout._has && newFullLayout._has("cartesian"); + if (hadCartesian && !hasCartesian) { + purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll(".subplot"), oldFullLayout); + oldFullLayout._defs.selectAll(".axesclip").remove(); + delete oldFullLayout._axisConstraintGroups; + delete oldFullLayout._axisMatchGroups; + } else if (oldSubplotList.cartesian) { + for (i = 0; i < oldSubplotList.cartesian.length; i++) { + var oldSubplotId = oldSubplotList.cartesian[i]; + if (oldSubplotId.indexOf(zindexSeparator) !== -1) continue; + if (!newPlots[oldSubplotId]) { + var selector = "." + oldSubplotId + ",." + oldSubplotId + "-x,." + oldSubplotId + "-y"; + oldFullLayout._cartesianlayer.selectAll(selector).remove(); + removeSubplotExtras(oldSubplotId, oldFullLayout); + } + } + } +}; +cartesian.drawFramework = function(gd) { + var fullLayout = gd._fullLayout; + var calcdata = gd.calcdata; + var i; + var traceZorderGroups = {}; + for (i = 0; i < calcdata.length; i++) { + var cdi = calcdata[i][0]; + var trace = cdi.trace; + var zi = trace.zorder || 0; + if (!traceZorderGroups[zi]) traceZorderGroups[zi] = []; + traceZorderGroups[zi].push(cdi); + } + var zindices = Object.keys(traceZorderGroups).map(Number).sort(Lib$W.sorterAsc); + if (!zindices.length) zindices = [0]; + fullLayout._zindices = zindices; + var initialSubplotData = makeSubplotData(gd); + var len = initialSubplotData.length; + var subplotData = []; + for (i = 0; i < len; i++) { + subplotData[i] = initialSubplotData[i].slice(); + } + for (var z = 1; z < zindices.length; z++) { + var newSubplotData = []; + for (i = 0; i < len; i++) { + newSubplotData[i] = initialSubplotData[i].slice(); + newSubplotData[i][0] += zindexSeparator + (z + 1); + } + subplotData = subplotData.concat(newSubplotData); + } + var subplotLayers = fullLayout._cartesianlayer.selectAll(".subplot").data(subplotData, String); + subplotLayers.enter().append("g").attr("class", function(d) { + return "subplot " + d[0]; + }); + subplotLayers.order(); + subplotLayers.exit().call(purgeSubplotLayers, fullLayout); + subplotLayers.each(function(d) { + var id = d[0]; + var posZ = id.indexOf(zindexSeparator); + var hasZ = posZ !== -1; + var idWithoutZ = hasZ ? id.slice(0, posZ) : id; + var plotinfo = fullLayout._plots[id]; + if (!plotinfo) { + plotinfo = Lib$W.extendFlat({}, fullLayout._plots[idWithoutZ]); + if (plotinfo) { + plotinfo.id = id; + fullLayout._plots[id] = plotinfo; + fullLayout._subplots.cartesian.push(id); + } + } + if (plotinfo) { + plotinfo.plotgroup = d3$l.select(this); + makeSubplotLayer(gd, plotinfo); + if (!hasZ) { + plotinfo.draglayer = ensureSingle(fullLayout._draggers, "g", id); + } + } + }); +}; +cartesian.rangePlot = function(gd, plotinfo, cdSubplot) { + makeSubplotLayer(gd, plotinfo); + plotOne$1(gd, plotinfo, cdSubplot); + Plots$6.style(gd); +}; +function makeSubplotData(gd) { + var fullLayout = gd._fullLayout; + var numZ = fullLayout._zindices.length; + var ids = fullLayout._subplots.cartesian; + var len = ids.length; + var i, j, id, plotinfo, xa, ya; + var regulars = []; + var overlays = []; + for (i = 0; i < len; i++) { + id = ids[i]; + plotinfo = fullLayout._plots[id]; + xa = plotinfo.xaxis; + ya = plotinfo.yaxis; + var xa2 = xa._mainAxis; + var ya2 = ya._mainAxis; + var mainplot = xa2._id + ya2._id; + var mainplotinfo = fullLayout._plots[mainplot]; + plotinfo.overlays = []; + if (mainplot !== id && mainplotinfo) { + plotinfo.mainplot = mainplot; + plotinfo.mainplotinfo = mainplotinfo; + overlays.push(id); + } else { + plotinfo.mainplot = void 0; + plotinfo.mainplotinfo = void 0; + regulars.push(id); + } + } + for (i = 0; i < overlays.length; i++) { + id = overlays[i]; + plotinfo = fullLayout._plots[id]; + plotinfo.mainplotinfo.overlays.push(plotinfo); + } + var subplotIds = regulars.concat(overlays); + var subplotData = []; + for (i = 0; i < len; i++) { + id = subplotIds[i]; + plotinfo = fullLayout._plots[id]; + xa = plotinfo.xaxis; + ya = plotinfo.yaxis; + var d = []; + for (var z = 1; z <= numZ; z++) { + var zStr = ""; + if (z > 1) zStr += zindexSeparator + z; + d.push(id + zStr); + for (j = 0; j < plotinfo.overlays.length; j++) { + d.push(plotinfo.overlays[j].id + zStr); + } + } + d = d.concat([ + xa.layer, + ya.layer, + xa.overlaying || "", + ya.overlaying || "" + ]); + subplotData.push(d); + } + return subplotData; +} +function makeSubplotLayer(gd, plotinfo) { + var fullLayout = gd._fullLayout; + var plotgroup = plotinfo.plotgroup; + var id = plotinfo.id; + var posZ = id.indexOf(zindexSeparator); + var hasZ = posZ !== -1; + var xLayer = constants$w.layerValue2layerClass[plotinfo.xaxis.layer]; + var yLayer = constants$w.layerValue2layerClass[plotinfo.yaxis.layer]; + var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; + if (!plotinfo.mainplot || fullLayout._zindices.length > 1) { + if (hasOnlyLargeSploms) { + plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above"); + plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above"); + plotinfo.xaxislayer = ensureSingle(plotgroup, "g", "xaxislayer-above"); + plotinfo.yaxislayer = ensureSingle(plotgroup, "g", "yaxislayer-above"); + } else { + if (!hasZ) { + var backLayer = ensureSingle(plotgroup, "g", "layer-subplot"); + plotinfo.shapelayer = ensureSingle(backLayer, "g", "shapelayer"); + plotinfo.imagelayer = ensureSingle(backLayer, "g", "imagelayer"); + plotinfo.minorGridlayer = ensureSingle(plotgroup, "g", "minor-gridlayer"); + plotinfo.gridlayer = ensureSingle(plotgroup, "g", "gridlayer"); + plotinfo.zerolinelayer = ensureSingle(plotgroup, "g", "zerolinelayer"); + var betweenLayer = ensureSingle(plotgroup, "g", "layer-between"); + plotinfo.shapelayerBetween = ensureSingle(betweenLayer, "g", "shapelayer"); + plotinfo.imagelayerBetween = ensureSingle(betweenLayer, "g", "imagelayer"); + ensureSingle(plotgroup, "path", "xlines-below"); + ensureSingle(plotgroup, "path", "ylines-below"); + plotinfo.overlinesBelow = ensureSingle(plotgroup, "g", "overlines-below"); + ensureSingle(plotgroup, "g", "xaxislayer-below"); + ensureSingle(plotgroup, "g", "yaxislayer-below"); + plotinfo.overaxesBelow = ensureSingle(plotgroup, "g", "overaxes-below"); + } + plotinfo.overplot = ensureSingle(plotgroup, "g", "overplot"); + plotinfo.plot = ensureSingle(plotinfo.overplot, "g", id); + if (!hasZ) { + plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above"); + plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above"); + plotinfo.overlinesAbove = ensureSingle(plotgroup, "g", "overlines-above"); + ensureSingle(plotgroup, "g", "xaxislayer-above"); + ensureSingle(plotgroup, "g", "yaxislayer-above"); + plotinfo.overaxesAbove = ensureSingle(plotgroup, "g", "overaxes-above"); + plotinfo.xlines = plotgroup.select(".xlines-" + xLayer); + plotinfo.ylines = plotgroup.select(".ylines-" + yLayer); + plotinfo.xaxislayer = plotgroup.select(".xaxislayer-" + xLayer); + plotinfo.yaxislayer = plotgroup.select(".yaxislayer-" + yLayer); + } + } + } else { + var mainplotinfo = plotinfo.mainplotinfo; + var mainplotgroup = mainplotinfo.plotgroup; + var xId = id + "-x"; + var yId = id + "-y"; + plotinfo.minorGridlayer = mainplotinfo.minorGridlayer; + plotinfo.gridlayer = mainplotinfo.gridlayer; + plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; + ensureSingle(mainplotinfo.overlinesBelow, "path", xId); + ensureSingle(mainplotinfo.overlinesBelow, "path", yId); + ensureSingle(mainplotinfo.overaxesBelow, "g", xId); + ensureSingle(mainplotinfo.overaxesBelow, "g", yId); + plotinfo.plot = ensureSingle(mainplotinfo.overplot, "g", id); + ensureSingle(mainplotinfo.overlinesAbove, "path", xId); + ensureSingle(mainplotinfo.overlinesAbove, "path", yId); + ensureSingle(mainplotinfo.overaxesAbove, "g", xId); + ensureSingle(mainplotinfo.overaxesAbove, "g", yId); + plotinfo.xlines = mainplotgroup.select(".overlines-" + xLayer).select("." + xId); + plotinfo.ylines = mainplotgroup.select(".overlines-" + yLayer).select("." + yId); + plotinfo.xaxislayer = mainplotgroup.select(".overaxes-" + xLayer).select("." + xId); + plotinfo.yaxislayer = mainplotgroup.select(".overaxes-" + yLayer).select("." + yId); + } + if (!hasZ) { + if (!hasOnlyLargeSploms) { + ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.yaxis._id); + plotinfo.minorGridlayer.selectAll("g").map(function(d) { + return d[0]; + }).sort(axisIds$3.idSort); + ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.xaxis._id); + ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.yaxis._id); + plotinfo.gridlayer.selectAll("g").map(function(d) { + return d[0]; + }).sort(axisIds$3.idSort); + } + plotinfo.xlines.style("fill", "none").classed("crisp", true); + plotinfo.ylines.style("fill", "none").classed("crisp", true); + } +} +function purgeSubplotLayers(layers, fullLayout) { + if (!layers) return; + var overlayIdsToRemove = {}; + layers.each(function(d) { + var id = d[0]; + var plotgroup = d3$l.select(this); + plotgroup.remove(); + removeSubplotExtras(id, fullLayout); + overlayIdsToRemove[id] = true; + }); + for (var k in fullLayout._plots) { + var subplotInfo = fullLayout._plots[k]; + var overlays = subplotInfo.overlays || []; + for (var j = 0; j < overlays.length; j++) { + var overlayInfo = overlays[j]; + if (overlayIdsToRemove[overlayInfo.id]) { + overlayInfo.plot.selectAll(".trace").remove(); + } + } + } +} +function removeSubplotExtras(subplotId, fullLayout) { + fullLayout._draggers.selectAll("g." + subplotId).remove(); + fullLayout._defs.select("#clip" + fullLayout._uid + subplotId + "plot").remove(); +} +cartesian.toSVG = function(gd) { + var imageRoot = gd._fullLayout._glimages; + var root = d3$l.select(gd).selectAll(".svg-container"); + var canvases = root.filter(function(d, i) { + return i === root.size() - 1; + }).selectAll(".gl-canvas-context, .gl-canvas-focus"); + function canvasToImage() { + var canvas2 = this; + var imageData = canvas2.toDataURL("image/png"); + var image = imageRoot.append("svg:image"); + image.attr({ + xmlns: xmlnsNamespaces$1.svg, + "xlink:href": imageData, + preserveAspectRatio: "none", + x: 0, + y: 0, + width: canvas2.style.width, + height: canvas2.style.height + }); + } + canvases.each(canvasToImage); +}; +cartesian.updateFx = requireGraph_interact().updateFx; +var subtypes = subtypes$3; +var scatter$1 = { + hasLines: subtypes.hasLines, + hasMarkers: subtypes.hasMarkers, + hasText: subtypes.hasText, + isBubble: subtypes.isBubble, + attributes: attributes$A, + layoutAttributes: layout_attributes$5, + supplyDefaults: defaults$h, + crossTraceDefaults: cross_trace_defaults$1, + supplyLayoutDefaults: layout_defaults$4, + calc: calc_1$3.calc, + crossTraceCalc: cross_trace_calc, + arraysToCalcdata: arrays_to_calcdata$1, + plot: plot$7, + colorbar: marker_colorbar, + formatLabels: format_labels$1, + style: style_1$3.style, + styleOnSelect: style_1$3.styleOnSelect, + hoverPoints: hover$5, + selectPoints: select$3, + animatable: true, + moduleType: "trace", + name: "scatter", + basePlotModule: cartesian, + categories: [ + "cartesian", + "svg", + "symbols", + "errorBarsOK", + "showLegend", + "scatter-like", + "zoomScale" + ], + meta: { + description: [ + "The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts.", + "The data visualized as scatter point or lines is set in `x` and `y`.", + "Text (appearing either on the chart or on hover only) is via `text`.", + "Bubble charts are achieved by setting `marker.size` and/or `marker.color`", + "to numerical arrays." + ].join(" ") + } +}; +var d3$k = d3Exports; +var Color$q = colorExports; +var ARROWPATHS = arrow_paths; +var Lib$V = libExports; +var strScale$1 = Lib$V.strScale; +var strRotate = Lib$V.strRotate; +var strTranslate$5 = Lib$V.strTranslate; +var draw_arrow_head = function drawArrowHead(el3, ends, options) { + var el = el3.node(); + var headStyle = ARROWPATHS[options.arrowhead || 0]; + var startHeadStyle = ARROWPATHS[options.startarrowhead || 0]; + var scale2 = (options.arrowwidth || 1) * (options.arrowsize || 1); + var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1); + var doStart = ends.indexOf("start") >= 0; + var doEnd = ends.indexOf("end") >= 0; + var backOff = headStyle.backoff * scale2 + options.standoff; + var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff; + var start, end, startRot, endRot; + if (el.nodeName === "line") { + start = { x: +el3.attr("x1"), y: +el3.attr("y1") }; + end = { x: +el3.attr("x2"), y: +el3.attr("y2") }; + var dx = start.x - end.x; + var dy = start.y - end.y; + startRot = Math.atan2(dy, dx); + endRot = startRot + Math.PI; + if (backOff && startBackOff) { + if (backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) { + hideLine(); + return; + } + } + if (backOff) { + if (backOff * backOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var backOffX = backOff * Math.cos(startRot); + var backOffY = backOff * Math.sin(startRot); + end.x += backOffX; + end.y += backOffY; + el3.attr({ x2: end.x, y2: end.y }); + } + if (startBackOff) { + if (startBackOff * startBackOff > dx * dx + dy * dy) { + hideLine(); + return; + } + var startBackOffX = startBackOff * Math.cos(startRot); + var startbackOffY = startBackOff * Math.sin(startRot); + start.x -= startBackOffX; + start.y -= startbackOffY; + el3.attr({ x1: start.x, y1: start.y }); + } + } else if (el.nodeName === "path") { + var pathlen = el.getTotalLength(); + var dashArray = ""; + if (pathlen < backOff + startBackOff) { + hideLine(); + return; + } + var start0 = el.getPointAtLength(0); + var dstart = el.getPointAtLength(0.1); + startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); + start = el.getPointAtLength(Math.min(startBackOff, pathlen)); + dashArray = "0px," + startBackOff + "px,"; + var end0 = el.getPointAtLength(pathlen); + var dend = el.getPointAtLength(pathlen - 0.1); + endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); + end = el.getPointAtLength(Math.max(0, pathlen - backOff)); + var shortening = dashArray ? startBackOff + backOff : backOff; + dashArray += pathlen - shortening + "px," + pathlen + "px"; + el3.style("stroke-dasharray", dashArray); + } + function hideLine() { + el3.style("stroke-dasharray", "0px,100px"); + } + function drawhead(arrowHeadStyle, p, rot, arrowScale) { + if (!arrowHeadStyle.path) return; + if (arrowHeadStyle.noRotate) rot = 0; + d3$k.select(el.parentNode).append("path").attr({ + class: el3.attr("class"), + d: arrowHeadStyle.path, + transform: strTranslate$5(p.x, p.y) + strRotate(rot * 180 / Math.PI) + strScale$1(arrowScale) + }).style({ + fill: Color$q.rgb(options.arrowcolor), + "stroke-width": 0 + }); + } + if (doStart) drawhead(startHeadStyle, start, startRot, startScale); + if (doEnd) drawhead(headStyle, end, endRot, scale2); +}; +var d3$j = d3Exports; +var Registry$i = registry; +var Plots$5 = plotsExports; +var Lib$U = libExports; +var strTranslate$4 = Lib$U.strTranslate; +var Axes$e = axesExports; +var Color$p = colorExports; +var Drawing$e = drawingExports; +var Fx$4 = fx$1; +var svgTextUtils$9 = svg_text_utils; +var setCursor$1 = setcursor; +var dragElement$1 = dragelementExports; +var arrayEditor$3 = plot_template.arrayEditor; +var drawArrowHead2 = draw_arrow_head; +var draw_1$1 = { + draw: draw$a, + drawOne, + drawRaw: drawRaw$1 +}; +function draw$a(gd) { + var fullLayout = gd._fullLayout; + fullLayout._infolayer.selectAll(".annotation").remove(); + for (var i = 0; i < fullLayout.annotations.length; i++) { + if (fullLayout.annotations[i].visible) { + drawOne(gd, i); + } + } + return Plots$5.previousPromises(gd); +} +function drawOne(gd, index2) { + var fullLayout = gd._fullLayout; + var options = fullLayout.annotations[index2] || {}; + var xa = Axes$e.getFromId(gd, options.xref); + var ya = Axes$e.getFromId(gd, options.yref); + if (xa) xa.setScale(); + if (ya) ya.setScale(); + drawRaw$1(gd, options, index2, false, xa, ya); +} +function shiftPosition(axa, dAx, axLetter, gs, options) { + var optAx = options[axLetter]; + var axRef = options[axLetter + "ref"]; + var vertical = axLetter.indexOf("y") !== -1; + var axDomainRef = Axes$e.getRefType(axRef) === "domain"; + var gsDim = vertical ? gs.h : gs.w; + if (axa) { + if (axDomainRef) { + return optAx + (vertical ? -dAx : dAx) / axa._length; + } else { + return axa.p2r(axa.r2p(optAx) + dAx); + } + } else { + return optAx + (vertical ? -dAx : dAx) / gsDim; + } +} +function drawRaw$1(gd, options, index2, subplotId, xa, ya) { + var fullLayout = gd._fullLayout; + var gs = gd._fullLayout._size; + var edits = gd._context.edits; + var className, containerStr; + if (subplotId) { + className = "annotation-" + subplotId; + containerStr = subplotId + ".annotations"; + } else { + className = "annotation"; + containerStr = "annotations"; + } + var editHelpers = arrayEditor$3(gd.layout, containerStr, options); + var modifyBase = editHelpers.modifyBase; + var modifyItem = editHelpers.modifyItem; + var getUpdateObj = editHelpers.getUpdateObj; + fullLayout._infolayer.selectAll("." + className + '[data-index="' + index2 + '"]').remove(); + var annClipID = "clip" + fullLayout._uid + "_ann" + index2; + if (!options._input || options.visible === false) { + d3$j.selectAll("#" + annClipID).remove(); + return; + } + var annPosPx = { x: {}, y: {} }; + var textangle = +options.textangle || 0; + var annGroup = fullLayout._infolayer.append("g").classed(className, true).attr("data-index", String(index2)).style("opacity", options.opacity); + var annTextGroup = annGroup.append("g").classed("annotation-text-g", true); + var editTextPosition = edits[options.showarrow ? "annotationTail" : "annotationPosition"]; + var textEvents = options.captureevents || edits.annotationText || editTextPosition; + function makeEventData2(initialEvent) { + var eventData5 = { + index: index2, + annotation: options._input, + fullAnnotation: options, + event: initialEvent + }; + if (subplotId) { + eventData5.subplotId = subplotId; + } + return eventData5; + } + var annTextGroupInner = annTextGroup.append("g").style("pointer-events", textEvents ? "all" : null).call(setCursor$1, "pointer").on("click", function() { + gd._dragging = false; + gd.emit("plotly_clickannotation", makeEventData2(d3$j.event)); + }); + if (options.hovertext) { + annTextGroupInner.on("mouseover", function() { + var hoverOptions = options.hoverlabel; + var hoverFont = hoverOptions.font; + var bBox = this.getBoundingClientRect(); + var bBoxRef = gd.getBoundingClientRect(); + Fx$4.loneHover({ + x0: bBox.left - bBoxRef.left, + x1: bBox.right - bBoxRef.left, + y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, + text: options.hovertext, + color: hoverOptions.bgcolor, + borderColor: hoverOptions.bordercolor, + fontFamily: hoverFont.family, + fontSize: hoverFont.size, + fontColor: hoverFont.color, + fontWeight: hoverFont.weight, + fontStyle: hoverFont.style, + fontVariant: hoverFont.variant, + fontShadow: hoverFont.fontShadow, + fontLineposition: hoverFont.fontLineposition, + fontTextcase: hoverFont.fontTextcase + }, { + container: fullLayout._hoverlayer.node(), + outerContainer: fullLayout._paper.node(), + gd + }); + }).on("mouseout", function() { + Fx$4.loneUnhover(fullLayout._hoverlayer.node()); + }); + } + var borderwidth = options.borderwidth; + var borderpad = options.borderpad; + var borderfull = borderwidth + borderpad; + var annTextBG = annTextGroupInner.append("rect").attr("class", "bg").style("stroke-width", borderwidth + "px").call(Color$p.stroke, options.bordercolor).call(Color$p.fill, options.bgcolor); + var isSizeConstrained = options.width || options.height; + var annTextClip = fullLayout._topclips.selectAll("#" + annClipID).data(isSizeConstrained ? [0] : []); + annTextClip.enter().append("clipPath").classed("annclip", true).attr("id", annClipID).append("rect"); + annTextClip.exit().remove(); + var font2 = options.font; + var text = fullLayout._meta ? Lib$U.templateString(options.text, fullLayout._meta) : options.text; + var annText = annTextGroupInner.append("text").classed("annotation-text", true).text(text); + function textLayout2(s) { + s.call(Drawing$e.font, font2).attr({ + "text-anchor": { + left: "start", + right: "end" + }[options.align] || "middle" + }); + svgTextUtils$9.convertToTspans(s, gd, drawGraphicalElements); + return s; + } + function drawGraphicalElements() { + var anchor3 = annText.selectAll("a"); + if (anchor3.size() === 1 && anchor3.text() === annText.text()) { + var wholeLink = annTextGroupInner.insert("a", ":first-child").attr({ + "xlink:xlink:href": anchor3.attr("xlink:href"), + "xlink:xlink:show": anchor3.attr("xlink:show") + }).style({ cursor: "pointer" }); + wholeLink.node().appendChild(annTextBG.node()); + } + var mathjaxGroup = annTextGroupInner.select(".annotation-text-math-group"); + var hasMathjax = !mathjaxGroup.empty(); + var anntextBB = Drawing$e.bBox( + (hasMathjax ? mathjaxGroup : annText).node() + ); + var textWidth = anntextBB.width; + var textHeight = anntextBB.height; + var annWidth = options.width || textWidth; + var annHeight = options.height || textHeight; + var outerWidth = Math.round(annWidth + 2 * borderfull); + var outerHeight = Math.round(annHeight + 2 * borderfull); + function shiftFraction(v, anchor2) { + if (anchor2 === "auto") { + if (v < 1 / 3) anchor2 = "left"; + else if (v > 2 / 3) anchor2 = "right"; + else anchor2 = "center"; + } + return { + center: 0, + middle: 0, + left: 0.5, + bottom: -0.5, + right: -0.5, + top: 0.5 + }[anchor2]; + } + var annotationIsOffscreen = false; + var letters = ["x", "y"]; + for (var i = 0; i < letters.length; i++) { + var axLetter = letters[i]; + var axRef = options[axLetter + "ref"] || axLetter; + var tailRef = options["a" + axLetter + "ref"]; + var ax = { x: xa, y: ya }[axLetter]; + var dimAngle = (textangle + (axLetter === "x" ? 0 : -90)) * Math.PI / 180; + var annSizeFromWidth = outerWidth * Math.cos(dimAngle); + var annSizeFromHeight = outerHeight * Math.sin(dimAngle); + var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight); + var anchor = options[axLetter + "anchor"]; + var overallShift = options[axLetter + "shift"] * (axLetter === "x" ? 1 : -1); + var posPx = annPosPx[axLetter]; + var basePx; + var textPadShift; + var alignPosition; + var autoAlignFraction; + var textShift; + var axRefType = Axes$e.getRefType(axRef); + if (ax && axRefType !== "domain") { + var posFraction = ax.r2fraction(options[axLetter]); + if (posFraction < 0 || posFraction > 1) { + if (tailRef === axRef) { + posFraction = ax.r2fraction(options["a" + axLetter]); + if (posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + } + } else { + annotationIsOffscreen = true; + } + } + basePx = ax._offset + ax.r2p(options[axLetter]); + autoAlignFraction = 0.5; + } else { + var axRefTypeEqDomain = axRefType === "domain"; + if (axLetter === "x") { + alignPosition = options[axLetter]; + basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.l + gs.w * alignPosition; + } else { + alignPosition = 1 - options[axLetter]; + basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.t + gs.h * alignPosition; + } + autoAlignFraction = options.showarrow ? 0.5 : alignPosition; + } + if (options.showarrow) { + posPx.head = basePx; + var arrowLength = options["a" + axLetter]; + textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - annSizeFromHeight * shiftFraction(0.5, options.yanchor); + if (tailRef === axRef) { + var tailRefType = Axes$e.getRefType(tailRef); + if (tailRefType === "domain") { + if (axLetter === "y") { + arrowLength = 1 - arrowLength; + } + posPx.tail = ax._offset + ax._length * arrowLength; + } else if (tailRefType === "paper") { + if (axLetter === "y") { + arrowLength = 1 - arrowLength; + posPx.tail = gs.t + gs.h * arrowLength; + } else { + posPx.tail = gs.l + gs.w * arrowLength; + } + } else { + posPx.tail = ax._offset + ax.r2p(arrowLength); + } + textPadShift = textShift; + } else { + posPx.tail = basePx + arrowLength; + textPadShift = textShift + arrowLength; + } + posPx.text = posPx.tail + textShift; + var maxPx = fullLayout[axLetter === "x" ? "width" : "height"]; + if (axRef === "paper") { + posPx.head = Lib$U.constrain(posPx.head, 1, maxPx - 1); + } + if (tailRef === "pixel") { + var shiftPlus = -Math.max(posPx.tail - 3, posPx.text); + var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx; + if (shiftPlus > 0) { + posPx.tail += shiftPlus; + posPx.text += shiftPlus; + } else if (shiftMinus > 0) { + posPx.tail -= shiftMinus; + posPx.text -= shiftMinus; + } + } + posPx.tail += overallShift; + posPx.head += overallShift; + } else { + textShift = annSize * shiftFraction(autoAlignFraction, anchor); + textPadShift = textShift; + posPx.text = basePx + textShift; + } + posPx.text += overallShift; + textShift += overallShift; + textPadShift += overallShift; + options["_" + axLetter + "padplus"] = annSize / 2 + textPadShift; + options["_" + axLetter + "padminus"] = annSize / 2 - textPadShift; + options["_" + axLetter + "size"] = annSize; + options["_" + axLetter + "shift"] = textShift; + } + if (annotationIsOffscreen) { + annTextGroupInner.remove(); + return; + } + var xShift = 0; + var yShift = 0; + if (options.align !== "left") { + xShift = (annWidth - textWidth) * (options.align === "center" ? 0.5 : 1); + } + if (options.valign !== "top") { + yShift = (annHeight - textHeight) * (options.valign === "middle" ? 0.5 : 1); + } + if (hasMathjax) { + mathjaxGroup.select("svg").attr({ + x: borderfull + xShift - 1, + y: borderfull + yShift + }).call(Drawing$e.setClipUrl, isSizeConstrained ? annClipID : null, gd); + } else { + var texty = borderfull + yShift - anntextBB.top; + var textx = borderfull + xShift - anntextBB.left; + annText.call(svgTextUtils$9.positionText, textx, texty).call(Drawing$e.setClipUrl, isSizeConstrained ? annClipID : null, gd); + } + annTextClip.select("rect").call( + Drawing$e.setRect, + borderfull, + borderfull, + annWidth, + annHeight + ); + annTextBG.call( + Drawing$e.setRect, + borderwidth / 2, + borderwidth / 2, + outerWidth - borderwidth, + outerHeight - borderwidth + ); + annTextGroupInner.call( + Drawing$e.setTranslate, + Math.round(annPosPx.x.text - outerWidth / 2), + Math.round(annPosPx.y.text - outerHeight / 2) + ); + annTextGroup.attr({ transform: "rotate(" + textangle + "," + annPosPx.x.text + "," + annPosPx.y.text + ")" }); + var drawArrow = function(dx, dy) { + annGroup.selectAll(".annotation-arrow-g").remove(); + var headX = annPosPx.x.head; + var headY = annPosPx.y.head; + var tailX = annPosPx.x.tail + dx; + var tailY = annPosPx.y.tail + dy; + var textX = annPosPx.x.text + dx; + var textY = annPosPx.y.text + dy; + var transform = Lib$U.rotationXYMatrix(textangle, textX, textY); + var applyTransform = Lib$U.apply2DTransform(transform); + var applyTransform2 = Lib$U.apply2DTransform2(transform); + var width = +annTextBG.attr("width"); + var height = +annTextBG.attr("height"); + var xLeft = textX - 0.5 * width; + var xRight = xLeft + width; + var yTop = textY - 0.5 * height; + var yBottom = yTop + height; + var edges = [ + [xLeft, yTop, xLeft, yBottom], + [xLeft, yBottom, xRight, yBottom], + [xRight, yBottom, xRight, yTop], + [xRight, yTop, xLeft, yTop] + ].map(applyTransform2); + if (edges.reduce(function(a, x) { + return a ^ !!Lib$U.segmentsIntersect( + headX, + headY, + headX + 1e6, + headY + 1e6, + x[0], + x[1], + x[2], + x[3] + ); + }, false)) { + return; + } + edges.forEach(function(x) { + var p = Lib$U.segmentsIntersect( + tailX, + tailY, + headX, + headY, + x[0], + x[1], + x[2], + x[3] + ); + if (p) { + tailX = p.x; + tailY = p.y; + } + }); + var strokewidth = options.arrowwidth; + var arrowColor = options.arrowcolor; + var arrowSide = options.arrowside; + var arrowGroup = annGroup.append("g").style({ opacity: Color$p.opacity(arrowColor) }).classed("annotation-arrow-g", true); + var arrow = arrowGroup.append("path").attr("d", "M" + tailX + "," + tailY + "L" + headX + "," + headY).style("stroke-width", strokewidth + "px").call(Color$p.stroke, Color$p.rgb(arrowColor)); + drawArrowHead2(arrow, arrowSide, options); + if (edits.annotationPosition && arrow.node().parentNode && !subplotId) { + var arrowDragHeadX = headX; + var arrowDragHeadY = headY; + if (options.standoff) { + var arrowLength2 = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2)); + arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength2; + arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength2; + } + var arrowDrag = arrowGroup.append("path").classed("annotation-arrow", true).classed("anndrag", true).classed("cursor-move", true).attr({ + d: "M3,3H-3V-3H3ZM0,0L" + (tailX - arrowDragHeadX) + "," + (tailY - arrowDragHeadY), + transform: strTranslate$4(arrowDragHeadX, arrowDragHeadY) + }).style("stroke-width", strokewidth + 6 + "px").call(Color$p.stroke, "rgba(0,0,0,0)").call(Color$p.fill, "rgba(0,0,0,0)"); + var annx0, anny0; + dragElement$1.init({ + element: arrowDrag.node(), + gd, + prepFn: function() { + var pos = Drawing$e.getTranslate(annTextGroupInner); + annx0 = pos.x; + anny0 = pos.y; + if (xa && xa.autorange) { + modifyBase(xa._name + ".autorange", true); + } + if (ya && ya.autorange) { + modifyBase(ya._name + ".autorange", true); + } + }, + moveFn: function(dx2, dy2) { + var annxy0 = applyTransform(annx0, anny0); + var xcenter = annxy0[0] + dx2; + var ycenter = annxy0[1] + dy2; + annTextGroupInner.call(Drawing$e.setTranslate, xcenter, ycenter); + modifyItem( + "x", + shiftPosition(xa, dx2, "x", gs, options) + ); + modifyItem( + "y", + shiftPosition(ya, dy2, "y", gs, options) + ); + if (options.axref === options.xref) { + modifyItem("ax", shiftPosition(xa, dx2, "ax", gs, options)); + } + if (options.ayref === options.yref) { + modifyItem("ay", shiftPosition(ya, dy2, "ay", gs, options)); + } + arrowGroup.attr("transform", strTranslate$4(dx2, dy2)); + annTextGroup.attr({ + transform: "rotate(" + textangle + "," + xcenter + "," + ycenter + ")" + }); + }, + doneFn: function() { + Registry$i.call("_guiRelayout", gd, getUpdateObj()); + var notesBox = document.querySelector(".js-notes-box-panel"); + if (notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } + }; + if (options.showarrow) drawArrow(0, 0); + if (editTextPosition) { + var baseTextTransform; + dragElement$1.init({ + element: annTextGroupInner.node(), + gd, + prepFn: function() { + baseTextTransform = annTextGroup.attr("transform"); + }, + moveFn: function(dx, dy) { + var csr = "pointer"; + if (options.showarrow) { + if (options.axref === options.xref) { + modifyItem("ax", shiftPosition(xa, dx, "ax", gs, options)); + } else { + modifyItem("ax", options.ax + dx); + } + if (options.ayref === options.yref) { + modifyItem("ay", shiftPosition(ya, dy, "ay", gs.w, options)); + } else { + modifyItem("ay", options.ay + dy); + } + drawArrow(dx, dy); + } else if (!subplotId) { + var xUpdate, yUpdate; + if (xa) { + xUpdate = shiftPosition(xa, dx, "x", gs, options); + } else { + var widthFraction = options._xsize / gs.w; + var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2; + xUpdate = dragElement$1.align( + xLeft + dx / gs.w, + widthFraction, + 0, + 1, + options.xanchor + ); + } + if (ya) { + yUpdate = shiftPosition(ya, dy, "y", gs, options); + } else { + var heightFraction = options._ysize / gs.h; + var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2; + yUpdate = dragElement$1.align( + yBottom - dy / gs.h, + heightFraction, + 0, + 1, + options.yanchor + ); + } + modifyItem("x", xUpdate); + modifyItem("y", yUpdate); + if (!xa || !ya) { + csr = dragElement$1.getCursor( + xa ? 0.5 : xUpdate, + ya ? 0.5 : yUpdate, + options.xanchor, + options.yanchor + ); + } + } else return; + annTextGroup.attr({ + transform: strTranslate$4(dx, dy) + baseTextTransform + }); + setCursor$1(annTextGroupInner, csr); + }, + clickFn: function(_2, initialEvent) { + if (options.captureevents) { + gd.emit("plotly_clickannotation", makeEventData2(initialEvent)); + } + }, + doneFn: function() { + setCursor$1(annTextGroupInner); + Registry$i.call("_guiRelayout", gd, getUpdateObj()); + var notesBox = document.querySelector(".js-notes-box-panel"); + if (notesBox) notesBox.redraw(notesBox.selectedObj); + } + }); + } + } + if (edits.annotationText) { + annText.call(svgTextUtils$9.makeEditable, { delegate: annTextGroupInner, gd }).call(textLayout2).on("edit", function(_text) { + options.text = _text; + this.call(textLayout2); + modifyItem("text", _text); + if (xa && xa.autorange) { + modifyBase(xa._name + ".autorange", true); + } + if (ya && ya.autorange) { + modifyBase(ya._name + ".autorange", true); + } + Registry$i.call("_guiRelayout", gd, getUpdateObj()); + }); + } else annText.call(textLayout2); +} +var Lib$T = libExports; +var Registry$h = registry; +var arrayEditor$2 = plot_template.arrayEditor; +var click2 = { + hasClickToShow, + onClick +}; +function hasClickToShow(gd, hoverData) { + var sets = getToggleSets(gd, hoverData); + return sets.on.length > 0 || sets.explicitOff.length > 0; +} +function onClick(gd, hoverData) { + var toggleSets = getToggleSets(gd, hoverData); + var onSet = toggleSets.on; + var offSet = toggleSets.off.concat(toggleSets.explicitOff); + var update2 = {}; + var annotationsOut = gd._fullLayout.annotations; + var i, editHelpers; + if (!(onSet.length || offSet.length)) return; + for (i = 0; i < onSet.length; i++) { + editHelpers = arrayEditor$2(gd.layout, "annotations", annotationsOut[onSet[i]]); + editHelpers.modifyItem("visible", true); + Lib$T.extendFlat(update2, editHelpers.getUpdateObj()); + } + for (i = 0; i < offSet.length; i++) { + editHelpers = arrayEditor$2(gd.layout, "annotations", annotationsOut[offSet[i]]); + editHelpers.modifyItem("visible", false); + Lib$T.extendFlat(update2, editHelpers.getUpdateObj()); + } + return Registry$h.call("update", gd, {}, update2); +} +function getToggleSets(gd, hoverData) { + var annotations2 = gd._fullLayout.annotations; + var onSet = []; + var offSet = []; + var explicitOffSet = []; + var hoverLen = (hoverData || []).length; + var i, j, anni, showMode, pointj, xa, ya, toggleType; + for (i = 0; i < annotations2.length; i++) { + anni = annotations2[i]; + showMode = anni.clicktoshow; + if (showMode) { + for (j = 0; j < hoverLen; j++) { + pointj = hoverData[j]; + xa = pointj.xaxis; + ya = pointj.yaxis; + if (xa._id === anni.xref && ya._id === anni.yref && xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) && ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)) { + if (anni.visible) { + if (showMode === "onout") toggleType = offSet; + else toggleType = explicitOffSet; + } else { + toggleType = onSet; + } + toggleType.push(i); + break; + } + } + if (j === hoverLen) { + if (anni.visible && showMode === "onout") offSet.push(i); + } + } + } + return { on: onSet, off: offSet, explicitOff: explicitOffSet }; +} +function clickData2r(d, ax) { + return ax.type === "log" ? ax.l2r(d) : ax.d2r(d); +} +var Lib$S = libExports; +var Color$o = colorExports; +var common_defaults = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce2) { + coerce2("opacity"); + var bgColor = coerce2("bgcolor"); + var borderColor = coerce2("bordercolor"); + var borderOpacity = Color$o.opacity(borderColor); + coerce2("borderpad"); + var borderWidth = coerce2("borderwidth"); + var showArrow = coerce2("showarrow"); + coerce2("text", showArrow ? " " : fullLayout._dfltTitle.annotation); + coerce2("textangle"); + Lib$S.coerceFont(coerce2, "font", fullLayout.font); + coerce2("width"); + coerce2("align"); + var h = coerce2("height"); + if (h) coerce2("valign"); + if (showArrow) { + var arrowside = coerce2("arrowside"); + var arrowhead; + var arrowsize; + if (arrowside.indexOf("end") !== -1) { + arrowhead = coerce2("arrowhead"); + arrowsize = coerce2("arrowsize"); + } + if (arrowside.indexOf("start") !== -1) { + coerce2("startarrowhead", arrowhead); + coerce2("startarrowsize", arrowsize); + } + coerce2("arrowcolor", borderOpacity ? annOut.bordercolor : Color$o.defaultLine); + coerce2("arrowwidth", (borderOpacity && borderWidth || 1) * 2); + coerce2("standoff"); + coerce2("startstandoff"); + } + var hoverText = coerce2("hovertext"); + var globalHoverLabel = fullLayout.hoverlabel || {}; + if (hoverText) { + var hoverBG = coerce2( + "hoverlabel.bgcolor", + globalHoverLabel.bgcolor || (Color$o.opacity(bgColor) ? Color$o.rgb(bgColor) : Color$o.defaultLine) + ); + var hoverBorder = coerce2( + "hoverlabel.bordercolor", + globalHoverLabel.bordercolor || Color$o.contrast(hoverBG) + ); + var fontDflt = Lib$S.extendFlat({}, globalHoverLabel.font); + if (!fontDflt.color) { + fontDflt.color = hoverBorder; + } + Lib$S.coerceFont(coerce2, "hoverlabel.font", fontDflt); + } + coerce2("captureevents", !!hoverText); +}; +var Lib$R = libExports; +var Axes$d = axesExports; +var handleArrayContainerDefaults$6 = array_container_defaults; +var handleAnnotationCommonDefaults$1 = common_defaults; +var attributes$u = attributes$B; +var defaults$g = function supplyLayoutDefaults5(layoutIn, layoutOut) { + handleArrayContainerDefaults$6(layoutIn, layoutOut, { + name: "annotations", + handleItemDefaults: handleAnnotationDefaults$1 + }); +}; +function handleAnnotationDefaults$1(annIn, annOut, fullLayout) { + function coerce2(attr, dflt) { + return Lib$R.coerce(annIn, annOut, attributes$u, attr, dflt); + } + var visible = coerce2("visible"); + var clickToShow = coerce2("clicktoshow"); + if (!(visible || clickToShow)) return; + handleAnnotationCommonDefaults$1(annIn, annOut, fullLayout, coerce2); + var showArrow = annOut.showarrow; + var axLetters2 = ["x", "y"]; + var arrowPosDflt = [-10, -30]; + var gdMock = { _fullLayout: fullLayout }; + for (var i = 0; i < 2; i++) { + var axLetter = axLetters2[i]; + var axRef = Axes$d.coerceRef(annIn, annOut, gdMock, axLetter, "", "paper"); + if (axRef !== "paper") { + var ax = Axes$d.getFromId(gdMock, axRef); + ax._annIndices.push(annOut._index); + } + Axes$d.coercePosition(annOut, gdMock, coerce2, axRef, axLetter, 0.5); + if (showArrow) { + var arrowPosAttr = "a" + axLetter; + var aaxRef = Axes$d.coerceRef( + annIn, + annOut, + gdMock, + arrowPosAttr, + "pixel", + ["pixel", "paper"] + ); + if (aaxRef !== "pixel" && aaxRef !== axRef) { + aaxRef = annOut[arrowPosAttr] = "pixel"; + } + var aDflt = aaxRef === "pixel" ? arrowPosDflt[i] : 0.4; + Axes$d.coercePosition(annOut, gdMock, coerce2, aaxRef, arrowPosAttr, aDflt); + } + coerce2(axLetter + "anchor"); + coerce2(axLetter + "shift"); + } + Lib$R.noneOrAll(annIn, annOut, ["x", "y"]); + if (showArrow) { + Lib$R.noneOrAll(annIn, annOut, ["ax", "ay"]); + } + if (clickToShow) { + var xClick = coerce2("xclick"); + var yClick = coerce2("yclick"); + annOut._xclick = xClick === void 0 ? annOut.x : Axes$d.cleanPosition(xClick, gdMock, annOut.xref); + annOut._yclick = yClick === void 0 ? annOut.y : Axes$d.cleanPosition(yClick, gdMock, annOut.yref); + } +} +var Lib$Q = libExports; +var Axes$c = axesExports; +var draw$9 = draw_1$1.draw; +var calc_autorange$2 = function calcAutorange(gd) { + var fullLayout = gd._fullLayout; + var annotationList = Lib$Q.filterVisible(fullLayout.annotations); + if (annotationList.length && gd._fullData.length) { + return Lib$Q.syncOrAsync([draw$9, annAutorange], gd); + } +}; +function annAutorange(gd) { + var fullLayout = gd._fullLayout; + Lib$Q.filterVisible(fullLayout.annotations).forEach(function(ann) { + var xa = Axes$c.getFromId(gd, ann.xref); + var ya = Axes$c.getFromId(gd, ann.yref); + var xRefType = Axes$c.getRefType(ann.xref); + var yRefType = Axes$c.getRefType(ann.yref); + ann._extremes = {}; + if (xRefType === "range") calcAxisExpansion$1(ann, xa); + if (yRefType === "range") calcAxisExpansion$1(ann, ya); + }); +} +function calcAxisExpansion$1(ann, ax) { + var axId = ax._id; + var letter = axId.charAt(0); + var pos = ann[letter]; + var apos = ann["a" + letter]; + var ref2 = ann[letter + "ref"]; + var aref = ann["a" + letter + "ref"]; + var padplus = ann["_" + letter + "padplus"]; + var padminus = ann["_" + letter + "padminus"]; + var shift = { x: 1, y: -1 }[letter] * ann[letter + "shift"]; + var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0; + var headPlus = headSize + shift; + var headMinus = headSize - shift; + var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; + var startHeadPlus = startHeadSize + shift; + var startHeadMinus = startHeadSize - shift; + var extremes; + if (aref === ref2) { + var extremeArrowHead = Axes$c.findExtremes(ax, [ax.r2c(pos)], { + ppadplus: headPlus, + ppadminus: headMinus + }); + var extremeText = Axes$c.findExtremes(ax, [ax.r2c(apos)], { + ppadplus: Math.max(padplus, startHeadPlus), + ppadminus: Math.max(padminus, startHeadMinus) + }); + extremes = { + min: [extremeArrowHead.min[0], extremeText.min[0]], + max: [extremeArrowHead.max[0], extremeText.max[0]] + }; + } else { + startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus; + startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus; + extremes = Axes$c.findExtremes(ax, [ax.r2c(pos)], { + ppadplus: Math.max(padplus, headPlus, startHeadPlus), + ppadminus: Math.max(padminus, headMinus, startHeadMinus) + }); + } + ann._extremes[axId] = extremes; +} +var isNumeric$a = fastIsnumeric; +var toLogRange$1 = to_log_range; +var convert_coords$1 = function convertCoords(gd, ax, newType, doExtra) { + ax = ax || {}; + var toLog = newType === "log" && ax.type === "linear"; + var fromLog2 = newType === "linear" && ax.type === "log"; + if (!(toLog || fromLog2)) return; + var annotations2 = gd._fullLayout.annotations; + var axLetter = ax._id.charAt(0); + var ann; + var attrPrefix; + function convert3(attr) { + var currentVal = ann[attr]; + var newVal = null; + if (toLog) newVal = toLogRange$1(currentVal, ax.range); + else newVal = Math.pow(10, currentVal); + if (!isNumeric$a(newVal)) newVal = null; + doExtra(attrPrefix + attr, newVal); + } + for (var i = 0; i < annotations2.length; i++) { + ann = annotations2[i]; + attrPrefix = "annotations[" + i + "]."; + if (ann[axLetter + "ref"] === ax._id) convert3(axLetter); + if (ann["a" + axLetter + "ref"] === ax._id) convert3("a" + axLetter); + } +}; +var drawModule$1 = draw_1$1; +var clickModule = click2; +var annotations = { + moduleType: "component", + name: "annotations", + layoutAttributes: attributes$B, + supplyLayoutDefaults: defaults$g, + includeBasePlot: include_components("annotations"), + calcAutorange: calc_autorange$2, + draw: drawModule$1.draw, + drawOne: drawModule$1.drawOne, + drawRaw: drawModule$1.drawRaw, + hasClickToShow: clickModule.hasClickToShow, + onClick: clickModule.onClick, + convertCoords: convert_coords$1 +}; +var annAttrs$1 = attributes$B; +var overrideAll$4 = edit_types.overrideAll; +var templatedArray$5 = plot_template.templatedArray; +var attributes$t = overrideAll$4(templatedArray$5("annotation", { + visible: annAttrs$1.visible, + x: { + valType: "any", + description: [ + "Sets the annotation's x position." + ].join(" ") + }, + y: { + valType: "any", + description: [ + "Sets the annotation's y position." + ].join(" ") + }, + z: { + valType: "any", + description: [ + "Sets the annotation's z position." + ].join(" ") + }, + ax: { + valType: "number", + description: [ + "Sets the x component of the arrow tail about the arrow head (in pixels)." + ].join(" ") + }, + ay: { + valType: "number", + description: [ + "Sets the y component of the arrow tail about the arrow head (in pixels)." + ].join(" ") + }, + xanchor: annAttrs$1.xanchor, + xshift: annAttrs$1.xshift, + yanchor: annAttrs$1.yanchor, + yshift: annAttrs$1.yshift, + text: annAttrs$1.text, + textangle: annAttrs$1.textangle, + font: annAttrs$1.font, + width: annAttrs$1.width, + height: annAttrs$1.height, + opacity: annAttrs$1.opacity, + align: annAttrs$1.align, + valign: annAttrs$1.valign, + bgcolor: annAttrs$1.bgcolor, + bordercolor: annAttrs$1.bordercolor, + borderpad: annAttrs$1.borderpad, + borderwidth: annAttrs$1.borderwidth, + showarrow: annAttrs$1.showarrow, + arrowcolor: annAttrs$1.arrowcolor, + arrowhead: annAttrs$1.arrowhead, + startarrowhead: annAttrs$1.startarrowhead, + arrowside: annAttrs$1.arrowside, + arrowsize: annAttrs$1.arrowsize, + startarrowsize: annAttrs$1.startarrowsize, + arrowwidth: annAttrs$1.arrowwidth, + standoff: annAttrs$1.standoff, + startstandoff: annAttrs$1.startstandoff, + hovertext: annAttrs$1.hovertext, + hoverlabel: annAttrs$1.hoverlabel, + captureevents: annAttrs$1.captureevents + // maybes later? + // clicktoshow: annAttrs.clicktoshow, + // xclick: annAttrs.xclick, + // yclick: annAttrs.yclick, + // not needed! + // axref: 'pixel' + // ayref: 'pixel' + // xref: 'x' + // yref: 'y + // zref: 'z' +}), "calc", "from-root"); +var Lib$P = libExports; +var Axes$b = axesExports; +var handleArrayContainerDefaults$5 = array_container_defaults; +var handleAnnotationCommonDefaults2 = common_defaults; +var attributes$s = attributes$t; +var defaults$f = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { + handleArrayContainerDefaults$5(sceneLayoutIn, sceneLayoutOut, { + name: "annotations", + handleItemDefaults: handleAnnotationDefaults, + fullLayout: opts.fullLayout + }); +}; +function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) { + function coerce2(attr, dflt) { + return Lib$P.coerce(annIn, annOut, attributes$s, attr, dflt); + } + function coercePosition(axLetter) { + var axName = axLetter + "axis"; + var gdMock = { _fullLayout: {} }; + gdMock._fullLayout[axName] = sceneLayout[axName]; + return Axes$b.coercePosition(annOut, gdMock, coerce2, axLetter, axLetter, 0.5); + } + var visible = coerce2("visible"); + if (!visible) return; + handleAnnotationCommonDefaults2(annIn, annOut, opts.fullLayout, coerce2); + coercePosition("x"); + coercePosition("y"); + coercePosition("z"); + Lib$P.noneOrAll(annIn, annOut, ["x", "y", "z"]); + annOut.xref = "x"; + annOut.yref = "y"; + annOut.zref = "z"; + coerce2("xanchor"); + coerce2("yanchor"); + coerce2("xshift"); + coerce2("yshift"); + if (annOut.showarrow) { + annOut.axref = "pixel"; + annOut.ayref = "pixel"; + coerce2("ax", -10); + coerce2("ay", -30); + Lib$P.noneOrAll(annIn, annOut, ["ax", "ay"]); + } +} +var Lib$O = libExports; +var Axes$a = axesExports; +var convert$2 = function convert(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var anns = fullSceneLayout.annotations; + for (var i = 0; i < anns.length; i++) { + mockAnnAxes(anns[i], scene); + } + scene.fullLayout._infolayer.selectAll(".annotation-" + scene.id).remove(); +}; +function mockAnnAxes(ann, scene) { + var fullSceneLayout = scene.fullSceneLayout; + var domain2 = fullSceneLayout.domain; + var size = scene.fullLayout._size; + var base = { + // this gets fill in on render + pdata: null, + // to get setConvert to not execute cleanly + type: "linear", + // don't try to update them on `editable: true` + autorange: false, + // set infinite range so that annotation draw routine + // does not try to remove 'outside-range' annotations, + // this case is handled in the render loop + range: [-Infinity, Infinity] + }; + ann._xa = {}; + Lib$O.extendFlat(ann._xa, base); + Axes$a.setConvert(ann._xa); + ann._xa._offset = size.l + domain2.x[0] * size.w; + ann._xa.l2p = function() { + return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain2.x[1] - domain2.x[0]); + }; + ann._ya = {}; + Lib$O.extendFlat(ann._ya, base); + Axes$a.setConvert(ann._ya); + ann._ya._offset = size.t + (1 - domain2.y[1]) * size.h; + ann._ya.l2p = function() { + return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain2.y[1] - domain2.y[0]); + }; +} +function xformMatrix(m, v) { + var out = [0, 0, 0, 0]; + var i, j; + for (i = 0; i < 4; ++i) { + for (j = 0; j < 4; ++j) { + out[j] += m[4 * i + j] * v[i]; + } + } + return out; +} +function project$1(camera, v) { + var p = xformMatrix( + camera.projection, + xformMatrix( + camera.view, + xformMatrix(camera.model, [v[0], v[1], v[2], 1]) + ) + ); + return p; +} +var project_1 = project$1; +var drawRaw = draw_1$1.drawRaw; +var project = project_1; +var axLetters = ["x", "y", "z"]; +var draw$8 = function draw2(scene) { + var fullSceneLayout = scene.fullSceneLayout; + var dataScale = scene.dataScale; + var anns = fullSceneLayout.annotations; + for (var i = 0; i < anns.length; i++) { + var ann = anns[i]; + var annotationIsOffscreen = false; + for (var j = 0; j < 3; j++) { + var axLetter = axLetters[j]; + var pos = ann[axLetter]; + var ax = fullSceneLayout[axLetter + "axis"]; + var posFraction = ax.r2fraction(pos); + if (posFraction < 0 || posFraction > 1) { + annotationIsOffscreen = true; + break; + } + } + if (annotationIsOffscreen) { + scene.fullLayout._infolayer.select(".annotation-" + scene.id + '[data-index="' + i + '"]').remove(); + } else { + ann._pdata = project(scene.glplot.cameraParams, [ + fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], + fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], + fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] + ]); + drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); + } + } +}; +var Registry$g = registry; +var Lib$N = libExports; +var annotations3d = { + moduleType: "component", + name: "annotations3d", + schema: { + subplots: { + scene: { annotations: attributes$t } + } + }, + layoutAttributes: attributes$t, + handleDefaults: defaults$f, + includeBasePlot: includeGL3D, + convert: convert$2, + draw: draw$8 +}; +function includeGL3D(layoutIn, layoutOut) { + var GL3D = Registry$g.subplotsRegistry.gl3d; + if (!GL3D) return; + var attrRegex = GL3D.attrRegex; + var keys = Object.keys(layoutIn); + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + if (attrRegex.test(k) && (layoutIn[k].annotations || []).length) { + Lib$N.pushUnique(layoutOut._basePlotModules, GL3D); + Lib$N.pushUnique(layoutOut._subplots.gl3d, k); + } + } +} +var annAttrs = attributes$B; +var fontAttrs$7 = font_attributes; +var scatterLineAttrs$1 = attributes$A.line; +var dash$1 = attributes$M.dash; +var extendFlat$b = extend$5.extendFlat; +var templatedArray$4 = plot_template.templatedArray; +var axisPlaceableObjs$1 = axis_placeable_objects; +var basePlotAttributes = attributes$O; +var shapeTexttemplateAttrs = template_attributes.shapeTexttemplateAttrs; +var shapeLabelTexttemplateVars = label_texttemplate; +var attributes$r = templatedArray$4("shape", { + visible: extendFlat$b({}, basePlotAttributes.visible, { + editType: "calc+arraydraw", + description: [ + "Determines whether or not this shape is visible.", + "If *legendonly*, the shape is not drawn,", + "but can appear as a legend item", + "(provided that the legend itself is visible)." + ].join(" ") + }), + showlegend: { + valType: "boolean", + dflt: false, + editType: "calc+arraydraw", + description: [ + "Determines whether or not this", + "shape is shown in the legend." + ].join(" ") + }, + legend: extendFlat$b({}, basePlotAttributes.legend, { + editType: "calc+arraydraw", + description: [ + "Sets the reference to a legend to show this shape in.", + "References to these legends are *legend*, *legend2*, *legend3*, etc.", + "Settings for these legends are set in the layout, under", + "`layout.legend`, `layout.legend2`, etc." + ].join(" ") + }), + legendgroup: extendFlat$b({}, basePlotAttributes.legendgroup, { + editType: "calc+arraydraw", + description: [ + "Sets the legend group for this shape.", + "Traces and shapes part of the same legend group hide/show at the same time", + "when toggling legend items." + ].join(" ") + }), + legendgrouptitle: { + text: extendFlat$b({}, basePlotAttributes.legendgrouptitle.text, { + editType: "calc+arraydraw" + }), + font: fontAttrs$7({ + editType: "calc+arraydraw", + description: [ + "Sets this legend group's title font." + ].join(" ") + }), + editType: "calc+arraydraw" + }, + legendrank: extendFlat$b({}, basePlotAttributes.legendrank, { + editType: "calc+arraydraw", + description: [ + "Sets the legend rank for this shape.", + "Items and groups with smaller ranks are presented on top/left side while", + "with *reversed* `legend.traceorder` they are on bottom/right side.", + "The default legendrank is 1000,", + "so that you can use ranks less than 1000 to place certain items before all unranked items,", + "and ranks greater than 1000 to go after all unranked items.", + "When having unranked or equal rank items shapes would be displayed after traces", + "i.e. according to their order in data and layout." + ].join(" ") + }), + legendwidth: extendFlat$b({}, basePlotAttributes.legendwidth, { + editType: "calc+arraydraw", + description: "Sets the width (in px or fraction) of the legend for this shape." + }), + type: { + valType: "enumerated", + values: ["circle", "rect", "path", "line"], + editType: "calc+arraydraw", + description: [ + "Specifies the shape type to be drawn.", + "If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`)", + "with respect to the axes' sizing mode.", + "If *circle*, a circle is drawn from", + "((`x0`+`x1`)/2, (`y0`+`y1`)/2))", + "with radius", + "(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|)", + "with respect to the axes' sizing mode.", + "If *rect*, a rectangle is drawn linking", + "(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`)", + "with respect to the axes' sizing mode.", + "If *path*, draw a custom SVG path using `path`.", + "with respect to the axes' sizing mode." + ].join(" ") + }, + layer: { + valType: "enumerated", + values: ["below", "above", "between"], + dflt: "above", + editType: "arraydraw", + description: [ + "Specifies whether shapes are drawn below gridlines (*below*),", + "between gridlines and traces (*between*) or above traces (*above*)." + ].join(" ") + }, + xref: extendFlat$b({}, annAttrs.xref, { + description: [ + "Sets the shape's x coordinate axis.", + axisPlaceableObjs$1.axisRefDescription("x", "left", "right") + ].join(" ") + }), + xsizemode: { + valType: "enumerated", + values: ["scaled", "pixel"], + dflt: "scaled", + editType: "calc+arraydraw", + description: [ + "Sets the shapes's sizing mode along the x axis.", + "If set to *scaled*, `x0`, `x1` and x coordinates within `path` refer to", + "data values on the x axis or a fraction of the plot area's width", + "(`xref` set to *paper*).", + "If set to *pixel*, `xanchor` specifies the x position in terms", + "of data or plot fraction but `x0`, `x1` and x coordinates within `path`", + "are pixels relative to `xanchor`. This way, the shape can have", + "a fixed width while maintaining a position relative to data or", + "plot fraction." + ].join(" ") + }, + xanchor: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Only relevant in conjunction with `xsizemode` set to *pixel*.", + "Specifies the anchor point on the x axis to which `x0`, `x1`", + "and x coordinates within `path` are relative to.", + "E.g. useful to attach a pixel sized shape to a certain data value.", + "No effect when `xsizemode` not set to *pixel*." + ].join(" ") + }, + x0: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the shape's starting x position.", + "See `type` and `xsizemode` for more info." + ].join(" ") + }, + x1: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the shape's end x position.", + "See `type` and `xsizemode` for more info." + ].join(" ") + }, + x0shift: { + valType: "number", + dflt: 0, + min: -1, + max: 1, + editType: "calc", + description: [ + "Shifts `x0` away from the center of the category when `xref` is a *category* or", + "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", + "corresponds to the end of the category." + ].join(" ") + }, + x1shift: { + valType: "number", + dflt: 0, + min: -1, + max: 1, + editType: "calc", + description: [ + "Shifts `x1` away from the center of the category when `xref` is a *category* or", + "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", + "corresponds to the end of the category." + ].join(" ") + }, + yref: extendFlat$b({}, annAttrs.yref, { + description: [ + "Sets the shape's y coordinate axis.", + axisPlaceableObjs$1.axisRefDescription("y", "bottom", "top") + ].join(" ") + }), + ysizemode: { + valType: "enumerated", + values: ["scaled", "pixel"], + dflt: "scaled", + editType: "calc+arraydraw", + description: [ + "Sets the shapes's sizing mode along the y axis.", + "If set to *scaled*, `y0`, `y1` and y coordinates within `path` refer to", + "data values on the y axis or a fraction of the plot area's height", + "(`yref` set to *paper*).", + "If set to *pixel*, `yanchor` specifies the y position in terms", + "of data or plot fraction but `y0`, `y1` and y coordinates within `path`", + "are pixels relative to `yanchor`. This way, the shape can have", + "a fixed height while maintaining a position relative to data or", + "plot fraction." + ].join(" ") + }, + yanchor: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Only relevant in conjunction with `ysizemode` set to *pixel*.", + "Specifies the anchor point on the y axis to which `y0`, `y1`", + "and y coordinates within `path` are relative to.", + "E.g. useful to attach a pixel sized shape to a certain data value.", + "No effect when `ysizemode` not set to *pixel*." + ].join(" ") + }, + y0: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the shape's starting y position.", + "See `type` and `ysizemode` for more info." + ].join(" ") + }, + y1: { + valType: "any", + editType: "calc+arraydraw", + description: [ + "Sets the shape's end y position.", + "See `type` and `ysizemode` for more info." + ].join(" ") + }, + y0shift: { + valType: "number", + dflt: 0, + min: -1, + max: 1, + editType: "calc", + description: [ + "Shifts `y0` away from the center of the category when `yref` is a *category* or", + "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", + "corresponds to the end of the category." + ].join(" ") + }, + y1shift: { + valType: "number", + dflt: 0, + min: -1, + max: 1, + editType: "calc", + description: [ + "Shifts `y1` away from the center of the category when `yref` is a *category* or", + "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", + "corresponds to the end of the category." + ].join(" ") + }, + path: { + valType: "string", + editType: "calc+arraydraw", + description: [ + "For `type` *path* - a valid SVG path with the pixel values", + "replaced by data values in `xsizemode`/`ysizemode` being *scaled*", + "and taken unmodified as pixels relative to `xanchor` and `yanchor`", + "in case of *pixel* size mode.", + "There are a few restrictions / quirks", + "only absolute instructions, not relative. So the allowed segments", + "are: M, L, H, V, Q, C, T, S, and Z", + "arcs (A) are not allowed because radius rx and ry are relative.", + "In the future we could consider supporting relative commands,", + "but we would have to decide on how to handle date and log axes.", + "Note that even as is, Q and C Bezier paths that are smooth on", + "linear axes may not be smooth on log, and vice versa.", + 'no chained "polybezier" commands - specify the segment type for', + "each one.", + "On category axes, values are numbers scaled to the serial numbers", + "of categories because using the categories themselves there would", + "be no way to describe fractional positions", + "On data axes: because space and T are both normal components of path", + "strings, we can't use either to separate date from time parts.", + "Therefore we'll use underscore for this purpose:", + "2015-02-21_13:45:56.789" + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 1, + editType: "arraydraw", + description: "Sets the opacity of the shape." + }, + line: { + color: extendFlat$b({}, scatterLineAttrs$1.color, { editType: "arraydraw" }), + width: extendFlat$b({}, scatterLineAttrs$1.width, { editType: "calc+arraydraw" }), + dash: extendFlat$b({}, dash$1, { editType: "arraydraw" }), + editType: "calc+arraydraw" + }, + fillcolor: { + valType: "color", + dflt: "rgba(0,0,0,0)", + editType: "arraydraw", + description: [ + "Sets the color filling the shape's interior. Only applies to closed shapes." + ].join(" ") + }, + fillrule: { + valType: "enumerated", + values: ["evenodd", "nonzero"], + dflt: "evenodd", + editType: "arraydraw", + description: [ + "Determines which regions of complex paths constitute the interior.", + "For more info please visit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule" + ].join(" ") + }, + editable: { + valType: "boolean", + dflt: false, + editType: "calc+arraydraw", + description: [ + "Determines whether the shape could be activated for edit or not.", + "Has no effect when the older editable shapes mode is enabled via", + "`config.editable` or `config.edits.shapePosition`." + ].join(" ") + }, + label: { + text: { + valType: "string", + dflt: "", + editType: "arraydraw", + description: [ + "Sets the text to display with shape.", + "It is also used for legend item if `name` is not provided." + ].join(" ") + }, + texttemplate: shapeTexttemplateAttrs({}, { keys: Object.keys(shapeLabelTexttemplateVars) }), + font: fontAttrs$7({ + editType: "calc+arraydraw", + colorEditType: "arraydraw", + description: "Sets the shape label text font." + }), + textposition: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right", + "start", + "middle", + "end" + ], + editType: "arraydraw", + description: [ + "Sets the position of the label text relative to the shape.", + "Supported values for rectangles, circles and paths are", + "*top left*, *top center*, *top right*, *middle left*,", + "*middle center*, *middle right*, *bottom left*, *bottom center*,", + "and *bottom right*.", + "Supported values for lines are *start*, *middle*, and *end*.", + "Default: *middle center* for rectangles, circles, and paths; *middle* for lines." + ].join(" ") + }, + textangle: { + valType: "angle", + dflt: "auto", + editType: "calc+arraydraw", + description: [ + "Sets the angle at which the label text is drawn", + "with respect to the horizontal. For lines, angle *auto*", + "is the same angle as the line. For all other shapes,", + "angle *auto* is horizontal." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "auto", + editType: "calc+arraydraw", + description: [ + "Sets the label's horizontal position anchor", + "This anchor binds the specified `textposition` to the *left*, *center*", + "or *right* of the label text.", + "For example, if `textposition` is set to *top right* and", + "`xanchor` to *right* then the right-most portion of the", + "label text lines up with the right-most edge of the", + "shape." + ].join(" ") + }, + yanchor: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + editType: "calc+arraydraw", + description: [ + "Sets the label's vertical position anchor", + "This anchor binds the specified `textposition` to the *top*, *middle*", + "or *bottom* of the label text.", + "For example, if `textposition` is set to *top right* and", + "`yanchor` to *top* then the top-most portion of the", + "label text lines up with the top-most edge of the", + "shape." + ].join(" ") + }, + padding: { + valType: "number", + dflt: 3, + min: 0, + editType: "arraydraw", + description: "Sets padding (in px) between edge of label and edge of shape." + }, + editType: "arraydraw" + }, + editType: "arraydraw" +}); +var Lib$M = libExports; +var Axes$9 = axesExports; +var handleArrayContainerDefaults$4 = array_container_defaults; +var attributes$q = attributes$r; +var helpers$j = helpers$w; +var defaults$e = function supplyLayoutDefaults6(layoutIn, layoutOut) { + handleArrayContainerDefaults$4(layoutIn, layoutOut, { + name: "shapes", + handleItemDefaults: handleShapeDefaults + }); +}; +function dfltLabelYanchor$1(isLine, labelTextPosition) { + return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; +} +function handleShapeDefaults(shapeIn, shapeOut, fullLayout) { + function coerce2(attr, dflt) { + return Lib$M.coerce(shapeIn, shapeOut, attributes$q, attr, dflt); + } + shapeOut._isShape = true; + var visible = coerce2("visible"); + if (!visible) return; + var showlegend = coerce2("showlegend"); + if (showlegend) { + coerce2("legend"); + coerce2("legendwidth"); + coerce2("legendgroup"); + coerce2("legendgrouptitle.text"); + Lib$M.coerceFont(coerce2, "legendgrouptitle.font"); + coerce2("legendrank"); + } + var path = coerce2("path"); + var dfltType = path ? "path" : "rect"; + var shapeType = coerce2("type", dfltType); + var noPath = shapeType !== "path"; + if (noPath) delete shapeOut.path; + coerce2("editable"); + coerce2("layer"); + coerce2("opacity"); + coerce2("fillcolor"); + coerce2("fillrule"); + var lineWidth = coerce2("line.width"); + if (lineWidth) { + coerce2("line.color"); + coerce2("line.dash"); + } + var xSizeMode = coerce2("xsizemode"); + var ySizeMode = coerce2("ysizemode"); + var axLetters2 = ["x", "y"]; + for (var i = 0; i < 2; i++) { + var axLetter = axLetters2[i]; + var attrAnchor = axLetter + "anchor"; + var sizeMode = axLetter === "x" ? xSizeMode : ySizeMode; + var gdMock = { _fullLayout: fullLayout }; + var ax; + var pos2r; + var r2pos; + var axRef = Axes$9.coerceRef( + shapeIn, + shapeOut, + gdMock, + axLetter, + void 0, + "paper" + ); + var axRefType = Axes$9.getRefType(axRef); + if (axRefType === "range") { + ax = Axes$9.getFromId(gdMock, axRef); + ax._shapeIndices.push(shapeOut._index); + r2pos = helpers$j.rangeToShapePosition(ax); + pos2r = helpers$j.shapePositionToRange(ax); + if (ax.type === "category" || ax.type === "multicategory") { + coerce2(axLetter + "0shift"); + coerce2(axLetter + "1shift"); + } + } else { + pos2r = r2pos = Lib$M.identity; + } + if (noPath) { + var dflt0 = 0.25; + var dflt1 = 0.75; + var attr0 = axLetter + "0"; + var attr1 = axLetter + "1"; + var in0 = shapeIn[attr0]; + var in1 = shapeIn[attr1]; + shapeIn[attr0] = pos2r(shapeIn[attr0], true); + shapeIn[attr1] = pos2r(shapeIn[attr1], true); + if (sizeMode === "pixel") { + coerce2(attr0, 0); + coerce2(attr1, 10); + } else { + Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attr0, dflt0); + Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attr1, dflt1); + } + shapeOut[attr0] = r2pos(shapeOut[attr0]); + shapeOut[attr1] = r2pos(shapeOut[attr1]); + shapeIn[attr0] = in0; + shapeIn[attr1] = in1; + } + if (sizeMode === "pixel") { + var inAnchor = shapeIn[attrAnchor]; + shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); + Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attrAnchor, 0.25); + shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); + shapeIn[attrAnchor] = inAnchor; + } + } + if (noPath) { + Lib$M.noneOrAll(shapeIn, shapeOut, ["x0", "x1", "y0", "y1"]); + } + var isLine = shapeType === "line"; + var labelTextTemplate, labelText; + if (noPath) { + labelTextTemplate = coerce2("label.texttemplate"); + } + if (!labelTextTemplate) { + labelText = coerce2("label.text"); + } + if (labelText || labelTextTemplate) { + coerce2("label.textangle"); + var labelTextPosition = coerce2("label.textposition", isLine ? "middle" : "middle center"); + coerce2("label.xanchor"); + coerce2("label.yanchor", dfltLabelYanchor$1(isLine, labelTextPosition)); + coerce2("label.padding"); + Lib$M.coerceFont(coerce2, "label.font", fullLayout.font); + } +} +var Color$n = colorExports; +var Lib$L = libExports; +function dfltLabelYanchor(isLine, labelTextPosition) { + return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; +} +var defaults$d = function supplyDrawNewShapeDefaults(layoutIn, layoutOut, coerce2) { + coerce2("newshape.visible"); + coerce2("newshape.name"); + coerce2("newshape.showlegend"); + coerce2("newshape.legend"); + coerce2("newshape.legendwidth"); + coerce2("newshape.legendgroup"); + coerce2("newshape.legendgrouptitle.text"); + Lib$L.coerceFont(coerce2, "newshape.legendgrouptitle.font"); + coerce2("newshape.legendrank"); + coerce2("newshape.drawdirection"); + coerce2("newshape.layer"); + coerce2("newshape.fillcolor"); + coerce2("newshape.fillrule"); + coerce2("newshape.opacity"); + var newshapeLineWidth = coerce2("newshape.line.width"); + if (newshapeLineWidth) { + var bgcolor = (layoutIn || {}).plot_bgcolor || "#FFF"; + coerce2("newshape.line.color", Color$n.contrast(bgcolor)); + coerce2("newshape.line.dash"); + } + var isLine = layoutIn.dragmode === "drawline"; + var labelText = coerce2("newshape.label.text"); + var labelTextTemplate = coerce2("newshape.label.texttemplate"); + if (labelText || labelTextTemplate) { + coerce2("newshape.label.textangle"); + var labelTextPosition = coerce2("newshape.label.textposition", isLine ? "middle" : "middle center"); + coerce2("newshape.label.xanchor"); + coerce2("newshape.label.yanchor", dfltLabelYanchor(isLine, labelTextPosition)); + coerce2("newshape.label.padding"); + Lib$L.coerceFont(coerce2, "newshape.label.font", layoutOut.font); + } + coerce2("activeshape.fillcolor"); + coerce2("activeshape.opacity"); +}; +var Lib$K = libExports; +var Axes$8 = axesExports; +var constants$v = constants$I; +var helpers$i = helpers$w; +var calc_autorange$1 = function calcAutorange2(gd) { + var fullLayout = gd._fullLayout; + var shapeList = Lib$K.filterVisible(fullLayout.shapes); + if (!shapeList.length || !gd._fullData.length) return; + for (var i = 0; i < shapeList.length; i++) { + var shape = shapeList[i]; + shape._extremes = {}; + var ax; + var bounds; + var xRefType = Axes$8.getRefType(shape.xref); + var yRefType = Axes$8.getRefType(shape.yref); + if (shape.xref !== "paper" && xRefType !== "domain") { + ax = Axes$8.getFromId(gd, shape.xref); + bounds = shapeBounds(ax, shape, constants$v.paramIsX); + if (bounds) { + shape._extremes[ax._id] = Axes$8.findExtremes(ax, bounds, calcXPaddingOptions(shape)); + } + } + if (shape.yref !== "paper" && yRefType !== "domain") { + ax = Axes$8.getFromId(gd, shape.yref); + bounds = shapeBounds(ax, shape, constants$v.paramIsY); + if (bounds) { + shape._extremes[ax._id] = Axes$8.findExtremes(ax, bounds, calcYPaddingOptions(shape)); + } + } + } +}; +function calcXPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); +} +function calcYPaddingOptions(shape) { + return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); +} +function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { + var ppad = lineWidth / 2; + var axisDirectionReverted = isYAxis; + if (sizeMode === "pixel") { + var coords = path ? helpers$i.extractPathCoords(path, isYAxis ? constants$v.paramIsY : constants$v.paramIsX) : [v0, v1]; + var maxValue = Lib$K.aggNums(Math.max, null, coords); + var minValue = Lib$K.aggNums(Math.min, null, coords); + var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad; + var afterPad = maxValue > 0 ? maxValue + ppad : ppad; + return { + ppad, + ppadplus: axisDirectionReverted ? beforePad : afterPad, + ppadminus: axisDirectionReverted ? afterPad : beforePad + }; + } else { + return { ppad }; + } +} +function shapeBounds(ax, shape, paramsToUse) { + var dim = ax._id.charAt(0) === "x" ? "x" : "y"; + var isCategory = ax.type === "category" || ax.type === "multicategory"; + var v0; + var v1; + var shiftStart = 0; + var shiftEnd = 0; + var convertVal = isCategory ? ax.r2c : ax.d2c; + var isSizeModeScale = shape[dim + "sizemode"] === "scaled"; + if (isSizeModeScale) { + v0 = shape[dim + "0"]; + v1 = shape[dim + "1"]; + if (isCategory) { + shiftStart = shape[dim + "0shift"]; + shiftEnd = shape[dim + "1shift"]; + } + } else { + v0 = shape[dim + "anchor"]; + v1 = shape[dim + "anchor"]; + } + if (v0 !== void 0) return [convertVal(v0) + shiftStart, convertVal(v1) + shiftEnd]; + if (!shape.path) return; + var min = Infinity; + var max = -Infinity; + var segments = shape.path.match(constants$v.segmentRE); + var i; + var segment2; + var drawnParam; + var params; + var val; + if (ax.type === "date") convertVal = helpers$i.decodeDate(convertVal); + for (i = 0; i < segments.length; i++) { + segment2 = segments[i]; + drawnParam = paramsToUse[segment2.charAt(0)].drawn; + if (drawnParam === void 0) continue; + params = segments[i].substr(1).match(constants$v.paramRE); + if (!params || params.length < drawnParam) continue; + val = convertVal(params[drawnParam]); + if (val < min) min = val; + if (val > max) max = val; + } + if (max >= min) return [min, max]; +} +var drawModule = draw_1$3; +var shapes = { + moduleType: "component", + name: "shapes", + layoutAttributes: attributes$r, + supplyLayoutDefaults: defaults$e, + supplyDrawNewShapeDefaults: defaults$d, + includeBasePlot: include_components("shapes"), + calcAutorange: calc_autorange$1, + draw: drawModule.draw, + drawOne: drawModule.drawOne +}; +var cartesianConstants = constants$U; +var templatedArray$3 = plot_template.templatedArray; +var axisPlaceableObjs = axis_placeable_objects; +var attributes$p = templatedArray$3("image", { + visible: { + valType: "boolean", + dflt: true, + editType: "arraydraw", + description: [ + "Determines whether or not this image is visible." + ].join(" ") + }, + source: { + valType: "string", + editType: "arraydraw", + description: [ + "Specifies the URL of the image to be used.", + "The URL must be accessible from the domain where the", + "plot code is run, and can be either relative or absolute." + ].join(" ") + }, + layer: { + valType: "enumerated", + values: ["below", "above"], + dflt: "above", + editType: "arraydraw", + description: [ + "Specifies whether images are drawn below or above traces.", + "When `xref` and `yref` are both set to `paper`,", + "image is drawn below the entire plot area." + ].join(" ") + }, + sizex: { + valType: "number", + dflt: 0, + editType: "arraydraw", + description: [ + "Sets the image container size horizontally.", + "The image will be sized based on the `position` value.", + "When `xref` is set to `paper`, units are sized relative", + "to the plot width.", + "When `xref` ends with ` domain`, units are sized relative", + "to the axis width." + ].join(" ") + }, + sizey: { + valType: "number", + dflt: 0, + editType: "arraydraw", + description: [ + "Sets the image container size vertically.", + "The image will be sized based on the `position` value.", + "When `yref` is set to `paper`, units are sized relative", + "to the plot height.", + "When `yref` ends with ` domain`, units are sized relative", + "to the axis height." + ].join(" ") + }, + sizing: { + valType: "enumerated", + values: ["fill", "contain", "stretch"], + dflt: "contain", + editType: "arraydraw", + description: [ + "Specifies which dimension of the image to constrain." + ].join(" ") + }, + opacity: { + valType: "number", + min: 0, + max: 1, + dflt: 1, + editType: "arraydraw", + description: "Sets the opacity of the image." + }, + x: { + valType: "any", + dflt: 0, + editType: "arraydraw", + description: [ + "Sets the image's x position.", + "When `xref` is set to `paper`, units are sized relative", + "to the plot height.", + "See `xref` for more info" + ].join(" ") + }, + y: { + valType: "any", + dflt: 0, + editType: "arraydraw", + description: [ + "Sets the image's y position.", + "When `yref` is set to `paper`, units are sized relative", + "to the plot height.", + "See `yref` for more info" + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["left", "center", "right"], + dflt: "left", + editType: "arraydraw", + description: "Sets the anchor for the x position" + }, + yanchor: { + valType: "enumerated", + values: ["top", "middle", "bottom"], + dflt: "top", + editType: "arraydraw", + description: "Sets the anchor for the y position." + }, + xref: { + valType: "enumerated", + values: [ + "paper", + cartesianConstants.idRegex.x.toString() + ], + dflt: "paper", + editType: "arraydraw", + description: [ + "Sets the images's x coordinate axis.", + axisPlaceableObjs.axisRefDescription("x", "left", "right") + ].join(" ") + }, + yref: { + valType: "enumerated", + values: [ + "paper", + cartesianConstants.idRegex.y.toString() + ], + dflt: "paper", + editType: "arraydraw", + description: [ + "Sets the images's y coordinate axis.", + axisPlaceableObjs.axisRefDescription("y", "bottom", "top") + ].join(" ") + }, + editType: "arraydraw" +}); +var Lib$J = libExports; +var Axes$7 = axesExports; +var handleArrayContainerDefaults$3 = array_container_defaults; +var attributes$o = attributes$p; +var name$3 = "images"; +var defaults$c = function supplyLayoutDefaults7(layoutIn, layoutOut) { + var opts = { + name: name$3, + handleItemDefaults: imageDefaults + }; + handleArrayContainerDefaults$3(layoutIn, layoutOut, opts); +}; +function imageDefaults(imageIn, imageOut, fullLayout) { + function coerce2(attr, dflt) { + return Lib$J.coerce(imageIn, imageOut, attributes$o, attr, dflt); + } + var source = coerce2("source"); + var visible = coerce2("visible", !!source); + if (!visible) return imageOut; + coerce2("layer"); + coerce2("xanchor"); + coerce2("yanchor"); + coerce2("sizex"); + coerce2("sizey"); + coerce2("sizing"); + coerce2("opacity"); + var gdMock = { _fullLayout: fullLayout }; + var axLetters2 = ["x", "y"]; + for (var i = 0; i < 2; i++) { + var axLetter = axLetters2[i]; + var axRef = Axes$7.coerceRef(imageIn, imageOut, gdMock, axLetter, "paper", void 0); + if (axRef !== "paper") { + var ax = Axes$7.getFromId(gdMock, axRef); + ax._imgIndices.push(imageOut._index); + } + Axes$7.coercePosition(imageOut, gdMock, coerce2, axRef, axLetter, 0); + } + return imageOut; +} +var d3$i = d3Exports; +var Drawing$d = drawingExports; +var Axes$6 = axesExports; +var axisIds$2 = axis_ids; +var xmlnsNamespaces = xmlns_namespaces; +var draw$7 = function draw3(gd) { + var fullLayout = gd._fullLayout; + var imageDataAbove = []; + var imageDataSubplot = {}; + var imageDataBelow = []; + var subplot; + var i; + for (i = 0; i < fullLayout.images.length; i++) { + var img = fullLayout.images[i]; + if (img.visible) { + if (img.layer === "below" && img.xref !== "paper" && img.yref !== "paper") { + subplot = axisIds$2.ref2id(img.xref) + axisIds$2.ref2id(img.yref); + var plotinfo = fullLayout._plots[subplot]; + if (!plotinfo) { + imageDataBelow.push(img); + continue; + } + if (plotinfo.mainplot) { + subplot = plotinfo.mainplot.id; + } + if (!imageDataSubplot[subplot]) { + imageDataSubplot[subplot] = []; + } + imageDataSubplot[subplot].push(img); + } else if (img.layer === "above") { + imageDataAbove.push(img); + } else { + imageDataBelow.push(img); + } + } + } + var anchors = { + x: { + left: { sizing: "xMin", offset: 0 }, + center: { sizing: "xMid", offset: -1 / 2 }, + right: { sizing: "xMax", offset: -1 } + }, + y: { + top: { sizing: "YMin", offset: 0 }, + middle: { sizing: "YMid", offset: -1 / 2 }, + bottom: { sizing: "YMax", offset: -1 } + } + }; + function setImage(d) { + var thisImage = d3$i.select(this); + if (this._imgSrc === d.source) { + return; + } + thisImage.attr("xmlns", xmlnsNamespaces.svg); + if (d.source && d.source.slice(0, 5) === "data:") { + thisImage.attr("xlink:href", d.source); + this._imgSrc = d.source; + } else { + var imagePromise = new Promise((function(resolve) { + var img2 = new Image(); + this.img = img2; + img2.setAttribute("crossOrigin", "anonymous"); + img2.onerror = errorHandler; + img2.onload = function() { + var canvas2 = document.createElement("canvas"); + canvas2.width = this.width; + canvas2.height = this.height; + var ctx2 = canvas2.getContext("2d", { willReadFrequently: true }); + ctx2.drawImage(this, 0, 0); + var dataURL = canvas2.toDataURL("image/png"); + thisImage.attr("xlink:href", dataURL); + resolve(); + }; + thisImage.on("error", errorHandler); + img2.src = d.source; + this._imgSrc = d.source; + function errorHandler() { + thisImage.remove(); + resolve(); + } + }).bind(this)); + gd._promises.push(imagePromise); + } + } + function applyAttributes2(d) { + var thisImage = d3$i.select(this); + var xa = Axes$6.getFromId(gd, d.xref); + var ya = Axes$6.getFromId(gd, d.yref); + var xIsDomain = Axes$6.getRefType(d.xref) === "domain"; + var yIsDomain = Axes$6.getRefType(d.yref) === "domain"; + var size = fullLayout._size; + var width, height; + if (xa !== void 0) { + width = typeof d.xref === "string" && xIsDomain ? xa._length * d.sizex : Math.abs(xa.l2p(d.sizex) - xa.l2p(0)); + } else { + width = d.sizex * size.w; + } + if (ya !== void 0) { + height = typeof d.yref === "string" && yIsDomain ? ya._length * d.sizey : Math.abs(ya.l2p(d.sizey) - ya.l2p(0)); + } else { + height = d.sizey * size.h; + } + var xOffset = width * anchors.x[d.xanchor].offset; + var yOffset = height * anchors.y[d.yanchor].offset; + var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; + var xPos, yPos; + if (xa !== void 0) { + xPos = typeof d.xref === "string" && xIsDomain ? xa._length * d.x + xa._offset : xa.r2p(d.x) + xa._offset; + } else { + xPos = d.x * size.w + size.l; + } + xPos += xOffset; + if (ya !== void 0) { + yPos = typeof d.yref === "string" && yIsDomain ? ( + // consistent with "paper" yref value, where positive values + // move up the page + ya._length * (1 - d.y) + ya._offset + ) : ya.r2p(d.y) + ya._offset; + } else { + yPos = size.h - d.y * size.h + size.t; + } + yPos += yOffset; + switch (d.sizing) { + case "fill": + sizing += " slice"; + break; + case "stretch": + sizing = "none"; + break; + } + thisImage.attr({ + x: xPos, + y: yPos, + width, + height, + preserveAspectRatio: sizing, + opacity: d.opacity + }); + var xId = xa && Axes$6.getRefType(d.xref) !== "domain" ? xa._id : ""; + var yId = ya && Axes$6.getRefType(d.yref) !== "domain" ? ya._id : ""; + var clipAxes = xId + yId; + Drawing$d.setClipUrl( + thisImage, + clipAxes ? "clip" + fullLayout._uid + clipAxes : null, + gd + ); + } + var imagesBelow = fullLayout._imageLowerLayer.selectAll("image").data(imageDataBelow); + var imagesAbove = fullLayout._imageUpperLayer.selectAll("image").data(imageDataAbove); + imagesBelow.enter().append("image"); + imagesAbove.enter().append("image"); + imagesBelow.exit().remove(); + imagesAbove.exit().remove(); + imagesBelow.each(function(d) { + setImage.bind(this)(d); + applyAttributes2.bind(this)(d); + }); + imagesAbove.each(function(d) { + setImage.bind(this)(d); + applyAttributes2.bind(this)(d); + }); + var allSubplots = Object.keys(fullLayout._plots); + for (i = 0; i < allSubplots.length; i++) { + subplot = allSubplots[i]; + var subplotObj = fullLayout._plots[subplot]; + if (!subplotObj.imagelayer) continue; + var imagesOnSubplot = subplotObj.imagelayer.selectAll("image").data(imageDataSubplot[subplot] || []); + imagesOnSubplot.enter().append("image"); + imagesOnSubplot.exit().remove(); + imagesOnSubplot.each(function(d) { + setImage.bind(this)(d); + applyAttributes2.bind(this)(d); + }); + } +}; +var isNumeric$9 = fastIsnumeric; +var toLogRange2 = to_log_range; +var convert_coords = function convertCoords2(gd, ax, newType, doExtra) { + ax = ax || {}; + var toLog = newType === "log" && ax.type === "linear"; + var fromLog2 = newType === "linear" && ax.type === "log"; + if (!(toLog || fromLog2)) return; + var images2 = gd._fullLayout.images; + var axLetter = ax._id.charAt(0); + var image; + var attrPrefix; + for (var i = 0; i < images2.length; i++) { + image = images2[i]; + attrPrefix = "images[" + i + "]."; + if (image[axLetter + "ref"] === ax._id) { + var currentPos = image[axLetter]; + var currentSize = image["size" + axLetter]; + var newPos = null; + var newSize = null; + if (toLog) { + newPos = toLogRange2(currentPos, ax.range); + var dx = currentSize / Math.pow(10, newPos) / 2; + newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; + } else { + newPos = Math.pow(10, currentPos); + newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); + } + if (!isNumeric$9(newPos)) { + newPos = null; + newSize = null; + } else if (!isNumeric$9(newSize)) newSize = null; + doExtra(attrPrefix + axLetter, newPos); + doExtra(attrPrefix + "size" + axLetter, newSize); + } + } +}; +var images = { + moduleType: "component", + name: "images", + layoutAttributes: attributes$p, + supplyLayoutDefaults: defaults$c, + includeBasePlot: include_components("images"), + draw: draw$7, + convertCoords: convert_coords +}; +var constants$u = { + // layout attribute name + name: "updatemenus", + // class names + containerClassName: "updatemenu-container", + headerGroupClassName: "updatemenu-header-group", + headerClassName: "updatemenu-header", + headerArrowClassName: "updatemenu-header-arrow", + dropdownButtonGroupClassName: "updatemenu-dropdown-button-group", + dropdownButtonClassName: "updatemenu-dropdown-button", + buttonClassName: "updatemenu-button", + itemRectClassName: "updatemenu-item-rect", + itemTextClassName: "updatemenu-item-text", + // DOM attribute name in button group keeping track + // of active update menu + menuIndexAttrName: "updatemenu-active-index", + // id root pass to Plots.autoMargin + autoMarginIdRoot: "updatemenu-", + // options when 'active: -1' + blankHeaderOpts: { label: " " }, + // min item width / height + minWidth: 30, + minHeight: 30, + // padding around item text + textPadX: 24, + arrowPadX: 16, + // item rect radii + rx: 2, + ry: 2, + // item text x offset off left edge + textOffsetX: 12, + // item text y offset (w.r.t. middle) + textOffsetY: 3, + // arrow offset off right edge + arrowOffsetX: 4, + // gap between header and buttons + gapButtonHeader: 5, + // gap between between buttons + gapButton: 2, + // color given to active buttons + activeColor: "#F4FAFF", + // color given to hovered buttons + hoverColor: "#F4FAFF", + // symbol for menu open arrow + arrowSymbol: { + left: "◄", + right: "►", + up: "▲", + down: "▼" + } +}; +var fontAttrs$6 = font_attributes; +var colorAttrs$2 = attributes$N; +var extendFlat$a = extend$5.extendFlat; +var overrideAll$3 = edit_types.overrideAll; +var padAttrs$1 = pad_attributes; +var templatedArray$2 = plot_template.templatedArray; +var buttonsAttrs = templatedArray$2("button", { + visible: { + valType: "boolean", + description: "Determines whether or not this button is visible." + }, + method: { + valType: "enumerated", + values: ["restyle", "relayout", "animate", "update", "skip"], + dflt: "restyle", + description: [ + "Sets the Plotly method to be called on click.", + "If the `skip` method is used, the API updatemenu will function as normal", + "but will perform no API calls and will not bind automatically to state", + "updates. This may be used to create a component interface and attach to", + "updatemenu events manually via JavaScript." + ].join(" ") + }, + args: { + valType: "info_array", + freeLength: true, + items: [ + { valType: "any" }, + { valType: "any" }, + { valType: "any" } + ], + description: [ + "Sets the arguments values to be passed to the Plotly", + "method set in `method` on click." + ].join(" ") + }, + args2: { + valType: "info_array", + freeLength: true, + items: [ + { valType: "any" }, + { valType: "any" }, + { valType: "any" } + ], + description: [ + "Sets a 2nd set of `args`,", + "these arguments values are passed to the Plotly", + "method set in `method` when clicking this button while in the active state.", + "Use this to create toggle buttons." + ].join(" ") + }, + label: { + valType: "string", + dflt: "", + description: "Sets the text label to appear on the button." + }, + execute: { + valType: "boolean", + dflt: true, + description: [ + "When true, the API method is executed. When false, all other behaviors are the same", + "and command execution is skipped. This may be useful when hooking into, for example,", + "the `plotly_buttonclicked` method and executing the API command manually without losing", + "the benefit of the updatemenu automatically binding to the state of the plot through the", + "specification of `method` and `args`." + ].join(" ") + } +}); +var attributes$n = overrideAll$3(templatedArray$2("updatemenu", { + _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], + visible: { + valType: "boolean", + description: [ + "Determines whether or not the update menu is visible." + ].join(" ") + }, + type: { + valType: "enumerated", + values: ["dropdown", "buttons"], + dflt: "dropdown", + description: [ + "Determines whether the buttons are accessible via a dropdown menu", + "or whether the buttons are stacked horizontally or vertically" + ].join(" ") + }, + direction: { + valType: "enumerated", + values: ["left", "right", "up", "down"], + dflt: "down", + description: [ + "Determines the direction in which the buttons are laid out, whether", + "in a dropdown menu or a row/column of buttons. For `left` and `up`,", + "the buttons will still appear in left-to-right or top-to-bottom order", + "respectively." + ].join(" ") + }, + active: { + valType: "integer", + min: -1, + dflt: 0, + description: [ + "Determines which button (by index starting from 0) is", + "considered active." + ].join(" ") + }, + showactive: { + valType: "boolean", + dflt: true, + description: "Highlights active dropdown item or active button if true." + }, + buttons: buttonsAttrs, + x: { + valType: "number", + min: -2, + max: 3, + dflt: -0.05, + description: "Sets the x position (in normalized coordinates) of the update menu." + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "right", + description: [ + "Sets the update menu's horizontal position anchor.", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the range selector." + ].join(" ") + }, + y: { + valType: "number", + min: -2, + max: 3, + dflt: 1, + description: "Sets the y position (in normalized coordinates) of the update menu." + }, + yanchor: { + valType: "enumerated", + values: ["auto", "top", "middle", "bottom"], + dflt: "top", + description: [ + "Sets the update menu's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the range selector." + ].join(" ") + }, + pad: extendFlat$a(padAttrs$1({ editType: "arraydraw" }), { + description: "Sets the padding around the buttons or dropdown menu." + }), + font: fontAttrs$6({ + description: "Sets the font of the update menu button text." + }), + bgcolor: { + valType: "color", + description: "Sets the background color of the update menu buttons." + }, + bordercolor: { + valType: "color", + dflt: colorAttrs$2.borderLine, + description: "Sets the color of the border enclosing the update menu." + }, + borderwidth: { + valType: "number", + min: 0, + dflt: 1, + editType: "arraydraw", + description: "Sets the width (in px) of the border enclosing the update menu." + } +}), "arraydraw", "from-root"); +var Lib$I = libExports; +var handleArrayContainerDefaults$2 = array_container_defaults; +var attributes$m = attributes$n; +var constants$t = constants$u; +var name$2 = constants$t.name; +var buttonAttrs$1 = attributes$m.buttons; +var defaults$b = function updateMenusDefaults(layoutIn, layoutOut) { + var opts = { + name: name$2, + handleItemDefaults: menuDefaults + }; + handleArrayContainerDefaults$2(layoutIn, layoutOut, opts); +}; +function menuDefaults(menuIn, menuOut, layoutOut) { + function coerce2(attr, dflt) { + return Lib$I.coerce(menuIn, menuOut, attributes$m, attr, dflt); + } + var buttons2 = handleArrayContainerDefaults$2(menuIn, menuOut, { + name: "buttons", + handleItemDefaults: buttonDefaults$1 + }); + var visible = coerce2("visible", buttons2.length > 0); + if (!visible) return; + coerce2("active"); + coerce2("direction"); + coerce2("type"); + coerce2("showactive"); + coerce2("x"); + coerce2("y"); + Lib$I.noneOrAll(menuIn, menuOut, ["x", "y"]); + coerce2("xanchor"); + coerce2("yanchor"); + coerce2("pad.t"); + coerce2("pad.r"); + coerce2("pad.b"); + coerce2("pad.l"); + Lib$I.coerceFont(coerce2, "font", layoutOut.font); + coerce2("bgcolor", layoutOut.paper_bgcolor); + coerce2("bordercolor"); + coerce2("borderwidth"); +} +function buttonDefaults$1(buttonIn, buttonOut) { + function coerce2(attr, dflt) { + return Lib$I.coerce(buttonIn, buttonOut, buttonAttrs$1, attr, dflt); + } + var visible = coerce2( + "visible", + buttonIn.method === "skip" || Array.isArray(buttonIn.args) + ); + if (visible) { + coerce2("method"); + coerce2("args"); + coerce2("args2"); + coerce2("label"); + coerce2("execute"); + } +} +var scrollbox = ScrollBox$1; +var d3$h = d3Exports; +var Color$m = colorExports; +var Drawing$c = drawingExports; +var Lib$H = libExports; +function ScrollBox$1(gd, container, id) { + this.gd = gd; + this.container = container; + this.id = id; + this.position = null; + this.translateX = null; + this.translateY = null; + this.hbar = null; + this.vbar = null; + this.bg = this.container.selectAll("rect.scrollbox-bg").data([0]); + this.bg.exit().on(".drag", null).on("wheel", null).remove(); + this.bg.enter().append("rect").classed("scrollbox-bg", true).style("pointer-events", "all").attr({ + opacity: 0, + x: 0, + y: 0, + width: 0, + height: 0 + }); +} +ScrollBox$1.barWidth = 2; +ScrollBox$1.barLength = 20; +ScrollBox$1.barRadius = 2; +ScrollBox$1.barPad = 1; +ScrollBox$1.barColor = "#808BA4"; +ScrollBox$1.prototype.enable = function enable(position, translateX, translateY) { + var fullLayout = this.gd._fullLayout; + var fullWidth = fullLayout.width; + var fullHeight = fullLayout.height; + this.position = position; + var l = this.position.l; + var w = this.position.w; + var t = this.position.t; + var h = this.position.h; + var direction = this.position.direction; + var isDown = direction === "down"; + var isLeft = direction === "left"; + var isRight = direction === "right"; + var isUp = direction === "up"; + var boxW = w; + var boxH = h; + var boxL, boxR; + var boxT, boxB; + if (!isDown && !isLeft && !isRight && !isUp) { + this.position.direction = "down"; + isDown = true; + } + var isVertical2 = isDown || isUp; + if (isVertical2) { + boxL = l; + boxR = boxL + boxW; + if (isDown) { + boxT = t; + boxB = Math.min(boxT + boxH, fullHeight); + boxH = boxB - boxT; + } else { + boxB = t + boxH; + boxT = Math.max(boxB - boxH, 0); + boxH = boxB - boxT; + } + } else { + boxT = t; + boxB = boxT + boxH; + if (isLeft) { + boxR = l + boxW; + boxL = Math.max(boxR - boxW, 0); + boxW = boxR - boxL; + } else { + boxL = l; + boxR = Math.min(boxL + boxW, fullWidth); + boxW = boxR - boxL; + } + } + this._box = { + l: boxL, + t: boxT, + w: boxW, + h: boxH + }; + var needsHorizontalScrollBar = w > boxW; + var hbarW = ScrollBox$1.barLength + 2 * ScrollBox$1.barPad; + var hbarH = ScrollBox$1.barWidth + 2 * ScrollBox$1.barPad; + var hbarL = l; + var hbarT = t + h; + if (hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; + var hbar = this.container.selectAll("rect.scrollbar-horizontal").data( + needsHorizontalScrollBar ? [0] : [] + ); + hbar.exit().on(".drag", null).remove(); + hbar.enter().append("rect").classed("scrollbar-horizontal", true).call(Color$m.fill, ScrollBox$1.barColor); + if (needsHorizontalScrollBar) { + this.hbar = hbar.attr({ + rx: ScrollBox$1.barRadius, + ry: ScrollBox$1.barRadius, + x: hbarL, + y: hbarT, + width: hbarW, + height: hbarH + }); + this._hbarXMin = hbarL + hbarW / 2; + this._hbarTranslateMax = boxW - hbarW; + } else { + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } + var needsVerticalScrollBar = h > boxH; + var vbarW = ScrollBox$1.barWidth + 2 * ScrollBox$1.barPad; + var vbarH = ScrollBox$1.barLength + 2 * ScrollBox$1.barPad; + var vbarL = l + w; + var vbarT = t; + if (vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; + var vbar = this.container.selectAll("rect.scrollbar-vertical").data( + needsVerticalScrollBar ? [0] : [] + ); + vbar.exit().on(".drag", null).remove(); + vbar.enter().append("rect").classed("scrollbar-vertical", true).call(Color$m.fill, ScrollBox$1.barColor); + if (needsVerticalScrollBar) { + this.vbar = vbar.attr({ + rx: ScrollBox$1.barRadius, + ry: ScrollBox$1.barRadius, + x: vbarL, + y: vbarT, + width: vbarW, + height: vbarH + }); + this._vbarYMin = vbarT + vbarH / 2; + this._vbarTranslateMax = boxH - vbarH; + } else { + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } + var clipId = this.id; + var clipL = boxL - 0.5; + var clipR = needsVerticalScrollBar ? boxR + vbarW + 0.5 : boxR + 0.5; + var clipT = boxT - 0.5; + var clipB = needsHorizontalScrollBar ? boxB + hbarH + 0.5 : boxB + 0.5; + var clipPath = fullLayout._topdefs.selectAll("#" + clipId).data(needsHorizontalScrollBar || needsVerticalScrollBar ? [0] : []); + clipPath.exit().remove(); + clipPath.enter().append("clipPath").attr("id", clipId).append("rect"); + if (needsHorizontalScrollBar || needsVerticalScrollBar) { + this._clipRect = clipPath.select("rect").attr({ + x: Math.floor(clipL), + y: Math.floor(clipT), + width: Math.ceil(clipR) - Math.floor(clipL), + height: Math.ceil(clipB) - Math.floor(clipT) + }); + this.container.call(Drawing$c.setClipUrl, clipId, this.gd); + this.bg.attr({ + x: l, + y: t, + width: w, + height: h + }); + } else { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container.on("wheel", null).on(".drag", null).call(Drawing$c.setClipUrl, null); + delete this._clipRect; + } + if (needsHorizontalScrollBar || needsVerticalScrollBar) { + var onBoxDrag = d3$h.behavior.drag().on("dragstart", function() { + d3$h.event.sourceEvent.preventDefault(); + }).on("drag", this._onBoxDrag.bind(this)); + this.container.on("wheel", null).on("wheel", this._onBoxWheel.bind(this)).on(".drag", null).call(onBoxDrag); + var onBarDrag = d3$h.behavior.drag().on("dragstart", function() { + d3$h.event.sourceEvent.preventDefault(); + d3$h.event.sourceEvent.stopPropagation(); + }).on("drag", this._onBarDrag.bind(this)); + if (needsHorizontalScrollBar) { + this.hbar.on(".drag", null).call(onBarDrag); + } + if (needsVerticalScrollBar) { + this.vbar.on(".drag", null).call(onBarDrag); + } + } + this.setTranslate(translateX, translateY); +}; +ScrollBox$1.prototype.disable = function disable() { + if (this.hbar || this.vbar) { + this.bg.attr({ + width: 0, + height: 0 + }); + this.container.on("wheel", null).on(".drag", null).call(Drawing$c.setClipUrl, null); + delete this._clipRect; + } + if (this.hbar) { + this.hbar.on(".drag", null); + this.hbar.remove(); + delete this.hbar; + delete this._hbarXMin; + delete this._hbarTranslateMax; + } + if (this.vbar) { + this.vbar.on(".drag", null); + this.vbar.remove(); + delete this.vbar; + delete this._vbarYMin; + delete this._vbarTranslateMax; + } +}; +ScrollBox$1.prototype._onBoxDrag = function _onBoxDrag() { + var translateX = this.translateX; + var translateY = this.translateY; + if (this.hbar) { + translateX -= d3$h.event.dx; + } + if (this.vbar) { + translateY -= d3$h.event.dy; + } + this.setTranslate(translateX, translateY); +}; +ScrollBox$1.prototype._onBoxWheel = function _onBoxWheel() { + var translateX = this.translateX; + var translateY = this.translateY; + if (this.hbar) { + translateX += d3$h.event.deltaY; + } + if (this.vbar) { + translateY += d3$h.event.deltaY; + } + this.setTranslate(translateX, translateY); +}; +ScrollBox$1.prototype._onBarDrag = function _onBarDrag() { + var translateX = this.translateX; + var translateY = this.translateY; + if (this.hbar) { + var xMin = translateX + this._hbarXMin; + var xMax = xMin + this._hbarTranslateMax; + var x = Lib$H.constrain(d3$h.event.x, xMin, xMax); + var xf = (x - xMin) / (xMax - xMin); + var translateXMax = this.position.w - this._box.w; + translateX = xf * translateXMax; + } + if (this.vbar) { + var yMin = translateY + this._vbarYMin; + var yMax = yMin + this._vbarTranslateMax; + var y = Lib$H.constrain(d3$h.event.y, yMin, yMax); + var yf = (y - yMin) / (yMax - yMin); + var translateYMax = this.position.h - this._box.h; + translateY = yf * translateYMax; + } + this.setTranslate(translateX, translateY); +}; +ScrollBox$1.prototype.setTranslate = function setTranslate(translateX, translateY) { + var translateXMax = this.position.w - this._box.w; + var translateYMax = this.position.h - this._box.h; + translateX = Lib$H.constrain(translateX || 0, 0, translateXMax); + translateY = Lib$H.constrain(translateY || 0, 0, translateYMax); + this.translateX = translateX; + this.translateY = translateY; + this.container.call( + Drawing$c.setTranslate, + this._box.l - this.position.l - translateX, + this._box.t - this.position.t - translateY + ); + if (this._clipRect) { + this._clipRect.attr({ + x: Math.floor(this.position.l + translateX - 0.5), + y: Math.floor(this.position.t + translateY - 0.5) + }); + } + if (this.hbar) { + var xf = translateX / translateXMax; + this.hbar.call( + Drawing$c.setTranslate, + translateX + xf * this._hbarTranslateMax, + translateY + ); + } + if (this.vbar) { + var yf = translateY / translateYMax; + this.vbar.call( + Drawing$c.setTranslate, + translateX, + translateY + yf * this._vbarTranslateMax + ); + } +}; +var d3$g = d3Exports; +var Plots$4 = plotsExports; +var Color$l = colorExports; +var Drawing$b = drawingExports; +var Lib$G = libExports; +var svgTextUtils$8 = svg_text_utils; +var arrayEditor$1 = plot_template.arrayEditor; +var LINE_SPACING$4 = alignment$1.LINE_SPACING; +var constants$s = constants$u; +var ScrollBox = scrollbox; +var draw$6 = function draw4(gd) { + var fullLayout = gd._fullLayout; + var menuData = Lib$G.filterVisible(fullLayout[constants$s.name]); + function clearAutoMargin(menuOpts2) { + Plots$4.autoMargin(gd, autoMarginId$1(menuOpts2)); + } + var menus = fullLayout._menulayer.selectAll("g." + constants$s.containerClassName).data(menuData.length > 0 ? [0] : []); + menus.enter().append("g").classed(constants$s.containerClassName, true).style("cursor", "pointer"); + menus.exit().each(function() { + d3$g.select(this).selectAll("g." + constants$s.headerGroupClassName).each(clearAutoMargin); + }).remove(); + if (menuData.length === 0) return; + var headerGroups = menus.selectAll("g." + constants$s.headerGroupClassName).data(menuData, keyFunction$1); + headerGroups.enter().append("g").classed(constants$s.headerGroupClassName, true); + var gButton = Lib$G.ensureSingle(menus, "g", constants$s.dropdownButtonGroupClassName, function(s) { + s.style("pointer-events", "all"); + }); + for (var i = 0; i < menuData.length; i++) { + var menuOpts = menuData[i]; + findDimensions$1(gd, menuOpts); + } + var scrollBoxId = "updatemenus" + fullLayout._uid; + var scrollBox = new ScrollBox(gd, gButton, scrollBoxId); + if (headerGroups.enter().size()) { + gButton.node().parentNode.appendChild(gButton.node()); + gButton.call(removeAllButtons); + } + headerGroups.exit().each(function(menuOpts2) { + gButton.call(removeAllButtons); + clearAutoMargin(menuOpts2); + }).remove(); + headerGroups.each(function(menuOpts2) { + var gHeader = d3$g.select(this); + var _gButton = menuOpts2.type === "dropdown" ? gButton : null; + Plots$4.manageCommandObserver(gd, menuOpts2, menuOpts2.buttons, function(data) { + setActive$1(gd, menuOpts2, menuOpts2.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); + }); + if (menuOpts2.type === "dropdown") { + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts2); + if (isActive$1(gButton, menuOpts2)) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts2); + } + } else { + drawButtons(gd, gHeader, null, null, menuOpts2); + } + }); +}; +function keyFunction$1(menuOpts) { + return menuOpts._index; +} +function isFolded(gButton) { + return +gButton.attr(constants$s.menuIndexAttrName) === -1; +} +function isActive$1(gButton, menuOpts) { + return +gButton.attr(constants$s.menuIndexAttrName) === menuOpts._index; +} +function setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { + menuOpts.active = buttonIndex; + arrayEditor$1(gd.layout, constants$s.name, menuOpts).applyUpdate("active", buttonIndex); + if (menuOpts.type === "buttons") { + drawButtons(gd, gHeader, null, null, menuOpts); + } else if (menuOpts.type === "dropdown") { + gButton.attr(constants$s.menuIndexAttrName, "-1"); + drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); + if (!isSilentUpdate) { + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + } + } +} +function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { + var header = Lib$G.ensureSingle(gHeader, "g", constants$s.headerClassName, function(s) { + s.style("pointer-events", "all"); + }); + var dims = menuOpts._dims; + var active = menuOpts.active; + var headerOpts = menuOpts.buttons[active] || constants$s.blankHeaderOpts; + var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; + var positionOverrides = { + width: dims.headerWidth, + height: dims.headerHeight + }; + header.call(drawItem, menuOpts, headerOpts, gd).call(setItemPosition, menuOpts, posOpts, positionOverrides); + var arrow = Lib$G.ensureSingle(gHeader, "text", constants$s.headerArrowClassName, function(s) { + s.attr("text-anchor", "end").call(Drawing$b.font, menuOpts.font).text(constants$s.arrowSymbol[menuOpts.direction]); + }); + arrow.attr({ + x: dims.headerWidth - constants$s.arrowOffsetX + menuOpts.pad.l, + y: dims.headerHeight / 2 + constants$s.textOffsetY + menuOpts.pad.t + }); + header.on("click", function() { + gButton.call( + removeAllButtons, + String(isActive$1(gButton, menuOpts) ? -1 : menuOpts._index) + ); + drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); + }); + header.on("mouseover", function() { + header.call(styleOnMouseOver); + }); + header.on("mouseout", function() { + header.call(styleOnMouseOut, menuOpts); + }); + Drawing$b.setTranslate(gHeader, dims.lx, dims.ly); +} +function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { + if (!gButton) { + gButton = gHeader; + gButton.attr("pointer-events", "all"); + } + var buttonData = !isFolded(gButton) || menuOpts.type === "buttons" ? menuOpts.buttons : []; + var klass = menuOpts.type === "dropdown" ? constants$s.dropdownButtonClassName : constants$s.buttonClassName; + var buttons2 = gButton.selectAll("g." + klass).data(Lib$G.filterVisible(buttonData)); + var enter = buttons2.enter().append("g").classed(klass, true); + var exit = buttons2.exit(); + if (menuOpts.type === "dropdown") { + enter.attr("opacity", "0").transition().attr("opacity", "1"); + exit.transition().attr("opacity", "0").remove(); + } else { + exit.remove(); + } + var x0 = 0; + var y0 = 0; + var dims = menuOpts._dims; + var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; + if (menuOpts.type === "dropdown") { + if (isVertical2) { + y0 = dims.headerHeight + constants$s.gapButtonHeader; + } else { + x0 = dims.headerWidth + constants$s.gapButtonHeader; + } + } + if (menuOpts.type === "dropdown" && menuOpts.direction === "up") { + y0 = -constants$s.gapButtonHeader + constants$s.gapButton - dims.openHeight; + } + if (menuOpts.type === "dropdown" && menuOpts.direction === "left") { + x0 = -constants$s.gapButtonHeader + constants$s.gapButton - dims.openWidth; + } + var posOpts = { + x: dims.lx + x0 + menuOpts.pad.l, + y: dims.ly + y0 + menuOpts.pad.t, + yPad: constants$s.gapButton, + xPad: constants$s.gapButton, + index: 0 + }; + var scrollBoxPosition = { + l: posOpts.x + menuOpts.borderwidth, + t: posOpts.y + menuOpts.borderwidth + }; + buttons2.each(function(buttonOpts, buttonIndex) { + var button = d3$g.select(this); + button.call(drawItem, menuOpts, buttonOpts, gd).call(setItemPosition, menuOpts, posOpts); + button.on("click", function() { + if (d3$g.event.defaultPrevented) return; + if (buttonOpts.execute) { + if (buttonOpts.args2 && menuOpts.active === buttonIndex) { + setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, -1); + Plots$4.executeAPICommand(gd, buttonOpts.method, buttonOpts.args2); + } else { + setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); + Plots$4.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); + } + } + gd.emit("plotly_buttonclicked", { menu: menuOpts, button: buttonOpts, active: menuOpts.active }); + }); + button.on("mouseover", function() { + button.call(styleOnMouseOver); + }); + button.on("mouseout", function() { + button.call(styleOnMouseOut, menuOpts); + buttons2.call(styleButtons, menuOpts); + }); + }); + buttons2.call(styleButtons, menuOpts); + if (isVertical2) { + scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); + scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; + } else { + scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; + scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); + } + scrollBoxPosition.direction = menuOpts.direction; + if (scrollBox) { + if (buttons2.size()) { + drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); + } else { + hideScrollBox(scrollBox); + } + } +} +function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { + var direction = menuOpts.direction; + var isVertical2 = direction === "up" || direction === "down"; + var dims = menuOpts._dims; + var active = menuOpts.active; + var translateX, translateY; + var i; + if (isVertical2) { + translateY = 0; + for (i = 0; i < active; i++) { + translateY += dims.heights[i] + constants$s.gapButton; + } + } else { + translateX = 0; + for (i = 0; i < active; i++) { + translateX += dims.widths[i] + constants$s.gapButton; + } + } + scrollBox.enable(position, translateX, translateY); + if (scrollBox.hbar) { + scrollBox.hbar.attr("opacity", "0").transition().attr("opacity", "1"); + } + if (scrollBox.vbar) { + scrollBox.vbar.attr("opacity", "0").transition().attr("opacity", "1"); + } +} +function hideScrollBox(scrollBox) { + var hasHBar = !!scrollBox.hbar; + var hasVBar = !!scrollBox.vbar; + if (hasHBar) { + scrollBox.hbar.transition().attr("opacity", "0").each("end", function() { + hasHBar = false; + if (!hasVBar) scrollBox.disable(); + }); + } + if (hasVBar) { + scrollBox.vbar.transition().attr("opacity", "0").each("end", function() { + hasVBar = false; + if (!hasHBar) scrollBox.disable(); + }); + } +} +function drawItem(item, menuOpts, itemOpts, gd) { + item.call(drawItemRect, menuOpts).call(drawItemText, menuOpts, itemOpts, gd); +} +function drawItemRect(item, menuOpts) { + var rect2 = Lib$G.ensureSingle(item, "rect", constants$s.itemRectClassName, function(s) { + s.attr({ + rx: constants$s.rx, + ry: constants$s.ry, + "shape-rendering": "crispEdges" + }); + }); + rect2.call(Color$l.stroke, menuOpts.bordercolor).call(Color$l.fill, menuOpts.bgcolor).style("stroke-width", menuOpts.borderwidth + "px"); +} +function drawItemText(item, menuOpts, itemOpts, gd) { + var text = Lib$G.ensureSingle(item, "text", constants$s.itemTextClassName, function(s) { + s.attr({ + "text-anchor": "start", + "data-notex": 1 + }); + }); + var tx = itemOpts.label; + var _meta = gd._fullLayout._meta; + if (_meta) tx = Lib$G.templateString(tx, _meta); + text.call(Drawing$b.font, menuOpts.font).text(tx).call(svgTextUtils$8.convertToTspans, gd); +} +function styleButtons(buttons2, menuOpts) { + var active = menuOpts.active; + buttons2.each(function(buttonOpts, i) { + var button = d3$g.select(this); + if (i === active && menuOpts.showactive) { + button.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, constants$s.activeColor); + } + }); +} +function styleOnMouseOver(item) { + item.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, constants$s.hoverColor); +} +function styleOnMouseOut(item, menuOpts) { + item.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, menuOpts.bgcolor); +} +function findDimensions$1(gd, menuOpts) { + var dims = menuOpts._dims = { + width1: 0, + height1: 0, + heights: [], + widths: [], + totalWidth: 0, + totalHeight: 0, + openWidth: 0, + openHeight: 0, + lx: 0, + ly: 0 + }; + var fakeButtons = Drawing$b.tester.selectAll("g." + constants$s.dropdownButtonClassName).data(Lib$G.filterVisible(menuOpts.buttons)); + fakeButtons.enter().append("g").classed(constants$s.dropdownButtonClassName, true); + var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; + fakeButtons.each(function(buttonOpts, i) { + var button = d3$g.select(this); + button.call(drawItem, menuOpts, buttonOpts, gd); + var text = button.select("." + constants$s.itemTextClassName); + var tWidth = text.node() && Drawing$b.bBox(text.node()).width; + var wEff = Math.max(tWidth + constants$s.textPadX, constants$s.minWidth); + var tHeight = menuOpts.font.size * LINE_SPACING$4; + var tLines = svgTextUtils$8.lineCount(text); + var hEff = Math.max(tHeight * tLines, constants$s.minHeight) + constants$s.textOffsetY; + hEff = Math.ceil(hEff); + wEff = Math.ceil(wEff); + dims.widths[i] = wEff; + dims.heights[i] = hEff; + dims.height1 = Math.max(dims.height1, hEff); + dims.width1 = Math.max(dims.width1, wEff); + if (isVertical2) { + dims.totalWidth = Math.max(dims.totalWidth, wEff); + dims.openWidth = dims.totalWidth; + dims.totalHeight += hEff + constants$s.gapButton; + dims.openHeight += hEff + constants$s.gapButton; + } else { + dims.totalWidth += wEff + constants$s.gapButton; + dims.openWidth += wEff + constants$s.gapButton; + dims.totalHeight = Math.max(dims.totalHeight, hEff); + dims.openHeight = dims.totalHeight; + } + }); + if (isVertical2) { + dims.totalHeight -= constants$s.gapButton; + } else { + dims.totalWidth -= constants$s.gapButton; + } + dims.headerWidth = dims.width1 + constants$s.arrowPadX; + dims.headerHeight = dims.height1; + if (menuOpts.type === "dropdown") { + if (isVertical2) { + dims.width1 += constants$s.arrowPadX; + dims.totalHeight = dims.height1; + } else { + dims.totalWidth = dims.width1; + } + dims.totalWidth += constants$s.arrowPadX; + } + fakeButtons.remove(); + var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; + var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * menuOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); + var xanchor = "left"; + if (Lib$G.isRightAnchor(menuOpts)) { + dims.lx -= paddedWidth; + xanchor = "right"; + } + if (Lib$G.isCenterAnchor(menuOpts)) { + dims.lx -= paddedWidth / 2; + xanchor = "center"; + } + var yanchor = "top"; + if (Lib$G.isBottomAnchor(menuOpts)) { + dims.ly -= paddedHeight; + yanchor = "bottom"; + } + if (Lib$G.isMiddleAnchor(menuOpts)) { + dims.ly -= paddedHeight / 2; + yanchor = "middle"; + } + dims.totalWidth = Math.ceil(dims.totalWidth); + dims.totalHeight = Math.ceil(dims.totalHeight); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); + Plots$4.autoMargin(gd, autoMarginId$1(menuOpts), { + x: menuOpts.x, + y: menuOpts.y, + l: paddedWidth * ({ right: 1, center: 0.5 }[xanchor] || 0), + r: paddedWidth * ({ left: 1, center: 0.5 }[xanchor] || 0), + b: paddedHeight * ({ top: 1, middle: 0.5 }[yanchor] || 0), + t: paddedHeight * ({ bottom: 1, middle: 0.5 }[yanchor] || 0) + }); +} +function autoMarginId$1(menuOpts) { + return constants$s.autoMarginIdRoot + menuOpts._index; +} +function setItemPosition(item, menuOpts, posOpts, overrideOpts) { + overrideOpts = overrideOpts || {}; + var rect2 = item.select("." + constants$s.itemRectClassName); + var text = item.select("." + constants$s.itemTextClassName); + var borderWidth = menuOpts.borderwidth; + var index2 = posOpts.index; + var dims = menuOpts._dims; + Drawing$b.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); + var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; + var finalHeight = overrideOpts.height || (isVertical2 ? dims.heights[index2] : dims.height1); + rect2.attr({ + x: 0, + y: 0, + width: overrideOpts.width || (isVertical2 ? dims.width1 : dims.widths[index2]), + height: finalHeight + }); + var tHeight = menuOpts.font.size * LINE_SPACING$4; + var tLines = svgTextUtils$8.lineCount(text); + var spanOffset = (tLines - 1) * tHeight / 2; + svgTextUtils$8.positionText( + text, + constants$s.textOffsetX, + finalHeight / 2 - spanOffset + constants$s.textOffsetY + ); + if (isVertical2) { + posOpts.y += dims.heights[index2] + posOpts.yPad; + } else { + posOpts.x += dims.widths[index2] + posOpts.xPad; + } + posOpts.index++; +} +function removeAllButtons(gButton, newMenuIndexAttr) { + gButton.attr(constants$s.menuIndexAttrName, newMenuIndexAttr || "-1").selectAll("g." + constants$s.dropdownButtonClassName).remove(); +} +var constants$r = constants$u; +var updatemenus = { + moduleType: "component", + name: constants$r.name, + layoutAttributes: attributes$n, + supplyLayoutDefaults: defaults$b, + draw: draw$6 +}; +var constants$q = { + // layout attribute name + name: "sliders", + // class names + containerClassName: "slider-container", + groupClassName: "slider-group", + railRectClass: "slider-rail-rect", + railTouchRectClass: "slider-rail-touch-rect", + gripRectClass: "slider-grip-rect", + tickRectClass: "slider-tick-rect", + labelsClass: "slider-labels", + labelGroupClass: "slider-label-group", + labelClass: "slider-label", + // id root pass to Plots.autoMargin + autoMarginIdRoot: "slider-", + railRadius: 2, + railWidth: 5, + railBorderWidth: 1, + railBorderColor: "#bec8d9", + railBgColor: "#f8fafc", + // The distance of the rail from the edge of the touchable area + // Slightly less than the step inset because of the curved edges + // of the rail + railInset: 8, + // The distance from the extremal tick marks to the edge of the + // touchable area. This is basically the same as the grip radius, + // but for other styles it wouldn't really need to be. + stepInset: 10, + gripRadius: 10, + gripWidth: 20, + gripHeight: 20, + gripBgActiveColor: "#dbdde0", + labelPadding: 8, + labelOffset: 0, + tickColor: "#333", + tickOffset: 25, + tickLength: 7, + minorTickOffset: 25, + minorTickLength: 4, + currentValueInset: 0 +}; +var fontAttrs$5 = font_attributes; +var padAttrs = pad_attributes; +var extendDeepAll = extend$5.extendDeepAll; +var overrideAll$2 = edit_types.overrideAll; +var animationAttrs = animation_attributes; +var templatedArray$1 = plot_template.templatedArray; +var constants$p = constants$q; +var stepsAttrs = templatedArray$1("step", { + visible: { + valType: "boolean", + dflt: true, + description: [ + "Determines whether or not this step is included in the slider." + ].join(" ") + }, + method: { + valType: "enumerated", + values: ["restyle", "relayout", "animate", "update", "skip"], + dflt: "restyle", + description: [ + "Sets the Plotly method to be called when the slider value is changed.", + "If the `skip` method is used, the API slider will function as normal", + "but will perform no API calls and will not bind automatically to state", + "updates. This may be used to create a component interface and attach to", + "slider events manually via JavaScript." + ].join(" ") + }, + args: { + valType: "info_array", + freeLength: true, + items: [ + { valType: "any" }, + { valType: "any" }, + { valType: "any" } + ], + description: [ + "Sets the arguments values to be passed to the Plotly", + "method set in `method` on slide." + ].join(" ") + }, + label: { + valType: "string", + description: "Sets the text label to appear on the slider" + }, + value: { + valType: "string", + description: [ + "Sets the value of the slider step, used to refer to the step programatically.", + "Defaults to the slider label if not provided." + ].join(" ") + }, + execute: { + valType: "boolean", + dflt: true, + description: [ + "When true, the API method is executed. When false, all other behaviors are the same", + "and command execution is skipped. This may be useful when hooking into, for example,", + "the `plotly_sliderchange` method and executing the API command manually without losing", + "the benefit of the slider automatically binding to the state of the plot through the", + "specification of `method` and `args`." + ].join(" ") + } +}); +var attributes$l = overrideAll$2(templatedArray$1("slider", { + visible: { + valType: "boolean", + dflt: true, + description: [ + "Determines whether or not the slider is visible." + ].join(" ") + }, + active: { + valType: "number", + min: 0, + dflt: 0, + description: [ + "Determines which button (by index starting from 0) is", + "considered active." + ].join(" ") + }, + steps: stepsAttrs, + lenmode: { + valType: "enumerated", + values: ["fraction", "pixels"], + dflt: "fraction", + description: [ + "Determines whether this slider length", + "is set in units of plot *fraction* or in *pixels.", + "Use `len` to set the value." + ].join(" ") + }, + len: { + valType: "number", + min: 0, + dflt: 1, + description: [ + "Sets the length of the slider", + "This measure excludes the padding of both ends.", + "That is, the slider's length is this length minus the", + "padding on both ends." + ].join(" ") + }, + x: { + valType: "number", + min: -2, + max: 3, + dflt: 0, + description: "Sets the x position (in normalized coordinates) of the slider." + }, + pad: extendDeepAll(padAttrs({ editType: "arraydraw" }), { + description: "Set the padding of the slider component along each side." + }, { t: { dflt: 20 } }), + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "left", + description: [ + "Sets the slider's horizontal position anchor.", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the range selector." + ].join(" ") + }, + y: { + valType: "number", + min: -2, + max: 3, + dflt: 0, + description: "Sets the y position (in normalized coordinates) of the slider." + }, + yanchor: { + valType: "enumerated", + values: ["auto", "top", "middle", "bottom"], + dflt: "top", + description: [ + "Sets the slider's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the range selector." + ].join(" ") + }, + transition: { + duration: { + valType: "number", + min: 0, + dflt: 150, + description: "Sets the duration of the slider transition" + }, + easing: { + valType: "enumerated", + values: animationAttrs.transition.easing.values, + dflt: "cubic-in-out", + description: "Sets the easing function of the slider transition" + } + }, + currentvalue: { + visible: { + valType: "boolean", + dflt: true, + description: [ + "Shows the currently-selected value above the slider." + ].join(" ") + }, + xanchor: { + valType: "enumerated", + values: ["left", "center", "right"], + dflt: "left", + description: [ + "The alignment of the value readout relative to the length of the slider." + ].join(" ") + }, + offset: { + valType: "number", + dflt: 10, + description: [ + "The amount of space, in pixels, between the current value label", + "and the slider." + ].join(" ") + }, + prefix: { + valType: "string", + description: "When currentvalue.visible is true, this sets the prefix of the label." + }, + suffix: { + valType: "string", + description: "When currentvalue.visible is true, this sets the suffix of the label." + }, + font: fontAttrs$5({ + description: "Sets the font of the current value label text." + }) + }, + font: fontAttrs$5({ + description: "Sets the font of the slider step labels." + }), + activebgcolor: { + valType: "color", + dflt: constants$p.gripBgActiveColor, + description: [ + "Sets the background color of the slider grip", + "while dragging." + ].join(" ") + }, + bgcolor: { + valType: "color", + dflt: constants$p.railBgColor, + description: "Sets the background color of the slider." + }, + bordercolor: { + valType: "color", + dflt: constants$p.railBorderColor, + description: "Sets the color of the border enclosing the slider." + }, + borderwidth: { + valType: "number", + min: 0, + dflt: constants$p.railBorderWidth, + description: "Sets the width (in px) of the border enclosing the slider." + }, + ticklen: { + valType: "number", + min: 0, + dflt: constants$p.tickLength, + description: "Sets the length in pixels of step tick marks" + }, + tickcolor: { + valType: "color", + dflt: constants$p.tickColor, + description: "Sets the color of the border enclosing the slider." + }, + tickwidth: { + valType: "number", + min: 0, + dflt: 1, + description: "Sets the tick width (in px)." + }, + minorticklen: { + valType: "number", + min: 0, + dflt: constants$p.minorTickLength, + description: "Sets the length in pixels of minor step tick marks" + } +}), "arraydraw", "from-root"); +var Lib$F = libExports; +var handleArrayContainerDefaults$1 = array_container_defaults; +var attributes$k = attributes$l; +var constants$o = constants$q; +var name$1 = constants$o.name; +var stepAttrs = attributes$k.steps; +var defaults$a = function slidersDefaults(layoutIn, layoutOut) { + handleArrayContainerDefaults$1(layoutIn, layoutOut, { + name: name$1, + handleItemDefaults: sliderDefaults + }); +}; +function sliderDefaults(sliderIn, sliderOut, layoutOut) { + function coerce2(attr, dflt) { + return Lib$F.coerce(sliderIn, sliderOut, attributes$k, attr, dflt); + } + var steps = handleArrayContainerDefaults$1(sliderIn, sliderOut, { + name: "steps", + handleItemDefaults: stepDefaults + }); + var stepCount = 0; + for (var i = 0; i < steps.length; i++) { + if (steps[i].visible) stepCount++; + } + var visible; + if (stepCount < 2) visible = sliderOut.visible = false; + else visible = coerce2("visible"); + if (!visible) return; + sliderOut._stepCount = stepCount; + var visSteps = sliderOut._visibleSteps = Lib$F.filterVisible(steps); + var active = coerce2("active"); + if (!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index; + coerce2("x"); + coerce2("y"); + Lib$F.noneOrAll(sliderIn, sliderOut, ["x", "y"]); + coerce2("xanchor"); + coerce2("yanchor"); + coerce2("len"); + coerce2("lenmode"); + coerce2("pad.t"); + coerce2("pad.r"); + coerce2("pad.b"); + coerce2("pad.l"); + Lib$F.coerceFont(coerce2, "font", layoutOut.font); + var currentValueIsVisible = coerce2("currentvalue.visible"); + if (currentValueIsVisible) { + coerce2("currentvalue.xanchor"); + coerce2("currentvalue.prefix"); + coerce2("currentvalue.suffix"); + coerce2("currentvalue.offset"); + Lib$F.coerceFont(coerce2, "currentvalue.font", sliderOut.font); + } + coerce2("transition.duration"); + coerce2("transition.easing"); + coerce2("bgcolor"); + coerce2("activebgcolor"); + coerce2("bordercolor"); + coerce2("borderwidth"); + coerce2("ticklen"); + coerce2("tickwidth"); + coerce2("tickcolor"); + coerce2("minorticklen"); +} +function stepDefaults(valueIn, valueOut) { + function coerce2(attr, dflt) { + return Lib$F.coerce(valueIn, valueOut, stepAttrs, attr, dflt); + } + var visible; + if (valueIn.method !== "skip" && !Array.isArray(valueIn.args)) { + visible = valueOut.visible = false; + } else visible = coerce2("visible"); + if (visible) { + coerce2("method"); + coerce2("args"); + var label = coerce2("label", "step-" + valueOut._index); + coerce2("value", label); + coerce2("execute"); + } +} +var d3$f = d3Exports; +var Plots$3 = plotsExports; +var Color$k = colorExports; +var Drawing$a = drawingExports; +var Lib$E = libExports; +var strTranslate$3 = Lib$E.strTranslate; +var svgTextUtils$7 = svg_text_utils; +var arrayEditor = plot_template.arrayEditor; +var constants$n = constants$q; +var alignmentConstants$2 = alignment$1; +var LINE_SPACING$3 = alignmentConstants$2.LINE_SPACING; +var FROM_TL$2 = alignmentConstants$2.FROM_TL; +var FROM_BR$2 = alignmentConstants$2.FROM_BR; +var draw$5 = function draw5(gd) { + var staticPlot = gd._context.staticPlot; + var fullLayout = gd._fullLayout; + var sliderData = makeSliderData(fullLayout, gd); + var sliders2 = fullLayout._infolayer.selectAll("g." + constants$n.containerClassName).data(sliderData.length > 0 ? [0] : []); + sliders2.enter().append("g").classed(constants$n.containerClassName, true).style("cursor", staticPlot ? null : "ew-resize"); + function clearSlider(sliderOpts2) { + if (sliderOpts2._commandObserver) { + sliderOpts2._commandObserver.remove(); + delete sliderOpts2._commandObserver; + } + Plots$3.autoMargin(gd, autoMarginId(sliderOpts2)); + } + sliders2.exit().each(function() { + d3$f.select(this).selectAll("g." + constants$n.groupClassName).each(clearSlider); + }).remove(); + if (sliderData.length === 0) return; + var sliderGroups = sliders2.selectAll("g." + constants$n.groupClassName).data(sliderData, keyFunction); + sliderGroups.enter().append("g").classed(constants$n.groupClassName, true); + sliderGroups.exit().each(clearSlider).remove(); + for (var i = 0; i < sliderData.length; i++) { + var sliderOpts = sliderData[i]; + findDimensions(gd, sliderOpts); + } + sliderGroups.each(function(sliderOpts2) { + var gSlider = d3$f.select(this); + computeLabelSteps(sliderOpts2); + Plots$3.manageCommandObserver(gd, sliderOpts2, sliderOpts2._visibleSteps, function(data) { + var opts = gSlider.data()[0]; + if (opts.active === data.index) return; + if (opts._dragging) return; + setActive(gd, gSlider, opts, data.index, false, true); + }); + drawSlider(gd, d3$f.select(this), sliderOpts2); + }); +}; +function autoMarginId(sliderOpts) { + return constants$n.autoMarginIdRoot + sliderOpts._index; +} +function makeSliderData(fullLayout, gd) { + var contOpts = fullLayout[constants$n.name]; + var sliderData = []; + for (var i = 0; i < contOpts.length; i++) { + var item = contOpts[i]; + if (!item.visible) continue; + item._gd = gd; + sliderData.push(item); + } + return sliderData; +} +function keyFunction(opts) { + return opts._index; +} +function findDimensions(gd, sliderOpts) { + var sliderLabels = Drawing$a.tester.selectAll("g." + constants$n.labelGroupClass).data(sliderOpts._visibleSteps); + sliderLabels.enter().append("g").classed(constants$n.labelGroupClass, true); + var maxLabelWidth = 0; + var labelHeight = 0; + sliderLabels.each(function(stepOpts) { + var labelGroup = d3$f.select(this); + var text = drawLabel2(labelGroup, { step: stepOpts }, sliderOpts); + var textNode = text.node(); + if (textNode) { + var bBox = Drawing$a.bBox(textNode); + labelHeight = Math.max(labelHeight, bBox.height); + maxLabelWidth = Math.max(maxLabelWidth, bBox.width); + } + }); + sliderLabels.remove(); + var dims = sliderOpts._dims = {}; + dims.inputAreaWidth = Math.max( + constants$n.railWidth, + constants$n.gripHeight + ); + var graphSize = gd._fullLayout._size; + dims.lx = graphSize.l + graphSize.w * sliderOpts.x; + dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); + if (sliderOpts.lenmode === "fraction") { + dims.outerLength = Math.round(graphSize.w * sliderOpts.len); + } else { + dims.outerLength = sliderOpts.len; + } + dims.inputAreaStart = 0; + dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); + var textableInputLength = dims.inputAreaLength - 2 * constants$n.stepInset; + var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1); + var computedSpacePerLabel = maxLabelWidth + constants$n.labelPadding; + dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); + dims.labelHeight = labelHeight; + dims.currentValueMaxWidth = 0; + dims.currentValueHeight = 0; + dims.currentValueTotalHeight = 0; + dims.currentValueMaxLines = 1; + if (sliderOpts.currentvalue.visible) { + var dummyGroup = Drawing$a.tester.append("g"); + sliderLabels.each(function(stepOpts) { + var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); + var curValSize = curValPrefix.node() && Drawing$a.bBox(curValPrefix.node()) || { width: 0, height: 0 }; + var lines = svgTextUtils$7.lineCount(curValPrefix); + dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); + dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); + dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); + }); + dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; + dummyGroup.remove(); + } + dims.height = dims.currentValueTotalHeight + constants$n.tickOffset + sliderOpts.ticklen + constants$n.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; + var xanchor = "left"; + if (Lib$E.isRightAnchor(sliderOpts)) { + dims.lx -= dims.outerLength; + xanchor = "right"; + } + if (Lib$E.isCenterAnchor(sliderOpts)) { + dims.lx -= dims.outerLength / 2; + xanchor = "center"; + } + var yanchor = "top"; + if (Lib$E.isBottomAnchor(sliderOpts)) { + dims.ly -= dims.height; + yanchor = "bottom"; + } + if (Lib$E.isMiddleAnchor(sliderOpts)) { + dims.ly -= dims.height / 2; + yanchor = "middle"; + } + dims.outerLength = Math.ceil(dims.outerLength); + dims.height = Math.ceil(dims.height); + dims.lx = Math.round(dims.lx); + dims.ly = Math.round(dims.ly); + var marginOpts = { + y: sliderOpts.y, + b: dims.height * FROM_BR$2[yanchor], + t: dims.height * FROM_TL$2[yanchor] + }; + if (sliderOpts.lenmode === "fraction") { + marginOpts.l = 0; + marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL$2[xanchor]; + marginOpts.r = 0; + marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR$2[xanchor]; + } else { + marginOpts.x = sliderOpts.x; + marginOpts.l = dims.outerLength * FROM_TL$2[xanchor]; + marginOpts.r = dims.outerLength * FROM_BR$2[xanchor]; + } + Plots$3.autoMargin(gd, autoMarginId(sliderOpts), marginOpts); +} +function drawSlider(gd, sliderGroup, sliderOpts) { + if (!(sliderOpts.steps[sliderOpts.active] || {}).visible) { + sliderOpts.active = sliderOpts._visibleSteps[0]._index; + } + sliderGroup.call(drawCurrentValue, sliderOpts).call(drawRail, sliderOpts).call(drawLabelGroup, sliderOpts).call(drawTicks, sliderOpts).call(drawTouchRect, gd, sliderOpts).call(drawGrip, gd, sliderOpts); + var dims = sliderOpts._dims; + Drawing$a.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); + sliderGroup.call(setGripPosition, sliderOpts, false); + sliderGroup.call(drawCurrentValue, sliderOpts); +} +function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { + if (!sliderOpts.currentvalue.visible) return; + var dims = sliderOpts._dims; + var x0, textAnchor; + switch (sliderOpts.currentvalue.xanchor) { + case "right": + x0 = dims.inputAreaLength - constants$n.currentValueInset - dims.currentValueMaxWidth; + textAnchor = "left"; + break; + case "center": + x0 = dims.inputAreaLength * 0.5; + textAnchor = "middle"; + break; + default: + x0 = constants$n.currentValueInset; + textAnchor = "left"; + } + var text = Lib$E.ensureSingle(sliderGroup, "text", constants$n.labelClass, function(s) { + s.attr({ + "text-anchor": textAnchor, + "data-notex": 1 + }); + }); + var str2 = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ""; + if (typeof valueOverride === "string") { + str2 += valueOverride; + } else { + var curVal = sliderOpts.steps[sliderOpts.active].label; + var _meta = sliderOpts._gd._fullLayout._meta; + if (_meta) curVal = Lib$E.templateString(curVal, _meta); + str2 += curVal; + } + if (sliderOpts.currentvalue.suffix) { + str2 += sliderOpts.currentvalue.suffix; + } + text.call(Drawing$a.font, sliderOpts.currentvalue.font).text(str2).call(svgTextUtils$7.convertToTspans, sliderOpts._gd); + var lines = svgTextUtils$7.lineCount(text); + var y0 = (dims.currentValueMaxLines + 1 - lines) * sliderOpts.currentvalue.font.size * LINE_SPACING$3; + svgTextUtils$7.positionText(text, x0, y0); + return text; +} +function drawGrip(sliderGroup, gd, sliderOpts) { + var grip = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.gripRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all"); + }); + grip.attr({ + width: constants$n.gripWidth, + height: constants$n.gripHeight, + rx: constants$n.gripRadius, + ry: constants$n.gripRadius + }).call(Color$k.stroke, sliderOpts.bordercolor).call(Color$k.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px"); +} +function drawLabel2(item, data, sliderOpts) { + var text = Lib$E.ensureSingle(item, "text", constants$n.labelClass, function(s) { + s.attr({ + "text-anchor": "middle", + "data-notex": 1 + }); + }); + var tx = data.step.label; + var _meta = sliderOpts._gd._fullLayout._meta; + if (_meta) tx = Lib$E.templateString(tx, _meta); + text.call(Drawing$a.font, sliderOpts.font).text(tx).call(svgTextUtils$7.convertToTspans, sliderOpts._gd); + return text; +} +function drawLabelGroup(sliderGroup, sliderOpts) { + var labels = Lib$E.ensureSingle(sliderGroup, "g", constants$n.labelsClass); + var dims = sliderOpts._dims; + var labelItems = labels.selectAll("g." + constants$n.labelGroupClass).data(dims.labelSteps); + labelItems.enter().append("g").classed(constants$n.labelGroupClass, true); + labelItems.exit().remove(); + labelItems.each(function(d) { + var item = d3$f.select(this); + item.call(drawLabel2, d, sliderOpts); + Drawing$a.setTranslate( + item, + normalizedValueToPosition(sliderOpts, d.fraction), + constants$n.tickOffset + sliderOpts.ticklen + // position is the baseline of the top line of text only, even + // if the label spans multiple lines + sliderOpts.font.size * LINE_SPACING$3 + constants$n.labelOffset + dims.currentValueTotalHeight + ); + }); +} +function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { + var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1)); + var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index; + if (quantizedIndex !== sliderOpts.active) { + setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition); + } +} +function setActive(gd, sliderGroup, sliderOpts, index2, doCallback, doTransition) { + var previousActive = sliderOpts.active; + sliderOpts.active = index2; + arrayEditor(gd.layout, constants$n.name, sliderOpts).applyUpdate("active", index2); + var step = sliderOpts.steps[sliderOpts.active]; + sliderGroup.call(setGripPosition, sliderOpts, doTransition); + sliderGroup.call(drawCurrentValue, sliderOpts); + gd.emit("plotly_sliderchange", { + slider: sliderOpts, + step: sliderOpts.steps[sliderOpts.active], + interaction: doCallback, + previousActive + }); + if (step && step.method && doCallback) { + if (sliderGroup._nextMethod) { + sliderGroup._nextMethod.step = step; + sliderGroup._nextMethod.doCallback = doCallback; + sliderGroup._nextMethod.doTransition = doTransition; + } else { + sliderGroup._nextMethod = { step, doCallback, doTransition }; + sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { + var _step = sliderGroup._nextMethod.step; + if (!_step.method) return; + if (_step.execute) { + Plots$3.executeAPICommand(gd, _step.method, _step.args); + } + sliderGroup._nextMethod = null; + sliderGroup._nextMethodRaf = null; + }); + } + } +} +function attachGripEvents(item, gd, sliderGroup) { + if (gd._context.staticPlot) return; + var node = sliderGroup.node(); + var $gd = d3$f.select(gd); + function getSliderOpts() { + return sliderGroup.data()[0]; + } + function mouseDownHandler() { + var sliderOpts = getSliderOpts(); + gd.emit("plotly_sliderstart", { slider: sliderOpts }); + var grip = sliderGroup.select("." + constants$n.gripRectClass); + d3$f.event.stopPropagation(); + d3$f.event.preventDefault(); + grip.call(Color$k.fill, sliderOpts.activebgcolor); + var normalizedPosition = positionToNormalizedValue(sliderOpts, d3$f.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); + sliderOpts._dragging = true; + function mouseMoveHandler() { + var sliderOpts2 = getSliderOpts(); + var normalizedPosition2 = positionToNormalizedValue(sliderOpts2, d3$f.mouse(node)[0]); + handleInput(gd, sliderGroup, sliderOpts2, normalizedPosition2, false); + } + $gd.on("mousemove", mouseMoveHandler); + $gd.on("touchmove", mouseMoveHandler); + function mouseUpHandler() { + var sliderOpts2 = getSliderOpts(); + sliderOpts2._dragging = false; + grip.call(Color$k.fill, sliderOpts2.bgcolor); + $gd.on("mouseup", null); + $gd.on("mousemove", null); + $gd.on("touchend", null); + $gd.on("touchmove", null); + gd.emit("plotly_sliderend", { + slider: sliderOpts2, + step: sliderOpts2.steps[sliderOpts2.active] + }); + } + $gd.on("mouseup", mouseUpHandler); + $gd.on("touchend", mouseUpHandler); + } + item.on("mousedown", mouseDownHandler); + item.on("touchstart", mouseDownHandler); +} +function drawTicks(sliderGroup, sliderOpts) { + var tick = sliderGroup.selectAll("rect." + constants$n.tickRectClass).data(sliderOpts._visibleSteps); + var dims = sliderOpts._dims; + tick.enter().append("rect").classed(constants$n.tickRectClass, true); + tick.exit().remove(); + tick.attr({ + width: sliderOpts.tickwidth + "px", + "shape-rendering": "crispEdges" + }); + tick.each(function(d, i) { + var isMajor = i % dims.labelStride === 0; + var item = d3$f.select(this); + item.attr({ height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen }).call(Color$k.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); + Drawing$a.setTranslate( + item, + normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth, + (isMajor ? constants$n.tickOffset : constants$n.minorTickOffset) + dims.currentValueTotalHeight + ); + }); +} +function computeLabelSteps(sliderOpts) { + var dims = sliderOpts._dims; + dims.labelSteps = []; + var nsteps = sliderOpts._stepCount; + for (var i = 0; i < nsteps; i += dims.labelStride) { + dims.labelSteps.push({ + fraction: i / (nsteps - 1), + step: sliderOpts._visibleSteps[i] + }); + } +} +function setGripPosition(sliderGroup, sliderOpts, doTransition) { + var grip = sliderGroup.select("rect." + constants$n.gripRectClass); + var quantizedIndex = 0; + for (var i = 0; i < sliderOpts._stepCount; i++) { + if (sliderOpts._visibleSteps[i]._index === sliderOpts.active) { + quantizedIndex = i; + break; + } + } + var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1)); + if (sliderOpts._invokingCommand) return; + var el = grip; + if (doTransition && sliderOpts.transition.duration > 0) { + el = el.transition().duration(sliderOpts.transition.duration).ease(sliderOpts.transition.easing); + } + el.attr("transform", strTranslate$3(x - constants$n.gripWidth * 0.5, sliderOpts._dims.currentValueTotalHeight)); +} +function normalizedValueToPosition(sliderOpts, normalizedPosition) { + var dims = sliderOpts._dims; + return dims.inputAreaStart + constants$n.stepInset + (dims.inputAreaLength - 2 * constants$n.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); +} +function positionToNormalizedValue(sliderOpts, position) { + var dims = sliderOpts._dims; + return Math.min(1, Math.max(0, (position - constants$n.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants$n.stepInset - 2 * dims.inputAreaStart))); +} +function drawTouchRect(sliderGroup, gd, sliderOpts) { + var dims = sliderOpts._dims; + var rect2 = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.railTouchRectClass, function(s) { + s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all"); + }); + rect2.attr({ + width: dims.inputAreaLength, + height: Math.max(dims.inputAreaWidth, constants$n.tickOffset + sliderOpts.ticklen + dims.labelHeight) + }).call(Color$k.fill, sliderOpts.bgcolor).attr("opacity", 0); + Drawing$a.setTranslate(rect2, 0, dims.currentValueTotalHeight); +} +function drawRail(sliderGroup, sliderOpts) { + var dims = sliderOpts._dims; + var computedLength = dims.inputAreaLength - constants$n.railInset * 2; + var rect2 = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.railRectClass); + rect2.attr({ + width: computedLength, + height: constants$n.railWidth, + rx: constants$n.railRadius, + ry: constants$n.railRadius, + "shape-rendering": "crispEdges" + }).call(Color$k.stroke, sliderOpts.bordercolor).call(Color$k.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px"); + Drawing$a.setTranslate( + rect2, + constants$n.railInset, + (dims.inputAreaWidth - constants$n.railWidth) * 0.5 + dims.currentValueTotalHeight + ); +} +var constants$m = constants$q; +var sliders = { + moduleType: "component", + name: constants$m.name, + layoutAttributes: attributes$l, + supplyLayoutDefaults: defaults$a, + draw: draw$5 +}; +var colorAttributes = attributes$N; +var attributes$j = { + bgcolor: { + valType: "color", + dflt: colorAttributes.background, + editType: "plot", + description: "Sets the background color of the range slider." + }, + bordercolor: { + valType: "color", + dflt: colorAttributes.defaultLine, + editType: "plot", + description: "Sets the border color of the range slider." + }, + borderwidth: { + valType: "integer", + dflt: 0, + min: 0, + editType: "plot", + description: "Sets the border width of the range slider." + }, + autorange: { + valType: "boolean", + dflt: true, + editType: "calc", + impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, + description: [ + "Determines whether or not the range slider range is", + "computed in relation to the input data.", + "If `range` is provided, then `autorange` is set to *false*." + ].join(" ") + }, + range: { + valType: "info_array", + items: [ + { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } }, + { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } } + ], + editType: "calc", + impliedEdits: { autorange: false }, + description: [ + "Sets the range of the range slider.", + "If not set, defaults to the full xaxis range.", + "If the axis `type` is *log*, then you must take the", + "log of your desired range.", + "If the axis `type` is *date*, it should be date strings,", + "like date data, though Date objects and unix milliseconds", + "will be accepted and converted to strings.", + "If the axis `type` is *category*, it should be numbers,", + "using the scale where each category is assigned a serial", + "number from zero in the order it appears." + ].join(" ") + }, + thickness: { + valType: "number", + dflt: 0.15, + min: 0, + max: 1, + editType: "plot", + description: [ + "The height of the range slider as a fraction of the", + "total plot area height." + ].join(" ") + }, + visible: { + valType: "boolean", + dflt: true, + editType: "calc", + description: [ + "Determines whether or not the range slider will be visible.", + "If visible, perpendicular axes will be set to `fixedrange`" + ].join(" ") + }, + editType: "calc" +}; +var oppaxis_attributes = { + // not really a 'subplot' attribute container, + // but this is the flag we use to denote attributes that + // support yaxis, yaxis2, yaxis3, ... counters + _isSubplotObj: true, + rangemode: { + valType: "enumerated", + values: ["auto", "fixed", "match"], + dflt: "match", + editType: "calc", + description: [ + "Determines whether or not the range of this axis in", + "the rangeslider use the same value than in the main plot", + "when zooming in/out.", + "If *auto*, the autorange will be used.", + "If *fixed*, the `range` is used.", + "If *match*, the current range of the corresponding y-axis on the main subplot is used." + ].join(" ") + }, + range: { + valType: "info_array", + items: [ + { valType: "any", editType: "plot" }, + { valType: "any", editType: "plot" } + ], + editType: "plot", + description: [ + "Sets the range of this axis for the rangeslider." + ].join(" ") + }, + editType: "calc" +}; +var helpers$h = {}; +var constants$l = { + // attribute container name + name: "rangeslider", + // class names + containerClassName: "rangeslider-container", + bgClassName: "rangeslider-bg", + rangePlotClassName: "rangeslider-rangeplot", + maskMinClassName: "rangeslider-mask-min", + maskMaxClassName: "rangeslider-mask-max", + slideBoxClassName: "rangeslider-slidebox", + grabberMinClassName: "rangeslider-grabber-min", + grabAreaMinClassName: "rangeslider-grabarea-min", + handleMinClassName: "rangeslider-handle-min", + grabberMaxClassName: "rangeslider-grabber-max", + grabAreaMaxClassName: "rangeslider-grabarea-max", + handleMaxClassName: "rangeslider-handle-max", + maskMinOppAxisClassName: "rangeslider-mask-min-opp-axis", + maskMaxOppAxisClassName: "rangeslider-mask-max-opp-axis", + // style constants + maskColor: "rgba(0,0,0,0.4)", + maskOppAxisColor: "rgba(0,0,0,0.2)", + slideBoxFill: "transparent", + slideBoxCursor: "ew-resize", + grabAreaFill: "transparent", + grabAreaCursor: "col-resize", + grabAreaWidth: 10, + handleWidth: 4, + handleRadius: 1, + handleStrokeWidth: 1, + extraPad: 15 +}; +var axisIDs = axis_ids; +var svgTextUtils$6 = svg_text_utils; +var constants$k = constants$l; +var LINE_SPACING$2 = alignment$1.LINE_SPACING; +var name = constants$k.name; +function isVisible(ax) { + var rangeSlider = ax && ax[name]; + return rangeSlider && rangeSlider.visible; +} +helpers$h.isVisible = isVisible; +helpers$h.makeData = function(fullLayout) { + var axes2 = axisIDs.list({ _fullLayout: fullLayout }, "x", true); + var margin = fullLayout.margin; + var rangeSliderData = []; + if (!fullLayout._has("gl2d")) { + for (var i = 0; i < axes2.length; i++) { + var ax = axes2[i]; + if (isVisible(ax)) { + rangeSliderData.push(ax); + var opts = ax[name]; + opts._id = name + ax._id; + opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; + opts._offsetShift = Math.floor(opts.borderwidth / 2); + } + } + } + fullLayout._rangeSliderData = rangeSliderData; +}; +helpers$h.autoMarginOpts = function(gd, ax) { + var fullLayout = gd._fullLayout; + var opts = ax[name]; + var axLetter = ax._id.charAt(0); + var bottomDepth = 0; + var titleHeight = 0; + if (ax.side === "bottom") { + bottomDepth = ax._depth; + if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { + titleHeight = 1.5 * ax.title.font.size + 10 + opts._offsetShift; + var extraLines = (ax.title.text.match(svgTextUtils$6.BR_TAG_ALL) || []).length; + titleHeight += extraLines * ax.title.font.size * LINE_SPACING$2; + } + } + return { + x: 0, + y: ax._counterDomainMin, + l: 0, + r: 0, + t: 0, + b: opts._height + bottomDepth + Math.max(fullLayout.margin.b, titleHeight), + pad: constants$k.extraPad + opts._offsetShift * 2 + }; +}; +var defaults$9; +var hasRequiredDefaults$1; +function requireDefaults$1() { + if (hasRequiredDefaults$1) return defaults$9; + hasRequiredDefaults$1 = 1; + var Lib2 = libExports; + var Template2 = plot_template; + var axisIds2 = axis_ids; + var attributes2 = attributes$j; + var oppAxisAttrs2 = oppaxis_attributes; + defaults$9 = function handleDefaults3(layoutIn, layoutOut, axName) { + var axIn = layoutIn[axName]; + var axOut = layoutOut[axName]; + if (!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; + if (!Lib2.isPlainObject(axIn.rangeslider)) { + axIn.rangeslider = {}; + } + var containerIn = axIn.rangeslider; + var containerOut = Template2.newContainer(axOut, "rangeslider"); + function coerce2(attr, dflt) { + return Lib2.coerce(containerIn, containerOut, attributes2, attr, dflt); + } + var rangeContainerIn, rangeContainerOut; + function coerceRange(attr, dflt) { + return Lib2.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs2, attr, dflt); + } + var visible = coerce2("visible"); + if (!visible) return; + coerce2("bgcolor", layoutOut.plot_bgcolor); + coerce2("bordercolor"); + coerce2("borderwidth"); + coerce2("thickness"); + coerce2("autorange", !axOut.isValidRange(containerIn.range)); + coerce2("range"); + var subplots = layoutOut._subplots; + if (subplots) { + var yIds = subplots.cartesian.filter(function(subplotId) { + return subplotId.substr(0, subplotId.indexOf("y")) === axisIds2.name2id(axName); + }).map(function(subplotId) { + return subplotId.substr(subplotId.indexOf("y"), subplotId.length); + }); + var yNames = Lib2.simpleMap(yIds, axisIds2.id2name); + for (var i = 0; i < yNames.length; i++) { + var yName = yNames[i]; + rangeContainerIn = containerIn[yName] || {}; + rangeContainerOut = Template2.newContainer(containerOut, yName, "yaxis"); + var yAxOut = layoutOut[yName]; + var rangemodeDflt; + if (rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { + rangemodeDflt = "fixed"; + } + var rangeMode = coerceRange("rangemode", rangemodeDflt); + if (rangeMode !== "match") { + coerceRange("range", yAxOut.range.slice()); + } + } + } + containerOut._input = containerIn; + }; + return defaults$9; +} +var calc_autorange; +var hasRequiredCalc_autorange; +function requireCalc_autorange() { + if (hasRequiredCalc_autorange) return calc_autorange; + hasRequiredCalc_autorange = 1; + var listAxes = axis_ids.list; + var getAutoRange2 = autorange$2.getAutoRange; + var constants2 = constants$l; + calc_autorange = function calcAutorange3(gd) { + var axes2 = listAxes(gd, "x", true); + for (var i = 0; i < axes2.length; i++) { + var ax = axes2[i]; + var opts = ax[constants2.name]; + if (opts && opts.visible && opts.autorange) { + opts._input.autorange = true; + opts._input.range = opts.range = getAutoRange2(gd, ax); + } + } + }; + return calc_autorange; +} +var draw$4; +var hasRequiredDraw; +function requireDraw() { + if (hasRequiredDraw) return draw$4; + hasRequiredDraw = 1; + var d32 = d3Exports; + var Registry2 = registry; + var Plots2 = plotsExports; + var Lib2 = libExports; + var strTranslate2 = Lib2.strTranslate; + var Drawing2 = drawingExports; + var Color2 = colorExports; + var Titles2 = titles; + var Cartesian = cartesian; + var axisIDs2 = axis_ids; + var dragElement2 = dragelementExports; + var setCursor3 = setcursor; + var constants2 = constants$l; + draw$4 = function(gd) { + var fullLayout = gd._fullLayout; + var rangeSliderData = fullLayout._rangeSliderData; + for (var i = 0; i < rangeSliderData.length; i++) { + var opts = rangeSliderData[i][constants2.name]; + opts._clipId = opts._id + "-" + fullLayout._uid; + } + function keyFunction2(axisOpts) { + return axisOpts._name; + } + var rangeSliders = fullLayout._infolayer.selectAll("g." + constants2.containerClassName).data(rangeSliderData, keyFunction2); + rangeSliders.exit().each(function(axisOpts) { + var opts2 = axisOpts[constants2.name]; + fullLayout._topdefs.select("#" + opts2._clipId).remove(); + }).remove(); + if (rangeSliderData.length === 0) return; + rangeSliders.enter().append("g").classed(constants2.containerClassName, true).attr("pointer-events", "all"); + rangeSliders.each(function(axisOpts) { + var rangeSlider = d32.select(this); + var opts2 = axisOpts[constants2.name]; + var oppAxisOpts = fullLayout[axisIDs2.id2name(axisOpts.anchor)]; + var oppAxisRangeOpts = opts2[axisIDs2.id2name(axisOpts.anchor)]; + if (opts2.range) { + var rng = Lib2.simpleMap(opts2.range, axisOpts.r2l); + var axRng = Lib2.simpleMap(axisOpts.range, axisOpts.r2l); + var newRng; + if (axRng[0] < axRng[1]) { + newRng = [ + Math.min(rng[0], axRng[0]), + Math.max(rng[1], axRng[1]) + ]; + } else { + newRng = [ + Math.max(rng[0], axRng[0]), + Math.min(rng[1], axRng[1]) + ]; + } + opts2.range = opts2._input.range = Lib2.simpleMap(newRng, axisOpts.l2r); + } + axisOpts.cleanRange("rangeslider.range"); + var gs = fullLayout._size; + var domain2 = axisOpts.domain; + opts2._width = gs.w * (domain2[1] - domain2[0]); + var x = Math.round(gs.l + gs.w * domain2[0]); + var y = Math.round( + gs.t + gs.h * (1 - axisOpts._counterDomainMin) + (axisOpts.side === "bottom" ? axisOpts._depth : 0) + opts2._offsetShift + constants2.extraPad + ); + rangeSlider.attr("transform", strTranslate2(x, y)); + opts2._rl = Lib2.simpleMap(opts2.range, axisOpts.r2l); + var rl0 = opts2._rl[0]; + var rl1 = opts2._rl[1]; + var drl = rl1 - rl0; + opts2.p2d = function(v) { + return v / opts2._width * drl + rl0; + }; + opts2.d2p = function(v) { + return (v - rl0) / drl * opts2._width; + }; + if (axisOpts.rangebreaks) { + var rsBreaks = axisOpts.locateBreaks(rl0, rl1); + if (rsBreaks.length) { + var j, brk; + var lBreaks = 0; + for (j = 0; j < rsBreaks.length; j++) { + brk = rsBreaks[j]; + lBreaks += brk.max - brk.min; + } + var m2 = opts2._width / (rl1 - rl0 - lBreaks); + var _B = [-m2 * rl0]; + for (j = 0; j < rsBreaks.length; j++) { + brk = rsBreaks[j]; + _B.push(_B[_B.length - 1] - m2 * (brk.max - brk.min)); + } + opts2.d2p = function(v) { + var b = _B[0]; + for (var j2 = 0; j2 < rsBreaks.length; j2++) { + var brk2 = rsBreaks[j2]; + if (v >= brk2.max) b = _B[j2 + 1]; + else if (v < brk2.min) break; + } + return b + m2 * v; + }; + for (j = 0; j < rsBreaks.length; j++) { + brk = rsBreaks[j]; + brk.pmin = opts2.d2p(brk.min); + brk.pmax = opts2.d2p(brk.max); + } + opts2.p2d = function(v) { + var b = _B[0]; + for (var j2 = 0; j2 < rsBreaks.length; j2++) { + var brk2 = rsBreaks[j2]; + if (v >= brk2.pmax) b = _B[j2 + 1]; + else if (v < brk2.pmin) break; + } + return (v - b) / m2; + }; + } + } + if (oppAxisRangeOpts.rangemode !== "match") { + var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]); + var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]); + var distOppAxis = range1OppAxis - range0OppAxis; + opts2.d2pOppAxis = function(v) { + return (v - range0OppAxis) / distOppAxis * opts2._height; + }; + } + rangeSlider.call(drawBg, gd, axisOpts, opts2).call(addClipPath, gd, axisOpts, opts2).call(drawRangePlot, gd, axisOpts, opts2).call(drawMasks, gd, axisOpts, opts2, oppAxisRangeOpts).call(drawSlideBox, gd, axisOpts, opts2).call(drawGrabbers, gd, axisOpts, opts2); + setupDragElement2(rangeSlider, gd, axisOpts, opts2); + setPixelRange(rangeSlider, gd, axisOpts, opts2, oppAxisOpts, oppAxisRangeOpts); + if (axisOpts.side === "bottom") { + Titles2.draw(gd, axisOpts._id + "title", { + propContainer: axisOpts, + propName: axisOpts._name + ".title", + placeholder: fullLayout._dfltTitle.x, + attributes: { + x: axisOpts._offset + axisOpts._length / 2, + y: y + opts2._height + opts2._offsetShift + 10 + 1.5 * axisOpts.title.font.size, + "text-anchor": "middle" + } + }); + } + }); + }; + function eventX(event) { + if (typeof event.clientX === "number") { + return event.clientX; + } + if (event.touches && event.touches.length > 0) { + return event.touches[0].clientX; + } + return 0; + } + function setupDragElement2(rangeSlider, gd, axisOpts, opts) { + if (gd._context.staticPlot) return; + var slideBox = rangeSlider.select("rect." + constants2.slideBoxClassName).node(); + var grabAreaMin = rangeSlider.select("rect." + constants2.grabAreaMinClassName).node(); + var grabAreaMax = rangeSlider.select("rect." + constants2.grabAreaMaxClassName).node(); + function mouseDownHandler() { + var event = d32.event; + var target = event.target; + var startX = eventX(event); + var offsetX = startX - rangeSlider.node().getBoundingClientRect().left; + var minVal = opts.d2p(axisOpts._rl[0]); + var maxVal = opts.d2p(axisOpts._rl[1]); + var dragCover = dragElement2.coverSlip(); + this.addEventListener("touchmove", mouseMove); + this.addEventListener("touchend", mouseUp); + dragCover.addEventListener("mousemove", mouseMove); + dragCover.addEventListener("mouseup", mouseUp); + function mouseMove(e) { + var clientX = eventX(e); + var delta2 = +clientX - startX; + var pixelMin, pixelMax, cursor2; + switch (target) { + case slideBox: + cursor2 = "ew-resize"; + if (minVal + delta2 > axisOpts._length || maxVal + delta2 < 0) { + return; + } + pixelMin = minVal + delta2; + pixelMax = maxVal + delta2; + break; + case grabAreaMin: + cursor2 = "col-resize"; + if (minVal + delta2 > axisOpts._length) { + return; + } + pixelMin = minVal + delta2; + pixelMax = maxVal; + break; + case grabAreaMax: + cursor2 = "col-resize"; + if (maxVal + delta2 < 0) { + return; + } + pixelMin = minVal; + pixelMax = maxVal + delta2; + break; + default: + cursor2 = "ew-resize"; + pixelMin = offsetX; + pixelMax = offsetX + delta2; + break; + } + if (pixelMax < pixelMin) { + var tmp = pixelMax; + pixelMax = pixelMin; + pixelMin = tmp; + } + opts._pixelMin = pixelMin; + opts._pixelMax = pixelMax; + setCursor3(d32.select(dragCover), cursor2); + setDataRange(rangeSlider, gd, axisOpts, opts); + } + function mouseUp() { + dragCover.removeEventListener("mousemove", mouseMove); + dragCover.removeEventListener("mouseup", mouseUp); + this.removeEventListener("touchmove", mouseMove); + this.removeEventListener("touchend", mouseUp); + Lib2.removeElement(dragCover); + } + } + rangeSlider.on("mousedown", mouseDownHandler); + rangeSlider.on("touchstart", mouseDownHandler); + } + function setDataRange(rangeSlider, gd, axisOpts, opts) { + function clamp2(v) { + return axisOpts.l2r(Lib2.constrain(v, opts._rl[0], opts._rl[1])); + } + var dataMin = clamp2(opts.p2d(opts._pixelMin)); + var dataMax = clamp2(opts.p2d(opts._pixelMax)); + window.requestAnimationFrame(function() { + Registry2.call("_guiRelayout", gd, axisOpts._name + ".range", [dataMin, dataMax]); + }); + } + function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { + var hw2 = constants2.handleWidth / 2; + function clamp2(v) { + return Lib2.constrain(v, 0, opts._width); + } + function clampOppAxis(v) { + return Lib2.constrain(v, 0, opts._height); + } + function clampHandle(v) { + return Lib2.constrain(v, -hw2, opts._width + hw2); + } + var pixelMin = clamp2(opts.d2p(axisOpts._rl[0])); + var pixelMax = clamp2(opts.d2p(axisOpts._rl[1])); + rangeSlider.select("rect." + constants2.slideBoxClassName).attr("x", pixelMin).attr("width", pixelMax - pixelMin); + rangeSlider.select("rect." + constants2.maskMinClassName).attr("width", pixelMin); + rangeSlider.select("rect." + constants2.maskMaxClassName).attr("x", pixelMax).attr("width", opts._width - pixelMax); + if (oppAxisRangeOpts.rangemode !== "match") { + var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])); + var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); + rangeSlider.select("rect." + constants2.maskMinOppAxisClassName).attr("x", pixelMin).attr("height", pixelMinOppAxis).attr("width", pixelMax - pixelMin); + rangeSlider.select("rect." + constants2.maskMaxOppAxisClassName).attr("x", pixelMin).attr("y", pixelMaxOppAxis).attr("height", opts._height - pixelMaxOppAxis).attr("width", pixelMax - pixelMin); + rangeSlider.select("rect." + constants2.slideBoxClassName).attr("y", pixelMinOppAxis).attr("height", pixelMaxOppAxis - pixelMinOppAxis); + } + var offset = 0.5; + var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset; + var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; + rangeSlider.select("g." + constants2.grabberMinClassName).attr("transform", strTranslate2(xMin, offset)); + rangeSlider.select("g." + constants2.grabberMaxClassName).attr("transform", strTranslate2(xMax, offset)); + } + function drawBg(rangeSlider, gd, axisOpts, opts) { + var bg = Lib2.ensureSingle(rangeSlider, "rect", constants2.bgClassName, function(s) { + s.attr({ + x: 0, + y: 0, + "shape-rendering": "crispEdges" + }); + }); + var borderCorrect = opts.borderwidth % 2 === 0 ? opts.borderwidth : opts.borderwidth - 1; + var offsetShift = -opts._offsetShift; + var lw = Drawing2.crispRound(gd, opts.borderwidth); + bg.attr({ + width: opts._width + borderCorrect, + height: opts._height + borderCorrect, + transform: strTranslate2(offsetShift, offsetShift), + "stroke-width": lw + }).call(Color2.stroke, opts.bordercolor).call(Color2.fill, opts.bgcolor); + } + function addClipPath(rangeSlider, gd, axisOpts, opts) { + var fullLayout = gd._fullLayout; + var clipPath = Lib2.ensureSingleById(fullLayout._topdefs, "clipPath", opts._clipId, function(s) { + s.append("rect").attr({ x: 0, y: 0 }); + }); + clipPath.select("rect").attr({ + width: opts._width, + height: opts._height + }); + } + function drawRangePlot(rangeSlider, gd, axisOpts, opts) { + var calcData = gd.calcdata; + var rangePlots = rangeSlider.selectAll("g." + constants2.rangePlotClassName).data(axisOpts._subplotsWith, Lib2.identity); + rangePlots.enter().append("g").attr("class", function(id) { + return constants2.rangePlotClassName + " " + id; + }).call(Drawing2.setClipUrl, opts._clipId, gd); + rangePlots.order(); + rangePlots.exit().remove(); + var mainplotinfo; + rangePlots.each(function(id, i) { + var plotgroup = d32.select(this); + var isMainPlot = i === 0; + var oppAxisOpts = axisIDs2.getFromId(gd, id, "y"); + var oppAxisName = oppAxisOpts._name; + var oppAxisRangeOpts = opts[oppAxisName]; + var mockFigure = { + data: [], + layout: { + xaxis: { + type: axisOpts.type, + domain: [0, 1], + range: opts.range.slice(), + calendar: axisOpts.calendar + }, + width: opts._width, + height: opts._height, + margin: { t: 0, b: 0, l: 0, r: 0 } + }, + _context: gd._context + }; + if (axisOpts.rangebreaks) { + mockFigure.layout.xaxis.rangebreaks = axisOpts.rangebreaks; + } + mockFigure.layout[oppAxisName] = { + type: oppAxisOpts.type, + domain: [0, 1], + range: oppAxisRangeOpts.rangemode !== "match" ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), + calendar: oppAxisOpts.calendar + }; + if (oppAxisOpts.rangebreaks) { + mockFigure.layout[oppAxisName].rangebreaks = oppAxisOpts.rangebreaks; + } + Plots2.supplyDefaults(mockFigure); + var xa = mockFigure._fullLayout.xaxis; + var ya = mockFigure._fullLayout[oppAxisName]; + xa.clearCalc(); + xa.setScale(); + ya.clearCalc(); + ya.setScale(); + var plotinfo = { + id, + plotgroup, + xaxis: xa, + yaxis: ya, + isRangePlot: true + }; + if (isMainPlot) mainplotinfo = plotinfo; + else { + plotinfo.mainplot = "xy"; + plotinfo.mainplotinfo = mainplotinfo; + } + Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); + }); + } + function filterRangePlotCalcData(calcData, subplotId) { + var out = []; + for (var i = 0; i < calcData.length; i++) { + var calcTrace = calcData[i]; + var trace = calcTrace[0].trace; + if (trace.xaxis + trace.yaxis === subplotId) { + out.push(calcTrace); + } + } + return out; + } + function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { + var maskMin = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMinClassName, function(s) { + s.attr({ + x: 0, + y: 0, + "shape-rendering": "crispEdges" + }); + }); + maskMin.attr("height", opts._height).call(Color2.fill, constants2.maskColor); + var maskMax = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMaxClassName, function(s) { + s.attr({ + y: 0, + "shape-rendering": "crispEdges" + }); + }); + maskMax.attr("height", opts._height).call(Color2.fill, constants2.maskColor); + if (oppAxisRangeOpts.rangemode !== "match") { + var maskMinOppAxis = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMinOppAxisClassName, function(s) { + s.attr({ + y: 0, + "shape-rendering": "crispEdges" + }); + }); + maskMinOppAxis.attr("width", opts._width).call(Color2.fill, constants2.maskOppAxisColor); + var maskMaxOppAxis = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMaxOppAxisClassName, function(s) { + s.attr({ + y: 0, + "shape-rendering": "crispEdges" + }); + }); + maskMaxOppAxis.attr("width", opts._width).style("border-top", constants2.maskOppBorder).call(Color2.fill, constants2.maskOppAxisColor); + } + } + function drawSlideBox(rangeSlider, gd, axisOpts, opts) { + if (gd._context.staticPlot) return; + var slideBox = Lib2.ensureSingle(rangeSlider, "rect", constants2.slideBoxClassName, function(s) { + s.attr({ + y: 0, + cursor: constants2.slideBoxCursor, + "shape-rendering": "crispEdges" + }); + }); + slideBox.attr({ + height: opts._height, + fill: constants2.slideBoxFill + }); + } + function drawGrabbers(rangeSlider, gd, axisOpts, opts) { + var grabberMin = Lib2.ensureSingle(rangeSlider, "g", constants2.grabberMinClassName); + var grabberMax = Lib2.ensureSingle(rangeSlider, "g", constants2.grabberMaxClassName); + var handleFixAttrs = { + x: 0, + width: constants2.handleWidth, + rx: constants2.handleRadius, + fill: Color2.background, + stroke: Color2.defaultLine, + "stroke-width": constants2.handleStrokeWidth, + "shape-rendering": "crispEdges" + }; + var handleDynamicAttrs = { + y: Math.round(opts._height / 4), + height: Math.round(opts._height / 2) + }; + var handleMin = Lib2.ensureSingle(grabberMin, "rect", constants2.handleMinClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMin.attr(handleDynamicAttrs); + var handleMax = Lib2.ensureSingle(grabberMax, "rect", constants2.handleMaxClassName, function(s) { + s.attr(handleFixAttrs); + }); + handleMax.attr(handleDynamicAttrs); + var grabAreaFixAttrs = { + width: constants2.grabAreaWidth, + x: 0, + y: 0, + fill: constants2.grabAreaFill, + cursor: !gd._context.staticPlot ? constants2.grabAreaCursor : void 0 + }; + var grabAreaMin = Lib2.ensureSingle(grabberMin, "rect", constants2.grabAreaMinClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMin.attr("height", opts._height); + var grabAreaMax = Lib2.ensureSingle(grabberMax, "rect", constants2.grabAreaMaxClassName, function(s) { + s.attr(grabAreaFixAttrs); + }); + grabAreaMax.attr("height", opts._height); + } + return draw$4; +} +var Lib$D = libExports; +var attrs$1 = attributes$j; +var oppAxisAttrs = oppaxis_attributes; +var helpers$g = helpers$h; +var rangeslider = { + moduleType: "component", + name: "rangeslider", + schema: { + subplots: { + xaxis: { + rangeslider: Lib$D.extendFlat({}, attrs$1, { + yaxis: oppAxisAttrs + }) + } + } + }, + layoutAttributes: attributes$j, + handleDefaults: requireDefaults$1(), + calcAutorange: requireCalc_autorange(), + draw: requireDraw(), + isVisible: helpers$g.isVisible, + makeData: helpers$g.makeData, + autoMarginOpts: helpers$g.autoMarginOpts +}; +var fontAttrs$4 = font_attributes; +var colorAttrs$1 = attributes$N; +var templatedArray = plot_template.templatedArray; +var buttonAttrs = templatedArray("button", { + visible: { + valType: "boolean", + dflt: true, + editType: "plot", + description: "Determines whether or not this button is visible." + }, + step: { + valType: "enumerated", + values: ["month", "year", "day", "hour", "minute", "second", "all"], + dflt: "month", + editType: "plot", + description: [ + "The unit of measurement that the `count` value will set the range by." + ].join(" ") + }, + stepmode: { + valType: "enumerated", + values: ["backward", "todate"], + dflt: "backward", + editType: "plot", + description: [ + "Sets the range update mode.", + "If *backward*, the range update shifts the start of range", + "back *count* times *step* milliseconds.", + "If *todate*, the range update shifts the start of range", + "back to the first timestamp from *count* times", + "*step* milliseconds back.", + "For example, with `step` set to *year* and `count` set to *1*", + "the range update shifts the start of the range back to", + "January 01 of the current year.", + "Month and year *todate* are currently available only", + "for the built-in (Gregorian) calendar." + ].join(" ") + }, + count: { + valType: "number", + min: 0, + dflt: 1, + editType: "plot", + description: [ + "Sets the number of steps to take to update the range.", + "Use with `step` to specify the update interval." + ].join(" ") + }, + label: { + valType: "string", + editType: "plot", + description: "Sets the text label to appear on the button." + }, + editType: "plot", + description: [ + "Sets the specifications for each buttons.", + "By default, a range selector comes with no buttons." + ].join(" ") +}); +var attributes$i = { + visible: { + valType: "boolean", + editType: "plot", + description: [ + "Determines whether or not this range selector is visible.", + "Note that range selectors are only available for x axes of", + "`type` set to or auto-typed to *date*." + ].join(" ") + }, + buttons: buttonAttrs, + x: { + valType: "number", + min: -2, + max: 3, + editType: "plot", + description: "Sets the x position (in normalized coordinates) of the range selector." + }, + xanchor: { + valType: "enumerated", + values: ["auto", "left", "center", "right"], + dflt: "left", + editType: "plot", + description: [ + "Sets the range selector's horizontal position anchor.", + "This anchor binds the `x` position to the *left*, *center*", + "or *right* of the range selector." + ].join(" ") + }, + y: { + valType: "number", + min: -2, + max: 3, + editType: "plot", + description: "Sets the y position (in normalized coordinates) of the range selector." + }, + yanchor: { + valType: "enumerated", + values: ["auto", "top", "middle", "bottom"], + dflt: "bottom", + editType: "plot", + description: [ + "Sets the range selector's vertical position anchor", + "This anchor binds the `y` position to the *top*, *middle*", + "or *bottom* of the range selector." + ].join(" ") + }, + font: fontAttrs$4({ + editType: "plot", + description: "Sets the font of the range selector button text." + }), + bgcolor: { + valType: "color", + dflt: colorAttrs$1.lightLine, + editType: "plot", + description: "Sets the background color of the range selector buttons." + }, + activecolor: { + valType: "color", + editType: "plot", + description: "Sets the background color of the active range selector button." + }, + bordercolor: { + valType: "color", + dflt: colorAttrs$1.defaultLine, + editType: "plot", + description: "Sets the color of the border enclosing the range selector." + }, + borderwidth: { + valType: "number", + min: 0, + dflt: 0, + editType: "plot", + description: "Sets the width (in px) of the border enclosing the range selector." + }, + editType: "plot" +}; +var constants$j = { + // 'y' position pad above counter axis domain + yPad: 0.02, + // minimum button width (regardless of text size) + minButtonWidth: 30, + // buttons rect radii + rx: 3, + ry: 3, + // light fraction used to compute the 'activecolor' default + lightAmount: 25, + darkAmount: 10 +}; +var Lib$C = libExports; +var Color$j = colorExports; +var Template$1 = plot_template; +var handleArrayContainerDefaults2 = array_container_defaults; +var attributes$h = attributes$i; +var constants$i = constants$j; +var defaults$8 = function handleDefaults2(containerIn, containerOut, layout, counterAxes, calendar) { + var selectorIn = containerIn.rangeselector || {}; + var selectorOut = Template$1.newContainer(containerOut, "rangeselector"); + function coerce2(attr, dflt) { + return Lib$C.coerce(selectorIn, selectorOut, attributes$h, attr, dflt); + } + var buttons2 = handleArrayContainerDefaults2(selectorIn, selectorOut, { + name: "buttons", + handleItemDefaults: buttonDefaults, + calendar + }); + var visible = coerce2("visible", buttons2.length > 0); + if (visible) { + var posDflt = getPosDflt(containerOut, layout, counterAxes); + coerce2("x", posDflt[0]); + coerce2("y", posDflt[1]); + Lib$C.noneOrAll(containerIn, containerOut, ["x", "y"]); + coerce2("xanchor"); + coerce2("yanchor"); + Lib$C.coerceFont(coerce2, "font", layout.font); + var bgColor = coerce2("bgcolor"); + coerce2("activecolor", Color$j.contrast(bgColor, constants$i.lightAmount, constants$i.darkAmount)); + coerce2("bordercolor"); + coerce2("borderwidth"); + } +}; +function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) { + var calendar = opts.calendar; + function coerce2(attr, dflt) { + return Lib$C.coerce(buttonIn, buttonOut, attributes$h.buttons, attr, dflt); + } + var visible = coerce2("visible"); + if (visible) { + var step = coerce2("step"); + if (step !== "all") { + if (calendar && calendar !== "gregorian" && (step === "month" || step === "year")) { + buttonOut.stepmode = "backward"; + } else { + coerce2("stepmode"); + } + coerce2("count"); + } + coerce2("label"); + } +} +function getPosDflt(containerOut, layout, counterAxes) { + var anchoredList = counterAxes.filter(function(ax) { + return layout[ax].anchor === containerOut._id; + }); + var posY = 0; + for (var i = 0; i < anchoredList.length; i++) { + var domain2 = layout[anchoredList[i]].domain; + if (domain2) posY = Math.max(domain2[1], posY); + } + return [containerOut.domain[0], posY + constants$i.yPad]; +} +const require$$0$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$4); +var d3Time = require$$0$2; +var titleCase = libExports.titleCase; +var get_update_object = function getUpdateObject(axisLayout, buttonLayout) { + var axName = axisLayout._name; + var update2 = {}; + if (buttonLayout.step === "all") { + update2[axName + ".autorange"] = true; + } else { + var xrange = getXRange(axisLayout, buttonLayout); + update2[axName + ".range[0]"] = xrange[0]; + update2[axName + ".range[1]"] = xrange[1]; + } + return update2; +}; +function getXRange(axisLayout, buttonLayout) { + var currentRange = axisLayout.range; + var base = new Date(axisLayout.r2l(currentRange[1])); + var step = buttonLayout.step; + var utcStep = d3Time["utc" + titleCase(step)]; + var count2 = buttonLayout.count; + var range0; + switch (buttonLayout.stepmode) { + case "backward": + range0 = axisLayout.l2r(+utcStep.offset(base, -count2)); + break; + case "todate": + var base2 = utcStep.offset(base, -count2); + range0 = axisLayout.l2r(+utcStep.ceil(base2)); + break; + } + var range1 = currentRange[1]; + return [range0, range1]; +} +var d3$e = d3Exports; +var Registry$f = registry; +var Plots$2 = plotsExports; +var Color$i = colorExports; +var Drawing$9 = drawingExports; +var Lib$B = libExports; +var strTranslate$2 = Lib$B.strTranslate; +var svgTextUtils$5 = svg_text_utils; +var axisIds$1 = axis_ids; +var alignmentConstants$1 = alignment$1; +var LINE_SPACING$1 = alignmentConstants$1.LINE_SPACING; +var FROM_TL$1 = alignmentConstants$1.FROM_TL; +var FROM_BR$1 = alignmentConstants$1.FROM_BR; +var constants$h = constants$j; +var getUpdateObject2 = get_update_object; +var draw$3 = function draw6(gd) { + var fullLayout = gd._fullLayout; + var selectors = fullLayout._infolayer.selectAll(".rangeselector").data(makeSelectorData(gd), selectorKeyFunc); + selectors.enter().append("g").classed("rangeselector", true); + selectors.exit().remove(); + selectors.style({ + cursor: "pointer", + "pointer-events": "all" + }); + selectors.each(function(d) { + var selector = d3$e.select(this); + var axisLayout = d; + var selectorLayout = axisLayout.rangeselector; + var buttons2 = selector.selectAll("g.button").data(Lib$B.filterVisible(selectorLayout.buttons)); + buttons2.enter().append("g").classed("button", true); + buttons2.exit().remove(); + buttons2.each(function(d2) { + var button = d3$e.select(this); + var update2 = getUpdateObject2(axisLayout, d2); + d2._isActive = isActive(axisLayout, d2, update2); + button.call(drawButtonRect, selectorLayout, d2); + button.call(drawButtonText, selectorLayout, d2, gd); + button.on("click", function() { + if (gd._dragged) return; + Registry$f.call("_guiRelayout", gd, update2); + }); + button.on("mouseover", function() { + d2._isHovered = true; + button.call(drawButtonRect, selectorLayout, d2); + }); + button.on("mouseout", function() { + d2._isHovered = false; + button.call(drawButtonRect, selectorLayout, d2); + }); + }); + reposition(gd, buttons2, selectorLayout, axisLayout._name, selector); + }); +}; +function makeSelectorData(gd) { + var axes2 = axisIds$1.list(gd, "x", true); + var data = []; + for (var i = 0; i < axes2.length; i++) { + var axis = axes2[i]; + if (axis.rangeselector && axis.rangeselector.visible) { + data.push(axis); + } + } + return data; +} +function selectorKeyFunc(d) { + return d._id; +} +function isActive(axisLayout, opts, update2) { + if (opts.step === "all") { + return axisLayout.autorange === true; + } else { + var keys = Object.keys(update2); + return axisLayout.range[0] === update2[keys[0]] && axisLayout.range[1] === update2[keys[1]]; + } +} +function drawButtonRect(button, selectorLayout, d) { + var rect2 = Lib$B.ensureSingle(button, "rect", "selector-rect", function(s) { + s.attr("shape-rendering", "crispEdges"); + }); + rect2.attr({ + rx: constants$h.rx, + ry: constants$h.ry + }); + rect2.call(Color$i.stroke, selectorLayout.bordercolor).call(Color$i.fill, getFillColor(selectorLayout, d)).style("stroke-width", selectorLayout.borderwidth + "px"); +} +function getFillColor(selectorLayout, d) { + return d._isActive || d._isHovered ? selectorLayout.activecolor : selectorLayout.bgcolor; +} +function drawButtonText(button, selectorLayout, d, gd) { + function textLayout2(s) { + svgTextUtils$5.convertToTspans(s, gd); + } + var text = Lib$B.ensureSingle(button, "text", "selector-text", function(s) { + s.attr("text-anchor", "middle"); + }); + text.call(Drawing$9.font, selectorLayout.font).text(getLabel2(d, gd._fullLayout._meta)).call(textLayout2); +} +function getLabel2(opts, _meta) { + if (opts.label) { + return _meta ? Lib$B.templateString(opts.label, _meta) : opts.label; + } + if (opts.step === "all") return "all"; + return opts.count + opts.step.charAt(0); +} +function reposition(gd, buttons2, opts, axName, selector) { + var width = 0; + var height = 0; + var borderWidth = opts.borderwidth; + buttons2.each(function() { + var button = d3$e.select(this); + var text = button.select(".selector-text"); + var tHeight = opts.font.size * LINE_SPACING$1; + var hEff = Math.max(tHeight * svgTextUtils$5.lineCount(text), 16) + 3; + height = Math.max(height, hEff); + }); + buttons2.each(function() { + var button = d3$e.select(this); + var rect2 = button.select(".selector-rect"); + var text = button.select(".selector-text"); + var tWidth = text.node() && Drawing$9.bBox(text.node()).width; + var tHeight = opts.font.size * LINE_SPACING$1; + var tLines = svgTextUtils$5.lineCount(text); + var wEff = Math.max(tWidth + 10, constants$h.minButtonWidth); + button.attr("transform", strTranslate$2(borderWidth + width, borderWidth)); + rect2.attr({ + x: 0, + y: 0, + width: wEff, + height + }); + svgTextUtils$5.positionText( + text, + wEff / 2, + height / 2 - (tLines - 1) * tHeight / 2 + 3 + ); + width += wEff + 5; + }); + var graphSize = gd._fullLayout._size; + var lx = graphSize.l + graphSize.w * opts.x; + var ly = graphSize.t + graphSize.h * (1 - opts.y); + var xanchor = "left"; + if (Lib$B.isRightAnchor(opts)) { + lx -= width; + xanchor = "right"; + } + if (Lib$B.isCenterAnchor(opts)) { + lx -= width / 2; + xanchor = "center"; + } + var yanchor = "top"; + if (Lib$B.isBottomAnchor(opts)) { + ly -= height; + yanchor = "bottom"; + } + if (Lib$B.isMiddleAnchor(opts)) { + ly -= height / 2; + yanchor = "middle"; + } + width = Math.ceil(width); + height = Math.ceil(height); + lx = Math.round(lx); + ly = Math.round(ly); + Plots$2.autoMargin(gd, axName + "-range-selector", { + x: opts.x, + y: opts.y, + l: width * FROM_TL$1[xanchor], + r: width * FROM_BR$1[xanchor], + b: height * FROM_BR$1[yanchor], + t: height * FROM_TL$1[yanchor] + }); + selector.attr("transform", strTranslate$2(lx, ly)); +} +var rangeselector = { + moduleType: "component", + name: "rangeselector", + schema: { + subplots: { + xaxis: { rangeselector: attributes$i } + } + }, + layoutAttributes: attributes$i, + handleDefaults: defaults$8, + draw: draw$3 +}; +var domain = {}; +var extendFlat$9 = extend$5.extendFlat; +domain.attributes = function(opts, extra) { + opts = opts || {}; + extra = extra || {}; + var base = { + valType: "info_array", + editType: opts.editType, + items: [ + { valType: "number", min: 0, max: 1, editType: opts.editType }, + { valType: "number", min: 0, max: 1, editType: opts.editType } + ], + dflt: [0, 1] + }; + var namePart = opts.name ? opts.name + " " : ""; + var contPart = opts.trace ? "trace " : "subplot "; + var descPart = extra.description ? " " + extra.description : ""; + var out = { + x: extendFlat$9({}, base, { + description: [ + "Sets the horizontal domain of this ", + namePart, + contPart, + "(in plot fraction).", + descPart + ].join("") + }), + y: extendFlat$9({}, base, { + description: [ + "Sets the vertical domain of this ", + namePart, + contPart, + "(in plot fraction).", + descPart + ].join("") + }), + editType: opts.editType + }; + if (!opts.noGridCell) { + out.row = { + valType: "integer", + min: 0, + dflt: 0, + editType: opts.editType, + description: [ + "If there is a layout grid, use the domain ", + "for this row in the grid for this ", + namePart, + contPart, + ".", + descPart + ].join("") + }; + out.column = { + valType: "integer", + min: 0, + dflt: 0, + editType: opts.editType, + description: [ + "If there is a layout grid, use the domain ", + "for this column in the grid for this ", + namePart, + contPart, + ".", + descPart + ].join("") + }; + } + return out; +}; +domain.defaults = function(containerOut, layout, coerce2, dfltDomains) { + var dfltX = dfltDomains && dfltDomains.x || [0, 1]; + var dfltY = dfltDomains && dfltDomains.y || [0, 1]; + var grid2 = layout.grid; + if (grid2) { + var column = coerce2("domain.column"); + if (column !== void 0) { + if (column < grid2.columns) dfltX = grid2._domains.x[column]; + else delete containerOut.domain.column; + } + var row = coerce2("domain.row"); + if (row !== void 0) { + if (row < grid2.rows) dfltY = grid2._domains.y[row]; + else delete containerOut.domain.row; + } + } + var x = coerce2("domain.x", dfltX); + var y = coerce2("domain.y", dfltY); + if (!(x[0] < x[1])) containerOut.domain.x = dfltX.slice(); + if (!(y[0] < y[1])) containerOut.domain.y = dfltY.slice(); +}; +var Lib$A = libExports; +var counterRegex = regex.counter; +var domainAttrs$3 = domain.attributes; +var cartesianIdRegex = constants$U.idRegex; +var Template = plot_template; +var gridAttrs = { + rows: { + valType: "integer", + min: 1, + editType: "plot", + description: [ + "The number of rows in the grid. If you provide a 2D `subplots`", + "array or a `yaxes` array, its length is used as the default.", + "But it's also possible to have a different length, if you", + "want to leave a row at the end for non-cartesian subplots." + ].join(" ") + }, + roworder: { + valType: "enumerated", + values: ["top to bottom", "bottom to top"], + dflt: "top to bottom", + editType: "plot", + description: [ + "Is the first row the top or the bottom? Note that columns", + "are always enumerated from left to right." + ].join(" ") + }, + columns: { + valType: "integer", + min: 1, + editType: "plot", + description: [ + "The number of columns in the grid. If you provide a 2D `subplots`", + "array, the length of its longest row is used as the default.", + "If you give an `xaxes` array, its length is used as the default.", + "But it's also possible to have a different length, if you", + "want to leave a row at the end for non-cartesian subplots." + ].join(" ") + }, + subplots: { + valType: "info_array", + freeLength: true, + dimensions: 2, + items: { valType: "enumerated", values: [counterRegex("xy").toString(), ""], editType: "plot" }, + editType: "plot", + description: [ + "Used for freeform grids, where some axes may be shared across subplots", + "but others are not. Each entry should be a cartesian subplot id, like", + "*xy* or *x3y2*, or ** to leave that cell empty. You may reuse x axes", + "within the same column, and y axes within the same row.", + "Non-cartesian subplots and traces that support `domain` can place themselves", + "in this grid separately using the `gridcell` attribute." + ].join(" ") + }, + xaxes: { + valType: "info_array", + freeLength: true, + items: { valType: "enumerated", values: [cartesianIdRegex.x.toString(), ""], editType: "plot" }, + editType: "plot", + description: [ + "Used with `yaxes` when the x and y axes are shared across columns and rows.", + "Each entry should be an x axis id like *x*, *x2*, etc., or ** to", + "not put an x axis in that column. Entries other than ** must be unique.", + "Ignored if `subplots` is present. If missing but `yaxes` is present,", + "will generate consecutive IDs." + ].join(" ") + }, + yaxes: { + valType: "info_array", + freeLength: true, + items: { valType: "enumerated", values: [cartesianIdRegex.y.toString(), ""], editType: "plot" }, + editType: "plot", + description: [ + "Used with `yaxes` when the x and y axes are shared across columns and rows.", + "Each entry should be an y axis id like *y*, *y2*, etc., or ** to", + "not put a y axis in that row. Entries other than ** must be unique.", + "Ignored if `subplots` is present. If missing but `xaxes` is present,", + "will generate consecutive IDs." + ].join(" ") + }, + pattern: { + valType: "enumerated", + values: ["independent", "coupled"], + dflt: "coupled", + editType: "plot", + description: [ + "If no `subplots`, `xaxes`, or `yaxes` are given but we do have `rows` and `columns`,", + "we can generate defaults using consecutive axis IDs, in two ways:", + "*coupled* gives one x axis per column and one y axis per row.", + "*independent* uses a new xy pair for each cell, left-to-right across each row", + "then iterating rows according to `roworder`." + ].join(" ") + }, + xgap: { + valType: "number", + min: 0, + max: 1, + editType: "plot", + description: [ + "Horizontal space between grid cells, expressed as a fraction", + "of the total width available to one cell. Defaults to 0.1", + "for coupled-axes grids and 0.2 for independent grids." + ].join(" ") + }, + ygap: { + valType: "number", + min: 0, + max: 1, + editType: "plot", + description: [ + "Vertical space between grid cells, expressed as a fraction", + "of the total height available to one cell. Defaults to 0.1", + "for coupled-axes grids and 0.3 for independent grids." + ].join(" ") + }, + domain: domainAttrs$3({ name: "grid", editType: "plot", noGridCell: true }, { + description: [ + "The first and last cells end exactly at the domain", + "edges, with no grout around the edges." + ].join(" ") + }), + xside: { + valType: "enumerated", + values: ["bottom", "bottom plot", "top plot", "top"], + dflt: "bottom plot", + editType: "plot", + description: [ + "Sets where the x axis labels and titles go. *bottom* means", + "the very bottom of the grid. *bottom plot* is the lowest plot", + "that each x axis is used in. *top* and *top plot* are similar." + ].join(" ") + }, + yside: { + valType: "enumerated", + values: ["left", "left plot", "right plot", "right"], + dflt: "left plot", + editType: "plot", + description: [ + "Sets where the y axis labels and titles go. *left* means", + "the very left edge of the grid. *left plot* is the leftmost plot", + "that each y axis is used in. *right* and *right plot* are similar." + ].join(" ") + }, + editType: "plot" +}; +function getAxes(layout, grid2, axLetter) { + var gridVal = grid2[axLetter + "axes"]; + var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); + if (Array.isArray(gridVal)) return gridVal; + if (splomVal.length) return splomVal; +} +function sizeDefaults(layoutIn, layoutOut) { + var gridIn = layoutIn.grid || {}; + var xAxes = getAxes(layoutOut, gridIn, "x"); + var yAxes = getAxes(layoutOut, gridIn, "y"); + if (!layoutIn.grid && !xAxes && !yAxes) return; + var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); + var hasXaxes = Array.isArray(xAxes); + var hasYaxes = Array.isArray(yAxes); + var isSplomGenerated = hasXaxes && xAxes !== gridIn.xaxes && hasYaxes && yAxes !== gridIn.yaxes; + var dfltRows, dfltColumns; + if (hasSubplotGrid) { + dfltRows = gridIn.subplots.length; + dfltColumns = gridIn.subplots[0].length; + } else { + if (hasYaxes) dfltRows = yAxes.length; + if (hasXaxes) dfltColumns = xAxes.length; + } + var gridOut = Template.newContainer(layoutOut, "grid"); + function coerce2(attr, dflt) { + return Lib$A.coerce(gridIn, gridOut, gridAttrs, attr, dflt); + } + var rows = coerce2("rows", dfltRows); + var columns = coerce2("columns", dfltColumns); + if (!(rows * columns > 1)) { + delete layoutOut.grid; + return; + } + if (!hasSubplotGrid && !hasXaxes && !hasYaxes) { + var useDefaultSubplots = coerce2("pattern") === "independent"; + if (useDefaultSubplots) hasSubplotGrid = true; + } + gridOut._hasSubplotGrid = hasSubplotGrid; + var rowOrder = coerce2("roworder"); + var reversed = rowOrder === "top to bottom"; + var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; + var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; + var dfltSideX, dfltSideY; + if (isSplomGenerated && layoutOut._splomGridDflt) { + dfltSideX = layoutOut._splomGridDflt.xside; + dfltSideY = layoutOut._splomGridDflt.yside; + } + gridOut._domains = { + x: fillGridPositions("x", coerce2, dfltGapX, dfltSideX, columns), + y: fillGridPositions("y", coerce2, dfltGapY, dfltSideY, rows, reversed) + }; +} +function fillGridPositions(axLetter, coerce2, dfltGap, dfltSide, len, reversed) { + var dirGap = coerce2(axLetter + "gap", dfltGap); + var domain2 = coerce2("domain." + axLetter); + coerce2(axLetter + "side", dfltSide); + var out = new Array(len); + var start = domain2[0]; + var step = (domain2[1] - start) / (len - dirGap); + var cellDomain = step * (1 - dirGap); + for (var i = 0; i < len; i++) { + var cellStart = start + step * i; + out[reversed ? len - 1 - i : i] = [cellStart, cellStart + cellDomain]; + } + return out; +} +function contentDefaults(layoutIn, layoutOut) { + var gridOut = layoutOut.grid; + if (!gridOut || !gridOut._domains) return; + var gridIn = layoutIn.grid || {}; + var subplots = layoutOut._subplots; + var hasSubplotGrid = gridOut._hasSubplotGrid; + var rows = gridOut.rows; + var columns = gridOut.columns; + var useDefaultSubplots = gridOut.pattern === "independent"; + var i, j, xId, yId, subplotId, subplotsOut, yPos; + var axisMap = gridOut._axisMap = {}; + if (hasSubplotGrid) { + var subplotsIn = gridIn.subplots || []; + subplotsOut = gridOut.subplots = new Array(rows); + var index2 = 1; + for (i = 0; i < rows; i++) { + var rowOut = subplotsOut[i] = new Array(columns); + var rowIn = subplotsIn[i] || []; + for (j = 0; j < columns; j++) { + if (useDefaultSubplots) { + subplotId = index2 === 1 ? "xy" : "x" + index2 + "y" + index2; + index2++; + } else subplotId = rowIn[j]; + rowOut[j] = ""; + if (subplots.cartesian.indexOf(subplotId) !== -1) { + yPos = subplotId.indexOf("y"); + xId = subplotId.slice(0, yPos); + yId = subplotId.slice(yPos); + if (axisMap[xId] !== void 0 && axisMap[xId] !== j || axisMap[yId] !== void 0 && axisMap[yId] !== i) { + continue; + } + rowOut[j] = subplotId; + axisMap[xId] = j; + axisMap[yId] = i; + } + } + } + } else { + var xAxes = getAxes(layoutOut, gridIn, "x"); + var yAxes = getAxes(layoutOut, gridIn, "y"); + gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, "x"); + gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, "y"); + } + var anchors = gridOut._anchors = {}; + var reversed = gridOut.roworder === "top to bottom"; + for (var axisId in axisMap) { + var axLetter = axisId.charAt(0); + var side = gridOut[axLetter + "side"]; + var i0, inc, iFinal; + if (side.length < 8) { + anchors[axisId] = "free"; + } else if (axLetter === "x") { + if (side.charAt(0) === "t" === reversed) { + i0 = 0; + inc = 1; + iFinal = rows; + } else { + i0 = rows - 1; + inc = -1; + iFinal = -1; + } + if (hasSubplotGrid) { + var column = axisMap[axisId]; + for (i = i0; i !== iFinal; i += inc) { + subplotId = subplotsOut[i][column]; + if (!subplotId) continue; + yPos = subplotId.indexOf("y"); + if (subplotId.slice(0, yPos) === axisId) { + anchors[axisId] = subplotId.slice(yPos); + break; + } + } + } else { + for (i = i0; i !== iFinal; i += inc) { + yId = gridOut.yaxes[i]; + if (subplots.cartesian.indexOf(axisId + yId) !== -1) { + anchors[axisId] = yId; + break; + } + } + } + } else { + if (side.charAt(0) === "l") { + i0 = 0; + inc = 1; + iFinal = columns; + } else { + i0 = columns - 1; + inc = -1; + iFinal = -1; + } + if (hasSubplotGrid) { + var row = axisMap[axisId]; + for (i = i0; i !== iFinal; i += inc) { + subplotId = subplotsOut[row][i]; + if (!subplotId) continue; + yPos = subplotId.indexOf("y"); + if (subplotId.slice(yPos) === axisId) { + anchors[axisId] = subplotId.slice(0, yPos); + break; + } + } + } else { + for (i = i0; i !== iFinal; i += inc) { + xId = gridOut.xaxes[i]; + if (subplots.cartesian.indexOf(xId + axisId) !== -1) { + anchors[axisId] = xId; + break; + } + } + } + } + } +} +function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { + var out = new Array(len); + var i; + function fillOneAxis(i2, axisId) { + if (axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === void 0) { + out[i2] = axisId; + axisMap[axisId] = i2; + } else out[i2] = ""; + } + if (Array.isArray(axesIn)) { + for (i = 0; i < len; i++) { + fillOneAxis(i, axesIn[i]); + } + } else { + fillOneAxis(0, axLetter); + for (i = 1; i < len; i++) { + fillOneAxis(i, axLetter + (i + 1)); + } + } + return out; +} +var grid = { + moduleType: "component", + name: "grid", + schema: { + layout: { grid: gridAttrs } + }, + layoutAttributes: gridAttrs, + sizeDefaults, + contentDefaults +}; +var attributes$g = { + visible: { + valType: "boolean", + editType: "calc", + description: [ + "Determines whether or not this set of error bars is visible." + ].join(" ") + }, + type: { + valType: "enumerated", + values: ["percent", "constant", "sqrt", "data"], + editType: "calc", + description: [ + "Determines the rule used to generate the error bars.", + "If *constant`, the bar lengths are of a constant value.", + "Set this constant in `value`.", + "If *percent*, the bar lengths correspond to a percentage of", + "underlying data. Set this percentage in `value`.", + "If *sqrt*, the bar lengths correspond to the square of the", + "underlying data.", + "If *data*, the bar lengths are set with data set `array`." + ].join(" ") + }, + symmetric: { + valType: "boolean", + editType: "calc", + description: [ + "Determines whether or not the error bars have the same length", + "in both direction", + "(top/bottom for vertical bars, left/right for horizontal bars." + ].join(" ") + }, + array: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the data corresponding the length of each error bar.", + "Values are plotted relative to the underlying data." + ].join(" ") + }, + arrayminus: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the data corresponding the length of each error bar in the", + "bottom (left) direction for vertical (horizontal) bars", + "Values are plotted relative to the underlying data." + ].join(" ") + }, + value: { + valType: "number", + min: 0, + dflt: 10, + editType: "calc", + description: [ + "Sets the value of either the percentage", + "(if `type` is set to *percent*) or the constant", + "(if `type` is set to *constant*) corresponding to the lengths of", + "the error bars." + ].join(" ") + }, + valueminus: { + valType: "number", + min: 0, + dflt: 10, + editType: "calc", + description: [ + "Sets the value of either the percentage", + "(if `type` is set to *percent*) or the constant", + "(if `type` is set to *constant*) corresponding to the lengths of", + "the error bars in the", + "bottom (left) direction for vertical (horizontal) bars" + ].join(" ") + }, + traceref: { + valType: "integer", + min: 0, + dflt: 0, + editType: "style" + }, + tracerefminus: { + valType: "integer", + min: 0, + dflt: 0, + editType: "style" + }, + copy_ystyle: { + valType: "boolean", + editType: "plot" + }, + copy_zstyle: { + valType: "boolean", + editType: "style" + }, + color: { + valType: "color", + editType: "style", + description: "Sets the stoke color of the error bars." + }, + thickness: { + valType: "number", + min: 0, + dflt: 2, + editType: "style", + description: "Sets the thickness (in px) of the error bars." + }, + width: { + valType: "number", + min: 0, + editType: "plot", + description: [ + "Sets the width (in px) of the cross-bar at both ends", + "of the error bars." + ].join(" ") + }, + editType: "calc", + _deprecated: { + opacity: { + valType: "number", + editType: "style", + description: [ + "Obsolete.", + "Use the alpha channel in error bar `color` to set the opacity." + ].join(" ") + } + } +}; +var defaults$7; +var hasRequiredDefaults; +function requireDefaults() { + if (hasRequiredDefaults) return defaults$7; + hasRequiredDefaults = 1; + var isNumeric2 = fastIsnumeric; + var Registry2 = registry; + var Lib2 = libExports; + var Template2 = plot_template; + var attributes2 = attributes$g; + defaults$7 = function(traceIn, traceOut, defaultColor, opts) { + var objName = "error_" + opts.axis; + var containerOut = Template2.newContainer(traceOut, objName); + var containerIn = traceIn[objName] || {}; + function coerce2(attr, dflt) { + return Lib2.coerce(containerIn, containerOut, attributes2, attr, dflt); + } + var hasErrorBars = containerIn.array !== void 0 || containerIn.value !== void 0 || containerIn.type === "sqrt"; + var visible = coerce2("visible", hasErrorBars); + if (visible === false) return; + var type = coerce2("type", "array" in containerIn ? "data" : "percent"); + var symmetric = true; + if (type !== "sqrt") { + symmetric = coerce2( + "symmetric", + !((type === "data" ? "arrayminus" : "valueminus") in containerIn) + ); + } + if (type === "data") { + coerce2("array"); + coerce2("traceref"); + if (!symmetric) { + coerce2("arrayminus"); + coerce2("tracerefminus"); + } + } else if (type === "percent" || type === "constant") { + coerce2("value"); + if (!symmetric) coerce2("valueminus"); + } + var copyAttr = "copy_" + opts.inherit + "style"; + if (opts.inherit) { + var inheritObj = traceOut["error_" + opts.inherit]; + if ((inheritObj || {}).visible) { + coerce2(copyAttr, !(containerIn.color || isNumeric2(containerIn.thickness) || isNumeric2(containerIn.width))); + } + } + if (!opts.inherit || !containerOut[copyAttr]) { + coerce2("color", defaultColor); + coerce2("thickness"); + coerce2("width", Registry2.traceIs(traceOut, "gl3d") ? 0 : 4); + } + }; + return defaults$7; +} +var compute_error; +var hasRequiredCompute_error; +function requireCompute_error() { + if (hasRequiredCompute_error) return compute_error; + hasRequiredCompute_error = 1; + compute_error = function makeComputeError(opts) { + var type = opts.type; + var symmetric = opts.symmetric; + if (type === "data") { + var array2 = opts.array || []; + if (symmetric) { + return function computeError(dataPt, index2) { + var val = +array2[index2]; + return [val, val]; + }; + } else { + var arrayminus = opts.arrayminus || []; + return function computeError(dataPt, index2) { + var val = +array2[index2]; + var valMinus = +arrayminus[index2]; + if (!isNaN(val) || !isNaN(valMinus)) { + return [valMinus || 0, val || 0]; + } + return [NaN, NaN]; + }; + } + } else { + var computeErrorValue = makeComputeErrorValue(type, opts.value); + var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); + if (symmetric || opts.valueminus === void 0) { + return function computeError(dataPt) { + var val = computeErrorValue(dataPt); + return [val, val]; + }; + } else { + return function computeError(dataPt) { + return [ + computeErrorValueMinus(dataPt), + computeErrorValue(dataPt) + ]; + }; + } + } + }; + function makeComputeErrorValue(type, value2) { + if (type === "percent") { + return function(dataPt) { + return Math.abs(dataPt * value2 / 100); + }; + } + if (type === "constant") { + return function() { + return Math.abs(value2); + }; + } + if (type === "sqrt") { + return function(dataPt) { + return Math.sqrt(Math.abs(dataPt)); + }; + } + } + return compute_error; +} +var calc$8; +var hasRequiredCalc; +function requireCalc() { + if (hasRequiredCalc) return calc$8; + hasRequiredCalc = 1; + var isNumeric2 = fastIsnumeric; + var Registry2 = registry; + var Axes2 = axesExports; + var Lib2 = libExports; + var makeComputeError = requireCompute_error(); + calc$8 = function calc6(gd) { + var calcdata = gd.calcdata; + for (var i = 0; i < calcdata.length; i++) { + var calcTrace = calcdata[i]; + var trace = calcTrace[0].trace; + if (trace.visible === true && Registry2.traceIs(trace, "errorBarsOK")) { + var xa = Axes2.getFromId(gd, trace.xaxis); + var ya = Axes2.getFromId(gd, trace.yaxis); + calcOneAxis(calcTrace, trace, xa, "x"); + calcOneAxis(calcTrace, trace, ya, "y"); + } + } + }; + function calcOneAxis(calcTrace, trace, axis, coord) { + var opts = trace["error_" + coord] || {}; + var isVisible2 = opts.visible && ["linear", "log"].indexOf(axis.type) !== -1; + var vals = []; + if (!isVisible2) return; + var computeError = makeComputeError(opts); + for (var i = 0; i < calcTrace.length; i++) { + var calcPt = calcTrace[i]; + var iIn = calcPt.i; + if (iIn === void 0) iIn = i; + else if (iIn === null) continue; + var calcCoord = calcPt[coord]; + if (!isNumeric2(axis.c2l(calcCoord))) continue; + var errors = computeError(calcCoord, iIn); + if (isNumeric2(errors[0]) && isNumeric2(errors[1])) { + var shoe = calcPt[coord + "s"] = calcCoord - errors[0]; + var hat = calcPt[coord + "h"] = calcCoord + errors[1]; + vals.push(shoe, hat); + } + } + var axId = axis._id; + var baseExtremes = trace._extremes[axId]; + var extremes = Axes2.findExtremes( + axis, + vals, + Lib2.extendFlat({ tozero: baseExtremes.opts.tozero }, { padded: true }) + ); + baseExtremes.min = baseExtremes.min.concat(extremes.min); + baseExtremes.max = baseExtremes.max.concat(extremes.max); + } + return calc$8; +} +var plot$6; +var hasRequiredPlot; +function requirePlot() { + if (hasRequiredPlot) return plot$6; + hasRequiredPlot = 1; + var d32 = d3Exports; + var isNumeric2 = fastIsnumeric; + var Drawing2 = drawingExports; + var subTypes2 = subtypes$3; + plot$6 = function plot5(gd, traces, plotinfo, transitionOpts) { + var isNew; + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var hasAnimation = transitionOpts && transitionOpts.duration > 0; + var isStatic = gd._context.staticPlot; + traces.each(function(d) { + var trace = d[0].trace; + var xObj = trace.error_x || {}; + var yObj = trace.error_y || {}; + var keyFunc2; + if (trace.ids) { + keyFunc2 = function(d2) { + return d2.id; + }; + } + var sparse = subTypes2.hasMarkers(trace) && trace.marker.maxdisplayed > 0; + if (!yObj.visible && !xObj.visible) d = []; + var errorbars2 = d32.select(this).selectAll("g.errorbar").data(d, keyFunc2); + errorbars2.exit().remove(); + if (!d.length) return; + if (!xObj.visible) errorbars2.selectAll("path.xerror").remove(); + if (!yObj.visible) errorbars2.selectAll("path.yerror").remove(); + errorbars2.style("opacity", 1); + var enter = errorbars2.enter().append("g").classed("errorbar", true); + if (hasAnimation) { + enter.style("opacity", 0).transition().duration(transitionOpts.duration).style("opacity", 1); + } + Drawing2.setClipUrl(errorbars2, plotinfo.layerClipId, gd); + errorbars2.each(function(d2) { + var errorbar = d32.select(this); + var coords = errorCoords(d2, xa, ya); + if (sparse && !d2.vis) return; + var path; + var yerror = errorbar.select("path.yerror"); + if (yObj.visible && isNumeric2(coords.x) && isNumeric2(coords.yh) && isNumeric2(coords.ys)) { + var yw = yObj.width; + path = "M" + (coords.x - yw) + "," + coords.yh + "h" + 2 * yw + // hat + "m-" + yw + ",0V" + coords.ys; + if (!coords.noYS) path += "m-" + yw + ",0h" + 2 * yw; + isNew = !yerror.size(); + if (isNew) { + yerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("yerror", true); + } else if (hasAnimation) { + yerror = yerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing); + } + yerror.attr("d", path); + } else yerror.remove(); + var xerror = errorbar.select("path.xerror"); + if (xObj.visible && isNumeric2(coords.y) && isNumeric2(coords.xh) && isNumeric2(coords.xs)) { + var xw = (xObj.copy_ystyle ? yObj : xObj).width; + path = "M" + coords.xh + "," + (coords.y - xw) + "v" + 2 * xw + // hat + "m0,-" + xw + "H" + coords.xs; + if (!coords.noXS) path += "m0,-" + xw + "v" + 2 * xw; + isNew = !xerror.size(); + if (isNew) { + xerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("xerror", true); + } else if (hasAnimation) { + xerror = xerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing); + } + xerror.attr("d", path); + } else xerror.remove(); + }); + }); + }; + function errorCoords(d, xa, ya) { + var out = { + x: xa.c2p(d.x), + y: ya.c2p(d.y) + }; + if (d.yh !== void 0) { + out.yh = ya.c2p(d.yh); + out.ys = ya.c2p(d.ys); + if (!isNumeric2(out.ys)) { + out.noYS = true; + out.ys = ya.c2p(d.ys, true); + } + } + if (d.xh !== void 0) { + out.xh = xa.c2p(d.xh); + out.xs = xa.c2p(d.xs); + if (!isNumeric2(out.xs)) { + out.noXS = true; + out.xs = xa.c2p(d.xs, true); + } + } + return out; + } + return plot$6; +} +var style$5; +var hasRequiredStyle; +function requireStyle() { + if (hasRequiredStyle) return style$5; + hasRequiredStyle = 1; + var d32 = d3Exports; + var Color2 = colorExports; + style$5 = function style5(traces) { + traces.each(function(d) { + var trace = d[0].trace; + var yObj = trace.error_y || {}; + var xObj = trace.error_x || {}; + var s = d32.select(this); + s.selectAll("path.yerror").style("stroke-width", yObj.thickness + "px").call(Color2.stroke, yObj.color); + if (xObj.copy_ystyle) xObj = yObj; + s.selectAll("path.xerror").style("stroke-width", xObj.thickness + "px").call(Color2.stroke, xObj.color); + }); + }; + return style$5; +} +var Lib$z = libExports; +var overrideAll$1 = edit_types.overrideAll; +var attributes$f = attributes$g; +var xyAttrs = { + error_x: Lib$z.extendFlat({}, attributes$f), + error_y: Lib$z.extendFlat({}, attributes$f) +}; +delete xyAttrs.error_x.copy_zstyle; +delete xyAttrs.error_y.copy_zstyle; +delete xyAttrs.error_y.copy_ystyle; +var xyzAttrs = { + error_x: Lib$z.extendFlat({}, attributes$f), + error_y: Lib$z.extendFlat({}, attributes$f), + error_z: Lib$z.extendFlat({}, attributes$f) +}; +delete xyzAttrs.error_x.copy_ystyle; +delete xyzAttrs.error_y.copy_ystyle; +delete xyzAttrs.error_z.copy_ystyle; +delete xyzAttrs.error_z.copy_zstyle; +var errorbars = { + moduleType: "component", + name: "errorbars", + schema: { + traces: { + scatter: xyAttrs, + bar: xyAttrs, + histogram: xyAttrs, + scatter3d: overrideAll$1(xyzAttrs, "calc", "nested"), + scattergl: overrideAll$1(xyAttrs, "calc", "nested") + } + }, + supplyDefaults: requireDefaults(), + calc: requireCalc(), + makeComputeError: requireCompute_error(), + plot: requirePlot(), + style: requireStyle(), + hoverInfo +}; +function hoverInfo(calcPoint, trace, hoverPoint) { + if ((trace.error_y || {}).visible) { + hoverPoint.yerr = calcPoint.yh - calcPoint.y; + if (!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys; + } + if ((trace.error_x || {}).visible) { + hoverPoint.xerr = calcPoint.xh - calcPoint.x; + if (!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs; + } +} +var constants$g = { + cn: { + colorbar: "colorbar", + cbbg: "cbbg", + cbfill: "cbfill", + cbfills: "cbfills", + cbline: "cbline", + cblines: "cblines", + cbaxis: "cbaxis", + cbtitleunshift: "cbtitleunshift", + cbtitle: "cbtitle", + cboutline: "cboutline", + crisp: "crisp", + jsPlaceholder: "js-placeholder" + } +}; +var d3$d = d3Exports; +var tinycolor$2 = tinycolorExports; +var Plots$1 = plotsExports; +var Registry$e = registry; +var Axes$5 = axesExports; +var dragElement = dragelementExports; +var Lib$y = libExports; +var strTranslate$1 = Lib$y.strTranslate; +var extendFlat$8 = extend$5.extendFlat; +var setCursor2 = setcursor; +var Drawing$8 = drawingExports; +var Color$h = colorExports; +var Titles = titles; +var svgTextUtils$4 = svg_text_utils; +var flipScale = helpers$L.flipScale; +var handleAxisDefaults2 = axis_defaults; +var handleAxisPositionDefaults = position_defaults; +var axisLayoutAttrs = layout_attributes$4; +var alignmentConstants = alignment$1; +var LINE_SPACING = alignmentConstants.LINE_SPACING; +var FROM_TL = alignmentConstants.FROM_TL; +var FROM_BR = alignmentConstants.FROM_BR; +var cn = constants$g.cn; +function draw$2(gd) { + var fullLayout = gd._fullLayout; + var colorBars = fullLayout._infolayer.selectAll("g." + cn.colorbar).data(makeColorBarData(gd), function(opts) { + return opts._id; + }); + colorBars.enter().append("g").attr("class", function(opts) { + return opts._id; + }).classed(cn.colorbar, true); + colorBars.each(function(opts) { + var g = d3$d.select(this); + Lib$y.ensureSingle(g, "rect", cn.cbbg); + Lib$y.ensureSingle(g, "g", cn.cbfills); + Lib$y.ensureSingle(g, "g", cn.cblines); + Lib$y.ensureSingle(g, "g", cn.cbaxis, function(s) { + s.classed(cn.crisp, true); + }); + Lib$y.ensureSingle(g, "g", cn.cbtitleunshift, function(s) { + s.append("g").classed(cn.cbtitle, true); + }); + Lib$y.ensureSingle(g, "rect", cn.cboutline); + var done = drawColorBar(g, opts, gd); + if (done && done.then) (gd._promises || []).push(done); + if (gd._context.edits.colorbarPosition) { + makeEditable(g, opts, gd); + } + }); + colorBars.exit().each(function(opts) { + Plots$1.autoMargin(gd, opts._id); + }).remove(); + colorBars.order(); +} +function makeColorBarData(gd) { + var fullLayout = gd._fullLayout; + var calcdata = gd.calcdata; + var out = []; + var opts; + var cont; + var trace; + var cbOpt; + function initOpts(opts2) { + return extendFlat$8(opts2, { + // fillcolor can be a d3 scale, domain is z values, range is colors + // or leave it out for no fill, + // or set to a string constant for single-color fill + _fillcolor: null, + // line.color has the same options as fillcolor + _line: { color: null, width: null, dash: null }, + // levels of lines to draw. + // note that this DOES NOT determine the extent of the bar + // that's given by the domain of fillcolor + // (or line.color if no fillcolor domain) + _levels: { start: null, end: null, size: null }, + // separate fill levels (for example, heatmap coloring of a + // contour map) if this is omitted, fillcolors will be + // evaluated halfway between levels + _filllevels: null, + // for continuous colorscales: fill with a gradient instead of explicit levels + // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]] + _fillgradient: null, + // when using a gradient, we need the data range specified separately + _zrange: null + }); + } + function calcOpts() { + if (typeof cbOpt.calc === "function") { + cbOpt.calc(gd, trace, opts); + } else { + opts._fillgradient = cont.reversescale ? flipScale(cont.colorscale) : cont.colorscale; + opts._zrange = [cont[cbOpt.min], cont[cbOpt.max]]; + } + } + for (var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + trace = cd[0].trace; + if (!trace._module) continue; + var moduleOpts = trace._module.colorbar; + if (trace.visible === true && moduleOpts) { + var allowsMultiplotCbs = Array.isArray(moduleOpts); + var cbOpts = allowsMultiplotCbs ? moduleOpts : [moduleOpts]; + for (var j = 0; j < cbOpts.length; j++) { + cbOpt = cbOpts[j]; + var contName = cbOpt.container; + cont = contName ? trace[contName] : trace; + if (cont && cont.showscale) { + opts = initOpts(cont.colorbar); + opts._id = "cb" + trace.uid + (allowsMultiplotCbs && contName ? "-" + contName : ""); + opts._traceIndex = trace.index; + opts._propPrefix = (contName ? contName + "." : "") + "colorbar."; + opts._meta = trace._meta; + calcOpts(); + out.push(opts); + } + } + } + } + for (var k in fullLayout._colorAxes) { + cont = fullLayout[k]; + if (cont.showscale) { + var colorAxOpts = fullLayout._colorAxes[k]; + opts = initOpts(cont.colorbar); + opts._id = "cb" + k; + opts._propPrefix = k + ".colorbar."; + opts._meta = fullLayout._meta; + cbOpt = { min: "cmin", max: "cmax" }; + if (colorAxOpts[0] !== "heatmap") { + trace = colorAxOpts[1]; + cbOpt.calc = trace._module.colorbar.calc; + } + calcOpts(); + out.push(opts); + } + } + return out; +} +function drawColorBar(g, opts, gd) { + var isVertical2 = opts.orientation === "v"; + var len = opts.len; + var lenmode = opts.lenmode; + var thickness = opts.thickness; + var thicknessmode = opts.thicknessmode; + var outlinewidth = opts.outlinewidth; + var borderwidth = opts.borderwidth; + var bgcolor = opts.bgcolor; + var xanchor = opts.xanchor; + var yanchor = opts.yanchor; + var xpad = opts.xpad; + var ypad = opts.ypad; + var optsX = opts.x; + var optsY = isVertical2 ? opts.y : 1 - opts.y; + var isPaperY = opts.yref === "paper"; + var isPaperX = opts.xref === "paper"; + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var fillColor = opts._fillcolor; + var line2 = opts._line; + var title = opts.title; + var titleSide = title.side; + var zrange = opts._zrange || d3$d.extent((typeof fillColor === "function" ? fillColor : line2.color).domain()); + var lineColormap = typeof line2.color === "function" ? line2.color : function() { + return line2.color; + }; + var fillColormap = typeof fillColor === "function" ? fillColor : function() { + return fillColor; + }; + var levelsIn = opts._levels; + var levelsOut = calcLevels(gd, opts, zrange); + var fillLevels = levelsOut.fill; + var lineLevels = levelsOut.line; + var thickPx = Math.round(thickness * (thicknessmode === "fraction" ? isVertical2 ? gs.w : gs.h : 1)); + var thickFrac = thickPx / (isVertical2 ? gs.w : gs.h); + var lenPx = Math.round(len * (lenmode === "fraction" ? isVertical2 ? gs.h : gs.w : 1)); + var lenFrac = lenPx / (isVertical2 ? gs.h : gs.w); + var posW = isPaperX ? gs.w : gd._fullLayout.width; + var posH = isPaperY ? gs.h : gd._fullLayout.height; + var uPx = Math.round( + isVertical2 ? optsX * posW + xpad : optsY * posH + ypad + ); + var xRatio = { center: 0.5, right: 1 }[xanchor] || 0; + var yRatio = { top: 1, middle: 0.5 }[yanchor] || 0; + var uFrac = isVertical2 ? optsX - xRatio * thickFrac : optsY - yRatio * thickFrac; + var vFrac = isVertical2 ? optsY - yRatio * lenFrac : optsX - xRatio * lenFrac; + var vPx = Math.round( + isVertical2 ? posH * (1 - vFrac) : posW * vFrac + ); + opts._lenFrac = lenFrac; + opts._thickFrac = thickFrac; + opts._uFrac = uFrac; + opts._vFrac = vFrac; + var ax = opts._axis = mockColorBarAxis(gd, opts, zrange); + ax.position = thickFrac + (isVertical2 ? optsX + xpad / gs.w : optsY + ypad / gs.h); + var topOrBottom = ["top", "bottom"].indexOf(titleSide) !== -1; + if (isVertical2 && topOrBottom) { + ax.title.side = titleSide; + ax.titlex = optsX + xpad / gs.w; + ax.titley = vFrac + (title.side === "top" ? lenFrac - ypad / gs.h : ypad / gs.h); + } + if (!isVertical2 && !topOrBottom) { + ax.title.side = titleSide; + ax.titley = optsY + ypad / gs.h; + ax.titlex = vFrac + xpad / gs.w; + } + if (line2.color && opts.tickmode === "auto") { + ax.tickmode = "linear"; + ax.tick0 = levelsIn.start; + var dtick2 = levelsIn.size; + var autoNtick = Lib$y.constrain(lenPx / 50, 4, 15) + 1; + var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick2); + if (dtFactor > 1) { + var dtexp = Math.pow(10, Math.floor(Math.log(dtFactor) / Math.LN10)); + dtick2 *= dtexp * Lib$y.roundUp(dtFactor / dtexp, [2, 5, 10]); + if ((Math.abs(levelsIn.start) / levelsIn.size + 1e-6) % 1 < 2e-6) { + ax.tick0 = 0; + } + } + ax.dtick = dtick2; + } + ax.domain = isVertical2 ? [ + vFrac + ypad / gs.h, + vFrac + lenFrac - ypad / gs.h + ] : [ + vFrac + xpad / gs.w, + vFrac + lenFrac - xpad / gs.w + ]; + ax.setScale(); + g.attr("transform", strTranslate$1(Math.round(gs.l), Math.round(gs.t))); + var titleCont = g.select("." + cn.cbtitleunshift).attr("transform", strTranslate$1(-Math.round(gs.l), -Math.round(gs.t))); + var ticklabelposition = ax.ticklabelposition; + var titleFontSize = ax.title.font.size; + var axLayer = g.select("." + cn.cbaxis); + var titleEl; + var titleHeight = 0; + var titleWidth = 0; + function drawTitle2(titleClass, titleOpts) { + var dfltTitleOpts = { + propContainer: ax, + propName: opts._propPrefix + "title", + traceIndex: opts._traceIndex, + _meta: opts._meta, + placeholder: fullLayout._dfltTitle.colorbar, + containerGroup: g.select("." + cn.cbtitle) + }; + var otherClass = titleClass.charAt(0) === "h" ? titleClass.substr(1) : "h" + titleClass; + g.selectAll("." + otherClass + ",." + otherClass + "-math-group").remove(); + Titles.draw(gd, titleClass, extendFlat$8(dfltTitleOpts, titleOpts || {})); + } + function drawDummyTitle() { + if (isVertical2 && topOrBottom || !isVertical2 && !topOrBottom) { + var x, y; + if (titleSide === "top") { + x = xpad + gs.l + posW * optsX; + y = ypad + gs.t + posH * (1 - vFrac - lenFrac) + 3 + titleFontSize * 0.75; + } + if (titleSide === "bottom") { + x = xpad + gs.l + posW * optsX; + y = ypad + gs.t + posH * (1 - vFrac) - 3 - titleFontSize * 0.25; + } + if (titleSide === "right") { + y = ypad + gs.t + posH * optsY + 3 + titleFontSize * 0.75; + x = xpad + gs.l + posW * vFrac; + } + drawTitle2(ax._id + "title", { + attributes: { x, y, "text-anchor": isVertical2 ? "start" : "middle" } + }); + } + } + function drawCbTitle() { + if (isVertical2 && !topOrBottom || !isVertical2 && topOrBottom) { + var pos = ax.position || 0; + var mid = ax._offset + ax._length / 2; + var x, y; + if (titleSide === "right") { + y = mid; + x = gs.l + posW * pos + 10 + titleFontSize * (ax.showticklabels ? 1 : 0.5); + } else { + x = mid; + if (titleSide === "bottom") { + y = gs.t + posH * pos + 10 + (ticklabelposition.indexOf("inside") === -1 ? ax.tickfont.size : 0) + (ax.ticks !== "intside" ? opts.ticklen || 0 : 0); + } + if (titleSide === "top") { + var nlines = title.text.split("
").length; + y = gs.t + posH * pos + 10 - thickPx - LINE_SPACING * titleFontSize * nlines; + } + } + drawTitle2((isVertical2 ? ( + // the 'h' + is a hack to get around the fact that + // convertToTspans rotates any 'y...' class by 90 degrees. + // TODO: find a better way to control this. + "h" + ) : "v") + ax._id + "title", { + avoid: { + selection: d3$d.select(gd).selectAll("g." + ax._id + "tick"), + side: titleSide, + offsetTop: isVertical2 ? 0 : gs.t, + offsetLeft: isVertical2 ? gs.l : 0, + maxShift: isVertical2 ? fullLayout.width : fullLayout.height + }, + attributes: { x, y, "text-anchor": "middle" }, + transform: { rotate: isVertical2 ? -90 : 0, offset: 0 } + }); + } + } + function drawAxis() { + if (!isVertical2 && !topOrBottom || isVertical2 && topOrBottom) { + var titleGroup = g.select("." + cn.cbtitle); + var titleText = titleGroup.select("text"); + var titleTrans = [-outlinewidth / 2, outlinewidth / 2]; + var mathJaxNode = titleGroup.select(".h" + ax._id + "title-math-group").node(); + var lineSize = 15.6; + if (titleText.node()) { + lineSize = parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING; + } + var bb; + if (mathJaxNode) { + bb = Drawing$8.bBox(mathJaxNode); + titleWidth = bb.width; + titleHeight = bb.height; + if (titleHeight > lineSize) { + titleTrans[1] -= (titleHeight - lineSize) / 2; + } + } else if (titleText.node() && !titleText.classed(cn.jsPlaceholder)) { + bb = Drawing$8.bBox(titleText.node()); + titleWidth = bb.width; + titleHeight = bb.height; + } + if (isVertical2) { + if (titleHeight) { + titleHeight += 5; + if (titleSide === "top") { + ax.domain[1] -= titleHeight / gs.h; + titleTrans[1] *= -1; + } else { + ax.domain[0] += titleHeight / gs.h; + var nlines = svgTextUtils$4.lineCount(titleText); + titleTrans[1] += (1 - nlines) * lineSize; + } + titleGroup.attr("transform", strTranslate$1(titleTrans[0], titleTrans[1])); + ax.setScale(); + } + } else { + if (titleWidth) { + if (titleSide === "right") { + ax.domain[0] += (titleWidth + titleFontSize / 2) / gs.w; + } + titleGroup.attr("transform", strTranslate$1(titleTrans[0], titleTrans[1])); + ax.setScale(); + } + } + } + g.selectAll("." + cn.cbfills + ",." + cn.cblines).attr( + "transform", + isVertical2 ? strTranslate$1(0, Math.round(gs.h * (1 - ax.domain[1]))) : strTranslate$1(Math.round(gs.w * ax.domain[0]), 0) + ); + axLayer.attr( + "transform", + isVertical2 ? strTranslate$1(0, Math.round(-gs.t)) : strTranslate$1(Math.round(-gs.l), 0) + ); + var fills = g.select("." + cn.cbfills).selectAll("rect." + cn.cbfill).attr("style", "").data(fillLevels); + fills.enter().append("rect").classed(cn.cbfill, true).attr("style", ""); + fills.exit().remove(); + var zBounds = zrange.map(ax.c2p).map(Math.round).sort(function(a, b) { + return a - b; + }); + fills.each(function(d, i) { + var z = [ + i === 0 ? zrange[0] : (fillLevels[i] + fillLevels[i - 1]) / 2, + i === fillLevels.length - 1 ? zrange[1] : (fillLevels[i] + fillLevels[i + 1]) / 2 + ].map(ax.c2p).map(Math.round); + if (isVertical2) { + z[1] = Lib$y.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]); + } + var fillEl = d3$d.select(this).attr(isVertical2 ? "x" : "y", uPx).attr(isVertical2 ? "y" : "x", d3$d.min(z)).attr(isVertical2 ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical2 ? "height" : "width", Math.max(d3$d.max(z) - d3$d.min(z), 2)); + if (opts._fillgradient) { + Drawing$8.gradient(fillEl, gd, opts._id, isVertical2 ? "vertical" : "horizontalreversed", opts._fillgradient, "fill"); + } else { + var colorString = fillColormap(d).replace("e-", ""); + fillEl.attr("fill", tinycolor$2(colorString).toHexString()); + } + }); + var lines = g.select("." + cn.cblines).selectAll("path." + cn.cbline).data(line2.color && line2.width ? lineLevels : []); + lines.enter().append("path").classed(cn.cbline, true); + lines.exit().remove(); + lines.each(function(d) { + var a = uPx; + var b = Math.round(ax.c2p(d)) + line2.width / 2 % 1; + d3$d.select(this).attr( + "d", + "M" + (isVertical2 ? a + "," + b : b + "," + a) + (isVertical2 ? "h" : "v") + thickPx + ).call(Drawing$8.lineGroupStyle, line2.width, lineColormap(d), line2.dash); + }); + axLayer.selectAll("g." + ax._id + "tick,path").remove(); + var shift = uPx + thickPx + (outlinewidth || 0) / 2 - (opts.ticks === "outside" ? 1 : 0); + var vals = Axes$5.calcTicks(ax); + var tickSign = Axes$5.getTickSigns(ax)[2]; + Axes$5.drawTicks(gd, ax, { + vals: ax.ticks === "inside" ? Axes$5.clipEnds(ax, vals) : vals, + layer: axLayer, + path: Axes$5.makeTickPath(ax, shift, tickSign), + transFn: Axes$5.makeTransTickFn(ax) + }); + return Axes$5.drawLabels(gd, ax, { + vals, + layer: axLayer, + transFn: Axes$5.makeTransTickLabelFn(ax), + labelFns: Axes$5.makeLabelFns(ax, shift) + }); + } + function positionCB() { + var bb; + var innerThickness = thickPx + outlinewidth / 2; + if (ticklabelposition.indexOf("inside") === -1) { + bb = Drawing$8.bBox(axLayer.node()); + innerThickness += isVertical2 ? bb.width : bb.height; + } + titleEl = titleCont.select("text"); + var titleWidth2 = 0; + var topSideVertical = isVertical2 && titleSide === "top"; + var rightSideHorizontal = !isVertical2 && titleSide === "right"; + var moveY = 0; + if (titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { + var _titleHeight; + var mathJaxNode = titleCont.select(".h" + ax._id + "title-math-group").node(); + if (mathJaxNode && (isVertical2 && topOrBottom || !isVertical2 && !topOrBottom)) { + bb = Drawing$8.bBox(mathJaxNode); + titleWidth2 = bb.width; + _titleHeight = bb.height; + } else { + bb = Drawing$8.bBox(titleCont.node()); + titleWidth2 = bb.right - gs.l - (isVertical2 ? uPx : vPx); + _titleHeight = bb.bottom - gs.t - (isVertical2 ? vPx : uPx); + if (!isVertical2 && titleSide === "top") { + innerThickness += bb.height; + moveY = bb.height; + } + } + if (rightSideHorizontal) { + titleEl.attr("transform", strTranslate$1(titleWidth2 / 2 + titleFontSize / 2, 0)); + titleWidth2 *= 2; + } + innerThickness = Math.max( + innerThickness, + isVertical2 ? titleWidth2 : _titleHeight + ); + } + var outerThickness = (isVertical2 ? xpad : ypad) * 2 + innerThickness + borderwidth + outlinewidth / 2; + var hColorbarMoveTitle = 0; + if (!isVertical2 && title.text && yanchor === "bottom" && optsY <= 0) { + hColorbarMoveTitle = outerThickness / 2; + outerThickness += hColorbarMoveTitle; + moveY += hColorbarMoveTitle; + } + fullLayout._hColorbarMoveTitle = hColorbarMoveTitle; + fullLayout._hColorbarMoveCBTitle = moveY; + var extraW = borderwidth + outlinewidth; + var lx = (isVertical2 ? uPx : vPx) - extraW / 2 - (isVertical2 ? xpad : 0); + var ly = (isVertical2 ? vPx : uPx) - (isVertical2 ? lenPx : ypad + moveY - hColorbarMoveTitle); + g.select("." + cn.cbbg).attr("x", lx).attr("y", ly).attr(isVertical2 ? "width" : "height", Math.max(outerThickness - hColorbarMoveTitle, 2)).attr(isVertical2 ? "height" : "width", Math.max(lenPx + extraW, 2)).call(Color$h.fill, bgcolor).call(Color$h.stroke, opts.bordercolor).style("stroke-width", borderwidth); + var moveX = rightSideHorizontal ? Math.max(titleWidth2 - 10, 0) : 0; + g.selectAll("." + cn.cboutline).attr("x", (isVertical2 ? uPx : vPx + xpad) + moveX).attr("y", (isVertical2 ? vPx + ypad - lenPx : uPx) + (topSideVertical ? titleHeight : 0)).attr(isVertical2 ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical2 ? "height" : "width", Math.max(lenPx - (isVertical2 ? 2 * ypad + titleHeight : 2 * xpad + moveX), 2)).call(Color$h.stroke, opts.outlinecolor).style({ + fill: "none", + "stroke-width": outlinewidth + }); + var xShift = isVertical2 ? xRatio * outerThickness : 0; + var yShift = isVertical2 ? 0 : (1 - yRatio) * outerThickness - moveY; + xShift = isPaperX ? gs.l - xShift : -xShift; + yShift = isPaperY ? gs.t - yShift : -yShift; + g.attr("transform", strTranslate$1( + xShift, + yShift + )); + if (!isVertical2 && (borderwidth || tinycolor$2(bgcolor).getAlpha() && !tinycolor$2.equals(fullLayout.paper_bgcolor, bgcolor))) { + var tickLabels = axLayer.selectAll("text"); + var numTicks = tickLabels[0].length; + var border = g.select("." + cn.cbbg).node(); + var oBb = Drawing$8.bBox(border); + var oTr = Drawing$8.getTranslate(g); + var TEXTPAD2 = 2; + tickLabels.each(function(d, i) { + var first = 0; + var last = numTicks - 1; + if (i === first || i === last) { + var iBb = Drawing$8.bBox(this); + var iTr = Drawing$8.getTranslate(this); + var deltaX; + if (i === last) { + var iRight = iBb.right + iTr.x; + var oRight = oBb.right + oTr.x + vPx - borderwidth - TEXTPAD2 + optsX; + deltaX = oRight - iRight; + if (deltaX > 0) deltaX = 0; + } else if (i === first) { + var iLeft = iBb.left + iTr.x; + var oLeft = oBb.left + oTr.x + vPx + borderwidth + TEXTPAD2; + deltaX = oLeft - iLeft; + if (deltaX < 0) deltaX = 0; + } + if (deltaX) { + if (numTicks < 3) { + this.setAttribute( + "transform", + "translate(" + deltaX + ",0) " + this.getAttribute("transform") + ); + } else { + this.setAttribute("visibility", "hidden"); + } + } + } + }); + } + var marginOpts = {}; + var lFrac = FROM_TL[xanchor]; + var rFrac = FROM_BR[xanchor]; + var tFrac = FROM_TL[yanchor]; + var bFrac = FROM_BR[yanchor]; + var extraThickness = outerThickness - thickPx; + if (isVertical2) { + if (lenmode === "pixels") { + marginOpts.y = optsY; + marginOpts.t = lenPx * tFrac; + marginOpts.b = lenPx * bFrac; + } else { + marginOpts.t = marginOpts.b = 0; + marginOpts.yt = optsY + len * tFrac; + marginOpts.yb = optsY - len * bFrac; + } + if (thicknessmode === "pixels") { + marginOpts.x = optsX; + marginOpts.l = outerThickness * lFrac; + marginOpts.r = outerThickness * rFrac; + } else { + marginOpts.l = extraThickness * lFrac; + marginOpts.r = extraThickness * rFrac; + marginOpts.xl = optsX - thickness * lFrac; + marginOpts.xr = optsX + thickness * rFrac; + } + } else { + if (lenmode === "pixels") { + marginOpts.x = optsX; + marginOpts.l = lenPx * lFrac; + marginOpts.r = lenPx * rFrac; + } else { + marginOpts.l = marginOpts.r = 0; + marginOpts.xl = optsX + len * lFrac; + marginOpts.xr = optsX - len * rFrac; + } + if (thicknessmode === "pixels") { + marginOpts.y = 1 - optsY; + marginOpts.t = outerThickness * tFrac; + marginOpts.b = outerThickness * bFrac; + } else { + marginOpts.t = extraThickness * tFrac; + marginOpts.b = extraThickness * bFrac; + marginOpts.yt = optsY - thickness * tFrac; + marginOpts.yb = optsY + thickness * bFrac; + } + } + var sideY = opts.y < 0.5 ? "b" : "t"; + var sideX = opts.x < 0.5 ? "l" : "r"; + gd._fullLayout._reservedMargin[opts._id] = {}; + var possibleReservedMargins = { + r: fullLayout.width - lx - xShift, + l: lx + marginOpts.r, + b: fullLayout.height - ly - yShift, + t: ly + marginOpts.b + }; + if (isPaperX && isPaperY) { + Plots$1.autoMargin(gd, opts._id, marginOpts); + } else if (isPaperX) { + gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY]; + } else if (isPaperY) { + gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX]; + } else { + if (isVertical2) { + gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX]; + } else { + gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY]; + } + } + } + return Lib$y.syncOrAsync([ + Plots$1.previousPromises, + drawDummyTitle, + drawAxis, + drawCbTitle, + Plots$1.previousPromises, + positionCB + ], gd); +} +function makeEditable(g, opts, gd) { + var isVertical2 = opts.orientation === "v"; + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + var t02, xf, yf; + dragElement.init({ + element: g.node(), + gd, + prepFn: function() { + t02 = g.attr("transform"); + setCursor2(g); + }, + moveFn: function(dx, dy) { + g.attr("transform", t02 + strTranslate$1(dx, dy)); + xf = dragElement.align( + (isVertical2 ? opts._uFrac : opts._vFrac) + dx / gs.w, + isVertical2 ? opts._thickFrac : opts._lenFrac, + 0, + 1, + opts.xanchor + ); + yf = dragElement.align( + (isVertical2 ? opts._vFrac : 1 - opts._uFrac) - dy / gs.h, + isVertical2 ? opts._lenFrac : opts._thickFrac, + 0, + 1, + opts.yanchor + ); + var csr = dragElement.getCursor(xf, yf, opts.xanchor, opts.yanchor); + setCursor2(g, csr); + }, + doneFn: function() { + setCursor2(g); + if (xf !== void 0 && yf !== void 0) { + var update2 = {}; + update2[opts._propPrefix + "x"] = xf; + update2[opts._propPrefix + "y"] = yf; + if (opts._traceIndex !== void 0) { + Registry$e.call("_guiRestyle", gd, update2, opts._traceIndex); + } else { + Registry$e.call("_guiRelayout", gd, update2); + } + } + } + }); +} +function calcLevels(gd, opts, zrange) { + var levelsIn = opts._levels; + var lineLevels = []; + var fillLevels = []; + var l; + var i; + var l0 = levelsIn.end + levelsIn.size / 100; + var ls = levelsIn.size; + var zr0 = 1.001 * zrange[0] - 1e-3 * zrange[1]; + var zr1 = 1.001 * zrange[1] - 1e-3 * zrange[0]; + for (i = 0; i < 1e5; i++) { + l = levelsIn.start + i * ls; + if (ls > 0 ? l >= l0 : l <= l0) break; + if (l > zr0 && l < zr1) lineLevels.push(l); + } + if (opts._fillgradient) { + fillLevels = [0]; + } else if (typeof opts._fillcolor === "function") { + var fillLevelsIn = opts._filllevels; + if (fillLevelsIn) { + l0 = fillLevelsIn.end + fillLevelsIn.size / 100; + ls = fillLevelsIn.size; + for (i = 0; i < 1e5; i++) { + l = fillLevelsIn.start + i * ls; + if (ls > 0 ? l >= l0 : l <= l0) break; + if (l > zrange[0] && l < zrange[1]) fillLevels.push(l); + } + } else { + fillLevels = lineLevels.map(function(v) { + return v - levelsIn.size / 2; + }); + fillLevels.push(fillLevels[fillLevels.length - 1] + levelsIn.size); + } + } else if (opts._fillcolor && typeof opts._fillcolor === "string") { + fillLevels = [0]; + } + if (levelsIn.size < 0) { + lineLevels.reverse(); + fillLevels.reverse(); + } + return { line: lineLevels, fill: fillLevels }; +} +function mockColorBarAxis(gd, opts, zrange) { + var fullLayout = gd._fullLayout; + var isVertical2 = opts.orientation === "v"; + var cbAxisIn = { + type: "linear", + range: zrange, + tickmode: opts.tickmode, + nticks: opts.nticks, + tick0: opts.tick0, + dtick: opts.dtick, + tickvals: opts.tickvals, + ticktext: opts.ticktext, + ticks: opts.ticks, + ticklen: opts.ticklen, + tickwidth: opts.tickwidth, + tickcolor: opts.tickcolor, + showticklabels: opts.showticklabels, + labelalias: opts.labelalias, + ticklabelposition: opts.ticklabelposition, + ticklabeloverflow: opts.ticklabeloverflow, + ticklabelstep: opts.ticklabelstep, + tickfont: opts.tickfont, + tickangle: opts.tickangle, + tickformat: opts.tickformat, + exponentformat: opts.exponentformat, + minexponent: opts.minexponent, + separatethousands: opts.separatethousands, + showexponent: opts.showexponent, + showtickprefix: opts.showtickprefix, + tickprefix: opts.tickprefix, + showticksuffix: opts.showticksuffix, + ticksuffix: opts.ticksuffix, + title: opts.title, + showline: true, + anchor: "free", + side: isVertical2 ? "right" : "bottom", + position: 1 + }; + var letter = isVertical2 ? "y" : "x"; + var cbAxisOut = { + type: "linear", + _id: letter + opts._id + }; + var axisOptions = { + letter, + font: fullLayout.font, + noAutotickangles: letter === "y", + noHover: true, + noTickson: true, + noTicklabelmode: true, + noInsideRange: true, + calendar: fullLayout.calendar + // not really necessary (yet?) + }; + function coerce2(attr, dflt) { + return Lib$y.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt); + } + handleAxisDefaults2(cbAxisIn, cbAxisOut, coerce2, axisOptions, fullLayout); + handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce2, axisOptions); + return cbAxisOut; +} +var draw_1 = { + draw: draw$2 +}; +var colorbar = { + moduleType: "component", + name: "colorbar", + attributes: attributes$J, + supplyDefaults: defaults$o, + draw: draw_1.draw, + hasColorbar: has_colorbar +}; +var legend = { + moduleType: "component", + name: "legend", + layoutAttributes: attributes$G, + supplyLayoutDefaults: defaults$m, + draw: draw$d, + style: style$8 +}; +var localeEn = { + moduleType: "locale", + name: "en", + dictionary: { + "Click to enter Colorscale title": "Click to enter Colourscale title" + }, + format: { + days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], + shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], + months: [ + "January", + "February", + "March", + "April", + "May", + "June", + "July", + "August", + "September", + "October", + "November", + "December" + ], + shortMonths: [ + "Jan", + "Feb", + "Mar", + "Apr", + "May", + "Jun", + "Jul", + "Aug", + "Sep", + "Oct", + "Nov", + "Dec" + ], + periods: ["AM", "PM"], + dateTime: "%a %b %e %X %Y", + date: "%d/%m/%Y", + time: "%H:%M:%S", + decimal: ".", + thousands: ",", + grouping: [3], + currency: ["$", ""], + year: "%Y", + month: "%b %Y", + dayMonth: "%b %-d", + dayMonthYear: "%b %-d, %Y" + } +}; +var localeEnUs = { + moduleType: "locale", + name: "en-US", + dictionary: { + "Click to enter Colorscale title": "Click to enter Colorscale title" + }, + format: { + date: "%m/%d/%Y" + } +}; +var Registry$d = registry; +var Lib$x = libExports; +var extendFlat$7 = Lib$x.extendFlat; +var extendDeep = Lib$x.extendDeep; +function cloneLayoutOverride(tileClass) { + var override; + switch (tileClass) { + case "themes__thumb": + override = { + autosize: true, + width: 150, + height: 150, + title: { text: "" }, + showlegend: false, + margin: { l: 5, r: 5, t: 5, b: 5, pad: 0 }, + annotations: [] + }; + break; + case "thumbnail": + override = { + title: { text: "" }, + hidesources: true, + showlegend: false, + borderwidth: 0, + bordercolor: "", + margin: { l: 1, r: 1, t: 1, b: 1, pad: 0 }, + annotations: [] + }; + break; + default: + override = {}; + } + return override; +} +function keyIsAxis(keyName) { + var types = ["xaxis", "yaxis", "zaxis"]; + return types.indexOf(keyName.slice(0, 5)) > -1; +} +var cloneplot = function clonePlot(graphObj, options) { + var i; + var oldData = graphObj.data; + var oldLayout = graphObj.layout; + var newData = extendDeep([], oldData); + var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass)); + var context2 = graphObj._context || {}; + if (options.width) newLayout.width = options.width; + if (options.height) newLayout.height = options.height; + if (options.tileClass === "thumbnail" || options.tileClass === "themes__thumb") { + newLayout.annotations = []; + var keys = Object.keys(newLayout); + for (i = 0; i < keys.length; i++) { + if (keyIsAxis(keys[i])) { + newLayout[keys[i]].title = { text: "" }; + } + } + for (i = 0; i < newData.length; i++) { + var trace = newData[i]; + trace.showscale = false; + if (trace.marker) trace.marker.showscale = false; + if (Registry$d.traceIs(trace, "pie-like")) trace.textposition = "none"; + } + } + if (Array.isArray(options.annotations)) { + for (i = 0; i < options.annotations.length; i++) { + newLayout.annotations.push(options.annotations[i]); + } + } + var sceneIds = Object.keys(newLayout).filter(function(key) { + return key.match(/^scene\d*$/); + }); + if (sceneIds.length) { + var axesImageOverride = {}; + if (options.tileClass === "thumbnail") { + axesImageOverride = { + title: { text: "" }, + showaxeslabels: false, + showticklabels: false, + linetickenable: false + }; + } + for (i = 0; i < sceneIds.length; i++) { + var scene = newLayout[sceneIds[i]]; + if (!scene.xaxis) { + scene.xaxis = {}; + } + if (!scene.yaxis) { + scene.yaxis = {}; + } + if (!scene.zaxis) { + scene.zaxis = {}; + } + extendFlat$7(scene.xaxis, axesImageOverride); + extendFlat$7(scene.yaxis, axesImageOverride); + extendFlat$7(scene.zaxis, axesImageOverride); + scene._scene = null; + } + } + var gd = document.createElement("div"); + if (options.tileClass) gd.className = options.tileClass; + var plotTile = { + gd, + td: gd, + // for external (image server) compatibility + layout: newLayout, + data: newData, + config: { + staticPlot: options.staticPlot === void 0 ? true : options.staticPlot, + plotGlPixelRatio: options.plotGlPixelRatio === void 0 ? 2 : options.plotGlPixelRatio, + displaylogo: options.displaylogo || false, + showLink: options.showLink || false, + showTips: options.showTips || false, + mapboxAccessToken: context2.mapboxAccessToken + } + }; + if (options.setBackground !== "transparent") { + plotTile.config.setBackground = options.setBackground || "opaque"; + } + plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass); + return plotTile; +}; +var EventEmitter = eventsExports.EventEmitter; +var Registry$c = registry; +var Lib$w = libExports; +var helpers$f = helpers$o; +var clonePlot2 = cloneplot; +var toSVG2 = tosvg; +var svgToImg = svgtoimg; +function toImage(gd, opts) { + var ev = new EventEmitter(); + var clone2 = clonePlot2(gd, {}); + var clonedGd = clone2.gd; + clonedGd.style.position = "absolute"; + clonedGd.style.left = "-5000px"; + document.body.appendChild(clonedGd); + function wait() { + var delay = helpers$f.getDelay(clonedGd._fullLayout); + setTimeout(function() { + var svg = toSVG2(clonedGd); + var canvas2 = document.createElement("canvas"); + canvas2.id = Lib$w.randstr(); + ev = svgToImg({ + format: opts.format, + width: clonedGd._fullLayout.width, + height: clonedGd._fullLayout.height, + canvas: canvas2, + emitter: ev, + svg + }); + ev.clean = function() { + if (clonedGd) document.body.removeChild(clonedGd); + }; + }, delay); + } + var redrawFunc = helpers$f.getRedrawFunc(clonedGd); + Registry$c.call("_doPlot", clonedGd, clone2.data, clone2.layout, clone2.config).then(redrawFunc).then(wait).catch(function(err) { + ev.emit("error", err); + }); + return ev; +} +var toimage = toImage; +var helpers$e = helpers$o; +var Snapshot = { + getDelay: helpers$e.getDelay, + getRedrawFunc: helpers$e.getRedrawFunc, + clone: cloneplot, + toSVG: tosvg, + svgToImg: svgtoimg, + toImage: toimage, + downloadImage: download +}; +var snapshot = Snapshot; +(function(exports2) { + exports2.version = version$2.version; + var Registry2 = registry; + var register = exports2.register = Registry2.register; + var plotApi2 = plot_api$1; + var methodNames = Object.keys(plotApi2); + for (var i = 0; i < methodNames.length; i++) { + var name2 = methodNames[i]; + if (name2.charAt(0) !== "_") exports2[name2] = plotApi2[name2]; + register({ + moduleType: "apiMethod", + name: name2, + fn: plotApi2[name2] + }); + } + register(scatter$1); + register([ + annotations, + annotations3d, + selections, + shapes, + images, + updatemenus, + sliders, + rangeslider, + rangeselector, + grid, + errorbars, + colorscale, + colorbar, + legend, + // legend needs to come after shape | legend defaults depends on shapes + fx$1, + // fx needs to come after legend | unified hover defaults depends on legends + modebar + ]); + register([ + localeEn, + localeEnUs + ]); + if (window.PlotlyLocales && Array.isArray(window.PlotlyLocales)) { + register(window.PlotlyLocales); + delete window.PlotlyLocales; + } + exports2.Icons = ploticon; + var Fx2 = fx$1; + var Plots2 = plotsExports; + exports2.Plots = { + resize: Plots2.resize, + graphJson: Plots2.graphJson, + sendDataToCloud: Plots2.sendDataToCloud + }; + exports2.Fx = { + hover: Fx2.hover, + unhover: Fx2.unhover, + loneHover: Fx2.loneHover, + loneUnhover: Fx2.loneUnhover + }; + exports2.Snapshot = snapshot; + exports2.PlotSchema = plot_schema; +})(core$1); +var core = core$1; +const Plotly = /* @__PURE__ */ index$3.getDefaultExportFromCjs(core); +var constants$f = { + // padding in pixels around text + TEXTPAD: 3, + // 'value' and 'label' are not really necessary for bar traces, + // but they were made available to `texttemplate` (maybe by accident) + // via tokens `%{value}` and `%{label}` starting in 1.50.0, + // so let's include them in the event data also. + eventDataKeys: ["value", "label"] +}; +var scatterAttrs$2 = attributes$A; +var axisHoverFormat$3 = axis_format_attributes.axisHoverFormat; +var hovertemplateAttrs$4 = template_attributes.hovertemplateAttrs; +var texttemplateAttrs$4 = template_attributes.texttemplateAttrs; +var colorScaleAttrs$3 = attributes$I; +var fontAttrs$3 = font_attributes; +var constants$e = constants$f; +var pattern$3 = attributes$M.pattern; +var extendFlat$6 = extend$5.extendFlat; +var textFontAttrs$1 = fontAttrs$3({ + editType: "calc", + arrayOk: true, + colorEditType: "style", + description: "" +}); +var scatterMarkerAttrs$1 = scatterAttrs$2.marker; +var scatterMarkerLineAttrs$1 = scatterMarkerAttrs$1.line; +var markerLineWidth = extendFlat$6( + {}, + scatterMarkerLineAttrs$1.width, + { dflt: 0 } +); +var markerLine = extendFlat$6({ + width: markerLineWidth, + editType: "calc" +}, colorScaleAttrs$3("marker.line")); +var marker = extendFlat$6({ + line: markerLine, + editType: "calc" +}, colorScaleAttrs$3("marker"), { + opacity: { + valType: "number", + arrayOk: true, + dflt: 1, + min: 0, + max: 1, + editType: "style", + description: "Sets the opacity of the bars." + }, + pattern: pattern$3, + cornerradius: { + valType: "any", + editType: "calc", + description: [ + "Sets the rounding of corners. May be an integer number of pixels,", + "or a percentage of bar width (as a string ending in %). Defaults to `layout.barcornerradius`.", + "In stack or relative barmode, the first trace to set cornerradius is used for the whole stack." + ].join(" ") + } +}); +var attributes$e = { + x: scatterAttrs$2.x, + x0: scatterAttrs$2.x0, + dx: scatterAttrs$2.dx, + y: scatterAttrs$2.y, + y0: scatterAttrs$2.y0, + dy: scatterAttrs$2.dy, + xperiod: scatterAttrs$2.xperiod, + yperiod: scatterAttrs$2.yperiod, + xperiod0: scatterAttrs$2.xperiod0, + yperiod0: scatterAttrs$2.yperiod0, + xperiodalignment: scatterAttrs$2.xperiodalignment, + yperiodalignment: scatterAttrs$2.yperiodalignment, + xhoverformat: axisHoverFormat$3("x"), + yhoverformat: axisHoverFormat$3("y"), + text: scatterAttrs$2.text, + texttemplate: texttemplateAttrs$4({ editType: "plot" }, { + keys: constants$e.eventDataKeys + }), + hovertext: scatterAttrs$2.hovertext, + hovertemplate: hovertemplateAttrs$4({}, { + keys: constants$e.eventDataKeys + }), + textposition: { + valType: "enumerated", + values: ["inside", "outside", "auto", "none"], + dflt: "auto", + arrayOk: true, + editType: "calc", + description: [ + "Specifies the location of the `text`.", + "*inside* positions `text` inside, next to the bar end", + "(rotated and scaled if needed).", + "*outside* positions `text` outside, next to the bar end", + "(scaled if needed), unless there is another bar stacked on", + "this one, then the text gets pushed inside.", + "*auto* tries to position `text` inside the bar, but if", + "the bar is too small and no bar is stacked on this one", + "the text is moved outside.", + "If *none*, no text appears." + ].join(" ") + }, + insidetextanchor: { + valType: "enumerated", + values: ["end", "middle", "start"], + dflt: "end", + editType: "plot", + description: [ + "Determines if texts are kept at center or start/end points in `textposition` *inside* mode." + ].join(" ") + }, + textangle: { + valType: "angle", + dflt: "auto", + editType: "plot", + description: [ + "Sets the angle of the tick labels with respect to the bar.", + "For example, a `tickangle` of -90 draws the tick labels", + "vertically. With *auto* the texts may automatically be", + "rotated to fit with the maximum size in bars." + ].join(" ") + }, + textfont: extendFlat$6({}, textFontAttrs$1, { + description: "Sets the font used for `text`." + }), + insidetextfont: extendFlat$6({}, textFontAttrs$1, { + description: "Sets the font used for `text` lying inside the bar." + }), + outsidetextfont: extendFlat$6({}, textFontAttrs$1, { + description: "Sets the font used for `text` lying outside the bar." + }), + constraintext: { + valType: "enumerated", + values: ["inside", "outside", "both", "none"], + dflt: "both", + editType: "calc", + description: [ + "Constrain the size of text inside or outside a bar to be no", + "larger than the bar itself." + ].join(" ") + }, + cliponaxis: extendFlat$6({}, scatterAttrs$2.cliponaxis, { + description: [ + "Determines whether the text nodes", + "are clipped about the subplot axes.", + "To show the text nodes above axis lines and tick labels,", + "make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." + ].join(" ") + }), + orientation: { + valType: "enumerated", + values: ["v", "h"], + editType: "calc+clearAxisTypes", + description: [ + "Sets the orientation of the bars.", + "With *v* (*h*), the value of the each bar spans", + "along the vertical (horizontal)." + ].join(" ") + }, + base: { + valType: "any", + dflt: null, + arrayOk: true, + editType: "calc", + description: [ + "Sets where the bar base is drawn (in position axis units).", + "In *stack* or *relative* barmode,", + "traces that set *base* will be excluded", + "and drawn in *overlay* mode instead." + ].join(" ") + }, + offset: { + valType: "number", + dflt: null, + arrayOk: true, + editType: "calc", + description: [ + "Shifts the position where the bar is drawn", + "(in position axis units).", + "In *group* barmode,", + "traces that set *offset* will be excluded", + "and drawn in *overlay* mode instead." + ].join(" ") + }, + width: { + valType: "number", + dflt: null, + min: 0, + arrayOk: true, + editType: "calc", + description: [ + "Sets the bar width (in position axis units)." + ].join(" ") + }, + marker, + offsetgroup: scatterAttrs$2.offsetgroup, + alignmentgroup: scatterAttrs$2.alignmentgroup, + selected: { + marker: { + opacity: scatterAttrs$2.selected.marker.opacity, + color: scatterAttrs$2.selected.marker.color, + editType: "style" + }, + textfont: scatterAttrs$2.selected.textfont, + editType: "style" + }, + unselected: { + marker: { + opacity: scatterAttrs$2.unselected.marker.opacity, + color: scatterAttrs$2.unselected.marker.color, + editType: "style" + }, + textfont: scatterAttrs$2.unselected.textfont, + editType: "style" + }, + zorder: scatterAttrs$2.zorder, + _deprecated: { + bardir: { + valType: "enumerated", + editType: "calc", + values: ["v", "h"], + description: "Renamed to `orientation`." + } + } +}; +var layout_attributes$2 = { + barmode: { + valType: "enumerated", + values: ["stack", "group", "overlay", "relative"], + dflt: "group", + editType: "calc", + description: [ + "Determines how bars at the same location coordinate", + "are displayed on the graph.", + "With *stack*, the bars are stacked on top of one another", + "With *relative*, the bars are stacked on top of one another,", + "with negative values below the axis, positive values above", + "With *group*, the bars are plotted next to one another", + "centered around the shared location.", + "With *overlay*, the bars are plotted over one another,", + "you might need to reduce *opacity* to see multiple bars." + ].join(" ") + }, + barnorm: { + valType: "enumerated", + values: ["", "fraction", "percent"], + dflt: "", + editType: "calc", + description: [ + "Sets the normalization for bar traces on the graph.", + "With *fraction*, the value of each bar is divided by the sum of all", + "values at that location coordinate.", + "*percent* is the same but multiplied by 100 to show percentages." + ].join(" ") + }, + bargap: { + valType: "number", + min: 0, + max: 1, + editType: "calc", + description: [ + "Sets the gap (in plot fraction) between bars of", + "adjacent location coordinates." + ].join(" ") + }, + bargroupgap: { + valType: "number", + min: 0, + max: 1, + dflt: 0, + editType: "calc", + description: [ + "Sets the gap (in plot fraction) between bars of", + "the same location coordinate." + ].join(" ") + }, + barcornerradius: { + valType: "any", + editType: "calc", + description: [ + "Sets the rounding of bar corners. May be an integer number of pixels,", + "or a percentage of bar width (as a string ending in %)." + ].join(" ") + } +}; +var Color$g = colorExports; +var hasColorscale$2 = helpers$L.hasColorscale; +var colorscaleDefaults$1 = defaults$n; +var coercePattern$1 = libExports.coercePattern; +var style_defaults = function handleStyleDefaults(traceIn, traceOut, coerce2, defaultColor, layout) { + var markerColor = coerce2("marker.color", defaultColor); + var hasMarkerColorscale = hasColorscale$2(traceIn, "marker"); + if (hasMarkerColorscale) { + colorscaleDefaults$1( + traceIn, + traceOut, + layout, + coerce2, + { prefix: "marker.", cLetter: "c" } + ); + } + coerce2("marker.line.color", Color$g.defaultLine); + if (hasColorscale$2(traceIn, "marker.line")) { + colorscaleDefaults$1( + traceIn, + traceOut, + layout, + coerce2, + { prefix: "marker.line.", cLetter: "c" } + ); + } + coerce2("marker.line.width"); + coerce2("marker.opacity"); + coercePattern$1(coerce2, "marker.pattern", markerColor, hasMarkerColorscale); + coerce2("selected.marker.color"); + coerce2("unselected.marker.color"); +}; +var isNumeric$8 = fastIsnumeric; +var Lib$v = libExports; +var Color$f = colorExports; +var Registry$b = registry; +var handleXYDefaults$1 = xy_defaults; +var handlePeriodDefaults$2 = period_defaults; +var handleStyleDefaults$1 = style_defaults; +var handleGroupingDefaults$1 = grouping_defaults; +var attributes$d = attributes$e; +var coerceFont = Lib$v.coerceFont; +function supplyDefaults$1(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$v.coerce(traceIn, traceOut, attributes$d, attr, dflt); + } + var len = handleXYDefaults$1(traceIn, traceOut, layout, coerce2); + if (!len) { + traceOut.visible = false; + return; + } + handlePeriodDefaults$2(traceIn, traceOut, layout, coerce2); + coerce2("xhoverformat"); + coerce2("yhoverformat"); + coerce2("zorder"); + coerce2("orientation", traceOut.x && !traceOut.y ? "h" : "v"); + coerce2("base"); + coerce2("offset"); + coerce2("width"); + coerce2("text"); + coerce2("hovertext"); + coerce2("hovertemplate"); + var textposition = coerce2("textposition"); + handleText$3(traceIn, traceOut, layout, coerce2, textposition, { + moduleHasSelected: true, + moduleHasUnselected: true, + moduleHasConstrain: true, + moduleHasCliponaxis: true, + moduleHasTextangle: true, + moduleHasInsideanchor: true + }); + handleStyleDefaults$1(traceIn, traceOut, coerce2, defaultColor, layout); + var lineColor = (traceOut.marker.line || {}).color; + var errorBarsSupplyDefaults = Registry$b.getComponentMethod("errorbars", "supplyDefaults"); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$f.defaultLine, { axis: "y" }); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$f.defaultLine, { axis: "x", inherit: "y" }); + Lib$v.coerceSelectionMarkerOpacity(traceOut, coerce2); +} +function crossTraceDefaults3(fullData, fullLayout) { + var traceIn, traceOut; + function coerce2(attr, dflt) { + return Lib$v.coerce(traceOut._input, traceOut, attributes$d, attr, dflt); + } + for (var i = 0; i < fullData.length; i++) { + traceOut = fullData[i]; + if (traceOut.type === "bar") { + traceIn = traceOut._input; + var r = coerce2("marker.cornerradius", fullLayout.barcornerradius); + if (traceOut.marker) { + traceOut.marker.cornerradius = validateCornerradius$2(r); + } + if (fullLayout.barmode === "group") { + handleGroupingDefaults$1(traceIn, traceOut, fullLayout, coerce2); + } + } + } +} +function validateCornerradius$2(r) { + if (isNumeric$8(r)) { + r = +r; + if (r >= 0) return r; + } else if (typeof r === "string") { + r = r.trim(); + if (r.slice(-1) === "%" && isNumeric$8(r.slice(0, -1))) { + r = +r.slice(0, -1); + if (r >= 0) return r + "%"; + } + } + return void 0; +} +function handleText$3(traceIn, traceOut, layout, coerce2, textposition, opts) { + opts = opts || {}; + var moduleHasSelected = !(opts.moduleHasSelected === false); + var moduleHasUnselected = !(opts.moduleHasUnselected === false); + var moduleHasConstrain = !(opts.moduleHasConstrain === false); + var moduleHasCliponaxis = !(opts.moduleHasCliponaxis === false); + var moduleHasTextangle = !(opts.moduleHasTextangle === false); + var moduleHasInsideanchor = !(opts.moduleHasInsideanchor === false); + var hasPathbar = !!opts.hasPathbar; + var hasBoth = Array.isArray(textposition) || textposition === "auto"; + var hasInside = hasBoth || textposition === "inside"; + var hasOutside = hasBoth || textposition === "outside"; + if (hasInside || hasOutside) { + var dfltFont = coerceFont(coerce2, "textfont", layout.font); + var insideTextFontDefault = Lib$v.extendFlat({}, dfltFont); + var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color; + var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet; + if (isColorInheritedFromLayoutFont) { + delete insideTextFontDefault.color; + } + coerceFont(coerce2, "insidetextfont", insideTextFontDefault); + if (hasPathbar) { + var pathbarTextFontDefault = Lib$v.extendFlat({}, dfltFont); + if (isColorInheritedFromLayoutFont) { + delete pathbarTextFontDefault.color; + } + coerceFont(coerce2, "pathbar.textfont", pathbarTextFontDefault); + } + if (hasOutside) coerceFont(coerce2, "outsidetextfont", dfltFont); + if (moduleHasSelected) coerce2("selected.textfont.color"); + if (moduleHasUnselected) coerce2("unselected.textfont.color"); + if (moduleHasConstrain) coerce2("constraintext"); + if (moduleHasCliponaxis) coerce2("cliponaxis"); + if (moduleHasTextangle) coerce2("textangle"); + coerce2("texttemplate"); + } + if (hasInside) { + if (moduleHasInsideanchor) coerce2("insidetextanchor"); + } +} +var defaults$6 = { + supplyDefaults: supplyDefaults$1, + crossTraceDefaults: crossTraceDefaults3, + handleText: handleText$3, + validateCornerradius: validateCornerradius$2 +}; +var Registry$a = registry; +var Axes$4 = axesExports; +var Lib$u = libExports; +var layoutAttributes$2 = layout_attributes$2; +var validateCornerradius$1 = defaults$6.validateCornerradius; +var layout_defaults$2 = function(layoutIn, layoutOut, fullData) { + function coerce2(attr, dflt) { + return Lib$u.coerce(layoutIn, layoutOut, layoutAttributes$2, attr, dflt); + } + var hasBars = false; + var shouldBeGapless = false; + var gappedAnyway = false; + var usedSubplots = {}; + var mode = coerce2("barmode"); + for (var i = 0; i < fullData.length; i++) { + var trace = fullData[i]; + if (Registry$a.traceIs(trace, "bar") && trace.visible) hasBars = true; + else continue; + if (mode === "group") { + var subploti = trace.xaxis + trace.yaxis; + if (usedSubplots[subploti]) gappedAnyway = true; + usedSubplots[subploti] = true; + } + if (trace.visible && trace.type === "histogram") { + var pa = Axes$4.getFromId( + { _fullLayout: layoutOut }, + trace[trace.orientation === "v" ? "xaxis" : "yaxis"] + ); + if (pa.type !== "category") shouldBeGapless = true; + } + } + if (!hasBars) { + delete layoutOut.barmode; + return; + } + if (mode !== "overlay") coerce2("barnorm"); + coerce2("bargap", shouldBeGapless && !gappedAnyway ? 0 : 0.2); + coerce2("bargroupgap"); + var r = coerce2("barcornerradius"); + layoutOut.barcornerradius = validateCornerradius$1(r); +}; +var Lib$t = libExports; +var arrays_to_calcdata = function arraysToCalcdata2(cd, trace) { + for (var i = 0; i < cd.length; i++) cd[i].i = i; + Lib$t.mergeArray(trace.text, cd, "tx"); + Lib$t.mergeArray(trace.hovertext, cd, "htx"); + var marker2 = trace.marker; + if (marker2) { + Lib$t.mergeArray(marker2.opacity, cd, "mo", true); + Lib$t.mergeArray(marker2.color, cd, "mc"); + var markerLine2 = marker2.line; + if (markerLine2) { + Lib$t.mergeArray(markerLine2.color, cd, "mlc"); + Lib$t.mergeArrayCastPositive(markerLine2.width, cd, "mlw"); + } + } +}; +var Axes$3 = axesExports; +var alignPeriod$2 = align_period; +var hasColorscale$1 = helpers$L.hasColorscale; +var colorscaleCalc = calc$c; +var arraysToCalcdata$1 = arrays_to_calcdata; +var calcSelection2 = calc_selection; +var calc$7 = function calc3(gd, trace) { + var xa = Axes$3.getFromId(gd, trace.xaxis || "x"); + var ya = Axes$3.getFromId(gd, trace.yaxis || "y"); + var size, pos, origPos, pObj, hasPeriod, pLetter; + var sizeOpts = { + msUTC: !!(trace.base || trace.base === 0) + }; + if (trace.orientation === "h") { + size = xa.makeCalcdata(trace, "x", sizeOpts); + origPos = ya.makeCalcdata(trace, "y"); + pObj = alignPeriod$2(trace, ya, "y", origPos); + hasPeriod = !!trace.yperiodalignment; + pLetter = "y"; + } else { + size = ya.makeCalcdata(trace, "y", sizeOpts); + origPos = xa.makeCalcdata(trace, "x"); + pObj = alignPeriod$2(trace, xa, "x", origPos); + hasPeriod = !!trace.xperiodalignment; + pLetter = "x"; + } + pos = pObj.vals; + var serieslen = Math.min(pos.length, size.length); + var cd = new Array(serieslen); + for (var i = 0; i < serieslen; i++) { + cd[i] = { p: pos[i], s: size[i] }; + if (hasPeriod) { + cd[i].orig_p = origPos[i]; + cd[i][pLetter + "End"] = pObj.ends[i]; + cd[i][pLetter + "Start"] = pObj.starts[i]; + } + if (trace.ids) { + cd[i].id = String(trace.ids[i]); + } + } + if (hasColorscale$1(trace, "marker")) { + colorscaleCalc(gd, trace, { + vals: trace.marker.color, + containerStr: "marker" + }); + } + if (hasColorscale$1(trace, "marker.line")) { + colorscaleCalc(gd, trace, { + vals: trace.marker.line.color, + containerStr: "marker.line" + }); + } + arraysToCalcdata$1(cd, trace); + calcSelection2(cd, trace); + return cd; +}; +var d3$c = d3Exports; +var Lib$s = libExports; +function resizeText$4(gd, gTrace, traceType) { + var fullLayout = gd._fullLayout; + var minSize = fullLayout["_" + traceType + "Text_minsize"]; + if (minSize) { + var shouldHide = fullLayout.uniformtext.mode === "hide"; + var selector; + switch (traceType) { + case "funnelarea": + case "pie": + case "sunburst": + selector = "g.slice"; + break; + case "treemap": + case "icicle": + selector = "g.slice, g.pathbar"; + break; + default: + selector = "g.points > g.point"; + } + gTrace.selectAll(selector).each(function(d) { + var transform = d.transform; + if (transform) { + transform.scale = shouldHide && transform.hide ? 0 : minSize / transform.fontSize; + var el = d3$c.select(this).select("text"); + Lib$s.setTransormAndDisplay(el, transform); + } + }); + } +} +function recordMinTextSize$3(traceType, transform, fullLayout) { + if (fullLayout.uniformtext.mode) { + var minKey = getMinKey(traceType); + var minSize = fullLayout.uniformtext.minsize; + var size = transform.scale * transform.fontSize; + transform.hide = size < minSize; + fullLayout[minKey] = fullLayout[minKey] || Infinity; + if (!transform.hide) { + fullLayout[minKey] = Math.min( + fullLayout[minKey], + Math.max(size, minSize) + ); + } + } +} +function clearMinTextSize$3(traceType, fullLayout) { + var minKey = getMinKey(traceType); + fullLayout[minKey] = void 0; +} +function getMinKey(traceType) { + return "_" + traceType + "Text_minsize"; +} +var uniform_text = { + recordMinTextSize: recordMinTextSize$3, + clearMinTextSize: clearMinTextSize$3, + resizeText: resizeText$4 +}; +var helpers$d = {}; +var isNumeric$7 = fastIsnumeric; +var tinycolor$1 = tinycolorExports; +var isArrayOrTypedArray$2 = libExports.isArrayOrTypedArray; +helpers$d.coerceString = function(attributeDefinition, value2, defaultValue) { + if (typeof value2 === "string") { + if (value2 || !attributeDefinition.noBlank) return value2; + } else if (typeof value2 === "number" || value2 === true) { + if (!attributeDefinition.strict) return String(value2); + } + return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; +}; +helpers$d.coerceNumber = function(attributeDefinition, value2, defaultValue) { + if (isNumeric$7(value2)) { + value2 = +value2; + var min = attributeDefinition.min; + var max = attributeDefinition.max; + var isOutOfBounds = min !== void 0 && value2 < min || max !== void 0 && value2 > max; + if (!isOutOfBounds) return value2; + } + return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; +}; +helpers$d.coerceColor = function(attributeDefinition, value2, defaultValue) { + if (tinycolor$1(value2).isValid()) return value2; + return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; +}; +helpers$d.coerceEnumerated = function(attributeDefinition, value2, defaultValue) { + if (attributeDefinition.coerceNumber) value2 = +value2; + if (attributeDefinition.values.indexOf(value2) !== -1) return value2; + return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; +}; +helpers$d.getValue = function(arrayOrScalar, index2) { + var value2; + if (!isArrayOrTypedArray$2(arrayOrScalar)) value2 = arrayOrScalar; + else if (index2 < arrayOrScalar.length) value2 = arrayOrScalar[index2]; + return value2; +}; +helpers$d.getLineWidth = function(trace, di) { + var w = 0 < di.mlw ? di.mlw : !isArrayOrTypedArray$2(trace.marker.line.width) ? trace.marker.line.width : 0; + return w; +}; +var d3$b = d3Exports; +var Color$e = colorExports; +var Drawing$7 = drawingExports; +var Lib$r = libExports; +var Registry$9 = registry; +var resizeText$3 = uniform_text.resizeText; +var attributes$c = attributes$e; +var attributeTextFont = attributes$c.textfont; +var attributeInsideTextFont = attributes$c.insidetextfont; +var attributeOutsideTextFont = attributes$c.outsidetextfont; +var helpers$c = helpers$d; +function style$4(gd) { + var s = d3$b.select(gd).selectAll('g[class^="barlayer"]').selectAll("g.trace"); + resizeText$3(gd, s, "bar"); + var barcount = s.size(); + var fullLayout = gd._fullLayout; + s.style("opacity", function(d) { + return d[0].trace.opacity; + }).each(function(d) { + if (fullLayout.barmode === "stack" && barcount > 1 || fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width) { + d3$b.select(this).attr("shape-rendering", "crispEdges"); + } + }); + s.selectAll("g.points").each(function(d) { + var sel = d3$b.select(this); + var trace = d[0].trace; + stylePoints(sel, trace, gd); + }); + Registry$9.getComponentMethod("errorbars", "style")(s); +} +function stylePoints(sel, trace, gd) { + Drawing$7.pointStyle(sel.selectAll("path"), trace, gd); + styleTextPoints(sel, trace, gd); +} +function styleTextPoints(sel, trace, gd) { + sel.selectAll("text").each(function(d) { + var tx = d3$b.select(this); + var font2 = Lib$r.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); + Drawing$7.font(tx, font2); + }); +} +function styleOnSelect(gd, cd, sel) { + var trace = cd[0].trace; + if (trace.selectedpoints) { + stylePointsInSelectionMode(sel, trace, gd); + } else { + stylePoints(sel, trace, gd); + Registry$9.getComponentMethod("errorbars", "style")(sel); + } +} +function stylePointsInSelectionMode(s, trace, gd) { + Drawing$7.selectedPointStyle(s.selectAll("path"), trace); + styleTextInSelectionMode(s.selectAll("text"), trace, gd); +} +function styleTextInSelectionMode(txs, trace, gd) { + txs.each(function(d) { + var tx = d3$b.select(this); + var font2; + if (d.selected) { + font2 = Lib$r.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); + var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color; + if (selectedFontColor) { + font2.color = selectedFontColor; + } + Drawing$7.font(tx, font2); + } else { + Drawing$7.selectedTextStyle(tx, trace); + } + }); +} +function determineFont(tx, d, trace, gd) { + var layoutFont = gd._fullLayout.font; + var textFont = trace.textfont; + if (tx.classed("bartext-inside")) { + var barColor = getBarColor(d, trace); + textFont = getInsideTextFont(trace, d.i, layoutFont, barColor); + } else if (tx.classed("bartext-outside")) { + textFont = getOutsideTextFont(trace, d.i, layoutFont); + } + return textFont; +} +function getTextFont(trace, index2, defaultValue) { + return getFontValue( + attributeTextFont, + trace.textfont, + index2, + defaultValue + ); +} +function getInsideTextFont(trace, index2, layoutFont, barColor) { + var defaultFont = getTextFont(trace, index2, layoutFont); + var wouldFallBackToLayoutFont = trace._input.textfont === void 0 || trace._input.textfont.color === void 0 || Array.isArray(trace.textfont.color) && trace.textfont.color[index2] === void 0; + if (wouldFallBackToLayoutFont) { + defaultFont = { + color: Color$e.contrast(barColor), + family: defaultFont.family, + size: defaultFont.size, + weight: defaultFont.weight, + style: defaultFont.style, + variant: defaultFont.variant, + textcase: defaultFont.textcase, + lineposition: defaultFont.lineposition, + shadow: defaultFont.shadow + }; + } + return getFontValue( + attributeInsideTextFont, + trace.insidetextfont, + index2, + defaultFont + ); +} +function getOutsideTextFont(trace, index2, layoutFont) { + var defaultFont = getTextFont(trace, index2, layoutFont); + return getFontValue( + attributeOutsideTextFont, + trace.outsidetextfont, + index2, + defaultFont + ); +} +function getFontValue(attributeDefinition, attributeValue, index2, defaultValue) { + attributeValue = attributeValue || {}; + var familyValue = helpers$c.getValue(attributeValue.family, index2); + var sizeValue = helpers$c.getValue(attributeValue.size, index2); + var colorValue = helpers$c.getValue(attributeValue.color, index2); + var weightValue = helpers$c.getValue(attributeValue.weight, index2); + var styleValue = helpers$c.getValue(attributeValue.style, index2); + var variantValue = helpers$c.getValue(attributeValue.variant, index2); + var textcaseValue = helpers$c.getValue(attributeValue.textcase, index2); + var linepositionValue = helpers$c.getValue(attributeValue.lineposition, index2); + var shadowValue = helpers$c.getValue(attributeValue.shadow, index2); + return { + family: helpers$c.coerceString( + attributeDefinition.family, + familyValue, + defaultValue.family + ), + size: helpers$c.coerceNumber( + attributeDefinition.size, + sizeValue, + defaultValue.size + ), + color: helpers$c.coerceColor( + attributeDefinition.color, + colorValue, + defaultValue.color + ), + weight: helpers$c.coerceString( + attributeDefinition.weight, + weightValue, + defaultValue.weight + ), + style: helpers$c.coerceString( + attributeDefinition.style, + styleValue, + defaultValue.style + ), + variant: helpers$c.coerceString( + attributeDefinition.variant, + variantValue, + defaultValue.variant + ), + textcase: helpers$c.coerceString( + attributeDefinition.variant, + textcaseValue, + defaultValue.textcase + ), + lineposition: helpers$c.coerceString( + attributeDefinition.variant, + linepositionValue, + defaultValue.lineposition + ), + shadow: helpers$c.coerceString( + attributeDefinition.variant, + shadowValue, + defaultValue.shadow + ) + }; +} +function getBarColor(cd, trace) { + if (trace.type === "waterfall") { + return trace[cd.dir].marker.color; + } + return cd.mcc || cd.mc || trace.marker.color; +} +var style_1$2 = { + style: style$4, + styleTextPoints, + styleOnSelect, + getInsideTextFont, + getOutsideTextFont, + getBarColor, + resizeText: resizeText$3 +}; +var d3$a = d3Exports; +var isNumeric$6 = fastIsnumeric; +var Lib$q = libExports; +var svgTextUtils$3 = svg_text_utils; +var Color$d = colorExports; +var Drawing$6 = drawingExports; +var Registry$8 = registry; +var tickText = axesExports.tickText; +var uniformText$3 = uniform_text; +var recordMinTextSize$2 = uniformText$3.recordMinTextSize; +var clearMinTextSize$2 = uniformText$3.clearMinTextSize; +var style$3 = style_1$2; +var helpers$b = helpers$d; +var constants$d = constants$f; +var attributes$b = attributes$e; +var attributeText = attributes$b.text; +var attributeTextPosition = attributes$b.textposition; +var appendArrayPointValue$2 = helpers$J.appendArrayPointValue; +var TEXTPAD$3 = constants$d.TEXTPAD; +function keyFunc(d) { + return d.id; +} +function getKeyFunc(trace) { + if (trace.ids) { + return keyFunc; + } +} +function sign$1(v) { + return (v > 0) - (v < 0); +} +function dirSign(a, b) { + return a < b ? 1 : -1; +} +function getXY(di, xa, ya, isHorizontal) { + var s = []; + var p = []; + var sAxis = isHorizontal ? xa : ya; + var pAxis = isHorizontal ? ya : xa; + s[0] = sAxis.c2p(di.s0, true); + p[0] = pAxis.c2p(di.p0, true); + s[1] = sAxis.c2p(di.s1, true); + p[1] = pAxis.c2p(di.p1, true); + return isHorizontal ? [s, p] : [p, s]; +} +function transition(selection, fullLayout, opts, makeOnCompleteCallback) { + if (!fullLayout.uniformtext.mode && hasTransition(opts)) { + var onComplete; + if (makeOnCompleteCallback) { + onComplete = makeOnCompleteCallback(); + } + return selection.transition().duration(opts.duration).ease(opts.easing).each("end", function() { + onComplete && onComplete(); + }).each("interrupt", function() { + onComplete && onComplete(); + }); + } else { + return selection; + } +} +function hasTransition(transitionOpts) { + return transitionOpts && transitionOpts.duration > 0; +} +function plot$5(gd, plotinfo, cdModule, traceLayer, opts, makeOnCompleteCallback) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var fullLayout = gd._fullLayout; + var isStatic = gd._context.staticPlot; + if (!opts) { + opts = { + mode: fullLayout.barmode, + norm: fullLayout.barmode, + gap: fullLayout.bargap, + groupgap: fullLayout.bargroupgap + }; + clearMinTextSize$2("bar", fullLayout); + } + var bartraces = Lib$q.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) { + var plotGroup = d3$a.select(this); + var trace = cd[0].trace; + var t = cd[0].t; + var isWaterfall = trace.type === "waterfall"; + var isFunnel = trace.type === "funnel"; + var isHistogram = trace.type === "histogram"; + var isBar = trace.type === "bar"; + var shouldDisplayZeros = isBar || isFunnel; + var adjustPixel = 0; + if (isWaterfall && trace.connector.visible && trace.connector.mode === "between") { + adjustPixel = trace.connector.line.width / 2; + } + var isHorizontal = trace.orientation === "h"; + var withTransition = hasTransition(opts); + var pointGroup = Lib$q.ensureSingle(plotGroup, "g", "points"); + var keyFunc2 = getKeyFunc(trace); + var bars = pointGroup.selectAll("g.point").data(Lib$q.identity, keyFunc2); + bars.enter().append("g").classed("point", true); + bars.exit().remove(); + bars.each(function(di, i) { + var bar2 = d3$a.select(this); + var xy = getXY(di, xa, ya, isHorizontal); + var x0 = xy[0][0]; + var x1 = xy[0][1]; + var y0 = xy[1][0]; + var y1 = xy[1][1]; + var isBlank = (isHorizontal ? x1 - x0 : y1 - y0) === 0; + if (isBlank && shouldDisplayZeros && helpers$b.getLineWidth(trace, di)) { + isBlank = false; + } + if (!isBlank) { + isBlank = !isNumeric$6(x0) || !isNumeric$6(x1) || !isNumeric$6(y0) || !isNumeric$6(y1); + } + di.isBlank = isBlank; + if (isBlank) { + if (isHorizontal) { + x1 = x0; + } else { + y1 = y0; + } + } + if (adjustPixel && !isBlank) { + if (isHorizontal) { + x0 -= dirSign(x0, x1) * adjustPixel; + x1 += dirSign(x0, x1) * adjustPixel; + } else { + y0 -= dirSign(y0, y1) * adjustPixel; + y1 += dirSign(y0, y1) * adjustPixel; + } + } + var lw; + var mc; + if (trace.type === "waterfall") { + if (!isBlank) { + var cont = trace[di.dir].marker; + lw = cont.line.width; + mc = cont.color; + } + } else { + lw = helpers$b.getLineWidth(trace, di); + mc = di.mc || trace.marker.color; + } + function roundWithLine(v) { + var offset = d3$a.round(lw / 2 % 1, 2); + return opts.gap === 0 && opts.groupgap === 0 ? d3$a.round(Math.round(v) - offset, 2) : v; + } + function expandToVisible(v, vc, hideZeroSpan) { + if (hideZeroSpan && v === vc) { + return v; + } + return Math.abs(v - vc) >= 2 ? roundWithLine(v) : ( + // but if it's very thin, expand it so it's + // necessarily visible, even if it might overlap + // its neighbor + v > vc ? Math.ceil(v) : Math.floor(v) + ); + } + var op = Color$d.opacity(mc); + var fixpx = op < 1 || lw > 0.01 ? roundWithLine : expandToVisible; + if (!gd._context.staticPlot) { + x0 = fixpx(x0, x1, isHorizontal); + x1 = fixpx(x1, x0, isHorizontal); + y0 = fixpx(y0, y1, !isHorizontal); + y1 = fixpx(y1, y0, !isHorizontal); + } + var c2p = isHorizontal ? xa.c2p : ya.c2p; + var outerBound; + if (di.s0 > 0) { + outerBound = di._sMax; + } else if (di.s0 < 0) { + outerBound = di._sMin; + } else { + outerBound = di.s1 > 0 ? di._sMax : di._sMin; + } + function calcCornerRadius(crValue, crForm) { + if (!crValue) return 0; + var barWidth = isHorizontal ? Math.abs(y1 - y0) : Math.abs(x1 - x0); + var barLength = isHorizontal ? Math.abs(x1 - x0) : Math.abs(y1 - y0); + var stackedBarTotalLength = fixpx(Math.abs(c2p(outerBound, true) - c2p(0, true))); + var maxRadius = di.hasB ? Math.min(barWidth / 2, barLength / 2) : Math.min(barWidth / 2, stackedBarTotalLength); + var crPx; + if (crForm === "%") { + var crPercent = Math.min(50, crValue); + crPx = barWidth * (crPercent / 100); + } else { + crPx = crValue; + } + return fixpx(Math.max(Math.min(crPx, maxRadius), 0)); + } + var r = isBar || isHistogram ? calcCornerRadius(t.cornerradiusvalue, t.cornerradiusform) : 0; + var path, h; + var rectanglePath = "M" + x0 + "," + y0 + "V" + y1 + "H" + x1 + "V" + y0 + "Z"; + var overhead = 0; + if (r && di.s) { + var refPoint = sign$1(di.s0) === 0 || sign$1(di.s) === sign$1(di.s0) ? di.s1 : di.s0; + overhead = fixpx(!di.hasB ? Math.abs(c2p(outerBound, true) - c2p(refPoint, true)) : 0); + if (overhead < r) { + var xdir = dirSign(x0, x1); + var ydir = dirSign(y0, y1); + var cornersweep = xdir === -ydir ? 1 : 0; + if (isHorizontal) { + if (di.hasB) { + path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z"; + } else { + h = Math.abs(x1 - x0) + overhead; + var dy1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0; + var dy2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0; + var xminfunc = xdir > 0 ? Math.max : Math.min; + path = "M" + x0 + "," + y0 + "V" + (y1 - dy1 * ydir) + "H" + xminfunc(x1 - (r - overhead) * xdir, x0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir - dy2) + "V" + (y0 + r * ydir + dy2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + xminfunc(x1 - (r - overhead) * xdir, x0) + "," + (y0 + dy1 * ydir) + "Z"; + } + } else { + if (di.hasB) { + path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z"; + } else { + h = Math.abs(y1 - y0) + overhead; + var dx1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0; + var dx2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0; + var yminfunc = ydir > 0 ? Math.max : Math.min; + path = "M" + (x0 + dx1 * xdir) + "," + y0 + "V" + yminfunc(y1 - (r - overhead) * ydir, y0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir - dx2) + "," + y1 + "H" + (x1 - r * xdir + dx2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - dx1 * xdir) + "," + yminfunc(y1 - (r - overhead) * ydir, y0) + "V" + y0 + "Z"; + } + } + } else { + path = rectanglePath; + } + } else { + path = rectanglePath; + } + var sel = transition(Lib$q.ensureSingle(bar2, "path"), fullLayout, opts, makeOnCompleteCallback); + sel.style("vector-effect", isStatic ? "none" : "non-scaling-stroke").attr("d", isNaN((x1 - x0) * (y1 - y0)) || isBlank && gd._context.staticPlot ? "M0,0Z" : path).call(Drawing$6.setClipUrl, plotinfo.layerClipId, gd); + if (!fullLayout.uniformtext.mode && withTransition) { + var styleFns = Drawing$6.makePointStyleFns(trace); + Drawing$6.singlePointStyle(di, sel, trace, styleFns, gd); + } + appendBarText(gd, plotinfo, bar2, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback); + if (plotinfo.layerClipId) { + Drawing$6.hideOutsideRangePoint(di, bar2.select("text"), xa, ya, trace.xcalendar, trace.ycalendar); + } + }); + var hasClipOnAxisFalse = trace.cliponaxis === false; + Drawing$6.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd); + }); + Registry$8.getComponentMethod("errorbars", "plot")(gd, bartraces, plotinfo, opts); +} +function appendBarText(gd, plotinfo, bar2, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback) { + var xa = plotinfo.xaxis; + var ya = plotinfo.yaxis; + var fullLayout = gd._fullLayout; + var textPosition; + function appendTextNode(bar3, text2, font3) { + var textSelection2 = Lib$q.ensureSingle(bar3, "text").text(text2).attr({ + class: "bartext bartext-" + textPosition, + "text-anchor": "middle", + // prohibit tex interpretation until we can handle + // tex and regular text together + "data-notex": 1 + }).call(Drawing$6.font, font3).call(svgTextUtils$3.convertToTspans, gd); + return textSelection2; + } + var trace = cd[0].trace; + var isHorizontal = trace.orientation === "h"; + var text = getText(fullLayout, cd, i, xa, ya); + textPosition = getTextPosition(trace, i); + var inStackOrRelativeMode = opts.mode === "stack" || opts.mode === "relative"; + var calcBar = cd[i]; + var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost; + var hasB = calcBar.hasB; + var barIsRounded = r && r - overhead > TEXTPAD$3; + if (!text || textPosition === "none" || (calcBar.isBlank || x0 === x1 || y0 === y1) && (textPosition === "auto" || textPosition === "inside")) { + bar2.select("text").remove(); + return; + } + var layoutFont = fullLayout.font; + var barColor = style$3.getBarColor(cd[i], trace); + var insideTextFont = style$3.getInsideTextFont(trace, i, layoutFont, barColor); + var outsideTextFont = style$3.getOutsideTextFont(trace, i, layoutFont); + var insidetextanchor = trace.insidetextanchor || "end"; + var di = bar2.datum(); + if (isHorizontal) { + if (xa.type === "log" && di.s0 <= 0) { + if (xa.range[0] < xa.range[1]) { + x0 = 0; + } else { + x0 = xa._length; + } + } + } else { + if (ya.type === "log" && di.s0 <= 0) { + if (ya.range[0] < ya.range[1]) { + y0 = ya._length; + } else { + y0 = 0; + } + } + } + var lx = Math.abs(x1 - x0); + var ly = Math.abs(y1 - y0); + var barWidth = lx - 2 * TEXTPAD$3; + var barHeight = ly - 2 * TEXTPAD$3; + var textSelection; + var textBB; + var textWidth; + var textHeight; + var font2; + if (textPosition === "outside") { + if (!isOutmostBar && !calcBar.hasB) textPosition = "inside"; + } + if (textPosition === "auto") { + if (isOutmostBar) { + textPosition = "inside"; + font2 = Lib$q.ensureUniformFontSize(gd, insideTextFont); + textSelection = appendTextNode(bar2, text, font2); + textBB = Drawing$6.bBox(textSelection.node()); + textWidth = textBB.width; + textHeight = textBB.height; + var textHasSize = textWidth > 0 && textHeight > 0; + var fitsInside; + if (barIsRounded) { + if (hasB) { + fitsInside = textfitsInsideBar(barWidth - 2 * r, barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * r, textWidth, textHeight, isHorizontal); + } else if (isHorizontal) { + fitsInside = textfitsInsideBar(barWidth - (r - overhead), barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * (r - overhead), textWidth, textHeight, isHorizontal); + } else { + fitsInside = textfitsInsideBar(barWidth, barHeight - (r - overhead), textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth - 2 * (r - overhead), barHeight, textWidth, textHeight, isHorizontal); + } + } else { + fitsInside = textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal); + } + if (textHasSize && fitsInside) { + textPosition = "inside"; + } else { + textPosition = "outside"; + textSelection.remove(); + textSelection = null; + } + } else { + textPosition = "inside"; + } + } + if (!textSelection) { + font2 = Lib$q.ensureUniformFontSize(gd, textPosition === "outside" ? outsideTextFont : insideTextFont); + textSelection = appendTextNode(bar2, text, font2); + var currentTransform = textSelection.attr("transform"); + textSelection.attr("transform", ""); + textBB = Drawing$6.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; + textSelection.attr("transform", currentTransform); + if (textWidth <= 0 || textHeight <= 0) { + textSelection.remove(); + return; + } + } + var angle = trace.textangle; + var transform, constrained; + if (textPosition === "outside") { + constrained = trace.constraintext === "both" || trace.constraintext === "outside"; + transform = toMoveOutsideBar(x0, x1, y0, y1, textBB, { + isHorizontal, + constrained, + angle + }); + } else { + constrained = trace.constraintext === "both" || trace.constraintext === "inside"; + transform = toMoveInsideBar$1(x0, x1, y0, y1, textBB, { + isHorizontal, + constrained, + angle, + anchor: insidetextanchor, + hasB, + r, + overhead + }); + } + transform.fontSize = font2.size; + recordMinTextSize$2(trace.type === "histogram" ? "bar" : trace.type, transform, fullLayout); + calcBar.transform = transform; + var s = transition(textSelection, fullLayout, opts, makeOnCompleteCallback); + Lib$q.setTransormAndDisplay(s, transform); +} +function textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal) { + if (barWidth < 0 || barHeight < 0) return false; + var fitsInside = textWidth <= barWidth && textHeight <= barHeight; + var fitsInsideIfRotated = textWidth <= barHeight && textHeight <= barWidth; + var fitsInsideIfShrunk = isHorizontal ? barWidth >= textWidth * (barHeight / textHeight) : barHeight >= textHeight * (barWidth / textWidth); + return fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk; +} +function getRotateFromAngle(angle) { + return angle === "auto" ? 0 : angle; +} +function getRotatedTextSize(textBB, rotate2) { + var a = Math.PI / 180 * rotate2; + var absSin = Math.abs(Math.sin(a)); + var absCos = Math.abs(Math.cos(a)); + return { + x: textBB.width * absCos + textBB.height * absSin, + y: textBB.width * absSin + textBB.height * absCos + }; +} +function toMoveInsideBar$1(x0, x1, y0, y1, textBB, opts) { + var isHorizontal = !!opts.isHorizontal; + var constrained = !!opts.constrained; + var angle = opts.angle || 0; + var anchor = opts.anchor; + var isEnd = anchor === "end"; + var isStart = anchor === "start"; + var leftToRight = opts.leftToRight || 0; + var toRight = (leftToRight + 1) / 2; + var toLeft = 1 - toRight; + var hasB = opts.hasB; + var r = opts.r; + var overhead = opts.overhead; + var textWidth = textBB.width; + var textHeight = textBB.height; + var lx = Math.abs(x1 - x0); + var ly = Math.abs(y1 - y0); + var textpad = lx > 2 * TEXTPAD$3 && ly > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; + lx -= 2 * textpad; + ly -= 2 * textpad; + var rotate2 = getRotateFromAngle(angle); + if (angle === "auto" && !(textWidth <= lx && textHeight <= ly) && (textWidth > lx || textHeight > ly) && (!(textWidth > ly || textHeight > lx) || textWidth < textHeight !== lx < ly)) { + rotate2 += 90; + } + var t = getRotatedTextSize(textBB, rotate2); + var scale2, padForRounding; + if (r && r - overhead > TEXTPAD$3) { + var scaleAndPad = scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB); + scale2 = scaleAndPad.scale; + padForRounding = scaleAndPad.pad; + } else { + scale2 = 1; + if (constrained) { + scale2 = Math.min( + 1, + lx / t.x, + ly / t.y + ); + } + padForRounding = 0; + } + var textX = textBB.left * toLeft + textBB.right * toRight; + var textY = (textBB.top + textBB.bottom) / 2; + var targetX = (x0 + TEXTPAD$3) * toLeft + (x1 - TEXTPAD$3) * toRight; + var targetY = (y0 + y1) / 2; + var anchorX = 0; + var anchorY = 0; + if (isStart || isEnd) { + var extrapad = (isHorizontal ? t.x : t.y) / 2; + if (r && (isEnd || hasB)) { + textpad += padForRounding; + } + var dir = isHorizontal ? dirSign(x0, x1) : dirSign(y0, y1); + if (isHorizontal) { + if (isStart) { + targetX = x0 + dir * textpad; + anchorX = -dir * extrapad; + } else { + targetX = x1 - dir * textpad; + anchorX = dir * extrapad; + } + } else { + if (isStart) { + targetY = y0 + dir * textpad; + anchorY = -dir * extrapad; + } else { + targetY = y1 - dir * textpad; + anchorY = dir * extrapad; + } + } + } + return { + textX, + textY, + targetX, + targetY, + anchorX, + anchorY, + scale: scale2, + rotate: rotate2 + }; +} +function scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB) { + var barWidth = Math.max(0, Math.abs(x1 - x0) - 2 * TEXTPAD$3); + var barHeight = Math.max(0, Math.abs(y1 - y0) - 2 * TEXTPAD$3); + var R2 = r - TEXTPAD$3; + var clippedR = overhead ? R2 - Math.sqrt(R2 * R2 - (R2 - overhead) * (R2 - overhead)) : R2; + var rX = hasB ? R2 * 2 : isHorizontal ? R2 - overhead : 2 * clippedR; + var rY = hasB ? R2 * 2 : isHorizontal ? 2 * clippedR : R2 - overhead; + var a, b, c; + var scale2, pad2; + if (t.y / t.x >= barHeight / (barWidth - rX)) { + scale2 = barHeight / t.y; + } else if (t.y / t.x <= (barHeight - rY) / barWidth) { + scale2 = barWidth / t.x; + } else if (!hasB && isHorizontal) { + a = t.x * t.x + t.y * t.y / 4; + b = -2 * t.x * (barWidth - R2) - t.y * (barHeight / 2 - R2); + c = (barWidth - R2) * (barWidth - R2) + (barHeight / 2 - R2) * (barHeight / 2 - R2) - R2 * R2; + scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); + } else if (!hasB) { + a = t.x * t.x / 4 + t.y * t.y; + b = -t.x * (barWidth / 2 - R2) - 2 * t.y * (barHeight - R2); + c = (barWidth / 2 - R2) * (barWidth / 2 - R2) + (barHeight - R2) * (barHeight - R2) - R2 * R2; + scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); + } else { + a = (t.x * t.x + t.y * t.y) / 4; + b = -t.x * (barWidth / 2 - R2) - t.y * (barHeight / 2 - R2); + c = (barWidth / 2 - R2) * (barWidth / 2 - R2) + (barHeight / 2 - R2) * (barHeight / 2 - R2) - R2 * R2; + scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); + } + scale2 = Math.min(1, scale2); + if (isHorizontal) { + pad2 = Math.max(0, R2 - Math.sqrt(Math.max(0, R2 * R2 - (R2 - (barHeight - t.y * scale2) / 2) * (R2 - (barHeight - t.y * scale2) / 2))) - overhead); + } else { + pad2 = Math.max(0, R2 - Math.sqrt(Math.max(0, R2 * R2 - (R2 - (barWidth - t.x * scale2) / 2) * (R2 - (barWidth - t.x * scale2) / 2))) - overhead); + } + return { scale: scale2, pad: pad2 }; +} +function toMoveOutsideBar(x0, x1, y0, y1, textBB, opts) { + var isHorizontal = !!opts.isHorizontal; + var constrained = !!opts.constrained; + var angle = opts.angle || 0; + var textWidth = textBB.width; + var textHeight = textBB.height; + var lx = Math.abs(x1 - x0); + var ly = Math.abs(y1 - y0); + var textpad; + if (isHorizontal) { + textpad = ly > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; + } else { + textpad = lx > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; + } + var scale2 = 1; + if (constrained) { + scale2 = isHorizontal ? Math.min(1, ly / textHeight) : Math.min(1, lx / textWidth); + } + var rotate2 = getRotateFromAngle(angle); + var t = getRotatedTextSize(textBB, rotate2); + var extrapad = (isHorizontal ? t.x : t.y) / 2; + var textX = (textBB.left + textBB.right) / 2; + var textY = (textBB.top + textBB.bottom) / 2; + var targetX = (x0 + x1) / 2; + var targetY = (y0 + y1) / 2; + var anchorX = 0; + var anchorY = 0; + var dir = isHorizontal ? dirSign(x1, x0) : dirSign(y0, y1); + if (isHorizontal) { + targetX = x1 - dir * textpad; + anchorX = dir * extrapad; + } else { + targetY = y1 + dir * textpad; + anchorY = -dir * extrapad; + } + return { + textX, + textY, + targetX, + targetY, + anchorX, + anchorY, + scale: scale2, + rotate: rotate2 + }; +} +function getText(fullLayout, cd, index2, xa, ya) { + var trace = cd[0].trace; + var texttemplate = trace.texttemplate; + var value2; + if (texttemplate) { + value2 = calcTexttemplate(fullLayout, cd, index2, xa, ya); + } else if (trace.textinfo) { + value2 = calcTextinfo(cd, index2, xa, ya); + } else { + value2 = helpers$b.getValue(trace.text, index2); + } + return helpers$b.coerceString(attributeText, value2); +} +function getTextPosition(trace, index2) { + var value2 = helpers$b.getValue(trace.textposition, index2); + return helpers$b.coerceEnumerated(attributeTextPosition, value2); +} +function calcTexttemplate(fullLayout, cd, index2, xa, ya) { + var trace = cd[0].trace; + var texttemplate = Lib$q.castOption(trace, index2, "texttemplate"); + if (!texttemplate) return ""; + var isHistogram = trace.type === "histogram"; + var isWaterfall = trace.type === "waterfall"; + var isFunnel = trace.type === "funnel"; + var isHorizontal = trace.orientation === "h"; + var pLetter, pAxis; + var vLetter, vAxis; + if (isHorizontal) { + pLetter = "y"; + pAxis = ya; + vLetter = "x"; + vAxis = xa; + } else { + pLetter = "x"; + pAxis = xa; + vLetter = "y"; + vAxis = ya; + } + function formatLabel(u) { + return tickText(pAxis, pAxis.c2l(u), true).text; + } + function formatNumber(v) { + return tickText(vAxis, vAxis.c2l(v), true).text; + } + var cdi = cd[index2]; + var obj = {}; + obj.label = cdi.p; + obj.labelLabel = obj[pLetter + "Label"] = formatLabel(cdi.p); + var tx = Lib$q.castOption(trace, cdi.i, "text"); + if (tx === 0 || tx) obj.text = tx; + obj.value = cdi.s; + obj.valueLabel = obj[vLetter + "Label"] = formatNumber(cdi.s); + var pt = {}; + appendArrayPointValue$2(pt, trace, cdi.i); + if (isHistogram || pt.x === void 0) pt.x = isHorizontal ? obj.value : obj.label; + if (isHistogram || pt.y === void 0) pt.y = isHorizontal ? obj.label : obj.value; + if (isHistogram || pt.xLabel === void 0) pt.xLabel = isHorizontal ? obj.valueLabel : obj.labelLabel; + if (isHistogram || pt.yLabel === void 0) pt.yLabel = isHorizontal ? obj.labelLabel : obj.valueLabel; + if (isWaterfall) { + obj.delta = +cdi.rawS || cdi.s; + obj.deltaLabel = formatNumber(obj.delta); + obj.final = cdi.v; + obj.finalLabel = formatNumber(obj.final); + obj.initial = obj.final - obj.delta; + obj.initialLabel = formatNumber(obj.initial); + } + if (isFunnel) { + obj.value = cdi.s; + obj.valueLabel = formatNumber(obj.value); + obj.percentInitial = cdi.begR; + obj.percentInitialLabel = Lib$q.formatPercent(cdi.begR); + obj.percentPrevious = cdi.difR; + obj.percentPreviousLabel = Lib$q.formatPercent(cdi.difR); + obj.percentTotal = cdi.sumR; + obj.percenTotalLabel = Lib$q.formatPercent(cdi.sumR); + } + var customdata = Lib$q.castOption(trace, cdi.i, "customdata"); + if (customdata) obj.customdata = customdata; + return Lib$q.texttemplateString(texttemplate, obj, fullLayout._d3locale, pt, obj, trace._meta || {}); +} +function calcTextinfo(cd, index2, xa, ya) { + var trace = cd[0].trace; + var isHorizontal = trace.orientation === "h"; + var isWaterfall = trace.type === "waterfall"; + var isFunnel = trace.type === "funnel"; + function formatLabel(u) { + var pAxis = isHorizontal ? ya : xa; + return tickText(pAxis, u, true).text; + } + function formatNumber(v) { + var sAxis = isHorizontal ? xa : ya; + return tickText(sAxis, +v, true).text; + } + var textinfo = trace.textinfo; + var cdi = cd[index2]; + var parts = textinfo.split("+"); + var text = []; + var tx; + var hasFlag = function(flag) { + return parts.indexOf(flag) !== -1; + }; + if (hasFlag("label")) { + text.push(formatLabel(cd[index2].p)); + } + if (hasFlag("text")) { + tx = Lib$q.castOption(trace, cdi.i, "text"); + if (tx === 0 || tx) text.push(tx); + } + if (isWaterfall) { + var delta2 = +cdi.rawS || cdi.s; + var final = cdi.v; + var initial = final - delta2; + if (hasFlag("initial")) text.push(formatNumber(initial)); + if (hasFlag("delta")) text.push(formatNumber(delta2)); + if (hasFlag("final")) text.push(formatNumber(final)); + } + if (isFunnel) { + if (hasFlag("value")) text.push(formatNumber(cdi.s)); + var nPercent = 0; + if (hasFlag("percent initial")) nPercent++; + if (hasFlag("percent previous")) nPercent++; + if (hasFlag("percent total")) nPercent++; + var hasMultiplePercents = nPercent > 1; + if (hasFlag("percent initial")) { + tx = Lib$q.formatPercent(cdi.begR); + if (hasMultiplePercents) tx += " of initial"; + text.push(tx); + } + if (hasFlag("percent previous")) { + tx = Lib$q.formatPercent(cdi.difR); + if (hasMultiplePercents) tx += " of previous"; + text.push(tx); + } + if (hasFlag("percent total")) { + tx = Lib$q.formatPercent(cdi.sumR); + if (hasMultiplePercents) tx += " of total"; + text.push(tx); + } + } + return text.join("
"); +} +var plot_1$1 = { + plot: plot$5, + toMoveInsideBar: toMoveInsideBar$1 +}; +var Fx$3 = fx$1; +var Registry$7 = registry; +var Color$c = colorExports; +var fillText$1 = libExports.fillText; +var getLineWidth = helpers$d.getLineWidth; +var hoverLabelText$1 = axesExports.hoverLabelText; +var BADNUM$2 = numerical.BADNUM; +function hoverPoints$2(pointData, xval, yval, hovermode, opts) { + var barPointData = hoverOnBars(pointData, xval, yval, hovermode, opts); + if (barPointData) { + var cd = barPointData.cd; + var trace = cd[0].trace; + var di = cd[barPointData.index]; + barPointData.color = getTraceColor$1(trace, di); + Registry$7.getComponentMethod("errorbars", "hoverInfo")(di, trace, barPointData); + return [barPointData]; + } +} +function hoverOnBars(pointData, xval, yval, hovermode, opts) { + var cd = pointData.cd; + var trace = cd[0].trace; + var t = cd[0].t; + var isClosest = hovermode === "closest"; + var isWaterfall = trace.type === "waterfall"; + var maxHoverDistance = pointData.maxHoverDistance; + var maxSpikeDistance = pointData.maxSpikeDistance; + var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; + if (trace.orientation === "h") { + posVal = yval; + sizeVal = xval; + posLetter = "y"; + sizeLetter = "x"; + dx = sizeFn; + dy = positionFn; + } else { + posVal = xval; + sizeVal = yval; + posLetter = "x"; + sizeLetter = "y"; + dy = sizeFn; + dx = positionFn; + } + var period = trace[posLetter + "period"]; + var isClosestOrPeriod = isClosest || period; + function thisBarMinPos(di2) { + return thisBarExtPos(di2, -1); + } + function thisBarMaxPos(di2) { + return thisBarExtPos(di2, 1); + } + function thisBarExtPos(di2, sgn) { + var w = di2.w; + return di2[posLetter] + sgn * w / 2; + } + function periodLength(di2) { + return di2[posLetter + "End"] - di2[posLetter + "Start"]; + } + var minPos = isClosest ? thisBarMinPos : period ? function(di2) { + return di2.p - periodLength(di2) / 2; + } : function(di2) { + return Math.min(thisBarMinPos(di2), di2.p - t.bardelta / 2); + }; + var maxPos = isClosest ? thisBarMaxPos : period ? function(di2) { + return di2.p + periodLength(di2) / 2; + } : function(di2) { + return Math.max(thisBarMaxPos(di2), di2.p + t.bardelta / 2); + }; + function inbox(_minPos, _maxPos, maxDistance) { + if (opts.finiteRange) maxDistance = 0; + return Fx$3.inbox( + _minPos - posVal, + _maxPos - posVal, + maxDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1 + ); + } + function positionFn(di2) { + return inbox(minPos(di2), maxPos(di2), maxHoverDistance); + } + function thisBarPositionFn(di2) { + return inbox(thisBarMinPos(di2), thisBarMaxPos(di2), maxSpikeDistance); + } + function getSize(di2) { + var s = di2[sizeLetter]; + if (isWaterfall) { + var rawS = Math.abs(di2.rawS) || 0; + if (sizeVal > 0) { + s += rawS; + } else if (sizeVal < 0) { + s -= rawS; + } + } + return s; + } + function sizeFn(di2) { + var v = sizeVal; + var b = di2.b; + var s = getSize(di2); + return Fx$3.inbox(b - v, s - v, maxHoverDistance + (s - v) / (s - b) - 1); + } + function thisBarSizeFn(di2) { + var v = sizeVal; + var b = di2.b; + var s = getSize(di2); + return Fx$3.inbox(b - v, s - v, maxSpikeDistance + (s - v) / (s - b) - 1); + } + var pa = pointData[posLetter + "a"]; + var sa = pointData[sizeLetter + "a"]; + pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); + function dxy(di2) { + return (dx(di2) + dy(di2)) / 2; + } + var distfn = Fx$3.getDistanceFunction(hovermode, dx, dy, dxy); + Fx$3.getClosest(cd, distfn, pointData); + if (pointData.index === false) return; + if (cd[pointData.index].p === BADNUM$2) return; + if (!isClosestOrPeriod) { + minPos = function(di2) { + return Math.min(thisBarMinPos(di2), di2.p - t.bargroupwidth / 2); + }; + maxPos = function(di2) { + return Math.max(thisBarMaxPos(di2), di2.p + t.bargroupwidth / 2); + }; + } + var index2 = pointData.index; + var di = cd[index2]; + var size = trace.base ? di.b + di.s : di.s; + pointData[sizeLetter + "0"] = pointData[sizeLetter + "1"] = sa.c2p(di[sizeLetter], true); + pointData[sizeLetter + "LabelVal"] = size; + var extent2 = t.extents[t.extents.round(di.p)]; + pointData[posLetter + "0"] = pa.c2p(isClosest ? minPos(di) : extent2[0], true); + pointData[posLetter + "1"] = pa.c2p(isClosest ? maxPos(di) : extent2[1], true); + var hasPeriod = di.orig_p !== void 0; + pointData[posLetter + "LabelVal"] = hasPeriod ? di.orig_p : di.p; + pointData.labelLabel = hoverLabelText$1(pa, pointData[posLetter + "LabelVal"], trace[posLetter + "hoverformat"]); + pointData.valueLabel = hoverLabelText$1(sa, pointData[sizeLetter + "LabelVal"], trace[sizeLetter + "hoverformat"]); + pointData.baseLabel = hoverLabelText$1(sa, di.b, trace[sizeLetter + "hoverformat"]); + pointData.spikeDistance = (thisBarSizeFn(di) + thisBarPositionFn(di)) / 2; + pointData[posLetter + "Spike"] = pa.c2p(di.p, true); + fillText$1(di, trace, pointData); + pointData.hovertemplate = trace.hovertemplate; + return pointData; +} +function getTraceColor$1(trace, di) { + var mc = di.mcc || trace.marker.color; + var mlc = di.mlcc || trace.marker.line.color; + var mlw = getLineWidth(trace, di); + if (Color$c.opacity(mc)) return mc; + else if (Color$c.opacity(mlc) && mlw) return mlc; +} +var hover$4 = { + hoverPoints: hoverPoints$2 +}; +var event_data$2 = function eventData(out, pt, trace) { + out.x = "xVal" in pt ? pt.xVal : pt.x; + out.y = "yVal" in pt ? pt.yVal : pt.y; + if (pt.xa) out.xaxis = pt.xa; + if (pt.ya) out.yaxis = pt.ya; + if (trace.orientation === "h") { + out.label = out.y; + out.value = out.x; + } else { + out.label = out.x; + out.value = out.y; + } + return out; +}; +var select$2 = function selectPoints2(searchInfo, selectionTester) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var trace = cd[0].trace; + var isFunnel = trace.type === "funnel"; + var isHorizontal = trace.orientation === "h"; + var selection = []; + var i; + if (selectionTester === false) { + for (i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for (i = 0; i < cd.length; i++) { + var di = cd[i]; + var ct = "ct" in di ? di.ct : getCentroid(di, xa, ya, isHorizontal, isFunnel); + if (selectionTester.contains(ct, false, i, searchInfo)) { + selection.push({ + pointNumber: i, + x: xa.c2d(di.x), + y: ya.c2d(di.y) + }); + di.selected = 1; + } else { + di.selected = 0; + } + } + } + return selection; +}; +function getCentroid(d, xa, ya, isHorizontal, isFunnel) { + var x0 = xa.c2p(isHorizontal ? d.s0 : d.p0, true); + var x1 = xa.c2p(isHorizontal ? d.s1 : d.p1, true); + var y0 = ya.c2p(isHorizontal ? d.p0 : d.s0, true); + var y1 = ya.c2p(isHorizontal ? d.p1 : d.s1, true); + if (isFunnel) { + return [(x0 + x1) / 2, (y0 + y1) / 2]; + } else { + if (isHorizontal) { + return [x1, (y0 + y1) / 2]; + } else { + return [(x0 + x1) / 2, y1]; + } + } +} +var bar$2 = { + attributes: attributes$e, + layoutAttributes: layout_attributes$2, + supplyDefaults: defaults$6.supplyDefaults, + crossTraceDefaults: defaults$6.crossTraceDefaults, + supplyLayoutDefaults: layout_defaults$2, + calc: calc$7, + crossTraceCalc: cross_trace_calc$1.crossTraceCalc, + colorbar: marker_colorbar, + arraysToCalcdata: arrays_to_calcdata, + plot: plot_1$1.plot, + style: style_1$2.style, + styleOnSelect: style_1$2.styleOnSelect, + hoverPoints: hover$4.hoverPoints, + eventData: event_data$2, + selectPoints: select$2, + moduleType: "trace", + name: "bar", + basePlotModule: cartesian, + categories: ["bar-like", "cartesian", "svg", "bar", "oriented", "errorBarsOK", "showLegend", "zoomScale"], + animatable: true, + meta: { + description: [ + "The data visualized by the span of the bars is set in `y`", + "if `orientation` is set to *v* (the default)", + "and the labels are set in `x`.", + "By setting `orientation` to *h*, the roles are interchanged." + ].join(" ") + } +}; +var bar = bar$2; +const bar$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(bar); +var bin_attributes = function makeBinAttrs(axLetter, match) { + return { + start: { + valType: "any", + // for date axes + editType: "calc", + description: [ + "Sets the starting value for the", + axLetter, + "axis bins. Defaults to the minimum data value,", + "shifted down if necessary to make nice round values", + "and to remove ambiguous bin edges. For example, if most of the", + "data is integers we shift the bin edges 0.5 down, so a `size`", + "of 5 would have a default `start` of -0.5, so it is clear", + "that 0-4 are in the first bin, 5-9 in the second, but", + "continuous data gets a start of 0 and bins [0,5), [5,10) etc.", + "Dates behave similarly, and `start` should be a date string.", + "For category data, `start` is based on the category serial", + "numbers, and defaults to -0.5.", + match ? "If multiple non-overlaying histograms share a subplot, the first explicit `start` is used exactly and all others are shifted down (if necessary) to differ from that one by an integer number of bins." : "" + ].join(" ") + }, + end: { + valType: "any", + // for date axes + editType: "calc", + description: [ + "Sets the end value for the", + axLetter, + "axis bins. The last bin may not end exactly at this value,", + "we increment the bin edge by `size` from `start` until we", + "reach or exceed `end`. Defaults to the maximum data value.", + "Like `start`, for dates use a date string, and for category", + "data `end` is based on the category serial numbers." + ].join(" ") + }, + size: { + valType: "any", + // for date axes + editType: "calc", + description: [ + "Sets the size of each", + axLetter, + "axis bin.", + "Default behavior: If `nbins" + axLetter + "` is 0 or omitted,", + "we choose a nice round bin size such that the number of bins", + "is about the same as the typical number of samples in each bin.", + "If `nbins" + axLetter + "` is provided, we choose a nice round", + "bin size giving no more than that many bins.", + "For date data, use milliseconds or *M* for months, as in", + "`axis.dtick`. For category data, the number of categories to", + "bin together (always defaults to 1).", + match ? "If multiple non-overlaying histograms share a subplot, the first explicit `size` is used and all others discarded. If no `size` is provided,the sample data from all traces is combined to determine `size` as described above." : "" + ].join(" ") + }, + editType: "calc" + }; +}; +var constants$c = { + eventDataKeys: ["binNumber"] +}; +var barAttrs = attributes$e; +var axisHoverFormat$2 = axis_format_attributes.axisHoverFormat; +var hovertemplateAttrs$3 = template_attributes.hovertemplateAttrs; +var texttemplateAttrs$3 = template_attributes.texttemplateAttrs; +var fontAttrs$2 = font_attributes; +var makeBinAttrs2 = bin_attributes; +var constants$b = constants$c; +var extendFlat$5 = extend$5.extendFlat; +var attributes$a = { + x: { + valType: "data_array", + editType: "calc+clearAxisTypes", + description: [ + "Sets the sample data to be binned on the x axis." + ].join(" ") + }, + y: { + valType: "data_array", + editType: "calc+clearAxisTypes", + description: [ + "Sets the sample data to be binned on the y axis." + ].join(" ") + }, + xhoverformat: axisHoverFormat$2("x"), + yhoverformat: axisHoverFormat$2("y"), + text: extendFlat$5({}, barAttrs.text, { + description: [ + "Sets hover text elements associated with each bar.", + "If a single string, the same string appears over all bars.", + "If an array of string, the items are mapped in order to the", + "this trace's coordinates." + ].join(" ") + }), + hovertext: extendFlat$5({}, barAttrs.hovertext, { + description: "Same as `text`." + }), + orientation: barAttrs.orientation, + histfunc: { + valType: "enumerated", + values: ["count", "sum", "avg", "min", "max"], + dflt: "count", + editType: "calc", + description: [ + "Specifies the binning function used for this histogram trace.", + "If *count*, the histogram values are computed by counting the", + "number of values lying inside each bin.", + "If *sum*, *avg*, *min*, *max*,", + "the histogram values are computed using", + "the sum, the average, the minimum or the maximum", + "of the values lying inside each bin respectively." + ].join(" ") + }, + histnorm: { + valType: "enumerated", + values: ["", "percent", "probability", "density", "probability density"], + dflt: "", + editType: "calc", + description: [ + "Specifies the type of normalization used for this histogram trace.", + "If **, the span of each bar corresponds to the number of", + "occurrences (i.e. the number of data points lying inside the bins).", + "If *percent* / *probability*, the span of each bar corresponds to", + "the percentage / fraction of occurrences with respect to the total", + "number of sample points", + "(here, the sum of all bin HEIGHTS equals 100% / 1).", + "If *density*, the span of each bar corresponds to the number of", + "occurrences in a bin divided by the size of the bin interval", + "(here, the sum of all bin AREAS equals the", + "total number of sample points).", + "If *probability density*, the area of each bar corresponds to the", + "probability that an event will fall into the corresponding bin", + "(here, the sum of all bin AREAS equals 1)." + ].join(" ") + }, + cumulative: { + enabled: { + valType: "boolean", + dflt: false, + editType: "calc", + description: [ + "If true, display the cumulative distribution by summing the", + "binned values. Use the `direction` and `centralbin` attributes", + "to tune the accumulation method.", + "Note: in this mode, the *density* `histnorm` settings behave", + "the same as their equivalents without *density*:", + "** and *density* both rise to the number of data points, and", + "*probability* and *probability density* both rise to the", + "number of sample points." + ].join(" ") + }, + direction: { + valType: "enumerated", + values: ["increasing", "decreasing"], + dflt: "increasing", + editType: "calc", + description: [ + "Only applies if cumulative is enabled.", + "If *increasing* (default) we sum all prior bins, so the result", + "increases from left to right. If *decreasing* we sum later bins", + "so the result decreases from left to right." + ].join(" ") + }, + currentbin: { + valType: "enumerated", + values: ["include", "exclude", "half"], + dflt: "include", + editType: "calc", + description: [ + "Only applies if cumulative is enabled.", + "Sets whether the current bin is included, excluded, or has half", + "of its value included in the current cumulative value.", + "*include* is the default for compatibility with various other", + "tools, however it introduces a half-bin bias to the results.", + "*exclude* makes the opposite half-bin bias, and *half* removes", + "it." + ].join(" ") + }, + editType: "calc" + }, + nbinsx: { + valType: "integer", + min: 0, + dflt: 0, + editType: "calc", + description: [ + "Specifies the maximum number of desired bins. This value will be used", + "in an algorithm that will decide the optimal bin size such that the", + "histogram best visualizes the distribution of the data.", + "Ignored if `xbins.size` is provided." + ].join(" ") + }, + xbins: makeBinAttrs2("x", true), + nbinsy: { + valType: "integer", + min: 0, + dflt: 0, + editType: "calc", + description: [ + "Specifies the maximum number of desired bins. This value will be used", + "in an algorithm that will decide the optimal bin size such that the", + "histogram best visualizes the distribution of the data.", + "Ignored if `ybins.size` is provided." + ].join(" ") + }, + ybins: makeBinAttrs2("y", true), + autobinx: { + valType: "boolean", + dflt: null, + editType: "calc", + description: [ + "Obsolete: since v1.42 each bin attribute is auto-determined", + "separately and `autobinx` is not needed. However, we accept", + "`autobinx: true` or `false` and will update `xbins` accordingly", + "before deleting `autobinx` from the trace." + ].join(" ") + }, + autobiny: { + valType: "boolean", + dflt: null, + editType: "calc", + description: [ + "Obsolete: since v1.42 each bin attribute is auto-determined", + "separately and `autobiny` is not needed. However, we accept", + "`autobiny: true` or `false` and will update `ybins` accordingly", + "before deleting `autobiny` from the trace." + ].join(" ") + }, + bingroup: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "Set a group of histogram traces which will have compatible bin settings.", + "Note that traces on the same subplot and with the same *orientation*", + "under `barmode` *stack*, *relative* and *group* are forced into the same bingroup,", + "Using `bingroup`, traces under `barmode` *overlay* and on different axes", + "(of the same axis type) can have compatible bin settings.", + "Note that histogram and histogram2d* trace can share the same `bingroup`" + ].join(" ") + }, + hovertemplate: hovertemplateAttrs$3({}, { + keys: constants$b.eventDataKeys + }), + texttemplate: texttemplateAttrs$3({ + arrayOk: false, + editType: "plot" + }, { + keys: ["label", "value"] + }), + textposition: extendFlat$5({}, barAttrs.textposition, { + arrayOk: false + }), + textfont: fontAttrs$2({ + arrayOk: false, + editType: "plot", + colorEditType: "style", + description: "Sets the text font." + }), + outsidetextfont: fontAttrs$2({ + arrayOk: false, + editType: "plot", + colorEditType: "style", + description: "Sets the font used for `text` lying outside the bar." + }), + insidetextfont: fontAttrs$2({ + arrayOk: false, + editType: "plot", + colorEditType: "style", + description: "Sets the font used for `text` lying inside the bar." + }), + insidetextanchor: barAttrs.insidetextanchor, + textangle: barAttrs.textangle, + cliponaxis: barAttrs.cliponaxis, + constraintext: barAttrs.constraintext, + marker: barAttrs.marker, + offsetgroup: barAttrs.offsetgroup, + alignmentgroup: barAttrs.alignmentgroup, + selected: barAttrs.selected, + unselected: barAttrs.unselected, + _deprecated: { + bardir: barAttrs._deprecated.bardir + }, + zorder: barAttrs.zorder +}; +var Registry$6 = registry; +var Lib$p = libExports; +var Color$b = colorExports; +var handleText$2 = defaults$6.handleText; +var handleStyleDefaults2 = style_defaults; +var attributes$9 = attributes$a; +var defaults$5 = function supplyDefaults3(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$p.coerce(traceIn, traceOut, attributes$9, attr, dflt); + } + var x = coerce2("x"); + var y = coerce2("y"); + var cumulative = coerce2("cumulative.enabled"); + if (cumulative) { + coerce2("cumulative.direction"); + coerce2("cumulative.currentbin"); + } + coerce2("text"); + var textposition = coerce2("textposition"); + handleText$2(traceIn, traceOut, layout, coerce2, textposition, { + moduleHasSelected: true, + moduleHasUnselected: true, + moduleHasConstrain: true, + moduleHasCliponaxis: true, + moduleHasTextangle: true, + moduleHasInsideanchor: true + }); + coerce2("hovertext"); + coerce2("hovertemplate"); + coerce2("xhoverformat"); + coerce2("yhoverformat"); + var orientation = coerce2("orientation", y && !x ? "h" : "v"); + var sampleLetter = orientation === "v" ? "x" : "y"; + var aggLetter = orientation === "v" ? "y" : "x"; + var len = x && y ? Math.min(Lib$p.minRowLength(x) && Lib$p.minRowLength(y)) : Lib$p.minRowLength(traceOut[sampleLetter] || []); + if (!len) { + traceOut.visible = false; + return; + } + traceOut._length = len; + var handleCalendarDefaults = Registry$6.getComponentMethod("calendars", "handleTraceDefaults"); + handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout); + var hasAggregationData = traceOut[aggLetter]; + if (hasAggregationData) coerce2("histfunc"); + coerce2("histnorm"); + coerce2("autobin" + sampleLetter); + handleStyleDefaults2(traceIn, traceOut, coerce2, defaultColor, layout); + Lib$p.coerceSelectionMarkerOpacity(traceOut, coerce2); + var lineColor = (traceOut.marker.line || {}).color; + var errorBarsSupplyDefaults = Registry$6.getComponentMethod("errorbars", "supplyDefaults"); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$b.defaultLine, { axis: "y" }); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$b.defaultLine, { axis: "x", inherit: "y" }); + coerce2("zorder"); +}; +var Lib$o = libExports; +var axisIds = axis_ids; +var traceIs = registry.traceIs; +var handleGroupingDefaults2 = grouping_defaults; +var validateCornerradius = defaults$6.validateCornerradius; +var nestedProperty2 = Lib$o.nestedProperty; +var getAxisGroup2 = constraints.getAxisGroup; +var BINATTRS = [ + { aStr: { x: "xbins.start", y: "ybins.start" }, name: "start" }, + { aStr: { x: "xbins.end", y: "ybins.end" }, name: "end" }, + { aStr: { x: "xbins.size", y: "ybins.size" }, name: "size" }, + { aStr: { x: "nbinsx", y: "nbinsy" }, name: "nbins" } +]; +var BINDIRECTIONS = ["x", "y"]; +var cross_trace_defaults = function crossTraceDefaults4(fullData, fullLayout) { + var allBinOpts = fullLayout._histogramBinOpts = {}; + var histTraces = []; + var mustMatchTracesLookup = {}; + var otherTracesList = []; + var traceOut, traces, groupName, binDir; + var i, j, k; + function coerce2(attr2, dflt) { + return Lib$o.coerce(traceOut._input, traceOut, traceOut._module.attributes, attr2, dflt); + } + function orientation2binDir(traceOut2) { + return traceOut2.orientation === "v" ? "x" : "y"; + } + function getAxisType(traceOut2, binDir2) { + var ax = axisIds.getFromTrace({ _fullLayout: fullLayout }, traceOut2, binDir2); + return ax.type; + } + function fillBinOpts(traceOut2, groupName2, binDir2) { + var fallbackGroupName = traceOut2.uid + "__" + binDir2; + if (!groupName2) groupName2 = fallbackGroupName; + var axType = getAxisType(traceOut2, binDir2); + var calendar = traceOut2[binDir2 + "calendar"] || ""; + var binOpts2 = allBinOpts[groupName2]; + var needsNewItem = true; + if (binOpts2) { + if (axType === binOpts2.axType && calendar === binOpts2.calendar) { + needsNewItem = false; + binOpts2.traces.push(traceOut2); + binOpts2.dirs.push(binDir2); + } else { + groupName2 = fallbackGroupName; + if (axType !== binOpts2.axType) { + Lib$o.warn([ + "Attempted to group the bins of trace", + traceOut2.index, + "set on a", + "type:" + axType, + "axis", + "with bins on", + "type:" + binOpts2.axType, + "axis." + ].join(" ")); + } + if (calendar !== binOpts2.calendar) { + Lib$o.warn([ + "Attempted to group the bins of trace", + traceOut2.index, + "set with a", + calendar, + "calendar", + "with bins", + binOpts2.calendar ? "on a " + binOpts2.calendar + " calendar" : "w/o a set calendar" + ].join(" ")); + } + } + } + if (needsNewItem) { + allBinOpts[groupName2] = { + traces: [traceOut2], + dirs: [binDir2], + axType, + calendar: traceOut2[binDir2 + "calendar"] || "" + }; + } + traceOut2["_" + binDir2 + "bingroup"] = groupName2; + } + for (i = 0; i < fullData.length; i++) { + traceOut = fullData[i]; + if (traceIs(traceOut, "histogram")) { + histTraces.push(traceOut); + delete traceOut._xautoBinFinished; + delete traceOut._yautoBinFinished; + if (traceOut.type === "histogram") { + var r = coerce2("marker.cornerradius", fullLayout.barcornerradius); + if (traceOut.marker) { + traceOut.marker.cornerradius = validateCornerradius(r); + } + } + if (!traceIs(traceOut, "2dMap")) { + handleGroupingDefaults2(traceOut._input, traceOut, fullLayout, coerce2); + } + } + } + var alignmentOpts = fullLayout._alignmentOpts || {}; + for (i = 0; i < histTraces.length; i++) { + traceOut = histTraces[i]; + groupName = ""; + if (!traceIs(traceOut, "2dMap")) { + binDir = orientation2binDir(traceOut); + if (fullLayout.barmode === "group" && traceOut.alignmentgroup) { + var pa = traceOut[binDir + "axis"]; + var aGroupId = getAxisGroup2(fullLayout, pa) + traceOut.orientation; + if ((alignmentOpts[aGroupId] || {})[traceOut.alignmentgroup]) { + groupName = aGroupId; + } + } + if (!groupName && fullLayout.barmode !== "overlay") { + groupName = getAxisGroup2(fullLayout, traceOut.xaxis) + getAxisGroup2(fullLayout, traceOut.yaxis) + orientation2binDir(traceOut); + } + } + if (groupName) { + if (!mustMatchTracesLookup[groupName]) { + mustMatchTracesLookup[groupName] = []; + } + mustMatchTracesLookup[groupName].push(traceOut); + } else { + otherTracesList.push(traceOut); + } + } + for (groupName in mustMatchTracesLookup) { + traces = mustMatchTracesLookup[groupName]; + if (traces.length === 1) { + otherTracesList.push(traces[0]); + continue; + } + var binGroupFound = false; + if (traces.length) { + traceOut = traces[0]; + binGroupFound = coerce2("bingroup"); + } + groupName = binGroupFound || groupName; + for (i = 0; i < traces.length; i++) { + traceOut = traces[i]; + var bingroupIn = traceOut._input.bingroup; + if (bingroupIn && bingroupIn !== groupName) { + Lib$o.warn([ + "Trace", + traceOut.index, + "must match", + "within bingroup", + groupName + ".", + "Ignoring its bingroup:", + bingroupIn, + "setting." + ].join(" ")); + } + traceOut.bingroup = groupName; + fillBinOpts(traceOut, groupName, orientation2binDir(traceOut)); + } + } + for (i = 0; i < otherTracesList.length; i++) { + traceOut = otherTracesList[i]; + var binGroup = coerce2("bingroup"); + if (traceIs(traceOut, "2dMap")) { + for (k = 0; k < 2; k++) { + binDir = BINDIRECTIONS[k]; + var binGroupInDir = coerce2( + binDir + "bingroup", + binGroup ? binGroup + "__" + binDir : null + ); + fillBinOpts(traceOut, binGroupInDir, binDir); + } + } else { + fillBinOpts(traceOut, binGroup, orientation2binDir(traceOut)); + } + } + for (groupName in allBinOpts) { + var binOpts = allBinOpts[groupName]; + traces = binOpts.traces; + for (j = 0; j < BINATTRS.length; j++) { + var attrSpec = BINATTRS[j]; + var attr = attrSpec.name; + var aStr; + var autoVals; + if (attr === "nbins" && binOpts.sizeFound) continue; + for (i = 0; i < traces.length; i++) { + traceOut = traces[i]; + binDir = binOpts.dirs[i]; + aStr = attrSpec.aStr[binDir]; + if (nestedProperty2(traceOut._input, aStr).get() !== void 0) { + binOpts[attr] = coerce2(aStr); + binOpts[attr + "Found"] = true; + break; + } + autoVals = (traceOut._autoBin || {})[binDir] || {}; + if (autoVals[attr]) { + nestedProperty2(traceOut, aStr).set(autoVals[attr]); + } + } + if (attr === "start" || attr === "end") { + for (; i < traces.length; i++) { + traceOut = traces[i]; + if (traceOut["_" + binDir + "bingroup"]) { + autoVals = (traceOut._autoBin || {})[binDir] || {}; + coerce2(aStr, autoVals[attr]); + } + } + } + if (attr === "nbins" && !binOpts.sizeFound && !binOpts.nbinsFound) { + traceOut = traces[0]; + binOpts[attr] = coerce2(aStr); + } + } + } +}; +var isNumeric$5 = fastIsnumeric; +var bin_functions = { + count: function(n, i, size) { + size[n]++; + return 1; + }, + sum: function(n, i, size, counterData) { + var v = counterData[i]; + if (isNumeric$5(v)) { + v = Number(v); + size[n] += v; + return v; + } + return 0; + }, + avg: function(n, i, size, counterData, counts) { + var v = counterData[i]; + if (isNumeric$5(v)) { + v = Number(v); + size[n] += v; + counts[n]++; + } + return 0; + }, + min: function(n, i, size, counterData) { + var v = counterData[i]; + if (isNumeric$5(v)) { + v = Number(v); + if (!isNumeric$5(size[n])) { + size[n] = v; + return v; + } else if (size[n] > v) { + var delta2 = v - size[n]; + size[n] = v; + return delta2; + } + } + return 0; + }, + max: function(n, i, size, counterData) { + var v = counterData[i]; + if (isNumeric$5(v)) { + v = Number(v); + if (!isNumeric$5(size[n])) { + size[n] = v; + return v; + } else if (size[n] < v) { + var delta2 = v - size[n]; + size[n] = v; + return delta2; + } + } + return 0; + } +}; +var norm_functions = { + percent: function(size, total) { + var nMax = size.length; + var norm2 = 100 / total; + for (var n = 0; n < nMax; n++) size[n] *= norm2; + }, + probability: function(size, total) { + var nMax = size.length; + for (var n = 0; n < nMax; n++) size[n] /= total; + }, + density: function(size, total, inc, yinc) { + var nMax = size.length; + yinc = yinc || 1; + for (var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; + }, + "probability density": function(size, total, inc, yinc) { + var nMax = size.length; + if (yinc) total /= yinc; + for (var n = 0; n < nMax; n++) size[n] *= inc[n] / total; + } +}; +var average = function doAvg(size, counts) { + var nMax = size.length; + var total = 0; + for (var i = 0; i < nMax; i++) { + if (counts[i]) { + size[i] /= counts[i]; + total += size[i]; + } else size[i] = null; + } + return total; +}; +var numConstants = numerical; +var oneYear = numConstants.ONEAVGYEAR; +var oneMonth = numConstants.ONEAVGMONTH; +var oneDay = numConstants.ONEDAY; +var oneHour = numConstants.ONEHOUR; +var oneMin = numConstants.ONEMIN; +var oneSec = numConstants.ONESEC; +var tickIncrement = axesExports.tickIncrement; +var bin_label_vals = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) { + var dv0 = -1.1 * rightGap; + var dv1 = -0.1 * rightGap; + var dv2 = leftGap - dv1; + var edge0 = binEdges[0]; + var edge1 = binEdges[1]; + var leftDigit = Math.min( + biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar), + biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar) + ); + var rightDigit = Math.min( + biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar), + biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar) + ); + var digit, disambiguateEdges; + if (leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4e3) { + digit = leftDigit; + disambiguateEdges = false; + } else { + digit = Math.min(leftDigit, rightDigit); + disambiguateEdges = true; + } + if (pa.type === "date" && digit > oneDay) { + var dashExclude = digit === oneYear ? 1 : 6; + var increment2 = digit === oneYear ? "M12" : "M1"; + return function(v, isRightEdge) { + var dateStr = pa.c2d(v, oneYear, calendar); + var dashPos = dateStr.indexOf("-", dashExclude); + if (dashPos > 0) dateStr = dateStr.substr(0, dashPos); + var roundedV = pa.d2c(dateStr, 0, calendar); + if (roundedV < v) { + var nextV = tickIncrement(roundedV, increment2, false, calendar); + if ((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; + } + if (isRightEdge && disambiguateEdges) { + return tickIncrement(roundedV, increment2, true, calendar); + } + return roundedV; + }; + } + return function(v, isRightEdge) { + var roundedV = digit * Math.round(v / digit); + if (roundedV + digit / 10 < v && roundedV + digit * 0.9 < v + leftGap) { + roundedV += digit; + } + if (isRightEdge && disambiguateEdges) { + roundedV -= digit; + } + return roundedV; + }; +}; +function biggestDigitChanged(v1, v2, pa, calendar) { + if (v1 * v2 <= 0) return Infinity; + var dv2 = Math.abs(v2 - v1); + var isDate = pa.type === "date"; + var digit = biggestGuaranteedDigitChanged(dv2, isDate); + for (var i = 0; i < 10; i++) { + var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate); + if (digit === nextDigit) break; + if (didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit; + else break; + } + return digit; +} +function biggestGuaranteedDigitChanged(dv2, isDate) { + if (isDate && dv2 > oneSec) { + if (dv2 > oneDay) { + if (dv2 > oneYear * 1.1) return oneYear; + if (dv2 > oneMonth * 1.1) return oneMonth; + return oneDay; + } + if (dv2 > oneHour) return oneHour; + if (dv2 > oneMin) return oneMin; + return oneSec; + } + return Math.pow(10, Math.floor(Math.log(dv2) / Math.LN10)); +} +function didDigitChange(digit, v1, v2, isDate, pa, calendar) { + if (isDate && digit > oneDay) { + var dateParts1 = dateParts(v1, pa, calendar); + var dateParts2 = dateParts(v2, pa, calendar); + var parti = digit === oneYear ? 0 : 1; + return dateParts1[parti] !== dateParts2[parti]; + } + return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; +} +function dateParts(v, pa, calendar) { + var parts = pa.c2d(v, oneYear, calendar).split("-"); + if (parts[0] === "") { + parts.unshift(); + parts[0] = "-" + parts[0]; + } + return parts; +} +var isNumeric$4 = fastIsnumeric; +var Lib$n = libExports; +var Registry$5 = registry; +var Axes$2 = axesExports; +var arraysToCalcdata3 = arrays_to_calcdata; +var binFunctions = bin_functions; +var normFunctions = norm_functions; +var doAvg2 = average; +var getBinSpanLabelRound2 = bin_label_vals; +function calc$6(gd, trace) { + var pos = []; + var size = []; + var isHorizontal = trace.orientation === "h"; + var pa = Axes$2.getFromId(gd, isHorizontal ? trace.yaxis : trace.xaxis); + var mainData = isHorizontal ? "y" : "x"; + var counterData = { x: "y", y: "x" }[mainData]; + var calendar = trace[mainData + "calendar"]; + var cumulativeSpec = trace.cumulative; + var i; + var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); + var binSpec = binsAndPos[0]; + var pos0 = binsAndPos[1]; + var nonuniformBins = typeof binSpec.size === "string"; + var binEdges = []; + var bins = nonuniformBins ? binEdges : binSpec; + var inc = []; + var counts = []; + var inputPoints = []; + var total = 0; + var norm2 = trace.histnorm; + var func = trace.histfunc; + var densityNorm = norm2.indexOf("density") !== -1; + var i2, binEnd, n; + if (cumulativeSpec.enabled && densityNorm) { + norm2 = norm2.replace(/ ?density$/, ""); + densityNorm = false; + } + var extremeFunc = func === "max" || func === "min"; + var sizeInit = extremeFunc ? null : 0; + var binFunc = binFunctions.count; + var normFunc = normFunctions[norm2]; + var isAvg = false; + var pr2c = function(v) { + return pa.r2c(v, 0, calendar); + }; + var rawCounterData; + if (Lib$n.isArrayOrTypedArray(trace[counterData]) && func !== "count") { + rawCounterData = trace[counterData]; + isAvg = func === "avg"; + binFunc = binFunctions[func]; + } + i = pr2c(binSpec.start); + binEnd = pr2c(binSpec.end) + (i - Axes$2.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; + while (i < binEnd && pos.length < 1e6) { + i2 = Axes$2.tickIncrement(i, binSpec.size, false, calendar); + pos.push((i + i2) / 2); + size.push(sizeInit); + inputPoints.push([]); + binEdges.push(i); + if (densityNorm) inc.push(1 / (i2 - i)); + if (isAvg) counts.push(0); + if (i2 <= i) break; + i = i2; + } + binEdges.push(i); + if (!nonuniformBins && pa.type === "date") { + bins = { + start: pr2c(bins.start), + end: pr2c(bins.end), + size: bins.size + }; + } + if (!gd._fullLayout._roundFnOpts) gd._fullLayout._roundFnOpts = {}; + var groupName = trace["_" + mainData + "bingroup"]; + var roundFnOpts = { leftGap: Infinity, rightGap: Infinity }; + if (groupName) { + if (!gd._fullLayout._roundFnOpts[groupName]) gd._fullLayout._roundFnOpts[groupName] = roundFnOpts; + roundFnOpts = gd._fullLayout._roundFnOpts[groupName]; + } + var nMax = size.length; + var uniqueValsPerBin = true; + var leftGap = roundFnOpts.leftGap; + var rightGap = roundFnOpts.rightGap; + var ptNumber2cdIndex = {}; + for (i = 0; i < pos0.length; i++) { + var posi = pos0[i]; + n = Lib$n.findBin(posi, bins); + if (n >= 0 && n < nMax) { + total += binFunc(n, i, size, rawCounterData, counts); + if (uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) { + uniqueValsPerBin = false; + } + inputPoints[n].push(i); + ptNumber2cdIndex[i] = n; + leftGap = Math.min(leftGap, posi - binEdges[n]); + rightGap = Math.min(rightGap, binEdges[n + 1] - posi); + } + } + roundFnOpts.leftGap = leftGap; + roundFnOpts.rightGap = rightGap; + var roundFn; + if (!uniqueValsPerBin) { + roundFn = function(v, isRightEdge) { + return function() { + var roundFnOpts2 = gd._fullLayout._roundFnOpts[groupName]; + return getBinSpanLabelRound2( + roundFnOpts2.leftGap, + roundFnOpts2.rightGap, + binEdges, + pa, + calendar + )(v, isRightEdge); + }; + }; + } + if (isAvg) total = doAvg2(size, counts); + if (normFunc) normFunc(size, total, inc); + if (cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin); + var seriesLen = Math.min(pos.length, size.length); + var cd = []; + var firstNonzero = 0; + var lastNonzero = seriesLen - 1; + for (i = 0; i < seriesLen; i++) { + if (size[i]) { + firstNonzero = i; + break; + } + } + for (i = seriesLen - 1; i >= firstNonzero; i--) { + if (size[i]) { + lastNonzero = i; + break; + } + } + for (i = firstNonzero; i <= lastNonzero; i++) { + if (isNumeric$4(pos[i]) && isNumeric$4(size[i])) { + var cdi = { + p: pos[i], + s: size[i], + b: 0 + }; + if (!cumulativeSpec.enabled) { + cdi.pts = inputPoints[i]; + if (uniqueValsPerBin) { + cdi.ph0 = cdi.ph1 = inputPoints[i].length ? pos0[inputPoints[i][0]] : pos[i]; + } else { + trace._computePh = true; + cdi.ph0 = roundFn(binEdges[i]); + cdi.ph1 = roundFn(binEdges[i + 1], true); + } + } + cd.push(cdi); + } + } + if (cd.length === 1) { + cd[0].width1 = Axes$2.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; + } + arraysToCalcdata3(cd, trace); + if (Lib$n.isArrayOrTypedArray(trace.selectedpoints)) { + Lib$n.tagSelected(cd, trace, ptNumber2cdIndex); + } + return cd; +} +function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { + var binAttr = mainData + "bins"; + var fullLayout = gd._fullLayout; + var groupName = trace["_" + mainData + "bingroup"]; + var binOpts = fullLayout._histogramBinOpts[groupName]; + var isOverlay = fullLayout.barmode === "overlay"; + var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec; + var r2c = function(v) { + return pa.r2c(v, 0, calendar); + }; + var c2r = function(v) { + return pa.c2r(v, 0, calendar); + }; + var cleanBound = pa.type === "date" ? function(v) { + return v || v === 0 ? Lib$n.cleanDate(v, null, calendar) : null; + } : function(v) { + return isNumeric$4(v) ? Number(v) : null; + }; + function setBound(attr, bins, newBins) { + if (bins[attr + "Found"]) { + bins[attr] = cleanBound(bins[attr]); + if (bins[attr] === null) bins[attr] = newBins[attr]; + } else { + autoVals[attr] = bins[attr] = newBins[attr]; + Lib$n.nestedProperty(traces[0], binAttr + "." + attr).set(newBins[attr]); + } + } + if (trace["_" + mainData + "autoBinFinished"]) { + delete trace["_" + mainData + "autoBinFinished"]; + } else { + traces = binOpts.traces; + var allPos = []; + var isFirstVisible = true; + var has2dMap = false; + var hasHist2dContour = false; + for (i = 0; i < traces.length; i++) { + tracei = traces[i]; + if (tracei.visible) { + var mainDatai = binOpts.dirs[i]; + pos0 = tracei["_" + mainDatai + "pos0"] = pa.makeCalcdata(tracei, mainDatai); + allPos = Lib$n.concat(allPos, pos0); + delete tracei["_" + mainData + "autoBinFinished"]; + if (trace.visible === true) { + if (isFirstVisible) { + isFirstVisible = false; + } else { + delete tracei._autoBin; + tracei["_" + mainData + "autoBinFinished"] = 1; + } + if (Registry$5.traceIs(tracei, "2dMap")) { + has2dMap = true; + } + if (tracei.type === "histogram2dcontour") { + hasHist2dContour = true; + } + } + } + } + calendar = traces[0][mainData + "calendar"]; + var newBinSpec = Axes$2.autoBin(allPos, pa, binOpts.nbins, has2dMap, calendar, binOpts.sizeFound && binOpts.size); + var autoBin = traces[0]._autoBin = {}; + autoVals = autoBin[binOpts.dirs[0]] = {}; + if (hasHist2dContour) { + if (!binOpts.size) { + newBinSpec.start = c2r(Axes$2.tickIncrement( + r2c(newBinSpec.start), + newBinSpec.size, + true, + calendar + )); + } + if (binOpts.end === void 0) { + newBinSpec.end = c2r(Axes$2.tickIncrement( + r2c(newBinSpec.end), + newBinSpec.size, + false, + calendar + )); + } + } + if (isOverlay && !Registry$5.traceIs(trace, "2dMap") && newBinSpec._dataSpan === 0 && pa.type !== "category" && pa.type !== "multicategory" && trace.bingroup === "" && typeof trace.xbins === "undefined") { + if (_overlayEdgeCase) return [newBinSpec, pos0, true]; + newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr); + } + cumulativeSpec = tracei.cumulative || {}; + if (cumulativeSpec.enabled && cumulativeSpec.currentbin !== "include") { + if (cumulativeSpec.direction === "decreasing") { + newBinSpec.start = c2r(Axes$2.tickIncrement( + r2c(newBinSpec.start), + newBinSpec.size, + true, + calendar + )); + } else { + newBinSpec.end = c2r(Axes$2.tickIncrement( + r2c(newBinSpec.end), + newBinSpec.size, + false, + calendar + )); + } + } + binOpts.size = newBinSpec.size; + if (!binOpts.sizeFound) { + autoVals.size = newBinSpec.size; + Lib$n.nestedProperty(traces[0], binAttr + ".size").set(newBinSpec.size); + } + setBound("start", binOpts, newBinSpec); + setBound("end", binOpts, newBinSpec); + } + pos0 = trace["_" + mainData + "pos0"]; + delete trace["_" + mainData + "pos0"]; + var traceInputBins = trace._input[binAttr] || {}; + var traceBinOptsCalc = Lib$n.extendFlat({}, binOpts); + var mainStart = binOpts.start; + var startIn = pa.r2l(traceInputBins.start); + var hasStart = startIn !== void 0; + if ((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) { + var traceStart = hasStart ? startIn : Lib$n.aggNums(Math.min, null, pos0); + var dummyAx = { + type: pa.type === "category" || pa.type === "multicategory" ? "linear" : pa.type, + r2l: pa.r2l, + dtick: binOpts.size, + tick0: mainStart, + calendar, + range: [traceStart, Axes$2.tickIncrement(traceStart, binOpts.size, false, calendar)].map(pa.l2r) + }; + var newStart = Axes$2.tickFirst(dummyAx); + if (newStart > pa.r2l(traceStart)) { + newStart = Axes$2.tickIncrement(newStart, binOpts.size, true, calendar); + } + traceBinOptsCalc.start = pa.l2r(newStart); + if (!hasStart) Lib$n.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.start); + } + var mainEnd = binOpts.end; + var endIn = pa.r2l(traceInputBins.end); + var hasEnd = endIn !== void 0; + if ((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) { + var traceEnd = hasEnd ? endIn : Lib$n.aggNums(Math.max, null, pos0); + traceBinOptsCalc.end = pa.l2r(traceEnd); + if (!hasEnd) Lib$n.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.end); + } + var autoBinAttr = "autobin" + mainData; + if (trace._input[autoBinAttr] === false) { + trace._input[binAttr] = Lib$n.extendFlat({}, trace[binAttr] || {}); + delete trace._input[autoBinAttr]; + delete trace[autoBinAttr]; + } + return [traceBinOptsCalc, pos0]; +} +function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { + var fullLayout = gd._fullLayout; + var overlaidTraceGroup = getConnectedHistograms(gd, trace); + var pastThisTrace = false; + var minSize = Infinity; + var singleValuedTraces = [trace]; + var i, tracei, binOpts; + for (i = 0; i < overlaidTraceGroup.length; i++) { + tracei = overlaidTraceGroup[i]; + if (tracei === trace) { + pastThisTrace = true; + } else if (!pastThisTrace) { + binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]]; + minSize = Math.min(minSize, binOpts.size || tracei[binAttr].size); + } else { + var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true); + var binSpeci = resulti[0]; + var isSingleValued = resulti[2]; + tracei["_" + mainData + "autoBinFinished"] = 1; + tracei["_" + mainData + "pos0"] = resulti[1]; + if (isSingleValued) { + singleValuedTraces.push(tracei); + } else { + minSize = Math.min(minSize, binSpeci.size); + } + } + } + var dataVals = new Array(singleValuedTraces.length); + for (i = 0; i < singleValuedTraces.length; i++) { + var pos0 = singleValuedTraces[i]["_" + mainData + "pos0"]; + for (var j = 0; j < pos0.length; j++) { + if (pos0[j] !== void 0) { + dataVals[i] = pos0[j]; + break; + } + } + } + if (!isFinite(minSize)) { + minSize = Lib$n.distinctVals(dataVals).minDiff; + } + for (i = 0; i < singleValuedTraces.length; i++) { + tracei = singleValuedTraces[i]; + var calendar = tracei[mainData + "calendar"]; + var newBins = { + start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar), + end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar), + size: minSize + }; + tracei._input[binAttr] = tracei[binAttr] = newBins; + binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]]; + if (binOpts) Lib$n.extendFlat(binOpts, newBins); + } + return trace[binAttr]; +} +function getConnectedHistograms(gd, trace) { + var xid = trace.xaxis; + var yid = trace.yaxis; + var orientation = trace.orientation; + var out = []; + var fullData = gd._fullData; + for (var i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; + if (tracei.type === "histogram" && tracei.visible === true && tracei.orientation === orientation && tracei.xaxis === xid && tracei.yaxis === yid) { + out.push(tracei); + } + } + return out; +} +function cdf(size, direction, currentBin) { + var i, vi, prevSum; + function firstHalfPoint(i2) { + prevSum = size[i2]; + size[i2] /= 2; + } + function nextHalfPoint(i2) { + vi = size[i2]; + size[i2] = prevSum + vi / 2; + prevSum += vi; + } + if (currentBin === "half") { + if (direction === "increasing") { + firstHalfPoint(0); + for (i = 1; i < size.length; i++) { + nextHalfPoint(i); + } + } else { + firstHalfPoint(size.length - 1); + for (i = size.length - 2; i >= 0; i--) { + nextHalfPoint(i); + } + } + } else if (direction === "increasing") { + for (i = 1; i < size.length; i++) { + size[i] += size[i - 1]; + } + if (currentBin === "exclude") { + size.unshift(0); + size.pop(); + } + } else { + for (i = size.length - 2; i >= 0; i--) { + size[i] += size[i + 1]; + } + if (currentBin === "exclude") { + size.push(0); + size.shift(); + } + } +} +var calc_1$2 = { + calc: calc$6 +}; +var barHover = hover$4.hoverPoints; +var hoverLabelText = axesExports.hoverLabelText; +var hover$3 = function hoverPoints2(pointData, xval, yval, hovermode, opts) { + var pts = barHover(pointData, xval, yval, hovermode, opts); + if (!pts) return; + pointData = pts[0]; + var di = pointData.cd[pointData.index]; + var trace = pointData.cd[0].trace; + if (!trace.cumulative.enabled) { + var posLetter = trace.orientation === "h" ? "y" : "x"; + pointData[posLetter + "Label"] = hoverLabelText(pointData[posLetter + "a"], [di.ph0, di.ph1], trace[posLetter + "hoverformat"]); + } + return pts; +}; +var event_data$1 = function eventData2(out, pt, trace, cd, pointNumber) { + out.x = "xVal" in pt ? pt.xVal : pt.x; + out.y = "yVal" in pt ? pt.yVal : pt.y; + if ("zLabelVal" in pt) out.z = pt.zLabelVal; + if (pt.xa) out.xaxis = pt.xa; + if (pt.ya) out.yaxis = pt.ya; + if (!(trace.cumulative || {}).enabled) { + var pts = Array.isArray(pointNumber) ? cd[0].pts[pointNumber[0]][pointNumber[1]] : cd[pointNumber].pts; + out.pointNumbers = pts; + out.binNumber = out.pointNumber; + delete out.pointNumber; + delete out.pointIndex; + var pointIndices; + if (trace._indexToPoints) { + pointIndices = []; + for (var i = 0; i < pts.length; i++) { + pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]); + } + } else { + pointIndices = pts; + } + out.pointIndices = pointIndices; + } + return out; +}; +var histogram$2 = { + attributes: attributes$a, + layoutAttributes: layout_attributes$2, + supplyDefaults: defaults$5, + crossTraceDefaults: cross_trace_defaults, + supplyLayoutDefaults: layout_defaults$2, + calc: calc_1$2.calc, + crossTraceCalc: cross_trace_calc$1.crossTraceCalc, + plot: plot_1$1.plot, + layerName: "barlayer", + style: style_1$2.style, + styleOnSelect: style_1$2.styleOnSelect, + colorbar: marker_colorbar, + hoverPoints: hover$3, + selectPoints: select$2, + eventData: event_data$1, + moduleType: "trace", + name: "histogram", + basePlotModule: cartesian, + categories: ["bar-like", "cartesian", "svg", "bar", "histogram", "oriented", "errorBarsOK", "showLegend"], + meta: { + description: [ + "The sample data from which statistics are computed is set in `x`", + "for vertically spanning histograms and", + "in `y` for horizontally spanning histograms.", + "Binning options are set `xbins` and `ybins` respectively", + "if no aggregation data is provided." + ].join(" ") + } +}; +var histogram = histogram$2; +const histogram$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(histogram); +var baseAttrs$2 = attributes$O; +var domainAttrs$2 = domain.attributes; +var fontAttrs$1 = font_attributes; +var colorAttrs = attributes$N; +var hovertemplateAttrs$2 = template_attributes.hovertemplateAttrs; +var texttemplateAttrs$2 = template_attributes.texttemplateAttrs; +var extendFlat$4 = extend$5.extendFlat; +var pattern$2 = attributes$M.pattern; +var textFontAttrs = fontAttrs$1({ + editType: "plot", + arrayOk: true, + colorEditType: "plot", + description: "Sets the font used for `textinfo`." +}); +var attributes$8 = { + labels: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the sector labels.", + "If `labels` entries are duplicated, we sum associated `values`", + "or simply count occurrences if `values` is not provided.", + "For other array attributes (including color) we use the first", + "non-empty entry among all occurrences of the label." + ].join(" ") + }, + // equivalent of x0 and dx, if label is missing + label0: { + valType: "number", + dflt: 0, + editType: "calc", + description: [ + "Alternate to `labels`.", + "Builds a numeric set of labels.", + "Use with `dlabel`", + "where `label0` is the starting label and `dlabel` the step." + ].join(" ") + }, + dlabel: { + valType: "number", + dflt: 1, + editType: "calc", + description: "Sets the label step. See `label0` for more info." + }, + values: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the values of the sectors.", + "If omitted, we count occurrences of each label." + ].join(" ") + }, + marker: { + colors: { + valType: "data_array", + // TODO 'color_array' ? + editType: "calc", + description: [ + "Sets the color of each sector.", + "If not specified, the default trace color set is used", + "to pick the sector colors." + ].join(" ") + }, + line: { + color: { + valType: "color", + dflt: colorAttrs.defaultLine, + arrayOk: true, + editType: "style", + description: [ + "Sets the color of the line enclosing each sector." + ].join(" ") + }, + width: { + valType: "number", + min: 0, + dflt: 0, + arrayOk: true, + editType: "style", + description: [ + "Sets the width (in px) of the line enclosing each sector." + ].join(" ") + }, + editType: "calc" + }, + pattern: pattern$2, + editType: "calc" + }, + text: { + valType: "data_array", + editType: "plot", + description: [ + "Sets text elements associated with each sector.", + "If trace `textinfo` contains a *text* flag, these elements will be seen", + "on the chart.", + "If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,", + "these elements will be seen in the hover labels." + ].join(" ") + }, + hovertext: { + valType: "string", + dflt: "", + arrayOk: true, + editType: "style", + description: [ + "Sets hover text elements associated with each sector.", + "If a single string, the same string appears for", + "all data points.", + "If an array of string, the items are mapped in order of", + "this trace's sectors.", + "To be seen, trace `hoverinfo` must contain a *text* flag." + ].join(" ") + }, + // 'see eg:' + // 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif', + // '(this example involves a map too - may someday be a whole trace type', + // 'of its own. but the point is the size of the whole pie is important.)' + scalegroup: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "If there are multiple pie charts that should be sized according to", + "their totals, link them by providing a non-empty group id here", + "shared by every trace in the same group." + ].join(" ") + }, + // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels) + textinfo: { + valType: "flaglist", + flags: ["label", "text", "value", "percent"], + extras: ["none"], + editType: "calc", + description: [ + "Determines which trace information appear on the graph." + ].join(" ") + }, + hoverinfo: extendFlat$4({}, baseAttrs$2.hoverinfo, { + flags: ["label", "text", "value", "percent", "name"] + }), + hovertemplate: hovertemplateAttrs$2({}, { + keys: ["label", "color", "value", "percent", "text"] + }), + texttemplate: texttemplateAttrs$2({ editType: "plot" }, { + keys: ["label", "color", "value", "percent", "text"] + }), + textposition: { + valType: "enumerated", + values: ["inside", "outside", "auto", "none"], + dflt: "auto", + arrayOk: true, + editType: "plot", + description: [ + "Specifies the location of the `textinfo`." + ].join(" ") + }, + textfont: extendFlat$4({}, textFontAttrs, { + description: "Sets the font used for `textinfo`." + }), + insidetextorientation: { + valType: "enumerated", + values: ["horizontal", "radial", "tangential", "auto"], + dflt: "auto", + editType: "plot", + description: [ + "Controls the orientation of the text inside chart sectors.", + "When set to *auto*, text may be oriented in any direction in order", + "to be as big as possible in the middle of a sector.", + "The *horizontal* option orients text to be parallel with the bottom", + "of the chart, and may make text smaller in order to achieve that goal.", + "The *radial* option orients text along the radius of the sector.", + "The *tangential* option orients text perpendicular to the radius of the sector." + ].join(" ") + }, + insidetextfont: extendFlat$4({}, textFontAttrs, { + description: "Sets the font used for `textinfo` lying inside the sector." + }), + outsidetextfont: extendFlat$4({}, textFontAttrs, { + description: "Sets the font used for `textinfo` lying outside the sector." + }), + automargin: { + valType: "boolean", + dflt: false, + editType: "plot", + description: [ + "Determines whether outside text labels can push the margins." + ].join(" ") + }, + title: { + text: { + valType: "string", + dflt: "", + editType: "plot", + description: [ + "Sets the title of the chart.", + "If it is empty, no title is displayed.", + "Note that before the existence of `title.text`, the title's", + "contents used to be defined as the `title` attribute itself.", + "This behavior has been deprecated." + ].join(" ") + }, + font: extendFlat$4({}, textFontAttrs, { + description: [ + "Sets the font used for `title`.", + "Note that the title's font used to be set", + "by the now deprecated `titlefont` attribute." + ].join(" ") + }), + position: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle center", + "bottom left", + "bottom center", + "bottom right" + ], + editType: "plot", + description: [ + "Specifies the location of the `title`.", + "Note that the title's position used to be set", + "by the now deprecated `titleposition` attribute." + ].join(" ") + }, + editType: "plot" + }, + // position and shape + domain: domainAttrs$2({ name: "pie", trace: true, editType: "calc" }), + hole: { + valType: "number", + min: 0, + max: 1, + dflt: 0, + editType: "calc", + description: [ + "Sets the fraction of the radius to cut out of the pie.", + "Use this to make a donut chart." + ].join(" ") + }, + // ordering and direction + sort: { + valType: "boolean", + dflt: true, + editType: "calc", + description: [ + "Determines whether or not the sectors are reordered", + "from largest to smallest." + ].join(" ") + }, + direction: { + /** + * there are two common conventions, both of which place the first + * (largest, if sorted) slice with its left edge at 12 o'clock but + * succeeding slices follow either cw or ccw from there. + * + * see http://visage.co/data-visualization-101-pie-charts/ + */ + valType: "enumerated", + values: ["clockwise", "counterclockwise"], + dflt: "counterclockwise", + editType: "calc", + description: [ + "Specifies the direction at which succeeding sectors follow", + "one another." + ].join(" ") + }, + rotation: { + valType: "angle", + dflt: 0, + editType: "calc", + description: [ + "Instead of the first slice starting at 12 o'clock,", + "rotate to some other angle." + ].join(" ") + }, + pull: { + valType: "number", + min: 0, + max: 1, + dflt: 0, + arrayOk: true, + editType: "calc", + description: [ + "Sets the fraction of larger radius to pull the sectors", + "out from the center. This can be a constant", + "to pull all slices apart from each other equally", + "or an array to highlight one or more slices." + ].join(" ") + }, + _deprecated: { + title: { + valType: "string", + dflt: "", + editType: "calc", + description: [ + "Deprecated in favor of `title.text`.", + "Note that value of `title` is no longer a simple", + "*string* but a set of sub-attributes." + ].join(" ") + }, + titlefont: extendFlat$4({}, textFontAttrs, { + description: "Deprecated in favor of `title.font`." + }), + titleposition: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle center", + "bottom left", + "bottom center", + "bottom right" + ], + editType: "calc", + description: "Deprecated in favor of `title.position`." + } + } +}; +var isNumeric$3 = fastIsnumeric; +var Lib$m = libExports; +var attributes$7 = attributes$8; +var handleDomainDefaults$1 = domain.defaults; +var handleText$1 = defaults$6.handleText; +var coercePattern = libExports.coercePattern; +function handleLabelsAndValues(labels, values) { + var hasLabels = Lib$m.isArrayOrTypedArray(labels); + var hasValues = Lib$m.isArrayOrTypedArray(values); + var len = Math.min( + hasLabels ? labels.length : Infinity, + hasValues ? values.length : Infinity + ); + if (!isFinite(len)) len = 0; + if (len && hasValues) { + var hasPositive; + for (var i = 0; i < len; i++) { + var v = values[i]; + if (isNumeric$3(v) && v > 0) { + hasPositive = true; + break; + } + } + if (!hasPositive) len = 0; + } + return { + hasLabels, + hasValues, + len + }; +} +function handleMarkerDefaults$2(traceIn, traceOut, layout, coerce2, isPie) { + var lineWidth = coerce2("marker.line.width"); + if (lineWidth) { + coerce2( + "marker.line.color", + isPie ? void 0 : layout.paper_bgcolor + // case of funnelarea, sunburst, icicle, treemap + ); + } + var markerColors = coerce2("marker.colors"); + coercePattern(coerce2, "marker.pattern", markerColors); + if (traceIn.marker && !traceOut.marker.pattern.fgcolor) traceOut.marker.pattern.fgcolor = traceIn.marker.colors; + if (!traceOut.marker.pattern.bgcolor) traceOut.marker.pattern.bgcolor = layout.paper_bgcolor; +} +function supplyDefaults4(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$m.coerce(traceIn, traceOut, attributes$7, attr, dflt); + } + var labels = coerce2("labels"); + var values = coerce2("values"); + var res = handleLabelsAndValues(labels, values); + var len = res.len; + traceOut._hasLabels = res.hasLabels; + traceOut._hasValues = res.hasValues; + if (!traceOut._hasLabels && traceOut._hasValues) { + coerce2("label0"); + coerce2("dlabel"); + } + if (!len) { + traceOut.visible = false; + return; + } + traceOut._length = len; + handleMarkerDefaults$2(traceIn, traceOut, layout, coerce2, true); + coerce2("scalegroup"); + var textData = coerce2("text"); + var textTemplate = coerce2("texttemplate"); + var textInfo; + if (!textTemplate) textInfo = coerce2("textinfo", Lib$m.isArrayOrTypedArray(textData) ? "text+percent" : "percent"); + coerce2("hovertext"); + coerce2("hovertemplate"); + if (textTemplate || textInfo && textInfo !== "none") { + var textposition = coerce2("textposition"); + handleText$1(traceIn, traceOut, layout, coerce2, textposition, { + moduleHasSelected: false, + moduleHasUnselected: false, + moduleHasConstrain: false, + moduleHasCliponaxis: false, + moduleHasTextangle: false, + moduleHasInsideanchor: false + }); + var hasBoth = Array.isArray(textposition) || textposition === "auto"; + var hasOutside = hasBoth || textposition === "outside"; + if (hasOutside) { + coerce2("automargin"); + } + if (textposition === "inside" || textposition === "auto" || Array.isArray(textposition)) { + coerce2("insidetextorientation"); + } + } else if (textInfo === "none") { + coerce2("textposition", "none"); + } + handleDomainDefaults$1(traceOut, layout, coerce2); + var hole = coerce2("hole"); + var title = coerce2("title.text"); + if (title) { + var titlePosition = coerce2("title.position", hole ? "middle center" : "top center"); + if (!hole && titlePosition === "middle center") traceOut.title.position = "top center"; + Lib$m.coerceFont(coerce2, "title.font", layout.font); + } + coerce2("sort"); + coerce2("direction"); + coerce2("rotation"); + coerce2("pull"); +} +var defaults$4 = { + handleMarkerDefaults: handleMarkerDefaults$2, + supplyDefaults: supplyDefaults4 +}; +var layout_attributes$1 = { + hiddenlabels: { + valType: "data_array", + editType: "calc", + description: [ + "hiddenlabels is the funnelarea & pie chart analog of", + "visible:'legendonly'", + "but it can contain many labels, and can simultaneously", + "hide slices from several pies/funnelarea charts" + ].join(" ") + }, + piecolorway: { + valType: "colorlist", + editType: "calc", + description: [ + "Sets the default pie slice colors. Defaults to the main", + "`colorway` used for trace colors. If you specify a new", + "list here it can still be extended with lighter and darker", + "colors, see `extendpiecolors`." + ].join(" ") + }, + extendpiecolors: { + valType: "boolean", + dflt: true, + editType: "calc", + description: [ + "If `true`, the pie slice colors (whether given by `piecolorway` or", + "inherited from `colorway`) will be extended to three times its", + "original length by first repeating every color 20% lighter then", + "each color 20% darker. This is intended to reduce the likelihood", + "of reusing the same color when you have many slices, but you can", + "set `false` to disable.", + "Colors provided in the trace, using `marker.colors`, are never", + "extended." + ].join(" ") + } +}; +var Lib$l = libExports; +var layoutAttributes$1 = layout_attributes$1; +var layout_defaults$1 = function supplyLayoutDefaults8(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$l.coerce(layoutIn, layoutOut, layoutAttributes$1, attr, dflt); + } + coerce2("hiddenlabels"); + coerce2("piecolorway", layoutOut.colorway); + coerce2("extendpiecolors"); +}; +var isNumeric$2 = fastIsnumeric; +var tinycolor = tinycolorExports; +var Color$a = colorExports; +var extendedColorWayList = {}; +function calc$5(gd, trace) { + var cd = []; + var fullLayout = gd._fullLayout; + var hiddenLabels = fullLayout.hiddenlabels || []; + var labels = trace.labels; + var colors = trace.marker.colors || []; + var vals = trace.values; + var len = trace._length; + var hasValues = trace._hasValues && len; + var i, pt; + if (trace.dlabel) { + labels = new Array(len); + for (i = 0; i < len; i++) { + labels[i] = String(trace.label0 + i * trace.dlabel); + } + } + var allThisTraceLabels = {}; + var pullColor = makePullColorFn(fullLayout["_" + trace.type + "colormap"]); + var vTotal = 0; + var isAggregated = false; + for (i = 0; i < len; i++) { + var v, label, hidden; + if (hasValues) { + v = vals[i]; + if (!isNumeric$2(v)) continue; + v = +v; + } else v = 1; + label = labels[i]; + if (label === void 0 || label === "") label = i; + label = String(label); + var thisLabelIndex = allThisTraceLabels[label]; + if (thisLabelIndex === void 0) { + allThisTraceLabels[label] = cd.length; + hidden = hiddenLabels.indexOf(label) !== -1; + if (!hidden) vTotal += v; + cd.push({ + v, + label, + color: pullColor(colors[i], label), + i, + pts: [i], + hidden + }); + } else { + isAggregated = true; + pt = cd[thisLabelIndex]; + pt.v += v; + pt.pts.push(i); + if (!pt.hidden) vTotal += v; + if (pt.color === false && colors[i]) { + pt.color = pullColor(colors[i], label); + } + } + } + cd = cd.filter(function(elem) { + return elem.v >= 0; + }); + var shouldSort = trace.type === "funnelarea" ? isAggregated : trace.sort; + if (shouldSort) cd.sort(function(a, b) { + return b.v - a.v; + }); + if (cd[0]) cd[0].vTotal = vTotal; + return cd; +} +function makePullColorFn(colorMap) { + return function pullColor(color2, id) { + if (!color2) return false; + color2 = tinycolor(color2); + if (!color2.isValid()) return false; + color2 = Color$a.addOpacity(color2, color2.getAlpha()); + if (!colorMap[id]) colorMap[id] = color2; + return color2; + }; +} +function crossTraceCalc2(gd, plotinfo) { + var desiredType = (plotinfo || {}).type; + if (!desiredType) desiredType = "pie"; + var fullLayout = gd._fullLayout; + var calcdata = gd.calcdata; + var colorWay = fullLayout[desiredType + "colorway"]; + var colorMap = fullLayout["_" + desiredType + "colormap"]; + if (fullLayout["extend" + desiredType + "colors"]) { + colorWay = generateExtendedColors(colorWay, extendedColorWayList); + } + var dfltColorCount = 0; + for (var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var traceType = cd[0].trace.type; + if (traceType !== desiredType) continue; + for (var j = 0; j < cd.length; j++) { + var pt = cd[j]; + if (pt.color === false) { + if (colorMap[pt.label]) { + pt.color = colorMap[pt.label]; + } else { + colorMap[pt.label] = pt.color = colorWay[dfltColorCount % colorWay.length]; + dfltColorCount++; + } + } + } + } +} +function generateExtendedColors(colorList, extendedColorWays) { + var i; + var colorString = JSON.stringify(colorList); + var colors = extendedColorWays[colorString]; + if (!colors) { + colors = colorList.slice(); + for (i = 0; i < colorList.length; i++) { + colors.push(tinycolor(colorList[i]).lighten(20).toHexString()); + } + for (i = 0; i < colorList.length; i++) { + colors.push(tinycolor(colorList[i]).darken(20).toHexString()); + } + extendedColorWays[colorString] = colors; + } + return colors; +} +var calc_1$1 = { + calc: calc$5, + crossTraceCalc: crossTraceCalc2, + makePullColorFn, + generateExtendedColors +}; +var appendArrayMultiPointValues = helpers$J.appendArrayMultiPointValues; +var event_data = function eventData3(pt, trace) { + var out = { + curveNumber: trace.index, + pointNumbers: pt.pts, + data: trace._input, + fullData: trace, + label: pt.label, + color: pt.color, + value: pt.v, + percent: pt.percent, + text: pt.text, + bbox: pt.bbox, + // pt.v (and pt.i below) for backward compatibility + v: pt.v + }; + if (pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0]; + appendArrayMultiPointValues(out, trace, pt.pts); + if (trace.type === "funnelarea") { + delete out.v; + delete out.i; + } + return out; +}; +var d3$9 = d3Exports; +var Plots = plotsExports; +var Fx$2 = fx$1; +var Color$9 = colorExports; +var Drawing$5 = drawingExports; +var Lib$k = libExports; +var strScale = Lib$k.strScale; +var strTranslate = Lib$k.strTranslate; +var svgTextUtils$2 = svg_text_utils; +var uniformText$2 = uniform_text; +var recordMinTextSize$1 = uniformText$2.recordMinTextSize; +var clearMinTextSize$1 = uniformText$2.clearMinTextSize; +var TEXTPAD$2 = constants$f.TEXTPAD; +var helpers$a = helpers$F; +var eventData4 = event_data; +var isValidTextValue = libExports.isValidTextValue; +function plot$4(gd, cdModule) { + var isStatic = gd._context.staticPlot; + var fullLayout = gd._fullLayout; + var gs = fullLayout._size; + clearMinTextSize$1("pie", fullLayout); + prerenderTitles(cdModule, gd); + layoutAreas(cdModule, gs); + var plotGroups = Lib$k.makeTraceGroups(fullLayout._pielayer, cdModule, "trace").each(function(cd) { + var plotGroup = d3$9.select(this); + var cd0 = cd[0]; + var trace = cd0.trace; + setCoords(cd); + plotGroup.attr("stroke-linejoin", "round"); + plotGroup.each(function() { + var slices = d3$9.select(this).selectAll("g.slice").data(cd); + slices.enter().append("g").classed("slice", true); + slices.exit().remove(); + var quadrants = [ + [[], []], + // y<0: x<0, x>=0 + [[], []] + // y>=0: x<0, x>=0 + ]; + var hasOutsideText = false; + slices.each(function(pt, i) { + if (pt.hidden) { + d3$9.select(this).selectAll("path,g").remove(); + return; + } + pt.pointNumber = pt.i; + pt.curveNumber = trace.index; + quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt); + var cx = cd0.cx; + var cy = cd0.cy; + var sliceTop = d3$9.select(this); + var slicePath = sliceTop.selectAll("path.surface").data([pt]); + slicePath.enter().append("path").classed("surface", true).style({ "pointer-events": isStatic ? "none" : "all" }); + sliceTop.call(attachFxHandlers$2, gd, cd); + if (trace.pull) { + var pull = +helpers$a.castOption(trace.pull, pt.pts) || 0; + if (pull > 0) { + cx += pull * pt.pxmid[0]; + cy += pull * pt.pxmid[1]; + } + } + pt.cxFinal = cx; + pt.cyFinal = cy; + function arc2(start, finish, cw, scale2) { + var dx = scale2 * (finish[0] - start[0]); + var dy = scale2 * (finish[1] - start[1]); + return "a" + scale2 * cd0.r + "," + scale2 * cd0.r + " 0 " + pt.largeArc + (cw ? " 1 " : " 0 ") + dx + "," + dy; + } + var hole = trace.hole; + if (pt.v === cd0.vTotal) { + var outerCircle = "M" + (cx + pt.px0[0]) + "," + (cy + pt.px0[1]) + arc2(pt.px0, pt.pxmid, true, 1) + arc2(pt.pxmid, pt.px0, true, 1) + "Z"; + if (hole) { + slicePath.attr( + "d", + "M" + (cx + hole * pt.px0[0]) + "," + (cy + hole * pt.px0[1]) + arc2(pt.px0, pt.pxmid, false, hole) + arc2(pt.pxmid, pt.px0, false, hole) + "Z" + outerCircle + ); + } else slicePath.attr("d", outerCircle); + } else { + var outerArc = arc2(pt.px0, pt.px1, true, 1); + if (hole) { + var rim = 1 - hole; + slicePath.attr( + "d", + "M" + (cx + hole * pt.px1[0]) + "," + (cy + hole * pt.px1[1]) + arc2(pt.px1, pt.px0, false, hole) + "l" + rim * pt.px0[0] + "," + rim * pt.px0[1] + outerArc + "Z" + ); + } else { + slicePath.attr( + "d", + "M" + cx + "," + cy + "l" + pt.px0[0] + "," + pt.px0[1] + outerArc + "Z" + ); + } + } + formatSliceLabel$1(gd, pt, cd0); + var textPosition = helpers$a.castOption(trace.textposition, pt.pts); + var sliceTextGroup = sliceTop.selectAll("g.slicetext").data(pt.text && textPosition !== "none" ? [0] : []); + sliceTextGroup.enter().append("g").classed("slicetext", true); + sliceTextGroup.exit().remove(); + sliceTextGroup.each(function() { + var sliceText = Lib$k.ensureSingle(d3$9.select(this), "text", "", function(s) { + s.attr("data-notex", 1); + }); + var font2 = Lib$k.ensureUniformFontSize( + gd, + textPosition === "outside" ? determineOutsideTextFont(trace, pt, fullLayout.font) : determineInsideTextFont(trace, pt, fullLayout.font) + ); + sliceText.text(pt.text).attr({ + class: "slicetext", + transform: "", + "text-anchor": "middle" + }).call(Drawing$5.font, font2).call(svgTextUtils$2.convertToTspans, gd); + var textBB = Drawing$5.bBox(sliceText.node()); + var transform; + if (textPosition === "outside") { + transform = transformOutsideText(textBB, pt); + } else { + transform = transformInsideText(textBB, pt, cd0); + if (textPosition === "auto" && transform.scale < 1) { + var newFont = Lib$k.ensureUniformFontSize(gd, trace.outsidetextfont); + sliceText.call(Drawing$5.font, newFont); + textBB = Drawing$5.bBox(sliceText.node()); + transform = transformOutsideText(textBB, pt); + } + } + var textPosAngle = transform.textPosAngle; + var textXY = textPosAngle === void 0 ? pt.pxmid : getCoords(cd0.r, textPosAngle); + transform.targetX = cx + textXY[0] * transform.rCenter + (transform.x || 0); + transform.targetY = cy + textXY[1] * transform.rCenter + (transform.y || 0); + computeTransform(transform, textBB); + if (transform.outside) { + var targetY = transform.targetY; + pt.yLabelMin = targetY - textBB.height / 2; + pt.yLabelMid = targetY; + pt.yLabelMax = targetY + textBB.height / 2; + pt.labelExtraX = 0; + pt.labelExtraY = 0; + hasOutsideText = true; + } + transform.fontSize = font2.size; + recordMinTextSize$1(trace.type, transform, fullLayout); + cd[i].transform = transform; + Lib$k.setTransormAndDisplay(sliceText, transform); + }); + }); + var titleTextGroup = d3$9.select(this).selectAll("g.titletext").data(trace.title.text ? [0] : []); + titleTextGroup.enter().append("g").classed("titletext", true); + titleTextGroup.exit().remove(); + titleTextGroup.each(function() { + var titleText = Lib$k.ensureSingle(d3$9.select(this), "text", "", function(s) { + s.attr("data-notex", 1); + }); + var txt = trace.title.text; + if (trace._meta) { + txt = Lib$k.templateString(txt, trace._meta); + } + titleText.text(txt).attr({ + class: "titletext", + transform: "", + "text-anchor": "middle" + }).call(Drawing$5.font, trace.title.font).call(svgTextUtils$2.convertToTspans, gd); + var transform; + if (trace.title.position === "middle center") { + transform = positionTitleInside(cd0); + } else { + transform = positionTitleOutside(cd0, gs); + } + titleText.attr( + "transform", + strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty) + ); + }); + if (hasOutsideText) scootLabels(quadrants, trace); + plotTextLines(slices, trace); + if (hasOutsideText && trace.automargin) { + var traceBbox = Drawing$5.bBox(plotGroup.node()); + var domain2 = trace.domain; + var vpw = gs.w * (domain2.x[1] - domain2.x[0]); + var vph = gs.h * (domain2.y[1] - domain2.y[0]); + var xgap = (0.5 * vpw - cd0.r) / gs.w; + var ygap = (0.5 * vph - cd0.r) / gs.h; + Plots.autoMargin(gd, "pie." + trace.uid + ".automargin", { + xl: domain2.x[0] - xgap, + xr: domain2.x[1] + xgap, + yb: domain2.y[0] - ygap, + yt: domain2.y[1] + ygap, + l: Math.max(cd0.cx - cd0.r - traceBbox.left, 0), + r: Math.max(traceBbox.right - (cd0.cx + cd0.r), 0), + b: Math.max(traceBbox.bottom - (cd0.cy + cd0.r), 0), + t: Math.max(cd0.cy - cd0.r - traceBbox.top, 0), + pad: 5 + }); + } + }); + }); + setTimeout(function() { + plotGroups.selectAll("tspan").each(function() { + var s = d3$9.select(this); + if (s.attr("dy")) s.attr("dy", s.attr("dy")); + }); + }, 0); +} +function plotTextLines(slices, trace) { + slices.each(function(pt) { + var sliceTop = d3$9.select(this); + if (!pt.labelExtraX && !pt.labelExtraY) { + sliceTop.select("path.textline").remove(); + return; + } + var sliceText = sliceTop.select("g.slicetext text"); + pt.transform.targetX += pt.labelExtraX; + pt.transform.targetY += pt.labelExtraY; + Lib$k.setTransormAndDisplay(sliceText, pt.transform); + var lineStartX = pt.cxFinal + pt.pxmid[0]; + var lineStartY = pt.cyFinal + pt.pxmid[1]; + var textLinePath = "M" + lineStartX + "," + lineStartY; + var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4; + if (pt.labelExtraX) { + var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0]; + var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]); + if (Math.abs(yFromX) > Math.abs(yNet)) { + textLinePath += "l" + yNet * pt.pxmid[0] / pt.pxmid[1] + "," + yNet + "H" + (lineStartX + pt.labelExtraX + finalX); + } else { + textLinePath += "l" + pt.labelExtraX + "," + yFromX + "v" + (yNet - yFromX) + "h" + finalX; + } + } else { + textLinePath += "V" + (pt.yLabelMid + pt.labelExtraY) + "h" + finalX; + } + Lib$k.ensureSingle(sliceTop, "path", "textline").call(Color$9.stroke, trace.outsidetextfont.color).attr({ + "stroke-width": Math.min(2, trace.outsidetextfont.size / 8), + d: textLinePath, + fill: "none" + }); + }); +} +function attachFxHandlers$2(sliceTop, gd, cd) { + var cd0 = cd[0]; + var cx = cd0.cx; + var cy = cd0.cy; + var trace = cd0.trace; + var isFunnelArea = trace.type === "funnelarea"; + if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false; + if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false; + sliceTop.on("mouseover", function(pt) { + var fullLayout2 = gd._fullLayout; + var trace2 = gd._fullData[trace.index]; + if (gd._dragging || fullLayout2.hovermode === false) return; + var hoverinfo = trace2.hoverinfo; + if (Array.isArray(hoverinfo)) { + hoverinfo = Fx$2.castHoverinfo({ + hoverinfo: [helpers$a.castOption(hoverinfo, pt.pts)], + _module: trace._module + }, fullLayout2, 0); + } + if (hoverinfo === "all") hoverinfo = "label+text+value+percent+name"; + if (trace2.hovertemplate || hoverinfo !== "none" && hoverinfo !== "skip" && hoverinfo) { + var rInscribed = pt.rInscribed || 0; + var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed); + var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed); + var separators = fullLayout2.separators; + var text = []; + if (hoverinfo && hoverinfo.indexOf("label") !== -1) text.push(pt.label); + pt.text = helpers$a.castOption(trace2.hovertext || trace2.text, pt.pts); + if (hoverinfo && hoverinfo.indexOf("text") !== -1) { + var tx = pt.text; + if (Lib$k.isValidTextValue(tx)) text.push(tx); + } + pt.value = pt.v; + pt.valueLabel = helpers$a.formatPieValue(pt.v, separators); + if (hoverinfo && hoverinfo.indexOf("value") !== -1) text.push(pt.valueLabel); + pt.percent = pt.v / cd0.vTotal; + pt.percentLabel = helpers$a.formatPiePercent(pt.percent, separators); + if (hoverinfo && hoverinfo.indexOf("percent") !== -1) text.push(pt.percentLabel); + var hoverLabel = trace2.hoverlabel; + var hoverFont = hoverLabel.font; + var bbox = []; + Fx$2.loneHover({ + trace, + x0: hoverCenterX - rInscribed * cd0.r, + x1: hoverCenterX + rInscribed * cd0.r, + y: hoverCenterY, + _x0: isFunnelArea ? cx + pt.TL[0] : hoverCenterX - rInscribed * cd0.r, + _x1: isFunnelArea ? cx + pt.TR[0] : hoverCenterX + rInscribed * cd0.r, + _y0: isFunnelArea ? cy + pt.TL[1] : hoverCenterY - rInscribed * cd0.r, + _y1: isFunnelArea ? cy + pt.BL[1] : hoverCenterY + rInscribed * cd0.r, + text: text.join("
"), + name: trace2.hovertemplate || hoverinfo.indexOf("name") !== -1 ? trace2.name : void 0, + idealAlign: pt.pxmid[0] < 0 ? "left" : "right", + color: helpers$a.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, + borderColor: helpers$a.castOption(hoverLabel.bordercolor, pt.pts), + fontFamily: helpers$a.castOption(hoverFont.family, pt.pts), + fontSize: helpers$a.castOption(hoverFont.size, pt.pts), + fontColor: helpers$a.castOption(hoverFont.color, pt.pts), + nameLength: helpers$a.castOption(hoverLabel.namelength, pt.pts), + textAlign: helpers$a.castOption(hoverLabel.align, pt.pts), + hovertemplate: helpers$a.castOption(trace2.hovertemplate, pt.pts), + hovertemplateLabels: pt, + eventData: [eventData4(pt, trace2)] + }, { + container: fullLayout2._hoverlayer.node(), + outerContainer: fullLayout2._paper.node(), + gd, + inOut_bbox: bbox + }); + pt.bbox = bbox[0]; + trace._hasHoverLabel = true; + } + trace._hasHoverEvent = true; + gd.emit("plotly_hover", { + points: [eventData4(pt, trace2)], + event: d3$9.event + }); + }); + sliceTop.on("mouseout", function(evt) { + var fullLayout2 = gd._fullLayout; + var trace2 = gd._fullData[trace.index]; + var pt = d3$9.select(this).datum(); + if (trace._hasHoverEvent) { + evt.originalEvent = d3$9.event; + gd.emit("plotly_unhover", { + points: [eventData4(pt, trace2)], + event: d3$9.event + }); + trace._hasHoverEvent = false; + } + if (trace._hasHoverLabel) { + Fx$2.loneUnhover(fullLayout2._hoverlayer.node()); + trace._hasHoverLabel = false; + } + }); + sliceTop.on("click", function(pt) { + var fullLayout2 = gd._fullLayout; + var trace2 = gd._fullData[trace.index]; + if (gd._dragging || fullLayout2.hovermode === false) return; + gd._hoverdata = [eventData4(pt, trace2)]; + Fx$2.click(gd, d3$9.event); + }); +} +function determineOutsideTextFont(trace, pt, layoutFont) { + var color2 = helpers$a.castOption(trace.outsidetextfont.color, pt.pts) || helpers$a.castOption(trace.textfont.color, pt.pts) || layoutFont.color; + var family = helpers$a.castOption(trace.outsidetextfont.family, pt.pts) || helpers$a.castOption(trace.textfont.family, pt.pts) || layoutFont.family; + var size = helpers$a.castOption(trace.outsidetextfont.size, pt.pts) || helpers$a.castOption(trace.textfont.size, pt.pts) || layoutFont.size; + var weight = helpers$a.castOption(trace.outsidetextfont.weight, pt.pts) || helpers$a.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight; + var style5 = helpers$a.castOption(trace.outsidetextfont.style, pt.pts) || helpers$a.castOption(trace.textfont.style, pt.pts) || layoutFont.style; + var variant = helpers$a.castOption(trace.outsidetextfont.variant, pt.pts) || helpers$a.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant; + var textcase = helpers$a.castOption(trace.outsidetextfont.textcase, pt.pts) || helpers$a.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase; + var lineposition = helpers$a.castOption(trace.outsidetextfont.lineposition, pt.pts) || helpers$a.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition; + var shadow = helpers$a.castOption(trace.outsidetextfont.shadow, pt.pts) || helpers$a.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow; + return { + color: color2, + family, + size, + weight, + style: style5, + variant, + textcase, + lineposition, + shadow + }; +} +function determineInsideTextFont(trace, pt, layoutFont) { + var customColor = helpers$a.castOption(trace.insidetextfont.color, pt.pts); + if (!customColor && trace._input.textfont) { + customColor = helpers$a.castOption(trace._input.textfont.color, pt.pts); + } + var family = helpers$a.castOption(trace.insidetextfont.family, pt.pts) || helpers$a.castOption(trace.textfont.family, pt.pts) || layoutFont.family; + var size = helpers$a.castOption(trace.insidetextfont.size, pt.pts) || helpers$a.castOption(trace.textfont.size, pt.pts) || layoutFont.size; + var weight = helpers$a.castOption(trace.insidetextfont.weight, pt.pts) || helpers$a.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight; + var style5 = helpers$a.castOption(trace.insidetextfont.style, pt.pts) || helpers$a.castOption(trace.textfont.style, pt.pts) || layoutFont.style; + var variant = helpers$a.castOption(trace.insidetextfont.variant, pt.pts) || helpers$a.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant; + var textcase = helpers$a.castOption(trace.insidetextfont.textcase, pt.pts) || helpers$a.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase; + var lineposition = helpers$a.castOption(trace.insidetextfont.lineposition, pt.pts) || helpers$a.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition; + var shadow = helpers$a.castOption(trace.insidetextfont.shadow, pt.pts) || helpers$a.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow; + return { + color: customColor || Color$9.contrast(pt.color), + family, + size, + weight, + style: style5, + variant, + textcase, + lineposition, + shadow + }; +} +function prerenderTitles(cdModule, gd) { + var cd0, trace; + for (var i = 0; i < cdModule.length; i++) { + cd0 = cdModule[i][0]; + trace = cd0.trace; + if (trace.title.text) { + var txt = trace.title.text; + if (trace._meta) { + txt = Lib$k.templateString(txt, trace._meta); + } + var dummyTitle = Drawing$5.tester.append("text").attr("data-notex", 1).text(txt).call(Drawing$5.font, trace.title.font).call(svgTextUtils$2.convertToTspans, gd); + var bBox = Drawing$5.bBox(dummyTitle.node(), true); + cd0.titleBox = { + width: bBox.width, + height: bBox.height + }; + dummyTitle.remove(); + } + } +} +function transformInsideText(textBB, pt, cd0) { + var r = cd0.r || pt.rpx1; + var rInscribed = pt.rInscribed; + var isEmpty = pt.startangle === pt.stopangle; + if (isEmpty) { + return { + rCenter: 1 - rInscribed, + scale: 0, + rotate: 0, + textPosAngle: 0 + }; + } + var ring = pt.ring; + var isCircle = ring === 1 && Math.abs(pt.startangle - pt.stopangle) === Math.PI * 2; + var halfAngle = pt.halfangle; + var midAngle = pt.midangle; + var orientation = cd0.trace.insidetextorientation; + var isHorizontal = orientation === "horizontal"; + var isTangential = orientation === "tangential"; + var isRadial = orientation === "radial"; + var isAuto = orientation === "auto"; + var allTransforms = []; + var newT; + if (!isAuto) { + var considerCrossing = function(angle, key) { + if (isCrossing(pt, angle)) { + var dStart = Math.abs(angle - pt.startangle); + var dStop = Math.abs(angle - pt.stopangle); + var closestEdge = dStart < dStop ? dStart : dStop; + if (key === "tan") { + newT = calcTanTransform(textBB, r, ring, closestEdge, 0); + } else { + newT = calcRadTransform(textBB, r, ring, closestEdge, Math.PI / 2); + } + newT.textPosAngle = angle; + allTransforms.push(newT); + } + }; + var i; + if (isHorizontal || isTangential) { + for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * i, "tan"); + for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1), "tan"); + } + if (isHorizontal || isRadial) { + for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1.5), "rad"); + for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 0.5), "rad"); + } + } + if (isCircle || isAuto || isHorizontal) { + var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height); + newT = { + scale: rInscribed * r * 2 / textDiameter, + // and the center position and rotation in this case + rCenter: 1 - rInscribed, + rotate: 0 + }; + newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; + if (newT.scale >= 1) return newT; + allTransforms.push(newT); + } + if (isAuto || isRadial) { + newT = calcRadTransform(textBB, r, ring, halfAngle, midAngle); + newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; + allTransforms.push(newT); + } + if (isAuto || isTangential) { + newT = calcTanTransform(textBB, r, ring, halfAngle, midAngle); + newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; + allTransforms.push(newT); + } + var id = 0; + var maxScale = 0; + for (var k = 0; k < allTransforms.length; k++) { + var s = allTransforms[k].scale; + if (maxScale < s) { + maxScale = s; + id = k; + } + if (!isAuto && maxScale >= 1) { + break; + } + } + return allTransforms[id]; +} +function isCrossing(pt, angle) { + var start = pt.startangle; + var stop = pt.stopangle; + return start > angle && angle > stop || start < angle && angle < stop; +} +function calcRadTransform(textBB, r, ring, halfAngle, midAngle) { + r = Math.max(0, r - 2 * TEXTPAD$2); + var a = textBB.width / textBB.height; + var s = calcMaxHalfSize(a, halfAngle, r, ring); + return { + scale: s * 2 / textBB.height, + rCenter: calcRCenter(a, s / r), + rotate: calcRotate(midAngle) + }; +} +function calcTanTransform(textBB, r, ring, halfAngle, midAngle) { + r = Math.max(0, r - 2 * TEXTPAD$2); + var a = textBB.height / textBB.width; + var s = calcMaxHalfSize(a, halfAngle, r, ring); + return { + scale: s * 2 / textBB.width, + rCenter: calcRCenter(a, s / r), + rotate: calcRotate(midAngle + Math.PI / 2) + }; +} +function calcRCenter(a, b) { + return Math.cos(b) - a * b; +} +function calcRotate(t) { + return (180 / Math.PI * t + 720) % 180 - 90; +} +function calcMaxHalfSize(a, halfAngle, r, ring) { + var q = a + 1 / (2 * Math.tan(halfAngle)); + return r * Math.min( + 1 / (Math.sqrt(q * q + 0.5) + q), + ring / (Math.sqrt(a * a + ring / 2) + a) + ); +} +function getInscribedRadiusFraction(pt, cd0) { + if (pt.v === cd0.vTotal && !cd0.trace.hole) return 1; + return Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2); +} +function transformOutsideText(textBB, pt) { + var x = pt.pxmid[0]; + var y = pt.pxmid[1]; + var dx = textBB.width / 2; + var dy = textBB.height / 2; + if (x < 0) dx *= -1; + if (y < 0) dy *= -1; + return { + scale: 1, + rCenter: 1, + rotate: 0, + x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2, + y: dy / (1 + x * x / (y * y)), + outside: true + }; +} +function positionTitleInside(cd0) { + var textDiameter = Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height); + return { + x: cd0.cx, + y: cd0.cy, + scale: cd0.trace.hole * cd0.r * 2 / textDiameter, + tx: 0, + ty: -cd0.titleBox.height / 2 + cd0.trace.title.font.size + }; +} +function positionTitleOutside(cd0, plotSize) { + var scaleX = 1; + var scaleY = 1; + var maxPull; + var trace = cd0.trace; + var topMiddle = { + x: cd0.cx, + y: cd0.cy + }; + var translate2 = { + tx: 0, + ty: 0 + }; + translate2.ty += trace.title.font.size; + maxPull = getMaxPull(trace); + if (trace.title.position.indexOf("top") !== -1) { + topMiddle.y -= (1 + maxPull) * cd0.r; + translate2.ty -= cd0.titleBox.height; + } else if (trace.title.position.indexOf("bottom") !== -1) { + topMiddle.y += (1 + maxPull) * cd0.r; + } + var rx = applyAspectRatio(cd0.r, cd0.trace.aspectratio); + var maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2; + if (trace.title.position.indexOf("left") !== -1) { + maxWidth = maxWidth + rx; + topMiddle.x -= (1 + maxPull) * rx; + translate2.tx += cd0.titleBox.width / 2; + } else if (trace.title.position.indexOf("center") !== -1) { + maxWidth *= 2; + } else if (trace.title.position.indexOf("right") !== -1) { + maxWidth = maxWidth + rx; + topMiddle.x += (1 + maxPull) * rx; + translate2.tx -= cd0.titleBox.width / 2; + } + scaleX = maxWidth / cd0.titleBox.width; + scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height; + return { + x: topMiddle.x, + y: topMiddle.y, + scale: Math.min(scaleX, scaleY), + tx: translate2.tx, + ty: translate2.ty + }; +} +function applyAspectRatio(x, aspectratio) { + return x / (aspectratio === void 0 ? 1 : aspectratio); +} +function getTitleSpace(cd0, plotSize) { + var trace = cd0.trace; + var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]); + return Math.min(cd0.titleBox.height, pieBoxHeight / 2); +} +function getMaxPull(trace) { + var maxPull = trace.pull; + if (!maxPull) return 0; + var j; + if (Lib$k.isArrayOrTypedArray(maxPull)) { + maxPull = 0; + for (j = 0; j < trace.pull.length; j++) { + if (trace.pull[j] > maxPull) maxPull = trace.pull[j]; + } + } + return maxPull; +} +function scootLabels(quadrants, trace) { + var xHalf, yHalf, equatorFirst, farthestX, farthestY, xDiffSign, yDiffSign, thisQuad, oppositeQuad, wholeSide, i, thisQuadOutside, firstOppositeOutsidePt; + function topFirst(a, b) { + return a.pxmid[1] - b.pxmid[1]; + } + function bottomFirst(a, b) { + return b.pxmid[1] - a.pxmid[1]; + } + function scootOneLabel(thisPt, prevPt2) { + if (!prevPt2) prevPt2 = {}; + var prevOuterY = prevPt2.labelExtraY + (yHalf ? prevPt2.yLabelMax : prevPt2.yLabelMin); + var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax; + var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin; + var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]); + var newExtraY = prevOuterY - thisInnerY; + var xBuffer, i2, otherPt, otherOuterY, otherOuterX, newExtraX; + if (newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY; + if (!Lib$k.isArrayOrTypedArray(trace.pull)) return; + for (i2 = 0; i2 < wholeSide.length; i2++) { + otherPt = wholeSide[i2]; + if (otherPt === thisPt || (helpers$a.castOption(trace.pull, thisPt.pts) || 0) >= (helpers$a.castOption(trace.pull, otherPt.pts) || 0)) { + continue; + } + if ((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) { + otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]); + newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY; + if (newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY; + } else if ((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) { + xBuffer = 3 * xDiffSign * Math.abs(i2 - wholeSide.indexOf(thisPt)); + otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]); + newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX; + if (newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX; + } + } + } + for (yHalf = 0; yHalf < 2; yHalf++) { + equatorFirst = yHalf ? topFirst : bottomFirst; + farthestY = yHalf ? Math.max : Math.min; + yDiffSign = yHalf ? 1 : -1; + for (xHalf = 0; xHalf < 2; xHalf++) { + farthestX = xHalf ? Math.max : Math.min; + xDiffSign = xHalf ? 1 : -1; + thisQuad = quadrants[yHalf][xHalf]; + thisQuad.sort(equatorFirst); + oppositeQuad = quadrants[1 - yHalf][xHalf]; + wholeSide = oppositeQuad.concat(thisQuad); + thisQuadOutside = []; + for (i = 0; i < thisQuad.length; i++) { + if (thisQuad[i].yLabelMid !== void 0) thisQuadOutside.push(thisQuad[i]); + } + firstOppositeOutsidePt = false; + for (i = 0; yHalf && i < oppositeQuad.length; i++) { + if (oppositeQuad[i].yLabelMid !== void 0) { + firstOppositeOutsidePt = oppositeQuad[i]; + break; + } + } + for (i = 0; i < thisQuadOutside.length; i++) { + var prevPt = i && thisQuadOutside[i - 1]; + if (firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt; + scootOneLabel(thisQuadOutside[i], prevPt); + } + } + } +} +function layoutAreas(cdModule, plotSize) { + var scaleGroups = []; + for (var i = 0; i < cdModule.length; i++) { + var cd0 = cdModule[i][0]; + var trace = cd0.trace; + var domain2 = trace.domain; + var width = plotSize.w * (domain2.x[1] - domain2.x[0]); + var height = plotSize.h * (domain2.y[1] - domain2.y[0]); + if (trace.title.text && trace.title.position !== "middle center") { + height -= getTitleSpace(cd0, plotSize); + } + var rx = width / 2; + var ry = height / 2; + if (trace.type === "funnelarea" && !trace.scalegroup) { + ry /= trace.aspectratio; + } + cd0.r = Math.min(rx, ry) / (1 + getMaxPull(trace)); + cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2; + cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - height / 2; + if (trace.title.text && trace.title.position.indexOf("bottom") !== -1) { + cd0.cy -= getTitleSpace(cd0, plotSize); + } + if (trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) { + scaleGroups.push(trace.scalegroup); + } + } + groupScale(cdModule, scaleGroups); +} +function groupScale(cdModule, scaleGroups) { + var cd0, i, trace; + for (var k = 0; k < scaleGroups.length; k++) { + var min = Infinity; + var g = scaleGroups[k]; + for (i = 0; i < cdModule.length; i++) { + cd0 = cdModule[i][0]; + trace = cd0.trace; + if (trace.scalegroup === g) { + var area2; + if (trace.type === "pie") { + area2 = cd0.r * cd0.r; + } else if (trace.type === "funnelarea") { + var rx, ry; + if (trace.aspectratio > 1) { + rx = cd0.r; + ry = rx / trace.aspectratio; + } else { + ry = cd0.r; + rx = ry * trace.aspectratio; + } + rx *= (1 + trace.baseratio) / 2; + area2 = rx * ry; + } + min = Math.min(min, area2 / cd0.vTotal); + } + } + for (i = 0; i < cdModule.length; i++) { + cd0 = cdModule[i][0]; + trace = cd0.trace; + if (trace.scalegroup === g) { + var v = min * cd0.vTotal; + if (trace.type === "funnelarea") { + v /= (1 + trace.baseratio) / 2; + v /= trace.aspectratio; + } + cd0.r = Math.sqrt(v); + } + } + } +} +function setCoords(cd) { + var cd0 = cd[0]; + var r = cd0.r; + var trace = cd0.trace; + var currentAngle = helpers$a.getRotationAngle(trace.rotation); + var angleFactor = 2 * Math.PI / cd0.vTotal; + var firstPt = "px0"; + var lastPt = "px1"; + var i, cdi, currentCoords; + if (trace.direction === "counterclockwise") { + for (i = 0; i < cd.length; i++) { + if (!cd[i].hidden) break; + } + if (i === cd.length) return; + currentAngle += angleFactor * cd[i].v; + angleFactor *= -1; + firstPt = "px1"; + lastPt = "px0"; + } + currentCoords = getCoords(r, currentAngle); + for (i = 0; i < cd.length; i++) { + cdi = cd[i]; + if (cdi.hidden) continue; + cdi[firstPt] = currentCoords; + cdi.startangle = currentAngle; + currentAngle += angleFactor * cdi.v / 2; + cdi.pxmid = getCoords(r, currentAngle); + cdi.midangle = currentAngle; + currentAngle += angleFactor * cdi.v / 2; + currentCoords = getCoords(r, currentAngle); + cdi.stopangle = currentAngle; + cdi[lastPt] = currentCoords; + cdi.largeArc = cdi.v > cd0.vTotal / 2 ? 1 : 0; + cdi.halfangle = Math.PI * Math.min(cdi.v / cd0.vTotal, 0.5); + cdi.ring = 1 - trace.hole; + cdi.rInscribed = getInscribedRadiusFraction(cdi, cd0); + } +} +function getCoords(r, angle) { + return [r * Math.sin(angle), -r * Math.cos(angle)]; +} +function formatSliceLabel$1(gd, pt, cd0) { + var fullLayout = gd._fullLayout; + var trace = cd0.trace; + var texttemplate = trace.texttemplate; + var textinfo = trace.textinfo; + if (!texttemplate && textinfo && textinfo !== "none") { + var parts = textinfo.split("+"); + var hasFlag = function(flag) { + return parts.indexOf(flag) !== -1; + }; + var hasLabel = hasFlag("label"); + var hasText = hasFlag("text"); + var hasValue = hasFlag("value"); + var hasPercent = hasFlag("percent"); + var separators = fullLayout.separators; + var text; + text = hasLabel ? [pt.label] : []; + if (hasText) { + var tx = helpers$a.getFirstFilled(trace.text, pt.pts); + if (isValidTextValue(tx)) text.push(tx); + } + if (hasValue) text.push(helpers$a.formatPieValue(pt.v, separators)); + if (hasPercent) text.push(helpers$a.formatPiePercent(pt.v / cd0.vTotal, separators)); + pt.text = text.join("
"); + } + function makeTemplateVariables(pt2) { + return { + label: pt2.label, + value: pt2.v, + valueLabel: helpers$a.formatPieValue(pt2.v, fullLayout.separators), + percent: pt2.v / cd0.vTotal, + percentLabel: helpers$a.formatPiePercent(pt2.v / cd0.vTotal, fullLayout.separators), + color: pt2.color, + text: pt2.text, + customdata: Lib$k.castOption(trace, pt2.i, "customdata") + }; + } + if (texttemplate) { + var txt = Lib$k.castOption(trace, pt.i, "texttemplate"); + if (!txt) { + pt.text = ""; + } else { + var obj = makeTemplateVariables(pt); + var ptTx = helpers$a.getFirstFilled(trace.text, pt.pts); + if (isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx; + pt.text = Lib$k.texttemplateString(txt, obj, gd._fullLayout._d3locale, obj, trace._meta || {}); + } + } +} +function computeTransform(transform, textBB) { + var a = transform.rotate * Math.PI / 180; + var cosA = Math.cos(a); + var sinA = Math.sin(a); + var midX = (textBB.left + textBB.right) / 2; + var midY = (textBB.top + textBB.bottom) / 2; + transform.textX = midX * cosA - midY * sinA; + transform.textY = midX * sinA + midY * cosA; + transform.noCenter = true; +} +var plot_1 = { + plot: plot$4, + transformInsideText, + computeTransform +}; +var d3$8 = d3Exports; +var styleOne$4 = style_one; +var resizeText$2 = uniform_text.resizeText; +var style$2 = function style2(gd) { + var s = gd._fullLayout._pielayer.selectAll(".trace"); + resizeText$2(gd, s, "pie"); + s.each(function(cd) { + var cd0 = cd[0]; + var trace = cd0.trace; + var traceSelection = d3$8.select(this); + traceSelection.style({ opacity: trace.opacity }); + traceSelection.selectAll("path.surface").each(function(pt) { + d3$8.select(this).call(styleOne$4, pt, trace, gd); + }); + }); +}; +var base_plot$1 = {}; +(function(exports2) { + var plots2 = plotsExports; + exports2.name = "pie"; + exports2.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + plots2.plotBasePlot(exports2.name, gd, traces, transitionOpts, makeOnCompleteCallback); + }; + exports2.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + plots2.cleanBasePlot(exports2.name, newFullData, newFullLayout, oldFullData, oldFullLayout); + }; +})(base_plot$1); +var pie$2 = { + attributes: attributes$8, + supplyDefaults: defaults$4.supplyDefaults, + supplyLayoutDefaults: layout_defaults$1, + layoutAttributes: layout_attributes$1, + calc: calc_1$1.calc, + crossTraceCalc: calc_1$1.crossTraceCalc, + plot: plot_1.plot, + style: style$2, + styleOne: style_one, + moduleType: "trace", + name: "pie", + basePlotModule: base_plot$1, + categories: ["pie-like", "pie", "showLegend"], + meta: { + description: [ + "A data visualized by the sectors of the pie is set in `values`.", + "The sector labels are set in `labels`.", + "The sector colors are set in `marker.colors`" + ].join(" ") + } +}; +var pie = pie$2; +const pie$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(pie); +var delta$2 = { + INCREASING: { + COLOR: "#3D9970", + SYMBOL: "▲" + }, + DECREASING: { + COLOR: "#FF4136", + SYMBOL: "▼" + } +}; +var extendFlat$3 = libExports.extendFlat; +var scatterAttrs$1 = attributes$A; +var axisHoverFormat$1 = axis_format_attributes.axisHoverFormat; +var dash = attributes$M.dash; +var fxAttrs = attributes$P; +var delta$1 = delta$2; +var INCREASING_COLOR = delta$1.INCREASING.COLOR; +var DECREASING_COLOR = delta$1.DECREASING.COLOR; +var lineAttrs = scatterAttrs$1.line; +function directionAttrs(lineColorDefault) { + return { + line: { + color: extendFlat$3({}, lineAttrs.color, { dflt: lineColorDefault }), + width: lineAttrs.width, + dash, + editType: "style" + }, + editType: "style" + }; +} +var attributes$6 = { + xperiod: scatterAttrs$1.xperiod, + xperiod0: scatterAttrs$1.xperiod0, + xperiodalignment: scatterAttrs$1.xperiodalignment, + xhoverformat: axisHoverFormat$1("x"), + yhoverformat: axisHoverFormat$1("y"), + x: { + valType: "data_array", + editType: "calc+clearAxisTypes", + description: [ + "Sets the x coordinates.", + "If absent, linear coordinate will be generated." + ].join(" ") + }, + open: { + valType: "data_array", + editType: "calc", + description: "Sets the open values." + }, + high: { + valType: "data_array", + editType: "calc", + description: "Sets the high values." + }, + low: { + valType: "data_array", + editType: "calc", + description: "Sets the low values." + }, + close: { + valType: "data_array", + editType: "calc", + description: "Sets the close values." + }, + line: { + width: extendFlat$3({}, lineAttrs.width, { + description: [ + lineAttrs.width, + "Note that this style setting can also be set per", + "direction via `increasing.line.width` and", + "`decreasing.line.width`." + ].join(" ") + }), + dash: extendFlat$3({}, dash, { + description: [ + dash.description, + "Note that this style setting can also be set per", + "direction via `increasing.line.dash` and", + "`decreasing.line.dash`." + ].join(" ") + }), + editType: "style" + }, + increasing: directionAttrs(INCREASING_COLOR), + decreasing: directionAttrs(DECREASING_COLOR), + text: { + valType: "string", + dflt: "", + arrayOk: true, + editType: "calc", + description: [ + "Sets hover text elements associated with each sample point.", + "If a single string, the same string appears over", + "all the data points.", + "If an array of string, the items are mapped in order to", + "this trace's sample points." + ].join(" ") + }, + hovertext: { + valType: "string", + dflt: "", + arrayOk: true, + editType: "calc", + description: "Same as `text`." + }, + tickwidth: { + valType: "number", + min: 0, + max: 0.5, + dflt: 0.3, + editType: "calc", + description: [ + "Sets the width of the open/close tick marks", + "relative to the *x* minimal interval." + ].join(" ") + }, + hoverlabel: extendFlat$3({}, fxAttrs.hoverlabel, { + split: { + valType: "boolean", + dflt: false, + editType: "style", + description: [ + "Show hover information (open, close, high, low) in", + "separate labels." + ].join(" ") + } + }), + zorder: scatterAttrs$1.zorder +}; +var Registry$4 = registry; +var Lib$j = libExports; +var ohlc_defaults = function handleOHLC(traceIn, traceOut, coerce2, layout) { + var x = coerce2("x"); + var open = coerce2("open"); + var high = coerce2("high"); + var low = coerce2("low"); + var close = coerce2("close"); + coerce2("hoverlabel.split"); + var handleCalendarDefaults = Registry$4.getComponentMethod("calendars", "handleTraceDefaults"); + handleCalendarDefaults(traceIn, traceOut, ["x"], layout); + if (!(open && high && low && close)) return; + var len = Math.min(open.length, high.length, low.length, close.length); + if (x) len = Math.min(len, Lib$j.minRowLength(x)); + traceOut._length = len; + return len; +}; +var Lib$i = libExports; +var handleOHLC2 = ohlc_defaults; +var handlePeriodDefaults$1 = period_defaults; +var attributes$5 = attributes$6; +var defaults$3 = function supplyDefaults5(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$i.coerce(traceIn, traceOut, attributes$5, attr, dflt); + } + var len = handleOHLC2(traceIn, traceOut, coerce2, layout); + if (!len) { + traceOut.visible = false; + return; + } + handlePeriodDefaults$1(traceIn, traceOut, layout, coerce2, { x: true }); + coerce2("xhoverformat"); + coerce2("yhoverformat"); + coerce2("line.width"); + coerce2("line.dash"); + handleDirection(traceIn, traceOut, coerce2, "increasing"); + handleDirection(traceIn, traceOut, coerce2, "decreasing"); + coerce2("text"); + coerce2("hovertext"); + coerce2("tickwidth"); + layout._requestRangeslider[traceOut.xaxis] = true; + coerce2("zorder"); +}; +function handleDirection(traceIn, traceOut, coerce2, direction) { + coerce2(direction + ".line.color"); + coerce2(direction + ".line.width", traceOut.line.width); + coerce2(direction + ".line.dash", traceOut.line.dash); +} +var Lib$h = libExports; +var _ = Lib$h._; +var Axes$1 = axesExports; +var alignPeriod$1 = align_period; +var BADNUM$1 = numerical.BADNUM; +function calc$4(gd, trace) { + var xa = Axes$1.getFromId(gd, trace.xaxis); + var ya = Axes$1.getFromId(gd, trace.yaxis); + var tickLen = convertTickWidth(gd, xa, trace); + var minDiff = trace._minDiff; + trace._minDiff = null; + var origX = trace._origX; + trace._origX = null; + var x = trace._xcalc; + trace._xcalc = null; + var cd = calcCommon(gd, trace, origX, x, ya, ptFunc); + trace._extremes[xa._id] = Axes$1.findExtremes(xa, x, { vpad: minDiff / 2 }); + if (cd.length) { + Lib$h.extendFlat(cd[0].t, { + wHover: minDiff / 2, + tickLen + }); + return cd; + } else { + return [{ t: { empty: true } }]; + } +} +function ptFunc(o, h, l, c) { + return { + o, + h, + l, + c + }; +} +function calcCommon(gd, trace, origX, x, ya, ptFunc2) { + var o = ya.makeCalcdata(trace, "open"); + var h = ya.makeCalcdata(trace, "high"); + var l = ya.makeCalcdata(trace, "low"); + var c = ya.makeCalcdata(trace, "close"); + var hasTextArray = Lib$h.isArrayOrTypedArray(trace.text); + var hasHovertextArray = Lib$h.isArrayOrTypedArray(trace.hovertext); + var increasing = true; + var cPrev = null; + var hasPeriod = !!trace.xperiodalignment; + var cd = []; + for (var i = 0; i < x.length; i++) { + var xi = x[i]; + var oi = o[i]; + var hi = h[i]; + var li = l[i]; + var ci = c[i]; + if (xi !== BADNUM$1 && oi !== BADNUM$1 && hi !== BADNUM$1 && li !== BADNUM$1 && ci !== BADNUM$1) { + if (ci === oi) { + if (cPrev !== null && ci !== cPrev) increasing = ci > cPrev; + } else increasing = ci > oi; + cPrev = ci; + var pt = ptFunc2(oi, hi, li, ci); + pt.pos = xi; + pt.yc = (oi + ci) / 2; + pt.i = i; + pt.dir = increasing ? "increasing" : "decreasing"; + pt.x = pt.pos; + pt.y = [li, hi]; + if (hasPeriod) pt.orig_p = origX[i]; + if (hasTextArray) pt.tx = trace.text[i]; + if (hasHovertextArray) pt.htx = trace.hovertext[i]; + cd.push(pt); + } else { + cd.push({ pos: xi, empty: true }); + } + } + trace._extremes[ya._id] = Axes$1.findExtremes(ya, Lib$h.concat(l, h), { padded: true }); + if (cd.length) { + cd[0].t = { + labels: { + open: _(gd, "open:") + " ", + high: _(gd, "high:") + " ", + low: _(gd, "low:") + " ", + close: _(gd, "close:") + " " + } + }; + } + return cd; +} +function convertTickWidth(gd, xa, trace) { + var minDiff = trace._minDiff; + if (!minDiff) { + var fullData = gd._fullData; + var ohlcTracesOnThisXaxis = []; + minDiff = Infinity; + var i; + for (i = 0; i < fullData.length; i++) { + var tracei = fullData[i]; + if (tracei.type === "ohlc" && tracei.visible === true && tracei.xaxis === xa._id) { + ohlcTracesOnThisXaxis.push(tracei); + var origX = xa.makeCalcdata(tracei, "x"); + tracei._origX = origX; + var xcalc = alignPeriod$1(trace, xa, "x", origX).vals; + tracei._xcalc = xcalc; + var _minDiff = Lib$h.distinctVals(xcalc).minDiff; + if (_minDiff && isFinite(_minDiff)) { + minDiff = Math.min(minDiff, _minDiff); + } + } + } + if (minDiff === Infinity) minDiff = 1; + for (i = 0; i < ohlcTracesOnThisXaxis.length; i++) { + ohlcTracesOnThisXaxis[i]._minDiff = minDiff; + } + } + return minDiff * trace.tickwidth; +} +var calc_1 = { + calc: calc$4 +}; +var d3$7 = d3Exports; +var Lib$g = libExports; +var plot$3 = function plot2(gd, plotinfo, cdOHLC, ohlcLayer) { + var ya = plotinfo.yaxis; + var xa = plotinfo.xaxis; + var posHasRangeBreaks = !!xa.rangebreaks; + Lib$g.makeTraceGroups(ohlcLayer, cdOHLC, "trace ohlc").each(function(cd) { + var plotGroup = d3$7.select(this); + var cd0 = cd[0]; + var t = cd0.t; + var trace = cd0.trace; + if (trace.visible !== true || t.empty) { + plotGroup.remove(); + return; + } + var tickLen = t.tickLen; + var paths = plotGroup.selectAll("path").data(Lib$g.identity); + paths.enter().append("path"); + paths.exit().remove(); + paths.attr("d", function(d) { + if (d.empty) return "M0,0Z"; + var xo = xa.c2p(d.pos - tickLen, true); + var xc = xa.c2p(d.pos + tickLen, true); + var x = posHasRangeBreaks ? (xo + xc) / 2 : xa.c2p(d.pos, true); + var yo = ya.c2p(d.o, true); + var yh = ya.c2p(d.h, true); + var yl = ya.c2p(d.l, true); + var yc = ya.c2p(d.c, true); + return "M" + xo + "," + yo + "H" + x + "M" + x + "," + yh + "V" + yl + "M" + xc + "," + yc + "H" + x; + }); + }); +}; +var d3$6 = d3Exports; +var Drawing$4 = drawingExports; +var Color$8 = colorExports; +var style$1 = function style3(gd, cd, sel) { + var s = sel ? sel : d3$6.select(gd).selectAll("g.ohlclayer").selectAll("g.trace"); + s.style("opacity", function(d) { + return d[0].trace.opacity; + }); + s.each(function(d) { + var trace = d[0].trace; + d3$6.select(this).selectAll("path").each(function(di) { + if (di.empty) return; + var dirLine = trace[di.dir].line; + d3$6.select(this).style("fill", "none").call(Color$8.stroke, dirLine.color).call(Drawing$4.dashLine, dirLine.dash, dirLine.width).style("opacity", trace.selectedpoints && !di.selected ? 0.3 : 1); + }); + }); +}; +var Axes = axesExports; +var Lib$f = libExports; +var Fx$1 = fx$1; +var Color$7 = colorExports; +var fillText = libExports.fillText; +var delta = delta$2; +var DIRSYMBOL = { + increasing: delta.INCREASING.SYMBOL, + decreasing: delta.DECREASING.SYMBOL +}; +function hoverPoints$1(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var trace = cd[0].trace; + if (trace.hoverlabel.split) { + return hoverSplit(pointData, xval, yval, hovermode); + } + return hoverOnPoints(pointData, xval, yval, hovermode); +} +function _getClosestPoint(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var xa = pointData.xa; + var trace = cd[0].trace; + var t = cd[0].t; + var type = trace.type; + var minAttr = type === "ohlc" ? "l" : "min"; + var maxAttr = type === "ohlc" ? "h" : "max"; + var hoverPseudoDistance, spikePseudoDistance; + var centerShift = t.bPos || 0; + var shiftPos = function(di2) { + return di2.pos + centerShift - xval; + }; + var displayHalfWidth = t.bdPos || t.tickLen; + var hoverHalfWidth = t.wHover; + var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0]))); + hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; + spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; + function dx(di2) { + var pos = shiftPos(di2); + return Fx$1.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance); + } + function dy(di2) { + var min = di2[minAttr]; + var max = di2[maxAttr]; + return min === max || Fx$1.inbox(min - yval, max - yval, hoverPseudoDistance); + } + function dxy(di2) { + return (dx(di2) + dy(di2)) / 2; + } + var distfn = Fx$1.getDistanceFunction(hovermode, dx, dy, dxy); + Fx$1.getClosest(cd, distfn, pointData); + if (pointData.index === false) return null; + var di = cd[pointData.index]; + if (di.empty) return null; + var dir = di.dir; + var container = trace[dir]; + var lc = container.line.color; + if (Color$7.opacity(lc) && container.line.width) pointData.color = lc; + else pointData.color = container.fillcolor; + pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true); + pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true); + pointData.xLabelVal = di.orig_p !== void 0 ? di.orig_p : di.pos; + pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; + pointData.xSpike = xa.c2p(di.pos, true); + return pointData; +} +function hoverSplit(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; + var closeBoxData = []; + var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode); + if (!closestPoint) return []; + var cdIndex = closestPoint.index; + var di = cd[cdIndex]; + var hoverinfo = di.hi || trace.hoverinfo; + var hoverParts = hoverinfo.split("+"); + var isAll = hoverinfo === "all"; + var hasY = isAll || hoverParts.indexOf("y") !== -1; + if (!hasY) return []; + var attrs2 = ["high", "open", "close", "low"]; + var usedVals = {}; + for (var i = 0; i < attrs2.length; i++) { + var attr = attrs2[i]; + var val = trace[attr][closestPoint.index]; + var valPx = ya.c2p(val, true); + var pointData2; + if (val in usedVals) { + pointData2 = usedVals[val]; + pointData2.yLabel += "
" + t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat); + } else { + pointData2 = Lib$f.extendFlat({}, closestPoint); + pointData2.y0 = pointData2.y1 = valPx; + pointData2.yLabelVal = val; + pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat); + pointData2.name = ""; + closeBoxData.push(pointData2); + usedVals[val] = pointData2; + } + } + return closeBoxData; +} +function hoverOnPoints(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var ya = pointData.ya; + var trace = cd[0].trace; + var t = cd[0].t; + var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode); + if (!closestPoint) return []; + var cdIndex = closestPoint.index; + var di = cd[cdIndex]; + var i = closestPoint.index = di.i; + var dir = di.dir; + function getLabelLine(attr) { + return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i], trace.yhoverformat); + } + var hoverinfo = di.hi || trace.hoverinfo; + var hoverParts = hoverinfo.split("+"); + var isAll = hoverinfo === "all"; + var hasY = isAll || hoverParts.indexOf("y") !== -1; + var hasText = isAll || hoverParts.indexOf("text") !== -1; + var textParts = hasY ? [ + getLabelLine("open"), + getLabelLine("high"), + getLabelLine("low"), + getLabelLine("close") + " " + DIRSYMBOL[dir] + ] : []; + if (hasText) fillText(di, trace, textParts); + closestPoint.extraText = textParts.join("
"); + closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true); + return [closestPoint]; +} +var hover$2 = { + hoverPoints: hoverPoints$1 +}; +var select$1 = function selectPoints3(searchInfo, selectionTester) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var i; + var posOffset = cd[0].t.bPos || 0; + if (selectionTester === false) { + for (i = 0; i < cd.length; i++) { + cd[i].selected = 0; + } + } else { + for (i = 0; i < cd.length; i++) { + var di = cd[i]; + if (selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) { + selection.push({ + pointNumber: di.i, + x: xa.c2d(di.pos), + y: ya.c2d(di.yc) + }); + di.selected = 1; + } else { + di.selected = 0; + } + } + } + return selection; +}; +var ohlc$2 = { + moduleType: "trace", + name: "ohlc", + basePlotModule: cartesian, + categories: ["cartesian", "svg", "showLegend"], + meta: { + description: [ + "The ohlc (short for Open-High-Low-Close) is a style of financial chart describing", + "open, high, low and close for a given `x` coordinate (most likely time).", + "The tip of the lines represent the `low` and `high` values and", + "the horizontal segments represent the `open` and `close` values.", + "Sample points where the close value is higher (lower) then the open", + "value are called increasing (decreasing).", + "By default, increasing items are drawn in green whereas", + "decreasing are drawn in red." + ].join(" ") + }, + attributes: attributes$6, + supplyDefaults: defaults$3, + calc: calc_1.calc, + plot: plot$3, + style: style$1, + hoverPoints: hover$2.hoverPoints, + selectPoints: select$1 +}; +var ohlc = ohlc$2; +const ohlc$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(ohlc); +var Registry$3 = registry; +var Lib$e = libExports; +var getTraceColor2 = get_trace_color; +function hoverPoints3(pointData, xval, yval, hovermode) { + var cd = pointData.cd; + var stash = cd[0].t; + var trace = cd[0].trace; + var xa = pointData.xa; + var ya = pointData.ya; + var x = stash.x; + var y = stash.y; + var xpx = xa.c2p(xval); + var ypx = ya.c2p(yval); + var maxDistance = pointData.distance; + var ids; + if (stash.tree) { + var xl = xa.p2c(xpx - maxDistance); + var xr = xa.p2c(xpx + maxDistance); + var yl = ya.p2c(ypx - maxDistance); + var yr = ya.p2c(ypx + maxDistance); + if (hovermode === "x") { + ids = stash.tree.range( + Math.min(xl, xr), + Math.min(ya._rl[0], ya._rl[1]), + Math.max(xl, xr), + Math.max(ya._rl[0], ya._rl[1]) + ); + } else { + ids = stash.tree.range( + Math.min(xl, xr), + Math.min(yl, yr), + Math.max(xl, xr), + Math.max(yl, yr) + ); + } + } else { + ids = stash.ids; + } + var k, closestId, ptx, pty, i, dx, dy, dist2, dxy; + var minDist = maxDistance; + if (hovermode === "x") { + var xPeriod = !!trace.xperiodalignment; + var yPeriod = !!trace.yperiodalignment; + for (i = 0; i < ids.length; i++) { + k = ids[i]; + ptx = x[k]; + dx = Math.abs(xa.c2p(ptx) - xpx); + if (xPeriod) { + var x0 = xa.c2p(trace._xStarts[k]); + var x1 = xa.c2p(trace._xEnds[k]); + dx = xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity; + } + if (dx < minDist) { + minDist = dx; + pty = y[k]; + dy = ya.c2p(pty) - ypx; + if (yPeriod) { + var y0 = ya.c2p(trace._yStarts[k]); + var y1 = ya.c2p(trace._yEnds[k]); + dy = ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity; + } + dxy = Math.sqrt(dx * dx + dy * dy); + closestId = ids[i]; + } + } + } else { + for (i = ids.length - 1; i > -1; i--) { + k = ids[i]; + ptx = x[k]; + pty = y[k]; + dx = xa.c2p(ptx) - xpx; + dy = ya.c2p(pty) - ypx; + dist2 = Math.sqrt(dx * dx + dy * dy); + if (dist2 < minDist) { + minDist = dxy = dist2; + closestId = k; + } + } + } + pointData.index = closestId; + pointData.distance = minDist; + pointData.dxy = dxy; + if (closestId === void 0) return [pointData]; + return [calcHover(pointData, x, y, trace)]; +} +function calcHover(pointData, x, y, trace) { + var xa = pointData.xa; + var ya = pointData.ya; + var minDist = pointData.distance; + var dxy = pointData.dxy; + var id = pointData.index; + var di = { + pointNumber: id, + x: x[id], + y: y[id] + }; + di.tx = Lib$e.isArrayOrTypedArray(trace.text) ? trace.text[id] : trace.text; + di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext; + di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata; + di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition; + var font2 = trace.textfont; + if (font2) { + di.ts = Lib$e.isArrayOrTypedArray(font2.size) ? font2.size[id] : font2.size; + di.tc = Lib$e.isArrayOrTypedArray(font2.color) ? font2.color[id] : font2.color; + di.tf = Array.isArray(font2.family) ? font2.family[id] : font2.family; + di.tw = Array.isArray(font2.weight) ? font2.weight[id] : font2.weight; + di.ty = Array.isArray(font2.style) ? font2.style[id] : font2.style; + di.tv = Array.isArray(font2.variant) ? font2.variant[id] : font2.variant; + } + var marker2 = trace.marker; + if (marker2) { + di.ms = Lib$e.isArrayOrTypedArray(marker2.size) ? marker2.size[id] : marker2.size; + di.mo = Lib$e.isArrayOrTypedArray(marker2.opacity) ? marker2.opacity[id] : marker2.opacity; + di.mx = Lib$e.isArrayOrTypedArray(marker2.symbol) ? marker2.symbol[id] : marker2.symbol; + di.ma = Lib$e.isArrayOrTypedArray(marker2.angle) ? marker2.angle[id] : marker2.angle; + di.mc = Lib$e.isArrayOrTypedArray(marker2.color) ? marker2.color[id] : marker2.color; + } + var line2 = marker2 && marker2.line; + if (line2) { + di.mlc = Array.isArray(line2.color) ? line2.color[id] : line2.color; + di.mlw = Lib$e.isArrayOrTypedArray(line2.width) ? line2.width[id] : line2.width; + } + var grad = marker2 && marker2.gradient; + if (grad && grad.type !== "none") { + di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type; + di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color; + } + var xp = xa.c2p(di.x, true); + var yp = ya.c2p(di.y, true); + var rad = di.mrc || 1; + var hoverlabel = trace.hoverlabel; + if (hoverlabel) { + di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor; + di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor; + di.hts = Lib$e.isArrayOrTypedArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size; + di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color; + di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family; + di.hnl = Lib$e.isArrayOrTypedArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength; + } + var hoverinfo = trace.hoverinfo; + if (hoverinfo) { + di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo; + } + var hovertemplate = trace.hovertemplate; + if (hovertemplate) { + di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate; + } + var fakeCd = {}; + fakeCd[pointData.index] = di; + var origX = trace._origX; + var origY = trace._origY; + var pointData2 = Lib$e.extendFlat({}, pointData, { + color: getTraceColor2(trace, di), + x0: xp - rad, + x1: xp + rad, + xLabelVal: origX ? origX[id] : di.x, + y0: yp - rad, + y1: yp + rad, + yLabelVal: origY ? origY[id] : di.y, + cd: fakeCd, + distance: minDist, + spikeDistance: dxy, + hovertemplate: di.ht + }); + if (di.htx) pointData2.text = di.htx; + else if (di.tx) pointData2.text = di.tx; + else if (trace.text) pointData2.text = trace.text; + Lib$e.fillText(di, trace, pointData2); + Registry$3.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData2); + return pointData2; +} +var hover$1 = { + hoverPoints: hoverPoints3 +}; +var attributes$4 = { exports: {} }; +var SYMBOL_SIZE$1 = 20; +var constants$a = { + TOO_MANY_POINTS: 1e5, + SYMBOL_SDF_SIZE: 200, + SYMBOL_SIZE: SYMBOL_SIZE$1, + SYMBOL_STROKE: SYMBOL_SIZE$1 / 20, + DOT_RE: /-dot/, + OPEN_RE: /-open/, + DASHES: { + solid: [1], + dot: [1, 1], + dash: [4, 1], + longdash: [8, 1], + dashdot: [4, 1, 1, 1], + longdashdot: [8, 1, 1, 1] + } +}; +var baseAttrs$1 = attributes$O; +var fontAttrs = font_attributes; +var makeFillcolorAttr2 = fillcolor_attribute; +var scatterAttrs = attributes$A; +var axisHoverFormat = axis_format_attributes.axisHoverFormat; +var colorScaleAttrs$2 = attributes$I; +var sortObjectKeys2 = sort_object_keys; +var extendFlat$2 = extend$5.extendFlat; +var overrideAll = edit_types.overrideAll; +var DASHES = constants$a.DASHES; +var scatterLineAttrs = scatterAttrs.line; +var scatterMarkerAttrs = scatterAttrs.marker; +var scatterMarkerLineAttrs = scatterMarkerAttrs.line; +var attrs = attributes$4.exports = overrideAll({ + x: scatterAttrs.x, + x0: scatterAttrs.x0, + dx: scatterAttrs.dx, + y: scatterAttrs.y, + y0: scatterAttrs.y0, + dy: scatterAttrs.dy, + xperiod: scatterAttrs.xperiod, + yperiod: scatterAttrs.yperiod, + xperiod0: scatterAttrs.xperiod0, + yperiod0: scatterAttrs.yperiod0, + xperiodalignment: scatterAttrs.xperiodalignment, + yperiodalignment: scatterAttrs.yperiodalignment, + xhoverformat: axisHoverFormat("x"), + yhoverformat: axisHoverFormat("y"), + text: scatterAttrs.text, + hovertext: scatterAttrs.hovertext, + textposition: scatterAttrs.textposition, + textfont: fontAttrs({ + noFontShadow: true, + noFontLineposition: true, + noFontTextcase: true, + editType: "calc", + colorEditType: "style", + arrayOk: true, + noNumericWeightValues: true, + variantValues: ["normal", "small-caps"], + description: "Sets the text font." + }), + mode: { + valType: "flaglist", + flags: ["lines", "markers", "text"], + extras: ["none"], + description: [ + "Determines the drawing mode for this scatter trace." + ].join(" ") + }, + line: { + color: scatterLineAttrs.color, + width: scatterLineAttrs.width, + shape: { + valType: "enumerated", + values: ["linear", "hv", "vh", "hvh", "vhv"], + dflt: "linear", + editType: "plot", + description: [ + "Determines the line shape.", + "The values correspond to step-wise line shapes." + ].join(" ") + }, + dash: { + valType: "enumerated", + values: sortObjectKeys2(DASHES), + dflt: "solid", + description: "Sets the style of the lines." + } + }, + marker: extendFlat$2({}, colorScaleAttrs$2("marker"), { + symbol: scatterMarkerAttrs.symbol, + angle: scatterMarkerAttrs.angle, + size: scatterMarkerAttrs.size, + sizeref: scatterMarkerAttrs.sizeref, + sizemin: scatterMarkerAttrs.sizemin, + sizemode: scatterMarkerAttrs.sizemode, + opacity: scatterMarkerAttrs.opacity, + colorbar: scatterMarkerAttrs.colorbar, + line: extendFlat$2({}, colorScaleAttrs$2("marker.line"), { + width: scatterMarkerLineAttrs.width + }) + }), + connectgaps: scatterAttrs.connectgaps, + fill: extendFlat$2({}, scatterAttrs.fill, { dflt: "none" }), + fillcolor: makeFillcolorAttr2(), + // no hoveron + selected: { + marker: scatterAttrs.selected.marker, + textfont: scatterAttrs.selected.textfont + }, + unselected: { + marker: scatterAttrs.unselected.marker, + textfont: scatterAttrs.unselected.textfont + }, + opacity: baseAttrs$1.opacity +}, "calc", "nested"); +attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = "calc+clearAxisTypes"; +attrs.hovertemplate = scatterAttrs.hovertemplate; +attrs.texttemplate = scatterAttrs.texttemplate; +var attributesExports = attributes$4.exports; +var helpers$9 = {}; +var constants$9 = constants$a; +helpers$9.isOpenSymbol = function(symbol) { + return typeof symbol === "string" ? constants$9.OPEN_RE.test(symbol) : symbol % 200 > 100; +}; +helpers$9.isDotSymbol = function(symbol) { + return typeof symbol === "string" ? constants$9.DOT_RE.test(symbol) : symbol > 200; +}; +var Lib$d = libExports; +var Registry$2 = registry; +var helpers$8 = helpers$9; +var attributes$3 = attributesExports; +var constants$8 = constants$B; +var subTypes$3 = subtypes$3; +var handleXYDefaults2 = xy_defaults; +var handlePeriodDefaults2 = period_defaults; +var handleMarkerDefaults$1 = marker_defaults; +var handleLineDefaults = line_defaults; +var handleFillColorDefaults = fillcolor_defaults; +var handleTextDefaults = text_defaults; +var defaults$2 = function supplyDefaults6(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$d.coerce(traceIn, traceOut, attributes$3, attr, dflt); + } + var isOpen = traceIn.marker ? helpers$8.isOpenSymbol(traceIn.marker.symbol) : false; + var isBubble = subTypes$3.isBubble(traceIn); + var len = handleXYDefaults2(traceIn, traceOut, layout, coerce2); + if (!len) { + traceOut.visible = false; + return; + } + handlePeriodDefaults2(traceIn, traceOut, layout, coerce2); + coerce2("xhoverformat"); + coerce2("yhoverformat"); + var defaultMode = len < constants$8.PTS_LINESONLY ? "lines+markers" : "lines"; + coerce2("text"); + coerce2("hovertext"); + coerce2("hovertemplate"); + coerce2("mode", defaultMode); + if (subTypes$3.hasMarkers(traceOut)) { + handleMarkerDefaults$1(traceIn, traceOut, defaultColor, layout, coerce2, { noAngleRef: true, noStandOff: true }); + coerce2("marker.line.width", isOpen || isBubble ? 1 : 0); + } + if (subTypes$3.hasLines(traceOut)) { + coerce2("connectgaps"); + handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce2); + coerce2("line.shape"); + } + if (subTypes$3.hasText(traceOut)) { + coerce2("texttemplate"); + handleTextDefaults(traceIn, traceOut, layout, coerce2, { + noFontShadow: true, + noFontLineposition: true, + noFontTextcase: true + }); + } + var lineColor = (traceOut.line || {}).color; + var markerColor = (traceOut.marker || {}).color; + coerce2("fill"); + if (traceOut.fill !== "none") { + handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce2); + } + var errorBarsSupplyDefaults = Registry$2.getComponentMethod("errorbars", "supplyDefaults"); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" }); + errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" }); + Lib$d.coerceSelectionMarkerOpacity(traceOut, coerce2); +}; +var scatterFormatLabels = format_labels$1; +var format_labels = function formatLabels2(cdi, trace, fullLayout) { + var i = cdi.i; + if (!("x" in cdi)) cdi.x = trace._x[i]; + if (!("y" in cdi)) cdi.y = trace._y[i]; + return scatterFormatLabels(cdi, trace, fullLayout); +}; +function ge(a, y, c, l, h) { + var i = h + 1; + while (l <= h) { + var m = l + h >>> 1, x = a[m]; + var p = c !== void 0 ? c(x, y) : x - y; + if (p >= 0) { + i = m; + h = m - 1; + } else { + l = m + 1; + } + } + return i; +} +function gt(a, y, c, l, h) { + var i = h + 1; + while (l <= h) { + var m = l + h >>> 1, x = a[m]; + var p = c !== void 0 ? c(x, y) : x - y; + if (p > 0) { + i = m; + h = m - 1; + } else { + l = m + 1; + } + } + return i; +} +function lt(a, y, c, l, h) { + var i = l - 1; + while (l <= h) { + var m = l + h >>> 1, x = a[m]; + var p = c !== void 0 ? c(x, y) : x - y; + if (p < 0) { + i = m; + l = m + 1; + } else { + h = m - 1; + } + } + return i; +} +function le(a, y, c, l, h) { + var i = l - 1; + while (l <= h) { + var m = l + h >>> 1, x = a[m]; + var p = c !== void 0 ? c(x, y) : x - y; + if (p <= 0) { + i = m; + l = m + 1; + } else { + h = m - 1; + } + } + return i; +} +function eq(a, y, c, l, h) { + while (l <= h) { + var m = l + h >>> 1, x = a[m]; + var p = c !== void 0 ? c(x, y) : x - y; + if (p === 0) { + return m; + } + if (p <= 0) { + l = m + 1; + } else { + h = m - 1; + } + } + return -1; +} +function norm(a, y, c, l, h, f) { + if (typeof c === "function") { + return f(a, y, c, l === void 0 ? 0 : l | 0, h === void 0 ? a.length - 1 : h | 0); + } + return f(a, y, void 0, c === void 0 ? 0 : c | 0, l === void 0 ? a.length - 1 : l | 0); +} +var searchBounds = { + ge: function(a, y, c, l, h) { + return norm(a, y, c, l, h, ge); + }, + gt: function(a, y, c, l, h) { + return norm(a, y, c, l, h, gt); + }, + lt: function(a, y, c, l, h) { + return norm(a, y, c, l, h, lt); + }, + le: function(a, y, c, l, h) { + return norm(a, y, c, l, h, le); + }, + eq: function(a, y, c, l, h) { + return norm(a, y, c, l, h, eq); + } +}; +var clamp_1 = clamp$4; +function clamp$4(value2, min, max) { + return min < max ? value2 < min ? min : value2 > max ? max : value2 : value2 < max ? max : value2 > min ? min : value2; +} +var pickByAlias = function pick(src2, props, keepRest) { + var result = {}, prop, i; + if (typeof props === "string") props = toList(props); + if (Array.isArray(props)) { + var res = {}; + for (i = 0; i < props.length; i++) { + res[props[i]] = true; + } + props = res; + } + for (prop in props) { + props[prop] = toList(props[prop]); + } + var occupied = {}; + for (prop in props) { + var aliases = props[prop]; + if (Array.isArray(aliases)) { + for (i = 0; i < aliases.length; i++) { + var alias = aliases[i]; + if (keepRest) { + occupied[alias] = true; + } + if (alias in src2) { + result[prop] = src2[alias]; + if (keepRest) { + for (var j = i; j < aliases.length; j++) { + occupied[aliases[j]] = true; + } + } + break; + } + } + } else if (prop in src2) { + if (props[prop]) { + result[prop] = src2[prop]; + } + if (keepRest) { + occupied[prop] = true; + } + } + } + if (keepRest) { + for (prop in src2) { + if (occupied[prop]) continue; + result[prop] = src2[prop]; + } + } + return result; +}; +var CACHE = {}; +function toList(arg) { + if (CACHE[arg]) return CACHE[arg]; + if (typeof arg === "string") { + arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/); + } + return arg; +} +var pick$7 = pickByAlias; +var parseRect_1 = parseRect$3; +function parseRect$3(arg) { + var rect2; + if (arguments.length > 1) { + arg = arguments; + } + if (typeof arg === "string") { + arg = arg.split(/\s/).map(parseFloat); + } else if (typeof arg === "number") { + arg = [arg]; + } + if (arg.length && typeof arg[0] === "number") { + if (arg.length === 1) { + rect2 = { + width: arg[0], + height: arg[0], + x: 0, + y: 0 + }; + } else if (arg.length === 2) { + rect2 = { + width: arg[0], + height: arg[1], + x: 0, + y: 0 + }; + } else { + rect2 = { + x: arg[0], + y: arg[1], + width: arg[2] - arg[0] || 0, + height: arg[3] - arg[1] || 0 + }; + } + } else if (arg) { + arg = pick$7(arg, { + left: "x l left Left", + top: "y t top Top", + width: "w width W Width", + height: "h height W Width", + bottom: "b bottom Bottom", + right: "r right Right" + }); + rect2 = { + x: arg.left || 0, + y: arg.top || 0 + }; + if (arg.width == null) { + if (arg.right) rect2.width = arg.right - rect2.x; + else rect2.width = 0; + } else { + rect2.width = arg.width; + } + if (arg.height == null) { + if (arg.bottom) rect2.height = arg.bottom - rect2.y; + else rect2.height = 0; + } else { + rect2.height = arg.height; + } + } + return rect2; +} +var arrayBounds = normalize$7; +function normalize$7(arr, dim) { + if (!arr || arr.length == null) throw Error("Argument should be an array"); + if (dim == null) dim = 1; + else dim = Math.floor(dim); + var bounds = Array(dim * 2); + for (var offset = 0; offset < dim; offset++) { + var max = -Infinity, min = Infinity, i = offset, l = arr.length; + for (; i < l; i += dim) { + if (arr[i] > max) max = arr[i]; + if (arr[i] < min) min = arr[i]; + } + bounds[offset] = min; + bounds[dim + offset] = max; + } + return bounds; +} +var defined$1 = function defined() { + for (var i = 0; i < arguments.length; i++) { + if (typeof arguments[i] !== "undefined") { + return arguments[i]; + } + } +}; +var dtype$3 = function(dtype2) { + switch (dtype2) { + case "int8": + return Int8Array; + case "int16": + return Int16Array; + case "int32": + return Int32Array; + case "uint8": + return Uint8Array; + case "uint16": + return Uint16Array; + case "uint32": + return Uint32Array; + case "float32": + return Float32Array; + case "float64": + return Float64Array; + case "array": + return Array; + case "uint8_clamped": + return Uint8ClampedArray; + } +}; +var dtype$2 = dtype$3; +var flattenVertexData_1 = flattenVertexData; +function flattenVertexData(data, output, offset) { + if (!data) throw new TypeError("must specify data as first parameter"); + offset = +(offset || 0) | 0; + if (Array.isArray(data) && (data[0] && typeof data[0][0] === "number")) { + var dim = data[0].length; + var length2 = data.length * dim; + var i, j, k, l; + if (!output || typeof output === "string") { + output = new (dtype$2(output || "float32"))(length2 + offset); + } + var dstLength = output.length - offset; + if (length2 !== dstLength) { + throw new Error("source length " + length2 + " (" + dim + "x" + data.length + ") does not match destination length " + dstLength); + } + for (i = 0, k = offset; i < data.length; i++) { + for (j = 0; j < dim; j++) { + output[k++] = data[i][j] === null ? NaN : data[i][j]; + } + } + } else { + if (!output || typeof output === "string") { + var Ctor = dtype$2(output || "float32"); + if (Array.isArray(data) || output === "array") { + output = new Ctor(data.length + offset); + for (i = 0, k = offset, l = output.length; k < l; k++, i++) { + output[k] = data[i] === null ? NaN : data[i]; + } + } else { + if (offset === 0) { + output = new Ctor(data); + } else { + output = new Ctor(data.length + offset); + output.set(data, offset); + } + } + } else { + output.set(data, offset); + } + } + return output; +} +var isObj$2 = function(x) { + var type = typeof x; + return x !== null && (type === "object" || type === "function"); +}; +var mathLog2 = Math.log2 || function(x) { + return Math.log(x) * Math.LOG2E; +}; +const search = searchBounds; +const clamp$3 = clamp_1; +const rect = parseRect_1; +const getBounds$4 = arrayBounds; +const pick$6 = pickByAlias; +const defined2 = defined$1; +const flatten$4 = flattenVertexData_1; +const isObj$1 = isObj$2; +const dtype$1 = dtype$3; +const log2 = mathLog2; +const MAX_GROUP_ID = 1073741824; +var quad = function cluster(srcPoints, options) { + if (!options) options = {}; + srcPoints = flatten$4(srcPoints, "float64"); + options = pick$6(options, { + bounds: "range bounds dataBox databox", + maxDepth: "depth maxDepth maxdepth level maxLevel maxlevel levels", + dtype: "type dtype format out dst output destination" + // sort: 'sortBy sortby sort', + // pick: 'pick levelPoint', + // nodeSize: 'node nodeSize minNodeSize minSize size' + }); + let maxDepth = defined2(options.maxDepth, 255); + let bounds = defined2(options.bounds, getBounds$4(srcPoints, 2)); + if (bounds[0] === bounds[2]) bounds[2]++; + if (bounds[1] === bounds[3]) bounds[3]++; + let points = normalize$6(srcPoints, bounds); + let n = srcPoints.length >>> 1; + let ids; + if (!options.dtype) options.dtype = "array"; + if (typeof options.dtype === "string") { + ids = new (dtype$1(options.dtype))(n); + } else if (options.dtype) { + ids = options.dtype; + if (Array.isArray(ids)) ids.length = n; + } + for (let i = 0; i < n; ++i) { + ids[i] = i; + } + let levels = []; + let sublevels = []; + let groups = []; + let offsets = []; + sort(0, 0, 1, ids, 0, 1); + let offset = 0; + for (let level = 0; level < levels.length; level++) { + let levelItems = levels[level]; + if (ids.set) ids.set(levelItems, offset); + else { + for (let i = 0, l = levelItems.length; i < l; i++) { + ids[i + offset] = levelItems[i]; + } + } + let nextOffset = offset + levels[level].length; + offsets[level] = [offset, nextOffset]; + offset = nextOffset; + } + ids.range = range; + return ids; + function sort(x, y, diam, ids2, level, group2) { + if (!ids2.length) return null; + let levelItems = levels[level] || (levels[level] = []); + let levelGroups = groups[level] || (groups[level] = []); + let sublevel = sublevels[level] || (sublevels[level] = []); + let offset2 = levelItems.length; + level++; + if (level > maxDepth || group2 > MAX_GROUP_ID) { + for (let i = 0; i < ids2.length; i++) { + levelItems.push(ids2[i]); + levelGroups.push(group2); + sublevel.push(null, null, null, null); + } + return offset2; + } + levelItems.push(ids2[0]); + levelGroups.push(group2); + if (ids2.length <= 1) { + sublevel.push(null, null, null, null); + return offset2; + } + let d2 = diam * 0.5; + let cx = x + d2, cy = y + d2; + let lolo = [], lohi = [], hilo = [], hihi = []; + for (let i = 1, l = ids2.length; i < l; i++) { + let idx = ids2[i], x2 = points[idx * 2], y2 = points[idx * 2 + 1]; + x2 < cx ? y2 < cy ? lolo.push(idx) : lohi.push(idx) : y2 < cy ? hilo.push(idx) : hihi.push(idx); + } + group2 <<= 2; + sublevel.push( + sort(x, y, d2, lolo, level, group2), + sort(x, cy, d2, lohi, level, group2 + 1), + sort(cx, y, d2, hilo, level, group2 + 2), + sort(cx, cy, d2, hihi, level, group2 + 3) + ); + return offset2; + } + function range(...args) { + let options2; + if (isObj$1(args[args.length - 1])) { + let arg = args.pop(); + if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) { + args = [arg]; + options2 = {}; + } + options2 = pick$6(arg, { + level: "level maxLevel", + d: "d diam diameter r radius px pxSize pixel pixelSize maxD size minSize", + lod: "lod details ranges offsets" + }); + } else { + options2 = {}; + } + if (!args.length) args = bounds; + let box = rect(...args); + let [minX, minY, maxX, maxY2] = [ + Math.min(box.x, box.x + box.width), + Math.min(box.y, box.y + box.height), + Math.max(box.x, box.x + box.width), + Math.max(box.y, box.y + box.height) + ]; + let [nminX, nminY, nmaxX, nmaxY] = normalize$6([minX, minY, maxX, maxY2], bounds); + let maxLevel = defined2(options2.level, levels.length); + if (options2.d != null) { + let d; + if (typeof options2.d === "number") d = [options2.d, options2.d]; + else if (options2.d.length) d = options2.d; + maxLevel = Math.min( + Math.max( + Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))), + Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1]))) + ), + maxLevel + ); + } + maxLevel = Math.min(maxLevel, levels.length); + if (options2.lod) { + return lod(nminX, nminY, nmaxX, nmaxY, maxLevel); + } + let selection = []; + select3(0, 0, 1, 0, 0, 1); + function select3(lox, loy, d, level, from, to) { + if (from === null || to === null) return; + let hix = lox + d; + let hiy = loy + d; + if (nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy) return; + if (level >= maxLevel) return; + if (from === to) return; + let levelItems = levels[level]; + if (to === void 0) to = levelItems.length; + for (let i = from; i < to; i++) { + let id = levelItems[i]; + let px2 = srcPoints[id * 2]; + let py = srcPoints[id * 2 + 1]; + if (px2 >= minX && px2 <= maxX && py >= minY && py <= maxY2) { + selection.push(id); + } + } + let offsets2 = sublevels[level]; + let off0 = offsets2[from * 4 + 0]; + let off1 = offsets2[from * 4 + 1]; + let off2 = offsets2[from * 4 + 2]; + let off3 = offsets2[from * 4 + 3]; + let end = nextOffset(offsets2, from + 1); + let d2 = d * 0.5; + let nextLevel = level + 1; + select3(lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end); + select3(lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end); + select3(lox + d2, loy, d2, nextLevel, off2, off3 || end); + select3(lox + d2, loy + d2, d2, nextLevel, off3, end); + } + function nextOffset(offsets2, from) { + let offset2 = null, i = 0; + while (offset2 === null) { + offset2 = offsets2[from * 4 + i]; + i++; + if (i > offsets2.length) return null; + } + return offset2; + } + return selection; + } + function lod(lox, loy, hix, hiy, maxLevel) { + let ranges = []; + for (let level = 0; level < maxLevel; level++) { + let levelGroups = groups[level]; + let from = offsets[level][0]; + let levelGroupStart = group(lox, loy, level); + let levelGroupEnd = group(hix, hiy, level); + let startOffset = search.ge(levelGroups, levelGroupStart); + let endOffset = search.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1); + ranges[level] = [startOffset + from, endOffset + from]; + } + return ranges; + } + function group(x, y, level) { + let group2 = 1; + let cx = 0.5, cy = 0.5; + let diam = 0.5; + for (let i = 0; i < level; i++) { + group2 <<= 2; + group2 += x < cx ? y < cy ? 0 : 1 : y < cy ? 2 : 3; + diam *= 0.5; + cx += x < cx ? -diam : diam; + cy += y < cy ? -diam : diam; + } + return group2; + } +}; +function normalize$6(pts, bounds) { + let [lox, loy, hix, hiy] = bounds; + let scaleX = 1 / (hix - lox); + let scaleY = 1 / (hiy - loy); + let result = new Array(pts.length); + for (let i = 0, n = pts.length / 2; i < n; i++) { + result[2 * i] = clamp$3((pts[2 * i] - lox) * scaleX, 0, 1); + result[2 * i + 1] = clamp$3((pts[2 * i + 1] - loy) * scaleY, 0, 1); + } + return result; +} +var pointCluster = quad; +var absSvgPath = absolutize; +function absolutize(path) { + var startX = 0; + var startY = 0; + var x = 0; + var y = 0; + return path.map(function(seg) { + seg = seg.slice(); + var type = seg[0]; + var command2 = type.toUpperCase(); + if (type != command2) { + seg[0] = command2; + switch (type) { + case "a": + seg[6] += x; + seg[7] += y; + break; + case "v": + seg[1] += y; + break; + case "h": + seg[1] += x; + break; + default: + for (var i = 1; i < seg.length; ) { + seg[i++] += x; + seg[i++] += y; + } + } + } + switch (command2) { + case "Z": + x = startX; + y = startY; + break; + case "H": + x = seg[1]; + break; + case "V": + y = seg[1]; + break; + case "M": + x = startX = seg[1]; + y = startY = seg[2]; + break; + default: + x = seg[seg.length - 2]; + y = seg[seg.length - 1]; + } + return seg; + }); +} +var _slicedToArray$1 = /* @__PURE__ */ function() { + function sliceIterator(arr, i) { + var _arr = []; + var _n = true; + var _d = false; + var _e = void 0; + try { + for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"]) _i["return"](); + } finally { + if (_d) throw _e; + } + } + return _arr; + } + return function(arr, i) { + if (Array.isArray(arr)) { + return arr; + } else if (Symbol.iterator in Object(arr)) { + return sliceIterator(arr, i); + } else { + throw new TypeError("Invalid attempt to destructure non-iterable instance"); + } + }; +}(); +var TAU = Math.PI * 2; +var mapToEllipse = function mapToEllipse2(_ref, rx, ry, cosphi, sinphi, centerx, centery) { + var x = _ref.x, y = _ref.y; + x *= rx; + y *= ry; + var xp = cosphi * x - sinphi * y; + var yp = sinphi * x + cosphi * y; + return { + x: xp + centerx, + y: yp + centery + }; +}; +var approxUnitArc = function approxUnitArc2(ang1, ang2) { + var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); + var x1 = Math.cos(ang1); + var y1 = Math.sin(ang1); + var x2 = Math.cos(ang1 + ang2); + var y2 = Math.sin(ang1 + ang2); + return [{ + x: x1 - y1 * a, + y: y1 + x1 * a + }, { + x: x2 + y2 * a, + y: y2 - x2 * a + }, { + x: x2, + y: y2 + }]; +}; +var vectorAngle = function vectorAngle2(ux, uy, vx, vy) { + var sign2 = ux * vy - uy * vx < 0 ? -1 : 1; + var dot2 = ux * vx + uy * vy; + if (dot2 > 1) { + dot2 = 1; + } + if (dot2 < -1) { + dot2 = -1; + } + return sign2 * Math.acos(dot2); +}; +var getArcCenter = function getArcCenter2(px2, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { + var rxsq = Math.pow(rx, 2); + var rysq = Math.pow(ry, 2); + var pxpsq = Math.pow(pxp, 2); + var pypsq = Math.pow(pyp, 2); + var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; + if (radicant < 0) { + radicant = 0; + } + radicant /= rxsq * pypsq + rysq * pxpsq; + radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); + var centerxp = radicant * rx / ry * pyp; + var centeryp = radicant * -ry / rx * pxp; + var centerx = cosphi * centerxp - sinphi * centeryp + (px2 + cx) / 2; + var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; + var vx1 = (pxp - centerxp) / rx; + var vy1 = (pyp - centeryp) / ry; + var vx2 = (-pxp - centerxp) / rx; + var vy2 = (-pyp - centeryp) / ry; + var ang1 = vectorAngle(1, 0, vx1, vy1); + var ang2 = vectorAngle(vx1, vy1, vx2, vy2); + if (sweepFlag === 0 && ang2 > 0) { + ang2 -= TAU; + } + if (sweepFlag === 1 && ang2 < 0) { + ang2 += TAU; + } + return [centerx, centery, ang1, ang2]; +}; +var arcToBezier = function arcToBezier2(_ref2) { + var px2 = _ref2.px, py = _ref2.py, cx = _ref2.cx, cy = _ref2.cy, rx = _ref2.rx, ry = _ref2.ry, _ref2$xAxisRotation = _ref2.xAxisRotation, xAxisRotation = _ref2$xAxisRotation === void 0 ? 0 : _ref2$xAxisRotation, _ref2$largeArcFlag = _ref2.largeArcFlag, largeArcFlag = _ref2$largeArcFlag === void 0 ? 0 : _ref2$largeArcFlag, _ref2$sweepFlag = _ref2.sweepFlag, sweepFlag = _ref2$sweepFlag === void 0 ? 0 : _ref2$sweepFlag; + var curves = []; + if (rx === 0 || ry === 0) { + return []; + } + var sinphi = Math.sin(xAxisRotation * TAU / 360); + var cosphi = Math.cos(xAxisRotation * TAU / 360); + var pxp = cosphi * (px2 - cx) / 2 + sinphi * (py - cy) / 2; + var pyp = -sinphi * (px2 - cx) / 2 + cosphi * (py - cy) / 2; + if (pxp === 0 && pyp === 0) { + return []; + } + rx = Math.abs(rx); + ry = Math.abs(ry); + var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); + if (lambda > 1) { + rx *= Math.sqrt(lambda); + ry *= Math.sqrt(lambda); + } + var _getArcCenter = getArcCenter(px2, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), _getArcCenter2 = _slicedToArray$1(_getArcCenter, 4), centerx = _getArcCenter2[0], centery = _getArcCenter2[1], ang1 = _getArcCenter2[2], ang2 = _getArcCenter2[3]; + var ratio = Math.abs(ang2) / (TAU / 4); + if (Math.abs(1 - ratio) < 1e-7) { + ratio = 1; + } + var segments = Math.max(Math.ceil(ratio), 1); + ang2 /= segments; + for (var i = 0; i < segments; i++) { + curves.push(approxUnitArc(ang1, ang2)); + ang1 += ang2; + } + return curves.map(function(curve) { + var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), x1 = _mapToEllipse.x, y1 = _mapToEllipse.y; + var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), x2 = _mapToEllipse2.x, y2 = _mapToEllipse2.y; + var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), x = _mapToEllipse3.x, y = _mapToEllipse3.y; + return { x1, y1, x2, y2, x, y }; + }); +}; +const modules = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + default: arcToBezier +}, Symbol.toStringTag, { value: "Module" })); +const require$$0$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(modules); +var normalizeSvgPath$1 = normalize$5; +var arcToCurve = require$$0$1; +function normalize$5(path) { + var prev; + var result = []; + var bezierX = 0; + var bezierY = 0; + var startX = 0; + var startY = 0; + var quadX = null; + var quadY = null; + var x = 0; + var y = 0; + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i]; + var command2 = seg[0]; + switch (command2) { + case "M": + startX = seg[1]; + startY = seg[2]; + break; + case "A": + var curves = arcToCurve({ + px: x, + py: y, + cx: seg[6], + cy: seg[7], + rx: seg[1], + ry: seg[2], + xAxisRotation: seg[3], + largeArcFlag: seg[4], + sweepFlag: seg[5] + }); + if (!curves.length) continue; + for (var j = 0, c; j < curves.length; j++) { + c = curves[j]; + seg = ["C", c.x1, c.y1, c.x2, c.y2, c.x, c.y]; + if (j < curves.length - 1) result.push(seg); + } + break; + case "S": + var cx = x; + var cy = y; + if (prev == "C" || prev == "S") { + cx += cx - bezierX; + cy += cy - bezierY; + } + seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]]; + break; + case "T": + if (prev == "Q" || prev == "T") { + quadX = x * 2 - quadX; + quadY = y * 2 - quadY; + } else { + quadX = x; + quadY = y; + } + seg = quadratic$1(x, y, quadX, quadY, seg[1], seg[2]); + break; + case "Q": + quadX = seg[1]; + quadY = seg[2]; + seg = quadratic$1(x, y, seg[1], seg[2], seg[3], seg[4]); + break; + case "L": + seg = line$1(x, y, seg[1], seg[2]); + break; + case "H": + seg = line$1(x, y, seg[1], y); + break; + case "V": + seg = line$1(x, y, x, seg[1]); + break; + case "Z": + seg = line$1(x, y, startX, startY); + break; + } + prev = command2; + x = seg[seg.length - 2]; + y = seg[seg.length - 1]; + if (seg.length > 4) { + bezierX = seg[seg.length - 4]; + bezierY = seg[seg.length - 3]; + } else { + bezierX = x; + bezierY = y; + } + result.push(seg); + } + return result; +} +function line$1(x1, y1, x2, y2) { + return ["C", x1, y1, x2, y2, x2, y2]; +} +function quadratic$1(x1, y1, cx, cy, x2, y2) { + return [ + "C", + x1 / 3 + 2 / 3 * cx, + y1 / 3 + 2 / 3 * cy, + x2 / 3 + 2 / 3 * cx, + y2 / 3 + 2 / 3 * cy, + x2, + y2 + ]; +} +var isSvgPath$2 = function isPath(str2) { + if (typeof str2 !== "string") return false; + str2 = str2.trim(); + if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str2) && /[\dz]$/i.test(str2) && str2.length > 4) return true; + return false; +}; +var parse$4 = parseSvgPath; +var abs$1 = absSvgPath; +var normalize$4 = normalizeSvgPath$1; +var isSvgPath$1 = isSvgPath$2; +var svgPathBounds = pathBounds$1; +function pathBounds$1(path) { + if (Array.isArray(path) && path.length === 1 && typeof path[0] === "string") path = path[0]; + if (typeof path === "string") { + if (!isSvgPath$1(path)) throw Error("String is not an SVG path."); + path = parse$4(path); + } + if (!Array.isArray(path)) throw Error("Argument should be a string or an array of path segments."); + path = abs$1(path); + path = normalize$4(path); + if (!path.length) return [0, 0, 0, 0]; + var bounds = [Infinity, Infinity, -Infinity, -Infinity]; + for (var i = 0, l = path.length; i < l; i++) { + var points = path[i].slice(1); + for (var j = 0; j < points.length; j += 2) { + if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0]; + if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1]; + if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0]; + if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1]; + } + } + return bounds; +} +var π = Math.PI; +var _120 = radians$1(120); +var normalizeSvgPath = normalize$3; +function normalize$3(path) { + var prev; + var result = []; + var bezierX = 0; + var bezierY = 0; + var startX = 0; + var startY = 0; + var quadX = null; + var quadY = null; + var x = 0; + var y = 0; + for (var i = 0, len = path.length; i < len; i++) { + var seg = path[i]; + var command2 = seg[0]; + switch (command2) { + case "M": + startX = seg[1]; + startY = seg[2]; + break; + case "A": + seg = arc(x, y, seg[1], seg[2], radians$1(seg[3]), seg[4], seg[5], seg[6], seg[7]); + seg.unshift("C"); + if (seg.length > 7) { + result.push(seg.splice(0, 7)); + seg.unshift("C"); + } + break; + case "S": + var cx = x; + var cy = y; + if (prev == "C" || prev == "S") { + cx += cx - bezierX; + cy += cy - bezierY; + } + seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]]; + break; + case "T": + if (prev == "Q" || prev == "T") { + quadX = x * 2 - quadX; + quadY = y * 2 - quadY; + } else { + quadX = x; + quadY = y; + } + seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]); + break; + case "Q": + quadX = seg[1]; + quadY = seg[2]; + seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]); + break; + case "L": + seg = line(x, y, seg[1], seg[2]); + break; + case "H": + seg = line(x, y, seg[1], y); + break; + case "V": + seg = line(x, y, x, seg[1]); + break; + case "Z": + seg = line(x, y, startX, startY); + break; + } + prev = command2; + x = seg[seg.length - 2]; + y = seg[seg.length - 1]; + if (seg.length > 4) { + bezierX = seg[seg.length - 4]; + bezierY = seg[seg.length - 3]; + } else { + bezierX = x; + bezierY = y; + } + result.push(seg); + } + return result; +} +function line(x1, y1, x2, y2) { + return ["C", x1, y1, x2, y2, x2, y2]; +} +function quadratic(x1, y1, cx, cy, x2, y2) { + return [ + "C", + x1 / 3 + 2 / 3 * cx, + y1 / 3 + 2 / 3 * cy, + x2 / 3 + 2 / 3 * cx, + y2 / 3 + 2 / 3 * cy, + x2, + y2 + ]; +} +function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { + if (!recursive) { + var xy = rotate(x1, y1, -angle); + x1 = xy.x; + y1 = xy.y; + xy = rotate(x2, y2, -angle); + x2 = xy.x; + y2 = xy.y; + var x = (x1 - x2) / 2; + var y = (y1 - y2) / 2; + var h = x * x / (rx * rx) + y * y / (ry * ry); + if (h > 1) { + h = Math.sqrt(h); + rx = h * rx; + ry = h * ry; + } + var rx2 = rx * rx; + var ry2 = ry * ry; + var k = (large_arc_flag == sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); + if (k == Infinity) k = 1; + var cx = k * rx * y / ry + (x1 + x2) / 2; + var cy = k * -ry * x / rx + (y1 + y2) / 2; + var f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); + var f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); + f1 = x1 < cx ? π - f1 : f1; + f2 = x2 < cx ? π - f2 : f2; + if (f1 < 0) f1 = π * 2 + f1; + if (f2 < 0) f2 = π * 2 + f2; + if (sweep_flag && f1 > f2) f1 = f1 - π * 2; + if (!sweep_flag && f2 > f1) f2 = f2 - π * 2; + } else { + f1 = recursive[0]; + f2 = recursive[1]; + cx = recursive[2]; + cy = recursive[3]; + } + if (Math.abs(f2 - f1) > _120) { + var f2old = f2; + var x2old = x2; + var y2old = y2; + f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); + x2 = cx + rx * Math.cos(f2); + y2 = cy + ry * Math.sin(f2); + var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); + } + var t = Math.tan((f2 - f1) / 4); + var hx = 4 / 3 * rx * t; + var hy = 4 / 3 * ry * t; + var curve = [ + 2 * x1 - (x1 + hx * Math.sin(f1)), + 2 * y1 - (y1 - hy * Math.cos(f1)), + x2 + hx * Math.sin(f2), + y2 - hy * Math.cos(f2), + x2, + y2 + ]; + if (recursive) return curve; + if (res) curve = curve.concat(res); + for (var i = 0; i < curve.length; ) { + var rot = rotate(curve[i], curve[i + 1], angle); + curve[i++] = rot.x; + curve[i++] = rot.y; + } + return curve; +} +function rotate(x, y, rad) { + return { + x: x * Math.cos(rad) - y * Math.sin(rad), + y: x * Math.sin(rad) + y * Math.cos(rad) + }; +} +function radians$1(degress) { + return degress * (π / 180); +} +var abs = absSvgPath; +var normalize$2 = normalizeSvgPath; +var methods = { + "M": "moveTo", + "C": "bezierCurveTo" +}; +var drawSvgPath = function(context2, segments) { + context2.beginPath(); + normalize$2(abs(segments)).forEach( + function(segment2) { + var command2 = segment2[0]; + var args = segment2.slice(1); + context2[methods[command2]].apply(context2, args); + } + ); + context2.closePath(); +}; +var bitmapSdf$1 = calcSDF; +var INF = 1e20; +function calcSDF(src2, options) { + if (!options) options = {}; + var cutoff = options.cutoff == null ? 0.25 : options.cutoff; + var radius = options.radius == null ? 8 : options.radius; + var channel = options.channel || 0; + var w, h, size, data, intData, stride, ctx2, canvas2, imgData, i, l; + if (ArrayBuffer.isView(src2) || Array.isArray(src2)) { + if (!options.width || !options.height) throw Error("For raw data width and height should be provided by options"); + w = options.width, h = options.height; + data = src2; + if (!options.stride) stride = Math.floor(src2.length / w / h); + else stride = options.stride; + } else { + if (window.HTMLCanvasElement && src2 instanceof window.HTMLCanvasElement) { + canvas2 = src2; + ctx2 = canvas2.getContext("2d"); + w = canvas2.width, h = canvas2.height; + imgData = ctx2.getImageData(0, 0, w, h); + data = imgData.data; + stride = 4; + } else if (window.CanvasRenderingContext2D && src2 instanceof window.CanvasRenderingContext2D) { + canvas2 = src2.canvas; + ctx2 = src2; + w = canvas2.width, h = canvas2.height; + imgData = ctx2.getImageData(0, 0, w, h); + data = imgData.data; + stride = 4; + } else if (window.ImageData && src2 instanceof window.ImageData) { + imgData = src2; + w = src2.width, h = src2.height; + data = imgData.data; + stride = 4; + } + } + size = Math.max(w, h); + if (window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray || window.Uint8Array && data instanceof window.Uint8Array) { + intData = data; + data = Array(w * h); + for (i = 0, l = Math.floor(intData.length / stride); i < l; i++) { + data[i] = intData[i * stride + channel] / 255; + } + } else { + if (stride !== 1) throw Error("Raw data can have only 1 value per pixel"); + } + var gridOuter = Array(w * h); + var gridInner = Array(w * h); + var f = Array(size); + var d = Array(size); + var z = Array(size + 1); + var v = Array(size); + for (i = 0, l = w * h; i < l; i++) { + var a = data[i]; + gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2); + gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2); + } + edt(gridOuter, w, h, f, d, v, z); + edt(gridInner, w, h, f, d, v, z); + var dist2 = window.Float32Array ? new Float32Array(w * h) : new Array(w * h); + for (i = 0, l = w * h; i < l; i++) { + dist2[i] = Math.min(Math.max(1 - ((gridOuter[i] - gridInner[i]) / radius + cutoff), 0), 1); + } + return dist2; +} +function edt(data, width, height, f, d, v, z) { + for (var x = 0; x < width; x++) { + for (var y = 0; y < height; y++) { + f[y] = data[y * width + x]; + } + edt1d(f, d, v, z, height); + for (y = 0; y < height; y++) { + data[y * width + x] = d[y]; + } + } + for (y = 0; y < height; y++) { + for (x = 0; x < width; x++) { + f[x] = data[y * width + x]; + } + edt1d(f, d, v, z, width); + for (x = 0; x < width; x++) { + data[y * width + x] = Math.sqrt(d[x]); + } + } +} +function edt1d(f, d, v, z, n) { + v[0] = 0; + z[0] = -1e20; + z[1] = 1e20; + for (var q = 1, k = 0; q < n; q++) { + var s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); + while (s <= z[k]) { + k--; + s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); + } + k++; + v[k] = q; + z[k] = s; + z[k + 1] = 1e20; + } + for (q = 0, k = 0; q < n; q++) { + while (z[k + 1] < q) k++; + d[q] = (q - v[k]) * (q - v[k]) + f[v[k]]; + } +} +var pathBounds = svgPathBounds; +var parsePath = parseSvgPath; +var drawPath = drawSvgPath; +var isSvgPath = isSvgPath$2; +var bitmapSdf = bitmapSdf$1; +var canvas$1 = document.createElement("canvas"); +var ctx$1 = canvas$1.getContext("2d"); +var svgPathSdf = pathSdf; +function pathSdf(path, options) { + if (!isSvgPath(path)) throw Error("Argument should be valid svg path string"); + if (!options) options = {}; + var w, h; + if (options.shape) { + w = options.shape[0]; + h = options.shape[1]; + } else { + w = canvas$1.width = options.w || options.width || 200; + h = canvas$1.height = options.h || options.height || 200; + } + var size = Math.min(w, h); + var stroke = options.stroke || 0; + var viewbox = options.viewbox || options.viewBox || pathBounds(path); + var scale2 = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])]; + var maxScale = Math.min(scale2[0] || 0, scale2[1] || 0) / 2; + ctx$1.fillStyle = "black"; + ctx$1.fillRect(0, 0, w, h); + ctx$1.fillStyle = "white"; + if (stroke) { + if (typeof stroke != "number") stroke = 1; + if (stroke > 0) { + ctx$1.strokeStyle = "white"; + } else { + ctx$1.strokeStyle = "black"; + } + ctx$1.lineWidth = Math.abs(stroke); + } + ctx$1.translate(w * 0.5, h * 0.5); + ctx$1.scale(maxScale, maxScale); + if (isPath2DSupported()) { + var path2d = new Path2D(path); + ctx$1.fill(path2d); + stroke && ctx$1.stroke(path2d); + } else { + var segments = parsePath(path); + drawPath(ctx$1, segments); + ctx$1.fill(); + stroke && ctx$1.stroke(); + } + ctx$1.setTransform(1, 0, 0, 1, 0, 0); + var data = bitmapSdf(ctx$1, { + cutoff: options.cutoff != null ? options.cutoff : 0.5, + radius: options.radius != null ? options.radius : size * 0.5 + }); + return data; +} +var path2DSupported; +function isPath2DSupported() { + if (path2DSupported != null) return path2DSupported; + var ctx2 = document.createElement("canvas").getContext("2d"); + ctx2.canvas.width = ctx2.canvas.height = 1; + if (!window.Path2D) return path2DSupported = false; + var path = new Path2D("M0,0h1v1h-1v-1Z"); + ctx2.fillStyle = "black"; + ctx2.fill(path); + var idata = ctx2.getImageData(0, 0, 1, 1); + return path2DSupported = idata && idata.data && idata.data[3] === 255; +} +var colorName = { + "aliceblue": [240, 248, 255], + "antiquewhite": [250, 235, 215], + "aqua": [0, 255, 255], + "aquamarine": [127, 255, 212], + "azure": [240, 255, 255], + "beige": [245, 245, 220], + "bisque": [255, 228, 196], + "black": [0, 0, 0], + "blanchedalmond": [255, 235, 205], + "blue": [0, 0, 255], + "blueviolet": [138, 43, 226], + "brown": [165, 42, 42], + "burlywood": [222, 184, 135], + "cadetblue": [95, 158, 160], + "chartreuse": [127, 255, 0], + "chocolate": [210, 105, 30], + "coral": [255, 127, 80], + "cornflowerblue": [100, 149, 237], + "cornsilk": [255, 248, 220], + "crimson": [220, 20, 60], + "cyan": [0, 255, 255], + "darkblue": [0, 0, 139], + "darkcyan": [0, 139, 139], + "darkgoldenrod": [184, 134, 11], + "darkgray": [169, 169, 169], + "darkgreen": [0, 100, 0], + "darkgrey": [169, 169, 169], + "darkkhaki": [189, 183, 107], + "darkmagenta": [139, 0, 139], + "darkolivegreen": [85, 107, 47], + "darkorange": [255, 140, 0], + "darkorchid": [153, 50, 204], + "darkred": [139, 0, 0], + "darksalmon": [233, 150, 122], + "darkseagreen": [143, 188, 143], + "darkslateblue": [72, 61, 139], + "darkslategray": [47, 79, 79], + "darkslategrey": [47, 79, 79], + "darkturquoise": [0, 206, 209], + "darkviolet": [148, 0, 211], + "deeppink": [255, 20, 147], + "deepskyblue": [0, 191, 255], + "dimgray": [105, 105, 105], + "dimgrey": [105, 105, 105], + "dodgerblue": [30, 144, 255], + "firebrick": [178, 34, 34], + "floralwhite": [255, 250, 240], + "forestgreen": [34, 139, 34], + "fuchsia": [255, 0, 255], + "gainsboro": [220, 220, 220], + "ghostwhite": [248, 248, 255], + "gold": [255, 215, 0], + "goldenrod": [218, 165, 32], + "gray": [128, 128, 128], + "green": [0, 128, 0], + "greenyellow": [173, 255, 47], + "grey": [128, 128, 128], + "honeydew": [240, 255, 240], + "hotpink": [255, 105, 180], + "indianred": [205, 92, 92], + "indigo": [75, 0, 130], + "ivory": [255, 255, 240], + "khaki": [240, 230, 140], + "lavender": [230, 230, 250], + "lavenderblush": [255, 240, 245], + "lawngreen": [124, 252, 0], + "lemonchiffon": [255, 250, 205], + "lightblue": [173, 216, 230], + "lightcoral": [240, 128, 128], + "lightcyan": [224, 255, 255], + "lightgoldenrodyellow": [250, 250, 210], + "lightgray": [211, 211, 211], + "lightgreen": [144, 238, 144], + "lightgrey": [211, 211, 211], + "lightpink": [255, 182, 193], + "lightsalmon": [255, 160, 122], + "lightseagreen": [32, 178, 170], + "lightskyblue": [135, 206, 250], + "lightslategray": [119, 136, 153], + "lightslategrey": [119, 136, 153], + "lightsteelblue": [176, 196, 222], + "lightyellow": [255, 255, 224], + "lime": [0, 255, 0], + "limegreen": [50, 205, 50], + "linen": [250, 240, 230], + "magenta": [255, 0, 255], + "maroon": [128, 0, 0], + "mediumaquamarine": [102, 205, 170], + "mediumblue": [0, 0, 205], + "mediumorchid": [186, 85, 211], + "mediumpurple": [147, 112, 219], + "mediumseagreen": [60, 179, 113], + "mediumslateblue": [123, 104, 238], + "mediumspringgreen": [0, 250, 154], + "mediumturquoise": [72, 209, 204], + "mediumvioletred": [199, 21, 133], + "midnightblue": [25, 25, 112], + "mintcream": [245, 255, 250], + "mistyrose": [255, 228, 225], + "moccasin": [255, 228, 181], + "navajowhite": [255, 222, 173], + "navy": [0, 0, 128], + "oldlace": [253, 245, 230], + "olive": [128, 128, 0], + "olivedrab": [107, 142, 35], + "orange": [255, 165, 0], + "orangered": [255, 69, 0], + "orchid": [218, 112, 214], + "palegoldenrod": [238, 232, 170], + "palegreen": [152, 251, 152], + "paleturquoise": [175, 238, 238], + "palevioletred": [219, 112, 147], + "papayawhip": [255, 239, 213], + "peachpuff": [255, 218, 185], + "peru": [205, 133, 63], + "pink": [255, 192, 203], + "plum": [221, 160, 221], + "powderblue": [176, 224, 230], + "purple": [128, 0, 128], + "rebeccapurple": [102, 51, 153], + "red": [255, 0, 0], + "rosybrown": [188, 143, 143], + "royalblue": [65, 105, 225], + "saddlebrown": [139, 69, 19], + "salmon": [250, 128, 114], + "sandybrown": [244, 164, 96], + "seagreen": [46, 139, 87], + "seashell": [255, 245, 238], + "sienna": [160, 82, 45], + "silver": [192, 192, 192], + "skyblue": [135, 206, 235], + "slateblue": [106, 90, 205], + "slategray": [112, 128, 144], + "slategrey": [112, 128, 144], + "snow": [255, 250, 250], + "springgreen": [0, 255, 127], + "steelblue": [70, 130, 180], + "tan": [210, 180, 140], + "teal": [0, 128, 128], + "thistle": [216, 191, 216], + "tomato": [255, 99, 71], + "turquoise": [64, 224, 208], + "violet": [238, 130, 238], + "wheat": [245, 222, 179], + "white": [255, 255, 255], + "whitesmoke": [245, 245, 245], + "yellow": [255, 255, 0], + "yellowgreen": [154, 205, 50] +}; +var names = colorName; +var colorParse = parse$3; +var baseHues = { + red: 0, + orange: 60, + yellow: 120, + green: 180, + blue: 240, + purple: 300 +}; +function parse$3(cstr) { + var m, parts = [], alpha = 1, space; + if (typeof cstr === "string") { + cstr = cstr.toLowerCase(); + if (names[cstr]) { + parts = names[cstr].slice(); + space = "rgb"; + } else if (cstr === "transparent") { + alpha = 0; + space = "rgb"; + parts = [0, 0, 0]; + } else if (/^#[A-Fa-f0-9]+$/.test(cstr)) { + var base = cstr.slice(1); + var size = base.length; + var isShort = size <= 4; + alpha = 1; + if (isShort) { + parts = [ + parseInt(base[0] + base[0], 16), + parseInt(base[1] + base[1], 16), + parseInt(base[2] + base[2], 16) + ]; + if (size === 4) { + alpha = parseInt(base[3] + base[3], 16) / 255; + } + } else { + parts = [ + parseInt(base[0] + base[1], 16), + parseInt(base[2] + base[3], 16), + parseInt(base[4] + base[5], 16) + ]; + if (size === 8) { + alpha = parseInt(base[6] + base[7], 16) / 255; + } + } + if (!parts[0]) parts[0] = 0; + if (!parts[1]) parts[1] = 0; + if (!parts[2]) parts[2] = 0; + space = "rgb"; + } else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) { + var name2 = m[1]; + var isRGB = name2 === "rgb"; + var base = name2.replace(/a$/, ""); + space = base; + var size = base === "cmyk" ? 4 : base === "gray" ? 1 : 3; + parts = m[2].trim().split(/\s*[,\/]\s*|\s+/).map(function(x, i) { + if (/%$/.test(x)) { + if (i === size) return parseFloat(x) / 100; + if (base === "rgb") return parseFloat(x) * 255 / 100; + return parseFloat(x); + } else if (base[i] === "h") { + if (/deg$/.test(x)) { + return parseFloat(x); + } else if (baseHues[x] !== void 0) { + return baseHues[x]; + } + } + return parseFloat(x); + }); + if (name2 === base) parts.push(1); + alpha = isRGB ? 1 : parts[size] === void 0 ? 1 : parts[size]; + parts = parts.slice(0, size); + } else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) { + parts = cstr.match(/([0-9]+)/g).map(function(value2) { + return parseFloat(value2); + }); + space = cstr.match(/([a-z])/ig).join("").toLowerCase(); + } + } else if (!isNaN(cstr)) { + space = "rgb"; + parts = [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255]; + } else if (Array.isArray(cstr) || cstr.length) { + parts = [cstr[0], cstr[1], cstr[2]]; + space = "rgb"; + alpha = cstr.length === 4 ? cstr[3] : 1; + } else if (cstr instanceof Object) { + if (cstr.r != null || cstr.red != null || cstr.R != null) { + space = "rgb"; + parts = [ + cstr.r || cstr.red || cstr.R || 0, + cstr.g || cstr.green || cstr.G || 0, + cstr.b || cstr.blue || cstr.B || 0 + ]; + } else { + space = "hsl"; + parts = [ + cstr.h || cstr.hue || cstr.H || 0, + cstr.s || cstr.saturation || cstr.S || 0, + cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness + ]; + } + alpha = cstr.a || cstr.alpha || cstr.opacity || 1; + if (cstr.opacity != null) alpha /= 100; + } + return { + space, + values: parts, + alpha + }; +} +var rgb$3 = {}; +var rgb$2 = rgb$3; +var hsl$4 = { + name: "hsl", + min: [0, 0, 0], + max: [360, 100, 100], + channel: ["hue", "saturation", "lightness"], + alias: ["HSL"], + rgb: function(hsl2) { + var h = hsl2[0] / 360, s = hsl2[1] / 100, l = hsl2[2] / 100, t12, t22, t32, rgb2, val; + if (s === 0) { + val = l * 255; + return [val, val, val]; + } + if (l < 0.5) { + t22 = l * (1 + s); + } else { + t22 = l + s - l * s; + } + t12 = 2 * l - t22; + rgb2 = [0, 0, 0]; + for (var i = 0; i < 3; i++) { + t32 = h + 1 / 3 * -(i - 1); + if (t32 < 0) { + t32++; + } else if (t32 > 1) { + t32--; + } + if (6 * t32 < 1) { + val = t12 + (t22 - t12) * 6 * t32; + } else if (2 * t32 < 1) { + val = t22; + } else if (3 * t32 < 2) { + val = t12 + (t22 - t12) * (2 / 3 - t32) * 6; + } else { + val = t12; + } + rgb2[i] = val * 255; + } + return rgb2; + } +}; +rgb$2.hsl = function(rgb2) { + var r = rgb2[0] / 255, g = rgb2[1] / 255, b = rgb2[2] / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), delta2 = max - min, h, s, l; + if (max === min) { + h = 0; + } else if (r === max) { + h = (g - b) / delta2; + } else if (g === max) { + h = 2 + (b - r) / delta2; + } else if (b === max) { + h = 4 + (r - g) / delta2; + } + h = Math.min(h * 60, 360); + if (h < 0) { + h += 360; + } + l = (min + max) / 2; + if (max === min) { + s = 0; + } else if (l <= 0.5) { + s = delta2 / (max + min); + } else { + s = delta2 / (2 - max - min); + } + return [h, s * 100, l * 100]; +}; +var parse$2 = colorParse; +var hsl$3 = hsl$4; +var clamp$2 = clamp_1; +var colorRgba = function rgba(color2) { + var values; + var parsed = parse$2(color2); + if (!parsed.space) return []; + values = Array(3); + values[0] = clamp$2(parsed.values[0], 0, 255); + values[1] = clamp$2(parsed.values[1], 0, 255); + values[2] = clamp$2(parsed.values[2], 0, 255); + if (parsed.space[0] === "h") { + values = hsl$3.rgb(values); + } + values.push(clamp$2(parsed.alpha, 0, 1)); + return values; +}; +var rgba$7 = colorRgba; +var clamp$1 = clamp_1; +var dtype = dtype$3; +var colorNormalize = function normalize(color2, type) { + if (type === "float" || !type) type = "array"; + if (type === "uint") type = "uint8"; + if (type === "uint_clamped") type = "uint8_clamped"; + var Ctor = dtype(type); + var output = new Ctor(4); + var normalize3 = type !== "uint8" && type !== "uint8_clamped"; + if (!color2.length || typeof color2 === "string") { + color2 = rgba$7(color2); + color2[0] /= 255; + color2[1] /= 255; + color2[2] /= 255; + } + if (isInt(color2)) { + output[0] = color2[0]; + output[1] = color2[1]; + output[2] = color2[2]; + output[3] = color2[3] != null ? color2[3] : 255; + if (normalize3) { + output[0] /= 255; + output[1] /= 255; + output[2] /= 255; + output[3] /= 255; + } + return output; + } + if (!normalize3) { + output[0] = clamp$1(Math.floor(color2[0] * 255), 0, 255); + output[1] = clamp$1(Math.floor(color2[1] * 255), 0, 255); + output[2] = clamp$1(Math.floor(color2[2] * 255), 0, 255); + output[3] = color2[3] == null ? 255 : clamp$1(Math.floor(color2[3] * 255), 0, 255); + } else { + output[0] = color2[0]; + output[1] = color2[1]; + output[2] = color2[2]; + output[3] = color2[3] != null ? color2[3] : 1; + } + return output; +}; +function isInt(color2) { + if (color2 instanceof Uint8Array || color2 instanceof Uint8ClampedArray) return true; + if (Array.isArray(color2) && (color2[0] > 1 || color2[0] === 0) && (color2[1] > 1 || color2[1] === 0) && (color2[2] > 1 || color2[2] === 0) && (!color2[3] || color2[3] > 1)) return true; + return false; +} +var isNumeric$1 = fastIsnumeric; +var rgba$6 = colorNormalize; +var Colorscale$1 = colorscale; +var colorDflt = attributes$N.defaultLine; +var isArrayOrTypedArray$1 = array$2.isArrayOrTypedArray; +var colorDfltRgba = rgba$6(colorDflt); +var opacityDflt = 1; +function calculateColor(colorIn, opacityIn) { + var colorOut = colorIn; + colorOut[3] *= opacityIn; + return colorOut; +} +function validateColor(colorIn) { + if (isNumeric$1(colorIn)) return colorDfltRgba; + var colorOut = rgba$6(colorIn); + return colorOut.length ? colorOut : colorDfltRgba; +} +function validateOpacity(opacityIn) { + return isNumeric$1(opacityIn) ? opacityIn : opacityDflt; +} +function formatColor$1(containerIn, opacityIn, len) { + var colorIn = containerIn.color; + if (colorIn && colorIn._inputArray) colorIn = colorIn._inputArray; + var isArrayColorIn = isArrayOrTypedArray$1(colorIn); + var isArrayOpacityIn = isArrayOrTypedArray$1(opacityIn); + var cOpts = Colorscale$1.extractOpts(containerIn); + var colorOut = []; + var sclFunc, getColor, getOpacity, colori, opacityi; + if (cOpts.colorscale !== void 0) { + sclFunc = Colorscale$1.makeColorScaleFuncFromTrace(containerIn); + } else { + sclFunc = validateColor; + } + if (isArrayColorIn) { + getColor = function(c, i2) { + return c[i2] === void 0 ? colorDfltRgba : rgba$6(sclFunc(c[i2])); + }; + } else getColor = validateColor; + if (isArrayOpacityIn) { + getOpacity = function(o, i2) { + return o[i2] === void 0 ? opacityDflt : validateOpacity(o[i2]); + }; + } else getOpacity = validateOpacity; + if (isArrayColorIn || isArrayOpacityIn) { + for (var i = 0; i < len; i++) { + colori = getColor(colorIn, i); + opacityi = getOpacity(opacityIn, i); + colorOut[i] = calculateColor(colori, opacityi); + } + } else colorOut = calculateColor(rgba$6(colorIn), opacityIn); + return colorOut; +} +var gl_format_color = { + formatColor: formatColor$1 +}; +var isNumeric = fastIsnumeric; +var svgSdf = svgPathSdf; +var rgba$5 = colorNormalize; +var Registry$1 = registry; +var Lib$c = libExports; +var isArrayOrTypedArray = Lib$c.isArrayOrTypedArray; +var Drawing$3 = drawingExports; +var AxisIDs$1 = axis_ids; +var formatColor = gl_format_color.formatColor; +var subTypes$2 = subtypes$3; +var makeBubbleSizeFn2 = make_bubble_size_func; +var helpers$7 = helpers$9; +var constants$7 = constants$a; +var DESELECTDIM$1 = interactions.DESELECTDIM; +var TEXTOFFSETSIGN = { + start: 1, + left: 1, + end: -1, + right: -1, + middle: 0, + center: 0, + bottom: 1, + top: -1 +}; +var appendArrayPointValue$1 = helpers$J.appendArrayPointValue; +function convertStyle(gd, trace) { + var i; + var opts = { + marker: void 0, + markerSel: void 0, + markerUnsel: void 0, + line: void 0, + fill: void 0, + errorX: void 0, + errorY: void 0, + text: void 0, + textSel: void 0, + textUnsel: void 0 + }; + var plotGlPixelRatio = gd._context.plotGlPixelRatio; + if (trace.visible !== true) return opts; + if (subTypes$2.hasText(trace)) { + opts.text = convertTextStyle(gd, trace); + opts.textSel = convertTextSelection(gd, trace, trace.selected); + opts.textUnsel = convertTextSelection(gd, trace, trace.unselected); + } + if (subTypes$2.hasMarkers(trace)) { + opts.marker = convertMarkerStyle(gd, trace); + opts.markerSel = convertMarkerSelection(gd, trace, trace.selected); + opts.markerUnsel = convertMarkerSelection(gd, trace, trace.unselected); + if (!trace.unselected && isArrayOrTypedArray(trace.marker.opacity)) { + var mo = trace.marker.opacity; + opts.markerUnsel.opacity = new Array(mo.length); + for (i = 0; i < mo.length; i++) { + opts.markerUnsel.opacity[i] = DESELECTDIM$1 * mo[i]; + } + } + } + if (subTypes$2.hasLines(trace)) { + opts.line = { + overlay: true, + thickness: trace.line.width * plotGlPixelRatio, + color: trace.line.color, + opacity: trace.opacity + }; + var dashes = (constants$7.DASHES[trace.line.dash] || [1]).slice(); + for (i = 0; i < dashes.length; ++i) { + dashes[i] *= trace.line.width * plotGlPixelRatio; + } + opts.line.dashes = dashes; + } + if (trace.error_x && trace.error_x.visible) { + opts.errorX = convertErrorBarStyle(trace, trace.error_x, plotGlPixelRatio); + } + if (trace.error_y && trace.error_y.visible) { + opts.errorY = convertErrorBarStyle(trace, trace.error_y, plotGlPixelRatio); + } + if (!!trace.fill && trace.fill !== "none") { + opts.fill = { + closed: true, + fill: trace.fillcolor, + thickness: 0 + }; + } + return opts; +} +function convertTextStyle(gd, trace) { + var fullLayout = gd._fullLayout; + var count2 = trace._length; + var textfontIn = trace.textfont; + var textpositionIn = trace.textposition; + var textPos = isArrayOrTypedArray(textpositionIn) ? textpositionIn : [textpositionIn]; + var tfc = textfontIn.color; + var tfs = textfontIn.size; + var tff = textfontIn.family; + var tfw = textfontIn.weight; + var tfy = textfontIn.style; + var tfv = textfontIn.variant; + var optsOut = {}; + var i; + var plotGlPixelRatio = gd._context.plotGlPixelRatio; + var texttemplate = trace.texttemplate; + if (texttemplate) { + optsOut.text = []; + var d3locale = fullLayout._d3locale; + var isArray2 = Array.isArray(texttemplate); + var N = isArray2 ? Math.min(texttemplate.length, count2) : count2; + var txt = isArray2 ? function(i2) { + return texttemplate[i2]; + } : function() { + return texttemplate; + }; + for (i = 0; i < N; i++) { + var d = { i }; + var labels = trace._module.formatLabels(d, trace, fullLayout); + var pointValues = {}; + appendArrayPointValue$1(pointValues, trace, i); + var meta = trace._meta || {}; + optsOut.text.push(Lib$c.texttemplateString(txt(i), labels, d3locale, pointValues, d, meta)); + } + } else { + if (isArrayOrTypedArray(trace.text) && trace.text.length < count2) { + optsOut.text = trace.text.slice(); + } else { + optsOut.text = trace.text; + } + } + if (isArrayOrTypedArray(optsOut.text)) { + for (i = optsOut.text.length; i < count2; i++) { + optsOut.text[i] = ""; + } + } + optsOut.opacity = trace.opacity; + optsOut.font = {}; + optsOut.align = []; + optsOut.baseline = []; + for (i = 0; i < textPos.length; i++) { + var tp = textPos[i].split(/\s+/); + switch (tp[1]) { + case "left": + optsOut.align.push("right"); + break; + case "right": + optsOut.align.push("left"); + break; + default: + optsOut.align.push(tp[1]); + } + switch (tp[0]) { + case "top": + optsOut.baseline.push("bottom"); + break; + case "bottom": + optsOut.baseline.push("top"); + break; + default: + optsOut.baseline.push(tp[0]); + } + } + if (isArrayOrTypedArray(tfc)) { + optsOut.color = new Array(count2); + for (i = 0; i < count2; i++) { + optsOut.color[i] = tfc[i]; + } + } else { + optsOut.color = tfc; + } + if (isArrayOrTypedArray(tfs) || Array.isArray(tff) || isArrayOrTypedArray(tfw) || Array.isArray(tfy) || Array.isArray(tfv)) { + optsOut.font = new Array(count2); + for (i = 0; i < count2; i++) { + var fonti = optsOut.font[i] = {}; + fonti.size = (Lib$c.isTypedArray(tfs) ? tfs[i] : isArrayOrTypedArray(tfs) ? isNumeric(tfs[i]) ? tfs[i] : 0 : tfs) * plotGlPixelRatio; + fonti.family = Array.isArray(tff) ? tff[i] : tff; + fonti.weight = weightFallBack(isArrayOrTypedArray(tfw) ? tfw[i] : tfw); + fonti.style = Array.isArray(tfy) ? tfy[i] : tfy; + fonti.variant = Array.isArray(tfv) ? tfv[i] : tfv; + } + } else { + optsOut.font = { + size: tfs * plotGlPixelRatio, + family: tff, + weight: weightFallBack(tfw), + style: tfy, + variant: tfv + }; + } + return optsOut; +} +function weightFallBack(w) { + if (w <= 1e3) { + return w > 500 ? "bold" : "normal"; + } + return w; +} +function convertMarkerStyle(gd, trace) { + var count2 = trace._length; + var optsIn = trace.marker; + var optsOut = {}; + var i; + var multiSymbol = isArrayOrTypedArray(optsIn.symbol); + var multiAngle = isArrayOrTypedArray(optsIn.angle); + var multiColor = isArrayOrTypedArray(optsIn.color); + var multiLineColor = isArrayOrTypedArray(optsIn.line.color); + var multiOpacity = isArrayOrTypedArray(optsIn.opacity); + var multiSize = isArrayOrTypedArray(optsIn.size); + var multiLineWidth = isArrayOrTypedArray(optsIn.line.width); + var isOpen; + if (!multiSymbol) isOpen = helpers$7.isOpenSymbol(optsIn.symbol); + if (multiSymbol || multiColor || multiLineColor || multiOpacity || multiAngle) { + optsOut.symbols = new Array(count2); + optsOut.angles = new Array(count2); + optsOut.colors = new Array(count2); + optsOut.borderColors = new Array(count2); + var symbols = optsIn.symbol; + var angles2 = optsIn.angle; + var colors = formatColor(optsIn, optsIn.opacity, count2); + var borderColors = formatColor(optsIn.line, optsIn.opacity, count2); + if (!isArrayOrTypedArray(borderColors[0])) { + var borderColor = borderColors; + borderColors = Array(count2); + for (i = 0; i < count2; i++) { + borderColors[i] = borderColor; + } + } + if (!isArrayOrTypedArray(colors[0])) { + var color2 = colors; + colors = Array(count2); + for (i = 0; i < count2; i++) { + colors[i] = color2; + } + } + if (!isArrayOrTypedArray(symbols)) { + var symbol = symbols; + symbols = Array(count2); + for (i = 0; i < count2; i++) { + symbols[i] = symbol; + } + } + if (!isArrayOrTypedArray(angles2)) { + var angle = angles2; + angles2 = Array(count2); + for (i = 0; i < count2; i++) { + angles2[i] = angle; + } + } + optsOut.symbols = symbols; + optsOut.angles = angles2; + optsOut.colors = colors; + optsOut.borderColors = borderColors; + for (i = 0; i < count2; i++) { + if (multiSymbol) { + isOpen = helpers$7.isOpenSymbol(optsIn.symbol[i]); + } + if (isOpen) { + borderColors[i] = colors[i].slice(); + colors[i] = colors[i].slice(); + colors[i][3] = 0; + } + } + optsOut.opacity = trace.opacity; + optsOut.markers = new Array(count2); + for (i = 0; i < count2; i++) { + optsOut.markers[i] = getSymbolSdf({ + mx: optsOut.symbols[i], + ma: optsOut.angles[i] + }, trace); + } + } else { + if (isOpen) { + optsOut.color = rgba$5(optsIn.color, "uint8"); + optsOut.color[3] = 0; + optsOut.borderColor = rgba$5(optsIn.color, "uint8"); + } else { + optsOut.color = rgba$5(optsIn.color, "uint8"); + optsOut.borderColor = rgba$5(optsIn.line.color, "uint8"); + } + optsOut.opacity = trace.opacity * optsIn.opacity; + optsOut.marker = getSymbolSdf({ + mx: optsIn.symbol, + ma: optsIn.angle + }, trace); + } + var sizeFactor = 1; + var markerSizeFunc = makeBubbleSizeFn2(trace, sizeFactor); + var s; + if (multiSize || multiLineWidth) { + var sizes2 = optsOut.sizes = new Array(count2); + var borderSizes = optsOut.borderSizes = new Array(count2); + var sizeTotal = 0; + var sizeAvg; + if (multiSize) { + for (i = 0; i < count2; i++) { + sizes2[i] = markerSizeFunc(optsIn.size[i]); + sizeTotal += sizes2[i]; + } + sizeAvg = sizeTotal / count2; + } else { + s = markerSizeFunc(optsIn.size); + for (i = 0; i < count2; i++) { + sizes2[i] = s; + } + } + if (multiLineWidth) { + for (i = 0; i < count2; i++) { + borderSizes[i] = optsIn.line.width[i]; + } + } else { + s = optsIn.line.width; + for (i = 0; i < count2; i++) { + borderSizes[i] = s; + } + } + optsOut.sizeAvg = sizeAvg; + } else { + optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10); + optsOut.borderSizes = markerSizeFunc(optsIn.line.width); + } + return optsOut; +} +function convertMarkerSelection(gd, trace, target) { + var optsIn = trace.marker; + var optsOut = {}; + if (!target) return optsOut; + if (target.marker && target.marker.symbol) { + optsOut = convertMarkerStyle(gd, Lib$c.extendFlat({}, optsIn, target.marker)); + } else if (target.marker) { + if (target.marker.size) optsOut.size = target.marker.size; + if (target.marker.color) optsOut.colors = target.marker.color; + if (target.marker.opacity !== void 0) optsOut.opacity = target.marker.opacity; + } + return optsOut; +} +function convertTextSelection(gd, trace, target) { + var optsOut = {}; + if (!target) return optsOut; + if (target.textfont) { + var optsIn = { + opacity: 1, + text: trace.text, + texttemplate: trace.texttemplate, + textposition: trace.textposition, + textfont: Lib$c.extendFlat({}, trace.textfont) + }; + if (target.textfont) { + Lib$c.extendFlat(optsIn.textfont, target.textfont); + } + optsOut = convertTextStyle(gd, optsIn); + } + return optsOut; +} +function convertErrorBarStyle(trace, target, plotGlPixelRatio) { + var optsOut = { + capSize: target.width * 2 * plotGlPixelRatio, + lineWidth: target.thickness * plotGlPixelRatio, + color: target.color + }; + if (target.copy_ystyle) { + optsOut = trace.error_y; + } + return optsOut; +} +var SYMBOL_SDF_SIZE = constants$7.SYMBOL_SDF_SIZE; +var SYMBOL_SIZE = constants$7.SYMBOL_SIZE; +var SYMBOL_STROKE = constants$7.SYMBOL_STROKE; +var SYMBOL_SDF = {}; +var SYMBOL_SVG_CIRCLE = Drawing$3.symbolFuncs[0](SYMBOL_SIZE * 0.05); +function getSymbolSdf(d, trace) { + var symbol = d.mx; + if (symbol === "circle") return null; + var symbolPath, symbolSdf; + var symbolNumber = Drawing$3.symbolNumber(symbol); + var symbolFunc = Drawing$3.symbolFuncs[symbolNumber % 100]; + var symbolNoDot = !!Drawing$3.symbolNoDot[symbolNumber % 100]; + var symbolNoFill = !!Drawing$3.symbolNoFill[symbolNumber % 100]; + var isDot = helpers$7.isDotSymbol(symbol); + if (d.ma) symbol += "_" + d.ma; + if (SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; + var angle = Drawing$3.getMarkerAngle(d, trace); + if (isDot && !symbolNoDot) { + symbolPath = symbolFunc(SYMBOL_SIZE * 1.1, angle) + SYMBOL_SVG_CIRCLE; + } else { + symbolPath = symbolFunc(SYMBOL_SIZE, angle); + } + symbolSdf = svgSdf(symbolPath, { + w: SYMBOL_SDF_SIZE, + h: SYMBOL_SDF_SIZE, + viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE], + stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE + }); + SYMBOL_SDF[symbol] = symbolSdf; + return symbolSdf || null; +} +function convertLinePositions(gd, trace, positions) { + var len = positions.length; + var count2 = len / 2; + var linePositions; + var i; + if (subTypes$2.hasLines(trace) && count2) { + if (trace.line.shape === "hv") { + linePositions = []; + for (i = 0; i < count2 - 1; i++) { + if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN, NaN, NaN, NaN); + } else { + linePositions.push(positions[i * 2], positions[i * 2 + 1]); + if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) { + linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]); + } else { + linePositions.push(NaN, NaN); + } + } + } + linePositions.push(positions[len - 2], positions[len - 1]); + } else if (trace.line.shape === "hvh") { + linePositions = []; + for (i = 0; i < count2 - 1; i++) { + if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) { + if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) { + linePositions.push(positions[i * 2], positions[i * 2 + 1]); + } else { + linePositions.push(NaN, NaN); + } + linePositions.push(NaN, NaN); + } else { + var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2; + linePositions.push( + positions[i * 2], + positions[i * 2 + 1], + midPtX, + positions[i * 2 + 1], + midPtX, + positions[i * 2 + 3] + ); + } + } + linePositions.push(positions[len - 2], positions[len - 1]); + } else if (trace.line.shape === "vhv") { + linePositions = []; + for (i = 0; i < count2 - 1; i++) { + if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) { + if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) { + linePositions.push(positions[i * 2], positions[i * 2 + 1]); + } else { + linePositions.push(NaN, NaN); + } + linePositions.push(NaN, NaN); + } else { + var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2; + linePositions.push( + positions[i * 2], + positions[i * 2 + 1], + positions[i * 2], + midPtY, + positions[i * 2 + 2], + midPtY + ); + } + } + linePositions.push(positions[len - 2], positions[len - 1]); + } else if (trace.line.shape === "vh") { + linePositions = []; + for (i = 0; i < count2 - 1; i++) { + if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { + linePositions.push(NaN, NaN, NaN, NaN); + } else { + linePositions.push(positions[i * 2], positions[i * 2 + 1]); + if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) { + linePositions.push(positions[i * 2], positions[i * 2 + 3]); + } else { + linePositions.push(NaN, NaN); + } + } + } + linePositions.push(positions[len - 2], positions[len - 1]); + } else { + linePositions = positions; + } + } + var hasNaN = false; + for (i = 0; i < linePositions.length; i++) { + if (isNaN(linePositions[i])) { + hasNaN = true; + break; + } + } + var join = hasNaN || linePositions.length > constants$7.TOO_MANY_POINTS ? "rect" : subTypes$2.hasMarkers(trace) ? "rect" : "round"; + if (hasNaN && trace.connectgaps) { + var lastX = linePositions[0]; + var lastY = linePositions[1]; + for (i = 0; i < linePositions.length; i += 2) { + if (isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { + linePositions[i] = lastX; + linePositions[i + 1] = lastY; + } else { + lastX = linePositions[i]; + lastY = linePositions[i + 1]; + } + } + } + return { + join, + positions: linePositions + }; +} +function convertErrorBarPositions(gd, trace, positions, x, y) { + var makeComputeError = Registry$1.getComponentMethod("errorbars", "makeComputeError"); + var xa = AxisIDs$1.getFromId(gd, trace.xaxis, "x"); + var ya = AxisIDs$1.getFromId(gd, trace.yaxis, "y"); + var count2 = positions.length / 2; + var out = {}; + function convertOneAxis(coords, ax) { + var axLetter = ax._id.charAt(0); + var opts = trace["error_" + axLetter]; + if (opts && opts.visible && (ax.type === "linear" || ax.type === "log")) { + var computeError = makeComputeError(opts); + var pOffset = { x: 0, y: 1 }[axLetter]; + var eOffset = { x: [0, 1, 2, 3], y: [2, 3, 0, 1] }[axLetter]; + var errors = new Float64Array(4 * count2); + var minShoe = Infinity; + var maxHat = -Infinity; + for (var i = 0, j = 0; i < count2; i++, j += 4) { + var dc = coords[i]; + if (isNumeric(dc)) { + var dl = positions[i * 2 + pOffset]; + var vals = computeError(dc, i); + var lv = vals[0]; + var hv = vals[1]; + if (isNumeric(lv) && isNumeric(hv)) { + var shoe = dc - lv; + var hat = dc + hv; + errors[j + eOffset[0]] = dl - ax.c2l(shoe); + errors[j + eOffset[1]] = ax.c2l(hat) - dl; + errors[j + eOffset[2]] = 0; + errors[j + eOffset[3]] = 0; + minShoe = Math.min(minShoe, dc - lv); + maxHat = Math.max(maxHat, dc + hv); + } + } + } + out[axLetter] = { + positions, + errors, + _bnds: [minShoe, maxHat] + }; + } + } + convertOneAxis(x, xa); + convertOneAxis(y, ya); + return out; +} +function convertTextPosition(gd, trace, textOpts, markerOpts) { + var count2 = trace._length; + var out = {}; + var i; + if (subTypes$2.hasMarkers(trace)) { + var fontOpts = textOpts.font; + var align3 = textOpts.align; + var baseline = textOpts.baseline; + out.offset = new Array(count2); + for (i = 0; i < count2; i++) { + var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size; + var fs = isArrayOrTypedArray(fontOpts) ? fontOpts[i].size : fontOpts.size; + var a = isArrayOrTypedArray(align3) ? align3.length > 1 ? align3[i] : align3[0] : align3; + var b = isArrayOrTypedArray(baseline) ? baseline.length > 1 ? baseline[i] : baseline[0] : baseline; + var hSign = TEXTOFFSETSIGN[a]; + var vSign = TEXTOFFSETSIGN[b]; + var xPad = ms ? ms / 0.8 + 1 : 0; + var yPad = -vSign * xPad - vSign * 0.5; + out.offset[i] = [hSign * xPad / fs, yPad / fs]; + } + } + return out; +} +var convert$1 = { + style: convertStyle, + markerStyle: convertMarkerStyle, + markerSelection: convertMarkerSelection, + linePositions: convertLinePositions, + errorBarPositions: convertErrorBarPositions, + textPosition: convertTextPosition +}; +var Lib$b = libExports; +var scene_update = function sceneUpdate(gd, subplot) { + var scene = subplot._scene; + var resetOpts = { + // number of traces in subplot, since scene:subplot -> 1:1 + count: 0, + // whether scene requires init hook in plot call (dirty plot call) + dirty: true, + // last used options + lineOptions: [], + fillOptions: [], + markerOptions: [], + markerSelectedOptions: [], + markerUnselectedOptions: [], + errorXOptions: [], + errorYOptions: [], + textOptions: [], + textSelectedOptions: [], + textUnselectedOptions: [], + // selection batches + selectBatch: [], + unselectBatch: [] + }; + var initOpts = { + fill2d: false, + scatter2d: false, + error2d: false, + line2d: false, + glText: false, + select2d: false + }; + if (!subplot._scene) { + scene = subplot._scene = {}; + scene.init = function init2() { + Lib$b.extendFlat(scene, initOpts, resetOpts); + }; + scene.init(); + scene.update = function update2(opt) { + var opts = Lib$b.repeat(opt, scene.count); + if (scene.fill2d) scene.fill2d.update(opts); + if (scene.scatter2d) scene.scatter2d.update(opts); + if (scene.line2d) scene.line2d.update(opts); + if (scene.error2d) scene.error2d.update(opts.concat(opts)); + if (scene.select2d) scene.select2d.update(opts); + if (scene.glText) { + for (var i = 0; i < scene.count; i++) { + scene.glText[i].update(opt); + } + } + }; + scene.draw = function draw8() { + var count2 = scene.count; + var fill2d = scene.fill2d; + var error2d = scene.error2d; + var line2d = scene.line2d; + var scatter2d = scene.scatter2d; + var glText = scene.glText; + var select2d = scene.select2d; + var selectBatch = scene.selectBatch; + var unselectBatch = scene.unselectBatch; + for (var i = 0; i < count2; i++) { + if (fill2d && scene.fillOrder[i]) { + fill2d.draw(scene.fillOrder[i]); + } + if (line2d && scene.lineOptions[i]) { + line2d.draw(i); + } + if (error2d) { + if (scene.errorXOptions[i]) error2d.draw(i); + if (scene.errorYOptions[i]) error2d.draw(i + count2); + } + if (scatter2d && scene.markerOptions[i]) { + if (unselectBatch[i].length) { + var arg = Lib$b.repeat([], scene.count); + arg[i] = unselectBatch[i]; + scatter2d.draw(arg); + } else if (!selectBatch[i].length) { + scatter2d.draw(i); + } + } + if (glText[i] && scene.textOptions[i]) { + glText[i].render(); + } + } + if (select2d) { + select2d.draw(selectBatch); + } + scene.dirty = false; + }; + scene.destroy = function destroy2() { + if (scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy(); + if (scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy(); + if (scene.error2d && scene.error2d.destroy) scene.error2d.destroy(); + if (scene.line2d && scene.line2d.destroy) scene.line2d.destroy(); + if (scene.select2d && scene.select2d.destroy) scene.select2d.destroy(); + if (scene.glText) { + scene.glText.forEach(function(text) { + if (text.destroy) text.destroy(); + }); + } + scene.lineOptions = null; + scene.fillOptions = null; + scene.markerOptions = null; + scene.markerSelectedOptions = null; + scene.markerUnselectedOptions = null; + scene.errorXOptions = null; + scene.errorYOptions = null; + scene.textOptions = null; + scene.textSelectedOptions = null; + scene.textUnselectedOptions = null; + scene.selectBatch = null; + scene.unselectBatch = null; + subplot._scene = null; + }; + } + if (!scene.dirty) { + Lib$b.extendFlat(scene, resetOpts); + } + return scene; +}; +var cluster$2 = pointCluster; +var Lib$a = libExports; +var AxisIDs = axis_ids; +var findExtremes = autorange$2.findExtremes; +var alignPeriod2 = align_period; +var scatterCalc = calc_1$3; +var calcMarkerSize = scatterCalc.calcMarkerSize; +var calcAxisExpansion = scatterCalc.calcAxisExpansion; +var setFirstScatter = scatterCalc.setFirstScatter; +var calcColorscale = colorscale_calc; +var convert2 = convert$1; +var sceneUpdate2 = scene_update; +var BADNUM = numerical.BADNUM; +var TOO_MANY_POINTS = constants$a.TOO_MANY_POINTS; +var calc$3 = function calc4(gd, trace) { + var fullLayout = gd._fullLayout; + var xa = trace._xA = AxisIDs.getFromId(gd, trace.xaxis, "x"); + var ya = trace._yA = AxisIDs.getFromId(gd, trace.yaxis, "y"); + var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; + var len = trace._length; + var hasTooManyPoints = len >= TOO_MANY_POINTS; + var len2 = len * 2; + var stash = {}; + var i; + var origX = xa.makeCalcdata(trace, "x"); + var origY = ya.makeCalcdata(trace, "y"); + var xObj = alignPeriod2(trace, xa, "x", origX); + var yObj = alignPeriod2(trace, ya, "y", origY); + var x = xObj.vals; + var y = yObj.vals; + trace._x = x; + trace._y = y; + if (trace.xperiodalignment) { + trace._origX = origX; + trace._xStarts = xObj.starts; + trace._xEnds = xObj.ends; + } + if (trace.yperiodalignment) { + trace._origY = origY; + trace._yStarts = yObj.starts; + trace._yEnds = yObj.ends; + } + var positions = new Array(len2); + var _ids = new Array(len); + for (i = 0; i < len; i++) { + positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; + positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; + _ids[i] = i; + } + if (xa.type === "log") { + for (i = 0; i < len2; i += 2) { + positions[i] = xa.c2l(positions[i]); + } + } + if (ya.type === "log") { + for (i = 1; i < len2; i += 2) { + positions[i] = ya.c2l(positions[i]); + } + } + if (hasTooManyPoints && (xa.type !== "log" && ya.type !== "log")) { + stash.tree = cluster$2(positions); + } else { + stash.ids = _ids; + } + calcColorscale(gd, trace); + var opts = sceneOptions(gd, subplot, trace, positions, x, y); + var scene = sceneUpdate2(gd, subplot); + setFirstScatter(fullLayout, trace); + var ppad; + if (!hasTooManyPoints) { + ppad = calcMarkerSize(trace, len); + } else if (opts.marker) { + ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3); + } + calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); + if (opts.errorX) expandForErrorBars(trace, xa, opts.errorX); + if (opts.errorY) expandForErrorBars(trace, ya, opts.errorY); + if (opts.fill && !scene.fill2d) scene.fill2d = true; + if (opts.marker && !scene.scatter2d) scene.scatter2d = true; + if (opts.line && !scene.line2d) scene.line2d = true; + if ((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true; + if (opts.text && !scene.glText) scene.glText = true; + if (opts.marker) opts.marker.snap = len; + scene.lineOptions.push(opts.line); + scene.errorXOptions.push(opts.errorX); + scene.errorYOptions.push(opts.errorY); + scene.fillOptions.push(opts.fill); + scene.markerOptions.push(opts.marker); + scene.markerSelectedOptions.push(opts.markerSel); + scene.markerUnselectedOptions.push(opts.markerUnsel); + scene.textOptions.push(opts.text); + scene.textSelectedOptions.push(opts.textSel); + scene.textUnselectedOptions.push(opts.textUnsel); + scene.selectBatch.push([]); + scene.unselectBatch.push([]); + stash._scene = scene; + stash.index = scene.count; + stash.x = x; + stash.y = y; + stash.positions = positions; + scene.count++; + return [{ x: false, y: false, t: stash, trace }]; +}; +function expandForErrorBars(trace, ax, opts) { + var extremes = trace._extremes[ax._id]; + var errExt = findExtremes(ax, opts._bnds, { padded: true }); + extremes.min = extremes.min.concat(errExt.min); + extremes.max = extremes.max.concat(errExt.max); +} +function sceneOptions(gd, subplot, trace, positions, x, y) { + var opts = convert2.style(gd, trace); + if (opts.marker) { + opts.marker.positions = positions; + } + if (opts.line && positions.length > 1) { + Lib$a.extendFlat( + opts.line, + convert2.linePositions(gd, trace, positions) + ); + } + if (opts.errorX || opts.errorY) { + var errors = convert2.errorBarPositions(gd, trace, positions, x, y); + if (opts.errorX) { + Lib$a.extendFlat(opts.errorX, errors.x); + } + if (opts.errorY) { + Lib$a.extendFlat(opts.errorY, errors.y); + } + } + if (opts.text) { + Lib$a.extendFlat( + opts.text, + { positions }, + convert2.textPosition(gd, trace, opts.text, opts.marker) + ); + Lib$a.extendFlat( + opts.textSel, + { positions }, + convert2.textPosition(gd, trace, opts.text, opts.markerSel) + ); + Lib$a.extendFlat( + opts.textUnsel, + { positions }, + convert2.textPosition(gd, trace, opts.text, opts.markerUnsel) + ); + } + return opts; +} +var Lib$9 = libExports; +var Color$6 = colorExports; +var DESELECTDIM = interactions.DESELECTDIM; +function styleTextSelection$2(cd) { + var cd0 = cd[0]; + var trace = cd0.trace; + var stash = cd0.t; + var scene = stash._scene; + var index2 = stash.index; + var els = scene.selectBatch[index2]; + var unels = scene.unselectBatch[index2]; + var baseOpts = scene.textOptions[index2]; + var selOpts = scene.textSelectedOptions[index2] || {}; + var unselOpts = scene.textUnselectedOptions[index2] || {}; + var opts = Lib$9.extendFlat({}, baseOpts); + var i, j; + if (els.length || unels.length) { + var stc = selOpts.color; + var utc = unselOpts.color; + var base = baseOpts.color; + var hasArrayBase = Lib$9.isArrayOrTypedArray(base); + opts.color = new Array(trace._length); + for (i = 0; i < els.length; i++) { + j = els[i]; + opts.color[j] = stc || (hasArrayBase ? base[j] : base); + } + for (i = 0; i < unels.length; i++) { + j = unels[i]; + var basej = hasArrayBase ? base[j] : base; + opts.color[j] = utc ? utc : stc ? basej : Color$6.addOpacity(basej, DESELECTDIM); + } + } + scene.glText[index2].update(opts); +} +var edit_style = { + styleTextSelection: styleTextSelection$2 +}; +var subTypes$1 = subtypes$3; +var styleTextSelection$1 = edit_style.styleTextSelection; +var select = function select2(searchInfo, selectionTester) { + var cd = searchInfo.cd; + var xa = searchInfo.xaxis; + var ya = searchInfo.yaxis; + var selection = []; + var trace = cd[0].trace; + var stash = cd[0].t; + var len = trace._length; + var x = stash.x; + var y = stash.y; + var scene = stash._scene; + var index2 = stash.index; + if (!scene) return selection; + var hasText = subTypes$1.hasText(trace); + var hasMarkers = subTypes$1.hasMarkers(trace); + var hasOnlyLines = !hasMarkers && !hasText; + if (trace.visible !== true || hasOnlyLines) return selection; + var els = []; + var unels = []; + if (selectionTester !== false && !selectionTester.degenerate) { + for (var i = 0; i < len; i++) { + if (selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) { + els.push(i); + selection.push({ + pointNumber: i, + x: xa.c2d(x[i]), + y: ya.c2d(y[i]) + }); + } else { + unels.push(i); + } + } + } + if (hasMarkers) { + var scatter2d = scene.scatter2d; + if (!els.length && !unels.length) { + var baseOpts = new Array(scene.count); + baseOpts[index2] = scene.markerOptions[index2]; + scatter2d.update.apply(scatter2d, baseOpts); + } else if (!scene.selectBatch[index2].length && !scene.unselectBatch[index2].length) { + var unselOpts = new Array(scene.count); + unselOpts[index2] = scene.markerUnselectedOptions[index2]; + scatter2d.update.apply(scatter2d, unselOpts); + } + } + scene.selectBatch[index2] = els; + scene.unselectBatch[index2] = unels; + if (hasText) { + styleTextSelection$1(cd); + } + return selection; +}; +var hover2 = hover$1; +var base_index = { + moduleType: "trace", + name: "scattergl", + basePlotModule: cartesian, + categories: ["gl", "regl", "cartesian", "symbols", "errorBarsOK", "showLegend", "scatter-like"], + attributes: attributesExports, + supplyDefaults: defaults$2, + crossTraceDefaults: cross_trace_defaults$1, + colorbar: marker_colorbar, + formatLabels: format_labels, + calc: calc$3, + hoverPoints: hover2.hoverPoints, + selectPoints: select, + meta: { + hrName: "scatter_gl", + description: [ + "The data visualized as scatter point or lines is set in `x` and `y`", + "using the WebGL plotting engine.", + "Bubble charts are achieved by setting `marker.size` and/or `marker.color`", + "to a numerical arrays." + ].join(" ") + } +}; +var plot$2 = { exports: {} }; +var colorId$1 = { exports: {} }; +var clamp = clamp_1; +colorId$1.exports = toNumber; +colorId$1.exports.to = toNumber; +colorId$1.exports.from = fromNumber; +function toNumber(rgba3, normalized) { + if (normalized == null) normalized = true; + var r = rgba3[0], g = rgba3[1], b = rgba3[2], a = rgba3[3]; + if (a == null) a = normalized ? 1 : 255; + if (normalized) { + r *= 255; + g *= 255; + b *= 255; + a *= 255; + } + r = clamp(r, 0, 255) & 255; + g = clamp(g, 0, 255) & 255; + b = clamp(b, 0, 255) & 255; + a = clamp(a, 0, 255) & 255; + var n = r * 16777216 + (g << 16) + (b << 8) + a; + return n; +} +function fromNumber(n, normalized) { + n = +n; + var r = n >>> 24; + var g = (n & 16711680) >>> 16; + var b = (n & 65280) >>> 8; + var a = n & 255; + if (normalized === false) return [r, g, b, a]; + return [r / 255, g / 255, b / 255, a / 255]; +} +var colorIdExports = colorId$1.exports; +var browser = function(strings) { + if (typeof strings === "string") strings = [strings]; + var exprs = [].slice.call(arguments, 1); + var parts = []; + for (var i = 0; i < strings.length - 1; i++) { + parts.push(strings[i], exprs[i] || ""); + } + parts.push(strings[i]); + return parts.join(""); +}; +var updateDiff$2 = function updateDiff(obj, diff, mappers) { + if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2); + for (var i = 0, l = mappers.length; i < l; i++) { + var dict = mappers[i]; + for (var prop in dict) { + if (diff[prop] !== void 0 && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue; + if (prop in diff) { + var result; + if (dict[prop] === true) result = diff[prop]; + else if (dict[prop] === false) continue; + else if (typeof dict[prop] === "function") { + result = dict[prop](diff[prop], obj, diff); + if (result === void 0) continue; + } + obj[prop] = result; + } + } + } + return obj; +}; +var isIexplorer = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); +var toFloat32 = { exports: {} }; +toFloat32.exports = float32$2; +toFloat32.exports.float32 = toFloat32.exports.float = float32$2; +toFloat32.exports.fract32 = toFloat32.exports.fract = fract32$2; +var narr = new Float32Array(1); +function fract32$2(arr, fract) { + if (arr.length) { + if (arr instanceof Float32Array) return new Float32Array(arr.length); + if (!(fract instanceof Float32Array)) fract = float32$2(arr); + for (var i = 0, l = fract.length; i < l; i++) { + fract[i] = arr[i] - fract[i]; + } + return fract; + } + return float32$2(arr - float32$2(arr)); +} +function float32$2(arr) { + if (arr.length) { + if (arr instanceof Float32Array) return arr; + return new Float32Array(arr); + } + narr[0] = arr; + return narr[0]; +} +var toFloat32Exports = toFloat32.exports; +function _iterableToArrayLimit(arr, i) { + var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; + if (null != _i) { + var _s, _e, _x, _r, _arr = [], _n = true, _d = false; + try { + if (_x = (_i = _i.call(arr)).next, 0 === i) ; + else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = true) ; + } catch (err) { + _d = true, _e = err; + } finally { + try { + if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; + } finally { + if (_d) throw _e; + } + } + return _arr; + } +} +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); +} +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + return arr2; +} +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} +var rgba$4 = colorNormalize; +var getBounds$3 = arrayBounds; +var colorId = colorIdExports; +var cluster$1 = pointCluster; +var extend$4 = index$3.objectAssign; +var glslify = browser; +var pick$5 = pickByAlias; +var updateDiff$1 = updateDiff$2; +var flatten$3 = flattenVertexData_1; +var ie = isIexplorer; +var f32 = toFloat32Exports; +var parseRect$2 = parseRect_1; +var scatter = Scatter; +function Scatter(regl, options) { + var _this = this; + if (!(this instanceof Scatter)) return new Scatter(regl, options); + if (typeof regl === "function") { + if (!options) options = {}; + options.regl = regl; + } else { + options = regl; + regl = null; + } + if (options && options.length) options.positions = options; + regl = options.regl; + var gl = regl._gl, paletteTexture, palette = [], paletteIds = {}, groups = [], markerTextures = [null], markerCache = [null]; + var maxColors = 255, maxSize = 100; + this.tooManyColors = ie; + paletteTexture = regl.texture({ + data: new Uint8Array(maxColors * 4), + width: maxColors, + height: 1, + type: "uint8", + format: "rgba", + wrapS: "clamp", + wrapT: "clamp", + mag: "nearest", + min: "nearest" + }); + extend$4(this, { + regl, + gl, + groups, + markerCache, + markerTextures, + palette, + paletteIds, + paletteTexture, + maxColors, + maxSize, + canvas: gl.canvas + }); + this.update(options); + var shaderOptions = { + uniforms: { + constPointSize: !!options.constPointSize, + opacity: regl.prop("opacity"), + paletteSize: function paletteSize(ctx2, prop) { + return [_this.tooManyColors ? 0 : maxColors, paletteTexture.height]; + }, + pixelRatio: regl.context("pixelRatio"), + scale: regl.prop("scale"), + scaleFract: regl.prop("scaleFract"), + translate: regl.prop("translate"), + translateFract: regl.prop("translateFract"), + markerTexture: regl.prop("markerTexture"), + paletteTexture + }, + attributes: { + // FIXME: optimize these parts + x: function x(ctx2, prop) { + return prop.xAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 0 + }; + }, + y: function y(ctx2, prop) { + return prop.yAttr || { + buffer: prop.positionBuffer, + stride: 8, + offset: 4 + }; + }, + xFract: function xFract(ctx2, prop) { + return prop.xAttr ? { + constant: [0, 0] + } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 0 + }; + }, + yFract: function yFract(ctx2, prop) { + return prop.yAttr ? { + constant: [0, 0] + } : { + buffer: prop.positionFractBuffer, + stride: 8, + offset: 4 + }; + }, + size: function size(ctx2, prop) { + return prop.size.length ? { + buffer: prop.sizeBuffer, + stride: 2, + offset: 0 + } : { + constant: [Math.round(prop.size * 255 / _this.maxSize)] + }; + }, + borderSize: function borderSize(ctx2, prop) { + return prop.borderSize.length ? { + buffer: prop.sizeBuffer, + stride: 2, + offset: 1 + } : { + constant: [Math.round(prop.borderSize * 255 / _this.maxSize)] + }; + }, + colorId: function colorId2(ctx2, prop) { + return prop.color.length ? { + buffer: prop.colorBuffer, + stride: _this.tooManyColors ? 8 : 4, + offset: 0 + } : { + constant: _this.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [prop.color] + }; + }, + borderColorId: function borderColorId(ctx2, prop) { + return prop.borderColor.length ? { + buffer: prop.colorBuffer, + stride: _this.tooManyColors ? 8 : 4, + offset: _this.tooManyColors ? 4 : 2 + } : { + constant: _this.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [prop.borderColor] + }; + }, + isActive: function isActive2(ctx2, prop) { + return prop.activation === true ? { + constant: [1] + } : prop.activation ? prop.activation : { + constant: [0] + }; + } + }, + blend: { + enable: true, + color: [0, 0, 0, 1], + // photoshop blending + func: { + srcRGB: "src alpha", + dstRGB: "one minus src alpha", + srcAlpha: "one minus dst alpha", + dstAlpha: "one" + } + }, + scissor: { + enable: true, + box: regl.prop("viewport") + }, + viewport: regl.prop("viewport"), + stencil: { + enable: false + }, + depth: { + enable: false + }, + elements: regl.prop("elements"), + count: regl.prop("count"), + offset: regl.prop("offset"), + primitive: "points" + }; + var markerOptions = extend$4({}, shaderOptions); + markerOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\nuniform sampler2D markerTexture;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(markerTexture, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n }\n else {\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n }\n\n}\n"]); + markerOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n return isDirect ? id / 255. : texture2D(paletteTexture,\n vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n )\n );\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pointSizeScale;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]); + this.drawMarker = regl(markerOptions); + var circleOptions = extend$4({}, shaderOptions); + circleOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nuniform float opacity;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n float t;\n t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n return t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n float radius, alpha = 1.0, delta = fragWidth;\n\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n if (radius > 1.0 + delta) {\n discard;\n }\n\n alpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n float borderRadius = fragBorderRadius;\n float ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n vec4 color = mix(fragColor, fragBorderColor, ratio);\n color.a *= alpha * opacity;\n gl_FragColor = color;\n}\n"]); + circleOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 paletteSize, scale, scaleFract, translate, translateFract;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n return isDirect ? id / 255. : texture2D(paletteTexture,\n vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n )\n );\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pointSizeScale;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]); + if (ie) { + circleOptions.frag = circleOptions.frag.replace("smoothstep", "smoothStep"); + markerOptions.frag = markerOptions.frag.replace("smoothstep", "smoothStep"); + } + this.drawCircle = regl(circleOptions); +} +Scatter.defaults = { + color: "black", + borderColor: "transparent", + borderSize: 0, + size: 12, + opacity: 1, + marker: void 0, + viewport: null, + range: null, + pixelSize: null, + count: 0, + offset: 0, + bounds: null, + positions: [], + snap: 1e4 +}; +Scatter.prototype.render = function() { + if (arguments.length) { + this.update.apply(this, arguments); + } + this.draw(); + return this; +}; +Scatter.prototype.draw = function() { + var _this2 = this; + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + var groups = this.groups; + if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) { + args = args[0]; + } + this.regl._refresh(); + if (args.length) { + for (var i = 0; i < args.length; i++) { + this.drawItem(i, args[i]); + } + } else { + groups.forEach(function(group, i2) { + _this2.drawItem(i2); + }); + } + return this; +}; +Scatter.prototype.drawItem = function(id, els) { + var groups = this.groups; + var group = groups[id]; + if (typeof els === "number") { + id = els; + group = groups[els]; + els = null; + } + if (!(group && group.count && group.opacity)) return; + if (group.activation[0]) { + this.drawCircle(this.getMarkerDrawOptions(0, group, els)); + } + var batch = []; + for (var i = 1; i < group.activation.length; i++) { + if (!group.activation[i] || group.activation[i] !== true && !group.activation[i].data.length) continue; + batch.push.apply(batch, _toConsumableArray(this.getMarkerDrawOptions(i, group, els))); + } + if (batch.length) { + this.drawMarker(batch); + } +}; +Scatter.prototype.getMarkerDrawOptions = function(markerId, group, elements) { + var range = group.range, tree2 = group.tree, viewport = group.viewport, activation = group.activation, selectionBuffer = group.selectionBuffer, count2 = group.count; + this.regl; + if (!tree2) { + if (elements) { + return [extend$4({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + count: elements.length, + elements, + offset: 0 + })]; + } + return [extend$4({}, group, { + markerTexture: this.markerTextures[markerId], + activation: activation[markerId], + offset: 0 + })]; + } + var batch = []; + var lod = tree2.range(range, { + lod: true, + px: [(range[2] - range[0]) / viewport.width, (range[3] - range[1]) / viewport.height] + }); + if (elements) { + var markerActivation = activation[markerId]; + var mask = markerActivation.data; + var data = new Uint8Array(count2); + for (var i = 0; i < elements.length; i++) { + var id = elements[i]; + data[id] = mask ? mask[id] : 1; + } + selectionBuffer.subdata(data); + } + for (var l = lod.length; l--; ) { + var _lod$l = _slicedToArray(lod[l], 2), from = _lod$l[0], to = _lod$l[1]; + batch.push(extend$4({}, group, { + markerTexture: this.markerTextures[markerId], + activation: elements ? selectionBuffer : activation[markerId], + offset: from, + count: to - from + })); + } + return batch; +}; +Scatter.prototype.update = function() { + var _this3 = this; + for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + args[_key2] = arguments[_key2]; + } + if (!args.length) return; + if (args.length === 1 && Array.isArray(args[0])) args = args[0]; + var groups = this.groups, gl = this.gl, regl = this.regl, maxSize = this.maxSize, maxColors = this.maxColors, palette = this.palette; + this.groups = groups = args.map(function(options, i) { + var group = groups[i]; + if (options === void 0) return group; + if (options === null) options = { + positions: null + }; + else if (typeof options === "function") options = { + ondraw: options + }; + else if (typeof options[0] === "number") options = { + positions: options + }; + options = pick$5(options, { + positions: "positions data points", + snap: "snap cluster lod tree", + size: "sizes size radius", + borderSize: "borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline", + color: "colors color fill fill-color fillColor", + borderColor: "borderColors borderColor stroke stroke-color strokeColor", + marker: "markers marker shape", + range: "range dataBox databox", + viewport: "viewport viewPort viewBox viewbox", + opacity: "opacity alpha transparency", + bounds: "bound bounds boundaries limits", + tooManyColors: "tooManyColors palette paletteMode optimizePalette enablePalette" + }); + if (options.positions === null) options.positions = []; + if (options.tooManyColors != null) _this3.tooManyColors = options.tooManyColors; + if (!group) { + groups[i] = group = { + id: i, + scale: null, + translate: null, + scaleFract: null, + translateFract: null, + // buffers for active markers + activation: [], + // buffer for filtered markers + selectionBuffer: regl.buffer({ + data: new Uint8Array(0), + usage: "stream", + type: "uint8" + }), + // buffers with data: it is faster to switch them per-pass + // than provide one congregate buffer + sizeBuffer: regl.buffer({ + data: new Uint8Array(0), + usage: "dynamic", + type: "uint8" + }), + colorBuffer: regl.buffer({ + data: new Uint8Array(0), + usage: "dynamic", + type: "uint8" + }), + positionBuffer: regl.buffer({ + data: new Uint8Array(0), + usage: "dynamic", + type: "float" + }), + positionFractBuffer: regl.buffer({ + data: new Uint8Array(0), + usage: "dynamic", + type: "float" + }) + }; + options = extend$4({}, Scatter.defaults, options); + } + if (options.positions && !("marker" in options)) { + options.marker = group.marker; + delete group.marker; + } + if (options.marker && !("positions" in options)) { + options.positions = group.positions; + delete group.positions; + } + var hasSize = 0, hasColor = 0; + updateDiff$1(group, options, [{ + snap: true, + size: function size2(s, group2) { + if (s == null) s = Scatter.defaults.size; + hasSize += s && s.length ? 1 : 0; + return s; + }, + borderSize: function borderSize2(s, group2) { + if (s == null) s = Scatter.defaults.borderSize; + hasSize += s && s.length ? 1 : 0; + return s; + }, + opacity: parseFloat, + // add colors to palette, save references + color: function color3(c, group2) { + if (c == null) c = Scatter.defaults.color; + c = _this3.updateColor(c); + hasColor++; + return c; + }, + borderColor: function borderColor2(c, group2) { + if (c == null) c = Scatter.defaults.borderColor; + c = _this3.updateColor(c); + hasColor++; + return c; + }, + bounds: function bounds(_bounds, group2, options2) { + if (!("range" in options2)) options2.range = null; + return _bounds; + }, + positions: function positions(_positions, group2, options2) { + var snap = group2.snap; + var positionBuffer = group2.positionBuffer, positionFractBuffer = group2.positionFractBuffer, selectionBuffer = group2.selectionBuffer; + if (_positions.x || _positions.y) { + if (_positions.x.length) { + group2.xAttr = { + buffer: regl.buffer(_positions.x), + offset: 0, + stride: 4, + count: _positions.x.length + }; + } else { + group2.xAttr = { + buffer: _positions.x.buffer, + offset: _positions.x.offset * 4 || 0, + stride: (_positions.x.stride || 1) * 4, + count: _positions.x.count + }; + } + if (_positions.y.length) { + group2.yAttr = { + buffer: regl.buffer(_positions.y), + offset: 0, + stride: 4, + count: _positions.y.length + }; + } else { + group2.yAttr = { + buffer: _positions.y.buffer, + offset: _positions.y.offset * 4 || 0, + stride: (_positions.y.stride || 1) * 4, + count: _positions.y.count + }; + } + group2.count = Math.max(group2.xAttr.count, group2.yAttr.count); + return _positions; + } + _positions = flatten$3(_positions, "float64"); + var count3 = group2.count = Math.floor(_positions.length / 2); + var bounds = group2.bounds = count3 ? getBounds$3(_positions, 2) : null; + if (!options2.range && !group2.range) { + delete group2.range; + options2.range = bounds; + } + if (!options2.marker && !group2.marker) { + delete group2.marker; + options2.marker = null; + } + if (snap && (snap === true || count3 > snap)) { + group2.tree = cluster$1(_positions, { + bounds + }); + } else if (snap && snap.length) { + group2.tree = snap; + } + if (group2.tree) { + var opts = { + primitive: "points", + usage: "static", + data: group2.tree, + type: "uint32" + }; + if (group2.elements) group2.elements(opts); + else group2.elements = regl.elements(opts); + } + var float_data = f32.float32(_positions); + positionBuffer({ + data: float_data, + usage: "dynamic" + }); + var frac_data = f32.fract32(_positions, float_data); + positionFractBuffer({ + data: frac_data, + usage: "dynamic" + }); + selectionBuffer({ + data: new Uint8Array(count3), + type: "uint8", + usage: "stream" + }); + return _positions; + } + }, { + // create marker ids corresponding to known marker textures + marker: function marker2(markers, group2, options2) { + var activation = group2.activation; + activation.forEach(function(buffer2) { + return buffer2 && buffer2.destroy && buffer2.destroy(); + }); + activation.length = 0; + if (!markers || typeof markers[0] === "number") { + var id = _this3.addMarker(markers); + activation[id] = true; + } else { + var markerMasks = []; + for (var _i = 0, l = Math.min(markers.length, group2.count); _i < l; _i++) { + var _id = _this3.addMarker(markers[_i]); + if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group2.count); + markerMasks[_id][_i] = 1; + } + for (var _id2 = 0; _id2 < markerMasks.length; _id2++) { + if (!markerMasks[_id2]) continue; + var opts = { + data: markerMasks[_id2], + type: "uint8", + usage: "static" + }; + if (!activation[_id2]) { + activation[_id2] = regl.buffer(opts); + } else { + activation[_id2](opts); + } + activation[_id2].data = markerMasks[_id2]; + } + } + return markers; + }, + range: function range(_range, group2, options2) { + var bounds = group2.bounds; + if (!bounds) return; + if (!_range) _range = bounds; + group2.scale = [1 / (_range[2] - _range[0]), 1 / (_range[3] - _range[1])]; + group2.translate = [-_range[0], -_range[1]]; + group2.scaleFract = f32.fract(group2.scale); + group2.translateFract = f32.fract(group2.translate); + return _range; + }, + viewport: function viewport(vp) { + var rect2 = parseRect$2(vp || [gl.drawingBufferWidth, gl.drawingBufferHeight]); + return rect2; + } + }]); + if (hasSize) { + var _group = group, count2 = _group.count, size = _group.size, borderSize = _group.borderSize, sizeBuffer = _group.sizeBuffer; + var sizes2 = new Uint8Array(count2 * 2); + if (size.length || borderSize.length) { + for (var _i2 = 0; _i2 < count2; _i2++) { + sizes2[_i2 * 2] = Math.round((size[_i2] == null ? size : size[_i2]) * 255 / maxSize); + sizes2[_i2 * 2 + 1] = Math.round((borderSize[_i2] == null ? borderSize : borderSize[_i2]) * 255 / maxSize); + } + } + sizeBuffer({ + data: sizes2, + usage: "dynamic" + }); + } + if (hasColor) { + var _group2 = group, _count = _group2.count, color2 = _group2.color, borderColor = _group2.borderColor, colorBuffer = _group2.colorBuffer; + var colors; + if (_this3.tooManyColors) { + if (color2.length || borderColor.length) { + colors = new Uint8Array(_count * 8); + for (var _i3 = 0; _i3 < _count; _i3++) { + var _colorId = color2[_i3]; + colors[_i3 * 8] = palette[_colorId * 4]; + colors[_i3 * 8 + 1] = palette[_colorId * 4 + 1]; + colors[_i3 * 8 + 2] = palette[_colorId * 4 + 2]; + colors[_i3 * 8 + 3] = palette[_colorId * 4 + 3]; + var borderColorId = borderColor[_i3]; + colors[_i3 * 8 + 4] = palette[borderColorId * 4]; + colors[_i3 * 8 + 5] = palette[borderColorId * 4 + 1]; + colors[_i3 * 8 + 6] = palette[borderColorId * 4 + 2]; + colors[_i3 * 8 + 7] = palette[borderColorId * 4 + 3]; + } + } + } else { + if (color2.length || borderColor.length) { + colors = new Uint8Array(_count * 4 + 2); + for (var _i4 = 0; _i4 < _count; _i4++) { + if (color2[_i4] != null) { + colors[_i4 * 4] = color2[_i4] % maxColors; + colors[_i4 * 4 + 1] = Math.floor(color2[_i4] / maxColors); + } + if (borderColor[_i4] != null) { + colors[_i4 * 4 + 2] = borderColor[_i4] % maxColors; + colors[_i4 * 4 + 3] = Math.floor(borderColor[_i4] / maxColors); + } + } + } + } + colorBuffer({ + data: colors || new Uint8Array(0), + type: "uint8", + usage: "dynamic" + }); + } + return group; + }); +}; +Scatter.prototype.addMarker = function(sdf) { + var markerTextures = this.markerTextures, regl = this.regl, markerCache = this.markerCache; + var pos = sdf == null ? 0 : markerCache.indexOf(sdf); + if (pos >= 0) return pos; + var distArr; + if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { + distArr = sdf; + } else { + distArr = new Uint8Array(sdf.length); + for (var i = 0, l = sdf.length; i < l; i++) { + distArr[i] = sdf[i] * 255; + } + } + var radius = Math.floor(Math.sqrt(distArr.length)); + pos = markerTextures.length; + markerCache.push(sdf); + markerTextures.push(regl.texture({ + channels: 1, + data: distArr, + radius, + mag: "linear", + min: "linear" + })); + return pos; +}; +Scatter.prototype.updateColor = function(colors) { + var paletteIds = this.paletteIds, palette = this.palette, maxColors = this.maxColors; + if (!Array.isArray(colors)) { + colors = [colors]; + } + var idx = []; + if (typeof colors[0] === "number") { + var grouped = []; + if (Array.isArray(colors)) { + for (var i = 0; i < colors.length; i += 4) { + grouped.push(colors.slice(i, i + 4)); + } + } else { + for (var _i5 = 0; _i5 < colors.length; _i5 += 4) { + grouped.push(colors.subarray(_i5, _i5 + 4)); + } + } + colors = grouped; + } + for (var _i6 = 0; _i6 < colors.length; _i6++) { + var color2 = colors[_i6]; + color2 = rgba$4(color2, "uint8"); + var id = colorId(color2, false); + if (paletteIds[id] == null) { + var pos = palette.length; + paletteIds[id] = Math.floor(pos / 4); + palette[pos] = color2[0]; + palette[pos + 1] = color2[1]; + palette[pos + 2] = color2[2]; + palette[pos + 3] = color2[3]; + } + idx[_i6] = paletteIds[id]; + } + if (!this.tooManyColors && palette.length > maxColors * 4) this.tooManyColors = true; + this.updatePalette(palette); + return idx.length === 1 ? idx[0] : idx; +}; +Scatter.prototype.updatePalette = function(palette) { + if (this.tooManyColors) return; + var maxColors = this.maxColors, paletteTexture = this.paletteTexture; + var requiredHeight = Math.ceil(palette.length * 0.25 / maxColors); + if (requiredHeight > 1) { + palette = palette.slice(); + for (var i = palette.length * 0.25 % maxColors; i < requiredHeight * maxColors; i++) { + palette.push(0, 0, 0, 0); + } + } + if (paletteTexture.height < requiredHeight) { + paletteTexture.resize(maxColors, requiredHeight); + } + paletteTexture.subimage({ + width: Math.min(palette.length * 0.25, maxColors), + height: requiredHeight, + data: palette + }, 0, 0); +}; +Scatter.prototype.destroy = function() { + this.groups.forEach(function(group) { + group.sizeBuffer.destroy(); + group.positionBuffer.destroy(); + group.positionFractBuffer.destroy(); + group.colorBuffer.destroy(); + group.activation.forEach(function(b) { + return b && b.destroy && b.destroy(); + }); + group.selectionBuffer.destroy(); + if (group.elements) group.elements.destroy(); + }); + this.groups.length = 0; + this.paletteTexture.destroy(); + this.markerTextures.forEach(function(txt) { + return txt && txt.destroy && txt.destroy(); + }); + return this; +}; +var extend$1$1 = index$3.objectAssign; +var reglScatter2d = function reglScatter2d2(regl, options) { + var scatter$12 = new scatter(regl, options); + var render = scatter$12.render.bind(scatter$12); + extend$1$1(render, { + render, + update: scatter$12.update.bind(scatter$12), + draw: scatter$12.draw.bind(scatter$12), + destroy: scatter$12.destroy.bind(scatter$12), + regl: scatter$12.regl, + gl: scatter$12.gl, + canvas: scatter$12.gl.canvas, + groups: scatter$12.groups, + markers: scatter$12.markerCache, + palette: scatter$12.palette + }); + return render; +}; +var bundle = reglScatter2d; +var earcut$1 = { exports: {} }; +earcut$1.exports = earcut; +earcut$1.exports.default = earcut; +function earcut(data, holeIndices, dim) { + dim = dim || 2; + var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; + if (!outerNode || outerNode.next === outerNode.prev) return triangles; + var minX, minY, maxX, maxY2, x, y, invSize; + if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); + if (data.length > 80 * dim) { + minX = maxX = data[0]; + minY = maxY2 = data[1]; + for (var i = dim; i < outerLen; i += dim) { + x = data[i]; + y = data[i + 1]; + if (x < minX) minX = x; + if (y < minY) minY = y; + if (x > maxX) maxX = x; + if (y > maxY2) maxY2 = y; + } + invSize = Math.max(maxX - minX, maxY2 - minY); + invSize = invSize !== 0 ? 32767 / invSize : 0; + } + earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); + return triangles; +} +function linkedList(data, start, end, dim, clockwise) { + var i, last; + if (clockwise === signedArea(data, start, end, dim) > 0) { + for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); + } else { + for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); + } + if (last && equals(last, last.next)) { + removeNode(last); + last = last.next; + } + return last; +} +function filterPoints(start, end) { + if (!start) return start; + if (!end) end = start; + var p = start, again; + do { + again = false; + if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { + removeNode(p); + p = end = p.prev; + if (p === p.next) break; + again = true; + } else { + p = p.next; + } + } while (again || p !== end); + return end; +} +function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { + if (!ear) return; + if (!pass && invSize) indexCurve(ear, minX, minY, invSize); + var stop = ear, prev, next; + while (ear.prev !== ear.next) { + prev = ear.prev; + next = ear.next; + if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { + triangles.push(prev.i / dim | 0); + triangles.push(ear.i / dim | 0); + triangles.push(next.i / dim | 0); + removeNode(ear); + ear = next.next; + stop = next.next; + continue; + } + ear = next; + if (ear === stop) { + if (!pass) { + earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); + } else if (pass === 1) { + ear = cureLocalIntersections(filterPoints(ear), triangles, dim); + earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); + } else if (pass === 2) { + splitEarcut(ear, triangles, dim, minX, minY, invSize); + } + break; + } + } +} +function isEar(ear) { + var a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + var p = c.next; + while (p !== a) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.next; + } + return true; +} +function isEarHashed(ear, minX, minY, invSize) { + var a = ear.prev, b = ear, c = ear.next; + if (area(a, b, c) >= 0) return false; + var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; + var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; + var minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); + var p = ear.prevZ, n = ear.nextZ; + while (p && p.z >= minZ && n && n.z <= maxZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + while (p && p.z >= minZ) { + if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; + p = p.prevZ; + } + while (n && n.z <= maxZ) { + if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; + n = n.nextZ; + } + return true; +} +function cureLocalIntersections(start, triangles, dim) { + var p = start; + do { + var a = p.prev, b = p.next.next; + if (!equals(a, b) && intersects$1(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { + triangles.push(a.i / dim | 0); + triangles.push(p.i / dim | 0); + triangles.push(b.i / dim | 0); + removeNode(p); + removeNode(p.next); + p = start = b; + } + p = p.next; + } while (p !== start); + return filterPoints(p); +} +function splitEarcut(start, triangles, dim, minX, minY, invSize) { + var a = start; + do { + var b = a.next.next; + while (b !== a.prev) { + if (a.i !== b.i && isValidDiagonal(a, b)) { + var c = splitPolygon(a, b); + a = filterPoints(a, a.next); + c = filterPoints(c, c.next); + earcutLinked(a, triangles, dim, minX, minY, invSize, 0); + earcutLinked(c, triangles, dim, minX, minY, invSize, 0); + return; + } + b = b.next; + } + a = a.next; + } while (a !== start); +} +function eliminateHoles(data, holeIndices, outerNode, dim) { + var queue2 = [], i, len, start, end, list; + for (i = 0, len = holeIndices.length; i < len; i++) { + start = holeIndices[i] * dim; + end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + list = linkedList(data, start, end, dim, false); + if (list === list.next) list.steiner = true; + queue2.push(getLeftmost(list)); + } + queue2.sort(compareX); + for (i = 0; i < queue2.length; i++) { + outerNode = eliminateHole(queue2[i], outerNode); + } + return outerNode; +} +function compareX(a, b) { + return a.x - b.x; +} +function eliminateHole(hole, outerNode) { + var bridge = findHoleBridge(hole, outerNode); + if (!bridge) { + return outerNode; + } + var bridgeReverse = splitPolygon(bridge, hole); + filterPoints(bridgeReverse, bridgeReverse.next); + return filterPoints(bridge, bridge.next); +} +function findHoleBridge(hole, outerNode) { + var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; + do { + if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { + var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); + if (x <= hx && x > qx) { + qx = x; + m = p.x < p.next.x ? p : p.next; + if (x === hx) return m; + } + } + p = p.next; + } while (p !== outerNode); + if (!m) return null; + var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; + p = m; + do { + if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { + tan = Math.abs(hy - p.y) / (hx - p.x); + if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { + m = p; + tanMin = tan; + } + } + p = p.next; + } while (p !== stop); + return m; +} +function sectorContainsSector(m, p) { + return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; +} +function indexCurve(start, minX, minY, invSize) { + var p = start; + do { + if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); + p.prevZ = p.prev; + p.nextZ = p.next; + p = p.next; + } while (p !== start); + p.prevZ.nextZ = null; + p.prevZ = null; + sortLinked(p); +} +function sortLinked(list) { + var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; + do { + p = list; + list = null; + tail = null; + numMerges = 0; + while (p) { + numMerges++; + q = p; + pSize = 0; + for (i = 0; i < inSize; i++) { + pSize++; + q = q.nextZ; + if (!q) break; + } + qSize = inSize; + while (pSize > 0 || qSize > 0 && q) { + if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { + e = p; + p = p.nextZ; + pSize--; + } else { + e = q; + q = q.nextZ; + qSize--; + } + if (tail) tail.nextZ = e; + else list = e; + e.prevZ = tail; + tail = e; + } + p = q; + } + tail.nextZ = null; + inSize *= 2; + } while (numMerges > 1); + return list; +} +function zOrder(x, y, minX, minY, invSize) { + x = (x - minX) * invSize | 0; + y = (y - minY) * invSize | 0; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; +} +function getLeftmost(start) { + var p = start, leftmost = start; + do { + if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; + p = p.next; + } while (p !== start); + return leftmost; +} +function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py) { + return (cx - px2) * (ay - py) >= (ax - px2) * (cy - py) && (ax - px2) * (by - py) >= (bx - px2) * (ay - py) && (bx - px2) * (cy - py) >= (cx - px2) * (by - py); +} +function isValidDiagonal(a, b) { + return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges + (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible + (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors + equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); +} +function area(p, q, r) { + return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); +} +function equals(p1, p2) { + return p1.x === p2.x && p1.y === p2.y; +} +function intersects$1(p1, q1, p2, q2) { + var o1 = sign(area(p1, q1, p2)); + var o2 = sign(area(p1, q1, q2)); + var o3 = sign(area(p2, q2, p1)); + var o4 = sign(area(p2, q2, q1)); + if (o1 !== o2 && o3 !== o4) return true; + if (o1 === 0 && onSegment(p1, p2, q1)) return true; + if (o2 === 0 && onSegment(p1, q2, q1)) return true; + if (o3 === 0 && onSegment(p2, p1, q2)) return true; + if (o4 === 0 && onSegment(p2, q1, q2)) return true; + return false; +} +function onSegment(p, q, r) { + return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); +} +function sign(num) { + return num > 0 ? 1 : num < 0 ? -1 : 0; +} +function intersectsPolygon(a, b) { + var p = a; + do { + if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects$1(p, p.next, a, b)) return true; + p = p.next; + } while (p !== a); + return false; +} +function locallyInside(a, b) { + return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; +} +function middleInside(a, b) { + var p = a, inside = false, px2 = (a.x + b.x) / 2, py = (a.y + b.y) / 2; + do { + if (p.y > py !== p.next.y > py && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) + inside = !inside; + p = p.next; + } while (p !== a); + return inside; +} +function splitPolygon(a, b) { + var a2 = new Node$2(a.i, a.x, a.y), b2 = new Node$2(b.i, b.x, b.y), an = a.next, bp = b.prev; + a.next = b; + b.prev = a; + a2.next = an; + an.prev = a2; + b2.next = a2; + a2.prev = b2; + bp.next = b2; + b2.prev = bp; + return b2; +} +function insertNode(i, x, y, last) { + var p = new Node$2(i, x, y); + if (!last) { + p.prev = p; + p.next = p; + } else { + p.next = last.next; + p.prev = last; + last.next.prev = p; + last.next = p; + } + return p; +} +function removeNode(p) { + p.next.prev = p.prev; + p.prev.next = p.next; + if (p.prevZ) p.prevZ.nextZ = p.nextZ; + if (p.nextZ) p.nextZ.prevZ = p.prevZ; +} +function Node$2(i, x, y) { + this.i = i; + this.x = x; + this.y = y; + this.prev = null; + this.next = null; + this.z = 0; + this.prevZ = null; + this.nextZ = null; + this.steiner = false; +} +earcut.deviation = function(data, holeIndices, dim, triangles) { + var hasHoles = holeIndices && holeIndices.length; + var outerLen = hasHoles ? holeIndices[0] * dim : data.length; + var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); + if (hasHoles) { + for (var i = 0, len = holeIndices.length; i < len; i++) { + var start = holeIndices[i] * dim; + var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; + polygonArea -= Math.abs(signedArea(data, start, end, dim)); + } + } + var trianglesArea = 0; + for (i = 0; i < triangles.length; i += 3) { + var a = triangles[i] * dim; + var b = triangles[i + 1] * dim; + var c = triangles[i + 2] * dim; + trianglesArea += Math.abs( + (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1]) + ); + } + return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); +}; +function signedArea(data, start, end, dim) { + var sum = 0; + for (var i = start, j = end - dim; i < end; i += dim) { + sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); + j = i; + } + return sum; +} +earcut.flatten = function(data) { + var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0; + for (var i = 0; i < data.length; i++) { + for (var j = 0; j < data[i].length; j++) { + for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); + } + if (i > 0) { + holeIndex += data[i - 1].length; + result.holes.push(holeIndex); + } + } + return result; +}; +var earcutExports = earcut$1.exports; +var getBounds$2 = arrayBounds; +var arrayNormalize = normalize$1; +function normalize$1(arr, dim, bounds) { + if (!arr || arr.length == null) throw Error("Argument should be an array"); + if (dim == null) dim = 1; + if (bounds == null) bounds = getBounds$2(arr, dim); + for (var offset = 0; offset < dim; offset++) { + var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length; + if (max === Infinity && min === -Infinity) { + for (i = offset; i < l; i += dim) { + arr[i] = arr[i] === max ? 1 : arr[i] === min ? 0 : 0.5; + } + } else if (max === Infinity) { + for (i = offset; i < l; i += dim) { + arr[i] = arr[i] === max ? 1 : 0; + } + } else if (min === -Infinity) { + for (i = offset; i < l; i += dim) { + arr[i] = arr[i] === min ? 0 : 1; + } + } else { + var range = max - min; + for (i = offset; i < l; i += dim) { + if (!isNaN(arr[i])) { + arr[i] = range === 0 ? 0.5 : (arr[i] - min) / range; + } + } + } + } + return arr; +} +var isImplemented$1 = function() { + var weakMap, obj; + if (typeof WeakMap !== "function") return false; + try { + weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]); + } catch (e) { + return false; + } + if (String(weakMap) !== "[object WeakMap]") return false; + if (typeof weakMap.set !== "function") return false; + if (weakMap.set({}, 1) !== weakMap) return false; + if (typeof weakMap.delete !== "function") return false; + if (typeof weakMap.has !== "function") return false; + if (weakMap.get(obj) !== "one") return false; + return true; +}; +var isImplemented; +var hasRequiredIsImplemented; +function requireIsImplemented() { + if (hasRequiredIsImplemented) return isImplemented; + hasRequiredIsImplemented = 1; + var create2 = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; + isImplemented = function() { + var setPrototypeOf2 = Object.setPrototypeOf, customCreate = arguments[0] || create2; + if (typeof setPrototypeOf2 !== "function") return false; + return getPrototypeOf(setPrototypeOf2(customCreate(null), plainObject)) === plainObject; + }; + return isImplemented; +} +var create_1; +var hasRequiredCreate; +function requireCreate() { + if (hasRequiredCreate) return create_1; + hasRequiredCreate = 1; + var create2 = Object.create, shim2; + if (!requireIsImplemented()()) { + shim2 = requireShim(); + } + create_1 = function() { + var nullObject, polyProps, desc; + if (!shim2) return create2; + if (shim2.level !== 1) return create2; + nullObject = {}; + polyProps = {}; + desc = { configurable: false, enumerable: false, writable: true, value: void 0 }; + Object.getOwnPropertyNames(Object.prototype).forEach(function(name2) { + if (name2 === "__proto__") { + polyProps[name2] = { + configurable: true, + enumerable: false, + writable: true, + value: void 0 + }; + return; + } + polyProps[name2] = desc; + }); + Object.defineProperties(nullObject, polyProps); + Object.defineProperty(shim2, "nullPolyfill", { + configurable: false, + enumerable: false, + writable: false, + value: nullObject + }); + return function(prototype, props) { + return create2(prototype === null ? nullObject : prototype, props); + }; + }(); + return create_1; +} +var shim; +var hasRequiredShim; +function requireShim() { + if (hasRequiredShim) return shim; + hasRequiredShim = 1; + var isObject = index$3.isObject, value2 = index$3.validValue, objIsPrototypeOf = Object.prototype.isPrototypeOf, defineProperty = Object.defineProperty, nullDesc = { configurable: true, enumerable: false, writable: true, value: void 0 }, validate3; + validate3 = function(obj, prototype) { + value2(obj); + if (prototype === null || isObject(prototype)) return obj; + throw new TypeError("Prototype must be null or an object"); + }; + shim = function(status) { + var fn, set; + if (!status) return null; + if (status.level === 2) { + if (status.set) { + set = status.set; + fn = function(obj, prototype) { + set.call(validate3(obj, prototype), prototype); + return obj; + }; + } else { + fn = function(obj, prototype) { + validate3(obj, prototype).__proto__ = prototype; + return obj; + }; + } + } else { + fn = function self2(obj, prototype) { + var isNullBase; + validate3(obj, prototype); + isNullBase = objIsPrototypeOf.call(self2.nullPolyfill, obj); + if (isNullBase) delete self2.nullPolyfill.__proto__; + if (prototype === null) prototype = self2.nullPolyfill; + obj.__proto__ = prototype; + if (isNullBase) defineProperty(self2.nullPolyfill, "__proto__", nullDesc); + return obj; + }; + } + return Object.defineProperty(fn, "level", { + configurable: false, + enumerable: false, + writable: false, + value: status.level + }); + }( + function() { + var tmpObj1 = /* @__PURE__ */ Object.create(null), tmpObj2 = {}, set, desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); + if (desc) { + try { + set = desc.set; + set.call(tmpObj1, tmpObj2); + } catch (ignore) { + } + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set, level: 2 }; + } + tmpObj1.__proto__ = tmpObj2; + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; + tmpObj1 = {}; + tmpObj1.__proto__ = tmpObj2; + if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; + return false; + }() + ); + requireCreate(); + return shim; +} +var setPrototypeOf; +var hasRequiredSetPrototypeOf; +function requireSetPrototypeOf() { + if (hasRequiredSetPrototypeOf) return setPrototypeOf; + hasRequiredSetPrototypeOf = 1; + setPrototypeOf = requireIsImplemented()() ? Object.setPrototypeOf : requireShim(); + return setPrototypeOf; +} +var validObject; +var hasRequiredValidObject; +function requireValidObject() { + if (hasRequiredValidObject) return validObject; + hasRequiredValidObject = 1; + var isObject = index$3.isObject; + validObject = function(value2) { + if (!isObject(value2)) throw new TypeError(value2 + " is not an Object"); + return value2; + }; + return validObject; +} +var randomUniq; +var hasRequiredRandomUniq; +function requireRandomUniq() { + if (hasRequiredRandomUniq) return randomUniq; + hasRequiredRandomUniq = 1; + var generated = /* @__PURE__ */ Object.create(null), random = Math.random; + randomUniq = function() { + var str2; + do { + str2 = random().toString(36).slice(2); + } while (generated[str2]); + return str2; + }; + return randomUniq; +} +var array$1 = { exports: {} }; +var clear; +var hasRequiredClear; +function requireClear() { + if (hasRequiredClear) return clear; + hasRequiredClear = 1; + var value2 = index$3.validValue; + clear = function() { + value2(this).length = 0; + return this; + }; + return clear; +} +var coerce; +var hasRequiredCoerce; +function requireCoerce() { + if (hasRequiredCoerce) return coerce; + hasRequiredCoerce = 1; + var isValue = index$3.is, isObject = index$3.is$1; + var objectToString = Object.prototype.toString; + coerce = function(value2) { + if (!isValue(value2)) return null; + if (isObject(value2)) { + var valueToString = value2.toString; + if (typeof valueToString !== "function") return null; + if (valueToString === objectToString) return null; + } + try { + return "" + value2; + } catch (error) { + return null; + } + }; + return coerce; +} +var safeToString; +var hasRequiredSafeToString; +function requireSafeToString() { + if (hasRequiredSafeToString) return safeToString; + hasRequiredSafeToString = 1; + safeToString = function(value2) { + try { + return value2.toString(); + } catch (error) { + try { + return String(value2); + } catch (error2) { + return null; + } + } + }; + return safeToString; +} +var toShortString; +var hasRequiredToShortString; +function requireToShortString() { + if (hasRequiredToShortString) return toShortString; + hasRequiredToShortString = 1; + var safeToString2 = requireSafeToString(); + var reNewLine = /[\n\r\u2028\u2029]/g; + toShortString = function(value2) { + var string2 = safeToString2(value2); + if (string2 === null) return ""; + if (string2.length > 100) string2 = string2.slice(0, 99) + "…"; + string2 = string2.replace(reNewLine, function(char) { + switch (char) { + case "\n": + return "\\n"; + case "\r": + return "\\r"; + case "\u2028": + return "\\u2028"; + case "\u2029": + return "\\u2029"; + default: + throw new Error("Unexpected character"); + } + }); + return string2; + }; + return toShortString; +} +var resolveErrorMessage; +var hasRequiredResolveErrorMessage; +function requireResolveErrorMessage() { + if (hasRequiredResolveErrorMessage) return resolveErrorMessage; + hasRequiredResolveErrorMessage = 1; + var stringCoerce = requireCoerce(), toShortString2 = requireToShortString(); + resolveErrorMessage = function(errorMessage, value2, inputOptions) { + if (inputOptions && inputOptions.errorMessage) { + errorMessage = stringCoerce(inputOptions.errorMessage); + } + var valueInsertIndex = errorMessage.indexOf("%v"); + var valueToken = valueInsertIndex > -1 ? toShortString2(value2) : null; + if (inputOptions && inputOptions.name) { + var nameInsertIndex = errorMessage.indexOf("%n"); + if (nameInsertIndex > -1) { + if (valueInsertIndex > -1) { + var firstToken, secondToken, firstInsertIndex, secondInsertIndex; + if (nameInsertIndex > valueInsertIndex) { + firstToken = valueToken; + firstInsertIndex = valueInsertIndex; + secondToken = inputOptions.name; + secondInsertIndex = nameInsertIndex; + } else { + firstToken = inputOptions.name; + firstInsertIndex = nameInsertIndex; + secondToken = valueToken; + secondInsertIndex = valueInsertIndex; + } + return errorMessage.slice(0, firstInsertIndex) + firstToken + errorMessage.slice(firstInsertIndex + 2, secondInsertIndex) + secondToken + errorMessage.slice(secondInsertIndex + 2); + } + return errorMessage.slice(0, nameInsertIndex) + inputOptions.name + errorMessage.slice(nameInsertIndex + 2); + } + } + if (valueInsertIndex > -1) { + return errorMessage.slice(0, valueInsertIndex) + valueToken + errorMessage.slice(valueInsertIndex + 2); + } + return errorMessage; + }; + return resolveErrorMessage; +} +var resolveException; +var hasRequiredResolveException; +function requireResolveException() { + if (hasRequiredResolveException) return resolveException; + hasRequiredResolveException = 1; + var isValue = index$3.is, resolveErrorMessage2 = requireResolveErrorMessage(); + resolveException = function(value2, defaultMessage, inputOptions) { + if (inputOptions && !isValue(value2)) { + if ("default" in inputOptions) return inputOptions["default"]; + if (inputOptions.isOptional) return null; + } + var ErrorConstructor = inputOptions && inputOptions.Error || TypeError; + var error = new ErrorConstructor(resolveErrorMessage2(defaultMessage, value2, inputOptions)); + if (inputOptions && inputOptions.errorCode) error.code = inputOptions.errorCode; + throw error; + }; + return resolveException; +} +var ensure$1; +var hasRequiredEnsure$1; +function requireEnsure$1() { + if (hasRequiredEnsure$1) return ensure$1; + hasRequiredEnsure$1 = 1; + var resolveException2 = requireResolveException(), is = index$3.is; + ensure$1 = function(value2) { + if (is(value2)) return value2; + var options = arguments[1]; + var errorMessage = options && options.name ? "Expected a value for %n, received %v" : "Cannot use %v"; + return resolveException2(value2, errorMessage, options); + }; + return ensure$1; +} +var ensure; +var hasRequiredEnsure; +function requireEnsure() { + if (hasRequiredEnsure) return ensure; + hasRequiredEnsure = 1; + var resolveException2 = requireResolveException(), is = index$3.is$2; + ensure = function(value2) { + if (is(value2)) return value2; + var options = arguments[1]; + var errorMessage = options && options.name ? "Expected a plain function for %n, received %v" : "%v is not a plain function"; + return resolveException2(value2, errorMessage, options); + }; + return ensure; +} +var copy; +var hasRequiredCopy; +function requireCopy() { + if (hasRequiredCopy) return copy; + hasRequiredCopy = 1; + var aFrom = index$3.requireFrom(), assign = index$3.assign, value2 = index$3.validValue; + copy = function(obj) { + var copy2 = Object(value2(obj)), propertyNames = arguments[1], options = Object(arguments[2]); + if (copy2 !== obj && !propertyNames) return copy2; + var result = {}; + if (propertyNames) { + aFrom(propertyNames, function(propertyName) { + if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; + }); + } else { + assign(result, obj); + } + return result; + }; + return copy; +} +var autoBind; +var hasRequiredAutoBind; +function requireAutoBind() { + if (hasRequiredAutoBind) return autoBind; + hasRequiredAutoBind = 1; + var isValue = index$3.is, ensureValue = requireEnsure$1(), ensurePlainFunction = requireEnsure(), copy2 = requireCopy(), normalizeOptions = index$3.normalizeOptions, map2 = index$3.requireMap(); + var bind = Function.prototype.bind, defineProperty = Object.defineProperty, hasOwnProperty = Object.prototype.hasOwnProperty, define2; + define2 = function(name2, desc, options) { + var value2 = ensureValue(desc) && ensurePlainFunction(desc.value), dgs; + dgs = copy2(desc); + delete dgs.writable; + delete dgs.value; + dgs.get = function() { + if (!options.overwriteDefinition && hasOwnProperty.call(this, name2)) return value2; + desc.value = bind.call(value2, options.resolveContext ? options.resolveContext(this) : this); + defineProperty(this, name2, desc); + return this[name2]; + }; + return dgs; + }; + autoBind = function(props) { + var options = normalizeOptions(arguments[1]); + if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext); + return map2(props, function(desc, name2) { + return define2(name2, desc, options); + }); + }; + return autoBind; +} +var es6Iterator; +var hasRequiredEs6Iterator; +function requireEs6Iterator() { + if (hasRequiredEs6Iterator) return es6Iterator; + hasRequiredEs6Iterator = 1; + var clear2 = requireClear(), assign = index$3.assign, callable = index$3.validCallable, value2 = index$3.validValue, d = index$3.dExports, autoBind2 = requireAutoBind(), Symbol2 = index$3.requireEs6Symbol(); + var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator; + es6Iterator = Iterator = function(list, context2) { + if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); + defineProperties(this, { + __list__: d("w", value2(list)), + __context__: d("w", context2), + __nextIndex__: d("w", 0) + }); + if (!context2) return; + callable(context2.on); + context2.on("_add", this._onAdd); + context2.on("_delete", this._onDelete); + context2.on("_clear", this._onClear); + }; + delete Iterator.prototype.constructor; + defineProperties( + Iterator.prototype, + assign( + { + _next: d(function() { + var i; + if (!this.__list__) return void 0; + if (this.__redo__) { + i = this.__redo__.shift(); + if (i !== void 0) return i; + } + if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; + this._unBind(); + return void 0; + }), + next: d(function() { + return this._createResult(this._next()); + }), + _createResult: d(function(i) { + if (i === void 0) return { done: true, value: void 0 }; + return { done: false, value: this._resolve(i) }; + }), + _resolve: d(function(i) { + return this.__list__[i]; + }), + _unBind: d(function() { + this.__list__ = null; + delete this.__redo__; + if (!this.__context__) return; + this.__context__.off("_add", this._onAdd); + this.__context__.off("_delete", this._onDelete); + this.__context__.off("_clear", this._onClear); + this.__context__ = null; + }), + toString: d(function() { + return "[object " + (this[Symbol2.toStringTag] || "Object") + "]"; + }) + }, + autoBind2({ + _onAdd: d(function(index2) { + if (index2 >= this.__nextIndex__) return; + ++this.__nextIndex__; + if (!this.__redo__) { + defineProperty(this, "__redo__", d("c", [index2])); + return; + } + this.__redo__.forEach(function(redo2, i) { + if (redo2 >= index2) this.__redo__[i] = ++redo2; + }, this); + this.__redo__.push(index2); + }), + _onDelete: d(function(index2) { + var i; + if (index2 >= this.__nextIndex__) return; + --this.__nextIndex__; + if (!this.__redo__) return; + i = this.__redo__.indexOf(index2); + if (i !== -1) this.__redo__.splice(i, 1); + this.__redo__.forEach(function(redo2, j) { + if (redo2 > index2) this.__redo__[j] = --redo2; + }, this); + }), + _onClear: d(function() { + if (this.__redo__) clear2.call(this.__redo__); + this.__nextIndex__ = 0; + }) + }) + ) + ); + defineProperty( + Iterator.prototype, + Symbol2.iterator, + d(function() { + return this; + }) + ); + return es6Iterator; +} +var hasRequiredArray; +function requireArray() { + if (hasRequiredArray) return array$1.exports; + hasRequiredArray = 1; + var setPrototypeOf2 = requireSetPrototypeOf(), contains = index$3.contains, d = index$3.dExports, Symbol2 = index$3.requireEs6Symbol(), Iterator = requireEs6Iterator(); + var defineProperty = Object.defineProperty, ArrayIterator; + ArrayIterator = array$1.exports = function(arr, kind) { + if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); + Iterator.call(this, arr); + if (!kind) kind = "value"; + else if (contains.call(kind, "key+value")) kind = "key+value"; + else if (contains.call(kind, "key")) kind = "key"; + else kind = "value"; + defineProperty(this, "__kind__", d("", kind)); + }; + if (setPrototypeOf2) setPrototypeOf2(ArrayIterator, Iterator); + delete ArrayIterator.prototype.constructor; + ArrayIterator.prototype = Object.create(Iterator.prototype, { + _resolve: d(function(i) { + if (this.__kind__ === "value") return this.__list__[i]; + if (this.__kind__ === "key+value") return [i, this.__list__[i]]; + return i; + }) + }); + defineProperty(ArrayIterator.prototype, Symbol2.toStringTag, d("c", "Array Iterator")); + return array$1.exports; +} +var string$1 = { exports: {} }; +var hasRequiredString; +function requireString() { + if (hasRequiredString) return string$1.exports; + hasRequiredString = 1; + var setPrototypeOf2 = requireSetPrototypeOf(), d = index$3.dExports, Symbol2 = index$3.requireEs6Symbol(), Iterator = requireEs6Iterator(); + var defineProperty = Object.defineProperty, StringIterator; + StringIterator = string$1.exports = function(str2) { + if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); + str2 = String(str2); + Iterator.call(this, str2); + defineProperty(this, "__length__", d("", str2.length)); + }; + if (setPrototypeOf2) setPrototypeOf2(StringIterator, Iterator); + delete StringIterator.prototype.constructor; + StringIterator.prototype = Object.create(Iterator.prototype, { + _next: d(function() { + if (!this.__list__) return void 0; + if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; + this._unBind(); + return void 0; + }), + _resolve: d(function(i) { + var char = this.__list__[i], code2; + if (this.__nextIndex__ === this.__length__) return char; + code2 = char.charCodeAt(0); + if (code2 >= 55296 && code2 <= 56319) return char + this.__list__[this.__nextIndex__++]; + return char; + }) + }); + defineProperty(StringIterator.prototype, Symbol2.toStringTag, d("c", "String Iterator")); + return string$1.exports; +} +var isIterable; +var hasRequiredIsIterable; +function requireIsIterable() { + if (hasRequiredIsIterable) return isIterable; + hasRequiredIsIterable = 1; + var isArguments = index$3.requireIsArguments(), isValue = index$3.isValue, isString = index$3.requireIsString(); + var iteratorSymbol = index$3.requireEs6Symbol().iterator, isArray2 = Array.isArray; + isIterable = function(value2) { + if (!isValue(value2)) return false; + if (isArray2(value2)) return true; + if (isString(value2)) return true; + if (isArguments(value2)) return true; + return typeof value2[iteratorSymbol] === "function"; + }; + return isIterable; +} +var validIterable; +var hasRequiredValidIterable; +function requireValidIterable() { + if (hasRequiredValidIterable) return validIterable; + hasRequiredValidIterable = 1; + var isIterable2 = requireIsIterable(); + validIterable = function(value2) { + if (!isIterable2(value2)) throw new TypeError(value2 + " is not iterable"); + return value2; + }; + return validIterable; +} +var get2; +var hasRequiredGet; +function requireGet() { + if (hasRequiredGet) return get2; + hasRequiredGet = 1; + var isArguments = index$3.requireIsArguments(), isString = index$3.requireIsString(), ArrayIterator = requireArray(), StringIterator = requireString(), iterable = requireValidIterable(), iteratorSymbol = index$3.requireEs6Symbol().iterator; + get2 = function(obj) { + if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol](); + if (isArguments(obj)) return new ArrayIterator(obj); + if (isString(obj)) return new StringIterator(obj); + return new ArrayIterator(obj); + }; + return get2; +} +var forOf; +var hasRequiredForOf; +function requireForOf() { + if (hasRequiredForOf) return forOf; + hasRequiredForOf = 1; + var isArguments = index$3.requireIsArguments(), callable = index$3.validCallable, isString = index$3.requireIsString(), get3 = requireGet(); + var isArray2 = Array.isArray, call = Function.prototype.call, some = Array.prototype.some; + forOf = function(iterable, cb) { + var mode, thisArg = arguments[2], result, doBreak, broken, i, length2, char, code2; + if (isArray2(iterable) || isArguments(iterable)) mode = "array"; + else if (isString(iterable)) mode = "string"; + else iterable = get3(iterable); + callable(cb); + doBreak = function() { + broken = true; + }; + if (mode === "array") { + some.call(iterable, function(value2) { + call.call(cb, thisArg, value2, doBreak); + return broken; + }); + return; + } + if (mode === "string") { + length2 = iterable.length; + for (i = 0; i < length2; ++i) { + char = iterable[i]; + if (i + 1 < length2) { + code2 = char.charCodeAt(0); + if (code2 >= 55296 && code2 <= 56319) char += iterable[++i]; + } + call.call(cb, thisArg, char, doBreak); + if (broken) break; + } + return; + } + result = iterable.next(); + while (!result.done) { + call.call(cb, thisArg, result.value, doBreak); + if (broken) return; + result = iterable.next(); + } + }; + return forOf; +} +var isNativeImplemented; +var hasRequiredIsNativeImplemented; +function requireIsNativeImplemented() { + if (hasRequiredIsNativeImplemented) return isNativeImplemented; + hasRequiredIsNativeImplemented = 1; + isNativeImplemented = function() { + if (typeof WeakMap !== "function") return false; + return Object.prototype.toString.call(/* @__PURE__ */ new WeakMap()) === "[object WeakMap]"; + }(); + return isNativeImplemented; +} +var polyfill; +var hasRequiredPolyfill; +function requirePolyfill() { + if (hasRequiredPolyfill) return polyfill; + hasRequiredPolyfill = 1; + var isValue = index$3.isValue, setPrototypeOf2 = requireSetPrototypeOf(), object2 = requireValidObject(), ensureValue = index$3.validValue, randomUniq2 = requireRandomUniq(), d = index$3.dExports, getIterator = requireGet(), forOf2 = requireForOf(), toStringTagSymbol = index$3.requireEs6Symbol().toStringTag, isNative = requireIsNativeImplemented(), isArray2 = Array.isArray, defineProperty = Object.defineProperty, objHasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf, WeakMapPoly; + polyfill = WeakMapPoly = function() { + var iterable = arguments[0], self2; + if (!(this instanceof WeakMapPoly)) throw new TypeError("Constructor requires 'new'"); + self2 = isNative && setPrototypeOf2 && WeakMap !== WeakMapPoly ? setPrototypeOf2(/* @__PURE__ */ new WeakMap(), getPrototypeOf(this)) : this; + if (isValue(iterable)) { + if (!isArray2(iterable)) iterable = getIterator(iterable); + } + defineProperty(self2, "__weakMapData__", d("c", "$weakMap$" + randomUniq2())); + if (!iterable) return self2; + forOf2(iterable, function(val) { + ensureValue(val); + self2.set(val[0], val[1]); + }); + return self2; + }; + if (isNative) { + if (setPrototypeOf2) setPrototypeOf2(WeakMapPoly, WeakMap); + WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) }); + } + Object.defineProperties(WeakMapPoly.prototype, { + delete: d(function(key) { + if (objHasOwnProperty.call(object2(key), this.__weakMapData__)) { + delete key[this.__weakMapData__]; + return true; + } + return false; + }), + get: d(function(key) { + if (!objHasOwnProperty.call(object2(key), this.__weakMapData__)) return void 0; + return key[this.__weakMapData__]; + }), + has: d(function(key) { + return objHasOwnProperty.call(object2(key), this.__weakMapData__); + }), + set: d(function(key, value2) { + defineProperty(object2(key), this.__weakMapData__, d("c", value2)); + return this; + }), + toString: d(function() { + return "[object WeakMap]"; + }) + }); + defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap")); + return polyfill; +} +var es6WeakMap = isImplemented$1() ? WeakMap : requirePolyfill(); +var arrayFindIndex = function(arr, predicate, ctx2) { + if (typeof Array.prototype.findIndex === "function") { + return arr.findIndex(predicate, ctx2); + } + if (typeof predicate !== "function") { + throw new TypeError("predicate must be a function"); + } + var list = Object(arr); + var len = list.length; + if (len === 0) { + return -1; + } + for (var i = 0; i < len; i++) { + if (predicate.call(ctx2, list[i], i, list)) { + return i; + } + } + return -1; +}; +const rgba$3 = colorNormalize; +const getBounds$1 = arrayBounds; +const extend$3 = index$3.objectAssign; +const pick$4 = pickByAlias; +const flatten$2 = flattenVertexData_1; +const triangulate = earcutExports; +const normalize2 = arrayNormalize; +const { float32: float32$1, fract32: fract32$1 } = toFloat32Exports; +const WeakMap$2 = es6WeakMap; +const parseRect$1 = parseRect_1; +const findIndex = arrayFindIndex; +const rectVert = ` +precision highp float; + +attribute vec2 aCoord, bCoord, aCoordFract, bCoordFract; +attribute vec4 color; +attribute float lineEnd, lineTop; + +uniform vec2 scale, scaleFract, translate, translateFract; +uniform float thickness, pixelRatio, id, depth; +uniform vec4 viewport; + +varying vec4 fragColor; +varying vec2 tangent; + +vec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) { + // the order is important + return position * scale + translate + + positionFract * scale + translateFract + + position * scaleFract + + positionFract * scaleFract; +} + +void main() { + float lineStart = 1. - lineEnd; + float lineOffset = lineTop * 2. - 1.; + + vec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract); + tangent = normalize(diff * scale * viewport.zw); + vec2 normal = vec2(-tangent.y, tangent.x); + + vec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart + + project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd + + + thickness * normal * .5 * lineOffset / viewport.zw; + + gl_Position = vec4(position * 2.0 - 1.0, depth, 1); + + fragColor = color / 255.; +} +`; +const rectFrag = ` +precision highp float; + +uniform float dashLength, pixelRatio, thickness, opacity, id; +uniform sampler2D dashTexture; + +varying vec4 fragColor; +varying vec2 tangent; + +void main() { + float alpha = 1.; + + float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25; + float dash = texture2D(dashTexture, vec2(t, .5)).r; + + gl_FragColor = fragColor; + gl_FragColor.a *= alpha * opacity * dash; +} +`; +const fillVert = ` +precision highp float; + +attribute vec2 position, positionFract; + +uniform vec4 color; +uniform vec2 scale, scaleFract, translate, translateFract; +uniform float pixelRatio, id; +uniform vec4 viewport; +uniform float opacity; + +varying vec4 fragColor; + +const float MAX_LINES = 256.; + +void main() { + float depth = (MAX_LINES - 4. - id) / (MAX_LINES); + + vec2 position = position * scale + translate + + positionFract * scale + translateFract + + position * scaleFract + + positionFract * scaleFract; + + gl_Position = vec4(position * 2.0 - 1.0, depth, 1); + + fragColor = color / 255.; + fragColor.a *= opacity; +} +`; +const fillFrag = ` +precision highp float; +varying vec4 fragColor; + +void main() { + gl_FragColor = fragColor; +} +`; +const milterVert = ` +precision highp float; + +attribute vec2 aCoord, bCoord, nextCoord, prevCoord; +attribute vec4 aColor, bColor; +attribute float lineEnd, lineTop; + +uniform vec2 scale, translate; +uniform float thickness, pixelRatio, id, depth; +uniform vec4 viewport; +uniform float miterLimit, miterMode; + +varying vec4 fragColor; +varying vec4 startCutoff, endCutoff; +varying vec2 tangent; +varying vec2 startCoord, endCoord; +varying float enableStartMiter, enableEndMiter; + +const float REVERSE_THRESHOLD = -.875; +const float MIN_DIFF = 1e-6; + +// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead +// TODO: precalculate dot products, normalize things beforehead etc. +// TODO: refactor to rectangular algorithm + +float distToLine(vec2 p, vec2 a, vec2 b) { + vec2 diff = b - a; + vec2 perp = normalize(vec2(-diff.y, diff.x)); + return dot(p - a, perp); +} + +bool isNaN( float val ){ + return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; +} + +void main() { + vec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord; + + vec2 adjustedScale; + adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x; + adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y; + + vec2 scaleRatio = adjustedScale * viewport.zw; + vec2 normalWidth = thickness / scaleRatio; + + float lineStart = 1. - lineEnd; + float lineBot = 1. - lineTop; + + fragColor = (lineStart * aColor + lineEnd * bColor) / 255.; + + if (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return; + + if (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord); + if (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord); + + + vec2 prevDiff = aCoord - prevCoord; + vec2 currDiff = bCoord - aCoord; + vec2 nextDiff = nextCoord - bCoord; + + vec2 prevTangent = normalize(prevDiff * scaleRatio); + vec2 currTangent = normalize(currDiff * scaleRatio); + vec2 nextTangent = normalize(nextDiff * scaleRatio); + + vec2 prevNormal = vec2(-prevTangent.y, prevTangent.x); + vec2 currNormal = vec2(-currTangent.y, currTangent.x); + vec2 nextNormal = vec2(-nextTangent.y, nextTangent.x); + + vec2 startJoinDirection = normalize(prevTangent - currTangent); + vec2 endJoinDirection = normalize(currTangent - nextTangent); + + // collapsed/unidirectional segment cases + // FIXME: there should be more elegant solution + vec2 prevTanDiff = abs(prevTangent - currTangent); + vec2 nextTanDiff = abs(nextTangent - currTangent); + if (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) { + startJoinDirection = currNormal; + } + if (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) { + endJoinDirection = currNormal; + } + if (aCoord == bCoord) { + endJoinDirection = startJoinDirection; + currNormal = prevNormal; + currTangent = prevTangent; + } + + tangent = currTangent; + + //calculate join shifts relative to normals + float startJoinShift = dot(currNormal, startJoinDirection); + float endJoinShift = dot(currNormal, endJoinDirection); + + float startMiterRatio = abs(1. / startJoinShift); + float endMiterRatio = abs(1. / endJoinShift); + + vec2 startJoin = startJoinDirection * startMiterRatio; + vec2 endJoin = endJoinDirection * endMiterRatio; + + vec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin; + startTopJoin = sign(startJoinShift) * startJoin * .5; + startBotJoin = -startTopJoin; + + endTopJoin = sign(endJoinShift) * endJoin * .5; + endBotJoin = -endTopJoin; + + vec2 aTopCoord = aCoord + normalWidth * startTopJoin; + vec2 bTopCoord = bCoord + normalWidth * endTopJoin; + vec2 aBotCoord = aCoord + normalWidth * startBotJoin; + vec2 bBotCoord = bCoord + normalWidth * endBotJoin; + + //miter anti-clipping + float baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x))); + float abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x))); + + //prevent close to reverse direction switch + bool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal); + bool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal); + + if (prevReverse) { + //make join rectangular + vec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5; + float normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.); + aBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5; + aTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5; + } + else if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) { + //handle miter clipping + bTopCoord -= normalWidth * endTopJoin; + bTopCoord += normalize(endTopJoin * normalWidth) * baClipping; + } + + if (nextReverse) { + //make join rectangular + vec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5; + float normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.); + bBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5; + bTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5; + } + else if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) { + //handle miter clipping + aBotCoord -= normalWidth * startBotJoin; + aBotCoord += normalize(startBotJoin * normalWidth) * abClipping; + } + + vec2 aTopPosition = (aTopCoord) * adjustedScale + translate; + vec2 aBotPosition = (aBotCoord) * adjustedScale + translate; + + vec2 bTopPosition = (bTopCoord) * adjustedScale + translate; + vec2 bBotPosition = (bBotCoord) * adjustedScale + translate; + + //position is normalized 0..1 coord on the screen + vec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd; + + startCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy; + endCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy; + + gl_Position = vec4(position * 2.0 - 1.0, depth, 1); + + enableStartMiter = step(dot(currTangent, prevTangent), .5); + enableEndMiter = step(dot(currTangent, nextTangent), .5); + + //bevel miter cutoffs + if (miterMode == 1.) { + if (enableStartMiter == 1.) { + vec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5; + startCutoff = vec4(aCoord, aCoord); + startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio; + startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; + startCutoff += viewport.xyxy; + startCutoff += startMiterWidth.xyxy; + } + + if (enableEndMiter == 1.) { + vec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5; + endCutoff = vec4(bCoord, bCoord); + endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio; + endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; + endCutoff += viewport.xyxy; + endCutoff += endMiterWidth.xyxy; + } + } + + //round miter cutoffs + else if (miterMode == 2.) { + if (enableStartMiter == 1.) { + vec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5; + startCutoff = vec4(aCoord, aCoord); + startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio; + startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; + startCutoff += viewport.xyxy; + startCutoff += startMiterWidth.xyxy; + } + + if (enableEndMiter == 1.) { + vec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5; + endCutoff = vec4(bCoord, bCoord); + endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio; + endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; + endCutoff += viewport.xyxy; + endCutoff += endMiterWidth.xyxy; + } + } +} +`; +const milterFrag = ` +precision highp float; + +uniform float dashLength, pixelRatio, thickness, opacity, id, miterMode; +uniform sampler2D dashTexture; + +varying vec4 fragColor; +varying vec2 tangent; +varying vec4 startCutoff, endCutoff; +varying vec2 startCoord, endCoord; +varying float enableStartMiter, enableEndMiter; + +float distToLine(vec2 p, vec2 a, vec2 b) { + vec2 diff = b - a; + vec2 perp = normalize(vec2(-diff.y, diff.x)); + return dot(p - a, perp); +} + +void main() { + float alpha = 1., distToStart, distToEnd; + float cutoff = thickness * .5; + + //bevel miter + if (miterMode == 1.) { + if (enableStartMiter == 1.) { + distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw); + if (distToStart < -1.) { + discard; + return; + } + alpha *= min(max(distToStart + 1., 0.), 1.); + } + + if (enableEndMiter == 1.) { + distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw); + if (distToEnd < -1.) { + discard; + return; + } + alpha *= min(max(distToEnd + 1., 0.), 1.); + } + } + + // round miter + else if (miterMode == 2.) { + if (enableStartMiter == 1.) { + distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw); + if (distToStart < 0.) { + float radius = length(gl_FragCoord.xy - startCoord); + + if(radius > cutoff + .5) { + discard; + return; + } + + alpha -= smoothstep(cutoff - .5, cutoff + .5, radius); + } + } + + if (enableEndMiter == 1.) { + distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw); + if (distToEnd < 0.) { + float radius = length(gl_FragCoord.xy - endCoord); + + if(radius > cutoff + .5) { + discard; + return; + } + + alpha -= smoothstep(cutoff - .5, cutoff + .5, radius); + } + } + } + + float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25; + float dash = texture2D(dashTexture, vec2(t, .5)).r; + + gl_FragColor = fragColor; + gl_FragColor.a *= alpha * opacity * dash; +} +`; +var reglLine2d = Line2D; +function Line2D(regl, options) { + if (!(this instanceof Line2D)) return new Line2D(regl, options); + if (typeof regl === "function") { + if (!options) options = {}; + options.regl = regl; + } else { + options = regl; + } + if (options.length) options.positions = options; + regl = options.regl; + if (!regl.hasExtension("ANGLE_instanced_arrays")) { + throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled"); + } + this.gl = regl._gl; + this.regl = regl; + this.passes = []; + this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl); + this.update(options); +} +Line2D.dashMult = 2; +Line2D.maxPatternLength = 256; +Line2D.precisionThreshold = 3e6; +Line2D.maxPoints = 1e4; +Line2D.maxLines = 2048; +Line2D.shaders = new WeakMap$2(); +Line2D.createShaders = function(regl) { + let offsetBuffer = regl.buffer({ + usage: "static", + type: "float", + data: [0, 1, 0, 0, 1, 1, 1, 0] + }); + let shaderOptions = { + primitive: "triangle strip", + instances: regl.prop("count"), + count: 4, + offset: 0, + uniforms: { + miterMode: (ctx2, prop) => prop.join === "round" ? 2 : 1, + miterLimit: regl.prop("miterLimit"), + scale: regl.prop("scale"), + scaleFract: regl.prop("scaleFract"), + translateFract: regl.prop("translateFract"), + translate: regl.prop("translate"), + thickness: regl.prop("thickness"), + dashTexture: regl.prop("dashTexture"), + opacity: regl.prop("opacity"), + pixelRatio: regl.context("pixelRatio"), + id: regl.prop("id"), + dashLength: regl.prop("dashLength"), + viewport: (c, p) => [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight], + depth: regl.prop("depth") + }, + blend: { + enable: true, + color: [0, 0, 0, 0], + equation: { + rgb: "add", + alpha: "add" + }, + func: { + srcRGB: "src alpha", + dstRGB: "one minus src alpha", + srcAlpha: "one minus dst alpha", + dstAlpha: "one" + } + }, + depth: { + enable: (c, p) => { + return !p.overlay; + } + }, + stencil: { enable: false }, + scissor: { + enable: true, + box: regl.prop("viewport") + }, + viewport: regl.prop("viewport") + }; + let drawRectLine = regl(extend$3({ + vert: rectVert, + frag: rectFrag, + attributes: { + // if point is at the end of segment + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // if point is at the top of segment + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // beginning of line coordinate + aCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 8, + divisor: 1 + }, + // end of line coordinate + bCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 16, + divisor: 1 + }, + aCoordFract: { + buffer: regl.prop("positionFractBuffer"), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoordFract: { + buffer: regl.prop("positionFractBuffer"), + stride: 8, + offset: 16, + divisor: 1 + }, + color: { + buffer: regl.prop("colorBuffer"), + stride: 4, + offset: 0, + divisor: 1 + } + } + }, shaderOptions)); + let drawMiterLine; + try { + drawMiterLine = regl(extend$3({ + // culling removes polygon creasing + cull: { + enable: true, + face: "back" + }, + vert: milterVert, + frag: milterFrag, + attributes: { + // is line end + lineEnd: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 0 + }, + // is line top + lineTop: { + buffer: offsetBuffer, + divisor: 0, + stride: 8, + offset: 4 + }, + // left color + aColor: { + buffer: regl.prop("colorBuffer"), + stride: 4, + offset: 0, + divisor: 1 + }, + // right color + bColor: { + buffer: regl.prop("colorBuffer"), + stride: 4, + offset: 4, + divisor: 1 + }, + prevCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 0, + divisor: 1 + }, + aCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 8, + divisor: 1 + }, + bCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 16, + divisor: 1 + }, + nextCoord: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 24, + divisor: 1 + } + } + }, shaderOptions)); + } catch (e) { + drawMiterLine = drawRectLine; + } + let drawFill = regl({ + primitive: "triangle", + elements: (ctx2, prop) => prop.triangles, + offset: 0, + vert: fillVert, + frag: fillFrag, + uniforms: { + scale: regl.prop("scale"), + color: regl.prop("fill"), + scaleFract: regl.prop("scaleFract"), + translateFract: regl.prop("translateFract"), + translate: regl.prop("translate"), + opacity: regl.prop("opacity"), + pixelRatio: regl.context("pixelRatio"), + id: regl.prop("id"), + viewport: (ctx2, prop) => [prop.viewport.x, prop.viewport.y, ctx2.viewportWidth, ctx2.viewportHeight] + }, + attributes: { + position: { + buffer: regl.prop("positionBuffer"), + stride: 8, + offset: 8 + }, + positionFract: { + buffer: regl.prop("positionFractBuffer"), + stride: 8, + offset: 8 + } + }, + blend: shaderOptions.blend, + depth: { enable: false }, + scissor: shaderOptions.scissor, + stencil: shaderOptions.stencil, + viewport: shaderOptions.viewport + }); + return { + fill: drawFill, + rect: drawRectLine, + miter: drawMiterLine + }; +}; +Line2D.defaults = { + dashes: null, + join: "miter", + miterLimit: 1, + thickness: 10, + cap: "square", + color: "black", + opacity: 1, + overlay: false, + viewport: null, + range: null, + close: false, + fill: null +}; +Line2D.prototype.render = function(...args) { + if (args.length) { + this.update(...args); + } + this.draw(); +}; +Line2D.prototype.draw = function(...args) { + (args.length ? args : this.passes).forEach((s, i) => { + if (s && Array.isArray(s)) return this.draw(...s); + if (typeof s === "number") s = this.passes[s]; + if (!(s && s.count > 1 && s.opacity)) return; + this.regl._refresh(); + if (s.fill && s.triangles && s.triangles.length > 2) { + this.shaders.fill(s); + } + if (!s.thickness) return; + if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) { + this.shaders.rect(s); + } else if (s.join === "rect" || !s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints)) { + this.shaders.rect(s); + } else { + this.shaders.miter(s); + } + }); + return this; +}; +Line2D.prototype.update = function(options) { + if (!options) return; + if (options.length != null) { + if (typeof options[0] === "number") options = [{ positions: options }]; + } else if (!Array.isArray(options)) options = [options]; + let { regl, gl } = this; + options.forEach((o, i) => { + let state = this.passes[i]; + if (o === void 0) return; + if (o === null) { + this.passes[i] = null; + return; + } + if (typeof o[0] === "number") o = { positions: o }; + o = pick$4(o, { + positions: "positions points data coords", + thickness: "thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth", + join: "lineJoin linejoin join type mode", + miterLimit: "miterlimit miterLimit", + dashes: "dash dashes dasharray dash-array dashArray", + color: "color colour stroke colors colours stroke-color strokeColor", + fill: "fill fill-color fillColor", + opacity: "alpha opacity", + overlay: "overlay crease overlap intersect", + close: "closed close closed-path closePath", + range: "range dataBox", + viewport: "viewport viewBox", + hole: "holes hole hollow", + splitNull: "splitNull" + }); + if (!state) { + this.passes[i] = state = { + id: i, + scale: null, + scaleFract: null, + translate: null, + translateFract: null, + count: 0, + hole: [], + depth: 0, + dashLength: 1, + dashTexture: regl.texture({ + channels: 1, + data: new Uint8Array([255]), + width: 1, + height: 1, + mag: "linear", + min: "linear" + }), + colorBuffer: regl.buffer({ + usage: "dynamic", + type: "uint8", + data: new Uint8Array() + }), + positionBuffer: regl.buffer({ + usage: "dynamic", + type: "float", + data: new Uint8Array() + }), + positionFractBuffer: regl.buffer({ + usage: "dynamic", + type: "float", + data: new Uint8Array() + }) + }; + o = extend$3({}, Line2D.defaults, o); + } + if (o.thickness != null) state.thickness = parseFloat(o.thickness); + if (o.opacity != null) state.opacity = parseFloat(o.opacity); + if (o.miterLimit != null) state.miterLimit = parseFloat(o.miterLimit); + if (o.overlay != null) { + state.overlay = !!o.overlay; + if (i < Line2D.maxLines) { + state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1; + } + } + if (o.join != null) state.join = o.join; + if (o.hole != null) state.hole = o.hole; + if (o.fill != null) state.fill = !o.fill ? null : rgba$3(o.fill, "uint8"); + if (o.viewport != null) state.viewport = parseRect$1(o.viewport); + if (!state.viewport) { + state.viewport = parseRect$1([ + gl.drawingBufferWidth, + gl.drawingBufferHeight + ]); + } + if (o.close != null) state.close = o.close; + if (o.positions === null) o.positions = []; + if (o.positions) { + let positions, count2; + if (o.positions.x && o.positions.y) { + let xPos = o.positions.x; + let yPos = o.positions.y; + count2 = state.count = Math.max( + xPos.length, + yPos.length + ); + positions = new Float64Array(count2 * 2); + for (let i2 = 0; i2 < count2; i2++) { + positions[i2 * 2] = xPos[i2]; + positions[i2 * 2 + 1] = yPos[i2]; + } + } else { + positions = flatten$2(o.positions, "float64"); + count2 = state.count = Math.floor(positions.length / 2); + } + let bounds = state.bounds = getBounds$1(positions, 2); + if (state.fill) { + let pos = []; + let ids = {}; + let lastId = 0; + for (let i2 = 0, ptr = 0, l = state.count; i2 < l; i2++) { + let x = positions[i2 * 2]; + let y = positions[i2 * 2 + 1]; + if (isNaN(x) || isNaN(y) || x == null || y == null) { + x = positions[lastId * 2]; + y = positions[lastId * 2 + 1]; + ids[i2] = lastId; + } else { + lastId = i2; + } + pos[ptr++] = x; + pos[ptr++] = y; + } + if (o.splitNull) { + if (!(state.count - 1 in ids)) ids[state.count] = state.count - 1; + let splits = Object.keys(ids).map(Number).sort((a, b) => a - b); + let split_triangles = []; + let base = 0; + let hole_base = state.hole != null ? state.hole[0] : null; + if (hole_base != null) { + let last_id = findIndex(splits, (e) => e >= hole_base); + splits = splits.slice(0, last_id); + splits.push(hole_base); + } + for (let i2 = 0; i2 < splits.length; i2++) { + let seg_pos = pos.slice(base * 2, splits[i2] * 2).concat( + hole_base ? pos.slice(hole_base * 2) : [] + ); + let hole = (state.hole || []).map((e) => e - hole_base + (splits[i2] - base)); + let triangles = triangulate(seg_pos, hole); + triangles = triangles.map( + (e) => e + base + (e + base < splits[i2] ? 0 : hole_base - splits[i2]) + ); + split_triangles.push(...triangles); + base = splits[i2] + 1; + } + for (let i2 = 0, l = split_triangles.length; i2 < l; i2++) { + if (ids[split_triangles[i2]] != null) split_triangles[i2] = ids[split_triangles[i2]]; + } + state.triangles = split_triangles; + } else { + let triangles = triangulate(pos, state.hole || []); + for (let i2 = 0, l = triangles.length; i2 < l; i2++) { + if (ids[triangles[i2]] != null) triangles[i2] = ids[triangles[i2]]; + } + state.triangles = triangles; + } + } + let npos = new Float64Array(positions); + normalize2(npos, 2, bounds); + let positionData = new Float64Array(count2 * 2 + 6); + if (state.close) { + if (positions[0] === positions[count2 * 2 - 2] && positions[1] === positions[count2 * 2 - 1]) { + positionData[0] = npos[count2 * 2 - 4]; + positionData[1] = npos[count2 * 2 - 3]; + } else { + positionData[0] = npos[count2 * 2 - 2]; + positionData[1] = npos[count2 * 2 - 1]; + } + } else { + positionData[0] = npos[0]; + positionData[1] = npos[1]; + } + positionData.set(npos, 2); + if (state.close) { + if (positions[0] === positions[count2 * 2 - 2] && positions[1] === positions[count2 * 2 - 1]) { + positionData[count2 * 2 + 2] = npos[2]; + positionData[count2 * 2 + 3] = npos[3]; + state.count -= 1; + } else { + positionData[count2 * 2 + 2] = npos[0]; + positionData[count2 * 2 + 3] = npos[1]; + positionData[count2 * 2 + 4] = npos[2]; + positionData[count2 * 2 + 5] = npos[3]; + } + } else { + positionData[count2 * 2 + 2] = npos[count2 * 2 - 2]; + positionData[count2 * 2 + 3] = npos[count2 * 2 - 1]; + positionData[count2 * 2 + 4] = npos[count2 * 2 - 2]; + positionData[count2 * 2 + 5] = npos[count2 * 2 - 1]; + } + var float_data = float32$1(positionData); + state.positionBuffer(float_data); + var frac_data = fract32$1(positionData, float_data); + state.positionFractBuffer(frac_data); + } + if (o.range) { + state.range = o.range; + } else if (!state.range) { + state.range = state.bounds; + } + if ((o.range || o.positions) && state.count) { + let bounds = state.bounds; + let boundsW = bounds[2] - bounds[0], boundsH = bounds[3] - bounds[1]; + let rangeW = state.range[2] - state.range[0], rangeH = state.range[3] - state.range[1]; + state.scale = [ + boundsW / rangeW, + boundsH / rangeH + ]; + state.translate = [ + -state.range[0] / rangeW + bounds[0] / rangeW || 0, + -state.range[1] / rangeH + bounds[1] / rangeH || 0 + ]; + state.scaleFract = fract32$1(state.scale); + state.translateFract = fract32$1(state.translate); + } + if (o.dashes) { + let dashLength = 0, dashData; + if (!o.dashes || o.dashes.length < 2) { + dashLength = 1; + dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]); + } else { + dashLength = 0; + for (let i2 = 0; i2 < o.dashes.length; ++i2) { + dashLength += o.dashes[i2]; + } + dashData = new Uint8Array(dashLength * Line2D.dashMult); + let ptr = 0; + let fillColor = 255; + for (let k = 0; k < 2; k++) { + for (let i2 = 0; i2 < o.dashes.length; ++i2) { + for (let j = 0, l = o.dashes[i2] * Line2D.dashMult * 0.5; j < l; ++j) { + dashData[ptr++] = fillColor; + } + fillColor ^= 255; + } + } + } + state.dashLength = dashLength; + state.dashTexture({ + channels: 1, + data: dashData, + width: dashData.length, + height: 1, + mag: "linear", + min: "linear" + }, 0, 0); + } + if (o.color) { + let count2 = state.count; + let colors = o.color; + if (!colors) colors = "transparent"; + let colorData = new Uint8Array(count2 * 4 + 4); + if (!Array.isArray(colors) || typeof colors[0] === "number") { + let c = rgba$3(colors, "uint8"); + for (let i2 = 0; i2 < count2 + 1; i2++) { + colorData.set(c, i2 * 4); + } + } else { + for (let i2 = 0; i2 < count2; i2++) { + let c = rgba$3(colors[i2], "uint8"); + colorData.set(c, i2 * 4); + } + colorData.set(rgba$3(colors[0], "uint8"), count2 * 4); + } + state.colorBuffer({ + usage: "dynamic", + type: "uint8", + data: colorData + }); + } + }); + if (options.length < this.passes.length) { + for (let i = options.length; i < this.passes.length; i++) { + let pass = this.passes[i]; + if (!pass) continue; + pass.colorBuffer.destroy(); + pass.positionBuffer.destroy(); + pass.dashTexture.destroy(); + } + this.passes.length = options.length; + } + let passes = []; + for (let i = 0; i < this.passes.length; i++) { + if (this.passes[i] !== null) passes.push(this.passes[i]); + } + this.passes = passes; + return this; +}; +Line2D.prototype.destroy = function() { + this.passes.forEach((pass) => { + pass.colorBuffer.destroy(); + pass.positionBuffer.destroy(); + pass.dashTexture.destroy(); + }); + this.passes.length = 0; + return this; +}; +const getBounds = arrayBounds; +const rgba$2 = colorNormalize; +const updateDiff2 = updateDiff$2; +const pick$3 = pickByAlias; +const extend$2 = index$3.objectAssign; +const flatten$1 = flattenVertexData_1; +const { float32, fract32 } = toFloat32Exports; +var reglError2d = Error2D; +const WEIGHTS = [ + //direction, lineWidth shift, capSize shift + // x-error bar + [1, 0, 0, 1, 0, 0], + [1, 0, 0, -1, 0, 0], + [-1, 0, 0, -1, 0, 0], + [-1, 0, 0, -1, 0, 0], + [-1, 0, 0, 1, 0, 0], + [1, 0, 0, 1, 0, 0], + // x-error right cap + [1, 0, -1, 0, 0, 1], + [1, 0, -1, 0, 0, -1], + [1, 0, 1, 0, 0, -1], + [1, 0, 1, 0, 0, -1], + [1, 0, 1, 0, 0, 1], + [1, 0, -1, 0, 0, 1], + // x-error left cap + [-1, 0, -1, 0, 0, 1], + [-1, 0, -1, 0, 0, -1], + [-1, 0, 1, 0, 0, -1], + [-1, 0, 1, 0, 0, -1], + [-1, 0, 1, 0, 0, 1], + [-1, 0, -1, 0, 0, 1], + // y-error bar + [0, 1, 1, 0, 0, 0], + [0, 1, -1, 0, 0, 0], + [0, -1, -1, 0, 0, 0], + [0, -1, -1, 0, 0, 0], + [0, 1, 1, 0, 0, 0], + [0, -1, 1, 0, 0, 0], + // y-error top cap + [0, 1, 0, -1, 1, 0], + [0, 1, 0, -1, -1, 0], + [0, 1, 0, 1, -1, 0], + [0, 1, 0, 1, 1, 0], + [0, 1, 0, -1, 1, 0], + [0, 1, 0, 1, -1, 0], + // y-error bottom cap + [0, -1, 0, -1, 1, 0], + [0, -1, 0, -1, -1, 0], + [0, -1, 0, 1, -1, 0], + [0, -1, 0, 1, 1, 0], + [0, -1, 0, -1, 1, 0], + [0, -1, 0, 1, -1, 0] +]; +function Error2D(regl, options) { + if (typeof regl === "function") { + if (!options) options = {}; + options.regl = regl; + } else { + options = regl; + } + if (options.length) options.positions = options; + regl = options.regl; + if (!regl.hasExtension("ANGLE_instanced_arrays")) { + throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled"); + } + let gl = regl._gl, drawErrors, positionBuffer, positionFractBuffer, colorBuffer, errorBuffer, meshBuffer, defaults2 = { + color: "black", + capSize: 5, + lineWidth: 1, + opacity: 1, + viewport: null, + range: null, + offset: 0, + count: 0, + bounds: null, + positions: [], + errors: [] + }, groups = []; + colorBuffer = regl.buffer({ + usage: "dynamic", + type: "uint8", + data: new Uint8Array(0) + }); + positionBuffer = regl.buffer({ + usage: "dynamic", + type: "float", + data: new Uint8Array(0) + }); + positionFractBuffer = regl.buffer({ + usage: "dynamic", + type: "float", + data: new Uint8Array(0) + }); + errorBuffer = regl.buffer({ + usage: "dynamic", + type: "float", + data: new Uint8Array(0) + }); + meshBuffer = regl.buffer({ + usage: "static", + type: "float", + data: WEIGHTS + }); + update2(options); + drawErrors = regl({ + vert: ` + precision highp float; + + attribute vec2 position, positionFract; + attribute vec4 error; + attribute vec4 color; + + attribute vec2 direction, lineOffset, capOffset; + + uniform vec4 viewport; + uniform float lineWidth, capSize; + uniform vec2 scale, scaleFract, translate, translateFract; + + varying vec4 fragColor; + + void main() { + fragColor = color / 255.; + + vec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset; + + vec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw; + + vec2 position = position + dxy; + + vec2 pos = (position + translate) * scale + + (positionFract + translateFract) * scale + + (position + translate) * scaleFract + + (positionFract + translateFract) * scaleFract; + + pos += pixelOffset / viewport.zw; + + gl_Position = vec4(pos * 2. - 1., 0, 1); + } + `, + frag: ` + precision highp float; + + varying vec4 fragColor; + + uniform float opacity; + + void main() { + gl_FragColor = fragColor; + gl_FragColor.a *= opacity; + } + `, + uniforms: { + range: regl.prop("range"), + lineWidth: regl.prop("lineWidth"), + capSize: regl.prop("capSize"), + opacity: regl.prop("opacity"), + scale: regl.prop("scale"), + translate: regl.prop("translate"), + scaleFract: regl.prop("scaleFract"), + translateFract: regl.prop("translateFract"), + viewport: (ctx2, prop) => [prop.viewport.x, prop.viewport.y, ctx2.viewportWidth, ctx2.viewportHeight] + }, + attributes: { + //dynamic attributes + color: { + buffer: colorBuffer, + offset: (ctx2, prop) => prop.offset * 4, + divisor: 1 + }, + position: { + buffer: positionBuffer, + offset: (ctx2, prop) => prop.offset * 8, + divisor: 1 + }, + positionFract: { + buffer: positionFractBuffer, + offset: (ctx2, prop) => prop.offset * 8, + divisor: 1 + }, + error: { + buffer: errorBuffer, + offset: (ctx2, prop) => prop.offset * 16, + divisor: 1 + }, + //static attributes + direction: { + buffer: meshBuffer, + stride: 24, + offset: 0 + }, + lineOffset: { + buffer: meshBuffer, + stride: 24, + offset: 8 + }, + capOffset: { + buffer: meshBuffer, + stride: 24, + offset: 16 + } + }, + primitive: "triangles", + blend: { + enable: true, + color: [0, 0, 0, 0], + equation: { + rgb: "add", + alpha: "add" + }, + func: { + srcRGB: "src alpha", + dstRGB: "one minus src alpha", + srcAlpha: "one minus dst alpha", + dstAlpha: "one" + } + }, + depth: { + enable: false + }, + scissor: { + enable: true, + box: regl.prop("viewport") + }, + viewport: regl.prop("viewport"), + stencil: false, + instances: regl.prop("count"), + count: WEIGHTS.length + }); + extend$2(error2d, { + update: update2, + draw: draw8, + destroy: destroy2, + regl, + gl, + canvas: gl.canvas, + groups + }); + return error2d; + function error2d(opts) { + if (opts) { + update2(opts); + } else if (opts === null) { + destroy2(); + } + draw8(); + } + function draw8(options2) { + if (typeof options2 === "number") return drawGroup(options2); + if (options2 && !Array.isArray(options2)) options2 = [options2]; + regl._refresh(); + groups.forEach((s, i) => { + if (!s) return; + if (options2) { + if (!options2[i]) s.draw = false; + else s.draw = true; + } + if (!s.draw) { + s.draw = true; + return; + } + drawGroup(i); + }); + } + function drawGroup(s) { + if (typeof s === "number") s = groups[s]; + if (s == null) return; + if (!(s && s.count && s.color && s.opacity && s.positions && s.positions.length > 1)) return; + s.scaleRatio = [ + s.scale[0] * s.viewport.width, + s.scale[1] * s.viewport.height + ]; + drawErrors(s); + if (s.after) s.after(s); + } + function update2(options2) { + if (!options2) return; + if (options2.length != null) { + if (typeof options2[0] === "number") options2 = [{ positions: options2 }]; + } else if (!Array.isArray(options2)) options2 = [options2]; + let pointCount = 0, errorCount = 0; + error2d.groups = groups = options2.map((options3, i) => { + let group = groups[i]; + if (!options3) return group; + else if (typeof options3 === "function") options3 = { after: options3 }; + else if (typeof options3[0] === "number") options3 = { positions: options3 }; + options3 = pick$3(options3, { + color: "color colors fill", + capSize: "capSize cap capsize cap-size", + lineWidth: "lineWidth line-width width line thickness", + opacity: "opacity alpha", + range: "range dataBox", + viewport: "viewport viewBox", + errors: "errors error", + positions: "positions position data points" + }); + if (!group) { + groups[i] = group = { + id: i, + scale: null, + translate: null, + scaleFract: null, + translateFract: null, + draw: true + }; + options3 = extend$2({}, defaults2, options3); + } + updateDiff2(group, options3, [{ + lineWidth: (v) => +v * 0.5, + capSize: (v) => +v * 0.5, + opacity: parseFloat, + errors: (errors) => { + errors = flatten$1(errors); + errorCount += errors.length; + return errors; + }, + positions: (positions, state) => { + positions = flatten$1(positions, "float64"); + state.count = Math.floor(positions.length / 2); + state.bounds = getBounds(positions, 2); + state.offset = pointCount; + pointCount += state.count; + return positions; + } + }, { + color: (colors, state) => { + let count2 = state.count; + if (!colors) colors = "transparent"; + if (!Array.isArray(colors) || typeof colors[0] === "number") { + let color2 = colors; + colors = Array(count2); + for (let i2 = 0; i2 < count2; i2++) { + colors[i2] = color2; + } + } + if (colors.length < count2) throw Error("Not enough colors"); + let colorData = new Uint8Array(count2 * 4); + for (let i2 = 0; i2 < count2; i2++) { + let c = rgba$2(colors[i2], "uint8"); + colorData.set(c, i2 * 4); + } + return colorData; + }, + range: (range, state, options4) => { + let bounds = state.bounds; + if (!range) range = bounds; + state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])]; + state.translate = [-range[0], -range[1]]; + state.scaleFract = fract32(state.scale); + state.translateFract = fract32(state.translate); + return range; + }, + viewport: (vp) => { + let viewport; + if (Array.isArray(vp)) { + viewport = { + x: vp[0], + y: vp[1], + width: vp[2] - vp[0], + height: vp[3] - vp[1] + }; + } else if (vp) { + viewport = { + x: vp.x || vp.left || 0, + y: vp.y || vp.top || 0 + }; + if (vp.right) viewport.width = vp.right - viewport.x; + else viewport.width = vp.w || vp.width || 0; + if (vp.bottom) viewport.height = vp.bottom - viewport.y; + else viewport.height = vp.h || vp.height || 0; + } else { + viewport = { + x: 0, + y: 0, + width: gl.drawingBufferWidth, + height: gl.drawingBufferHeight + }; + } + return viewport; + } + }]); + return group; + }); + if (pointCount || errorCount) { + let len = groups.reduce((acc, group, i) => { + return acc + (group ? group.count : 0); + }, 0); + let positionData = new Float64Array(len * 2); + let colorData = new Uint8Array(len * 4); + let errorData = new Float32Array(len * 4); + groups.forEach((group, i) => { + if (!group) return; + let { positions, count: count2, offset, color: color2, errors } = group; + if (!count2) return; + colorData.set(color2, offset * 4); + errorData.set(errors, offset * 4); + positionData.set(positions, offset * 2); + }); + var float_data = float32(positionData); + positionBuffer(float_data); + var frac_data = fract32(positionData, float_data); + positionFractBuffer(frac_data); + colorBuffer(colorData); + errorBuffer(errorData); + } + } + function destroy2() { + positionBuffer.destroy(); + positionFractBuffer.destroy(); + colorBuffer.destroy(); + errorBuffer.destroy(); + meshBuffer.destroy(); + } +} +var reg = /[\'\"]/; +var unquote$1 = function unquote(str2) { + if (!str2) { + return ""; + } + if (reg.test(str2.charAt(0))) { + str2 = str2.substr(1); + } + if (reg.test(str2.charAt(str2.length - 1))) { + str2 = str2.substr(0, str2.length - 1); + } + return str2; +}; +const require$$2$1 = [ + "inherit", + "initial", + "unset" +]; +const require$$3 = [ + "caption", + "icon", + "menu", + "message-box", + "small-caption", + "status-bar" +]; +const require$$4 = [ + "normal", + "bold", + "bolder", + "lighter", + "100", + "200", + "300", + "400", + "500", + "600", + "700", + "800", + "900" +]; +const require$$5 = [ + "normal", + "italic", + "oblique" +]; +const require$$6 = [ + "normal", + "condensed", + "semi-condensed", + "extra-condensed", + "ultra-condensed", + "expanded", + "semi-expanded", + "extra-expanded", + "ultra-expanded" +]; +function parse$1(str2, opts) { + if (typeof str2 !== "string") return [str2]; + var res = [str2]; + if (typeof opts === "string" || Array.isArray(opts)) { + opts = { brackets: opts }; + } else if (!opts) opts = {}; + var brackets = opts.brackets ? Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets] : ["{}", "[]", "()"]; + var escape = opts.escape || "___"; + var flat = !!opts.flat; + brackets.forEach(function(bracket) { + var pRE = new RegExp(["\\", bracket[0], "[^\\", bracket[0], "\\", bracket[1], "]*\\", bracket[1]].join("")); + var ids = []; + function replaceToken(token, idx, str3) { + var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1; + ids.push(refId); + return escape + refId + escape; + } + res.forEach(function(str3, i) { + var prevStr; + var a = 0; + while (str3 != prevStr) { + prevStr = str3; + str3 = str3.replace(pRE, replaceToken); + if (a++ > 1e4) throw Error("References have circular dependency. Please, check them."); + } + res[i] = str3; + }); + ids = ids.reverse(); + res = res.map(function(str3) { + ids.forEach(function(id) { + str3 = str3.replace(new RegExp("(\\" + escape + id + "\\" + escape + ")", "g"), bracket[0] + "$1" + bracket[1]); + }); + return str3; + }); + }); + var re2 = new RegExp("\\" + escape + "([0-9]+)\\" + escape); + function nest(str3, refs, escape2) { + var res2 = [], match; + var a = 0; + while (match = re2.exec(str3)) { + if (a++ > 1e4) throw Error("Circular references in parenthesis"); + res2.push(str3.slice(0, match.index)); + res2.push(nest(refs[match[1]], refs)); + str3 = str3.slice(match.index + match[0].length); + } + res2.push(str3); + return res2; + } + return flat ? res : nest(res[0], res); +} +function stringify$1(arg, opts) { + if (opts && opts.flat) { + var escape = opts && opts.escape || "___"; + var str2 = arg[0], prevStr; + if (!str2) return ""; + var re2 = new RegExp("\\" + escape + "([0-9]+)\\" + escape); + var a = 0; + while (str2 != prevStr) { + if (a++ > 1e4) throw Error("Circular references in " + arg); + prevStr = str2; + str2 = str2.replace(re2, replaceRef); + } + return str2; + } + return arg.reduce(function f(prev, curr) { + if (Array.isArray(curr)) { + curr = curr.reduce(f, ""); + } + return prev + curr; + }, ""); + function replaceRef(match, idx) { + if (arg[idx] == null) throw Error("Reference " + idx + "is undefined"); + return arg[idx]; + } +} +function parenthesis(arg, opts) { + if (Array.isArray(arg)) { + return stringify$1(arg, opts); + } else { + return parse$1(arg, opts); + } +} +parenthesis.parse = parse$1; +parenthesis.stringify = stringify$1; +var parenthesis_1 = parenthesis; +var paren = parenthesis_1; +var stringSplitBy = function splitBy(string2, separator, o) { + if (string2 == null) throw Error("First argument should be a string"); + if (separator == null) throw Error("Separator should be a string or a RegExp"); + if (!o) o = {}; + else if (typeof o === "string" || Array.isArray(o)) { + o = { ignore: o }; + } + if (o.escape == null) o.escape = true; + if (o.ignore == null) o.ignore = ["[]", "()", "{}", "<>", '""', "''", "``", "“”", "«»"]; + else { + if (typeof o.ignore === "string") { + o.ignore = [o.ignore]; + } + o.ignore = o.ignore.map(function(pair) { + if (pair.length === 1) pair = pair + pair; + return pair; + }); + } + var tokens = paren.parse(string2, { flat: true, brackets: o.ignore }); + var str2 = tokens[0]; + var parts = str2.split(separator); + if (o.escape) { + var cleanParts = []; + for (var i = 0; i < parts.length; i++) { + var prev = parts[i]; + var part = parts[i + 1]; + if (prev[prev.length - 1] === "\\" && prev[prev.length - 2] !== "\\") { + cleanParts.push(prev + separator + part); + i++; + } else { + cleanParts.push(prev); + } + } + parts = cleanParts; + } + for (var i = 0; i < parts.length; i++) { + tokens[0] = parts[i]; + parts[i] = paren.stringify(tokens, { flat: true }); + } + return parts; +}; +const require$$0 = [ + "xx-small", + "x-small", + "small", + "medium", + "large", + "x-large", + "xx-large", + "larger", + "smaller" +]; +var sizes = require$$0; +var util = { + isSize: function isSize(value2) { + return /^[\d\.]/.test(value2) || value2.indexOf("/") !== -1 || sizes.indexOf(value2) !== -1; + } +}; +var unquote2 = unquote$1; +var globalKeywords = require$$2$1; +var systemFontKeywords = require$$3; +var fontWeightKeywords = require$$4; +var fontStyleKeywords = require$$5; +var fontStretchKeywords = require$$6; +var splitBy2 = stringSplitBy; +var isSize$1 = util.isSize; +var parse = parseFont; +var cache = parseFont.cache = {}; +function parseFont(value2) { + if (typeof value2 !== "string") throw new Error("Font argument must be a string."); + if (cache[value2]) return cache[value2]; + if (value2 === "") { + throw new Error("Cannot parse an empty string."); + } + if (systemFontKeywords.indexOf(value2) !== -1) { + return cache[value2] = { system: value2 }; + } + var font2 = { + style: "normal", + variant: "normal", + weight: "normal", + stretch: "normal", + lineHeight: "normal", + size: "1rem", + family: ["serif"] + }; + var tokens = splitBy2(value2, /\s+/); + var token; + while (token = tokens.shift()) { + if (globalKeywords.indexOf(token) !== -1) { + ["style", "variant", "weight", "stretch"].forEach(function(prop) { + font2[prop] = token; + }); + return cache[value2] = font2; + } + if (fontStyleKeywords.indexOf(token) !== -1) { + font2.style = token; + continue; + } + if (token === "normal" || token === "small-caps") { + font2.variant = token; + continue; + } + if (fontStretchKeywords.indexOf(token) !== -1) { + font2.stretch = token; + continue; + } + if (fontWeightKeywords.indexOf(token) !== -1) { + font2.weight = token; + continue; + } + if (isSize$1(token)) { + var parts = splitBy2(token, "/"); + font2.size = parts[0]; + if (parts[1] != null) { + font2.lineHeight = parseLineHeight(parts[1]); + } else if (tokens[0] === "/") { + tokens.shift(); + font2.lineHeight = parseLineHeight(tokens.shift()); + } + if (!tokens.length) { + throw new Error("Missing required font-family."); + } + font2.family = splitBy2(tokens.join(" "), /\s*,\s*/).map(unquote2); + return cache[value2] = font2; + } + throw new Error("Unknown or unsupported font token: " + token); + } + throw new Error("Missing required font-size."); +} +function parseLineHeight(value2) { + var parsed = parseFloat(value2); + if (parsed.toString() === value2) { + return parsed; + } + return value2; +} +var pick$2 = pickByAlias; +var isSize2 = util.isSize; +var globals = a2o(require$$2$1); +var systems = a2o(require$$3); +var weights = a2o(require$$4); +var styles = a2o(require$$5); +var stretches = a2o(require$$6); +var variants = { "normal": 1, "small-caps": 1 }; +var fams = { + "serif": 1, + "sans-serif": 1, + "monospace": 1, + "cursive": 1, + "fantasy": 1, + "system-ui": 1 +}; +var defaults$1 = { + size: "1rem", + family: "serif" +}; +var stringify = function stringifyFont(o) { + o = pick$2(o, { + style: "style fontstyle fontStyle font-style slope distinction", + variant: "variant font-variant fontVariant fontvariant var capitalization", + weight: "weight w font-weight fontWeight fontweight", + stretch: "stretch font-stretch fontStretch fontstretch width", + size: "size s font-size fontSize fontsize height em emSize", + lineHeight: "lh line-height lineHeight lineheight leading", + family: "font family fontFamily font-family fontfamily type typeface face", + system: "system reserved default global" + }); + if (o.system) { + if (o.system) verify(o.system, systems); + return o.system; + } + verify(o.style, styles); + verify(o.variant, variants); + verify(o.weight, weights); + verify(o.stretch, stretches); + if (o.size == null) o.size = defaults$1.size; + if (typeof o.size === "number") o.size += "px"; + if (!isSize2) throw Error("Bad size value `" + o.size + "`"); + if (!o.family) o.family = defaults$1.family; + if (Array.isArray(o.family)) { + if (!o.family.length) o.family = [defaults$1.family]; + o.family = o.family.map(function(f) { + return fams[f] ? f : '"' + f + '"'; + }).join(", "); + } + var result = []; + result.push(o.style); + if (o.variant !== o.style) result.push(o.variant); + if (o.weight !== o.variant && o.weight !== o.style) result.push(o.weight); + if (o.stretch !== o.weight && o.stretch !== o.variant && o.stretch !== o.style) result.push(o.stretch); + result.push(o.size + (o.lineHeight == null || o.lineHeight === "normal" || o.lineHeight + "" === "1" ? "" : "/" + o.lineHeight)); + result.push(o.family); + return result.filter(Boolean).join(" "); +}; +function verify(value2, values) { + if (value2 && !values[value2] && !globals[value2]) throw Error("Unknown keyword `" + value2 + "`"); + return value2; +} +function a2o(a) { + var o = {}; + for (var i = 0; i < a.length; i++) { + o[a[i]] = 1; + } + return o; +} +var cssFont = { + parse, + stringify +}; +var regl_unchecked = { exports: {} }; +(function(module2, exports2) { + (function(global, factory2) { + module2.exports = factory2(); + })(index$3.commonjsGlobal, function() { + var extend2 = function(base, opts) { + var keys = Object.keys(opts); + for (var i = 0; i < keys.length; ++i) { + base[keys[i]] = opts[keys[i]]; + } + return base; + }; + var VARIABLE_COUNTER = 0; + var DYN_FUNC = 0; + var DYN_CONSTANT = 5; + var DYN_ARRAY = 6; + function DynamicVariable(type, data) { + this.id = VARIABLE_COUNTER++; + this.type = type; + this.data = data; + } + function escapeStr(str2) { + return str2.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); + } + function splitParts(str2) { + if (str2.length === 0) { + return []; + } + var firstChar = str2.charAt(0); + var lastChar = str2.charAt(str2.length - 1); + if (str2.length > 1 && firstChar === lastChar && (firstChar === '"' || firstChar === "'")) { + return ['"' + escapeStr(str2.substr(1, str2.length - 2)) + '"']; + } + var parts = /\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str2); + if (parts) { + return splitParts(str2.substr(0, parts.index)).concat(splitParts(parts[1])).concat(splitParts(str2.substr(parts.index + parts[0].length))); + } + var subparts = str2.split("."); + if (subparts.length === 1) { + return ['"' + escapeStr(str2) + '"']; + } + var result = []; + for (var i = 0; i < subparts.length; ++i) { + result = result.concat(splitParts(subparts[i])); + } + return result; + } + function toAccessorString(str2) { + return "[" + splitParts(str2).join("][") + "]"; + } + function defineDynamic(type, data) { + return new DynamicVariable(type, toAccessorString(data + "")); + } + function isDynamic(x) { + return typeof x === "function" && !x._reglType || x instanceof DynamicVariable; + } + function unbox(x, path) { + if (typeof x === "function") { + return new DynamicVariable(DYN_FUNC, x); + } else if (typeof x === "number" || typeof x === "boolean") { + return new DynamicVariable(DYN_CONSTANT, x); + } else if (Array.isArray(x)) { + return new DynamicVariable(DYN_ARRAY, x.map(function(y, i) { + return unbox(y); + })); + } else if (x instanceof DynamicVariable) { + return x; + } + } + var dynamic = { + DynamicVariable, + define: defineDynamic, + isDynamic, + unbox, + accessor: toAccessorString + }; + var raf = { + next: typeof requestAnimationFrame === "function" ? function(cb) { + return requestAnimationFrame(cb); + } : function(cb) { + return setTimeout(cb, 16); + }, + cancel: typeof cancelAnimationFrame === "function" ? function(raf2) { + return cancelAnimationFrame(raf2); + } : clearTimeout + }; + var clock = typeof performance !== "undefined" && performance.now ? function() { + return performance.now(); + } : function() { + return +/* @__PURE__ */ new Date(); + }; + function createStringStore() { + var stringIds = { "": 0 }; + var stringValues = [""]; + return { + id: function(str2) { + var result = stringIds[str2]; + if (result) { + return result; + } + result = stringIds[str2] = stringValues.length; + stringValues.push(str2); + return result; + }, + str: function(id) { + return stringValues[id]; + } + }; + } + function createCanvas2(element, onDone, pixelRatio) { + var canvas2 = document.createElement("canvas"); + extend2(canvas2.style, { + border: 0, + margin: 0, + padding: 0, + top: 0, + left: 0, + width: "100%", + height: "100%" + }); + element.appendChild(canvas2); + if (element === document.body) { + canvas2.style.position = "absolute"; + extend2(element.style, { + margin: 0, + padding: 0 + }); + } + function resize2() { + var w = window.innerWidth; + var h = window.innerHeight; + if (element !== document.body) { + var bounds = canvas2.getBoundingClientRect(); + w = bounds.right - bounds.left; + h = bounds.bottom - bounds.top; + } + canvas2.width = pixelRatio * w; + canvas2.height = pixelRatio * h; + } + var resizeObserver; + if (element !== document.body && typeof ResizeObserver === "function") { + resizeObserver = new ResizeObserver(function() { + setTimeout(resize2); + }); + resizeObserver.observe(element); + } else { + window.addEventListener("resize", resize2, false); + } + function onDestroy() { + if (resizeObserver) { + resizeObserver.disconnect(); + } else { + window.removeEventListener("resize", resize2); + } + element.removeChild(canvas2); + } + resize2(); + return { + canvas: canvas2, + onDestroy + }; + } + function createContext(canvas2, contextAttributes) { + function get3(name2) { + try { + return canvas2.getContext(name2, contextAttributes); + } catch (e) { + return null; + } + } + return get3("webgl") || get3("experimental-webgl") || get3("webgl-experimental"); + } + function isHTMLElement(obj) { + return typeof obj.nodeName === "string" && typeof obj.appendChild === "function" && typeof obj.getBoundingClientRect === "function"; + } + function isWebGLContext(obj) { + return typeof obj.drawArrays === "function" || typeof obj.drawElements === "function"; + } + function parseExtensions(input) { + if (typeof input === "string") { + return input.split(); + } + return input; + } + function getElement(desc) { + if (typeof desc === "string") { + return document.querySelector(desc); + } + return desc; + } + function parseArgs(args_) { + var args = args_ || {}; + var element, container, canvas2, gl; + var contextAttributes = {}; + var extensions = []; + var optionalExtensions = []; + var pixelRatio = typeof window === "undefined" ? 1 : window.devicePixelRatio; + var profile = false; + var cachedCode = {}; + var onDone = function(err) { + }; + var onDestroy = function() { + }; + if (typeof args === "string") { + element = document.querySelector(args); + } else if (typeof args === "object") { + if (isHTMLElement(args)) { + element = args; + } else if (isWebGLContext(args)) { + gl = args; + canvas2 = gl.canvas; + } else { + if ("gl" in args) { + gl = args.gl; + } else if ("canvas" in args) { + canvas2 = getElement(args.canvas); + } else if ("container" in args) { + container = getElement(args.container); + } + if ("attributes" in args) { + contextAttributes = args.attributes; + } + if ("extensions" in args) { + extensions = parseExtensions(args.extensions); + } + if ("optionalExtensions" in args) { + optionalExtensions = parseExtensions(args.optionalExtensions); + } + if ("onDone" in args) { + onDone = args.onDone; + } + if ("profile" in args) { + profile = !!args.profile; + } + if ("pixelRatio" in args) { + pixelRatio = +args.pixelRatio; + } + if ("cachedCode" in args) { + cachedCode = args.cachedCode; + } + } + } else ; + if (element) { + if (element.nodeName.toLowerCase() === "canvas") { + canvas2 = element; + } else { + container = element; + } + } + if (!gl) { + if (!canvas2) { + var result = createCanvas2(container || document.body, onDone, pixelRatio); + if (!result) { + return null; + } + canvas2 = result.canvas; + onDestroy = result.onDestroy; + } + if (contextAttributes.premultipliedAlpha === void 0) contextAttributes.premultipliedAlpha = true; + gl = createContext(canvas2, contextAttributes); + } + if (!gl) { + onDestroy(); + onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"); + return null; + } + return { + gl, + canvas: canvas2, + container, + extensions, + optionalExtensions, + pixelRatio, + profile, + cachedCode, + onDone, + onDestroy + }; + } + function createExtensionCache(gl, config) { + var extensions = {}; + function tryLoadExtension(name_) { + var name3 = name_.toLowerCase(); + var ext; + try { + ext = extensions[name3] = gl.getExtension(name3); + } catch (e) { + } + return !!ext; + } + for (var i = 0; i < config.extensions.length; ++i) { + var name2 = config.extensions[i]; + if (!tryLoadExtension(name2)) { + config.onDestroy(); + config.onDone('"' + name2 + '" extension is not supported by the current WebGL context, try upgrading your system or a different browser'); + return null; + } + } + config.optionalExtensions.forEach(tryLoadExtension); + return { + extensions, + restore: function() { + Object.keys(extensions).forEach(function(name3) { + if (extensions[name3] && !tryLoadExtension(name3)) { + throw new Error("(regl): error restoring extension " + name3); + } + }); + } + }; + } + function loop(n, f) { + var result = Array(n); + for (var i = 0; i < n; ++i) { + result[i] = f(i); + } + return result; + } + var GL_BYTE = 5120; + var GL_UNSIGNED_BYTE$1 = 5121; + var GL_SHORT = 5122; + var GL_UNSIGNED_SHORT = 5123; + var GL_INT = 5124; + var GL_UNSIGNED_INT = 5125; + var GL_FLOAT$1 = 5126; + function nextPow16(v) { + for (var i = 16; i <= 1 << 28; i *= 16) { + if (v <= i) { + return i; + } + } + return 0; + } + function log22(v) { + var r, shift; + r = (v > 65535) << 4; + v >>>= r; + shift = (v > 255) << 3; + v >>>= shift; + r |= shift; + shift = (v > 15) << 2; + v >>>= shift; + r |= shift; + shift = (v > 3) << 1; + v >>>= shift; + r |= shift; + return r | v >> 1; + } + function createPool() { + var bufferPool = loop(8, function() { + return []; + }); + function alloc(n) { + var sz = nextPow16(n); + var bin = bufferPool[log22(sz) >> 2]; + if (bin.length > 0) { + return bin.pop(); + } + return new ArrayBuffer(sz); + } + function free2(buf) { + bufferPool[log22(buf.byteLength) >> 2].push(buf); + } + function allocType(type, n) { + var result = null; + switch (type) { + case GL_BYTE: + result = new Int8Array(alloc(n), 0, n); + break; + case GL_UNSIGNED_BYTE$1: + result = new Uint8Array(alloc(n), 0, n); + break; + case GL_SHORT: + result = new Int16Array(alloc(2 * n), 0, n); + break; + case GL_UNSIGNED_SHORT: + result = new Uint16Array(alloc(2 * n), 0, n); + break; + case GL_INT: + result = new Int32Array(alloc(4 * n), 0, n); + break; + case GL_UNSIGNED_INT: + result = new Uint32Array(alloc(4 * n), 0, n); + break; + case GL_FLOAT$1: + result = new Float32Array(alloc(4 * n), 0, n); + break; + default: + return null; + } + if (result.length !== n) { + return result.subarray(0, n); + } + return result; + } + function freeType(array2) { + free2(array2.buffer); + } + return { + alloc, + free: free2, + allocType, + freeType + }; + } + var pool2 = createPool(); + pool2.zero = createPool(); + var GL_SUBPIXEL_BITS = 3408; + var GL_RED_BITS = 3410; + var GL_GREEN_BITS = 3411; + var GL_BLUE_BITS = 3412; + var GL_ALPHA_BITS = 3413; + var GL_DEPTH_BITS = 3414; + var GL_STENCIL_BITS = 3415; + var GL_ALIASED_POINT_SIZE_RANGE = 33901; + var GL_ALIASED_LINE_WIDTH_RANGE = 33902; + var GL_MAX_TEXTURE_SIZE = 3379; + var GL_MAX_VIEWPORT_DIMS = 3386; + var GL_MAX_VERTEX_ATTRIBS = 34921; + var GL_MAX_VERTEX_UNIFORM_VECTORS = 36347; + var GL_MAX_VARYING_VECTORS = 36348; + var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661; + var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660; + var GL_MAX_TEXTURE_IMAGE_UNITS = 34930; + var GL_MAX_FRAGMENT_UNIFORM_VECTORS = 36349; + var GL_MAX_CUBE_MAP_TEXTURE_SIZE = 34076; + var GL_MAX_RENDERBUFFER_SIZE = 34024; + var GL_VENDOR = 7936; + var GL_RENDERER = 7937; + var GL_VERSION = 7938; + var GL_SHADING_LANGUAGE_VERSION = 35724; + var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 34047; + var GL_MAX_COLOR_ATTACHMENTS_WEBGL = 36063; + var GL_MAX_DRAW_BUFFERS_WEBGL = 34852; + var GL_TEXTURE_2D = 3553; + var GL_TEXTURE_CUBE_MAP = 34067; + var GL_TEXTURE_CUBE_MAP_POSITIVE_X = 34069; + var GL_TEXTURE0 = 33984; + var GL_RGBA = 6408; + var GL_FLOAT = 5126; + var GL_UNSIGNED_BYTE = 5121; + var GL_FRAMEBUFFER = 36160; + var GL_FRAMEBUFFER_COMPLETE = 36053; + var GL_COLOR_ATTACHMENT0 = 36064; + var GL_COLOR_BUFFER_BIT$1 = 16384; + var wrapLimits = function(gl, extensions) { + var maxAnisotropic = 1; + if (extensions.ext_texture_filter_anisotropic) { + maxAnisotropic = gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); + } + var maxDrawbuffers = 1; + var maxColorAttachments = 1; + if (extensions.webgl_draw_buffers) { + maxDrawbuffers = gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL); + maxColorAttachments = gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL); + } + var readFloat = !!extensions.oes_texture_float; + if (readFloat) { + var readFloatTexture = gl.createTexture(); + gl.bindTexture(GL_TEXTURE_2D, readFloatTexture); + gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, null); + var fbo = gl.createFramebuffer(); + gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); + gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, readFloatTexture, 0); + gl.bindTexture(GL_TEXTURE_2D, null); + if (gl.checkFramebufferStatus(GL_FRAMEBUFFER) !== GL_FRAMEBUFFER_COMPLETE) readFloat = false; + else { + gl.viewport(0, 0, 1, 1); + gl.clearColor(1, 0, 0, 1); + gl.clear(GL_COLOR_BUFFER_BIT$1); + var pixels = pool2.allocType(GL_FLOAT, 4); + gl.readPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT, pixels); + if (gl.getError()) readFloat = false; + else { + gl.deleteFramebuffer(fbo); + gl.deleteTexture(readFloatTexture); + readFloat = pixels[0] === 1; + } + pool2.freeType(pixels); + } + } + var isIE = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion) || /Edge/.test(navigator.userAgent)); + var npotTextureCube = true; + if (!isIE) { + var cubeTexture = gl.createTexture(); + var data = pool2.allocType(GL_UNSIGNED_BYTE, 36); + gl.activeTexture(GL_TEXTURE0); + gl.bindTexture(GL_TEXTURE_CUBE_MAP, cubeTexture); + gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); + pool2.freeType(data); + gl.bindTexture(GL_TEXTURE_CUBE_MAP, null); + gl.deleteTexture(cubeTexture); + npotTextureCube = !gl.getError(); + } + return { + // drawing buffer bit depth + colorBits: [ + gl.getParameter(GL_RED_BITS), + gl.getParameter(GL_GREEN_BITS), + gl.getParameter(GL_BLUE_BITS), + gl.getParameter(GL_ALPHA_BITS) + ], + depthBits: gl.getParameter(GL_DEPTH_BITS), + stencilBits: gl.getParameter(GL_STENCIL_BITS), + subpixelBits: gl.getParameter(GL_SUBPIXEL_BITS), + // supported extensions + extensions: Object.keys(extensions).filter(function(ext) { + return !!extensions[ext]; + }), + // max aniso samples + maxAnisotropic, + // max draw buffers + maxDrawbuffers, + maxColorAttachments, + // point and line size ranges + pointSizeDims: gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE), + lineWidthDims: gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE), + maxViewportDims: gl.getParameter(GL_MAX_VIEWPORT_DIMS), + maxCombinedTextureUnits: gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS), + maxCubeMapSize: gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE), + maxRenderbufferSize: gl.getParameter(GL_MAX_RENDERBUFFER_SIZE), + maxTextureUnits: gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS), + maxTextureSize: gl.getParameter(GL_MAX_TEXTURE_SIZE), + maxAttributes: gl.getParameter(GL_MAX_VERTEX_ATTRIBS), + maxVertexUniforms: gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS), + maxVertexTextureUnits: gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS), + maxVaryingVectors: gl.getParameter(GL_MAX_VARYING_VECTORS), + maxFragmentUniforms: gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS), + // vendor info + glsl: gl.getParameter(GL_SHADING_LANGUAGE_VERSION), + renderer: gl.getParameter(GL_RENDERER), + vendor: gl.getParameter(GL_VENDOR), + version: gl.getParameter(GL_VERSION), + // quirks + readFloat, + npotTextureCube + }; + }; + var isTypedArray2 = function(x) { + return x instanceof Uint8Array || x instanceof Uint16Array || x instanceof Uint32Array || x instanceof Int8Array || x instanceof Int16Array || x instanceof Int32Array || x instanceof Float32Array || x instanceof Float64Array || x instanceof Uint8ClampedArray; + }; + function isNDArrayLike(obj) { + return !!obj && typeof obj === "object" && Array.isArray(obj.shape) && Array.isArray(obj.stride) && typeof obj.offset === "number" && obj.shape.length === obj.stride.length && (Array.isArray(obj.data) || isTypedArray2(obj.data)); + } + var values = function(obj) { + return Object.keys(obj).map(function(key) { + return obj[key]; + }); + }; + var flattenUtils = { + shape: arrayShape$1, + flatten: flattenArray + }; + function flatten1D(array2, nx, out) { + for (var i = 0; i < nx; ++i) { + out[i] = array2[i]; + } + } + function flatten2D(array2, nx, ny, out) { + var ptr = 0; + for (var i = 0; i < nx; ++i) { + var row = array2[i]; + for (var j = 0; j < ny; ++j) { + out[ptr++] = row[j]; + } + } + } + function flatten3D(array2, nx, ny, nz, out, ptr_) { + var ptr = ptr_; + for (var i = 0; i < nx; ++i) { + var row = array2[i]; + for (var j = 0; j < ny; ++j) { + var col = row[j]; + for (var k = 0; k < nz; ++k) { + out[ptr++] = col[k]; + } + } + } + } + function flattenRec(array2, shape, level, out, ptr) { + var stride = 1; + for (var i = level + 1; i < shape.length; ++i) { + stride *= shape[i]; + } + var n = shape[level]; + if (shape.length - level === 4) { + var nx = shape[level + 1]; + var ny = shape[level + 2]; + var nz = shape[level + 3]; + for (i = 0; i < n; ++i) { + flatten3D(array2[i], nx, ny, nz, out, ptr); + ptr += stride; + } + } else { + for (i = 0; i < n; ++i) { + flattenRec(array2[i], shape, level + 1, out, ptr); + ptr += stride; + } + } + } + function flattenArray(array2, shape, type, out_) { + var sz = 1; + if (shape.length) { + for (var i = 0; i < shape.length; ++i) { + sz *= shape[i]; + } + } else { + sz = 0; + } + var out = out_ || pool2.allocType(type, sz); + switch (shape.length) { + case 0: + break; + case 1: + flatten1D(array2, shape[0], out); + break; + case 2: + flatten2D(array2, shape[0], shape[1], out); + break; + case 3: + flatten3D(array2, shape[0], shape[1], shape[2], out, 0); + break; + default: + flattenRec(array2, shape, 0, out, 0); + } + return out; + } + function arrayShape$1(array_) { + var shape = []; + for (var array2 = array_; array2.length; array2 = array2[0]) { + shape.push(array2.length); + } + return shape; + } + var arrayTypes = { + "[object Int8Array]": 5120, + "[object Int16Array]": 5122, + "[object Int32Array]": 5124, + "[object Uint8Array]": 5121, + "[object Uint8ClampedArray]": 5121, + "[object Uint16Array]": 5123, + "[object Uint32Array]": 5125, + "[object Float32Array]": 5126, + "[object Float64Array]": 5121, + "[object ArrayBuffer]": 5121 + }; + var int8 = 5120; + var int16 = 5122; + var int32 = 5124; + var uint8 = 5121; + var uint16 = 5123; + var uint32 = 5125; + var float = 5126; + var float322 = 5126; + var glTypes = { + int8, + int16, + int32, + uint8, + uint16, + uint32, + float, + float32: float322 + }; + var dynamic$1 = 35048; + var stream = 35040; + var usageTypes = { + dynamic: dynamic$1, + stream, + "static": 35044 + }; + var arrayFlatten = flattenUtils.flatten; + var arrayShape = flattenUtils.shape; + var GL_STATIC_DRAW = 35044; + var GL_STREAM_DRAW = 35040; + var GL_UNSIGNED_BYTE$2 = 5121; + var GL_FLOAT$2 = 5126; + var DTYPES_SIZES = []; + DTYPES_SIZES[5120] = 1; + DTYPES_SIZES[5122] = 2; + DTYPES_SIZES[5124] = 4; + DTYPES_SIZES[5121] = 1; + DTYPES_SIZES[5123] = 2; + DTYPES_SIZES[5125] = 4; + DTYPES_SIZES[5126] = 4; + function typedArrayCode(data) { + return arrayTypes[Object.prototype.toString.call(data)] | 0; + } + function copyArray(out, inp) { + for (var i = 0; i < inp.length; ++i) { + out[i] = inp[i]; + } + } + function transpose2(result, data, shapeX, shapeY, strideX, strideY, offset) { + var ptr = 0; + for (var i = 0; i < shapeX; ++i) { + for (var j = 0; j < shapeY; ++j) { + result[ptr++] = data[strideX * i + strideY * j + offset]; + } + } + } + function wrapBufferState(gl, stats3, config, destroyBuffer) { + var bufferCount = 0; + var bufferSet = {}; + function REGLBuffer(type) { + this.id = bufferCount++; + this.buffer = gl.createBuffer(); + this.type = type; + this.usage = GL_STATIC_DRAW; + this.byteLength = 0; + this.dimension = 1; + this.dtype = GL_UNSIGNED_BYTE$2; + this.persistentData = null; + if (config.profile) { + this.stats = { size: 0 }; + } + } + REGLBuffer.prototype.bind = function() { + gl.bindBuffer(this.type, this.buffer); + }; + REGLBuffer.prototype.destroy = function() { + destroy2(this); + }; + var streamPool = []; + function createStream(type, data) { + var buffer2 = streamPool.pop(); + if (!buffer2) { + buffer2 = new REGLBuffer(type); + } + buffer2.bind(); + initBufferFromData(buffer2, data, GL_STREAM_DRAW, 0, 1, false); + return buffer2; + } + function destroyStream(stream$$1) { + streamPool.push(stream$$1); + } + function initBufferFromTypedArray(buffer2, data, usage) { + buffer2.byteLength = data.byteLength; + gl.bufferData(buffer2.type, data, usage); + } + function initBufferFromData(buffer2, data, usage, dtype2, dimension, persist) { + var shape; + buffer2.usage = usage; + if (Array.isArray(data)) { + buffer2.dtype = dtype2 || GL_FLOAT$2; + if (data.length > 0) { + var flatData; + if (Array.isArray(data[0])) { + shape = arrayShape(data); + var dim = 1; + for (var i = 1; i < shape.length; ++i) { + dim *= shape[i]; + } + buffer2.dimension = dim; + flatData = arrayFlatten(data, shape, buffer2.dtype); + initBufferFromTypedArray(buffer2, flatData, usage); + if (persist) { + buffer2.persistentData = flatData; + } else { + pool2.freeType(flatData); + } + } else if (typeof data[0] === "number") { + buffer2.dimension = dimension; + var typedData = pool2.allocType(buffer2.dtype, data.length); + copyArray(typedData, data); + initBufferFromTypedArray(buffer2, typedData, usage); + if (persist) { + buffer2.persistentData = typedData; + } else { + pool2.freeType(typedData); + } + } else if (isTypedArray2(data[0])) { + buffer2.dimension = data[0].length; + buffer2.dtype = dtype2 || typedArrayCode(data[0]) || GL_FLOAT$2; + flatData = arrayFlatten( + data, + [data.length, data[0].length], + buffer2.dtype + ); + initBufferFromTypedArray(buffer2, flatData, usage); + if (persist) { + buffer2.persistentData = flatData; + } else { + pool2.freeType(flatData); + } + } else ; + } + } else if (isTypedArray2(data)) { + buffer2.dtype = dtype2 || typedArrayCode(data); + buffer2.dimension = dimension; + initBufferFromTypedArray(buffer2, data, usage); + if (persist) { + buffer2.persistentData = new Uint8Array(new Uint8Array(data.buffer)); + } + } else if (isNDArrayLike(data)) { + shape = data.shape; + var stride = data.stride; + var offset = data.offset; + var shapeX = 0; + var shapeY = 0; + var strideX = 0; + var strideY = 0; + if (shape.length === 1) { + shapeX = shape[0]; + shapeY = 1; + strideX = stride[0]; + strideY = 0; + } else if (shape.length === 2) { + shapeX = shape[0]; + shapeY = shape[1]; + strideX = stride[0]; + strideY = stride[1]; + } else ; + buffer2.dtype = dtype2 || typedArrayCode(data.data) || GL_FLOAT$2; + buffer2.dimension = shapeY; + var transposeData2 = pool2.allocType(buffer2.dtype, shapeX * shapeY); + transpose2( + transposeData2, + data.data, + shapeX, + shapeY, + strideX, + strideY, + offset + ); + initBufferFromTypedArray(buffer2, transposeData2, usage); + if (persist) { + buffer2.persistentData = transposeData2; + } else { + pool2.freeType(transposeData2); + } + } else if (data instanceof ArrayBuffer) { + buffer2.dtype = GL_UNSIGNED_BYTE$2; + buffer2.dimension = dimension; + initBufferFromTypedArray(buffer2, data, usage); + if (persist) { + buffer2.persistentData = new Uint8Array(new Uint8Array(data)); + } + } else ; + } + function destroy2(buffer2) { + stats3.bufferCount--; + destroyBuffer(buffer2); + var handle = buffer2.buffer; + gl.deleteBuffer(handle); + buffer2.buffer = null; + delete bufferSet[buffer2.id]; + } + function createBuffer(options, type, deferInit, persistent) { + stats3.bufferCount++; + var buffer2 = new REGLBuffer(type); + bufferSet[buffer2.id] = buffer2; + function reglBuffer(options2) { + var usage = GL_STATIC_DRAW; + var data = null; + var byteLength2 = 0; + var dtype2 = 0; + var dimension = 1; + if (Array.isArray(options2) || isTypedArray2(options2) || isNDArrayLike(options2) || options2 instanceof ArrayBuffer) { + data = options2; + } else if (typeof options2 === "number") { + byteLength2 = options2 | 0; + } else if (options2) { + if ("data" in options2) { + data = options2.data; + } + if ("usage" in options2) { + usage = usageTypes[options2.usage]; + } + if ("type" in options2) { + dtype2 = glTypes[options2.type]; + } + if ("dimension" in options2) { + dimension = options2.dimension | 0; + } + if ("length" in options2) { + byteLength2 = options2.length | 0; + } + } + buffer2.bind(); + if (!data) { + if (byteLength2) gl.bufferData(buffer2.type, byteLength2, usage); + buffer2.dtype = dtype2 || GL_UNSIGNED_BYTE$2; + buffer2.usage = usage; + buffer2.dimension = dimension; + buffer2.byteLength = byteLength2; + } else { + initBufferFromData(buffer2, data, usage, dtype2, dimension, persistent); + } + if (config.profile) { + buffer2.stats.size = buffer2.byteLength * DTYPES_SIZES[buffer2.dtype]; + } + return reglBuffer; + } + function setSubData(data, offset) { + gl.bufferSubData(buffer2.type, offset, data); + } + function subdata(data, offset_) { + var offset = (offset_ || 0) | 0; + var shape; + buffer2.bind(); + if (isTypedArray2(data) || data instanceof ArrayBuffer) { + setSubData(data, offset); + } else if (Array.isArray(data)) { + if (data.length > 0) { + if (typeof data[0] === "number") { + var converted = pool2.allocType(buffer2.dtype, data.length); + copyArray(converted, data); + setSubData(converted, offset); + pool2.freeType(converted); + } else if (Array.isArray(data[0]) || isTypedArray2(data[0])) { + shape = arrayShape(data); + var flatData = arrayFlatten(data, shape, buffer2.dtype); + setSubData(flatData, offset); + pool2.freeType(flatData); + } else ; + } + } else if (isNDArrayLike(data)) { + shape = data.shape; + var stride = data.stride; + var shapeX = 0; + var shapeY = 0; + var strideX = 0; + var strideY = 0; + if (shape.length === 1) { + shapeX = shape[0]; + shapeY = 1; + strideX = stride[0]; + strideY = 0; + } else if (shape.length === 2) { + shapeX = shape[0]; + shapeY = shape[1]; + strideX = stride[0]; + strideY = stride[1]; + } else ; + var dtype2 = Array.isArray(data.data) ? buffer2.dtype : typedArrayCode(data.data); + var transposeData2 = pool2.allocType(dtype2, shapeX * shapeY); + transpose2( + transposeData2, + data.data, + shapeX, + shapeY, + strideX, + strideY, + data.offset + ); + setSubData(transposeData2, offset); + pool2.freeType(transposeData2); + } else ; + return reglBuffer; + } + if (!deferInit) { + reglBuffer(options); + } + reglBuffer._reglType = "buffer"; + reglBuffer._buffer = buffer2; + reglBuffer.subdata = subdata; + if (config.profile) { + reglBuffer.stats = buffer2.stats; + } + reglBuffer.destroy = function() { + destroy2(buffer2); + }; + return reglBuffer; + } + function restoreBuffers() { + values(bufferSet).forEach(function(buffer2) { + buffer2.buffer = gl.createBuffer(); + gl.bindBuffer(buffer2.type, buffer2.buffer); + gl.bufferData( + buffer2.type, + buffer2.persistentData || buffer2.byteLength, + buffer2.usage + ); + }); + } + if (config.profile) { + stats3.getTotalBufferSize = function() { + var total = 0; + Object.keys(bufferSet).forEach(function(key) { + total += bufferSet[key].stats.size; + }); + return total; + }; + } + return { + create: createBuffer, + createStream, + destroyStream, + clear: function() { + values(bufferSet).forEach(destroy2); + streamPool.forEach(destroy2); + }, + getBuffer: function(wrapper) { + if (wrapper && wrapper._buffer instanceof REGLBuffer) { + return wrapper._buffer; + } + return null; + }, + restore: restoreBuffers, + _initBuffer: initBufferFromData + }; + } + var points = 0; + var point = 0; + var lines = 1; + var line2 = 1; + var triangles = 4; + var triangle = 4; + var primTypes = { + points, + point, + lines, + line: line2, + triangles, + triangle, + "line loop": 2, + "line strip": 3, + "triangle strip": 5, + "triangle fan": 6 + }; + var GL_POINTS = 0; + var GL_LINES = 1; + var GL_TRIANGLES = 4; + var GL_BYTE$1 = 5120; + var GL_UNSIGNED_BYTE$3 = 5121; + var GL_SHORT$1 = 5122; + var GL_UNSIGNED_SHORT$1 = 5123; + var GL_INT$1 = 5124; + var GL_UNSIGNED_INT$1 = 5125; + var GL_ELEMENT_ARRAY_BUFFER = 34963; + var GL_STREAM_DRAW$1 = 35040; + var GL_STATIC_DRAW$1 = 35044; + function wrapElementsState(gl, extensions, bufferState, stats3) { + var elementSet = {}; + var elementCount = 0; + var elementTypes = { + "uint8": GL_UNSIGNED_BYTE$3, + "uint16": GL_UNSIGNED_SHORT$1 + }; + if (extensions.oes_element_index_uint) { + elementTypes.uint32 = GL_UNSIGNED_INT$1; + } + function REGLElementBuffer(buffer2) { + this.id = elementCount++; + elementSet[this.id] = this; + this.buffer = buffer2; + this.primType = GL_TRIANGLES; + this.vertCount = 0; + this.type = 0; + } + REGLElementBuffer.prototype.bind = function() { + this.buffer.bind(); + }; + var bufferPool = []; + function createElementStream(data) { + var result = bufferPool.pop(); + if (!result) { + result = new REGLElementBuffer(bufferState.create( + null, + GL_ELEMENT_ARRAY_BUFFER, + true, + false + )._buffer); + } + initElements(result, data, GL_STREAM_DRAW$1, -1, -1, 0, 0); + return result; + } + function destroyElementStream(elements) { + bufferPool.push(elements); + } + function initElements(elements, data, usage, prim, count2, byteLength2, type) { + elements.buffer.bind(); + var dtype2; + if (data) { + var predictedType = type; + if (!type && (!isTypedArray2(data) || isNDArrayLike(data) && !isTypedArray2(data.data))) { + predictedType = extensions.oes_element_index_uint ? GL_UNSIGNED_INT$1 : GL_UNSIGNED_SHORT$1; + } + bufferState._initBuffer( + elements.buffer, + data, + usage, + predictedType, + 3 + ); + } else { + gl.bufferData(GL_ELEMENT_ARRAY_BUFFER, byteLength2, usage); + elements.buffer.dtype = dtype2 || GL_UNSIGNED_BYTE$3; + elements.buffer.usage = usage; + elements.buffer.dimension = 3; + elements.buffer.byteLength = byteLength2; + } + dtype2 = type; + if (!type) { + switch (elements.buffer.dtype) { + case GL_UNSIGNED_BYTE$3: + case GL_BYTE$1: + dtype2 = GL_UNSIGNED_BYTE$3; + break; + case GL_UNSIGNED_SHORT$1: + case GL_SHORT$1: + dtype2 = GL_UNSIGNED_SHORT$1; + break; + case GL_UNSIGNED_INT$1: + case GL_INT$1: + dtype2 = GL_UNSIGNED_INT$1; + break; + } + elements.buffer.dtype = dtype2; + } + elements.type = dtype2; + var vertCount = count2; + if (vertCount < 0) { + vertCount = elements.buffer.byteLength; + if (dtype2 === GL_UNSIGNED_SHORT$1) { + vertCount >>= 1; + } else if (dtype2 === GL_UNSIGNED_INT$1) { + vertCount >>= 2; + } + } + elements.vertCount = vertCount; + var primType = prim; + if (prim < 0) { + primType = GL_TRIANGLES; + var dimension = elements.buffer.dimension; + if (dimension === 1) primType = GL_POINTS; + if (dimension === 2) primType = GL_LINES; + if (dimension === 3) primType = GL_TRIANGLES; + } + elements.primType = primType; + } + function destroyElements(elements) { + stats3.elementsCount--; + delete elementSet[elements.id]; + elements.buffer.destroy(); + elements.buffer = null; + } + function createElements(options, persistent) { + var buffer2 = bufferState.create(null, GL_ELEMENT_ARRAY_BUFFER, true); + var elements = new REGLElementBuffer(buffer2._buffer); + stats3.elementsCount++; + function reglElements(options2) { + if (!options2) { + buffer2(); + elements.primType = GL_TRIANGLES; + elements.vertCount = 0; + elements.type = GL_UNSIGNED_BYTE$3; + } else if (typeof options2 === "number") { + buffer2(options2); + elements.primType = GL_TRIANGLES; + elements.vertCount = options2 | 0; + elements.type = GL_UNSIGNED_BYTE$3; + } else { + var data = null; + var usage = GL_STATIC_DRAW$1; + var primType = -1; + var vertCount = -1; + var byteLength2 = 0; + var dtype2 = 0; + if (Array.isArray(options2) || isTypedArray2(options2) || isNDArrayLike(options2)) { + data = options2; + } else { + if ("data" in options2) { + data = options2.data; + } + if ("usage" in options2) { + usage = usageTypes[options2.usage]; + } + if ("primitive" in options2) { + primType = primTypes[options2.primitive]; + } + if ("count" in options2) { + vertCount = options2.count | 0; + } + if ("type" in options2) { + dtype2 = elementTypes[options2.type]; + } + if ("length" in options2) { + byteLength2 = options2.length | 0; + } else { + byteLength2 = vertCount; + if (dtype2 === GL_UNSIGNED_SHORT$1 || dtype2 === GL_SHORT$1) { + byteLength2 *= 2; + } else if (dtype2 === GL_UNSIGNED_INT$1 || dtype2 === GL_INT$1) { + byteLength2 *= 4; + } + } + } + initElements( + elements, + data, + usage, + primType, + vertCount, + byteLength2, + dtype2 + ); + } + return reglElements; + } + reglElements(options); + reglElements._reglType = "elements"; + reglElements._elements = elements; + reglElements.subdata = function(data, offset) { + buffer2.subdata(data, offset); + return reglElements; + }; + reglElements.destroy = function() { + destroyElements(elements); + }; + return reglElements; + } + return { + create: createElements, + createStream: createElementStream, + destroyStream: destroyElementStream, + getElements: function(elements) { + if (typeof elements === "function" && elements._elements instanceof REGLElementBuffer) { + return elements._elements; + } + return null; + }, + clear: function() { + values(elementSet).forEach(destroyElements); + } + }; + } + var FLOAT = new Float32Array(1); + var INT = new Uint32Array(FLOAT.buffer); + var GL_UNSIGNED_SHORT$3 = 5123; + function convertToHalfFloat(array2) { + var ushorts = pool2.allocType(GL_UNSIGNED_SHORT$3, array2.length); + for (var i = 0; i < array2.length; ++i) { + if (isNaN(array2[i])) { + ushorts[i] = 65535; + } else if (array2[i] === Infinity) { + ushorts[i] = 31744; + } else if (array2[i] === -Infinity) { + ushorts[i] = 64512; + } else { + FLOAT[0] = array2[i]; + var x = INT[0]; + var sgn = x >>> 31 << 15; + var exp = (x << 1 >>> 24) - 127; + var frac = x >> 13 & (1 << 10) - 1; + if (exp < -24) { + ushorts[i] = sgn; + } else if (exp < -14) { + var s = -14 - exp; + ushorts[i] = sgn + (frac + (1 << 10) >> s); + } else if (exp > 15) { + ushorts[i] = sgn + 31744; + } else { + ushorts[i] = sgn + (exp + 15 << 10) + frac; + } + } + } + return ushorts; + } + function isArrayLike(s) { + return Array.isArray(s) || isTypedArray2(s); + } + var GL_COMPRESSED_TEXTURE_FORMATS = 34467; + var GL_TEXTURE_2D$1 = 3553; + var GL_TEXTURE_CUBE_MAP$1 = 34067; + var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 = 34069; + var GL_RGBA$1 = 6408; + var GL_ALPHA = 6406; + var GL_RGB = 6407; + var GL_LUMINANCE = 6409; + var GL_LUMINANCE_ALPHA = 6410; + var GL_RGBA4 = 32854; + var GL_RGB5_A1 = 32855; + var GL_RGB565 = 36194; + var GL_UNSIGNED_SHORT_4_4_4_4 = 32819; + var GL_UNSIGNED_SHORT_5_5_5_1 = 32820; + var GL_UNSIGNED_SHORT_5_6_5 = 33635; + var GL_UNSIGNED_INT_24_8_WEBGL = 34042; + var GL_DEPTH_COMPONENT = 6402; + var GL_DEPTH_STENCIL = 34041; + var GL_SRGB_EXT = 35904; + var GL_SRGB_ALPHA_EXT = 35906; + var GL_HALF_FLOAT_OES = 36193; + var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 33776; + var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777; + var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778; + var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779; + var GL_COMPRESSED_RGB_ATC_WEBGL = 35986; + var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 35987; + var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 34798; + var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 35840; + var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 35841; + var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 35842; + var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 35843; + var GL_COMPRESSED_RGB_ETC1_WEBGL = 36196; + var GL_UNSIGNED_BYTE$4 = 5121; + var GL_UNSIGNED_SHORT$2 = 5123; + var GL_UNSIGNED_INT$2 = 5125; + var GL_FLOAT$3 = 5126; + var GL_TEXTURE_WRAP_S = 10242; + var GL_TEXTURE_WRAP_T = 10243; + var GL_REPEAT = 10497; + var GL_CLAMP_TO_EDGE = 33071; + var GL_MIRRORED_REPEAT = 33648; + var GL_TEXTURE_MAG_FILTER = 10240; + var GL_TEXTURE_MIN_FILTER = 10241; + var GL_NEAREST = 9728; + var GL_LINEAR = 9729; + var GL_NEAREST_MIPMAP_NEAREST = 9984; + var GL_LINEAR_MIPMAP_NEAREST = 9985; + var GL_NEAREST_MIPMAP_LINEAR = 9986; + var GL_LINEAR_MIPMAP_LINEAR = 9987; + var GL_GENERATE_MIPMAP_HINT = 33170; + var GL_DONT_CARE = 4352; + var GL_FASTEST = 4353; + var GL_NICEST = 4354; + var GL_TEXTURE_MAX_ANISOTROPY_EXT = 34046; + var GL_UNPACK_ALIGNMENT = 3317; + var GL_UNPACK_FLIP_Y_WEBGL = 37440; + var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 37441; + var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 37443; + var GL_BROWSER_DEFAULT_WEBGL = 37444; + var GL_TEXTURE0$1 = 33984; + var MIPMAP_FILTERS = [ + GL_NEAREST_MIPMAP_NEAREST, + GL_NEAREST_MIPMAP_LINEAR, + GL_LINEAR_MIPMAP_NEAREST, + GL_LINEAR_MIPMAP_LINEAR + ]; + var CHANNELS_FORMAT = [ + 0, + GL_LUMINANCE, + GL_LUMINANCE_ALPHA, + GL_RGB, + GL_RGBA$1 + ]; + var FORMAT_CHANNELS = {}; + FORMAT_CHANNELS[GL_LUMINANCE] = FORMAT_CHANNELS[GL_ALPHA] = FORMAT_CHANNELS[GL_DEPTH_COMPONENT] = 1; + FORMAT_CHANNELS[GL_DEPTH_STENCIL] = FORMAT_CHANNELS[GL_LUMINANCE_ALPHA] = 2; + FORMAT_CHANNELS[GL_RGB] = FORMAT_CHANNELS[GL_SRGB_EXT] = 3; + FORMAT_CHANNELS[GL_RGBA$1] = FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT] = 4; + function objectName(str2) { + return "[object " + str2 + "]"; + } + var CANVAS_CLASS = objectName("HTMLCanvasElement"); + var OFFSCREENCANVAS_CLASS = objectName("OffscreenCanvas"); + var CONTEXT2D_CLASS = objectName("CanvasRenderingContext2D"); + var BITMAP_CLASS = objectName("ImageBitmap"); + var IMAGE_CLASS = objectName("HTMLImageElement"); + var VIDEO_CLASS = objectName("HTMLVideoElement"); + var PIXEL_CLASSES = Object.keys(arrayTypes).concat([ + CANVAS_CLASS, + OFFSCREENCANVAS_CLASS, + CONTEXT2D_CLASS, + BITMAP_CLASS, + IMAGE_CLASS, + VIDEO_CLASS + ]); + var TYPE_SIZES = []; + TYPE_SIZES[GL_UNSIGNED_BYTE$4] = 1; + TYPE_SIZES[GL_FLOAT$3] = 4; + TYPE_SIZES[GL_HALF_FLOAT_OES] = 2; + TYPE_SIZES[GL_UNSIGNED_SHORT$2] = 2; + TYPE_SIZES[GL_UNSIGNED_INT$2] = 4; + var FORMAT_SIZES_SPECIAL = []; + FORMAT_SIZES_SPECIAL[GL_RGBA4] = 2; + FORMAT_SIZES_SPECIAL[GL_RGB5_A1] = 2; + FORMAT_SIZES_SPECIAL[GL_RGB565] = 2; + FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL] = 4; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL] = 0.5; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25; + FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL] = 0.5; + function isNumericArray(arr) { + return Array.isArray(arr) && (arr.length === 0 || typeof arr[0] === "number"); + } + function isRectArray(arr) { + if (!Array.isArray(arr)) { + return false; + } + var width = arr.length; + if (width === 0 || !isArrayLike(arr[0])) { + return false; + } + return true; + } + function classString(x) { + return Object.prototype.toString.call(x); + } + function isCanvasElement(object2) { + return classString(object2) === CANVAS_CLASS; + } + function isOffscreenCanvas(object2) { + return classString(object2) === OFFSCREENCANVAS_CLASS; + } + function isContext2D(object2) { + return classString(object2) === CONTEXT2D_CLASS; + } + function isBitmap(object2) { + return classString(object2) === BITMAP_CLASS; + } + function isImageElement(object2) { + return classString(object2) === IMAGE_CLASS; + } + function isVideoElement(object2) { + return classString(object2) === VIDEO_CLASS; + } + function isPixelData(object2) { + if (!object2) { + return false; + } + var className = classString(object2); + if (PIXEL_CLASSES.indexOf(className) >= 0) { + return true; + } + return isNumericArray(object2) || isRectArray(object2) || isNDArrayLike(object2); + } + function typedArrayCode$1(data) { + return arrayTypes[Object.prototype.toString.call(data)] | 0; + } + function convertData(result, data) { + var n = data.length; + switch (result.type) { + case GL_UNSIGNED_BYTE$4: + case GL_UNSIGNED_SHORT$2: + case GL_UNSIGNED_INT$2: + case GL_FLOAT$3: + var converted = pool2.allocType(result.type, n); + converted.set(data); + result.data = converted; + break; + case GL_HALF_FLOAT_OES: + result.data = convertToHalfFloat(data); + break; + } + } + function preConvert(image, n) { + return pool2.allocType( + image.type === GL_HALF_FLOAT_OES ? GL_FLOAT$3 : image.type, + n + ); + } + function postConvert(image, data) { + if (image.type === GL_HALF_FLOAT_OES) { + image.data = convertToHalfFloat(data); + pool2.freeType(data); + } else { + image.data = data; + } + } + function transposeData(image, array2, strideX, strideY, strideC, offset) { + var w = image.width; + var h = image.height; + var c = image.channels; + var n = w * h * c; + var data = preConvert(image, n); + var p = 0; + for (var i = 0; i < h; ++i) { + for (var j = 0; j < w; ++j) { + for (var k = 0; k < c; ++k) { + data[p++] = array2[strideX * j + strideY * i + strideC * k + offset]; + } + } + } + postConvert(image, data); + } + function getTextureSize(format2, type, width, height, isMipmap, isCube) { + var s; + if (typeof FORMAT_SIZES_SPECIAL[format2] !== "undefined") { + s = FORMAT_SIZES_SPECIAL[format2]; + } else { + s = FORMAT_CHANNELS[format2] * TYPE_SIZES[type]; + } + if (isCube) { + s *= 6; + } + if (isMipmap) { + var total = 0; + var w = width; + while (w >= 1) { + total += s * w * w; + w /= 2; + } + return total; + } else { + return s * width * height; + } + } + function createTextureSet(gl, extensions, limits, reglPoll, contextState, stats3, config) { + var mipmapHint = { + "don't care": GL_DONT_CARE, + "dont care": GL_DONT_CARE, + "nice": GL_NICEST, + "fast": GL_FASTEST + }; + var wrapModes = { + "repeat": GL_REPEAT, + "clamp": GL_CLAMP_TO_EDGE, + "mirror": GL_MIRRORED_REPEAT + }; + var magFilters = { + "nearest": GL_NEAREST, + "linear": GL_LINEAR + }; + var minFilters = extend2({ + "mipmap": GL_LINEAR_MIPMAP_LINEAR, + "nearest mipmap nearest": GL_NEAREST_MIPMAP_NEAREST, + "linear mipmap nearest": GL_LINEAR_MIPMAP_NEAREST, + "nearest mipmap linear": GL_NEAREST_MIPMAP_LINEAR, + "linear mipmap linear": GL_LINEAR_MIPMAP_LINEAR + }, magFilters); + var colorSpace = { + "none": 0, + "browser": GL_BROWSER_DEFAULT_WEBGL + }; + var textureTypes = { + "uint8": GL_UNSIGNED_BYTE$4, + "rgba4": GL_UNSIGNED_SHORT_4_4_4_4, + "rgb565": GL_UNSIGNED_SHORT_5_6_5, + "rgb5 a1": GL_UNSIGNED_SHORT_5_5_5_1 + }; + var textureFormats = { + "alpha": GL_ALPHA, + "luminance": GL_LUMINANCE, + "luminance alpha": GL_LUMINANCE_ALPHA, + "rgb": GL_RGB, + "rgba": GL_RGBA$1, + "rgba4": GL_RGBA4, + "rgb5 a1": GL_RGB5_A1, + "rgb565": GL_RGB565 + }; + var compressedTextureFormats = {}; + if (extensions.ext_srgb) { + textureFormats.srgb = GL_SRGB_EXT; + textureFormats.srgba = GL_SRGB_ALPHA_EXT; + } + if (extensions.oes_texture_float) { + textureTypes.float32 = textureTypes.float = GL_FLOAT$3; + } + if (extensions.oes_texture_half_float) { + textureTypes["float16"] = textureTypes["half float"] = GL_HALF_FLOAT_OES; + } + if (extensions.webgl_depth_texture) { + extend2(textureFormats, { + "depth": GL_DEPTH_COMPONENT, + "depth stencil": GL_DEPTH_STENCIL + }); + extend2(textureTypes, { + "uint16": GL_UNSIGNED_SHORT$2, + "uint32": GL_UNSIGNED_INT$2, + "depth stencil": GL_UNSIGNED_INT_24_8_WEBGL + }); + } + if (extensions.webgl_compressed_texture_s3tc) { + extend2(compressedTextureFormats, { + "rgb s3tc dxt1": GL_COMPRESSED_RGB_S3TC_DXT1_EXT, + "rgba s3tc dxt1": GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, + "rgba s3tc dxt3": GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, + "rgba s3tc dxt5": GL_COMPRESSED_RGBA_S3TC_DXT5_EXT + }); + } + if (extensions.webgl_compressed_texture_atc) { + extend2(compressedTextureFormats, { + "rgb atc": GL_COMPRESSED_RGB_ATC_WEBGL, + "rgba atc explicit alpha": GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL, + "rgba atc interpolated alpha": GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL + }); + } + if (extensions.webgl_compressed_texture_pvrtc) { + extend2(compressedTextureFormats, { + "rgb pvrtc 4bppv1": GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, + "rgb pvrtc 2bppv1": GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, + "rgba pvrtc 4bppv1": GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, + "rgba pvrtc 2bppv1": GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG + }); + } + if (extensions.webgl_compressed_texture_etc1) { + compressedTextureFormats["rgb etc1"] = GL_COMPRESSED_RGB_ETC1_WEBGL; + } + var supportedCompressedFormats = Array.prototype.slice.call( + gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS) + ); + Object.keys(compressedTextureFormats).forEach(function(name2) { + var format2 = compressedTextureFormats[name2]; + if (supportedCompressedFormats.indexOf(format2) >= 0) { + textureFormats[name2] = format2; + } + }); + var supportedFormats = Object.keys(textureFormats); + limits.textureFormats = supportedFormats; + var textureFormatsInvert = []; + Object.keys(textureFormats).forEach(function(key) { + var val = textureFormats[key]; + textureFormatsInvert[val] = key; + }); + var textureTypesInvert = []; + Object.keys(textureTypes).forEach(function(key) { + var val = textureTypes[key]; + textureTypesInvert[val] = key; + }); + var magFiltersInvert = []; + Object.keys(magFilters).forEach(function(key) { + var val = magFilters[key]; + magFiltersInvert[val] = key; + }); + var minFiltersInvert = []; + Object.keys(minFilters).forEach(function(key) { + var val = minFilters[key]; + minFiltersInvert[val] = key; + }); + var wrapModesInvert = []; + Object.keys(wrapModes).forEach(function(key) { + var val = wrapModes[key]; + wrapModesInvert[val] = key; + }); + var colorFormats = supportedFormats.reduce(function(color2, key) { + var glenum = textureFormats[key]; + if (glenum === GL_LUMINANCE || glenum === GL_ALPHA || glenum === GL_LUMINANCE || glenum === GL_LUMINANCE_ALPHA || glenum === GL_DEPTH_COMPONENT || glenum === GL_DEPTH_STENCIL || extensions.ext_srgb && (glenum === GL_SRGB_EXT || glenum === GL_SRGB_ALPHA_EXT)) { + color2[glenum] = glenum; + } else if (glenum === GL_RGB5_A1 || key.indexOf("rgba") >= 0) { + color2[glenum] = GL_RGBA$1; + } else { + color2[glenum] = GL_RGB; + } + return color2; + }, {}); + function TexFlags() { + this.internalformat = GL_RGBA$1; + this.format = GL_RGBA$1; + this.type = GL_UNSIGNED_BYTE$4; + this.compressed = false; + this.premultiplyAlpha = false; + this.flipY = false; + this.unpackAlignment = 1; + this.colorSpace = GL_BROWSER_DEFAULT_WEBGL; + this.width = 0; + this.height = 0; + this.channels = 0; + } + function copyFlags(result, other) { + result.internalformat = other.internalformat; + result.format = other.format; + result.type = other.type; + result.compressed = other.compressed; + result.premultiplyAlpha = other.premultiplyAlpha; + result.flipY = other.flipY; + result.unpackAlignment = other.unpackAlignment; + result.colorSpace = other.colorSpace; + result.width = other.width; + result.height = other.height; + result.channels = other.channels; + } + function parseFlags(flags, options) { + if (typeof options !== "object" || !options) { + return; + } + if ("premultiplyAlpha" in options) { + flags.premultiplyAlpha = options.premultiplyAlpha; + } + if ("flipY" in options) { + flags.flipY = options.flipY; + } + if ("alignment" in options) { + flags.unpackAlignment = options.alignment; + } + if ("colorSpace" in options) { + flags.colorSpace = colorSpace[options.colorSpace]; + } + if ("type" in options) { + var type = options.type; + flags.type = textureTypes[type]; + } + var w = flags.width; + var h = flags.height; + var c = flags.channels; + var hasChannels = false; + if ("shape" in options) { + w = options.shape[0]; + h = options.shape[1]; + if (options.shape.length === 3) { + c = options.shape[2]; + hasChannels = true; + } + } else { + if ("radius" in options) { + w = h = options.radius; + } + if ("width" in options) { + w = options.width; + } + if ("height" in options) { + h = options.height; + } + if ("channels" in options) { + c = options.channels; + hasChannels = true; + } + } + flags.width = w | 0; + flags.height = h | 0; + flags.channels = c | 0; + var hasFormat = false; + if ("format" in options) { + var formatStr = options.format; + var internalformat = flags.internalformat = textureFormats[formatStr]; + flags.format = colorFormats[internalformat]; + if (formatStr in textureTypes) { + if (!("type" in options)) { + flags.type = textureTypes[formatStr]; + } + } + if (formatStr in compressedTextureFormats) { + flags.compressed = true; + } + hasFormat = true; + } + if (!hasChannels && hasFormat) { + flags.channels = FORMAT_CHANNELS[flags.format]; + } else if (hasChannels && !hasFormat) { + if (flags.channels !== CHANNELS_FORMAT[flags.format]) { + flags.format = flags.internalformat = CHANNELS_FORMAT[flags.channels]; + } + } else ; + } + function setFlags(flags) { + gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flags.flipY); + gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, flags.premultiplyAlpha); + gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL, flags.colorSpace); + gl.pixelStorei(GL_UNPACK_ALIGNMENT, flags.unpackAlignment); + } + function TexImage() { + TexFlags.call(this); + this.xOffset = 0; + this.yOffset = 0; + this.data = null; + this.needsFree = false; + this.element = null; + this.needsCopy = false; + } + function parseImage(image, options) { + var data = null; + if (isPixelData(options)) { + data = options; + } else if (options) { + parseFlags(image, options); + if ("x" in options) { + image.xOffset = options.x | 0; + } + if ("y" in options) { + image.yOffset = options.y | 0; + } + if (isPixelData(options.data)) { + data = options.data; + } + } + if (options.copy) { + var viewW = contextState.viewportWidth; + var viewH = contextState.viewportHeight; + image.width = image.width || viewW - image.xOffset; + image.height = image.height || viewH - image.yOffset; + image.needsCopy = true; + } else if (!data) { + image.width = image.width || 1; + image.height = image.height || 1; + image.channels = image.channels || 4; + } else if (isTypedArray2(data)) { + image.channels = image.channels || 4; + image.data = data; + if (!("type" in options) && image.type === GL_UNSIGNED_BYTE$4) { + image.type = typedArrayCode$1(data); + } + } else if (isNumericArray(data)) { + image.channels = image.channels || 4; + convertData(image, data); + image.alignment = 1; + image.needsFree = true; + } else if (isNDArrayLike(data)) { + var array2 = data.data; + if (!Array.isArray(array2) && image.type === GL_UNSIGNED_BYTE$4) { + image.type = typedArrayCode$1(array2); + } + var shape = data.shape; + var stride = data.stride; + var shapeX, shapeY, shapeC, strideX, strideY, strideC; + if (shape.length === 3) { + shapeC = shape[2]; + strideC = stride[2]; + } else { + shapeC = 1; + strideC = 1; + } + shapeX = shape[0]; + shapeY = shape[1]; + strideX = stride[0]; + strideY = stride[1]; + image.alignment = 1; + image.width = shapeX; + image.height = shapeY; + image.channels = shapeC; + image.format = image.internalformat = CHANNELS_FORMAT[shapeC]; + image.needsFree = true; + transposeData(image, array2, strideX, strideY, strideC, data.offset); + } else if (isCanvasElement(data) || isOffscreenCanvas(data) || isContext2D(data)) { + if (isCanvasElement(data) || isOffscreenCanvas(data)) { + image.element = data; + } else { + image.element = data.canvas; + } + image.width = image.element.width; + image.height = image.element.height; + image.channels = 4; + } else if (isBitmap(data)) { + image.element = data; + image.width = data.width; + image.height = data.height; + image.channels = 4; + } else if (isImageElement(data)) { + image.element = data; + image.width = data.naturalWidth; + image.height = data.naturalHeight; + image.channels = 4; + } else if (isVideoElement(data)) { + image.element = data; + image.width = data.videoWidth; + image.height = data.videoHeight; + image.channels = 4; + } else if (isRectArray(data)) { + var w = image.width || data[0].length; + var h = image.height || data.length; + var c = image.channels; + if (isArrayLike(data[0][0])) { + c = c || data[0][0].length; + } else { + c = c || 1; + } + var arrayShape2 = flattenUtils.shape(data); + var n = 1; + for (var dd = 0; dd < arrayShape2.length; ++dd) { + n *= arrayShape2[dd]; + } + var allocData = preConvert(image, n); + flattenUtils.flatten(data, arrayShape2, "", allocData); + postConvert(image, allocData); + image.alignment = 1; + image.width = w; + image.height = h; + image.channels = c; + image.format = image.internalformat = CHANNELS_FORMAT[c]; + image.needsFree = true; + } + if (image.type === GL_FLOAT$3) ; + else if (image.type === GL_HALF_FLOAT_OES) ; + } + function setImage(info, target, miplevel) { + var element = info.element; + var data = info.data; + var internalformat = info.internalformat; + var format2 = info.format; + var type = info.type; + var width = info.width; + var height = info.height; + setFlags(info); + if (element) { + gl.texImage2D(target, miplevel, format2, format2, type, element); + } else if (info.compressed) { + gl.compressedTexImage2D(target, miplevel, internalformat, width, height, 0, data); + } else if (info.needsCopy) { + reglPoll(); + gl.copyTexImage2D( + target, + miplevel, + format2, + info.xOffset, + info.yOffset, + width, + height, + 0 + ); + } else { + gl.texImage2D(target, miplevel, format2, width, height, 0, format2, type, data || null); + } + } + function setSubImage(info, target, x, y, miplevel) { + var element = info.element; + var data = info.data; + var internalformat = info.internalformat; + var format2 = info.format; + var type = info.type; + var width = info.width; + var height = info.height; + setFlags(info); + if (element) { + gl.texSubImage2D( + target, + miplevel, + x, + y, + format2, + type, + element + ); + } else if (info.compressed) { + gl.compressedTexSubImage2D( + target, + miplevel, + x, + y, + internalformat, + width, + height, + data + ); + } else if (info.needsCopy) { + reglPoll(); + gl.copyTexSubImage2D( + target, + miplevel, + x, + y, + info.xOffset, + info.yOffset, + width, + height + ); + } else { + gl.texSubImage2D( + target, + miplevel, + x, + y, + width, + height, + format2, + type, + data + ); + } + } + var imagePool = []; + function allocImage() { + return imagePool.pop() || new TexImage(); + } + function freeImage(image) { + if (image.needsFree) { + pool2.freeType(image.data); + } + TexImage.call(image); + imagePool.push(image); + } + function MipMap() { + TexFlags.call(this); + this.genMipmaps = false; + this.mipmapHint = GL_DONT_CARE; + this.mipmask = 0; + this.images = Array(16); + } + function parseMipMapFromShape(mipmap, width, height) { + var img = mipmap.images[0] = allocImage(); + mipmap.mipmask = 1; + img.width = mipmap.width = width; + img.height = mipmap.height = height; + img.channels = mipmap.channels = 4; + } + function parseMipMapFromObject(mipmap, options) { + var imgData = null; + if (isPixelData(options)) { + imgData = mipmap.images[0] = allocImage(); + copyFlags(imgData, mipmap); + parseImage(imgData, options); + mipmap.mipmask = 1; + } else { + parseFlags(mipmap, options); + if (Array.isArray(options.mipmap)) { + var mipData = options.mipmap; + for (var i = 0; i < mipData.length; ++i) { + imgData = mipmap.images[i] = allocImage(); + copyFlags(imgData, mipmap); + imgData.width >>= i; + imgData.height >>= i; + parseImage(imgData, mipData[i]); + mipmap.mipmask |= 1 << i; + } + } else { + imgData = mipmap.images[0] = allocImage(); + copyFlags(imgData, mipmap); + parseImage(imgData, options); + mipmap.mipmask = 1; + } + } + copyFlags(mipmap, mipmap.images[0]); + if (mipmap.compressed && (mipmap.internalformat === GL_COMPRESSED_RGB_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT3_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)) ; + } + function setMipMap(mipmap, target) { + var images2 = mipmap.images; + for (var i = 0; i < images2.length; ++i) { + if (!images2[i]) { + return; + } + setImage(images2[i], target, i); + } + } + var mipPool = []; + function allocMipMap() { + var result = mipPool.pop() || new MipMap(); + TexFlags.call(result); + result.mipmask = 0; + for (var i = 0; i < 16; ++i) { + result.images[i] = null; + } + return result; + } + function freeMipMap(mipmap) { + var images2 = mipmap.images; + for (var i = 0; i < images2.length; ++i) { + if (images2[i]) { + freeImage(images2[i]); + } + images2[i] = null; + } + mipPool.push(mipmap); + } + function TexInfo() { + this.minFilter = GL_NEAREST; + this.magFilter = GL_NEAREST; + this.wrapS = GL_CLAMP_TO_EDGE; + this.wrapT = GL_CLAMP_TO_EDGE; + this.anisotropic = 1; + this.genMipmaps = false; + this.mipmapHint = GL_DONT_CARE; + } + function parseTexInfo(info, options) { + if ("min" in options) { + var minFilter = options.min; + info.minFilter = minFilters[minFilter]; + if (MIPMAP_FILTERS.indexOf(info.minFilter) >= 0 && !("faces" in options)) { + info.genMipmaps = true; + } + } + if ("mag" in options) { + var magFilter = options.mag; + info.magFilter = magFilters[magFilter]; + } + var wrapS = info.wrapS; + var wrapT = info.wrapT; + if ("wrap" in options) { + var wrap = options.wrap; + if (typeof wrap === "string") { + wrapS = wrapT = wrapModes[wrap]; + } else if (Array.isArray(wrap)) { + wrapS = wrapModes[wrap[0]]; + wrapT = wrapModes[wrap[1]]; + } + } else { + if ("wrapS" in options) { + var optWrapS = options.wrapS; + wrapS = wrapModes[optWrapS]; + } + if ("wrapT" in options) { + var optWrapT = options.wrapT; + wrapT = wrapModes[optWrapT]; + } + } + info.wrapS = wrapS; + info.wrapT = wrapT; + if ("anisotropic" in options) { + options.anisotropic; + info.anisotropic = options.anisotropic; + } + if ("mipmap" in options) { + var hasMipMap = false; + switch (typeof options.mipmap) { + case "string": + info.mipmapHint = mipmapHint[options.mipmap]; + info.genMipmaps = true; + hasMipMap = true; + break; + case "boolean": + hasMipMap = info.genMipmaps = options.mipmap; + break; + case "object": + info.genMipmaps = false; + hasMipMap = true; + break; + } + if (hasMipMap && !("min" in options)) { + info.minFilter = GL_NEAREST_MIPMAP_NEAREST; + } + } + } + function setTexInfo(info, target) { + gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, info.minFilter); + gl.texParameteri(target, GL_TEXTURE_MAG_FILTER, info.magFilter); + gl.texParameteri(target, GL_TEXTURE_WRAP_S, info.wrapS); + gl.texParameteri(target, GL_TEXTURE_WRAP_T, info.wrapT); + if (extensions.ext_texture_filter_anisotropic) { + gl.texParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, info.anisotropic); + } + if (info.genMipmaps) { + gl.hint(GL_GENERATE_MIPMAP_HINT, info.mipmapHint); + gl.generateMipmap(target); + } + } + var textureCount = 0; + var textureSet = {}; + var numTexUnits = limits.maxTextureUnits; + var textureUnits = Array(numTexUnits).map(function() { + return null; + }); + function REGLTexture(target) { + TexFlags.call(this); + this.mipmask = 0; + this.internalformat = GL_RGBA$1; + this.id = textureCount++; + this.refCount = 1; + this.target = target; + this.texture = gl.createTexture(); + this.unit = -1; + this.bindCount = 0; + this.texInfo = new TexInfo(); + if (config.profile) { + this.stats = { size: 0 }; + } + } + function tempBind(texture) { + gl.activeTexture(GL_TEXTURE0$1); + gl.bindTexture(texture.target, texture.texture); + } + function tempRestore() { + var prev = textureUnits[0]; + if (prev) { + gl.bindTexture(prev.target, prev.texture); + } else { + gl.bindTexture(GL_TEXTURE_2D$1, null); + } + } + function destroy2(texture) { + var handle = texture.texture; + var unit = texture.unit; + var target = texture.target; + if (unit >= 0) { + gl.activeTexture(GL_TEXTURE0$1 + unit); + gl.bindTexture(target, null); + textureUnits[unit] = null; + } + gl.deleteTexture(handle); + texture.texture = null; + texture.params = null; + texture.pixels = null; + texture.refCount = 0; + delete textureSet[texture.id]; + stats3.textureCount--; + } + extend2(REGLTexture.prototype, { + bind: function() { + var texture = this; + texture.bindCount += 1; + var unit = texture.unit; + if (unit < 0) { + for (var i = 0; i < numTexUnits; ++i) { + var other = textureUnits[i]; + if (other) { + if (other.bindCount > 0) { + continue; + } + other.unit = -1; + } + textureUnits[i] = texture; + unit = i; + break; + } + if (config.profile && stats3.maxTextureUnits < unit + 1) { + stats3.maxTextureUnits = unit + 1; + } + texture.unit = unit; + gl.activeTexture(GL_TEXTURE0$1 + unit); + gl.bindTexture(texture.target, texture.texture); + } + return unit; + }, + unbind: function() { + this.bindCount -= 1; + }, + decRef: function() { + if (--this.refCount <= 0) { + destroy2(this); + } + } + }); + function createTexture2D(a, b) { + var texture = new REGLTexture(GL_TEXTURE_2D$1); + textureSet[texture.id] = texture; + stats3.textureCount++; + function reglTexture2D(a2, b2) { + var texInfo = texture.texInfo; + TexInfo.call(texInfo); + var mipData = allocMipMap(); + if (typeof a2 === "number") { + if (typeof b2 === "number") { + parseMipMapFromShape(mipData, a2 | 0, b2 | 0); + } else { + parseMipMapFromShape(mipData, a2 | 0, a2 | 0); + } + } else if (a2) { + parseTexInfo(texInfo, a2); + parseMipMapFromObject(mipData, a2); + } else { + parseMipMapFromShape(mipData, 1, 1); + } + if (texInfo.genMipmaps) { + mipData.mipmask = (mipData.width << 1) - 1; + } + texture.mipmask = mipData.mipmask; + copyFlags(texture, mipData); + texture.internalformat = mipData.internalformat; + reglTexture2D.width = mipData.width; + reglTexture2D.height = mipData.height; + tempBind(texture); + setMipMap(mipData, GL_TEXTURE_2D$1); + setTexInfo(texInfo, GL_TEXTURE_2D$1); + tempRestore(); + freeMipMap(mipData); + if (config.profile) { + texture.stats.size = getTextureSize( + texture.internalformat, + texture.type, + mipData.width, + mipData.height, + texInfo.genMipmaps, + false + ); + } + reglTexture2D.format = textureFormatsInvert[texture.internalformat]; + reglTexture2D.type = textureTypesInvert[texture.type]; + reglTexture2D.mag = magFiltersInvert[texInfo.magFilter]; + reglTexture2D.min = minFiltersInvert[texInfo.minFilter]; + reglTexture2D.wrapS = wrapModesInvert[texInfo.wrapS]; + reglTexture2D.wrapT = wrapModesInvert[texInfo.wrapT]; + return reglTexture2D; + } + function subimage(image, x_, y_, level_) { + var x = x_ | 0; + var y = y_ | 0; + var level = level_ | 0; + var imageData = allocImage(); + copyFlags(imageData, texture); + imageData.width = 0; + imageData.height = 0; + parseImage(imageData, image); + imageData.width = imageData.width || (texture.width >> level) - x; + imageData.height = imageData.height || (texture.height >> level) - y; + tempBind(texture); + setSubImage(imageData, GL_TEXTURE_2D$1, x, y, level); + tempRestore(); + freeImage(imageData); + return reglTexture2D; + } + function resize2(w_, h_) { + var w = w_ | 0; + var h = h_ | 0 || w; + if (w === texture.width && h === texture.height) { + return reglTexture2D; + } + reglTexture2D.width = texture.width = w; + reglTexture2D.height = texture.height = h; + tempBind(texture); + for (var i = 0; texture.mipmask >> i; ++i) { + var _w = w >> i; + var _h = h >> i; + if (!_w || !_h) break; + gl.texImage2D( + GL_TEXTURE_2D$1, + i, + texture.format, + _w, + _h, + 0, + texture.format, + texture.type, + null + ); + } + tempRestore(); + if (config.profile) { + texture.stats.size = getTextureSize( + texture.internalformat, + texture.type, + w, + h, + false, + false + ); + } + return reglTexture2D; + } + reglTexture2D(a, b); + reglTexture2D.subimage = subimage; + reglTexture2D.resize = resize2; + reglTexture2D._reglType = "texture2d"; + reglTexture2D._texture = texture; + if (config.profile) { + reglTexture2D.stats = texture.stats; + } + reglTexture2D.destroy = function() { + texture.decRef(); + }; + return reglTexture2D; + } + function createTextureCube(a0, a1, a2, a3, a4, a5) { + var texture = new REGLTexture(GL_TEXTURE_CUBE_MAP$1); + textureSet[texture.id] = texture; + stats3.cubeCount++; + var faces = new Array(6); + function reglTextureCube(a02, a12, a22, a32, a42, a52) { + var i; + var texInfo = texture.texInfo; + TexInfo.call(texInfo); + for (i = 0; i < 6; ++i) { + faces[i] = allocMipMap(); + } + if (typeof a02 === "number" || !a02) { + var s = a02 | 0 || 1; + for (i = 0; i < 6; ++i) { + parseMipMapFromShape(faces[i], s, s); + } + } else if (typeof a02 === "object") { + if (a12) { + parseMipMapFromObject(faces[0], a02); + parseMipMapFromObject(faces[1], a12); + parseMipMapFromObject(faces[2], a22); + parseMipMapFromObject(faces[3], a32); + parseMipMapFromObject(faces[4], a42); + parseMipMapFromObject(faces[5], a52); + } else { + parseTexInfo(texInfo, a02); + parseFlags(texture, a02); + if ("faces" in a02) { + var faceInput = a02.faces; + for (i = 0; i < 6; ++i) { + copyFlags(faces[i], texture); + parseMipMapFromObject(faces[i], faceInput[i]); + } + } else { + for (i = 0; i < 6; ++i) { + parseMipMapFromObject(faces[i], a02); + } + } + } + } else ; + copyFlags(texture, faces[0]); + if (texInfo.genMipmaps) { + texture.mipmask = (faces[0].width << 1) - 1; + } else { + texture.mipmask = faces[0].mipmask; + } + texture.internalformat = faces[0].internalformat; + reglTextureCube.width = faces[0].width; + reglTextureCube.height = faces[0].height; + tempBind(texture); + for (i = 0; i < 6; ++i) { + setMipMap(faces[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i); + } + setTexInfo(texInfo, GL_TEXTURE_CUBE_MAP$1); + tempRestore(); + if (config.profile) { + texture.stats.size = getTextureSize( + texture.internalformat, + texture.type, + reglTextureCube.width, + reglTextureCube.height, + texInfo.genMipmaps, + true + ); + } + reglTextureCube.format = textureFormatsInvert[texture.internalformat]; + reglTextureCube.type = textureTypesInvert[texture.type]; + reglTextureCube.mag = magFiltersInvert[texInfo.magFilter]; + reglTextureCube.min = minFiltersInvert[texInfo.minFilter]; + reglTextureCube.wrapS = wrapModesInvert[texInfo.wrapS]; + reglTextureCube.wrapT = wrapModesInvert[texInfo.wrapT]; + for (i = 0; i < 6; ++i) { + freeMipMap(faces[i]); + } + return reglTextureCube; + } + function subimage(face, image, x_, y_, level_) { + var x = x_ | 0; + var y = y_ | 0; + var level = level_ | 0; + var imageData = allocImage(); + copyFlags(imageData, texture); + imageData.width = 0; + imageData.height = 0; + parseImage(imageData, image); + imageData.width = imageData.width || (texture.width >> level) - x; + imageData.height = imageData.height || (texture.height >> level) - y; + tempBind(texture); + setSubImage(imageData, GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + face, x, y, level); + tempRestore(); + freeImage(imageData); + return reglTextureCube; + } + function resize2(radius_) { + var radius = radius_ | 0; + if (radius === texture.width) { + return; + } + reglTextureCube.width = texture.width = radius; + reglTextureCube.height = texture.height = radius; + tempBind(texture); + for (var i = 0; i < 6; ++i) { + for (var j = 0; texture.mipmask >> j; ++j) { + gl.texImage2D( + GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i, + j, + texture.format, + radius >> j, + radius >> j, + 0, + texture.format, + texture.type, + null + ); + } + } + tempRestore(); + if (config.profile) { + texture.stats.size = getTextureSize( + texture.internalformat, + texture.type, + reglTextureCube.width, + reglTextureCube.height, + false, + true + ); + } + return reglTextureCube; + } + reglTextureCube(a0, a1, a2, a3, a4, a5); + reglTextureCube.subimage = subimage; + reglTextureCube.resize = resize2; + reglTextureCube._reglType = "textureCube"; + reglTextureCube._texture = texture; + if (config.profile) { + reglTextureCube.stats = texture.stats; + } + reglTextureCube.destroy = function() { + texture.decRef(); + }; + return reglTextureCube; + } + function destroyTextures() { + for (var i = 0; i < numTexUnits; ++i) { + gl.activeTexture(GL_TEXTURE0$1 + i); + gl.bindTexture(GL_TEXTURE_2D$1, null); + textureUnits[i] = null; + } + values(textureSet).forEach(destroy2); + stats3.cubeCount = 0; + stats3.textureCount = 0; + } + if (config.profile) { + stats3.getTotalTextureSize = function() { + var total = 0; + Object.keys(textureSet).forEach(function(key) { + total += textureSet[key].stats.size; + }); + return total; + }; + } + function restoreTextures() { + for (var i = 0; i < numTexUnits; ++i) { + var tex = textureUnits[i]; + if (tex) { + tex.bindCount = 0; + tex.unit = -1; + textureUnits[i] = null; + } + } + values(textureSet).forEach(function(texture) { + texture.texture = gl.createTexture(); + gl.bindTexture(texture.target, texture.texture); + for (var i2 = 0; i2 < 32; ++i2) { + if ((texture.mipmask & 1 << i2) === 0) { + continue; + } + if (texture.target === GL_TEXTURE_2D$1) { + gl.texImage2D( + GL_TEXTURE_2D$1, + i2, + texture.internalformat, + texture.width >> i2, + texture.height >> i2, + 0, + texture.internalformat, + texture.type, + null + ); + } else { + for (var j = 0; j < 6; ++j) { + gl.texImage2D( + GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + j, + i2, + texture.internalformat, + texture.width >> i2, + texture.height >> i2, + 0, + texture.internalformat, + texture.type, + null + ); + } + } + } + setTexInfo(texture.texInfo, texture.target); + }); + } + function refreshTextures() { + for (var i = 0; i < numTexUnits; ++i) { + var tex = textureUnits[i]; + if (tex) { + tex.bindCount = 0; + tex.unit = -1; + textureUnits[i] = null; + } + gl.activeTexture(GL_TEXTURE0$1 + i); + gl.bindTexture(GL_TEXTURE_2D$1, null); + gl.bindTexture(GL_TEXTURE_CUBE_MAP$1, null); + } + } + return { + create2D: createTexture2D, + createCube: createTextureCube, + clear: destroyTextures, + getTexture: function(wrapper) { + return null; + }, + restore: restoreTextures, + refresh: refreshTextures + }; + } + var GL_RENDERBUFFER = 36161; + var GL_RGBA4$1 = 32854; + var GL_RGB5_A1$1 = 32855; + var GL_RGB565$1 = 36194; + var GL_DEPTH_COMPONENT16 = 33189; + var GL_STENCIL_INDEX8 = 36168; + var GL_DEPTH_STENCIL$1 = 34041; + var GL_SRGB8_ALPHA8_EXT = 35907; + var GL_RGBA32F_EXT = 34836; + var GL_RGBA16F_EXT = 34842; + var GL_RGB16F_EXT = 34843; + var FORMAT_SIZES = []; + FORMAT_SIZES[GL_RGBA4$1] = 2; + FORMAT_SIZES[GL_RGB5_A1$1] = 2; + FORMAT_SIZES[GL_RGB565$1] = 2; + FORMAT_SIZES[GL_DEPTH_COMPONENT16] = 2; + FORMAT_SIZES[GL_STENCIL_INDEX8] = 1; + FORMAT_SIZES[GL_DEPTH_STENCIL$1] = 4; + FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT] = 4; + FORMAT_SIZES[GL_RGBA32F_EXT] = 16; + FORMAT_SIZES[GL_RGBA16F_EXT] = 8; + FORMAT_SIZES[GL_RGB16F_EXT] = 6; + function getRenderbufferSize(format2, width, height) { + return FORMAT_SIZES[format2] * width * height; + } + var wrapRenderbuffers = function(gl, extensions, limits, stats3, config) { + var formatTypes2 = { + "rgba4": GL_RGBA4$1, + "rgb565": GL_RGB565$1, + "rgb5 a1": GL_RGB5_A1$1, + "depth": GL_DEPTH_COMPONENT16, + "stencil": GL_STENCIL_INDEX8, + "depth stencil": GL_DEPTH_STENCIL$1 + }; + if (extensions.ext_srgb) { + formatTypes2["srgba"] = GL_SRGB8_ALPHA8_EXT; + } + if (extensions.ext_color_buffer_half_float) { + formatTypes2["rgba16f"] = GL_RGBA16F_EXT; + formatTypes2["rgb16f"] = GL_RGB16F_EXT; + } + if (extensions.webgl_color_buffer_float) { + formatTypes2["rgba32f"] = GL_RGBA32F_EXT; + } + var formatTypesInvert = []; + Object.keys(formatTypes2).forEach(function(key) { + var val = formatTypes2[key]; + formatTypesInvert[val] = key; + }); + var renderbufferCount = 0; + var renderbufferSet = {}; + function REGLRenderbuffer(renderbuffer) { + this.id = renderbufferCount++; + this.refCount = 1; + this.renderbuffer = renderbuffer; + this.format = GL_RGBA4$1; + this.width = 0; + this.height = 0; + if (config.profile) { + this.stats = { size: 0 }; + } + } + REGLRenderbuffer.prototype.decRef = function() { + if (--this.refCount <= 0) { + destroy2(this); + } + }; + function destroy2(rb) { + var handle = rb.renderbuffer; + gl.bindRenderbuffer(GL_RENDERBUFFER, null); + gl.deleteRenderbuffer(handle); + rb.renderbuffer = null; + rb.refCount = 0; + delete renderbufferSet[rb.id]; + stats3.renderbufferCount--; + } + function createRenderbuffer(a, b) { + var renderbuffer = new REGLRenderbuffer(gl.createRenderbuffer()); + renderbufferSet[renderbuffer.id] = renderbuffer; + stats3.renderbufferCount++; + function reglRenderbuffer(a2, b2) { + var w = 0; + var h = 0; + var format2 = GL_RGBA4$1; + if (typeof a2 === "object" && a2) { + var options = a2; + if ("shape" in options) { + var shape = options.shape; + w = shape[0] | 0; + h = shape[1] | 0; + } else { + if ("radius" in options) { + w = h = options.radius | 0; + } + if ("width" in options) { + w = options.width | 0; + } + if ("height" in options) { + h = options.height | 0; + } + } + if ("format" in options) { + format2 = formatTypes2[options.format]; + } + } else if (typeof a2 === "number") { + w = a2 | 0; + if (typeof b2 === "number") { + h = b2 | 0; + } else { + h = w; + } + } else if (!a2) { + w = h = 1; + } else ; + if (w === renderbuffer.width && h === renderbuffer.height && format2 === renderbuffer.format) { + return; + } + reglRenderbuffer.width = renderbuffer.width = w; + reglRenderbuffer.height = renderbuffer.height = h; + renderbuffer.format = format2; + gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer); + gl.renderbufferStorage(GL_RENDERBUFFER, format2, w, h); + if (config.profile) { + renderbuffer.stats.size = getRenderbufferSize(renderbuffer.format, renderbuffer.width, renderbuffer.height); + } + reglRenderbuffer.format = formatTypesInvert[renderbuffer.format]; + return reglRenderbuffer; + } + function resize2(w_, h_) { + var w = w_ | 0; + var h = h_ | 0 || w; + if (w === renderbuffer.width && h === renderbuffer.height) { + return reglRenderbuffer; + } + reglRenderbuffer.width = renderbuffer.width = w; + reglRenderbuffer.height = renderbuffer.height = h; + gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer); + gl.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h); + if (config.profile) { + renderbuffer.stats.size = getRenderbufferSize( + renderbuffer.format, + renderbuffer.width, + renderbuffer.height + ); + } + return reglRenderbuffer; + } + reglRenderbuffer(a, b); + reglRenderbuffer.resize = resize2; + reglRenderbuffer._reglType = "renderbuffer"; + reglRenderbuffer._renderbuffer = renderbuffer; + if (config.profile) { + reglRenderbuffer.stats = renderbuffer.stats; + } + reglRenderbuffer.destroy = function() { + renderbuffer.decRef(); + }; + return reglRenderbuffer; + } + if (config.profile) { + stats3.getTotalRenderbufferSize = function() { + var total = 0; + Object.keys(renderbufferSet).forEach(function(key) { + total += renderbufferSet[key].stats.size; + }); + return total; + }; + } + function restoreRenderbuffers() { + values(renderbufferSet).forEach(function(rb) { + rb.renderbuffer = gl.createRenderbuffer(); + gl.bindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer); + gl.renderbufferStorage(GL_RENDERBUFFER, rb.format, rb.width, rb.height); + }); + gl.bindRenderbuffer(GL_RENDERBUFFER, null); + } + return { + create: createRenderbuffer, + clear: function() { + values(renderbufferSet).forEach(destroy2); + }, + restore: restoreRenderbuffers + }; + }; + var GL_FRAMEBUFFER$1 = 36160; + var GL_RENDERBUFFER$1 = 36161; + var GL_TEXTURE_2D$2 = 3553; + var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 = 34069; + var GL_COLOR_ATTACHMENT0$1 = 36064; + var GL_DEPTH_ATTACHMENT = 36096; + var GL_STENCIL_ATTACHMENT = 36128; + var GL_DEPTH_STENCIL_ATTACHMENT = 33306; + var GL_FRAMEBUFFER_COMPLETE$1 = 36053; + var GL_HALF_FLOAT_OES$1 = 36193; + var GL_UNSIGNED_BYTE$5 = 5121; + var GL_FLOAT$4 = 5126; + var GL_RGB$1 = 6407; + var GL_RGBA$2 = 6408; + var textureFormatChannels = []; + textureFormatChannels[GL_RGBA$2] = 4; + textureFormatChannels[GL_RGB$1] = 3; + var textureTypeSizes = []; + textureTypeSizes[GL_UNSIGNED_BYTE$5] = 1; + textureTypeSizes[GL_FLOAT$4] = 4; + textureTypeSizes[GL_HALF_FLOAT_OES$1] = 2; + function wrapFBOState(gl, extensions, limits, textureState, renderbufferState, stats3) { + var framebufferState = { + cur: null, + next: null, + dirty: false, + setFBO: null + }; + var colorTextureFormats = ["rgba"]; + var colorRenderbufferFormats = ["rgba4", "rgb565", "rgb5 a1"]; + if (extensions.ext_srgb) { + colorRenderbufferFormats.push("srgba"); + } + if (extensions.ext_color_buffer_half_float) { + colorRenderbufferFormats.push("rgba16f", "rgb16f"); + } + if (extensions.webgl_color_buffer_float) { + colorRenderbufferFormats.push("rgba32f"); + } + if (extensions.oes_texture_half_float) ; + if (extensions.oes_texture_float) ; + function FramebufferAttachment(target, texture, renderbuffer) { + this.target = target; + this.texture = texture; + this.renderbuffer = renderbuffer; + var w = 0; + var h = 0; + if (texture) { + w = texture.width; + h = texture.height; + } else if (renderbuffer) { + w = renderbuffer.width; + h = renderbuffer.height; + } + this.width = w; + this.height = h; + } + function decRef(attachment) { + if (attachment) { + if (attachment.texture) { + attachment.texture._texture.decRef(); + } + if (attachment.renderbuffer) { + attachment.renderbuffer._renderbuffer.decRef(); + } + } + } + function incRefAndCheckShape(attachment, width, height) { + if (!attachment) { + return; + } + if (attachment.texture) { + var texture = attachment.texture._texture; + Math.max(1, texture.width); + Math.max(1, texture.height); + texture.refCount += 1; + } else { + var renderbuffer = attachment.renderbuffer._renderbuffer; + renderbuffer.refCount += 1; + } + } + function attach(location, attachment) { + if (attachment) { + if (attachment.texture) { + gl.framebufferTexture2D( + GL_FRAMEBUFFER$1, + location, + attachment.target, + attachment.texture._texture.texture, + 0 + ); + } else { + gl.framebufferRenderbuffer( + GL_FRAMEBUFFER$1, + location, + GL_RENDERBUFFER$1, + attachment.renderbuffer._renderbuffer.renderbuffer + ); + } + } + } + function parseAttachment(attachment) { + var target = GL_TEXTURE_2D$2; + var texture = null; + var renderbuffer = null; + var data = attachment; + if (typeof attachment === "object") { + data = attachment.data; + if ("target" in attachment) { + target = attachment.target | 0; + } + } + var type = data._reglType; + if (type === "texture2d") { + texture = data; + } else if (type === "textureCube") { + texture = data; + } else if (type === "renderbuffer") { + renderbuffer = data; + target = GL_RENDERBUFFER$1; + } else ; + return new FramebufferAttachment(target, texture, renderbuffer); + } + function allocAttachment(width, height, isTexture, format2, type) { + if (isTexture) { + var texture = textureState.create2D({ + width, + height, + format: format2, + type + }); + texture._texture.refCount = 0; + return new FramebufferAttachment(GL_TEXTURE_2D$2, texture, null); + } else { + var rb = renderbufferState.create({ + width, + height, + format: format2 + }); + rb._renderbuffer.refCount = 0; + return new FramebufferAttachment(GL_RENDERBUFFER$1, null, rb); + } + } + function unwrapAttachment(attachment) { + return attachment && (attachment.texture || attachment.renderbuffer); + } + function resizeAttachment(attachment, w, h) { + if (attachment) { + if (attachment.texture) { + attachment.texture.resize(w, h); + } else if (attachment.renderbuffer) { + attachment.renderbuffer.resize(w, h); + } + attachment.width = w; + attachment.height = h; + } + } + var framebufferCount = 0; + var framebufferSet = {}; + function REGLFramebuffer() { + this.id = framebufferCount++; + framebufferSet[this.id] = this; + this.framebuffer = gl.createFramebuffer(); + this.width = 0; + this.height = 0; + this.colorAttachments = []; + this.depthAttachment = null; + this.stencilAttachment = null; + this.depthStencilAttachment = null; + } + function decFBORefs(framebuffer) { + framebuffer.colorAttachments.forEach(decRef); + decRef(framebuffer.depthAttachment); + decRef(framebuffer.stencilAttachment); + decRef(framebuffer.depthStencilAttachment); + } + function destroy2(framebuffer) { + var handle = framebuffer.framebuffer; + gl.deleteFramebuffer(handle); + framebuffer.framebuffer = null; + stats3.framebufferCount--; + delete framebufferSet[framebuffer.id]; + } + function updateFramebuffer(framebuffer) { + var i; + gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebuffer.framebuffer); + var colorAttachments = framebuffer.colorAttachments; + for (i = 0; i < colorAttachments.length; ++i) { + attach(GL_COLOR_ATTACHMENT0$1 + i, colorAttachments[i]); + } + for (i = colorAttachments.length; i < limits.maxColorAttachments; ++i) { + gl.framebufferTexture2D( + GL_FRAMEBUFFER$1, + GL_COLOR_ATTACHMENT0$1 + i, + GL_TEXTURE_2D$2, + null, + 0 + ); + } + gl.framebufferTexture2D( + GL_FRAMEBUFFER$1, + GL_DEPTH_STENCIL_ATTACHMENT, + GL_TEXTURE_2D$2, + null, + 0 + ); + gl.framebufferTexture2D( + GL_FRAMEBUFFER$1, + GL_DEPTH_ATTACHMENT, + GL_TEXTURE_2D$2, + null, + 0 + ); + gl.framebufferTexture2D( + GL_FRAMEBUFFER$1, + GL_STENCIL_ATTACHMENT, + GL_TEXTURE_2D$2, + null, + 0 + ); + attach(GL_DEPTH_ATTACHMENT, framebuffer.depthAttachment); + attach(GL_STENCIL_ATTACHMENT, framebuffer.stencilAttachment); + attach(GL_DEPTH_STENCIL_ATTACHMENT, framebuffer.depthStencilAttachment); + var status = gl.checkFramebufferStatus(GL_FRAMEBUFFER$1); + if (!gl.isContextLost() && status !== GL_FRAMEBUFFER_COMPLETE$1) ; + gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebufferState.next ? framebufferState.next.framebuffer : null); + framebufferState.cur = framebufferState.next; + gl.getError(); + } + function createFBO(a0, a1) { + var framebuffer = new REGLFramebuffer(); + stats3.framebufferCount++; + function reglFramebuffer(a, b) { + var i; + var width = 0; + var height = 0; + var needsDepth = true; + var needsStencil = true; + var colorBuffer = null; + var colorTexture = true; + var colorFormat = "rgba"; + var colorType = "uint8"; + var colorCount = 1; + var depthBuffer = null; + var stencilBuffer = null; + var depthStencilBuffer = null; + var depthStencilTexture = false; + if (typeof a === "number") { + width = a | 0; + height = b | 0 || width; + } else if (!a) { + width = height = 1; + } else { + var options = a; + if ("shape" in options) { + var shape = options.shape; + width = shape[0]; + height = shape[1]; + } else { + if ("radius" in options) { + width = height = options.radius; + } + if ("width" in options) { + width = options.width; + } + if ("height" in options) { + height = options.height; + } + } + if ("color" in options || "colors" in options) { + colorBuffer = options.color || options.colors; + } + if (!colorBuffer) { + if ("colorCount" in options) { + colorCount = options.colorCount | 0; + } + if ("colorTexture" in options) { + colorTexture = !!options.colorTexture; + colorFormat = "rgba4"; + } + if ("colorType" in options) { + colorType = options.colorType; + if (!colorTexture) { + if (colorType === "half float" || colorType === "float16") { + colorFormat = "rgba16f"; + } else if (colorType === "float" || colorType === "float32") { + colorFormat = "rgba32f"; + } + } + } + if ("colorFormat" in options) { + colorFormat = options.colorFormat; + if (colorTextureFormats.indexOf(colorFormat) >= 0) { + colorTexture = true; + } else if (colorRenderbufferFormats.indexOf(colorFormat) >= 0) { + colorTexture = false; + } else ; + } + } + if ("depthTexture" in options || "depthStencilTexture" in options) { + depthStencilTexture = !!(options.depthTexture || options.depthStencilTexture); + } + if ("depth" in options) { + if (typeof options.depth === "boolean") { + needsDepth = options.depth; + } else { + depthBuffer = options.depth; + needsStencil = false; + } + } + if ("stencil" in options) { + if (typeof options.stencil === "boolean") { + needsStencil = options.stencil; + } else { + stencilBuffer = options.stencil; + needsDepth = false; + } + } + if ("depthStencil" in options) { + if (typeof options.depthStencil === "boolean") { + needsDepth = needsStencil = options.depthStencil; + } else { + depthStencilBuffer = options.depthStencil; + needsDepth = false; + needsStencil = false; + } + } + } + var colorAttachments = null; + var depthAttachment = null; + var stencilAttachment = null; + var depthStencilAttachment = null; + if (Array.isArray(colorBuffer)) { + colorAttachments = colorBuffer.map(parseAttachment); + } else if (colorBuffer) { + colorAttachments = [parseAttachment(colorBuffer)]; + } else { + colorAttachments = new Array(colorCount); + for (i = 0; i < colorCount; ++i) { + colorAttachments[i] = allocAttachment( + width, + height, + colorTexture, + colorFormat, + colorType + ); + } + } + width = width || colorAttachments[0].width; + height = height || colorAttachments[0].height; + if (depthBuffer) { + depthAttachment = parseAttachment(depthBuffer); + } else if (needsDepth && !needsStencil) { + depthAttachment = allocAttachment( + width, + height, + depthStencilTexture, + "depth", + "uint32" + ); + } + if (stencilBuffer) { + stencilAttachment = parseAttachment(stencilBuffer); + } else if (needsStencil && !needsDepth) { + stencilAttachment = allocAttachment( + width, + height, + false, + "stencil", + "uint8" + ); + } + if (depthStencilBuffer) { + depthStencilAttachment = parseAttachment(depthStencilBuffer); + } else if (!depthBuffer && !stencilBuffer && needsStencil && needsDepth) { + depthStencilAttachment = allocAttachment( + width, + height, + depthStencilTexture, + "depth stencil", + "depth stencil" + ); + } + for (i = 0; i < colorAttachments.length; ++i) { + incRefAndCheckShape(colorAttachments[i]); + if (colorAttachments[i] && colorAttachments[i].texture) { + textureFormatChannels[colorAttachments[i].texture._texture.format] * textureTypeSizes[colorAttachments[i].texture._texture.type]; + } + } + incRefAndCheckShape(depthAttachment); + incRefAndCheckShape(stencilAttachment); + incRefAndCheckShape(depthStencilAttachment); + decFBORefs(framebuffer); + framebuffer.width = width; + framebuffer.height = height; + framebuffer.colorAttachments = colorAttachments; + framebuffer.depthAttachment = depthAttachment; + framebuffer.stencilAttachment = stencilAttachment; + framebuffer.depthStencilAttachment = depthStencilAttachment; + reglFramebuffer.color = colorAttachments.map(unwrapAttachment); + reglFramebuffer.depth = unwrapAttachment(depthAttachment); + reglFramebuffer.stencil = unwrapAttachment(stencilAttachment); + reglFramebuffer.depthStencil = unwrapAttachment(depthStencilAttachment); + reglFramebuffer.width = framebuffer.width; + reglFramebuffer.height = framebuffer.height; + updateFramebuffer(framebuffer); + return reglFramebuffer; + } + function resize2(w_, h_) { + var w = Math.max(w_ | 0, 1); + var h = Math.max(h_ | 0 || w, 1); + if (w === framebuffer.width && h === framebuffer.height) { + return reglFramebuffer; + } + var colorAttachments = framebuffer.colorAttachments; + for (var i = 0; i < colorAttachments.length; ++i) { + resizeAttachment(colorAttachments[i], w, h); + } + resizeAttachment(framebuffer.depthAttachment, w, h); + resizeAttachment(framebuffer.stencilAttachment, w, h); + resizeAttachment(framebuffer.depthStencilAttachment, w, h); + framebuffer.width = reglFramebuffer.width = w; + framebuffer.height = reglFramebuffer.height = h; + updateFramebuffer(framebuffer); + return reglFramebuffer; + } + reglFramebuffer(a0, a1); + return extend2(reglFramebuffer, { + resize: resize2, + _reglType: "framebuffer", + _framebuffer: framebuffer, + destroy: function() { + destroy2(framebuffer); + decFBORefs(framebuffer); + }, + use: function(block) { + framebufferState.setFBO({ + framebuffer: reglFramebuffer + }, block); + } + }); + } + function createCubeFBO(options) { + var faces = Array(6); + function reglFramebufferCube(a) { + var i; + var params = { + color: null + }; + var radius = 0; + var colorBuffer = null; + var colorFormat = "rgba"; + var colorType = "uint8"; + var colorCount = 1; + if (typeof a === "number") { + radius = a | 0; + } else if (!a) { + radius = 1; + } else { + var options2 = a; + if ("shape" in options2) { + var shape = options2.shape; + radius = shape[0]; + } else { + if ("radius" in options2) { + radius = options2.radius | 0; + } + if ("width" in options2) { + radius = options2.width | 0; + } else if ("height" in options2) { + radius = options2.height | 0; + } + } + if ("color" in options2 || "colors" in options2) { + colorBuffer = options2.color || options2.colors; + } + if (!colorBuffer) { + if ("colorCount" in options2) { + colorCount = options2.colorCount | 0; + } + if ("colorType" in options2) { + colorType = options2.colorType; + } + if ("colorFormat" in options2) { + colorFormat = options2.colorFormat; + } + } + if ("depth" in options2) { + params.depth = options2.depth; + } + if ("stencil" in options2) { + params.stencil = options2.stencil; + } + if ("depthStencil" in options2) { + params.depthStencil = options2.depthStencil; + } + } + var colorCubes; + if (colorBuffer) { + if (Array.isArray(colorBuffer)) { + colorCubes = []; + for (i = 0; i < colorBuffer.length; ++i) { + colorCubes[i] = colorBuffer[i]; + } + } else { + colorCubes = [colorBuffer]; + } + } else { + colorCubes = Array(colorCount); + var cubeMapParams = { + radius, + format: colorFormat, + type: colorType + }; + for (i = 0; i < colorCount; ++i) { + colorCubes[i] = textureState.createCube(cubeMapParams); + } + } + params.color = Array(colorCubes.length); + for (i = 0; i < colorCubes.length; ++i) { + var cube = colorCubes[i]; + radius = radius || cube.width; + params.color[i] = { + target: GL_TEXTURE_CUBE_MAP_POSITIVE_X$2, + data: colorCubes[i] + }; + } + for (i = 0; i < 6; ++i) { + for (var j = 0; j < colorCubes.length; ++j) { + params.color[j].target = GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + i; + } + if (i > 0) { + params.depth = faces[0].depth; + params.stencil = faces[0].stencil; + params.depthStencil = faces[0].depthStencil; + } + if (faces[i]) { + faces[i](params); + } else { + faces[i] = createFBO(params); + } + } + return extend2(reglFramebufferCube, { + width: radius, + height: radius, + color: colorCubes + }); + } + function resize2(radius_) { + var i; + var radius = radius_ | 0; + if (radius === reglFramebufferCube.width) { + return reglFramebufferCube; + } + var colors = reglFramebufferCube.color; + for (i = 0; i < colors.length; ++i) { + colors[i].resize(radius); + } + for (i = 0; i < 6; ++i) { + faces[i].resize(radius); + } + reglFramebufferCube.width = reglFramebufferCube.height = radius; + return reglFramebufferCube; + } + reglFramebufferCube(options); + return extend2(reglFramebufferCube, { + faces, + resize: resize2, + _reglType: "framebufferCube", + destroy: function() { + faces.forEach(function(f) { + f.destroy(); + }); + } + }); + } + function restoreFramebuffers() { + framebufferState.cur = null; + framebufferState.next = null; + framebufferState.dirty = true; + values(framebufferSet).forEach(function(fb) { + fb.framebuffer = gl.createFramebuffer(); + updateFramebuffer(fb); + }); + } + return extend2(framebufferState, { + getFramebuffer: function(object2) { + if (typeof object2 === "function" && object2._reglType === "framebuffer") { + var fbo = object2._framebuffer; + if (fbo instanceof REGLFramebuffer) { + return fbo; + } + } + return null; + }, + create: createFBO, + createCube: createCubeFBO, + clear: function() { + values(framebufferSet).forEach(destroy2); + }, + restore: restoreFramebuffers + }); + } + var GL_FLOAT$5 = 5126; + var GL_ARRAY_BUFFER$1 = 34962; + var GL_ELEMENT_ARRAY_BUFFER$1 = 34963; + function AttributeRecord() { + this.state = 0; + this.x = 0; + this.y = 0; + this.z = 0; + this.w = 0; + this.buffer = null; + this.size = 0; + this.normalized = false; + this.type = GL_FLOAT$5; + this.offset = 0; + this.stride = 0; + this.divisor = 0; + } + function wrapAttributeState(gl, extensions, limits, stats3, bufferState, elementState, drawState) { + var NUM_ATTRIBUTES = limits.maxAttributes; + var attributeBindings = new Array(NUM_ATTRIBUTES); + for (var i = 0; i < NUM_ATTRIBUTES; ++i) { + attributeBindings[i] = new AttributeRecord(); + } + var vaoCount = 0; + var vaoSet = {}; + var state = { + Record: AttributeRecord, + scope: {}, + state: attributeBindings, + currentVAO: null, + targetVAO: null, + restore: extVAO() ? restoreVAO : function() { + }, + createVAO, + getVAO, + destroyBuffer, + setVAO: extVAO() ? setVAOEXT : setVAOEmulated, + clear: extVAO() ? destroyVAOEXT : function() { + } + }; + function destroyBuffer(buffer2) { + for (var i2 = 0; i2 < attributeBindings.length; ++i2) { + var record = attributeBindings[i2]; + if (record.buffer === buffer2) { + gl.disableVertexAttribArray(i2); + record.buffer = null; + } + } + } + function extVAO() { + return extensions.oes_vertex_array_object; + } + function extInstanced() { + return extensions.angle_instanced_arrays; + } + function getVAO(vao) { + if (typeof vao === "function" && vao._vao) { + return vao._vao; + } + return null; + } + function setVAOEXT(vao) { + if (vao === state.currentVAO) { + return; + } + var ext = extVAO(); + if (vao) { + ext.bindVertexArrayOES(vao.vao); + } else { + ext.bindVertexArrayOES(null); + } + state.currentVAO = vao; + } + function setVAOEmulated(vao) { + if (vao === state.currentVAO) { + return; + } + if (vao) { + vao.bindAttrs(); + } else { + var exti = extInstanced(); + for (var i2 = 0; i2 < attributeBindings.length; ++i2) { + var binding = attributeBindings[i2]; + if (binding.buffer) { + gl.enableVertexAttribArray(i2); + binding.buffer.bind(); + gl.vertexAttribPointer(i2, binding.size, binding.type, binding.normalized, binding.stride, binding.offfset); + if (exti && binding.divisor) { + exti.vertexAttribDivisorANGLE(i2, binding.divisor); + } + } else { + gl.disableVertexAttribArray(i2); + gl.vertexAttrib4f(i2, binding.x, binding.y, binding.z, binding.w); + } + } + if (drawState.elements) { + gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, drawState.elements.buffer.buffer); + } else { + gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null); + } + } + state.currentVAO = vao; + } + function destroyVAOEXT() { + values(vaoSet).forEach(function(vao) { + vao.destroy(); + }); + } + function REGLVAO() { + this.id = ++vaoCount; + this.attributes = []; + this.elements = null; + this.ownsElements = false; + this.count = 0; + this.offset = 0; + this.instances = -1; + this.primitive = 4; + var extension = extVAO(); + if (extension) { + this.vao = extension.createVertexArrayOES(); + } else { + this.vao = null; + } + vaoSet[this.id] = this; + this.buffers = []; + } + REGLVAO.prototype.bindAttrs = function() { + var exti = extInstanced(); + var attributes2 = this.attributes; + for (var i2 = 0; i2 < attributes2.length; ++i2) { + var attr = attributes2[i2]; + if (attr.buffer) { + gl.enableVertexAttribArray(i2); + gl.bindBuffer(GL_ARRAY_BUFFER$1, attr.buffer.buffer); + gl.vertexAttribPointer(i2, attr.size, attr.type, attr.normalized, attr.stride, attr.offset); + if (exti && attr.divisor) { + exti.vertexAttribDivisorANGLE(i2, attr.divisor); + } + } else { + gl.disableVertexAttribArray(i2); + gl.vertexAttrib4f(i2, attr.x, attr.y, attr.z, attr.w); + } + } + for (var j = attributes2.length; j < NUM_ATTRIBUTES; ++j) { + gl.disableVertexAttribArray(j); + } + var elements = elementState.getElements(this.elements); + if (elements) { + gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, elements.buffer.buffer); + } else { + gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null); + } + }; + REGLVAO.prototype.refresh = function() { + var ext = extVAO(); + if (ext) { + ext.bindVertexArrayOES(this.vao); + this.bindAttrs(); + state.currentVAO = null; + ext.bindVertexArrayOES(null); + } + }; + REGLVAO.prototype.destroy = function() { + if (this.vao) { + var extension = extVAO(); + if (this === state.currentVAO) { + state.currentVAO = null; + extension.bindVertexArrayOES(null); + } + extension.deleteVertexArrayOES(this.vao); + this.vao = null; + } + if (this.ownsElements) { + this.elements.destroy(); + this.elements = null; + this.ownsElements = false; + } + if (vaoSet[this.id]) { + delete vaoSet[this.id]; + stats3.vaoCount -= 1; + } + }; + function restoreVAO() { + var ext = extVAO(); + if (ext) { + values(vaoSet).forEach(function(vao) { + vao.refresh(); + }); + } + } + function createVAO(_attr) { + var vao = new REGLVAO(); + stats3.vaoCount += 1; + function updateVAO(options) { + var attributes2; + if (Array.isArray(options)) { + attributes2 = options; + if (vao.elements && vao.ownsElements) { + vao.elements.destroy(); + } + vao.elements = null; + vao.ownsElements = false; + vao.offset = 0; + vao.count = 0; + vao.instances = -1; + vao.primitive = 4; + } else { + if (options.elements) { + var elements = options.elements; + if (vao.ownsElements) { + if (typeof elements === "function" && elements._reglType === "elements") { + vao.elements.destroy(); + vao.ownsElements = false; + } else { + vao.elements(elements); + vao.ownsElements = false; + } + } else if (elementState.getElements(options.elements)) { + vao.elements = options.elements; + vao.ownsElements = false; + } else { + vao.elements = elementState.create(options.elements); + vao.ownsElements = true; + } + } else { + vao.elements = null; + vao.ownsElements = false; + } + attributes2 = options.attributes; + vao.offset = 0; + vao.count = -1; + vao.instances = -1; + vao.primitive = 4; + if (vao.elements) { + vao.count = vao.elements._elements.vertCount; + vao.primitive = vao.elements._elements.primType; + } + if ("offset" in options) { + vao.offset = options.offset | 0; + } + if ("count" in options) { + vao.count = options.count | 0; + } + if ("instances" in options) { + vao.instances = options.instances | 0; + } + if ("primitive" in options) { + vao.primitive = primTypes[options.primitive]; + } + } + var bufUpdated = {}; + var nattributes = vao.attributes; + nattributes.length = attributes2.length; + for (var i2 = 0; i2 < attributes2.length; ++i2) { + var spec = attributes2[i2]; + var rec = nattributes[i2] = new AttributeRecord(); + var data = spec.data || spec; + if (Array.isArray(data) || isTypedArray2(data) || isNDArrayLike(data)) { + var buf; + if (vao.buffers[i2]) { + buf = vao.buffers[i2]; + if (isTypedArray2(data) && buf._buffer.byteLength >= data.byteLength) { + buf.subdata(data); + } else { + buf.destroy(); + vao.buffers[i2] = null; + } + } + if (!vao.buffers[i2]) { + buf = vao.buffers[i2] = bufferState.create(spec, GL_ARRAY_BUFFER$1, false, true); + } + rec.buffer = bufferState.getBuffer(buf); + rec.size = rec.buffer.dimension | 0; + rec.normalized = false; + rec.type = rec.buffer.dtype; + rec.offset = 0; + rec.stride = 0; + rec.divisor = 0; + rec.state = 1; + bufUpdated[i2] = 1; + } else if (bufferState.getBuffer(spec)) { + rec.buffer = bufferState.getBuffer(spec); + rec.size = rec.buffer.dimension | 0; + rec.normalized = false; + rec.type = rec.buffer.dtype; + rec.offset = 0; + rec.stride = 0; + rec.divisor = 0; + rec.state = 1; + } else if (bufferState.getBuffer(spec.buffer)) { + rec.buffer = bufferState.getBuffer(spec.buffer); + rec.size = (+spec.size || rec.buffer.dimension) | 0; + rec.normalized = !!spec.normalized || false; + if ("type" in spec) { + rec.type = glTypes[spec.type]; + } else { + rec.type = rec.buffer.dtype; + } + rec.offset = (spec.offset || 0) | 0; + rec.stride = (spec.stride || 0) | 0; + rec.divisor = (spec.divisor || 0) | 0; + rec.state = 1; + } else if ("x" in spec) { + rec.x = +spec.x || 0; + rec.y = +spec.y || 0; + rec.z = +spec.z || 0; + rec.w = +spec.w || 0; + rec.state = 2; + } else ; + } + for (var j = 0; j < vao.buffers.length; ++j) { + if (!bufUpdated[j] && vao.buffers[j]) { + vao.buffers[j].destroy(); + vao.buffers[j] = null; + } + } + vao.refresh(); + return updateVAO; + } + updateVAO.destroy = function() { + for (var j = 0; j < vao.buffers.length; ++j) { + if (vao.buffers[j]) { + vao.buffers[j].destroy(); + } + } + vao.buffers.length = 0; + if (vao.ownsElements) { + vao.elements.destroy(); + vao.elements = null; + vao.ownsElements = false; + } + vao.destroy(); + }; + updateVAO._vao = vao; + updateVAO._reglType = "vao"; + return updateVAO(_attr); + } + return state; + } + var GL_FRAGMENT_SHADER = 35632; + var GL_VERTEX_SHADER = 35633; + var GL_ACTIVE_UNIFORMS = 35718; + var GL_ACTIVE_ATTRIBUTES = 35721; + function wrapShaderState(gl, stringStore, stats3, config) { + var fragShaders = {}; + var vertShaders = {}; + function ActiveInfo(name2, id, location, info) { + this.name = name2; + this.id = id; + this.location = location; + this.info = info; + } + function insertActiveInfo(list, info) { + for (var i = 0; i < list.length; ++i) { + if (list[i].id === info.id) { + list[i].location = info.location; + return; + } + } + list.push(info); + } + function getShader(type, id, command2) { + var cache2 = type === GL_FRAGMENT_SHADER ? fragShaders : vertShaders; + var shader = cache2[id]; + if (!shader) { + var source = stringStore.str(id); + shader = gl.createShader(type); + gl.shaderSource(shader, source); + gl.compileShader(shader); + cache2[id] = shader; + } + return shader; + } + var programCache = {}; + var programList = []; + var PROGRAM_COUNTER = 0; + function REGLProgram(fragId, vertId) { + this.id = PROGRAM_COUNTER++; + this.fragId = fragId; + this.vertId = vertId; + this.program = null; + this.uniforms = []; + this.attributes = []; + this.refCount = 1; + if (config.profile) { + this.stats = { + uniformsCount: 0, + attributesCount: 0 + }; + } + } + function linkProgram(desc, command2, attributeLocations) { + var i, info; + var fragShader = getShader(GL_FRAGMENT_SHADER, desc.fragId); + var vertShader = getShader(GL_VERTEX_SHADER, desc.vertId); + var program = desc.program = gl.createProgram(); + gl.attachShader(program, fragShader); + gl.attachShader(program, vertShader); + if (attributeLocations) { + for (i = 0; i < attributeLocations.length; ++i) { + var binding = attributeLocations[i]; + gl.bindAttribLocation(program, binding[0], binding[1]); + } + } + gl.linkProgram(program); + var numUniforms = gl.getProgramParameter(program, GL_ACTIVE_UNIFORMS); + if (config.profile) { + desc.stats.uniformsCount = numUniforms; + } + var uniforms = desc.uniforms; + for (i = 0; i < numUniforms; ++i) { + info = gl.getActiveUniform(program, i); + if (info) { + if (info.size > 1) { + for (var j = 0; j < info.size; ++j) { + var name2 = info.name.replace("[0]", "[" + j + "]"); + insertActiveInfo(uniforms, new ActiveInfo( + name2, + stringStore.id(name2), + gl.getUniformLocation(program, name2), + info + )); + } + } else { + insertActiveInfo(uniforms, new ActiveInfo( + info.name, + stringStore.id(info.name), + gl.getUniformLocation(program, info.name), + info + )); + } + } + } + var numAttributes = gl.getProgramParameter(program, GL_ACTIVE_ATTRIBUTES); + if (config.profile) { + desc.stats.attributesCount = numAttributes; + } + var attributes2 = desc.attributes; + for (i = 0; i < numAttributes; ++i) { + info = gl.getActiveAttrib(program, i); + if (info) { + insertActiveInfo(attributes2, new ActiveInfo( + info.name, + stringStore.id(info.name), + gl.getAttribLocation(program, info.name), + info + )); + } + } + } + if (config.profile) { + stats3.getMaxUniformsCount = function() { + var m = 0; + programList.forEach(function(desc) { + if (desc.stats.uniformsCount > m) { + m = desc.stats.uniformsCount; + } + }); + return m; + }; + stats3.getMaxAttributesCount = function() { + var m = 0; + programList.forEach(function(desc) { + if (desc.stats.attributesCount > m) { + m = desc.stats.attributesCount; + } + }); + return m; + }; + } + function restoreShaders() { + fragShaders = {}; + vertShaders = {}; + for (var i = 0; i < programList.length; ++i) { + linkProgram(programList[i], null, programList[i].attributes.map(function(info) { + return [info.location, info.name]; + })); + } + } + return { + clear: function() { + var deleteShader = gl.deleteShader.bind(gl); + values(fragShaders).forEach(deleteShader); + fragShaders = {}; + values(vertShaders).forEach(deleteShader); + vertShaders = {}; + programList.forEach(function(desc) { + gl.deleteProgram(desc.program); + }); + programList.length = 0; + programCache = {}; + stats3.shaderCount = 0; + }, + program: function(vertId, fragId, command2, attribLocations) { + var cache2 = programCache[fragId]; + if (!cache2) { + cache2 = programCache[fragId] = {}; + } + var prevProgram = cache2[vertId]; + if (prevProgram) { + prevProgram.refCount++; + if (!attribLocations) { + return prevProgram; + } + } + var program = new REGLProgram(fragId, vertId); + stats3.shaderCount++; + linkProgram(program, command2, attribLocations); + if (!prevProgram) { + cache2[vertId] = program; + } + programList.push(program); + return extend2(program, { + destroy: function() { + program.refCount--; + if (program.refCount <= 0) { + gl.deleteProgram(program.program); + var idx = programList.indexOf(program); + programList.splice(idx, 1); + stats3.shaderCount--; + } + if (cache2[program.vertId].refCount <= 0) { + gl.deleteShader(vertShaders[program.vertId]); + delete vertShaders[program.vertId]; + delete programCache[program.fragId][program.vertId]; + } + if (!Object.keys(programCache[program.fragId]).length) { + gl.deleteShader(fragShaders[program.fragId]); + delete fragShaders[program.fragId]; + delete programCache[program.fragId]; + } + } + }); + }, + restore: restoreShaders, + shader: getShader, + frag: -1, + vert: -1 + }; + } + var GL_RGBA$3 = 6408; + var GL_UNSIGNED_BYTE$6 = 5121; + var GL_PACK_ALIGNMENT = 3333; + var GL_FLOAT$6 = 5126; + function wrapReadPixels(gl, framebufferState, reglPoll, context2, glAttributes, extensions, limits) { + function readPixelsImpl(input) { + var type; + if (framebufferState.next === null) { + type = GL_UNSIGNED_BYTE$6; + } else { + type = framebufferState.next.colorAttachments[0].texture._texture.type; + } + var x = 0; + var y = 0; + var width = context2.framebufferWidth; + var height = context2.framebufferHeight; + var data = null; + if (isTypedArray2(input)) { + data = input; + } else if (input) { + x = input.x | 0; + y = input.y | 0; + width = (input.width || context2.framebufferWidth - x) | 0; + height = (input.height || context2.framebufferHeight - y) | 0; + data = input.data || null; + } + reglPoll(); + var size = width * height * 4; + if (!data) { + if (type === GL_UNSIGNED_BYTE$6) { + data = new Uint8Array(size); + } else if (type === GL_FLOAT$6) { + data = data || new Float32Array(size); + } + } + gl.pixelStorei(GL_PACK_ALIGNMENT, 4); + gl.readPixels( + x, + y, + width, + height, + GL_RGBA$3, + type, + data + ); + return data; + } + function readPixelsFBO(options) { + var result; + framebufferState.setFBO({ + framebuffer: options.framebuffer + }, function() { + result = readPixelsImpl(options); + }); + return result; + } + function readPixels(options) { + if (!options || !("framebuffer" in options)) { + return readPixelsImpl(options); + } else { + return readPixelsFBO(options); + } + } + return readPixels; + } + function hex_sha256(s) { + return rstr2hex(rstr_sha256(str2rstr_utf8(s))); + } + function rstr_sha256(s) { + return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8)); + } + function rstr2hex(input) { + var hex_tab = "0123456789abcdef"; + var output = ""; + var x; + for (var i = 0; i < input.length; i++) { + x = input.charCodeAt(i); + output += hex_tab.charAt(x >>> 4 & 15) + hex_tab.charAt(x & 15); + } + return output; + } + function str2rstr_utf8(input) { + var output = ""; + var i = -1; + var x, y; + while (++i < input.length) { + x = input.charCodeAt(i); + y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; + if (55296 <= x && x <= 56319 && 56320 <= y && y <= 57343) { + x = 65536 + ((x & 1023) << 10) + (y & 1023); + i++; + } + if (x <= 127) + output += String.fromCharCode(x); + else if (x <= 2047) + output += String.fromCharCode( + 192 | x >>> 6 & 31, + 128 | x & 63 + ); + else if (x <= 65535) + output += String.fromCharCode( + 224 | x >>> 12 & 15, + 128 | x >>> 6 & 63, + 128 | x & 63 + ); + else if (x <= 2097151) + output += String.fromCharCode( + 240 | x >>> 18 & 7, + 128 | x >>> 12 & 63, + 128 | x >>> 6 & 63, + 128 | x & 63 + ); + } + return output; + } + function rstr2binb(input) { + var output = Array(input.length >> 2); + for (var i = 0; i < output.length; i++) + output[i] = 0; + for (var i = 0; i < input.length * 8; i += 8) + output[i >> 5] |= (input.charCodeAt(i / 8) & 255) << 24 - i % 32; + return output; + } + function binb2rstr(input) { + var output = ""; + for (var i = 0; i < input.length * 32; i += 8) + output += String.fromCharCode(input[i >> 5] >>> 24 - i % 32 & 255); + return output; + } + function sha256_S(X, n) { + return X >>> n | X << 32 - n; + } + function sha256_R(X, n) { + return X >>> n; + } + function sha256_Ch(x, y, z) { + return x & y ^ ~x & z; + } + function sha256_Maj(x, y, z) { + return x & y ^ x & z ^ y & z; + } + function sha256_Sigma0256(x) { + return sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22); + } + function sha256_Sigma1256(x) { + return sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25); + } + function sha256_Gamma0256(x) { + return sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3); + } + function sha256_Gamma1256(x) { + return sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10); + } + var sha256_K = new Array( + 1116352408, + 1899447441, + -1245643825, + -373957723, + 961987163, + 1508970993, + -1841331548, + -1424204075, + -670586216, + 310598401, + 607225278, + 1426881987, + 1925078388, + -2132889090, + -1680079193, + -1046744716, + -459576895, + -272742522, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + -1740746414, + -1473132947, + -1341970488, + -1084653625, + -958395405, + -710438585, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + -2117940946, + -1838011259, + -1564481375, + -1474664885, + -1035236496, + -949202525, + -778901479, + -694614492, + -200395387, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + -2067236844, + -1933114872, + -1866530822, + -1538233109, + -1090935817, + -965641998 + ); + function binb_sha256(m, l) { + var HASH = new Array( + 1779033703, + -1150833019, + 1013904242, + -1521486534, + 1359893119, + -1694144372, + 528734635, + 1541459225 + ); + var W = new Array(64); + var a, b, c, d, e, f, g, h; + var i, j, T1, T2; + m[l >> 5] |= 128 << 24 - l % 32; + m[(l + 64 >> 9 << 4) + 15] = l; + for (i = 0; i < m.length; i += 16) { + a = HASH[0]; + b = HASH[1]; + c = HASH[2]; + d = HASH[3]; + e = HASH[4]; + f = HASH[5]; + g = HASH[6]; + h = HASH[7]; + for (j = 0; j < 64; j++) { + if (j < 16) W[j] = m[j + i]; + else W[j] = safe_add(safe_add( + safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), + sha256_Gamma0256(W[j - 15]) + ), W[j - 16]); + T1 = safe_add(safe_add( + safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), + sha256_K[j] + ), W[j]); + T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)); + h = g; + g = f; + f = e; + e = safe_add(d, T1); + d = c; + c = b; + b = a; + a = safe_add(T1, T2); + } + HASH[0] = safe_add(a, HASH[0]); + HASH[1] = safe_add(b, HASH[1]); + HASH[2] = safe_add(c, HASH[2]); + HASH[3] = safe_add(d, HASH[3]); + HASH[4] = safe_add(e, HASH[4]); + HASH[5] = safe_add(f, HASH[5]); + HASH[6] = safe_add(g, HASH[6]); + HASH[7] = safe_add(h, HASH[7]); + } + return HASH; + } + function safe_add(x, y) { + var lsw = (x & 65535) + (y & 65535); + var msw = (x >> 16) + (y >> 16) + (lsw >> 16); + return msw << 16 | lsw & 65535; + } + function slice2(x) { + return Array.prototype.slice.call(x); + } + function join(x) { + return slice2(x).join(""); + } + function createEnvironment(options) { + var cache2 = options && options.cache; + var varCounter = 0; + var linkedNames = []; + var linkedValues = []; + var isStable = []; + function link(value2, options2) { + var stable = options2 && options2.stable; + if (!stable) { + for (var i = 0; i < linkedValues.length; ++i) { + if (linkedValues[i] === value2 && !isStable[i]) { + return linkedNames[i]; + } + } + } + var name2 = "g" + varCounter++; + linkedNames.push(name2); + linkedValues.push(value2); + isStable.push(stable); + return name2; + } + function block() { + var code2 = []; + function push() { + code2.push.apply(code2, slice2(arguments)); + } + var vars = []; + function def() { + var name2 = "v" + varCounter++; + vars.push(name2); + if (arguments.length > 0) { + code2.push(name2, "="); + code2.push.apply(code2, slice2(arguments)); + code2.push(";"); + } + return name2; + } + return extend2(push, { + def, + toString: function() { + return join([ + vars.length > 0 ? "var " + vars.join(",") + ";" : "", + join(code2) + ]); + } + }); + } + function scope() { + var entry = block(); + var exit = block(); + var entryToString = entry.toString; + var exitToString = exit.toString; + function save(object2, prop) { + exit(object2, prop, "=", entry.def(object2, prop), ";"); + } + return extend2(function() { + entry.apply(entry, slice2(arguments)); + }, { + def: entry.def, + entry, + exit, + save, + set: function(object2, prop, value2) { + save(object2, prop); + entry(object2, prop, "=", value2, ";"); + }, + toString: function() { + return entryToString() + exitToString(); + } + }); + } + function conditional() { + var pred = join(arguments); + var thenBlock = scope(); + var elseBlock = scope(); + var thenToString = thenBlock.toString; + var elseToString = elseBlock.toString; + return extend2(thenBlock, { + then: function() { + thenBlock.apply(thenBlock, slice2(arguments)); + return this; + }, + else: function() { + elseBlock.apply(elseBlock, slice2(arguments)); + return this; + }, + toString: function() { + var elseClause = elseToString(); + if (elseClause) { + elseClause = "else{" + elseClause + "}"; + } + return join([ + "if(", + pred, + "){", + thenToString(), + "}", + elseClause + ]); + } + }); + } + var globalBlock = block(); + var procedures = {}; + function proc(name2, count2) { + var args = []; + function arg() { + var name3 = "a" + args.length; + args.push(name3); + return name3; + } + count2 = count2 || 0; + for (var i = 0; i < count2; ++i) { + arg(); + } + var body = scope(); + var bodyToString = body.toString; + var result = procedures[name2] = extend2(body, { + arg, + toString: function() { + return join([ + "function(", + args.join(), + "){", + bodyToString(), + "}" + ]); + } + }); + return result; + } + function compile() { + var code2 = [ + '"use strict";', + globalBlock, + "return {" + ]; + Object.keys(procedures).forEach(function(name2) { + code2.push('"', name2, '":', procedures[name2].toString(), ","); + }); + code2.push("}"); + var src2 = join(code2).replace(/;/g, ";\n").replace(/}/g, "}\n").replace(/{/g, "{\n"); + var key; + if (cache2) { + key = hex_sha256(src2); + if (cache2[key]) { + return cache2[key].apply(null, linkedValues); + } + } + var proc2 = Function.apply(null, linkedNames.concat(src2)); + if (cache2) { + cache2[key] = proc2; + } + return proc2.apply(null, linkedValues); + } + return { + global: globalBlock, + link, + block, + proc, + scope, + cond: conditional, + compile + }; + } + var CUTE_COMPONENTS = "xyzw".split(""); + var GL_UNSIGNED_BYTE$7 = 5121; + var ATTRIB_STATE_POINTER = 1; + var ATTRIB_STATE_CONSTANT = 2; + var DYN_FUNC$1 = 0; + var DYN_PROP$1 = 1; + var DYN_CONTEXT$1 = 2; + var DYN_STATE$1 = 3; + var DYN_THUNK = 4; + var DYN_CONSTANT$1 = 5; + var DYN_ARRAY$1 = 6; + var S_DITHER = "dither"; + var S_BLEND_ENABLE = "blend.enable"; + var S_BLEND_COLOR = "blend.color"; + var S_BLEND_EQUATION = "blend.equation"; + var S_BLEND_FUNC = "blend.func"; + var S_DEPTH_ENABLE = "depth.enable"; + var S_DEPTH_FUNC = "depth.func"; + var S_DEPTH_RANGE = "depth.range"; + var S_DEPTH_MASK = "depth.mask"; + var S_COLOR_MASK = "colorMask"; + var S_CULL_ENABLE = "cull.enable"; + var S_CULL_FACE = "cull.face"; + var S_FRONT_FACE = "frontFace"; + var S_LINE_WIDTH = "lineWidth"; + var S_POLYGON_OFFSET_ENABLE = "polygonOffset.enable"; + var S_POLYGON_OFFSET_OFFSET = "polygonOffset.offset"; + var S_SAMPLE_ALPHA = "sample.alpha"; + var S_SAMPLE_ENABLE = "sample.enable"; + var S_SAMPLE_COVERAGE = "sample.coverage"; + var S_STENCIL_ENABLE = "stencil.enable"; + var S_STENCIL_MASK = "stencil.mask"; + var S_STENCIL_FUNC = "stencil.func"; + var S_STENCIL_OPFRONT = "stencil.opFront"; + var S_STENCIL_OPBACK = "stencil.opBack"; + var S_SCISSOR_ENABLE = "scissor.enable"; + var S_SCISSOR_BOX = "scissor.box"; + var S_VIEWPORT = "viewport"; + var S_PROFILE = "profile"; + var S_FRAMEBUFFER = "framebuffer"; + var S_VERT = "vert"; + var S_FRAG = "frag"; + var S_ELEMENTS = "elements"; + var S_PRIMITIVE = "primitive"; + var S_COUNT = "count"; + var S_OFFSET = "offset"; + var S_INSTANCES = "instances"; + var S_VAO = "vao"; + var SUFFIX_WIDTH = "Width"; + var SUFFIX_HEIGHT = "Height"; + var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH; + var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT; + var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH; + var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT; + var S_DRAWINGBUFFER = "drawingBuffer"; + var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH; + var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT; + var NESTED_OPTIONS = [ + S_BLEND_FUNC, + S_BLEND_EQUATION, + S_STENCIL_FUNC, + S_STENCIL_OPFRONT, + S_STENCIL_OPBACK, + S_SAMPLE_COVERAGE, + S_VIEWPORT, + S_SCISSOR_BOX, + S_POLYGON_OFFSET_OFFSET + ]; + var GL_ARRAY_BUFFER$2 = 34962; + var GL_ELEMENT_ARRAY_BUFFER$2 = 34963; + var GL_CULL_FACE = 2884; + var GL_BLEND = 3042; + var GL_DITHER = 3024; + var GL_STENCIL_TEST = 2960; + var GL_DEPTH_TEST = 2929; + var GL_SCISSOR_TEST = 3089; + var GL_POLYGON_OFFSET_FILL = 32823; + var GL_SAMPLE_ALPHA_TO_COVERAGE = 32926; + var GL_SAMPLE_COVERAGE = 32928; + var GL_FLOAT$7 = 5126; + var GL_FLOAT_VEC2 = 35664; + var GL_FLOAT_VEC3 = 35665; + var GL_FLOAT_VEC4 = 35666; + var GL_INT$2 = 5124; + var GL_INT_VEC2 = 35667; + var GL_INT_VEC3 = 35668; + var GL_INT_VEC4 = 35669; + var GL_BOOL = 35670; + var GL_BOOL_VEC2 = 35671; + var GL_BOOL_VEC3 = 35672; + var GL_BOOL_VEC4 = 35673; + var GL_FLOAT_MAT2 = 35674; + var GL_FLOAT_MAT3 = 35675; + var GL_FLOAT_MAT4 = 35676; + var GL_SAMPLER_2D = 35678; + var GL_SAMPLER_CUBE = 35680; + var GL_TRIANGLES$1 = 4; + var GL_FRONT = 1028; + var GL_BACK = 1029; + var GL_CW = 2304; + var GL_CCW = 2305; + var GL_MIN_EXT = 32775; + var GL_MAX_EXT = 32776; + var GL_ALWAYS = 519; + var GL_KEEP = 7680; + var GL_ZERO = 0; + var GL_ONE = 1; + var GL_FUNC_ADD = 32774; + var GL_LESS = 513; + var GL_FRAMEBUFFER$2 = 36160; + var GL_COLOR_ATTACHMENT0$2 = 36064; + var blendFuncs = { + "0": 0, + "1": 1, + "zero": 0, + "one": 1, + "src color": 768, + "one minus src color": 769, + "src alpha": 770, + "one minus src alpha": 771, + "dst color": 774, + "one minus dst color": 775, + "dst alpha": 772, + "one minus dst alpha": 773, + "constant color": 32769, + "one minus constant color": 32770, + "constant alpha": 32771, + "one minus constant alpha": 32772, + "src alpha saturate": 776 + }; + var compareFuncs = { + "never": 512, + "less": 513, + "<": 513, + "equal": 514, + "=": 514, + "==": 514, + "===": 514, + "lequal": 515, + "<=": 515, + "greater": 516, + ">": 516, + "notequal": 517, + "!=": 517, + "!==": 517, + "gequal": 518, + ">=": 518, + "always": 519 + }; + var stencilOps = { + "0": 0, + "zero": 0, + "keep": 7680, + "replace": 7681, + "increment": 7682, + "decrement": 7683, + "increment wrap": 34055, + "decrement wrap": 34056, + "invert": 5386 + }; + var orientationType = { + "cw": GL_CW, + "ccw": GL_CCW + }; + function isBufferArgs(x) { + return Array.isArray(x) || isTypedArray2(x) || isNDArrayLike(x); + } + function sortState(state) { + return state.sort(function(a, b) { + if (a === S_VIEWPORT) { + return -1; + } else if (b === S_VIEWPORT) { + return 1; + } + return a < b ? -1 : 1; + }); + } + function Declaration(thisDep, contextDep, propDep, append) { + this.thisDep = thisDep; + this.contextDep = contextDep; + this.propDep = propDep; + this.append = append; + } + function isStatic(decl) { + return decl && !(decl.thisDep || decl.contextDep || decl.propDep); + } + function createStaticDecl(append) { + return new Declaration(false, false, false, append); + } + function createDynamicDecl(dyn, append) { + var type = dyn.type; + if (type === DYN_FUNC$1) { + var numArgs = dyn.data.length; + return new Declaration( + true, + numArgs >= 1, + numArgs >= 2, + append + ); + } else if (type === DYN_THUNK) { + var data = dyn.data; + return new Declaration( + data.thisDep, + data.contextDep, + data.propDep, + append + ); + } else if (type === DYN_CONSTANT$1) { + return new Declaration( + false, + false, + false, + append + ); + } else if (type === DYN_ARRAY$1) { + var thisDep = false; + var contextDep = false; + var propDep = false; + for (var i = 0; i < dyn.data.length; ++i) { + var subDyn = dyn.data[i]; + if (subDyn.type === DYN_PROP$1) { + propDep = true; + } else if (subDyn.type === DYN_CONTEXT$1) { + contextDep = true; + } else if (subDyn.type === DYN_STATE$1) { + thisDep = true; + } else if (subDyn.type === DYN_FUNC$1) { + thisDep = true; + var subArgs = subDyn.data; + if (subArgs >= 1) { + contextDep = true; + } + if (subArgs >= 2) { + propDep = true; + } + } else if (subDyn.type === DYN_THUNK) { + thisDep = thisDep || subDyn.data.thisDep; + contextDep = contextDep || subDyn.data.contextDep; + propDep = propDep || subDyn.data.propDep; + } + } + return new Declaration( + thisDep, + contextDep, + propDep, + append + ); + } else { + return new Declaration( + type === DYN_STATE$1, + type === DYN_CONTEXT$1, + type === DYN_PROP$1, + append + ); + } + } + var SCOPE_DECL = new Declaration(false, false, false, function() { + }); + function reglCore(gl, stringStore, extensions, limits, bufferState, elementState, textureState, framebufferState, uniformState, attributeState, shaderState, drawState, contextState, timer, cachedCode, config) { + var AttributeRecord2 = attributeState.Record; + var blendEquations = { + "add": 32774, + "subtract": 32778, + "reverse subtract": 32779 + }; + if (extensions.ext_blend_minmax) { + blendEquations.min = GL_MIN_EXT; + blendEquations.max = GL_MAX_EXT; + } + var extInstancing = extensions.angle_instanced_arrays; + var extDrawBuffers = extensions.webgl_draw_buffers; + var extVertexArrays = extensions.oes_vertex_array_object; + var currentState = { + dirty: true, + profile: config.profile + }; + var nextState = {}; + var GL_STATE_NAMES = []; + var GL_FLAGS = {}; + var GL_VARIABLES = {}; + function propName(name2) { + return name2.replace(".", "_"); + } + function stateFlag(sname, cap, init2) { + var name2 = propName(sname); + GL_STATE_NAMES.push(sname); + nextState[name2] = currentState[name2] = !!init2; + GL_FLAGS[name2] = cap; + } + function stateVariable(sname, func, init2) { + var name2 = propName(sname); + GL_STATE_NAMES.push(sname); + if (Array.isArray(init2)) { + currentState[name2] = init2.slice(); + nextState[name2] = init2.slice(); + } else { + currentState[name2] = nextState[name2] = init2; + } + GL_VARIABLES[name2] = func; + } + function hasVariableReference(exp) { + if (!isNaN(exp)) { + return false; + } + return true; + } + stateFlag(S_DITHER, GL_DITHER); + stateFlag(S_BLEND_ENABLE, GL_BLEND); + stateVariable(S_BLEND_COLOR, "blendColor", [0, 0, 0, 0]); + stateVariable( + S_BLEND_EQUATION, + "blendEquationSeparate", + [GL_FUNC_ADD, GL_FUNC_ADD] + ); + stateVariable( + S_BLEND_FUNC, + "blendFuncSeparate", + [GL_ONE, GL_ZERO, GL_ONE, GL_ZERO] + ); + stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true); + stateVariable(S_DEPTH_FUNC, "depthFunc", GL_LESS); + stateVariable(S_DEPTH_RANGE, "depthRange", [0, 1]); + stateVariable(S_DEPTH_MASK, "depthMask", true); + stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true]); + stateFlag(S_CULL_ENABLE, GL_CULL_FACE); + stateVariable(S_CULL_FACE, "cullFace", GL_BACK); + stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW); + stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1); + stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL); + stateVariable(S_POLYGON_OFFSET_OFFSET, "polygonOffset", [0, 0]); + stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE); + stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE); + stateVariable(S_SAMPLE_COVERAGE, "sampleCoverage", [1, false]); + stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST); + stateVariable(S_STENCIL_MASK, "stencilMask", -1); + stateVariable(S_STENCIL_FUNC, "stencilFunc", [GL_ALWAYS, 0, -1]); + stateVariable( + S_STENCIL_OPFRONT, + "stencilOpSeparate", + [GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP] + ); + stateVariable( + S_STENCIL_OPBACK, + "stencilOpSeparate", + [GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP] + ); + stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST); + stateVariable( + S_SCISSOR_BOX, + "scissor", + [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] + ); + stateVariable( + S_VIEWPORT, + S_VIEWPORT, + [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] + ); + var sharedState = { + gl, + context: contextState, + strings: stringStore, + next: nextState, + current: currentState, + draw: drawState, + elements: elementState, + buffer: bufferState, + shader: shaderState, + attributes: attributeState.state, + vao: attributeState, + uniforms: uniformState, + framebuffer: framebufferState, + extensions, + timer, + isBufferArgs + }; + var sharedConstants = { + primTypes, + compareFuncs, + blendFuncs, + blendEquations, + stencilOps, + glTypes, + orientationType + }; + if (extDrawBuffers) { + sharedConstants.backBuffer = [GL_BACK]; + sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function(i) { + if (i === 0) { + return [0]; + } + return loop(i, function(j) { + return GL_COLOR_ATTACHMENT0$2 + j; + }); + }); + } + var drawCallCounter = 0; + function createREGLEnvironment() { + var env = createEnvironment({ cache: cachedCode }); + var link = env.link; + var global = env.global; + env.id = drawCallCounter++; + env.batchId = "0"; + var SHARED = link(sharedState); + var shared = env.shared = { + props: "a0" + }; + Object.keys(sharedState).forEach(function(prop) { + shared[prop] = global.def(SHARED, ".", prop); + }); + var nextVars = env.next = {}; + var currentVars = env.current = {}; + Object.keys(GL_VARIABLES).forEach(function(variable) { + if (Array.isArray(currentState[variable])) { + nextVars[variable] = global.def(shared.next, ".", variable); + currentVars[variable] = global.def(shared.current, ".", variable); + } + }); + var constants2 = env.constants = {}; + Object.keys(sharedConstants).forEach(function(name2) { + constants2[name2] = global.def(JSON.stringify(sharedConstants[name2])); + }); + env.invoke = function(block, x) { + switch (x.type) { + case DYN_FUNC$1: + var argList = [ + "this", + shared.context, + shared.props, + env.batchId + ]; + return block.def( + link(x.data), + ".call(", + argList.slice(0, Math.max(x.data.length + 1, 4)), + ")" + ); + case DYN_PROP$1: + return block.def(shared.props, x.data); + case DYN_CONTEXT$1: + return block.def(shared.context, x.data); + case DYN_STATE$1: + return block.def("this", x.data); + case DYN_THUNK: + x.data.append(env, block); + return x.data.ref; + case DYN_CONSTANT$1: + return x.data.toString(); + case DYN_ARRAY$1: + return x.data.map(function(y) { + return env.invoke(block, y); + }); + } + }; + env.attribCache = {}; + var scopeAttribs = {}; + env.scopeAttrib = function(name2) { + var id = stringStore.id(name2); + if (id in scopeAttribs) { + return scopeAttribs[id]; + } + var binding = attributeState.scope[id]; + if (!binding) { + binding = attributeState.scope[id] = new AttributeRecord2(); + } + var result = scopeAttribs[id] = link(binding); + return result; + }; + return env; + } + function parseProfile(options) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + var profileEnable; + if (S_PROFILE in staticOptions) { + var value2 = !!staticOptions[S_PROFILE]; + profileEnable = createStaticDecl(function(env, scope) { + return value2; + }); + profileEnable.enable = value2; + } else if (S_PROFILE in dynamicOptions) { + var dyn = dynamicOptions[S_PROFILE]; + profileEnable = createDynamicDecl(dyn, function(env, scope) { + return env.invoke(scope, dyn); + }); + } + return profileEnable; + } + function parseFramebuffer(options, env) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + if (S_FRAMEBUFFER in staticOptions) { + var framebuffer = staticOptions[S_FRAMEBUFFER]; + if (framebuffer) { + framebuffer = framebufferState.getFramebuffer(framebuffer); + return createStaticDecl(function(env2, block) { + var FRAMEBUFFER = env2.link(framebuffer); + var shared = env2.shared; + block.set( + shared.framebuffer, + ".next", + FRAMEBUFFER + ); + var CONTEXT = shared.context; + block.set( + CONTEXT, + "." + S_FRAMEBUFFER_WIDTH, + FRAMEBUFFER + ".width" + ); + block.set( + CONTEXT, + "." + S_FRAMEBUFFER_HEIGHT, + FRAMEBUFFER + ".height" + ); + return FRAMEBUFFER; + }); + } else { + return createStaticDecl(function(env2, scope) { + var shared = env2.shared; + scope.set( + shared.framebuffer, + ".next", + "null" + ); + var CONTEXT = shared.context; + scope.set( + CONTEXT, + "." + S_FRAMEBUFFER_WIDTH, + CONTEXT + "." + S_DRAWINGBUFFER_WIDTH + ); + scope.set( + CONTEXT, + "." + S_FRAMEBUFFER_HEIGHT, + CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT + ); + return "null"; + }); + } + } else if (S_FRAMEBUFFER in dynamicOptions) { + var dyn = dynamicOptions[S_FRAMEBUFFER]; + return createDynamicDecl(dyn, function(env2, scope) { + var FRAMEBUFFER_FUNC = env2.invoke(scope, dyn); + var shared = env2.shared; + var FRAMEBUFFER_STATE = shared.framebuffer; + var FRAMEBUFFER = scope.def( + FRAMEBUFFER_STATE, + ".getFramebuffer(", + FRAMEBUFFER_FUNC, + ")" + ); + scope.set( + FRAMEBUFFER_STATE, + ".next", + FRAMEBUFFER + ); + var CONTEXT = shared.context; + scope.set( + CONTEXT, + "." + S_FRAMEBUFFER_WIDTH, + FRAMEBUFFER + "?" + FRAMEBUFFER + ".width:" + CONTEXT + "." + S_DRAWINGBUFFER_WIDTH + ); + scope.set( + CONTEXT, + "." + S_FRAMEBUFFER_HEIGHT, + FRAMEBUFFER + "?" + FRAMEBUFFER + ".height:" + CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT + ); + return FRAMEBUFFER; + }); + } else { + return null; + } + } + function parseViewportScissor(options, framebuffer, env) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + function parseBox(param) { + if (param in staticOptions) { + var box = staticOptions[param]; + var isStatic2 = true; + var x = box.x | 0; + var y = box.y | 0; + var w, h; + if ("width" in box) { + w = box.width | 0; + } else { + isStatic2 = false; + } + if ("height" in box) { + h = box.height | 0; + } else { + isStatic2 = false; + } + return new Declaration( + !isStatic2 && framebuffer && framebuffer.thisDep, + !isStatic2 && framebuffer && framebuffer.contextDep, + !isStatic2 && framebuffer && framebuffer.propDep, + function(env2, scope) { + var CONTEXT = env2.shared.context; + var BOX_W = w; + if (!("width" in box)) { + BOX_W = scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH, "-", x); + } + var BOX_H = h; + if (!("height" in box)) { + BOX_H = scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT, "-", y); + } + return [x, y, BOX_W, BOX_H]; + } + ); + } else if (param in dynamicOptions) { + var dynBox = dynamicOptions[param]; + var result = createDynamicDecl(dynBox, function(env2, scope) { + var BOX = env2.invoke(scope, dynBox); + var CONTEXT = env2.shared.context; + var BOX_X = scope.def(BOX, ".x|0"); + var BOX_Y = scope.def(BOX, ".y|0"); + var BOX_W = scope.def( + '"width" in ', + BOX, + "?", + BOX, + ".width|0:", + "(", + CONTEXT, + ".", + S_FRAMEBUFFER_WIDTH, + "-", + BOX_X, + ")" + ); + var BOX_H = scope.def( + '"height" in ', + BOX, + "?", + BOX, + ".height|0:", + "(", + CONTEXT, + ".", + S_FRAMEBUFFER_HEIGHT, + "-", + BOX_Y, + ")" + ); + return [BOX_X, BOX_Y, BOX_W, BOX_H]; + }); + if (framebuffer) { + result.thisDep = result.thisDep || framebuffer.thisDep; + result.contextDep = result.contextDep || framebuffer.contextDep; + result.propDep = result.propDep || framebuffer.propDep; + } + return result; + } else if (framebuffer) { + return new Declaration( + framebuffer.thisDep, + framebuffer.contextDep, + framebuffer.propDep, + function(env2, scope) { + var CONTEXT = env2.shared.context; + return [ + 0, + 0, + scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH), + scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT) + ]; + } + ); + } else { + return null; + } + } + var viewport = parseBox(S_VIEWPORT); + if (viewport) { + var prevViewport = viewport; + viewport = new Declaration( + viewport.thisDep, + viewport.contextDep, + viewport.propDep, + function(env2, scope) { + var VIEWPORT = prevViewport.append(env2, scope); + var CONTEXT = env2.shared.context; + scope.set( + CONTEXT, + "." + S_VIEWPORT_WIDTH, + VIEWPORT[2] + ); + scope.set( + CONTEXT, + "." + S_VIEWPORT_HEIGHT, + VIEWPORT[3] + ); + return VIEWPORT; + } + ); + } + return { + viewport, + scissor_box: parseBox(S_SCISSOR_BOX) + }; + } + function parseAttribLocations(options, attributes2) { + var staticOptions = options.static; + var staticProgram = typeof staticOptions[S_FRAG] === "string" && typeof staticOptions[S_VERT] === "string"; + if (staticProgram) { + if (Object.keys(attributes2.dynamic).length > 0) { + return null; + } + var staticAttributes = attributes2.static; + var sAttributes = Object.keys(staticAttributes); + if (sAttributes.length > 0 && typeof staticAttributes[sAttributes[0]] === "number") { + var bindings = []; + for (var i = 0; i < sAttributes.length; ++i) { + bindings.push([staticAttributes[sAttributes[i]] | 0, sAttributes[i]]); + } + return bindings; + } + } + return null; + } + function parseProgram(options, env, attribLocations) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + function parseShader(name2) { + if (name2 in staticOptions) { + var id = stringStore.id(staticOptions[name2]); + var result = createStaticDecl(function() { + return id; + }); + result.id = id; + return result; + } else if (name2 in dynamicOptions) { + var dyn = dynamicOptions[name2]; + return createDynamicDecl(dyn, function(env2, scope) { + var str2 = env2.invoke(scope, dyn); + var id2 = scope.def(env2.shared.strings, ".id(", str2, ")"); + return id2; + }); + } + return null; + } + var frag = parseShader(S_FRAG); + var vert = parseShader(S_VERT); + var program = null; + var progVar; + if (isStatic(frag) && isStatic(vert)) { + program = shaderState.program(vert.id, frag.id, null, attribLocations); + progVar = createStaticDecl(function(env2, scope) { + return env2.link(program); + }); + } else { + progVar = new Declaration( + frag && frag.thisDep || vert && vert.thisDep, + frag && frag.contextDep || vert && vert.contextDep, + frag && frag.propDep || vert && vert.propDep, + function(env2, scope) { + var SHADER_STATE = env2.shared.shader; + var fragId; + if (frag) { + fragId = frag.append(env2, scope); + } else { + fragId = scope.def(SHADER_STATE, ".", S_FRAG); + } + var vertId; + if (vert) { + vertId = vert.append(env2, scope); + } else { + vertId = scope.def(SHADER_STATE, ".", S_VERT); + } + var progDef = SHADER_STATE + ".program(" + vertId + "," + fragId; + return scope.def(progDef + ")"); + } + ); + } + return { + frag, + vert, + progVar, + program + }; + } + function parseDraw(options, env) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + var staticDraw = {}; + var vaoActive = false; + function parseVAO() { + if (S_VAO in staticOptions) { + var vao2 = staticOptions[S_VAO]; + if (vao2 !== null && attributeState.getVAO(vao2) === null) { + vao2 = attributeState.createVAO(vao2); + } + vaoActive = true; + staticDraw.vao = vao2; + return createStaticDecl(function(env2) { + var vaoRef = attributeState.getVAO(vao2); + if (vaoRef) { + return env2.link(vaoRef); + } else { + return "null"; + } + }); + } else if (S_VAO in dynamicOptions) { + vaoActive = true; + var dyn = dynamicOptions[S_VAO]; + return createDynamicDecl(dyn, function(env2, scope) { + var vaoRef = env2.invoke(scope, dyn); + return scope.def(env2.shared.vao + ".getVAO(" + vaoRef + ")"); + }); + } + return null; + } + var vao = parseVAO(); + var elementsActive = false; + function parseElements() { + if (S_ELEMENTS in staticOptions) { + var elements2 = staticOptions[S_ELEMENTS]; + staticDraw.elements = elements2; + if (isBufferArgs(elements2)) { + var e = staticDraw.elements = elementState.create(elements2, true); + elements2 = elementState.getElements(e); + elementsActive = true; + } else if (elements2) { + elements2 = elementState.getElements(elements2); + elementsActive = true; + } + var result = createStaticDecl(function(env2, scope) { + if (elements2) { + var result2 = env2.link(elements2); + env2.ELEMENTS = result2; + return result2; + } + env2.ELEMENTS = null; + return null; + }); + result.value = elements2; + return result; + } else if (S_ELEMENTS in dynamicOptions) { + elementsActive = true; + var dyn = dynamicOptions[S_ELEMENTS]; + return createDynamicDecl(dyn, function(env2, scope) { + var shared = env2.shared; + var IS_BUFFER_ARGS = shared.isBufferArgs; + var ELEMENT_STATE = shared.elements; + var elementDefn = env2.invoke(scope, dyn); + var elements3 = scope.def("null"); + var elementStream = scope.def(IS_BUFFER_ARGS, "(", elementDefn, ")"); + var ifte = env2.cond(elementStream).then(elements3, "=", ELEMENT_STATE, ".createStream(", elementDefn, ");").else(elements3, "=", ELEMENT_STATE, ".getElements(", elementDefn, ");"); + scope.entry(ifte); + scope.exit( + env2.cond(elementStream).then(ELEMENT_STATE, ".destroyStream(", elements3, ");") + ); + env2.ELEMENTS = elements3; + return elements3; + }); + } else if (vaoActive) { + return new Declaration( + vao.thisDep, + vao.contextDep, + vao.propDep, + function(env2, scope) { + return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.elements + ".getElements(" + env2.shared.vao + ".currentVAO.elements):null"); + } + ); + } + return null; + } + var elements = parseElements(); + function parsePrimitive() { + if (S_PRIMITIVE in staticOptions) { + var primitive2 = staticOptions[S_PRIMITIVE]; + staticDraw.primitive = primitive2; + return createStaticDecl(function(env2, scope) { + return primTypes[primitive2]; + }); + } else if (S_PRIMITIVE in dynamicOptions) { + var dynPrimitive = dynamicOptions[S_PRIMITIVE]; + return createDynamicDecl(dynPrimitive, function(env2, scope) { + var PRIM_TYPES = env2.constants.primTypes; + var prim = env2.invoke(scope, dynPrimitive); + return scope.def(PRIM_TYPES, "[", prim, "]"); + }); + } else if (elementsActive) { + if (isStatic(elements)) { + if (elements.value) { + return createStaticDecl(function(env2, scope) { + return scope.def(env2.ELEMENTS, ".primType"); + }); + } else { + return createStaticDecl(function() { + return GL_TRIANGLES$1; + }); + } + } else { + return new Declaration( + elements.thisDep, + elements.contextDep, + elements.propDep, + function(env2, scope) { + var elements2 = env2.ELEMENTS; + return scope.def(elements2, "?", elements2, ".primType:", GL_TRIANGLES$1); + } + ); + } + } else if (vaoActive) { + return new Declaration( + vao.thisDep, + vao.contextDep, + vao.propDep, + function(env2, scope) { + return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.primitive:" + GL_TRIANGLES$1); + } + ); + } + return null; + } + function parseParam(param, isOffset) { + if (param in staticOptions) { + var value2 = staticOptions[param] | 0; + if (isOffset) { + staticDraw.offset = value2; + } else { + staticDraw.instances = value2; + } + return createStaticDecl(function(env2, scope) { + if (isOffset) { + env2.OFFSET = value2; + } + return value2; + }); + } else if (param in dynamicOptions) { + var dynValue = dynamicOptions[param]; + return createDynamicDecl(dynValue, function(env2, scope) { + var result = env2.invoke(scope, dynValue); + if (isOffset) { + env2.OFFSET = result; + } + return result; + }); + } else if (isOffset) { + if (elementsActive) { + return createStaticDecl(function(env2, scope) { + env2.OFFSET = 0; + return 0; + }); + } else if (vaoActive) { + return new Declaration( + vao.thisDep, + vao.contextDep, + vao.propDep, + function(env2, scope) { + return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.offset:0"); + } + ); + } + } else if (vaoActive) { + return new Declaration( + vao.thisDep, + vao.contextDep, + vao.propDep, + function(env2, scope) { + return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.instances:-1"); + } + ); + } + return null; + } + var OFFSET = parseParam(S_OFFSET, true); + function parseVertCount() { + if (S_COUNT in staticOptions) { + var count3 = staticOptions[S_COUNT] | 0; + staticDraw.count = count3; + return createStaticDecl(function() { + return count3; + }); + } else if (S_COUNT in dynamicOptions) { + var dynCount = dynamicOptions[S_COUNT]; + return createDynamicDecl(dynCount, function(env2, scope) { + var result2 = env2.invoke(scope, dynCount); + return result2; + }); + } else if (elementsActive) { + if (isStatic(elements)) { + if (elements) { + if (OFFSET) { + return new Declaration( + OFFSET.thisDep, + OFFSET.contextDep, + OFFSET.propDep, + function(env2, scope) { + var result2 = scope.def( + env2.ELEMENTS, + ".vertCount-", + env2.OFFSET + ); + return result2; + } + ); + } else { + return createStaticDecl(function(env2, scope) { + return scope.def(env2.ELEMENTS, ".vertCount"); + }); + } + } else { + var result = createStaticDecl(function() { + return -1; + }); + return result; + } + } else { + var variable = new Declaration( + elements.thisDep || OFFSET.thisDep, + elements.contextDep || OFFSET.contextDep, + elements.propDep || OFFSET.propDep, + function(env2, scope) { + var elements2 = env2.ELEMENTS; + if (env2.OFFSET) { + return scope.def( + elements2, + "?", + elements2, + ".vertCount-", + env2.OFFSET, + ":-1" + ); + } + return scope.def(elements2, "?", elements2, ".vertCount:-1"); + } + ); + return variable; + } + } else if (vaoActive) { + var countVariable = new Declaration( + vao.thisDep, + vao.contextDep, + vao.propDep, + function(env2, scope) { + return scope.def(env2.shared.vao, ".currentVAO?", env2.shared.vao, ".currentVAO.count:-1"); + } + ); + return countVariable; + } + return null; + } + var primitive = parsePrimitive(); + var count2 = parseVertCount(); + var instances = parseParam(S_INSTANCES, false); + return { + elements, + primitive, + count: count2, + instances, + offset: OFFSET, + vao, + vaoActive, + elementsActive, + // static draw props + static: staticDraw + }; + } + function parseGLState(options, env) { + var staticOptions = options.static; + var dynamicOptions = options.dynamic; + var STATE = {}; + GL_STATE_NAMES.forEach(function(prop) { + var param = propName(prop); + function parseParam(parseStatic, parseDynamic) { + if (prop in staticOptions) { + var value2 = parseStatic(staticOptions[prop]); + STATE[param] = createStaticDecl(function() { + return value2; + }); + } else if (prop in dynamicOptions) { + var dyn = dynamicOptions[prop]; + STATE[param] = createDynamicDecl(dyn, function(env2, scope) { + return parseDynamic(env2, scope, env2.invoke(scope, dyn)); + }); + } + } + switch (prop) { + case S_CULL_ENABLE: + case S_BLEND_ENABLE: + case S_DITHER: + case S_STENCIL_ENABLE: + case S_DEPTH_ENABLE: + case S_SCISSOR_ENABLE: + case S_POLYGON_OFFSET_ENABLE: + case S_SAMPLE_ALPHA: + case S_SAMPLE_ENABLE: + case S_DEPTH_MASK: + return parseParam( + function(value2) { + return value2; + }, + function(env2, scope, value2) { + return value2; + } + ); + case S_DEPTH_FUNC: + return parseParam( + function(value2) { + return compareFuncs[value2]; + }, + function(env2, scope, value2) { + var COMPARE_FUNCS = env2.constants.compareFuncs; + return scope.def(COMPARE_FUNCS, "[", value2, "]"); + } + ); + case S_DEPTH_RANGE: + return parseParam( + function(value2) { + return value2; + }, + function(env2, scope, value2) { + var Z_NEAR = scope.def("+", value2, "[0]"); + var Z_FAR = scope.def("+", value2, "[1]"); + return [Z_NEAR, Z_FAR]; + } + ); + case S_BLEND_FUNC: + return parseParam( + function(value2) { + var srcRGB = "srcRGB" in value2 ? value2.srcRGB : value2.src; + var srcAlpha = "srcAlpha" in value2 ? value2.srcAlpha : value2.src; + var dstRGB = "dstRGB" in value2 ? value2.dstRGB : value2.dst; + var dstAlpha = "dstAlpha" in value2 ? value2.dstAlpha : value2.dst; + return [ + blendFuncs[srcRGB], + blendFuncs[dstRGB], + blendFuncs[srcAlpha], + blendFuncs[dstAlpha] + ]; + }, + function(env2, scope, value2) { + var BLEND_FUNCS = env2.constants.blendFuncs; + function read(prefix, suffix) { + var func = scope.def( + '"', + prefix, + suffix, + '" in ', + value2, + "?", + value2, + ".", + prefix, + suffix, + ":", + value2, + ".", + prefix + ); + return func; + } + var srcRGB = read("src", "RGB"); + var dstRGB = read("dst", "RGB"); + var SRC_RGB = scope.def(BLEND_FUNCS, "[", srcRGB, "]"); + var SRC_ALPHA = scope.def(BLEND_FUNCS, "[", read("src", "Alpha"), "]"); + var DST_RGB = scope.def(BLEND_FUNCS, "[", dstRGB, "]"); + var DST_ALPHA = scope.def(BLEND_FUNCS, "[", read("dst", "Alpha"), "]"); + return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA]; + } + ); + case S_BLEND_EQUATION: + return parseParam( + function(value2) { + if (typeof value2 === "string") { + return [ + blendEquations[value2], + blendEquations[value2] + ]; + } else if (typeof value2 === "object") { + return [ + blendEquations[value2.rgb], + blendEquations[value2.alpha] + ]; + } else ; + }, + function(env2, scope, value2) { + var BLEND_EQUATIONS = env2.constants.blendEquations; + var RGB = scope.def(); + var ALPHA = scope.def(); + var ifte = env2.cond("typeof ", value2, '==="string"'); + ifte.then( + RGB, + "=", + ALPHA, + "=", + BLEND_EQUATIONS, + "[", + value2, + "];" + ); + ifte.else( + RGB, + "=", + BLEND_EQUATIONS, + "[", + value2, + ".rgb];", + ALPHA, + "=", + BLEND_EQUATIONS, + "[", + value2, + ".alpha];" + ); + scope(ifte); + return [RGB, ALPHA]; + } + ); + case S_BLEND_COLOR: + return parseParam( + function(value2) { + return loop(4, function(i) { + return +value2[i]; + }); + }, + function(env2, scope, value2) { + return loop(4, function(i) { + return scope.def("+", value2, "[", i, "]"); + }); + } + ); + case S_STENCIL_MASK: + return parseParam( + function(value2) { + return value2 | 0; + }, + function(env2, scope, value2) { + return scope.def(value2, "|0"); + } + ); + case S_STENCIL_FUNC: + return parseParam( + function(value2) { + var cmp = value2.cmp || "keep"; + var ref2 = value2.ref || 0; + var mask = "mask" in value2 ? value2.mask : -1; + return [ + compareFuncs[cmp], + ref2, + mask + ]; + }, + function(env2, scope, value2) { + var COMPARE_FUNCS = env2.constants.compareFuncs; + var cmp = scope.def( + '"cmp" in ', + value2, + "?", + COMPARE_FUNCS, + "[", + value2, + ".cmp]", + ":", + GL_KEEP + ); + var ref2 = scope.def(value2, ".ref|0"); + var mask = scope.def( + '"mask" in ', + value2, + "?", + value2, + ".mask|0:-1" + ); + return [cmp, ref2, mask]; + } + ); + case S_STENCIL_OPFRONT: + case S_STENCIL_OPBACK: + return parseParam( + function(value2) { + var fail = value2.fail || "keep"; + var zfail = value2.zfail || "keep"; + var zpass = value2.zpass || "keep"; + return [ + prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT, + stencilOps[fail], + stencilOps[zfail], + stencilOps[zpass] + ]; + }, + function(env2, scope, value2) { + var STENCIL_OPS = env2.constants.stencilOps; + function read(name2) { + return scope.def( + '"', + name2, + '" in ', + value2, + "?", + STENCIL_OPS, + "[", + value2, + ".", + name2, + "]:", + GL_KEEP + ); + } + return [ + prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT, + read("fail"), + read("zfail"), + read("zpass") + ]; + } + ); + case S_POLYGON_OFFSET_OFFSET: + return parseParam( + function(value2) { + var factor = value2.factor | 0; + var units = value2.units | 0; + return [factor, units]; + }, + function(env2, scope, value2) { + var FACTOR = scope.def(value2, ".factor|0"); + var UNITS = scope.def(value2, ".units|0"); + return [FACTOR, UNITS]; + } + ); + case S_CULL_FACE: + return parseParam( + function(value2) { + var face = 0; + if (value2 === "front") { + face = GL_FRONT; + } else if (value2 === "back") { + face = GL_BACK; + } + return face; + }, + function(env2, scope, value2) { + return scope.def(value2, '==="front"?', GL_FRONT, ":", GL_BACK); + } + ); + case S_LINE_WIDTH: + return parseParam( + function(value2) { + return value2; + }, + function(env2, scope, value2) { + return value2; + } + ); + case S_FRONT_FACE: + return parseParam( + function(value2) { + return orientationType[value2]; + }, + function(env2, scope, value2) { + return scope.def(value2 + '==="cw"?' + GL_CW + ":" + GL_CCW); + } + ); + case S_COLOR_MASK: + return parseParam( + function(value2) { + return value2.map(function(v) { + return !!v; + }); + }, + function(env2, scope, value2) { + return loop(4, function(i) { + return "!!" + value2 + "[" + i + "]"; + }); + } + ); + case S_SAMPLE_COVERAGE: + return parseParam( + function(value2) { + var sampleValue = "value" in value2 ? value2.value : 1; + var sampleInvert = !!value2.invert; + return [sampleValue, sampleInvert]; + }, + function(env2, scope, value2) { + var VALUE2 = scope.def( + '"value" in ', + value2, + "?+", + value2, + ".value:1" + ); + var INVERT = scope.def("!!", value2, ".invert"); + return [VALUE2, INVERT]; + } + ); + } + }); + return STATE; + } + function parseUniforms(uniforms, env) { + var staticUniforms = uniforms.static; + var dynamicUniforms = uniforms.dynamic; + var UNIFORMS = {}; + Object.keys(staticUniforms).forEach(function(name2) { + var value2 = staticUniforms[name2]; + var result; + if (typeof value2 === "number" || typeof value2 === "boolean") { + result = createStaticDecl(function() { + return value2; + }); + } else if (typeof value2 === "function") { + var reglType = value2._reglType; + if (reglType === "texture2d" || reglType === "textureCube") { + result = createStaticDecl(function(env2) { + return env2.link(value2); + }); + } else if (reglType === "framebuffer" || reglType === "framebufferCube") { + result = createStaticDecl(function(env2) { + return env2.link(value2.color[0]); + }); + } else ; + } else if (isArrayLike(value2)) { + result = createStaticDecl(function(env2) { + var ITEM = env2.global.def( + "[", + loop(value2.length, function(i) { + return value2[i]; + }), + "]" + ); + return ITEM; + }); + } else ; + result.value = value2; + UNIFORMS[name2] = result; + }); + Object.keys(dynamicUniforms).forEach(function(key) { + var dyn = dynamicUniforms[key]; + UNIFORMS[key] = createDynamicDecl(dyn, function(env2, scope) { + return env2.invoke(scope, dyn); + }); + }); + return UNIFORMS; + } + function parseAttributes(attributes2, env) { + var staticAttributes = attributes2.static; + var dynamicAttributes = attributes2.dynamic; + var attributeDefs = {}; + Object.keys(staticAttributes).forEach(function(attribute) { + var value2 = staticAttributes[attribute]; + var id = stringStore.id(attribute); + var record = new AttributeRecord2(); + if (isBufferArgs(value2)) { + record.state = ATTRIB_STATE_POINTER; + record.buffer = bufferState.getBuffer( + bufferState.create(value2, GL_ARRAY_BUFFER$2, false, true) + ); + record.type = 0; + } else { + var buffer2 = bufferState.getBuffer(value2); + if (buffer2) { + record.state = ATTRIB_STATE_POINTER; + record.buffer = buffer2; + record.type = 0; + } else { + if ("constant" in value2) { + var constant2 = value2.constant; + record.buffer = "null"; + record.state = ATTRIB_STATE_CONSTANT; + if (typeof constant2 === "number") { + record.x = constant2; + } else { + CUTE_COMPONENTS.forEach(function(c, i) { + if (i < constant2.length) { + record[c] = constant2[i]; + } + }); + } + } else { + if (isBufferArgs(value2.buffer)) { + buffer2 = bufferState.getBuffer( + bufferState.create(value2.buffer, GL_ARRAY_BUFFER$2, false, true) + ); + } else { + buffer2 = bufferState.getBuffer(value2.buffer); + } + var offset = value2.offset | 0; + var stride = value2.stride | 0; + var size = value2.size | 0; + var normalized = !!value2.normalized; + var type = 0; + if ("type" in value2) { + type = glTypes[value2.type]; + } + var divisor = value2.divisor | 0; + record.buffer = buffer2; + record.state = ATTRIB_STATE_POINTER; + record.size = size; + record.normalized = normalized; + record.type = type || buffer2.dtype; + record.offset = offset; + record.stride = stride; + record.divisor = divisor; + } + } + } + attributeDefs[attribute] = createStaticDecl(function(env2, scope) { + var cache2 = env2.attribCache; + if (id in cache2) { + return cache2[id]; + } + var result = { + isStream: false + }; + Object.keys(record).forEach(function(key) { + result[key] = record[key]; + }); + if (record.buffer) { + result.buffer = env2.link(record.buffer); + result.type = result.type || result.buffer + ".dtype"; + } + cache2[id] = result; + return result; + }); + }); + Object.keys(dynamicAttributes).forEach(function(attribute) { + var dyn = dynamicAttributes[attribute]; + function appendAttributeCode(env2, block) { + var VALUE2 = env2.invoke(block, dyn); + var shared = env2.shared; + var constants2 = env2.constants; + var IS_BUFFER_ARGS = shared.isBufferArgs; + var BUFFER_STATE = shared.buffer; + var result = { + isStream: block.def(false) + }; + var defaultRecord = new AttributeRecord2(); + defaultRecord.state = ATTRIB_STATE_POINTER; + Object.keys(defaultRecord).forEach(function(key) { + result[key] = block.def("" + defaultRecord[key]); + }); + var BUFFER2 = result.buffer; + var TYPE = result.type; + block( + "if(", + IS_BUFFER_ARGS, + "(", + VALUE2, + ")){", + result.isStream, + "=true;", + BUFFER2, + "=", + BUFFER_STATE, + ".createStream(", + GL_ARRAY_BUFFER$2, + ",", + VALUE2, + ");", + TYPE, + "=", + BUFFER2, + ".dtype;", + "}else{", + BUFFER2, + "=", + BUFFER_STATE, + ".getBuffer(", + VALUE2, + ");", + "if(", + BUFFER2, + "){", + TYPE, + "=", + BUFFER2, + ".dtype;", + '}else if("constant" in ', + VALUE2, + "){", + result.state, + "=", + ATTRIB_STATE_CONSTANT, + ";", + "if(typeof " + VALUE2 + '.constant === "number"){', + result[CUTE_COMPONENTS[0]], + "=", + VALUE2, + ".constant;", + CUTE_COMPONENTS.slice(1).map(function(n) { + return result[n]; + }).join("="), + "=0;", + "}else{", + CUTE_COMPONENTS.map(function(name2, i) { + return result[name2] + "=" + VALUE2 + ".constant.length>" + i + "?" + VALUE2 + ".constant[" + i + "]:0;"; + }).join(""), + "}}else{", + "if(", + IS_BUFFER_ARGS, + "(", + VALUE2, + ".buffer)){", + BUFFER2, + "=", + BUFFER_STATE, + ".createStream(", + GL_ARRAY_BUFFER$2, + ",", + VALUE2, + ".buffer);", + "}else{", + BUFFER2, + "=", + BUFFER_STATE, + ".getBuffer(", + VALUE2, + ".buffer);", + "}", + TYPE, + '="type" in ', + VALUE2, + "?", + constants2.glTypes, + "[", + VALUE2, + ".type]:", + BUFFER2, + ".dtype;", + result.normalized, + "=!!", + VALUE2, + ".normalized;" + ); + function emitReadRecord(name2) { + block(result[name2], "=", VALUE2, ".", name2, "|0;"); + } + emitReadRecord("size"); + emitReadRecord("offset"); + emitReadRecord("stride"); + emitReadRecord("divisor"); + block("}}"); + block.exit( + "if(", + result.isStream, + "){", + BUFFER_STATE, + ".destroyStream(", + BUFFER2, + ");", + "}" + ); + return result; + } + attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode); + }); + return attributeDefs; + } + function parseContext(context2) { + var staticContext = context2.static; + var dynamicContext = context2.dynamic; + var result = {}; + Object.keys(staticContext).forEach(function(name2) { + var value2 = staticContext[name2]; + result[name2] = createStaticDecl(function(env, scope) { + if (typeof value2 === "number" || typeof value2 === "boolean") { + return "" + value2; + } else { + return env.link(value2); + } + }); + }); + Object.keys(dynamicContext).forEach(function(name2) { + var dyn = dynamicContext[name2]; + result[name2] = createDynamicDecl(dyn, function(env, scope) { + return env.invoke(scope, dyn); + }); + }); + return result; + } + function parseArguments(options, attributes2, uniforms, context2, env) { + options.static; + options.dynamic; + var attribLocations = parseAttribLocations(options, attributes2); + var framebuffer = parseFramebuffer(options); + var viewportAndScissor = parseViewportScissor(options, framebuffer); + var draw8 = parseDraw(options); + var state = parseGLState(options); + var shader = parseProgram(options, env, attribLocations); + function copyBox(name2) { + var defn = viewportAndScissor[name2]; + if (defn) { + state[name2] = defn; + } + } + copyBox(S_VIEWPORT); + copyBox(propName(S_SCISSOR_BOX)); + var dirty = Object.keys(state).length > 0; + var result = { + framebuffer, + draw: draw8, + shader, + state, + dirty, + scopeVAO: null, + drawVAO: null, + useVAO: false, + attributes: {} + }; + result.profile = parseProfile(options); + result.uniforms = parseUniforms(uniforms); + result.drawVAO = result.scopeVAO = draw8.vao; + if (!result.drawVAO && shader.program && !attribLocations && extensions.angle_instanced_arrays && draw8.static.elements) { + var useVAO = true; + var staticBindings = shader.program.attributes.map(function(attr) { + var binding = attributes2.static[attr]; + useVAO = useVAO && !!binding; + return binding; + }); + if (useVAO && staticBindings.length > 0) { + var vao = attributeState.getVAO(attributeState.createVAO({ + attributes: staticBindings, + elements: draw8.static.elements + })); + result.drawVAO = new Declaration(null, null, null, function(env2, scope) { + return env2.link(vao); + }); + result.useVAO = true; + } + } + if (attribLocations) { + result.useVAO = true; + } else { + result.attributes = parseAttributes(attributes2); + } + result.context = parseContext(context2); + return result; + } + function emitContext(env, scope, context2) { + var shared = env.shared; + var CONTEXT = shared.context; + var contextEnter = env.scope(); + Object.keys(context2).forEach(function(name2) { + scope.save(CONTEXT, "." + name2); + var defn = context2[name2]; + var value2 = defn.append(env, scope); + if (Array.isArray(value2)) { + contextEnter(CONTEXT, ".", name2, "=[", value2.join(), "];"); + } else { + contextEnter(CONTEXT, ".", name2, "=", value2, ";"); + } + }); + scope(contextEnter); + } + function emitPollFramebuffer(env, scope, framebuffer, skipCheck) { + var shared = env.shared; + var GL = shared.gl; + var FRAMEBUFFER_STATE = shared.framebuffer; + var EXT_DRAW_BUFFERS; + if (extDrawBuffers) { + EXT_DRAW_BUFFERS = scope.def(shared.extensions, ".webgl_draw_buffers"); + } + var constants2 = env.constants; + var DRAW_BUFFERS = constants2.drawBuffer; + var BACK_BUFFER = constants2.backBuffer; + var NEXT; + if (framebuffer) { + NEXT = framebuffer.append(env, scope); + } else { + NEXT = scope.def(FRAMEBUFFER_STATE, ".next"); + } + if (!skipCheck) { + scope("if(", NEXT, "!==", FRAMEBUFFER_STATE, ".cur){"); + } + scope( + "if(", + NEXT, + "){", + GL, + ".bindFramebuffer(", + GL_FRAMEBUFFER$2, + ",", + NEXT, + ".framebuffer);" + ); + if (extDrawBuffers) { + scope( + EXT_DRAW_BUFFERS, + ".drawBuffersWEBGL(", + DRAW_BUFFERS, + "[", + NEXT, + ".colorAttachments.length]);" + ); + } + scope( + "}else{", + GL, + ".bindFramebuffer(", + GL_FRAMEBUFFER$2, + ",null);" + ); + if (extDrawBuffers) { + scope(EXT_DRAW_BUFFERS, ".drawBuffersWEBGL(", BACK_BUFFER, ");"); + } + scope( + "}", + FRAMEBUFFER_STATE, + ".cur=", + NEXT, + ";" + ); + if (!skipCheck) { + scope("}"); + } + } + function emitPollState(env, scope, args) { + var shared = env.shared; + var GL = shared.gl; + var CURRENT_VARS = env.current; + var NEXT_VARS = env.next; + var CURRENT_STATE = shared.current; + var NEXT_STATE = shared.next; + var block = env.cond(CURRENT_STATE, ".dirty"); + GL_STATE_NAMES.forEach(function(prop) { + var param = propName(prop); + if (param in args.state) { + return; + } + var NEXT, CURRENT; + if (param in NEXT_VARS) { + NEXT = NEXT_VARS[param]; + CURRENT = CURRENT_VARS[param]; + var parts = loop(currentState[param].length, function(i) { + return block.def(NEXT, "[", i, "]"); + }); + block(env.cond(parts.map(function(p, i) { + return p + "!==" + CURRENT + "[" + i + "]"; + }).join("||")).then( + GL, + ".", + GL_VARIABLES[param], + "(", + parts, + ");", + parts.map(function(p, i) { + return CURRENT + "[" + i + "]=" + p; + }).join(";"), + ";" + )); + } else { + NEXT = block.def(NEXT_STATE, ".", param); + var ifte = env.cond(NEXT, "!==", CURRENT_STATE, ".", param); + block(ifte); + if (param in GL_FLAGS) { + ifte( + env.cond(NEXT).then(GL, ".enable(", GL_FLAGS[param], ");").else(GL, ".disable(", GL_FLAGS[param], ");"), + CURRENT_STATE, + ".", + param, + "=", + NEXT, + ";" + ); + } else { + ifte( + GL, + ".", + GL_VARIABLES[param], + "(", + NEXT, + ");", + CURRENT_STATE, + ".", + param, + "=", + NEXT, + ";" + ); + } + } + }); + if (Object.keys(args.state).length === 0) { + block(CURRENT_STATE, ".dirty=false;"); + } + scope(block); + } + function emitSetOptions(env, scope, options, filter2) { + var shared = env.shared; + var CURRENT_VARS = env.current; + var CURRENT_STATE = shared.current; + var GL = shared.gl; + var VALUE2; + sortState(Object.keys(options)).forEach(function(param) { + var defn = options[param]; + if (filter2 && !filter2(defn)) { + return; + } + var variable = defn.append(env, scope); + if (GL_FLAGS[param]) { + var flag = GL_FLAGS[param]; + if (isStatic(defn)) { + VALUE2 = env.link(variable, { stable: true }); + scope(env.cond(VALUE2).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");")); + scope(CURRENT_STATE, ".", param, "=", VALUE2, ";"); + } else { + scope(env.cond(variable).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");")); + scope(CURRENT_STATE, ".", param, "=", variable, ";"); + } + } else if (isArrayLike(variable)) { + var CURRENT = CURRENT_VARS[param]; + scope( + GL, + ".", + GL_VARIABLES[param], + "(", + variable, + ");", + variable.map(function(v, i) { + return CURRENT + "[" + i + "]=" + v; + }).join(";"), + ";" + ); + } else { + if (isStatic(defn)) { + VALUE2 = env.link(variable, { stable: true }); + scope( + GL, + ".", + GL_VARIABLES[param], + "(", + VALUE2, + ");", + CURRENT_STATE, + ".", + param, + "=", + VALUE2, + ";" + ); + } else { + scope( + GL, + ".", + GL_VARIABLES[param], + "(", + variable, + ");", + CURRENT_STATE, + ".", + param, + "=", + variable, + ";" + ); + } + } + }); + } + function injectExtensions(env, scope) { + if (extInstancing) { + env.instancing = scope.def( + env.shared.extensions, + ".angle_instanced_arrays" + ); + } + } + function emitProfile(env, scope, args, useScope, incrementCounter) { + var shared = env.shared; + var STATS = env.stats; + var CURRENT_STATE = shared.current; + var TIMER = shared.timer; + var profileArg = args.profile; + function perfCounter() { + if (typeof performance === "undefined") { + return "Date.now()"; + } else { + return "performance.now()"; + } + } + var CPU_START, QUERY_COUNTER; + function emitProfileStart(block) { + CPU_START = scope.def(); + block(CPU_START, "=", perfCounter(), ";"); + if (typeof incrementCounter === "string") { + block(STATS, ".count+=", incrementCounter, ";"); + } else { + block(STATS, ".count++;"); + } + if (timer) { + if (useScope) { + QUERY_COUNTER = scope.def(); + block(QUERY_COUNTER, "=", TIMER, ".getNumPendingQueries();"); + } else { + block(TIMER, ".beginQuery(", STATS, ");"); + } + } + } + function emitProfileEnd(block) { + block(STATS, ".cpuTime+=", perfCounter(), "-", CPU_START, ";"); + if (timer) { + if (useScope) { + block( + TIMER, + ".pushScopeStats(", + QUERY_COUNTER, + ",", + TIMER, + ".getNumPendingQueries(),", + STATS, + ");" + ); + } else { + block(TIMER, ".endQuery();"); + } + } + } + function scopeProfile(value2) { + var prev = scope.def(CURRENT_STATE, ".profile"); + scope(CURRENT_STATE, ".profile=", value2, ";"); + scope.exit(CURRENT_STATE, ".profile=", prev, ";"); + } + var USE_PROFILE; + if (profileArg) { + if (isStatic(profileArg)) { + if (profileArg.enable) { + emitProfileStart(scope); + emitProfileEnd(scope.exit); + scopeProfile("true"); + } else { + scopeProfile("false"); + } + return; + } + USE_PROFILE = profileArg.append(env, scope); + scopeProfile(USE_PROFILE); + } else { + USE_PROFILE = scope.def(CURRENT_STATE, ".profile"); + } + var start = env.block(); + emitProfileStart(start); + scope("if(", USE_PROFILE, "){", start, "}"); + var end = env.block(); + emitProfileEnd(end); + scope.exit("if(", USE_PROFILE, "){", end, "}"); + } + function emitAttributes(env, scope, args, attributes2, filter2) { + var shared = env.shared; + function typeLength(x) { + switch (x) { + case GL_FLOAT_VEC2: + case GL_INT_VEC2: + case GL_BOOL_VEC2: + return 2; + case GL_FLOAT_VEC3: + case GL_INT_VEC3: + case GL_BOOL_VEC3: + return 3; + case GL_FLOAT_VEC4: + case GL_INT_VEC4: + case GL_BOOL_VEC4: + return 4; + default: + return 1; + } + } + function emitBindAttribute(ATTRIBUTE, size, record) { + var GL = shared.gl; + var LOCATION = scope.def(ATTRIBUTE, ".location"); + var BINDING = scope.def(shared.attributes, "[", LOCATION, "]"); + var STATE = record.state; + var BUFFER2 = record.buffer; + var CONST_COMPONENTS = [ + record.x, + record.y, + record.z, + record.w + ]; + var COMMON_KEYS = [ + "buffer", + "normalized", + "offset", + "stride" + ]; + function emitBuffer() { + scope( + "if(!", + BINDING, + ".buffer){", + GL, + ".enableVertexAttribArray(", + LOCATION, + ");}" + ); + var TYPE = record.type; + var SIZE; + if (!record.size) { + SIZE = size; + } else { + SIZE = scope.def(record.size, "||", size); + } + scope( + "if(", + BINDING, + ".type!==", + TYPE, + "||", + BINDING, + ".size!==", + SIZE, + "||", + COMMON_KEYS.map(function(key) { + return BINDING + "." + key + "!==" + record[key]; + }).join("||"), + "){", + GL, + ".bindBuffer(", + GL_ARRAY_BUFFER$2, + ",", + BUFFER2, + ".buffer);", + GL, + ".vertexAttribPointer(", + [ + LOCATION, + SIZE, + TYPE, + record.normalized, + record.stride, + record.offset + ], + ");", + BINDING, + ".type=", + TYPE, + ";", + BINDING, + ".size=", + SIZE, + ";", + COMMON_KEYS.map(function(key) { + return BINDING + "." + key + "=" + record[key] + ";"; + }).join(""), + "}" + ); + if (extInstancing) { + var DIVISOR = record.divisor; + scope( + "if(", + BINDING, + ".divisor!==", + DIVISOR, + "){", + env.instancing, + ".vertexAttribDivisorANGLE(", + [LOCATION, DIVISOR], + ");", + BINDING, + ".divisor=", + DIVISOR, + ";}" + ); + } + } + function emitConstant() { + scope( + "if(", + BINDING, + ".buffer){", + GL, + ".disableVertexAttribArray(", + LOCATION, + ");", + BINDING, + ".buffer=null;", + "}if(", + CUTE_COMPONENTS.map(function(c, i) { + return BINDING + "." + c + "!==" + CONST_COMPONENTS[i]; + }).join("||"), + "){", + GL, + ".vertexAttrib4f(", + LOCATION, + ",", + CONST_COMPONENTS, + ");", + CUTE_COMPONENTS.map(function(c, i) { + return BINDING + "." + c + "=" + CONST_COMPONENTS[i] + ";"; + }).join(""), + "}" + ); + } + if (STATE === ATTRIB_STATE_POINTER) { + emitBuffer(); + } else if (STATE === ATTRIB_STATE_CONSTANT) { + emitConstant(); + } else { + scope("if(", STATE, "===", ATTRIB_STATE_POINTER, "){"); + emitBuffer(); + scope("}else{"); + emitConstant(); + scope("}"); + } + } + attributes2.forEach(function(attribute) { + var name2 = attribute.name; + var arg = args.attributes[name2]; + var record; + if (arg) { + if (!filter2(arg)) { + return; + } + record = arg.append(env, scope); + } else { + if (!filter2(SCOPE_DECL)) { + return; + } + var scopeAttrib = env.scopeAttrib(name2); + record = {}; + Object.keys(new AttributeRecord2()).forEach(function(key) { + record[key] = scope.def(scopeAttrib, ".", key); + }); + } + emitBindAttribute( + env.link(attribute), + typeLength(attribute.info.type), + record + ); + }); + } + function emitUniforms(env, scope, args, uniforms, filter2, isBatchInnerLoop) { + var shared = env.shared; + var GL = shared.gl; + var infix; + for (var i = 0; i < uniforms.length; ++i) { + var uniform = uniforms[i]; + var name2 = uniform.name; + var type = uniform.info.type; + var arg = args.uniforms[name2]; + var UNIFORM = env.link(uniform); + var LOCATION = UNIFORM + ".location"; + var VALUE2; + if (arg) { + if (!filter2(arg)) { + continue; + } + if (isStatic(arg)) { + var value2 = arg.value; + if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) { + var TEX_VALUE = env.link(value2._texture || value2.color[0]._texture); + scope(GL, ".uniform1i(", LOCATION, ",", TEX_VALUE + ".bind());"); + scope.exit(TEX_VALUE, ".unbind();"); + } else if (type === GL_FLOAT_MAT2 || type === GL_FLOAT_MAT3 || type === GL_FLOAT_MAT4) { + var MAT_VALUE = env.global.def("new Float32Array([" + Array.prototype.slice.call(value2) + "])"); + var dim = 2; + if (type === GL_FLOAT_MAT3) { + dim = 3; + } else if (type === GL_FLOAT_MAT4) { + dim = 4; + } + scope( + GL, + ".uniformMatrix", + dim, + "fv(", + LOCATION, + ",false,", + MAT_VALUE, + ");" + ); + } else { + switch (type) { + case GL_FLOAT$7: + infix = "1f"; + break; + case GL_FLOAT_VEC2: + infix = "2f"; + break; + case GL_FLOAT_VEC3: + infix = "3f"; + break; + case GL_FLOAT_VEC4: + infix = "4f"; + break; + case GL_BOOL: + infix = "1i"; + break; + case GL_INT$2: + infix = "1i"; + break; + case GL_BOOL_VEC2: + infix = "2i"; + break; + case GL_INT_VEC2: + infix = "2i"; + break; + case GL_BOOL_VEC3: + infix = "3i"; + break; + case GL_INT_VEC3: + infix = "3i"; + break; + case GL_BOOL_VEC4: + infix = "4i"; + break; + case GL_INT_VEC4: + infix = "4i"; + break; + } + scope( + GL, + ".uniform", + infix, + "(", + LOCATION, + ",", + isArrayLike(value2) ? Array.prototype.slice.call(value2) : value2, + ");" + ); + } + continue; + } else { + VALUE2 = arg.append(env, scope); + } + } else { + if (!filter2(SCOPE_DECL)) { + continue; + } + VALUE2 = scope.def(shared.uniforms, "[", stringStore.id(name2), "]"); + } + if (type === GL_SAMPLER_2D) { + scope( + "if(", + VALUE2, + "&&", + VALUE2, + '._reglType==="framebuffer"){', + VALUE2, + "=", + VALUE2, + ".color[0];", + "}" + ); + } else if (type === GL_SAMPLER_CUBE) { + scope( + "if(", + VALUE2, + "&&", + VALUE2, + '._reglType==="framebufferCube"){', + VALUE2, + "=", + VALUE2, + ".color[0];", + "}" + ); + } + var unroll = 1; + switch (type) { + case GL_SAMPLER_2D: + case GL_SAMPLER_CUBE: + var TEX = scope.def(VALUE2, "._texture"); + scope(GL, ".uniform1i(", LOCATION, ",", TEX, ".bind());"); + scope.exit(TEX, ".unbind();"); + continue; + case GL_INT$2: + case GL_BOOL: + infix = "1i"; + break; + case GL_INT_VEC2: + case GL_BOOL_VEC2: + infix = "2i"; + unroll = 2; + break; + case GL_INT_VEC3: + case GL_BOOL_VEC3: + infix = "3i"; + unroll = 3; + break; + case GL_INT_VEC4: + case GL_BOOL_VEC4: + infix = "4i"; + unroll = 4; + break; + case GL_FLOAT$7: + infix = "1f"; + break; + case GL_FLOAT_VEC2: + infix = "2f"; + unroll = 2; + break; + case GL_FLOAT_VEC3: + infix = "3f"; + unroll = 3; + break; + case GL_FLOAT_VEC4: + infix = "4f"; + unroll = 4; + break; + case GL_FLOAT_MAT2: + infix = "Matrix2fv"; + break; + case GL_FLOAT_MAT3: + infix = "Matrix3fv"; + break; + case GL_FLOAT_MAT4: + infix = "Matrix4fv"; + break; + } + if (infix.charAt(0) === "M") { + scope(GL, ".uniform", infix, "(", LOCATION, ","); + var matSize = Math.pow(type - GL_FLOAT_MAT2 + 2, 2); + var STORAGE = env.global.def("new Float32Array(", matSize, ")"); + if (Array.isArray(VALUE2)) { + scope( + "false,(", + loop(matSize, function(i2) { + return STORAGE + "[" + i2 + "]=" + VALUE2[i2]; + }), + ",", + STORAGE, + ")" + ); + } else { + scope( + "false,(Array.isArray(", + VALUE2, + ")||", + VALUE2, + " instanceof Float32Array)?", + VALUE2, + ":(", + loop(matSize, function(i2) { + return STORAGE + "[" + i2 + "]=" + VALUE2 + "[" + i2 + "]"; + }), + ",", + STORAGE, + ")" + ); + } + scope(");"); + } else if (unroll > 1) { + var prev = []; + var cur = []; + for (var j = 0; j < unroll; ++j) { + if (Array.isArray(VALUE2)) { + cur.push(VALUE2[j]); + } else { + cur.push(scope.def(VALUE2 + "[" + j + "]")); + } + if (isBatchInnerLoop) { + prev.push(scope.def()); + } + } + if (isBatchInnerLoop) { + scope("if(!", env.batchId, "||", prev.map(function(p, i2) { + return p + "!==" + cur[i2]; + }).join("||"), "){", prev.map(function(p, i2) { + return p + "=" + cur[i2] + ";"; + }).join("")); + } + scope(GL, ".uniform", infix, "(", LOCATION, ",", cur.join(","), ");"); + if (isBatchInnerLoop) { + scope("}"); + } + } else { + if (isBatchInnerLoop) { + var prevS = scope.def(); + scope( + "if(!", + env.batchId, + "||", + prevS, + "!==", + VALUE2, + "){", + prevS, + "=", + VALUE2, + ";" + ); + } + scope(GL, ".uniform", infix, "(", LOCATION, ",", VALUE2, ");"); + if (isBatchInnerLoop) { + scope("}"); + } + } + } + } + function emitDraw(env, outer, inner, args) { + var shared = env.shared; + var GL = shared.gl; + var DRAW_STATE = shared.draw; + var drawOptions = args.draw; + function emitElements() { + var defn = drawOptions.elements; + var ELEMENTS2; + var scope = outer; + if (defn) { + if (defn.contextDep && args.contextDynamic || defn.propDep) { + scope = inner; + } + ELEMENTS2 = defn.append(env, scope); + if (drawOptions.elementsActive) { + scope( + "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" + ); + } + } else { + ELEMENTS2 = scope.def(); + scope( + ELEMENTS2, + "=", + DRAW_STATE, + ".", + S_ELEMENTS, + ";", + "if(", + ELEMENTS2, + "){", + GL, + ".bindBuffer(", + GL_ELEMENT_ARRAY_BUFFER$2, + ",", + ELEMENTS2, + ".buffer.buffer);}", + "else if(", + shared.vao, + ".currentVAO){", + ELEMENTS2, + "=", + env.shared.elements + ".getElements(" + shared.vao, + ".currentVAO.elements);", + !extVertexArrays ? "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" : "", + "}" + ); + } + return ELEMENTS2; + } + function emitCount() { + var defn = drawOptions.count; + var COUNT2; + var scope = outer; + if (defn) { + if (defn.contextDep && args.contextDynamic || defn.propDep) { + scope = inner; + } + COUNT2 = defn.append(env, scope); + } else { + COUNT2 = scope.def(DRAW_STATE, ".", S_COUNT); + } + return COUNT2; + } + var ELEMENTS = emitElements(); + function emitValue(name2) { + var defn = drawOptions[name2]; + if (defn) { + if (defn.contextDep && args.contextDynamic || defn.propDep) { + return defn.append(env, inner); + } else { + return defn.append(env, outer); + } + } else { + return outer.def(DRAW_STATE, ".", name2); + } + } + var PRIMITIVE = emitValue(S_PRIMITIVE); + var OFFSET = emitValue(S_OFFSET); + var COUNT = emitCount(); + if (typeof COUNT === "number") { + if (COUNT === 0) { + return; + } + } else { + inner("if(", COUNT, "){"); + inner.exit("}"); + } + var INSTANCES, EXT_INSTANCING; + if (extInstancing) { + INSTANCES = emitValue(S_INSTANCES); + EXT_INSTANCING = env.instancing; + } + var ELEMENT_TYPE = ELEMENTS + ".type"; + var elementsStatic = drawOptions.elements && isStatic(drawOptions.elements) && !drawOptions.vaoActive; + function emitInstancing() { + function drawElements() { + inner(EXT_INSTANCING, ".drawElementsInstancedANGLE(", [ + PRIMITIVE, + COUNT, + ELEMENT_TYPE, + OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)", + INSTANCES + ], ");"); + } + function drawArrays() { + inner( + EXT_INSTANCING, + ".drawArraysInstancedANGLE(", + [PRIMITIVE, OFFSET, COUNT, INSTANCES], + ");" + ); + } + if (ELEMENTS && ELEMENTS !== "null") { + if (!elementsStatic) { + inner("if(", ELEMENTS, "){"); + drawElements(); + inner("}else{"); + drawArrays(); + inner("}"); + } else { + drawElements(); + } + } else { + drawArrays(); + } + } + function emitRegular() { + function drawElements() { + inner(GL + ".drawElements(" + [ + PRIMITIVE, + COUNT, + ELEMENT_TYPE, + OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)" + ] + ");"); + } + function drawArrays() { + inner(GL + ".drawArrays(" + [PRIMITIVE, OFFSET, COUNT] + ");"); + } + if (ELEMENTS && ELEMENTS !== "null") { + if (!elementsStatic) { + inner("if(", ELEMENTS, "){"); + drawElements(); + inner("}else{"); + drawArrays(); + inner("}"); + } else { + drawElements(); + } + } else { + drawArrays(); + } + } + if (extInstancing && (typeof INSTANCES !== "number" || INSTANCES >= 0)) { + if (typeof INSTANCES === "string") { + inner("if(", INSTANCES, ">0){"); + emitInstancing(); + inner("}else if(", INSTANCES, "<0){"); + emitRegular(); + inner("}"); + } else { + emitInstancing(); + } + } else { + emitRegular(); + } + } + function createBody(emitBody, parentEnv, args, program, count2) { + var env = createREGLEnvironment(); + var scope = env.proc("body", count2); + if (extInstancing) { + env.instancing = scope.def( + env.shared.extensions, + ".angle_instanced_arrays" + ); + } + emitBody(env, scope, args, program); + return env.compile().body; + } + function emitDrawBody(env, draw8, args, program) { + injectExtensions(env, draw8); + if (args.useVAO) { + if (args.drawVAO) { + draw8(env.shared.vao, ".setVAO(", args.drawVAO.append(env, draw8), ");"); + } else { + draw8(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);"); + } + } else { + draw8(env.shared.vao, ".setVAO(null);"); + emitAttributes(env, draw8, args, program.attributes, function() { + return true; + }); + } + emitUniforms(env, draw8, args, program.uniforms, function() { + return true; + }, false); + emitDraw(env, draw8, draw8, args); + } + function emitDrawProc(env, args) { + var draw8 = env.proc("draw", 1); + injectExtensions(env, draw8); + emitContext(env, draw8, args.context); + emitPollFramebuffer(env, draw8, args.framebuffer); + emitPollState(env, draw8, args); + emitSetOptions(env, draw8, args.state); + emitProfile(env, draw8, args, false, true); + var program = args.shader.progVar.append(env, draw8); + draw8(env.shared.gl, ".useProgram(", program, ".program);"); + if (args.shader.program) { + emitDrawBody(env, draw8, args, args.shader.program); + } else { + draw8(env.shared.vao, ".setVAO(null);"); + var drawCache = env.global.def("{}"); + var PROG_ID = draw8.def(program, ".id"); + var CACHED_PROC = draw8.def(drawCache, "[", PROG_ID, "]"); + draw8( + env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0);").else( + CACHED_PROC, + "=", + drawCache, + "[", + PROG_ID, + "]=", + env.link(function(program2) { + return createBody(emitDrawBody, env, args, program2, 1); + }), + "(", + program, + ");", + CACHED_PROC, + ".call(this,a0);" + ) + ); + } + if (Object.keys(args.state).length > 0) { + draw8(env.shared.current, ".dirty=true;"); + } + if (env.shared.vao) { + draw8(env.shared.vao, ".setVAO(null);"); + } + } + function emitBatchDynamicShaderBody(env, scope, args, program) { + env.batchId = "a1"; + injectExtensions(env, scope); + function all() { + return true; + } + emitAttributes(env, scope, args, program.attributes, all); + emitUniforms(env, scope, args, program.uniforms, all, false); + emitDraw(env, scope, scope, args); + } + function emitBatchBody(env, scope, args, program) { + injectExtensions(env, scope); + var contextDynamic = args.contextDep; + var BATCH_ID = scope.def(); + var PROP_LIST = "a0"; + var NUM_PROPS = "a1"; + var PROPS = scope.def(); + env.shared.props = PROPS; + env.batchId = BATCH_ID; + var outer = env.scope(); + var inner = env.scope(); + scope( + outer.entry, + "for(", + BATCH_ID, + "=0;", + BATCH_ID, + "<", + NUM_PROPS, + ";++", + BATCH_ID, + "){", + PROPS, + "=", + PROP_LIST, + "[", + BATCH_ID, + "];", + inner, + "}", + outer.exit + ); + function isInnerDefn(defn) { + return defn.contextDep && contextDynamic || defn.propDep; + } + function isOuterDefn(defn) { + return !isInnerDefn(defn); + } + if (args.needsContext) { + emitContext(env, inner, args.context); + } + if (args.needsFramebuffer) { + emitPollFramebuffer(env, inner, args.framebuffer); + } + emitSetOptions(env, inner, args.state, isInnerDefn); + if (args.profile && isInnerDefn(args.profile)) { + emitProfile(env, inner, args, false, true); + } + if (!program) { + var progCache = env.global.def("{}"); + var PROGRAM = args.shader.progVar.append(env, inner); + var PROG_ID = inner.def(PROGRAM, ".id"); + var CACHED_PROC = inner.def(progCache, "[", PROG_ID, "]"); + inner( + env.shared.gl, + ".useProgram(", + PROGRAM, + ".program);", + "if(!", + CACHED_PROC, + "){", + CACHED_PROC, + "=", + progCache, + "[", + PROG_ID, + "]=", + env.link(function(program2) { + return createBody( + emitBatchDynamicShaderBody, + env, + args, + program2, + 2 + ); + }), + "(", + PROGRAM, + ");}", + CACHED_PROC, + ".call(this,a0[", + BATCH_ID, + "],", + BATCH_ID, + ");" + ); + } else { + if (args.useVAO) { + if (args.drawVAO) { + if (isInnerDefn(args.drawVAO)) { + inner(env.shared.vao, ".setVAO(", args.drawVAO.append(env, inner), ");"); + } else { + outer(env.shared.vao, ".setVAO(", args.drawVAO.append(env, outer), ");"); + } + } else { + outer(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);"); + } + } else { + outer(env.shared.vao, ".setVAO(null);"); + emitAttributes(env, outer, args, program.attributes, isOuterDefn); + emitAttributes(env, inner, args, program.attributes, isInnerDefn); + } + emitUniforms(env, outer, args, program.uniforms, isOuterDefn, false); + emitUniforms(env, inner, args, program.uniforms, isInnerDefn, true); + emitDraw(env, outer, inner, args); + } + } + function emitBatchProc(env, args) { + var batch = env.proc("batch", 2); + env.batchId = "0"; + injectExtensions(env, batch); + var contextDynamic = false; + var needsContext = true; + Object.keys(args.context).forEach(function(name2) { + contextDynamic = contextDynamic || args.context[name2].propDep; + }); + if (!contextDynamic) { + emitContext(env, batch, args.context); + needsContext = false; + } + var framebuffer = args.framebuffer; + var needsFramebuffer = false; + if (framebuffer) { + if (framebuffer.propDep) { + contextDynamic = needsFramebuffer = true; + } else if (framebuffer.contextDep && contextDynamic) { + needsFramebuffer = true; + } + if (!needsFramebuffer) { + emitPollFramebuffer(env, batch, framebuffer); + } + } else { + emitPollFramebuffer(env, batch, null); + } + if (args.state.viewport && args.state.viewport.propDep) { + contextDynamic = true; + } + function isInnerDefn(defn) { + return defn.contextDep && contextDynamic || defn.propDep; + } + emitPollState(env, batch, args); + emitSetOptions(env, batch, args.state, function(defn) { + return !isInnerDefn(defn); + }); + if (!args.profile || !isInnerDefn(args.profile)) { + emitProfile(env, batch, args, false, "a1"); + } + args.contextDep = contextDynamic; + args.needsContext = needsContext; + args.needsFramebuffer = needsFramebuffer; + var progDefn = args.shader.progVar; + if (progDefn.contextDep && contextDynamic || progDefn.propDep) { + emitBatchBody( + env, + batch, + args, + null + ); + } else { + var PROGRAM = progDefn.append(env, batch); + batch(env.shared.gl, ".useProgram(", PROGRAM, ".program);"); + if (args.shader.program) { + emitBatchBody( + env, + batch, + args, + args.shader.program + ); + } else { + batch(env.shared.vao, ".setVAO(null);"); + var batchCache = env.global.def("{}"); + var PROG_ID = batch.def(PROGRAM, ".id"); + var CACHED_PROC = batch.def(batchCache, "[", PROG_ID, "]"); + batch( + env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0,a1);").else( + CACHED_PROC, + "=", + batchCache, + "[", + PROG_ID, + "]=", + env.link(function(program) { + return createBody(emitBatchBody, env, args, program, 2); + }), + "(", + PROGRAM, + ");", + CACHED_PROC, + ".call(this,a0,a1);" + ) + ); + } + } + if (Object.keys(args.state).length > 0) { + batch(env.shared.current, ".dirty=true;"); + } + if (env.shared.vao) { + batch(env.shared.vao, ".setVAO(null);"); + } + } + function emitScopeProc(env, args) { + var scope = env.proc("scope", 3); + env.batchId = "a2"; + var shared = env.shared; + var CURRENT_STATE = shared.current; + emitContext(env, scope, args.context); + if (args.framebuffer) { + args.framebuffer.append(env, scope); + } + sortState(Object.keys(args.state)).forEach(function(name2) { + var defn = args.state[name2]; + var value2 = defn.append(env, scope); + if (isArrayLike(value2)) { + value2.forEach(function(v, i) { + if (hasVariableReference(v)) { + scope.set(env.next[name2], "[" + i + "]", v); + } else { + scope.set(env.next[name2], "[" + i + "]", env.link(v, { stable: true })); + } + }); + } else { + if (isStatic(defn)) { + scope.set(shared.next, "." + name2, env.link(value2, { stable: true })); + } else { + scope.set(shared.next, "." + name2, value2); + } + } + }); + emitProfile(env, scope, args, true, true); + [S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach( + function(opt) { + var variable = args.draw[opt]; + if (!variable) { + return; + } + var VARIABLE2 = variable.append(env, scope); + if (hasVariableReference(VARIABLE2)) { + scope.set(shared.draw, "." + opt, VARIABLE2); + } else { + scope.set(shared.draw, "." + opt, env.link(VARIABLE2), { stable: true }); + } + } + ); + Object.keys(args.uniforms).forEach(function(opt) { + var value2 = args.uniforms[opt].append(env, scope); + if (Array.isArray(value2)) { + value2 = "[" + value2.map(function(v) { + if (hasVariableReference(v)) { + return v; + } else { + return env.link(v, { stable: true }); + } + }) + "]"; + } + scope.set( + shared.uniforms, + "[" + env.link(stringStore.id(opt), { stable: true }) + "]", + value2 + ); + }); + Object.keys(args.attributes).forEach(function(name2) { + var record = args.attributes[name2].append(env, scope); + var scopeAttrib = env.scopeAttrib(name2); + Object.keys(new AttributeRecord2()).forEach(function(prop) { + scope.set(scopeAttrib, "." + prop, record[prop]); + }); + }); + if (args.scopeVAO) { + var VARIABLE = args.scopeVAO.append(env, scope); + if (hasVariableReference(VARIABLE)) { + scope.set(shared.vao, ".targetVAO", VARIABLE); + } else { + scope.set(shared.vao, ".targetVAO", env.link(VARIABLE, { stable: true })); + } + } + function saveShader(name2) { + var shader = args.shader[name2]; + if (shader) { + var VARIABLE2 = shader.append(env, scope); + if (hasVariableReference(VARIABLE2)) { + scope.set(shared.shader, "." + name2, VARIABLE2); + } else { + scope.set(shared.shader, "." + name2, env.link(VARIABLE2, { stable: true })); + } + } + } + saveShader(S_VERT); + saveShader(S_FRAG); + if (Object.keys(args.state).length > 0) { + scope(CURRENT_STATE, ".dirty=true;"); + scope.exit(CURRENT_STATE, ".dirty=true;"); + } + scope("a1(", env.shared.context, ",a0,", env.batchId, ");"); + } + function isDynamicObject(object2) { + if (typeof object2 !== "object" || isArrayLike(object2)) { + return; + } + var props = Object.keys(object2); + for (var i = 0; i < props.length; ++i) { + if (dynamic.isDynamic(object2[props[i]])) { + return true; + } + } + return false; + } + function splatObject(env, options, name2) { + var object2 = options.static[name2]; + if (!object2 || !isDynamicObject(object2)) { + return; + } + var globals2 = env.global; + var keys = Object.keys(object2); + var thisDep = false; + var contextDep = false; + var propDep = false; + var objectRef = env.global.def("{}"); + keys.forEach(function(key) { + var value2 = object2[key]; + if (dynamic.isDynamic(value2)) { + if (typeof value2 === "function") { + value2 = object2[key] = dynamic.unbox(value2); + } + var deps = createDynamicDecl(value2, null); + thisDep = thisDep || deps.thisDep; + propDep = propDep || deps.propDep; + contextDep = contextDep || deps.contextDep; + } else { + globals2(objectRef, ".", key, "="); + switch (typeof value2) { + case "number": + globals2(value2); + break; + case "string": + globals2('"', value2, '"'); + break; + case "object": + if (Array.isArray(value2)) { + globals2("[", value2.join(), "]"); + } + break; + default: + globals2(env.link(value2)); + break; + } + globals2(";"); + } + }); + function appendBlock(env2, block) { + keys.forEach(function(key) { + var value2 = object2[key]; + if (!dynamic.isDynamic(value2)) { + return; + } + var ref2 = env2.invoke(block, value2); + block(objectRef, ".", key, "=", ref2, ";"); + }); + } + options.dynamic[name2] = new dynamic.DynamicVariable(DYN_THUNK, { + thisDep, + contextDep, + propDep, + ref: objectRef, + append: appendBlock + }); + delete options.static[name2]; + } + function compileCommand(options, attributes2, uniforms, context2, stats3) { + var env = createREGLEnvironment(); + env.stats = env.link(stats3); + Object.keys(attributes2.static).forEach(function(key) { + splatObject(env, attributes2, key); + }); + NESTED_OPTIONS.forEach(function(name2) { + splatObject(env, options, name2); + }); + var args = parseArguments(options, attributes2, uniforms, context2, env); + if (args.shader.program) { + args.shader.program.attributes.sort(function(a, b) { + return a.name < b.name ? -1 : 1; + }); + args.shader.program.uniforms.sort(function(a, b) { + return a.name < b.name ? -1 : 1; + }); + } + emitDrawProc(env, args); + emitScopeProc(env, args); + emitBatchProc(env, args); + return extend2(env.compile(), { + destroy: function() { + args.shader.program.destroy(); + } + }); + } + return { + next: nextState, + current: currentState, + procs: function() { + var env = createREGLEnvironment(); + var poll = env.proc("poll"); + var refresh = env.proc("refresh"); + var common = env.block(); + poll(common); + refresh(common); + var shared = env.shared; + var GL = shared.gl; + var NEXT_STATE = shared.next; + var CURRENT_STATE = shared.current; + common(CURRENT_STATE, ".dirty=false;"); + emitPollFramebuffer(env, poll); + emitPollFramebuffer(env, refresh, null, true); + var INSTANCING; + if (extInstancing) { + INSTANCING = env.link(extInstancing); + } + if (extensions.oes_vertex_array_object) { + refresh(env.link(extensions.oes_vertex_array_object), ".bindVertexArrayOES(null);"); + } + var BINDING = refresh.def(shared.attributes); + var TEMP_BINDING = refresh.def(0); + var ifte = env.cond(TEMP_BINDING, ".buffer"); + ifte.then( + GL, + ".enableVertexAttribArray(i);", + GL, + ".bindBuffer(", + GL_ARRAY_BUFFER$2, + ",", + TEMP_BINDING, + ".buffer.buffer);", + GL, + ".vertexAttribPointer(i,", + TEMP_BINDING, + ".size,", + TEMP_BINDING, + ".type,", + TEMP_BINDING, + ".normalized,", + TEMP_BINDING, + ".stride,", + TEMP_BINDING, + ".offset);" + ).else( + GL, + ".disableVertexAttribArray(i);", + GL, + ".vertexAttrib4f(i,", + TEMP_BINDING, + ".x,", + TEMP_BINDING, + ".y,", + TEMP_BINDING, + ".z,", + TEMP_BINDING, + ".w);", + TEMP_BINDING, + ".buffer=null;" + ); + var MAX_ATTRIBUTES = env.link(limits.maxAttributes, { stable: true }); + refresh( + "for(var i=0;i<", + MAX_ATTRIBUTES, + ";++i){", + TEMP_BINDING, + "=", + BINDING, + "[i];", + ifte, + "}" + ); + if (extInstancing) { + refresh( + "for(var i=0;i<", + MAX_ATTRIBUTES, + ";++i){", + INSTANCING, + ".vertexAttribDivisorANGLE(i,", + BINDING, + "[i].divisor);", + "}" + ); + } + refresh( + env.shared.vao, + ".currentVAO=null;", + env.shared.vao, + ".setVAO(", + env.shared.vao, + ".targetVAO);" + ); + Object.keys(GL_FLAGS).forEach(function(flag) { + var cap = GL_FLAGS[flag]; + var NEXT = common.def(NEXT_STATE, ".", flag); + var block = env.block(); + block( + "if(", + NEXT, + "){", + GL, + ".enable(", + cap, + ")}else{", + GL, + ".disable(", + cap, + ")}", + CURRENT_STATE, + ".", + flag, + "=", + NEXT, + ";" + ); + refresh(block); + poll( + "if(", + NEXT, + "!==", + CURRENT_STATE, + ".", + flag, + "){", + block, + "}" + ); + }); + Object.keys(GL_VARIABLES).forEach(function(name2) { + var func = GL_VARIABLES[name2]; + var init2 = currentState[name2]; + var NEXT, CURRENT; + var block = env.block(); + block(GL, ".", func, "("); + if (isArrayLike(init2)) { + var n = init2.length; + NEXT = env.global.def(NEXT_STATE, ".", name2); + CURRENT = env.global.def(CURRENT_STATE, ".", name2); + block( + loop(n, function(i) { + return NEXT + "[" + i + "]"; + }), + ");", + loop(n, function(i) { + return CURRENT + "[" + i + "]=" + NEXT + "[" + i + "];"; + }).join("") + ); + poll( + "if(", + loop(n, function(i) { + return NEXT + "[" + i + "]!==" + CURRENT + "[" + i + "]"; + }).join("||"), + "){", + block, + "}" + ); + } else { + NEXT = common.def(NEXT_STATE, ".", name2); + CURRENT = common.def(CURRENT_STATE, ".", name2); + block( + NEXT, + ");", + CURRENT_STATE, + ".", + name2, + "=", + NEXT, + ";" + ); + poll( + "if(", + NEXT, + "!==", + CURRENT, + "){", + block, + "}" + ); + } + refresh(block); + }); + return env.compile(); + }(), + compile: compileCommand + }; + } + function stats2() { + return { + vaoCount: 0, + bufferCount: 0, + elementsCount: 0, + framebufferCount: 0, + shaderCount: 0, + textureCount: 0, + cubeCount: 0, + renderbufferCount: 0, + maxTextureUnits: 0 + }; + } + var GL_QUERY_RESULT_EXT = 34918; + var GL_QUERY_RESULT_AVAILABLE_EXT = 34919; + var GL_TIME_ELAPSED_EXT = 35007; + var createTimer = function(gl, extensions) { + if (!extensions.ext_disjoint_timer_query) { + return null; + } + var queryPool = []; + function allocQuery() { + return queryPool.pop() || extensions.ext_disjoint_timer_query.createQueryEXT(); + } + function freeQuery(query) { + queryPool.push(query); + } + var pendingQueries = []; + function beginQuery(stats3) { + var query = allocQuery(); + extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT, query); + pendingQueries.push(query); + pushScopeStats(pendingQueries.length - 1, pendingQueries.length, stats3); + } + function endQuery() { + extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT); + } + function PendingStats() { + this.startQueryIndex = -1; + this.endQueryIndex = -1; + this.sum = 0; + this.stats = null; + } + var pendingStatsPool = []; + function allocPendingStats() { + return pendingStatsPool.pop() || new PendingStats(); + } + function freePendingStats(pendingStats2) { + pendingStatsPool.push(pendingStats2); + } + var pendingStats = []; + function pushScopeStats(start, end, stats3) { + var ps = allocPendingStats(); + ps.startQueryIndex = start; + ps.endQueryIndex = end; + ps.sum = 0; + ps.stats = stats3; + pendingStats.push(ps); + } + var timeSum = []; + var queryPtr = []; + function update2() { + var ptr, i; + var n = pendingQueries.length; + if (n === 0) { + return; + } + queryPtr.length = Math.max(queryPtr.length, n + 1); + timeSum.length = Math.max(timeSum.length, n + 1); + timeSum[0] = 0; + queryPtr[0] = 0; + var queryTime = 0; + ptr = 0; + for (i = 0; i < pendingQueries.length; ++i) { + var query = pendingQueries[i]; + if (extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT)) { + queryTime += extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_EXT); + freeQuery(query); + } else { + pendingQueries[ptr++] = query; + } + timeSum[i + 1] = queryTime; + queryPtr[i + 1] = ptr; + } + pendingQueries.length = ptr; + ptr = 0; + for (i = 0; i < pendingStats.length; ++i) { + var stats3 = pendingStats[i]; + var start = stats3.startQueryIndex; + var end = stats3.endQueryIndex; + stats3.sum += timeSum[end] - timeSum[start]; + var startPtr = queryPtr[start]; + var endPtr = queryPtr[end]; + if (endPtr === startPtr) { + stats3.stats.gpuTime += stats3.sum / 1e6; + freePendingStats(stats3); + } else { + stats3.startQueryIndex = startPtr; + stats3.endQueryIndex = endPtr; + pendingStats[ptr++] = stats3; + } + } + pendingStats.length = ptr; + } + return { + beginQuery, + endQuery, + pushScopeStats, + update: update2, + getNumPendingQueries: function() { + return pendingQueries.length; + }, + clear: function() { + queryPool.push.apply(queryPool, pendingQueries); + for (var i = 0; i < queryPool.length; i++) { + extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i]); + } + pendingQueries.length = 0; + queryPool.length = 0; + }, + restore: function() { + pendingQueries.length = 0; + queryPool.length = 0; + } + }; + }; + var GL_COLOR_BUFFER_BIT = 16384; + var GL_DEPTH_BUFFER_BIT = 256; + var GL_STENCIL_BUFFER_BIT = 1024; + var GL_ARRAY_BUFFER = 34962; + var CONTEXT_LOST_EVENT = "webglcontextlost"; + var CONTEXT_RESTORED_EVENT = "webglcontextrestored"; + var DYN_PROP = 1; + var DYN_CONTEXT = 2; + var DYN_STATE = 3; + function find(haystack, needle) { + for (var i = 0; i < haystack.length; ++i) { + if (haystack[i] === needle) { + return i; + } + } + return -1; + } + function wrapREGL(args) { + var config = parseArgs(args); + if (!config) { + return null; + } + var gl = config.gl; + var glAttributes = gl.getContextAttributes(); + gl.isContextLost(); + var extensionState = createExtensionCache(gl, config); + if (!extensionState) { + return null; + } + var stringStore = createStringStore(); + var stats$$1 = stats2(); + var cachedCode = config.cachedCode || {}; + var extensions = extensionState.extensions; + var timer = createTimer(gl, extensions); + var START_TIME = clock(); + var WIDTH = gl.drawingBufferWidth; + var HEIGHT = gl.drawingBufferHeight; + var contextState = { + tick: 0, + time: 0, + viewportWidth: WIDTH, + viewportHeight: HEIGHT, + framebufferWidth: WIDTH, + framebufferHeight: HEIGHT, + drawingBufferWidth: WIDTH, + drawingBufferHeight: HEIGHT, + pixelRatio: config.pixelRatio + }; + var uniformState = {}; + var drawState = { + elements: null, + primitive: 4, + // GL_TRIANGLES + count: -1, + offset: 0, + instances: -1 + }; + var limits = wrapLimits(gl, extensions); + var bufferState = wrapBufferState( + gl, + stats$$1, + config, + destroyBuffer + ); + var elementState = wrapElementsState(gl, extensions, bufferState, stats$$1); + var attributeState = wrapAttributeState( + gl, + extensions, + limits, + stats$$1, + bufferState, + elementState, + drawState + ); + function destroyBuffer(buffer2) { + return attributeState.destroyBuffer(buffer2); + } + var shaderState = wrapShaderState(gl, stringStore, stats$$1, config); + var textureState = createTextureSet( + gl, + extensions, + limits, + function() { + core2.procs.poll(); + }, + contextState, + stats$$1, + config + ); + var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats$$1, config); + var framebufferState = wrapFBOState( + gl, + extensions, + limits, + textureState, + renderbufferState, + stats$$1 + ); + var core2 = reglCore( + gl, + stringStore, + extensions, + limits, + bufferState, + elementState, + textureState, + framebufferState, + uniformState, + attributeState, + shaderState, + drawState, + contextState, + timer, + cachedCode, + config + ); + var readPixels = wrapReadPixels( + gl, + framebufferState, + core2.procs.poll, + contextState + ); + var nextState = core2.next; + var canvas2 = gl.canvas; + var rafCallbacks = []; + var lossCallbacks = []; + var restoreCallbacks = []; + var destroyCallbacks = [config.onDestroy]; + var activeRAF = null; + function handleRAF() { + if (rafCallbacks.length === 0) { + if (timer) { + timer.update(); + } + activeRAF = null; + return; + } + activeRAF = raf.next(handleRAF); + poll(); + for (var i = rafCallbacks.length - 1; i >= 0; --i) { + var cb = rafCallbacks[i]; + if (cb) { + cb(contextState, null, 0); + } + } + gl.flush(); + if (timer) { + timer.update(); + } + } + function startRAF() { + if (!activeRAF && rafCallbacks.length > 0) { + activeRAF = raf.next(handleRAF); + } + } + function stopRAF() { + if (activeRAF) { + raf.cancel(handleRAF); + activeRAF = null; + } + } + function handleContextLoss(event) { + event.preventDefault(); + stopRAF(); + lossCallbacks.forEach(function(cb) { + cb(); + }); + } + function handleContextRestored(event) { + gl.getError(); + extensionState.restore(); + shaderState.restore(); + bufferState.restore(); + textureState.restore(); + renderbufferState.restore(); + framebufferState.restore(); + attributeState.restore(); + if (timer) { + timer.restore(); + } + core2.procs.refresh(); + startRAF(); + restoreCallbacks.forEach(function(cb) { + cb(); + }); + } + if (canvas2) { + canvas2.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false); + canvas2.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false); + } + function destroy2() { + rafCallbacks.length = 0; + stopRAF(); + if (canvas2) { + canvas2.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss); + canvas2.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored); + } + shaderState.clear(); + framebufferState.clear(); + renderbufferState.clear(); + attributeState.clear(); + textureState.clear(); + elementState.clear(); + bufferState.clear(); + if (timer) { + timer.clear(); + } + destroyCallbacks.forEach(function(cb) { + cb(); + }); + } + function compileProcedure(options) { + function flattenNestedOptions(options2) { + var result = extend2({}, options2); + delete result.uniforms; + delete result.attributes; + delete result.context; + delete result.vao; + if ("stencil" in result && result.stencil.op) { + result.stencil.opBack = result.stencil.opFront = result.stencil.op; + delete result.stencil.op; + } + function merge(name2) { + if (name2 in result) { + var child = result[name2]; + delete result[name2]; + Object.keys(child).forEach(function(prop) { + result[name2 + "." + prop] = child[prop]; + }); + } + } + merge("blend"); + merge("depth"); + merge("cull"); + merge("stencil"); + merge("polygonOffset"); + merge("scissor"); + merge("sample"); + if ("vao" in options2) { + result.vao = options2.vao; + } + return result; + } + function separateDynamic(object2, useArrays) { + var staticItems = {}; + var dynamicItems = {}; + Object.keys(object2).forEach(function(option) { + var value2 = object2[option]; + if (dynamic.isDynamic(value2)) { + dynamicItems[option] = dynamic.unbox(value2, option); + return; + } else if (useArrays && Array.isArray(value2)) { + for (var i = 0; i < value2.length; ++i) { + if (dynamic.isDynamic(value2[i])) { + dynamicItems[option] = dynamic.unbox(value2, option); + return; + } + } + } + staticItems[option] = value2; + }); + return { + dynamic: dynamicItems, + static: staticItems + }; + } + var context2 = separateDynamic(options.context || {}, true); + var uniforms = separateDynamic(options.uniforms || {}, true); + var attributes2 = separateDynamic(options.attributes || {}, false); + var opts = separateDynamic(flattenNestedOptions(options), false); + var stats$$12 = { + gpuTime: 0, + cpuTime: 0, + count: 0 + }; + var compiled = core2.compile(opts, attributes2, uniforms, context2, stats$$12); + var draw8 = compiled.draw; + var batch = compiled.batch; + var scope = compiled.scope; + var EMPTY_ARRAY = []; + function reserve(count2) { + while (EMPTY_ARRAY.length < count2) { + EMPTY_ARRAY.push(null); + } + return EMPTY_ARRAY; + } + function REGLCommand(args2, body) { + var i; + if (typeof args2 === "function") { + return scope.call(this, null, args2, 0); + } else if (typeof body === "function") { + if (typeof args2 === "number") { + for (i = 0; i < args2; ++i) { + scope.call(this, null, body, i); + } + } else if (Array.isArray(args2)) { + for (i = 0; i < args2.length; ++i) { + scope.call(this, args2[i], body, i); + } + } else { + return scope.call(this, args2, body, 0); + } + } else if (typeof args2 === "number") { + if (args2 > 0) { + return batch.call(this, reserve(args2 | 0), args2 | 0); + } + } else if (Array.isArray(args2)) { + if (args2.length) { + return batch.call(this, args2, args2.length); + } + } else { + return draw8.call(this, args2); + } + } + return extend2(REGLCommand, { + stats: stats$$12, + destroy: function() { + compiled.destroy(); + } + }); + } + var setFBO = framebufferState.setFBO = compileProcedure({ + framebuffer: dynamic.define.call(null, DYN_PROP, "framebuffer") + }); + function clearImpl(_2, options) { + var clearFlags = 0; + core2.procs.poll(); + var c = options.color; + if (c) { + gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0); + clearFlags |= GL_COLOR_BUFFER_BIT; + } + if ("depth" in options) { + gl.clearDepth(+options.depth); + clearFlags |= GL_DEPTH_BUFFER_BIT; + } + if ("stencil" in options) { + gl.clearStencil(options.stencil | 0); + clearFlags |= GL_STENCIL_BUFFER_BIT; + } + gl.clear(clearFlags); + } + function clear2(options) { + if ("framebuffer" in options) { + if (options.framebuffer && options.framebuffer_reglType === "framebufferCube") { + for (var i = 0; i < 6; ++i) { + setFBO(extend2({ + framebuffer: options.framebuffer.faces[i] + }, options), clearImpl); + } + } else { + setFBO(options, clearImpl); + } + } else { + clearImpl(null, options); + } + } + function frame(cb) { + rafCallbacks.push(cb); + function cancel() { + var i = find(rafCallbacks, cb); + function pendingCancel() { + var index2 = find(rafCallbacks, pendingCancel); + rafCallbacks[index2] = rafCallbacks[rafCallbacks.length - 1]; + rafCallbacks.length -= 1; + if (rafCallbacks.length <= 0) { + stopRAF(); + } + } + rafCallbacks[i] = pendingCancel; + } + startRAF(); + return { + cancel + }; + } + function pollViewport() { + var viewport = nextState.viewport; + var scissorBox = nextState.scissor_box; + viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0; + contextState.viewportWidth = contextState.framebufferWidth = contextState.drawingBufferWidth = viewport[2] = scissorBox[2] = gl.drawingBufferWidth; + contextState.viewportHeight = contextState.framebufferHeight = contextState.drawingBufferHeight = viewport[3] = scissorBox[3] = gl.drawingBufferHeight; + } + function poll() { + contextState.tick += 1; + contextState.time = now(); + pollViewport(); + core2.procs.poll(); + } + function refresh() { + textureState.refresh(); + pollViewport(); + core2.procs.refresh(); + if (timer) { + timer.update(); + } + } + function now() { + return (clock() - START_TIME) / 1e3; + } + refresh(); + function addListener2(event, callback) { + var callbacks; + switch (event) { + case "frame": + return frame(callback); + case "lost": + callbacks = lossCallbacks; + break; + case "restore": + callbacks = restoreCallbacks; + break; + case "destroy": + callbacks = destroyCallbacks; + break; + } + callbacks.push(callback); + return { + cancel: function() { + for (var i = 0; i < callbacks.length; ++i) { + if (callbacks[i] === callback) { + callbacks[i] = callbacks[callbacks.length - 1]; + callbacks.pop(); + return; + } + } + } + }; + } + function getCachedCode() { + return cachedCode; + } + function preloadCachedCode(moreCache) { + Object.entries(moreCache).forEach(function(kv) { + cachedCode[kv[0]] = kv[1]; + }); + } + var regl = extend2(compileProcedure, { + // Clear current FBO + clear: clear2, + // Short cuts for dynamic variables + prop: dynamic.define.bind(null, DYN_PROP), + context: dynamic.define.bind(null, DYN_CONTEXT), + this: dynamic.define.bind(null, DYN_STATE), + // executes an empty draw command + draw: compileProcedure({}), + // Resources + buffer: function(options) { + return bufferState.create(options, GL_ARRAY_BUFFER, false, false); + }, + elements: function(options) { + return elementState.create(options, false); + }, + texture: textureState.create2D, + cube: textureState.createCube, + renderbuffer: renderbufferState.create, + framebuffer: framebufferState.create, + framebufferCube: framebufferState.createCube, + vao: attributeState.createVAO, + // Expose context attributes + attributes: glAttributes, + // Frame rendering + frame, + on: addListener2, + // System limits + limits, + hasExtension: function(name2) { + return limits.extensions.indexOf(name2.toLowerCase()) >= 0; + }, + // Read pixels + read: readPixels, + // Destroy regl and all associated resources + destroy: destroy2, + // Direct GL state manipulation + _gl: gl, + _refresh: refresh, + poll: function() { + poll(); + if (timer) { + timer.update(); + } + }, + // Current time + now, + // regl Statistics Information + stats: stats$$1, + // cache generated code + getCachedCode, + preloadCachedCode + }); + config.onDone(null, regl); + return regl; + } + return wrapREGL; + }); +})(regl_unchecked); +var regl_uncheckedExports = regl_unchecked.exports; +var pick$1 = pickByAlias; +var context = function setContext(o) { + if (!o) o = {}; + else if (typeof o === "string") o = { container: o }; + if (isCanvas(o)) { + o = { container: o }; + } else if (isElement(o)) { + o = { container: o }; + } else if (isContext(o)) { + o = { gl: o }; + } else { + o = pick$1(o, { + container: "container target element el canvas holder parent parentNode wrapper use ref root node", + gl: "gl context webgl glContext", + attrs: "attributes attrs contextAttributes", + pixelRatio: "pixelRatio pxRatio px ratio pxratio pixelratio", + width: "w width", + height: "h height" + }, true); + } + if (!o.pixelRatio) o.pixelRatio = index$3.commonjsGlobal.pixelRatio || 1; + if (o.gl) { + return o.gl; + } + if (o.canvas) { + o.container = o.canvas.parentNode; + } + if (o.container) { + if (typeof o.container === "string") { + var c = document.querySelector(o.container); + if (!c) throw Error("Element " + o.container + " is not found"); + o.container = c; + } + if (isCanvas(o.container)) { + o.canvas = o.container; + o.container = o.canvas.parentNode; + } else if (!o.canvas) { + o.canvas = createCanvas(); + o.container.appendChild(o.canvas); + resize(o); + } + } else if (!o.canvas) { + if (typeof document !== "undefined") { + o.container = document.body || document.documentElement; + o.canvas = createCanvas(); + o.container.appendChild(o.canvas); + resize(o); + } else { + throw Error("Not DOM environment. Use headless-gl."); + } + } + if (!o.gl) { + ["webgl", "experimental-webgl", "webgl-experimental"].some(function(c2) { + try { + o.gl = o.canvas.getContext(c2, o.attrs); + } catch (e) { + } + return o.gl; + }); + } + return o.gl; +}; +function resize(o) { + if (o.container) { + if (o.container == document.body) { + if (!document.body.style.width) o.canvas.width = o.width || o.pixelRatio * index$3.commonjsGlobal.innerWidth; + if (!document.body.style.height) o.canvas.height = o.height || o.pixelRatio * index$3.commonjsGlobal.innerHeight; + } else { + var bounds = o.container.getBoundingClientRect(); + o.canvas.width = o.width || bounds.right - bounds.left; + o.canvas.height = o.height || bounds.bottom - bounds.top; + } + } +} +function isCanvas(e) { + return typeof e.getContext === "function" && "width" in e && "height" in e; +} +function isElement(e) { + return typeof e.nodeName === "string" && typeof e.appendChild === "function" && typeof e.getBoundingClientRect === "function"; +} +function isContext(e) { + return typeof e.drawArrays === "function" || typeof e.drawElements === "function"; +} +function createCanvas() { + var canvas2 = document.createElement("canvas"); + canvas2.style.position = "absolute"; + canvas2.style.top = 0; + canvas2.style.left = 0; + return canvas2; +} +var stringifyFont2 = stringify; +var defaultChars = [32, 126]; +var fontAtlas$1 = atlas; +function atlas(options) { + options = options || {}; + var shape = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512]; + var canvas2 = options.canvas || document.createElement("canvas"); + var font2 = options.font; + var step = typeof options.step === "number" ? [options.step, options.step] : options.step || [32, 32]; + var chars2 = options.chars || defaultChars; + if (font2 && typeof font2 !== "string") font2 = stringifyFont2(font2); + if (!Array.isArray(chars2)) { + chars2 = String(chars2).split(""); + } else if (chars2.length === 2 && typeof chars2[0] === "number" && typeof chars2[1] === "number") { + var newchars = []; + for (var i = chars2[0], j = 0; i <= chars2[1]; i++) { + newchars[j++] = String.fromCharCode(i); + } + chars2 = newchars; + } + shape = shape.slice(); + canvas2.width = shape[0]; + canvas2.height = shape[1]; + var ctx2 = canvas2.getContext("2d"); + ctx2.fillStyle = "#000"; + ctx2.fillRect(0, 0, canvas2.width, canvas2.height); + ctx2.font = font2; + ctx2.textAlign = "center"; + ctx2.textBaseline = "middle"; + ctx2.fillStyle = "#fff"; + var x = step[0] / 2; + var y = step[1] / 2; + for (var i = 0; i < chars2.length; i++) { + ctx2.fillText(chars2[i], x, y); + if ((x += step[0]) > shape[0] - step[0] / 2) x = step[0] / 2, y += step[1]; + } + return canvas2; +} +var pool$1 = {}; +var twiddle = {}; +var INT_BITS = 32; +twiddle.INT_BITS = INT_BITS; +twiddle.INT_MAX = 2147483647; +twiddle.INT_MIN = -1 << INT_BITS - 1; +twiddle.sign = function(v) { + return (v > 0) - (v < 0); +}; +twiddle.abs = function(v) { + var mask = v >> INT_BITS - 1; + return (v ^ mask) - mask; +}; +twiddle.min = function(x, y) { + return y ^ (x ^ y) & -(x < y); +}; +twiddle.max = function(x, y) { + return x ^ (x ^ y) & -(x < y); +}; +twiddle.isPow2 = function(v) { + return !(v & v - 1) && !!v; +}; +twiddle.log2 = function(v) { + var r, shift; + r = (v > 65535) << 4; + v >>>= r; + shift = (v > 255) << 3; + v >>>= shift; + r |= shift; + shift = (v > 15) << 2; + v >>>= shift; + r |= shift; + shift = (v > 3) << 1; + v >>>= shift; + r |= shift; + return r | v >> 1; +}; +twiddle.log10 = function(v) { + return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0; +}; +twiddle.popCount = function(v) { + v = v - (v >>> 1 & 1431655765); + v = (v & 858993459) + (v >>> 2 & 858993459); + return (v + (v >>> 4) & 252645135) * 16843009 >>> 24; +}; +function countTrailingZeros(v) { + var c = 32; + v &= -v; + if (v) c--; + if (v & 65535) c -= 16; + if (v & 16711935) c -= 8; + if (v & 252645135) c -= 4; + if (v & 858993459) c -= 2; + if (v & 1431655765) c -= 1; + return c; +} +twiddle.countTrailingZeros = countTrailingZeros; +twiddle.nextPow2 = function(v) { + v += v === 0; + --v; + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v + 1; +}; +twiddle.prevPow2 = function(v) { + v |= v >>> 1; + v |= v >>> 2; + v |= v >>> 4; + v |= v >>> 8; + v |= v >>> 16; + return v - (v >>> 1); +}; +twiddle.parity = function(v) { + v ^= v >>> 16; + v ^= v >>> 8; + v ^= v >>> 4; + v &= 15; + return 27030 >>> v & 1; +}; +var REVERSE_TABLE = new Array(256); +(function(tab) { + for (var i = 0; i < 256; ++i) { + var v = i, r = i, s = 7; + for (v >>>= 1; v; v >>>= 1) { + r <<= 1; + r |= v & 1; + --s; + } + tab[i] = r << s & 255; + } +})(REVERSE_TABLE); +twiddle.reverse = function(v) { + return REVERSE_TABLE[v & 255] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255]; +}; +twiddle.interleave2 = function(x, y) { + x &= 65535; + x = (x | x << 8) & 16711935; + x = (x | x << 4) & 252645135; + x = (x | x << 2) & 858993459; + x = (x | x << 1) & 1431655765; + y &= 65535; + y = (y | y << 8) & 16711935; + y = (y | y << 4) & 252645135; + y = (y | y << 2) & 858993459; + y = (y | y << 1) & 1431655765; + return x | y << 1; +}; +twiddle.deinterleave2 = function(v, n) { + v = v >>> n & 1431655765; + v = (v | v >>> 1) & 858993459; + v = (v | v >>> 2) & 252645135; + v = (v | v >>> 4) & 16711935; + v = (v | v >>> 16) & 65535; + return v << 16 >> 16; +}; +twiddle.interleave3 = function(x, y, z) { + x &= 1023; + x = (x | x << 16) & 4278190335; + x = (x | x << 8) & 251719695; + x = (x | x << 4) & 3272356035; + x = (x | x << 2) & 1227133513; + y &= 1023; + y = (y | y << 16) & 4278190335; + y = (y | y << 8) & 251719695; + y = (y | y << 4) & 3272356035; + y = (y | y << 2) & 1227133513; + x |= y << 1; + z &= 1023; + z = (z | z << 16) & 4278190335; + z = (z | z << 8) & 251719695; + z = (z | z << 4) & 3272356035; + z = (z | z << 2) & 1227133513; + return x | z << 2; +}; +twiddle.deinterleave3 = function(v, n) { + v = v >>> n & 1227133513; + v = (v | v >>> 2) & 3272356035; + v = (v | v >>> 4) & 251719695; + v = (v | v >>> 8) & 4278190335; + v = (v | v >>> 16) & 1023; + return v << 22 >> 22; +}; +twiddle.nextCombination = function(v) { + var t = v | v - 1; + return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1; +}; +function dupe_array(count2, value2, i) { + var c = count2[i] | 0; + if (c <= 0) { + return []; + } + var result = new Array(c), j; + if (i === count2.length - 1) { + for (j = 0; j < c; ++j) { + result[j] = value2; + } + } else { + for (j = 0; j < c; ++j) { + result[j] = dupe_array(count2, value2, i + 1); + } + } + return result; +} +function dupe_number(count2, value2) { + var result, i; + result = new Array(count2); + for (i = 0; i < count2; ++i) { + result[i] = value2; + } + return result; +} +function dupe(count2, value2) { + if (typeof value2 === "undefined") { + value2 = 0; + } + switch (typeof count2) { + case "number": + if (count2 > 0) { + return dupe_number(count2 | 0, value2); + } + break; + case "object": + if (typeof count2.length === "number") { + return dupe_array(count2, value2, 0); + } + break; + } + return []; +} +var dup$1 = dupe; +var buffer = {}; +var base64Js = {}; +base64Js.byteLength = byteLength; +base64Js.toByteArray = toByteArray; +base64Js.fromByteArray = fromByteArray; +var lookup = []; +var revLookup = []; +var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; +var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; +} +revLookup["-".charCodeAt(0)] = 62; +revLookup["_".charCodeAt(0)] = 63; +function getLens(b64) { + var len = b64.length; + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + var validLen = b64.indexOf("="); + if (validLen === -1) validLen = len; + var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; + return [validLen, placeHoldersLen]; +} +function byteLength(b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +function _byteLength(b64, validLen, placeHoldersLen) { + return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; +} +function toByteArray(b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + var curByte = 0; + var len = placeHoldersLen > 0 ? validLen - 4 : validLen; + var i; + for (i = 0; i < len; i += 4) { + tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = tmp >> 16 & 255; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 2) { + tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; + arr[curByte++] = tmp & 255; + } + if (placeHoldersLen === 1) { + tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; + arr[curByte++] = tmp >> 8 & 255; + arr[curByte++] = tmp & 255; + } + return arr; +} +function tripletToBase64(num) { + return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; +} +function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); + output.push(tripletToBase64(tmp)); + } + return output.join(""); +} +function fromByteArray(uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; + var parts = []; + var maxChunkLength = 16383; + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push( + lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" + ); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push( + lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" + ); + } + return parts.join(""); +} +var ieee754 = {}; +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ +ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer2[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) { + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); +}; +ieee754.write = function(buffer2, value2, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value2 < 0 || value2 === 0 && 1 / value2 < 0 ? 1 : 0; + value2 = Math.abs(value2); + if (isNaN(value2) || value2 === Infinity) { + m = isNaN(value2) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value2) / Math.LN2); + if (value2 * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value2 += rt / c; + } else { + value2 += rt * Math.pow(2, 1 - eBias); + } + if (value2 * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value2 * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value2 * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer2[offset + i - d] |= s * 128; +}; +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +(function(exports2) { + const base64 = base64Js; + const ieee754$1 = ieee754; + const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; + exports2.Buffer = Buffer2; + exports2.SlowBuffer = SlowBuffer; + exports2.INSPECT_MAX_BYTES = 50; + const K_MAX_LENGTH = 2147483647; + exports2.kMaxLength = K_MAX_LENGTH; + Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); + if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { + console.error( + "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." + ); + } + function typedArraySupport() { + try { + const arr = new Uint8Array(1); + const proto2 = { foo: function() { + return 42; + } }; + Object.setPrototypeOf(proto2, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto2); + return arr.foo() === 42; + } catch (e) { + return false; + } + } + Object.defineProperty(Buffer2.prototype, "parent", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) return void 0; + return this.buffer; + } + }); + Object.defineProperty(Buffer2.prototype, "offset", { + enumerable: true, + get: function() { + if (!Buffer2.isBuffer(this)) return void 0; + return this.byteOffset; + } + }); + function createBuffer(length2) { + if (length2 > K_MAX_LENGTH) { + throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); + } + const buf = new Uint8Array(length2); + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function Buffer2(arg, encodingOrOffset, length2) { + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ); + } + return allocUnsafe(arg); + } + return from(arg, encodingOrOffset, length2); + } + Buffer2.poolSize = 8192; + function from(value2, encodingOrOffset, length2) { + if (typeof value2 === "string") { + return fromString(value2, encodingOrOffset); + } + if (ArrayBuffer.isView(value2)) { + return fromArrayView(value2); + } + if (value2 == null) { + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2 + ); + } + if (isInstance(value2, ArrayBuffer) || value2 && isInstance(value2.buffer, ArrayBuffer)) { + return fromArrayBuffer(value2, encodingOrOffset, length2); + } + if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value2, SharedArrayBuffer) || value2 && isInstance(value2.buffer, SharedArrayBuffer))) { + return fromArrayBuffer(value2, encodingOrOffset, length2); + } + if (typeof value2 === "number") { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ); + } + const valueOf = value2.valueOf && value2.valueOf(); + if (valueOf != null && valueOf !== value2) { + return Buffer2.from(valueOf, encodingOrOffset, length2); + } + const b = fromObject(value2); + if (b) return b; + if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value2[Symbol.toPrimitive] === "function") { + return Buffer2.from(value2[Symbol.toPrimitive]("string"), encodingOrOffset, length2); + } + throw new TypeError( + "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2 + ); + } + Buffer2.from = function(value2, encodingOrOffset, length2) { + return from(value2, encodingOrOffset, length2); + }; + Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); + Object.setPrototypeOf(Buffer2, Uint8Array); + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be of type number'); + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"'); + } + } + function alloc(size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size); + } + if (fill !== void 0) { + return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); + } + return createBuffer(size); + } + Buffer2.alloc = function(size, fill, encoding) { + return alloc(size, fill, encoding); + }; + function allocUnsafe(size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0); + } + Buffer2.allocUnsafe = function(size) { + return allocUnsafe(size); + }; + Buffer2.allocUnsafeSlow = function(size) { + return allocUnsafe(size); + }; + function fromString(string2, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + if (!Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + const length2 = byteLength2(string2, encoding) | 0; + let buf = createBuffer(length2); + const actual = buf.write(string2, encoding); + if (actual !== length2) { + buf = buf.slice(0, actual); + } + return buf; + } + function fromArrayLike(array2) { + const length2 = array2.length < 0 ? 0 : checked(array2.length) | 0; + const buf = createBuffer(length2); + for (let i = 0; i < length2; i += 1) { + buf[i] = array2[i] & 255; + } + return buf; + } + function fromArrayView(arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy2 = new Uint8Array(arrayView); + return fromArrayBuffer(copy2.buffer, copy2.byteOffset, copy2.byteLength); + } + return fromArrayLike(arrayView); + } + function fromArrayBuffer(array2, byteOffset, length2) { + if (byteOffset < 0 || array2.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds'); + } + if (array2.byteLength < byteOffset + (length2 || 0)) { + throw new RangeError('"length" is outside of buffer bounds'); + } + let buf; + if (byteOffset === void 0 && length2 === void 0) { + buf = new Uint8Array(array2); + } else if (length2 === void 0) { + buf = new Uint8Array(array2, byteOffset); + } else { + buf = new Uint8Array(array2, byteOffset, length2); + } + Object.setPrototypeOf(buf, Buffer2.prototype); + return buf; + } + function fromObject(obj) { + if (Buffer2.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + if (buf.length === 0) { + return buf; + } + obj.copy(buf, 0, 0, len); + return buf; + } + if (obj.length !== void 0) { + if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { + return createBuffer(0); + } + return fromArrayLike(obj); + } + if (obj.type === "Buffer" && Array.isArray(obj.data)) { + return fromArrayLike(obj.data); + } + } + function checked(length2) { + if (length2 >= K_MAX_LENGTH) { + throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); + } + return length2 | 0; + } + function SlowBuffer(length2) { + if (+length2 != length2) { + length2 = 0; + } + return Buffer2.alloc(+length2); + } + Buffer2.isBuffer = function isBuffer(b) { + return b != null && b._isBuffer === true && b !== Buffer2.prototype; + }; + Buffer2.compare = function compare(a, b) { + if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength); + if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ); + } + if (a === b) return 0; + let x = a.length; + let y = b.length; + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + Buffer2.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + Buffer2.concat = function concat(list, length2) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + if (list.length === 0) { + return Buffer2.alloc(0); + } + let i; + if (length2 === void 0) { + length2 = 0; + for (i = 0; i < list.length; ++i) { + length2 += list[i].length; + } + } + const buffer2 = Buffer2.allocUnsafe(length2); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer2.length) { + if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf); + buf.copy(buffer2, pos); + } else { + Uint8Array.prototype.set.call( + buffer2, + buf, + pos + ); + } + } else if (!Buffer2.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } else { + buf.copy(buffer2, pos); + } + pos += buf.length; + } + return buffer2; + }; + function byteLength2(string2, encoding) { + if (Buffer2.isBuffer(string2)) { + return string2.length; + } + if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { + return string2.byteLength; + } + if (typeof string2 !== "string") { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 + ); + } + const len = string2.length; + const mustMatch = arguments.length > 2 && arguments[2] === true; + if (!mustMatch && len === 0) return 0; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + return utf8ToBytes(string2).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string2).length; + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string2).length; + } + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.byteLength = byteLength2; + function slowToString(encoding, start, end) { + let loweredCase = false; + if (start === void 0 || start < 0) { + start = 0; + } + if (start > this.length) { + return ""; + } + if (end === void 0 || end > this.length) { + end = this.length; + } + if (end <= 0) { + return ""; + } + end >>>= 0; + start >>>= 0; + if (end <= start) { + return ""; + } + if (!encoding) encoding = "utf8"; + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + case "ascii": + return asciiSlice(this, start, end); + case "latin1": + case "binary": + return latin1Slice(this, start, end); + case "base64": + return base64Slice(this, start, end); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + Buffer2.prototype._isBuffer = true; + function swap(b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; + } + Buffer2.prototype.swap16 = function swap16() { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + Buffer2.prototype.swap32 = function swap32() { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + Buffer2.prototype.swap64 = function swap64() { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + Buffer2.prototype.toString = function toString2() { + const length2 = this.length; + if (length2 === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length2); + return slowToString.apply(this, arguments); + }; + Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; + Buffer2.prototype.equals = function equals2(b) { + if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer2.compare(this, b) === 0; + }; + Buffer2.prototype.inspect = function inspect() { + let str2 = ""; + const max = exports2.INSPECT_MAX_BYTES; + str2 = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); + if (this.length > max) str2 += " ... "; + return ""; + }; + if (customInspectSymbol) { + Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; + } + Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer2.from(target, target.offset, target.byteLength); + } + if (!Buffer2.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target + ); + } + if (start === void 0) { + start = 0; + } + if (end === void 0) { + end = target ? target.length : 0; + } + if (thisStart === void 0) { + thisStart = 0; + } + if (thisEnd === void 0) { + thisEnd = this.length; + } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + if (this === target) return 0; + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) { + if (buffer2.length === 0) return -1; + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 2147483647) { + byteOffset = 2147483647; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; + if (numberIsNaN(byteOffset)) { + byteOffset = dir ? 0 : buffer2.length - 1; + } + if (byteOffset < 0) byteOffset = buffer2.length + byteOffset; + if (byteOffset >= buffer2.length) { + if (dir) return -1; + else byteOffset = buffer2.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + if (typeof val === "string") { + val = Buffer2.from(val, encoding); + } + if (Buffer2.isBuffer(val)) { + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer2, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 255; + if (typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); + } + } + return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir); + } + throw new TypeError("val must be string, number or Buffer"); + } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + if (encoding !== void 0) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + function read(buf, i2) { + if (indexSize === 1) { + return buf[i2]; + } else { + return buf.readUInt16BE(i2 * indexSize); + } + } + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } + return -1; + } + Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + function hexWrite(buf, string2, offset, length2) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length2) { + length2 = remaining; + } else { + length2 = Number(length2); + if (length2 > remaining) { + length2 = remaining; + } + } + const strLen = string2.length; + if (length2 > strLen / 2) { + length2 = strLen / 2; + } + let i; + for (i = 0; i < length2; ++i) { + const parsed = parseInt(string2.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; + } + function utf8Write(buf, string2, offset, length2) { + return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); + } + function asciiWrite(buf, string2, offset, length2) { + return blitBuffer(asciiToBytes(string2), buf, offset, length2); + } + function base64Write(buf, string2, offset, length2) { + return blitBuffer(base64ToBytes(string2), buf, offset, length2); + } + function ucs2Write(buf, string2, offset, length2) { + return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); + } + Buffer2.prototype.write = function write(string2, offset, length2, encoding) { + if (offset === void 0) { + encoding = "utf8"; + length2 = this.length; + offset = 0; + } else if (length2 === void 0 && typeof offset === "string") { + encoding = offset; + length2 = this.length; + offset = 0; + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length2)) { + length2 = length2 >>> 0; + if (encoding === void 0) encoding = "utf8"; + } else { + encoding = length2; + length2 = void 0; + } + } else { + throw new Error( + "Buffer.write(string, encoding, offset[, length]) is no longer supported" + ); + } + const remaining = this.length - offset; + if (length2 === void 0 || length2 > remaining) length2 = remaining; + if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + if (!encoding) encoding = "utf8"; + let loweredCase = false; + for (; ; ) { + switch (encoding) { + case "hex": + return hexWrite(this, string2, offset, length2); + case "utf8": + case "utf-8": + return utf8Write(this, string2, offset, length2); + case "ascii": + case "latin1": + case "binary": + return asciiWrite(this, string2, offset, length2); + case "base64": + return base64Write(this, string2, offset, length2); + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string2, offset, length2); + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + Buffer2.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0) + }; + }; + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return base64.fromByteArray(buf); + } else { + return base64.fromByteArray(buf.slice(start, end)); + } + } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + switch (bytesPerSequence) { + case 1: + if (firstByte < 128) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 192) === 128) { + tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; + if (tempCodePoint > 127) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; + if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { + tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; + if (tempCodePoint > 65535 && tempCodePoint < 1114112) { + codePoint = tempCodePoint; + } + } + } + } + if (codePoint === null) { + codePoint = 65533; + bytesPerSequence = 1; + } else if (codePoint > 65535) { + codePoint -= 65536; + res.push(codePoint >>> 10 & 1023 | 55296); + codePoint = 56320 | codePoint & 1023; + } + res.push(codePoint); + i += bytesPerSequence; + } + return decodeCodePointsArray(res); + } + const MAX_ARGUMENTS_LENGTH = 4096; + function decodeCodePointsArray(codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); + } + let res = ""; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res; + } + function asciiSlice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 127); + } + return ret; + } + function latin1Slice(buf, start, end) { + let ret = ""; + end = Math.min(buf.length, end); + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + function hexSlice(buf, start, end) { + const len = buf.length; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + let out = ""; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out; + } + function utf16leSlice(buf, start, end) { + const bytes = buf.slice(start, end); + let res = ""; + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + Buffer2.prototype.slice = function slice2(start, end) { + const len = this.length; + start = ~~start; + end = end === void 0 ? len : ~~end; + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + if (end < start) end = start; + const newBuf = this.subarray(start, end); + Object.setPrototypeOf(newBuf, Buffer2.prototype); + return newBuf; + }; + function checkOffset(offset, ext, length2) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); + if (offset + ext > length2) throw new RangeError("Trying to access beyond buffer length"); + } + Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) { + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset, byteLength3, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength3 && (mul *= 256)) { + val += this[offset + i] * mul; + } + return val; + }; + Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) { + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength3, this.length); + } + let val = this[offset + --byteLength3]; + let mul = 1; + while (byteLength3 > 0 && (mul *= 256)) { + val += this[offset + --byteLength3] * mul; + } + return val; + }; + Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | this[offset + 1] << 8; + }; + Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] << 8 | this[offset + 1]; + }; + Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; + }; + Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); + }; + Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; + const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; + return BigInt(lo) + (BigInt(hi) << BigInt(32)); + }); + Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; + return (BigInt(hi) << BigInt(32)) + BigInt(lo); + }); + Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) { + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset, byteLength3, this.length); + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength3 && (mul *= 256)) { + val += this[offset + i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength3); + return val; + }; + Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) { + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) checkOffset(offset, byteLength3, this.length); + let i = byteLength3; + let mul = 1; + let val = this[offset + --i]; + while (i > 0 && (mul *= 256)) { + val += this[offset + --i] * mul; + } + mul *= 128; + if (val >= mul) val -= Math.pow(2, 8 * byteLength3); + return val; + }; + Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 128)) return this[offset]; + return (255 - this[offset] + 1) * -1; + }; + Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset] | this[offset + 1] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset + 1] | this[offset] << 8; + return val & 32768 ? val | 4294901760 : val; + }; + Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; + }; + Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; + }; + Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); + return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); + }); + Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { + offset = offset >>> 0; + validateNumber(offset, "offset"); + const first = this[offset]; + const last = this[offset + 7]; + if (first === void 0 || last === void 0) { + boundsError(offset, this.length - 8); + } + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; + return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); + }); + Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, true, 23, 4); + }; + Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754$1.read(this, offset, false, 23, 4); + }; + Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, true, 52, 8); + }; + Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754$1.read(this, offset, false, 52, 8); + }; + function checkInt(buf, value2, offset, ext, max, min) { + if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value2 > max || value2 < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + } + Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value2, offset, byteLength3, noAssert) { + value2 = +value2; + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength3) - 1; + checkInt(this, value2, offset, byteLength3, maxBytes, 0); + } + let mul = 1; + let i = 0; + this[offset] = value2 & 255; + while (++i < byteLength3 && (mul *= 256)) { + this[offset + i] = value2 / mul & 255; + } + return offset + byteLength3; + }; + Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value2, offset, byteLength3, noAssert) { + value2 = +value2; + offset = offset >>> 0; + byteLength3 = byteLength3 >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength3) - 1; + checkInt(this, value2, offset, byteLength3, maxBytes, 0); + } + let i = byteLength3 - 1; + let mul = 1; + this[offset + i] = value2 & 255; + while (--i >= 0 && (mul *= 256)) { + this[offset + i] = value2 / mul & 255; + } + return offset + byteLength3; + }; + Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 1, 255, 0); + this[offset] = value2 & 255; + return offset + 1; + }; + Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0); + this[offset] = value2 & 255; + this[offset + 1] = value2 >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0); + this[offset] = value2 >>> 8; + this[offset + 1] = value2 & 255; + return offset + 2; + }; + Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0); + this[offset + 3] = value2 >>> 24; + this[offset + 2] = value2 >>> 16; + this[offset + 1] = value2 >>> 8; + this[offset] = value2 & 255; + return offset + 4; + }; + Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0); + this[offset] = value2 >>> 24; + this[offset + 1] = value2 >>> 16; + this[offset + 2] = value2 >>> 8; + this[offset + 3] = value2 & 255; + return offset + 4; + }; + function wrtBigUInt64LE(buf, value2, offset, min, max) { + checkIntBI(value2, min, max, buf, offset, 7); + let lo = Number(value2 & BigInt(4294967295)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value2 >> BigInt(32) & BigInt(4294967295)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset; + } + function wrtBigUInt64BE(buf, value2, offset, min, max) { + checkIntBI(value2, min, max, buf, offset, 7); + let lo = Number(value2 & BigInt(4294967295)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value2 >> BigInt(32) & BigInt(4294967295)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8; + } + Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value2, offset = 0) { + return wrtBigUInt64LE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value2, offset = 0) { + return wrtBigUInt64BE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff")); + }); + Buffer2.prototype.writeIntLE = function writeIntLE(value2, offset, byteLength3, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength3 - 1); + checkInt(this, value2, offset, byteLength3, limit - 1, -limit); + } + let i = 0; + let mul = 1; + let sub = 0; + this[offset] = value2 & 255; + while (++i < byteLength3 && (mul *= 256)) { + if (value2 < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (value2 / mul >> 0) - sub & 255; + } + return offset + byteLength3; + }; + Buffer2.prototype.writeIntBE = function writeIntBE(value2, offset, byteLength3, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, 8 * byteLength3 - 1); + checkInt(this, value2, offset, byteLength3, limit - 1, -limit); + } + let i = byteLength3 - 1; + let mul = 1; + let sub = 0; + this[offset + i] = value2 & 255; + while (--i >= 0 && (mul *= 256)) { + if (value2 < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (value2 / mul >> 0) - sub & 255; + } + return offset + byteLength3; + }; + Buffer2.prototype.writeInt8 = function writeInt8(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 1, 127, -128); + if (value2 < 0) value2 = 255 + value2 + 1; + this[offset] = value2 & 255; + return offset + 1; + }; + Buffer2.prototype.writeInt16LE = function writeInt16LE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768); + this[offset] = value2 & 255; + this[offset + 1] = value2 >>> 8; + return offset + 2; + }; + Buffer2.prototype.writeInt16BE = function writeInt16BE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768); + this[offset] = value2 >>> 8; + this[offset + 1] = value2 & 255; + return offset + 2; + }; + Buffer2.prototype.writeInt32LE = function writeInt32LE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648); + this[offset] = value2 & 255; + this[offset + 1] = value2 >>> 8; + this[offset + 2] = value2 >>> 16; + this[offset + 3] = value2 >>> 24; + return offset + 4; + }; + Buffer2.prototype.writeInt32BE = function writeInt32BE(value2, offset, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648); + if (value2 < 0) value2 = 4294967295 + value2 + 1; + this[offset] = value2 >>> 24; + this[offset + 1] = value2 >>> 16; + this[offset + 2] = value2 >>> 8; + this[offset + 3] = value2 & 255; + return offset + 4; + }; + Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value2, offset = 0) { + return wrtBigUInt64LE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value2, offset = 0) { + return wrtBigUInt64BE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); + }); + function checkIEEE754(buf, value2, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); + } + function writeFloat(buf, value2, offset, littleEndian, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value2, offset, 4); + } + ieee754$1.write(buf, value2, offset, littleEndian, 23, 4); + return offset + 4; + } + Buffer2.prototype.writeFloatLE = function writeFloatLE(value2, offset, noAssert) { + return writeFloat(this, value2, offset, true, noAssert); + }; + Buffer2.prototype.writeFloatBE = function writeFloatBE(value2, offset, noAssert) { + return writeFloat(this, value2, offset, false, noAssert); + }; + function writeDouble(buf, value2, offset, littleEndian, noAssert) { + value2 = +value2; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value2, offset, 8); + } + ieee754$1.write(buf, value2, offset, littleEndian, 52, 8); + return offset + 8; + } + Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value2, offset, noAssert) { + return writeDouble(this, value2, offset, true, noAssert); + }; + Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value2, offset, noAssert) { + return writeDouble(this, value2, offset, false, noAssert); + }; + Buffer2.prototype.copy = function copy2(target, targetStart, start, end) { + if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer"); + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + const len = end - start; + if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + return len; + }; + Buffer2.prototype.fill = function fill(val, start, end, encoding) { + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (encoding !== void 0 && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + if (val.length === 1) { + const code2 = val.charCodeAt(0); + if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { + val = code2; + } + } + } else if (typeof val === "number") { + val = val & 255; + } else if (typeof val === "boolean") { + val = Number(val); + } + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + if (end <= start) { + return this; + } + start = start >>> 0; + end = end === void 0 ? this.length : end >>> 0; + if (!val) val = 0; + let i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + '" is invalid for argument "value"'); + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + return this; + }; + const errors = {}; + function E2(sym, getMessage, Base) { + errors[sym] = class NodeError extends Base { + constructor() { + super(); + Object.defineProperty(this, "message", { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + this.name = `${this.name} [${sym}]`; + this.stack; + delete this.name; + } + get code() { + return sym; + } + set code(value2) { + Object.defineProperty(this, "code", { + configurable: true, + enumerable: true, + value: value2, + writable: true + }); + } + toString() { + return `${this.name} [${sym}]: ${this.message}`; + } + }; + } + E2( + "ERR_BUFFER_OUT_OF_BOUNDS", + function(name2) { + if (name2) { + return `${name2} is outside of buffer bounds`; + } + return "Attempt to access memory outside buffer bounds"; + }, + RangeError + ); + E2( + "ERR_INVALID_ARG_TYPE", + function(name2, actual) { + return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; + }, + TypeError + ); + E2( + "ERR_OUT_OF_RANGE", + function(str2, range, input) { + let msg2 = `The value of "${str2}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === "bigint") { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += "n"; + } + msg2 += ` It must be ${range}. Received ${received}`; + return msg2; + }, + RangeError + ); + function addNumericalSeparator(val) { + let res = ""; + let i = val.length; + const start = val[0] === "-" ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}`; + } + function checkBounds(buf, offset, byteLength3) { + validateNumber(offset, "offset"); + if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) { + boundsError(offset, buf.length - (byteLength3 + 1)); + } + } + function checkIntBI(value2, min, max, buf, offset, byteLength3) { + if (value2 > max || value2 < min) { + const n = typeof min === "bigint" ? "n" : ""; + let range; + { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`; + } else { + range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`; + } + } + throw new errors.ERR_OUT_OF_RANGE("value", range, value2); + } + checkBounds(buf, offset, byteLength3); + } + function validateNumber(value2, name2) { + if (typeof value2 !== "number") { + throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value2); + } + } + function boundsError(value2, length2, type) { + if (Math.floor(value2) !== value2) { + validateNumber(value2, type); + throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value2); + } + if (length2 < 0) { + throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); + } + throw new errors.ERR_OUT_OF_RANGE( + "offset", + `>= ${0} and <= ${length2}`, + value2 + ); + } + const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + function base64clean(str2) { + str2 = str2.split("=")[0]; + str2 = str2.trim().replace(INVALID_BASE64_RE, ""); + if (str2.length < 2) return ""; + while (str2.length % 4 !== 0) { + str2 = str2 + "="; + } + return str2; + } + function utf8ToBytes(string2, units) { + units = units || Infinity; + let codePoint; + const length2 = string2.length; + let leadSurrogate = null; + const bytes = []; + for (let i = 0; i < length2; ++i) { + codePoint = string2.charCodeAt(i); + if (codePoint > 55295 && codePoint < 57344) { + if (!leadSurrogate) { + if (codePoint > 56319) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } else if (i + 1 === length2) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + continue; + } + leadSurrogate = codePoint; + continue; + } + if (codePoint < 56320) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + leadSurrogate = codePoint; + continue; + } + codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; + } else if (leadSurrogate) { + if ((units -= 3) > -1) bytes.push(239, 191, 189); + } + leadSurrogate = null; + if (codePoint < 128) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 2048) { + if ((units -= 2) < 0) break; + bytes.push( + codePoint >> 6 | 192, + codePoint & 63 | 128 + ); + } else if (codePoint < 65536) { + if ((units -= 3) < 0) break; + bytes.push( + codePoint >> 12 | 224, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else if (codePoint < 1114112) { + if ((units -= 4) < 0) break; + bytes.push( + codePoint >> 18 | 240, + codePoint >> 12 & 63 | 128, + codePoint >> 6 & 63 | 128, + codePoint & 63 | 128 + ); + } else { + throw new Error("Invalid code point"); + } + } + return bytes; + } + function asciiToBytes(str2) { + const byteArray = []; + for (let i = 0; i < str2.length; ++i) { + byteArray.push(str2.charCodeAt(i) & 255); + } + return byteArray; + } + function utf16leToBytes(str2, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str2.length; ++i) { + if ((units -= 2) < 0) break; + c = str2.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + return byteArray; + } + function base64ToBytes(str2) { + return base64.toByteArray(base64clean(str2)); + } + function blitBuffer(src2, dst, offset, length2) { + let i; + for (i = 0; i < length2; ++i) { + if (i + offset >= dst.length || i >= src2.length) break; + dst[i + offset] = src2[i]; + } + return i; + } + function isInstance(obj, type) { + return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; + } + function numberIsNaN(obj) { + return obj !== obj; + } + const hexSliceLookupTable = function() { + const alphabet = "0123456789abcdef"; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table; + }(); + function defineBigIntMethod(fn) { + return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; + } + function BufferBigIntNotDefined() { + throw new Error("BigInt not supported"); + } +})(buffer); +var bits = twiddle; +var dup = dup$1; +var Buffer = buffer.Buffer; +if (!index$3.commonjsGlobal.__TYPEDARRAY_POOL) { + index$3.commonjsGlobal.__TYPEDARRAY_POOL = { + UINT8: dup([32, 0]), + UINT16: dup([32, 0]), + UINT32: dup([32, 0]), + BIGUINT64: dup([32, 0]), + INT8: dup([32, 0]), + INT16: dup([32, 0]), + INT32: dup([32, 0]), + BIGINT64: dup([32, 0]), + FLOAT: dup([32, 0]), + DOUBLE: dup([32, 0]), + DATA: dup([32, 0]), + UINT8C: dup([32, 0]), + BUFFER: dup([32, 0]) + }; +} +var hasUint8C = typeof Uint8ClampedArray !== "undefined"; +var hasBigUint64 = typeof BigUint64Array !== "undefined"; +var hasBigInt64 = typeof BigInt64Array !== "undefined"; +var POOL = index$3.commonjsGlobal.__TYPEDARRAY_POOL; +if (!POOL.UINT8C) { + POOL.UINT8C = dup([32, 0]); +} +if (!POOL.BIGUINT64) { + POOL.BIGUINT64 = dup([32, 0]); +} +if (!POOL.BIGINT64) { + POOL.BIGINT64 = dup([32, 0]); +} +if (!POOL.BUFFER) { + POOL.BUFFER = dup([32, 0]); +} +var DATA = POOL.DATA, BUFFER = POOL.BUFFER; +pool$1.free = function free(array2) { + if (Buffer.isBuffer(array2)) { + BUFFER[bits.log2(array2.length)].push(array2); + } else { + if (Object.prototype.toString.call(array2) !== "[object ArrayBuffer]") { + array2 = array2.buffer; + } + if (!array2) { + return; + } + var n = array2.length || array2.byteLength; + var log_n = bits.log2(n) | 0; + DATA[log_n].push(array2); + } +}; +function freeArrayBuffer(buffer2) { + if (!buffer2) { + return; + } + var n = buffer2.length || buffer2.byteLength; + var log_n = bits.log2(n); + DATA[log_n].push(buffer2); +} +function freeTypedArray(array2) { + freeArrayBuffer(array2.buffer); +} +pool$1.freeUint8 = pool$1.freeUint16 = pool$1.freeUint32 = pool$1.freeBigUint64 = pool$1.freeInt8 = pool$1.freeInt16 = pool$1.freeInt32 = pool$1.freeBigInt64 = pool$1.freeFloat32 = pool$1.freeFloat = pool$1.freeFloat64 = pool$1.freeDouble = pool$1.freeUint8Clamped = pool$1.freeDataView = freeTypedArray; +pool$1.freeArrayBuffer = freeArrayBuffer; +pool$1.freeBuffer = function freeBuffer(array2) { + BUFFER[bits.log2(array2.length)].push(array2); +}; +pool$1.malloc = function malloc(n, dtype2) { + if (dtype2 === void 0 || dtype2 === "arraybuffer") { + return mallocArrayBuffer(n); + } else { + switch (dtype2) { + case "uint8": + return mallocUint8(n); + case "uint16": + return mallocUint16(n); + case "uint32": + return mallocUint32(n); + case "int8": + return mallocInt8(n); + case "int16": + return mallocInt16(n); + case "int32": + return mallocInt32(n); + case "float": + case "float32": + return mallocFloat(n); + case "double": + case "float64": + return mallocDouble(n); + case "uint8_clamped": + return mallocUint8Clamped(n); + case "bigint64": + return mallocBigInt64(n); + case "biguint64": + return mallocBigUint64(n); + case "buffer": + return mallocBuffer(n); + case "data": + case "dataview": + return mallocDataView(n); + default: + return null; + } + } + return null; +}; +function mallocArrayBuffer(n) { + var n = bits.nextPow2(n); + var log_n = bits.log2(n); + var d = DATA[log_n]; + if (d.length > 0) { + return d.pop(); + } + return new ArrayBuffer(n); +} +pool$1.mallocArrayBuffer = mallocArrayBuffer; +function mallocUint8(n) { + return new Uint8Array(mallocArrayBuffer(n), 0, n); +} +pool$1.mallocUint8 = mallocUint8; +function mallocUint16(n) { + return new Uint16Array(mallocArrayBuffer(2 * n), 0, n); +} +pool$1.mallocUint16 = mallocUint16; +function mallocUint32(n) { + return new Uint32Array(mallocArrayBuffer(4 * n), 0, n); +} +pool$1.mallocUint32 = mallocUint32; +function mallocInt8(n) { + return new Int8Array(mallocArrayBuffer(n), 0, n); +} +pool$1.mallocInt8 = mallocInt8; +function mallocInt16(n) { + return new Int16Array(mallocArrayBuffer(2 * n), 0, n); +} +pool$1.mallocInt16 = mallocInt16; +function mallocInt32(n) { + return new Int32Array(mallocArrayBuffer(4 * n), 0, n); +} +pool$1.mallocInt32 = mallocInt32; +function mallocFloat(n) { + return new Float32Array(mallocArrayBuffer(4 * n), 0, n); +} +pool$1.mallocFloat32 = pool$1.mallocFloat = mallocFloat; +function mallocDouble(n) { + return new Float64Array(mallocArrayBuffer(8 * n), 0, n); +} +pool$1.mallocFloat64 = pool$1.mallocDouble = mallocDouble; +function mallocUint8Clamped(n) { + if (hasUint8C) { + return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n); + } else { + return mallocUint8(n); + } +} +pool$1.mallocUint8Clamped = mallocUint8Clamped; +function mallocBigUint64(n) { + if (hasBigUint64) { + return new BigUint64Array(mallocArrayBuffer(8 * n), 0, n); + } else { + return null; + } +} +pool$1.mallocBigUint64 = mallocBigUint64; +function mallocBigInt64(n) { + if (hasBigInt64) { + return new BigInt64Array(mallocArrayBuffer(8 * n), 0, n); + } else { + return null; + } +} +pool$1.mallocBigInt64 = mallocBigInt64; +function mallocDataView(n) { + return new DataView(mallocArrayBuffer(n), 0, n); +} +pool$1.mallocDataView = mallocDataView; +function mallocBuffer(n) { + n = bits.nextPow2(n); + var log_n = bits.log2(n); + var cache2 = BUFFER[log_n]; + if (cache2.length > 0) { + return cache2.pop(); + } + return new Buffer(n); +} +pool$1.mallocBuffer = mallocBuffer; +pool$1.clearCache = function clearCache() { + for (var i = 0; i < 32; ++i) { + POOL.UINT8[i].length = 0; + POOL.UINT16[i].length = 0; + POOL.UINT32[i].length = 0; + POOL.INT8[i].length = 0; + POOL.INT16[i].length = 0; + POOL.INT32[i].length = 0; + POOL.FLOAT[i].length = 0; + POOL.DOUBLE[i].length = 0; + POOL.BIGUINT64[i].length = 0; + POOL.BIGINT64[i].length = 0; + POOL.UINT8C[i].length = 0; + DATA[i].length = 0; + BUFFER[i].length = 0; + } +}; +var toString = Object.prototype.toString; +var isPlainObj = function(x) { + var prototype; + return toString.call(x) === "[object Object]" && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); +}; +var parseUnit$2 = function parseUnit(str2, out) { + if (!out) + out = [0, ""]; + str2 = String(str2); + var num = parseFloat(str2, 10); + out[0] = num; + out[1] = str2.match(/[\d.\-\+]*\s*(.*)/)[1] || ""; + return out; +}; +var parseUnit$1 = parseUnit$2; +var topx = toPX; +var PIXELS_PER_INCH = 96; +function getPropertyInPX(element, prop) { + var parts = parseUnit$1(getComputedStyle(element).getPropertyValue(prop)); + return parts[0] * toPX(parts[1], element); +} +function getSizeBrutal(unit, element) { + var testDIV = document.createElement("div"); + testDIV.style["font-size"] = "128" + unit; + element.appendChild(testDIV); + var size = getPropertyInPX(testDIV, "font-size") / 128; + element.removeChild(testDIV); + return size; +} +function toPX(str2, element) { + element = element || document.body; + str2 = (str2 || "px").trim().toLowerCase(); + if (element === window || element === document) { + element = document.body; + } + switch (str2) { + case "%": + return element.clientHeight / 100; + case "ch": + case "ex": + return getSizeBrutal(str2, element); + case "em": + return getPropertyInPX(element, "font-size"); + case "rem": + return getPropertyInPX(document.body, "font-size"); + case "vw": + return window.innerWidth / 100; + case "vh": + return window.innerHeight / 100; + case "vmin": + return Math.min(window.innerWidth, window.innerHeight) / 100; + case "vmax": + return Math.max(window.innerWidth, window.innerHeight) / 100; + case "in": + return PIXELS_PER_INCH; + case "cm": + return PIXELS_PER_INCH / 2.54; + case "mm": + return PIXELS_PER_INCH / 25.4; + case "pt": + return PIXELS_PER_INCH / 72; + case "pc": + return PIXELS_PER_INCH / 6; + } + return 1; +} +var detectKerning = kerning$1; +var canvas = kerning$1.canvas = document.createElement("canvas"); +var ctx = canvas.getContext("2d"); +var asciiPairs = createPairs([32, 126]); +kerning$1.createPairs = createPairs; +kerning$1.ascii = asciiPairs; +function kerning$1(family, o) { + if (Array.isArray(family)) family = family.join(", "); + var table = {}, pairs, fs = 16, threshold = 0.05; + if (o) { + if (o.length === 2 && typeof o[0] === "number") { + pairs = createPairs(o); + } else if (Array.isArray(o)) { + pairs = o; + } else { + if (o.o) pairs = createPairs(o.o); + else if (o.pairs) pairs = o.pairs; + if (o.fontSize) fs = o.fontSize; + if (o.threshold != null) threshold = o.threshold; + } + } + if (!pairs) pairs = asciiPairs; + ctx.font = fs + "px " + family; + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var width = ctx.measureText(pair[0]).width + ctx.measureText(pair[1]).width; + var kerningWidth = ctx.measureText(pair).width; + if (Math.abs(width - kerningWidth) > fs * threshold) { + var emWidth = (kerningWidth - width) / fs; + table[pair] = emWidth * 1e3; + } + } + return table; +} +function createPairs(range) { + var pairs = []; + for (var i = range[0]; i <= range[1]; i++) { + var leftChar = String.fromCharCode(i); + for (var j = range[0]; j < range[1]; j++) { + var rightChar = String.fromCharCode(j); + var pair = leftChar + rightChar; + pairs.push(pair); + } + } + return pairs; +} +var fontMeasure = measure; +measure.canvas = document.createElement("canvas"); +measure.cache = {}; +function measure(font2, o) { + if (!o) o = {}; + if (typeof font2 === "string" || Array.isArray(font2)) { + o.family = font2; + } + var family = Array.isArray(o.family) ? o.family.join(", ") : o.family; + if (!family) throw Error("`family` must be defined"); + var fs = o.size || o.fontSize || o.em || 48; + var weight = o.weight || o.fontWeight || ""; + var style5 = o.style || o.fontStyle || ""; + var font2 = [style5, weight, fs].join(" ") + "px " + family; + var origin = o.origin || "top"; + if (measure.cache[family]) { + if (fs <= measure.cache[family].em) { + return applyOrigin(measure.cache[family], origin); + } + } + var canvas2 = o.canvas || measure.canvas; + var ctx2 = canvas2.getContext("2d"); + var chars2 = { + upper: o.upper !== void 0 ? o.upper : "H", + lower: o.lower !== void 0 ? o.lower : "x", + descent: o.descent !== void 0 ? o.descent : "p", + ascent: o.ascent !== void 0 ? o.ascent : "h", + tittle: o.tittle !== void 0 ? o.tittle : "i", + overshoot: o.overshoot !== void 0 ? o.overshoot : "O" + }; + var l = Math.ceil(fs * 1.5); + canvas2.height = l; + canvas2.width = l * 0.5; + ctx2.font = font2; + var char = "H"; + var result = { + top: 0 + }; + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillStyle = "black"; + ctx2.fillText(char, 0, 0); + var topPx = firstTop(ctx2.getImageData(0, 0, l, l)); + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "bottom"; + ctx2.fillText(char, 0, l); + var bottomPx = firstTop(ctx2.getImageData(0, 0, l, l)); + result.lineHeight = result.bottom = l - bottomPx + topPx; + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "alphabetic"; + ctx2.fillText(char, 0, l); + var baselinePx = firstTop(ctx2.getImageData(0, 0, l, l)); + var baseline = l - baselinePx - 1 + topPx; + result.baseline = result.alphabetic = baseline; + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "middle"; + ctx2.fillText(char, 0, l * 0.5); + var medianPx = firstTop(ctx2.getImageData(0, 0, l, l)); + result.median = result.middle = l - medianPx - 1 + topPx - l * 0.5; + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "hanging"; + ctx2.fillText(char, 0, l * 0.5); + var hangingPx = firstTop(ctx2.getImageData(0, 0, l, l)); + result.hanging = l - hangingPx - 1 + topPx - l * 0.5; + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "ideographic"; + ctx2.fillText(char, 0, l); + var ideographicPx = firstTop(ctx2.getImageData(0, 0, l, l)); + result.ideographic = l - ideographicPx - 1 + topPx; + if (chars2.upper) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.upper, 0, 0); + result.upper = firstTop(ctx2.getImageData(0, 0, l, l)); + result.capHeight = result.baseline - result.upper; + } + if (chars2.lower) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.lower, 0, 0); + result.lower = firstTop(ctx2.getImageData(0, 0, l, l)); + result.xHeight = result.baseline - result.lower; + } + if (chars2.tittle) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.tittle, 0, 0); + result.tittle = firstTop(ctx2.getImageData(0, 0, l, l)); + } + if (chars2.ascent) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.ascent, 0, 0); + result.ascent = firstTop(ctx2.getImageData(0, 0, l, l)); + } + if (chars2.descent) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.descent, 0, 0); + result.descent = firstBottom(ctx2.getImageData(0, 0, l, l)); + } + if (chars2.overshoot) { + ctx2.clearRect(0, 0, l, l); + ctx2.textBaseline = "top"; + ctx2.fillText(chars2.overshoot, 0, 0); + var overshootPx = firstBottom(ctx2.getImageData(0, 0, l, l)); + result.overshoot = overshootPx - baseline; + } + for (var name2 in result) { + result[name2] /= fs; + } + result.em = fs; + measure.cache[family] = result; + return applyOrigin(result, origin); +} +function applyOrigin(obj, origin) { + var res = {}; + if (typeof origin === "string") origin = obj[origin]; + for (var name2 in obj) { + if (name2 === "em") continue; + res[name2] = obj[name2] - origin; + } + return res; +} +function firstTop(iData) { + var l = iData.height; + var data = iData.data; + for (var i = 3; i < data.length; i += 4) { + if (data[i] !== 0) { + return Math.floor((i - 3) * 0.25 / l); + } + } +} +function firstBottom(iData) { + var l = iData.height; + var data = iData.data; + for (var i = data.length - 1; i > 0; i -= 4) { + if (data[i] !== 0) { + return Math.floor((i - 3) * 0.25 / l); + } + } +} +var Font = cssFont; +var pick2 = pickByAlias; +var createRegl$1 = regl_uncheckedExports; +var createGl = context; +var WeakMap$1 = es6WeakMap; +var rgba$1 = colorNormalize; +var fontAtlas = fontAtlas$1; +var pool = pool$1; +var parseRect = parseRect_1; +var isObj = isPlainObj; +var parseUnit2 = parseUnit$2; +var px = topx; +var kerning = detectKerning; +var extend$1 = index$3.objectAssign; +var metrics = fontMeasure; +var flatten = flattenVertexData_1; +var ref = twiddle; +var nextPow2 = ref.nextPow2; +var shaderCache = new WeakMap$1(); +var isStretchSupported = false; +if (document.body) { + var el = document.body.appendChild(document.createElement("div")); + el.style.font = "italic small-caps bold condensed 16px/2 cursive"; + if (getComputedStyle(el).fontStretch) { + isStretchSupported = true; + } + document.body.removeChild(el); +} +var GlText = function GlText2(o) { + if (isRegl(o)) { + o = { regl: o }; + this.gl = o.regl._gl; + } else { + this.gl = createGl(o); + } + this.shader = shaderCache.get(this.gl); + if (!this.shader) { + this.regl = o.regl || createRegl$1({ gl: this.gl }); + } else { + this.regl = this.shader.regl; + } + this.charBuffer = this.regl.buffer({ type: "uint8", usage: "stream" }); + this.sizeBuffer = this.regl.buffer({ type: "float", usage: "stream" }); + if (!this.shader) { + this.shader = this.createShader(); + shaderCache.set(this.gl, this.shader); + } + this.batch = []; + this.fontSize = []; + this.font = []; + this.fontAtlas = []; + this.draw = this.shader.draw.bind(this); + this.render = function() { + this.regl._refresh(); + this.draw(this.batch); + }; + this.canvas = this.gl.canvas; + this.update(isObj(o) ? o : {}); +}; +GlText.prototype.createShader = function createShader() { + var regl = this.regl; + var draw8 = regl({ + blend: { + enable: true, + color: [0, 0, 0, 1], + func: { + srcRGB: "src alpha", + dstRGB: "one minus src alpha", + srcAlpha: "one minus dst alpha", + dstAlpha: "one" + } + }, + stencil: { enable: false }, + depth: { enable: false }, + count: regl.prop("count"), + offset: regl.prop("offset"), + attributes: { + charOffset: { + offset: 4, + stride: 8, + buffer: regl.this("sizeBuffer") + }, + width: { + offset: 0, + stride: 8, + buffer: regl.this("sizeBuffer") + }, + char: regl.this("charBuffer"), + position: regl.this("position") + }, + uniforms: { + atlasSize: function(c, p) { + return [p.atlas.width, p.atlas.height]; + }, + atlasDim: function(c, p) { + return [p.atlas.cols, p.atlas.rows]; + }, + atlas: function(c, p) { + return p.atlas.texture; + }, + charStep: function(c, p) { + return p.atlas.step; + }, + em: function(c, p) { + return p.atlas.em; + }, + color: regl.prop("color"), + opacity: regl.prop("opacity"), + viewport: regl.this("viewportArray"), + scale: regl.this("scale"), + align: regl.prop("align"), + baseline: regl.prop("baseline"), + translate: regl.this("translate"), + positionOffset: regl.prop("positionOffset") + }, + primitive: "points", + viewport: regl.this("viewport"), + vert: "\n precision highp float;\n attribute float width, charOffset, char;\n attribute vec2 position;\n uniform float fontSize, charStep, em, align, baseline;\n uniform vec4 viewport;\n uniform vec4 color;\n uniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n varying vec2 charCoord, charId;\n varying float charWidth;\n varying vec4 fontColor;\n void main () {\n vec2 offset = floor(em * (vec2(align + charOffset, baseline)\n + vec2(positionOffset.x, -positionOffset.y)))\n / (viewport.zw * scale.xy);\n\n vec2 position = (position + translate) * scale;\n position += offset * scale;\n\n charCoord = position * viewport.zw + viewport.xy;\n\n gl_Position = vec4(position * 2. - 1., 0, 1);\n\n gl_PointSize = charStep;\n\n charId.x = mod(char, atlasDim.x);\n charId.y = floor(char / atlasDim.x);\n\n charWidth = width * em;\n\n fontColor = color / 255.;\n }", + frag: "\n precision highp float;\n uniform float fontSize, charStep, opacity;\n uniform vec2 atlasSize;\n uniform vec4 viewport;\n uniform sampler2D atlas;\n varying vec4 fontColor;\n varying vec2 charCoord, charId;\n varying float charWidth;\n\n float lightness(vec4 color) {\n return color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n }\n\n void main () {\n vec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n float halfCharStep = floor(charStep * .5 + .5);\n\n // invert y and shift by 1px (FF expecially needs that)\n uv.y = charStep - uv.y;\n\n // ignore points outside of character bounding box\n float halfCharWidth = ceil(charWidth * .5);\n if (floor(uv.x) > halfCharStep + halfCharWidth ||\n floor(uv.x) < halfCharStep - halfCharWidth) return;\n\n uv += charId * charStep;\n uv = uv / atlasSize;\n\n vec4 color = fontColor;\n vec4 mask = texture2D(atlas, uv);\n\n float maskY = lightness(mask);\n // float colorY = lightness(color);\n color.a *= maskY;\n color.a *= opacity;\n\n // color.a += .1;\n\n // antialiasing, see yiq color space y-channel formula\n // color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n gl_FragColor = color;\n }" + }); + var atlas2 = {}; + return { regl, draw: draw8, atlas: atlas2 }; +}; +GlText.prototype.update = function update(o) { + var this$1$1 = this; + if (typeof o === "string") { + o = { text: o }; + } else if (!o) { + return; + } + o = pick2(o, { + position: "position positions coord coords coordinates", + font: "font fontFace fontface typeface cssFont css-font family fontFamily", + fontSize: "fontSize fontsize size font-size", + text: "text texts chars characters value values symbols", + align: "align alignment textAlign textbaseline", + baseline: "baseline textBaseline textbaseline", + direction: "dir direction textDirection", + color: "color colour fill fill-color fillColor textColor textcolor", + kerning: "kerning kern", + range: "range dataBox", + viewport: "vp viewport viewBox viewbox viewPort", + opacity: "opacity alpha transparency visible visibility opaque", + offset: "offset positionOffset padding shift indent indentation" + }, true); + if (o.opacity != null) { + if (Array.isArray(o.opacity)) { + this.opacity = o.opacity.map(function(o2) { + return parseFloat(o2); + }); + } else { + this.opacity = parseFloat(o.opacity); + } + } + if (o.viewport != null) { + this.viewport = parseRect(o.viewport); + this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]; + } + if (this.viewport == null) { + this.viewport = { + x: 0, + y: 0, + width: this.gl.drawingBufferWidth, + height: this.gl.drawingBufferHeight + }; + this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]; + } + if (o.kerning != null) { + this.kerning = o.kerning; + } + if (o.offset != null) { + if (typeof o.offset === "number") { + o.offset = [o.offset, 0]; + } + this.positionOffset = flatten(o.offset); + } + if (o.direction) { + this.direction = o.direction; + } + if (o.range) { + this.range = o.range; + this.scale = [1 / (o.range[2] - o.range[0]), 1 / (o.range[3] - o.range[1])]; + this.translate = [-o.range[0], -o.range[1]]; + } + if (o.scale) { + this.scale = o.scale; + } + if (o.translate) { + this.translate = o.translate; + } + if (!this.scale) { + this.scale = [1 / this.viewport.width, 1 / this.viewport.height]; + } + if (!this.translate) { + this.translate = [0, 0]; + } + if (!this.font.length && !o.font) { + o.font = GlText.baseFontSize + "px sans-serif"; + } + var newFont = false, newFontSize = false; + if (o.font) { + (Array.isArray(o.font) ? o.font : [o.font]).forEach(function(font3, i2) { + if (typeof font3 === "string") { + try { + font3 = Font.parse(font3); + } catch (e) { + font3 = Font.parse(GlText.baseFontSize + "px " + font3); + } + } else { + var fontStyle = font3.style; + var fontWeight = font3.weight; + var fontStretch = font3.stretch; + var fontVariant = font3.variant; + font3 = Font.parse(Font.stringify(font3)); + if (fontStyle) font3.style = fontStyle; + if (fontWeight) font3.weight = fontWeight; + if (fontStretch) font3.stretch = fontStretch; + if (fontVariant) font3.variant = fontVariant; + } + var baseString = Font.stringify({ + size: GlText.baseFontSize, + family: font3.family, + stretch: isStretchSupported ? font3.stretch : void 0, + variant: font3.variant, + weight: font3.weight, + style: font3.style + }); + var unit = parseUnit2(font3.size); + var fs = Math.round(unit[0] * px(unit[1])); + if (fs !== this$1$1.fontSize[i2]) { + newFontSize = true; + this$1$1.fontSize[i2] = fs; + } + if (!this$1$1.font[i2] || baseString != this$1$1.font[i2].baseString) { + newFont = true; + this$1$1.font[i2] = GlText.fonts[baseString]; + if (!this$1$1.font[i2]) { + var family = font3.family.join(", "); + var style5 = [font3.style]; + if (font3.style != font3.variant) { + style5.push(font3.variant); + } + if (font3.variant != font3.weight) { + style5.push(font3.weight); + } + if (isStretchSupported && font3.weight != font3.stretch) { + style5.push(font3.stretch); + } + this$1$1.font[i2] = { + baseString, + // typeface + family, + weight: font3.weight, + stretch: font3.stretch, + style: font3.style, + variant: font3.variant, + // widths of characters + width: {}, + // kernin pairs offsets + kerning: {}, + metrics: metrics(family, { + origin: "top", + fontSize: GlText.baseFontSize, + fontStyle: style5.join(" ") + }) + }; + GlText.fonts[baseString] = this$1$1.font[i2]; + } + } + }); + } + if (newFont || newFontSize) { + this.font.forEach(function(font3, i2) { + var fontString = Font.stringify({ + size: this$1$1.fontSize[i2], + family: font3.family, + stretch: isStretchSupported ? font3.stretch : void 0, + variant: font3.variant, + weight: font3.weight, + style: font3.style + }); + this$1$1.fontAtlas[i2] = this$1$1.shader.atlas[fontString]; + if (!this$1$1.fontAtlas[i2]) { + var metrics2 = font3.metrics; + this$1$1.shader.atlas[fontString] = this$1$1.fontAtlas[i2] = { + fontString, + // even step is better for rendered characters + step: Math.ceil(this$1$1.fontSize[i2] * metrics2.bottom * 0.5) * 2, + em: this$1$1.fontSize[i2], + cols: 0, + rows: 0, + height: 0, + width: 0, + chars: [], + ids: {}, + texture: this$1$1.regl.texture() + }; + } + if (o.text == null) { + o.text = this$1$1.text; + } + }); + } + if (typeof o.text === "string" && o.position && o.position.length > 2) { + var textArray = Array(o.position.length * 0.5); + for (var i = 0; i < textArray.length; i++) { + textArray[i] = o.text; + } + o.text = textArray; + } + var newAtlasChars; + if (o.text != null || newFont) { + this.textOffsets = [0]; + if (Array.isArray(o.text)) { + this.count = o.text[0].length; + this.counts = [this.count]; + for (var i$1 = 1; i$1 < o.text.length; i$1++) { + this.textOffsets[i$1] = this.textOffsets[i$1 - 1] + o.text[i$1 - 1].length; + this.count += o.text[i$1].length; + this.counts.push(o.text[i$1].length); + } + this.text = o.text.join(""); + } else { + this.text = o.text; + this.count = this.text.length; + this.counts = [this.count]; + } + newAtlasChars = []; + this.font.forEach(function(font3, idx) { + GlText.atlasContext.font = font3.baseString; + var atlas3 = this$1$1.fontAtlas[idx]; + for (var i2 = 0; i2 < this$1$1.text.length; i2++) { + var char2 = this$1$1.text.charAt(i2); + if (atlas3.ids[char2] == null) { + atlas3.ids[char2] = atlas3.chars.length; + atlas3.chars.push(char2); + newAtlasChars.push(char2); + } + if (font3.width[char2] == null) { + font3.width[char2] = GlText.atlasContext.measureText(char2).width / GlText.baseFontSize; + if (this$1$1.kerning) { + var pairs = []; + for (var baseChar in font3.width) { + pairs.push(baseChar + char2, char2 + baseChar); + } + extend$1(font3.kerning, kerning(font3.family, { + pairs + })); + } + } + } + }); + } + if (o.position) { + if (o.position.length > 2) { + var flat = !o.position[0].length; + var positionData = pool.mallocFloat(this.count * 2); + for (var i$2 = 0, ptr = 0; i$2 < this.counts.length; i$2++) { + var count2 = this.counts[i$2]; + if (flat) { + for (var j = 0; j < count2; j++) { + positionData[ptr++] = o.position[i$2 * 2]; + positionData[ptr++] = o.position[i$2 * 2 + 1]; + } + } else { + for (var j$1 = 0; j$1 < count2; j$1++) { + positionData[ptr++] = o.position[i$2][0]; + positionData[ptr++] = o.position[i$2][1]; + } + } + } + if (this.position.call) { + this.position({ + type: "float", + data: positionData + }); + } else { + this.position = this.regl.buffer({ + type: "float", + data: positionData + }); + } + pool.freeFloat(positionData); + } else { + if (this.position.destroy) { + this.position.destroy(); + } + this.position = { + constant: o.position + }; + } + } + if (o.text || newFont) { + var charIds = pool.mallocUint8(this.count); + var sizeData = pool.mallocFloat(this.count * 2); + this.textWidth = []; + for (var i$3 = 0, ptr$1 = 0; i$3 < this.counts.length; i$3++) { + var count$1 = this.counts[i$3]; + var font2 = this.font[i$3] || this.font[0]; + var atlas2 = this.fontAtlas[i$3] || this.fontAtlas[0]; + for (var j$2 = 0; j$2 < count$1; j$2++) { + var char = this.text.charAt(ptr$1); + var prevChar = this.text.charAt(ptr$1 - 1); + charIds[ptr$1] = atlas2.ids[char]; + sizeData[ptr$1 * 2] = font2.width[char]; + if (j$2) { + var prevWidth = sizeData[ptr$1 * 2 - 2]; + var currWidth = sizeData[ptr$1 * 2]; + var prevOffset = sizeData[ptr$1 * 2 - 1]; + var offset = prevOffset + prevWidth * 0.5 + currWidth * 0.5; + if (this.kerning) { + var kerning$12 = font2.kerning[prevChar + char]; + if (kerning$12) { + offset += kerning$12 * 1e-3; + } + } + sizeData[ptr$1 * 2 + 1] = offset; + } else { + sizeData[ptr$1 * 2 + 1] = sizeData[ptr$1 * 2] * 0.5; + } + ptr$1++; + } + this.textWidth.push( + !sizeData.length ? 0 : ( + // last offset + half last width + sizeData[ptr$1 * 2 - 2] * 0.5 + sizeData[ptr$1 * 2 - 1] + ) + ); + } + if (!o.align) { + o.align = this.align; + } + this.charBuffer({ data: charIds, type: "uint8", usage: "stream" }); + this.sizeBuffer({ data: sizeData, type: "float", usage: "stream" }); + pool.freeUint8(charIds); + pool.freeFloat(sizeData); + if (newAtlasChars.length) { + this.font.forEach(function(font3, i2) { + var atlas3 = this$1$1.fontAtlas[i2]; + var step = atlas3.step; + var maxCols = Math.floor(GlText.maxAtlasSize / step); + var cols = Math.min(maxCols, atlas3.chars.length); + var rows = Math.ceil(atlas3.chars.length / cols); + var atlasWidth = nextPow2(cols * step); + var atlasHeight = nextPow2(rows * step); + atlas3.width = atlasWidth; + atlas3.height = atlasHeight; + atlas3.rows = rows; + atlas3.cols = cols; + if (!atlas3.em) { + return; + } + atlas3.texture({ + data: fontAtlas({ + canvas: GlText.atlasCanvas, + font: atlas3.fontString, + chars: atlas3.chars, + shape: [atlasWidth, atlasHeight], + step: [step, step] + }) + }); + }); + } + } + if (o.align) { + this.align = o.align; + this.alignOffset = this.textWidth.map(function(textWidth, i2) { + var align3 = !Array.isArray(this$1$1.align) ? this$1$1.align : this$1$1.align.length > 1 ? this$1$1.align[i2] : this$1$1.align[0]; + if (typeof align3 === "number") { + return align3; + } + switch (align3) { + case "right": + case "end": + return -textWidth; + case "center": + case "centre": + case "middle": + return -textWidth * 0.5; + } + return 0; + }); + } + if (this.baseline == null && o.baseline == null) { + o.baseline = 0; + } + if (o.baseline != null) { + this.baseline = o.baseline; + if (!Array.isArray(this.baseline)) { + this.baseline = [this.baseline]; + } + this.baselineOffset = this.baseline.map(function(baseline, i2) { + var m = (this$1$1.font[i2] || this$1$1.font[0]).metrics; + var base = 0; + base += m.bottom * 0.5; + if (typeof baseline === "number") { + base += baseline - m.baseline; + } else { + base += -m[baseline]; + } + base *= -1; + return base; + }); + } + if (o.color != null) { + if (!o.color) { + o.color = "transparent"; + } + if (typeof o.color === "string" || !isNaN(o.color)) { + this.color = rgba$1(o.color, "uint8"); + } else { + var colorData; + if (typeof o.color[0] === "number" && o.color.length > this.counts.length) { + var l = o.color.length; + colorData = pool.mallocUint8(l); + var sub = (o.color.subarray || o.color.slice).bind(o.color); + for (var i$4 = 0; i$4 < l; i$4 += 4) { + colorData.set(rgba$1(sub(i$4, i$4 + 4), "uint8"), i$4); + } + } else { + var l$1 = o.color.length; + colorData = pool.mallocUint8(l$1 * 4); + for (var i$5 = 0; i$5 < l$1; i$5++) { + colorData.set(rgba$1(o.color[i$5] || 0, "uint8"), i$5 * 4); + } + } + this.color = colorData; + } + } + if (o.position || o.text || o.color || o.baseline || o.align || o.font || o.offset || o.opacity) { + var isBatch = this.color.length > 4 || this.baselineOffset.length > 1 || this.align && this.align.length > 1 || this.fontAtlas.length > 1 || this.positionOffset.length > 2; + if (isBatch) { + var length2 = Math.max( + this.position.length * 0.5 || 0, + this.color.length * 0.25 || 0, + this.baselineOffset.length || 0, + this.alignOffset.length || 0, + this.font.length || 0, + this.opacity.length || 0, + this.positionOffset.length * 0.5 || 0 + ); + this.batch = Array(length2); + for (var i$6 = 0; i$6 < this.batch.length; i$6++) { + this.batch[i$6] = { + count: this.counts.length > 1 ? this.counts[i$6] : this.counts[0], + offset: this.textOffsets.length > 1 ? this.textOffsets[i$6] : this.textOffsets[0], + color: !this.color ? [0, 0, 0, 255] : this.color.length <= 4 ? this.color : this.color.subarray(i$6 * 4, i$6 * 4 + 4), + opacity: Array.isArray(this.opacity) ? this.opacity[i$6] : this.opacity, + baseline: this.baselineOffset[i$6] != null ? this.baselineOffset[i$6] : this.baselineOffset[0], + align: !this.align ? 0 : this.alignOffset[i$6] != null ? this.alignOffset[i$6] : this.alignOffset[0], + atlas: this.fontAtlas[i$6] || this.fontAtlas[0], + positionOffset: this.positionOffset.length > 2 ? this.positionOffset.subarray(i$6 * 2, i$6 * 2 + 2) : this.positionOffset + }; + } + } else { + if (this.count) { + this.batch = [{ + count: this.count, + offset: 0, + color: this.color || [0, 0, 0, 255], + opacity: Array.isArray(this.opacity) ? this.opacity[0] : this.opacity, + baseline: this.baselineOffset[0], + align: this.alignOffset ? this.alignOffset[0] : 0, + atlas: this.fontAtlas[0], + positionOffset: this.positionOffset + }]; + } else { + this.batch = []; + } + } + } +}; +GlText.prototype.destroy = function destroy() { +}; +GlText.prototype.kerning = true; +GlText.prototype.position = { constant: new Float32Array(2) }; +GlText.prototype.translate = null; +GlText.prototype.scale = null; +GlText.prototype.font = null; +GlText.prototype.text = ""; +GlText.prototype.positionOffset = [0, 0]; +GlText.prototype.opacity = 1; +GlText.prototype.color = new Uint8Array([0, 0, 0, 255]); +GlText.prototype.alignOffset = [0, 0]; +GlText.maxAtlasSize = 1024; +GlText.atlasCanvas = document.createElement("canvas"); +GlText.atlasContext = GlText.atlasCanvas.getContext("2d", { alpha: false }); +GlText.baseFontSize = 64; +GlText.fonts = {}; +function isRegl(o) { + return typeof o === "function" && o._gl && o.prop && o.texture && o.buffer; +} +var dist = GlText; +var Color$5 = colorExports; +var noop2 = function() { +}; +var show_no_webgl_msg = function showNoWebGlMsg(scene) { + for (var prop in scene) { + if (typeof scene[prop] === "function") scene[prop] = noop2; + } + scene.destroy = function() { + scene.container.parentNode.removeChild(scene.container); + }; + var div = document.createElement("div"); + div.className = "no-webgl"; + div.style.cursor = "pointer"; + div.style.fontSize = "24px"; + div.style.color = Color$5.defaults[0]; + div.style.position = "absolute"; + div.style.left = div.style.top = "0px"; + div.style.width = div.style.height = "100%"; + div.style["background-color"] = Color$5.lightLine; + div.style["z-index"] = 30; + var p = document.createElement("p"); + p.textContent = "WebGL is not supported by your browser - visit https://get.webgl.org for more info"; + p.style.position = "relative"; + p.style.top = "50%"; + p.style.left = "50%"; + p.style.height = "30%"; + p.style.width = "50%"; + p.style.margin = "-15% 0 0 -25%"; + div.appendChild(p); + scene.container.appendChild(div); + scene.container.style.background = "#FFFFFF"; + scene.container.onclick = function() { + window.open("https://get.webgl.org"); + }; + return false; +}; +var showNoWebGlMsg2 = show_no_webgl_msg; +var createRegl = regl_uncheckedExports; +var prepare_regl = function prepareRegl(gd, extensions, reglPrecompiled2) { + var fullLayout = gd._fullLayout; + var success = true; + fullLayout._glcanvas.each(function(d) { + if (d.regl) { + d.regl.preloadCachedCode(reglPrecompiled2); + return; + } + if (d.pick && !fullLayout._has("parcoords")) return; + try { + d.regl = createRegl({ + canvas: this, + attributes: { + antialias: !d.pick, + preserveDrawingBuffer: true + }, + pixelRatio: gd._context.plotGlPixelRatio || index$3.commonjsGlobal.devicePixelRatio, + extensions: extensions || [], + cachedCode: reglPrecompiled2 || {} + }); + } catch (e) { + success = false; + } + if (!d.regl) success = false; + if (success) { + this.addEventListener("webglcontextlost", function(event) { + if (gd && gd.emit) { + gd.emit("plotly_webglcontextlost", { + event, + layer: d.key + }); + } + }, false); + } + }); + if (!success) { + showNoWebGlMsg2({ container: fullLayout._glcontainer.node() }); + } + return success; +}; +var createScatter = bundle; +var createLine = reglLine2d; +var createError = reglError2d; +var Text = dist; +var Lib$8 = libExports; +var selectMode = helpers$B.selectMode; +var prepareRegl2 = prepare_regl; +var subTypes = subtypes$3; +var linkTraces2 = link_traces; +var styleTextSelection = edit_style.styleTextSelection; +var reglPrecompiled = {}; +function getViewport(fullLayout, xaxis, yaxis, plotGlPixelRatio) { + var gs = fullLayout._size; + var width = fullLayout.width * plotGlPixelRatio; + var height = fullLayout.height * plotGlPixelRatio; + var l = gs.l * plotGlPixelRatio; + var b = gs.b * plotGlPixelRatio; + var r = gs.r * plotGlPixelRatio; + var t = gs.t * plotGlPixelRatio; + var w = gs.w * plotGlPixelRatio; + var h = gs.h * plotGlPixelRatio; + return [ + l + xaxis.domain[0] * w, + b + yaxis.domain[0] * h, + width - r - (1 - xaxis.domain[1]) * w, + height - t - (1 - yaxis.domain[1]) * h + ]; +} +var exports$1 = plot$2.exports = function plot3(gd, subplot, cdata) { + if (!cdata.length) return; + var fullLayout = gd._fullLayout; + var scene = subplot._scene; + var xaxis = subplot.xaxis; + var yaxis = subplot.yaxis; + var i, j; + if (!scene) return; + var success = prepareRegl2(gd, ["ANGLE_instanced_arrays", "OES_element_index_uint"], reglPrecompiled); + if (!success) { + scene.init(); + return; + } + var count2 = scene.count; + var regl = fullLayout._glcanvas.data()[0].regl; + linkTraces2(gd, subplot, cdata); + if (scene.dirty) { + if ((scene.line2d || scene.error2d) && !(scene.scatter2d || scene.fill2d || scene.glText)) { + regl.clear({}); + } + if (scene.error2d === true) { + scene.error2d = createError(regl); + } + if (scene.line2d === true) { + scene.line2d = createLine(regl); + } + if (scene.scatter2d === true) { + scene.scatter2d = createScatter(regl); + } + if (scene.fill2d === true) { + scene.fill2d = createLine(regl); + } + if (scene.glText === true) { + scene.glText = new Array(count2); + for (i = 0; i < count2; i++) { + scene.glText[i] = new Text(regl); + } + } + if (scene.glText) { + if (count2 > scene.glText.length) { + var textsToAdd = count2 - scene.glText.length; + for (i = 0; i < textsToAdd; i++) { + scene.glText.push(new Text(regl)); + } + } else if (count2 < scene.glText.length) { + var textsToRemove = scene.glText.length - count2; + var removedTexts = scene.glText.splice(count2, textsToRemove); + removedTexts.forEach(function(text) { + text.destroy(); + }); + } + for (i = 0; i < count2; i++) { + scene.glText[i].update(scene.textOptions[i]); + } + } + if (scene.line2d) { + scene.line2d.update(scene.lineOptions); + scene.lineOptions = scene.lineOptions.map(function(lineOptions) { + if (lineOptions && lineOptions.positions) { + var srcPos = lineOptions.positions; + var firstptdef = 0; + while (firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) { + firstptdef += 2; + } + var lastptdef = srcPos.length - 2; + while (lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) { + lastptdef -= 2; + } + lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2); + } + return lineOptions; + }); + scene.line2d.update(scene.lineOptions); + } + if (scene.error2d) { + var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []); + scene.error2d.update(errorBatch); + } + if (scene.scatter2d) { + scene.scatter2d.update(scene.markerOptions); + } + scene.fillOrder = Lib$8.repeat(null, count2); + if (scene.fill2d) { + scene.fillOptions = scene.fillOptions.map(function(fillOptions, i2) { + var cdscatter = cdata[i2]; + if (!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return; + var cd = cdscatter[0]; + var trace2 = cd.trace; + var stash2 = cd.t; + var lineOptions = scene.lineOptions[i2]; + var last, j2; + var fillData = []; + if (trace2._ownfill) fillData.push(i2); + if (trace2._nexttrace) fillData.push(i2 + 1); + if (fillData.length) scene.fillOrder[i2] = fillData; + var pos = []; + var srcPos = lineOptions && lineOptions.positions || stash2.positions; + var firstptdef, lastptdef; + if (trace2.fill === "tozeroy") { + firstptdef = 0; + while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) { + firstptdef += 2; + } + lastptdef = srcPos.length - 2; + while (lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) { + lastptdef -= 2; + } + if (srcPos[firstptdef + 1] !== 0) { + pos = [srcPos[firstptdef], 0]; + } + pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2)); + if (srcPos[lastptdef + 1] !== 0) { + pos = pos.concat([srcPos[lastptdef], 0]); + } + } else if (trace2.fill === "tozerox") { + firstptdef = 0; + while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) { + firstptdef += 2; + } + lastptdef = srcPos.length - 2; + while (lastptdef > firstptdef && isNaN(srcPos[lastptdef])) { + lastptdef -= 2; + } + if (srcPos[firstptdef] !== 0) { + pos = [0, srcPos[firstptdef + 1]]; + } + pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2)); + if (srcPos[lastptdef] !== 0) { + pos = pos.concat([0, srcPos[lastptdef + 1]]); + } + } else if (trace2.fill === "toself" || trace2.fill === "tonext") { + pos = []; + last = 0; + fillOptions.splitNull = true; + for (j2 = 0; j2 < srcPos.length; j2 += 2) { + if (isNaN(srcPos[j2]) || isNaN(srcPos[j2 + 1])) { + pos = pos.concat(srcPos.slice(last, j2)); + pos.push(srcPos[last], srcPos[last + 1]); + pos.push(null, null); + last = j2 + 2; + } + } + pos = pos.concat(srcPos.slice(last)); + if (last) { + pos.push(srcPos[last], srcPos[last + 1]); + } + } else { + var nextTrace = trace2._nexttrace; + if (nextTrace) { + var nextOptions = scene.lineOptions[i2 + 1]; + if (nextOptions) { + var nextPos = nextOptions.positions; + if (trace2.fill === "tonexty") { + pos = srcPos.slice(); + for (i2 = Math.floor(nextPos.length / 2); i2--; ) { + var xx = nextPos[i2 * 2]; + var yy = nextPos[i2 * 2 + 1]; + if (isNaN(xx) || isNaN(yy)) continue; + pos.push(xx, yy); + } + fillOptions.fill = nextTrace.fillcolor; + } + } + } + } + if (trace2._prevtrace && trace2._prevtrace.fill === "tonext") { + var prevLinePos = scene.lineOptions[i2 - 1].positions; + var offset = pos.length / 2; + last = offset; + var hole = [last]; + for (j2 = 0; j2 < prevLinePos.length; j2 += 2) { + if (isNaN(prevLinePos[j2]) || isNaN(prevLinePos[j2 + 1])) { + hole.push(j2 / 2 + offset + 1); + last = j2 + 2; + } + } + pos = pos.concat(prevLinePos); + fillOptions.hole = hole; + } + fillOptions.fillmode = trace2.fill; + fillOptions.opacity = trace2.opacity; + fillOptions.positions = pos; + return fillOptions; + }); + scene.fill2d.update(scene.fillOptions); + } + } + var dragmode = fullLayout.dragmode; + var isSelectMode = selectMode(dragmode); + var clickSelectEnabled = fullLayout.clickmode.indexOf("select") > -1; + for (i = 0; i < count2; i++) { + var cd0 = cdata[i][0]; + var trace = cd0.trace; + var stash = cd0.t; + var index2 = stash.index; + var len = trace._length; + var x = stash.x; + var y = stash.y; + if (trace.selectedpoints || isSelectMode || clickSelectEnabled) { + if (!isSelectMode) isSelectMode = true; + if (trace.selectedpoints) { + var selPts = scene.selectBatch[index2] = Lib$8.selIndices2selPoints(trace); + var selDict = {}; + for (j = 0; j < selPts.length; j++) { + selDict[selPts[j]] = 1; + } + var unselPts = []; + for (j = 0; j < len; j++) { + if (!selDict[j]) unselPts.push(j); + } + scene.unselectBatch[index2] = unselPts; + } + var xpx = stash.xpx = new Array(len); + var ypx = stash.ypx = new Array(len); + for (j = 0; j < len; j++) { + xpx[j] = xaxis.c2p(x[j]); + ypx[j] = yaxis.c2p(y[j]); + } + } else { + stash.xpx = stash.ypx = null; + } + } + if (isSelectMode) { + if (!scene.select2d) { + scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl); + } + if (scene.scatter2d) { + var unselOpts = new Array(count2); + for (i = 0; i < count2; i++) { + unselOpts[i] = scene.selectBatch[i].length || scene.unselectBatch[i].length ? scene.markerUnselectedOptions[i] : {}; + } + scene.scatter2d.update(unselOpts); + } + if (scene.select2d) { + scene.select2d.update(scene.markerOptions); + scene.select2d.update(scene.markerSelectedOptions); + } + if (scene.glText) { + cdata.forEach(function(cdscatter) { + var trace2 = ((cdscatter || [])[0] || {}).trace || {}; + if (subTypes.hasText(trace2)) { + styleTextSelection(cdscatter); + } + }); + } + } else { + if (scene.scatter2d) { + scene.scatter2d.update(scene.markerOptions); + } + } + var vpRange0 = { + viewport: getViewport(fullLayout, xaxis, yaxis, gd._context.plotGlPixelRatio), + // TODO do we need those fallbacks? + range: [ + (xaxis._rl || xaxis.range)[0], + (yaxis._rl || yaxis.range)[0], + (xaxis._rl || xaxis.range)[1], + (yaxis._rl || yaxis.range)[1] + ] + }; + var vpRange = Lib$8.repeat(vpRange0, scene.count); + if (scene.fill2d) { + scene.fill2d.update(vpRange); + } + if (scene.line2d) { + scene.line2d.update(vpRange); + } + if (scene.error2d) { + scene.error2d.update(vpRange.concat(vpRange)); + } + if (scene.scatter2d) { + scene.scatter2d.update(vpRange); + } + if (scene.select2d) { + scene.select2d.update(vpRange); + } + if (scene.glText) { + scene.glText.forEach(function(text) { + text.update(vpRange0); + }); + } +}; +exports$1.reglPrecompiled = reglPrecompiled; +var plotExports = plot$2.exports; +var index$2 = base_index; +index$2.plot = plotExports; +var scattergl$2 = index$2; +var scattergl = scattergl$2; +const scattergl$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(scattergl); +var base_plot = {}; +(function(exports2) { + var plots2 = plotsExports; + exports2.name = "treemap"; + exports2.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { + plots2.plotBasePlot(exports2.name, gd, traces, transitionOpts, makeOnCompleteCallback); + }; + exports2.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { + plots2.cleanBasePlot(exports2.name, newFullData, newFullLayout, oldFullData, oldFullLayout); + }; +})(base_plot); +var constants$6 = { + CLICK_TRANSITION_TIME: 750, + CLICK_TRANSITION_EASING: "linear", + eventDataKeys: [ + // string + "currentPath", + "root", + "entry", + // no need to add 'parent' here + // percentages i.e. ratios + "percentRoot", + "percentEntry", + "percentParent" + ] +}; +var baseAttrs = attributes$O; +var hovertemplateAttrs$1 = template_attributes.hovertemplateAttrs; +var texttemplateAttrs$1 = template_attributes.texttemplateAttrs; +var colorScaleAttrs$1 = attributes$I; +var domainAttrs$1 = domain.attributes; +var pieAttrs$1 = attributes$8; +var constants$5 = constants$6; +var extendFlat$1 = extend$5.extendFlat; +var pattern$1 = attributes$M.pattern; +var attributes$2 = { + labels: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the labels of each of the sectors." + ].join(" ") + }, + parents: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the parent sectors for each of the sectors.", + "Empty string items '' are understood to reference", + "the root node in the hierarchy.", + 'If `ids` is filled, `parents` items are understood to be "ids" themselves.', + "When `ids` is not set, plotly attempts to find matching items in `labels`,", + "but beware they must be unique." + ].join(" ") + }, + values: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the values associated with each of the sectors.", + "Use with `branchvalues` to determine how the values are summed." + ].join(" ") + }, + branchvalues: { + valType: "enumerated", + values: ["remainder", "total"], + dflt: "remainder", + editType: "calc", + description: [ + "Determines how the items in `values` are summed.", + "When set to *total*, items in `values` are taken to be value of all its descendants.", + "When set to *remainder*, items in `values` corresponding to the root and the branches sectors", + "are taken to be the extra part not part of the sum of the values at their leaves." + ].join(" ") + }, + count: { + valType: "flaglist", + flags: [ + "branches", + "leaves" + ], + dflt: "leaves", + editType: "calc", + description: [ + "Determines default for `values` when it is not provided,", + "by inferring a 1 for each of the *leaves* and/or *branches*, otherwise 0." + ].join(" ") + }, + level: { + valType: "any", + editType: "plot", + anim: true, + description: [ + "Sets the level from which this trace hierarchy is rendered.", + "Set `level` to `''` to start from the root node in the hierarchy.", + 'Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching', + "item in `labels`." + ].join(" ") + }, + maxdepth: { + valType: "integer", + editType: "plot", + dflt: -1, + description: [ + "Sets the number of rendered sectors from any given `level`.", + "Set `maxdepth` to *-1* to render all the levels in the hierarchy." + ].join(" ") + }, + marker: extendFlat$1( + { + colors: { + valType: "data_array", + editType: "calc", + description: [ + "Sets the color of each sector of this trace.", + "If not specified, the default trace color set is used", + "to pick the sector colors." + ].join(" ") + }, + // colorinheritance: { + // valType: 'enumerated', + // values: ['per-branch', 'per-label', false] + // }, + line: { + color: extendFlat$1({}, pieAttrs$1.marker.line.color, { + dflt: null, + description: [ + "Sets the color of the line enclosing each sector.", + "Defaults to the `paper_bgcolor` value." + ].join(" ") + }), + width: extendFlat$1({}, pieAttrs$1.marker.line.width, { dflt: 1 }), + editType: "calc" + }, + pattern: pattern$1, + editType: "calc" + }, + colorScaleAttrs$1("marker", { + colorAttr: "colors", + anim: false + // TODO: set to anim: true? + }) + ), + text: pieAttrs$1.text, + textinfo: { + valType: "flaglist", + flags: [ + "label", + "text", + "value", + "current path", + "percent root", + "percent entry", + "percent parent" + ], + extras: ["none"], + editType: "plot", + description: [ + "Determines which trace information appear on the graph." + ].join(" ") + }, + // TODO: incorporate `label` and `value` in the eventData + texttemplate: texttemplateAttrs$1({ editType: "plot" }, { + keys: constants$5.eventDataKeys.concat(["label", "value"]) + }), + hovertext: pieAttrs$1.hovertext, + hoverinfo: extendFlat$1({}, baseAttrs.hoverinfo, { + flags: [ + "label", + "text", + "value", + "name", + "current path", + "percent root", + "percent entry", + "percent parent" + ], + dflt: "label+text+value+name" + }), + hovertemplate: hovertemplateAttrs$1({}, { + keys: constants$5.eventDataKeys + }), + textfont: pieAttrs$1.textfont, + insidetextorientation: pieAttrs$1.insidetextorientation, + insidetextfont: pieAttrs$1.insidetextfont, + outsidetextfont: extendFlat$1({}, pieAttrs$1.outsidetextfont, { + description: [ + "Sets the font used for `textinfo` lying outside the sector.", + "This option refers to the root of the hierarchy", + "presented at the center of a sunburst graph.", + "Please note that if a hierarchy has multiple root nodes,", + "this option won't have any effect and `insidetextfont` would be used." + ].join(" ") + }), + sort: pieAttrs$1.sort, + root: { + color: { + valType: "color", + editType: "calc", + dflt: "rgba(0,0,0,0)", + description: [ + "sets the color of the root node for a sunburst/treemap/icicle trace.", + "this has no effect when a colorscale is used to set the markers." + ].join(" ") + }, + editType: "calc" + }, + domain: domainAttrs$1({ name: "sunburst", trace: true, editType: "calc" }) +}; +var constants$4 = { + CLICK_TRANSITION_TIME: 750, + CLICK_TRANSITION_EASING: "poly", + eventDataKeys: [ + // string + "currentPath", + "root", + "entry", + // no need to add 'parent' here + // percentages i.e. ratios + "percentRoot", + "percentEntry", + "percentParent" + ], + gapWithPathbar: 1 + // i.e. one pixel +}; +var hovertemplateAttrs = template_attributes.hovertemplateAttrs; +var texttemplateAttrs = template_attributes.texttemplateAttrs; +var colorScaleAttrs2 = attributes$I; +var domainAttrs = domain.attributes; +var pieAttrs = attributes$8; +var sunburstAttrs = attributes$2; +var constants$3 = constants$4; +var extendFlat = extend$5.extendFlat; +var pattern = attributes$M.pattern; +var attributes$1 = { + labels: sunburstAttrs.labels, + parents: sunburstAttrs.parents, + values: sunburstAttrs.values, + branchvalues: sunburstAttrs.branchvalues, + count: sunburstAttrs.count, + level: sunburstAttrs.level, + maxdepth: sunburstAttrs.maxdepth, + tiling: { + packing: { + valType: "enumerated", + values: [ + "squarify", + "binary", + "dice", + "slice", + "slice-dice", + "dice-slice" + ], + dflt: "squarify", + editType: "plot", + description: [ + "Determines d3 treemap solver.", + "For more info please refer to https://github.com/d3/d3-hierarchy#treemap-tiling" + ].join(" ") + }, + squarifyratio: { + valType: "number", + min: 1, + dflt: 1, + editType: "plot", + description: [ + "When using *squarify* `packing` algorithm, according to https://github.com/d3/d3-hierarchy/blob/v3.1.1/README.md#squarify_ratio", + "this option specifies the desired aspect ratio of the generated rectangles.", + "The ratio must be specified as a number greater than or equal to one.", + "Note that the orientation of the generated rectangles (tall or wide)", + "is not implied by the ratio; for example, a ratio of two will attempt", + "to produce a mixture of rectangles whose width:height ratio is either 2:1 or 1:2.", + "When using *squarify*, unlike d3 which uses the Golden Ratio i.e. 1.618034,", + "Plotly applies 1 to increase squares in treemap layouts." + ].join(" ") + }, + flip: { + valType: "flaglist", + flags: [ + "x", + "y" + ], + dflt: "", + editType: "plot", + description: [ + "Determines if the positions obtained from solver are flipped on each axis." + ].join(" ") + }, + pad: { + valType: "number", + min: 0, + dflt: 3, + editType: "plot", + description: [ + "Sets the inner padding (in px)." + ].join(" ") + }, + editType: "calc" + }, + marker: extendFlat( + { + pad: { + t: { + valType: "number", + min: 0, + editType: "plot", + description: [ + "Sets the padding form the top (in px)." + ].join(" ") + }, + l: { + valType: "number", + min: 0, + editType: "plot", + description: [ + "Sets the padding form the left (in px)." + ].join(" ") + }, + r: { + valType: "number", + min: 0, + editType: "plot", + description: [ + "Sets the padding form the right (in px)." + ].join(" ") + }, + b: { + valType: "number", + min: 0, + editType: "plot", + description: [ + "Sets the padding form the bottom (in px)." + ].join(" ") + }, + editType: "calc" + }, + colors: sunburstAttrs.marker.colors, + pattern, + depthfade: { + valType: "enumerated", + values: [true, false, "reversed"], + editType: "style", + description: [ + "Determines if the sector colors are faded towards", + "the background from the leaves up to the headers.", + "This option is unavailable when a `colorscale` is present,", + "defaults to false when `marker.colors` is set,", + "but otherwise defaults to true.", + "When set to *reversed*, the fading direction is inverted,", + "that is the top elements within hierarchy are drawn with fully saturated colors", + "while the leaves are faded towards the background color." + ].join(" ") + }, + line: sunburstAttrs.marker.line, + cornerradius: { + valType: "number", + min: 0, + dflt: 0, + editType: "plot", + description: [ + "Sets the maximum rounding of corners (in px)." + ].join(" ") + }, + editType: "calc" + }, + colorScaleAttrs2("marker", { + colorAttr: "colors", + anim: false + // TODO: set to anim: true? + }) + ), + pathbar: { + visible: { + valType: "boolean", + dflt: true, + editType: "plot", + description: [ + "Determines if the path bar is drawn", + "i.e. outside the trace `domain` and", + "with one pixel gap." + ].join(" ") + }, + side: { + valType: "enumerated", + values: [ + "top", + "bottom" + ], + dflt: "top", + editType: "plot", + description: [ + "Determines on which side of the the treemap the", + "`pathbar` should be presented." + ].join(" ") + }, + edgeshape: { + valType: "enumerated", + values: [ + ">", + "<", + "|", + "/", + "\\" + ], + dflt: ">", + editType: "plot", + description: [ + "Determines which shape is used for edges between `barpath` labels." + ].join(" ") + }, + thickness: { + valType: "number", + min: 12, + editType: "plot", + description: [ + "Sets the thickness of `pathbar` (in px). If not specified the `pathbar.textfont.size` is used", + "with 3 pixles extra padding on each side." + ].join(" ") + }, + textfont: extendFlat({}, pieAttrs.textfont, { + description: "Sets the font used inside `pathbar`." + }), + editType: "calc" + }, + text: pieAttrs.text, + textinfo: sunburstAttrs.textinfo, + // TODO: incorporate `label` and `value` in the eventData + texttemplate: texttemplateAttrs({ editType: "plot" }, { + keys: constants$3.eventDataKeys.concat(["label", "value"]) + }), + hovertext: pieAttrs.hovertext, + hoverinfo: sunburstAttrs.hoverinfo, + hovertemplate: hovertemplateAttrs({}, { + keys: constants$3.eventDataKeys + }), + textfont: pieAttrs.textfont, + insidetextfont: pieAttrs.insidetextfont, + outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, { + description: [ + "Sets the font used for `textinfo` lying outside the sector.", + "This option refers to the root of the hierarchy", + "presented on top left corner of a treemap graph.", + "Please note that if a hierarchy has multiple root nodes,", + "this option won't have any effect and `insidetextfont` would be used." + ].join(" ") + }), + textposition: { + valType: "enumerated", + values: [ + "top left", + "top center", + "top right", + "middle left", + "middle center", + "middle right", + "bottom left", + "bottom center", + "bottom right" + ], + dflt: "top left", + editType: "plot", + description: [ + "Sets the positions of the `text` elements." + ].join(" ") + }, + sort: pieAttrs.sort, + root: sunburstAttrs.root, + domain: domainAttrs({ name: "treemap", trace: true, editType: "calc" }) +}; +var layout_attributes = { + treemapcolorway: { + valType: "colorlist", + editType: "calc", + description: [ + "Sets the default treemap slice colors. Defaults to the main", + "`colorway` used for trace colors. If you specify a new", + "list here it can still be extended with lighter and darker", + "colors, see `extendtreemapcolors`." + ].join(" ") + }, + extendtreemapcolors: { + valType: "boolean", + dflt: true, + editType: "calc", + description: [ + "If `true`, the treemap slice colors (whether given by `treemapcolorway` or", + "inherited from `colorway`) will be extended to three times its", + "original length by first repeating every color 20% lighter then", + "each color 20% darker. This is intended to reduce the likelihood", + "of reusing the same color when you have many slices, but you can", + "set `false` to disable.", + "Colors provided in the trace, using `marker.colors`, are never", + "extended." + ].join(" ") + } +}; +var Lib$7 = libExports; +var attributes = attributes$1; +var Color$4 = colorExports; +var handleDomainDefaults = domain.defaults; +var handleText = defaults$6.handleText; +var TEXTPAD$1 = constants$f.TEXTPAD; +var handleMarkerDefaults = defaults$4.handleMarkerDefaults; +var Colorscale = colorscale; +var hasColorscale = Colorscale.hasColorscale; +var colorscaleDefaults = Colorscale.handleDefaults; +var defaults = function supplyDefaults7(traceIn, traceOut, defaultColor, layout) { + function coerce2(attr, dflt) { + return Lib$7.coerce(traceIn, traceOut, attributes, attr, dflt); + } + var labels = coerce2("labels"); + var parents = coerce2("parents"); + if (!labels || !labels.length || !parents || !parents.length) { + traceOut.visible = false; + return; + } + var vals = coerce2("values"); + if (vals && vals.length) { + coerce2("branchvalues"); + } else { + coerce2("count"); + } + coerce2("level"); + coerce2("maxdepth"); + var packing = coerce2("tiling.packing"); + if (packing === "squarify") { + coerce2("tiling.squarifyratio"); + } + coerce2("tiling.flip"); + coerce2("tiling.pad"); + var text = coerce2("text"); + coerce2("texttemplate"); + if (!traceOut.texttemplate) coerce2("textinfo", Lib$7.isArrayOrTypedArray(text) ? "text+label" : "label"); + coerce2("hovertext"); + coerce2("hovertemplate"); + var hasPathbar = coerce2("pathbar.visible"); + var textposition = "auto"; + handleText(traceIn, traceOut, layout, coerce2, textposition, { + hasPathbar, + moduleHasSelected: false, + moduleHasUnselected: false, + moduleHasConstrain: false, + moduleHasCliponaxis: false, + moduleHasTextangle: false, + moduleHasInsideanchor: false + }); + coerce2("textposition"); + var bottomText = traceOut.textposition.indexOf("bottom") !== -1; + handleMarkerDefaults(traceIn, traceOut, layout, coerce2); + var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, "marker", "colors") || (traceIn.marker || {}).coloraxis; + if (withColorscale) { + colorscaleDefaults(traceIn, traceOut, layout, coerce2, { prefix: "marker.", cLetter: "c" }); + } else { + coerce2("marker.depthfade", !(traceOut.marker.colors || []).length); + } + var headerSize = traceOut.textfont.size * 2; + coerce2("marker.pad.t", bottomText ? headerSize / 4 : headerSize); + coerce2("marker.pad.l", headerSize / 4); + coerce2("marker.pad.r", headerSize / 4); + coerce2("marker.pad.b", bottomText ? headerSize : headerSize / 4); + coerce2("marker.cornerradius"); + traceOut._hovered = { + marker: { + line: { + width: 2, + color: Color$4.contrast(layout.paper_bgcolor) + } + } + }; + if (hasPathbar) { + coerce2("pathbar.thickness", traceOut.pathbar.textfont.size + 2 * TEXTPAD$1); + coerce2("pathbar.side"); + coerce2("pathbar.edgeshape"); + } + coerce2("sort"); + coerce2("root.color"); + handleDomainDefaults(traceOut, layout, coerce2); + traceOut._length = null; +}; +var Lib$6 = libExports; +var layoutAttributes = layout_attributes; +var layout_defaults = function supplyLayoutDefaults9(layoutIn, layoutOut) { + function coerce2(attr, dflt) { + return Lib$6.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt); + } + coerce2("treemapcolorway", layoutOut.colorway); + coerce2("extendtreemapcolors"); +}; +var calc$2 = {}; +var calc$1 = {}; +function defaultSeparation$1(a, b) { + return a.parent === b.parent ? 1 : 2; +} +function meanX(children) { + return children.reduce(meanXReduce, 0) / children.length; +} +function meanXReduce(x, c) { + return x + c.x; +} +function maxY(children) { + return 1 + children.reduce(maxYReduce, 0); +} +function maxYReduce(y, c) { + return Math.max(y, c.y); +} +function leafLeft(node) { + var children; + while (children = node.children) node = children[0]; + return node; +} +function leafRight(node) { + var children; + while (children = node.children) node = children[children.length - 1]; + return node; +} +function cluster2() { + var separation = defaultSeparation$1, dx = 1, dy = 1, nodeSize = false; + function cluster3(root) { + var previousNode, x = 0; + root.eachAfter(function(node) { + var children = node.children; + if (children) { + node.x = meanX(children); + node.y = maxY(children); + } else { + node.x = previousNode ? x += separation(node, previousNode) : 0; + node.y = 0; + previousNode = node; + } + }); + var left = leafLeft(root), right = leafRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; + return root.eachAfter(nodeSize ? function(node) { + node.x = (node.x - root.x) * dx; + node.y = (root.y - node.y) * dy; + } : function(node) { + node.x = (node.x - x0) / (x1 - x0) * dx; + node.y = (1 - (root.y ? node.y / root.y : 1)) * dy; + }); + } + cluster3.separation = function(x) { + return arguments.length ? (separation = x, cluster3) : separation; + }; + cluster3.size = function(x) { + return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster3) : nodeSize ? null : [dx, dy]; + }; + cluster3.nodeSize = function(x) { + return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster3) : nodeSize ? [dx, dy] : null; + }; + return cluster3; +} +function count(node) { + var sum = 0, children = node.children, i = children && children.length; + if (!i) sum = 1; + else while (--i >= 0) sum += children[i].value; + node.value = sum; +} +function node_count() { + return this.eachAfter(count); +} +function node_each(callback) { + var node = this, current, next = [node], children, i, n; + do { + current = next.reverse(), next = []; + while (node = current.pop()) { + callback(node), children = node.children; + if (children) for (i = 0, n = children.length; i < n; ++i) { + next.push(children[i]); + } + } + } while (next.length); + return this; +} +function node_eachBefore(callback) { + var node = this, nodes = [node], children, i; + while (node = nodes.pop()) { + callback(node), children = node.children; + if (children) for (i = children.length - 1; i >= 0; --i) { + nodes.push(children[i]); + } + } + return this; +} +function node_eachAfter(callback) { + var node = this, nodes = [node], next = [], children, i, n; + while (node = nodes.pop()) { + next.push(node), children = node.children; + if (children) for (i = 0, n = children.length; i < n; ++i) { + nodes.push(children[i]); + } + } + while (node = next.pop()) { + callback(node); + } + return this; +} +function node_sum(value2) { + return this.eachAfter(function(node) { + var sum = +value2(node.data) || 0, children = node.children, i = children && children.length; + while (--i >= 0) sum += children[i].value; + node.value = sum; + }); +} +function node_sort(compare) { + return this.eachBefore(function(node) { + if (node.children) { + node.children.sort(compare); + } + }); +} +function node_path(end) { + var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start]; + while (start !== ancestor) { + start = start.parent; + nodes.push(start); + } + var k = nodes.length; + while (end !== ancestor) { + nodes.splice(k, 0, end); + end = end.parent; + } + return nodes; +} +function leastCommonAncestor(a, b) { + if (a === b) return a; + var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null; + a = aNodes.pop(); + b = bNodes.pop(); + while (a === b) { + c = a; + a = aNodes.pop(); + b = bNodes.pop(); + } + return c; +} +function node_ancestors() { + var node = this, nodes = [node]; + while (node = node.parent) { + nodes.push(node); + } + return nodes; +} +function node_descendants() { + var nodes = []; + this.each(function(node) { + nodes.push(node); + }); + return nodes; +} +function node_leaves() { + var leaves = []; + this.eachBefore(function(node) { + if (!node.children) { + leaves.push(node); + } + }); + return leaves; +} +function node_links() { + var root = this, links = []; + root.each(function(node) { + if (node !== root) { + links.push({ source: node.parent, target: node }); + } + }); + return links; +} +function hierarchy(data, children) { + var root = new Node$1(data), valued = +data.value && (root.value = data.value), node, nodes = [root], child, childs, i, n; + if (children == null) children = defaultChildren; + while (node = nodes.pop()) { + if (valued) node.value = +node.data.value; + if ((childs = children(node.data)) && (n = childs.length)) { + node.children = new Array(n); + for (i = n - 1; i >= 0; --i) { + nodes.push(child = node.children[i] = new Node$1(childs[i])); + child.parent = node; + child.depth = node.depth + 1; + } + } + } + return root.eachBefore(computeHeight); +} +function node_copy() { + return hierarchy(this).eachBefore(copyData); +} +function defaultChildren(d) { + return d.children; +} +function copyData(node) { + node.data = node.data.data; +} +function computeHeight(node) { + var height = 0; + do + node.height = height; + while ((node = node.parent) && node.height < ++height); +} +function Node$1(data) { + this.data = data; + this.depth = this.height = 0; + this.parent = null; +} +Node$1.prototype = hierarchy.prototype = { + constructor: Node$1, + count: node_count, + each: node_each, + eachAfter: node_eachAfter, + eachBefore: node_eachBefore, + sum: node_sum, + sort: node_sort, + path: node_path, + ancestors: node_ancestors, + descendants: node_descendants, + leaves: node_leaves, + links: node_links, + copy: node_copy +}; +var slice = Array.prototype.slice; +function shuffle(array2) { + var m = array2.length, t, i; + while (m) { + i = Math.random() * m-- | 0; + t = array2[m]; + array2[m] = array2[i]; + array2[i] = t; + } + return array2; +} +function enclose(circles) { + var i = 0, n = (circles = shuffle(slice.call(circles))).length, B2 = [], p, e; + while (i < n) { + p = circles[i]; + if (e && enclosesWeak(e, p)) ++i; + else e = encloseBasis(B2 = extendBasis(B2, p)), i = 0; + } + return e; +} +function extendBasis(B2, p) { + var i, j; + if (enclosesWeakAll(p, B2)) return [p]; + for (i = 0; i < B2.length; ++i) { + if (enclosesNot(p, B2[i]) && enclosesWeakAll(encloseBasis2(B2[i], p), B2)) { + return [B2[i], p]; + } + } + for (i = 0; i < B2.length - 1; ++i) { + for (j = i + 1; j < B2.length; ++j) { + if (enclosesNot(encloseBasis2(B2[i], B2[j]), p) && enclosesNot(encloseBasis2(B2[i], p), B2[j]) && enclosesNot(encloseBasis2(B2[j], p), B2[i]) && enclosesWeakAll(encloseBasis3(B2[i], B2[j], p), B2)) { + return [B2[i], B2[j], p]; + } + } + } + throw new Error(); +} +function enclosesNot(a, b) { + var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y; + return dr < 0 || dr * dr < dx * dx + dy * dy; +} +function enclosesWeak(a, b) { + var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y; + return dr > 0 && dr * dr > dx * dx + dy * dy; +} +function enclosesWeakAll(a, B2) { + for (var i = 0; i < B2.length; ++i) { + if (!enclosesWeak(a, B2[i])) { + return false; + } + } + return true; +} +function encloseBasis(B2) { + switch (B2.length) { + case 1: + return encloseBasis1(B2[0]); + case 2: + return encloseBasis2(B2[0], B2[1]); + case 3: + return encloseBasis3(B2[0], B2[1], B2[2]); + } +} +function encloseBasis1(a) { + return { + x: a.x, + y: a.y, + r: a.r + }; +} +function encloseBasis2(a, b) { + var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1, l = Math.sqrt(x21 * x21 + y21 * y21); + return { + x: (x1 + x2 + x21 / l * r21) / 2, + y: (y1 + y2 + y21 / l * r21) / 2, + r: (l + r1 + r2) / 2 + }; +} +function encloseBasis3(a, b, c) { + var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x3 = c.x, y3 = c.y, r3 = c.r, a2 = x1 - x2, a3 = x1 - x3, b2 = y1 - y2, b3 = y1 - y3, c2 = r2 - r1, c3 = r3 - r1, d1 = x1 * x1 + y1 * y1 - r1 * r1, d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2, d32 = d1 - x3 * x3 - y3 * y3 + r3 * r3, ab2 = a3 * b2 - a2 * b3, xa = (b2 * d32 - b3 * d2) / (ab2 * 2) - x1, xb = (b3 * c2 - b2 * c3) / ab2, ya = (a3 * d2 - a2 * d32) / (ab2 * 2) - y1, yb = (a2 * c3 - a3 * c2) / ab2, A2 = xb * xb + yb * yb - 1, B2 = 2 * (r1 + xa * xb + ya * yb), C2 = xa * xa + ya * ya - r1 * r1, r = -(A2 ? (B2 + Math.sqrt(B2 * B2 - 4 * A2 * C2)) / (2 * A2) : C2 / B2); + return { + x: x1 + xa + xb * r, + y: y1 + ya + yb * r, + r + }; +} +function place(b, a, c) { + var dx = b.x - a.x, x, a2, dy = b.y - a.y, y, b2, d2 = dx * dx + dy * dy; + if (d2) { + a2 = a.r + c.r, a2 *= a2; + b2 = b.r + c.r, b2 *= b2; + if (a2 > b2) { + x = (d2 + b2 - a2) / (2 * d2); + y = Math.sqrt(Math.max(0, b2 / d2 - x * x)); + c.x = b.x - x * dx - y * dy; + c.y = b.y - x * dy + y * dx; + } else { + x = (d2 + a2 - b2) / (2 * d2); + y = Math.sqrt(Math.max(0, a2 / d2 - x * x)); + c.x = a.x + x * dx - y * dy; + c.y = a.y + x * dy + y * dx; + } + } else { + c.x = a.x + c.r; + c.y = a.y; + } +} +function intersects(a, b) { + var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y; + return dr > 0 && dr * dr > dx * dx + dy * dy; +} +function score(node) { + var a = node._, b = node.next._, ab2 = a.r + b.r, dx = (a.x * b.r + b.x * a.r) / ab2, dy = (a.y * b.r + b.y * a.r) / ab2; + return dx * dx + dy * dy; +} +function Node(circle) { + this._ = circle; + this.next = null; + this.previous = null; +} +function packEnclose(circles) { + if (!(n = circles.length)) return 0; + var a, b, c, n, aa, ca, i, j, k, sj, sk; + a = circles[0], a.x = 0, a.y = 0; + if (!(n > 1)) return a.r; + b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0; + if (!(n > 2)) return a.r + b.r; + place(b, a, c = circles[2]); + a = new Node(a), b = new Node(b), c = new Node(c); + a.next = c.previous = b; + b.next = a.previous = c; + c.next = b.previous = a; + pack: for (i = 3; i < n; ++i) { + place(a._, b._, c = circles[i]), c = new Node(c); + j = b.next, k = a.previous, sj = b._.r, sk = a._.r; + do { + if (sj <= sk) { + if (intersects(j._, c._)) { + b = j, a.next = b, b.previous = a, --i; + continue pack; + } + sj += j._.r, j = j.next; + } else { + if (intersects(k._, c._)) { + a = k, a.next = b, b.previous = a, --i; + continue pack; + } + sk += k._.r, k = k.previous; + } + } while (j !== k.next); + c.previous = a, c.next = b, a.next = b.previous = b = c; + aa = score(a); + while ((c = c.next) !== b) { + if ((ca = score(c)) < aa) { + a = c, aa = ca; + } + } + b = a.next; + } + a = [b._], c = b; + while ((c = c.next) !== b) a.push(c._); + c = enclose(a); + for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y; + return c.r; +} +function siblings(circles) { + packEnclose(circles); + return circles; +} +function optional(f) { + return f == null ? null : required(f); +} +function required(f) { + if (typeof f !== "function") throw new Error(); + return f; +} +function constantZero() { + return 0; +} +function constant$1(x) { + return function() { + return x; + }; +} +function defaultRadius(d) { + return Math.sqrt(d.value); +} +function index$1() { + var radius = null, dx = 1, dy = 1, padding = constantZero; + function pack(root) { + root.x = dx / 2, root.y = dy / 2; + if (radius) { + root.eachBefore(radiusLeaf(radius)).eachAfter(packChildren(padding, 0.5)).eachBefore(translateChild(1)); + } else { + root.eachBefore(radiusLeaf(defaultRadius)).eachAfter(packChildren(constantZero, 1)).eachAfter(packChildren(padding, root.r / Math.min(dx, dy))).eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r))); + } + return root; + } + pack.radius = function(x) { + return arguments.length ? (radius = optional(x), pack) : radius; + }; + pack.size = function(x) { + return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy]; + }; + pack.padding = function(x) { + return arguments.length ? (padding = typeof x === "function" ? x : constant$1(+x), pack) : padding; + }; + return pack; +} +function radiusLeaf(radius) { + return function(node) { + if (!node.children) { + node.r = Math.max(0, +radius(node) || 0); + } + }; +} +function packChildren(padding, k) { + return function(node) { + if (children = node.children) { + var children, i, n = children.length, r = padding(node) * k || 0, e; + if (r) for (i = 0; i < n; ++i) children[i].r += r; + e = packEnclose(children); + if (r) for (i = 0; i < n; ++i) children[i].r -= r; + node.r = e + r; + } + }; +} +function translateChild(k) { + return function(node) { + var parent = node.parent; + node.r *= k; + if (parent) { + node.x = parent.x + k * node.x; + node.y = parent.y + k * node.y; + } + }; +} +function roundNode(node) { + node.x0 = Math.round(node.x0); + node.y0 = Math.round(node.y0); + node.x1 = Math.round(node.x1); + node.y1 = Math.round(node.y1); +} +function treemapDice(parent, x0, y0, x1, y1) { + var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value; + while (++i < n) { + node = nodes[i], node.y0 = y0, node.y1 = y1; + node.x0 = x0, node.x1 = x0 += node.value * k; + } +} +function partition$3() { + var dx = 1, dy = 1, padding = 0, round2 = false; + function partition3(root) { + var n = root.height + 1; + root.x0 = root.y0 = padding; + root.x1 = dx; + root.y1 = dy / n; + root.eachBefore(positionNode(dy, n)); + if (round2) root.eachBefore(roundNode); + return root; + } + function positionNode(dy2, n) { + return function(node) { + if (node.children) { + treemapDice(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n); + } + var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding; + if (x1 < x0) x0 = x1 = (x0 + x1) / 2; + if (y1 < y0) y0 = y1 = (y0 + y1) / 2; + node.x0 = x0; + node.y0 = y0; + node.x1 = x1; + node.y1 = y1; + }; + } + partition3.round = function(x) { + return arguments.length ? (round2 = !!x, partition3) : round2; + }; + partition3.size = function(x) { + return arguments.length ? (dx = +x[0], dy = +x[1], partition3) : [dx, dy]; + }; + partition3.padding = function(x) { + return arguments.length ? (padding = +x, partition3) : padding; + }; + return partition3; +} +var keyPrefix = "$", preroot = { depth: -1 }, ambiguous = {}; +function defaultId(d) { + return d.id; +} +function defaultParentId(d) { + return d.parentId; +} +function stratify() { + var id = defaultId, parentId = defaultParentId; + function stratify2(data) { + var d, i, n = data.length, root, parent, node, nodes = new Array(n), nodeId, nodeKey, nodeByKey = {}; + for (i = 0; i < n; ++i) { + d = data[i], node = nodes[i] = new Node$1(d); + if ((nodeId = id(d, i, data)) != null && (nodeId += "")) { + nodeKey = keyPrefix + (node.id = nodeId); + nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node; + } + } + for (i = 0; i < n; ++i) { + node = nodes[i], nodeId = parentId(data[i], i, data); + if (nodeId == null || !(nodeId += "")) { + if (root) throw new Error("multiple roots"); + root = node; + } else { + parent = nodeByKey[keyPrefix + nodeId]; + if (!parent) throw new Error("missing: " + nodeId); + if (parent === ambiguous) throw new Error("ambiguous: " + nodeId); + if (parent.children) parent.children.push(node); + else parent.children = [node]; + node.parent = parent; + } + } + if (!root) throw new Error("no root"); + root.parent = preroot; + root.eachBefore(function(node2) { + node2.depth = node2.parent.depth + 1; + --n; + }).eachBefore(computeHeight); + root.parent = null; + if (n > 0) throw new Error("cycle"); + return root; + } + stratify2.id = function(x) { + return arguments.length ? (id = required(x), stratify2) : id; + }; + stratify2.parentId = function(x) { + return arguments.length ? (parentId = required(x), stratify2) : parentId; + }; + return stratify2; +} +function defaultSeparation(a, b) { + return a.parent === b.parent ? 1 : 2; +} +function nextLeft(v) { + var children = v.children; + return children ? children[0] : v.t; +} +function nextRight(v) { + var children = v.children; + return children ? children[children.length - 1] : v.t; +} +function moveSubtree(wm, wp, shift) { + var change = shift / (wp.i - wm.i); + wp.c -= change; + wp.s += shift; + wm.c += change; + wp.z += shift; + wp.m += shift; +} +function executeShifts(v) { + var shift = 0, change = 0, children = v.children, i = children.length, w; + while (--i >= 0) { + w = children[i]; + w.z += shift; + w.m += shift; + shift += w.s + (change += w.c); + } +} +function nextAncestor(vim, v, ancestor) { + return vim.a.parent === v.parent ? vim.a : ancestor; +} +function TreeNode(node, i) { + this._ = node; + this.parent = null; + this.children = null; + this.A = null; + this.a = this; + this.z = 0; + this.m = 0; + this.c = 0; + this.s = 0; + this.t = null; + this.i = i; +} +TreeNode.prototype = Object.create(Node$1.prototype); +function treeRoot(root) { + var tree2 = new TreeNode(root, 0), node, nodes = [tree2], child, children, i, n; + while (node = nodes.pop()) { + if (children = node._.children) { + node.children = new Array(n = children.length); + for (i = n - 1; i >= 0; --i) { + nodes.push(child = node.children[i] = new TreeNode(children[i], i)); + child.parent = node; + } + } + } + (tree2.parent = new TreeNode(null, 0)).children = [tree2]; + return tree2; +} +function tree() { + var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = null; + function tree2(root) { + var t = treeRoot(root); + t.eachAfter(firstWalk), t.parent.m = -t.z; + t.eachBefore(secondWalk); + if (nodeSize) root.eachBefore(sizeNode); + else { + var left = root, right = root, bottom = root; + root.eachBefore(function(node) { + if (node.x < left.x) left = node; + if (node.x > right.x) right = node; + if (node.depth > bottom.depth) bottom = node; + }); + var s = left === right ? 1 : separation(left, right) / 2, tx = s - left.x, kx = dx / (right.x + s + tx), ky = dy / (bottom.depth || 1); + root.eachBefore(function(node) { + node.x = (node.x + tx) * kx; + node.y = node.depth * ky; + }); + } + return root; + } + function firstWalk(v) { + var children = v.children, siblings2 = v.parent.children, w = v.i ? siblings2[v.i - 1] : null; + if (children) { + executeShifts(v); + var midpoint = (children[0].z + children[children.length - 1].z) / 2; + if (w) { + v.z = w.z + separation(v._, w._); + v.m = v.z - midpoint; + } else { + v.z = midpoint; + } + } else if (w) { + v.z = w.z + separation(v._, w._); + } + v.parent.A = apportion(v, w, v.parent.A || siblings2[0]); + } + function secondWalk(v) { + v._.x = v.z + v.parent.m; + v.m += v.parent.m; + } + function apportion(v, w, ancestor) { + if (w) { + var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; + while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) { + vom = nextLeft(vom); + vop = nextRight(vop); + vop.a = v; + shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); + if (shift > 0) { + moveSubtree(nextAncestor(vim, v, ancestor), v, shift); + sip += shift; + sop += shift; + } + sim += vim.m; + sip += vip.m; + som += vom.m; + sop += vop.m; + } + if (vim && !nextRight(vop)) { + vop.t = vim; + vop.m += sim - sop; + } + if (vip && !nextLeft(vom)) { + vom.t = vip; + vom.m += sip - som; + ancestor = v; + } + } + return ancestor; + } + function sizeNode(node) { + node.x *= dx; + node.y = node.depth * dy; + } + tree2.separation = function(x) { + return arguments.length ? (separation = x, tree2) : separation; + }; + tree2.size = function(x) { + return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree2) : nodeSize ? null : [dx, dy]; + }; + tree2.nodeSize = function(x) { + return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree2) : nodeSize ? [dx, dy] : null; + }; + return tree2; +} +function treemapSlice(parent, x0, y0, x1, y1) { + var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value; + while (++i < n) { + node = nodes[i], node.x0 = x0, node.x1 = x1; + node.y0 = y0, node.y1 = y0 += node.value * k; + } +} +var phi = (1 + Math.sqrt(5)) / 2; +function squarifyRatio(ratio, parent, x0, y0, x1, y1) { + var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value2 = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta; + while (i0 < n) { + dx = x1 - x0, dy = y1 - y0; + do + sumValue = nodes[i1++].value; + while (!sumValue && i1 < n); + minValue = maxValue = sumValue; + alpha = Math.max(dy / dx, dx / dy) / (value2 * ratio); + beta = sumValue * sumValue * alpha; + minRatio = Math.max(maxValue / beta, beta / minValue); + for (; i1 < n; ++i1) { + sumValue += nodeValue = nodes[i1].value; + if (nodeValue < minValue) minValue = nodeValue; + if (nodeValue > maxValue) maxValue = nodeValue; + beta = sumValue * sumValue * alpha; + newRatio = Math.max(maxValue / beta, beta / minValue); + if (newRatio > minRatio) { + sumValue -= nodeValue; + break; + } + minRatio = newRatio; + } + rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) }); + if (row.dice) treemapDice(row, x0, y0, x1, value2 ? y0 += dy * sumValue / value2 : y1); + else treemapSlice(row, x0, y0, value2 ? x0 += dx * sumValue / value2 : x1, y1); + value2 -= sumValue, i0 = i1; + } + return rows; +} +const squarify = function custom(ratio) { + function squarify2(parent, x0, y0, x1, y1) { + squarifyRatio(ratio, parent, x0, y0, x1, y1); + } + squarify2.ratio = function(x) { + return custom((x = +x) > 1 ? x : 1); + }; + return squarify2; +}(phi); +function index() { + var tile = squarify, round2 = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero; + function treemap2(root) { + root.x0 = root.y0 = 0; + root.x1 = dx; + root.y1 = dy; + root.eachBefore(positionNode); + paddingStack = [0]; + if (round2) root.eachBefore(roundNode); + return root; + } + function positionNode(node) { + var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p; + if (x1 < x0) x0 = x1 = (x0 + x1) / 2; + if (y1 < y0) y0 = y1 = (y0 + y1) / 2; + node.x0 = x0; + node.y0 = y0; + node.x1 = x1; + node.y1 = y1; + if (node.children) { + p = paddingStack[node.depth + 1] = paddingInner(node) / 2; + x0 += paddingLeft(node) - p; + y0 += paddingTop(node) - p; + x1 -= paddingRight(node) - p; + y1 -= paddingBottom(node) - p; + if (x1 < x0) x0 = x1 = (x0 + x1) / 2; + if (y1 < y0) y0 = y1 = (y0 + y1) / 2; + tile(node, x0, y0, x1, y1); + } + } + treemap2.round = function(x) { + return arguments.length ? (round2 = !!x, treemap2) : round2; + }; + treemap2.size = function(x) { + return arguments.length ? (dx = +x[0], dy = +x[1], treemap2) : [dx, dy]; + }; + treemap2.tile = function(x) { + return arguments.length ? (tile = required(x), treemap2) : tile; + }; + treemap2.padding = function(x) { + return arguments.length ? treemap2.paddingInner(x).paddingOuter(x) : treemap2.paddingInner(); + }; + treemap2.paddingInner = function(x) { + return arguments.length ? (paddingInner = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingInner; + }; + treemap2.paddingOuter = function(x) { + return arguments.length ? treemap2.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap2.paddingTop(); + }; + treemap2.paddingTop = function(x) { + return arguments.length ? (paddingTop = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingTop; + }; + treemap2.paddingRight = function(x) { + return arguments.length ? (paddingRight = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingRight; + }; + treemap2.paddingBottom = function(x) { + return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingBottom; + }; + treemap2.paddingLeft = function(x) { + return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingLeft; + }; + return treemap2; +} +function binary(parent, x0, y0, x1, y1) { + var nodes = parent.children, i, n = nodes.length, sum, sums = new Array(n + 1); + for (sums[0] = sum = i = 0; i < n; ++i) { + sums[i + 1] = sum += nodes[i].value; + } + partition3(0, n, parent.value, x0, y0, x1, y1); + function partition3(i2, j, value2, x02, y02, x12, y12) { + if (i2 >= j - 1) { + var node = nodes[i2]; + node.x0 = x02, node.y0 = y02; + node.x1 = x12, node.y1 = y12; + return; + } + var valueOffset = sums[i2], valueTarget = value2 / 2 + valueOffset, k = i2 + 1, hi = j - 1; + while (k < hi) { + var mid = k + hi >>> 1; + if (sums[mid] < valueTarget) k = mid + 1; + else hi = mid; + } + if (valueTarget - sums[k - 1] < sums[k] - valueTarget && i2 + 1 < k) --k; + var valueLeft = sums[k] - valueOffset, valueRight = value2 - valueLeft; + if (x12 - x02 > y12 - y02) { + var xk = (x02 * valueRight + x12 * valueLeft) / value2; + partition3(i2, k, valueLeft, x02, y02, xk, y12); + partition3(k, j, valueRight, xk, y02, x12, y12); + } else { + var yk = (y02 * valueRight + y12 * valueLeft) / value2; + partition3(i2, k, valueLeft, x02, y02, x12, yk); + partition3(k, j, valueRight, x02, yk, x12, y12); + } + } +} +function sliceDice(parent, x0, y0, x1, y1) { + (parent.depth & 1 ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1); +} +const resquarify = function custom2(ratio) { + function resquarify2(parent, x0, y0, x1, y1) { + if ((rows = parent._squarify) && rows.ratio === ratio) { + var rows, row, nodes, i, j = -1, n, m = rows.length, value2 = parent.value; + while (++j < m) { + row = rows[j], nodes = row.children; + for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value; + if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value2); + else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value2, y1); + value2 -= row.value; + } + } else { + parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1); + rows.ratio = ratio; + } + } + resquarify2.ratio = function(x) { + return custom2((x = +x) > 1 ? x : 1); + }; + return resquarify2; +}(phi); +const src$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + cluster: cluster2, + hierarchy, + pack: index$1, + packEnclose: enclose, + packSiblings: siblings, + partition: partition$3, + stratify, + tree, + treemap: index, + treemapBinary: binary, + treemapDice, + treemapResquarify: resquarify, + treemapSlice, + treemapSliceDice: sliceDice, + treemapSquarify: squarify +}, Symbol.toStringTag, { value: "Module" })); +const require$$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$1); +(function(exports2) { + var d3Hierarchy2 = require$$1; + var isNumeric2 = fastIsnumeric; + var Lib2 = libExports; + var makeColorScaleFn = colorscale.makeColorScaleFuncFromTrace; + var makePullColorFn2 = calc_1$1.makePullColorFn; + var generateExtendedColors2 = calc_1$1.generateExtendedColors; + var colorscaleCalc2 = colorscale.calc; + var ALMOST_EQUAL2 = numerical.ALMOST_EQUAL; + var sunburstExtendedColorWays = {}; + var treemapExtendedColorWays = {}; + var icicleExtendedColorWays = {}; + exports2.calc = function(gd, trace) { + var fullLayout = gd._fullLayout; + var ids = trace.ids; + var hasIds = Lib2.isArrayOrTypedArray(ids); + var labels = trace.labels; + var parents = trace.parents; + var values = trace.values; + var hasValues = Lib2.isArrayOrTypedArray(values); + var cd = []; + var parent2children = {}; + var refs = {}; + var addToLookup = function(parent, v) { + if (parent2children[parent]) parent2children[parent].push(v); + else parent2children[parent] = [v]; + refs[v] = 1; + }; + var isValidKey = function(k2) { + return k2 || typeof k2 === "number"; + }; + var isValidVal = function(i2) { + return !hasValues || isNumeric2(values[i2]) && values[i2] >= 0; + }; + var len; + var isValid; + var getId2; + if (hasIds) { + len = Math.min(ids.length, parents.length); + isValid = function(i2) { + return isValidKey(ids[i2]) && isValidVal(i2); + }; + getId2 = function(i2) { + return String(ids[i2]); + }; + } else { + len = Math.min(labels.length, parents.length); + isValid = function(i2) { + return isValidKey(labels[i2]) && isValidVal(i2); + }; + getId2 = function(i2) { + return String(labels[i2]); + }; + } + if (hasValues) len = Math.min(len, values.length); + for (var i = 0; i < len; i++) { + if (isValid(i)) { + var id = getId2(i); + var pid = isValidKey(parents[i]) ? String(parents[i]) : ""; + var cdi = { + i, + id, + pid, + label: isValidKey(labels[i]) ? String(labels[i]) : "" + }; + if (hasValues) cdi.v = +values[i]; + cd.push(cdi); + addToLookup(pid, id); + } + } + if (!parent2children[""]) { + var impliedRoots = []; + var k; + for (k in parent2children) { + if (!refs[k]) { + impliedRoots.push(k); + } + } + if (impliedRoots.length === 1) { + k = impliedRoots[0]; + cd.unshift({ + hasImpliedRoot: true, + id: k, + pid: "", + label: k + }); + } else { + return Lib2.warn([ + "Multiple implied roots, cannot build", + trace.type, + "hierarchy of", + trace.name + ".", + "These roots include:", + impliedRoots.join(", ") + ].join(" ")); + } + } else if (parent2children[""].length > 1) { + var dummyId = Lib2.randstr(); + for (var j = 0; j < cd.length; j++) { + if (cd[j].pid === "") { + cd[j].pid = dummyId; + } + } + cd.unshift({ + hasMultipleRoots: true, + id: dummyId, + pid: "", + label: "" + }); + } + var root; + try { + root = d3Hierarchy2.stratify().id(function(d) { + return d.id; + }).parentId(function(d) { + return d.pid; + })(cd); + } catch (e) { + return Lib2.warn([ + "Failed to build", + trace.type, + "hierarchy of", + trace.name + ".", + "Error:", + e.message + ].join(" ")); + } + var hierarchy2 = d3Hierarchy2.hierarchy(root); + var failed = false; + if (hasValues) { + switch (trace.branchvalues) { + case "remainder": + hierarchy2.sum(function(d) { + return d.data.v; + }); + break; + case "total": + hierarchy2.each(function(d) { + var cdi2 = d.data.data; + var v = cdi2.v; + if (d.children) { + var partialSum = d.children.reduce(function(a, c) { + return a + c.data.data.v; + }, 0); + if (cdi2.hasImpliedRoot || cdi2.hasMultipleRoots) { + v = partialSum; + } + if (v < partialSum * ALMOST_EQUAL2) { + failed = true; + return Lib2.warn([ + "Total value for node", + d.data.data.id, + "of", + trace.name, + "is smaller than the sum of its children.", + "\nparent value =", + v, + "\nchildren sum =", + partialSum + ].join(" ")); + } + } + d.value = v; + }); + break; + } + } else { + countDescendants(hierarchy2, trace, { + branches: trace.count.indexOf("branches") !== -1, + leaves: trace.count.indexOf("leaves") !== -1 + }); + } + if (failed) return; + if (trace.sort) { + hierarchy2.sort(function(a, b) { + return b.value - a.value; + }); + } + var pullColor; + var scaleColor; + var colors = trace.marker.colors || []; + var hasColors = !!colors.length; + if (trace._hasColorscale) { + if (!hasColors) { + colors = hasValues ? trace.values : trace._values; + } + colorscaleCalc2(gd, trace, { + vals: colors, + containerStr: "marker", + cLetter: "c" + }); + scaleColor = makeColorScaleFn(trace.marker); + } else { + pullColor = makePullColorFn2(fullLayout["_" + trace.type + "colormap"]); + } + hierarchy2.each(function(d) { + var cdi2 = d.data.data; + cdi2.color = trace._hasColorscale ? scaleColor(colors[cdi2.i]) : pullColor(colors[cdi2.i], cdi2.id); + }); + cd[0].hierarchy = hierarchy2; + return cd; + }; + exports2._runCrossTraceCalc = function(desiredType, gd) { + var fullLayout = gd._fullLayout; + var calcdata = gd.calcdata; + var colorWay = fullLayout[desiredType + "colorway"]; + var colorMap = fullLayout["_" + desiredType + "colormap"]; + if (fullLayout["extend" + desiredType + "colors"]) { + colorWay = generateExtendedColors2( + colorWay, + desiredType === "icicle" ? icicleExtendedColorWays : desiredType === "treemap" ? treemapExtendedColorWays : sunburstExtendedColorWays + ); + } + var dfltColorCount = 0; + var rootColor; + function pickColor(d) { + var cdi = d.data.data; + var id = cdi.id; + if (cdi.color === false) { + if (colorMap[id]) { + cdi.color = colorMap[id]; + } else if (d.parent) { + if (d.parent.parent) { + cdi.color = d.parent.data.data.color; + } else { + colorMap[id] = cdi.color = colorWay[dfltColorCount % colorWay.length]; + dfltColorCount++; + } + } else { + cdi.color = rootColor; + } + } + } + for (var i = 0; i < calcdata.length; i++) { + var cd = calcdata[i]; + var cd0 = cd[0]; + if (cd0.trace.type === desiredType && cd0.hierarchy) { + rootColor = cd0.trace.root.color; + cd0.hierarchy.each(pickColor); + } + } + }; + exports2.crossTraceCalc = function(gd) { + return exports2._runCrossTraceCalc("sunburst", gd); + }; + function countDescendants(node, trace, opts) { + var nChild = 0; + var children = node.children; + if (children) { + var len = children.length; + for (var i = 0; i < len; i++) { + nChild += countDescendants(children[i], trace, opts); + } + if (opts.branches) nChild++; + } else { + if (opts.leaves) nChild++; + } + node.value = node.data.data.value = nChild; + if (!trace._values) trace._values = []; + trace._values[node.data.data.i] = nChild; + return nChild; + } +})(calc$1); +var calc5 = calc$1; +calc$2.calc = function(gd, trace) { + return calc5.calc(gd, trace); +}; +calc$2.crossTraceCalc = function(gd) { + return calc5._runCrossTraceCalc("treemap", gd); +}; +var helpers$6 = {}; +(function(exports2) { + var Lib2 = libExports; + var Color2 = colorExports; + var setCursor3 = setcursor; + var pieHelpers2 = helpers$F; + exports2.findEntryWithLevel = function(hierarchy2, level) { + var out; + if (level) { + hierarchy2.eachAfter(function(pt) { + if (exports2.getPtId(pt) === level) { + return out = pt.copy(); + } + }); + } + return out || hierarchy2; + }; + exports2.findEntryWithChild = function(hierarchy2, childId) { + var out; + hierarchy2.eachAfter(function(pt) { + var children = pt.children || []; + for (var i = 0; i < children.length; i++) { + var child = children[i]; + if (exports2.getPtId(child) === childId) { + return out = pt.copy(); + } + } + }); + return out || hierarchy2; + }; + exports2.isEntry = function(pt) { + return !pt.parent; + }; + exports2.isLeaf = function(pt) { + return !pt.children; + }; + exports2.getPtId = function(pt) { + return pt.data.data.id; + }; + exports2.getPtLabel = function(pt) { + return pt.data.data.label; + }; + exports2.getValue = function(d) { + return d.value; + }; + exports2.isHierarchyRoot = function(pt) { + return getParentId(pt) === ""; + }; + exports2.setSliceCursor = function(sliceTop, gd, opts) { + var hide = opts.isTransitioning; + if (!hide) { + var pt = sliceTop.datum(); + hide = opts.hideOnRoot && exports2.isHierarchyRoot(pt) || opts.hideOnLeaves && exports2.isLeaf(pt); + } + setCursor3(sliceTop, hide ? null : "pointer"); + }; + function determineOutsideTextFont2(trace, pt, layoutFont) { + return { + color: exports2.getOutsideTextFontKey("color", trace, pt, layoutFont), + family: exports2.getOutsideTextFontKey("family", trace, pt, layoutFont), + size: exports2.getOutsideTextFontKey("size", trace, pt, layoutFont), + weight: exports2.getOutsideTextFontKey("weight", trace, pt, layoutFont), + style: exports2.getOutsideTextFontKey("style", trace, pt, layoutFont), + variant: exports2.getOutsideTextFontKey("variant", trace, pt, layoutFont), + textcase: exports2.getOutsideTextFontKey("textcase", trace, pt, layoutFont), + lineposition: exports2.getOutsideTextFontKey("lineposition", trace, pt, layoutFont), + shadow: exports2.getOutsideTextFontKey("shadow", trace, pt, layoutFont) + }; + } + function determineInsideTextFont2(trace, pt, layoutFont, opts) { + var onPathbar2 = (opts || {}).onPathbar; + var cdi = pt.data.data; + var ptNumber = cdi.i; + var customColor = Lib2.castOption( + trace, + ptNumber, + (onPathbar2 ? "pathbar.textfont" : "insidetextfont") + ".color" + ); + if (!customColor && trace._input.textfont) { + customColor = Lib2.castOption(trace._input, ptNumber, "textfont.color"); + } + return { + color: customColor || Color2.contrast(cdi.color), + family: exports2.getInsideTextFontKey("family", trace, pt, layoutFont, opts), + size: exports2.getInsideTextFontKey("size", trace, pt, layoutFont, opts), + weight: exports2.getInsideTextFontKey("weight", trace, pt, layoutFont, opts), + style: exports2.getInsideTextFontKey("style", trace, pt, layoutFont, opts), + variant: exports2.getInsideTextFontKey("variant", trace, pt, layoutFont, opts), + textcase: exports2.getInsideTextFontKey("textcase", trace, pt, layoutFont, opts), + lineposition: exports2.getInsideTextFontKey("lineposition", trace, pt, layoutFont, opts), + shadow: exports2.getInsideTextFontKey("shadow", trace, pt, layoutFont, opts) + }; + } + exports2.getInsideTextFontKey = function(keyStr, trace, pt, layoutFont, opts) { + var onPathbar2 = (opts || {}).onPathbar; + var cont = onPathbar2 ? "pathbar.textfont" : "insidetextfont"; + var ptNumber = pt.data.data.i; + return Lib2.castOption(trace, ptNumber, cont + "." + keyStr) || Lib2.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size; + }; + exports2.getOutsideTextFontKey = function(keyStr, trace, pt, layoutFont) { + var ptNumber = pt.data.data.i; + return Lib2.castOption(trace, ptNumber, "outsidetextfont." + keyStr) || Lib2.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size; + }; + exports2.isOutsideText = function(trace, pt) { + return !trace._hasColorscale && exports2.isHierarchyRoot(pt); + }; + exports2.determineTextFont = function(trace, pt, layoutFont, opts) { + return exports2.isOutsideText(trace, pt) ? determineOutsideTextFont2(trace, pt, layoutFont) : determineInsideTextFont2(trace, pt, layoutFont, opts); + }; + exports2.hasTransition = function(transitionOpts) { + return !!(transitionOpts && transitionOpts.duration > 0); + }; + exports2.getMaxDepth = function(trace) { + return trace.maxdepth >= 0 ? trace.maxdepth : Infinity; + }; + exports2.isHeader = function(pt, trace) { + return !(exports2.isLeaf(pt) || pt.depth === trace._maxDepth - 1); + }; + function getParentId(pt) { + return pt.data.data.pid; + } + exports2.getParent = function(hierarchy2, pt) { + return exports2.findEntryWithLevel(hierarchy2, getParentId(pt)); + }; + exports2.listPath = function(d, keyStr) { + var parent = d.parent; + if (!parent) return []; + var list = keyStr ? [parent.data[keyStr]] : [parent]; + return exports2.listPath(parent, keyStr).concat(list); + }; + exports2.getPath = function(d) { + return exports2.listPath(d, "label").join("/") + "/"; + }; + exports2.formatValue = pieHelpers2.formatPieValue; + exports2.formatPercent = function(v, separators) { + var tx = Lib2.formatPercent(v, 0); + if (tx === "0%") tx = pieHelpers2.formatPiePercent(v, separators); + return tx; + }; +})(helpers$6); +function define(constructor, factory2, prototype) { + constructor.prototype = factory2.prototype = prototype; + prototype.constructor = constructor; +} +function extend(parent, definition) { + var prototype = Object.create(parent.prototype); + for (var key in definition) prototype[key] = definition[key]; + return prototype; +} +function Color$3() { +} +var darker = 0.7; +var brighter = 1 / darker; +var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`), reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`), reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`), reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`), reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`), reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`); +var named = { + aliceblue: 15792383, + antiquewhite: 16444375, + aqua: 65535, + aquamarine: 8388564, + azure: 15794175, + beige: 16119260, + bisque: 16770244, + black: 0, + blanchedalmond: 16772045, + blue: 255, + blueviolet: 9055202, + brown: 10824234, + burlywood: 14596231, + cadetblue: 6266528, + chartreuse: 8388352, + chocolate: 13789470, + coral: 16744272, + cornflowerblue: 6591981, + cornsilk: 16775388, + crimson: 14423100, + cyan: 65535, + darkblue: 139, + darkcyan: 35723, + darkgoldenrod: 12092939, + darkgray: 11119017, + darkgreen: 25600, + darkgrey: 11119017, + darkkhaki: 12433259, + darkmagenta: 9109643, + darkolivegreen: 5597999, + darkorange: 16747520, + darkorchid: 10040012, + darkred: 9109504, + darksalmon: 15308410, + darkseagreen: 9419919, + darkslateblue: 4734347, + darkslategray: 3100495, + darkslategrey: 3100495, + darkturquoise: 52945, + darkviolet: 9699539, + deeppink: 16716947, + deepskyblue: 49151, + dimgray: 6908265, + dimgrey: 6908265, + dodgerblue: 2003199, + firebrick: 11674146, + floralwhite: 16775920, + forestgreen: 2263842, + fuchsia: 16711935, + gainsboro: 14474460, + ghostwhite: 16316671, + gold: 16766720, + goldenrod: 14329120, + gray: 8421504, + green: 32768, + greenyellow: 11403055, + grey: 8421504, + honeydew: 15794160, + hotpink: 16738740, + indianred: 13458524, + indigo: 4915330, + ivory: 16777200, + khaki: 15787660, + lavender: 15132410, + lavenderblush: 16773365, + lawngreen: 8190976, + lemonchiffon: 16775885, + lightblue: 11393254, + lightcoral: 15761536, + lightcyan: 14745599, + lightgoldenrodyellow: 16448210, + lightgray: 13882323, + lightgreen: 9498256, + lightgrey: 13882323, + lightpink: 16758465, + lightsalmon: 16752762, + lightseagreen: 2142890, + lightskyblue: 8900346, + lightslategray: 7833753, + lightslategrey: 7833753, + lightsteelblue: 11584734, + lightyellow: 16777184, + lime: 65280, + limegreen: 3329330, + linen: 16445670, + magenta: 16711935, + maroon: 8388608, + mediumaquamarine: 6737322, + mediumblue: 205, + mediumorchid: 12211667, + mediumpurple: 9662683, + mediumseagreen: 3978097, + mediumslateblue: 8087790, + mediumspringgreen: 64154, + mediumturquoise: 4772300, + mediumvioletred: 13047173, + midnightblue: 1644912, + mintcream: 16121850, + mistyrose: 16770273, + moccasin: 16770229, + navajowhite: 16768685, + navy: 128, + oldlace: 16643558, + olive: 8421376, + olivedrab: 7048739, + orange: 16753920, + orangered: 16729344, + orchid: 14315734, + palegoldenrod: 15657130, + palegreen: 10025880, + paleturquoise: 11529966, + palevioletred: 14381203, + papayawhip: 16773077, + peachpuff: 16767673, + peru: 13468991, + pink: 16761035, + plum: 14524637, + powderblue: 11591910, + purple: 8388736, + rebeccapurple: 6697881, + red: 16711680, + rosybrown: 12357519, + royalblue: 4286945, + saddlebrown: 9127187, + salmon: 16416882, + sandybrown: 16032864, + seagreen: 3050327, + seashell: 16774638, + sienna: 10506797, + silver: 12632256, + skyblue: 8900331, + slateblue: 6970061, + slategray: 7372944, + slategrey: 7372944, + snow: 16775930, + springgreen: 65407, + steelblue: 4620980, + tan: 13808780, + teal: 32896, + thistle: 14204888, + tomato: 16737095, + turquoise: 4251856, + violet: 15631086, + wheat: 16113331, + white: 16777215, + whitesmoke: 16119285, + yellow: 16776960, + yellowgreen: 10145074 +}; +define(Color$3, color, { + copy(channels) { + return Object.assign(new this.constructor(), this, channels); + }, + displayable() { + return this.rgb().displayable(); + }, + hex: color_formatHex, + // Deprecated! Use color.formatHex. + formatHex: color_formatHex, + formatHex8: color_formatHex8, + formatHsl: color_formatHsl, + formatRgb: color_formatRgb, + toString: color_formatRgb +}); +function color_formatHex() { + return this.rgb().formatHex(); +} +function color_formatHex8() { + return this.rgb().formatHex8(); +} +function color_formatHsl() { + return hslConvert(this).formatHsl(); +} +function color_formatRgb() { + return this.rgb().formatRgb(); +} +function color(format2) { + var m, l; + format2 = (format2 + "").trim().toLowerCase(); + return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba2(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba2(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba2(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba2(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; +} +function rgbn(n) { + return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1); +} +function rgba2(r, g, b, a) { + if (a <= 0) r = g = b = NaN; + return new Rgb(r, g, b, a); +} +function rgbConvert(o) { + if (!(o instanceof Color$3)) o = color(o); + if (!o) return new Rgb(); + o = o.rgb(); + return new Rgb(o.r, o.g, o.b, o.opacity); +} +function rgb$1(r, g, b, opacity) { + return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); +} +function Rgb(r, g, b, opacity) { + this.r = +r; + this.g = +g; + this.b = +b; + this.opacity = +opacity; +} +define(Rgb, rgb$1, extend(Color$3, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); + }, + rgb() { + return this; + }, + clamp() { + return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity)); + }, + displayable() { + return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1); + }, + hex: rgb_formatHex, + // Deprecated! Use color.formatHex. + formatHex: rgb_formatHex, + formatHex8: rgb_formatHex8, + formatRgb: rgb_formatRgb, + toString: rgb_formatRgb +})); +function rgb_formatHex() { + return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`; +} +function rgb_formatHex8() { + return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`; +} +function rgb_formatRgb() { + const a = clampa(this.opacity); + return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`; +} +function clampa(opacity) { + return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity)); +} +function clampi(value2) { + return Math.max(0, Math.min(255, Math.round(value2) || 0)); +} +function hex(value2) { + value2 = clampi(value2); + return (value2 < 16 ? "0" : "") + value2.toString(16); +} +function hsla(h, s, l, a) { + if (a <= 0) h = s = l = NaN; + else if (l <= 0 || l >= 1) h = s = NaN; + else if (s <= 0) h = NaN; + return new Hsl(h, s, l, a); +} +function hslConvert(o) { + if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); + if (!(o instanceof Color$3)) o = color(o); + if (!o) return new Hsl(); + if (o instanceof Hsl) return o; + o = o.rgb(); + var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; + if (s) { + if (r === max) h = (g - b) / s + (g < b) * 6; + else if (g === max) h = (b - r) / s + 2; + else h = (r - g) / s + 4; + s /= l < 0.5 ? max + min : 2 - max - min; + h *= 60; + } else { + s = l > 0 && l < 1 ? 0 : h; + } + return new Hsl(h, s, l, o.opacity); +} +function hsl$2(h, s, l, opacity) { + return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); +} +function Hsl(h, s, l, opacity) { + this.h = +h; + this.s = +s; + this.l = +l; + this.opacity = +opacity; +} +define(Hsl, hsl$2, extend(Color$3, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Hsl(this.h, this.s, this.l * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Hsl(this.h, this.s, this.l * k, this.opacity); + }, + rgb() { + var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; + return new Rgb( + hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), + hsl2rgb(h, m1, m2), + hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), + this.opacity + ); + }, + clamp() { + return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity)); + }, + displayable() { + return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); + }, + formatHsl() { + const a = clampa(this.opacity); + return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`; + } +})); +function clamph(value2) { + value2 = (value2 || 0) % 360; + return value2 < 0 ? value2 + 360 : value2; +} +function clampt(value2) { + return Math.max(0, Math.min(1, value2 || 0)); +} +function hsl2rgb(h, m1, m2) { + return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; +} +const radians = Math.PI / 180; +const degrees$1 = 180 / Math.PI; +const K = 18, Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1; +function labConvert(o) { + if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); + if (o instanceof Hcl) return hcl2lab(o); + if (!(o instanceof Rgb)) o = rgbConvert(o); + var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z; + if (r === g && g === b) x = z = y; + else { + x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); + z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); + } + return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); +} +function lab$1(l, a, b, opacity) { + return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); +} +function Lab(l, a, b, opacity) { + this.l = +l; + this.a = +a; + this.b = +b; + this.opacity = +opacity; +} +define(Lab, lab$1, extend(Color$3, { + brighter(k) { + return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity); + }, + darker(k) { + return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity); + }, + rgb() { + var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; + x = Xn * lab2xyz(x); + y = Yn * lab2xyz(y); + z = Zn * lab2xyz(z); + return new Rgb( + lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), + lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.033454 * z), + lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), + this.opacity + ); + } +})); +function xyz2lab(t) { + return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; +} +function lab2xyz(t) { + return t > t1 ? t * t * t : t2 * (t - t0); +} +function lrgb2rgb(x) { + return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); +} +function rgb2lrgb(x) { + return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); +} +function hclConvert(o) { + if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); + if (!(o instanceof Lab)) o = labConvert(o); + if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity); + var h = Math.atan2(o.b, o.a) * degrees$1; + return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); +} +function hcl$2(h, c, l, opacity) { + return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); +} +function Hcl(h, c, l, opacity) { + this.h = +h; + this.c = +c; + this.l = +l; + this.opacity = +opacity; +} +function hcl2lab(o) { + if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity); + var h = o.h * radians; + return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); +} +define(Hcl, hcl$2, extend(Color$3, { + brighter(k) { + return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity); + }, + darker(k) { + return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity); + }, + rgb() { + return hcl2lab(this).rgb(); + } +})); +var A = -0.14861, B = 1.78277, C = -0.29227, D = -0.90649, E = 1.97294, ED = E * D, EB = E * B, BC_DA = B * C - D * A; +function cubehelixConvert(o) { + if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); + if (!(o instanceof Rgb)) o = rgbConvert(o); + var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), h = s ? Math.atan2(k, bl) * degrees$1 - 120 : NaN; + return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); +} +function cubehelix$2(h, s, l, opacity) { + return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); +} +function Cubehelix(h, s, l, opacity) { + this.h = +h; + this.s = +s; + this.l = +l; + this.opacity = +opacity; +} +define(Cubehelix, cubehelix$2, extend(Color$3, { + brighter(k) { + k = k == null ? brighter : Math.pow(brighter, k); + return new Cubehelix(this.h, this.s, this.l * k, this.opacity); + }, + darker(k) { + k = k == null ? darker : Math.pow(darker, k); + return new Cubehelix(this.h, this.s, this.l * k, this.opacity); + }, + rgb() { + var h = isNaN(this.h) ? 0 : (this.h + 120) * radians, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh2 = Math.cos(h), sinh2 = Math.sin(h); + return new Rgb( + 255 * (l + a * (A * cosh2 + B * sinh2)), + 255 * (l + a * (C * cosh2 + D * sinh2)), + 255 * (l + a * (E * cosh2)), + this.opacity + ); + } +})); +function basis(t12, v0, v1, v2, v3) { + var t22 = t12 * t12, t32 = t22 * t12; + return ((1 - 3 * t12 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t12 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6; +} +function basis$1(values) { + var n = values.length - 1; + return function(t) { + var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1; + return basis((t - i / n) * n, v0, v1, v2, v3); + }; +} +function basisClosed(values) { + var n = values.length; + return function(t) { + var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n]; + return basis((t - i / n) * n, v0, v1, v2, v3); + }; +} +const constant = (x) => () => x; +function linear(a, d) { + return function(t) { + return a + t * d; + }; +} +function exponential(a, b, y) { + return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { + return Math.pow(a + t * b, y); + }; +} +function hue$1(a, b) { + var d = b - a; + return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a); +} +function gamma(y) { + return (y = +y) === 1 ? nogamma : function(a, b) { + return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a); + }; +} +function nogamma(a, b) { + var d = b - a; + return d ? linear(a, d) : constant(isNaN(a) ? b : a); +} +const rgb = function rgbGamma(y) { + var color2 = gamma(y); + function rgb2(start, end) { + var r = color2((start = rgb$1(start)).r, (end = rgb$1(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.r = r(t); + start.g = g(t); + start.b = b(t); + start.opacity = opacity(t); + return start + ""; + }; + } + rgb2.gamma = rgbGamma; + return rgb2; +}(1); +function rgbSpline(spline) { + return function(colors) { + var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2; + for (i = 0; i < n; ++i) { + color2 = rgb$1(colors[i]); + r[i] = color2.r || 0; + g[i] = color2.g || 0; + b[i] = color2.b || 0; + } + r = spline(r); + g = spline(g); + b = spline(b); + color2.opacity = 1; + return function(t) { + color2.r = r(t); + color2.g = g(t); + color2.b = b(t); + return color2 + ""; + }; + }; +} +var rgbBasis = rgbSpline(basis$1); +var rgbBasisClosed = rgbSpline(basisClosed); +function numberArray(a, b) { + if (!b) b = []; + var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i; + return function(t) { + for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t; + return c; + }; +} +function isNumberArray(x) { + return ArrayBuffer.isView(x) && !(x instanceof DataView); +} +function array(a, b) { + return (isNumberArray(b) ? numberArray : genericArray)(a, b); +} +function genericArray(a, b) { + var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i; + for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]); + for (; i < nb; ++i) c[i] = b[i]; + return function(t) { + for (i = 0; i < na; ++i) c[i] = x[i](t); + return c; + }; +} +function date(a, b) { + var d = /* @__PURE__ */ new Date(); + return a = +a, b = +b, function(t) { + return d.setTime(a * (1 - t) + b * t), d; + }; +} +function number(a, b) { + return a = +a, b = +b, function(t) { + return a * (1 - t) + b * t; + }; +} +function object(a, b) { + var i = {}, c = {}, k; + if (a === null || typeof a !== "object") a = {}; + if (b === null || typeof b !== "object") b = {}; + for (k in b) { + if (k in a) { + i[k] = value(a[k], b[k]); + } else { + c[k] = b[k]; + } + } + return function(t) { + for (k in i) c[k] = i[k](t); + return c; + }; +} +var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = new RegExp(reA.source, "g"); +function zero(b) { + return function() { + return b; + }; +} +function one(b) { + return function(t) { + return b(t) + ""; + }; +} +function string(a, b) { + var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; + a = a + "", b = b + ""; + while ((am = reA.exec(a)) && (bm = reB.exec(b))) { + if ((bs = bm.index) > bi) { + bs = b.slice(bi, bs); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + if ((am = am[0]) === (bm = bm[0])) { + if (s[i]) s[i] += bm; + else s[++i] = bm; + } else { + s[++i] = null; + q.push({ i, x: number(am, bm) }); + } + bi = reB.lastIndex; + } + if (bi < b.length) { + bs = b.slice(bi); + if (s[i]) s[i] += bs; + else s[++i] = bs; + } + return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) { + for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t); + return s.join(""); + }); +} +function value(a, b) { + var t = typeof b, c; + return b == null || t === "boolean" ? constant(b) : (t === "number" ? number : t === "string" ? (c = color(b)) ? (b = c, rgb) : string : b instanceof color ? rgb : b instanceof Date ? date : isNumberArray(b) ? numberArray : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object : number)(a, b); +} +function discrete(range) { + var n = range.length; + return function(t) { + return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))]; + }; +} +function hue(a, b) { + var i = hue$1(+a, +b); + return function(t) { + var x = i(t); + return x - 360 * Math.floor(x / 360); + }; +} +function round(a, b) { + return a = +a, b = +b, function(t) { + return Math.round(a * (1 - t) + b * t); + }; +} +var degrees = 180 / Math.PI; +var identity2 = { + translateX: 0, + translateY: 0, + rotate: 0, + skewX: 0, + scaleX: 1, + scaleY: 1 +}; +function decompose(a, b, c, d, e, f) { + var scaleX, scaleY, skewX; + if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX; + if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX; + if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY; + if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; + return { + translateX: e, + translateY: f, + rotate: Math.atan2(b, a) * degrees, + skewX: Math.atan(skewX) * degrees, + scaleX, + scaleY + }; +} +var svgNode; +function parseCss(value2) { + const m = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value2 + ""); + return m.isIdentity ? identity2 : decompose(m.a, m.b, m.c, m.d, m.e, m.f); +} +function parseSvg(value2) { + if (value2 == null) return identity2; + if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); + svgNode.setAttribute("transform", value2); + if (!(value2 = svgNode.transform.baseVal.consolidate())) return identity2; + value2 = value2.matrix; + return decompose(value2.a, value2.b, value2.c, value2.d, value2.e, value2.f); +} +function interpolateTransform(parse2, pxComma, pxParen, degParen) { + function pop(s) { + return s.length ? s.pop() + " " : ""; + } + function translate2(xa, ya, xb, yb, s, q) { + if (xa !== xb || ya !== yb) { + var i = s.push("translate(", null, pxComma, null, pxParen); + q.push({ i: i - 4, x: number(xa, xb) }, { i: i - 2, x: number(ya, yb) }); + } else if (xb || yb) { + s.push("translate(" + xb + pxComma + yb + pxParen); + } + } + function rotate2(a, b, s, q) { + if (a !== b) { + if (a - b > 180) b += 360; + else if (b - a > 180) a += 360; + q.push({ i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b) }); + } else if (b) { + s.push(pop(s) + "rotate(" + b + degParen); + } + } + function skewX(a, b, s, q) { + if (a !== b) { + q.push({ i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b) }); + } else if (b) { + s.push(pop(s) + "skewX(" + b + degParen); + } + } + function scale2(xa, ya, xb, yb, s, q) { + if (xa !== xb || ya !== yb) { + var i = s.push(pop(s) + "scale(", null, ",", null, ")"); + q.push({ i: i - 4, x: number(xa, xb) }, { i: i - 2, x: number(ya, yb) }); + } else if (xb !== 1 || yb !== 1) { + s.push(pop(s) + "scale(" + xb + "," + yb + ")"); + } + } + return function(a, b) { + var s = [], q = []; + a = parse2(a), b = parse2(b); + translate2(a.translateX, a.translateY, b.translateX, b.translateY, s, q); + rotate2(a.rotate, b.rotate, s, q); + skewX(a.skewX, b.skewX, s, q); + scale2(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q); + a = b = null; + return function(t) { + var i = -1, n = q.length, o; + while (++i < n) s[(o = q[i]).i] = o.x(t); + return s.join(""); + }; + }; +} +var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)"); +var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")"); +var epsilon2 = 1e-12; +function cosh(x) { + return ((x = Math.exp(x)) + 1 / x) / 2; +} +function sinh(x) { + return ((x = Math.exp(x)) - 1 / x) / 2; +} +function tanh(x) { + return ((x = Math.exp(2 * x)) - 1) / (x + 1); +} +const zoom = function zoomRho(rho, rho2, rho4) { + function zoom2(p0, p1) { + var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; + if (d2 < epsilon2) { + S = Math.log(w1 / w0) / rho; + i = function(t) { + return [ + ux0 + t * dx, + uy0 + t * dy, + w0 * Math.exp(rho * t * S) + ]; + }; + } else { + var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); + S = (r1 - r0) / rho; + i = function(t) { + var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); + return [ + ux0 + u * dx, + uy0 + u * dy, + w0 * coshr0 / cosh(rho * s + r0) + ]; + }; + } + i.duration = S * 1e3 * rho / Math.SQRT2; + return i; + } + zoom2.rho = function(_2) { + var _1 = Math.max(1e-3, +_2), _22 = _1 * _1, _4 = _22 * _22; + return zoomRho(_1, _22, _4); + }; + return zoom2; +}(Math.SQRT2, 2, 4); +function hsl(hue2) { + return function(start, end) { + var h = hue2((start = hsl$2(start)).h, (end = hsl$2(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.h = h(t); + start.s = s(t); + start.l = l(t); + start.opacity = opacity(t); + return start + ""; + }; + }; +} +const hsl$1 = hsl(hue$1); +var hslLong = hsl(nogamma); +function lab(start, end) { + var l = nogamma((start = lab$1(start)).l, (end = lab$1(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.l = l(t); + start.a = a(t); + start.b = b(t); + start.opacity = opacity(t); + return start + ""; + }; +} +function hcl(hue2) { + return function(start, end) { + var h = hue2((start = hcl$2(start)).h, (end = hcl$2(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.h = h(t); + start.c = c(t); + start.l = l(t); + start.opacity = opacity(t); + return start + ""; + }; + }; +} +const hcl$1 = hcl(hue$1); +var hclLong = hcl(nogamma); +function cubehelix(hue2) { + return function cubehelixGamma(y) { + y = +y; + function cubehelix2(start, end) { + var h = hue2((start = cubehelix$2(start)).h, (end = cubehelix$2(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); + return function(t) { + start.h = h(t); + start.s = s(t); + start.l = l(Math.pow(t, y)); + start.opacity = opacity(t); + return start + ""; + }; + } + cubehelix2.gamma = cubehelixGamma; + return cubehelix2; + }(1); +} +const cubehelix$1 = cubehelix(hue$1); +var cubehelixLong = cubehelix(nogamma); +function piecewise(interpolate2, values) { + if (values === void 0) values = interpolate2, interpolate2 = value; + var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n); + while (i < n) I[i] = interpolate2(v, v = values[++i]); + return function(t) { + var i2 = Math.max(0, Math.min(n - 1, Math.floor(t *= n))); + return I[i2](t - i2); + }; +} +function quantize(interpolator, n) { + var samples = new Array(n); + for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1)); + return samples; +} +const src = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ + __proto__: null, + interpolate: value, + interpolateArray: array, + interpolateBasis: basis$1, + interpolateBasisClosed: basisClosed, + interpolateCubehelix: cubehelix$1, + interpolateCubehelixLong: cubehelixLong, + interpolateDate: date, + interpolateDiscrete: discrete, + interpolateHcl: hcl$1, + interpolateHclLong: hclLong, + interpolateHsl: hsl$1, + interpolateHslLong: hslLong, + interpolateHue: hue, + interpolateLab: lab, + interpolateNumber: number, + interpolateNumberArray: numberArray, + interpolateObject: object, + interpolateRgb: rgb, + interpolateRgbBasis: rgbBasis, + interpolateRgbBasisClosed: rgbBasisClosed, + interpolateRound: round, + interpolateString: string, + interpolateTransformCss, + interpolateTransformSvg, + interpolateZoom: zoom, + piecewise, + quantize +}, Symbol.toStringTag, { value: "Module" })); +const require$$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src); +var flip_tree = function flipTree(node, size, opts) { + var tmp; + if (opts.swapXY) { + tmp = node.x0; + node.x0 = node.y0; + node.y0 = tmp; + tmp = node.x1; + node.x1 = node.y1; + node.y1 = tmp; + } + if (opts.flipX) { + tmp = node.x0; + node.x0 = size[0] - node.x1; + node.x1 = size[0] - tmp; + } + if (opts.flipY) { + tmp = node.y0; + node.y0 = size[1] - node.y1; + node.y1 = size[1] - tmp; + } + var children = node.children; + if (children) { + for (var i = 0; i < children.length; i++) { + flipTree(children[i], size, opts); + } + } +}; +var d3Hierarchy = require$$1; +var flipTree2 = flip_tree; +var partition$2 = function partition(entry, size, opts) { + var flipX = opts.flipX; + var flipY = opts.flipY; + var swapXY = opts.packing === "dice-slice"; + var top = opts.pad[flipY ? "bottom" : "top"]; + var left = opts.pad[flipX ? "right" : "left"]; + var right = opts.pad[flipX ? "left" : "right"]; + var bottom = opts.pad[flipY ? "top" : "bottom"]; + var tmp; + if (swapXY) { + tmp = left; + left = top; + top = tmp; + tmp = right; + right = bottom; + bottom = tmp; + } + var result = d3Hierarchy.treemap().tile(getTilingMethod(opts.packing, opts.squarifyratio)).paddingInner(opts.pad.inner).paddingLeft(left).paddingRight(right).paddingTop(top).paddingBottom(bottom).size( + swapXY ? [size[1], size[0]] : size + )(entry); + if (swapXY || flipX || flipY) { + flipTree2(result, size, { + swapXY, + flipX, + flipY + }); + } + return result; +}; +function getTilingMethod(key, squarifyratio) { + switch (key) { + case "squarify": + return d3Hierarchy.treemapSquarify.ratio(squarifyratio); + case "binary": + return d3Hierarchy.treemapBinary; + case "dice": + return d3Hierarchy.treemapDice; + case "slice": + return d3Hierarchy.treemapSlice; + default: + return d3Hierarchy.treemapSliceDice; + } +} +var Drawing$2 = drawingExports; +var Color$2 = colorExports; +var fill_one = function fillOne2(s, pt, trace, gd, fadedColor) { + var cdi = pt.data.data; + var ptNumber = cdi.i; + var color2 = fadedColor || cdi.color; + if (ptNumber >= 0) { + pt.i = cdi.i; + var marker2 = trace.marker; + if (marker2.pattern) { + if (!marker2.colors || !marker2.pattern.shape) { + marker2.color = color2; + pt.color = color2; + } + } else { + marker2.color = color2; + pt.color = color2; + } + Drawing$2.pointStyle(s, trace, gd, pt); + } else { + Color$2.fill(s, color2); + } +}; +var d3$5 = d3Exports; +var Color$1 = colorExports; +var Lib$5 = libExports; +var helpers$5 = helpers$6; +var resizeText$1 = uniform_text.resizeText; +var fillOne$1 = fill_one; +function style4(gd) { + var s = gd._fullLayout._treemaplayer.selectAll(".trace"); + resizeText$1(gd, s, "treemap"); + s.each(function(cd) { + var gTrace = d3$5.select(this); + var cd0 = cd[0]; + var trace = cd0.trace; + gTrace.style("opacity", trace.opacity); + gTrace.selectAll("path.surface").each(function(pt) { + d3$5.select(this).call(styleOne$3, pt, trace, gd, { + hovered: false + }); + }); + }); +} +function styleOne$3(s, pt, trace, gd, opts) { + var hovered = (opts || {}).hovered; + var cdi = pt.data.data; + var ptNumber = cdi.i; + var lineColor; + var lineWidth; + var fillColor = cdi.color; + var isRoot = helpers$5.isHierarchyRoot(pt); + var opacity = 1; + if (hovered) { + lineColor = trace._hovered.marker.line.color; + lineWidth = trace._hovered.marker.line.width; + } else { + if (isRoot && fillColor === trace.root.color) { + opacity = 100; + lineColor = "rgba(0,0,0,0)"; + lineWidth = 0; + } else { + lineColor = Lib$5.castOption(trace, ptNumber, "marker.line.color") || Color$1.defaultLine; + lineWidth = Lib$5.castOption(trace, ptNumber, "marker.line.width") || 0; + if (!trace._hasColorscale && !pt.onPathbar) { + var depthfade = trace.marker.depthfade; + if (depthfade) { + var fadedColor = Color$1.combine(Color$1.addOpacity(trace._backgroundColor, 0.75), fillColor); + var n; + if (depthfade === true) { + var maxDepth = helpers$5.getMaxDepth(trace); + if (isFinite(maxDepth)) { + if (helpers$5.isLeaf(pt)) { + n = 0; + } else { + n = trace._maxVisibleLayers - (pt.data.depth - trace._entryDepth); + } + } else { + n = pt.data.height + 1; + } + } else { + n = pt.data.depth - trace._entryDepth; + if (!trace._atRootLevel) n++; + } + if (n > 0) { + for (var i = 0; i < n; i++) { + var ratio = 0.5 * i / n; + fillColor = Color$1.combine(Color$1.addOpacity(fadedColor, ratio), fillColor); + } + } + } + } + } + } + s.call(fillOne$1, pt, trace, gd, fillColor).style("stroke-width", lineWidth).call(Color$1.stroke, lineColor).style("opacity", opacity); +} +var style_1$1 = { + style: style4, + styleOne: styleOne$3 +}; +var d3$4 = d3Exports; +var Registry = registry; +var appendArrayPointValue = helpers$J.appendArrayPointValue; +var Fx = fx$1; +var Lib$4 = libExports; +var Events = events; +var helpers$4 = helpers$6; +var pieHelpers = helpers$F; +var formatValue = pieHelpers.formatPieValue; +var fx = function attachFxHandlers(sliceTop, entry, gd, cd, opts) { + var cd0 = cd[0]; + var trace = cd0.trace; + var hierarchy2 = cd0.hierarchy; + var isSunburst = trace.type === "sunburst"; + var isTreemapOrIcicle = trace.type === "treemap" || trace.type === "icicle"; + if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false; + if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false; + var onMouseOver = function(pt) { + var fullLayoutNow = gd._fullLayout; + if (gd._dragging || fullLayoutNow.hovermode === false) return; + var traceNow = gd._fullData[trace.index]; + var cdi = pt.data.data; + var ptNumber = cdi.i; + var isRoot = helpers$4.isHierarchyRoot(pt); + var parent = helpers$4.getParent(hierarchy2, pt); + var val = helpers$4.getValue(pt); + var _cast = function(astr) { + return Lib$4.castOption(traceNow, ptNumber, astr); + }; + var hovertemplate = _cast("hovertemplate"); + var hoverinfo = Fx.castHoverinfo(traceNow, fullLayoutNow, ptNumber); + var separators = fullLayoutNow.separators; + var eventData5; + if (hovertemplate || hoverinfo && hoverinfo !== "none" && hoverinfo !== "skip") { + var hoverCenterX; + var hoverCenterY; + if (isSunburst) { + hoverCenterX = cd0.cx + pt.pxmid[0] * (1 - pt.rInscribed); + hoverCenterY = cd0.cy + pt.pxmid[1] * (1 - pt.rInscribed); + } + if (isTreemapOrIcicle) { + hoverCenterX = pt._hoverX; + hoverCenterY = pt._hoverY; + } + var hoverPt = {}; + var parts = []; + var thisText = []; + var hasFlag = function(flag) { + return parts.indexOf(flag) !== -1; + }; + if (hoverinfo) { + parts = hoverinfo === "all" ? traceNow._module.attributes.hoverinfo.flags : hoverinfo.split("+"); + } + hoverPt.label = cdi.label; + if (hasFlag("label") && hoverPt.label) thisText.push(hoverPt.label); + if (cdi.hasOwnProperty("v")) { + hoverPt.value = cdi.v; + hoverPt.valueLabel = formatValue(hoverPt.value, separators); + if (hasFlag("value")) thisText.push(hoverPt.valueLabel); + } + hoverPt.currentPath = pt.currentPath = helpers$4.getPath(pt.data); + if (hasFlag("current path") && !isRoot) { + thisText.push(hoverPt.currentPath); + } + var tx; + var allPercents = []; + var insertPercent = function() { + if (allPercents.indexOf(tx) === -1) { + thisText.push(tx); + allPercents.push(tx); + } + }; + hoverPt.percentParent = pt.percentParent = val / helpers$4.getValue(parent); + hoverPt.parent = pt.parentString = helpers$4.getPtLabel(parent); + if (hasFlag("percent parent")) { + tx = helpers$4.formatPercent(hoverPt.percentParent, separators) + " of " + hoverPt.parent; + insertPercent(); + } + hoverPt.percentEntry = pt.percentEntry = val / helpers$4.getValue(entry); + hoverPt.entry = pt.entry = helpers$4.getPtLabel(entry); + if (hasFlag("percent entry") && !isRoot && !pt.onPathbar) { + tx = helpers$4.formatPercent(hoverPt.percentEntry, separators) + " of " + hoverPt.entry; + insertPercent(); + } + hoverPt.percentRoot = pt.percentRoot = val / helpers$4.getValue(hierarchy2); + hoverPt.root = pt.root = helpers$4.getPtLabel(hierarchy2); + if (hasFlag("percent root") && !isRoot) { + tx = helpers$4.formatPercent(hoverPt.percentRoot, separators) + " of " + hoverPt.root; + insertPercent(); + } + hoverPt.text = _cast("hovertext") || _cast("text"); + if (hasFlag("text")) { + tx = hoverPt.text; + if (Lib$4.isValidTextValue(tx)) thisText.push(tx); + } + eventData5 = [makeEventData(pt, traceNow, opts.eventDataKeys)]; + var hoverItems = { + trace: traceNow, + y: hoverCenterY, + _x0: pt._x0, + _x1: pt._x1, + _y0: pt._y0, + _y1: pt._y1, + text: thisText.join("
"), + name: hovertemplate || hasFlag("name") ? traceNow.name : void 0, + color: _cast("hoverlabel.bgcolor") || cdi.color, + borderColor: _cast("hoverlabel.bordercolor"), + fontFamily: _cast("hoverlabel.font.family"), + fontSize: _cast("hoverlabel.font.size"), + fontColor: _cast("hoverlabel.font.color"), + fontWeight: _cast("hoverlabel.font.weight"), + fontStyle: _cast("hoverlabel.font.style"), + fontVariant: _cast("hoverlabel.font.variant"), + nameLength: _cast("hoverlabel.namelength"), + textAlign: _cast("hoverlabel.align"), + hovertemplate, + hovertemplateLabels: hoverPt, + eventData: eventData5 + }; + if (isSunburst) { + hoverItems.x0 = hoverCenterX - pt.rInscribed * pt.rpx1; + hoverItems.x1 = hoverCenterX + pt.rInscribed * pt.rpx1; + hoverItems.idealAlign = pt.pxmid[0] < 0 ? "left" : "right"; + } + if (isTreemapOrIcicle) { + hoverItems.x = hoverCenterX; + hoverItems.idealAlign = hoverCenterX < 0 ? "left" : "right"; + } + var bbox = []; + Fx.loneHover(hoverItems, { + container: fullLayoutNow._hoverlayer.node(), + outerContainer: fullLayoutNow._paper.node(), + gd, + inOut_bbox: bbox + }); + eventData5[0].bbox = bbox[0]; + trace._hasHoverLabel = true; + } + if (isTreemapOrIcicle) { + var slice2 = sliceTop.select("path.surface"); + opts.styleOne(slice2, pt, traceNow, gd, { + hovered: true + }); + } + trace._hasHoverEvent = true; + gd.emit("plotly_hover", { + points: eventData5 || [makeEventData(pt, traceNow, opts.eventDataKeys)], + event: d3$4.event + }); + }; + var onMouseOut = function(evt) { + var fullLayoutNow = gd._fullLayout; + var traceNow = gd._fullData[trace.index]; + var pt = d3$4.select(this).datum(); + if (trace._hasHoverEvent) { + evt.originalEvent = d3$4.event; + gd.emit("plotly_unhover", { + points: [makeEventData(pt, traceNow, opts.eventDataKeys)], + event: d3$4.event + }); + trace._hasHoverEvent = false; + } + if (trace._hasHoverLabel) { + Fx.loneUnhover(fullLayoutNow._hoverlayer.node()); + trace._hasHoverLabel = false; + } + if (isTreemapOrIcicle) { + var slice2 = sliceTop.select("path.surface"); + opts.styleOne(slice2, pt, traceNow, gd, { + hovered: false + }); + } + }; + var onClick2 = function(pt) { + var fullLayoutNow = gd._fullLayout; + var traceNow = gd._fullData[trace.index]; + var noTransition = isSunburst && (helpers$4.isHierarchyRoot(pt) || helpers$4.isLeaf(pt)); + var id = helpers$4.getPtId(pt); + var nextEntry = helpers$4.isEntry(pt) ? helpers$4.findEntryWithChild(hierarchy2, id) : helpers$4.findEntryWithLevel(hierarchy2, id); + var nextLevel = helpers$4.getPtId(nextEntry); + var typeClickEvtData = { + points: [makeEventData(pt, traceNow, opts.eventDataKeys)], + event: d3$4.event + }; + if (!noTransition) typeClickEvtData.nextLevel = nextLevel; + var clickVal = Events.triggerHandler(gd, "plotly_" + trace.type + "click", typeClickEvtData); + if (clickVal !== false && fullLayoutNow.hovermode) { + gd._hoverdata = [makeEventData(pt, traceNow, opts.eventDataKeys)]; + Fx.click(gd, d3$4.event); + } + if (noTransition) return; + if (clickVal === false) return; + if (gd._dragging) return; + if (gd._transitioning) return; + Registry.call("_storeDirectGUIEdit", traceNow, fullLayoutNow._tracePreGUI[traceNow.uid], { + level: traceNow.level + }); + var frame = { + data: [{ level: nextLevel }], + traces: [trace.index] + }; + var animOpts = { + frame: { + redraw: false, + duration: opts.transitionTime + }, + transition: { + duration: opts.transitionTime, + easing: opts.transitionEasing + }, + mode: "immediate", + fromcurrent: true + }; + Fx.loneUnhover(fullLayoutNow._hoverlayer.node()); + Registry.call("animate", gd, frame, animOpts); + }; + sliceTop.on("mouseover", onMouseOver); + sliceTop.on("mouseout", onMouseOut); + sliceTop.on("click", onClick2); +}; +function makeEventData(pt, trace, keys) { + var cdi = pt.data.data; + var out = { + curveNumber: trace.index, + pointNumber: cdi.i, + data: trace._input, + fullData: trace + // TODO more things like 'children', 'siblings', 'hierarchy? + }; + for (var i = 0; i < keys.length; i++) { + var key = keys[i]; + if (key in pt) out[key] = pt[key]; + } + if ("parentString" in pt && !helpers$4.isHierarchyRoot(pt)) out.parent = pt.parentString; + appendArrayPointValue(out, trace, cdi.i); + return out; +} +var d3$3 = d3Exports; +var Lib$3 = libExports; +var Drawing$1 = drawingExports; +var svgTextUtils$1 = svg_text_utils; +var partition$1 = partition$2; +var styleOne$2 = style_1$1.styleOne; +var constants$2 = constants$4; +var helpers$3 = helpers$6; +var attachFxHandlers$1 = fx; +var onPathbar$1 = true; +var draw_ancestors = function drawAncestors(gd, cd, entry, slices, opts) { + var barDifY = opts.barDifY; + var width = opts.width; + var height = opts.height; + var viewX = opts.viewX; + var viewY = opts.viewY; + var pathSlice = opts.pathSlice; + var toMoveInsideSlice = opts.toMoveInsideSlice; + var strTransform = opts.strTransform; + var hasTransition2 = opts.hasTransition; + var handleSlicesExit = opts.handleSlicesExit; + var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator; + var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator; + var refRect = {}; + var isStatic = gd._context.staticPlot; + var fullLayout = gd._fullLayout; + var cd0 = cd[0]; + var trace = cd0.trace; + var hierarchy2 = cd0.hierarchy; + var eachWidth = width / trace._entryDepth; + var pathIds = helpers$3.listPath(entry.data, "id"); + var sliceData = partition$1(hierarchy2.copy(), [width, height], { + packing: "dice", + pad: { + inner: 0, + top: 0, + left: 0, + right: 0, + bottom: 0 + } + }).descendants(); + sliceData = sliceData.filter(function(pt) { + var level = pathIds.indexOf(pt.data.id); + if (level === -1) return false; + pt.x0 = eachWidth * level; + pt.x1 = eachWidth * (level + 1); + pt.y0 = barDifY; + pt.y1 = barDifY + height; + pt.onPathbar = true; + return true; + }); + sliceData.reverse(); + slices = slices.data(sliceData, helpers$3.getPtId); + slices.enter().append("g").classed("pathbar", true); + handleSlicesExit(slices, onPathbar$1, refRect, [width, height], pathSlice); + slices.order(); + var updateSlices = slices; + if (hasTransition2) { + updateSlices = updateSlices.transition().each("end", function() { + var sliceTop = d3$3.select(this); + helpers$3.setSliceCursor(sliceTop, gd, { + hideOnRoot: false, + hideOnLeaves: false, + isTransitioning: false + }); + }); + } + updateSlices.each(function(pt) { + pt._x0 = viewX(pt.x0); + pt._x1 = viewX(pt.x1); + pt._y0 = viewY(pt.y0); + pt._y1 = viewY(pt.y1); + pt._hoverX = viewX(pt.x1 - Math.min(width, height) / 2); + pt._hoverY = viewY(pt.y1 - height / 2); + var sliceTop = d3$3.select(this); + var slicePath = Lib$3.ensureSingle(sliceTop, "path", "surface", function(s) { + s.style("pointer-events", isStatic ? "none" : "all"); + }); + if (hasTransition2) { + slicePath.transition().attrTween("d", function(pt2) { + var interp = makeUpdateSliceInterpolator(pt2, onPathbar$1, refRect, [width, height]); + return function(t) { + return pathSlice(interp(t)); + }; + }); + } else { + slicePath.attr("d", pathSlice); + } + sliceTop.call(attachFxHandlers$1, entry, gd, cd, { + styleOne: styleOne$2, + eventDataKeys: constants$2.eventDataKeys, + transitionTime: constants$2.CLICK_TRANSITION_TIME, + transitionEasing: constants$2.CLICK_TRANSITION_EASING + }).call(helpers$3.setSliceCursor, gd, { + hideOnRoot: false, + hideOnLeaves: false, + isTransitioning: gd._transitioning + }); + slicePath.call(styleOne$2, pt, trace, gd, { + hovered: false + }); + pt._text = (helpers$3.getPtLabel(pt) || "").split("
").join(" ") || ""; + var sliceTextGroup = Lib$3.ensureSingle(sliceTop, "g", "slicetext"); + var sliceText = Lib$3.ensureSingle(sliceTextGroup, "text", "", function(s) { + s.attr("data-notex", 1); + }); + var font2 = Lib$3.ensureUniformFontSize(gd, helpers$3.determineTextFont(trace, pt, fullLayout.font, { + onPathbar: true + })); + sliceText.text(pt._text || " ").classed("slicetext", true).attr("text-anchor", "start").call(Drawing$1.font, font2).call(svgTextUtils$1.convertToTspans, gd); + pt.textBB = Drawing$1.bBox(sliceText.node()); + pt.transform = toMoveInsideSlice(pt, { + fontSize: font2.size, + onPathbar: true + }); + pt.transform.fontSize = font2.size; + if (hasTransition2) { + sliceText.transition().attrTween("transform", function(pt2) { + var interp = makeUpdateTextInterpolator(pt2, onPathbar$1, refRect, [width, height]); + return function(t) { + return strTransform(interp(t)); + }; + }); + } else { + sliceText.attr("transform", strTransform(pt)); + } + }); +}; +var d3$2 = d3Exports; +var interpolate = require$$2.interpolate; +var helpers$2 = helpers$6; +var Lib$2 = libExports; +var TEXTPAD = constants$f.TEXTPAD; +var barPlot = plot_1$1; +var toMoveInsideBar = barPlot.toMoveInsideBar; +var uniformText$1 = uniform_text; +var recordMinTextSize = uniformText$1.recordMinTextSize; +var constants$1 = constants$4; +var drawAncestors2 = draw_ancestors; +function getKey(pt) { + return helpers$2.isHierarchyRoot(pt) ? "" : ( + // don't use the dummyId + helpers$2.getPtId(pt) + ); +} +var plot_one = function plotOne(gd, cd, element, transitionOpts, drawDescendants3) { + var fullLayout = gd._fullLayout; + var cd0 = cd[0]; + var trace = cd0.trace; + var type = trace.type; + var isIcicle = type === "icicle"; + var hierarchy2 = cd0.hierarchy; + var entry = helpers$2.findEntryWithLevel(hierarchy2, trace.level); + var gTrace = d3$2.select(element); + var selAncestors = gTrace.selectAll("g.pathbar"); + var selDescendants = gTrace.selectAll("g.slice"); + if (!entry) { + selAncestors.remove(); + selDescendants.remove(); + return; + } + var isRoot = helpers$2.isHierarchyRoot(entry); + var hasTransition2 = !fullLayout.uniformtext.mode && helpers$2.hasTransition(transitionOpts); + var maxDepth = helpers$2.getMaxDepth(trace); + var hasVisibleDepth = function(pt) { + return pt.data.depth - entry.data.depth < maxDepth; + }; + var gs = fullLayout._size; + var domain2 = trace.domain; + var vpw = gs.w * (domain2.x[1] - domain2.x[0]); + var vph = gs.h * (domain2.y[1] - domain2.y[0]); + var barW = vpw; + var barH = trace.pathbar.thickness; + var barPad = trace.marker.line.width + constants$1.gapWithPathbar; + var barDifY = !trace.pathbar.visible ? 0 : trace.pathbar.side.indexOf("bottom") > -1 ? vph + barPad : -(barH + barPad); + var pathbarOrigin = { + x0: barW, + // slide to the right + x1: barW, + y0: barDifY, + y1: barDifY + barH + }; + var findClosestEdge = function(pt, ref2, size) { + var e = trace.tiling.pad; + var isLeftOfRect = function(x) { + return x - e <= ref2.x0; + }; + var isRightOfRect = function(x) { + return x + e >= ref2.x1; + }; + var isBottomOfRect = function(y) { + return y - e <= ref2.y0; + }; + var isTopOfRect = function(y) { + return y + e >= ref2.y1; + }; + if (pt.x0 === ref2.x0 && pt.x1 === ref2.x1 && pt.y0 === ref2.y0 && pt.y1 === ref2.y1) { + return { + x0: pt.x0, + x1: pt.x1, + y0: pt.y0, + y1: pt.y1 + }; + } + return { + x0: isLeftOfRect(pt.x0 - e) ? 0 : isRightOfRect(pt.x0 - e) ? size[0] : pt.x0, + x1: isLeftOfRect(pt.x1 + e) ? 0 : isRightOfRect(pt.x1 + e) ? size[0] : pt.x1, + y0: isBottomOfRect(pt.y0 - e) ? 0 : isTopOfRect(pt.y0 - e) ? size[1] : pt.y0, + y1: isBottomOfRect(pt.y1 + e) ? 0 : isTopOfRect(pt.y1 + e) ? size[1] : pt.y1 + }; + }; + var prevEntry = null; + var prevLookupPathbar = {}; + var prevLookupSlices = {}; + var nextOfPrevEntry = null; + var getPrev = function(pt, onPathbar2) { + return onPathbar2 ? prevLookupPathbar[getKey(pt)] : prevLookupSlices[getKey(pt)]; + }; + var getOrigin = function(pt, onPathbar2, refRect, size) { + if (onPathbar2) { + return prevLookupPathbar[getKey(hierarchy2)] || pathbarOrigin; + } else { + var ref2 = prevLookupSlices[trace.level] || refRect; + if (hasVisibleDepth(pt)) { + return findClosestEdge(pt, ref2, size); + } + } + return {}; + }; + if (cd0.hasMultipleRoots && isRoot) { + maxDepth++; + } + trace._maxDepth = maxDepth; + trace._backgroundColor = fullLayout.paper_bgcolor; + trace._entryDepth = entry.data.depth; + trace._atRootLevel = isRoot; + var cenX = -vpw / 2 + gs.l + gs.w * (domain2.x[1] + domain2.x[0]) / 2; + var cenY = -vph / 2 + gs.t + gs.h * (1 - (domain2.y[1] + domain2.y[0]) / 2); + var viewMapX = function(x) { + return cenX + x; + }; + var viewMapY = function(y) { + return cenY + y; + }; + var barY0 = viewMapY(0); + var barX0 = viewMapX(0); + var viewBarX = function(x) { + return barX0 + x; + }; + var viewBarY = function(y) { + return barY0 + y; + }; + function pos(x, y) { + return x + "," + y; + } + var xStart = viewBarX(0); + var limitX0 = function(p) { + p.x = Math.max(xStart, p.x); + }; + var edgeshape = trace.pathbar.edgeshape; + var pathAncestor = function(d) { + var _x0 = viewBarX(Math.max(Math.min(d.x0, d.x0), 0)); + var _x1 = viewBarX(Math.min(Math.max(d.x1, d.x1), barW)); + var _y0 = viewBarY(d.y0); + var _y1 = viewBarY(d.y1); + var halfH = barH / 2; + var pL = {}; + var pR = {}; + pL.x = _x0; + pR.x = _x1; + pL.y = pR.y = (_y0 + _y1) / 2; + var pA = { x: _x0, y: _y0 }; + var pB = { x: _x1, y: _y0 }; + var pC = { x: _x1, y: _y1 }; + var pD = { x: _x0, y: _y1 }; + if (edgeshape === ">") { + pA.x -= halfH; + pB.x -= halfH; + pC.x -= halfH; + pD.x -= halfH; + } else if (edgeshape === "/") { + pC.x -= halfH; + pD.x -= halfH; + pL.x -= halfH / 2; + pR.x -= halfH / 2; + } else if (edgeshape === "\\") { + pA.x -= halfH; + pB.x -= halfH; + pL.x -= halfH / 2; + pR.x -= halfH / 2; + } else if (edgeshape === "<") { + pL.x -= halfH; + pR.x -= halfH; + } + limitX0(pA); + limitX0(pD); + limitX0(pL); + limitX0(pB); + limitX0(pC); + limitX0(pR); + return "M" + pos(pA.x, pA.y) + "L" + pos(pB.x, pB.y) + "L" + pos(pR.x, pR.y) + "L" + pos(pC.x, pC.y) + "L" + pos(pD.x, pD.y) + "L" + pos(pL.x, pL.y) + "Z"; + }; + var pad2 = trace[isIcicle ? "tiling" : "marker"].pad; + var hasFlag = function(f) { + return trace.textposition.indexOf(f) !== -1; + }; + var hasTop = hasFlag("top"); + var hasLeft = hasFlag("left"); + var hasRight = hasFlag("right"); + var hasBottom = hasFlag("bottom"); + var pathDescendant = function(d) { + var _x0 = viewMapX(d.x0); + var _x1 = viewMapX(d.x1); + var _y0 = viewMapY(d.y0); + var _y1 = viewMapY(d.y1); + var dx = _x1 - _x0; + var dy = _y1 - _y0; + if (!dx || !dy) return ""; + var cornerradius = trace.marker.cornerradius || 0; + var r = Math.min(cornerradius, dx / 2, dy / 2); + if (r && d.data && d.data.data && d.data.data.label) { + if (hasTop) r = Math.min(r, pad2.t); + if (hasLeft) r = Math.min(r, pad2.l); + if (hasRight) r = Math.min(r, pad2.r); + if (hasBottom) r = Math.min(r, pad2.b); + } + var arc2 = function(rx, ry) { + return r ? "a" + pos(r, r) + " 0 0 1 " + pos(rx, ry) : ""; + }; + return "M" + pos(_x0, _y0 + r) + arc2(r, -r) + "L" + pos(_x1 - r, _y0) + arc2(r, r) + "L" + pos(_x1, _y1 - r) + arc2(-r, r) + "L" + pos(_x0 + r, _y1) + arc2(-r, -r) + "Z"; + }; + var toMoveInsideSlice = function(pt, opts) { + var x0 = pt.x0; + var x1 = pt.x1; + var y0 = pt.y0; + var y1 = pt.y1; + var textBB = pt.textBB; + var _hasTop = hasTop || opts.isHeader && !hasBottom; + var anchor = _hasTop ? "start" : hasBottom ? "end" : "middle"; + var _hasRight = hasFlag("right"); + var _hasLeft = hasFlag("left") || opts.onPathbar; + var leftToRight = _hasLeft ? -1 : _hasRight ? 1 : 0; + if (opts.isHeader) { + x0 += (isIcicle ? pad2 : pad2.l) - TEXTPAD; + x1 -= (isIcicle ? pad2 : pad2.r) - TEXTPAD; + if (x0 >= x1) { + var mid = (x0 + x1) / 2; + x0 = mid; + x1 = mid; + } + var limY; + if (hasBottom) { + limY = y1 - (isIcicle ? pad2 : pad2.b); + if (y0 < limY && limY < y1) y0 = limY; + } else { + limY = y0 + (isIcicle ? pad2 : pad2.t); + if (y0 < limY && limY < y1) y1 = limY; + } + } + var transform = toMoveInsideBar(x0, x1, y0, y1, textBB, { + isHorizontal: false, + constrained: true, + angle: 0, + anchor, + leftToRight + }); + transform.fontSize = opts.fontSize; + transform.targetX = viewMapX(transform.targetX); + transform.targetY = viewMapY(transform.targetY); + if (isNaN(transform.targetX) || isNaN(transform.targetY)) { + return {}; + } + if (x0 !== x1 && y0 !== y1) { + recordMinTextSize(trace.type, transform, fullLayout); + } + return { + scale: transform.scale, + rotate: transform.rotate, + textX: transform.textX, + textY: transform.textY, + anchorX: transform.anchorX, + anchorY: transform.anchorY, + targetX: transform.targetX, + targetY: transform.targetY + }; + }; + var interpFromParent = function(pt, onPathbar2) { + var parentPrev; + var i = 0; + var Q = pt; + while (!parentPrev && i < maxDepth) { + i++; + Q = Q.parent; + if (Q) { + parentPrev = getPrev(Q, onPathbar2); + } else i = maxDepth; + } + return parentPrev || {}; + }; + var makeExitSliceInterpolator = function(pt, onPathbar2, refRect, size) { + var prev = getPrev(pt, onPathbar2); + var next; + if (onPathbar2) { + next = pathbarOrigin; + } else { + var entryPrev = getPrev(entry, onPathbar2); + if (entryPrev) { + next = findClosestEdge(pt, entryPrev, size); + } else { + next = {}; + } + } + return interpolate(prev, next); + }; + var makeUpdateSliceInterpolator = function(pt, onPathbar2, refRect, size, opts) { + var prev0 = getPrev(pt, onPathbar2); + var prev; + if (prev0) { + prev = prev0; + } else { + if (onPathbar2) { + prev = pathbarOrigin; + } else { + if (prevEntry) { + if (pt.parent) { + var ref2 = nextOfPrevEntry || refRect; + if (ref2 && !onPathbar2) { + prev = findClosestEdge(pt, ref2, size); + } else { + prev = {}; + Lib$2.extendFlat(prev, interpFromParent(pt, onPathbar2)); + } + } else { + prev = Lib$2.extendFlat({}, pt); + if (isIcicle) { + if (opts.orientation === "h") { + if (opts.flipX) prev.x0 = pt.x1; + else prev.x1 = 0; + } else { + if (opts.flipY) prev.y0 = pt.y1; + else prev.y1 = 0; + } + } + } + } else { + prev = {}; + } + } + } + return interpolate(prev, { + x0: pt.x0, + x1: pt.x1, + y0: pt.y0, + y1: pt.y1 + }); + }; + var makeUpdateTextInterpolator = function(pt, onPathbar2, refRect, size) { + var prev0 = getPrev(pt, onPathbar2); + var prev = {}; + var origin = getOrigin(pt, onPathbar2, refRect, size); + Lib$2.extendFlat(prev, { + transform: toMoveInsideSlice({ + x0: origin.x0, + x1: origin.x1, + y0: origin.y0, + y1: origin.y1, + textBB: pt.textBB, + _text: pt._text + }, { + isHeader: helpers$2.isHeader(pt, trace) + }) + }); + if (prev0) { + prev = prev0; + } else { + if (pt.parent) { + Lib$2.extendFlat(prev, interpFromParent(pt, onPathbar2)); + } + } + var transform = pt.transform; + if (pt.x0 !== pt.x1 && pt.y0 !== pt.y1) { + recordMinTextSize(trace.type, transform, fullLayout); + } + return interpolate(prev, { + transform: { + scale: transform.scale, + rotate: transform.rotate, + textX: transform.textX, + textY: transform.textY, + anchorX: transform.anchorX, + anchorY: transform.anchorY, + targetX: transform.targetX, + targetY: transform.targetY + } + }); + }; + var handleSlicesExit = function(slices, onPathbar2, refRect, size, pathSlice) { + var width = size[0]; + var height = size[1]; + if (hasTransition2) { + slices.exit().transition().each(function() { + var sliceTop = d3$2.select(this); + var slicePath = sliceTop.select("path.surface"); + slicePath.transition().attrTween("d", function(pt2) { + var interp = makeExitSliceInterpolator(pt2, onPathbar2, refRect, [width, height]); + return function(t) { + return pathSlice(interp(t)); + }; + }); + var sliceTextGroup = sliceTop.select("g.slicetext"); + sliceTextGroup.attr("opacity", 0); + }).remove(); + } else { + slices.exit().remove(); + } + }; + var strTransform = function(d) { + var transform = d.transform; + if (d.x0 !== d.x1 && d.y0 !== d.y1) { + recordMinTextSize(trace.type, transform, fullLayout); + } + return Lib$2.getTextTransform({ + textX: transform.textX, + textY: transform.textY, + anchorX: transform.anchorX, + anchorY: transform.anchorY, + targetX: transform.targetX, + targetY: transform.targetY, + scale: transform.scale, + rotate: transform.rotate + }); + }; + if (hasTransition2) { + selAncestors.each(function(pt) { + prevLookupPathbar[getKey(pt)] = { + x0: pt.x0, + x1: pt.x1, + y0: pt.y0, + y1: pt.y1 + }; + if (pt.transform) { + prevLookupPathbar[getKey(pt)].transform = { + textX: pt.transform.textX, + textY: pt.transform.textY, + anchorX: pt.transform.anchorX, + anchorY: pt.transform.anchorY, + targetX: pt.transform.targetX, + targetY: pt.transform.targetY, + scale: pt.transform.scale, + rotate: pt.transform.rotate + }; + } + }); + selDescendants.each(function(pt) { + prevLookupSlices[getKey(pt)] = { + x0: pt.x0, + x1: pt.x1, + y0: pt.y0, + y1: pt.y1 + }; + if (pt.transform) { + prevLookupSlices[getKey(pt)].transform = { + textX: pt.transform.textX, + textY: pt.transform.textY, + anchorX: pt.transform.anchorX, + anchorY: pt.transform.anchorY, + targetX: pt.transform.targetX, + targetY: pt.transform.targetY, + scale: pt.transform.scale, + rotate: pt.transform.rotate + }; + } + if (!prevEntry && helpers$2.isEntry(pt)) { + prevEntry = pt; + } + }); + } + nextOfPrevEntry = drawDescendants3(gd, cd, entry, selDescendants, { + width: vpw, + height: vph, + viewX: viewMapX, + viewY: viewMapY, + pathSlice: pathDescendant, + toMoveInsideSlice, + prevEntry, + makeUpdateSliceInterpolator, + makeUpdateTextInterpolator, + handleSlicesExit, + hasTransition: hasTransition2, + strTransform + }); + if (trace.pathbar.visible) { + drawAncestors2(gd, cd, entry, selAncestors, { + barDifY, + width: barW, + height: barH, + viewX: viewBarX, + viewY: viewBarY, + pathSlice: pathAncestor, + toMoveInsideSlice, + makeUpdateSliceInterpolator, + makeUpdateTextInterpolator, + handleSlicesExit, + hasTransition: hasTransition2, + strTransform + }); + } else { + selAncestors.remove(); + } +}; +var d3$1 = d3Exports; +var helpers$1 = helpers$6; +var uniformText = uniform_text; +var clearMinTextSize = uniformText.clearMinTextSize; +var resizeText = style_1$2.resizeText; +var plotOne2 = plot_one; +var draw$1 = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback, opts) { + var type = opts.type; + var drawDescendants3 = opts.drawDescendants; + var fullLayout = gd._fullLayout; + var layer = fullLayout["_" + type + "layer"]; + var join, onComplete; + var isFullReplot = !transitionOpts; + clearMinTextSize(type, fullLayout); + join = layer.selectAll("g.trace." + type).data(cdmodule, function(cd) { + return cd[0].trace.uid; + }); + join.enter().append("g").classed("trace", true).classed(type, true); + join.order(); + if (!fullLayout.uniformtext.mode && helpers$1.hasTransition(transitionOpts)) { + if (makeOnCompleteCallback) { + onComplete = makeOnCompleteCallback(); + } + var transition2 = d3$1.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { + onComplete && onComplete(); + }).each("interrupt", function() { + onComplete && onComplete(); + }); + transition2.each(function() { + layer.selectAll("g.trace").each(function(cd) { + plotOne2(gd, cd, this, transitionOpts, drawDescendants3); + }); + }); + } else { + join.each(function(cd) { + plotOne2(gd, cd, this, transitionOpts, drawDescendants3); + }); + if (fullLayout.uniformtext.mode) { + resizeText(gd, layer.selectAll(".trace"), type); + } + } + if (isFullReplot) { + join.exit().remove(); + } +}; +var plot$1 = {}; +var Color = colorExports; +var Lib$1 = libExports; +uniform_text.resizeText; +var fillOne3 = fill_one; +function styleOne$1(s, pt, trace, gd) { + var cdi = pt.data.data; + var isLeaf = !pt.children; + var ptNumber = cdi.i; + var lineColor = Lib$1.castOption(trace, ptNumber, "marker.line.color") || Color.defaultLine; + var lineWidth = Lib$1.castOption(trace, ptNumber, "marker.line.width") || 0; + s.call(fillOne3, pt, trace, gd).style("stroke-width", lineWidth).call(Color.stroke, lineColor).style("opacity", isLeaf ? trace.leaf.opacity : null); +} +var style_1 = { + styleOne: styleOne$1 +}; +(function(exports2) { + var d32 = d3Exports; + var d3Hierarchy2 = require$$1; + var interpolate2 = require$$2.interpolate; + var Drawing2 = drawingExports; + var Lib2 = libExports; + var svgTextUtils2 = svg_text_utils; + var uniformText2 = uniform_text; + var recordMinTextSize2 = uniformText2.recordMinTextSize; + var clearMinTextSize2 = uniformText2.clearMinTextSize; + var piePlot = plot_1; + var getRotationAngle = helpers$F.getRotationAngle; + var computeTransform2 = piePlot.computeTransform; + var transformInsideText2 = piePlot.transformInsideText; + var styleOne3 = style_1.styleOne; + var resizeText2 = style_1$2.resizeText; + var attachFxHandlers3 = fx; + var constants2 = constants$6; + var helpers2 = helpers$6; + exports2.plot = function(gd, cdmodule, transitionOpts, makeOnCompleteCallback) { + var fullLayout = gd._fullLayout; + var layer = fullLayout._sunburstlayer; + var join, onComplete; + var isFullReplot = !transitionOpts; + var hasTransition2 = !fullLayout.uniformtext.mode && helpers2.hasTransition(transitionOpts); + clearMinTextSize2("sunburst", fullLayout); + join = layer.selectAll("g.trace.sunburst").data(cdmodule, function(cd) { + return cd[0].trace.uid; + }); + join.enter().append("g").classed("trace", true).classed("sunburst", true).attr("stroke-linejoin", "round"); + join.order(); + if (hasTransition2) { + if (makeOnCompleteCallback) { + onComplete = makeOnCompleteCallback(); + } + var transition2 = d32.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { + onComplete && onComplete(); + }).each("interrupt", function() { + onComplete && onComplete(); + }); + transition2.each(function() { + layer.selectAll("g.trace").each(function(cd) { + plotOne3(gd, cd, this, transitionOpts); + }); + }); + } else { + join.each(function(cd) { + plotOne3(gd, cd, this, transitionOpts); + }); + if (fullLayout.uniformtext.mode) { + resizeText2(gd, fullLayout._sunburstlayer.selectAll(".trace"), "sunburst"); + } + } + if (isFullReplot) { + join.exit().remove(); + } + }; + function plotOne3(gd, cd, element, transitionOpts) { + var isStatic = gd._context.staticPlot; + var fullLayout = gd._fullLayout; + var hasTransition2 = !fullLayout.uniformtext.mode && helpers2.hasTransition(transitionOpts); + var gTrace = d32.select(element); + var slices = gTrace.selectAll("g.slice"); + var cd0 = cd[0]; + var trace = cd0.trace; + var hierarchy2 = cd0.hierarchy; + var entry = helpers2.findEntryWithLevel(hierarchy2, trace.level); + var maxDepth = helpers2.getMaxDepth(trace); + var gs = fullLayout._size; + var domain2 = trace.domain; + var vpw = gs.w * (domain2.x[1] - domain2.x[0]); + var vph = gs.h * (domain2.y[1] - domain2.y[0]); + var rMax = 0.5 * Math.min(vpw, vph); + var cx = cd0.cx = gs.l + gs.w * (domain2.x[1] + domain2.x[0]) / 2; + var cy = cd0.cy = gs.t + gs.h * (1 - domain2.y[0]) - vph / 2; + if (!entry) { + return slices.remove(); + } + var prevEntry = null; + var prevLookup = {}; + if (hasTransition2) { + slices.each(function(pt) { + prevLookup[helpers2.getPtId(pt)] = { + rpx0: pt.rpx0, + rpx1: pt.rpx1, + x0: pt.x0, + x1: pt.x1, + transform: pt.transform + }; + if (!prevEntry && helpers2.isEntry(pt)) { + prevEntry = pt; + } + }); + } + var sliceData = partition3(entry).descendants(); + var maxHeight = entry.height + 1; + var yOffset = 0; + var cutoff = maxDepth; + if (cd0.hasMultipleRoots && helpers2.isHierarchyRoot(entry)) { + sliceData = sliceData.slice(1); + maxHeight -= 1; + yOffset = 1; + cutoff += 1; + } + sliceData = sliceData.filter(function(pt) { + return pt.y1 <= cutoff; + }); + var baseX = getRotationAngle(trace.rotation); + if (baseX) { + sliceData.forEach(function(pt) { + pt.x0 += baseX; + pt.x1 += baseX; + }); + } + var maxY2 = Math.min(maxHeight, maxDepth); + var y2rpx = function(y) { + return (y - yOffset) / maxY2 * rMax; + }; + var rx2px = function(r, x) { + return [r * Math.cos(x), -r * Math.sin(x)]; + }; + var pathSlice = function(d) { + return Lib2.pathAnnulus(d.rpx0, d.rpx1, d.x0, d.x1, cx, cy); + }; + var getTargetX = function(d) { + return cx + getTextXY(d)[0] * (d.transform.rCenter || 0) + (d.transform.x || 0); + }; + var getTargetY = function(d) { + return cy + getTextXY(d)[1] * (d.transform.rCenter || 0) + (d.transform.y || 0); + }; + slices = slices.data(sliceData, helpers2.getPtId); + slices.enter().append("g").classed("slice", true); + if (hasTransition2) { + slices.exit().transition().each(function() { + var sliceTop = d32.select(this); + var slicePath = sliceTop.select("path.surface"); + slicePath.transition().attrTween("d", function(pt2) { + var interp = makeExitSliceInterpolator(pt2); + return function(t) { + return pathSlice(interp(t)); + }; + }); + var sliceTextGroup = sliceTop.select("g.slicetext"); + sliceTextGroup.attr("opacity", 0); + }).remove(); + } else { + slices.exit().remove(); + } + slices.order(); + var nextX1ofPrevEntry = null; + if (hasTransition2 && prevEntry) { + var prevEntryId = helpers2.getPtId(prevEntry); + slices.each(function(pt) { + if (nextX1ofPrevEntry === null && helpers2.getPtId(pt) === prevEntryId) { + nextX1ofPrevEntry = pt.x1; + } + }); + } + var updateSlices = slices; + if (hasTransition2) { + updateSlices = updateSlices.transition().each("end", function() { + var sliceTop = d32.select(this); + helpers2.setSliceCursor(sliceTop, gd, { + hideOnRoot: true, + hideOnLeaves: true, + isTransitioning: false + }); + }); + } + updateSlices.each(function(pt) { + var sliceTop = d32.select(this); + var slicePath = Lib2.ensureSingle(sliceTop, "path", "surface", function(s) { + s.style("pointer-events", isStatic ? "none" : "all"); + }); + pt.rpx0 = y2rpx(pt.y0); + pt.rpx1 = y2rpx(pt.y1); + pt.xmid = (pt.x0 + pt.x1) / 2; + pt.pxmid = rx2px(pt.rpx1, pt.xmid); + pt.midangle = -(pt.xmid - Math.PI / 2); + pt.startangle = -(pt.x0 - Math.PI / 2); + pt.stopangle = -(pt.x1 - Math.PI / 2); + pt.halfangle = 0.5 * Math.min(Lib2.angleDelta(pt.x0, pt.x1) || Math.PI, Math.PI); + pt.ring = 1 - pt.rpx0 / pt.rpx1; + pt.rInscribed = getInscribedRadiusFraction2(pt); + if (hasTransition2) { + slicePath.transition().attrTween("d", function(pt2) { + var interp = makeUpdateSliceInterpolator(pt2); + return function(t) { + return pathSlice(interp(t)); + }; + }); + } else { + slicePath.attr("d", pathSlice); + } + sliceTop.call(attachFxHandlers3, entry, gd, cd, { + eventDataKeys: constants2.eventDataKeys, + transitionTime: constants2.CLICK_TRANSITION_TIME, + transitionEasing: constants2.CLICK_TRANSITION_EASING + }).call(helpers2.setSliceCursor, gd, { + hideOnRoot: true, + hideOnLeaves: true, + isTransitioning: gd._transitioning + }); + slicePath.call(styleOne3, pt, trace, gd); + var sliceTextGroup = Lib2.ensureSingle(sliceTop, "g", "slicetext"); + var sliceText = Lib2.ensureSingle(sliceTextGroup, "text", "", function(s) { + s.attr("data-notex", 1); + }); + var font2 = Lib2.ensureUniformFontSize(gd, helpers2.determineTextFont(trace, pt, fullLayout.font)); + sliceText.text(exports2.formatSliceLabel(pt, entry, trace, cd, fullLayout)).classed("slicetext", true).attr("text-anchor", "middle").call(Drawing2.font, font2).call(svgTextUtils2.convertToTspans, gd); + var textBB = Drawing2.bBox(sliceText.node()); + pt.transform = transformInsideText2(textBB, pt, cd0); + pt.transform.targetX = getTargetX(pt); + pt.transform.targetY = getTargetY(pt); + var strTransform = function(d, textBB2) { + var transform = d.transform; + computeTransform2(transform, textBB2); + transform.fontSize = font2.size; + recordMinTextSize2(trace.type, transform, fullLayout); + return Lib2.getTextTransform(transform); + }; + if (hasTransition2) { + sliceText.transition().attrTween("transform", function(pt2) { + var interp = makeUpdateTextInterpolator(pt2); + return function(t) { + return strTransform(interp(t), textBB); + }; + }); + } else { + sliceText.attr("transform", strTransform(pt, textBB)); + } + }); + function makeExitSliceInterpolator(pt) { + var id = helpers2.getPtId(pt); + var prev = prevLookup[id]; + var entryPrev = prevLookup[helpers2.getPtId(entry)]; + var next; + if (entryPrev) { + var a = (pt.x1 > entryPrev.x1 ? 2 * Math.PI : 0) + baseX; + next = pt.rpx1 < entryPrev.rpx1 ? { x0: pt.x0, x1: pt.x1, rpx0: 0, rpx1: 0 } : { x0: a, x1: a, rpx0: pt.rpx0, rpx1: pt.rpx1 }; + } else { + var parent; + var parentId = helpers2.getPtId(pt.parent); + slices.each(function(pt2) { + if (helpers2.getPtId(pt2) === parentId) { + return parent = pt2; + } + }); + var parentChildren = parent.children; + var ci; + parentChildren.forEach(function(pt2, i) { + if (helpers2.getPtId(pt2) === id) { + return ci = i; + } + }); + var n = parentChildren.length; + var interp = interpolate2(parent.x0, parent.x1); + next = { + rpx0: rMax, + rpx1: rMax, + x0: interp(ci / n), + x1: interp((ci + 1) / n) + }; + } + return interpolate2(prev, next); + } + function makeUpdateSliceInterpolator(pt) { + var prev0 = prevLookup[helpers2.getPtId(pt)]; + var prev; + var next = { x0: pt.x0, x1: pt.x1, rpx0: pt.rpx0, rpx1: pt.rpx1 }; + if (prev0) { + prev = prev0; + } else { + if (prevEntry) { + if (pt.parent) { + if (nextX1ofPrevEntry) { + var a = (pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0) + baseX; + prev = { x0: a, x1: a }; + } else { + prev = { rpx0: rMax, rpx1: rMax }; + Lib2.extendFlat(prev, interpX0X1FromParent(pt)); + } + } else { + prev = { rpx0: 0, rpx1: 0 }; + } + } else { + prev = { x0: baseX, x1: baseX }; + } + } + return interpolate2(prev, next); + } + function makeUpdateTextInterpolator(pt) { + var prev0 = prevLookup[helpers2.getPtId(pt)]; + var prev; + var transform = pt.transform; + if (prev0) { + prev = prev0; + } else { + prev = { + rpx1: pt.rpx1, + transform: { + textPosAngle: transform.textPosAngle, + scale: 0, + rotate: transform.rotate, + rCenter: transform.rCenter, + x: transform.x, + y: transform.y + } + }; + if (prevEntry) { + if (pt.parent) { + if (nextX1ofPrevEntry) { + var a = pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0; + prev.x0 = prev.x1 = a; + } else { + Lib2.extendFlat(prev, interpX0X1FromParent(pt)); + } + } else { + prev.x0 = prev.x1 = baseX; + } + } else { + prev.x0 = prev.x1 = baseX; + } + } + var textPosAngleFn = interpolate2(prev.transform.textPosAngle, pt.transform.textPosAngle); + var rpx1Fn = interpolate2(prev.rpx1, pt.rpx1); + var x0Fn2 = interpolate2(prev.x0, pt.x0); + var x1Fn2 = interpolate2(prev.x1, pt.x1); + var scaleFn = interpolate2(prev.transform.scale, transform.scale); + var rotateFn = interpolate2(prev.transform.rotate, transform.rotate); + var pow = transform.rCenter === 0 ? 3 : prev.transform.rCenter === 0 ? 1 / 3 : 1; + var _rCenterFn = interpolate2(prev.transform.rCenter, transform.rCenter); + var rCenterFn = function(t) { + return _rCenterFn(Math.pow(t, pow)); + }; + return function(t) { + var rpx1 = rpx1Fn(t); + x0Fn2(t); + x1Fn2(t); + var rCenter = rCenterFn(t); + var textPosAngle = textPosAngleFn(t); + var d = { + rpx1, + transform: { + textPosAngle, + rCenter, + x: transform.x, + y: transform.y + } + }; + recordMinTextSize2(trace.type, transform, fullLayout); + return { + transform: { + targetX: getTargetX(d), + targetY: getTargetY(d), + scale: scaleFn(t), + rotate: rotateFn(t), + rCenter + } + }; + }; + } + function interpX0X1FromParent(pt) { + var parent = pt.parent; + var parentPrev = prevLookup[helpers2.getPtId(parent)]; + var out = {}; + if (parentPrev) { + var parentChildren = parent.children; + var ci = parentChildren.indexOf(pt); + var n = parentChildren.length; + var interp = interpolate2(parentPrev.x0, parentPrev.x1); + out.x0 = interp(ci / n); + out.x1 = interp(ci / n); + } else { + out.x0 = out.x1 = 0; + } + return out; + } + } + function partition3(entry) { + return d3Hierarchy2.partition().size([2 * Math.PI, entry.height + 1])(entry); + } + exports2.formatSliceLabel = function(pt, entry, trace, cd, fullLayout) { + var texttemplate = trace.texttemplate; + var textinfo = trace.textinfo; + if (!texttemplate && (!textinfo || textinfo === "none")) { + return ""; + } + var separators = fullLayout.separators; + var cd0 = cd[0]; + var cdi = pt.data.data; + var hierarchy2 = cd0.hierarchy; + var isRoot = helpers2.isHierarchyRoot(pt); + var parent = helpers2.getParent(hierarchy2, pt); + var val = helpers2.getValue(pt); + if (!texttemplate) { + var parts = textinfo.split("+"); + var hasFlag = function(flag) { + return parts.indexOf(flag) !== -1; + }; + var thisText = []; + var tx; + if (hasFlag("label") && cdi.label) { + thisText.push(cdi.label); + } + if (cdi.hasOwnProperty("v") && hasFlag("value")) { + thisText.push(helpers2.formatValue(cdi.v, separators)); + } + if (!isRoot) { + if (hasFlag("current path")) { + thisText.push(helpers2.getPath(pt.data)); + } + var nPercent = 0; + if (hasFlag("percent parent")) nPercent++; + if (hasFlag("percent entry")) nPercent++; + if (hasFlag("percent root")) nPercent++; + var hasMultiplePercents = nPercent > 1; + if (nPercent) { + var percent; + var addPercent = function(key) { + tx = helpers2.formatPercent(percent, separators); + if (hasMultiplePercents) tx += " of " + key; + thisText.push(tx); + }; + if (hasFlag("percent parent") && !isRoot) { + percent = val / helpers2.getValue(parent); + addPercent("parent"); + } + if (hasFlag("percent entry")) { + percent = val / helpers2.getValue(entry); + addPercent("entry"); + } + if (hasFlag("percent root")) { + percent = val / helpers2.getValue(hierarchy2); + addPercent("root"); + } + } + } + if (hasFlag("text")) { + tx = Lib2.castOption(trace, cdi.i, "text"); + if (Lib2.isValidTextValue(tx)) thisText.push(tx); + } + return thisText.join("
"); + } + var txt = Lib2.castOption(trace, cdi.i, "texttemplate"); + if (!txt) return ""; + var obj = {}; + if (cdi.label) obj.label = cdi.label; + if (cdi.hasOwnProperty("v")) { + obj.value = cdi.v; + obj.valueLabel = helpers2.formatValue(cdi.v, separators); + } + obj.currentPath = helpers2.getPath(pt.data); + if (!isRoot) { + obj.percentParent = val / helpers2.getValue(parent); + obj.percentParentLabel = helpers2.formatPercent( + obj.percentParent, + separators + ); + obj.parent = helpers2.getPtLabel(parent); + } + obj.percentEntry = val / helpers2.getValue(entry); + obj.percentEntryLabel = helpers2.formatPercent( + obj.percentEntry, + separators + ); + obj.entry = helpers2.getPtLabel(entry); + obj.percentRoot = val / helpers2.getValue(hierarchy2); + obj.percentRootLabel = helpers2.formatPercent( + obj.percentRoot, + separators + ); + obj.root = helpers2.getPtLabel(hierarchy2); + if (cdi.hasOwnProperty("color")) { + obj.color = cdi.color; + } + var ptTx = Lib2.castOption(trace, cdi.i, "text"); + if (Lib2.isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx; + obj.customdata = Lib2.castOption(trace, cdi.i, "customdata"); + return Lib2.texttemplateString(txt, obj, fullLayout._d3locale, obj, trace._meta || {}); + }; + function getInscribedRadiusFraction2(pt) { + if (pt.rpx0 === 0 && Lib2.isFullCircle([pt.x0, pt.x1])) { + return 1; + } else { + return Math.max(0, Math.min( + 1 / (1 + 1 / Math.sin(pt.halfangle)), + pt.ring / 2 + )); + } + } + function getTextXY(d) { + return getCoords2(d.rpx1, d.transform.textPosAngle); + } + function getCoords2(r, angle) { + return [r * Math.sin(angle), -r * Math.cos(angle)]; + } +})(plot$1); +var d3 = d3Exports; +var Lib = libExports; +var Drawing = drawingExports; +var svgTextUtils = svg_text_utils; +var partition2 = partition$2; +var styleOne2 = style_1$1.styleOne; +var constants = constants$4; +var helpers = helpers$6; +var attachFxHandlers2 = fx; +var formatSliceLabel = plot$1.formatSliceLabel; +var onPathbar = false; +var draw_descendants = function drawDescendants(gd, cd, entry, slices, opts) { + var width = opts.width; + var height = opts.height; + var viewX = opts.viewX; + var viewY = opts.viewY; + var pathSlice = opts.pathSlice; + var toMoveInsideSlice = opts.toMoveInsideSlice; + var strTransform = opts.strTransform; + var hasTransition2 = opts.hasTransition; + var handleSlicesExit = opts.handleSlicesExit; + var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator; + var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator; + var prevEntry = opts.prevEntry; + var refRect = {}; + var isStatic = gd._context.staticPlot; + var fullLayout = gd._fullLayout; + var cd0 = cd[0]; + var trace = cd0.trace; + var hasLeft = trace.textposition.indexOf("left") !== -1; + var hasRight = trace.textposition.indexOf("right") !== -1; + var hasBottom = trace.textposition.indexOf("bottom") !== -1; + var noRoomForHeader = !hasBottom && !trace.marker.pad.t || hasBottom && !trace.marker.pad.b; + var allData = partition2(entry, [width, height], { + packing: trace.tiling.packing, + squarifyratio: trace.tiling.squarifyratio, + flipX: trace.tiling.flip.indexOf("x") > -1, + flipY: trace.tiling.flip.indexOf("y") > -1, + pad: { + inner: trace.tiling.pad, + top: trace.marker.pad.t, + left: trace.marker.pad.l, + right: trace.marker.pad.r, + bottom: trace.marker.pad.b + } + }); + var sliceData = allData.descendants(); + var minVisibleDepth = Infinity; + var maxVisibleDepth = -Infinity; + sliceData.forEach(function(pt) { + var depth = pt.depth; + if (depth >= trace._maxDepth) { + pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2; + pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2; + } else { + minVisibleDepth = Math.min(minVisibleDepth, depth); + maxVisibleDepth = Math.max(maxVisibleDepth, depth); + } + }); + slices = slices.data(sliceData, helpers.getPtId); + trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0; + slices.enter().append("g").classed("slice", true); + handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice); + slices.order(); + var nextOfPrevEntry = null; + if (hasTransition2 && prevEntry) { + var prevEntryId = helpers.getPtId(prevEntry); + slices.each(function(pt) { + if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) { + nextOfPrevEntry = { + x0: pt.x0, + x1: pt.x1, + y0: pt.y0, + y1: pt.y1 + }; + } + }); + } + var getRefRect = function() { + return nextOfPrevEntry || { + x0: 0, + x1: width, + y0: 0, + y1: height + }; + }; + var updateSlices = slices; + if (hasTransition2) { + updateSlices = updateSlices.transition().each("end", function() { + var sliceTop = d3.select(this); + helpers.setSliceCursor(sliceTop, gd, { + hideOnRoot: true, + hideOnLeaves: false, + isTransitioning: false + }); + }); + } + updateSlices.each(function(pt) { + var isHeader = helpers.isHeader(pt, trace); + pt._x0 = viewX(pt.x0); + pt._x1 = viewX(pt.x1); + pt._y0 = viewY(pt.y0); + pt._y1 = viewY(pt.y1); + pt._hoverX = viewX(pt.x1 - trace.marker.pad.r), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.marker.pad.b / 2) : viewY(pt.y0 + trace.marker.pad.t / 2); + var sliceTop = d3.select(this); + var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) { + s.style("pointer-events", isStatic ? "none" : "all"); + }); + if (hasTransition2) { + slicePath.transition().attrTween("d", function(pt2) { + var interp = makeUpdateSliceInterpolator(pt2, onPathbar, getRefRect(), [width, height]); + return function(t) { + return pathSlice(interp(t)); + }; + }); + } else { + slicePath.attr("d", pathSlice); + } + sliceTop.call(attachFxHandlers2, entry, gd, cd, { + styleOne: styleOne2, + eventDataKeys: constants.eventDataKeys, + transitionTime: constants.CLICK_TRANSITION_TIME, + transitionEasing: constants.CLICK_TRANSITION_EASING + }).call(helpers.setSliceCursor, gd, { isTransitioning: gd._transitioning }); + slicePath.call(styleOne2, pt, trace, gd, { + hovered: false + }); + if (pt.x0 === pt.x1 || pt.y0 === pt.y1) { + pt._text = ""; + } else { + if (isHeader) { + pt._text = noRoomForHeader ? "" : helpers.getPtLabel(pt) || ""; + } else { + pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || ""; + } + } + var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext"); + var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) { + s.attr("data-notex", 1); + }); + var font2 = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font)); + var text = pt._text || " "; + var singleLineHeader = isHeader && text.indexOf("
") === -1; + sliceText.text(text).classed("slicetext", true).attr("text-anchor", hasRight ? "end" : hasLeft || singleLineHeader ? "start" : "middle").call(Drawing.font, font2).call(svgTextUtils.convertToTspans, gd); + pt.textBB = Drawing.bBox(sliceText.node()); + pt.transform = toMoveInsideSlice(pt, { + fontSize: font2.size, + isHeader + }); + pt.transform.fontSize = font2.size; + if (hasTransition2) { + sliceText.transition().attrTween("transform", function(pt2) { + var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]); + return function(t) { + return strTransform(interp(t)); + }; + }); + } else { + sliceText.attr("transform", strTransform(pt)); + } + }); + return nextOfPrevEntry; +}; +var draw7 = draw$1; +var drawDescendants2 = draw_descendants; +var plot4 = function _plot2(gd, cdmodule, transitionOpts, makeOnCompleteCallback) { + return draw7(gd, cdmodule, transitionOpts, makeOnCompleteCallback, { + type: "treemap", + drawDescendants: drawDescendants2 + }); +}; +var treemap$2 = { + moduleType: "trace", + name: "treemap", + basePlotModule: base_plot, + categories: [], + animatable: true, + attributes: attributes$1, + layoutAttributes: layout_attributes, + supplyDefaults: defaults, + supplyLayoutDefaults: layout_defaults, + calc: calc$2.calc, + crossTraceCalc: calc$2.crossTraceCalc, + plot: plot4, + style: style_1$1.style, + colorbar: marker_colorbar, + meta: { + description: [ + "Visualize hierarchal data from leaves (and/or outer branches) towards root", + "with rectangles. The treemap sectors are determined by the entries in", + "*labels* or *ids* and in *parents*." + ].join(" ") + } +}; +var treemap = treemap$2; +const treemap$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(treemap); +Plotly.register([bar$1, histogram$1, pie$1, ohlc$1, scattergl$1, treemap$1]); +function ChartErrorOverlay(_ref) { + var { + errorMessage, + onDiscard, + onConfirm, + onCancel, + "data-testid": dataTestId + } = _ref; + var messageTestId = dataTestId != null ? "".concat(dataTestId, "-message") : void 0; + return /* @__PURE__ */ index$3.jsxRuntimeExports.jsx("div", { + className: "chart-panel-overlay chart-error-overlay", + children: /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { + className: "chart-panel-overlay-content chart-error-overlay-content", + children: [/* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { + className: "info-message", + "data-testid": messageTestId, + children: [errorMessage, /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.CopyButton, { + copy: errorMessage, + style: { + margin: "0" + } + })] + }), /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { + children: [onCancel && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { + onClick: onCancel, + kind: "secondary", + children: "Cancel" + }), onDiscard && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { + onClick: onDiscard, + kind: "secondary", + children: "Dismiss" + }), onConfirm && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { + onClick: onConfirm, + kind: "primary", + children: "Continue" + })] + })] + }) + }); +} +function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { + _defineProperty(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _defineProperty(e, r, t) { + return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +var log = Log.module("Chart"); +class Chart extends React.Component { + /** + * Convert a font awesome icon definition to a plotly icon definition + * @param faIcon The icon to convert + */ + static convertIcon(faIcon) { + var [width, , , , path] = faIcon.icon; + var stringPath = "".concat(path); + return { + width, + path: stringPath, + ascent: width, + descent: 0, + transform: "matrix(1, 0, 0, 1, 0, 0)" + }; + } + static downsampleButtonTitle(isDownsampleInProgress, isDownsamplingDisabled) { + if (isDownsampleInProgress) { + return "Downsampling in progress..."; + } + return isDownsamplingDisabled ? "Downsampling disabled, click to enable" : "Downsampling enabled, click to disable"; + } + static downsampleButtonAttr(isDownsampleInProgress, isDownsamplingDisabled) { + if (isDownsampleInProgress) { + return "animation-spin"; + } + return isDownsamplingDisabled ? void 0 : "fill-active"; + } + constructor(props) { + super(props); + _defineProperty(this, "currentSeries", void 0); + _defineProperty(this, "PlotComponent", void 0); + _defineProperty(this, "plot", void 0); + _defineProperty(this, "plotWrapper", void 0); + _defineProperty(this, "plotWrapperMerged", void 0); + _defineProperty(this, "columnFormats", void 0); + _defineProperty(this, "dateTimeFormatterOptions", void 0); + _defineProperty(this, "decimalFormatOptions", void 0); + _defineProperty(this, "integerFormatOptions", void 0); + _defineProperty(this, "webgl", void 0); + _defineProperty(this, "rect", void 0); + _defineProperty(this, "ranges", void 0); + _defineProperty(this, "isSubscribed", void 0); + _defineProperty(this, "isLoadedFired", void 0); + _defineProperty(this, "resizeObserver", void 0); + _defineProperty(this, "getCachedConfig", memoizeOne((downsamplingError, isDownsampleFinished, isDownsampleInProgress, isDownsamplingDisabled, data, error) => { + var customButtons = []; + var hasDownsampleError = Boolean(downsamplingError); + if (hasDownsampleError) { + customButtons.push({ + name: "Downsampling failed: ".concat(downsamplingError), + title: "Downsampling failed", + click: () => { + this.toggleErrorMessage("".concat(downsamplingError)); + }, + icon: Chart.convertIcon(icons.dhWarningFilled), + attr: "fill-warning" + }); + } + var hasError = Boolean(error); + if (hasError) { + customButtons.push({ + name: "Error: ".concat(error), + title: "Error", + click: () => { + this.toggleErrorMessage("".concat(error)); + }, + icon: Chart.convertIcon(icons.dhWarningFilled), + attr: "fill-warning" + }); + } + if (isDownsampleFinished || isDownsampleInProgress || isDownsamplingDisabled || hasDownsampleError) { + var name2 = Chart.downsampleButtonTitle(isDownsampleInProgress, isDownsamplingDisabled); + var attr = Chart.downsampleButtonAttr(isDownsampleInProgress, isDownsamplingDisabled); + var icon = isDownsampleInProgress ? icons.vsLoading : icons.dhGraphLineDown; + customButtons.push({ + name: name2, + title: "Downsampling status", + icon: Chart.convertIcon(icon), + click: this.handleDownsampleClick, + attr + }); + } + var has2D = data.some((_ref) => { + var { + type + } = _ref; + return type != null && !type.includes("3d"); + }); + var has3D = data.some((_ref2) => { + var { + type + } = _ref2; + return type != null && type.includes("3d"); + }); + var buttons2D = ["zoomIn2d", "zoomOut2d", "autoScale2d", "resetScale2d"]; + var buttons3D = ["orbitRotation", "tableRotation", "resetCameraDefault3d"]; + return { + displaylogo: false, + // scales the plot to the container size + // https://github.com/plotly/react-plotly.js/issues/102 + responsive: true, + // Display the mode bar if there's an error or downsampling so user can see progress + // Yes, the value is a boolean or the string 'hover': https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js#L249 + displayModeBar: ( + // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions + isDownsampleInProgress || hasDownsampleError || hasError ? true : "hover" + ), + // Each array gets grouped together in the mode bar + modeBarButtons: [ + customButtons, + ["toImage"], + ["zoom2d", "pan2d"], + // These work the same for both 2d and 3d + [...has2D ? buttons2D : [], ...has3D ? buttons3D : []] + ] + }; + })); + index$3.bindAllMethods(this); + this.PlotComponent = createPlotlyComponent(props.Plotly); + this.plot = /* @__PURE__ */ React.createRef(); + this.plotWrapper = /* @__PURE__ */ React.createRef(); + this.plotWrapperMerged = mergeRefs(this.plotWrapper, props.containerRef); + this.columnFormats = []; + this.dateTimeFormatterOptions = {}; + this.decimalFormatOptions = {}; + this.integerFormatOptions = {}; + this.isSubscribed = false; + this.isLoadedFired = false; + this.currentSeries = 0; + this.resizeObserver = new window.ResizeObserver(this.handleResize); + this.state = { + data: null, + downsamplingError: null, + isDownsampleFinished: false, + isDownsampleInProgress: false, + isDownsamplingDisabled: false, + error: null, + shownError: null, + layout: { + datarevision: 0 + }, + revision: 0, + shownBlocker: null + }; + } + componentDidMount() { + this.updateDimensions(); + this.updateModelDimensions(); + this.initData(); + this.initFormatter(); + var { + isActive: isActive2, + model + } = this.props; + if (isActive2) { + this.subscribe(model); + } + if (this.plotWrapper.current != null) { + this.resizeObserver.observe(this.plotWrapper.current); + } + this.handleThemeChange(); + } + componentDidUpdate(prevProps) { + var { + isActive: isActive2, + model, + settings, + theme + } = this.props; + this.updateFormatterSettings(settings); + if (model !== prevProps.model) { + this.unsubscribe(prevProps.model); + this.subscribe(model); + } + if (isActive2 !== prevProps.isActive) { + if (isActive2) { + this.updateDimensions(); + this.subscribe(model); + } else { + this.unsubscribe(model); + } + } + if (theme !== prevProps.theme) { + this.handleThemeChange(); + } + } + componentWillUnmount() { + var { + model + } = this.props; + this.unsubscribe(model); + this.resizeObserver.disconnect(); + } + // Listen for resizing of the element and update the canvas appropriately + getPlotRect() { + var _this$plotWrapper$cur, _this$plotWrapper$cur2; + return (_this$plotWrapper$cur = (_this$plotWrapper$cur2 = this.plotWrapper.current) === null || _this$plotWrapper$cur2 === void 0 ? void 0 : _this$plotWrapper$cur2.getBoundingClientRect()) !== null && _this$plotWrapper$cur !== void 0 ? _this$plotWrapper$cur : null; + } + initData() { + var { + model + } = this.props; + this.setState((_ref3) => { + var { + layout + } = _ref3; + return { + data: model.getData(), + layout: _objectSpread(_objectSpread({}, layout), model.getLayout()) + }; + }); + } + subscribe(model) { + if (this.isSubscribed) { + return; + } + if (!this.rect || this.rect.width === 0 || this.rect.height === 0) { + log.debug2("Delaying subscription until model dimensions are set"); + return; + } + model.subscribe(this.handleModelEvent); + this.isSubscribed = true; + } + unsubscribe(model) { + if (!this.isSubscribed) { + return; + } + model.unsubscribe(this.handleModelEvent); + this.isSubscribed = false; + } + handleAfterPlot() { + if (this.plot.current != null) ; + } + handleDownsampleClick() { + this.setState((_ref4) => { + var { + isDownsamplingDisabled + } = _ref4; + return { + downsamplingError: null, + isDownsampleInProgress: false, + isDownsampleFinished: false, + isDownsamplingDisabled: !isDownsamplingDisabled + }; + }, () => { + var { + model + } = this.props; + var { + isDownsamplingDisabled + } = this.state; + model.setDownsamplingDisabled(isDownsamplingDisabled); + }); + } + handleErrorClose() { + this.setState({ + shownError: null + }); + } + handleDownsampleErrorClose() { + this.setState({ + downsamplingError: null + }); + } + handleModelEvent(event) { + var { + type, + detail + } = event; + log.debug2("Received data update", type, detail); + switch (type) { + case index$3.ChartModel.EVENT_UPDATED: { + this.currentSeries += 1; + this.setState((state) => { + var { + layout, + revision + } = state; + if (typeof layout.datarevision === "number") { + layout.datarevision += 1; + } + return { + data: detail, + layout, + revision: revision + 1 + }; + }); + var { + onUpdate + } = this.props; + onUpdate({ + isLoading: !this.isLoadedFired + }); + break; + } + case index$3.ChartModel.EVENT_LOADFINISHED: { + var { + onUpdate: _onUpdate + } = this.props; + this.isLoadedFired = true; + _onUpdate({ + isLoading: false + }); + break; + } + case index$3.ChartModel.EVENT_DISCONNECT: { + var { + onDisconnect + } = this.props; + onDisconnect(); + break; + } + case index$3.ChartModel.EVENT_RECONNECT: { + var { + onReconnect + } = this.props; + onReconnect(); + break; + } + case index$3.ChartModel.EVENT_DOWNSAMPLESTARTED: { + this.setState({ + isDownsampleFinished: false, + isDownsampleInProgress: true, + downsamplingError: null + }); + break; + } + case index$3.ChartModel.EVENT_DOWNSAMPLEFINISHED: { + this.setState({ + isDownsampleFinished: true, + isDownsampleInProgress: false, + downsamplingError: null + }); + break; + } + case index$3.ChartModel.EVENT_DOWNSAMPLENEEDED: + case index$3.ChartModel.EVENT_DOWNSAMPLEFAILED: { + var _message; + var downsamplingError = (_message = detail.message) !== null && _message !== void 0 ? _message : detail; + this.setState({ + isDownsampleFinished: false, + isDownsampleInProgress: false, + isDownsamplingDisabled: false, + downsamplingError + }); + var { + onError + } = this.props; + onError(new DownsamplingError(downsamplingError == null ? void 0 : "".concat(downsamplingError))); + break; + } + case index$3.ChartModel.EVENT_ERROR: { + var _error = "".concat(detail); + this.setState({ + error: _error + }); + var { + onError: _onError + } = this.props; + _onError(new Error(_error)); + break; + } + case index$3.ChartModel.EVENT_BLOCKER: { + var blocker = "".concat(detail); + this.setState({ + shownBlocker: blocker + }); + break; + } + case index$3.ChartModel.EVENT_BLOCKER_CLEAR: { + this.setState({ + shownBlocker: null + }); + break; + } + case index$3.ChartModel.EVENT_LAYOUT_UPDATED: { + var newLayout = detail; + this.setState((_ref5) => { + var { + layout, + revision + } = _ref5; + return { + layout: _objectSpread(_objectSpread({}, layout), newLayout), + revision: revision + 1 + }; + }); + break; + } + default: + log.debug("Unknown event type", type, event); + } + } + handlePlotUpdate(figure) { + var { + layout + } = figure; + var ranges = index$3.ChartUtils.getLayoutRanges(layout); + var isRangesChanged = !deepEqual(ranges, this.ranges); + if (isRangesChanged) { + this.ranges = ranges; + this.updateModelDimensions(true); + } + } + handleRelayout(changes) { + log.debug("handleRelayout", changes); + if (changes.hiddenlabels != null) { + var { + onSettingsChanged + } = this.props; + var hiddenSeries = [...changes.hiddenlabels]; + onSettingsChanged({ + hiddenSeries + }); + } + this.updateModelDimensions(); + } + handleResize() { + this.updateDimensions(); + } + handleRestyle(_ref6) { + var [changes, seriesIndexes] = _ref6; + log.debug("handleRestyle", changes, seriesIndexes); + if (Object.keys(changes).includes("visible")) { + var { + data + } = this.state; + var { + onSettingsChanged + } = this.props; + if (data != null) { + var hiddenSeries = data.reduce((acc, _ref7) => { + var { + name: name2, + visible + } = _ref7; + return name2 != null && visible === "legendonly" ? [...acc, name2] : acc; + }, []); + onSettingsChanged({ + hiddenSeries + }); + } + } + } + handleThemeChange() { + var { + theme, + model + } = this.props; + var { + dh + } = model; + var chartUtils = new index$3.ChartUtils(dh); + this.setState((_ref8) => { + var { + layout + } = _ref8; + return { + layout: _objectSpread(_objectSpread({}, layout), {}, { + template: chartUtils.makeDefaultTemplate(theme) + }) + }; + }); + } + /** + * Toggle the error message. If it is already being displayed, then hide it. + */ + toggleErrorMessage(error) { + this.setState((_ref9) => { + var { + shownError + } = _ref9; + return { + shownError: shownError === error ? null : error + }; + }); + } + /** + * Update the models dimensions and ranges. + * Note that this will update it all whether the plot size changes OR the range + * the user is looking at has changed (eg. panning/zooming). + * Could update each independently, but doing them at the same time keeps the + * ChartModel API a bit cleaner. + * @param force Force a change even if the chart dimensions haven't changed (eg. after pan/zoom) + */ + updateModelDimensions() { + var force = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; + var rect2 = this.getPlotRect(); + if (!rect2) { + log.warn("Unable to get plotting rect"); + return; + } + var isRectChanged = !this.rect || this.rect.width !== rect2.width || this.rect.height !== rect2.height; + if (isRectChanged || force) { + this.rect = rect2; + var { + isActive: isActive2, + model + } = this.props; + model.setDimensions(rect2); + if (isActive2) { + this.subscribe(model); + } + } + } + initFormatter() { + var { + settings + } = this.props; + this.updateFormatterSettings(settings); + } + updateFormatterSettings(settings) { + var columnFormats = FormatterUtils.getColumnFormats(settings); + var dateTimeFormatterOptions = FormatterUtils.getDateTimeFormatterOptions(settings); + var { + defaultDecimalFormatOptions = {}, + defaultIntegerFormatOptions = {} + } = settings; + if (!deepEqual(this.columnFormats, columnFormats) || !deepEqual(this.dateTimeFormatterOptions, dateTimeFormatterOptions) || !deepEqual(this.decimalFormatOptions, defaultDecimalFormatOptions) || !deepEqual(this.integerFormatOptions, defaultIntegerFormatOptions)) { + this.columnFormats = FormatterUtils.getColumnFormats(settings); + this.dateTimeFormatterOptions = dateTimeFormatterOptions; + this.decimalFormatOptions = defaultDecimalFormatOptions; + this.integerFormatOptions = defaultIntegerFormatOptions; + this.updateFormatter(); + } + if (this.webgl !== settings.webgl) { + this.webgl = settings.webgl; + this.updateRenderOptions(); + } + } + updateFormatter() { + var { + model + } = this.props; + var formatter = new Formatter(model.dh, this.columnFormats, this.dateTimeFormatterOptions, this.decimalFormatOptions, this.integerFormatOptions); + model.setFormatter(formatter); + } + updateRenderOptions() { + var { + model + } = this.props; + var renderOptions = { + webgl: this.webgl + }; + model.setRenderOptions(renderOptions); + } + updateDimensions() { + var rect2 = this.getPlotRect(); + var { + Plotly: PlotlyProp + } = this.props; + if (this.plot.current != null && rect2 != null && rect2.width > 0 && rect2.height > 0) { + PlotlyProp.relayout(this.plot.current.el, { + autosize: true + }).catch((e) => { + log.debug("Unable to resize, promise rejected", e); + }); + } + } + render() { + var { + PlotComponent + } = this; + var { + data, + downsamplingError, + isDownsampleFinished, + isDownsampleInProgress, + isDownsamplingDisabled, + error, + shownError, + layout, + revision, + shownBlocker + } = this.state; + var config = this.getCachedConfig(downsamplingError, isDownsampleFinished, isDownsampleInProgress, isDownsamplingDisabled, data !== null && data !== void 0 ? data : [], error); + var { + model + } = this.props; + var isPlotShown = data != null && shownBlocker == null; + var errorOverlay = null; + if (shownBlocker != null) { + errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { + errorMessage: "".concat(shownBlocker), + onConfirm: () => { + model.fireBlockerClear(); + } + }); + } else if (shownError != null) { + errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { + errorMessage: "".concat(downsamplingError), + onDiscard: () => { + this.handleDownsampleErrorClose(); + }, + onConfirm: () => { + this.handleDownsampleErrorClose(); + this.handleDownsampleClick(); + } + }); + } else if (downsamplingError != null) { + errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { + errorMessage: "".concat(downsamplingError), + onDiscard: () => { + this.handleDownsampleErrorClose(); + }, + onConfirm: () => { + this.handleDownsampleErrorClose(); + this.handleDownsampleClick(); + } + }); + } + return /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { + className: "h-100 w-100 chart-wrapper", + ref: this.plotWrapperMerged, + children: [isPlotShown && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx( + PlotComponent, + { + ref: this.plot, + data, + layout, + revision, + config, + onAfterPlot: this.handleAfterPlot, + onError: log.error, + onRelayout: this.handleRelayout, + onUpdate: this.handlePlotUpdate, + onRestyle: this.handleRestyle, + style: { + height: "100%", + width: "100%" + } + } + ), errorOverlay] + }); + } +} +_defineProperty(Chart, "defaultProps", { + isActive: true, + settings: { + timeZone: "America/New_York", + defaultDateTimeFormat: index$3.DateUtils.FULL_DATE_FORMAT, + showTimeZone: false, + showTSeparator: true, + formatter: [], + webgl: true + }, + Plotly, + onDisconnect: () => void 0, + onReconnect: () => void 0, + onUpdate: () => void 0, + onError: () => void 0, + onSettingsChanged: () => void 0 +}); +function ChartContainer(props) { + var chartTheme = useChartTheme(); + return /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(Chart, _objectSpread(_objectSpread({}, props), {}, { + theme: chartTheme + })); +} +exports.default = ChartContainer; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs b/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs new file mode 100644 index 000000000..1252748af --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs @@ -0,0 +1,12476 @@ +"use strict"; +const plugin = require("@deephaven/plugin"); +const React = require("react"); +const Log = require("@deephaven/log"); +const components = require("@deephaven/components"); +var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; +function getDefaultExportFromCjs(x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; +} +function getAugmentedNamespace(n2) { + if (n2.__esModule) return n2; + var f2 = n2.default; + if (typeof f2 == "function") { + var a = function a2() { + if (this instanceof a2) { + return Reflect.construct(f2, arguments, this.constructor); + } + return f2.apply(this, arguments); + }; + a.prototype = f2.prototype; + } else a = {}; + Object.defineProperty(a, "__esModule", { value: true }); + Object.keys(n2).forEach(function(k) { + var d2 = Object.getOwnPropertyDescriptor(n2, k); + Object.defineProperty(a, k, d2.get ? d2 : { + enumerable: true, + get: function() { + return n2[k]; + } + }); + }); + return a; +} +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production_min = {}; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty$1 = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; +function toObject(val) { + if (val === null || val === void 0) { + throw new TypeError("Object.assign cannot be called with null or undefined"); + } + return Object(val); +} +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + var test1 = new String("abc"); + test1[5] = "de"; + if (Object.getOwnPropertyNames(test1)[0] === "5") { + return false; + } + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2["_" + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { + return test2[n2]; + }); + if (order2.join("") !== "0123456789") { + return false; + } + var test3 = {}; + "abcdefghijklmnopqrst".split("").forEach(function(letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { + return false; + } + return true; + } catch (err) { + return false; + } +} +var objectAssign = shouldUseNative() ? Object.assign : function(target, source) { + var from2; + var to = toObject(target); + var symbols; + for (var s = 1; s < arguments.length; s++) { + from2 = Object(arguments[s]); + for (var key in from2) { + if (hasOwnProperty$1.call(from2, key)) { + to[key] = from2[key]; + } + } + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from2); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from2, symbols[i])) { + to[symbols[i]] = from2[symbols[i]]; + } + } + } + } + return to; +}; +/** @license React v17.0.2 + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var f = React, g = 60103; +reactJsxRuntime_production_min.Fragment = 60107; +if ("function" === typeof Symbol && Symbol.for) { + var h = Symbol.for; + g = h("react.element"); + reactJsxRuntime_production_min.Fragment = h("react.fragment"); +} +var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; +function q(c, a, k) { + var b, d2 = {}, e = null, l = null; + void 0 !== k && (e = "" + k); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (l = a.ref); + for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d2[b] = a[b]); + if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d2[b] && (d2[b] = a[b]); + return { $$typeof: g, type: c, key: e, ref: l, props: d2, _owner: m.current }; +} +reactJsxRuntime_production_min.jsx = q; +reactJsxRuntime_production_min.jsxs = q; +{ + jsxRuntime.exports = reactJsxRuntime_production_min; +} +var jsxRuntimeExports = jsxRuntime.exports; +const log$4 = Log.module("@deephaven/js-plugin-grid-toolbar"); +function GridToolbarMiddleware({ + Component, + ...props +}) { + const handleExport = React.useCallback(() => { + log$4.info("Export clicked"); + }, []); + const handleResetFilters = React.useCallback(() => { + log$4.info("[0] Reset Filters clicked", props, Component); + }, [props, Component]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleExport, + children: "Export" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) + ] }); +} +function ownKeys$3(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread$3(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys$3(Object(t), true).forEach(function(r2) { + _defineProperty$9(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _defineProperty$9(e, r, t) { + return (r = _toPropertyKey$9(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey$9(t) { + var i = _toPrimitive$9(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive$9(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +var Chart = /* @__PURE__ */ React.lazy(() => Promise.resolve().then(() => require("./Chart-DElXbH_b.cjs"))); +function LazyChart(props) { + return /* @__PURE__ */ jsxRuntimeExports.jsx(React.Suspense, { + fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(components.LoadingOverlay, {}), + children: /* @__PURE__ */ jsxRuntimeExports.jsx(Chart, _objectSpread$3({}, props)) + }); +} +function removeNullAndUndefined() { + for (var _len = arguments.length, maybeDefined = new Array(_len), _key = 0; _key < _len; _key++) { + maybeDefined[_key] = arguments[_key]; + } + return maybeDefined.filter((m2) => m2 != null); +} +function _defineProperty$8(obj, key, value2) { + key = _toPropertyKey$8(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$8(arg) { + var key = _toPrimitive$8(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$8(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class CanceledPromiseError extends Error { + constructor() { + super(...arguments); + _defineProperty$8(this, "isCanceled", true); + } +} +function bindAllMethods(instance) { + var traversePrototypeChain = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; + var methodNames = getAllMethodNames(instance, traversePrototypeChain); + methodNames.forEach((methodName) => { + instance[methodName] = instance[methodName].bind(instance); + }); +} +function getAllMethodNames(instance, traversePrototypeChain) { + var methodNames = /* @__PURE__ */ new Set(); + var current = instance; + var level = 0; + while (current != null && current !== Object.prototype && (level <= 1 || traversePrototypeChain)) { + for (var name of Object.getOwnPropertyNames(current)) { + var _Object$getOwnPropert; + if (name !== "constructor" && // Ensure this is a method and not a getter + typeof ((_Object$getOwnPropert = Object.getOwnPropertyDescriptor(current, name)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.value) === "function") { + methodNames.add(name); + } + } + current = Object.getPrototypeOf(current); + level += 1; + } + return [...methodNames.keys()]; +} +function _defineProperty$7(obj, key, value2) { + key = _toPropertyKey$7(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$7(arg) { + var key = _toPrimitive$7(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$7(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class TimeoutError extends Error { + constructor() { + super(...arguments); + _defineProperty$7(this, "isTimeout", true); + } +} +class PromiseUtils { + /** + * Creates a promise that can be canceled by calling the `cancel` function + * Pass an optional `cleanupFunc` to perform actions on the resolved item after promise is cancelled. + * @param promise The item to resolve + * @param cleanup Function to cleanup the resolved item after cancelation. Called after both this promise is cancelled and the wrapped item was resolved (order does not matter). + */ + static makeCancelable(promise2, cleanup) { + var hasCanceled = false; + var resolved; + var rejectFn; + var wrappedPromise = new Promise((resolve, reject) => { + rejectFn = reject; + Promise.resolve(promise2).then((val) => { + if (hasCanceled) { + if (cleanup) { + cleanup(val); + } + } else { + resolved = val; + resolve(val); + } + }).catch((error) => reject(error)); + }); + wrappedPromise.cancel = () => { + hasCanceled = true; + rejectFn(new CanceledPromiseError()); + if (resolved != null && cleanup) { + cleanup(resolved); + } + }; + return wrappedPromise; + } + static isCanceled(error) { + return error instanceof CanceledPromiseError; + } + static isTimedOut(error) { + return error instanceof TimeoutError; + } + /** + * Wrap a callback call in a Promise + setTimeout. + * @param timeoutMs + * @param callback + */ + static withTimeout(timeoutMs, callback) { + return new Promise((resolve, reject) => { + setTimeout(() => { + try { + resolve(callback()); + } catch (err) { + reject(err); + } + }, timeoutMs); + }); + } +} +function assertInstanceOf(instance, type) { + if (!(instance instanceof type)) { + throw new Error("Expected instance of ".concat(type.name)); + } +} +function assertNotNull(value2) { + var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "Value is null or undefined"; + if (value2 == null) throw new Error(message); +} +class TextUtils { + /** + * Joins a list of strings with a comma, keeping the oxford comma and adding "and" as appropriate. + * Eg. + * One + * One and Two + * One, Two, and Three + * @param items The items to join in a list + * @param conjunction Conjunction to use between the last two items + */ + static join(items) { + var conjunction = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "and"; + if (items == null || items.length === 0) { + return ""; + } + if (items.length === 1) { + return items[0]; + } + if (items.length === 2) { + return "".concat(items[0], " ").concat(conjunction, " ").concat(items[1]); + } + var itemText = items.slice(0, items.length - 1).join(", "); + var lastItem = items[items.length - 1]; + return "".concat(itemText, ", ").concat(conjunction, " ").concat(lastItem); + } + /** + * Converts text to lower case, handling null if necessary and returning an empty string + * @param text The text to convert to lower case + * @param isNullAllowed True if a null string should return an empty string from this function. If false an error is thrown if null is passed in. + */ + static toLower(text) { + var isNullAllowed = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; + if (text == null) { + if (isNullAllowed) { + return ""; + } + throw new Error("Null string passed in to TextUtils.toLower"); + } + return text.toLowerCase(); + } + /** + * + * @param a The string to sort + * @param b Second string to sort + * @param isAscending Whether to sort ascending or descending + */ + static sort(a, b) { + var isAscending = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; + if (a < b) { + return isAscending ? -1 : 1; + } + if (a > b) { + return isAscending ? 1 : -1; + } + return 0; + } +} +function ownKeys$2(object, enumerableOnly) { + var keys2 = Object.keys(object); + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + enumerableOnly && (symbols = symbols.filter(function(sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + })), keys2.push.apply(keys2, symbols); + } + return keys2; +} +function _objectSpread$2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = null != arguments[i] ? arguments[i] : {}; + i % 2 ? ownKeys$2(Object(source), true).forEach(function(key) { + _defineProperty$6(target, key, source[key]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function(key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + return target; +} +function _defineProperty$6(obj, key, value2) { + key = _toPropertyKey$6(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$6(arg) { + var key = _toPrimitive$6(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$6(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +var DATE_TIME_REGEX = /\s*(\d{4})([-./](\d{1,2}|[a-z]+))?([-./](\d{1,2}))?([tT\s](\d{2})([:](\d{2}))?([:](\d{2}))?([.](\d{1,9}))?)?(.*)/; +class DateUtils { + /** + * + * @param timeZone The time zone to parse this time in. E.g. America/New_York + * @param year The year for the date + * @param month The month, starting at 0 + * @param day The day, starting at 1 + * @param hour The hours + * @param minute The minutes + * @param second The seconds + * @param ns The nanoseconds + */ + static makeDateWrapper(dh, timeZone, year) { + var month = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; + var day = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 1; + var hour = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 0; + var minute = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : 0; + var second = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : 0; + var ns = arguments.length > 8 && arguments[8] !== void 0 ? arguments[8] : 0; + if (!timeZone) { + throw new Error("No timezone provided"); + } + var yearString = "".concat(year).padStart(4, "0"); + var monthString = "".concat(month + 1).padStart(2, "0"); + var dayString = "".concat(day).padStart(2, "0"); + var hourString = "".concat(hour).padStart(2, "0"); + var minuteString = "".concat(minute).padStart(2, "0"); + var secondString = "".concat(second).padStart(2, "0"); + var nanoString = "".concat(ns).padStart(9, "0"); + var dateString = "".concat(yearString, "-").concat(monthString, "-").concat(dayString, " ").concat(hourString, ":").concat(minuteString, ":").concat(secondString, ".").concat(nanoString); + return dh.i18n.DateTimeFormat.parse(DateUtils.FULL_DATE_FORMAT, dateString, dh.i18n.TimeZone.getTimeZone(timeZone)); + } + /** + * Takes the string the user entered and returns the next nanos value + * @param nanoString The nano string to get the next one of + * @returns The value of the next nanos + */ + static getNextNanos(nanoString) { + var sigNanos = parseInt(nanoString, 10); + var zeros = "0".repeat(9 - nanoString.length); + var nextNanoString = "".concat(sigNanos + 1).concat(zeros); + return parseInt(nextNanoString, 10); + } + /** + * @param components The string components that were parsed from the original string + * @param values The values that were parsed from the components + * @param timeZone The time zone to parse the date in. E.g. America/New_York + * @returns Returns the DateWrapper for the next date, or null if a full date was passed in + */ + static getNextDate(dh, components2, values, timeZone) { + var { + year, + month, + date, + hours, + minutes, + seconds, + nanos + } = values; + if (components2.nanos != null) { + if (components2.nanos.length === 9) { + return null; + } + nanos = DateUtils.getNextNanos(components2.nanos); + if (nanos > 999999999) { + seconds += 1; + nanos = 0; + } + } else if (components2.seconds != null) { + seconds += 1; + } else if (components2.minutes != null) { + minutes += 1; + } else if (components2.hours != null) { + hours += 1; + } else if (components2.date != null) { + date += 1; + } else if (components2.month != null) { + month += 1; + } else { + year += 1; + } + var jsDate = new Date(year, month, date, hours, minutes, seconds); + return DateUtils.makeDateWrapper(dh, timeZone, jsDate.getFullYear(), jsDate.getMonth(), jsDate.getDate(), jsDate.getHours(), jsDate.getMinutes(), jsDate.getSeconds(), nanos); + } + /** + * Get the JS month value for the provided string. + * Matches digits or a month name (eg. '1', '01', 'jan', 'january' should all work) + * @param monthString The string to parse to a JS month value + * @returns number The JS month value, which starts at 0 for january, or NaN if nothing could be parsed + */ + static parseMonth(monthString) { + var month = parseInt(monthString, 10); + if (!Number.isNaN(month)) { + if (month >= 1 && month <= 12) { + return month - 1; + } + return NaN; + } + var cleanMonthString = monthString.trim().toLowerCase(); + if (cleanMonthString.length >= 3) { + for (var i = 0; i < DateUtils.months.length; i += 1) { + if (DateUtils.months[i].startsWith(cleanMonthString)) { + return i; + } + } + } + return NaN; + } + /** + * Parse a date object out of the provided string segments. + * Also using `parseMonth` to get month names like Aug/August rather than + * simply doing `parseInt`. + * @param yearString The year part of the string + * @param monthString The month part of the string + * @param dayString The day part of the string + * @param hourString The hour part of the string + * @param minuteString The minute part of the string + * @param secondString The second part of the string + * @param nanoString The milli part of the string + */ + static parseDateValues(yearString, monthString, dayString, hourString, minuteString, secondString, nanoString) { + var year = parseInt(yearString, 10); + var month = monthString != null ? this.parseMonth(monthString) : 0; + var date = dayString != null ? parseInt(dayString, 10) : 1; + var hours = hourString != null ? parseInt(hourString, 10) : 0; + var minutes = minuteString != null ? parseInt(minuteString, 10) : 0; + var seconds = secondString != null ? parseInt(secondString, 10) : 0; + var nanos = nanoString != null ? parseInt(nanoString.padEnd(9, "0"), 10) : 0; + if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(date) || Number.isNaN(hours) || Number.isNaN(minutes) || Number.isNaN(seconds) || Number.isNaN(nanos)) { + return null; + } + return { + year, + month, + date, + hours, + minutes, + seconds, + nanos + }; + } + /** + * Parse out a date time string into it's string components. + * Anything that is not captured in the string will be undefined. + * + * @param dateTimeString The date time string to parse + * @param allowOverflow If true, will allow overflow characters after the date + * string + * @returns Containing the date time components + */ + static parseDateTimeString(dateTimeString) { + var allowOverflow = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; + var result = DATE_TIME_REGEX.exec(dateTimeString); + if (result == null) { + throw new Error("Unexpected date string: ".concat(dateTimeString)); + } + var [, year, , month, , date, , hours, , minutes, , seconds, , nanos, overflow] = result; + if (!allowOverflow && overflow != null && overflow.length > 0) { + throw new Error("Unexpected characters after date string '".concat(dateTimeString, "': ").concat(overflow)); + } + var dateParts = { + year, + month, + date, + hours, + minutes, + seconds, + nanos + }; + return allowOverflow ? _objectSpread$2(_objectSpread$2({}, dateParts), {}, { + overflow + }) : dateParts; + } + /** + * Parses the date range provided from a string of text. + * @param text The string to parse the date from. Can be a keyword like "today", or in the format "2018-08-04" + * @param timeZone The time zone to parse this range in. E.g. America/New_York + * @returns A tuple with the start and end value/null for that date range, or both null + */ + static parseDateRange(dh, text, timeZone) { + var cleanText = text.trim().toLowerCase(); + if (cleanText.length === 0) { + throw new Error("Cannot parse date range from empty string"); + } + if (cleanText === "null") { + return [null, null]; + } + if (cleanText === "today") { + var now = new Date(Date.now()); + var _startDate = DateUtils.makeDateWrapper(dh, timeZone, now.getFullYear(), now.getMonth(), now.getDate()); + var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); + var _endDate = DateUtils.makeDateWrapper(dh, timeZone, tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate()); + return [_startDate, _endDate]; + } + if (cleanText === "yesterday") { + var _now = new Date(Date.now()); + var yesterday = new Date(_now.getFullYear(), _now.getMonth(), _now.getDate() - 1); + var _startDate2 = DateUtils.makeDateWrapper(dh, timeZone, yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate()); + var _endDate2 = DateUtils.makeDateWrapper(dh, timeZone, _now.getFullYear(), _now.getMonth(), _now.getDate()); + return [_startDate2, _endDate2]; + } + if (cleanText === "now") { + var _now2 = new Date(Date.now()); + var date = dh.DateWrapper.ofJsDate(_now2); + return [date, null]; + } + var components2 = DateUtils.parseDateTimeString(cleanText); + if (components2.year == null && components2.month == null && components2.date == null) { + throw new Error("Unable to extract year, month, or day ".concat(cleanText)); + } + var values = DateUtils.parseDateValues(components2.year, components2.month, components2.date, components2.hours, components2.minutes, components2.seconds, components2.nanos); + if (values == null) { + throw new Error("Unable to extract date values from ".concat(components2)); + } + var startDate = DateUtils.makeDateWrapper(dh, timeZone, values.year, values.month, values.date, values.hours, values.minutes, values.seconds, values.nanos); + var endDate = DateUtils.getNextDate(dh, components2, values, timeZone); + return [startDate, endDate]; + } + /** + * Gets the Js Date object from the provided DateWrapper. + * In unit test, DateWrapper is just a number provided in millis, so handles that case. + * @param dateWrapper The DateWrapper object, or time in millis + */ + static getJsDate(dateWrapper) { + if (typeof dateWrapper === "number") { + return new Date(dateWrapper); + } + return dateWrapper.asDate(); + } + /** + * Trim overflow (usually timezone) from a date time string. + * @param dateTimeString The date time string to trim + * @returns The date time string without overflow + */ + static trimDateTimeStringTimeZone(dateTimeString) { + var { + overflow = "" + } = DateUtils.parseDateTimeString(dateTimeString, true); + if (overflow === "") { + return dateTimeString; + } + if (!/^\s[A-Za-z]+/.test(overflow)) { + throw new Error("Unexpected timezone format in overflow: '".concat(dateTimeString, "'")); + } + return dateTimeString.slice(0, -overflow.length); + } +} +_defineProperty$6(DateUtils, "FULL_DATE_FORMAT", "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"); +_defineProperty$6(DateUtils, "months", ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]); +function createFilterConditionFactory(columnNames, createColumnCondition) { + var conditionOperator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "or"; + return function filterConditionFactory(maybeTable) { + var maybeColumns = maybeTable === null || maybeTable === void 0 ? void 0 : maybeTable.findColumns(typeof columnNames === "string" ? [columnNames] : columnNames); + if (maybeColumns == null || maybeColumns.length === 0) { + return null; + } + var filterConditions = maybeColumns.map(createColumnCondition); + return filterConditions.reduce((current, next) => current[conditionOperator](next)); + }; +} +function createValueFilter(tableUtils, columnNames, value2, operator) { + return createFilterConditionFactory(columnNames, (col) => col.filter()[operator](tableUtils.makeFilterValue(col.type, value2)), "or"); +} +function _defineProperty$5(obj, key, value2) { + key = _toPropertyKey$5(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$5(arg) { + var key = _toPrimitive$5(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$5(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class Operator { +} +_defineProperty$5(Operator, "not", "not"); +_defineProperty$5(Operator, "and", "and"); +_defineProperty$5(Operator, "or", "or"); +function _defineProperty$4(obj, key, value2) { + key = _toPropertyKey$4(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$4(arg) { + var key = _toPrimitive$4(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$4(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +class Type { +} +_defineProperty$4(Type, "eq", "eq"); +_defineProperty$4(Type, "eqIgnoreCase", "eqIgnoreCase"); +_defineProperty$4(Type, "notEq", "notEq"); +_defineProperty$4(Type, "notEqIgnoreCase", "notEqIgnoreCase"); +_defineProperty$4(Type, "greaterThan", "greaterThan"); +_defineProperty$4(Type, "greaterThanOrEqualTo", "greaterThanOrEqualTo"); +_defineProperty$4(Type, "lessThan", "lessThan"); +_defineProperty$4(Type, "lessThanOrEqualTo", "lessThanOrEqualTo"); +_defineProperty$4(Type, "in", "in"); +_defineProperty$4(Type, "inIgnoreCase", "inIgnoreCase"); +_defineProperty$4(Type, "notIn", "notIn"); +_defineProperty$4(Type, "notInIgnoreCase", "notInIgnoreCase"); +_defineProperty$4(Type, "isTrue", "isTrue"); +_defineProperty$4(Type, "isFalse", "isFalse"); +_defineProperty$4(Type, "isNull", "isNull"); +_defineProperty$4(Type, "invoke", "invoke"); +_defineProperty$4(Type, "contains", "contains"); +_defineProperty$4(Type, "notContains", "notContains"); +_defineProperty$4(Type, "containsIgnoreCase", "containsIgnoreCase"); +_defineProperty$4(Type, "startsWith", "startsWith"); +_defineProperty$4(Type, "endsWith", "endsWith"); +_defineProperty$4(Type, "containsAny", "containsAny"); +Log.module("ViewportDataUtils"); +function getSize(table) { + return table == null || isClosed(table) ? 0 : table.size; +} +function isClosed(table) { + if ("isClosed" in table) { + return table.isClosed; + } + return false; +} +function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) { + try { + var info = gen[key](arg); + var value2 = info.value; + } catch (error) { + reject(error); + return; + } + if (info.done) { + resolve(value2); + } else { + Promise.resolve(value2).then(_next, _throw); + } +} +function _asyncToGenerator$1(fn) { + return function() { + var self3 = this, args = arguments; + return new Promise(function(resolve, reject) { + var gen = fn.apply(self3, args); + function _next(value2) { + asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value2); + } + function _throw(err) { + asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err); + } + _next(void 0); + }); + }; +} +function _defineProperty$3(obj, key, value2) { + key = _toPropertyKey$3(key); + if (key in obj) { + Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); + } else { + obj[key] = value2; + } + return obj; +} +function _toPropertyKey$3(arg) { + var key = _toPrimitive$3(arg, "string"); + return typeof key === "symbol" ? key : String(key); +} +function _toPrimitive$3(input, hint) { + if (typeof input !== "object" || input === null) return input; + var prim = input[Symbol.toPrimitive]; + if (prim !== void 0) { + var res = prim.call(input, hint); + if (typeof res !== "object") return res; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return (hint === "string" ? String : Number)(input); +} +var log$3 = Log.module("TableUtils"); +class TableUtils { + // Regex looking for a negative or positive integer or decimal number + /** + * Copy a given table and apply filters. + * @param maybeTable Table to copy and apply filters to + * @param filterFactories Filter condition factories to apply + * @returns A derived, filtered table + */ + static copyTableAndApplyFilters(maybeTable) { + var _arguments = arguments; + return _asyncToGenerator$1(function* () { + if (maybeTable == null) { + return null; + } + var derivedTable = yield maybeTable.copy(); + for (var _len = _arguments.length, filterFactories = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + filterFactories[_key - 1] = _arguments[_key]; + } + derivedTable.applyFilter(removeNullAndUndefined(...filterFactories.map((f2) => f2(derivedTable)))); + return derivedTable; + })(); + } + /** + * Executes a callback on a given table and returns a Promise that will resolve + * the next time a particular event type fires on the table. + * @param exec Callback function to execute. + * @param table Table that gets passed to the `exec` function and that is + * subscribed to for a given `eventType`. + * @param eventType The event type to listen for. + * @param timeout If the event doesn't fire within the timeout, the returned + * Promise will be rejected. + * @returns a Promise to the original table that resolves on next `eventType` + * event + */ + static getSortIndex(sort, columnName) { + for (var i = 0; i < sort.length; i += 1) { + var _s$column; + var s = sort[i]; + if (((_s$column = s.column) === null || _s$column === void 0 ? void 0 : _s$column.name) === columnName) { + return i; + } + } + return null; + } + /** + * @param tableSort The sorts from the table to get the sort from + * @param columnName The name of the column to get the sort for + * @returns The sort for the column, or null if it's not sorted + */ + static getSortForColumn(tableSort, columnName) { + var sortIndex = TableUtils.getSortIndex(tableSort, columnName); + if (sortIndex != null) { + return tableSort[sortIndex]; + } + return null; + } + static getFilterText(filter) { + if (filter) { + return filter.toString(); + } + return null; + } + /** Return the valid filter types for the column */ + static getFilterTypes(columnType) { + if (TableUtils.isBooleanType(columnType)) { + return [Type.isTrue, Type.isFalse, Type.isNull]; + } + if (TableUtils.isCharType(columnType) || TableUtils.isNumberType(columnType) || TableUtils.isDateType(columnType)) { + return [Type.eq, Type.notEq, Type.greaterThan, Type.greaterThanOrEqualTo, Type.lessThan, Type.lessThanOrEqualTo]; + } + if (TableUtils.isTextType(columnType)) { + return [Type.eq, Type.eqIgnoreCase, Type.notEq, Type.notEqIgnoreCase, Type.contains, Type.notContains, Type.startsWith, Type.endsWith]; + } + return []; + } + static getNextSort(columns, sorts, columnIndex) { + var column = columns[columnIndex]; + if (column == null) { + return null; + } + var sort = TableUtils.getSortForColumn(sorts, column.name); + if (sort === null) { + return this.makeColumnSort(columns, columnIndex, TableUtils.sortDirection.ascending, false); + } + if (sort.direction === TableUtils.sortDirection.ascending) { + return this.makeColumnSort(columns, columnIndex, TableUtils.sortDirection.descending, false); + } + return null; + } + static makeColumnSort(columns, columnIndex, direction, isAbs) { + var column = columns[columnIndex]; + if (column == null) { + return null; + } + if (direction === TableUtils.sortDirection.none) { + return null; + } + return { + column: { + name: column.name, + type: column.type + }, + isAbs, + direction + }; + } + /** + * Toggles the sort for the specified column + * @param sorts The current sorts from IrisGrid.state + * @param columns The columns to apply the sort to + * @param columnIndex The column index to apply the sort to + * @param addToExisting Add this sort to the existing sort + */ + static toggleSortForColumn(sorts, columns, columnIndex) { + var addToExisting = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false; + if (columns[columnIndex] == null) { + return []; + } + var newSort = TableUtils.getNextSort(columns, sorts, columnIndex); + return TableUtils.setSortForColumn(sorts, columns[columnIndex].name, newSort, addToExisting); + } + static sortColumn(sorts, columns, modelColumn, direction, isAbs, addToExisting) { + if (modelColumn < 0 || modelColumn >= columns.length) { + return []; + } + var newSort = TableUtils.makeColumnSort(columns, modelColumn, direction, isAbs); + return TableUtils.setSortForColumn(sorts, columns[modelColumn].name, newSort, addToExisting); + } + /** + * Sets the sort for the given column *and* removes any reverses + * @param tableSort The current sorts from IrisGrid.state + * @param columnName The column name to apply the sort to + * @param sort The sort object to add + * @param addToExisting Add this sort to the existing sort + * @returns Returns the modified array of sorts - removing reverses + */ + static setSortForColumn(tableSort, columnName, sort) { + var addToExisting = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false; + var sortIndex = TableUtils.getSortIndex(tableSort, columnName); + var sorts = []; + if (addToExisting) { + sorts = sorts.concat(tableSort.filter((_ref) => { + var { + direction + } = _ref; + return direction !== TableUtils.sortDirection.reverse; + })); + if (sortIndex !== null) { + sorts.splice(sortIndex, 1); + } + } + if (sort !== null) { + sorts.push(sort); + } + return sorts; + } + static getNormalizedType(columnType) { + switch (columnType) { + case "boolean": + case "java.lang.Boolean": + case TableUtils.dataType.BOOLEAN: + return TableUtils.dataType.BOOLEAN; + case "char": + case "java.lang.Character": + case TableUtils.dataType.CHAR: + return TableUtils.dataType.CHAR; + case "java.lang.String": + case TableUtils.dataType.STRING: + return TableUtils.dataType.STRING; + case "io.deephaven.db.tables.utils.DBDateTime": + case "io.deephaven.time.DateTime": + case "com.illumon.iris.db.tables.utils.DBDateTime": + case "java.time.Instant": + case "java.time.ZonedDateTime": + case TableUtils.dataType.DATETIME: + return TableUtils.dataType.DATETIME; + case "double": + case "java.lang.Double": + case "float": + case "java.lang.Float": + case "java.math.BigDecimal": + case TableUtils.dataType.DECIMAL: + return TableUtils.dataType.DECIMAL; + case "int": + case "java.lang.Integer": + case "long": + case "java.lang.Long": + case "short": + case "java.lang.Short": + case "byte": + case "java.lang.Byte": + case "java.math.BigInteger": + case TableUtils.dataType.INT: + return TableUtils.dataType.INT; + default: + return TableUtils.dataType.UNKNOWN; + } + } + static isLongType(columnType) { + switch (columnType) { + case "long": + case "java.lang.Long": + return true; + default: + return false; + } + } + static isDateType(columnType) { + switch (columnType) { + case "io.deephaven.db.tables.utils.DBDateTime": + case "io.deephaven.time.DateTime": + case "java.time.Instant": + case "java.time.ZonedDateTime": + case "com.illumon.iris.db.tables.utils.DBDateTime": + return true; + default: + return false; + } + } + static isNumberType(columnType) { + return TableUtils.isIntegerType(columnType) || TableUtils.isDecimalType(columnType); + } + static isIntegerType(columnType) { + switch (columnType) { + case "int": + case "java.lang.Integer": + case "java.math.BigInteger": + case "long": + case "java.lang.Long": + case "short": + case "java.lang.Short": + case "byte": + case "java.lang.Byte": + return true; + default: + return false; + } + } + static isDecimalType(columnType) { + switch (columnType) { + case "double": + case "java.lang.Double": + case "java.math.BigDecimal": + case "float": + case "java.lang.Float": + return true; + default: + return false; + } + } + static isBigDecimalType(columnType) { + switch (columnType) { + case "java.math.BigDecimal": + return true; + default: + return false; + } + } + static isBigIntegerType(columnType) { + switch (columnType) { + case "java.math.BigInteger": + return true; + default: + return false; + } + } + static isBooleanType(columnType) { + switch (columnType) { + case "boolean": + case "java.lang.Boolean": + return true; + default: + return false; + } + } + static isCharType(columnType) { + switch (columnType) { + case "char": + case "java.lang.Character": + return true; + default: + return false; + } + } + static isStringType(columnType) { + switch (columnType) { + case "java.lang.String": + return true; + default: + return false; + } + } + static isTextType(columnType) { + return this.isStringType(columnType) || this.isCharType(columnType); + } + /** + * Get base column type + * @param columnType Column type + * @returns Element type for array columns, original type for non-array columns + */ + static getBaseType(columnType) { + return columnType.split("[]")[0]; + } + /** + * Check if the column types are compatible + * @param type1 Column type to check + * @param type2 Column type to check + * @returns True, if types are compatible + */ + static isCompatibleType(type1, type2) { + return TableUtils.getNormalizedType(type1) === TableUtils.getNormalizedType(type2); + } + /** + * Adds quotes to a value if they're not already added + * @param value Value to add quotes around + */ + static quoteValue(value2) { + if (value2.length >= 2 && (value2.charAt(0) === '"' && value2.charAt(value2.length - 1) === '"' || value2.charAt(0) === "'" && value2.charAt(value2.length - 1) === "'")) { + return value2; + } + return '"'.concat(value2, '"'); + } + static isRangeOperation(operation) { + switch (operation) { + case "<": + case "<=": + case "=<": + case ">": + case ">=": + case "=>": + return true; + default: + return false; + } + } + /** + * @param filter The column filter to apply the range operation to + * @param operation The range operation to run + * @param value The value to use for the operation + * @returns The condition with the specified operation + */ + static makeRangeFilterWithOperation(filter, operation, value2) { + switch (operation) { + case "=": + return filter.eq(value2); + case "<": + return filter.lessThan(value2); + case "<=": + case "=<": + return filter.lessThanOrEqualTo(value2); + case ">": + return filter.greaterThan(value2); + case ">=": + case "=>": + return filter.greaterThanOrEqualTo(value2); + case "!=": + case "!": + return filter.notEq(value2); + default: + return null; + } + } + /** + * Wraps a table promise in a cancelable promise that will close the table if the promise is cancelled. + * Use in a component that loads a table, and call cancel when unmounting. + * @param table The table promise to wrap + */ + static makeCancelableTablePromise(table) { + return PromiseUtils.makeCancelable(table, (resolved) => { + resolved.close(); + }); + } + /** + * Make a cancelable promise for a one-shot table event with a timeout. + * @param table Table to listen for events on + * @param eventName Event to listen for + * @param timeout Event timeout in milliseconds, defaults to 0 + * @param matcher Optional function to determine if the promise can be resolved or stays pending + * @returns Resolves with the event data + */ + static makeCancelableTableEventPromise(table, eventName) { + var timeout = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; + var matcher = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; + var eventCleanup; + var timeoutId; + var isPending = true; + var wrappedPromise = new Promise((resolve, reject) => { + timeoutId = setTimeout(() => { + eventCleanup(); + isPending = false; + reject(new TimeoutError('Event "'.concat(eventName, '" timed out.'))); + }, timeout); + eventCleanup = table.addEventListener(eventName, (event) => { + if (matcher != null && !matcher(event)) { + log$3.debug2("Event triggered, but matcher returned false."); + return; + } + log$3.debug2("Event triggered, resolving."); + eventCleanup(); + clearTimeout(timeoutId); + isPending = false; + resolve(event); + }); + }); + wrappedPromise.cancel = () => { + if (isPending) { + log$3.debug2("Pending promise cleanup."); + eventCleanup(); + clearTimeout(timeoutId); + isPending = false; + return; + } + log$3.debug2("Ignoring non-pending promise cancel."); + }; + return wrappedPromise; + } + static removeCommas(value2) { + return value2.replace(/[\s|,]/g, ""); + } + static makeBooleanValue(text) { + var allowEmpty = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; + if (text === "" && allowEmpty) { + return null; + } + switch (text === null || text === void 0 ? void 0 : text.toLowerCase()) { + case "null": + return null; + case "0": + case "f": + case "fa": + case "fal": + case "fals": + case "false": + case "n": + case "no": + return false; + case "1": + case "t": + case "tr": + case "tru": + case "true": + case "y": + case "ye": + case "yes": + return true; + default: + throw new Error("Invalid boolean '".concat(text, "'")); + } + } + static makeNumberValue(text) { + if (text === "null" || text === "") { + return null; + } + var cleanText = text.toLowerCase().trim(); + if (cleanText === "∞" || cleanText === "infinity" || cleanText === "inf") { + return Number.POSITIVE_INFINITY; + } + if (cleanText === "-∞" || cleanText === "-infinity" || cleanText === "-inf") { + return Number.NEGATIVE_INFINITY; + } + var numberText = TableUtils.removeCommas(cleanText); + if (TableUtils.NUMBER_REGEX.test(numberText)) { + return parseFloat(numberText); + } + throw new Error("Invalid number '".concat(text, "'")); + } + static getFilterOperatorString(operation) { + switch (operation) { + case Type.eq: + return "="; + case Type.notEq: + return "!="; + case Type.greaterThan: + return ">"; + case Type.greaterThanOrEqualTo: + return ">="; + case Type.lessThan: + return "<"; + case Type.lessThanOrEqualTo: + return "<="; + case Type.contains: + return "~"; + case Type.notContains: + return "!~"; + default: + throw new Error("Unexpected filter type ".concat(operation)); + } + } + static isPartitionedTable(table) { + return table != null && table.getMergedTable !== void 0 && table.getKeyTable !== void 0 && table.getKeys !== void 0; + } + static isTreeTable(table) { + return table != null && table.expand !== void 0 && table.collapse !== void 0; + } + /** + * Copies the provided array, sorts by column name case insensitive, and returns the sorted array. + * @param columns The columns to sort + * @param isAscending Whether to sort ascending + */ + static sortColumns(columns) { + var isAscending = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; + return [...columns].sort((a, b) => { + var aName = a.name.toUpperCase(); + var bName = b.name.toUpperCase(); + return TextUtils.sort(aName, bName, isAscending); + }); + } + constructor(dh) { + _defineProperty$3(this, "dh", void 0); + this.dh = dh; + bindAllMethods(this); + } + /** + * Create a table containing a distinct list of values for given column name and + * applies the given sort direction. + * @param table Source table to derive table from + * @param columnName Column to dermine distinct values + * @param sortDirection Direction to sort + * @param filterConditionFactories Optional filters to apply. Note that these + * will be applied before the `selectCall` in case we need to base the filtering + * on columns other than the distinct value column + */ + createDistinctSortedColumnTable(table, columnName, sortDirection) { + var _arguments2 = arguments, _this = this; + return _asyncToGenerator$1(function* () { + if (table == null) { + return null; + } + var sourceTable = table; + for (var _len2 = _arguments2.length, filterConditionFactories = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) { + filterConditionFactories[_key2 - 3] = _arguments2[_key2]; + } + if (filterConditionFactories.length > 0) { + sourceTable = yield table.copy(); + yield sourceTable.applyFilter(removeNullAndUndefined(...filterConditionFactories.map((f2) => f2(sourceTable)))); + } + var column = sourceTable.findColumn(columnName); + var distinctTable = yield sourceTable.selectDistinct([column]); + if (sourceTable !== table) { + sourceTable.close(); + } + var distinctAscColSort = distinctTable.findColumn(columnName).sort()[sortDirection](); + return _this.applySort(distinctTable, [distinctAscColSort]); + })(); + } + /** + * Check if any columns contain a given value. + * @param table Table to search for values + * @param columnNames Column names to search + * @param value Value to search for + * @param isCaseSensitive Whether the value check is case sensitive + */ + doesColumnValueExist(table, columnNames, value2, isCaseSensitive) { + var _this2 = this; + return _asyncToGenerator$1(function* () { + if (table == null) { + return null; + } + var filterConditionFactory = createValueFilter(_this2, columnNames, value2, isCaseSensitive ? "eq" : "eqIgnoreCase"); + var tableCopy = yield table.copy(); + yield _this2.applyFilter(tableCopy, removeNullAndUndefined(filterConditionFactory(tableCopy))); + var size = getSize(tableCopy); + tableCopy.close(); + return size > 0; + })(); + } + /** + * Get the `dh.ValueType` corresponding to the given `dh.Column.type` value. + * @param columnType The column type to get the value type for + * @returns The `dh.ValueType` corresponding to the column type + */ + getValueType(columnType) { + if (columnType == null) { + return this.dh.ValueType.STRING; + } + var columnDataType = TableUtils.getNormalizedType(columnType); + switch (columnDataType) { + case TableUtils.dataType.BOOLEAN: + return this.dh.ValueType.BOOLEAN; + case TableUtils.dataType.CHAR: + case TableUtils.dataType.STRING: + return this.dh.ValueType.STRING; + case TableUtils.dataType.DATETIME: + return this.dh.ValueType.DATETIME; + case TableUtils.dataType.DECIMAL: + case TableUtils.dataType.INT: + if (TableUtils.isBigDecimalType(columnType) || TableUtils.isBigIntegerType(columnType)) { + return this.dh.ValueType.STRING; + } + return this.dh.ValueType.NUMBER; + default: + return this.dh.ValueType.STRING; + } + } + /** + * Create filter with the provided column and text. Handles multiple filters joined with && or || + * @param column The column to set the filter on + * @param text The text string to create the filter from + * @param timeZone The time zone to make this value in if it is a date type. E.g. America/New_York + * @returns Returns the created filter, null if text could not be parsed + */ + makeQuickFilter(column, text, timeZone) { + var orComponents = text.split("||"); + var orFilter = null; + for (var i = 0; i < orComponents.length; i += 1) { + var orComponent = orComponents[i]; + var andComponents = orComponent.split("&&"); + var andFilter = null; + for (var j = 0; j < andComponents.length; j += 1) { + var andComponent = andComponents[j].trim(); + if (andComponent.length > 0) { + var filter = this.makeQuickFilterFromComponent(column, andComponent, timeZone); + if (filter) { + if (andFilter) { + andFilter = andFilter.and(filter); + } else { + andFilter = filter; + } + } else { + throw new Error("Unable to parse quick filter from text ".concat(text)); + } + } + } + if (orFilter && andFilter) { + orFilter = orFilter.or(andFilter); + } else { + orFilter = andFilter; + } + } + return orFilter; + } + /** + * Create filter with the provided column and text of one component (no multiple conditions) + * @param column The column to set the filter on + * @param text The text string to create the filter from + * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York + * @returns Returns the created filter, null if text could not be parsed + */ + makeQuickFilterFromComponent(column, text, timeZone) { + var { + type + } = column; + if (TableUtils.isNumberType(type)) { + return this.makeQuickNumberFilter(column, text); + } + if (TableUtils.isBooleanType(type)) { + return this.makeQuickBooleanFilter(column, text); + } + if (timeZone != null && TableUtils.isDateType(type)) { + return this.makeQuickDateFilter(column, text, timeZone); + } + if (TableUtils.isCharType(type)) { + return this.makeQuickCharFilter(column, text); + } + return this.makeQuickTextFilter(column, text); + } + makeQuickNumberFilter(column, text) { + var columnFilter = column.filter(); + var { + dh + } = this; + var filter = null; + var regex = /\s*(>=|<=|=>|=<|>|<|!=|=|!)?(\s*-\s*)?(\s*\d*(?:,\d{3})*(?:\.\d*)?\s*)?(null|nan|infinity|inf|\u221E)?(.*)/i; + var result = regex.exec(text); + var operation = null; + var negativeSign = null; + var value2 = null; + var abnormalValue = null; + var overflow = null; + if (result !== null && result.length > 3) { + [, operation, negativeSign, value2, abnormalValue, overflow] = result; + } + if (overflow != null && overflow.trim().length > 0) { + return null; + } + if (operation == null) { + operation = "="; + } + if (abnormalValue != null) { + if (!(operation === "=" || operation === "!" || operation === "!=")) { + return null; + } + abnormalValue = abnormalValue.trim().toLowerCase(); + switch (abnormalValue) { + case "null": + filter = columnFilter.isNull(); + break; + case "nan": + filter = dh.FilterCondition.invoke("isNaN", columnFilter); + break; + case "infinity": + case "inf": + case "∞": + if (negativeSign != null) { + filter = dh.FilterCondition.invoke("isInf", columnFilter).and(columnFilter.lessThan(dh.FilterValue.ofNumber(0))); + } else { + filter = dh.FilterCondition.invoke("isInf", columnFilter).and(columnFilter.greaterThan(dh.FilterValue.ofNumber(0))); + } + break; + } + if (filter !== null && (operation === "!" || operation === "!=")) { + filter = filter.not(); + } + return filter; + } + if (value2 == null) { + return null; + } + value2 = TableUtils.removeCommas(value2); + if (TableUtils.isLongType(column.type)) { + try { + value2 = dh.FilterValue.ofNumber(dh.LongWrapper.ofString("".concat(negativeSign != null ? "-" : "").concat(value2))); + } catch (error) { + log$3.warn("Unable to create long filter", error); + return null; + } + } else { + value2 = parseFloat(value2); + if (value2 == null || Number.isNaN(value2)) { + return null; + } + value2 = dh.FilterValue.ofNumber(negativeSign != null ? 0 - value2 : value2); + } + filter = column.filter(); + return TableUtils.makeRangeFilterWithOperation(filter, operation, value2); + } + /** + * Given a text string from a table, escape quick filter operators in string with \ + * ex. =test returns \=test, null returns \null + * @param string quickfilter string to escape + * @returns escaped string + */ + static escapeQuickTextFilter(quickFilterText) { + var _operation, _value2; + if (quickFilterText == null) return null; + var regex = /^(!~|!=|~|=|!)?(.*)/; + var nullRegex = /^\\*null$/; + var result = regex.exec(quickFilterText); + var operation = null; + var value2 = null; + if (result !== null && result.length > 2) { + [, operation, value2] = result; + } + if (operation != null) { + var _value; + return "\\".concat(operation).concat((_value = value2) !== null && _value !== void 0 ? _value : ""); + } + if (value2 != null && nullRegex.test(value2.toLowerCase())) { + return "\\".concat(value2); + } + if (value2 != null && value2.startsWith("*")) { + return "\\".concat(value2); + } + if (value2 != null && value2.endsWith("*") && !value2.endsWith("\\*")) { + value2 = value2.substring(0, value2.length - 1); + return "".concat(value2, "\\*"); + } + return "".concat((_operation = operation) !== null && _operation !== void 0 ? _operation : "").concat((_value2 = value2) !== null && _value2 !== void 0 ? _value2 : ""); + } + /** + * Given an escaped quick filter, unescape the operators for giving it to the js api + * ex. \=test returns =test, \null returns null + * @param string quickfilter string to escape + * @returns escaped string + */ + static unescapeQuickTextFilter(quickFilterText) { + var _operation2, _value3; + var regex = /^(\\!~|\\!=|\\~|\\=|\\!)?(.*)/; + var nullRegex = /^\\*null$/; + var result = regex.exec(quickFilterText); + var operation = null; + var value2 = null; + if (result !== null && result.length > 2) { + [, operation, value2] = result; + } + if (operation != null) { + operation = operation.replace("\\", ""); + } + if (value2 != null && nullRegex.test(value2.toLowerCase())) { + value2 = value2.replace("\\", ""); + } + if (operation == null && value2 != null && value2.startsWith("\\*")) { + value2 = value2.substring(1); + } + if (operation == null && value2 != null && value2.endsWith("\\*")) { + value2 = value2.substring(0, value2.length - 2); + return "".concat(value2, "*"); + } + return "".concat((_operation2 = operation) !== null && _operation2 !== void 0 ? _operation2 : "").concat((_value3 = value2) !== null && _value3 !== void 0 ? _value3 : ""); + } + makeQuickTextFilter(column, text) { + var { + dh + } = this; + var cleanText = "".concat(text).trim(); + var regex = /^(!~|!=|~|=|!)?(.*)/; + var result = regex.exec(cleanText); + var operation = null; + var value2 = null; + if (result !== null && result.length > 2) { + [, operation, value2] = result; + if (value2 != null) { + value2 = value2.trim(); + } + } + if (value2 == null) { + return null; + } + if (value2.length === 0 && !(operation === "=" || operation === "!=")) { + return null; + } + if (operation == null) { + operation = "="; + } + var filter = column.filter(); + if (value2.toLowerCase() === "null") { + switch (operation) { + case "=": + return filter.isNull(); + case "!=": + case "!": + return filter.isNull().not(); + } + } + var prefix = null; + var suffix = null; + if (value2.startsWith("*")) { + prefix = "*"; + value2 = value2.substring(1); + } else if (value2.endsWith("*") && !value2.endsWith("\\*")) { + suffix = "*"; + value2 = value2.substring(0, value2.length - 1); + } + value2 = TableUtils.unescapeQuickTextFilter(value2); + switch (operation) { + case "~": { + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*")))); + } + case "!~": + return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*"))).not()); + case "!=": + if (prefix === "*") { + return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$"))).not()); + } + if (suffix === "*") { + return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*"))).not()); + } + return filter.notEqIgnoreCase(dh.FilterValue.ofString(value2.toLowerCase())); + case "=": + if (prefix === "*") { + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$")))); + } + if (suffix === "*") { + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*")))); + } + return filter.eqIgnoreCase(dh.FilterValue.ofString(value2.toLowerCase())); + } + return null; + } + // eslint-disable-next-line class-methods-use-this + makeQuickBooleanFilter(column, text) { + var regex = /^(!=|=|!)?(.*)/; + var result = regex.exec("".concat(text).trim()); + if (result === null) { + return null; + } + var [, operation, value2] = result; + var notEqual = operation === "!" || operation === "!="; + var cleanValue = value2.trim().toLowerCase(); + var filter = column.filter(); + try { + var boolValue = TableUtils.makeBooleanValue(cleanValue); + if (boolValue != null && boolValue) { + filter = filter.isTrue(); + } else if (boolValue === null) { + filter = filter.isNull(); + } else { + filter = filter.isFalse(); + } + return notEqual ? filter.not() : filter; + } catch (e) { + return null; + } + } + /** + * Builds a date filter parsed from the text string which may or may not include an operator. + * @param column The column to build the filter from, with or without a leading operator. + * @param text The date string text to parse. + * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York + */ + makeQuickDateFilter(column, text, timeZone) { + var cleanText = text.trim(); + var regex = /\s*(>=|<=|=>|=<|>|<|!=|!|=)?(.*)/; + var result = regex.exec(cleanText); + if (result == null || result.length <= 2) { + throw new Error("Unable to parse date filter: ".concat(text)); + } + var operation = null; + var dateText = null; + [, operation, dateText] = result; + var filterOperation = Type.eq; + switch (operation) { + case "<": + filterOperation = Type.lessThan; + break; + case "<=": + case "=<": + filterOperation = Type.lessThanOrEqualTo; + break; + case ">": + filterOperation = Type.greaterThan; + break; + case ">=": + case "=>": + filterOperation = Type.greaterThanOrEqualTo; + break; + case "!=": + case "!": + filterOperation = Type.notEq; + break; + case "=": + case "==": + default: + filterOperation = Type.eq; + break; + } + return this.makeQuickDateFilterWithOperation(column, dateText, filterOperation, timeZone); + } + /** + * Builds a date filter parsed from the text string with the provided filter. + * @param column The column to build the filter from. + * @param text The date string text to parse, without an operator. + * @param operation The filter operation to use. + * @param timeZone The time zone to make this filter with. E.g. America/New_York + */ + makeQuickDateFilterWithOperation(column, text, operation, timeZone) { + var { + dh + } = this; + var [startDate, endDate] = DateUtils.parseDateRange(dh, text, timeZone); + var startValue = startDate != null ? dh.FilterValue.ofNumber(startDate) : null; + var endValue = endDate != null ? dh.FilterValue.ofNumber(endDate) : null; + var filter = column.filter(); + if (startValue == null) { + return operation === Type.notEq ? filter.isNull().not() : filter.isNull(); + } + switch (operation) { + case Type.eq: { + if (endValue != null) { + var startFilter = filter.greaterThanOrEqualTo(startValue); + var endFilter = filter.lessThan(endValue); + return startFilter.and(endFilter); + } + return filter.eq(startValue); + } + case Type.lessThan: { + return filter.lessThan(startValue); + } + case Type.lessThanOrEqualTo: { + if (endValue != null) { + return filter.lessThan(endValue); + } + return filter.lessThanOrEqualTo(startValue); + } + case Type.greaterThan: { + if (endValue != null) { + return filter.greaterThanOrEqualTo(endValue); + } + return filter.greaterThan(startValue); + } + case Type.greaterThanOrEqualTo: + return filter.greaterThanOrEqualTo(startValue); + case Type.notEq: { + if (endValue != null) { + var _startFilter = filter.lessThan(startValue); + var _endFilter = filter.greaterThanOrEqualTo(endValue); + return _startFilter.or(_endFilter); + } + return filter.notEq(startValue); + } + default: + throw new Error("Invalid operator: ".concat(operation)); + } + } + makeQuickCharFilter(column, text) { + var { + dh + } = this; + var cleanText = "".concat(text).trim(); + var regex = /^(>=|<=|=>|=<|>|<|!=|=|!)?(null|"."|'.'|.)?(.*)/; + var result = regex.exec(cleanText); + var operation = null; + var value2 = null; + var overflow = null; + if (result !== null && result.length > 3) { + [, operation, value2, overflow] = result; + } + if (overflow != null && overflow.trim().length > 0) { + return null; + } + if (value2 == null || value2.length === 0) { + return null; + } + if (operation == null) { + operation = "="; + } + var filter = column.filter(); + if (value2.toLowerCase() === "null") { + switch (operation) { + case "=": + return filter.isNull(); + case "!=": + case "!": + return filter.isNull().not(); + default: + return null; + } + } + var filterValue = dh.FilterValue.ofString(TableUtils.isRangeOperation(operation) ? TableUtils.quoteValue(value2) : value2); + return TableUtils.makeRangeFilterWithOperation(filter, operation, filterValue); + } + makeAdvancedFilter(column, options, timeZone) { + var { + filterItems, + filterOperators, + invertSelection, + selectedValues + } = options; + var filter = null; + for (var i = 0; i < filterItems.length; i += 1) { + var filterItem = filterItems[i]; + var { + selectedType, + value: value2 + } = filterItem; + if (selectedType != null && selectedType.length > 0 && value2 != null && value2.length > 0) { + try { + var newFilter = this.makeAdvancedValueFilter(column, selectedType, value2, timeZone); + if (newFilter != null) { + if (i === 0) { + filter = newFilter; + } else if (filter !== null && i - 1 < filterOperators.length) { + var filterOperator = filterOperators[i - 1]; + if (filterOperator === Operator.and) { + filter = filter.and(newFilter); + } else if (filterOperator === Operator.or) { + filter = filter.or(newFilter); + } else { + log$3.error("Unexpected filter operator", filterOperator, newFilter); + filter = null; + break; + } + } + } else { + log$3.debug2("Empty filter ignored for", selectedType, value2); + } + } catch (err) { + log$3.error("Unable to create filter", err); + filter = null; + break; + } + } + } + var selectValueFilter = this.makeSelectValueFilter(column, selectedValues, invertSelection); + if (selectValueFilter != null) { + if (filter != null) { + filter = filter.and(selectValueFilter); + } else { + filter = selectValueFilter; + } + } + return filter; + } + makeAdvancedValueFilter(column, operation, value2, timeZone) { + var { + dh + } = this; + if (TableUtils.isDateType(column.type)) { + return this.makeQuickDateFilterWithOperation(column, value2, operation, timeZone); + } + if (TableUtils.isNumberType(column.type) || TableUtils.isCharType(column.type)) { + return this.makeQuickFilter(column, "".concat(TableUtils.getFilterOperatorString(operation)).concat(value2)); + } + var filterValue = this.makeFilterValue(column.type, value2); + var filter = column.filter(); + switch (operation) { + case Type.eq: + return filter.eq(filterValue); + case Type.eqIgnoreCase: + return filter.eqIgnoreCase(filterValue); + case Type.notEq: + return filter.notEq(filterValue); + case Type.notEqIgnoreCase: + return filter.notEqIgnoreCase(filterValue); + case Type.greaterThan: + return filter.greaterThan(filterValue); + case Type.greaterThanOrEqualTo: + return filter.greaterThanOrEqualTo(filterValue); + case Type.lessThan: + return filter.lessThan(filterValue); + case Type.lessThanOrEqualTo: + return filter.lessThanOrEqualTo(filterValue); + case Type.isTrue: + return filter.isTrue(); + case Type.isFalse: + return filter.isFalse(); + case Type.isNull: + return filter.isNull(); + case Type.contains: + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*")))); + case Type.notContains: + return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*"))).not()); + case Type.startsWith: + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*")))); + case Type.endsWith: + return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$")))); + case Type.in: + case Type.inIgnoreCase: + case Type.notIn: + case Type.notInIgnoreCase: + case Type.invoke: + default: + throw new Error("Unexpected filter operation: ".concat(operation)); + } + } + /** + * Create a filter condition that can search a column by a given `searchText` + * value. + * @param column The column to search + * @param searchText The text to search for + * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York + * @returns The filter condition that can be applied to the column + */ + makeSearchTextFilter(column, searchText, timeZone) { + var valueType = this.getValueType(column.type); + try { + if (valueType === this.dh.ValueType.BOOLEAN) { + var maybeFilterCondition = this.makeQuickBooleanFilter(column, searchText); + assertNotNull(maybeFilterCondition); + return maybeFilterCondition; + } + if (valueType === this.dh.ValueType.DATETIME) { + return this.makeQuickDateFilterWithOperation(column, DateUtils.trimDateTimeStringTimeZone(searchText), "eq", timeZone); + } + if (valueType === this.dh.ValueType.NUMBER) { + var _maybeFilterCondition = this.makeQuickNumberFilter(column, searchText); + assertNotNull(_maybeFilterCondition); + return _maybeFilterCondition; + } + if (TableUtils.isBigDecimalType(column.type) || TableUtils.isBigIntegerType(column.type)) { + return column.filter().eq(this.makeFilterValue(column.type, searchText)); + } + return column.filter().containsIgnoreCase(this.makeFilterValue(column.type, searchText)); + } catch (_unused) { + return this.makeNeverFilter(column); + } + } + /** + * Apply a filter to a table that won't match anything. + * @table The table to apply the filter to + * @columnName The name of the column to apploy the filter to + * @param timeout Timeout before cancelling the promise that waits for the next + * dh.Table.EVENT_FILTERCHANGED event + * @returns a Promise to the Table that resolves after the next + * dh.Table.EVENT_FILTERCHANGED event + */ + applyNeverFilter(table, columnName) { + var _arguments3 = arguments, _this3 = this; + return _asyncToGenerator$1(function* () { + var timeout = _arguments3.length > 2 && _arguments3[2] !== void 0 ? _arguments3[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; + if (table == null) { + return null; + } + var column = table.findColumn(columnName); + var filters = [_this3.makeNeverFilter(column)]; + yield _this3.applyFilter(table, filters, timeout); + return table; + })(); + } + /** + * Apply custom columns to a given table. Return a Promise that resolves with + * the table once the dh.Table.EVENT_CUSTOMCOLUMNSCHANGED event has fired. + * @param table The table to apply custom columns to. + * @param columns The list of column expressions or definitions to apply. + * @returns A Promise that will be resolved with the given table after the + * columns are applied. + */ + applyCustomColumns(table, columns) { + var _arguments4 = arguments, _this4 = this; + return _asyncToGenerator$1(function* () { + var timeout = _arguments4.length > 2 && _arguments4[2] !== void 0 ? _arguments4[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; + var { + dh + } = _this4; + return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applyCustomColumns(columns), table, dh.Table.EVENT_CUSTOMCOLUMNSCHANGED, timeout); + })(); + } + /** + * Apply filters to a given table. + * @param table Table to apply filters to + * @param filters Filters to apply + * @param timeout Timeout before cancelling the promise that waits for the next + * dh.Table.EVENT_FILTERCHANGED event + * @returns a Promise to the Table that resolves after the next + * dh.Table.EVENT_FILTERCHANGED event + */ + applyFilter(table, filters) { + var _arguments5 = arguments, _this5 = this; + return _asyncToGenerator$1(function* () { + var timeout = _arguments5.length > 2 && _arguments5[2] !== void 0 ? _arguments5[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; + var { + dh + } = _this5; + return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applyFilter(filters), table, dh.Table.EVENT_FILTERCHANGED, timeout); + })(); + } + /** + * Apply sorts to a given Table. + * @param table The table to apply sorts to + * @param sorts The sorts to apply + * @param timeout Timeout before cancelling the promise that waits for the next + * dh.Table.EVENT_SORTCHANGED event + * @returns a Promise to the Table that resolves after the next + * dh.Table.EVENT_SORTCHANGED event + */ + applySort(table, sorts) { + var _arguments6 = arguments, _this6 = this; + return _asyncToGenerator$1(function* () { + var timeout = _arguments6.length > 2 && _arguments6[2] !== void 0 ? _arguments6[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; + var { + dh + } = _this6; + return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applySort(sorts), table, dh.Table.EVENT_SORTCHANGED, timeout); + })(); + } + /** + * Create a filter condition that results in zero results for a given column + * @param column + */ + makeNeverFilter(column) { + var { + dh + } = this; + var value2 = null; + if (TableUtils.isTextType(column.type)) { + value2 = dh.FilterValue.ofString("a"); + } else if (TableUtils.isBooleanType(column.type)) { + value2 = dh.FilterValue.ofBoolean(true); + } else if (TableUtils.isDateType(column.type)) { + value2 = dh.FilterValue.ofNumber(dh.DateWrapper.ofJsDate(/* @__PURE__ */ new Date())); + } else { + value2 = dh.FilterValue.ofNumber(0); + } + var eqFilter = column.filter().eq(value2); + var notEqFilter = column.filter().notEq(value2); + return eqFilter.and(notEqFilter); + } + /** + * @param columnType The column type to make the filter value from. + * @param value The value to make the filter value from. + * @returns The FilterValue item for this column/value combination + */ + makeFilterValue(columnType, value2) { + var { + dh + } = this; + var type = TableUtils.getBaseType(columnType); + if (TableUtils.isTextType(type)) { + return dh.FilterValue.ofString(value2); + } + if (TableUtils.isLongType(type)) { + return dh.FilterValue.ofNumber(dh.LongWrapper.ofString(TableUtils.removeCommas(value2))); + } + return dh.FilterValue.ofNumber(TableUtils.removeCommas(value2)); + } + /** + * Takes a value and converts it to an `dh.FilterValue` + * + * @param columnType The column type to make the filter value from. + * @param value The value to actually set + * @returns The FilterValue item for this column/value combination + */ + makeFilterRawValue(columnType, rawValue) { + var { + dh + } = this; + if (TableUtils.isCharType(columnType)) { + return dh.FilterValue.ofString(typeof rawValue === "number" ? String.fromCharCode(rawValue) : rawValue); + } + if (TableUtils.isTextType(columnType)) { + return dh.FilterValue.ofString(rawValue); + } + if (TableUtils.isBooleanType(columnType)) { + return dh.FilterValue.ofBoolean(rawValue); + } + return dh.FilterValue.ofNumber(rawValue); + } + /** + * Creates an Eq filter for the given column and raw value + * @param column The column to set the filter on + * @param rawValue The nullable value to filter on + * @returns The filter for this column/value combination + */ + makeNullableEqFilter(column, rawValue) { + if (rawValue == null) { + return column.filter().isNull(); + } + return column.filter().eq(this.makeFilterRawValue(column.type, rawValue)); + } + /** + * Converts a string value to a value appropriate for the column + * @param columnType The column type to make the value for + * @param text The string value to make a type for + * @param timeZone The time zone to make this value in if it is a date type. E.g. America/New_York + */ + makeValue(columnType, text, timeZone) { + var { + dh + } = this; + if (text === "null") { + return null; + } + if (TableUtils.isTextType(columnType)) { + return text; + } + if (TableUtils.isLongType(columnType)) { + return dh.LongWrapper.ofString(TableUtils.removeCommas(text)); + } + if (TableUtils.isBooleanType(columnType)) { + return TableUtils.makeBooleanValue(text, true); + } + if (TableUtils.isDateType(columnType)) { + var [date] = DateUtils.parseDateRange(dh, text, timeZone); + return date; + } + if (TableUtils.isNumberType(columnType)) { + return TableUtils.makeNumberValue(text); + } + log$3.error("Unexpected column type", columnType); + return null; + } + /** + * Create a filter using the selected items + * Has a flag for invertSelection as we start from a "Select All" state and a user just deselects items. + * Since there may be millions of distinct items, it's easier to build an inverse filter. + * @param column The column to set the filter on + * @param selectedValues The values that are selected + * @param invertSelection Invert the selection (eg. All items are selected, then you deselect items) + * @returns Returns a `in` or `notIn` FilterCondition as necessary, or null if no filtering should be applied (everything selected) + */ + makeSelectValueFilter(column, selectedValues, invertSelection) { + var { + dh + } = this; + if (selectedValues.length === 0) { + if (invertSelection) { + return null; + } + return this.makeNeverFilter(column); + } + var values = []; + var isNullSelected = false; + for (var i = 0; i < selectedValues.length; i += 1) { + var value2 = selectedValues[i]; + if (value2 == null) { + isNullSelected = true; + } else if (TableUtils.isTextType(column.type)) { + values.push(dh.FilterValue.ofString(typeof value2 === "number" ? String.fromCharCode(value2) : value2)); + } else if (TableUtils.isBooleanType(column.type)) { + values.push(dh.FilterValue.ofBoolean(Boolean(value2))); + } else { + values.push(dh.FilterValue.ofNumber(value2)); + } + } + if (isNullSelected) { + if (values.length > 0) { + if (invertSelection) { + return column.filter().isNull().not().and(column.filter().notIn(values)); + } + return column.filter().isNull().or(column.filter().in(values)); + } + if (invertSelection) { + return column.filter().isNull().not(); + } + return column.filter().isNull(); + } + if (invertSelection) { + return column.filter().notIn(values); + } + return column.filter().in(values); + } +} +_defineProperty$3(TableUtils, "dataType", { + BOOLEAN: "boolean", + CHAR: "char", + DATETIME: "datetime", + DECIMAL: "decimal", + INT: "int", + STRING: "string", + UNKNOWN: "unknown" +}); +_defineProperty$3(TableUtils, "sortDirection", { + ascending: "ASC", + descending: "DESC", + reverse: "REVERSE", + none: null +}); +_defineProperty$3(TableUtils, "APPLY_TABLE_CHANGE_TIMEOUT_MS", 3e4); +_defineProperty$3(TableUtils, "REVERSE_TYPE", Object.freeze({ + NONE: "none", + PRE_SORT: "pre-sort", + POST_SORT: "post-sort" +})); +_defineProperty$3(TableUtils, "NUMBER_REGEX", /^-?\d+(\.\d+)?$/); +_defineProperty$3(TableUtils, "executeAndWaitForEvent", /* @__PURE__ */ function() { + var _ref2 = _asyncToGenerator$1(function* (exec, table, eventType) { + var timeout = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; + if (table == null) { + return null; + } + var eventPromise = TableUtils.makeCancelableTableEventPromise(table, eventType, timeout); + exec(table); + yield eventPromise; + return table; + }); + return function(_x, _x2, _x3) { + return _ref2.apply(this, arguments); + }; +}()); +var lodash = { exports: {} }; +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +lodash.exports; +(function(module2, exports2) { + (function() { + var undefined$1; + var VERSION = "4.17.21"; + var LARGE_ARRAY_SIZE = 200; + var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; + var HASH_UNDEFINED = "__lodash_hash_undefined__"; + var MAX_MEMOIZE_SIZE = 500; + var PLACEHOLDER = "__lodash_placeholder__"; + var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; + var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; + var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; + var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; + var HOT_COUNT = 800, HOT_SPAN = 16; + var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; + var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; + var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; + var wrapFlags = [ + ["ary", WRAP_ARY_FLAG], + ["bind", WRAP_BIND_FLAG], + ["bindKey", WRAP_BIND_KEY_FLAG], + ["curry", WRAP_CURRY_FLAG], + ["curryRight", WRAP_CURRY_RIGHT_FLAG], + ["flip", WRAP_FLIP_FLAG], + ["partial", WRAP_PARTIAL_FLAG], + ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], + ["rearg", WRAP_REARG_FLAG] + ]; + var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; + var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; + var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); + var reTrimStart = /^\s+/; + var reWhitespace = /\s/; + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + var reEscapeChar = /\\(\\)?/g; + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + var reFlags = /\w*$/; + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var reIsBinary = /^0b[01]+$/i; + var reIsHostCtor = /^\[object .+?Constructor\]$/; + var reIsOctal = /^0o[0-7]+$/i; + var reIsUint = /^(?:0|[1-9]\d*)$/; + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var reNoMatch = /($^)/; + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; + var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; + var reApos = RegExp(rsApos, "g"); + var reComboMark = RegExp(rsCombo, "g"); + var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); + var reUnicodeWord = RegExp([ + rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", + rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", + rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, + rsUpper + "+" + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join("|"), "g"); + var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + var contextProps = [ + "Array", + "Buffer", + "DataView", + "Date", + "Error", + "Float32Array", + "Float64Array", + "Function", + "Int8Array", + "Int16Array", + "Int32Array", + "Map", + "Math", + "Object", + "Promise", + "RegExp", + "Set", + "String", + "Symbol", + "TypeError", + "Uint8Array", + "Uint8ClampedArray", + "Uint16Array", + "Uint32Array", + "WeakMap", + "_", + "clearTimeout", + "isFinite", + "parseInt", + "setTimeout" + ]; + var templateCounter = -1; + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; + var deburredLetters = { + // Latin-1 Supplement block. + "À": "A", + "Á": "A", + "Â": "A", + "Ã": "A", + "Ä": "A", + "Å": "A", + "à": "a", + "á": "a", + "â": "a", + "ã": "a", + "ä": "a", + "å": "a", + "Ç": "C", + "ç": "c", + "Ð": "D", + "ð": "d", + "È": "E", + "É": "E", + "Ê": "E", + "Ë": "E", + "è": "e", + "é": "e", + "ê": "e", + "ë": "e", + "Ì": "I", + "Í": "I", + "Î": "I", + "Ï": "I", + "ì": "i", + "í": "i", + "î": "i", + "ï": "i", + "Ñ": "N", + "ñ": "n", + "Ò": "O", + "Ó": "O", + "Ô": "O", + "Õ": "O", + "Ö": "O", + "Ø": "O", + "ò": "o", + "ó": "o", + "ô": "o", + "õ": "o", + "ö": "o", + "ø": "o", + "Ù": "U", + "Ú": "U", + "Û": "U", + "Ü": "U", + "ù": "u", + "ú": "u", + "û": "u", + "ü": "u", + "Ý": "Y", + "ý": "y", + "ÿ": "y", + "Æ": "Ae", + "æ": "ae", + "Þ": "Th", + "þ": "th", + "ß": "ss", + // Latin Extended-A block. + "Ā": "A", + "Ă": "A", + "Ą": "A", + "ā": "a", + "ă": "a", + "ą": "a", + "Ć": "C", + "Ĉ": "C", + "Ċ": "C", + "Č": "C", + "ć": "c", + "ĉ": "c", + "ċ": "c", + "č": "c", + "Ď": "D", + "Đ": "D", + "ď": "d", + "đ": "d", + "Ē": "E", + "Ĕ": "E", + "Ė": "E", + "Ę": "E", + "Ě": "E", + "ē": "e", + "ĕ": "e", + "ė": "e", + "ę": "e", + "ě": "e", + "Ĝ": "G", + "Ğ": "G", + "Ġ": "G", + "Ģ": "G", + "ĝ": "g", + "ğ": "g", + "ġ": "g", + "ģ": "g", + "Ĥ": "H", + "Ħ": "H", + "ĥ": "h", + "ħ": "h", + "Ĩ": "I", + "Ī": "I", + "Ĭ": "I", + "Į": "I", + "İ": "I", + "ĩ": "i", + "ī": "i", + "ĭ": "i", + "į": "i", + "ı": "i", + "Ĵ": "J", + "ĵ": "j", + "Ķ": "K", + "ķ": "k", + "ĸ": "k", + "Ĺ": "L", + "Ļ": "L", + "Ľ": "L", + "Ŀ": "L", + "Ł": "L", + "ĺ": "l", + "ļ": "l", + "ľ": "l", + "ŀ": "l", + "ł": "l", + "Ń": "N", + "Ņ": "N", + "Ň": "N", + "Ŋ": "N", + "ń": "n", + "ņ": "n", + "ň": "n", + "ŋ": "n", + "Ō": "O", + "Ŏ": "O", + "Ő": "O", + "ō": "o", + "ŏ": "o", + "ő": "o", + "Ŕ": "R", + "Ŗ": "R", + "Ř": "R", + "ŕ": "r", + "ŗ": "r", + "ř": "r", + "Ś": "S", + "Ŝ": "S", + "Ş": "S", + "Š": "S", + "ś": "s", + "ŝ": "s", + "ş": "s", + "š": "s", + "Ţ": "T", + "Ť": "T", + "Ŧ": "T", + "ţ": "t", + "ť": "t", + "ŧ": "t", + "Ũ": "U", + "Ū": "U", + "Ŭ": "U", + "Ů": "U", + "Ű": "U", + "Ų": "U", + "ũ": "u", + "ū": "u", + "ŭ": "u", + "ů": "u", + "ű": "u", + "ų": "u", + "Ŵ": "W", + "ŵ": "w", + "Ŷ": "Y", + "ŷ": "y", + "Ÿ": "Y", + "Ź": "Z", + "Ż": "Z", + "Ž": "Z", + "ź": "z", + "ż": "z", + "ž": "z", + "IJ": "IJ", + "ij": "ij", + "Œ": "Oe", + "œ": "oe", + "ʼn": "'n", + "ſ": "s" + }; + var htmlEscapes = { + "&": "&", + "<": "<", + ">": ">", + '"': """, + "'": "'" + }; + var htmlUnescapes = { + "&": "&", + "<": "<", + ">": ">", + """: '"', + "'": "'" + }; + var stringEscapes = { + "\\": "\\", + "'": "'", + "\n": "n", + "\r": "r", + "\u2028": "u2028", + "\u2029": "u2029" + }; + var freeParseFloat = parseFloat, freeParseInt = parseInt; + var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; + var freeSelf = typeof self == "object" && self && self.Object === Object && self; + var root = freeGlobal || freeSelf || Function("return this")(); + var freeExports = exports2 && !exports2.nodeType && exports2; + var freeModule = freeExports && true && module2 && !module2.nodeType && module2; + var moduleExports = freeModule && freeModule.exports === freeExports; + var freeProcess = moduleExports && freeGlobal.process; + var nodeUtil = function() { + try { + var types = freeModule && freeModule.require && freeModule.require("util").types; + if (types) { + return types; + } + return freeProcess && freeProcess.binding && freeProcess.binding("util"); + } catch (e) { + } + }(); + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + function apply2(func, thisArg, args) { + switch (args.length) { + case 0: + return func.call(thisArg); + case 1: + return func.call(thisArg, args[0]); + case 2: + return func.call(thisArg, args[0], args[1]); + case 3: + return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); + } + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + var value2 = array[index]; + setter(accumulator, value2, iteratee(value2), array); + } + return accumulator; + } + function arrayEach(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; + } + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; + } + function arrayEvery(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; + } + function arrayFilter(array, predicate) { + var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; + while (++index < length) { + var value2 = array[index]; + if (predicate(value2, index, array)) { + result[resIndex++] = value2; + } + } + return result; + } + function arrayIncludes(array, value2) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value2, 0) > -1; + } + function arrayIncludesWith(array, value2, comparator) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (comparator(value2, array[index])) { + return true; + } + } + return false; + } + function arrayMap(array, iteratee) { + var index = -1, length = array == null ? 0 : array.length, result = Array(length); + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; + } + function arrayPush(array, values) { + var index = -1, length = values.length, offset = array.length; + while (++index < length) { + array[offset + index] = values[index]; + } + return array; + } + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; + } + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } + function arraySome(array, predicate) { + var index = -1, length = array == null ? 0 : array.length; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; + } + var asciiSize = baseProperty("length"); + function asciiToArray(string) { + return string.split(""); + } + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value2, key, collection2) { + if (predicate(value2, key, collection2)) { + result = key; + return false; + } + }); + return result; + } + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, index = fromIndex + (fromRight ? 1 : -1); + while (fromRight ? index-- : ++index < length) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; + } + function baseIndexOf(array, value2, fromIndex) { + return value2 === value2 ? strictIndexOf(array, value2, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); + } + function baseIndexOfWith(array, value2, fromIndex, comparator) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (comparator(array[index], value2)) { + return index; + } + } + return -1; + } + function baseIsNaN(value2) { + return value2 !== value2; + } + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? baseSum(array, iteratee) / length : NAN; + } + function baseProperty(key) { + return function(object) { + return object == null ? undefined$1 : object[key]; + }; + } + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined$1 : object[key]; + }; + } + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value2, index, collection2) { + accumulator = initAccum ? (initAccum = false, value2) : iteratee(accumulator, value2, index, collection2); + }); + return accumulator; + } + function baseSortBy(array, comparer) { + var length = array.length; + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + function baseSum(array, iteratee) { + var result, index = -1, length = array.length; + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined$1) { + result = result === undefined$1 ? current : result + current; + } + } + return result; + } + function baseTimes(n2, iteratee) { + var index = -1, result = Array(n2); + while (++index < n2) { + result[index] = iteratee(index); + } + return result; + } + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } + function baseTrim(string) { + return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; + } + function baseUnary(func) { + return function(value2) { + return func(value2); + }; + } + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + function cacheHas(cache, key) { + return cache.has(key); + } + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, length = strSymbols.length; + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { + } + return index; + } + function countHolders(array, placeholder) { + var length = array.length, result = 0; + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; + } + var deburrLetter = basePropertyOf(deburredLetters); + var escapeHtmlChar = basePropertyOf(htmlEscapes); + function escapeStringChar(chr) { + return "\\" + stringEscapes[chr]; + } + function getValue(object, key) { + return object == null ? undefined$1 : object[key]; + } + function hasUnicode(string) { + return reHasUnicode.test(string); + } + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } + function iteratorToArray(iterator) { + var data, result = []; + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; + } + function mapToArray(map2) { + var index = -1, result = Array(map2.size); + map2.forEach(function(value2, key) { + result[++index] = [key, value2]; + }); + return result; + } + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; + } + function replaceHolders(array, placeholder) { + var index = -1, length = array.length, resIndex = 0, result = []; + while (++index < length) { + var value2 = array[index]; + if (value2 === placeholder || value2 === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; + } + } + return result; + } + function setToArray(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value2) { + result[++index] = value2; + }); + return result; + } + function setToPairs(set) { + var index = -1, result = Array(set.size); + set.forEach(function(value2) { + result[++index] = [value2, value2]; + }); + return result; + } + function strictIndexOf(array, value2, fromIndex) { + var index = fromIndex - 1, length = array.length; + while (++index < length) { + if (array[index] === value2) { + return index; + } + } + return -1; + } + function strictLastIndexOf(array, value2, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value2) { + return index; + } + } + return index; + } + function stringSize(string) { + return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); + } + function stringToArray(string) { + return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); + } + function trimmedEndIndex(string) { + var index = string.length; + while (index-- && reWhitespace.test(string.charAt(index))) { + } + return index; + } + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; + } + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } + var runInContext = function runInContext2(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); + var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError; + var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; + var coreJsData = context["__core-js_shared__"]; + var funcToString = funcProto.toString; + var hasOwnProperty2 = objectProto.hasOwnProperty; + var idCounter = 0; + var maskSrcKey = function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); + return uid ? "Symbol(src)_1." + uid : ""; + }(); + var nativeObjectToString = objectProto.toString; + var objectCtorString = funcToString.call(Object2); + var oldDash = root._; + var reIsNative = RegExp2( + "^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" + ); + var Buffer = moduleExports ? context.Buffer : undefined$1, Symbol2 = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined$1, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined$1, symIterator = Symbol2 ? Symbol2.iterator : undefined$1, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined$1; + var defineProperty2 = function() { + try { + var func = getNative(Object2, "defineProperty"); + func({}, "", {}); + return func; + } catch (e) { + } + }(); + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; + var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse; + var DataView = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create"); + var metaMap = WeakMap && new WeakMap(); + var realNames = {}; + var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap); + var symbolProto = Symbol2 ? Symbol2.prototype : undefined$1, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined$1, symbolToString = symbolProto ? symbolProto.toString : undefined$1; + function lodash2(value2) { + if (isObjectLike(value2) && !isArray2(value2) && !(value2 instanceof LazyWrapper)) { + if (value2 instanceof LodashWrapper) { + return value2; + } + if (hasOwnProperty2.call(value2, "__wrapped__")) { + return wrapperClone(value2); + } + } + return new LodashWrapper(value2); + } + var baseCreate = /* @__PURE__ */ function() { + function object() { + } + return function(proto) { + if (!isObject2(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result2 = new object(); + object.prototype = undefined$1; + return result2; + }; + }(); + function baseLodash() { + } + function LodashWrapper(value2, chainAll) { + this.__wrapped__ = value2; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined$1; + } + lodash2.templateSettings = { + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + "escape": reEscape, + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + "evaluate": reEvaluate, + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + "interpolate": reInterpolate, + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + "variable": "", + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + "imports": { + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + "_": lodash2 + } + }; + lodash2.prototype = baseLodash.prototype; + lodash2.prototype.constructor = lodash2; + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + function LazyWrapper(value2) { + this.__wrapped__ = value2; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; + } + function lazyClone() { + var result2 = new LazyWrapper(this.__wrapped__); + result2.__actions__ = copyArray(this.__actions__); + result2.__dir__ = this.__dir__; + result2.__filtered__ = this.__filtered__; + result2.__iteratees__ = copyArray(this.__iteratees__); + result2.__takeCount__ = this.__takeCount__; + result2.__views__ = copyArray(this.__views__); + return result2; + } + function lazyReverse() { + if (this.__filtered__) { + var result2 = new LazyWrapper(this); + result2.__dir__ = -1; + result2.__filtered__ = true; + } else { + result2 = this.clone(); + result2.__dir__ *= -1; + } + return result2; + } + function lazyValue() { + var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); + if (!isArr || !isRight && arrLength == length && takeCount == length) { + return baseWrapperValue(array, this.__actions__); + } + var result2 = []; + outer: + while (length-- && resIndex < takeCount) { + index += dir; + var iterIndex = -1, value2 = array[index]; + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value2); + if (type == LAZY_MAP_FLAG) { + value2 = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result2[resIndex++] = value2; + } + return result2; + } + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + function Hash(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; + } + function hashDelete(key) { + var result2 = this.has(key) && delete this.__data__[key]; + this.size -= result2 ? 1 : 0; + return result2; + } + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result2 = data[key]; + return result2 === HASH_UNDEFINED ? undefined$1 : result2; + } + return hasOwnProperty2.call(data, key) ? data[key] : undefined$1; + } + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? data[key] !== undefined$1 : hasOwnProperty2.call(data, key); + } + function hashSet(key, value2) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = nativeCreate && value2 === undefined$1 ? HASH_UNDEFINED : value2; + return this; + } + Hash.prototype.clear = hashClear; + Hash.prototype["delete"] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + function ListCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } + function listCacheDelete(key) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } + function listCacheGet(key) { + var data = this.__data__, index = assocIndexOf(data, key); + return index < 0 ? undefined$1 : data[index][1]; + } + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; + } + function listCacheSet(key, value2) { + var data = this.__data__, index = assocIndexOf(data, key); + if (index < 0) { + ++this.size; + data.push([key, value2]); + } else { + data[index][1] = value2; + } + return this; + } + ListCache.prototype.clear = listCacheClear; + ListCache.prototype["delete"] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + function MapCache(entries) { + var index = -1, length = entries == null ? 0 : entries.length; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } + } + function mapCacheClear() { + this.size = 0; + this.__data__ = { + "hash": new Hash(), + "map": new (Map2 || ListCache)(), + "string": new Hash() + }; + } + function mapCacheDelete(key) { + var result2 = getMapData(this, key)["delete"](key); + this.size -= result2 ? 1 : 0; + return result2; + } + function mapCacheGet(key) { + return getMapData(this, key).get(key); + } + function mapCacheHas(key) { + return getMapData(this, key).has(key); + } + function mapCacheSet(key, value2) { + var data = getMapData(this, key), size2 = data.size; + data.set(key, value2); + this.size += data.size == size2 ? 0 : 1; + return this; + } + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype["delete"] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; + function SetCache(values2) { + var index = -1, length = values2 == null ? 0 : values2.length; + this.__data__ = new MapCache(); + while (++index < length) { + this.add(values2[index]); + } + } + function setCacheAdd(value2) { + this.__data__.set(value2, HASH_UNDEFINED); + return this; + } + function setCacheHas(value2) { + return this.__data__.has(value2); + } + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; + } + function stackClear() { + this.__data__ = new ListCache(); + this.size = 0; + } + function stackDelete(key) { + var data = this.__data__, result2 = data["delete"](key); + this.size = data.size; + return result2; + } + function stackGet(key) { + return this.__data__.get(key); + } + function stackHas(key) { + return this.__data__.has(key); + } + function stackSet(key, value2) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { + pairs.push([key, value2]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value2); + this.size = data.size; + return this; + } + Stack.prototype.clear = stackClear; + Stack.prototype["delete"] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + function arrayLikeKeys(value2, inherited) { + var isArr = isArray2(value2), isArg = !isArr && isArguments2(value2), isBuff = !isArr && !isArg && isBuffer(value2), isType = !isArr && !isArg && !isBuff && isTypedArray(value2), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value2.length, String2) : [], length = result2.length; + for (var key in value2) { + if ((inherited || hasOwnProperty2.call(value2, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. + (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. + isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. + isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. + isIndex(key, length)))) { + result2.push(key); + } + } + return result2; + } + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined$1; + } + function arraySampleSize(array, n2) { + return shuffleSelf(copyArray(array), baseClamp(n2, 0, array.length)); + } + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + function assignMergeValue(object, key, value2) { + if (value2 !== undefined$1 && !eq(object[key], value2) || value2 === undefined$1 && !(key in object)) { + baseAssignValue(object, key, value2); + } + } + function assignValue(object, key, value2) { + var objValue = object[key]; + if (!(hasOwnProperty2.call(object, key) && eq(objValue, value2)) || value2 === undefined$1 && !(key in object)) { + baseAssignValue(object, key, value2); + } + } + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + function baseAggregator(collection, setter, iteratee2, accumulator) { + baseEach(collection, function(value2, key, collection2) { + setter(accumulator, value2, iteratee2(value2), collection2); + }); + return accumulator; + } + function baseAssign(object, source) { + return object && copyObject(source, keys2(source), object); + } + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); + } + function baseAssignValue(object, key, value2) { + if (key == "__proto__" && defineProperty2) { + defineProperty2(object, key, { + "configurable": true, + "enumerable": true, + "value": value2, + "writable": true + }); + } else { + object[key] = value2; + } + } + function baseAt(object, paths) { + var index = -1, length = paths.length, result2 = Array2(length), skip = object == null; + while (++index < length) { + result2[index] = skip ? undefined$1 : get2(object, paths[index]); + } + return result2; + } + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined$1) { + number = number <= upper ? number : upper; + } + if (lower !== undefined$1) { + number = number >= lower ? number : lower; + } + } + return number; + } + function baseClone(value2, bitmask, customizer, key, object, stack) { + var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; + if (customizer) { + result2 = object ? customizer(value2, key, object, stack) : customizer(value2); + } + if (result2 !== undefined$1) { + return result2; + } + if (!isObject2(value2)) { + return value2; + } + var isArr = isArray2(value2); + if (isArr) { + result2 = initCloneArray(value2); + if (!isDeep) { + return copyArray(value2, result2); + } + } else { + var tag = getTag(value2), isFunc = tag == funcTag || tag == genTag; + if (isBuffer(value2)) { + return cloneBuffer(value2, isDeep); + } + if (tag == objectTag || tag == argsTag || isFunc && !object) { + result2 = isFlat || isFunc ? {} : initCloneObject(value2); + if (!isDeep) { + return isFlat ? copySymbolsIn(value2, baseAssignIn(result2, value2)) : copySymbols(value2, baseAssign(result2, value2)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value2 : {}; + } + result2 = initCloneByTag(value2, tag, isDeep); + } + } + stack || (stack = new Stack()); + var stacked = stack.get(value2); + if (stacked) { + return stacked; + } + stack.set(value2, result2); + if (isSet(value2)) { + value2.forEach(function(subValue) { + result2.add(baseClone(subValue, bitmask, customizer, subValue, value2, stack)); + }); + } else if (isMap(value2)) { + value2.forEach(function(subValue, key2) { + result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value2, stack)); + }); + } + var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys2; + var props = isArr ? undefined$1 : keysFunc(value2); + arrayEach(props || value2, function(subValue, key2) { + if (props) { + key2 = subValue; + subValue = value2[key2]; + } + assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value2, stack)); + }); + return result2; + } + function baseConforms(source) { + var props = keys2(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object2(object); + while (length--) { + var key = props[length], predicate = source[key], value2 = object[key]; + if (value2 === undefined$1 && !(key in object) || !predicate(value2)) { + return false; + } + } + return true; + } + function baseDelay(func, wait, args) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return setTimeout2(function() { + func.apply(undefined$1, args); + }, wait); + } + function baseDifference(array, values2, iteratee2, comparator) { + var index = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values2.length; + if (!length) { + return result2; + } + if (iteratee2) { + values2 = arrayMap(values2, baseUnary(iteratee2)); + } + if (comparator) { + includes2 = arrayIncludesWith; + isCommon = false; + } else if (values2.length >= LARGE_ARRAY_SIZE) { + includes2 = cacheHas; + isCommon = false; + values2 = new SetCache(values2); + } + outer: + while (++index < length) { + var value2 = array[index], computed = iteratee2 == null ? value2 : iteratee2(value2); + value2 = comparator || value2 !== 0 ? value2 : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values2[valuesIndex] === computed) { + continue outer; + } + } + result2.push(value2); + } else if (!includes2(values2, computed, comparator)) { + result2.push(value2); + } + } + return result2; + } + var baseEach = createBaseEach(baseForOwn); + var baseEachRight = createBaseEach(baseForOwnRight, true); + function baseEvery(collection, predicate) { + var result2 = true; + baseEach(collection, function(value2, index, collection2) { + result2 = !!predicate(value2, index, collection2); + return result2; + }); + return result2; + } + function baseExtremum(array, iteratee2, comparator) { + var index = -1, length = array.length; + while (++index < length) { + var value2 = array[index], current = iteratee2(value2); + if (current != null && (computed === undefined$1 ? current === current && !isSymbol2(current) : comparator(current, computed))) { + var computed = current, result2 = value2; + } + } + return result2; + } + function baseFill(array, value2, start, end) { + var length = array.length; + start = toInteger2(start); + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end === undefined$1 || end > length ? length : toInteger2(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value2; + } + return array; + } + function baseFilter(collection, predicate) { + var result2 = []; + baseEach(collection, function(value2, index, collection2) { + if (predicate(value2, index, collection2)) { + result2.push(value2); + } + }); + return result2; + } + function baseFlatten(array, depth, predicate, isStrict, result2) { + var index = -1, length = array.length; + predicate || (predicate = isFlattenable); + result2 || (result2 = []); + while (++index < length) { + var value2 = array[index]; + if (depth > 0 && predicate(value2)) { + if (depth > 1) { + baseFlatten(value2, depth - 1, predicate, isStrict, result2); + } else { + arrayPush(result2, value2); + } + } else if (!isStrict) { + result2[result2.length] = value2; + } + } + return result2; + } + var baseFor = createBaseFor(); + var baseForRight = createBaseFor(true); + function baseForOwn(object, iteratee2) { + return object && baseFor(object, iteratee2, keys2); + } + function baseForOwnRight(object, iteratee2) { + return object && baseForRight(object, iteratee2, keys2); + } + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction2(object[key]); + }); + } + function baseGet(object, path) { + path = castPath(path, object); + var index = 0, length = path.length; + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return index && index == length ? object : undefined$1; + } + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result2 = keysFunc(object); + return isArray2(object) ? result2 : arrayPush(result2, symbolsFunc(object)); + } + function baseGetTag(value2) { + if (value2 == null) { + return value2 === undefined$1 ? undefinedTag : nullTag; + } + return symToStringTag && symToStringTag in Object2(value2) ? getRawTag(value2) : objectToString(value2); + } + function baseGt(value2, other) { + return value2 > other; + } + function baseHas(object, key) { + return object != null && hasOwnProperty2.call(object, key); + } + function baseHasIn(object, key) { + return object != null && key in Object2(object); + } + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + function baseIntersection(arrays, iteratee2, comparator) { + var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee2) { + array = arrayMap(array, baseUnary(iteratee2)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined$1; + } + array = arrays[0]; + var index = -1, seen = caches[0]; + outer: + while (++index < length && result2.length < maxLength) { + var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; + value2 = comparator || value2 !== 0 ? value2 : 0; + if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache ? cacheHas(cache, computed) : includes2(arrays[othIndex], computed, comparator))) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result2.push(value2); + } + } + return result2; + } + function baseInverter(object, setter, iteratee2, accumulator) { + baseForOwn(object, function(value2, key, object2) { + setter(accumulator, iteratee2(value2), key, object2); + }); + return accumulator; + } + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined$1 : apply2(func, object, args); + } + function baseIsArguments(value2) { + return isObjectLike(value2) && baseGetTag(value2) == argsTag; + } + function baseIsArrayBuffer(value2) { + return isObjectLike(value2) && baseGetTag(value2) == arrayBufferTag; + } + function baseIsDate(value2) { + return isObjectLike(value2) && baseGetTag(value2) == dateTag; + } + function baseIsEqual(value2, other, bitmask, customizer, stack) { + if (value2 === other) { + return true; + } + if (value2 == null || other == null || !isObjectLike(value2) && !isObjectLike(other)) { + return value2 !== value2 && other !== other; + } + return baseIsEqualDeep(value2, other, bitmask, customizer, baseIsEqual, stack); + } + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack()); + return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__"); + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; + stack || (stack = new Stack()); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack()); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); + } + function baseIsMap(value2) { + return isObjectLike(value2) && getTag(value2) == mapTag; + } + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, length = index, noCustomizer = !customizer; + if (object == null) { + return !length; + } + object = Object2(object); + while (index--) { + var data = matchData[index]; + if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], objValue = object[key], srcValue = data[1]; + if (noCustomizer && data[2]) { + if (objValue === undefined$1 && !(key in object)) { + return false; + } + } else { + var stack = new Stack(); + if (customizer) { + var result2 = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result2 === undefined$1 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) { + return false; + } + } + } + return true; + } + function baseIsNative(value2) { + if (!isObject2(value2) || isMasked(value2)) { + return false; + } + var pattern = isFunction2(value2) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value2)); + } + function baseIsRegExp(value2) { + return isObjectLike(value2) && baseGetTag(value2) == regexpTag; + } + function baseIsSet(value2) { + return isObjectLike(value2) && getTag(value2) == setTag; + } + function baseIsTypedArray(value2) { + return isObjectLike(value2) && isLength(value2.length) && !!typedArrayTags[baseGetTag(value2)]; + } + function baseIteratee(value2) { + if (typeof value2 == "function") { + return value2; + } + if (value2 == null) { + return identity; + } + if (typeof value2 == "object") { + return isArray2(value2) ? baseMatchesProperty(value2[0], value2[1]) : baseMatches(value2); + } + return property(value2); + } + function baseKeys(object) { + if (!isPrototype2(object)) { + return nativeKeys(object); + } + var result2 = []; + for (var key in Object2(object)) { + if (hasOwnProperty2.call(object, key) && key != "constructor") { + result2.push(key); + } + } + return result2; + } + function baseKeysIn(object) { + if (!isObject2(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype2(object), result2 = []; + for (var key in object) { + if (!(key == "constructor" && (isProto || !hasOwnProperty2.call(object, key)))) { + result2.push(key); + } + } + return result2; + } + function baseLt(value2, other) { + return value2 < other; + } + function baseMap(collection, iteratee2) { + var index = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : []; + baseEach(collection, function(value2, key, collection2) { + result2[++index] = iteratee2(value2, key, collection2); + }); + return result2; + } + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get2(object, path); + return objValue === undefined$1 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack()); + if (isObject2(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } else { + var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source, stack) : undefined$1; + if (newValue === undefined$1) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined$1; + var isCommon = newValue === undefined$1; + if (isCommon) { + var isArr = isArray2(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray2(objValue)) { + newValue = objValue; + } else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } else { + newValue = []; + } + } else if (isPlainObject(srcValue) || isArguments2(srcValue)) { + newValue = objValue; + if (isArguments2(objValue)) { + newValue = toPlainObject(objValue); + } else if (!isObject2(objValue) || isFunction2(objValue)) { + newValue = initCloneObject(srcValue); + } + } else { + isCommon = false; + } + } + if (isCommon) { + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack["delete"](srcValue); + } + assignMergeValue(object, key, newValue); + } + function baseNth(array, n2) { + var length = array.length; + if (!length) { + return; + } + n2 += n2 < 0 ? length : 0; + return isIndex(n2, length) ? array[n2] : undefined$1; + } + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee2) { + if (isArray2(iteratee2)) { + return function(value2) { + return baseGet(value2, iteratee2.length === 1 ? iteratee2[0] : iteratee2); + }; + } + return iteratee2; + }); + } else { + iteratees = [identity]; + } + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + var result2 = baseMap(collection, function(value2, key, collection2) { + var criteria = arrayMap(iteratees, function(iteratee2) { + return iteratee2(value2); + }); + return { "criteria": criteria, "index": ++index, "value": value2 }; + }); + return baseSortBy(result2, function(object, other) { + return compareMultiple(object, other, orders); + }); + } + function basePick(object, paths) { + return basePickBy(object, paths, function(value2, path) { + return hasIn(object, path); + }); + } + function basePickBy(object, paths, predicate) { + var index = -1, length = paths.length, result2 = {}; + while (++index < length) { + var path = paths[index], value2 = baseGet(object, path); + if (predicate(value2, path)) { + baseSet(result2, castPath(path, object), value2); + } + } + return result2; + } + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; + } + function basePullAll(array, values2, iteratee2, comparator) { + var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values2.length, seen = array; + if (array === values2) { + values2 = copyArray(values2); + } + if (iteratee2) { + seen = arrayMap(array, baseUnary(iteratee2)); + } + while (++index < length) { + var fromIndex = 0, value2 = values2[index], computed = iteratee2 ? iteratee2(value2) : value2; + while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; + } + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, lastIndex = length - 1; + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; + } + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); + } + function baseRange(start, end, step, fromRight) { + var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result2 = Array2(length); + while (length--) { + result2[fromRight ? length : ++index] = start; + start += step; + } + return result2; + } + function baseRepeat(string, n2) { + var result2 = ""; + if (!string || n2 < 1 || n2 > MAX_SAFE_INTEGER) { + return result2; + } + do { + if (n2 % 2) { + result2 += string; + } + n2 = nativeFloor(n2 / 2); + if (n2) { + string += string; + } + } while (n2); + return result2; + } + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ""); + } + function baseSample(collection) { + return arraySample(values(collection)); + } + function baseSampleSize(collection, n2) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n2, 0, array.length)); + } + function baseSet(object, path, value2, customizer) { + if (!isObject2(object)) { + return object; + } + path = castPath(path, object); + var index = -1, length = path.length, lastIndex = length - 1, nested = object; + while (nested != null && ++index < length) { + var key = toKey(path[index]), newValue = value2; + if (key === "__proto__" || key === "constructor" || key === "prototype") { + return object; + } + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined$1; + if (newValue === undefined$1) { + newValue = isObject2(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; + } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; + var baseSetToString = !defineProperty2 ? identity : function(func, string) { + return defineProperty2(func, "toString", { + "configurable": true, + "enumerable": false, + "value": constant(string), + "writable": true + }); + }; + function baseShuffle(collection) { + return shuffleSelf(values(collection)); + } + function baseSlice(array, start, end) { + var index = -1, length = array.length; + if (start < 0) { + start = -start > length ? 0 : length + start; + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : end - start >>> 0; + start >>>= 0; + var result2 = Array2(length); + while (++index < length) { + result2[index] = array[index + start]; + } + return result2; + } + function baseSome(collection, predicate) { + var result2; + baseEach(collection, function(value2, index, collection2) { + result2 = predicate(value2, index, collection2); + return !result2; + }); + return !!result2; + } + function baseSortedIndex(array, value2, retHighest) { + var low = 0, high = array == null ? low : array.length; + if (typeof value2 == "number" && value2 === value2 && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = low + high >>> 1, computed = array[mid]; + if (computed !== null && !isSymbol2(computed) && (retHighest ? computed <= value2 : computed < value2)) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value2, identity, retHighest); + } + function baseSortedIndexBy(array, value2, iteratee2, retHighest) { + var low = 0, high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + value2 = iteratee2(value2); + var valIsNaN = value2 !== value2, valIsNull = value2 === null, valIsSymbol = isSymbol2(value2), valIsUndefined = value2 === undefined$1; + while (low < high) { + var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol2(computed); + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? computed <= value2 : computed < value2; + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } + function baseSortedUniq(array, iteratee2) { + var index = -1, length = array.length, resIndex = 0, result2 = []; + while (++index < length) { + var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; + if (!index || !eq(computed, seen)) { + var seen = computed; + result2[resIndex++] = value2 === 0 ? 0 : value2; + } + } + return result2; + } + function baseToNumber(value2) { + if (typeof value2 == "number") { + return value2; + } + if (isSymbol2(value2)) { + return NAN; + } + return +value2; + } + function baseToString(value2) { + if (typeof value2 == "string") { + return value2; + } + if (isArray2(value2)) { + return arrayMap(value2, baseToString) + ""; + } + if (isSymbol2(value2)) { + return symbolToString ? symbolToString.call(value2) : ""; + } + var result2 = value2 + ""; + return result2 == "0" && 1 / value2 == -Infinity ? "-0" : result2; + } + function baseUniq(array, iteratee2, comparator) { + var index = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2; + if (comparator) { + isCommon = false; + includes2 = arrayIncludesWith; + } else if (length >= LARGE_ARRAY_SIZE) { + var set2 = iteratee2 ? null : createSet(array); + if (set2) { + return setToArray(set2); + } + isCommon = false; + includes2 = cacheHas; + seen = new SetCache(); + } else { + seen = iteratee2 ? [] : result2; + } + outer: + while (++index < length) { + var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; + value2 = comparator || value2 !== 0 ? value2 : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee2) { + seen.push(computed); + } + result2.push(value2); + } else if (!includes2(seen, computed, comparator)) { + if (seen !== result2) { + seen.push(computed); + } + result2.push(value2); + } + } + return result2; + } + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; + } + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); + } + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, index = fromRight ? length : -1; + while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) { + } + return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); + } + function baseWrapperValue(value2, actions) { + var result2 = value2; + if (result2 instanceof LazyWrapper) { + result2 = result2.value(); + } + return arrayReduce(actions, function(result3, action) { + return action.func.apply(action.thisArg, arrayPush([result3], action.args)); + }, result2); + } + function baseXor(arrays, iteratee2, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, result2 = Array2(length); + while (++index < length) { + var array = arrays[index], othIndex = -1; + while (++othIndex < length) { + if (othIndex != index) { + result2[index] = baseDifference(result2[index] || array, arrays[othIndex], iteratee2, comparator); + } + } + } + return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); + } + function baseZipObject(props, values2, assignFunc) { + var index = -1, length = props.length, valsLength = values2.length, result2 = {}; + while (++index < length) { + var value2 = index < valsLength ? values2[index] : undefined$1; + assignFunc(result2, props[index], value2); + } + return result2; + } + function castArrayLikeObject(value2) { + return isArrayLikeObject(value2) ? value2 : []; + } + function castFunction(value2) { + return typeof value2 == "function" ? value2 : identity; + } + function castPath(value2, object) { + if (isArray2(value2)) { + return value2; + } + return isKey(value2, object) ? [value2] : stringToPath(toString(value2)); + } + var castRest = baseRest; + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined$1 ? length : end; + return !start && end >= length ? array : baseSlice(array, start, end); + } + var clearTimeout2 = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + buffer.copy(result2); + return result2; + } + function cloneArrayBuffer(arrayBuffer) { + var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result2).set(new Uint8Array(arrayBuffer)); + return result2; + } + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + function cloneRegExp(regexp) { + var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result2.lastIndex = regexp.lastIndex; + return result2; + } + function cloneSymbol(symbol) { + return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {}; + } + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + function compareAscending(value2, other) { + if (value2 !== other) { + var valIsDefined = value2 !== undefined$1, valIsNull = value2 === null, valIsReflexive = value2 === value2, valIsSymbol = isSymbol2(value2); + var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol2(other); + if (!othIsNull && !othIsSymbol && !valIsSymbol && value2 > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { + return 1; + } + if (!valIsNull && !valIsSymbol && !othIsSymbol && value2 < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { + return -1; + } + } + return 0; + } + function compareMultiple(object, other, orders) { + var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; + while (++index < length) { + var result2 = compareAscending(objCriteria[index], othCriteria[index]); + if (result2) { + if (index >= ordersLength) { + return result2; + } + var order = orders[index]; + return result2 * (order == "desc" ? -1 : 1); + } + } + return object.index - other.index; + } + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried; + while (++leftIndex < leftLength) { + result2[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result2[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result2[leftIndex++] = args[argsIndex++]; + } + return result2; + } + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried; + while (++argsIndex < rangeLength) { + result2[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result2[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result2[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result2; + } + function copyArray(source, array) { + var index = -1, length = source.length; + array || (array = Array2(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; + } + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + var index = -1, length = props.length; + while (++index < length) { + var key = props[index]; + var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined$1; + if (newValue === undefined$1) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); + } + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); + } + function createAggregator(setter, initializer) { + return function(collection, iteratee2) { + var func = isArray2(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; + return func(collection, setter, getIteratee(iteratee2, 2), accumulator); + }; + } + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1; + customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined$1; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined$1 : customizer; + length = 1; + } + object = Object2(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee2) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee2); + } + var length = collection.length, index = fromRight ? length : -1, iterable = Object2(collection); + while (fromRight ? index-- : ++index < length) { + if (iteratee2(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + function createBaseFor(fromRight) { + return function(object, iteratee2, keysFunc) { + var index = -1, iterable = Object2(object), props = keysFunc(object), length = props.length; + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee2(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; + } + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined$1; + var chr = strSymbols ? strSymbols[0] : string.charAt(0); + var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); + return chr[methodName]() + trailing; + }; + } + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); + }; + } + function createCtor(Ctor) { + return function() { + var args = arguments; + switch (args.length) { + case 0: + return new Ctor(); + case 1: + return new Ctor(args[0]); + case 2: + return new Ctor(args[0], args[1]); + case 3: + return new Ctor(args[0], args[1], args[2]); + case 4: + return new Ctor(args[0], args[1], args[2], args[3]); + case 5: + return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: + return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); + return isObject2(result2) ? result2 : thisBinding; + }; + } + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + function wrapper() { + var length = arguments.length, args = Array2(length), index = length, placeholder = getHolder(wrapper); + while (index--) { + args[index] = arguments[index]; + } + var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); + length -= holders.length; + if (length < arity) { + return createRecurry( + func, + bitmask, + createHybrid, + wrapper.placeholder, + undefined$1, + args, + holders, + undefined$1, + undefined$1, + arity - length + ); + } + var fn = this && this !== root && this instanceof wrapper ? Ctor : func; + return apply2(fn, this, args); + } + return wrapper; + } + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object2(collection); + if (!isArrayLike(collection)) { + var iteratee2 = getIteratee(predicate, 3); + collection = keys2(collection); + predicate = function(key) { + return iteratee2(iterable[key], key, iterable); + }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee2 ? collection[index] : index] : undefined$1; + }; + } + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == "wrapper") { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined$1; + if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); + } + } + return function() { + var args = arguments, value2 = args[0]; + if (wrapper && args.length == 1 && isArray2(value2)) { + return wrapper.plant(value2).value(); + } + var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value2; + while (++index2 < length) { + result2 = funcs[index2].call(this, result2); + } + return result2; + }; + }); + } + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func); + function wrapper() { + var length = arguments.length, args = Array2(length), index = length; + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, + bitmask, + createHybrid, + wrapper.placeholder, + thisArg, + args, + newHolders, + argPos, + ary2, + arity - length + ); + } + var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary2 < length) { + args.length = ary2; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; + } + function createInverter(setter, toIteratee) { + return function(object, iteratee2) { + return baseInverter(object, setter, toIteratee(iteratee2), {}); + }; + } + function createMathOperation(operator, defaultValue) { + return function(value2, other) { + var result2; + if (value2 === undefined$1 && other === undefined$1) { + return defaultValue; + } + if (value2 !== undefined$1) { + result2 = value2; + } + if (other !== undefined$1) { + if (result2 === undefined$1) { + return other; + } + if (typeof value2 == "string" || typeof other == "string") { + value2 = baseToString(value2); + other = baseToString(other); + } else { + value2 = baseToNumber(value2); + other = baseToNumber(other); + } + result2 = operator(value2, other); + } + return result2; + }; + } + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee2) { + return apply2(iteratee2, thisArg, args); + }); + }); + }); + } + function createPadding(length, chars) { + chars = chars === undefined$1 ? " " : baseToString(chars); + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); + } + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); + function wrapper() { + var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply2(fn, isBind ? thisArg : this, args); + } + return wrapper; + } + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != "number" && isIterateeCall(start, end, step)) { + end = step = undefined$1; + } + start = toFinite(start); + if (end === undefined$1) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined$1 ? start < end ? 1 : -1 : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } + function createRelationalOperation(operator) { + return function(value2, other) { + if (!(typeof value2 == "string" && typeof other == "string")) { + value2 = toNumber(value2); + other = toNumber(other); + } + return operator(value2, other); + }; + } + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; + bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= -4; + } + var newData = [ + func, + bitmask, + thisArg, + newPartials, + newHolders, + newPartialsRight, + newHoldersRight, + argPos, + ary2, + arity + ]; + var result2 = wrapFunc.apply(undefined$1, newData); + if (isLaziable(func)) { + setData(result2, newData); + } + result2.placeholder = placeholder; + return setWrapToString(result2, func, bitmask); + } + function createRound(methodName) { + var func = Math2[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger2(precision), 292); + if (precision && nativeIsFinite(number)) { + var pair = (toString(number) + "e").split("e"), value2 = func(pair[0] + "e" + (+pair[1] + precision)); + pair = (toString(value2) + "e").split("e"); + return +(pair[0] + "e" + (+pair[1] - precision)); + } + return func(number); + }; + } + var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values2) { + return new Set2(values2); + }; + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= -97; + partials = holders = undefined$1; + } + ary2 = ary2 === undefined$1 ? ary2 : nativeMax(toInteger2(ary2), 0); + arity = arity === undefined$1 ? arity : toInteger2(arity); + length -= holders ? holders.length : 0; + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, holdersRight = holders; + partials = holders = undefined$1; + } + var data = isBindKey ? undefined$1 : getData(func); + var newData = [ + func, + bitmask, + thisArg, + partials, + holders, + partialsRight, + holdersRight, + argPos, + ary2, + arity + ]; + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined$1 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= -25; + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result2 = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result2 = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result2 = createPartial(func, bitmask, thisArg, partials); + } else { + result2 = createHybrid.apply(undefined$1, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result2, newData), func, bitmask); + } + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined$1 || eq(objValue, objectProto[key]) && !hasOwnProperty2.call(object, key)) { + return srcValue; + } + return objValue; + } + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject2(objValue) && isObject2(srcValue)) { + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined$1, customDefaultsMerge, stack); + stack["delete"](srcValue); + } + return objValue; + } + function customOmitClone(value2) { + return isPlainObject(value2) ? undefined$1 : value2; + } + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined$1; + stack.set(array, other); + stack.set(other, array); + while (++index < arrLength) { + var arrValue = array[index], othValue = other[index]; + if (customizer) { + var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined$1) { + if (compared) { + continue; + } + result2 = false; + break; + } + if (seen) { + if (!arraySome(other, function(othValue2, othIndex) { + if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result2 = false; + break; + } + } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + result2 = false; + break; + } + } + stack["delete"](array); + stack["delete"](other); + return result2; + } + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { + return false; + } + object = object.buffer; + other = other.buffer; + case arrayBufferTag: + if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + case boolTag: + case dateTag: + case numberTag: + return eq(+object, +other); + case errorTag: + return object.name == other.name && object.message == other.message; + case regexpTag: + case stringTag: + return object == other + ""; + case mapTag: + var convert = mapToArray; + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + if (object.size != other.size && !isPartial) { + return false; + } + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + stack.set(object, other); + var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack["delete"](object); + return result2; + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; + } + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) { + return false; + } + } + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result2 = true; + stack.set(object, other); + stack.set(other, object); + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], othValue = other[key]; + if (customizer) { + var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); + } + if (!(compared === undefined$1 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { + result2 = false; + break; + } + skipCtor || (skipCtor = key == "constructor"); + } + if (result2 && !skipCtor) { + var objCtor = object.constructor, othCtor = other.constructor; + if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { + result2 = false; + } + } + stack["delete"](object); + stack["delete"](other); + return result2; + } + function flatRest(func) { + return setToString(overRest(func, undefined$1, flatten), func + ""); + } + function getAllKeys(object) { + return baseGetAllKeys(object, keys2, getSymbols); + } + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); + } + var getData = !metaMap ? noop2 : function(func) { + return metaMap.get(func); + }; + function getFuncName(func) { + var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty2.call(realNames, result2) ? array.length : 0; + while (length--) { + var data = array[length], otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result2; + } + function getHolder(func) { + var object = hasOwnProperty2.call(lodash2, "placeholder") ? lodash2 : func; + return object.placeholder; + } + function getIteratee() { + var result2 = lodash2.iteratee || iteratee; + result2 = result2 === iteratee ? baseIteratee : result2; + return arguments.length ? result2(arguments[0], arguments[1]) : result2; + } + function getMapData(map3, key) { + var data = map3.__data__; + return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; + } + function getMatchData(object) { + var result2 = keys2(object), length = result2.length; + while (length--) { + var key = result2[length], value2 = object[key]; + result2[length] = [key, value2, isStrictComparable(value2)]; + } + return result2; + } + function getNative(object, key) { + var value2 = getValue(object, key); + return baseIsNative(value2) ? value2 : undefined$1; + } + function getRawTag(value2) { + var isOwn = hasOwnProperty2.call(value2, symToStringTag), tag = value2[symToStringTag]; + try { + value2[symToStringTag] = undefined$1; + var unmasked = true; + } catch (e) { + } + var result2 = nativeObjectToString.call(value2); + if (unmasked) { + if (isOwn) { + value2[symToStringTag] = tag; + } else { + delete value2[symToStringTag]; + } + } + return result2; + } + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object2(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result2 = []; + while (object) { + arrayPush(result2, getSymbols(object)); + object = getPrototype(object); + } + return result2; + }; + var getTag = baseGetTag; + if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { + getTag = function(value2) { + var result2 = baseGetTag(value2), Ctor = result2 == objectTag ? value2.constructor : undefined$1, ctorString = Ctor ? toSource(Ctor) : ""; + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: + return dataViewTag; + case mapCtorString: + return mapTag; + case promiseCtorString: + return promiseTag; + case setCtorString: + return setTag; + case weakMapCtorString: + return weakMapTag; + } + } + return result2; + }; + } + function getView(start, end, transforms) { + var index = -1, length = transforms.length; + while (++index < length) { + var data = transforms[index], size2 = data.size; + switch (data.type) { + case "drop": + start += size2; + break; + case "dropRight": + end -= size2; + break; + case "take": + end = nativeMin(end, start + size2); + break; + case "takeRight": + start = nativeMax(start, end - size2); + break; + } + } + return { "start": start, "end": end }; + } + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; + } + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + var index = -1, length = path.length, result2 = false; + while (++index < length) { + var key = toKey(path[index]); + if (!(result2 = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result2 || ++index != length) { + return result2; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && (isArray2(object) || isArguments2(object)); + } + function initCloneArray(array) { + var length = array.length, result2 = new array.constructor(length); + if (length && typeof array[0] == "string" && hasOwnProperty2.call(array, "index")) { + result2.index = array.index; + result2.input = array.input; + } + return result2; + } + function initCloneObject(object) { + return typeof object.constructor == "function" && !isPrototype2(object) ? baseCreate(getPrototype(object)) : {}; + } + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + case boolTag: + case dateTag: + return new Ctor(+object); + case dataViewTag: + return cloneDataView(object, isDeep); + case float32Tag: + case float64Tag: + case int8Tag: + case int16Tag: + case int32Tag: + case uint8Tag: + case uint8ClampedTag: + case uint16Tag: + case uint32Tag: + return cloneTypedArray(object, isDeep); + case mapTag: + return new Ctor(); + case numberTag: + case stringTag: + return new Ctor(object); + case regexpTag: + return cloneRegExp(object); + case setTag: + return new Ctor(); + case symbolTag: + return cloneSymbol(object); + } + } + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; + details = details.join(length > 2 ? ", " : " "); + return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); + } + function isFlattenable(value2) { + return isArray2(value2) || isArguments2(value2) || !!(spreadableSymbol && value2 && value2[spreadableSymbol]); + } + function isIndex(value2, length) { + var type = typeof value2; + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && (type == "number" || type != "symbol" && reIsUint.test(value2)) && (value2 > -1 && value2 % 1 == 0 && value2 < length); + } + function isIterateeCall(value2, index, object) { + if (!isObject2(object)) { + return false; + } + var type = typeof index; + if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { + return eq(object[index], value2); + } + return false; + } + function isKey(value2, object) { + if (isArray2(value2)) { + return false; + } + var type = typeof value2; + if (type == "number" || type == "symbol" || type == "boolean" || value2 == null || isSymbol2(value2)) { + return true; + } + return reIsPlainProp.test(value2) || !reIsDeepProp.test(value2) || object != null && value2 in Object2(object); + } + function isKeyable(value2) { + var type = typeof value2; + return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value2 !== "__proto__" : value2 === null; + } + function isLaziable(func) { + var funcName = getFuncName(func), other = lodash2[funcName]; + if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; + } + function isMasked(func) { + return !!maskSrcKey && maskSrcKey in func; + } + var isMaskable = coreJsData ? isFunction2 : stubFalse; + function isPrototype2(value2) { + var Ctor = value2 && value2.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; + return value2 === proto; + } + function isStrictComparable(value2) { + return value2 === value2 && !isObject2(value2); + } + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object)); + }; + } + function memoizeCapped(func) { + var result2 = memoize2(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + var cache = result2.cache; + return result2; + } + function mergeData(data, source) { + var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; + if (!(isCommon || isCombo)) { + return data; + } + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; + } + var value2 = source[3]; + if (value2) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value2, source[4]) : value2; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + value2 = source[5]; + if (value2) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value2, source[6]) : value2; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + value2 = source[7]; + if (value2) { + data[7] = value2; + } + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + if (data[9] == null) { + data[9] = source[9]; + } + data[0] = source[0]; + data[1] = newBitmask; + return data; + } + function nativeKeysIn(object) { + var result2 = []; + if (object != null) { + for (var key in Object2(object)) { + result2.push(key); + } + } + return result2; + } + function objectToString(value2) { + return nativeObjectToString.call(value2); + } + function overRest(func, start, transform2) { + start = nativeMax(start === undefined$1 ? func.length - 1 : start, 0); + return function() { + var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array2(length); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array2(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform2(array); + return apply2(func, this, otherArgs); + }; + } + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + } + function reorder(array, indexes) { + var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined$1; + } + return array; + } + function safeGet(object, key) { + if (key === "constructor" && typeof object[key] === "function") { + return; + } + if (key == "__proto__") { + return; + } + return object[key]; + } + var setData = shortOut(baseSetData); + var setTimeout2 = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; + var setToString = shortOut(baseSetToString); + function setWrapToString(wrapper, reference, bitmask) { + var source = reference + ""; + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } + function shortOut(func) { + var count = 0, lastCalled = 0; + return function() { + var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined$1, arguments); + }; + } + function shuffleSelf(array, size2) { + var index = -1, length = array.length, lastIndex = length - 1; + size2 = size2 === undefined$1 ? length : size2; + while (++index < size2) { + var rand = baseRandom(index, lastIndex), value2 = array[rand]; + array[rand] = array[index]; + array[index] = value2; + } + array.length = size2; + return array; + } + var stringToPath = memoizeCapped(function(string) { + var result2 = []; + if (string.charCodeAt(0) === 46) { + result2.push(""); + } + string.replace(rePropName, function(match, number, quote, subString) { + result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); + }); + return result2; + }); + function toKey(value2) { + if (typeof value2 == "string" || isSymbol2(value2)) { + return value2; + } + var result2 = value2 + ""; + return result2 == "0" && 1 / value2 == -Infinity ? "-0" : result2; + } + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) { + } + try { + return func + ""; + } catch (e) { + } + } + return ""; + } + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value2 = "_." + pair[0]; + if (bitmask & pair[1] && !arrayIncludes(details, value2)) { + details.push(value2); + } + }); + return details.sort(); + } + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result2.__actions__ = copyArray(wrapper.__actions__); + result2.__index__ = wrapper.__index__; + result2.__values__ = wrapper.__values__; + return result2; + } + function chunk(array, size2, guard) { + if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined$1) { + size2 = 1; + } else { + size2 = nativeMax(toInteger2(size2), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size2 < 1) { + return []; + } + var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); + while (index < length) { + result2[resIndex++] = baseSlice(array, index, index += size2); + } + return result2; + } + function compact(array) { + var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = []; + while (++index < length) { + var value2 = array[index]; + if (value2) { + result2[resIndex++] = value2; + } + } + return result2; + } + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array2(length - 1), array = arguments[0], index = length; + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray2(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } + var difference = baseRest(function(array, values2) { + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; + }); + var differenceBy = baseRest(function(array, values2) { + var iteratee2 = last(values2); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined$1; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : []; + }); + var differenceWith = baseRest(function(array, values2) { + var comparator = last(values2); + if (isArrayLikeObject(comparator)) { + comparator = undefined$1; + } + return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined$1, comparator) : []; + }); + function drop(array, n2, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); + return baseSlice(array, n2 < 0 ? 0 : n2, length); + } + function dropRight(array, n2, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); + n2 = length - n2; + return baseSlice(array, 0, n2 < 0 ? 0 : n2); + } + function dropRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; + } + function dropWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; + } + function fill(array, value2, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != "number" && isIterateeCall(array, value2, start)) { + start = 0; + end = length; + } + return baseFill(array, value2, start, end); + } + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger2(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); + } + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined$1) { + index = toInteger2(fromIndex); + index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); + } + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; + } + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; + } + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined$1 ? 1 : toInteger2(depth); + return baseFlatten(array, depth); + } + function fromPairs(pairs) { + var index = -1, length = pairs == null ? 0 : pairs.length, result2 = {}; + while (++index < length) { + var pair = pairs[index]; + result2[pair[0]] = pair[1]; + } + return result2; + } + function head(array) { + return array && array.length ? array[0] : undefined$1; + } + function indexOf(array, value2, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger2(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value2, index); + } + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; + } + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; + }); + var intersectionBy = baseRest(function(arrays) { + var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + if (iteratee2 === last(mapped)) { + iteratee2 = undefined$1; + } else { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : []; + }); + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); + comparator = typeof comparator == "function" ? comparator : undefined$1; + if (comparator) { + mapped.pop(); + } + return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined$1, comparator) : []; + }); + function join(array, separator) { + return array == null ? "" : nativeJoin.call(array, separator); + } + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined$1; + } + function lastIndexOf(array, value2, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined$1) { + index = toInteger2(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value2 === value2 ? strictLastIndexOf(array, value2, index) : baseFindIndex(array, baseIsNaN, index, true); + } + function nth(array, n2) { + return array && array.length ? baseNth(array, toInteger2(n2)) : undefined$1; + } + var pull = baseRest(pullAll); + function pullAll(array, values2) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array; + } + function pullAllBy(array, values2, iteratee2) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array; + } + function pullAllWith(array, values2, comparator) { + return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined$1, comparator) : array; + } + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes); + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + return result2; + }); + function remove(array, predicate) { + var result2 = []; + if (!(array && array.length)) { + return result2; + } + var index = -1, indexes = [], length = array.length; + predicate = getIteratee(predicate, 3); + while (++index < length) { + var value2 = array[index]; + if (predicate(value2, index, array)) { + result2.push(value2); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result2; + } + function reverse(array) { + return array == null ? array : nativeReverse.call(array); + } + function slice2(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != "number" && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } else { + start = start == null ? 0 : toInteger2(start); + end = end === undefined$1 ? length : toInteger2(end); + } + return baseSlice(array, start, end); + } + function sortedIndex(array, value2) { + return baseSortedIndex(array, value2); + } + function sortedIndexBy(array, value2, iteratee2) { + return baseSortedIndexBy(array, value2, getIteratee(iteratee2, 2)); + } + function sortedIndexOf(array, value2) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value2); + if (index < length && eq(array[index], value2)) { + return index; + } + } + return -1; + } + function sortedLastIndex(array, value2) { + return baseSortedIndex(array, value2, true); + } + function sortedLastIndexBy(array, value2, iteratee2) { + return baseSortedIndexBy(array, value2, getIteratee(iteratee2, 2), true); + } + function sortedLastIndexOf(array, value2) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value2, true) - 1; + if (eq(array[index], value2)) { + return index; + } + } + return -1; + } + function sortedUniq(array) { + return array && array.length ? baseSortedUniq(array) : []; + } + function sortedUniqBy(array, iteratee2) { + return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : []; + } + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; + } + function take(array, n2, guard) { + if (!(array && array.length)) { + return []; + } + n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); + return baseSlice(array, 0, n2 < 0 ? 0 : n2); + } + function takeRight(array, n2, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); + n2 = length - n2; + return baseSlice(array, n2 < 0 ? 0 : n2, length); + } + function takeRightWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; + } + function takeWhile(array, predicate) { + return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; + } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); + var unionBy = baseRest(function(arrays) { + var iteratee2 = last(arrays); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined$1; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)); + }); + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == "function" ? comparator : undefined$1; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined$1, comparator); + }); + function uniq(array) { + return array && array.length ? baseUniq(array) : []; + } + function uniqBy(array, iteratee2) { + return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : []; + } + function uniqWith(array, comparator) { + comparator = typeof comparator == "function" ? comparator : undefined$1; + return array && array.length ? baseUniq(array, undefined$1, comparator) : []; + } + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } + function unzipWith(array, iteratee2) { + if (!(array && array.length)) { + return []; + } + var result2 = unzip(array); + if (iteratee2 == null) { + return result2; + } + return arrayMap(result2, function(group) { + return apply2(iteratee2, undefined$1, group); + }); + } + var without = baseRest(function(array, values2) { + return isArrayLikeObject(array) ? baseDifference(array, values2) : []; + }); + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); + var xorBy = baseRest(function(arrays) { + var iteratee2 = last(arrays); + if (isArrayLikeObject(iteratee2)) { + iteratee2 = undefined$1; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2)); + }); + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == "function" ? comparator : undefined$1; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined$1, comparator); + }); + var zip = baseRest(unzip); + function zipObject(props, values2) { + return baseZipObject(props || [], values2 || [], assignValue); + } + function zipObjectDeep(props, values2) { + return baseZipObject(props || [], values2 || [], baseSet); + } + var zipWith = baseRest(function(arrays) { + var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined$1; + iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined$1; + return unzipWith(arrays, iteratee2); + }); + function chain(value2) { + var result2 = lodash2(value2); + result2.__chain__ = true; + return result2; + } + function tap(value2, interceptor) { + interceptor(value2); + return value2; + } + function thru(value2, interceptor) { + return interceptor(value2); + } + var wrapperAt = flatRest(function(paths) { + var length = paths.length, start = length ? paths[0] : 0, value2 = this.__wrapped__, interceptor = function(object) { + return baseAt(object, paths); + }; + if (length > 1 || this.__actions__.length || !(value2 instanceof LazyWrapper) || !isIndex(start)) { + return this.thru(interceptor); + } + value2 = value2.slice(start, +start + (length ? 1 : 0)); + value2.__actions__.push({ + "func": thru, + "args": [interceptor], + "thisArg": undefined$1 + }); + return new LodashWrapper(value2, this.__chain__).thru(function(array) { + if (length && !array.length) { + array.push(undefined$1); + } + return array; + }); + }); + function wrapperChain() { + return chain(this); + } + function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); + } + function wrapperNext() { + if (this.__values__ === undefined$1) { + this.__values__ = toArray2(this.value()); + } + var done = this.__index__ >= this.__values__.length, value2 = done ? undefined$1 : this.__values__[this.__index__++]; + return { "done": done, "value": value2 }; + } + function wrapperToIterator() { + return this; + } + function wrapperPlant(value2) { + var result2, parent2 = this; + while (parent2 instanceof baseLodash) { + var clone2 = wrapperClone(parent2); + clone2.__index__ = 0; + clone2.__values__ = undefined$1; + if (result2) { + previous.__wrapped__ = clone2; + } else { + result2 = clone2; + } + var previous = clone2; + parent2 = parent2.__wrapped__; + } + previous.__wrapped__ = value2; + return result2; + } + function wrapperReverse() { + var value2 = this.__wrapped__; + if (value2 instanceof LazyWrapper) { + var wrapped = value2; + if (this.__actions__.length) { + wrapped = new LazyWrapper(this); + } + wrapped = wrapped.reverse(); + wrapped.__actions__.push({ + "func": thru, + "args": [reverse], + "thisArg": undefined$1 + }); + return new LodashWrapper(wrapped, this.__chain__); + } + return this.thru(reverse); + } + function wrapperValue() { + return baseWrapperValue(this.__wrapped__, this.__actions__); + } + var countBy = createAggregator(function(result2, value2, key) { + if (hasOwnProperty2.call(result2, key)) { + ++result2[key]; + } else { + baseAssignValue(result2, key, 1); + } + }); + function every(collection, predicate, guard) { + var func = isArray2(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined$1; + } + return func(collection, getIteratee(predicate, 3)); + } + function filter(collection, predicate) { + var func = isArray2(collection) ? arrayFilter : baseFilter; + return func(collection, getIteratee(predicate, 3)); + } + var find = createFind(findIndex); + var findLast = createFind(findLastIndex); + function flatMap(collection, iteratee2) { + return baseFlatten(map2(collection, iteratee2), 1); + } + function flatMapDeep(collection, iteratee2) { + return baseFlatten(map2(collection, iteratee2), INFINITY); + } + function flatMapDepth(collection, iteratee2, depth) { + depth = depth === undefined$1 ? 1 : toInteger2(depth); + return baseFlatten(map2(collection, iteratee2), depth); + } + function forEach2(collection, iteratee2) { + var func = isArray2(collection) ? arrayEach : baseEach; + return func(collection, getIteratee(iteratee2, 3)); + } + function forEachRight(collection, iteratee2) { + var func = isArray2(collection) ? arrayEachRight : baseEachRight; + return func(collection, getIteratee(iteratee2, 3)); + } + var groupBy = createAggregator(function(result2, value2, key) { + if (hasOwnProperty2.call(result2, key)) { + result2[key].push(value2); + } else { + baseAssignValue(result2, key, [value2]); + } + }); + function includes(collection, value2, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = fromIndex && !guard ? toInteger2(fromIndex) : 0; + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString2(collection) ? fromIndex <= length && collection.indexOf(value2, fromIndex) > -1 : !!length && baseIndexOf(collection, value2, fromIndex) > -1; + } + var invokeMap = baseRest(function(collection, path, args) { + var index = -1, isFunc = typeof path == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : []; + baseEach(collection, function(value2) { + result2[++index] = isFunc ? apply2(path, value2, args) : baseInvoke(value2, path, args); + }); + return result2; + }); + var keyBy = createAggregator(function(result2, value2, key) { + baseAssignValue(result2, key, value2); + }); + function map2(collection, iteratee2) { + var func = isArray2(collection) ? arrayMap : baseMap; + return func(collection, getIteratee(iteratee2, 3)); + } + function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray2(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined$1 : orders; + if (!isArray2(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); + } + var partition = createAggregator(function(result2, value2, key) { + result2[key ? 0 : 1].push(value2); + }, function() { + return [[], []]; + }); + function reduce(collection, iteratee2, accumulator) { + var func = isArray2(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); + } + function reduceRight(collection, iteratee2, accumulator) { + var func = isArray2(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; + return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); + } + function reject(collection, predicate) { + var func = isArray2(collection) ? arrayFilter : baseFilter; + return func(collection, negate(getIteratee(predicate, 3))); + } + function sample(collection) { + var func = isArray2(collection) ? arraySample : baseSample; + return func(collection); + } + function sampleSize(collection, n2, guard) { + if (guard ? isIterateeCall(collection, n2, guard) : n2 === undefined$1) { + n2 = 1; + } else { + n2 = toInteger2(n2); + } + var func = isArray2(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n2); + } + function shuffle(collection) { + var func = isArray2(collection) ? arrayShuffle : baseShuffle; + return func(collection); + } + function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString2(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; + } + function some(collection, predicate, guard) { + var func = isArray2(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined$1; + } + return func(collection, getIteratee(predicate, 3)); + } + var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); + }); + var now = ctxNow || function() { + return root.Date.now(); + }; + function after(n2, func) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + n2 = toInteger2(n2); + return function() { + if (--n2 < 1) { + return func.apply(this, arguments); + } + }; + } + function ary(func, n2, guard) { + n2 = guard ? undefined$1 : n2; + n2 = func && n2 == null ? func.length : n2; + return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n2); + } + function before(n2, func) { + var result2; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + n2 = toInteger2(n2); + return function() { + if (--n2 > 0) { + result2 = func.apply(this, arguments); + } + if (n2 <= 1) { + func = undefined$1; + } + return result2; + }; + } + var bind2 = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind2)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(func, bitmask, thisArg, partials, holders); + }); + var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG; + } + return createWrap(key, bitmask, object, partials, holders); + }); + function curry(func, arity, guard) { + arity = guard ? undefined$1 : arity; + var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); + result2.placeholder = curry.placeholder; + return result2; + } + function curryRight(func, arity, guard) { + arity = guard ? undefined$1 : arity; + var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); + result2.placeholder = curryRight.placeholder; + return result2; + } + function debounce(func, wait, options) { + var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + wait = toNumber(wait) || 0; + if (isObject2(options)) { + leading = !!options.leading; + maxing = "maxWait" in options; + maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + function invokeFunc(time) { + var args = lastArgs, thisArg = lastThis; + lastArgs = lastThis = undefined$1; + lastInvokeTime = time; + result2 = func.apply(thisArg, args); + return result2; + } + function leadingEdge(time) { + lastInvokeTime = time; + timerId = setTimeout2(timerExpired, wait); + return leading ? invokeFunc(time) : result2; + } + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; + return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; + } + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; + return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; + } + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + timerId = setTimeout2(timerExpired, remainingWait(time)); + } + function trailingEdge(time) { + timerId = undefined$1; + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined$1; + return result2; + } + function cancel() { + if (timerId !== undefined$1) { + clearTimeout2(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined$1; + } + function flush() { + return timerId === undefined$1 ? result2 : trailingEdge(now()); + } + function debounced() { + var time = now(), isInvoking = shouldInvoke(time); + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + if (isInvoking) { + if (timerId === undefined$1) { + return leadingEdge(lastCallTime); + } + if (maxing) { + clearTimeout2(timerId); + timerId = setTimeout2(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined$1) { + timerId = setTimeout2(timerExpired, wait); + } + return result2; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; + } + var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); + }); + var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); + }); + function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); + } + function memoize2(func, resolver) { + if (typeof func != "function" || resolver != null && typeof resolver != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + var memoized = function() { + var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; + if (cache.has(key)) { + return cache.get(key); + } + var result2 = func.apply(this, args); + memoized.cache = cache.set(key, result2) || cache; + return result2; + }; + memoized.cache = new (memoize2.Cache || MapCache)(); + return memoized; + } + memoize2.Cache = MapCache; + function negate(predicate) { + if (typeof predicate != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: + return !predicate.call(this); + case 1: + return !predicate.call(this, args[0]); + case 2: + return !predicate.call(this, args[0], args[1]); + case 3: + return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; + } + function once(func) { + return before(2, func); + } + var overArgs = castRest(function(func, transforms) { + transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, length = nativeMin(args.length, funcsLength); + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply2(func, this, args); + }); + }); + var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders); + }); + var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders); + }); + var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes); + }); + function rest(func, start) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + start = start === undefined$1 ? start : toInteger2(start); + return baseRest(func, start); + } + function spread(func, start) { + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + start = start == null ? 0 : nativeMax(toInteger2(start), 0); + return baseRest(function(args) { + var array = args[start], otherArgs = castSlice(args, 0, start); + if (array) { + arrayPush(otherArgs, array); + } + return apply2(func, this, otherArgs); + }); + } + function throttle(func, wait, options) { + var leading = true, trailing = true; + if (typeof func != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + if (isObject2(options)) { + leading = "leading" in options ? !!options.leading : leading; + trailing = "trailing" in options ? !!options.trailing : trailing; + } + return debounce(func, wait, { + "leading": leading, + "maxWait": wait, + "trailing": trailing + }); + } + function unary(func) { + return ary(func, 1); + } + function wrap(value2, wrapper) { + return partial(castFunction(wrapper), value2); + } + function castArray() { + if (!arguments.length) { + return []; + } + var value2 = arguments[0]; + return isArray2(value2) ? value2 : [value2]; + } + function clone(value2) { + return baseClone(value2, CLONE_SYMBOLS_FLAG); + } + function cloneWith(value2, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + return baseClone(value2, CLONE_SYMBOLS_FLAG, customizer); + } + function cloneDeep(value2) { + return baseClone(value2, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + } + function cloneDeepWith(value2, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + return baseClone(value2, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + } + function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys2(source)); + } + function eq(value2, other) { + return value2 === other || value2 !== value2 && other !== other; + } + var gt = createRelationalOperation(baseGt); + var gte = createRelationalOperation(function(value2, other) { + return value2 >= other; + }); + var isArguments2 = baseIsArguments(/* @__PURE__ */ function() { + return arguments; + }()) ? baseIsArguments : function(value2) { + return isObjectLike(value2) && hasOwnProperty2.call(value2, "callee") && !propertyIsEnumerable.call(value2, "callee"); + }; + var isArray2 = Array2.isArray; + var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + function isArrayLike(value2) { + return value2 != null && isLength(value2.length) && !isFunction2(value2); + } + function isArrayLikeObject(value2) { + return isObjectLike(value2) && isArrayLike(value2); + } + function isBoolean(value2) { + return value2 === true || value2 === false || isObjectLike(value2) && baseGetTag(value2) == boolTag; + } + var isBuffer = nativeIsBuffer || stubFalse; + var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + function isElement(value2) { + return isObjectLike(value2) && value2.nodeType === 1 && !isPlainObject(value2); + } + function isEmpty(value2) { + if (value2 == null) { + return true; + } + if (isArrayLike(value2) && (isArray2(value2) || typeof value2 == "string" || typeof value2.splice == "function" || isBuffer(value2) || isTypedArray(value2) || isArguments2(value2))) { + return !value2.length; + } + var tag = getTag(value2); + if (tag == mapTag || tag == setTag) { + return !value2.size; + } + if (isPrototype2(value2)) { + return !baseKeys(value2).length; + } + for (var key in value2) { + if (hasOwnProperty2.call(value2, key)) { + return false; + } + } + return true; + } + function isEqual(value2, other) { + return baseIsEqual(value2, other); + } + function isEqualWith(value2, other, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + var result2 = customizer ? customizer(value2, other) : undefined$1; + return result2 === undefined$1 ? baseIsEqual(value2, other, undefined$1, customizer) : !!result2; + } + function isError(value2) { + if (!isObjectLike(value2)) { + return false; + } + var tag = baseGetTag(value2); + return tag == errorTag || tag == domExcTag || typeof value2.message == "string" && typeof value2.name == "string" && !isPlainObject(value2); + } + function isFinite2(value2) { + return typeof value2 == "number" && nativeIsFinite(value2); + } + function isFunction2(value2) { + if (!isObject2(value2)) { + return false; + } + var tag = baseGetTag(value2); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; + } + function isInteger(value2) { + return typeof value2 == "number" && value2 == toInteger2(value2); + } + function isLength(value2) { + return typeof value2 == "number" && value2 > -1 && value2 % 1 == 0 && value2 <= MAX_SAFE_INTEGER; + } + function isObject2(value2) { + var type = typeof value2; + return value2 != null && (type == "object" || type == "function"); + } + function isObjectLike(value2) { + return value2 != null && typeof value2 == "object"; + } + var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); + } + function isMatchWith(object, source, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + return baseIsMatch(object, source, getMatchData(source), customizer); + } + function isNaN2(value2) { + return isNumber(value2) && value2 != +value2; + } + function isNative(value2) { + if (isMaskable(value2)) { + throw new Error2(CORE_ERROR_TEXT); + } + return baseIsNative(value2); + } + function isNull(value2) { + return value2 === null; + } + function isNil(value2) { + return value2 == null; + } + function isNumber(value2) { + return typeof value2 == "number" || isObjectLike(value2) && baseGetTag(value2) == numberTag; + } + function isPlainObject(value2) { + if (!isObjectLike(value2) || baseGetTag(value2) != objectTag) { + return false; + } + var proto = getPrototype(value2); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty2.call(proto, "constructor") && proto.constructor; + return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; + } + var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function isSafeInteger(value2) { + return isInteger(value2) && value2 >= -9007199254740991 && value2 <= MAX_SAFE_INTEGER; + } + var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function isString2(value2) { + return typeof value2 == "string" || !isArray2(value2) && isObjectLike(value2) && baseGetTag(value2) == stringTag; + } + function isSymbol2(value2) { + return typeof value2 == "symbol" || isObjectLike(value2) && baseGetTag(value2) == symbolTag; + } + var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function isUndefined(value2) { + return value2 === undefined$1; + } + function isWeakMap(value2) { + return isObjectLike(value2) && getTag(value2) == weakMapTag; + } + function isWeakSet(value2) { + return isObjectLike(value2) && baseGetTag(value2) == weakSetTag; + } + var lt = createRelationalOperation(baseLt); + var lte = createRelationalOperation(function(value2, other) { + return value2 <= other; + }); + function toArray2(value2) { + if (!value2) { + return []; + } + if (isArrayLike(value2)) { + return isString2(value2) ? stringToArray(value2) : copyArray(value2); + } + if (symIterator && value2[symIterator]) { + return iteratorToArray(value2[symIterator]()); + } + var tag = getTag(value2), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; + return func(value2); + } + function toFinite(value2) { + if (!value2) { + return value2 === 0 ? value2 : 0; + } + value2 = toNumber(value2); + if (value2 === INFINITY || value2 === -Infinity) { + var sign2 = value2 < 0 ? -1 : 1; + return sign2 * MAX_INTEGER; + } + return value2 === value2 ? value2 : 0; + } + function toInteger2(value2) { + var result2 = toFinite(value2), remainder = result2 % 1; + return result2 === result2 ? remainder ? result2 - remainder : result2 : 0; + } + function toLength(value2) { + return value2 ? baseClamp(toInteger2(value2), 0, MAX_ARRAY_LENGTH) : 0; + } + function toNumber(value2) { + if (typeof value2 == "number") { + return value2; + } + if (isSymbol2(value2)) { + return NAN; + } + if (isObject2(value2)) { + var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2; + value2 = isObject2(other) ? other + "" : other; + } + if (typeof value2 != "string") { + return value2 === 0 ? value2 : +value2; + } + value2 = baseTrim(value2); + var isBinary = reIsBinary.test(value2); + return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2; + } + function toPlainObject(value2) { + return copyObject(value2, keysIn(value2)); + } + function toSafeInteger(value2) { + return value2 ? baseClamp(toInteger2(value2), -9007199254740991, MAX_SAFE_INTEGER) : value2 === 0 ? value2 : 0; + } + function toString(value2) { + return value2 == null ? "" : baseToString(value2); + } + var assign2 = createAssigner(function(object, source) { + if (isPrototype2(source) || isArrayLike(source)) { + copyObject(source, keys2(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty2.call(source, key)) { + assignValue(object, key, source[key]); + } + } + }); + var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); + }); + var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); + }); + var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys2(source), object, customizer); + }); + var at = flatRest(baseAt); + function create2(prototype, properties) { + var result2 = baseCreate(prototype); + return properties == null ? result2 : baseAssign(result2, properties); + } + var defaults = baseRest(function(object, sources) { + object = Object2(object); + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined$1; + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value2 = object[key]; + if (value2 === undefined$1 || eq(value2, objectProto[key]) && !hasOwnProperty2.call(object, key)) { + object[key] = source[key]; + } + } + } + return object; + }); + var defaultsDeep = baseRest(function(args) { + args.push(undefined$1, customDefaultsMerge); + return apply2(mergeWith, undefined$1, args); + }); + function findKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + } + function findLastKey(object, predicate) { + return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + } + function forIn(object, iteratee2) { + return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn); + } + function forInRight(object, iteratee2) { + return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn); + } + function forOwn(object, iteratee2) { + return object && baseForOwn(object, getIteratee(iteratee2, 3)); + } + function forOwnRight(object, iteratee2) { + return object && baseForOwnRight(object, getIteratee(iteratee2, 3)); + } + function functions(object) { + return object == null ? [] : baseFunctions(object, keys2(object)); + } + function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); + } + function get2(object, path, defaultValue) { + var result2 = object == null ? undefined$1 : baseGet(object, path); + return result2 === undefined$1 ? defaultValue : result2; + } + function has(object, path) { + return object != null && hasPath(object, path, baseHas); + } + function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); + } + var invert = createInverter(function(result2, value2, key) { + if (value2 != null && typeof value2.toString != "function") { + value2 = nativeObjectToString.call(value2); + } + result2[value2] = key; + }, constant(identity)); + var invertBy = createInverter(function(result2, value2, key) { + if (value2 != null && typeof value2.toString != "function") { + value2 = nativeObjectToString.call(value2); + } + if (hasOwnProperty2.call(result2, value2)) { + result2[value2].push(key); + } else { + result2[value2] = [key]; + } + }, getIteratee); + var invoke = baseRest(baseInvoke); + function keys2(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); + } + function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + } + function mapKeys(object, iteratee2) { + var result2 = {}; + iteratee2 = getIteratee(iteratee2, 3); + baseForOwn(object, function(value2, key, object2) { + baseAssignValue(result2, iteratee2(value2, key, object2), value2); + }); + return result2; + } + function mapValues(object, iteratee2) { + var result2 = {}; + iteratee2 = getIteratee(iteratee2, 3); + baseForOwn(object, function(value2, key, object2) { + baseAssignValue(result2, key, iteratee2(value2, key, object2)); + }); + return result2; + } + var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); + }); + var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); + }); + var omit = flatRest(function(object, paths) { + var result2 = {}; + if (object == null) { + return result2; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result2); + if (isDeep) { + result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result2, paths[length]); + } + return result2; + }); + function omitBy(object, predicate) { + return pickBy(object, negate(getIteratee(predicate))); + } + var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); + }); + function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = getIteratee(predicate); + return basePickBy(object, props, function(value2, path) { + return predicate(value2, path[0]); + }); + } + function result(object, path, defaultValue) { + path = castPath(path, object); + var index = -1, length = path.length; + if (!length) { + length = 1; + object = undefined$1; + } + while (++index < length) { + var value2 = object == null ? undefined$1 : object[toKey(path[index])]; + if (value2 === undefined$1) { + index = length; + value2 = defaultValue; + } + object = isFunction2(value2) ? value2.call(object) : value2; + } + return object; + } + function set(object, path, value2) { + return object == null ? object : baseSet(object, path, value2); + } + function setWith(object, path, value2, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + return object == null ? object : baseSet(object, path, value2, customizer); + } + var toPairs = createToPairs(keys2); + var toPairsIn = createToPairs(keysIn); + function transform(object, iteratee2, accumulator) { + var isArr = isArray2(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); + iteratee2 = getIteratee(iteratee2, 4); + if (accumulator == null) { + var Ctor = object && object.constructor; + if (isArrLike) { + accumulator = isArr ? new Ctor() : []; + } else if (isObject2(object)) { + accumulator = isFunction2(Ctor) ? baseCreate(getPrototype(object)) : {}; + } else { + accumulator = {}; + } + } + (isArrLike ? arrayEach : baseForOwn)(object, function(value2, index, object2) { + return iteratee2(accumulator, value2, index, object2); + }); + return accumulator; + } + function unset(object, path) { + return object == null ? true : baseUnset(object, path); + } + function update(object, path, updater) { + return object == null ? object : baseUpdate(object, path, castFunction(updater)); + } + function updateWith(object, path, updater, customizer) { + customizer = typeof customizer == "function" ? customizer : undefined$1; + return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + } + function values(object) { + return object == null ? [] : baseValues(object, keys2(object)); + } + function valuesIn(object) { + return object == null ? [] : baseValues(object, keysIn(object)); + } + function clamp(number, lower, upper) { + if (upper === undefined$1) { + upper = lower; + lower = undefined$1; + } + if (upper !== undefined$1) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined$1) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); + } + function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined$1) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); + } + function random(lower, upper, floating) { + if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined$1; + } + if (floating === undefined$1) { + if (typeof upper == "boolean") { + floating = upper; + upper = undefined$1; + } else if (typeof lower == "boolean") { + floating = lower; + lower = undefined$1; + } + } + if (lower === undefined$1 && upper === undefined$1) { + lower = 0; + upper = 1; + } else { + lower = toFinite(lower); + if (upper === undefined$1) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); + } + return baseRandom(lower, upper); + } + var camelCase = createCompounder(function(result2, word, index) { + word = word.toLowerCase(); + return result2 + (index ? capitalize(word) : word); + }); + function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); + } + function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); + } + function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + var length = string.length; + position = position === undefined$1 ? length : baseClamp(toInteger2(position), 0, length); + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; + } + function escape(string) { + string = toString(string); + return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; + } + function escapeRegExp(string) { + string = toString(string); + return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; + } + var kebabCase = createCompounder(function(result2, word, index) { + return result2 + (index ? "-" : "") + word.toLowerCase(); + }); + var lowerCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + word.toLowerCase(); + }); + var lowerFirst = createCaseFirst("toLowerCase"); + function pad(string, length, chars) { + string = toString(string); + length = toInteger2(length); + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); + } + function padEnd(string, length, chars) { + string = toString(string); + length = toInteger2(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? string + createPadding(length - strLength, chars) : string; + } + function padStart(string, length, chars) { + string = toString(string); + length = toInteger2(length); + var strLength = length ? stringSize(string) : 0; + return length && strLength < length ? createPadding(length - strLength, chars) + string : string; + } + function parseInt2(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); + } + function repeat(string, n2, guard) { + if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined$1) { + n2 = 1; + } else { + n2 = toInteger2(n2); + } + return baseRepeat(toString(string), n2); + } + function replace() { + var args = arguments, string = toString(args[0]); + return args.length < 3 ? string : string.replace(args[1], args[2]); + } + var snakeCase = createCompounder(function(result2, word, index) { + return result2 + (index ? "_" : "") + word.toLowerCase(); + }); + function split(string, separator, limit) { + if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { + separator = limit = undefined$1; + } + limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); + } + var startCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + upperFirst(word); + }); + function startsWith(string, target, position) { + string = toString(string); + position = position == null ? 0 : baseClamp(toInteger2(position), 0, string.length); + target = baseToString(target); + return string.slice(position, position + target.length) == target; + } + function template(string, options, guard) { + var settings = lodash2.templateSettings; + if (guard && isIterateeCall(string, options, guard)) { + options = undefined$1; + } + string = toString(string); + options = assignInWith({}, options, settings, customDefaultsAssignIn); + var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys2(imports), importsValues = baseValues(imports, importsKeys); + var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; + var reDelimiters = RegExp2( + (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", + "g" + ); + var sourceURL = "//# sourceURL=" + (hasOwnProperty2.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; + string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { + interpolateValue || (interpolateValue = esTemplateValue); + source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); + if (escapeValue) { + isEscaping = true; + source += "' +\n__e(" + escapeValue + ") +\n'"; + } + if (evaluateValue) { + isEvaluating = true; + source += "';\n" + evaluateValue + ";\n__p += '"; + } + if (interpolateValue) { + source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; + } + index = offset + match.length; + return match; + }); + source += "';\n"; + var variable = hasOwnProperty2.call(options, "variable") && options.variable; + if (!variable) { + source = "with (obj) {\n" + source + "\n}\n"; + } else if (reForbiddenIdentifierChars.test(variable)) { + throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT); + } + source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); + source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; + var result2 = attempt(function() { + return Function2(importsKeys, sourceURL + "return " + source).apply(undefined$1, importsValues); + }); + result2.source = source; + if (isError(result2)) { + throw result2; + } + return result2; + } + function toLower(value2) { + return toString(value2).toLowerCase(); + } + function toUpper(value2) { + return toString(value2).toUpperCase(); + } + function trim(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined$1)) { + return baseTrim(string); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; + return castSlice(strSymbols, start, end).join(""); + } + function trimEnd(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined$1)) { + return string.slice(0, trimmedEndIndex(string) + 1); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; + return castSlice(strSymbols, 0, end).join(""); + } + function trimStart(string, chars, guard) { + string = toString(string); + if (string && (guard || chars === undefined$1)) { + return string.replace(reTrimStart, ""); + } + if (!string || !(chars = baseToString(chars))) { + return string; + } + var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); + return castSlice(strSymbols, start).join(""); + } + function truncate(string, options) { + var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; + if (isObject2(options)) { + var separator = "separator" in options ? options.separator : separator; + length = "length" in options ? toInteger2(options.length) : length; + omission = "omission" in options ? baseToString(options.omission) : omission; + } + string = toString(string); + var strLength = string.length; + if (hasUnicode(string)) { + var strSymbols = stringToArray(string); + strLength = strSymbols.length; + } + if (length >= strLength) { + return string; + } + var end = length - stringSize(omission); + if (end < 1) { + return omission; + } + var result2 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end); + if (separator === undefined$1) { + return result2 + omission; + } + if (strSymbols) { + end += result2.length - end; + } + if (isRegExp(separator)) { + if (string.slice(end).search(separator)) { + var match, substring = result2; + if (!separator.global) { + separator = RegExp2(separator.source, toString(reFlags.exec(separator)) + "g"); + } + separator.lastIndex = 0; + while (match = separator.exec(substring)) { + var newEnd = match.index; + } + result2 = result2.slice(0, newEnd === undefined$1 ? end : newEnd); + } + } else if (string.indexOf(baseToString(separator), end) != end) { + var index = result2.lastIndexOf(separator); + if (index > -1) { + result2 = result2.slice(0, index); + } + } + return result2 + omission; + } + function unescape(string) { + string = toString(string); + return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; + } + var upperCase = createCompounder(function(result2, word, index) { + return result2 + (index ? " " : "") + word.toUpperCase(); + }); + var upperFirst = createCaseFirst("toUpperCase"); + function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined$1 : pattern; + if (pattern === undefined$1) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; + } + var attempt = baseRest(function(func, args) { + try { + return apply2(func, undefined$1, args); + } catch (e) { + return isError(e) ? e : new Error2(e); + } + }); + var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind2(object[key], object)); + }); + return object; + }); + function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != "function") { + throw new TypeError2(FUNC_ERROR_TEXT); + } + return [toIteratee(pair[0]), pair[1]]; + }); + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply2(pair[0], this, args)) { + return apply2(pair[1], this, args); + } + } + }); + } + function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); + } + function constant(value2) { + return function() { + return value2; + }; + } + function defaultTo(value2, defaultValue) { + return value2 == null || value2 !== value2 ? defaultValue : value2; + } + var flow = createFlow(); + var flowRight = createFlow(true); + function identity(value2) { + return value2; + } + function iteratee(func) { + return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)); + } + function matches(source) { + return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); + } + function matchesProperty(path, srcValue) { + return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); + } + var method = baseRest(function(path, args) { + return function(object) { + return baseInvoke(object, path, args); + }; + }); + var methodOf = baseRest(function(object, args) { + return function(path) { + return baseInvoke(object, path, args); + }; + }); + function mixin2(object, source, options) { + var props = keys2(source), methodNames = baseFunctions(source, props); + if (options == null && !(isObject2(source) && (methodNames.length || !props.length))) { + options = source; + source = object; + object = this; + methodNames = baseFunctions(source, keys2(source)); + } + var chain2 = !(isObject2(options) && "chain" in options) || !!options.chain, isFunc = isFunction2(object); + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain2 || chainAll) { + var result2 = object(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__); + actions.push({ "func": func, "args": arguments, "thisArg": object }); + result2.__chain__ = chainAll; + return result2; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + return object; + } + function noConflict() { + if (root._ === this) { + root._ = oldDash; + } + return this; + } + function noop2() { + } + function nthArg(n2) { + n2 = toInteger2(n2); + return baseRest(function(args) { + return baseNth(args, n2); + }); + } + var over = createOver(arrayMap); + var overEvery = createOver(arrayEvery); + var overSome = createOver(arraySome); + function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); + } + function propertyOf(object) { + return function(path) { + return object == null ? undefined$1 : baseGet(object, path); + }; + } + var range = createRange(); + var rangeRight = createRange(true); + function stubArray() { + return []; + } + function stubFalse() { + return false; + } + function stubObject() { + return {}; + } + function stubString() { + return ""; + } + function stubTrue() { + return true; + } + function times(n2, iteratee2) { + n2 = toInteger2(n2); + if (n2 < 1 || n2 > MAX_SAFE_INTEGER) { + return []; + } + var index = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH); + iteratee2 = getIteratee(iteratee2); + n2 -= MAX_ARRAY_LENGTH; + var result2 = baseTimes(length, iteratee2); + while (++index < n2) { + iteratee2(index); + } + return result2; + } + function toPath(value2) { + if (isArray2(value2)) { + return arrayMap(value2, toKey); + } + return isSymbol2(value2) ? [value2] : copyArray(stringToPath(toString(value2))); + } + function uniqueId(prefix) { + var id = ++idCounter; + return toString(prefix) + id; + } + var add = createMathOperation(function(augend, addend) { + return augend + addend; + }, 0); + var ceil = createRound("ceil"); + var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; + }, 1); + var floor2 = createRound("floor"); + function max2(array) { + return array && array.length ? baseExtremum(array, identity, baseGt) : undefined$1; + } + function maxBy(array, iteratee2) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined$1; + } + function mean(array) { + return baseMean(array, identity); + } + function meanBy(array, iteratee2) { + return baseMean(array, getIteratee(iteratee2, 2)); + } + function min(array) { + return array && array.length ? baseExtremum(array, identity, baseLt) : undefined$1; + } + function minBy(array, iteratee2) { + return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined$1; + } + var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; + }, 1); + var round = createRound("round"); + var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; + }, 0); + function sum(array) { + return array && array.length ? baseSum(array, identity) : 0; + } + function sumBy(array, iteratee2) { + return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0; + } + lodash2.after = after; + lodash2.ary = ary; + lodash2.assign = assign2; + lodash2.assignIn = assignIn; + lodash2.assignInWith = assignInWith; + lodash2.assignWith = assignWith; + lodash2.at = at; + lodash2.before = before; + lodash2.bind = bind2; + lodash2.bindAll = bindAll; + lodash2.bindKey = bindKey; + lodash2.castArray = castArray; + lodash2.chain = chain; + lodash2.chunk = chunk; + lodash2.compact = compact; + lodash2.concat = concat; + lodash2.cond = cond; + lodash2.conforms = conforms; + lodash2.constant = constant; + lodash2.countBy = countBy; + lodash2.create = create2; + lodash2.curry = curry; + lodash2.curryRight = curryRight; + lodash2.debounce = debounce; + lodash2.defaults = defaults; + lodash2.defaultsDeep = defaultsDeep; + lodash2.defer = defer; + lodash2.delay = delay; + lodash2.difference = difference; + lodash2.differenceBy = differenceBy; + lodash2.differenceWith = differenceWith; + lodash2.drop = drop; + lodash2.dropRight = dropRight; + lodash2.dropRightWhile = dropRightWhile; + lodash2.dropWhile = dropWhile; + lodash2.fill = fill; + lodash2.filter = filter; + lodash2.flatMap = flatMap; + lodash2.flatMapDeep = flatMapDeep; + lodash2.flatMapDepth = flatMapDepth; + lodash2.flatten = flatten; + lodash2.flattenDeep = flattenDeep; + lodash2.flattenDepth = flattenDepth; + lodash2.flip = flip; + lodash2.flow = flow; + lodash2.flowRight = flowRight; + lodash2.fromPairs = fromPairs; + lodash2.functions = functions; + lodash2.functionsIn = functionsIn; + lodash2.groupBy = groupBy; + lodash2.initial = initial; + lodash2.intersection = intersection; + lodash2.intersectionBy = intersectionBy; + lodash2.intersectionWith = intersectionWith; + lodash2.invert = invert; + lodash2.invertBy = invertBy; + lodash2.invokeMap = invokeMap; + lodash2.iteratee = iteratee; + lodash2.keyBy = keyBy; + lodash2.keys = keys2; + lodash2.keysIn = keysIn; + lodash2.map = map2; + lodash2.mapKeys = mapKeys; + lodash2.mapValues = mapValues; + lodash2.matches = matches; + lodash2.matchesProperty = matchesProperty; + lodash2.memoize = memoize2; + lodash2.merge = merge; + lodash2.mergeWith = mergeWith; + lodash2.method = method; + lodash2.methodOf = methodOf; + lodash2.mixin = mixin2; + lodash2.negate = negate; + lodash2.nthArg = nthArg; + lodash2.omit = omit; + lodash2.omitBy = omitBy; + lodash2.once = once; + lodash2.orderBy = orderBy; + lodash2.over = over; + lodash2.overArgs = overArgs; + lodash2.overEvery = overEvery; + lodash2.overSome = overSome; + lodash2.partial = partial; + lodash2.partialRight = partialRight; + lodash2.partition = partition; + lodash2.pick = pick; + lodash2.pickBy = pickBy; + lodash2.property = property; + lodash2.propertyOf = propertyOf; + lodash2.pull = pull; + lodash2.pullAll = pullAll; + lodash2.pullAllBy = pullAllBy; + lodash2.pullAllWith = pullAllWith; + lodash2.pullAt = pullAt; + lodash2.range = range; + lodash2.rangeRight = rangeRight; + lodash2.rearg = rearg; + lodash2.reject = reject; + lodash2.remove = remove; + lodash2.rest = rest; + lodash2.reverse = reverse; + lodash2.sampleSize = sampleSize; + lodash2.set = set; + lodash2.setWith = setWith; + lodash2.shuffle = shuffle; + lodash2.slice = slice2; + lodash2.sortBy = sortBy; + lodash2.sortedUniq = sortedUniq; + lodash2.sortedUniqBy = sortedUniqBy; + lodash2.split = split; + lodash2.spread = spread; + lodash2.tail = tail; + lodash2.take = take; + lodash2.takeRight = takeRight; + lodash2.takeRightWhile = takeRightWhile; + lodash2.takeWhile = takeWhile; + lodash2.tap = tap; + lodash2.throttle = throttle; + lodash2.thru = thru; + lodash2.toArray = toArray2; + lodash2.toPairs = toPairs; + lodash2.toPairsIn = toPairsIn; + lodash2.toPath = toPath; + lodash2.toPlainObject = toPlainObject; + lodash2.transform = transform; + lodash2.unary = unary; + lodash2.union = union; + lodash2.unionBy = unionBy; + lodash2.unionWith = unionWith; + lodash2.uniq = uniq; + lodash2.uniqBy = uniqBy; + lodash2.uniqWith = uniqWith; + lodash2.unset = unset; + lodash2.unzip = unzip; + lodash2.unzipWith = unzipWith; + lodash2.update = update; + lodash2.updateWith = updateWith; + lodash2.values = values; + lodash2.valuesIn = valuesIn; + lodash2.without = without; + lodash2.words = words; + lodash2.wrap = wrap; + lodash2.xor = xor; + lodash2.xorBy = xorBy; + lodash2.xorWith = xorWith; + lodash2.zip = zip; + lodash2.zipObject = zipObject; + lodash2.zipObjectDeep = zipObjectDeep; + lodash2.zipWith = zipWith; + lodash2.entries = toPairs; + lodash2.entriesIn = toPairsIn; + lodash2.extend = assignIn; + lodash2.extendWith = assignInWith; + mixin2(lodash2, lodash2); + lodash2.add = add; + lodash2.attempt = attempt; + lodash2.camelCase = camelCase; + lodash2.capitalize = capitalize; + lodash2.ceil = ceil; + lodash2.clamp = clamp; + lodash2.clone = clone; + lodash2.cloneDeep = cloneDeep; + lodash2.cloneDeepWith = cloneDeepWith; + lodash2.cloneWith = cloneWith; + lodash2.conformsTo = conformsTo; + lodash2.deburr = deburr; + lodash2.defaultTo = defaultTo; + lodash2.divide = divide; + lodash2.endsWith = endsWith; + lodash2.eq = eq; + lodash2.escape = escape; + lodash2.escapeRegExp = escapeRegExp; + lodash2.every = every; + lodash2.find = find; + lodash2.findIndex = findIndex; + lodash2.findKey = findKey; + lodash2.findLast = findLast; + lodash2.findLastIndex = findLastIndex; + lodash2.findLastKey = findLastKey; + lodash2.floor = floor2; + lodash2.forEach = forEach2; + lodash2.forEachRight = forEachRight; + lodash2.forIn = forIn; + lodash2.forInRight = forInRight; + lodash2.forOwn = forOwn; + lodash2.forOwnRight = forOwnRight; + lodash2.get = get2; + lodash2.gt = gt; + lodash2.gte = gte; + lodash2.has = has; + lodash2.hasIn = hasIn; + lodash2.head = head; + lodash2.identity = identity; + lodash2.includes = includes; + lodash2.indexOf = indexOf; + lodash2.inRange = inRange; + lodash2.invoke = invoke; + lodash2.isArguments = isArguments2; + lodash2.isArray = isArray2; + lodash2.isArrayBuffer = isArrayBuffer; + lodash2.isArrayLike = isArrayLike; + lodash2.isArrayLikeObject = isArrayLikeObject; + lodash2.isBoolean = isBoolean; + lodash2.isBuffer = isBuffer; + lodash2.isDate = isDate; + lodash2.isElement = isElement; + lodash2.isEmpty = isEmpty; + lodash2.isEqual = isEqual; + lodash2.isEqualWith = isEqualWith; + lodash2.isError = isError; + lodash2.isFinite = isFinite2; + lodash2.isFunction = isFunction2; + lodash2.isInteger = isInteger; + lodash2.isLength = isLength; + lodash2.isMap = isMap; + lodash2.isMatch = isMatch; + lodash2.isMatchWith = isMatchWith; + lodash2.isNaN = isNaN2; + lodash2.isNative = isNative; + lodash2.isNil = isNil; + lodash2.isNull = isNull; + lodash2.isNumber = isNumber; + lodash2.isObject = isObject2; + lodash2.isObjectLike = isObjectLike; + lodash2.isPlainObject = isPlainObject; + lodash2.isRegExp = isRegExp; + lodash2.isSafeInteger = isSafeInteger; + lodash2.isSet = isSet; + lodash2.isString = isString2; + lodash2.isSymbol = isSymbol2; + lodash2.isTypedArray = isTypedArray; + lodash2.isUndefined = isUndefined; + lodash2.isWeakMap = isWeakMap; + lodash2.isWeakSet = isWeakSet; + lodash2.join = join; + lodash2.kebabCase = kebabCase; + lodash2.last = last; + lodash2.lastIndexOf = lastIndexOf; + lodash2.lowerCase = lowerCase; + lodash2.lowerFirst = lowerFirst; + lodash2.lt = lt; + lodash2.lte = lte; + lodash2.max = max2; + lodash2.maxBy = maxBy; + lodash2.mean = mean; + lodash2.meanBy = meanBy; + lodash2.min = min; + lodash2.minBy = minBy; + lodash2.stubArray = stubArray; + lodash2.stubFalse = stubFalse; + lodash2.stubObject = stubObject; + lodash2.stubString = stubString; + lodash2.stubTrue = stubTrue; + lodash2.multiply = multiply; + lodash2.nth = nth; + lodash2.noConflict = noConflict; + lodash2.noop = noop2; + lodash2.now = now; + lodash2.pad = pad; + lodash2.padEnd = padEnd; + lodash2.padStart = padStart; + lodash2.parseInt = parseInt2; + lodash2.random = random; + lodash2.reduce = reduce; + lodash2.reduceRight = reduceRight; + lodash2.repeat = repeat; + lodash2.replace = replace; + lodash2.result = result; + lodash2.round = round; + lodash2.runInContext = runInContext2; + lodash2.sample = sample; + lodash2.size = size; + lodash2.snakeCase = snakeCase; + lodash2.some = some; + lodash2.sortedIndex = sortedIndex; + lodash2.sortedIndexBy = sortedIndexBy; + lodash2.sortedIndexOf = sortedIndexOf; + lodash2.sortedLastIndex = sortedLastIndex; + lodash2.sortedLastIndexBy = sortedLastIndexBy; + lodash2.sortedLastIndexOf = sortedLastIndexOf; + lodash2.startCase = startCase; + lodash2.startsWith = startsWith; + lodash2.subtract = subtract; + lodash2.sum = sum; + lodash2.sumBy = sumBy; + lodash2.template = template; + lodash2.times = times; + lodash2.toFinite = toFinite; + lodash2.toInteger = toInteger2; + lodash2.toLength = toLength; + lodash2.toLower = toLower; + lodash2.toNumber = toNumber; + lodash2.toSafeInteger = toSafeInteger; + lodash2.toString = toString; + lodash2.toUpper = toUpper; + lodash2.trim = trim; + lodash2.trimEnd = trimEnd; + lodash2.trimStart = trimStart; + lodash2.truncate = truncate; + lodash2.unescape = unescape; + lodash2.uniqueId = uniqueId; + lodash2.upperCase = upperCase; + lodash2.upperFirst = upperFirst; + lodash2.each = forEach2; + lodash2.eachRight = forEachRight; + lodash2.first = head; + mixin2(lodash2, function() { + var source = {}; + baseForOwn(lodash2, function(func, methodName) { + if (!hasOwnProperty2.call(lodash2.prototype, methodName)) { + source[methodName] = func; + } + }); + return source; + }(), { "chain": false }); + lodash2.VERSION = VERSION; + arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { + lodash2[methodName].placeholder = lodash2; + }); + arrayEach(["drop", "take"], function(methodName, index) { + LazyWrapper.prototype[methodName] = function(n2) { + n2 = n2 === undefined$1 ? 1 : nativeMax(toInteger2(n2), 0); + var result2 = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone(); + if (result2.__filtered__) { + result2.__takeCount__ = nativeMin(n2, result2.__takeCount__); + } else { + result2.__views__.push({ + "size": nativeMin(n2, MAX_ARRAY_LENGTH), + "type": methodName + (result2.__dir__ < 0 ? "Right" : "") + }); + } + return result2; + }; + LazyWrapper.prototype[methodName + "Right"] = function(n2) { + return this.reverse()[methodName](n2).reverse(); + }; + }); + arrayEach(["filter", "map", "takeWhile"], function(methodName, index) { + var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; + LazyWrapper.prototype[methodName] = function(iteratee2) { + var result2 = this.clone(); + result2.__iteratees__.push({ + "iteratee": getIteratee(iteratee2, 3), + "type": type + }); + result2.__filtered__ = result2.__filtered__ || isFilter; + return result2; + }; + }); + arrayEach(["head", "last"], function(methodName, index) { + var takeName = "take" + (index ? "Right" : ""); + LazyWrapper.prototype[methodName] = function() { + return this[takeName](1).value()[0]; + }; + }); + arrayEach(["initial", "tail"], function(methodName, index) { + var dropName = "drop" + (index ? "" : "Right"); + LazyWrapper.prototype[methodName] = function() { + return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); + }; + }); + LazyWrapper.prototype.compact = function() { + return this.filter(identity); + }; + LazyWrapper.prototype.find = function(predicate) { + return this.filter(predicate).head(); + }; + LazyWrapper.prototype.findLast = function(predicate) { + return this.reverse().find(predicate); + }; + LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { + if (typeof path == "function") { + return new LazyWrapper(this); + } + return this.map(function(value2) { + return baseInvoke(value2, path, args); + }); + }); + LazyWrapper.prototype.reject = function(predicate) { + return this.filter(negate(getIteratee(predicate))); + }; + LazyWrapper.prototype.slice = function(start, end) { + start = toInteger2(start); + var result2 = this; + if (result2.__filtered__ && (start > 0 || end < 0)) { + return new LazyWrapper(result2); + } + if (start < 0) { + result2 = result2.takeRight(-start); + } else if (start) { + result2 = result2.drop(start); + } + if (end !== undefined$1) { + end = toInteger2(end); + result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start); + } + return result2; + }; + LazyWrapper.prototype.takeRightWhile = function(predicate) { + return this.reverse().takeWhile(predicate).reverse(); + }; + LazyWrapper.prototype.toArray = function() { + return this.take(MAX_ARRAY_LENGTH); + }; + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash2[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); + if (!lodashFunc) { + return; + } + lodash2.prototype[methodName] = function() { + var value2 = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value2 instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray2(value2); + var interceptor = function(value3) { + var result3 = lodashFunc.apply(lodash2, arrayPush([value3], args)); + return isTaker && chainAll ? result3[0] : result3; + }; + if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) { + isLazy = useLazy = false; + } + var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; + if (!retUnwrapped && useLazy) { + value2 = onlyLazy ? value2 : new LazyWrapper(this); + var result2 = func.apply(value2, args); + result2.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined$1 }); + return new LodashWrapper(result2, chainAll); + } + if (isUnwrapped && onlyLazy) { + return func.apply(this, args); + } + result2 = this.thru(interceptor); + return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2; + }; + }); + arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { + var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); + lodash2.prototype[methodName] = function() { + var args = arguments; + if (retUnwrapped && !this.__chain__) { + var value2 = this.value(); + return func.apply(isArray2(value2) ? value2 : [], args); + } + return this[chainName](function(value3) { + return func.apply(isArray2(value3) ? value3 : [], args); + }); + }; + }); + baseForOwn(LazyWrapper.prototype, function(func, methodName) { + var lodashFunc = lodash2[methodName]; + if (lodashFunc) { + var key = lodashFunc.name + ""; + if (!hasOwnProperty2.call(realNames, key)) { + realNames[key] = []; + } + realNames[key].push({ "name": methodName, "func": lodashFunc }); + } + }); + realNames[createHybrid(undefined$1, WRAP_BIND_KEY_FLAG).name] = [{ + "name": "wrapper", + "func": undefined$1 + }]; + LazyWrapper.prototype.clone = lazyClone; + LazyWrapper.prototype.reverse = lazyReverse; + LazyWrapper.prototype.value = lazyValue; + lodash2.prototype.at = wrapperAt; + lodash2.prototype.chain = wrapperChain; + lodash2.prototype.commit = wrapperCommit; + lodash2.prototype.next = wrapperNext; + lodash2.prototype.plant = wrapperPlant; + lodash2.prototype.reverse = wrapperReverse; + lodash2.prototype.toJSON = lodash2.prototype.valueOf = lodash2.prototype.value = wrapperValue; + lodash2.prototype.first = lodash2.prototype.head; + if (symIterator) { + lodash2.prototype[symIterator] = wrapperToIterator; + } + return lodash2; + }; + var _ = runInContext(); + if (freeModule) { + (freeModule.exports = _)._ = _; + freeExports._ = _; + } else { + root._ = _; + } + }).call(commonjsGlobal); +})(lodash, lodash.exports); +var lodashExports = lodash.exports; +function ownKeys$1(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread$1(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys$1(Object(t), true).forEach(function(r2) { + _defineProperty$2(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _defineProperty$2(e, r, t) { + return (r = _toPropertyKey$2(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey$2(t) { + var i = _toPrimitive$2(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive$2(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +var log$2 = Log.module("ChartUtils"); +var BUSINESS_COLUMN_TYPE = "io.deephaven.time.DateTime"; +var MILLIS_PER_HOUR = 36e5; +var NANOS_PER_MILLI = 1e6; +function isDateWrapper(value2) { + return value2.asDate !== void 0; +} +function isLongWrapper(value2) { + return value2.asNumber !== void 0; +} +function isDateTimeColumnFormatter(value2) { + return value2.dhTimeZone !== void 0; +} +function isRangedPlotlyAxis(value2) { + return value2 != null && value2.range != null && (value2.autorange === false || value2.autorange === void 0); +} +function isWebGLSupported() { + var canvas = document.createElement("canvas"); + var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); + return gl != null && gl instanceof WebGLRenderingContext; +} +var IS_WEBGL_SUPPORTED = isWebGLSupported(); +class ChartUtils { + /** + * Generate the plotly error bar data from the passed in data. + * Iris passes in the values as absolute, plotly needs them as relative. + * @param x The main data array + * @param xLow The absolute low values + * @param xHigh + * + * @returns The error_x object required by plotly, or null if none is required + */ + static getPlotlyErrorBars(x, xLow, xHigh) { + var array = xHigh.map((value2, i) => value2 - x[i]); + var arrayminus = xLow.map((value2, i) => x[i] - value2); + return { + type: "data", + symmetric: false, + array, + arrayminus + }; + } + static convertNumberPrefix(prefix) { + return prefix.replace(/\u00A4\u00A4/g, "USD").replace(/\u00A4/g, "$"); + } + static getPlotlyNumberFormat(formatter, columnType, formatPattern) { + if (formatPattern == null || formatPattern === "") { + return null; + } + var subpatterns = formatPattern.split(";"); + var matchArray = subpatterns[0].match(/^([^#,0.]*)([#,]*)([0,]*)(\.?)(0*)(#*)(E?0*)(%?)(.*)/); + assertNotNull(matchArray); + var [, prefix, placeholderDigits, zeroDigits, , decimalDigits, optionalDecimalDigits, numberType, percentSign, suffix] = matchArray; + var paddingLength = zeroDigits.replace(",", "").length; + var isCommaSeparated = placeholderDigits.indexOf(",") >= 0 || zeroDigits.indexOf(",") >= 0; + var comma = isCommaSeparated ? "," : ""; + var plotlyNumberType = numberType != null && numberType !== "" ? "e" : "f"; + var type = percentSign !== "" ? percentSign : plotlyNumberType; + var decimalLength = decimalDigits.length + optionalDecimalDigits.length; + var trimOption = ""; + var tickformat = "0".concat(paddingLength).concat(comma, ".").concat(decimalLength).concat(trimOption).concat(type); + var tickprefix = ChartUtils.convertNumberPrefix(prefix); + var ticksuffix = ChartUtils.convertNumberPrefix(suffix); + return { + tickformat, + tickprefix, + ticksuffix, + automargin: true + }; + } + /** + * Adds tick spacing for an axis that has gapBetweenMajorTicks defined. + * + * @param axisFormat the current axis format, may be null + * @param axis the current axis + * @param isDateType indicates if the columns is a date type + */ + static addTickSpacing(axisFormat, axis, isDateType) { + var { + gapBetweenMajorTicks + } = axis; + if (gapBetweenMajorTicks != null && gapBetweenMajorTicks > 0) { + var updatedFormat = axisFormat || {}; + var tickSpacing = gapBetweenMajorTicks; + if (isDateType) { + tickSpacing = gapBetweenMajorTicks / NANOS_PER_MILLI; + } + if (axis.log) { + tickSpacing = Math.log(tickSpacing); + } + updatedFormat.tickmode = "linear"; + updatedFormat.dtick = tickSpacing; + return updatedFormat; + } + return axisFormat; + } + /** + * Retrieve the data source for a given axis in a chart + * @param chart The chart to get the source for + * @param axis The axis to find the source for + * @returns The first source matching this axis + */ + static getSourceForAxis(chart, axis) { + for (var i = 0; i < chart.series.length; i += 1) { + var series = chart.series[i]; + for (var j = 0; j < series.sources.length; j += 1) { + var source = series.sources[j]; + if (source.axis === axis) { + return source; + } + } + } + return null; + } + /** + * Get visibility setting for the series object + * @param name The series name to get the visibility for + * @param settings Chart settings + * @returns True for visible series and 'legendonly' for hidden + */ + static getSeriesVisibility(name, settings) { + if (settings != null && settings.hiddenSeries != null && settings.hiddenSeries.includes(name)) { + return "legendonly"; + } + return true; + } + /** + * Get hidden labels array from chart settings + * @param settings Chart settings + * @returns Array of hidden series names + */ + static getHiddenLabels(settings) { + if (settings !== null && settings !== void 0 && settings.hiddenSeries) { + return [...settings.hiddenSeries]; + } + return []; + } + /** + * Create a default series data object. Apply styling to the object afterward. + * @returns A simple series data object with no styling + */ + static makeSeriesData(type, mode, name, showLegend) { + var orientation = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : ChartUtils.ORIENTATION.VERTICAL; + return { + type, + mode, + name, + orientation, + showlegend: showLegend !== null && showLegend !== void 0 ? showLegend : void 0 + }; + } + /** + * Get the Plotly marker symbol for the provided Deephaven shape + * Deephaven shapes: https://deephaven.io/enterprise/docs/plotting/visual-formatting/#point-formatting + * Plotly shapes: https://plotly.com/javascript/reference/scattergl/#scattergl-marker-symbol + * Table of plotly shapes: https://plotly.com/python/marker-style/#custom-marker-symbols + * @param deephavenShape Deephaven shape to get the marker symbol for + */ + static getMarkerSymbol(deephavenShape) { + switch (deephavenShape) { + case "SQUARE": + return "square"; + case "CIRCLE": + return "circle"; + case "DIAMOND": + return "diamond"; + case "UP_TRIANGLE": + return "triangle-up"; + case "DOWN_TRIANGLE": + return "triangle-down"; + case "RIGHT_TRIANGLE": + return "triangle-right"; + case "LEFT_TRIANGLE": + return "triangle-left"; + case "ELLIPSE": + case "HORIZONTAL_RECTANGLE": + case "VERTICAL_RECTANGLE": + default: + throw new Error("Unrecognized shape ".concat(deephavenShape)); + } + } + /** + * Get all axes for a given `Figure`. Iterates through all charts axes and concatenates them. + * @param figure Figure to get all axes for + */ + static getAllAxes(figure) { + return figure.charts.reduce((axes, chart) => [...axes, ...chart.axes], []); + } + /** + * Get the axis type map for the figure provided + * @param figure Figure to get the type map for + * @returns Axis type map for the figure provided + */ + static getAxisTypeMap(figure) { + var axes = ChartUtils.getAllAxes(figure); + return ChartUtils.groupArray(axes, "type"); + } + /** + * Retrieve the chart that contains the passed in series from the figure + * @param figure The figure to retrieve the chart from + * @param series The series to get the chart for + */ + static getChartForSeries(figure, series) { + var { + charts + } = figure; + for (var i = 0; i < charts.length; i += 1) { + var _chart = charts[i]; + for (var j = 0; j < _chart.series.length; j += 1) { + if (series === _chart.series[j]) { + return _chart; + } + } + } + return null; + } + /** + * Get an object mapping axis to their ranges + * @param layout The plotly layout object to get the ranges from + * @returns An object mapping the axis name to it's range + */ + static getLayoutRanges(layout) { + var ranges = {}; + var keys2 = Object.keys(layout).filter((key2) => key2.indexOf("axis") >= 0); + for (var i = 0; i < keys2.length; i += 1) { + var key = keys2[i]; + var value2 = layout[key]; + if (isRangedPlotlyAxis(value2)) { + ranges[key] = [...value2.range]; + } + } + return ranges; + } + static getAxisLayoutProperty(axisProperty, axisIndex) { + var axisIndexString = axisIndex > 0 ? "".concat(axisIndex + 1) : ""; + return "".concat(axisProperty !== null && axisProperty !== void 0 ? axisProperty : "", "axis").concat(axisIndexString); + } + /** + * Converts an open or close period to a declimal. e.g '09:30" to 9.5 + * + * @param period the open or close value of the period + */ + static periodToDecimal(period) { + var values = period.split(":"); + return Number(values[0]) + Number(values[1]) / 60; + } + /** + * Converts a decimal to a period. e.g 9.5 to '09:30' + * + * @param decimal the decimal value to + */ + static decimalToPeriod(decimal) { + var hours = Math.floor(decimal); + var minutes = Math.round((decimal - hours) * 60); + return "".concat(hours.toString().padStart(2, "0"), ":").concat(minutes.toString().padStart(2, "0")); + } + /** + * Groups an array and returns a map + * @param array The object to group + * @param property The property name to group by + * @returns A map containing the items grouped by their values for the property + */ + static groupArray(array, property) { + return array.reduce((result, item) => { + var _result$get; + var key = item[property]; + var group = (_result$get = result.get(key)) !== null && _result$get !== void 0 ? _result$get : []; + group.push(item); + result.set(key, group); + return result; + }, /* @__PURE__ */ new Map()); + } + /** + * Parses the colorway value of a theme and returns an array of colors + * Value could be a single string with space separated colors or already be an + * array of strings representing the colorway + * @param colorway The colorway value to normalize + * @returns Colorway array for the theme or undefined + */ + static normalizeColorway(colorway) { + if (colorway == null) { + return; + } + if (Array.isArray(colorway)) { + return colorway; + } + if (typeof colorway === "string") { + return colorway.split(" "); + } + log$2.warn("Unexpected colorway format: ".concat(colorway)); + } + static titleFromSettings(settings) { + var { + series, + xAxis, + title = "".concat((series !== null && series !== void 0 ? series : []).join(", "), " by ").concat(xAxis) + } = settings; + return title; + } + static getTimeZoneDiff(calendarTimeZone, formatterTimeZone) { + return formatterTimeZone ? (calendarTimeZone.standardOffset - formatterTimeZone.standardOffset) / 60 : 0; + } + /** + * Creates closed periods for a partial holiday. + * + * @param holidayPeriods the business periods for the holiday + * @param calendarPeriods the business periods for the calendar + * @returns an array of closed ranges for the partial holiday. Should be the ranges during the regular business hours that are _not_ specified by the holiday periods. + */ + static createClosedRangesForPartialHoliday(holidayPeriods, calendarPeriods) { + var calendarRanges = calendarPeriods.map((period) => [ChartUtils.periodToDecimal(period.open), ChartUtils.periodToDecimal(period.close)]); + calendarRanges.sort((a, b) => a[0] - b[0]); + if (calendarRanges.length === 0) { + calendarRanges.push([0, 24]); + } + var holidayRanges = holidayPeriods.map((period) => [ChartUtils.periodToDecimal(period.open), ChartUtils.periodToDecimal(period.close)]); + holidayRanges.sort((a, b) => a[0] - b[0]); + var closedRanges = []; + for (var c = 0; c < calendarRanges.length; c += 1) { + var calendarRange = calendarRanges[c]; + var lastClose = calendarRange[0]; + for (var h = 0; h < holidayRanges.length; h += 1) { + var holidayRange = holidayRanges[h]; + if (holidayRange[1] > lastClose && holidayRange[0] < calendarRange[1]) { + if (holidayRange[0] > lastClose) { + closedRanges.push([lastClose, holidayRange[0]]); + } + lastClose = holidayRange[1]; + } + } + if (lastClose < calendarRange[1]) { + closedRanges.push([lastClose, calendarRange[1]]); + } + } + return closedRanges; + } + constructor(dh) { + _defineProperty$2(this, "dh", void 0); + _defineProperty$2(this, "daysOfWeek", void 0); + this.dh = dh; + this.daysOfWeek = Object.freeze(dh.calendar.DayOfWeek.values()); + bindAllMethods(this); + } + /** + * Retrieve the axis formats from the provided figure. + * Currently defaults to just the x/y axes. + * @param figure The figure to get the axis formats for + * @param formatter The formatter to use when getting the axis format + * @returns A map of axis layout property names to axis formats + */ + getAxisFormats(figure, formatter) { + var axisFormats = /* @__PURE__ */ new Map(); + var nullFormat = { + tickformat: null, + ticksuffix: null + }; + var allAxes = ChartUtils.getAllAxes(figure); + var axisTypeMap = ChartUtils.groupArray(allAxes, "type"); + var { + charts + } = figure; + for (var i = 0; i < charts.length; i += 1) { + var _chart2 = charts[i]; + for (var j = 0; j < _chart2.series.length; j += 1) { + var series = _chart2.series[j]; + var { + sources + } = series; + var axisSources = sources.filter((source2) => source2.axis); + for (var k = 0; k < axisSources.length; k += 1) { + var source = axisSources[k]; + var { + axis: _axis + } = source; + var { + type: axisType + } = _axis; + var typeAxes = axisTypeMap.get(axisType); + assertNotNull(typeAxes); + var axisIndex = typeAxes.indexOf(_axis); + var axisProperty = this.getAxisPropertyName(axisType); + if (axisProperty != null) { + var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); + if (axisFormats.has(axisLayoutProperty)) { + log$2.debug("".concat(axisLayoutProperty, " already added.")); + } else { + log$2.debug("Adding ".concat(axisLayoutProperty, " to axisFormats.")); + var axisFormat = this.getPlotlyAxisFormat(source, formatter); + if (axisFormat === null) { + axisFormats.set(axisLayoutProperty, nullFormat); + } else { + axisFormats.set(axisLayoutProperty, axisFormat); + var { + businessCalendar + } = _axis; + if (businessCalendar != null) { + axisFormat.rangebreaks = this.createRangeBreaksFromBusinessCalendar(businessCalendar, formatter); + } + if (axisFormats.size === _chart2.axes.length) { + return axisFormats; + } + } + } + } + } + } + } + return axisFormats; + } + /** + * Converts the Iris plot style into a plotly chart type + * @param plotStyle The plotStyle to use, see dh.plot.SeriesPlotStyle + * @param isBusinessTime If the plot is using business time for an axis + * @param allowWebGL If WebGL is allowedd + */ + getPlotlyChartType(plotStyle, isBusinessTime) { + var allowWebGL = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; + var { + dh + } = this; + switch (plotStyle) { + case dh.plot.SeriesPlotStyle.SCATTER: + case dh.plot.SeriesPlotStyle.LINE: + return !isBusinessTime && IS_WEBGL_SUPPORTED && allowWebGL ? "scattergl" : "scatter"; + case dh.plot.SeriesPlotStyle.BAR: + case dh.plot.SeriesPlotStyle.STACKED_BAR: + return "bar"; + case dh.plot.SeriesPlotStyle.PIE: + return "pie"; + case dh.plot.SeriesPlotStyle.TREEMAP: + return "treemap"; + case dh.plot.SeriesPlotStyle.HISTOGRAM: + return "histogram"; + case dh.plot.SeriesPlotStyle.OHLC: + return "ohlc"; + default: + return void 0; + } + } + /** + * Converts the Iris plot style into a plotly chart mode + * @param plotStyle The plotStyle to use, see dh.plot.SeriesPlotStyle.* + * @param areLinesVisible Whether lines are visible or not + * @param areShapesVisible Whether shapes are visible or not + */ + getPlotlyChartMode(plotStyle, areLinesVisible, areShapesVisible) { + var { + dh + } = this; + var modes = /* @__PURE__ */ new Set(); + switch (plotStyle) { + case dh.plot.SeriesPlotStyle.SCATTER: + if (areLinesVisible !== null && areLinesVisible !== void 0 ? areLinesVisible : false) { + modes.add(ChartUtils.MODE_LINES); + } + if (areShapesVisible !== null && areShapesVisible !== void 0 ? areShapesVisible : true) { + modes.add(ChartUtils.MODE_MARKERS); + } + break; + case dh.plot.SeriesPlotStyle.LINE: + if (areLinesVisible !== null && areLinesVisible !== void 0 ? areLinesVisible : true) { + modes.add(ChartUtils.MODE_LINES); + } + if (areShapesVisible !== null && areShapesVisible !== void 0 ? areShapesVisible : false) { + modes.add(ChartUtils.MODE_MARKERS); + } + break; + } + return modes.size > 0 ? [...modes].join("+") : void 0; + } + /** + * Get the property to set on the series data for plotly + * @param plotStyle The plot style of the series + * @param sourceType The source type for the series + */ + getPlotlyProperty(plotStyle, sourceType) { + var { + dh + } = this; + switch (plotStyle) { + case dh.plot.SeriesPlotStyle.PIE: + switch (sourceType) { + case dh.plot.SourceType.X: + return "labels"; + case dh.plot.SourceType.Y: + return "values"; + } + break; + case dh.plot.SeriesPlotStyle.OHLC: + switch (sourceType) { + case dh.plot.SourceType.TIME: + return "x"; + } + break; + case dh.plot.SeriesPlotStyle.TREEMAP: + switch (sourceType) { + case dh.plot.SourceType.X: + return "ids"; + case dh.plot.SourceType.Y: + return "values"; + case dh.plot.SourceType.LABEL: + return "labels"; + case dh.plot.SourceType.PARENT: + return "parents"; + case dh.plot.SourceType.COLOR: + return "marker.colors"; + } + break; + } + switch (sourceType) { + case dh.plot.SourceType.X: + return "x"; + case dh.plot.SourceType.Y: + return "y"; + case dh.plot.SourceType.Z: + return "z"; + case dh.plot.SourceType.X_LOW: + return "xLow"; + case dh.plot.SourceType.X_HIGH: + return "xHigh"; + case dh.plot.SourceType.Y_LOW: + return "yLow"; + case dh.plot.SourceType.Y_HIGH: + return "yHigh"; + case dh.plot.SourceType.TIME: + return "time"; + case dh.plot.SourceType.OPEN: + return "open"; + case dh.plot.SourceType.HIGH: + return "high"; + case dh.plot.SourceType.LOW: + return "low"; + case dh.plot.SourceType.CLOSE: + return "close"; + case dh.plot.SourceType.SHAPE: + return "shape"; + case dh.plot.SourceType.SIZE: + return "size"; + case dh.plot.SourceType.LABEL: + return "label"; + case dh.plot.SourceType.COLOR: + return "color"; + case dh.plot.SourceType.PARENT: + return "parent"; + case dh.plot.SourceType.HOVER_TEXT: + return "hovertext"; + case dh.plot.SourceType.TEXT: + return "text"; + default: + throw new Error("Unrecognized source type: ".concat(sourceType)); + } + } + getPlotlySeriesOrientation(series) { + var _sources$, _sources$$axis; + var { + dh + } = this; + var { + sources + } = series; + if (sources.length === 2 && ((_sources$ = sources[0]) === null || _sources$ === void 0 ? void 0 : (_sources$$axis = _sources$.axis) === null || _sources$$axis === void 0 ? void 0 : _sources$$axis.type) === dh.plot.AxisType.Y) { + return ChartUtils.ORIENTATION.HORIZONTAL; + } + return ChartUtils.ORIENTATION.VERTICAL; + } + /** + * Create a data series (trace) for use with plotly + * @param series The series to create the series data with + * @param axisTypeMap The map of axes grouped by type + * @param seriesVisibility Visibility setting for the series + * @returns The series data (trace) object for use with plotly. + */ + makeSeriesDataFromSeries(series, axisTypeMap, seriesVisibility) { + var showLegend = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; + var allowWebGL = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true; + var { + name, + isLinesVisible, + isShapesVisible, + plotStyle, + lineColor, + shapeColor, + sources, + shape, + shapeSize + } = series; + var isBusinessTime = sources.some((source) => { + var _source$axis; + return (_source$axis = source.axis) === null || _source$axis === void 0 ? void 0 : _source$axis.businessCalendar; + }); + var type = this.getChartType(plotStyle, isBusinessTime, allowWebGL); + var mode = this.getPlotlyChartMode(plotStyle, isLinesVisible !== null && isLinesVisible !== void 0 ? isLinesVisible : void 0, isShapesVisible !== null && isShapesVisible !== void 0 ? isShapesVisible : void 0); + var orientation = this.getPlotlySeriesOrientation(series); + var seriesData = ChartUtils.makeSeriesData(type, mode, name, showLegend, orientation); + this.addSourcesToSeriesData(seriesData, plotStyle, sources, axisTypeMap); + this.addStylingToSeriesData(seriesData, plotStyle, lineColor, shapeColor, shape, shapeSize, seriesVisibility); + return seriesData; + } + addSourcesToSeriesData(seriesDataParam, plotStyle, sources, axisTypeMap) { + var seriesData = seriesDataParam; + for (var k = 0; k < sources.length; k += 1) { + var source = sources[k]; + var { + axis: _axis2, + type: sourceType + } = source; + var dataAttributeName = this.getPlotlyProperty(plotStyle, sourceType); + lodashExports.set(seriesData, dataAttributeName, []); + var axisProperty = _axis2 != null ? this.getAxisPropertyName(_axis2.type) : null; + if (axisProperty != null) { + var axes = axisTypeMap.get(_axis2.type); + if (axes) { + var axisIndex = axes.indexOf(_axis2); + var axisIndexString = axisIndex > 0 ? "".concat(axisIndex + 1) : ""; + seriesData["".concat(axisProperty, "axis")] = "".concat(axisProperty).concat(axisIndexString); + } + } + } + } + addStylingToSeriesData(seriesDataParam, plotStyle) { + var lineColor = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null; + var shapeColor = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; + var shape = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : null; + var shapeSize = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : null; + var seriesVisibility = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : null; + var { + dh + } = this; + var seriesData = seriesDataParam; + seriesData.marker = { + line: {} + }; + seriesData.line = { + width: 1 + // default line width for lines, should eventually be able to override + }; + if (plotStyle === dh.plot.SeriesPlotStyle.AREA) { + seriesData.fill = "tozeroy"; + } else if (plotStyle === dh.plot.SeriesPlotStyle.STACKED_AREA) { + seriesData.stackgroup = "stack"; + } else if (plotStyle === dh.plot.SeriesPlotStyle.STEP) { + seriesData.line.shape = "hv"; + } else if (plotStyle === dh.plot.SeriesPlotStyle.HISTOGRAM) { + seriesData.width = []; + } else if (plotStyle === dh.plot.SeriesPlotStyle.PIE) { + seriesData.textinfo = "label+percent"; + } else if (plotStyle === dh.plot.SeriesPlotStyle.TREEMAP) { + seriesData.hoverinfo = "text"; + seriesData.textinfo = "label+text"; + seriesData.tiling = { + packing: "squarify", + pad: 0 + }; + seriesData.textposition = "middle center"; + } + if (lineColor != null) { + if (plotStyle === dh.plot.SeriesPlotStyle.BAR) { + seriesData.marker.color = lineColor; + } else { + seriesData.line.color = lineColor; + } + } + if (shapeColor != null) { + seriesData.marker.color = shapeColor; + } + if (shape != null && shape.length > 0) { + try { + seriesData.marker.symbol = ChartUtils.getMarkerSymbol(shape); + } catch (e) { + log$2.warn("Unable to handle shape", shape, ":", e); + } + } + if (shapeSize != null) { + seriesData.marker.size = shapeSize * ChartUtils.DEFAULT_MARKER_SIZE; + } + if (seriesVisibility != null && plotStyle !== dh.plot.SeriesPlotStyle.PIE) { + seriesData.visible = seriesVisibility; + } + } + getChartType(plotStyle, isBusinessTime) { + var allowWebGL = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; + var { + dh + } = this; + switch (plotStyle) { + case dh.plot.SeriesPlotStyle.HISTOGRAM: + return "bar"; + default: + return this.getPlotlyChartType(plotStyle, isBusinessTime, allowWebGL); + } + } + /** + * Return the plotly axis property name + * @param axisType The axis type to get the property name for + */ + getAxisPropertyName(axisType) { + var { + dh + } = this; + switch (axisType) { + case dh.plot.AxisType.X: + return "x"; + case dh.plot.AxisType.Y: + return "y"; + default: + return null; + } + } + /** + * Returns the plotly "side" value for the provided axis position + * @param axisPosition The Iris AxisPosition of the axis + */ + getAxisSide(axisPosition) { + var { + dh + } = this; + switch (axisPosition) { + case dh.plot.AxisPosition.BOTTOM: + return "bottom"; + case dh.plot.AxisPosition.TOP: + return "top"; + case dh.plot.AxisPosition.LEFT: + return "left"; + case dh.plot.AxisPosition.RIGHT: + return "right"; + default: + return void 0; + } + } + /** + * Update the layout with all the axes information for the provided figure + * @param figure Figure to update the axes for + * @param layoutParam Layout object to update in place + * @param chartAxisRangeParser Function to retrieve the axis range parser + * @param plotWidth Width of the plot in pixels + * @param plotHeight Height of the plot in pixels + */ + updateFigureAxes(layoutParam, figure, chartAxisRangeParser) { + var plotWidth = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; + var plotHeight = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0; + var layout = layoutParam; + var figureAxes = ChartUtils.getAllAxes(figure); + for (var i = 0; i < figure.charts.length; i += 1) { + var _chart3 = figure.charts[i]; + var axisRangeParser = chartAxisRangeParser === null || chartAxisRangeParser === void 0 ? void 0 : chartAxisRangeParser(_chart3); + var bounds = this.getChartBounds(figure, _chart3, plotWidth, plotHeight); + this.updateLayoutAxes(layout, _chart3.axes, figureAxes, plotWidth, plotHeight, bounds, axisRangeParser); + } + this.removeStaleAxes(layout, figureAxes); + } + getChartBounds(figure, chart, plotWidth, plotHeight) { + var _axisPositionMap$get; + var { + dh + } = this; + var { + cols, + rows + } = figure; + var { + column, + colspan, + row, + rowspan + } = chart; + var endColumn = column + colspan; + var endRow = row + rowspan; + var columnSize = 1 / cols; + var rowSize = 1 / rows; + var xMarginSize = ChartUtils.AXIS_SIZE_PX / plotWidth; + var yMarginSize = ChartUtils.AXIS_SIZE_PX / plotHeight; + var bounds = { + // Need to invert the row positioning so the first one defined shows up on top instead of the bottom, since coordinates start in bottom left + bottom: (rows - endRow) * rowSize + (endRow < rows ? yMarginSize / 2 : 0), + top: (rows - row) * rowSize - (row > 0 ? yMarginSize / 2 : 0), + left: column * columnSize + (column > 0 ? xMarginSize / 2 : 0), + right: endColumn * columnSize - (endColumn < cols ? xMarginSize / 2 : 0) + }; + var axisPositionMap = ChartUtils.groupArray(chart.axes, "position"); + var rightAxes = (_axisPositionMap$get = axisPositionMap.get(dh.plot.AxisPosition.RIGHT)) !== null && _axisPositionMap$get !== void 0 ? _axisPositionMap$get : []; + if (rightAxes.length > 0) { + if (plotWidth > 0) { + bounds.right -= (bounds.right - bounds.left) * Math.max(0, Math.min(ChartUtils.LEGEND_WIDTH_PX / plotWidth, ChartUtils.MAX_LEGEND_SIZE)); + } else { + bounds.right -= (bounds.right - bounds.left) * ChartUtils.DEFAULT_AXIS_SIZE; + } + } + return bounds; + } + getPlotlyDateFormat(formatter, columnType, formatPattern) { + var { + dh + } = this; + var tickformat = formatPattern == null ? void 0 : formatPattern.replace("%", "%%").replace(/S{9}/g, "%9f").replace(/S{8}/g, "%8f").replace(/S{7}/g, "%7f").replace(/S{6}/g, "%6f").replace(/S{5}/g, "%5f").replace(/S{4}/g, "%4f").replace(/S{3}/g, "%3f").replace(/S{2}/g, "%2f").replace(/S{1}/g, "%1f").replace(/y{4}/g, "%Y").replace(/y{2}/g, "%y").replace(/M{4}/g, "%B").replace(/M{3}/g, "%b").replace(/M{2}/g, "%m").replace(/M{1}/g, "%-m").replace(/E{4,}/g, "%A").replace(/E{1,}/g, "%a").replace(/d{2}/g, "%d").replace(/([^%]|^)d{1}/g, "$1%-d").replace(/H{2}/g, "%H").replace(/h{2}/g, "%I").replace(/h{1}/g, "%-I").replace(/m{2}/g, "%M").replace(/s{2}/g, "%S").replace("'T'", "T").replace(" z", ""); + var ticksuffix; + var dataFormatter = formatter === null || formatter === void 0 ? void 0 : formatter.getColumnTypeFormatter(columnType); + if (dataFormatter != null && isDateTimeColumnFormatter(dataFormatter) && dataFormatter.dhTimeZone != null && dataFormatter.showTimeZone) { + ticksuffix = dh.i18n.DateTimeFormat.format(" z", /* @__PURE__ */ new Date(), dataFormatter.dhTimeZone); + } + return { + tickformat, + ticksuffix, + automargin: true + }; + } + /** + * Gets the plotly axis formatting information from the source passed in + * @param source The Source to get the formatter information from + * @param formatter The current formatter for formatting data + */ + getPlotlyAxisFormat(source) { + var formatter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null; + var { + dh + } = this; + var { + axis, + columnType + } = source; + var { + formatPattern + } = axis; + var axisFormat = null; + if (TableUtils.isDateType(columnType)) { + axisFormat = this.getPlotlyDateFormat(formatter, columnType, formatPattern); + axisFormat = ChartUtils.addTickSpacing(axisFormat, axis, true); + } else if (TableUtils.isNumberType(columnType)) { + axisFormat = ChartUtils.getPlotlyNumberFormat(formatter, columnType, formatPattern); + axisFormat = ChartUtils.addTickSpacing(axisFormat, axis, false); + } + if (axis.formatType === dh.plot.AxisFormatType.CATEGORY) { + if (axisFormat) { + axisFormat.type = "category"; + } else { + axisFormat = { + type: "category", + tickformat: void 0, + ticksuffix: void 0 + }; + } + } + return axisFormat; + } + /** + * Updates the axes positions and sizes in the layout object provided. + * If the axis did not exist in the layout previously, it is created and added. + * Any axis that no longer exists in axes is removed. + * With Downsampling enabled, will also update the range on the axis itself as appropriate + * @param layoutParam The layout object to update + * @param chartAxes The chart axes to update the layout with + * @param figureAxes All figure axes to update the layout with + * @param plotWidth The width of the plot to calculate the axis sizes for + * @param plotHeight The height of the plot to calculate the axis sizes for + * @param bounds The bounds for this set of axes + * @param axisRangeParser A function to retrieve the range parser for a given axis + */ + updateLayoutAxes(layoutParam, chartAxes, figureAxes) { + var plotWidth = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; + var plotHeight = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0; + var bounds = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : { + left: 0, + top: 0, + right: 1, + bottom: 1 + }; + var axisRangeParser = arguments.length > 6 ? arguments[6] : void 0; + var { + dh + } = this; + var xAxisSize = plotWidth > 0 ? Math.max(ChartUtils.MIN_AXIS_SIZE, Math.min(ChartUtils.AXIS_SIZE_PX / plotHeight, ChartUtils.MAX_AXIS_SIZE)) : ChartUtils.DEFAULT_AXIS_SIZE; + var yAxisSize = plotHeight > 0 ? Math.max(ChartUtils.MIN_AXIS_SIZE, Math.min(ChartUtils.AXIS_SIZE_PX / plotWidth, ChartUtils.MAX_AXIS_SIZE)) : ChartUtils.DEFAULT_AXIS_SIZE; + var layout = layoutParam; + var axisPositionMap = ChartUtils.groupArray(chartAxes, "position"); + var axisTypeMap = ChartUtils.groupArray(chartAxes, "type"); + var axisTypes = [...axisTypeMap.keys()]; + var figureAxisTypeMap = ChartUtils.groupArray(figureAxes, "type"); + for (var j = 0; j < axisTypes.length; j += 1) { + var axisType = axisTypes[j]; + var axisProperty = this.getAxisPropertyName(axisType); + if (axisProperty != null) { + var typeAxes = axisTypeMap.get(axisType); + var figureTypeAxes = figureAxisTypeMap.get(axisType); + var isYAxis = axisType === dh.plot.AxisType.Y; + var plotSize = isYAxis ? plotHeight : plotWidth; + assertNotNull(typeAxes); + assertNotNull(figureTypeAxes); + for (var chartAxisIndex = 0; chartAxisIndex < typeAxes.length; chartAxisIndex += 1) { + var _axis3 = typeAxes[chartAxisIndex]; + var figureAxisIndex = figureTypeAxes.indexOf(_axis3); + var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, figureAxisIndex); + if (layout[axisLayoutProperty] == null) { + layout[axisLayoutProperty] = {}; + } + var layoutAxis = layout[axisLayoutProperty]; + if (layoutAxis != null) { + this.updateLayoutAxis(layoutAxis, _axis3, chartAxisIndex, axisPositionMap, xAxisSize, yAxisSize, bounds); + var { + range: _range, + autorange + } = layoutAxis; + if (axisRangeParser != null && _range !== void 0 && (autorange === void 0 || autorange === false)) { + var rangeParser = axisRangeParser(_axis3); + var [rangeStart, rangeEnd] = rangeParser(_range); + log$2.debug("Setting downsample range", plotSize, rangeStart, rangeEnd); + _axis3.range(plotSize, rangeStart, rangeEnd); + } else { + _axis3.range(plotSize); + } + } + } + } + } + } + /** + * Remove any axes from the layout param that no longer belong to any series + * @param layoutParam Layout object to remove stale axes from + * @param axes All axes in the figure + */ + removeStaleAxes(layoutParam, axes) { + var layout = layoutParam; + var figureAxisTypeMap = ChartUtils.groupArray(axes, "type"); + var figureAxisTypes = [...figureAxisTypeMap.keys()]; + for (var i = 0; i < figureAxisTypes.length; i += 1) { + var axisType = figureAxisTypes[i]; + var typeAxes = figureAxisTypeMap.get(axisType); + assertNotNull(typeAxes); + var axisIndex = typeAxes.length; + var axisProperty = this.getAxisPropertyName(axisType); + if (axisProperty != null) { + var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); + while (layout[axisLayoutProperty] != null) { + delete layout[axisLayoutProperty]; + axisIndex += 1; + axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); + } + } + } + } + /** + * Updates the layout axis object in place + * @param layoutAxisParam The plotly layout axis param + * @param axis The Iris Axis to update the plotly layout with + * @param axisIndex The type index for this axis + * @param axisPositionMap All the axes mapped by position + * @param axisSize The size of each axis in percent + * @param bounds The bounds of the axes domains + */ + updateLayoutAxis(layoutAxisParam, axis, axisIndex, axisPositionMap, xAxisSize, yAxisSize, bounds) { + var _axis$label; + var { + dh + } = this; + var isYAxis = axis.type === dh.plot.AxisType.Y; + var axisSize = isYAxis ? yAxisSize : xAxisSize; + var layoutAxis = layoutAxisParam; + var label = (_axis$label = axis.label) !== null && _axis$label !== void 0 ? _axis$label : ""; + if (layoutAxis.title !== void 0 && typeof layoutAxis.title !== "string") { + layoutAxis.title.text = label; + } else { + layoutAxis.title = { + text: label + }; + } + if (axis.log) { + layoutAxis.type = "log"; + } + layoutAxis.side = this.getAxisSide(axis.position); + if (axisIndex > 0) { + var _this$getAxisProperty, _axisPositionMap$get2; + layoutAxis.overlaying = (_this$getAxisProperty = this.getAxisPropertyName(axis.type)) !== null && _this$getAxisProperty !== void 0 ? _this$getAxisProperty : void 0; + var positionAxes = (_axisPositionMap$get2 = axisPositionMap.get(axis.position)) !== null && _axisPositionMap$get2 !== void 0 ? _axisPositionMap$get2 : []; + var sideIndex = positionAxes.indexOf(axis); + if (sideIndex > 0) { + layoutAxis.anchor = "free"; + if (axis.position === dh.plot.AxisPosition.RIGHT) { + layoutAxis.position = bounds.right + (sideIndex - positionAxes.length + 1) * axisSize; + } else if (axis.position === dh.plot.AxisPosition.TOP) { + layoutAxis.position = bounds.top + (sideIndex - positionAxes.length + 1) * axisSize; + } else if (axis.position === dh.plot.AxisPosition.BOTTOM) { + layoutAxis.position = bounds.bottom + (positionAxes.length - sideIndex + 1) * axisSize; + } else if (axis.position === dh.plot.AxisPosition.LEFT) { + layoutAxis.position = bounds.left + (positionAxes.length - sideIndex + 1) * axisSize; + } + } + } else if (axis.type === dh.plot.AxisType.X) { + var leftAxes = axisPositionMap.get(dh.plot.AxisPosition.LEFT) || []; + var rightAxes = axisPositionMap.get(dh.plot.AxisPosition.RIGHT) || []; + var left = Math.max(bounds.left, bounds.left + (leftAxes.length - 1) * yAxisSize); + var right = Math.min(bounds.right - (rightAxes.length - 1) * yAxisSize, bounds.right); + layoutAxis.domain = [left, right]; + } else if (axis.type === dh.plot.AxisType.Y) { + var bottomAxes = axisPositionMap.get(dh.plot.AxisPosition.BOTTOM) || []; + var topAxes = axisPositionMap.get(dh.plot.AxisPosition.TOP) || []; + var bottom = Math.max(bounds.bottom, bounds.bottom + (bottomAxes.length - 1) * xAxisSize); + var top = Math.min(bounds.top - (topAxes.length - 1) * xAxisSize, bounds.top); + layoutAxis.domain = [bottom, top]; + } + var { + minRange, + maxRange, + log: logAxis + } = axis; + if (!Number.isNaN(minRange) || !Number.isNaN(maxRange)) { + layoutAxis.autorangeoptions = {}; + if (!Number.isNaN(minRange)) { + layoutAxis.autorangeoptions.minallowed = logAxis ? Math.log10(minRange) : minRange; + } + if (!Number.isNaN(maxRange)) { + layoutAxis.autorangeoptions.maxallowed = logAxis ? Math.log10(maxRange) : maxRange; + } + } + } + /** + * Creates the bounds for the periods specified. + * For example, if you pass in [['09:00', '17:00']], it will return [17, 9] (closing at 5pm, opening at 9am the next day) + * If you pass [['09:00', '12:00'], ['13:00', '17:00']], it will return [12, 13] (closing at noon, opening at 1pm) and [17, 9] (closing at 5pm, opening at 9am the next day) + * @param periods Periods to map + * @param timeZoneDiff Time zone difference in hours + * @returns Bounds for the periods in plotly format + */ + // eslint-disable-next-line class-methods-use-this + createBoundsFromPeriods(periods) { + var timeZoneDiff = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; + if (periods.length === 0) { + return []; + } + var numberPeriods = periods.map((period2) => [(ChartUtils.periodToDecimal(period2.open) + timeZoneDiff) % 24, (ChartUtils.periodToDecimal(period2.close) + timeZoneDiff) % 24]).sort((a, b) => a[0] - b[0]); + var bounds = []; + for (var i = 0; i < numberPeriods.length; i += 1) { + var period = numberPeriods[i]; + var nextPeriod = numberPeriods[(i + 1) % numberPeriods.length]; + bounds.push([period[1], nextPeriod[0]]); + } + return bounds; + } + /** + * Creates range breaks for plotly from business periods. + * @param periods Business periods to create the breaks for + * @param timeZoneDiff Time zone difference in hours + * @returns Plotly range breaks for the business periods + */ + createBreaksFromPeriods(periods) { + var timeZoneDiff = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; + var bounds = this.createBoundsFromPeriods(periods, timeZoneDiff); + return bounds.map((bound) => ({ + pattern: "hour", + bounds: bound + })); + } + /** + * Creates range break bounds for plotly from business days. + * For example a standard business week of ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY'] + * will result in [[6,1]] meaning close on Saturday and open on Monday. + * If you remove Wednesday from the array, then you get two closures [[6, 1], [3, 4]] + * + * @param businessDays the days to display on the x-axis + */ + createBoundsFromDays(businessDays) { + var weekLength = this.daysOfWeek.length; + if (businessDays.length === weekLength) { + return []; + } + var businessDaysInt = businessDays.map((day) => this.daysOfWeek.indexOf(day)); + var businessDaysSet = new Set(businessDaysInt); + var closedDays = /* @__PURE__ */ new Set(); + for (var i = 0; i < weekLength; i += 1) { + if (!businessDaysSet.has(i) && businessDaysSet.has((i - 1 + weekLength) % weekLength)) { + closedDays.add(i); + } + } + var boundsArray = []; + closedDays.forEach((closedDay) => { + for (var _i = 0; _i < weekLength; _i += 1) { + var adjustedDay = (closedDay + _i) % weekLength; + if (businessDaysSet.has(adjustedDay)) { + boundsArray.push([closedDay, adjustedDay]); + return; + } + } + throw new Error("Unable to find open day for closed day ".concat(closedDay, ", businessDays: ").concat(businessDays)); + }); + return boundsArray; + } + /** + * Breaks in plotly for business days + * @param businessDays Business days to create the breaks for + * @returns Plotly range breaks for the business days + */ + createBreaksFromDays(businessDays) { + var bounds = this.createBoundsFromDays(businessDays); + return bounds.map((bound) => ({ + pattern: "day of week", + bounds: bound + })); + } + /** + * Creates range breaks for plotly from a business calendar. + * @param businessCalendar Calendar to create the breaks from + * @param formatter Formatter to use for time zones + * @returns Plotly Rangebreaks for the business calendar + */ + createRangeBreaksFromBusinessCalendar(businessCalendar, formatter) { + var rangebreaks = []; + var { + businessPeriods, + businessDays, + holidays, + timeZone: calendarTimeZone + } = businessCalendar; + var typeFormatter = formatter === null || formatter === void 0 ? void 0 : formatter.getColumnTypeFormatter(BUSINESS_COLUMN_TYPE); + var formatterTimeZone; + if (isDateTimeColumnFormatter(typeFormatter)) { + formatterTimeZone = typeFormatter.dhTimeZone; + } + var timeZoneDiff = ChartUtils.getTimeZoneDiff(calendarTimeZone, formatterTimeZone); + if (holidays.length > 0) { + rangebreaks.push(...this.createRangeBreakValuesFromHolidays(holidays, calendarTimeZone, formatterTimeZone, businessCalendar)); + } + rangebreaks.push(...this.createBreaksFromPeriods(businessPeriods, timeZoneDiff)); + rangebreaks.push(...this.createBreaksFromDays(businessDays)); + return rangebreaks; + } + /** + * Creates an array of range breaks for all holidays. + * + * @param holidays an array of holidays + * @param calendarTimeZone the time zone for the business calendar + * @param formatterTimeZone the time zone for the formatter + * @param calendar the calendar the holidays are from + */ + createRangeBreakValuesFromHolidays(holidays, calendarTimeZone, formatterTimeZone, calendar) { + var fullHolidays = []; + var partialHolidays = []; + holidays.forEach((holiday) => { + if (holiday.businessPeriods.length > 0) { + partialHolidays.push(...this.createPartialHoliday(holiday, calendarTimeZone, formatterTimeZone, calendar)); + } else { + fullHolidays.push(this.createFullHoliday(holiday, calendarTimeZone, formatterTimeZone)); + } + }); + return [{ + values: fullHolidays + }, ...partialHolidays]; + } + /** + * Creates the range break value for a full holiday. A full holiday is day that has no business periods. + * + * @param holiday the full holiday + * @param calendarTimeZone the time zone for the business calendar + * @param formatterTimeZone the time zone for the formatter + */ + createFullHoliday(holiday, calendarTimeZone, formatterTimeZone) { + return this.adjustDateForTimeZone("".concat(holiday.date.toString(), " 00:00:00.000000"), calendarTimeZone, formatterTimeZone); + } + /** + * Creates the range break for a partial holiday. A partial holiday is holiday with business periods + * that are different than the default business periods. + * + * @param holiday the partial holiday + * @param calendarTimeZone the time zone for the business calendar + * @param formatterTimeZone the time zone for the formatter + * @param calendar the calendar the holiday is from. Used to check against the default business periods to ensure this holiday needs to be specified + * + * @returns an array of range breaks for the partial holiday + */ + createPartialHoliday(holiday, calendarTimeZone, formatterTimeZone, calendar) { + var _calendar$businessPer; + if (holiday.businessPeriods.length === 0) { + return []; + } + var dateString = holiday.date.toString(); + if (calendar) { + var dayOfWeek = new Date(dateString).getDay(); + var isBusinessDay = calendar.businessDays.includes(this.daysOfWeek[dayOfWeek]); + if (!isBusinessDay) { + return []; + } + } + var closedPeriods = ChartUtils.createClosedRangesForPartialHoliday(holiday.businessPeriods, (_calendar$businessPer = calendar === null || calendar === void 0 ? void 0 : calendar.businessPeriods) !== null && _calendar$businessPer !== void 0 ? _calendar$businessPer : []); + var rangeBreaks = []; + for (var i = 0; i < closedPeriods.length; i += 1) { + var [closeStart, closeEnd] = closedPeriods[i]; + if (closeStart !== closeEnd) { + var values = [this.adjustDateForTimeZone("".concat(dateString, " ").concat(ChartUtils.decimalToPeriod(closeStart), ":00.000000"), calendarTimeZone, formatterTimeZone)]; + var dvalue = MILLIS_PER_HOUR * (closeEnd - closeStart); + rangeBreaks.push({ + values, + dvalue + }); + } + } + return rangeBreaks; + } + /** + * Adjusts a date string from the calendar time zone to the formatter time zone. + * + * @param dateString the date string + * @param calendarTimeZone the time zone for the business calendar + * @param formatterTimeZone the time zone for the formatter + */ + adjustDateForTimeZone(dateString, calendarTimeZone, formatterTimeZone) { + if (formatterTimeZone && formatterTimeZone.standardOffset !== calendarTimeZone.standardOffset) { + return this.unwrapValue(this.wrapValue(dateString, BUSINESS_COLUMN_TYPE, calendarTimeZone), formatterTimeZone); + } + return dateString; + } + /** + * Creates the Figure settings from the Chart Builder settings + * This should be deprecated at some point, and have Chart Builder create the figure settings directly. + * This logic will still need to exist to translate existing charts, but could be part of a migration script + * to translate the data. + * Change when we decide to add more functionality to the Chart Builder. + * @param settings The chart builder settings + * @param settings.title The title for this figure + * @param settings.xAxis The name of the column to use for the x-axis + * @param settings.series The name of the columns to use for the series of this figure + * @param settings.type The plot style for this figure + */ + makeFigureSettings(settings, table) { + var { + dh + } = this; + var { + series, + xAxis: settingsAxis, + type + } = settings; + var title = ChartUtils.titleFromSettings(settings); + var xAxis = { + formatType: "".concat(dh.plot.AxisFormatType.NUMBER), + type: "".concat(dh.plot.AxisType.X), + position: "".concat(dh.plot.AxisPosition.BOTTOM) + }; + var yAxis = { + formatType: "".concat(dh.plot.AxisFormatType.NUMBER), + type: "".concat(dh.plot.AxisType.Y), + position: "".concat(dh.plot.AxisPosition.LEFT) + }; + return { + charts: [{ + chartType: "".concat(dh.plot.ChartType.XY), + axes: [xAxis, yAxis], + series: (series !== null && series !== void 0 ? series : []).map((name) => ({ + plotStyle: "".concat(type), + name, + dataSources: [{ + type: "".concat(dh.plot.SourceType.X), + columnName: settingsAxis !== null && settingsAxis !== void 0 ? settingsAxis : "", + axis: xAxis, + table + }, { + type: "".concat(dh.plot.SourceType.Y), + columnName: name, + axis: yAxis, + table + }] + })) + }], + title + }; + } + /** + * Unwraps a value provided from API to a value plotly can understand + * Eg. Unwraps DateWrapper, LongWrapper objects. + */ + unwrapValue(value2, timeZone) { + var { + dh + } = this; + if (value2 != null) { + if (isDateWrapper(value2)) { + return dh.i18n.DateTimeFormat.format(ChartUtils.DATE_FORMAT, value2, timeZone); + } + if (isLongWrapper(value2)) { + return value2.asNumber(); + } + } + return value2; + } + /** + * + * @param value The value to wrap up + * @param columnType The type of column this value is from + * @param timeZone The time zone if applicable + */ + wrapValue(value2, columnType) { + var timeZone = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null; + var { + dh + } = this; + if (TableUtils.isDateType(columnType) && typeof value2 === "string") { + var text = value2; + var format = ChartUtils.DATE_FORMAT.substr(0, value2.length); + var date = dh.i18n.DateTimeFormat.parse(format, text); + if (!timeZone) { + return date; + } + var tzFormat = "".concat(format, " Z"); + var estimatedOffset = dh.i18n.DateTimeFormat.format("Z", date, timeZone); + var estimatedDate = dh.i18n.DateTimeFormat.parse(tzFormat, "".concat(text, " ").concat(estimatedOffset)); + var offset = dh.i18n.DateTimeFormat.format("Z", estimatedDate, timeZone); + return dh.i18n.DateTimeFormat.parse(tzFormat, "".concat(text, " ").concat(offset)); + } + return value2; + } + makeLayoutAxis(type, theme) { + var { + dh + } = this; + var axis = { + automargin: true, + gridcolor: theme.gridcolor, + linecolor: theme.linecolor, + rangeslider: { + visible: false + }, + showline: true, + ticks: "outside", + ticklen: 5, + // act as padding, can't find a tick padding + tickcolor: theme.paper_bgcolor, + // hide ticks as padding + tickfont: { + color: theme.zerolinecolor + }, + title: { + font: { + color: theme.title_color + } + }, + legend: { + font: { + color: theme.legend_color + } + } + }; + if (type === dh.plot.AxisType.X) { + Object.assign(axis, { + showgrid: true + }); + } else if (type === dh.plot.AxisType.Y) { + Object.assign(axis, { + zerolinecolor: theme.zerolinecolor, + zerolinewidth: 2 + }); + } + return axis; + } + /** + * Creates a plotly layout template object based on a given theme. + * See https://plotly.com/javascript/reference/layout/#layout-template + * @param theme The theme to use for the layout template + * @returns The layout template object + */ + makeDefaultTemplate(theme) { + var { + error_band_line_color, + ohlc_increasing, + ohlc_decreasing, + title_color, + indicator_increasing, + indicator_decreasing, + indicator_gauge + } = theme; + return { + data: { + bar: [{ + marker: { + line: { + color: "transparent" + } + } + }], + scatter: [{ + error_x: { + color: error_band_line_color + }, + error_y: { + color: error_band_line_color + } + }], + ohlc: [{ + increasing: { + line: { + color: ohlc_increasing + } + }, + decreasing: { + line: { + color: ohlc_decreasing + } + } + }], + pie: [{ + outsidetextfont: { + color: title_color + } + }], + treemap: [{ + outsidetextfont: { + color: title_color + } + }], + indicator: [{ + title: { + font: { + color: title_color + } + }, + delta: { + decreasing: { + color: indicator_decreasing + }, + increasing: { + color: indicator_increasing + } + }, + gauge: { + bar: { + color: indicator_gauge + } + } + }] + }, + /* eslint-enable camelcase */ + layout: this.makeDefaultLayout(theme) + }; + } + /** + * Creates a plotly layout object based on a given theme. + * See https://plotly.com/javascript/reference/layout/ + * @param theme The theme to use for the layout + */ + makeDefaultLayout(theme) { + var { + dh + } = this; + var { + /* Used as top level properties of `Layout` */ + /* eslint-disable camelcase */ + paper_bgcolor, + plot_bgcolor, + title_color, + coastline_color, + land_color, + ocean_color, + lake_color, + river_color + /* eslint-disable camelcase */ + } = theme; + var layout = { + paper_bgcolor, + plot_bgcolor, + autosize: true, + colorway: ChartUtils.normalizeColorway(theme === null || theme === void 0 ? void 0 : theme.colorway), + font: { + family: "'Fira Sans', sans-serif", + color: title_color + }, + title: { + font: { + color: title_color + }, + xanchor: "center", + xref: "paper", + yanchor: "top", + pad: _objectSpread$1({}, ChartUtils.DEFAULT_TITLE_PADDING), + y: 1 + }, + legend: { + font: { + color: title_color + } + }, + margin: _objectSpread$1({}, ChartUtils.DEFAULT_MARGIN), + xaxis: this.makeLayoutAxis(dh.plot.AxisType.X, theme), + yaxis: this.makeLayoutAxis(dh.plot.AxisType.Y, theme), + polar: { + angularaxis: this.makeLayoutAxis(dh.plot.AxisType.SHAPE, theme), + radialaxis: this.makeLayoutAxis(dh.plot.AxisType.SHAPE, theme), + bgcolor: theme.plot_bgcolor + }, + scene: { + xaxis: this.makeLayoutAxis(dh.plot.AxisType.X, theme), + yaxis: this.makeLayoutAxis(dh.plot.AxisType.Y, theme), + zaxis: this.makeLayoutAxis(null, theme) + }, + geo: { + showcoastlines: true, + showframe: false, + showland: true, + showocean: true, + showlakes: true, + showrivers: true, + bgcolor: paper_bgcolor, + coastlinecolor: coastline_color, + landcolor: land_color, + oceancolor: ocean_color, + lakecolor: lake_color, + rivercolor: river_color + } + }; + layout.datarevision = 0; + return layout; + } + /** + * Hydrate settings from a JSONable object + * @param settings Dehydrated settings + */ + hydrateSettings(settings) { + var { + dh + } = this; + return _objectSpread$1(_objectSpread$1({}, settings), {}, { + type: settings.type != null ? dh.plot.SeriesPlotStyle[settings.type] : void 0 + }); + } +} +_defineProperty$2(ChartUtils, "DEFAULT_AXIS_SIZE", 0.15); +_defineProperty$2(ChartUtils, "MIN_AXIS_SIZE", 0.025); +_defineProperty$2(ChartUtils, "MAX_AXIS_SIZE", 0.2); +_defineProperty$2(ChartUtils, "AXIS_SIZE_PX", 75); +_defineProperty$2(ChartUtils, "LEGEND_WIDTH_PX", 50); +_defineProperty$2(ChartUtils, "MAX_LEGEND_SIZE", 0.25); +_defineProperty$2(ChartUtils, "ORIENTATION", Object.freeze({ + HORIZONTAL: "h", + VERTICAL: "v" +})); +_defineProperty$2(ChartUtils, "DATE_FORMAT", "yyyy-MM-dd HH:mm:ss.SSSSSS"); +_defineProperty$2(ChartUtils, "DEFAULT_MARGIN", Object.freeze({ + l: 60, + r: 50, + t: 30, + b: 60, + pad: 0 +})); +_defineProperty$2(ChartUtils, "DEFAULT_TITLE_PADDING", Object.freeze({ + t: 8 +})); +_defineProperty$2(ChartUtils, "SUBTITLE_LINE_HEIGHT", 25); +_defineProperty$2(ChartUtils, "DEFAULT_MARKER_SIZE", 6); +_defineProperty$2(ChartUtils, "MODE_MARKERS", "markers"); +_defineProperty$2(ChartUtils, "MODE_LINES", "lines"); +var noop = function() { +}; +var _undefined$1 = noop(); +var isValue$6 = function(val) { + return val !== _undefined$1 && val !== null; +}; +var isValue$5 = isValue$6; +var forEach$2 = Array.prototype.forEach, create$1 = Object.create; +var process$1 = function(src, obj) { + var key; + for (key in src) obj[key] = src[key]; +}; +var normalizeOptions = function(opts1) { + var result = create$1(null); + forEach$2.call(arguments, function(options) { + if (!isValue$5(options)) return; + process$1(Object(options), result); + }); + return result; +}; +var isImplemented$7 = function() { + var sign2 = Math.sign; + if (typeof sign2 !== "function") return false; + return sign2(10) === 1 && sign2(-20) === -1; +}; +var shim$5; +var hasRequiredShim$5; +function requireShim$5() { + if (hasRequiredShim$5) return shim$5; + hasRequiredShim$5 = 1; + shim$5 = function(value2) { + value2 = Number(value2); + if (isNaN(value2) || value2 === 0) return value2; + return value2 > 0 ? 1 : -1; + }; + return shim$5; +} +var sign$1 = isImplemented$7() ? Math.sign : requireShim$5(); +var sign = sign$1, abs = Math.abs, floor = Math.floor; +var toInteger$1 = function(value2) { + if (isNaN(value2)) return 0; + value2 = Number(value2); + if (value2 === 0 || !isFinite(value2)) return value2; + return sign(value2) * floor(abs(value2)); +}; +var toInteger = toInteger$1, max$1 = Math.max; +var toPosInteger = function(value2) { + return max$1(0, toInteger(value2)); +}; +var toPosInt$1 = toPosInteger; +var resolveLength$2 = function(optsLength, fnLength, isAsync) { + var length; + if (isNaN(optsLength)) { + length = fnLength; + if (!(length >= 0)) return 1; + if (isAsync && length) return length - 1; + return length; + } + if (optsLength === false) return false; + return toPosInt$1(optsLength); +}; +var validCallable = function(fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; +}; +var isValue$4 = isValue$6; +var validValue = function(value2) { + if (!isValue$4(value2)) throw new TypeError("Cannot use null or undefined"); + return value2; +}; +var callable$3 = validCallable, value = validValue, bind = Function.prototype.bind, call$1 = Function.prototype.call, keys$1 = Object.keys, objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; +var _iterate = function(method, defVal) { + return function(obj, cb) { + var list, thisArg = arguments[2], compareFn = arguments[3]; + obj = Object(value(obj)); + callable$3(cb); + list = keys$1(obj); + if (compareFn) { + list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : void 0); + } + if (typeof method !== "function") method = list[method]; + return call$1.call(method, list, function(key, index) { + if (!objPropertyIsEnumerable.call(obj, key)) return defVal; + return call$1.call(cb, thisArg, obj[key], key, obj, index); + }); + }; +}; +var forEach$1 = _iterate("forEach"); +var registeredExtensions = {}; +var custom = { exports: {} }; +var isImplemented$6 = function() { + var assign2 = Object.assign, obj; + if (typeof assign2 !== "function") return false; + obj = { foo: "raz" }; + assign2(obj, { bar: "dwa" }, { trzy: "trzy" }); + return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; +}; +var isImplemented$5; +var hasRequiredIsImplemented$4; +function requireIsImplemented$4() { + if (hasRequiredIsImplemented$4) return isImplemented$5; + hasRequiredIsImplemented$4 = 1; + isImplemented$5 = function() { + try { + Object.keys("primitive"); + return true; + } catch (e) { + return false; + } + }; + return isImplemented$5; +} +var shim$4; +var hasRequiredShim$4; +function requireShim$4() { + if (hasRequiredShim$4) return shim$4; + hasRequiredShim$4 = 1; + var isValue2 = isValue$6; + var keys2 = Object.keys; + shim$4 = function(object) { + return keys2(isValue2(object) ? Object(object) : object); + }; + return shim$4; +} +var keys; +var hasRequiredKeys; +function requireKeys() { + if (hasRequiredKeys) return keys; + hasRequiredKeys = 1; + keys = requireIsImplemented$4()() ? Object.keys : requireShim$4(); + return keys; +} +var shim$3; +var hasRequiredShim$3; +function requireShim$3() { + if (hasRequiredShim$3) return shim$3; + hasRequiredShim$3 = 1; + var keys2 = requireKeys(), value2 = validValue, max2 = Math.max; + shim$3 = function(dest, src) { + var error, i, length = max2(arguments.length, 2), assign2; + dest = Object(value2(dest)); + assign2 = function(key) { + try { + dest[key] = src[key]; + } catch (e) { + if (!error) error = e; + } + }; + for (i = 1; i < length; ++i) { + src = arguments[i]; + keys2(src).forEach(assign2); + } + if (error !== void 0) throw error; + return dest; + }; + return shim$3; +} +var assign$1 = isImplemented$6() ? Object.assign : requireShim$3(); +var isValue$3 = isValue$6; +var map$1 = { function: true, object: true }; +var isObject$1 = function(value2) { + return isValue$3(value2) && map$1[typeof value2] || false; +}; +(function(module2) { + var assign2 = assign$1, isObject2 = isObject$1, isValue2 = isValue$6, captureStackTrace = Error.captureStackTrace; + module2.exports = function(message) { + var err = new Error(message), code = arguments[1], ext = arguments[2]; + if (!isValue2(ext)) { + if (isObject2(code)) { + ext = code; + code = null; + } + } + if (isValue2(ext)) assign2(err, ext); + if (isValue2(code)) err.code = code; + if (captureStackTrace) captureStackTrace(err, module2.exports); + return err; + }; +})(custom); +var customExports = custom.exports; +var _defineLength = { exports: {} }; +var mixin$1; +var hasRequiredMixin; +function requireMixin() { + if (hasRequiredMixin) return mixin$1; + hasRequiredMixin = 1; + var value2 = validValue, defineProperty2 = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols2 = Object.getOwnPropertySymbols; + mixin$1 = function(target, source) { + var error, sourceObject = Object(value2(source)); + target = Object(value2(target)); + getOwnPropertyNames(sourceObject).forEach(function(name) { + try { + defineProperty2(target, name, getOwnPropertyDescriptor(source, name)); + } catch (e) { + error = e; + } + }); + if (typeof getOwnPropertySymbols2 === "function") { + getOwnPropertySymbols2(sourceObject).forEach(function(symbol) { + try { + defineProperty2(target, symbol, getOwnPropertyDescriptor(source, symbol)); + } catch (e) { + error = e; + } + }); + } + if (error !== void 0) throw error; + return target; + }; + return mixin$1; +} +var toPosInt = toPosInteger; +var test = function(arg1, arg2) { + return arg2; +}; +var desc, defineProperty, generate, mixin; +try { + Object.defineProperty(test, "length", { + configurable: true, + writable: false, + enumerable: false, + value: 1 + }); +} catch (ignore) { +} +if (test.length === 1) { + desc = { configurable: true, writable: false, enumerable: false }; + defineProperty = Object.defineProperty; + _defineLength.exports = function(fn, length) { + length = toPosInt(length); + if (fn.length === length) return fn; + desc.value = length; + return defineProperty(fn, "length", desc); + }; +} else { + mixin = requireMixin(); + generate = /* @__PURE__ */ function() { + var cache = []; + return function(length) { + var args, i = 0; + if (cache[length]) return cache[length]; + args = []; + while (length--) args.push("a" + (++i).toString(36)); + return new Function( + "fn", + "return function (" + args.join(", ") + ") { return fn.apply(this, arguments); };" + ); + }; + }(); + _defineLength.exports = function(src, length) { + var target; + length = toPosInt(length); + if (src.length === length) return src; + target = generate(length)(src); + try { + mixin(target, src); + } catch (ignore) { + } + return target; + }; +} +var _defineLengthExports = _defineLength.exports; +var d$2 = { exports: {} }; +var _undefined = void 0; +var is$4 = function(value2) { + return value2 !== _undefined && value2 !== null; +}; +var isValue$2 = is$4; +var possibleTypes = { + "object": true, + "function": true, + "undefined": true + /* document.all */ +}; +var is$3 = function(value2) { + if (!isValue$2(value2)) return false; + return hasOwnProperty.call(possibleTypes, typeof value2); +}; +var isObject = is$3; +var is$2 = function(value2) { + if (!isObject(value2)) return false; + try { + if (!value2.constructor) return false; + return value2.constructor.prototype === value2; + } catch (error) { + return false; + } +}; +var isPrototype = is$2; +var is$1 = function(value2) { + if (typeof value2 !== "function") return false; + if (!hasOwnProperty.call(value2, "length")) return false; + try { + if (typeof value2.length !== "number") return false; + if (typeof value2.call !== "function") return false; + if (typeof value2.apply !== "function") return false; + } catch (error) { + return false; + } + return !isPrototype(value2); +}; +var isFunction$1 = is$1; +var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; +var is = function(value2) { + if (!isFunction$1(value2)) return false; + if (classRe.test(functionToString.call(value2))) return false; + return true; +}; +var str = "razdwatrzy"; +var isImplemented$4 = function() { + if (typeof str.contains !== "function") return false; + return str.contains("dwa") === true && str.contains("foo") === false; +}; +var shim$2; +var hasRequiredShim$2; +function requireShim$2() { + if (hasRequiredShim$2) return shim$2; + hasRequiredShim$2 = 1; + var indexOf = String.prototype.indexOf; + shim$2 = function(searchString) { + return indexOf.call(this, searchString, arguments[1]) > -1; + }; + return shim$2; +} +var contains$1 = isImplemented$4() ? String.prototype.contains : requireShim$2(); +var isValue$1 = is$4, isPlainFunction = is, assign = assign$1, normalizeOpts$1 = normalizeOptions, contains = contains$1; +var d$1 = d$2.exports = function(dscr, value2) { + var c, e, w, options, desc2; + if (arguments.length < 2 || typeof dscr !== "string") { + options = value2; + value2 = dscr; + dscr = null; + } else { + options = arguments[2]; + } + if (isValue$1(dscr)) { + c = contains.call(dscr, "c"); + e = contains.call(dscr, "e"); + w = contains.call(dscr, "w"); + } else { + c = w = true; + e = false; + } + desc2 = { value: value2, configurable: c, enumerable: e, writable: w }; + return !options ? desc2 : assign(normalizeOpts$1(options), desc2); +}; +d$1.gs = function(dscr, get2, set) { + var c, e, options, desc2; + if (typeof dscr !== "string") { + options = set; + set = get2; + get2 = dscr; + dscr = null; + } else { + options = arguments[3]; + } + if (!isValue$1(get2)) { + get2 = void 0; + } else if (!isPlainFunction(get2)) { + options = get2; + get2 = set = void 0; + } else if (!isValue$1(set)) { + set = void 0; + } else if (!isPlainFunction(set)) { + options = set; + set = void 0; + } + if (isValue$1(dscr)) { + c = contains.call(dscr, "c"); + e = contains.call(dscr, "e"); + } else { + c = true; + e = false; + } + desc2 = { get: get2, set, configurable: c, enumerable: e }; + return !options ? desc2 : assign(normalizeOpts$1(options), desc2); +}; +var dExports = d$2.exports; +var eventEmitter = { exports: {} }; +(function(module2, exports2) { + var d2 = dExports, callable2 = validCallable, apply2 = Function.prototype.apply, call2 = Function.prototype.call, create2 = Object.create, defineProperty2 = Object.defineProperty, defineProperties2 = Object.defineProperties, hasOwnProperty2 = Object.prototype.hasOwnProperty, descriptor = { configurable: true, enumerable: false, writable: true }, on2, once, off, emit2, methods, descriptors, base; + on2 = function(type, listener) { + var data; + callable2(listener); + if (!hasOwnProperty2.call(this, "__ee__")) { + data = descriptor.value = create2(null); + defineProperty2(this, "__ee__", descriptor); + descriptor.value = null; + } else { + data = this.__ee__; + } + if (!data[type]) data[type] = listener; + else if (typeof data[type] === "object") data[type].push(listener); + else data[type] = [data[type], listener]; + return this; + }; + once = function(type, listener) { + var once2, self3; + callable2(listener); + self3 = this; + on2.call(this, type, once2 = function() { + off.call(self3, type, once2); + apply2.call(listener, this, arguments); + }); + once2.__eeOnceListener__ = listener; + return this; + }; + off = function(type, listener) { + var data, listeners, candidate, i; + callable2(listener); + if (!hasOwnProperty2.call(this, "__ee__")) return this; + data = this.__ee__; + if (!data[type]) return this; + listeners = data[type]; + if (typeof listeners === "object") { + for (i = 0; candidate = listeners[i]; ++i) { + if (candidate === listener || candidate.__eeOnceListener__ === listener) { + if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; + else listeners.splice(i, 1); + } + } + } else { + if (listeners === listener || listeners.__eeOnceListener__ === listener) { + delete data[type]; + } + } + return this; + }; + emit2 = function(type) { + var i, l, listener, listeners, args; + if (!hasOwnProperty2.call(this, "__ee__")) return; + listeners = this.__ee__[type]; + if (!listeners) return; + if (typeof listeners === "object") { + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; + listeners = listeners.slice(); + for (i = 0; listener = listeners[i]; ++i) { + apply2.call(listener, this, args); + } + } else { + switch (arguments.length) { + case 1: + call2.call(listeners, this); + break; + case 2: + call2.call(listeners, this, arguments[1]); + break; + case 3: + call2.call(listeners, this, arguments[1], arguments[2]); + break; + default: + l = arguments.length; + args = new Array(l - 1); + for (i = 1; i < l; ++i) { + args[i - 1] = arguments[i]; + } + apply2.call(listeners, this, args); + } + } + }; + methods = { + on: on2, + once, + off, + emit: emit2 + }; + descriptors = { + on: d2(on2), + once: d2(once), + off: d2(off), + emit: d2(emit2) + }; + base = defineProperties2({}, descriptors); + module2.exports = exports2 = function(o) { + return o == null ? create2(base) : defineProperties2(Object(o), descriptors); + }; + exports2.methods = methods; +})(eventEmitter, eventEmitter.exports); +var eventEmitterExports = eventEmitter.exports; +var isImplemented$3; +var hasRequiredIsImplemented$3; +function requireIsImplemented$3() { + if (hasRequiredIsImplemented$3) return isImplemented$3; + hasRequiredIsImplemented$3 = 1; + isImplemented$3 = function() { + var from2 = Array.from, arr, result; + if (typeof from2 !== "function") return false; + arr = ["raz", "dwa"]; + result = from2(arr); + return Boolean(result && result !== arr && result[1] === "dwa"); + }; + return isImplemented$3; +} +var isImplemented$2; +var hasRequiredIsImplemented$2; +function requireIsImplemented$2() { + if (hasRequiredIsImplemented$2) return isImplemented$2; + hasRequiredIsImplemented$2 = 1; + isImplemented$2 = function() { + if (typeof globalThis !== "object") return false; + if (!globalThis) return false; + return globalThis.Array === Array; + }; + return isImplemented$2; +} +var implementation; +var hasRequiredImplementation; +function requireImplementation() { + if (hasRequiredImplementation) return implementation; + hasRequiredImplementation = 1; + var naiveFallback = function() { + if (typeof self === "object" && self) return self; + if (typeof window === "object" && window) return window; + throw new Error("Unable to resolve global `this`"); + }; + implementation = function() { + if (this) return this; + try { + Object.defineProperty(Object.prototype, "__global__", { + get: function() { + return this; + }, + configurable: true + }); + } catch (error) { + return naiveFallback(); + } + try { + if (!__global__) return naiveFallback(); + return __global__; + } finally { + delete Object.prototype.__global__; + } + }(); + return implementation; +} +var globalThis_1; +var hasRequiredGlobalThis; +function requireGlobalThis() { + if (hasRequiredGlobalThis) return globalThis_1; + hasRequiredGlobalThis = 1; + globalThis_1 = requireIsImplemented$2()() ? globalThis : requireImplementation(); + return globalThis_1; +} +var isImplemented$1; +var hasRequiredIsImplemented$1; +function requireIsImplemented$1() { + if (hasRequiredIsImplemented$1) return isImplemented$1; + hasRequiredIsImplemented$1 = 1; + var global2 = requireGlobalThis(), validTypes = { object: true, symbol: true }; + isImplemented$1 = function() { + var Symbol2 = global2.Symbol; + var symbol; + if (typeof Symbol2 !== "function") return false; + symbol = Symbol2("test symbol"); + try { + String(symbol); + } catch (e) { + return false; + } + if (!validTypes[typeof Symbol2.iterator]) return false; + if (!validTypes[typeof Symbol2.toPrimitive]) return false; + if (!validTypes[typeof Symbol2.toStringTag]) return false; + return true; + }; + return isImplemented$1; +} +var isSymbol; +var hasRequiredIsSymbol; +function requireIsSymbol() { + if (hasRequiredIsSymbol) return isSymbol; + hasRequiredIsSymbol = 1; + isSymbol = function(value2) { + if (!value2) return false; + if (typeof value2 === "symbol") return true; + if (!value2.constructor) return false; + if (value2.constructor.name !== "Symbol") return false; + return value2[value2.constructor.toStringTag] === "Symbol"; + }; + return isSymbol; +} +var validateSymbol; +var hasRequiredValidateSymbol; +function requireValidateSymbol() { + if (hasRequiredValidateSymbol) return validateSymbol; + hasRequiredValidateSymbol = 1; + var isSymbol2 = requireIsSymbol(); + validateSymbol = function(value2) { + if (!isSymbol2(value2)) throw new TypeError(value2 + " is not a symbol"); + return value2; + }; + return validateSymbol; +} +var generateName; +var hasRequiredGenerateName; +function requireGenerateName() { + if (hasRequiredGenerateName) return generateName; + hasRequiredGenerateName = 1; + var d2 = dExports; + var create2 = Object.create, defineProperty2 = Object.defineProperty, objPrototype = Object.prototype; + var created = create2(null); + generateName = function(desc2) { + var postfix = 0, name, ie11BugWorkaround; + while (created[desc2 + (postfix || "")]) ++postfix; + desc2 += postfix || ""; + created[desc2] = true; + name = "@@" + desc2; + defineProperty2( + objPrototype, + name, + d2.gs(null, function(value2) { + if (ie11BugWorkaround) return; + ie11BugWorkaround = true; + defineProperty2(this, name, d2(value2)); + ie11BugWorkaround = false; + }) + ); + return name; + }; + return generateName; +} +var standardSymbols; +var hasRequiredStandardSymbols; +function requireStandardSymbols() { + if (hasRequiredStandardSymbols) return standardSymbols; + hasRequiredStandardSymbols = 1; + var d2 = dExports, NativeSymbol = requireGlobalThis().Symbol; + standardSymbols = function(SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + // To ensure proper interoperability with other native functions (e.g. Array.from) + // fallback to eventual native implementation of given symbol + hasInstance: d2( + "", + NativeSymbol && NativeSymbol.hasInstance || SymbolPolyfill("hasInstance") + ), + isConcatSpreadable: d2( + "", + NativeSymbol && NativeSymbol.isConcatSpreadable || SymbolPolyfill("isConcatSpreadable") + ), + iterator: d2("", NativeSymbol && NativeSymbol.iterator || SymbolPolyfill("iterator")), + match: d2("", NativeSymbol && NativeSymbol.match || SymbolPolyfill("match")), + replace: d2("", NativeSymbol && NativeSymbol.replace || SymbolPolyfill("replace")), + search: d2("", NativeSymbol && NativeSymbol.search || SymbolPolyfill("search")), + species: d2("", NativeSymbol && NativeSymbol.species || SymbolPolyfill("species")), + split: d2("", NativeSymbol && NativeSymbol.split || SymbolPolyfill("split")), + toPrimitive: d2( + "", + NativeSymbol && NativeSymbol.toPrimitive || SymbolPolyfill("toPrimitive") + ), + toStringTag: d2( + "", + NativeSymbol && NativeSymbol.toStringTag || SymbolPolyfill("toStringTag") + ), + unscopables: d2( + "", + NativeSymbol && NativeSymbol.unscopables || SymbolPolyfill("unscopables") + ) + }); + }; + return standardSymbols; +} +var symbolRegistry; +var hasRequiredSymbolRegistry; +function requireSymbolRegistry() { + if (hasRequiredSymbolRegistry) return symbolRegistry; + hasRequiredSymbolRegistry = 1; + var d2 = dExports, validateSymbol2 = requireValidateSymbol(); + var registry = /* @__PURE__ */ Object.create(null); + symbolRegistry = function(SymbolPolyfill) { + return Object.defineProperties(SymbolPolyfill, { + for: d2(function(key) { + if (registry[key]) return registry[key]; + return registry[key] = SymbolPolyfill(String(key)); + }), + keyFor: d2(function(symbol) { + var key; + validateSymbol2(symbol); + for (key in registry) { + if (registry[key] === symbol) return key; + } + return void 0; + }) + }); + }; + return symbolRegistry; +} +var polyfill; +var hasRequiredPolyfill; +function requirePolyfill() { + if (hasRequiredPolyfill) return polyfill; + hasRequiredPolyfill = 1; + var d2 = dExports, validateSymbol2 = requireValidateSymbol(), NativeSymbol = requireGlobalThis().Symbol, generateName2 = requireGenerateName(), setupStandardSymbols = requireStandardSymbols(), setupSymbolRegistry = requireSymbolRegistry(); + var create2 = Object.create, defineProperties2 = Object.defineProperties, defineProperty2 = Object.defineProperty; + var SymbolPolyfill, HiddenSymbol, isNativeSafe; + if (typeof NativeSymbol === "function") { + try { + String(NativeSymbol()); + isNativeSafe = true; + } catch (ignore) { + } + } else { + NativeSymbol = null; + } + HiddenSymbol = function Symbol2(description) { + if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor"); + return SymbolPolyfill(description); + }; + polyfill = SymbolPolyfill = function Symbol2(description) { + var symbol; + if (this instanceof Symbol2) throw new TypeError("Symbol is not a constructor"); + if (isNativeSafe) return NativeSymbol(description); + symbol = create2(HiddenSymbol.prototype); + description = description === void 0 ? "" : String(description); + return defineProperties2(symbol, { + __description__: d2("", description), + __name__: d2("", generateName2(description)) + }); + }; + setupStandardSymbols(SymbolPolyfill); + setupSymbolRegistry(SymbolPolyfill); + defineProperties2(HiddenSymbol.prototype, { + constructor: d2(SymbolPolyfill), + toString: d2("", function() { + return this.__name__; + }) + }); + defineProperties2(SymbolPolyfill.prototype, { + toString: d2(function() { + return "Symbol (" + validateSymbol2(this).__description__ + ")"; + }), + valueOf: d2(function() { + return validateSymbol2(this); + }) + }); + defineProperty2( + SymbolPolyfill.prototype, + SymbolPolyfill.toPrimitive, + d2("", function() { + var symbol = validateSymbol2(this); + if (typeof symbol === "symbol") return symbol; + return symbol.toString(); + }) + ); + defineProperty2(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d2("c", "Symbol")); + defineProperty2( + HiddenSymbol.prototype, + SymbolPolyfill.toStringTag, + d2("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]) + ); + defineProperty2( + HiddenSymbol.prototype, + SymbolPolyfill.toPrimitive, + d2("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]) + ); + return polyfill; +} +var es6Symbol; +var hasRequiredEs6Symbol; +function requireEs6Symbol() { + if (hasRequiredEs6Symbol) return es6Symbol; + hasRequiredEs6Symbol = 1; + es6Symbol = requireIsImplemented$1()() ? requireGlobalThis().Symbol : requirePolyfill(); + return es6Symbol; +} +var isArguments; +var hasRequiredIsArguments; +function requireIsArguments() { + if (hasRequiredIsArguments) return isArguments; + hasRequiredIsArguments = 1; + var objToString = Object.prototype.toString, id = objToString.call(/* @__PURE__ */ function() { + return arguments; + }()); + isArguments = function(value2) { + return objToString.call(value2) === id; + }; + return isArguments; +} +var isFunction; +var hasRequiredIsFunction; +function requireIsFunction() { + if (hasRequiredIsFunction) return isFunction; + hasRequiredIsFunction = 1; + var objToString = Object.prototype.toString, isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); + isFunction = function(value2) { + return typeof value2 === "function" && isFunctionStringTag(objToString.call(value2)); + }; + return isFunction; +} +var isString; +var hasRequiredIsString; +function requireIsString() { + if (hasRequiredIsString) return isString; + hasRequiredIsString = 1; + var objToString = Object.prototype.toString, id = objToString.call(""); + isString = function(value2) { + return typeof value2 === "string" || value2 && typeof value2 === "object" && (value2 instanceof String || objToString.call(value2) === id) || false; + }; + return isString; +} +var shim$1; +var hasRequiredShim$1; +function requireShim$1() { + if (hasRequiredShim$1) return shim$1; + hasRequiredShim$1 = 1; + var iteratorSymbol = requireEs6Symbol().iterator, isArguments2 = requireIsArguments(), isFunction2 = requireIsFunction(), toPosInt2 = toPosInteger, callable2 = validCallable, validValue$1 = validValue, isValue2 = isValue$6, isString2 = requireIsString(), isArray2 = Array.isArray, call2 = Function.prototype.call, desc2 = { configurable: true, enumerable: true, writable: true, value: null }, defineProperty2 = Object.defineProperty; + shim$1 = function(arrayLike) { + var mapFn = arguments[1], thisArg = arguments[2], Context, i, j, arr, length, code, iterator, result, getIterator, value2; + arrayLike = Object(validValue$1(arrayLike)); + if (isValue2(mapFn)) callable2(mapFn); + if (!this || this === Array || !isFunction2(this)) { + if (!mapFn) { + if (isArguments2(arrayLike)) { + length = arrayLike.length; + if (length !== 1) return Array.apply(null, arrayLike); + arr = new Array(1); + arr[0] = arrayLike[0]; + return arr; + } + if (isArray2(arrayLike)) { + arr = new Array(length = arrayLike.length); + for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; + return arr; + } + } + arr = []; + } else { + Context = this; + } + if (!isArray2(arrayLike)) { + if ((getIterator = arrayLike[iteratorSymbol]) !== void 0) { + iterator = callable2(getIterator).call(arrayLike); + if (Context) arr = new Context(); + result = iterator.next(); + i = 0; + while (!result.done) { + value2 = mapFn ? call2.call(mapFn, thisArg, result.value, i) : result.value; + if (Context) { + desc2.value = value2; + defineProperty2(arr, i, desc2); + } else { + arr[i] = value2; + } + result = iterator.next(); + ++i; + } + length = i; + } else if (isString2(arrayLike)) { + length = arrayLike.length; + if (Context) arr = new Context(); + for (i = 0, j = 0; i < length; ++i) { + value2 = arrayLike[i]; + if (i + 1 < length) { + code = value2.charCodeAt(0); + if (code >= 55296 && code <= 56319) value2 += arrayLike[++i]; + } + value2 = mapFn ? call2.call(mapFn, thisArg, value2, j) : value2; + if (Context) { + desc2.value = value2; + defineProperty2(arr, j, desc2); + } else { + arr[j] = value2; + } + ++j; + } + length = j; + } + } + if (length === void 0) { + length = toPosInt2(arrayLike.length); + if (Context) arr = new Context(length); + for (i = 0; i < length; ++i) { + value2 = mapFn ? call2.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; + if (Context) { + desc2.value = value2; + defineProperty2(arr, i, desc2); + } else { + arr[i] = value2; + } + } + } + if (Context) { + desc2.value = null; + arr.length = length; + } + return arr; + }; + return shim$1; +} +var from$1; +var hasRequiredFrom; +function requireFrom() { + if (hasRequiredFrom) return from$1; + hasRequiredFrom = 1; + from$1 = requireIsImplemented$3()() ? Array.from : requireShim$1(); + return from$1; +} +var from = requireFrom(), isArray = Array.isArray; +var toArray$1 = function(arrayLike) { + return isArray(arrayLike) ? arrayLike : from(arrayLike); +}; +var toArray = toArray$1, isValue = isValue$6, callable$2 = validCallable; +var slice = Array.prototype.slice, resolveArgs; +resolveArgs = function(args) { + return this.map(function(resolve, i) { + return resolve ? resolve(args[i]) : args[i]; + }).concat( + slice.call(args, this.length) + ); +}; +var resolveResolve$1 = function(resolvers) { + resolvers = toArray(resolvers); + resolvers.forEach(function(resolve) { + if (isValue(resolve)) callable$2(resolve); + }); + return resolveArgs.bind(resolvers); +}; +var callable$1 = validCallable; +var resolveNormalize$1 = function(userNormalizer) { + var normalizer; + if (typeof userNormalizer === "function") return { set: userNormalizer, get: userNormalizer }; + normalizer = { get: callable$1(userNormalizer.get) }; + if (userNormalizer.set !== void 0) { + normalizer.set = callable$1(userNormalizer.set); + if (userNormalizer.delete) normalizer.delete = callable$1(userNormalizer.delete); + if (userNormalizer.clear) normalizer.clear = callable$1(userNormalizer.clear); + return normalizer; + } + normalizer.set = normalizer.get; + return normalizer; +}; +var customError = customExports, defineLength = _defineLengthExports, d = dExports, ee = eventEmitterExports.methods, resolveResolve = resolveResolve$1, resolveNormalize = resolveNormalize$1; +var apply = Function.prototype.apply, call = Function.prototype.call, create = Object.create, defineProperties = Object.defineProperties, on = ee.on, emit = ee.emit; +var configureMap = function(original, length, options) { + var cache = create(null), conf, memLength, get2, set, del, clear, extDel, extGet, extHas, normalizer, getListeners, setListeners, deleteListeners, memoized, resolve; + if (length !== false) memLength = length; + else if (isNaN(original.length)) memLength = 1; + else memLength = original.length; + if (options.normalizer) { + normalizer = resolveNormalize(options.normalizer); + get2 = normalizer.get; + set = normalizer.set; + del = normalizer.delete; + clear = normalizer.clear; + } + if (options.resolvers != null) resolve = resolveResolve(options.resolvers); + if (get2) { + memoized = defineLength(function(arg) { + var id, result, args = arguments; + if (resolve) args = resolve(args); + id = get2(args); + if (id !== null) { + if (hasOwnProperty.call(cache, id)) { + if (getListeners) conf.emit("get", id, args, this); + return cache[id]; + } + } + if (args.length === 1) result = call.call(original, this, args[0]); + else result = apply.call(original, this, args); + if (id === null) { + id = get2(args); + if (id !== null) throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + id = set(args); + } else if (hasOwnProperty.call(cache, id)) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache[id] = result; + if (setListeners) conf.emit("set", id, null, result); + return result; + }, memLength); + } else if (length === 0) { + memoized = function() { + var result; + if (hasOwnProperty.call(cache, "data")) { + if (getListeners) conf.emit("get", "data", arguments, this); + return cache.data; + } + if (arguments.length) result = apply.call(original, this, arguments); + else result = call.call(original, this); + if (hasOwnProperty.call(cache, "data")) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache.data = result; + if (setListeners) conf.emit("set", "data", null, result); + return result; + }; + } else { + memoized = function(arg) { + var result, args = arguments, id; + if (resolve) args = resolve(arguments); + id = String(args[0]); + if (hasOwnProperty.call(cache, id)) { + if (getListeners) conf.emit("get", id, args, this); + return cache[id]; + } + if (args.length === 1) result = call.call(original, this, args[0]); + else result = apply.call(original, this, args); + if (hasOwnProperty.call(cache, id)) { + throw customError("Circular invocation", "CIRCULAR_INVOCATION"); + } + cache[id] = result; + if (setListeners) conf.emit("set", id, null, result); + return result; + }; + } + conf = { + original, + memoized, + profileName: options.profileName, + get: function(args) { + if (resolve) args = resolve(args); + if (get2) return get2(args); + return String(args[0]); + }, + has: function(id) { + return hasOwnProperty.call(cache, id); + }, + delete: function(id) { + var result; + if (!hasOwnProperty.call(cache, id)) return; + if (del) del(id); + result = cache[id]; + delete cache[id]; + if (deleteListeners) conf.emit("delete", id, result); + }, + clear: function() { + var oldCache = cache; + if (clear) clear(); + cache = create(null); + conf.emit("clear", oldCache); + }, + on: function(type, listener) { + if (type === "get") getListeners = true; + else if (type === "set") setListeners = true; + else if (type === "delete") deleteListeners = true; + return on.call(this, type, listener); + }, + emit, + updateEnv: function() { + original = conf.original; + } + }; + if (get2) { + extDel = defineLength(function(arg) { + var id, args = arguments; + if (resolve) args = resolve(args); + id = get2(args); + if (id === null) return; + conf.delete(id); + }, memLength); + } else if (length === 0) { + extDel = function() { + return conf.delete("data"); + }; + } else { + extDel = function(arg) { + if (resolve) arg = resolve(arguments)[0]; + return conf.delete(arg); + }; + } + extGet = defineLength(function() { + var id, args = arguments; + if (length === 0) return cache.data; + if (resolve) args = resolve(args); + if (get2) id = get2(args); + else id = String(args[0]); + return cache[id]; + }); + extHas = defineLength(function() { + var id, args = arguments; + if (length === 0) return conf.has("data"); + if (resolve) args = resolve(args); + if (get2) id = get2(args); + else id = String(args[0]); + if (id === null) return false; + return conf.has(id); + }); + defineProperties(memoized, { + __memoized__: d(true), + delete: d(extDel), + clear: d(conf.clear), + _get: d(extGet), + _has: d(extHas) + }); + return conf; +}; +var callable = validCallable, forEach = forEach$1, extensions = registeredExtensions, configure = configureMap, resolveLength$1 = resolveLength$2; +var plain$1 = function self2(fn) { + var options, length, conf; + callable(fn); + options = Object(arguments[1]); + if (options.async && options.promise) { + throw new Error("Options 'async' and 'promise' cannot be used together"); + } + if (hasOwnProperty.call(fn, "__memoized__") && !options.force) return fn; + length = resolveLength$1(options.length, fn.length, options.async && extensions.async); + conf = configure(fn, length, options); + forEach(extensions, function(extFn, name) { + if (options[name]) extFn(options[name], conf, options); + }); + if (self2.__profiler__) self2.__profiler__(conf); + conf.updateEnv(); + return conf.memoized; +}; +var primitive; +var hasRequiredPrimitive; +function requirePrimitive() { + if (hasRequiredPrimitive) return primitive; + hasRequiredPrimitive = 1; + primitive = function(args) { + var id, i, length = args.length; + if (!length) return ""; + id = String(args[i = 0]); + while (--length) id += "" + args[++i]; + return id; + }; + return primitive; +} +var getPrimitiveFixed; +var hasRequiredGetPrimitiveFixed; +function requireGetPrimitiveFixed() { + if (hasRequiredGetPrimitiveFixed) return getPrimitiveFixed; + hasRequiredGetPrimitiveFixed = 1; + getPrimitiveFixed = function(length) { + if (!length) { + return function() { + return ""; + }; + } + return function(args) { + var id = String(args[0]), i = 0, currentLength = length; + while (--currentLength) { + id += "" + args[++i]; + } + return id; + }; + }; + return getPrimitiveFixed; +} +var isImplemented; +var hasRequiredIsImplemented; +function requireIsImplemented() { + if (hasRequiredIsImplemented) return isImplemented; + hasRequiredIsImplemented = 1; + isImplemented = function() { + var numberIsNaN = Number.isNaN; + if (typeof numberIsNaN !== "function") return false; + return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); + }; + return isImplemented; +} +var shim; +var hasRequiredShim; +function requireShim() { + if (hasRequiredShim) return shim; + hasRequiredShim = 1; + shim = function(value2) { + return value2 !== value2; + }; + return shim; +} +var isNan; +var hasRequiredIsNan; +function requireIsNan() { + if (hasRequiredIsNan) return isNan; + hasRequiredIsNan = 1; + isNan = requireIsImplemented()() ? Number.isNaN : requireShim(); + return isNan; +} +var eIndexOf; +var hasRequiredEIndexOf; +function requireEIndexOf() { + if (hasRequiredEIndexOf) return eIndexOf; + hasRequiredEIndexOf = 1; + var numberIsNaN = requireIsNan(), toPosInt2 = toPosInteger, value2 = validValue, indexOf = Array.prototype.indexOf, objHasOwnProperty = Object.prototype.hasOwnProperty, abs2 = Math.abs, floor2 = Math.floor; + eIndexOf = function(searchElement) { + var i, length, fromIndex, val; + if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); + length = toPosInt2(value2(this).length); + fromIndex = arguments[1]; + if (isNaN(fromIndex)) fromIndex = 0; + else if (fromIndex >= 0) fromIndex = floor2(fromIndex); + else fromIndex = toPosInt2(this.length) - floor2(abs2(fromIndex)); + for (i = fromIndex; i < length; ++i) { + if (objHasOwnProperty.call(this, i)) { + val = this[i]; + if (numberIsNaN(val)) return i; + } + } + return -1; + }; + return eIndexOf; +} +var get; +var hasRequiredGet; +function requireGet() { + if (hasRequiredGet) return get; + hasRequiredGet = 1; + var indexOf = requireEIndexOf(); + var create2 = Object.create; + get = function() { + var lastId = 0, map2 = [], cache = create2(null); + return { + get: function(args) { + var index = 0, set = map2, i, length = args.length; + if (length === 0) return set[length] || null; + if (set = set[length]) { + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + return set[1][i] || null; + } + return null; + }, + set: function(args) { + var index = 0, set = map2, i, length = args.length; + if (length === 0) { + set[length] = ++lastId; + } else { + if (!set[length]) { + set[length] = [[], []]; + } + set = set[length]; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + set[1].push([[], []]); + } + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + } + set[1][i] = ++lastId; + } + cache[lastId] = args; + return lastId; + }, + delete: function(id) { + var index = 0, set = map2, i, args = cache[id], length = args.length, path = []; + if (length === 0) { + delete set[length]; + } else if (set = set[length]) { + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + path.push(set, i); + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + id = set[1][i]; + set[0].splice(i, 1); + set[1].splice(i, 1); + while (!set[0].length && path.length) { + i = path.pop(); + set = path.pop(); + set[0].splice(i, 1); + set[1].splice(i, 1); + } + } + delete cache[id]; + }, + clear: function() { + map2 = []; + cache = create2(null); + } + }; + }; + return get; +} +var get1; +var hasRequiredGet1; +function requireGet1() { + if (hasRequiredGet1) return get1; + hasRequiredGet1 = 1; + var indexOf = requireEIndexOf(); + get1 = function() { + var lastId = 0, argsMap = [], cache = []; + return { + get: function(args) { + var index = indexOf.call(argsMap, args[0]); + return index === -1 ? null : cache[index]; + }, + set: function(args) { + argsMap.push(args[0]); + cache.push(++lastId); + return lastId; + }, + delete: function(id) { + var index = indexOf.call(cache, id); + if (index !== -1) { + argsMap.splice(index, 1); + cache.splice(index, 1); + } + }, + clear: function() { + argsMap = []; + cache = []; + } + }; + }; + return get1; +} +var getFixed; +var hasRequiredGetFixed; +function requireGetFixed() { + if (hasRequiredGetFixed) return getFixed; + hasRequiredGetFixed = 1; + var indexOf = requireEIndexOf(), create2 = Object.create; + getFixed = function(length) { + var lastId = 0, map2 = [[], []], cache = create2(null); + return { + get: function(args) { + var index = 0, set = map2, i; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) return null; + return set[1][i] || null; + }, + set: function(args) { + var index = 0, set = map2, i; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + set[1].push([[], []]); + } + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + i = set[0].push(args[index]) - 1; + } + set[1][i] = ++lastId; + cache[lastId] = args; + return lastId; + }, + delete: function(id) { + var index = 0, set = map2, i, path = [], args = cache[id]; + while (index < length - 1) { + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + path.push(set, i); + set = set[1][i]; + ++index; + } + i = indexOf.call(set[0], args[index]); + if (i === -1) { + return; + } + id = set[1][i]; + set[0].splice(i, 1); + set[1].splice(i, 1); + while (!set[0].length && path.length) { + i = path.pop(); + set = path.pop(); + set[0].splice(i, 1); + set[1].splice(i, 1); + } + delete cache[id]; + }, + clear: function() { + map2 = [[], []]; + cache = create2(null); + } + }; + }; + return getFixed; +} +var async = {}; +var map; +var hasRequiredMap; +function requireMap() { + if (hasRequiredMap) return map; + hasRequiredMap = 1; + var callable2 = validCallable, forEach2 = forEach$1, call2 = Function.prototype.call; + map = function(obj, cb) { + var result = {}, thisArg = arguments[2]; + callable2(cb); + forEach2(obj, function(value2, key, targetObj, index) { + result[key] = call2.call(cb, thisArg, value2, key, targetObj, index); + }); + return result; + }; + return map; +} +var nextTick; +var hasRequiredNextTick; +function requireNextTick() { + if (hasRequiredNextTick) return nextTick; + hasRequiredNextTick = 1; + var ensureCallable = function(fn) { + if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); + return fn; + }; + var byObserver = function(Observer) { + var node = document.createTextNode(""), queue, currentQueue, i = 0; + new Observer(function() { + var callback; + if (!queue) { + if (!currentQueue) return; + queue = currentQueue; + } else if (currentQueue) { + queue = currentQueue.concat(queue); + } + currentQueue = queue; + queue = null; + if (typeof currentQueue === "function") { + callback = currentQueue; + currentQueue = null; + callback(); + return; + } + node.data = i = ++i % 2; + while (currentQueue) { + callback = currentQueue.shift(); + if (!currentQueue.length) currentQueue = null; + callback(); + } + }).observe(node, { characterData: true }); + return function(fn) { + ensureCallable(fn); + if (queue) { + if (typeof queue === "function") queue = [queue, fn]; + else queue.push(fn); + return; + } + queue = fn; + node.data = i = ++i % 2; + }; + }; + nextTick = function() { + if (typeof process === "object" && process && typeof process.nextTick === "function") { + return process.nextTick; + } + if (typeof queueMicrotask === "function") { + return function(cb) { + queueMicrotask(ensureCallable(cb)); + }; + } + if (typeof document === "object" && document) { + if (typeof MutationObserver === "function") return byObserver(MutationObserver); + if (typeof WebKitMutationObserver === "function") return byObserver(WebKitMutationObserver); + } + if (typeof setImmediate === "function") { + return function(cb) { + setImmediate(ensureCallable(cb)); + }; + } + if (typeof setTimeout === "function" || typeof setTimeout === "object") { + return function(cb) { + setTimeout(ensureCallable(cb), 0); + }; + } + return null; + }(); + return nextTick; +} +var hasRequiredAsync; +function requireAsync() { + if (hasRequiredAsync) return async; + hasRequiredAsync = 1; + var aFrom = requireFrom(), objectMap = requireMap(), mixin2 = requireMixin(), defineLength2 = _defineLengthExports, nextTick2 = requireNextTick(); + var slice2 = Array.prototype.slice, apply2 = Function.prototype.apply, create2 = Object.create; + registeredExtensions.async = function(tbi, conf) { + var waiting = create2(null), cache = create2(null), base = conf.memoized, original = conf.original, currentCallback, currentContext, currentArgs; + conf.memoized = defineLength2(function(arg) { + var args = arguments, last = args[args.length - 1]; + if (typeof last === "function") { + currentCallback = last; + args = slice2.call(args, 0, -1); + } + return base.apply(currentContext = this, currentArgs = args); + }, base); + try { + mixin2(conf.memoized, base); + } catch (ignore) { + } + conf.on("get", function(id) { + var cb, context, args; + if (!currentCallback) return; + if (waiting[id]) { + if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback]; + else waiting[id].push(currentCallback); + currentCallback = null; + return; + } + cb = currentCallback; + context = currentContext; + args = currentArgs; + currentCallback = currentContext = currentArgs = null; + nextTick2(function() { + var data; + if (hasOwnProperty.call(cache, id)) { + data = cache[id]; + conf.emit("getasync", id, args, context); + apply2.call(cb, data.context, data.args); + } else { + currentCallback = cb; + currentContext = context; + currentArgs = args; + base.apply(context, args); + } + }); + }); + conf.original = function() { + var args, cb, origCb, result; + if (!currentCallback) return apply2.call(original, this, arguments); + args = aFrom(arguments); + cb = function self3(err) { + var cb2, args2, id = self3.id; + if (id == null) { + nextTick2(apply2.bind(self3, this, arguments)); + return void 0; + } + delete self3.id; + cb2 = waiting[id]; + delete waiting[id]; + if (!cb2) { + return void 0; + } + args2 = aFrom(arguments); + if (conf.has(id)) { + if (err) { + conf.delete(id); + } else { + cache[id] = { context: this, args: args2 }; + conf.emit("setasync", id, typeof cb2 === "function" ? 1 : cb2.length); + } + } + if (typeof cb2 === "function") { + result = apply2.call(cb2, this, args2); + } else { + cb2.forEach(function(cb3) { + result = apply2.call(cb3, this, args2); + }, this); + } + return result; + }; + origCb = currentCallback; + currentCallback = currentContext = currentArgs = null; + args.push(cb); + result = apply2.call(original, this, args); + cb.cb = origCb; + currentCallback = cb; + return result; + }; + conf.on("set", function(id) { + if (!currentCallback) { + conf.delete(id); + return; + } + if (waiting[id]) { + if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback.cb]; + else waiting[id].push(currentCallback.cb); + } else { + waiting[id] = currentCallback.cb; + } + delete currentCallback.cb; + currentCallback.id = id; + currentCallback = null; + }); + conf.on("delete", function(id) { + var result; + if (hasOwnProperty.call(waiting, id)) return; + if (!cache[id]) return; + result = cache[id]; + delete cache[id]; + conf.emit("deleteasync", id, slice2.call(result.args, 1)); + }); + conf.on("clear", function() { + var oldCache = cache; + cache = create2(null); + conf.emit( + "clearasync", + objectMap(oldCache, function(data) { + return slice2.call(data.args, 1); + }) + ); + }); + }; + return async; +} +var promise = {}; +var primitiveSet; +var hasRequiredPrimitiveSet; +function requirePrimitiveSet() { + if (hasRequiredPrimitiveSet) return primitiveSet; + hasRequiredPrimitiveSet = 1; + var forEach2 = Array.prototype.forEach, create2 = Object.create; + primitiveSet = function(arg) { + var set = create2(null); + forEach2.call(arguments, function(name) { + set[name] = true; + }); + return set; + }; + return primitiveSet; +} +var isCallable; +var hasRequiredIsCallable; +function requireIsCallable() { + if (hasRequiredIsCallable) return isCallable; + hasRequiredIsCallable = 1; + isCallable = function(obj) { + return typeof obj === "function"; + }; + return isCallable; +} +var validateStringifiable; +var hasRequiredValidateStringifiable; +function requireValidateStringifiable() { + if (hasRequiredValidateStringifiable) return validateStringifiable; + hasRequiredValidateStringifiable = 1; + var isCallable2 = requireIsCallable(); + validateStringifiable = function(stringifiable) { + try { + if (stringifiable && isCallable2(stringifiable.toString)) return stringifiable.toString(); + return String(stringifiable); + } catch (e) { + throw new TypeError("Passed argument cannot be stringifed"); + } + }; + return validateStringifiable; +} +var validateStringifiableValue; +var hasRequiredValidateStringifiableValue; +function requireValidateStringifiableValue() { + if (hasRequiredValidateStringifiableValue) return validateStringifiableValue; + hasRequiredValidateStringifiableValue = 1; + var ensureValue = validValue, stringifiable = requireValidateStringifiable(); + validateStringifiableValue = function(value2) { + return stringifiable(ensureValue(value2)); + }; + return validateStringifiableValue; +} +var safeToString; +var hasRequiredSafeToString; +function requireSafeToString() { + if (hasRequiredSafeToString) return safeToString; + hasRequiredSafeToString = 1; + var isCallable2 = requireIsCallable(); + safeToString = function(value2) { + try { + if (value2 && isCallable2(value2.toString)) return value2.toString(); + return String(value2); + } catch (e) { + return ""; + } + }; + return safeToString; +} +var toShortStringRepresentation; +var hasRequiredToShortStringRepresentation; +function requireToShortStringRepresentation() { + if (hasRequiredToShortStringRepresentation) return toShortStringRepresentation; + hasRequiredToShortStringRepresentation = 1; + var safeToString2 = requireSafeToString(); + var reNewLine = /[\n\r\u2028\u2029]/g; + toShortStringRepresentation = function(value2) { + var string = safeToString2(value2); + if (string.length > 100) string = string.slice(0, 99) + "…"; + string = string.replace(reNewLine, function(char) { + return JSON.stringify(char).slice(1, -1); + }); + return string; + }; + return toShortStringRepresentation; +} +var isPromise = { exports: {} }; +var hasRequiredIsPromise; +function requireIsPromise() { + if (hasRequiredIsPromise) return isPromise.exports; + hasRequiredIsPromise = 1; + isPromise.exports = isPromise$1; + isPromise.exports.default = isPromise$1; + function isPromise$1(obj) { + return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; + } + return isPromise.exports; +} +var hasRequiredPromise; +function requirePromise() { + if (hasRequiredPromise) return promise; + hasRequiredPromise = 1; + var objectMap = requireMap(), primitiveSet2 = requirePrimitiveSet(), ensureString = requireValidateStringifiableValue(), toShortString = requireToShortStringRepresentation(), isPromise2 = requireIsPromise(), nextTick2 = requireNextTick(); + var create2 = Object.create, supportedModes = primitiveSet2("then", "then:finally", "done", "done:finally"); + registeredExtensions.promise = function(mode, conf) { + var waiting = create2(null), cache = create2(null), promises = create2(null); + if (mode === true) { + mode = null; + } else { + mode = ensureString(mode); + if (!supportedModes[mode]) { + throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode"); + } + } + conf.on("set", function(id, ignore, promise2) { + var isFailed = false; + if (!isPromise2(promise2)) { + cache[id] = promise2; + conf.emit("setasync", id, 1); + return; + } + waiting[id] = 1; + promises[id] = promise2; + var onSuccess = function(result) { + var count = waiting[id]; + if (isFailed) { + throw new Error( + "Memoizee error: Detected unordered then|done & finally resolution, which in turn makes proper detection of success/failure impossible (when in 'done:finally' mode)\nConsider to rely on 'then' or 'done' mode instead." + ); + } + if (!count) return; + delete waiting[id]; + cache[id] = result; + conf.emit("setasync", id, count); + }; + var onFailure = function() { + isFailed = true; + if (!waiting[id]) return; + delete waiting[id]; + delete promises[id]; + conf.delete(id); + }; + var resolvedMode = mode; + if (!resolvedMode) resolvedMode = "then"; + if (resolvedMode === "then") { + var nextTickFailure = function() { + nextTick2(onFailure); + }; + promise2 = promise2.then(function(result) { + nextTick2(onSuccess.bind(this, result)); + }, nextTickFailure); + if (typeof promise2.finally === "function") { + promise2.finally(nextTickFailure); + } + } else if (resolvedMode === "done") { + if (typeof promise2.done !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'done' in 'done' mode" + ); + } + promise2.done(onSuccess, onFailure); + } else if (resolvedMode === "done:finally") { + if (typeof promise2.done !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'done' in 'done:finally' mode" + ); + } + if (typeof promise2.finally !== "function") { + throw new Error( + "Memoizee error: Retrieved promise does not implement 'finally' in 'done:finally' mode" + ); + } + promise2.done(onSuccess); + promise2.finally(onFailure); + } + }); + conf.on("get", function(id, args, context) { + var promise2; + if (waiting[id]) { + ++waiting[id]; + return; + } + promise2 = promises[id]; + var emit2 = function() { + conf.emit("getasync", id, args, context); + }; + if (isPromise2(promise2)) { + if (typeof promise2.done === "function") promise2.done(emit2); + else { + promise2.then(function() { + nextTick2(emit2); + }); + } + } else { + emit2(); + } + }); + conf.on("delete", function(id) { + delete promises[id]; + if (waiting[id]) { + delete waiting[id]; + return; + } + if (!hasOwnProperty.call(cache, id)) return; + var result = cache[id]; + delete cache[id]; + conf.emit("deleteasync", id, [result]); + }); + conf.on("clear", function() { + var oldCache = cache; + cache = create2(null); + waiting = create2(null); + promises = create2(null); + conf.emit("clearasync", objectMap(oldCache, function(data) { + return [data]; + })); + }); + }; + return promise; +} +var dispose = {}; +var hasRequiredDispose; +function requireDispose() { + if (hasRequiredDispose) return dispose; + hasRequiredDispose = 1; + var callable2 = validCallable, forEach2 = forEach$1, extensions2 = registeredExtensions, apply2 = Function.prototype.apply; + extensions2.dispose = function(dispose2, conf, options) { + var del; + callable2(dispose2); + if (options.async && extensions2.async || options.promise && extensions2.promise) { + conf.on( + "deleteasync", + del = function(id, resultArray) { + apply2.call(dispose2, null, resultArray); + } + ); + conf.on("clearasync", function(cache) { + forEach2(cache, function(result, id) { + del(id, result); + }); + }); + return; + } + conf.on("delete", del = function(id, result) { + dispose2(result); + }); + conf.on("clear", function(cache) { + forEach2(cache, function(result, id) { + del(id, result); + }); + }); + }; + return dispose; +} +var maxAge = {}; +var maxTimeout; +var hasRequiredMaxTimeout; +function requireMaxTimeout() { + if (hasRequiredMaxTimeout) return maxTimeout; + hasRequiredMaxTimeout = 1; + maxTimeout = 2147483647; + return maxTimeout; +} +var validTimeout; +var hasRequiredValidTimeout; +function requireValidTimeout() { + if (hasRequiredValidTimeout) return validTimeout; + hasRequiredValidTimeout = 1; + var toPosInt2 = toPosInteger, maxTimeout2 = requireMaxTimeout(); + validTimeout = function(value2) { + value2 = toPosInt2(value2); + if (value2 > maxTimeout2) throw new TypeError(value2 + " exceeds maximum possible timeout"); + return value2; + }; + return validTimeout; +} +var hasRequiredMaxAge; +function requireMaxAge() { + if (hasRequiredMaxAge) return maxAge; + hasRequiredMaxAge = 1; + var aFrom = requireFrom(), forEach2 = forEach$1, nextTick2 = requireNextTick(), isPromise2 = requireIsPromise(), timeout = requireValidTimeout(), extensions2 = registeredExtensions; + var noop2 = Function.prototype, max2 = Math.max, min = Math.min, create2 = Object.create; + extensions2.maxAge = function(maxAge2, conf, options) { + var timeouts, postfix, preFetchAge, preFetchTimeouts; + maxAge2 = timeout(maxAge2); + if (!maxAge2) return; + timeouts = create2(null); + postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; + conf.on("set" + postfix, function(id) { + timeouts[id] = setTimeout(function() { + conf.delete(id); + }, maxAge2); + if (typeof timeouts[id].unref === "function") timeouts[id].unref(); + if (!preFetchTimeouts) return; + if (preFetchTimeouts[id]) { + if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); + } + preFetchTimeouts[id] = setTimeout(function() { + delete preFetchTimeouts[id]; + }, preFetchAge); + if (typeof preFetchTimeouts[id].unref === "function") preFetchTimeouts[id].unref(); + }); + conf.on("delete" + postfix, function(id) { + clearTimeout(timeouts[id]); + delete timeouts[id]; + if (!preFetchTimeouts) return; + if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); + delete preFetchTimeouts[id]; + }); + if (options.preFetch) { + if (options.preFetch === true || isNaN(options.preFetch)) { + preFetchAge = 0.333; + } else { + preFetchAge = max2(min(Number(options.preFetch), 1), 0); + } + if (preFetchAge) { + preFetchTimeouts = {}; + preFetchAge = (1 - preFetchAge) * maxAge2; + conf.on("get" + postfix, function(id, args, context) { + if (!preFetchTimeouts[id]) { + preFetchTimeouts[id] = "nextTick"; + nextTick2(function() { + var result; + if (preFetchTimeouts[id] !== "nextTick") return; + delete preFetchTimeouts[id]; + conf.delete(id); + if (options.async) { + args = aFrom(args); + args.push(noop2); + } + result = conf.memoized.apply(context, args); + if (options.promise) { + if (isPromise2(result)) { + if (typeof result.done === "function") result.done(noop2, noop2); + else result.then(noop2, noop2); + } + } + }); + } + }); + } + } + conf.on("clear" + postfix, function() { + forEach2(timeouts, function(id) { + clearTimeout(id); + }); + timeouts = {}; + if (preFetchTimeouts) { + forEach2(preFetchTimeouts, function(id) { + if (id !== "nextTick") clearTimeout(id); + }); + preFetchTimeouts = {}; + } + }); + }; + return maxAge; +} +var max = {}; +var lruQueue; +var hasRequiredLruQueue; +function requireLruQueue() { + if (hasRequiredLruQueue) return lruQueue; + hasRequiredLruQueue = 1; + var toPosInt2 = toPosInteger, create2 = Object.create, hasOwnProperty2 = Object.prototype.hasOwnProperty; + lruQueue = function(limit) { + var size = 0, base = 1, queue = create2(null), map2 = create2(null), index = 0, del; + limit = toPosInt2(limit); + return { + hit: function(id) { + var oldIndex = map2[id], nuIndex = ++index; + queue[nuIndex] = id; + map2[id] = nuIndex; + if (!oldIndex) { + ++size; + if (size <= limit) return; + id = queue[base]; + del(id); + return id; + } + delete queue[oldIndex]; + if (base !== oldIndex) return; + while (!hasOwnProperty2.call(queue, ++base)) continue; + }, + delete: del = function(id) { + var oldIndex = map2[id]; + if (!oldIndex) return; + delete queue[oldIndex]; + delete map2[id]; + --size; + if (base !== oldIndex) return; + if (!size) { + index = 0; + base = 1; + return; + } + while (!hasOwnProperty2.call(queue, ++base)) continue; + }, + clear: function() { + size = 0; + base = 1; + queue = create2(null); + map2 = create2(null); + index = 0; + } + }; + }; + return lruQueue; +} +var hasRequiredMax; +function requireMax() { + if (hasRequiredMax) return max; + hasRequiredMax = 1; + var toPosInteger$1 = toPosInteger, lruQueue2 = requireLruQueue(), extensions2 = registeredExtensions; + extensions2.max = function(max2, conf, options) { + var postfix, queue, hit; + max2 = toPosInteger$1(max2); + if (!max2) return; + queue = lruQueue2(max2); + postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; + conf.on( + "set" + postfix, + hit = function(id) { + id = queue.hit(id); + if (id === void 0) return; + conf.delete(id); + } + ); + conf.on("get" + postfix, hit); + conf.on("delete" + postfix, queue.delete); + conf.on("clear" + postfix, queue.clear); + }; + return max; +} +var refCounter = {}; +var hasRequiredRefCounter; +function requireRefCounter() { + if (hasRequiredRefCounter) return refCounter; + hasRequiredRefCounter = 1; + var d2 = dExports, extensions2 = registeredExtensions, create2 = Object.create, defineProperties2 = Object.defineProperties; + extensions2.refCounter = function(ignore, conf, options) { + var cache, postfix; + cache = create2(null); + postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; + conf.on("set" + postfix, function(id, length) { + cache[id] = length || 1; + }); + conf.on("get" + postfix, function(id) { + ++cache[id]; + }); + conf.on("delete" + postfix, function(id) { + delete cache[id]; + }); + conf.on("clear" + postfix, function() { + cache = {}; + }); + defineProperties2(conf.memoized, { + deleteRef: d2(function() { + var id = conf.get(arguments); + if (id === null) return null; + if (!cache[id]) return null; + if (!--cache[id]) { + conf.delete(id); + return true; + } + return false; + }), + getRefCount: d2(function() { + var id = conf.get(arguments); + if (id === null) return 0; + if (!cache[id]) return 0; + return cache[id]; + }) + }); + }; + return refCounter; +} +var normalizeOpts = normalizeOptions, resolveLength = resolveLength$2, plain = plain$1; +var memoizee = function(fn) { + var options = normalizeOpts(arguments[1]), length; + if (!options.normalizer) { + length = options.length = resolveLength(options.length, fn.length, options.async); + if (length !== 0) { + if (options.primitive) { + if (length === false) { + options.normalizer = requirePrimitive(); + } else if (length > 1) { + options.normalizer = requireGetPrimitiveFixed()(length); + } + } else if (length === false) options.normalizer = requireGet()(); + else if (length === 1) options.normalizer = requireGet1()(); + else options.normalizer = requireGetFixed()(length); + } + } + if (options.async) requireAsync(); + if (options.promise) requirePromise(); + if (options.dispose) requireDispose(); + if (options.maxAge) requireMaxAge(); + if (options.max) requireMax(); + if (options.refCounter) requireRefCounter(); + return plain(fn, options); +}; +const memoize = /* @__PURE__ */ getDefaultExportFromCjs(memoizee); +function _defineProperty$1(e, r, t) { + return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey$1(t) { + var i = _toPrimitive$1(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive$1(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +class ChartModel { + constructor(dh) { + _defineProperty$1(this, "dh", void 0); + _defineProperty$1(this, "listeners", void 0); + _defineProperty$1(this, "formatter", void 0); + _defineProperty$1(this, "renderOptions", void 0); + _defineProperty$1(this, "rect", void 0); + _defineProperty$1(this, "isDownsamplingDisabled", void 0); + _defineProperty$1(this, "title", void 0); + this.dh = dh; + this.listeners = []; + this.isDownsamplingDisabled = false; + } + /** Formatter settings for the chart, such as how to format dates and numbers */ + getData() { + return []; + } + getDefaultTitle() { + return ""; + } + getLayout() { + return {}; + } + getFilterColumnMap() { + return /* @__PURE__ */ new Map(); + } + isFilterRequired() { + return false; + } + // eslint-disable-next-line @typescript-eslint/no-empty-function + setFilter(filter) { + } + /** + * Close this model, clean up any underlying subscriptions + */ + // eslint-disable-next-line @typescript-eslint/no-empty-function + close() { + } + /** + * Set the formatter to use when charting the data. + * @param formatter The formatter to use to format the charting data + */ + setFormatter(formatter) { + this.formatter = formatter; + } + /** + * Set additional options for rendering the chart + * @param renderOptions Options for rendering the chart + */ + setRenderOptions(renderOptions) { + this.renderOptions = renderOptions; + } + /** + * Disable downsampling + * @param isDownsamplingDisabled True if downsampling should be disabled + */ + setDownsamplingDisabled(isDownsamplingDisabled) { + this.isDownsamplingDisabled = isDownsamplingDisabled; + } + /** + * Set the dimensions of the plot. May be needed to evaluate some of the percents + * @param rect The bounding rectangle of the plot + */ + setDimensions(rect) { + this.rect = rect; + } + setTitle(title) { + this.title = title; + } + /** + * Subscribe to this ChartModel and start listening for all events. + * @param callback Callback when an event occurs + */ + subscribe(callback) { + this.listeners.push(callback); + } + unsubscribe(callback) { + this.listeners = this.listeners.filter((listener) => listener !== callback); + } + fireEvent(event) { + for (var i = 0; i < this.listeners.length; i += 1) { + this.listeners[i](event); + } + } + fireUpdate(data) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_UPDATED, { + detail: data + })); + } + fireDisconnect() { + this.fireEvent(new CustomEvent(ChartModel.EVENT_DISCONNECT)); + } + fireReconnect() { + this.fireEvent(new CustomEvent(ChartModel.EVENT_RECONNECT)); + } + fireDownsampleStart(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLESTARTED, { + detail + })); + } + fireDownsampleFinish(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLEFINISHED, { + detail + })); + } + fireDownsampleFail(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLEFAILED, { + detail + })); + } + fireDownsampleNeeded(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLENEEDED, { + detail + })); + } + fireLoadFinished() { + this.fireEvent(new CustomEvent(ChartModel.EVENT_LOADFINISHED)); + } + fireError(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_ERROR, { + detail + })); + } + fireBlocker(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_BLOCKER, { + detail + })); + } + fireBlockerClear() { + this.fireEvent(new CustomEvent(ChartModel.EVENT_BLOCKER_CLEAR)); + } + fireLayoutUpdated(detail) { + this.fireEvent(new CustomEvent(ChartModel.EVENT_LAYOUT_UPDATED, { + detail + })); + } +} +_defineProperty$1(ChartModel, "EVENT_UPDATED", "ChartModel.EVENT_UPDATED"); +_defineProperty$1(ChartModel, "EVENT_DISCONNECT", "ChartModel.EVENT_DISCONNECT"); +_defineProperty$1(ChartModel, "EVENT_RECONNECT", "ChartModel.EVENT_RECONNECT"); +_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLESTARTED", "ChartModel.EVENT_DOWNSAMPLESTARTED"); +_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLEFINISHED", "ChartModel.EVENT_DOWNSAMPLEFINISHED"); +_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLEFAILED", "ChartModel.EVENT_DOWNSAMPLEFAILED"); +_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLENEEDED", "ChartModel.EVENT_DOWNSAMPLENEEDED"); +_defineProperty$1(ChartModel, "EVENT_LOADFINISHED", "ChartModel.EVENT_LOADFINISHED"); +_defineProperty$1(ChartModel, "EVENT_ERROR", "ChartModel.EVENT_ERROR"); +_defineProperty$1(ChartModel, "EVENT_BLOCKER", "ChartModel.EVENT_BLOCKER"); +_defineProperty$1(ChartModel, "EVENT_BLOCKER_CLEAR", "ChartModel.EVENT_BLOCKER_CLEAR"); +_defineProperty$1(ChartModel, "EVENT_LAYOUT_UPDATED", "ChartModel.EVENT_LAYOUT_UPDATED"); +function ownKeys(e, r) { + var t = Object.keys(e); + if (Object.getOwnPropertySymbols) { + var o = Object.getOwnPropertySymbols(e); + r && (o = o.filter(function(r2) { + return Object.getOwnPropertyDescriptor(e, r2).enumerable; + })), t.push.apply(t, o); + } + return t; +} +function _objectSpread(e) { + for (var r = 1; r < arguments.length; r++) { + var t = null != arguments[r] ? arguments[r] : {}; + r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { + _defineProperty(e, r2, t[r2]); + }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { + Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); + }); + } + return e; +} +function _defineProperty(e, r, t) { + return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; +} +function _toPropertyKey(t) { + var i = _toPrimitive(t, "string"); + return "symbol" == typeof i ? i : i + ""; +} +function _toPrimitive(t, r) { + if ("object" != typeof t || !t) return t; + var e = t[Symbol.toPrimitive]; + if (void 0 !== e) { + var i = e.call(t, r); + if ("object" != typeof i) return i; + throw new TypeError("@@toPrimitive must return a primitive value."); + } + return ("string" === r ? String : Number)(t); +} +var log$1 = Log.module("FigureChartModel"); +class FigureChartModel extends ChartModel { + /** + * @param dh JSAPI instance + * @param figure The figure object created by the API + * @param settings Chart settings + */ + constructor(dh, figure) { + var _this; + var settings = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; + super(dh); + _this = this; + _defineProperty(this, "chartUtils", void 0); + _defineProperty(this, "dh", void 0); + _defineProperty(this, "figure", void 0); + _defineProperty(this, "settings", void 0); + _defineProperty(this, "data", void 0); + _defineProperty(this, "layout", void 0); + _defineProperty(this, "seriesDataMap", void 0); + _defineProperty(this, "pendingSeries", void 0); + _defineProperty(this, "oneClicks", void 0); + _defineProperty(this, "filterColumnMap", void 0); + _defineProperty(this, "lastFilter", void 0); + _defineProperty(this, "isConnected", void 0); + _defineProperty(this, "seriesToProcess", void 0); + _defineProperty(this, "addPendingSeries", lodashExports.debounce(() => { + var axisTypeMap = ChartUtils.getAxisTypeMap(this.figure); + var { + pendingSeries + } = this; + var _loop = function _loop2() { + var _chart$showLegend; + var series = pendingSeries[i]; + var chart = _this.figure.charts.find((c) => c.series.includes(series)); + _this.addSeries(series, axisTypeMap, (_chart$showLegend = chart === null || chart === void 0 ? void 0 : chart.showLegend) !== null && _chart$showLegend !== void 0 ? _chart$showLegend : null); + series.subscribe(); + }; + for (var i = 0; i < pendingSeries.length; i += 1) { + _loop(); + } + this.pendingSeries = []; + }, FigureChartModel.ADD_SERIES_DEBOUNCE)); + _defineProperty(this, "getTimeZone", memoize((columnType, formatter) => { + if (formatter != null) { + var dataFormatter = formatter.getColumnTypeFormatter(columnType); + if (dataFormatter != null) { + return dataFormatter.dhTimeZone; + } + } + return void 0; + })); + _defineProperty(this, "getValueTranslator", memoize((columnType, formatter) => { + var timeZone = this.getTimeZone(columnType, formatter); + return (value2) => this.chartUtils.unwrapValue(value2, timeZone); + })); + _defineProperty(this, "getValueParser", memoize((columnType, formatter) => { + var timeZone = this.getTimeZone(columnType, formatter); + return (value2) => this.chartUtils.wrapValue(value2, columnType, timeZone); + })); + _defineProperty(this, "getRangeParser", memoize((columnType, formatter) => (range) => { + var [rangeStart, rangeEnd] = range; + var valueParser = this.getValueParser(columnType, formatter); + rangeStart = valueParser(rangeStart); + rangeEnd = valueParser(rangeEnd); + return [rangeStart, rangeEnd]; + })); + _defineProperty(this, "getAxisRangeParser", memoize((chart, formatter) => (axis) => { + var source = ChartUtils.getSourceForAxis(chart, axis); + if (source != null) { + return this.getRangeParser(source.columnType, formatter); + } + return (range) => range; + })); + this.handleFigureUpdated = this.handleFigureUpdated.bind(this); + this.handleFigureDisconnected = this.handleFigureDisconnected.bind(this); + this.handleFigureReconnected = this.handleFigureReconnected.bind(this); + this.handleFigureSeriesAdded = this.handleFigureSeriesAdded.bind(this); + this.handleDownsampleStart = this.handleDownsampleStart.bind(this); + this.handleDownsampleFinish = this.handleDownsampleFinish.bind(this); + this.handleDownsampleFail = this.handleDownsampleFail.bind(this); + this.handleDownsampleNeeded = this.handleDownsampleNeeded.bind(this); + this.handleRequestFailed = this.handleRequestFailed.bind(this); + this.dh = dh; + this.chartUtils = new ChartUtils(dh); + this.figure = figure; + this.settings = settings; + this.data = []; + this.layout = { + grid: { + rows: figure.rows, + columns: figure.cols, + pattern: "independent" + } + }; + this.seriesDataMap = /* @__PURE__ */ new Map(); + this.pendingSeries = []; + this.oneClicks = []; + this.filterColumnMap = /* @__PURE__ */ new Map(); + this.lastFilter = /* @__PURE__ */ new Map(); + this.isConnected = true; + this.seriesToProcess = /* @__PURE__ */ new Set(); + this.setTitle(this.getDefaultTitle()); + this.initAllSeries(); + this.updateAxisPositions(); + this.startListeningFigure(); + } + // Assume figure is connected to start + close() { + this.figure.close(); + this.addPendingSeries.cancel(); + this.stopListeningFigure(); + } + getDefaultTitle() { + if (this.figure.title != null && this.figure.title.length > 0) { + return this.figure.title; + } + if (this.figure.charts.length === 1) { + var _this$figure$charts$; + return (_this$figure$charts$ = this.figure.charts[0].title) !== null && _this$figure$charts$ !== void 0 ? _this$figure$charts$ : ""; + } + return ""; + } + initAllSeries() { + var _this2 = this; + this.oneClicks = []; + this.filterColumnMap.clear(); + var { + charts + } = this.figure; + var axisTypeMap = ChartUtils.getAxisTypeMap(this.figure); + var activeSeriesNames = []; + this.seriesToProcess = /* @__PURE__ */ new Set(); + var _loop2 = function _loop22() { + var chart = charts[i]; + for (var j = 0; j < chart.series.length; j += 1) { + var series = chart.series[j]; + activeSeriesNames.push(series.name); + _this2.addSeries(series, axisTypeMap, chart.showLegend); + } + var { + axes, + title + } = chart; + if (title != null && title.length > 0 && (charts.length > 1 || _this2.figure.title != null)) { + var xAxis = axes.find((axis) => axis.type === _this2.dh.plot.AxisType.X); + var yAxis = axes.find((axis) => axis.type === _this2.dh.plot.AxisType.Y); + if (xAxis == null || yAxis == null) { + log$1.warn("Chart title provided, but unknown how to map to the correct axes for this chart type", chart); + } else { + var _axisTypeMap$get$find, _axisTypeMap$get, _axisTypeMap$get$find2, _axisTypeMap$get2; + var xAxisIndex = ((_axisTypeMap$get$find = (_axisTypeMap$get = axisTypeMap.get(xAxis.type)) === null || _axisTypeMap$get === void 0 ? void 0 : _axisTypeMap$get.findIndex((a) => a === xAxis)) !== null && _axisTypeMap$get$find !== void 0 ? _axisTypeMap$get$find : 0) + 1; + var yAxisIndex = ((_axisTypeMap$get$find2 = (_axisTypeMap$get2 = axisTypeMap.get(yAxis.type)) === null || _axisTypeMap$get2 === void 0 ? void 0 : _axisTypeMap$get2.findIndex((a) => a === yAxis)) !== null && _axisTypeMap$get$find2 !== void 0 ? _axisTypeMap$get$find2 : 0) + 1; + var annotation = { + align: "center", + x: 0.5, + y: 1, + yshift: 17, + text: title, + showarrow: false, + // Typing is incorrect in Plotly for this, as it doesn't seem to be typed for the "domain" part: https://plotly.com/javascript/reference/layout/annotations/#layout-annotations-items-annotation-xref + xref: "x".concat(xAxisIndex, " domain"), + yref: "y".concat(yAxisIndex, " domain") + }; + if (_this2.layout.annotations == null) { + _this2.layout.annotations = [annotation]; + } else { + _this2.layout.annotations.push(annotation); + } + } + } + }; + for (var i = 0; i < charts.length; i += 1) { + _loop2(); + } + var allSeriesNames = [...this.seriesDataMap.keys()]; + var inactiveSeriesNames = allSeriesNames.filter((seriesName2) => activeSeriesNames.indexOf(seriesName2) < 0); + for (var _i = 0; _i < inactiveSeriesNames.length; _i += 1) { + var seriesName = inactiveSeriesNames[_i]; + this.seriesDataMap.delete(seriesName); + } + } + /** + * Add a series to the model + * @param series Series object to add + * @param axisTypeMap Map of axis type to the axes in this Figure + * @param showLegend Whether this series should show the legend or not + */ + addSeries(series, axisTypeMap, showLegend) { + var _this$renderOptions$w, _this$renderOptions; + var { + dh + } = this; + var seriesData = this.chartUtils.makeSeriesDataFromSeries(series, axisTypeMap, ChartUtils.getSeriesVisibility(series.name, this.settings), showLegend, (_this$renderOptions$w = (_this$renderOptions = this.renderOptions) === null || _this$renderOptions === void 0 ? void 0 : _this$renderOptions.webgl) !== null && _this$renderOptions$w !== void 0 ? _this$renderOptions$w : true); + this.seriesDataMap.set(series.name, seriesData); + this.seriesToProcess.add(series.name); + this.data = [...this.seriesDataMap.values()]; + if (series.plotStyle === dh.plot.SeriesPlotStyle.STACKED_BAR) { + this.layout.barmode = "stack"; + } else if (series.plotStyle === dh.plot.SeriesPlotStyle.PIE) { + this.layout.hiddenlabels = ChartUtils.getHiddenLabels(this.settings); + } + this.layout.showlegend = this.data.length > 1 || series.plotStyle === dh.plot.SeriesPlotStyle.PIE ? showLegend !== null && showLegend !== void 0 ? showLegend : void 0 : false; + if (series.oneClick != null) { + var { + oneClick + } = series; + var { + columns + } = oneClick; + for (var i = 0; i < columns.length; i += 1) { + this.filterColumnMap.set(columns[i].name, columns[i]); + } + this.oneClicks.push(oneClick); + } + this.updateLayoutFormats(); + } + // We need to debounce adding series so we subscribe to them all in the same tick + // This should no longer be necessary after IDS-5049 lands + subscribe(callback) { + super.subscribe(callback); + if (this.listeners.length === 1) { + this.initAllSeries(); + this.subscribeFigure(); + } + } + unsubscribe(callback) { + super.unsubscribe(callback); + if (this.listeners.length === 0) { + this.unsubscribeFigure(); + } + } + subscribeFigure() { + if (!this.isConnected) { + log$1.debug("Ignoring subscribe when figure in disconnected state"); + return; + } + this.figure.subscribe(this.isDownsamplingDisabled ? this.dh.plot.DownsampleOptions.DISABLE : this.dh.plot.DownsampleOptions.DEFAULT); + if (this.figure.errors.length > 0) { + log$1.error("Errors in figure", this.figure.errors); + this.fireError(this.figure.errors); + } + } + unsubscribeFigure() { + this.figure.unsubscribe(); + } + startListeningFigure() { + var { + dh + } = this; + this.figure.addEventListener(dh.plot.Figure.EVENT_UPDATED, this.handleFigureUpdated); + this.figure.addEventListener(dh.plot.Figure.EVENT_SERIES_ADDED, this.handleFigureSeriesAdded); + this.figure.addEventListener(dh.plot.Figure.EVENT_DISCONNECT, this.handleFigureDisconnected); + this.figure.addEventListener(dh.plot.Figure.EVENT_RECONNECT, this.handleFigureReconnected); + this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLESTARTED, this.handleDownsampleStart); + this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFINISHED, this.handleDownsampleFinish); + this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFAILED, this.handleDownsampleFail); + this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLENEEDED, this.handleDownsampleNeeded); + this.figure.addEventListener(dh.Client.EVENT_REQUEST_FAILED, this.handleRequestFailed); + } + stopListeningFigure() { + var { + dh + } = this; + this.figure.removeEventListener(dh.plot.Figure.EVENT_UPDATED, this.handleFigureUpdated); + this.figure.removeEventListener(dh.plot.Figure.EVENT_SERIES_ADDED, this.handleFigureSeriesAdded); + this.figure.removeEventListener(dh.plot.Figure.EVENT_DISCONNECT, this.handleFigureDisconnected); + this.figure.removeEventListener(dh.plot.Figure.EVENT_RECONNECT, this.handleFigureReconnected); + this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLESTARTED, this.handleDownsampleStart); + this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFINISHED, this.handleDownsampleFinish); + this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFAILED, this.handleDownsampleFail); + this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLENEEDED, this.handleDownsampleNeeded); + this.figure.removeEventListener(dh.Client.EVENT_REQUEST_FAILED, this.handleRequestFailed); + } + /** Gets the parser for a value with the provided column type */ + /** + * Gets the range parser for a particular column type + */ + /** + * Gets the parser for parsing the range from an axis within the given chart + */ + handleDownsampleStart(event) { + log$1.debug("Downsample started", event); + this.fireDownsampleStart(event.detail); + } + handleDownsampleFinish(event) { + log$1.debug("Downsample finished", event); + this.fireDownsampleFinish(event.detail); + } + handleDownsampleFail(event) { + log$1.error("Downsample failed", event); + this.fireDownsampleFail(event.detail); + } + handleDownsampleNeeded(event) { + log$1.info("Downsample needed", event); + this.fireDownsampleNeeded(event.detail); + } + handleFigureUpdated(event) { + var { + detail: figureUpdateEvent + } = event; + var { + series: seriesArray + } = figureUpdateEvent; + log$1.debug2("handleFigureUpdated", seriesArray); + for (var i = 0; i < seriesArray.length; i += 1) { + var series = seriesArray[i]; + log$1.debug2("handleFigureUpdated updating series", series.name); + var { + sources + } = series; + for (var j = 0; j < sources.length; j += 1) { + var source = sources[j]; + var { + columnType, + type + } = source; + var valueTranslator = this.getValueTranslator(columnType, this.formatter); + var dataArray = figureUpdateEvent.getArray(series, type, valueTranslator); + this.setDataArrayForSeries(series, type, dataArray); + } + this.seriesToProcess.delete(series.name); + this.cleanSeries(series); + } + if (this.seriesToProcess.size === 0) { + this.fireLoadFinished(); + } + var { + data + } = this; + this.fireUpdate(data); + } + handleRequestFailed(event) { + log$1.error("Request failed", event); + this.fireError(["".concat(event.detail)]); + } + /** + * Resubscribe to the figure, should be done if settings change + */ + resubscribe() { + if (this.listeners.length > 0) { + this.unsubscribeFigure(); + this.subscribeFigure(); + } + } + setFormatter(formatter) { + super.setFormatter(formatter); + this.updateLayoutFormats(); + this.resubscribe(); + } + setRenderOptions(renderOptions) { + super.setRenderOptions(renderOptions); + this.initAllSeries(); + } + setDownsamplingDisabled(isDownsamplingDisabled) { + super.setDownsamplingDisabled(isDownsamplingDisabled); + this.resubscribe(); + } + handleFigureDisconnected(event) { + log$1.debug("Figure disconnected", event); + this.isConnected = false; + if (this.listeners.length > 0) { + this.unsubscribeFigure(); + } + this.fireDisconnect(); + } + handleFigureReconnected(event) { + log$1.debug("Figure reconnected", event); + this.isConnected = true; + this.initAllSeries(); + this.fireReconnect(); + if (this.listeners.length > 0) { + this.subscribeFigure(); + } + } + handleFigureSeriesAdded(event) { + var { + detail: series + } = event; + log$1.debug("handleFigureSeriesAdded", series); + this.pendingSeries.push(series); + this.addPendingSeries(); + } + setDimensions(rect) { + super.setDimensions(rect); + this.updateAxisPositions(); + } + setTitle(title) { + var _match$length, _match; + super.setTitle(title); + var subtitleCount = (_match$length = (_match = (title !== null && title !== void 0 ? title : "").match(/
/g)) === null || _match === void 0 ? void 0 : _match.length) !== null && _match$length !== void 0 ? _match$length : 0; + var margin = ChartUtils.DEFAULT_MARGIN.t + subtitleCount * ChartUtils.SUBTITLE_LINE_HEIGHT; + if (this.layout.margin) { + this.layout.margin.t = margin; + } else { + this.layout.margin = { + t: margin + }; + } + if (typeof this.layout.title === "string") { + this.layout.title = title; + } else { + this.layout.title = _objectSpread({}, this.layout.title); + this.layout.title.text = title; + this.layout.title.pad = _objectSpread({}, this.layout.title.pad); + this.layout.title.pad.t = ChartUtils.DEFAULT_TITLE_PADDING.t + subtitleCount * ChartUtils.SUBTITLE_LINE_HEIGHT * 0.5; + } + this.fireLayoutUpdated({ + title: this.layout.title + }); + } + getPlotWidth() { + var _this$layout$margin$l, _this$layout$margin, _this$layout$margin$r, _this$layout$margin2; + if (!this.rect || !this.rect.width) { + return 0; + } + return Math.max(this.rect.width - ((_this$layout$margin$l = (_this$layout$margin = this.layout.margin) === null || _this$layout$margin === void 0 ? void 0 : _this$layout$margin.l) !== null && _this$layout$margin$l !== void 0 ? _this$layout$margin$l : 0) - ((_this$layout$margin$r = (_this$layout$margin2 = this.layout.margin) === null || _this$layout$margin2 === void 0 ? void 0 : _this$layout$margin2.r) !== null && _this$layout$margin$r !== void 0 ? _this$layout$margin$r : 0), 0); + } + getPlotHeight() { + var _this$layout$margin$t, _this$layout$margin3, _this$layout$margin$b, _this$layout$margin4; + if (!this.rect || !this.rect.height) { + return 0; + } + return Math.max(this.rect.height - ((_this$layout$margin$t = (_this$layout$margin3 = this.layout.margin) === null || _this$layout$margin3 === void 0 ? void 0 : _this$layout$margin3.t) !== null && _this$layout$margin$t !== void 0 ? _this$layout$margin$t : 0) - ((_this$layout$margin$b = (_this$layout$margin4 = this.layout.margin) === null || _this$layout$margin4 === void 0 ? void 0 : _this$layout$margin4.b) !== null && _this$layout$margin$b !== void 0 ? _this$layout$margin$b : 0), 0); + } + updateAxisPositions() { + var plotWidth = this.getPlotWidth(); + var plotHeight = this.getPlotHeight(); + this.chartUtils.updateFigureAxes(this.layout, this.figure, (chart) => this.getAxisRangeParser(chart, this.formatter), plotWidth, plotHeight); + } + /** + * Updates the format patterns used + */ + updateLayoutFormats() { + if (!this.formatter) { + return; + } + var axisFormats = this.chartUtils.getAxisFormats(this.figure, this.formatter); + axisFormats.forEach((axisFormat, axisLayoutProperty) => { + log$1.debug("Assigning ".concat(axisLayoutProperty), this.layout[axisLayoutProperty], axisFormat); + var props = this.layout[axisLayoutProperty]; + if (props != null) { + Object.assign(props, axisFormat); + } else { + log$1.debug("Ignoring null layout.".concat(axisLayoutProperty)); + } + }); + } + /** + * Set a specific array for the array of series properties specified. + * @param series The series to set the data array for. + * @param sourceType The source type within that series to set the data for. + * @param dataArray The array to use for the data for this series source. + */ + setDataArrayForSeries(series, sourceType, dataArray) { + var { + name, + plotStyle + } = series; + var seriesData = this.seriesDataMap.get(name); + var property = this.chartUtils.getPlotlyProperty(plotStyle, sourceType); + if (seriesData) { + lodashExports.set(seriesData, property, dataArray); + } + } + /** + * After setting all the data in the series data, we may need to adjust some other properties + * Eg. Calculating the width from the xLow/xHigh values; Plot.ly uses `width` instead of a low/high + * value for x. + * @param series The series to clean the data for + */ + cleanSeries(series) { + var { + dh + } = this; + var { + name, + plotStyle + } = series; + var seriesData = this.seriesDataMap.get(name); + if (seriesData == null) { + return; + } + if (plotStyle === dh.plot.SeriesPlotStyle.HISTOGRAM) { + var { + xLow, + xHigh + } = seriesData; + if (xLow && xHigh && xLow.length === xHigh.length) { + var width = []; + for (var i = 0; i < xLow.length; i += 1) { + width.push(xHigh[i] - xLow[i]); + } + seriesData.width = width; + } + } else if (plotStyle === dh.plot.SeriesPlotStyle.LINE || plotStyle === dh.plot.SeriesPlotStyle.ERROR_BAR || plotStyle === dh.plot.SeriesPlotStyle.BAR) { + var { + x, + xLow: _xLow, + xHigh: _xHigh, + y, + yLow, + yHigh + } = seriesData; + if (_xLow && _xHigh && _xLow !== x) { + seriesData.error_x = ChartUtils.getPlotlyErrorBars(x, _xLow, _xHigh); + } + if (yLow && yHigh && yLow !== y) { + seriesData.error_y = ChartUtils.getPlotlyErrorBars(y, yLow, yHigh); + } + } else if (plotStyle === dh.plot.SeriesPlotStyle.TREEMAP) { + var { + ids, + labels + } = seriesData; + if (ids !== void 0 && labels === void 0) { + seriesData.labels = ids; + } + } + } + getData() { + return this.data; + } + getLayout() { + return this.layout; + } + getFilterColumnMap() { + return new Map(this.filterColumnMap); + } + isFilterRequired() { + return this.oneClicks.find((oneClick) => oneClick.requireAllFiltersToDisplay) != null; + } + /** + * Sets the filter on the model. Will only set the values that have changed. + * @param filterMap Map of filter column names to values + */ + setFilter(filterMap) { + var _this3 = this; + if (this.oneClicks.length === 0) { + log$1.warn("Trying to set a filter, but no one click!"); + return; + } + log$1.debug("setFilter", filterMap); + var _loop3 = function _loop32() { + var oneClick = _this3.oneClicks[i]; + var { + columns + } = oneClick; + var keys2 = /* @__PURE__ */ new Set([...filterMap.keys(), ..._this3.lastFilter.keys()]); + keys2.forEach((key) => { + var value2 = filterMap.get(key); + if (_this3.lastFilter.get(key) !== value2 && columns.find((column) => column.name === key) != null) { + oneClick.setValueForColumn(key, value2); + } + }); + }; + for (var i = 0; i < this.oneClicks.length; i += 1) { + _loop3(); + } + this.lastFilter = new Map(filterMap); + } + setFigure(figure) { + this.close(); + this.figure = figure; + this.setTitle(this.getDefaultTitle()); + this.initAllSeries(); + this.updateAxisPositions(); + this.startListeningFigure(); + if (this.listeners.length > 0) { + this.subscribeFigure(); + } + } + updateSettings(settings) { + this.settings = settings; + } +} +_defineProperty(FigureChartModel, "ADD_SERIES_DEBOUNCE", 50); +function asyncGeneratorStep(n2, t, e, r, o, a, c) { + try { + var i = n2[a](c), u = i.value; + } catch (n3) { + return void e(n3); + } + i.done ? t(u) : Promise.resolve(u).then(r, o); +} +function _asyncToGenerator(n2) { + return function() { + var t = this, e = arguments; + return new Promise(function(r, o) { + var a = n2.apply(t, e); + function _next(n3) { + asyncGeneratorStep(a, r, o, _next, _throw, "next", n3); + } + function _throw(n3) { + asyncGeneratorStep(a, r, o, _next, _throw, "throw", n3); + } + _next(void 0); + }); + }; +} +class ChartModelFactory { + /** + * Creates a model from the settings provided. + * Tries to create a Figure in the API with it. + * @param dh JSAPI instance + * @param settings The chart builder settings + * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated + * @param settings.series The column names to use for creating the series of this chart + * @param settings.type Chart builder type, from ChartBuilder.types + * @param settings.xAxis The column name to use for the x-axis + * @param [settings.hiddenSeries] Array of hidden series names + * @param table The table to build the model for + * @returns The ChartModel Promise representing the figure + * CRA sets tsconfig to type check JS based on jsdoc comments. It isn't able to figure out FigureChartModel extends ChartModel + * This causes TS issues in 1 or 2 spots. Once this is TS it can be returned to just FigureChartModel + */ + static makeModelFromSettings(dh, settings, table) { + return _asyncToGenerator(function* () { + var figure = yield ChartModelFactory.makeFigureFromSettings(dh, settings, table); + return new FigureChartModel(dh, figure, settings); + })(); + } + /** + * Creates a model from the settings provided. + * Tries to create a Figure in the API with it. + * @param dh DH JSAPI instance + * @param settings The chart builder settings + * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated + * @param settings.series The column names to use for creating the series of this chart + * @param settings.type Chart builder type, from ChartBuilder.types + * @param settings.xAxis The column name to use for the x-axis + * @param [settings.hiddenSeries] Array of hidden series names + * @param table The table to build the model for + * @returns The Figure created with the settings provided + */ + static makeFigureFromSettings(dh, settings, table) { + return _asyncToGenerator(function* () { + var tableCopy = yield table.copy(); + tableCopy.applyCustomColumns(table.customColumns); + tableCopy.applyFilter(table.filter); + tableCopy.applySort(table.sort); + return dh.plot.Figure.create(new ChartUtils(dh).makeFigureSettings(settings, tableCopy)); + })(); + } + /** + * Creates a model from the settings provided. + * Tries to create a Figure in the API with it. + * @param dh DH JSAPI instance + * @param settings The chart builder settings + * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated + * @param settings.series The column names to use for creating the series of this chart + * @param settings.type Chart builder type, from ChartBuilder.types + * @param settings.xAxis The column name to use for the x-axis + * @param [settings.hiddenSeries] Array of hidden series names + * @param figure The figure to build the model for + * @returns The FigureChartModel representing the figure + * CRA sets tsconfig to type check JS based on jsdoc comments. It isn't able to figure out FigureChartModel extends ChartModel + * This causes TS issues in 1 or 2 spots. Once this is TS it can be returned to just FigureChartModel + */ + static makeModel(dh, settings, figure) { + return _asyncToGenerator(function* () { + return new FigureChartModel(dh, figure, settings); + })(); + } +} +Log.module("@deephaven/jsapi-bootstrap.ApiBootstrap"); +var ApiContext = /* @__PURE__ */ React.createContext(null); +function useContextOrThrow(context) { + var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "No value available in context. Was code wrapped in a provider?"; + var value2 = React.useContext(context); + if (value2 == null) { + throw new Error(message); + } + return value2; +} +function useApi() { + return useContextOrThrow(ApiContext, "No API available in useApi. Was code wrapped in ApiBootstrap or ApiContext.Provider?"); +} +const log = Log.module("@deephaven/js-plugin-grid-toolbar"); +const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; +function GridToolbarPanelMiddleware({ + Component, + fetch, + glEventHub, + ...props +}) { + const dh = useApi(); + const [view, setView] = React.useState("grid"); + const [chartModel, setChartModel] = React.useState(null); + const [isBuilding, setIsBuilding] = React.useState(false); + React.useEffect( + () => () => { + chartModel == null ? void 0 : chartModel.close(); + }, + [chartModel] + ); + const handleChart = React.useCallback(async () => { + if (view === "chart") { + setView("grid"); + return; + } + setIsBuilding(true); + try { + const table = await fetch(); + if (!(table == null ? void 0 : table.columns) || table.columns.length < 2) { + log.warn("Table has fewer than 2 columns; cannot build chart"); + return; + } + const settings = { + type: "LINE", + series: [table.columns[1].name], + xAxis: table.columns[0].name + }; + const model = await ChartModelFactory.makeModelFromSettings( + dh, + settings, + table + ); + setChartModel(model); + setView("chart"); + } catch (e) { + log.error("Failed to build chart model", e); + } finally { + setIsBuilding(false); + } + }, [dh, fetch, view]); + const handleResetFilters = React.useCallback(() => { + log.info("Reset Filters clicked"); + glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); + }, [glEventHub]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + disabled: isBuilding, + onClick: handleChart, + children: view === "chart" ? "Grid" : "Chart" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === "chart" && chartModel != null ? ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + /* @__PURE__ */ jsxRuntimeExports.jsx(LazyChart, { model: chartModel, className: "h-100 w-100" }) + ) : ( + // eslint-disable-next-line react/jsx-props-no-spreading + /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { fetch, glEventHub, ...props }) + ) }) + ] }); +} +const GridToolbarPlugin = { + name: "@deephaven/js-plugin-grid-toolbar", + type: plugin.PluginType.WIDGET_PLUGIN, + supportedTypes: [ + "Table", + "TreeTable", + "HierarchicalTable", + "PartitionedTable" + ], + component: GridToolbarMiddleware, + panelComponent: GridToolbarPanelMiddleware, + isMiddleware: true +}; +exports.ChartModel = ChartModel; +exports.ChartUtils = ChartUtils; +exports.DateUtils = DateUtils; +exports.GridToolbarMiddleware = GridToolbarMiddleware; +exports.GridToolbarPlugin = GridToolbarPlugin; +exports.TableUtils = TableUtils; +exports.assertInstanceOf = assertInstanceOf; +exports.assign = assign$1; +exports.bindAllMethods = bindAllMethods; +exports.commonjsGlobal = commonjsGlobal; +exports.contains = contains$1; +exports.dExports = dExports; +exports.getAugmentedNamespace = getAugmentedNamespace; +exports.getDefaultExportFromCjs = getDefaultExportFromCjs; +exports.is = is$4; +exports.is$1 = is$3; +exports.is$2 = is; +exports.isObject = isObject$1; +exports.isValue = isValue$6; +exports.jsxRuntimeExports = jsxRuntimeExports; +exports.normalizeOptions = normalizeOptions; +exports.objectAssign = objectAssign; +exports.requireEs6Symbol = requireEs6Symbol; +exports.requireFrom = requireFrom; +exports.requireIsArguments = requireIsArguments; +exports.requireIsString = requireIsString; +exports.requireMap = requireMap; +exports.validCallable = validCallable; +exports.validValue = validValue; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js index c7c58819f..fbd8c36ae 100644 --- a/plugins/grid-toolbar/src/js/dist/bundle/index.js +++ b/plugins/grid-toolbar/src/js/dist/bundle/index.js @@ -1,195 +1,6 @@ "use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); -const plugin = require("@deephaven/plugin"); -const require$$1 = require("react"); -const Log = require("@deephaven/log"); -var jsxRuntime = { exports: {} }; -var reactJsxRuntime_production_min = {}; -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; -function toObject(val) { - if (val === null || val === void 0) { - throw new TypeError("Object.assign cannot be called with null or undefined"); - } - return Object(val); -} -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - var test1 = new String("abc"); - test1[5] = "de"; - if (Object.getOwnPropertyNames(test1)[0] === "5") { - return false; - } - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2["_" + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { - return test2[n2]; - }); - if (order2.join("") !== "0123456789") { - return false; - } - var test3 = {}; - "abcdefghijklmnopqrst".split("").forEach(function(letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { - return false; - } - return true; - } catch (err) { - return false; - } -} -shouldUseNative() ? Object.assign : function(target, source) { - var from; - var to = toObject(target); - var symbols; - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - return to; -}; -/** @license React v17.0.2 - * react-jsx-runtime.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var f = require$$1, g = 60103; -reactJsxRuntime_production_min.Fragment = 60107; -if ("function" === typeof Symbol && Symbol.for) { - var h = Symbol.for; - g = h("react.element"); - reactJsxRuntime_production_min.Fragment = h("react.fragment"); -} -var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; -function q(c, a, k) { - var b, d = {}, e = null, l = null; - void 0 !== k && (e = "" + k); - void 0 !== a.key && (e = "" + a.key); - void 0 !== a.ref && (l = a.ref); - for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); - if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); - return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; -} -reactJsxRuntime_production_min.jsx = q; -reactJsxRuntime_production_min.jsxs = q; -{ - jsxRuntime.exports = reactJsxRuntime_production_min; -} -var jsxRuntimeExports = jsxRuntime.exports; -const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar"); -function GridToolbarMiddleware({ - Component, - ...props -}) { - const handleExport = require$$1.useCallback(() => { - log$1.info("Export clicked"); - }, []); - const handleResetFilters = require$$1.useCallback(() => { - log$1.info("[0] Reset Filters clicked", props, Component); - }, [props, Component]); - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleExport, - children: "Export" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) - ] }); -} -const log = Log.module("@deephaven/js-plugin-grid-toolbar"); -const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; -function GridToolbarPanelMiddleware({ - Component, - glEventHub, - ...props -}) { - const handleExport = require$$1.useCallback(() => { - log.info("Export clicked"); - }, []); - const handleResetFilters = require$$1.useCallback(() => { - log.info("[0] Reset Filters clicked", props, Component); - glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub, props, Component]); - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleExport, - children: "Export" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { glEventHub, ...props }) }) - ] }); -} -const GridToolbarPlugin = { - name: "@deephaven/js-plugin-grid-toolbar", - type: plugin.PluginType.WIDGET_PLUGIN, - supportedTypes: [ - "Table", - "TreeTable", - "HierarchicalTable", - "PartitionedTable" - ], - component: GridToolbarMiddleware, - panelComponent: GridToolbarPanelMiddleware, - isMiddleware: true -}; -exports.GridToolbarMiddleware = GridToolbarMiddleware; -exports.GridToolbarPlugin = GridToolbarPlugin; -exports.default = GridToolbarPlugin; +const index = require("./index-nioU_Oes.cjs"); +exports.GridToolbarMiddleware = index.GridToolbarMiddleware; +exports.GridToolbarPlugin = index.GridToolbarPlugin; +exports.default = index.GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/style.css b/plugins/grid-toolbar/src/js/dist/bundle/style.css new file mode 100644 index 000000000..0edc904dd --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/bundle/style.css @@ -0,0 +1,88 @@ +.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}.maplibregl-ctrl button:not(:disabled):hover{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgb(0 0 0/5%)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(width <= 480px){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999}/* stylelint-disable scss/at-import-no-partial-leading-underscore */ +/* stylelint-disable-next-line number-max-precision */ +.chart-error-overlay .chart-error-overlay-content .btn { + margin-top: 1rem; + margin-right: 1rem; +} +.chart-error-overlay .chart-error-overlay-content .info-message, +.chart-error-overlay .chart-error-overlay-content .waiting-filter-list { + text-align: left; +} + +/*# sourceMappingURL=ChartErrorOverlay.css.map */ +/* stylelint-disable scss/at-import-no-partial-leading-underscore */ +/* stylelint-disable-next-line number-max-precision */ +.plotly-notifier { + margin-right: 15px; +} + +.plotly-notifier .notifier-note { + color: var(--dh-color-fg, #f0f0ee) !important; + border: 0 !important; + border-radius: 2px !important; + background: var(--dh-color-plotly-notifier-note-bg) !important; + overflow-wrap: normal !important; + hyphens: unset !important; + margin-bottom: 0.5rem !important; + box-shadow: 0 0.1rem 1rem var(--dh-color-dropshadow) !important; +} + +.plotly-notifier .notifier-close { + color: var(--dh-color-gray-600) !important; + transition: all 0.2s ease-in-out !important; +} +.plotly-notifier .notifier-close:hover { + color: var(--dh-color-fg, #f0f0ee) !important; +} + +.chart-wrapper { + background: var(--dh-color-chart-bg); +} +.chart-wrapper .plot-container .cartesianlayer text { + user-select: none; +} +.chart-wrapper .plot-container .hovertext path, +.chart-wrapper .plot-container .axistext path { + stroke: none !important; +} +.chart-wrapper .plot-container .axistext path { + fill: var(--dh-color-plotly-axis-text) !important; + box-shadow: 4px 4px var(--dh-color-black); +} +.chart-wrapper .plot-container .zoomlayer .zoombox { + fill: var(--dh-color-plotly-zoombox) !important; +} +.chart-wrapper .plot-container .zoomlayer .zoombox-corners { + fill: var(--dh-color-plotly-zoombox-corners-fill); + stroke: var(--dh-color-plotly-zoombox-corners-stroke); +} +.chart-wrapper .js-plotly-plot .plotly [data-title]::before { + border-color: transparent transparent var(--dh-color-tooltip-bg); + z-index: 1002; +} +.chart-wrapper .js-plotly-plot .plotly [data-title]::after { + border-radius: 4px; + background: var(--dh-color-tooltip-bg); + color: var(--dh-color-tooltip-fg); + padding: 0.25rem 0.5rem; + box-shadow: var(--dh-color-tooltip-box-shadow); + z-index: 1001; +} +.chart-wrapper .js-plotly-plot .plotly .modebar { + z-index: auto; +} +.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=animation-spin] svg { + animation: fa-spin 2s infinite linear; +} +.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=fill-active] svg path { + fill: var(--dh-color-plotly-modebar-btn-active) !important; +} +.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=fill-warning] svg path { + fill: var(--dh-color-plotly-modebar-btn-warning) !important; +} + +.chart-error-popper .popper-content { + padding: 0.25rem; +} + +/*# sourceMappingURL=Chart.css.map */ diff --git a/plugins/grid-toolbar/src/js/package.json b/plugins/grid-toolbar/src/js/package.json index d535a52f3..3805b2095 100644 --- a/plugins/grid-toolbar/src/js/package.json +++ b/plugins/grid-toolbar/src/js/package.json @@ -47,8 +47,10 @@ "react-dom": "^17.0.2 || ^18.0.0 || ^19.0.0" }, "dependencies": { + "@deephaven/chart": "^0.106.0", "@deephaven/components": "^0.106.0", "@deephaven/icons": "^0.106.0", + "@deephaven/jsapi-bootstrap": "^0.106.0", "@deephaven/log": "^0.106.2", "@deephaven/plugin": "^0.106.4" }, diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index 215fdf93b..5eed4f9fa 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -1,4 +1,6 @@ -import { useCallback } from 'react'; +import { useCallback, useEffect, useState } from 'react'; +import { Chart, type ChartModel, ChartModelFactory } from '@deephaven/chart'; +import { useApi } from '@deephaven/jsapi-bootstrap'; import Log from '@deephaven/log'; // TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; @@ -10,17 +12,59 @@ const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; export function GridToolbarPanelMiddleware({ Component, + fetch, glEventHub, ...props }: WidgetMiddlewarePanelProps): JSX.Element { - const handleExport = useCallback(() => { - log.info('Export clicked'); - }, []); + const dh = useApi(); + const [view, setView] = useState<'grid' | 'chart'>('grid'); + const [chartModel, setChartModel] = useState(null); + const [isBuilding, setIsBuilding] = useState(false); + + useEffect( + () => () => { + chartModel?.close(); + }, + [chartModel] + ); + + const handleChart = useCallback(async () => { + if (view === 'chart') { + setView('grid'); + return; + } + setIsBuilding(true); + try { + // fetch is typed as () => Promise; for grid widgets it returns dh.Table + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const table = (await fetch()) as any; + if (!table?.columns || table.columns.length < 2) { + log.warn('Table has fewer than 2 columns; cannot build chart'); + return; + } + const settings = { + type: 'LINE' as const, + series: [table.columns[1].name as string], + xAxis: table.columns[0].name as string, + }; + const model = await ChartModelFactory.makeModelFromSettings( + dh, + settings, + table + ); + setChartModel(model); + setView('chart'); + } catch (e) { + log.error('Failed to build chart model', e); + } finally { + setIsBuilding(false); + } + }, [dh, fetch, view]); const handleResetFilters = useCallback(() => { - log.info('[0] Reset Filters clicked', props, Component); + log.info('Reset Filters clicked'); glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub, props, Component]); + }, [glEventHub]); return (
@@ -28,9 +72,10 @@ export function GridToolbarPanelMiddleware({
- {/* eslint-disable-next-line react/jsx-props-no-spreading */} - + {view === 'chart' && chartModel != null ? ( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + + ) : ( + // eslint-disable-next-line react/jsx-props-no-spreading + + )}
); diff --git a/plugins/grid-toolbar/src/js/vite.config.ts b/plugins/grid-toolbar/src/js/vite.config.ts index c6120d13a..aeb899f36 100644 --- a/plugins/grid-toolbar/src/js/vite.config.ts +++ b/plugins/grid-toolbar/src/js/vite.config.ts @@ -16,8 +16,10 @@ export default defineConfig(({ mode }) => ({ external: [ 'react', 'react-dom', + '@deephaven/chart', '@deephaven/components', '@deephaven/icons', + '@deephaven/jsapi-bootstrap', '@deephaven/log', '@deephaven/plugin', ], From 25b891d9aa944c24b82880bb7c771bf08199db14 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 12:15:13 -0600 Subject: [PATCH 03/11] WIP --- package-lock.json | 278 +- plugins/grid-toolbar/README.md | 36 + plugins/grid-toolbar/src/js/.gitignore | 0 .../src/js/dist/GridToolbarMiddleware.d.ts | 4 + .../js/dist/GridToolbarMiddleware.d.ts.map | 1 + .../src/js/dist/GridToolbarMiddleware.js | 27 + .../src/js/dist/GridToolbarMiddleware.js.map | 1 + .../js/dist/GridToolbarPanelMiddleware.d.ts | 4 + .../dist/GridToolbarPanelMiddleware.d.ts.map | 1 + .../src/js/dist/GridToolbarPanelMiddleware.js | 72 + .../js/dist/GridToolbarPanelMiddleware.js.map | 1 + .../src/js/dist/GridToolbarPlugin.d.ts | 4 + .../src/js/dist/GridToolbarPlugin.d.ts.map | 1 + .../src/js/dist/GridToolbarPlugin.js | 18 + .../src/js/dist/GridToolbarPlugin.js.map | 1 + .../src/js/dist/bundle/Chart-DElXbH_b.cjs | 90838 ---------------- .../src/js/dist/bundle/index-nioU_Oes.cjs | 12476 --- .../grid-toolbar/src/js/dist/bundle/index.js | 243 +- .../grid-toolbar/src/js/dist/bundle/style.css | 88 - plugins/grid-toolbar/src/js/dist/index.d.ts | 5 + .../grid-toolbar/src/js/dist/index.d.ts.map | 1 + plugins/grid-toolbar/src/js/dist/index.js | 5 + plugins/grid-toolbar/src/js/dist/index.js.map | 1 + .../src/js/dist/middlewareTypes.d.ts | 31 + .../src/js/dist/middlewareTypes.d.ts.map | 1 + .../src/js/dist/middlewareTypes.js | 2 + .../src/js/dist/middlewareTypes.js.map | 1 + .../src/js/src/GridToolbarPanelMiddleware.tsx | 12 +- 28 files changed, 582 insertions(+), 103571 deletions(-) create mode 100644 plugins/grid-toolbar/README.md create mode 100644 plugins/grid-toolbar/src/js/.gitignore create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js create mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map delete mode 100644 plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs delete mode 100644 plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs delete mode 100644 plugins/grid-toolbar/src/js/dist/bundle/style.css create mode 100644 plugins/grid-toolbar/src/js/dist/index.d.ts create mode 100644 plugins/grid-toolbar/src/js/dist/index.d.ts.map create mode 100644 plugins/grid-toolbar/src/js/dist/index.js create mode 100644 plugins/grid-toolbar/src/js/dist/index.js.map create mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts create mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map create mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.js create mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map diff --git a/package-lock.json b/package-lock.json index 9ed7d4f1e..0658e561c 100644 --- a/package-lock.json +++ b/package-lock.json @@ -208,6 +208,7 @@ "version": "7.26.10", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@ampproject/remapping": "^2.2.0", "@babel/code-frame": "^7.26.2", @@ -758,6 +759,7 @@ "version": "7.26.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/helper-plugin-utils": "^7.25.9" }, @@ -1551,6 +1553,7 @@ "version": "7.25.9", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@babel/helper-annotate-as-pure": "^7.25.9", "@babel/helper-module-imports": "^7.25.9", @@ -2059,7 +2062,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -4830,6 +4832,7 @@ "node_modules/@dnd-kit/core": { "version": "6.3.1", "license": "MIT", + "peer": true, "dependencies": { "@dnd-kit/accessibility": "^3.1.1", "@dnd-kit/utilities": "^3.2.2", @@ -4866,7 +4869,6 @@ "version": "4.1.0", "dev": true, "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" @@ -5390,6 +5392,7 @@ "node_modules/@fortawesome/fontawesome-svg-core": { "version": "6.7.2", "license": "MIT", + "peer": true, "dependencies": { "@fortawesome/fontawesome-common-types": "6.7.2" }, @@ -5400,6 +5403,7 @@ "node_modules/@fortawesome/react-fontawesome": { "version": "0.2.2", "license": "MIT", + "peer": true, "dependencies": { "prop-types": "^15.8.1" }, @@ -6425,7 +6429,6 @@ "node_modules/@jridgewell/source-map": { "version": "0.3.6", "license": "MIT", - "peer": true, "dependencies": { "@jridgewell/gen-mapping": "^0.3.5", "@jridgewell/trace-mapping": "^0.3.25" @@ -6447,7 +6450,6 @@ "version": "1.0.3", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "buffer": "^6.0.3" } @@ -7919,6 +7921,7 @@ "integrity": "sha512-/g2d4sW9nUDJOMz3mabVQvOGhVa4e/BN/Um7yca9Bb2XTzPPnfTWHWQg+IsEYO7M3Vx+EXvaM/I2pJWIMun1bg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@octokit/auth-token": "^4.0.0", "@octokit/graphql": "^7.1.0", @@ -8167,9 +8170,6 @@ "arm" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -8191,9 +8191,6 @@ "arm" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -8215,9 +8212,6 @@ "arm64" ], "dev": true, - "libc": [ - "glibc" - ], "license": "MIT", "optional": true, "os": [ @@ -8239,9 +8233,6 @@ "arm64" ], "dev": true, - "libc": [ - "musl" - ], "license": "MIT", "optional": true, "os": [ @@ -8369,7 +8360,6 @@ "version": "0.1.1", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": "^12.20.0 || ^14.18.0 || >=16.0.0" }, @@ -10157,6 +10147,7 @@ "node_modules/@react-spectrum/provider": { "version": "3.10.3", "license": "Apache-2.0", + "peer": true, "dependencies": { "@react-aria/i18n": "^3.12.7", "@react-aria/overlays": "^3.26.1", @@ -12450,7 +12441,6 @@ "node_modules/@types/eslint": { "version": "9.6.1", "license": "MIT", - "peer": true, "dependencies": { "@types/estree": "*", "@types/json-schema": "*" @@ -12459,7 +12449,6 @@ "node_modules/@types/eslint-scope": { "version": "3.7.7", "license": "MIT", - "peer": true, "dependencies": { "@types/eslint": "*", "@types/estree": "*" @@ -12663,6 +12652,7 @@ "node_modules/@types/node": { "version": "20.17.24", "license": "MIT", + "peer": true, "dependencies": { "undici-types": "~6.19.2" } @@ -12704,6 +12694,7 @@ "node_modules/@types/react": { "version": "17.0.83", "license": "MIT", + "peer": true, "dependencies": { "@types/prop-types": "*", "@types/scheduler": "^0.16", @@ -12860,6 +12851,7 @@ "version": "5.62.0", "dev": true, "license": "BSD-2-Clause", + "peer": true, "dependencies": { "@typescript-eslint/scope-manager": "5.62.0", "@typescript-eslint/types": "5.62.0", @@ -13044,7 +13036,6 @@ "node_modules/@webassemblyjs/ast": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/helper-numbers": "1.13.2", "@webassemblyjs/helper-wasm-bytecode": "1.13.2" @@ -13052,23 +13043,19 @@ }, "node_modules/@webassemblyjs/floating-point-hex-parser": { "version": "1.13.2", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-api-error": { "version": "1.13.2", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-buffer": { "version": "1.14.1", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-numbers": { "version": "1.13.2", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/floating-point-hex-parser": "1.13.2", "@webassemblyjs/helper-api-error": "1.13.2", @@ -13077,13 +13064,11 @@ }, "node_modules/@webassemblyjs/helper-wasm-bytecode": { "version": "1.13.2", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/helper-wasm-section": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -13094,7 +13079,6 @@ "node_modules/@webassemblyjs/ieee754": { "version": "1.13.2", "license": "MIT", - "peer": true, "dependencies": { "@xtuc/ieee754": "^1.2.0" } @@ -13102,20 +13086,17 @@ "node_modules/@webassemblyjs/leb128": { "version": "1.13.2", "license": "Apache-2.0", - "peer": true, "dependencies": { "@xtuc/long": "4.2.2" } }, "node_modules/@webassemblyjs/utf8": { "version": "1.13.2", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/@webassemblyjs/wasm-edit": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -13130,7 +13111,6 @@ "node_modules/@webassemblyjs/wasm-gen": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-wasm-bytecode": "1.13.2", @@ -13142,7 +13122,6 @@ "node_modules/@webassemblyjs/wasm-opt": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-buffer": "1.14.1", @@ -13153,7 +13132,6 @@ "node_modules/@webassemblyjs/wasm-parser": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@webassemblyjs/helper-api-error": "1.13.2", @@ -13166,7 +13144,6 @@ "node_modules/@webassemblyjs/wast-printer": { "version": "1.14.1", "license": "MIT", - "peer": true, "dependencies": { "@webassemblyjs/ast": "1.14.1", "@xtuc/long": "4.2.2" @@ -13174,13 +13151,11 @@ }, "node_modules/@xtuc/ieee754": { "version": "1.2.0", - "license": "BSD-3-Clause", - "peer": true + "license": "BSD-3-Clause" }, "node_modules/@xtuc/long": { "version": "4.2.2", - "license": "Apache-2.0", - "peer": true + "license": "Apache-2.0" }, "node_modules/@yarnpkg/lockfile": { "version": "1.1.0", @@ -13259,6 +13234,7 @@ "node_modules/acorn": { "version": "8.14.1", "license": "MIT", + "peer": true, "bin": { "acorn": "bin/acorn" }, @@ -13423,7 +13399,6 @@ "node_modules/ajv-formats": { "version": "2.1.1", "license": "MIT", - "peer": true, "dependencies": { "ajv": "^8.0.0" }, @@ -13439,7 +13414,6 @@ "node_modules/ajv-formats/node_modules/ajv": { "version": "8.17.1", "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -13453,8 +13427,7 @@ }, "node_modules/ajv-formats/node_modules/json-schema-traverse": { "version": "1.0.0", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/almost-equal": { "version": "1.1.0", @@ -13749,7 +13722,6 @@ "version": "2.0.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -14259,6 +14231,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "caniuse-lite": "^1.0.30001688", "electron-to-chromium": "^1.5.73", @@ -14456,7 +14429,6 @@ "version": "1.8.9", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "hookified": "^1.7.1", "keyv": "^5.3.1" @@ -14466,7 +14438,6 @@ "version": "5.3.2", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@keyv/serialize": "^1.0.3" } @@ -14644,7 +14615,6 @@ "node_modules/chrome-trace-event": { "version": "1.0.4", "license": "MIT", - "peer": true, "engines": { "node": ">=6.0" } @@ -14877,8 +14847,7 @@ "node_modules/colord": { "version": "2.9.3", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/columnify": { "version": "1.6.0", @@ -15305,7 +15274,6 @@ "version": "3.2.3", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=12 || >=16" } @@ -15365,7 +15333,6 @@ "version": "3.1.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "mdn-data": "2.12.2", "source-map-js": "^1.0.1" @@ -16093,29 +16060,6 @@ "dev": true, "license": "MIT" }, - "node_modules/encoding": { - "version": "0.1.13", - "resolved": "https://registry.npmjs.org/encoding/-/encoding-0.1.13.tgz", - "integrity": "sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A==", - "license": "MIT", - "optional": true, - "dependencies": { - "iconv-lite": "^0.6.2" - } - }, - "node_modules/encoding/node_modules/iconv-lite": { - "version": "0.6.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz", - "integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==", - "license": "MIT", - "optional": true, - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - } - }, "node_modules/end-of-stream": { "version": "1.4.4", "license": "MIT", @@ -16126,7 +16070,6 @@ "node_modules/enhanced-resolve": { "version": "5.18.1", "license": "MIT", - "peer": true, "dependencies": { "graceful-fs": "^4.2.4", "tapable": "^2.2.0" @@ -16316,8 +16259,7 @@ }, "node_modules/es-module-lexer": { "version": "1.6.0", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/es-object-atoms": { "version": "1.1.1", @@ -16858,6 +16800,7 @@ "version": "8.57.1", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@eslint-community/eslint-utils": "^4.2.0", "@eslint-community/regexpp": "^4.6.1", @@ -16950,6 +16893,7 @@ "version": "8.3.0", "dev": true, "license": "MIT", + "peer": true, "bin": { "eslint-config-prettier": "bin/cli.js" }, @@ -17007,7 +16951,6 @@ "resolved": "https://registry.npmjs.org/eslint-import-resolver-typescript/-/eslint-import-resolver-typescript-3.5.0.tgz", "integrity": "sha512-DEfpfuk+O/T5e9HBZOxocmwMuUGkvQQd5WRiMJF9kKNT9amByqOyGlWoAZAQiv0SZSy4GMtG1clmnvQA/RzA0A==", "dev": true, - "peer": true, "dependencies": { "debug": "^4.3.4", "enhanced-resolve": "^5.10.0", @@ -17033,7 +16976,6 @@ "resolved": "https://registry.npmjs.org/globby/-/globby-13.2.2.tgz", "integrity": "sha512-Y1zNGV+pzQdh7H39l9zgB4PJqjRNqydvdYCDG4HFXM4XuvSaQQlEc91IU1yALL8gUTDomgBAfz3XJdmUS+oo0w==", "dev": true, - "peer": true, "dependencies": { "dir-glob": "^3.0.1", "fast-glob": "^3.3.0", @@ -17053,7 +16995,6 @@ "resolved": "https://registry.npmjs.org/slash/-/slash-4.0.0.tgz", "integrity": "sha512-3dOsAHXXUkQTpOYcoAxLIorMTp4gIQr5IW3iVb7A7lFIp0VHhnynm9izx6TssdrIcVIESAlVjtnO2K8bg+Coew==", "dev": true, - "peer": true, "engines": { "node": ">=12" }, @@ -17066,7 +17007,6 @@ "resolved": "https://registry.npmjs.org/synckit/-/synckit-0.8.8.tgz", "integrity": "sha512-HwOKAP7Wc5aRGYdKH+dw0PRRpbO841v2DENBtjnR5HFWoiNByAl7vrx3p0G/rCyYXQsrxqtX48TImFtPcIHSpQ==", "dev": true, - "peer": true, "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" @@ -17142,6 +17082,7 @@ "version": "2.31.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@rtsao/scc": "^1.1.0", "array-includes": "^3.1.8", @@ -17216,6 +17157,7 @@ "version": "6.10.2", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "aria-query": "^5.3.2", "array-includes": "^3.1.8", @@ -17282,6 +17224,7 @@ "version": "7.37.4", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "array-includes": "^3.1.8", "array.prototype.findlast": "^1.2.5", @@ -17313,6 +17256,7 @@ "version": "4.6.2", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=10" }, @@ -17393,7 +17337,6 @@ "version": "2.1.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "eslint-visitor-keys": "^1.1.0" }, @@ -17408,7 +17351,6 @@ "version": "1.3.0", "dev": true, "license": "Apache-2.0", - "peer": true, "engines": { "node": ">=4" } @@ -17668,8 +17610,7 @@ "node_modules/fast-diff": { "version": "1.3.0", "dev": true, - "license": "Apache-2.0", - "peer": true + "license": "Apache-2.0" }, "node_modules/fast-glob": { "version": "3.3.3", @@ -17730,14 +17671,12 @@ "url": "https://opencollective.com/fastify" } ], - "license": "BSD-3-Clause", - "peer": true + "license": "BSD-3-Clause" }, "node_modules/fastest-levenshtein": { "version": "1.0.16", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 4.9.1" } @@ -18350,7 +18289,6 @@ "version": "4.10.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "resolve-pkg-maps": "^1.0.0" }, @@ -18537,14 +18475,12 @@ }, "node_modules/glob-to-regexp": { "version": "0.4.1", - "license": "BSD-2-Clause", - "peer": true + "license": "BSD-2-Clause" }, "node_modules/global-modules": { "version": "2.0.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "global-prefix": "^3.0.0" }, @@ -18556,7 +18492,6 @@ "version": "3.0.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ini": "^1.3.5", "kind-of": "^6.0.2", @@ -18570,7 +18505,6 @@ "version": "1.3.1", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "isexe": "^2.0.0" }, @@ -18662,8 +18596,7 @@ "node_modules/globjoin": { "version": "0.1.4", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/glsl-inject-defines": { "version": "1.0.3", @@ -19133,8 +19066,7 @@ "node_modules/hookified": { "version": "1.8.1", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/hosted-git-info": { "version": "9.0.2", @@ -19182,7 +19114,6 @@ "version": "3.3.1", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" }, @@ -19833,7 +19764,6 @@ "version": "5.0.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -20165,6 +20095,7 @@ "version": "29.7.0", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "@jest/core": "^29.7.0", "@jest/types": "^29.6.3", @@ -21208,7 +21139,8 @@ }, "node_modules/jquery": { "version": "3.7.1", - "license": "MIT" + "license": "MIT", + "peer": true }, "node_modules/js-cookie": { "version": "3.0.5", @@ -21529,8 +21461,7 @@ "node_modules/known-css-properties": { "version": "0.35.0", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/language-subtag-registry": { "version": "0.3.23", @@ -22146,7 +22077,6 @@ "node_modules/loader-runner": { "version": "4.3.0", "license": "MIT", - "peer": true, "engines": { "node": ">=6.11.5" } @@ -22214,8 +22144,7 @@ "node_modules/lodash.truncate": { "version": "4.4.2", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/log-symbols": { "version": "4.1.0", @@ -22500,7 +22429,6 @@ "version": "2.1.3", "dev": true, "license": "MIT", - "peer": true, "funding": { "type": "github", "url": "https://github.com/sponsors/wooorm" @@ -22722,8 +22650,7 @@ "node_modules/mdn-data": { "version": "2.12.2", "dev": true, - "license": "CC0-1.0", - "peer": true + "license": "CC0-1.0" }, "node_modules/memoize-one": { "version": "5.2.1", @@ -24670,6 +24597,7 @@ "dev": true, "hasInstallScript": true, "license": "MIT", + "peer": true, "dependencies": { "@napi-rs/wasm-runtime": "0.2.4", "@yarnpkg/lockfile": "^1.1.0", @@ -25833,6 +25761,7 @@ "node_modules/plotly.js": { "version": "2.35.3", "license": "MIT", + "peer": true, "dependencies": { "@plotly/d3": "3.8.2", "@plotly/d3-sankey": "0.7.2", @@ -25904,6 +25833,7 @@ "node_modules/popper.js": { "version": "1.16.1", "license": "MIT", + "peer": true, "funding": { "type": "opencollective", "url": "https://opencollective.com/popperjs" @@ -25933,6 +25863,7 @@ } ], "license": "MIT", + "peer": true, "dependencies": { "nanoid": "^3.3.8", "picocolors": "^1.1.1", @@ -26018,8 +25949,7 @@ "node_modules/postcss-resolve-nested-selector": { "version": "0.1.6", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/postcss-safe-parser": { "version": "7.0.1", @@ -26039,7 +25969,6 @@ } ], "license": "MIT", - "peer": true, "engines": { "node": ">=18.0" }, @@ -26053,6 +25982,7 @@ "integrity": "sha512-orRsuYpJVw8LdAwqqLykBj9ecS5/cRHlI5+nvTo8LcCKmzDmqVORXtOIYEEQuL9D4BxtA1lm5isAqzQZCoQ6Eg==", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "cssesc": "^3.0.0", "util-deprecate": "^1.0.2" @@ -26097,6 +26027,7 @@ "version": "3.0.0", "dev": true, "license": "MIT", + "peer": true, "bin": { "prettier": "bin/prettier.cjs" }, @@ -26111,7 +26042,6 @@ "version": "1.0.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-diff": "^1.1.2" }, @@ -26382,7 +26312,6 @@ "node_modules/randombytes": { "version": "2.1.0", "license": "MIT", - "peer": true, "dependencies": { "safe-buffer": "^5.1.0" } @@ -26390,6 +26319,7 @@ "node_modules/react": { "version": "17.0.2", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1" @@ -26516,6 +26446,7 @@ "node_modules/react-dom": { "version": "17.0.2", "license": "MIT", + "peer": true, "dependencies": { "loose-envify": "^1.1.0", "object-assign": "^4.1.1", @@ -26610,6 +26541,7 @@ "node_modules/react-redux": { "version": "7.2.9", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.15.4", "@types/react-redux": "^7.1.20", @@ -26973,6 +26905,7 @@ "node_modules/redux": { "version": "4.2.1", "license": "MIT", + "peer": true, "dependencies": { "@babel/runtime": "^7.9.2" } @@ -27057,7 +26990,6 @@ "version": "3.2.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" }, @@ -27531,7 +27463,6 @@ "node_modules/require-from-string": { "version": "2.0.2", "license": "MIT", - "peer": true, "engines": { "node": ">=0.10.0" } @@ -27589,7 +27520,6 @@ "version": "1.0.0", "dev": true, "license": "MIT", - "peer": true, "funding": { "url": "https://github.com/privatenumber/resolve-pkg-maps?sponsor=1" } @@ -28081,7 +28011,6 @@ "node_modules/schema-utils": { "version": "4.3.0", "license": "MIT", - "peer": true, "dependencies": { "@types/json-schema": "^7.0.9", "ajv": "^8.9.0", @@ -28114,7 +28043,6 @@ "node_modules/schema-utils/node_modules/ajv-keywords": { "version": "5.1.0", "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3" }, @@ -28124,8 +28052,7 @@ }, "node_modules/schema-utils/node_modules/json-schema-traverse": { "version": "1.0.0", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/semver": { "version": "6.3.1", @@ -28138,7 +28065,6 @@ "node_modules/serialize-javascript": { "version": "6.0.2", "license": "BSD-3-Clause", - "peer": true, "dependencies": { "randombytes": "^2.1.0" } @@ -28359,7 +28285,6 @@ "version": "4.0.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "ansi-styles": "^4.0.0", "astral-regex": "^2.0.0", @@ -28909,7 +28834,6 @@ } ], "license": "MIT", - "peer": true, "dependencies": { "@csstools/css-parser-algorithms": "^3.0.4", "@csstools/css-tokenizer": "^3.0.3", @@ -28971,7 +28895,6 @@ } ], "license": "MIT-0", - "peer": true, "engines": { "node": ">=18" }, @@ -28982,14 +28905,12 @@ "node_modules/stylelint/node_modules/balanced-match": { "version": "2.0.0", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/stylelint/node_modules/cosmiconfig": { "version": "9.0.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "env-paths": "^2.2.1", "import-fresh": "^3.3.0", @@ -29015,7 +28936,6 @@ "version": "10.0.7", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "flat-cache": "^6.1.7" } @@ -29024,7 +28944,6 @@ "version": "6.1.7", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "cacheable": "^1.8.9", "flatted": "^3.3.3", @@ -29035,7 +28954,6 @@ "version": "7.0.3", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">= 4" } @@ -29044,7 +28962,6 @@ "version": "13.2.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=18" }, @@ -29056,7 +28973,6 @@ "version": "5.0.0", "dev": true, "license": "MIT", - "peer": true, "engines": { "node": ">=8" } @@ -29065,7 +28981,6 @@ "version": "4.1.0", "dev": true, "license": "ISC", - "peer": true, "engines": { "node": ">=14" }, @@ -29077,7 +28992,6 @@ "version": "5.0.1", "dev": true, "license": "ISC", - "peer": true, "dependencies": { "imurmurhash": "^0.1.4", "signal-exit": "^4.0.1" @@ -29116,7 +29030,6 @@ "version": "3.2.0", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "has-flag": "^4.0.0", "supports-color": "^7.0.0" @@ -29172,8 +29085,7 @@ }, "node_modules/svg-tags": { "version": "1.0.0", - "dev": true, - "peer": true + "dev": true }, "node_modules/symbol-tree": { "version": "3.2.4", @@ -29183,7 +29095,6 @@ "version": "0.9.2", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "@pkgr/core": "^0.1.0", "tslib": "^2.6.2" @@ -29199,7 +29110,6 @@ "version": "6.9.0", "dev": true, "license": "BSD-3-Clause", - "peer": true, "dependencies": { "ajv": "^8.0.1", "lodash.truncate": "^4.4.2", @@ -29215,7 +29125,6 @@ "version": "8.17.1", "dev": true, "license": "MIT", - "peer": true, "dependencies": { "fast-deep-equal": "^3.1.3", "fast-uri": "^3.0.1", @@ -29230,13 +29139,11 @@ "node_modules/table/node_modules/json-schema-traverse": { "version": "1.0.0", "dev": true, - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/tapable": { "version": "2.2.1", "license": "MIT", - "peer": true, "engines": { "node": ">=6" } @@ -29374,7 +29281,6 @@ "node_modules/terser-webpack-plugin": { "version": "5.3.14", "license": "MIT", - "peer": true, "dependencies": { "@jridgewell/trace-mapping": "^0.3.25", "jest-worker": "^27.4.5", @@ -29407,7 +29313,6 @@ "node_modules/terser-webpack-plugin/node_modules/jest-worker": { "version": "27.5.1", "license": "MIT", - "peer": true, "dependencies": { "@types/node": "*", "merge-stream": "^2.0.0", @@ -29420,7 +29325,6 @@ "node_modules/terser-webpack-plugin/node_modules/supports-color": { "version": "8.1.1", "license": "MIT", - "peer": true, "dependencies": { "has-flag": "^4.0.0" }, @@ -29434,7 +29338,6 @@ "node_modules/terser/node_modules/source-map-support": { "version": "0.5.21", "license": "MIT", - "peer": true, "dependencies": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" @@ -29584,6 +29487,7 @@ "integrity": "sha512-5gTmgEY/sqK6gFXLIsQNH19lWb4ebPDLA4SdLP7dsWkIXHWlG66oPuVvXSGFPppYZz8ZDZq0dYYrbHfBCVUb1Q==", "dev": true, "license": "MIT", + "peer": true, "engines": { "node": ">=12" }, @@ -29925,6 +29829,7 @@ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.9.3.tgz", "integrity": "sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==", "dev": true, + "peer": true, "bin": { "tsc": "bin/tsc", "tsserver": "bin/tsserver" @@ -30400,6 +30305,7 @@ "version": "5.4.14", "dev": true, "license": "MIT", + "peer": true, "dependencies": { "esbuild": "^0.21.3", "postcss": "^8.4.43", @@ -30501,7 +30407,6 @@ "node_modules/watchpack": { "version": "2.4.2", "license": "MIT", - "peer": true, "dependencies": { "glob-to-regexp": "^0.4.1", "graceful-fs": "^4.1.2" @@ -30594,15 +30499,13 @@ "node_modules/webpack-sources": { "version": "3.2.3", "license": "MIT", - "peer": true, "engines": { "node": ">=10.13.0" } }, "node_modules/webpack/node_modules/json-parse-even-better-errors": { "version": "2.3.1", - "license": "MIT", - "peer": true + "license": "MIT" }, "node_modules/whatwg-encoding": { "version": "2.0.0", @@ -31351,8 +31254,10 @@ "version": "0.1.0", "license": "Apache-2.0", "dependencies": { + "@deephaven/chart": "^0.106.0", "@deephaven/components": "^0.106.0", "@deephaven/icons": "^0.106.0", + "@deephaven/jsapi-bootstrap": "^0.106.0", "@deephaven/log": "^0.106.2", "@deephaven/plugin": "^0.106.4" }, @@ -31366,6 +31271,36 @@ "react-dom": "^17.0.2 || ^18.0.0 || ^19.0.0" } }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/chart": { + "version": "0.106.2", + "resolved": "https://registry.npmjs.org/@deephaven/chart/-/chart-0.106.2.tgz", + "integrity": "sha512-38nyYZ56wpU8DakpWS2YbrdBUS6miDh6TsC20xYRZ+HFB2Io6NEsfqvW8rtir05N3UQXxTmGAew14Vqpdhc62g==", + "license": "Apache-2.0", + "dependencies": { + "@deephaven/components": "^0.106.2", + "@deephaven/icons": "^0.106.0", + "@deephaven/jsapi-types": "^1.0.0-dev0.37.2", + "@deephaven/jsapi-utils": "^0.106.2", + "@deephaven/log": "^0.106.2", + "@deephaven/react-hooks": "^0.106.2", + "@deephaven/utils": "^0.106.0", + "buffer": "^6.0.3", + "fast-deep-equal": "^3.1.3", + "lodash.debounce": "^4.0.8", + "lodash.set": "^4.3.2", + "memoize-one": "^5.1.1", + "memoizee": "^0.4.15", + "plotly.js": "^2.29.1", + "prop-types": "^15.7.2", + "react-plotly.js": "^2.6.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "plugins/grid-toolbar/src/js/node_modules/@deephaven/components": { "version": "0.106.2", "resolved": "https://registry.npmjs.org/@deephaven/components/-/components-0.106.2.tgz", @@ -31436,6 +31371,25 @@ "@fortawesome/react-fontawesome": "^0.2.0" } }, + "plugins/grid-toolbar/src/js/node_modules/@deephaven/jsapi-bootstrap": { + "version": "0.106.2", + "resolved": "https://registry.npmjs.org/@deephaven/jsapi-bootstrap/-/jsapi-bootstrap-0.106.2.tgz", + "integrity": "sha512-6Yi5X5WddNmbPB96ta7/BK7vsSlmT15XSgGUjMEY1xy14e+dqhedfcsfeq17O7RqSRKT0glvgw2YblD5JGYl8Q==", + "license": "Apache-2.0", + "dependencies": { + "@deephaven/components": "^0.106.2", + "@deephaven/jsapi-types": "^1.0.0-dev0.37.2", + "@deephaven/log": "^0.106.2", + "@deephaven/react-hooks": "^0.106.2", + "@deephaven/utils": "^0.106.0" + }, + "engines": { + "node": ">=16" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "plugins/grid-toolbar/src/js/node_modules/@deephaven/jsapi-types": { "version": "1.0.0-dev0.40.9", "resolved": "https://registry.npmjs.org/@deephaven/jsapi-types/-/jsapi-types-1.0.0-dev0.40.9.tgz", @@ -32915,7 +32869,8 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT" + "license": "MIT", + "peer": true }, "plugins/plotly-express/src/js/node_modules/@deephaven/dashboard": { "version": "1.17.1", @@ -33229,7 +33184,8 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT" + "license": "MIT", + "peer": true }, "plugins/plotly-express/src/js/node_modules/@deephaven/dashboard-core-plugins/node_modules/@deephaven/jsapi-components": { "version": "1.17.0", @@ -33734,7 +33690,8 @@ "version": "5.0.1", "resolved": "https://registry.npmjs.org/redux/-/redux-5.0.1.tgz", "integrity": "sha512-M9/ELqF6fy8FwmkpnF0S3YKOqMyoWJ4+CS5Efg2ct3oY9daQvd/Pc71FpGZsVsbl3Cpb+IIcjBDUnnyBdQbq4w==", - "license": "MIT" + "license": "MIT", + "peer": true }, "plugins/plotly-express/src/js/node_modules/@deephaven/redux": { "version": "1.17.0", @@ -33957,8 +33914,7 @@ "version": "0.27.0", "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", - "license": "MIT", - "peer": true + "license": "MIT" }, "plugins/plotly-express/src/js/node_modules/unist-util-find-after": { "version": "4.0.1", diff --git a/plugins/grid-toolbar/README.md b/plugins/grid-toolbar/README.md new file mode 100644 index 000000000..c7867631b --- /dev/null +++ b/plugins/grid-toolbar/README.md @@ -0,0 +1,36 @@ +# Deephaven Plugin: Grid Toolbar + +A middleware plugin that adds a toolbar to table widgets. The toolbar provides: + +- **Chart** — replaces the grid view with a line chart built from the first two columns of the table (col[0] = x-axis, col[1] = y-axis). Click **Grid** to toggle back. +- **Reset Filters** — clears all active filters on the table. + +This plugin is a proof of concept for the middleware plugin infrastructure ([web-client-ui#2660](https://github.com/deephaven/web-client-ui/pull/2660)), demonstrating that a middleware plugin can replace panel content entirely rather than just augmenting it. + +## Plugin Structure + +`src/js/src/GridToolbarPlugin.ts` — registers the plugin as a middleware widget plugin supporting `Table`, `TreeTable`, `HierarchicalTable`, and `PartitionedTable` types. + +`src/js/src/GridToolbarPanelMiddleware.tsx` — panel-level middleware that wraps `IrisGridPanel` with the toolbar UI and chart toggle logic. + +`src/js/src/GridToolbarMiddleware.tsx` — widget-level middleware (used when no panel-level chaining is available). + +## Building the Plugin + +Use the [`plugin_builder.py`](../../README.md#using-plugin_builderpy) from the root directory, or build the JS directly: + +```sh +cd src/js +npm run build +``` + +## Installation + +This is a pure JavaScript plugin — no Python package is required. + +1. Add an entry to `plugins/manifest.json`: + ```json + { "name": "grid-toolbar", "version": "0.0.0", "main": "src/js/dist/bundle/index.js" } + ``` + +2. Serve the plugin directory and point the app at it via `VITE_JS_PLUGINS_DEV_PORT`. diff --git a/plugins/grid-toolbar/src/js/.gitignore b/plugins/grid-toolbar/src/js/.gitignore new file mode 100644 index 000000000..e69de29bb diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts new file mode 100644 index 000000000..eb2cc87c5 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts @@ -0,0 +1,4 @@ +import type { WidgetMiddlewareComponentProps } from './middlewareTypes'; +export declare function GridToolbarMiddleware({ Component, ...props }: WidgetMiddlewareComponentProps): JSX.Element; +export default GridToolbarMiddleware; +//# sourceMappingURL=GridToolbarMiddleware.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map new file mode 100644 index 000000000..72f5481fd --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarMiddleware.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAIxE,wBAAgB,qBAAqB,CAAC,EACpC,SAAS,EACT,GAAG,KAAK,EACT,EAAE,8BAA8B,GAAG,GAAG,CAAC,OAAO,CAiC9C;AAED,eAAe,qBAAqB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js new file mode 100644 index 000000000..749c688f5 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js @@ -0,0 +1,27 @@ +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useCallback } from 'react'; +import Log from '@deephaven/log'; +const log = Log.module('@deephaven/js-plugin-grid-toolbar'); +export function GridToolbarMiddleware(_a) { + var { Component } = _a, props = __rest(_a, ["Component"]); + const handleExport = useCallback(() => { + log.info('Export clicked'); + }, []); + const handleResetFilters = useCallback(() => { + log.info('[0] Reset Filters clicked', props, Component); + }, [props, Component]); + return (_jsxs("div", { className: "grid-toolbar-middleware", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleExport, children: "Export" }), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsx("div", { className: "grid-toolbar-content", children: _jsx(Component, Object.assign({}, props)) })] })); +} +export default GridToolbarMiddleware; +//# sourceMappingURL=GridToolbarMiddleware.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map new file mode 100644 index 000000000..275683a2a --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAIjC,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,MAAM,UAAU,qBAAqB,CAAC,EAGL;QAHK,EACpC,SAAS,OAEsB,EAD5B,KAAK,cAF4B,aAGrC,CADS;IAER,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE;QACpC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IAC7B,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,2BAA2B,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IAEvB,OAAO,CACL,eAAK,SAAS,EAAC,yBAAyB,aACtC,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,YAAY,uBAGd,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,cAAK,SAAS,EAAC,sBAAsB,YAEnC,KAAC,SAAS,oBAAK,KAAK,EAAI,GACpB,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,qBAAqB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts new file mode 100644 index 000000000..1d574596e --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts @@ -0,0 +1,4 @@ +import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; +export declare function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, ...props }: WidgetMiddlewarePanelProps): JSX.Element; +export default GridToolbarPanelMiddleware; +//# sourceMappingURL=GridToolbarPanelMiddleware.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map new file mode 100644 index 000000000..6198b3ce4 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarPanelMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAOpE,wBAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG,GAAG,CAAC,OAAO,CAqF1C;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js new file mode 100644 index 000000000..114a61fd7 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js @@ -0,0 +1,72 @@ +var __rest = (this && this.__rest) || function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +}; +import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; +import { useCallback, useEffect, useState } from 'react'; +import { Chart, ChartModelFactory } from '@deephaven/chart'; +import { useApi } from '@deephaven/jsapi-bootstrap'; +import Log from '@deephaven/log'; +const log = Log.module('@deephaven/js-plugin-grid-toolbar'); +// Matches InputFilterEvent.CLEAR_ALL_FILTERS from @deephaven/dashboard-core-plugins +const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; +export function GridToolbarPanelMiddleware(_a) { + var { Component, fetch, glEventHub } = _a, props = __rest(_a, ["Component", "fetch", "glEventHub"]); + const dh = useApi(); + const [view, setView] = useState('grid'); + const [chartModel, setChartModel] = useState(null); + const [isBuilding, setIsBuilding] = useState(false); + useEffect(() => () => { + chartModel === null || chartModel === void 0 ? void 0 : chartModel.close(); + }, [chartModel]); + const handleChart = useCallback(async () => { + if (view === 'chart') { + setView('grid'); + return; + } + setIsBuilding(true); + try { + // fetch is typed as () => Promise; for grid widgets it returns dh.Table + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const table = (await fetch()); + if (!(table === null || table === void 0 ? void 0 : table.columns) || table.columns.length < 2) { + log.warn('Table has fewer than 2 columns; cannot build chart'); + return; + } + const settings = { + type: 'LINE', + series: [table.columns[1].name], + xAxis: table.columns[0].name, + }; + const model = await ChartModelFactory.makeModelFromSettings( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + dh, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + settings, table); + setChartModel(model); + setView('chart'); + } + catch (e) { + log.error('Failed to build chart model', e); + } + finally { + setIsBuilding(false); + } + }, [dh, fetch, view]); + const handleResetFilters = useCallback(() => { + log.info('Reset Filters clicked'); + glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); + }, [glEventHub]); + return (_jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: isBuilding, onClick: handleChart, children: view === 'chart' ? 'Grid' : 'Chart' }), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === 'chart' && chartModel != null ? (_jsx("div", { className: "h-100 w-100", children: _jsx(Chart, { model: chartModel }) })) : ( + // eslint-disable-next-line react/jsx-props-no-spreading + _jsx(Component, Object.assign({ fetch: fetch, glEventHub: glEventHub }, props))) })] })); +} +export default GridToolbarPanelMiddleware; +//# sourceMappingURL=GridToolbarPanelMiddleware.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map new file mode 100644 index 000000000..6f75ad5c1 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarPanelMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAIjC,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,oFAAoF;AACpF,MAAM,uBAAuB,GAAG,oCAAoC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CAAC,EAKd;QALc,EACzC,SAAS,EACT,KAAK,EACL,UAAU,OAEiB,EADxB,KAAK,cAJiC,oCAK1C,CADS;IAER,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IACpB,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAmB,MAAM,CAAC,CAAC;IAC3D,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,IAAI,CAAC,CAAC;IACtE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEpD,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,EAAE,CAAC;IACtB,CAAC,EACD,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACrB,OAAO,CAAC,MAAM,CAAC,CAAC;YAChB,OAAO;QACT,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC;YACH,iFAAiF;YACjF,8DAA8D;YAC9D,MAAM,KAAK,GAAG,CAAC,MAAM,KAAK,EAAE,CAAQ,CAAC;YACrC,IAAI,CAAC,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,CAAA,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAChD,GAAG,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;gBAC/D,OAAO;YACT,CAAC;YACD,MAAM,QAAQ,GAAG;gBACf,IAAI,EAAE,MAAe;gBACrB,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc,CAAC;gBACzC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc;aACvC,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,qBAAqB;YACzD,8DAA8D;YAC9D,EAAS;YACT,8DAA8D;YAC9D,QAAe,EACf,KAAK,CACN,CAAC;YACF,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,GAAG,CAAC,KAAK,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;QAC9C,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAClC,UAAU,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,OAAO,CACL,eAAK,SAAS,EAAC,qCAAqC,aAClD,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,UAAU,EACpB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,cAAK,SAAS,EAAC,kCAAkC,YAC9C,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,CACxC,cAAK,SAAS,EAAC,aAAa,YAE1B,KAAC,KAAK,IAAC,KAAK,EAAE,UAAiB,GAAI,GAC/B,CACP,CAAC,CAAC,CAAC;gBACF,wDAAwD;gBACxD,KAAC,SAAS,kBAAC,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,IAAM,KAAK,EAAI,CAC/D,GACG,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts new file mode 100644 index 000000000..5c1b2fd45 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts @@ -0,0 +1,4 @@ +import type { WidgetMiddlewarePlugin } from './middlewareTypes'; +export declare const GridToolbarPlugin: WidgetMiddlewarePlugin; +export default GridToolbarPlugin; +//# sourceMappingURL=GridToolbarPlugin.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map new file mode 100644 index 000000000..c7248911b --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarPlugin.d.ts","sourceRoot":"","sources":["../src/GridToolbarPlugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAIhE,eAAO,MAAM,iBAAiB,EAAE,sBAY/B,CAAC;AAEF,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js new file mode 100644 index 000000000..21c81114b --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js @@ -0,0 +1,18 @@ +import { PluginType } from '@deephaven/plugin'; +import { GridToolbarMiddleware } from './GridToolbarMiddleware'; +import { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; +export const GridToolbarPlugin = { + name: '@deephaven/js-plugin-grid-toolbar', + type: PluginType.WIDGET_PLUGIN, + supportedTypes: [ + 'Table', + 'TreeTable', + 'HierarchicalTable', + 'PartitionedTable', + ], + component: GridToolbarMiddleware, + panelComponent: GridToolbarPanelMiddleware, + isMiddleware: true, +}; +export default GridToolbarPlugin; +//# sourceMappingURL=GridToolbarPlugin.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map new file mode 100644 index 000000000..15c6a18ac --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GridToolbarPlugin.js","sourceRoot":"","sources":["../src/GridToolbarPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAG/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,CAAC,MAAM,iBAAiB,GAA2B;IACvD,IAAI,EAAE,mCAAmC;IACzC,IAAI,EAAE,UAAU,CAAC,aAAa;IAC9B,cAAc,EAAE;QACd,OAAO;QACP,WAAW;QACX,mBAAmB;QACnB,kBAAkB;KACnB;IACD,SAAS,EAAE,qBAAqB;IAChC,cAAc,EAAE,0BAA0B;IAC1C,YAAY,EAAE,IAAI;CACnB,CAAC;AAEF,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs b/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs deleted file mode 100644 index a46c05798..000000000 --- a/plugins/grid-toolbar/src/js/dist/bundle/Chart-DElXbH_b.cjs +++ /dev/null @@ -1,90838 +0,0 @@ -"use strict"; -Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" }); -const React = require("react"); -const index$3 = require("./index-nioU_Oes.cjs"); -const icons = require("@deephaven/icons"); -const Log = require("@deephaven/log"); -const components = require("@deephaven/components"); -function _defineProperty$6(obj, key, value2) { - key = _toPropertyKey$6(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$6(arg) { - var key = _toPrimitive$6(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$6(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class TableColumnFormatter { - /** - * Validates format object - * @param dh JSAPI instance - * @param format Format object - * @returns true for valid object - */ - static isValid(dh, format2) { - return true; - } - /** - * Check if the given formats match - * @param formatA format object to check - * @param formatB format object to check - * @returns True if the formats match - */ - static isSameFormat(formatA, formatB) { - throw new Error("isSameFormat not implemented"); - } - /** - * Create and return a Format object - * @param label The label of the format object - * @param formatString Format string to use for the format - * @param type The type of column to use for this format - * @returns A format object - */ - static makeFormat(label, formatString, type) { - return { - label, - formatString, - type - }; - } - /** - * @param value The value to format - * @param format Optional format object with value transformation options - * @returns String the formatted text string of the value passed in. - */ - format(value2, format2) { - return ""; - } -} -_defineProperty$6(TableColumnFormatter, "TYPE_GLOBAL", "type-global"); -_defineProperty$6(TableColumnFormatter, "TYPE_CONTEXT_PRESET", "type-context-preset"); -_defineProperty$6(TableColumnFormatter, "TYPE_CONTEXT_CUSTOM", "type-context-custom"); -class BooleanColumnFormatter extends TableColumnFormatter { - format(value2) { - switch (value2) { - case 1: - case true: - return "true"; - case 0: - case false: - return "false"; - default: - return ""; - } - } -} -class CharColumnFormatter extends TableColumnFormatter { - format(value2) { - return String.fromCharCode(value2); - } -} -function _defineProperty$5(obj, key, value2) { - key = _toPropertyKey$5(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$5(arg) { - var key = _toPrimitive$5(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$5(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -var log$3 = Log.module("DateTimeColumnFormatter"); -class DateTimeColumnFormatter extends TableColumnFormatter { - /** - * Validates format object - * @param dh JSAPI instance - * @param format Format object - * @returns true for valid object - */ - static isValid(dh, format2) { - if (format2.formatString == null) { - return false; - } - try { - dh.i18n.DateTimeFormat.format(format2.formatString, /* @__PURE__ */ new Date()); - return true; - } catch (e) { - return false; - } - } - static makeFormat(label, formatString) { - var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; - return { - label, - formatString, - type - }; - } - /** - * Check if the given formats match - * @param formatA format object to check - * @param formatB format object to check - * @returns True if the formats match - */ - static isSameFormat(formatA, formatB) { - return formatA === formatB || formatA !== null && formatB !== null && formatA.type === formatB.type && formatA.formatString === formatB.formatString; - } - static makeGlobalFormatStringMap(showTimeZone, showTSeparator) { - var separator = showTSeparator ? "'T'" : " "; - var tz = showTimeZone ? " z" : ""; - return /* @__PURE__ */ new Map([["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd".concat(separator, "HH:mm:ss").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSS").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSSSSSSSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSSSSSSSS").concat(tz)]]); - } - static getGlobalFormats(showTimeZone, showTSeparator) { - var formatStringMap = DateTimeColumnFormatter.makeGlobalFormatStringMap(showTimeZone, showTSeparator); - return [...formatStringMap.keys()]; - } - static makeFormatStringMap(showTimeZone, showTSeparator) { - var separator = showTSeparator !== void 0 && showTSeparator ? "'T'" : " "; - var tz = showTimeZone !== void 0 && showTimeZone ? " z" : ""; - return /* @__PURE__ */ new Map([["yyyy-MM-dd", "yyyy-MM-dd".concat(tz)], ["MM-dd-yyyy", "MM-dd-yyyy".concat(tz)], ["HH:mm:ss", "HH:mm:ss".concat(tz)], ["HH:mm:ss.SSS", "HH:mm:ss.SSS".concat(tz)], ["HH:mm:ss.SSSSSSSSS", "HH:mm:ss.SSSSSSSSS".concat(tz)], ["yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd".concat(separator, "HH:mm:ss").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSS").concat(tz)], ["yyyy-MM-dd HH:mm:ss.SSSSSSSSS", "yyyy-MM-dd".concat(separator, "HH:mm:ss.SSSSSSSSS").concat(tz)]]); - } - static getFormats(showTimeZone, showTSeparator) { - var formatStringMap = DateTimeColumnFormatter.makeFormatStringMap(showTimeZone, showTSeparator); - return [...formatStringMap.keys()]; - } - constructor(dh) { - var { - timeZone: timeZoneParam = "", - showTimeZone = true, - showTSeparator = false, - defaultDateTimeFormatString = DateTimeColumnFormatter.DEFAULT_DATETIME_FORMAT_STRING - } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - super(); - _defineProperty$5(this, "dh", void 0); - _defineProperty$5(this, "dhTimeZone", void 0); - _defineProperty$5(this, "defaultDateTimeFormatString", void 0); - _defineProperty$5(this, "showTimeZone", void 0); - _defineProperty$5(this, "showTSeparator", void 0); - _defineProperty$5(this, "formatStringMap", void 0); - var timeZone = timeZoneParam || DateTimeColumnFormatter.DEFAULT_TIME_ZONE_ID; - try { - this.dhTimeZone = dh.i18n.TimeZone.getTimeZone(timeZone); - } catch (e) { - log$3.error("Unsupported time zone id", timeZone); - this.dhTimeZone = dh.i18n.TimeZone.getTimeZone(DateTimeColumnFormatter.DEFAULT_TIME_ZONE_ID); - } - this.dh = dh; - this.defaultDateTimeFormatString = defaultDateTimeFormatString; - this.showTimeZone = showTimeZone; - this.showTSeparator = showTSeparator; - this.formatStringMap = DateTimeColumnFormatter.makeFormatStringMap(showTimeZone, showTSeparator); - } - getEffectiveFormatString(baseFormatString) { - var _this$formatStringMap; - return (_this$formatStringMap = this.formatStringMap.get(baseFormatString)) !== null && _this$formatStringMap !== void 0 ? _this$formatStringMap : baseFormatString; - } - format(value2) { - var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var baseFormatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultDateTimeFormatString; - var formatString = this.getEffectiveFormatString(baseFormatString); - try { - return this.dh.i18n.DateTimeFormat.format(formatString, value2, this.dhTimeZone); - } catch (e) { - log$3.error("Invalid format arguments"); - } - return ""; - } -} -_defineProperty$5(DateTimeColumnFormatter, "DEFAULT_DATETIME_FORMAT_STRING", "yyyy-MM-dd HH:mm:ss.SSS"); -_defineProperty$5(DateTimeColumnFormatter, "DEFAULT_TIME_ZONE_ID", "America/New_York"); -function _defineProperty$4(obj, key, value2) { - key = _toPropertyKey$4(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$4(arg) { - var key = _toPrimitive$4(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$4(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -var log$2 = Log.module("DecimalColumnFormatter"); -class DecimalColumnFormatter extends TableColumnFormatter { - /** - * Validates format object - * @param dh JSAPI instance - * @param format Format object - * @returns true for valid object - */ - static isValid(dh, format2) { - if (format2.formatString == null) { - return false; - } - try { - dh.i18n.NumberFormat.format(format2.formatString, 0); - return true; - } catch (e) { - return false; - } - } - /** - * Create a DecimalColumnFormat object with the parameters specified - * @param label Label for the format - * @param formatString Format string for the format - * @param multiplier Optional multiplier for the formatter - * @param type Type of format created - * @returns DecimalColumnFormat object - */ - static makeFormat(label, formatString) { - var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; - var multiplier = arguments.length > 3 ? arguments[3] : void 0; - return { - label, - type, - formatString, - multiplier - }; - } - /** - * Convenient function to create a DecimalFormatObject with Preset type set - * @param label Label for this format object - * @param formatString Format string to use - * @param multiplier Multiplier to use - * @returns DecimalColumnFormat object - */ - static makePresetFormat(label) { - var formatString = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ""; - var multiplier = arguments.length > 2 ? arguments[2] : void 0; - return DecimalColumnFormatter.makeFormat(label, formatString, TableColumnFormatter.TYPE_CONTEXT_PRESET, multiplier); - } - /** - * Convenient function to create a DecimalFormatObject with a default 'Custom Format' label and Custom type - * @param formatString Format string to use - * @param multiplier Multiplier to use - * @returns DecimalColumnFormat object - */ - static makeCustomFormat() { - var formatString = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; - var multiplier = arguments.length > 1 ? arguments[1] : void 0; - return DecimalColumnFormatter.makeFormat("Custom Format", formatString, TableColumnFormatter.TYPE_CONTEXT_CUSTOM, multiplier); - } - /** - * Check if the given formats match - * @param formatA format object to check - * @param formatB format object to check - * @returns True if the formats match - */ - static isSameFormat(formatA, formatB) { - return formatA === formatB || formatA != null && formatB != null && formatA.type === formatB.type && formatA.formatString === formatB.formatString && formatA.multiplier === formatB.multiplier; - } - constructor(dh) { - var { - defaultFormatString = DecimalColumnFormatter.DEFAULT_FORMAT_STRING - } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - super(); - _defineProperty$4(this, "defaultFormatString", void 0); - _defineProperty$4(this, "dh", void 0); - this.dh = dh; - this.defaultFormatString = defaultFormatString; - } - /** - * Format a value with the provided format object - * @param valueParam Value to format - * @param format Format object - * @returns Formatted string - */ - format(valueParam) { - var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var formatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultFormatString; - var value2 = format2.multiplier != null && format2.multiplier !== 0 ? valueParam * format2.multiplier : valueParam; - try { - return this.dh.i18n.NumberFormat.format(formatString, value2); - } catch (e) { - log$2.error("Invalid format arguments"); - } - return ""; - } -} -_defineProperty$4(DecimalColumnFormatter, "DEFAULT_FORMAT_STRING", "###,##0.0000"); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_PERCENT", DecimalColumnFormatter.makePresetFormat("Percent", "##0.00%")); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_BASIS_POINTS", DecimalColumnFormatter.makePresetFormat("Basis Points", "###,##0 bp", 1e4)); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_THOUSANDS", DecimalColumnFormatter.makePresetFormat("Thousands", "##0.000 k", 1e-3)); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_MILLIONS", DecimalColumnFormatter.makePresetFormat("Millions", "###,##0.000 mm", 1e-6)); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_SCIENTIFIC_NOTATION", DecimalColumnFormatter.makePresetFormat("Scientific Notation", "0.0000E0")); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND", DecimalColumnFormatter.makePresetFormat("Round", "###,##0")); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND_TWO_DECIMALS", DecimalColumnFormatter.makePresetFormat("0.00", "###,##0.00")); -_defineProperty$4(DecimalColumnFormatter, "FORMAT_ROUND_FOUR_DECIMALS", DecimalColumnFormatter.makePresetFormat("0.0000", "###,##0.0000")); -class DefaultColumnFormatter extends TableColumnFormatter { - format(value2) { - return "".concat(value2); - } -} -function _defineProperty$3(obj, key, value2) { - key = _toPropertyKey$3(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$3(arg) { - var key = _toPrimitive$3(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$3(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -var log$1 = Log.module("IntegerColumnFormatter"); -class IntegerColumnFormatter extends TableColumnFormatter { - /** - * Validates format object - * @param dh JSAPI instance - * @param format Format object - * @returns true for valid object - */ - static isValid(dh, format2) { - if (format2.formatString == null) { - return false; - } - try { - dh.i18n.NumberFormat.format(format2.formatString, 0); - return true; - } catch (e) { - return false; - } - } - /** - * Create an IntegerColumnFormat object with the parameters specified - * @param label Label for the format - * @param formatString Format string for the format - * @param multiplier Optional multiplier for the formatter - * @param type Type of format created - * @returns IntegerColumnFormat object - */ - static makeFormat(label, formatString) { - var type = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : TableColumnFormatter.TYPE_CONTEXT_PRESET; - var multiplier = arguments.length > 3 ? arguments[3] : void 0; - return { - label, - type, - formatString, - multiplier - }; - } - /** - * Convenient function to create a IntegerFormatObject with Preset type set - * @param label Label for this format object - * @param formatString Format string to use - * @param multiplier Multiplier to use - * @returns IntegerColumnFormat object - */ - static makePresetFormat(label) { - var formatString = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : ""; - var multiplier = arguments.length > 2 ? arguments[2] : void 0; - return IntegerColumnFormatter.makeFormat(label, formatString, TableColumnFormatter.TYPE_CONTEXT_PRESET, multiplier); - } - /** - * Convenient function to create a IntegerFormatObject with a default 'Custom Format' label and Custom type - * @param formatString Format string to use - * @param multiplier Multiplier to use - * @returns IntegerColumnFormat object - */ - static makeCustomFormat() { - var formatString = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : ""; - var multiplier = arguments.length > 1 ? arguments[1] : void 0; - return IntegerColumnFormatter.makeFormat("Custom Format", formatString, TableColumnFormatter.TYPE_CONTEXT_CUSTOM, multiplier); - } - /** - * Check if the given formats match - * @param formatA format object to check - * @param formatB format object to check - * @returns True if the formats match - */ - static isSameFormat(formatA, formatB) { - return formatA === formatB || formatA != null && formatB != null && formatA.type === formatB.type && formatA.formatString === formatB.formatString && formatA.multiplier === formatB.multiplier; - } - constructor(dh) { - var { - defaultFormatString = IntegerColumnFormatter.DEFAULT_FORMAT_STRING - } = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - super(); - _defineProperty$3(this, "dh", void 0); - _defineProperty$3(this, "defaultFormatString", void 0); - this.dh = dh; - this.defaultFormatString = defaultFormatString; - } - /** - * Format a value with the provided format object - * @param valueParam Value to format - * @param format Format object - * @returns Formatted string - */ - format(valueParam) { - var format2 = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : {}; - var formatString = format2.formatString != null && format2.formatString !== "" ? format2.formatString : this.defaultFormatString; - var value2 = format2.multiplier != null && format2.multiplier !== 0 ? valueParam * format2.multiplier : valueParam; - try { - return this.dh.i18n.NumberFormat.format(formatString, value2); - } catch (e) { - log$1.error("Invalid format arguments"); - } - return ""; - } -} -_defineProperty$3(IntegerColumnFormatter, "DEFAULT_FORMAT_STRING", "###,##0"); -_defineProperty$3(IntegerColumnFormatter, "FORMAT_THOUSANDS", IntegerColumnFormatter.makePresetFormat("Thousands", "##0.000 k", 1e-3)); -_defineProperty$3(IntegerColumnFormatter, "FORMAT_MILLIONS", IntegerColumnFormatter.makePresetFormat("Millions", "###,##0.000 mm", 1e-6)); -_defineProperty$3(IntegerColumnFormatter, "FORMAT_SCIENTIFIC_NOTATION", IntegerColumnFormatter.makePresetFormat("Scientific Notation", "0.0000E0")); -class StringColumnFormatter extends TableColumnFormatter { - format(value2) { - return value2; - } -} -function _defineProperty$2(obj, key, value2) { - key = _toPropertyKey$2(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$2(arg) { - var key = _toPrimitive$2(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$2(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class Formatter { - /** - * Converts FormattingRule[] to Map - * @param columnFormattingRules Array or column formatting rules - * @returns Map of columnName-to-format Maps indexed by normalized dataType - */ - static makeColumnFormatMap(columnFormattingRules) { - if (columnFormattingRules == null) { - return /* @__PURE__ */ new Map(); - } - return columnFormattingRules.reduce((map2, next) => { - var dataType = index$3.TableUtils.getNormalizedType(next.columnType); - if (dataType === null) { - return map2; - } - if (!map2.has(dataType)) { - map2.set(dataType, /* @__PURE__ */ new Map()); - } - var formatMap = map2.get(dataType); - formatMap === null || formatMap === void 0 ? void 0 : formatMap.set(next.columnName, next.format); - return map2; - }, /* @__PURE__ */ new Map()); - } - /** - * Creates a column formatting rule - * @param columnType Normalized data type - * @param columnName Column name - * @param format Format object - */ - static makeColumnFormattingRule(columnType, columnName, format2) { - return { - columnType, - columnName, - format: format2 - }; - } - /** - * @param dh JSAPI instance - * @param columnFormattingRules Optional array of column formatting rules - * @param dateTimeOptions Optional object with DateTime configuration - * @param decimalFormatOptions Optional object with Decimal configuration - * @param integerFormatOptions Optional object with Integer configuration - * @param truncateNumbersWithPound Determine if numbers should be truncated w/ repeating # instead of ellipsis at the end - */ - constructor(dh) { - var columnFormattingRules = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : []; - var dateTimeOptions = arguments.length > 2 ? arguments[2] : void 0; - var decimalFormatOptions = arguments.length > 3 ? arguments[3] : void 0; - var integerFormatOptions = arguments.length > 4 ? arguments[4] : void 0; - var truncateNumbersWithPound = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : false; - var showEmptyStrings = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : true; - var showNullStrings = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : true; - _defineProperty$2(this, "defaultColumnFormatter", void 0); - _defineProperty$2(this, "typeFormatterMap", void 0); - _defineProperty$2(this, "columnFormatMap", void 0); - _defineProperty$2(this, "truncateNumbersWithPound", void 0); - _defineProperty$2(this, "showEmptyStrings", void 0); - _defineProperty$2(this, "showNullStrings", void 0); - this.defaultColumnFormatter = new DefaultColumnFormatter(); - this.typeFormatterMap = /* @__PURE__ */ new Map([[index$3.TableUtils.dataType.BOOLEAN, new BooleanColumnFormatter()], [index$3.TableUtils.dataType.CHAR, new CharColumnFormatter()], [index$3.TableUtils.dataType.DATETIME, new DateTimeColumnFormatter(dh, dateTimeOptions)], [index$3.TableUtils.dataType.DECIMAL, new DecimalColumnFormatter(dh, decimalFormatOptions)], [index$3.TableUtils.dataType.INT, new IntegerColumnFormatter(dh, integerFormatOptions)], [index$3.TableUtils.dataType.STRING, new StringColumnFormatter()]]); - this.columnFormatMap = Formatter.makeColumnFormatMap(columnFormattingRules); - this.truncateNumbersWithPound = truncateNumbersWithPound; - this.showEmptyStrings = showEmptyStrings; - this.showNullStrings = showNullStrings; - } - /** - * Gets columnFormatMap indexed by name for a given column type, creates new Map entry if necessary - * @param columnType column type - * @param createIfNecessary create new entry if true - * @returns Map of format strings indexed by column name or undefined if it doesn't exist - */ - getColumnFormatMapForType(columnType) { - var createIfNecessary = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; - var dataType = index$3.TableUtils.getNormalizedType(columnType); - if (dataType === null) { - return void 0; - } - if (createIfNecessary && !this.columnFormatMap.has(dataType)) { - this.columnFormatMap.set(dataType, /* @__PURE__ */ new Map()); - } - return this.columnFormatMap.get(dataType); - } - /** - * Gets a column format object for a given column type and name - * @param columnType column type - * @param columnName column name - * @returns format object or null for Default - */ - getColumnFormat(columnType, columnName) { - var _columnFormatMap$get; - var columnFormatMap = this.getColumnFormatMapForType(columnType); - return (_columnFormatMap$get = columnFormatMap === null || columnFormatMap === void 0 ? void 0 : columnFormatMap.get(columnName)) !== null && _columnFormatMap$get !== void 0 ? _columnFormatMap$get : null; - } - getColumnTypeFormatter(columnType) { - var dataType = index$3.TableUtils.getNormalizedType(columnType); - var columnTypeFormatter = this.defaultColumnFormatter; - if (dataType) { - var _this$typeFormatterMa; - columnTypeFormatter = (_this$typeFormatterMa = this.typeFormatterMap.get(dataType)) !== null && _this$typeFormatterMa !== void 0 ? _this$typeFormatterMa : columnTypeFormatter; - } - return columnTypeFormatter; - } - /** - * Gets formatted string for a given value, column type and name - * @param value Value to format - * @param columnType Column type used to determine the formatting settings - * @param columnName Column name used to determine the formatting settings - * @param formatOverride Format object passed to the formatter in place of the format defined in columnFormatMap - */ - getFormattedString(value2, columnType) { - var columnName = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : ""; - var formatOverride = arguments.length > 3 ? arguments[3] : void 0; - if (value2 == null) { - return ""; - } - var formatter = this.getColumnTypeFormatter(columnType); - var format2 = formatOverride || this.getColumnFormat(columnType, columnName); - return formatter.format(value2, format2 !== null && format2 !== void 0 ? format2 : void 0); - } - /** - * Gets the timeZone name - * @returns The time zone name E.g. America/New_York - */ - get timeZone() { - var formatter = this.typeFormatterMap.get(index$3.TableUtils.dataType.DATETIME); - index$3.assertInstanceOf(formatter, DateTimeColumnFormatter); - return formatter.dhTimeZone.id; - } -} -function createFormatterFromSettings(dh, settings) { - var columnRules = getColumnFormats(settings); - var dateTimeOptions = getDateTimeFormatterOptions(settings); - var { - defaultDecimalFormatOptions, - defaultIntegerFormatOptions, - truncateNumbersWithPound, - showEmptyStrings, - showNullStrings - } = settings !== null && settings !== void 0 ? settings : {}; - return new Formatter(dh, columnRules, dateTimeOptions, defaultDecimalFormatOptions, defaultIntegerFormatOptions, truncateNumbersWithPound, showEmptyStrings, showNullStrings); -} -function getColumnFormats(settings) { - if (settings && settings.formatter) { - var { - formatter - } = settings; - return formatter; - } - return void 0; -} -function getDateTimeFormatterOptions(settings) { - return { - timeZone: settings === null || settings === void 0 ? void 0 : settings.timeZone, - defaultDateTimeFormatString: settings === null || settings === void 0 ? void 0 : settings.defaultDateTimeFormat, - showTimeZone: settings === null || settings === void 0 ? void 0 : settings.showTimeZone, - showTSeparator: settings === null || settings === void 0 ? void 0 : settings.showTSeparator - }; -} -function isCustomColumnFormatDefined(formatter, columnName, columnType) { - var columnFormat = formatter.getColumnFormat(columnType, columnName); - return columnFormat != null && (columnFormat.type === TableColumnFormatter.TYPE_CONTEXT_PRESET || columnFormat.type === TableColumnFormatter.TYPE_CONTEXT_CUSTOM); -} -const FormatterUtils = { - createFormatterFromSettings, - getColumnFormats, - getDateTimeFormatterOptions, - isCustomColumnFormatDefined -}; -function _defineProperty$1(e, r, t) { - return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey$1(t) { - var i = _toPrimitive$1(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive$1(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -class DownsamplingError extends Error { - constructor() { - super(...arguments); - _defineProperty$1(this, "isDownsamplingError", true); - } -} -var ChartThemeContext = /* @__PURE__ */ React.createContext(null); -function useContextOrThrow(context2) { - var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "No value available in context. Was code wrapped in a provider?"; - var value2 = React.useContext(context2); - if (value2 == null) { - throw new Error(message); - } - return value2; -} -function mergeRefs() { - for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) { - refs[_key] = arguments[_key]; - } - return (newRef) => { - refs.forEach((ref2) => { - if (ref2 != null) { - if (typeof ref2 === "function") { - ref2(newRef); - } else { - ref2.current = newRef; - } - } - }); - }; -} -function useChartTheme() { - return useContextOrThrow(ChartThemeContext, "No ChartThemeContext value found."); -} -var fastDeepEqual = function equal(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - if (a.constructor !== b.constructor) return false; - var length2, i, keys; - if (Array.isArray(a)) { - length2 = a.length; - if (length2 != b.length) return false; - for (i = length2; i-- !== 0; ) - if (!equal(a[i], b[i])) return false; - return true; - } - if (a.constructor === RegExp) return a.source === b.source && a.flags === b.flags; - if (a.valueOf !== Object.prototype.valueOf) return a.valueOf() === b.valueOf(); - if (a.toString !== Object.prototype.toString) return a.toString() === b.toString(); - keys = Object.keys(a); - length2 = keys.length; - if (length2 !== Object.keys(b).length) return false; - for (i = length2; i-- !== 0; ) - if (!Object.prototype.hasOwnProperty.call(b, keys[i])) return false; - for (i = length2; i-- !== 0; ) { - var key = keys[i]; - if (!equal(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; -}; -const deepEqual = /* @__PURE__ */ index$3.getDefaultExportFromCjs(fastDeepEqual); -var safeIsNaN = Number.isNaN || function ponyfill(value2) { - return typeof value2 === "number" && value2 !== value2; -}; -function isEqual(first, second2) { - if (first === second2) { - return true; - } - if (safeIsNaN(first) && safeIsNaN(second2)) { - return true; - } - return false; -} -function areInputsEqual(newInputs, lastInputs) { - if (newInputs.length !== lastInputs.length) { - return false; - } - for (var i = 0; i < newInputs.length; i++) { - if (!isEqual(newInputs[i], lastInputs[i])) { - return false; - } - } - return true; -} -function memoizeOne(resultFn, isEqual2) { - if (isEqual2 === void 0) { - isEqual2 = areInputsEqual; - } - var lastThis; - var lastArgs = []; - var lastResult; - var calledOnce = false; - function memoized() { - var newArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - newArgs[_i] = arguments[_i]; - } - if (calledOnce && lastThis === this && isEqual2(newArgs, lastArgs)) { - return lastResult; - } - lastResult = resultFn.apply(this, newArgs); - calledOnce = true; - lastThis = this; - lastArgs = newArgs; - return lastResult; - } - return memoized; -} -var factory = {}; -var propTypes = { exports: {} }; -var ReactPropTypesSecret$1 = "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"; -var ReactPropTypesSecret_1 = ReactPropTypesSecret$1; -var ReactPropTypesSecret = ReactPropTypesSecret_1; -function emptyFunction() { -} -function emptyFunctionWithReset() { -} -emptyFunctionWithReset.resetWarningCache = emptyFunction; -var factoryWithThrowingShims = function() { - function shim2(props, propName, componentName, location, propFullName, secret) { - if (secret === ReactPropTypesSecret) { - return; - } - var err = new Error( - "Calling PropTypes validators directly is not supported by the `prop-types` package. Use PropTypes.checkPropTypes() to call them. Read more at http://fb.me/use-check-prop-types" - ); - err.name = "Invariant Violation"; - throw err; - } - shim2.isRequired = shim2; - function getShim() { - return shim2; - } - var ReactPropTypes = { - array: shim2, - bigint: shim2, - bool: shim2, - func: shim2, - number: shim2, - object: shim2, - string: shim2, - symbol: shim2, - any: shim2, - arrayOf: getShim, - element: shim2, - elementType: shim2, - instanceOf: getShim, - node: shim2, - objectOf: getShim, - oneOf: getShim, - oneOfType: getShim, - shape: getShim, - exact: getShim, - checkPropTypes: emptyFunctionWithReset, - resetWarningCache: emptyFunction - }; - ReactPropTypes.PropTypes = ReactPropTypes; - return ReactPropTypes; -}; -{ - propTypes.exports = factoryWithThrowingShims(); -} -var propTypesExports = propTypes.exports; -(function(exports2) { - function _typeof(obj) { - "@babel/helpers - typeof"; - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { - return typeof obj2; - } : function(obj2) { - return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; - }, _typeof(obj); - } - Object.defineProperty(exports2, "__esModule", { - value: true - }); - exports2["default"] = plotComponentFactory; - var _react = _interopRequireWildcard(React); - var _propTypes = _interopRequireDefault(propTypesExports); - function _interopRequireDefault(obj) { - return obj && obj.__esModule ? obj : { "default": obj }; - } - function _getRequireWildcardCache(nodeInterop) { - if (typeof WeakMap !== "function") return null; - var cacheBabelInterop = /* @__PURE__ */ new WeakMap(); - var cacheNodeInterop = /* @__PURE__ */ new WeakMap(); - return (_getRequireWildcardCache = function _getRequireWildcardCache2(nodeInterop2) { - return nodeInterop2 ? cacheNodeInterop : cacheBabelInterop; - })(nodeInterop); - } - function _interopRequireWildcard(obj, nodeInterop) { - if (obj && obj.__esModule) { - return obj; - } - if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { - return { "default": obj }; - } - var cache2 = _getRequireWildcardCache(nodeInterop); - if (cache2 && cache2.has(obj)) { - return cache2.get(obj); - } - var newObj = {}; - var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; - for (var key in obj) { - if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { - var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; - if (desc && (desc.get || desc.set)) { - Object.defineProperty(newObj, key, desc); - } else { - newObj[key] = obj[key]; - } - } - } - newObj["default"] = obj; - if (cache2) { - cache2.set(obj, newObj); - } - return newObj; - } - function _classCallCheck(instance, Constructor) { - if (!(instance instanceof Constructor)) { - throw new TypeError("Cannot call a class as a function"); - } - } - function _defineProperties(target, props) { - for (var i = 0; i < props.length; i++) { - var descriptor = props[i]; - descriptor.enumerable = descriptor.enumerable || false; - descriptor.configurable = true; - if ("value" in descriptor) descriptor.writable = true; - Object.defineProperty(target, descriptor.key, descriptor); - } - } - function _createClass(Constructor, protoProps, staticProps) { - if (protoProps) _defineProperties(Constructor.prototype, protoProps); - Object.defineProperty(Constructor, "prototype", { writable: false }); - return Constructor; - } - function _inherits(subClass, superClass) { - if (typeof superClass !== "function" && superClass !== null) { - throw new TypeError("Super expression must either be null or a function"); - } - subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, writable: true, configurable: true } }); - Object.defineProperty(subClass, "prototype", { writable: false }); - if (superClass) _setPrototypeOf(subClass, superClass); - } - function _setPrototypeOf(o, p) { - _setPrototypeOf = Object.setPrototypeOf ? Object.setPrototypeOf.bind() : function _setPrototypeOf2(o2, p2) { - o2.__proto__ = p2; - return o2; - }; - return _setPrototypeOf(o, p); - } - function _createSuper(Derived) { - var hasNativeReflectConstruct = _isNativeReflectConstruct(); - return function _createSuperInternal() { - var Super = _getPrototypeOf(Derived), result; - if (hasNativeReflectConstruct) { - var NewTarget = _getPrototypeOf(this).constructor; - result = Reflect.construct(Super, arguments, NewTarget); - } else { - result = Super.apply(this, arguments); - } - return _possibleConstructorReturn(this, result); - }; - } - function _possibleConstructorReturn(self2, call) { - if (call && (_typeof(call) === "object" || typeof call === "function")) { - return call; - } else if (call !== void 0) { - throw new TypeError("Derived constructors may only return object or undefined"); - } - return _assertThisInitialized(self2); - } - function _assertThisInitialized(self2) { - if (self2 === void 0) { - throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); - } - return self2; - } - function _isNativeReflectConstruct() { - if (typeof Reflect === "undefined" || !Reflect.construct) return false; - if (Reflect.construct.sham) return false; - if (typeof Proxy === "function") return true; - try { - Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function() { - })); - return true; - } catch (e) { - return false; - } - } - function _getPrototypeOf(o) { - _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf.bind() : function _getPrototypeOf2(o2) { - return o2.__proto__ || Object.getPrototypeOf(o2); - }; - return _getPrototypeOf(o); - } - var eventNames2 = ["AfterExport", "AfterPlot", "Animated", "AnimatingFrame", "AnimationInterrupted", "AutoSize", "BeforeExport", "BeforeHover", "ButtonClicked", "Click", "ClickAnnotation", "Deselect", "DoubleClick", "Framework", "Hover", "LegendClick", "LegendDoubleClick", "Relayout", "Relayouting", "Restyle", "Redraw", "Selected", "Selecting", "SliderChange", "SliderEnd", "SliderStart", "SunburstClick", "Transitioning", "TransitionInterrupted", "Unhover", "WebGlContextLost"]; - var updateEvents = ["plotly_restyle", "plotly_redraw", "plotly_relayout", "plotly_relayouting", "plotly_doubleclick", "plotly_animated", "plotly_sunburstclick"]; - var isBrowser2 = typeof window !== "undefined"; - function plotComponentFactory(Plotly2) { - var PlotlyComponent = /* @__PURE__ */ function(_Component) { - _inherits(PlotlyComponent2, _Component); - var _super = _createSuper(PlotlyComponent2); - function PlotlyComponent2(props) { - var _this; - _classCallCheck(this, PlotlyComponent2); - _this = _super.call(this, props); - _this.p = Promise.resolve(); - _this.resizeHandler = null; - _this.handlers = {}; - _this.syncWindowResize = _this.syncWindowResize.bind(_assertThisInitialized(_this)); - _this.syncEventHandlers = _this.syncEventHandlers.bind(_assertThisInitialized(_this)); - _this.attachUpdateEvents = _this.attachUpdateEvents.bind(_assertThisInitialized(_this)); - _this.getRef = _this.getRef.bind(_assertThisInitialized(_this)); - _this.handleUpdate = _this.handleUpdate.bind(_assertThisInitialized(_this)); - _this.figureCallback = _this.figureCallback.bind(_assertThisInitialized(_this)); - _this.updatePlotly = _this.updatePlotly.bind(_assertThisInitialized(_this)); - return _this; - } - _createClass(PlotlyComponent2, [{ - key: "updatePlotly", - value: function updatePlotly(shouldInvokeResizeHandler, figureCallbackFunction, shouldAttachUpdateEvents) { - var _this2 = this; - this.p = this.p.then(function() { - if (_this2.unmounting) { - return; - } - if (!_this2.el) { - throw new Error("Missing element reference"); - } - return Plotly2.react(_this2.el, { - data: _this2.props.data, - layout: _this2.props.layout, - config: _this2.props.config, - frames: _this2.props.frames - }); - }).then(function() { - if (_this2.unmounting) { - return; - } - _this2.syncWindowResize(shouldInvokeResizeHandler); - _this2.syncEventHandlers(); - _this2.figureCallback(figureCallbackFunction); - if (shouldAttachUpdateEvents) { - _this2.attachUpdateEvents(); - } - })["catch"](function(err) { - if (_this2.props.onError) { - _this2.props.onError(err); - } - }); - } - }, { - key: "componentDidMount", - value: function componentDidMount() { - this.unmounting = false; - this.updatePlotly(true, this.props.onInitialized, true); - } - }, { - key: "componentDidUpdate", - value: function componentDidUpdate(prevProps) { - this.unmounting = false; - var numPrevFrames = prevProps.frames && prevProps.frames.length ? prevProps.frames.length : 0; - var numNextFrames = this.props.frames && this.props.frames.length ? this.props.frames.length : 0; - var figureChanged = !(prevProps.layout === this.props.layout && prevProps.data === this.props.data && prevProps.config === this.props.config && numNextFrames === numPrevFrames); - var revisionDefined = prevProps.revision !== void 0; - var revisionChanged = prevProps.revision !== this.props.revision; - if (!figureChanged && (!revisionDefined || revisionDefined && !revisionChanged)) { - return; - } - this.updatePlotly(false, this.props.onUpdate, false); - } - }, { - key: "componentWillUnmount", - value: function componentWillUnmount() { - this.unmounting = true; - this.figureCallback(this.props.onPurge); - if (this.resizeHandler && isBrowser2) { - window.removeEventListener("resize", this.resizeHandler); - this.resizeHandler = null; - } - this.removeUpdateEvents(); - Plotly2.purge(this.el); - } - }, { - key: "attachUpdateEvents", - value: function attachUpdateEvents() { - var _this3 = this; - if (!this.el || !this.el.removeListener) { - return; - } - updateEvents.forEach(function(updateEvent) { - _this3.el.on(updateEvent, _this3.handleUpdate); - }); - } - }, { - key: "removeUpdateEvents", - value: function removeUpdateEvents() { - var _this4 = this; - if (!this.el || !this.el.removeListener) { - return; - } - updateEvents.forEach(function(updateEvent) { - _this4.el.removeListener(updateEvent, _this4.handleUpdate); - }); - } - }, { - key: "handleUpdate", - value: function handleUpdate() { - this.figureCallback(this.props.onUpdate); - } - }, { - key: "figureCallback", - value: function figureCallback(callback) { - if (typeof callback === "function") { - var _this$el = this.el, data = _this$el.data, layout = _this$el.layout; - var frames = this.el._transitionData ? this.el._transitionData._frames : null; - var figure = { - data, - layout, - frames - }; - callback(figure, this.el); - } - } - }, { - key: "syncWindowResize", - value: function syncWindowResize(invoke) { - var _this5 = this; - if (!isBrowser2) { - return; - } - if (this.props.useResizeHandler && !this.resizeHandler) { - this.resizeHandler = function() { - return Plotly2.Plots.resize(_this5.el); - }; - window.addEventListener("resize", this.resizeHandler); - if (invoke) { - this.resizeHandler(); - } - } else if (!this.props.useResizeHandler && this.resizeHandler) { - window.removeEventListener("resize", this.resizeHandler); - this.resizeHandler = null; - } - } - }, { - key: "getRef", - value: function getRef(el) { - this.el = el; - if (this.props.debug && isBrowser2) { - window.gd = this.el; - } - } - // Attach and remove event handlers as they're added or removed from props: - }, { - key: "syncEventHandlers", - value: function syncEventHandlers() { - var _this6 = this; - eventNames2.forEach(function(eventName) { - var prop = _this6.props["on" + eventName]; - var handler = _this6.handlers[eventName]; - var hasHandler = Boolean(handler); - if (prop && !hasHandler) { - _this6.addEventHandler(eventName, prop); - } else if (!prop && hasHandler) { - _this6.removeEventHandler(eventName); - } else if (prop && hasHandler && prop !== handler) { - _this6.removeEventHandler(eventName); - _this6.addEventHandler(eventName, prop); - } - }); - } - }, { - key: "addEventHandler", - value: function addEventHandler(eventName, prop) { - this.handlers[eventName] = prop; - this.el.on(this.getPlotlyEventName(eventName), this.handlers[eventName]); - } - }, { - key: "removeEventHandler", - value: function removeEventHandler(eventName) { - this.el.removeListener(this.getPlotlyEventName(eventName), this.handlers[eventName]); - delete this.handlers[eventName]; - } - }, { - key: "getPlotlyEventName", - value: function getPlotlyEventName(eventName) { - return "plotly_" + eventName.toLowerCase(); - } - }, { - key: "render", - value: function render() { - return /* @__PURE__ */ _react["default"].createElement("div", { - id: this.props.divId, - style: this.props.style, - ref: this.getRef, - className: this.props.className - }); - } - }]); - return PlotlyComponent2; - }(_react.Component); - PlotlyComponent.propTypes = { - data: _propTypes["default"].arrayOf(_propTypes["default"].object), - config: _propTypes["default"].object, - layout: _propTypes["default"].object, - frames: _propTypes["default"].arrayOf(_propTypes["default"].object), - revision: _propTypes["default"].number, - onInitialized: _propTypes["default"].func, - onPurge: _propTypes["default"].func, - onError: _propTypes["default"].func, - onUpdate: _propTypes["default"].func, - debug: _propTypes["default"].bool, - style: _propTypes["default"].object, - className: _propTypes["default"].string, - useResizeHandler: _propTypes["default"].bool, - divId: _propTypes["default"].string - }; - eventNames2.forEach(function(eventName) { - PlotlyComponent.propTypes["on" + eventName] = _propTypes["default"].func; - }); - PlotlyComponent.defaultProps = { - debug: false, - useResizeHandler: false, - data: [], - style: { - position: "relative", - display: "inline-block" - } - }; - return PlotlyComponent; - } -})(factory); -const createPlotlyComponent$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(factory); -const createPlotlyComponent = typeof createPlotlyComponent$1 === "function" ? createPlotlyComponent$1 : ( - // eslint-disable-next-line @typescript-eslint/ban-ts-comment - // @ts-ignore - createPlotlyComponent$1.default -); -var core$1 = {}; -var version$2 = {}; -version$2.version = "2.35.3"; -var npo_src = { exports: {} }; -/*! Native Promise Only - v0.8.1 (c) Kyle Simpson - MIT License: http://getify.mit-license.org -*/ -(function(module2) { - (function UMD(name2, context2, definition) { - context2[name2] = context2[name2] || definition(); - if (module2.exports) { - module2.exports = context2[name2]; - } - })("Promise", typeof index$3.commonjsGlobal != "undefined" ? index$3.commonjsGlobal : index$3.commonjsGlobal, function DEF() { - var builtInProp, cycle, scheduling_queue, ToString = Object.prototype.toString, timer = typeof setImmediate != "undefined" ? function timer2(fn) { - return setImmediate(fn); - } : setTimeout; - try { - Object.defineProperty({}, "x", {}); - builtInProp = function builtInProp2(obj, name2, val, config) { - return Object.defineProperty(obj, name2, { - value: val, - writable: true, - configurable: config !== false - }); - }; - } catch (err) { - builtInProp = function builtInProp2(obj, name2, val) { - obj[name2] = val; - return obj; - }; - } - scheduling_queue = /* @__PURE__ */ function Queue() { - var first, last, item; - function Item(fn, self2) { - this.fn = fn; - this.self = self2; - this.next = void 0; - } - return { - add: function add(fn, self2) { - item = new Item(fn, self2); - if (last) { - last.next = item; - } else { - first = item; - } - last = item; - item = void 0; - }, - drain: function drain() { - var f = first; - first = last = cycle = void 0; - while (f) { - f.fn.call(f.self); - f = f.next; - } - } - }; - }(); - function schedule(fn, self2) { - scheduling_queue.add(fn, self2); - if (!cycle) { - cycle = timer(scheduling_queue.drain); - } - } - function isThenable(o) { - var _then, o_type = typeof o; - if (o != null && (o_type == "object" || o_type == "function")) { - _then = o.then; - } - return typeof _then == "function" ? _then : false; - } - function notify() { - for (var i = 0; i < this.chain.length; i++) { - notifyIsolated( - this, - this.state === 1 ? this.chain[i].success : this.chain[i].failure, - this.chain[i] - ); - } - this.chain.length = 0; - } - function notifyIsolated(self2, cb, chain) { - var ret, _then; - try { - if (cb === false) { - chain.reject(self2.msg); - } else { - if (cb === true) { - ret = self2.msg; - } else { - ret = cb.call(void 0, self2.msg); - } - if (ret === chain.promise) { - chain.reject(TypeError("Promise-chain cycle")); - } else if (_then = isThenable(ret)) { - _then.call(ret, chain.resolve, chain.reject); - } else { - chain.resolve(ret); - } - } - } catch (err) { - chain.reject(err); - } - } - function resolve(msg2) { - var _then, self2 = this; - if (self2.triggered) { - return; - } - self2.triggered = true; - if (self2.def) { - self2 = self2.def; - } - try { - if (_then = isThenable(msg2)) { - schedule(function() { - var def_wrapper = new MakeDefWrapper(self2); - try { - _then.call( - msg2, - function $resolve$() { - resolve.apply(def_wrapper, arguments); - }, - function $reject$() { - reject.apply(def_wrapper, arguments); - } - ); - } catch (err) { - reject.call(def_wrapper, err); - } - }); - } else { - self2.msg = msg2; - self2.state = 1; - if (self2.chain.length > 0) { - schedule(notify, self2); - } - } - } catch (err) { - reject.call(new MakeDefWrapper(self2), err); - } - } - function reject(msg2) { - var self2 = this; - if (self2.triggered) { - return; - } - self2.triggered = true; - if (self2.def) { - self2 = self2.def; - } - self2.msg = msg2; - self2.state = 2; - if (self2.chain.length > 0) { - schedule(notify, self2); - } - } - function iteratePromises(Constructor, arr, resolver, rejecter) { - for (var idx = 0; idx < arr.length; idx++) { - (function IIFE(idx2) { - Constructor.resolve(arr[idx2]).then( - function $resolver$(msg2) { - resolver(idx2, msg2); - }, - rejecter - ); - })(idx); - } - } - function MakeDefWrapper(self2) { - this.def = self2; - this.triggered = false; - } - function MakeDef(self2) { - this.promise = self2; - this.state = 0; - this.triggered = false; - this.chain = []; - this.msg = void 0; - } - function Promise2(executor) { - if (typeof executor != "function") { - throw TypeError("Not a function"); - } - if (this.__NPO__ !== 0) { - throw TypeError("Not a promise"); - } - this.__NPO__ = 1; - var def = new MakeDef(this); - this["then"] = function then(success, failure) { - var o = { - success: typeof success == "function" ? success : true, - failure: typeof failure == "function" ? failure : false - }; - o.promise = new this.constructor(function extractChain(resolve2, reject2) { - if (typeof resolve2 != "function" || typeof reject2 != "function") { - throw TypeError("Not a function"); - } - o.resolve = resolve2; - o.reject = reject2; - }); - def.chain.push(o); - if (def.state !== 0) { - schedule(notify, def); - } - return o.promise; - }; - this["catch"] = function $catch$(failure) { - return this.then(void 0, failure); - }; - try { - executor.call( - void 0, - function publicResolve(msg2) { - resolve.call(def, msg2); - }, - function publicReject(msg2) { - reject.call(def, msg2); - } - ); - } catch (err) { - reject.call(def, err); - } - } - var PromisePrototype = builtInProp( - {}, - "constructor", - Promise2, - /*configurable=*/ - false - ); - Promise2.prototype = PromisePrototype; - builtInProp( - PromisePrototype, - "__NPO__", - 0, - /*configurable=*/ - false - ); - builtInProp(Promise2, "resolve", function Promise$resolve(msg2) { - var Constructor = this; - if (msg2 && typeof msg2 == "object" && msg2.__NPO__ === 1) { - return msg2; - } - return new Constructor(function executor(resolve2, reject2) { - if (typeof resolve2 != "function" || typeof reject2 != "function") { - throw TypeError("Not a function"); - } - resolve2(msg2); - }); - }); - builtInProp(Promise2, "reject", function Promise$reject(msg2) { - return new this(function executor(resolve2, reject2) { - if (typeof resolve2 != "function" || typeof reject2 != "function") { - throw TypeError("Not a function"); - } - reject2(msg2); - }); - }); - builtInProp(Promise2, "all", function Promise$all(arr) { - var Constructor = this; - if (ToString.call(arr) != "[object Array]") { - return Constructor.reject(TypeError("Not an array")); - } - if (arr.length === 0) { - return Constructor.resolve([]); - } - return new Constructor(function executor(resolve2, reject2) { - if (typeof resolve2 != "function" || typeof reject2 != "function") { - throw TypeError("Not a function"); - } - var len = arr.length, msgs = Array(len), count2 = 0; - iteratePromises(Constructor, arr, function resolver(idx, msg2) { - msgs[idx] = msg2; - if (++count2 === len) { - resolve2(msgs); - } - }, reject2); - }); - }); - builtInProp(Promise2, "race", function Promise$race(arr) { - var Constructor = this; - if (ToString.call(arr) != "[object Array]") { - return Constructor.reject(TypeError("Not an array")); - } - return new Constructor(function executor(resolve2, reject2) { - if (typeof resolve2 != "function" || typeof reject2 != "function") { - throw TypeError("Not a function"); - } - iteratePromises(Constructor, arr, function resolver(idx, msg2) { - resolve2(msg2); - }, reject2); - }); - }); - return Promise2; - }); -})(npo_src); -var lib$1 = { exports: {} }; -var d3$G = { exports: {} }; -(function(module2) { - !(function() { - var d32 = { - version: "3.8.2" - }; - var d3_arraySlice = [].slice, d3_array = function(list) { - return d3_arraySlice.call(list); - }; - var d3_document = self.document; - function d3_documentElement(node) { - return node && (node.ownerDocument || node.document || node).documentElement; - } - function d3_window(node) { - return node && (node.ownerDocument && node.ownerDocument.defaultView || node.document && node || node.defaultView); - } - if (d3_document) { - try { - d3_array(d3_document.documentElement.childNodes)[0].nodeType; - } catch (e) { - d3_array = function(list) { - var i = list.length, array2 = new Array(i); - while (i--) array2[i] = list[i]; - return array2; - }; - } - } - if (!Date.now) Date.now = function() { - return +/* @__PURE__ */ new Date(); - }; - if (d3_document) { - try { - d3_document.createElement("DIV").style.setProperty("opacity", 0, ""); - } catch (error) { - var d3_element_prototype = this.Element.prototype, d3_element_setAttribute = d3_element_prototype.setAttribute, d3_element_setAttributeNS = d3_element_prototype.setAttributeNS, d3_style_prototype = this.CSSStyleDeclaration.prototype, d3_style_setProperty = d3_style_prototype.setProperty; - d3_element_prototype.setAttribute = function(name2, value2) { - d3_element_setAttribute.call(this, name2, value2 + ""); - }; - d3_element_prototype.setAttributeNS = function(space, local, value2) { - d3_element_setAttributeNS.call(this, space, local, value2 + ""); - }; - d3_style_prototype.setProperty = function(name2, value2, priority) { - d3_style_setProperty.call(this, name2, value2 + "", priority); - }; - } - } - d32.ascending = d3_ascending; - function d3_ascending(a, b) { - return a < b ? -1 : a > b ? 1 : a >= b ? 0 : NaN; - } - d32.descending = function(a, b) { - return b < a ? -1 : b > a ? 1 : b >= a ? 0 : NaN; - }; - d32.min = function(array2, f) { - var i = -1, n = array2.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array2[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array2[i]) != null && a > b) a = b; - } else { - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && a > b) a = b; - } - return a; - }; - d32.max = function(array2, f) { - var i = -1, n = array2.length, a, b; - if (arguments.length === 1) { - while (++i < n) if ((b = array2[i]) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = array2[i]) != null && b > a) a = b; - } else { - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { - a = b; - break; - } - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b > a) a = b; - } - return a; - }; - d32.extent = function(array2, f) { - var i = -1, n = array2.length, a, b, c; - if (arguments.length === 1) { - while (++i < n) if ((b = array2[i]) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = array2[i]) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } else { - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null && b >= b) { - a = c = b; - break; - } - while (++i < n) if ((b = f.call(array2, array2[i], i)) != null) { - if (a > b) a = b; - if (c < b) c = b; - } - } - return [a, c]; - }; - function d3_number(x) { - return x === null ? NaN : +x; - } - function d3_numeric(x) { - return !isNaN(x); - } - d32.sum = function(array2, f) { - var s = 0, n = array2.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = +array2[i])) s += a; - } else { - while (++i < n) if (d3_numeric(a = +f.call(array2, array2[i], i))) s += a; - } - return s; - }; - d32.mean = function(array2, f) { - var s = 0, n = array2.length, a, i = -1, j = n; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array2[i]))) s += a; - else --j; - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) s += a; - else --j; - } - if (j) return s / j; - }; - d32.quantile = function(values, p) { - var H = (values.length - 1) * p + 1, h = Math.floor(H), v = +values[h - 1], e = H - h; - return e ? v + e * (values[h] - v) : v; - }; - d32.median = function(array2, f) { - var numbers = [], n = array2.length, a, i = -1; - if (arguments.length === 1) { - while (++i < n) if (d3_numeric(a = d3_number(array2[i]))) numbers.push(a); - } else { - while (++i < n) if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) numbers.push(a); - } - if (numbers.length) return d32.quantile(numbers.sort(d3_ascending), 0.5); - }; - d32.variance = function(array2, f) { - var n = array2.length, m = 0, a, d, s = 0, i = -1, j = 0; - if (arguments.length === 1) { - while (++i < n) { - if (d3_numeric(a = d3_number(array2[i]))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } else { - while (++i < n) { - if (d3_numeric(a = d3_number(f.call(array2, array2[i], i)))) { - d = a - m; - m += d / ++j; - s += d * (a - m); - } - } - } - if (j > 1) return s / (j - 1); - }; - d32.deviation = function() { - var v = d32.variance.apply(this, arguments); - return v ? Math.sqrt(v) : v; - }; - function d3_bisector(compare) { - return { - left: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) < 0) lo = mid + 1; - else hi = mid; - } - return lo; - }, - right: function(a, x, lo, hi) { - if (arguments.length < 3) lo = 0; - if (arguments.length < 4) hi = a.length; - while (lo < hi) { - var mid = lo + hi >>> 1; - if (compare(a[mid], x) > 0) hi = mid; - else lo = mid + 1; - } - return lo; - } - }; - } - var d3_bisect = d3_bisector(d3_ascending); - d32.bisectLeft = d3_bisect.left; - d32.bisect = d32.bisectRight = d3_bisect.right; - d32.bisector = function(f) { - return d3_bisector(f.length === 1 ? function(d, x) { - return d3_ascending(f(d), x); - } : f); - }; - d32.shuffle = function(array2, i0, i1) { - if ((m = arguments.length) < 3) { - i1 = array2.length; - if (m < 2) i0 = 0; - } - var m = i1 - i0, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array2[m + i0], array2[m + i0] = array2[i + i0], array2[i + i0] = t; - } - return array2; - }; - d32.permute = function(array2, indexes) { - var i = indexes.length, permutes = new Array(i); - while (i--) permutes[i] = array2[indexes[i]]; - return permutes; - }; - d32.pairs = function(array2) { - var i = 0, n = array2.length - 1, p1 = array2[0], pairs = new Array(n < 0 ? 0 : n); - while (i < n) pairs[i] = [p1, p1 = array2[++i]]; - return pairs; - }; - d32.transpose = function(matrix2) { - if (!(n = matrix2.length)) return []; - for (var i = -1, m = d32.min(matrix2, d3_transposeLength), transpose2 = new Array(m); ++i < m; ) { - for (var j = -1, n, row = transpose2[i] = new Array(n); ++j < n; ) { - row[j] = matrix2[j][i]; - } - } - return transpose2; - }; - function d3_transposeLength(d) { - return d.length; - } - d32.zip = function() { - return d32.transpose(arguments); - }; - d32.keys = function(map2) { - var keys = []; - for (var key in map2) keys.push(key); - return keys; - }; - d32.values = function(map2) { - var values = []; - for (var key in map2) values.push(map2[key]); - return values; - }; - d32.entries = function(map2) { - var entries = []; - for (var key in map2) entries.push({ - key, - value: map2[key] - }); - return entries; - }; - d32.merge = function(arrays) { - var n = arrays.length, m, i = -1, j = 0, merged, array2; - while (++i < n) j += arrays[i].length; - merged = new Array(j); - while (--n >= 0) { - array2 = arrays[n]; - m = array2.length; - while (--m >= 0) { - merged[--j] = array2[m]; - } - } - return merged; - }; - var abs2 = Math.abs; - d32.range = function(start, stop, step) { - if (arguments.length < 3) { - step = 1; - if (arguments.length < 2) { - stop = start; - start = 0; - } - } - if ((stop - start) / step === Infinity) throw new Error("infinite range"); - var range = [], k = d3_range_integerScale(abs2(step)), i = -1, j; - start *= k, stop *= k, step *= k; - if (step < 0) while ((j = start + step * ++i) > stop) range.push(j / k); - else while ((j = start + step * ++i) < stop) range.push(j / k); - return range; - }; - function d3_range_integerScale(x) { - var k = 1; - while (x * k % 1) k *= 10; - return k; - } - function d3_class(ctor, properties) { - for (var key in properties) { - Object.defineProperty(ctor.prototype, key, { - value: properties[key], - enumerable: false - }); - } - } - d32.map = function(object2, f) { - var map2 = new d3_Map(); - if (object2 instanceof d3_Map) { - object2.forEach(function(key2, value2) { - map2.set(key2, value2); - }); - } else if (Array.isArray(object2)) { - var i = -1, n = object2.length, o; - if (arguments.length === 1) while (++i < n) map2.set(i, object2[i]); - else while (++i < n) map2.set(f.call(object2, o = object2[i], i), o); - } else { - for (var key in object2) map2.set(key, object2[key]); - } - return map2; - }; - function d3_Map() { - this._ = /* @__PURE__ */ Object.create(null); - } - var d3_map_proto = "__proto__", d3_map_zero = "\0"; - d3_class(d3_Map, { - has: d3_map_has, - get: function(key) { - return this._[d3_map_escape(key)]; - }, - set: function(key, value2) { - return this._[d3_map_escape(key)] = value2; - }, - remove: d3_map_remove, - keys: d3_map_keys, - values: function() { - var values = []; - for (var key in this._) values.push(this._[key]); - return values; - }, - entries: function() { - var entries = []; - for (var key in this._) entries.push({ - key: d3_map_unescape(key), - value: this._[key] - }); - return entries; - }, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key), this._[key]); - } - }); - function d3_map_escape(key) { - return (key += "") === d3_map_proto || key[0] === d3_map_zero ? d3_map_zero + key : key; - } - function d3_map_unescape(key) { - return (key += "")[0] === d3_map_zero ? key.slice(1) : key; - } - function d3_map_has(key) { - return d3_map_escape(key) in this._; - } - function d3_map_remove(key) { - return (key = d3_map_escape(key)) in this._ && delete this._[key]; - } - function d3_map_keys() { - var keys = []; - for (var key in this._) keys.push(d3_map_unescape(key)); - return keys; - } - function d3_map_size() { - var size = 0; - for (var key in this._) ++size; - return size; - } - function d3_map_empty() { - for (var key in this._) return false; - return true; - } - d32.nest = function() { - var nest = {}, keys = [], sortKeys = [], sortValues, rollup; - function map2(mapType, array2, depth) { - if (depth >= keys.length) return rollup ? rollup.call(nest, array2) : sortValues ? array2.sort(sortValues) : array2; - var i = -1, n = array2.length, key = keys[depth++], keyValue, object2, setter, valuesByKey = new d3_Map(), values; - while (++i < n) { - if (values = valuesByKey.get(keyValue = key(object2 = array2[i]))) { - values.push(object2); - } else { - valuesByKey.set(keyValue, [object2]); - } - } - if (mapType) { - object2 = mapType(); - setter = function(keyValue2, values2) { - object2.set(keyValue2, map2(mapType, values2, depth)); - }; - } else { - object2 = {}; - setter = function(keyValue2, values2) { - object2[keyValue2] = map2(mapType, values2, depth); - }; - } - valuesByKey.forEach(setter); - return object2; - } - function entries(map3, depth) { - if (depth >= keys.length) return map3; - var array2 = [], sortKey = sortKeys[depth++]; - map3.forEach(function(key, keyMap) { - array2.push({ - key, - values: entries(keyMap, depth) - }); - }); - return sortKey ? array2.sort(function(a, b) { - return sortKey(a.key, b.key); - }) : array2; - } - nest.map = function(array2, mapType) { - return map2(mapType, array2, 0); - }; - nest.entries = function(array2) { - return entries(map2(d32.map, array2, 0), 0); - }; - nest.key = function(d) { - keys.push(d); - return nest; - }; - nest.sortKeys = function(order) { - sortKeys[keys.length - 1] = order; - return nest; - }; - nest.sortValues = function(order) { - sortValues = order; - return nest; - }; - nest.rollup = function(f) { - rollup = f; - return nest; - }; - return nest; - }; - d32.set = function(array2) { - var set = new d3_Set(); - if (array2) for (var i = 0, n = array2.length; i < n; ++i) set.add(array2[i]); - return set; - }; - function d3_Set() { - this._ = /* @__PURE__ */ Object.create(null); - } - d3_class(d3_Set, { - has: d3_map_has, - add: function(key) { - this._[d3_map_escape(key += "")] = true; - return key; - }, - remove: d3_map_remove, - values: d3_map_keys, - size: d3_map_size, - empty: d3_map_empty, - forEach: function(f) { - for (var key in this._) f.call(this, d3_map_unescape(key)); - } - }); - d32.behavior = {}; - function d3_identity(d) { - return d; - } - d32.rebind = function(target, source) { - var i = 1, n = arguments.length, method; - while (++i < n) target[method = arguments[i]] = d3_rebind(target, source, source[method]); - return target; - }; - function d3_rebind(target, source, method) { - return function() { - var value2 = method.apply(source, arguments); - return value2 === source ? target : value2; - }; - } - function d3_vendorSymbol(object2, name2) { - if (name2 in object2) return name2; - name2 = name2.charAt(0).toUpperCase() + name2.slice(1); - for (var i = 0, n = d3_vendorPrefixes.length; i < n; ++i) { - var prefixName = d3_vendorPrefixes[i] + name2; - if (prefixName in object2) return prefixName; - } - } - var d3_vendorPrefixes = ["webkit", "ms", "moz", "Moz", "o", "O"]; - function d3_noop() { - } - d32.dispatch = function() { - var dispatch = new d3_dispatch(), i = -1, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - return dispatch; - }; - function d3_dispatch() { - } - d3_dispatch.prototype.on = function(type, listener) { - var i = type.indexOf("."), name2 = ""; - if (i >= 0) { - name2 = type.slice(i + 1); - type = type.slice(0, i); - } - if (type) return arguments.length < 2 ? this[type].on(name2) : this[type].on(name2, listener); - if (arguments.length === 2) { - if (listener == null) for (type in this) { - if (this.hasOwnProperty(type)) this[type].on(name2, null); - } - return this; - } - }; - function d3_dispatch_event(dispatch) { - var listeners2 = [], listenerByName = new d3_Map(); - function event() { - var z = listeners2, i = -1, n = z.length, l; - while (++i < n) if (l = z[i].on) l.apply(this, arguments); - return dispatch; - } - event.on = function(name2, listener) { - var l = listenerByName.get(name2), i; - if (arguments.length < 2) return l && l.on; - if (l) { - l.on = null; - listeners2 = listeners2.slice(0, i = listeners2.indexOf(l)).concat(listeners2.slice(i + 1)); - listenerByName.remove(name2); - } - if (listener) listeners2.push(listenerByName.set(name2, { - on: listener - })); - return dispatch; - }; - return event; - } - d32.event = null; - function d3_eventPreventDefault() { - d32.event.preventDefault(); - } - function d3_eventSource() { - var e = d32.event, s; - while (s = e.sourceEvent) e = s; - return e; - } - function d3_eventDispatch(target) { - var dispatch = new d3_dispatch(), i = 0, n = arguments.length; - while (++i < n) dispatch[arguments[i]] = d3_dispatch_event(dispatch); - dispatch.of = function(thiz, argumentz) { - return function(e1) { - try { - var e0 = e1.sourceEvent = d32.event; - e1.target = target; - d32.event = e1; - dispatch[e1.type].apply(thiz, argumentz); - } finally { - d32.event = e0; - } - }; - }; - return dispatch; - } - d32.requote = function(s) { - return s.replace(d3_requote_re, "\\$&"); - }; - var d3_requote_re = /[\\\^\$\*\+\?\|\[\]\(\)\.\{\}]/g; - var d3_subclass = {}.__proto__ ? function(object2, prototype) { - object2.__proto__ = prototype; - } : function(object2, prototype) { - for (var property in prototype) object2[property] = prototype[property]; - }; - function d3_selection(groups) { - d3_subclass(groups, d3_selectionPrototype); - return groups; - } - var d3_select = function(s, n) { - return n.querySelector(s); - }, d3_selectAll = function(s, n) { - return n.querySelectorAll(s); - }, d3_selectMatches = function(n, s) { - var d3_selectMatcher = n.matches || n[d3_vendorSymbol(n, "matchesSelector")]; - d3_selectMatches = function(n2, s2) { - return d3_selectMatcher.call(n2, s2); - }; - return d3_selectMatches(n, s); - }; - if (typeof Sizzle === "function") { - d3_select = function(s, n) { - return Sizzle(s, n)[0] || null; - }; - d3_selectAll = Sizzle; - d3_selectMatches = Sizzle.matchesSelector; - } - d32.selection = function() { - return d32.select(d3_document.documentElement); - }; - var d3_selectionPrototype = d32.selection.prototype = []; - d3_selectionPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, group, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(subnode = selector.call(node, node.__data__, i, j)); - if (subnode && "__data__" in node) subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selector(selector) { - return typeof selector === "function" ? selector : function() { - return d3_select(selector, this); - }; - } - d3_selectionPrototype.selectAll = function(selector) { - var subgroups = [], subgroup, node; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroups.push(subgroup = d3_array(selector.call(node, node.__data__, i, j))); - subgroup.parentNode = node; - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_selectorAll(selector) { - return typeof selector === "function" ? selector : function() { - return d3_selectAll(selector, this); - }; - } - var d3_nsXhtml = "http://www.w3.org/1999/xhtml"; - var d3_nsPrefix = { - svg: "http://www.w3.org/2000/svg", - xhtml: d3_nsXhtml, - xlink: "http://www.w3.org/1999/xlink", - xml: "http://www.w3.org/XML/1998/namespace", - xmlns: "http://www.w3.org/2000/xmlns/" - }; - d32.ns = { - prefix: d3_nsPrefix, - qualify: function(name2) { - var i = name2.indexOf(":"), prefix = name2; - if (i >= 0 && (prefix = name2.slice(0, i)) !== "xmlns") name2 = name2.slice(i + 1); - return d3_nsPrefix.hasOwnProperty(prefix) ? { - space: d3_nsPrefix[prefix], - local: name2 - } : name2; - } - }; - d3_selectionPrototype.attr = function(name2, value2) { - if (arguments.length < 2) { - if (typeof name2 === "string") { - var node = this.node(); - name2 = d32.ns.qualify(name2); - return name2.local ? node.getAttributeNS(name2.space, name2.local) : node.getAttribute(name2); - } - for (value2 in name2) this.each(d3_selection_attr(value2, name2[value2])); - return this; - } - return this.each(d3_selection_attr(name2, value2)); - }; - function d3_selection_attr(name2, value2) { - name2 = d32.ns.qualify(name2); - function attrNull() { - this.removeAttribute(name2); - } - function attrNullNS() { - this.removeAttributeNS(name2.space, name2.local); - } - function attrConstant() { - this.setAttribute(name2, value2); - } - function attrConstantNS() { - this.setAttributeNS(name2.space, name2.local, value2); - } - function attrFunction() { - var x = value2.apply(this, arguments); - if (x == null) this.removeAttribute(name2); - else this.setAttribute(name2, x); - } - function attrFunctionNS() { - var x = value2.apply(this, arguments); - if (x == null) this.removeAttributeNS(name2.space, name2.local); - else this.setAttributeNS(name2.space, name2.local, x); - } - return value2 == null ? name2.local ? attrNullNS : attrNull : typeof value2 === "function" ? name2.local ? attrFunctionNS : attrFunction : name2.local ? attrConstantNS : attrConstant; - } - function d3_collapse(s) { - return s.trim().replace(/\s+/g, " "); - } - d3_selectionPrototype.classed = function(name2, value2) { - if (arguments.length < 2) { - if (typeof name2 === "string") { - var node = this.node(), n = (name2 = d3_selection_classes(name2)).length, i = -1; - if (value2 = node.classList) { - while (++i < n) if (!value2.contains(name2[i])) return false; - } else { - value2 = node.getAttribute("class"); - while (++i < n) if (!d3_selection_classedRe(name2[i]).test(value2)) return false; - } - return true; - } - for (value2 in name2) this.each(d3_selection_classed(value2, name2[value2])); - return this; - } - return this.each(d3_selection_classed(name2, value2)); - }; - function d3_selection_classedRe(name2) { - return new RegExp("(?:^|\\s+)" + d32.requote(name2) + "(?:\\s+|$)", "g"); - } - function d3_selection_classes(name2) { - return (name2 + "").trim().split(/^|\s+/); - } - function d3_selection_classed(name2, value2) { - name2 = d3_selection_classes(name2).map(d3_selection_classedName); - var n = name2.length; - function classedConstant() { - var i = -1; - while (++i < n) name2[i](this, value2); - } - function classedFunction() { - var i = -1, x = value2.apply(this, arguments); - while (++i < n) name2[i](this, x); - } - return typeof value2 === "function" ? classedFunction : classedConstant; - } - function d3_selection_classedName(name2) { - var re2 = d3_selection_classedRe(name2); - return function(node, value2) { - if (c = node.classList) return value2 ? c.add(name2) : c.remove(name2); - var c = node.getAttribute("class") || ""; - if (value2) { - re2.lastIndex = 0; - if (!re2.test(c)) node.setAttribute("class", d3_collapse(c + " " + name2)); - } else { - node.setAttribute("class", d3_collapse(c.replace(re2, " "))); - } - }; - } - d3_selectionPrototype.style = function(name2, value2, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name2 !== "string") { - if (n < 2) value2 = ""; - for (priority in name2) this.each(d3_selection_style(priority, name2[priority], value2)); - return this; - } - if (n < 2) { - var node = this.node(); - return d3_window(node).getComputedStyle(node, null).getPropertyValue(name2); - } - priority = ""; - } - return this.each(d3_selection_style(name2, value2, priority)); - }; - function d3_selection_style(name2, value2, priority) { - function styleNull() { - this.style.removeProperty(name2); - } - function styleConstant() { - this.style.setProperty(name2, value2, priority); - } - function styleFunction() { - var x = value2.apply(this, arguments); - if (x == null) this.style.removeProperty(name2); - else this.style.setProperty(name2, x, priority); - } - return value2 == null ? styleNull : typeof value2 === "function" ? styleFunction : styleConstant; - } - d3_selectionPrototype.property = function(name2, value2) { - if (arguments.length < 2) { - if (typeof name2 === "string") return this.node()[name2]; - for (value2 in name2) this.each(d3_selection_property(value2, name2[value2])); - return this; - } - return this.each(d3_selection_property(name2, value2)); - }; - function d3_selection_property(name2, value2) { - function propertyNull() { - delete this[name2]; - } - function propertyConstant() { - this[name2] = value2; - } - function propertyFunction() { - var x = value2.apply(this, arguments); - if (x == null) delete this[name2]; - else this[name2] = x; - } - return value2 == null ? propertyNull : typeof value2 === "function" ? propertyFunction : propertyConstant; - } - d3_selectionPrototype.text = function(value2) { - return arguments.length ? this.each(typeof value2 === "function" ? function() { - var v = value2.apply(this, arguments); - this.textContent = v == null ? "" : v; - } : value2 == null ? function() { - this.textContent = ""; - } : function() { - this.textContent = value2; - }) : this.node().textContent; - }; - d3_selectionPrototype.html = function(value2) { - return arguments.length ? this.each(typeof value2 === "function" ? function() { - var v = value2.apply(this, arguments); - this.innerHTML = v == null ? "" : v; - } : value2 == null ? function() { - this.innerHTML = ""; - } : function() { - this.innerHTML = value2; - }) : this.node().innerHTML; - }; - d3_selectionPrototype.append = function(name2) { - name2 = d3_selection_creator(name2); - return this.select(function() { - return this.appendChild(name2.apply(this, arguments)); - }); - }; - function d3_selection_creator(name2) { - function create2() { - var document2 = this.ownerDocument, namespace = this.namespaceURI; - return namespace === d3_nsXhtml && document2.documentElement.namespaceURI === d3_nsXhtml ? document2.createElement(name2) : document2.createElementNS(namespace, name2); - } - function createNS() { - return this.ownerDocument.createElementNS(name2.space, name2.local); - } - return typeof name2 === "function" ? name2 : (name2 = d32.ns.qualify(name2)).local ? createNS : create2; - } - d3_selectionPrototype.insert = function(name2, before) { - name2 = d3_selection_creator(name2); - before = d3_selection_selector(before); - return this.select(function() { - return this.insertBefore(name2.apply(this, arguments), before.apply(this, arguments) || null); - }); - }; - d3_selectionPrototype.remove = function() { - return this.each(d3_selectionRemove); - }; - function d3_selectionRemove() { - var parent = this.parentNode; - if (parent) parent.removeChild(this); - } - d3_selectionPrototype.data = function(value2, key) { - var i = -1, n = this.length, group, node; - if (!arguments.length) { - value2 = new Array(n = (group = this[0]).length); - while (++i < n) { - if (node = group[i]) { - value2[i] = node.__data__; - } - } - return value2; - } - function bind(group2, groupData) { - var i2, n2 = group2.length, m = groupData.length, n0 = Math.min(n2, m), updateNodes = new Array(m), enterNodes = new Array(m), exitNodes = new Array(n2), node2, nodeData; - if (key) { - var nodeByKeyValue = new d3_Map(), keyValues = new Array(n2), keyValue; - for (i2 = -1; ++i2 < n2; ) { - if (node2 = group2[i2]) { - if (nodeByKeyValue.has(keyValue = key.call(node2, node2.__data__, i2))) { - exitNodes[i2] = node2; - } else { - nodeByKeyValue.set(keyValue, node2); - } - keyValues[i2] = keyValue; - } - } - for (i2 = -1; ++i2 < m; ) { - if (!(node2 = nodeByKeyValue.get(keyValue = key.call(groupData, nodeData = groupData[i2], i2)))) { - enterNodes[i2] = d3_selection_dataNode(nodeData); - } else if (node2 !== true) { - updateNodes[i2] = node2; - node2.__data__ = nodeData; - } - nodeByKeyValue.set(keyValue, true); - } - for (i2 = -1; ++i2 < n2; ) { - if (i2 in keyValues && nodeByKeyValue.get(keyValues[i2]) !== true) { - exitNodes[i2] = group2[i2]; - } - } - } else { - for (i2 = -1; ++i2 < n0; ) { - node2 = group2[i2]; - nodeData = groupData[i2]; - if (node2) { - node2.__data__ = nodeData; - updateNodes[i2] = node2; - } else { - enterNodes[i2] = d3_selection_dataNode(nodeData); - } - } - for (; i2 < m; ++i2) { - enterNodes[i2] = d3_selection_dataNode(groupData[i2]); - } - for (; i2 < n2; ++i2) { - exitNodes[i2] = group2[i2]; - } - } - enterNodes.update = updateNodes; - enterNodes.parentNode = updateNodes.parentNode = exitNodes.parentNode = group2.parentNode; - enter.push(enterNodes); - update2.push(updateNodes); - exit.push(exitNodes); - } - var enter = d3_selection_enter([]), update2 = d3_selection([]), exit = d3_selection([]); - if (typeof value2 === "function") { - while (++i < n) { - bind(group = this[i], value2.call(group, group.parentNode.__data__, i)); - } - } else { - while (++i < n) { - bind(group = this[i], value2); - } - } - update2.enter = function() { - return enter; - }; - update2.exit = function() { - return exit; - }; - return update2; - }; - function d3_selection_dataNode(data) { - return { - __data__: data - }; - } - d3_selectionPrototype.datum = function(value2) { - return arguments.length ? this.property("__data__", value2) : this.property("__data__"); - }; - d3_selectionPrototype.filter = function(filter2) { - var subgroups = [], subgroup, group, node; - if (typeof filter2 !== "function") filter2 = d3_selection_filter(filter2); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - subgroup.parentNode = (group = this[j]).parentNode; - for (var i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter2.call(node, node.__data__, i, j)) { - subgroup.push(node); - } - } - } - return d3_selection(subgroups); - }; - function d3_selection_filter(selector) { - return function() { - return d3_selectMatches(this, selector); - }; - } - d3_selectionPrototype.order = function() { - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = group.length - 1, next = group[i], node; --i >= 0; ) { - if (node = group[i]) { - if (next && next !== node.nextSibling) next.parentNode.insertBefore(node, next); - next = node; - } - } - } - return this; - }; - d3_selectionPrototype.sort = function(comparator) { - comparator = d3_selection_sortComparator.apply(this, arguments); - for (var j = -1, m = this.length; ++j < m; ) this[j].sort(comparator); - return this.order(); - }; - function d3_selection_sortComparator(comparator) { - if (!arguments.length) comparator = d3_ascending; - return function(a, b) { - return a && b ? comparator(a.__data__, b.__data__) : !a - !b; - }; - } - d3_selectionPrototype.each = function(callback) { - return d3_selection_each(this, function(node, i, j) { - callback.call(node, node.__data__, i, j); - }); - }; - function d3_selection_each(groups, callback) { - for (var j = 0, m = groups.length; j < m; j++) { - for (var group = groups[j], i = 0, n = group.length, node; i < n; i++) { - if (node = group[i]) callback(node, i, j); - } - } - return groups; - } - d3_selectionPrototype.call = function(callback) { - var args = d3_array(arguments); - callback.apply(args[0] = this, args); - return this; - }; - d3_selectionPrototype.empty = function() { - return !this.node(); - }; - d3_selectionPrototype.node = function() { - for (var j = 0, m = this.length; j < m; j++) { - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - var node = group[i]; - if (node) return node; - } - } - return null; - }; - d3_selectionPrototype.size = function() { - var n = 0; - d3_selection_each(this, function() { - ++n; - }); - return n; - }; - function d3_selection_enter(selection) { - d3_subclass(selection, d3_selection_enterPrototype); - return selection; - } - var d3_selection_enterPrototype = []; - d32.selection.enter = d3_selection_enter; - d32.selection.enter.prototype = d3_selection_enterPrototype; - d3_selection_enterPrototype.append = d3_selectionPrototype.append; - d3_selection_enterPrototype.empty = d3_selectionPrototype.empty; - d3_selection_enterPrototype.node = d3_selectionPrototype.node; - d3_selection_enterPrototype.call = d3_selectionPrototype.call; - d3_selection_enterPrototype.size = d3_selectionPrototype.size; - d3_selection_enterPrototype.select = function(selector) { - var subgroups = [], subgroup, subnode, upgroup, group, node; - for (var j = -1, m = this.length; ++j < m; ) { - upgroup = (group = this[j]).update; - subgroups.push(subgroup = []); - subgroup.parentNode = group.parentNode; - for (var i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - subgroup.push(upgroup[i] = subnode = selector.call(group.parentNode, node.__data__, i, j)); - subnode.__data__ = node.__data__; - } else { - subgroup.push(null); - } - } - } - return d3_selection(subgroups); - }; - d3_selection_enterPrototype.insert = function(name2, before) { - if (arguments.length < 2) before = d3_selection_enterInsertBefore(this); - return d3_selectionPrototype.insert.call(this, name2, before); - }; - function d3_selection_enterInsertBefore(enter) { - var i0, j0; - return function(d, i, j) { - var group = enter[j].update, n = group.length, node; - if (j != j0) j0 = j, i0 = 0; - if (i >= i0) i0 = i + 1; - while (!(node = group[i0]) && ++i0 < n) ; - return node; - }; - } - d32.select = function(node) { - var group; - if (typeof node === "string") { - group = [d3_select(node, d3_document)]; - group.parentNode = d3_document.documentElement; - } else { - group = [node]; - group.parentNode = d3_documentElement(node); - } - return d3_selection([group]); - }; - d32.selectAll = function(nodes) { - var group; - if (typeof nodes === "string") { - group = d3_array(d3_selectAll(nodes, d3_document)); - group.parentNode = d3_document.documentElement; - } else { - group = d3_array(nodes); - group.parentNode = null; - } - return d3_selection([group]); - }; - d3_selectionPrototype.on = function(type, listener, capture) { - var n = arguments.length; - if (n < 3) { - if (typeof type !== "string") { - if (n < 2) listener = false; - for (capture in type) this.each(d3_selection_on(capture, type[capture], listener)); - return this; - } - if (n < 2) return (n = this.node()["__on" + type]) && n._; - capture = false; - } - return this.each(d3_selection_on(type, listener, capture)); - }; - function d3_selection_on(type, listener, capture) { - var name2 = "__on" + type, i = type.indexOf("."), wrap = d3_selection_onListener; - if (i > 0) type = type.slice(0, i); - var filter2 = d3_selection_onFilters.get(type); - if (filter2) type = filter2, wrap = d3_selection_onFilter; - function onRemove() { - var l = this[name2]; - if (l) { - this.removeEventListener(type, l, l.$); - delete this[name2]; - } - } - function onAdd() { - var l = wrap(listener, d3_array(arguments)); - onRemove.call(this); - this.addEventListener(type, this[name2] = l, l.$ = capture); - l._ = listener; - } - function removeAll() { - var re2 = new RegExp("^__on([^.]+)" + d32.requote(type) + "$"), match; - for (var name3 in this) { - if (match = name3.match(re2)) { - var l = this[name3]; - this.removeEventListener(match[1], l, l.$); - delete this[name3]; - } - } - } - return i ? listener ? onAdd : onRemove : listener ? d3_noop : removeAll; - } - var d3_selection_onFilters = d32.map({ - mouseenter: "mouseover", - mouseleave: "mouseout" - }); - if (d3_document) { - d3_selection_onFilters.forEach(function(k) { - if ("on" + k in d3_document) d3_selection_onFilters.remove(k); - }); - } - function d3_selection_onListener(listener, argumentz) { - return function(e) { - var o = d32.event; - d32.event = e; - argumentz[0] = this.__data__; - try { - listener.apply(this, argumentz); - } finally { - d32.event = o; - } - }; - } - function d3_selection_onFilter(listener, argumentz) { - var l = d3_selection_onListener(listener, argumentz); - return function(e) { - var target = this, related = e.relatedTarget; - if (!related || related !== target && !(related.compareDocumentPosition(target) & 8)) { - l.call(target, e); - } - }; - } - var d3_event_dragSelect, d3_event_dragId = 0; - function d3_event_dragSuppress(node) { - var name2 = ".dragsuppress-" + ++d3_event_dragId, click3 = "click" + name2, w = d32.select(d3_window(node)).on("touchmove" + name2, d3_eventPreventDefault).on("dragstart" + name2, d3_eventPreventDefault).on("selectstart" + name2, d3_eventPreventDefault); - if (d3_event_dragSelect == null) { - d3_event_dragSelect = "onselectstart" in node ? false : d3_vendorSymbol(node.style, "userSelect"); - } - if (d3_event_dragSelect) { - var style5 = d3_documentElement(node).style, select3 = style5[d3_event_dragSelect]; - style5[d3_event_dragSelect] = "none"; - } - return function(suppressClick) { - w.on(name2, null); - if (d3_event_dragSelect) style5[d3_event_dragSelect] = select3; - if (suppressClick) { - var off = function() { - w.on(click3, null); - }; - w.on(click3, function() { - d3_eventPreventDefault(); - off(); - }, true); - setTimeout(off, 0); - } - }; - } - d32.mouse = function(container) { - return d3_mousePoint(container, d3_eventSource()); - }; - var d3_mouse_bug44083 = this.navigator && /WebKit/.test(this.navigator.userAgent) ? -1 : 0; - function d3_mousePoint(container, e) { - if (e.changedTouches) e = e.changedTouches[0]; - var svg = container.ownerSVGElement || container; - if (svg.createSVGPoint) { - var point = svg.createSVGPoint(); - if (d3_mouse_bug44083 < 0) { - var window2 = d3_window(container); - if (window2.scrollX || window2.scrollY) { - svg = d32.select("body").append("svg").style({ - position: "absolute", - top: 0, - left: 0, - margin: 0, - padding: 0, - border: "none" - }, "important"); - var ctm = svg[0][0].getScreenCTM(); - d3_mouse_bug44083 = !(ctm.f || ctm.e); - svg.remove(); - } - } - if (d3_mouse_bug44083) point.x = e.pageX, point.y = e.pageY; - else point.x = e.clientX, point.y = e.clientY; - point = point.matrixTransform(container.getScreenCTM().inverse()); - return [point.x, point.y]; - } - var rect2 = container.getBoundingClientRect(); - return [e.clientX - rect2.left - container.clientLeft, e.clientY - rect2.top - container.clientTop]; - } - d32.touch = function(container, touches, identifier) { - if (arguments.length < 3) identifier = touches, touches = d3_eventSource().changedTouches; - if (touches) for (var i = 0, n = touches.length, touch; i < n; ++i) { - if ((touch = touches[i]).identifier === identifier) { - return d3_mousePoint(container, touch); - } - } - }; - d32.behavior.drag = function() { - var event = d3_eventDispatch(drag, "drag", "dragstart", "dragend"), origin = null, mousedown = dragstart(d3_noop, d32.mouse, d3_window, "mousemove", "mouseup"), touchstart = dragstart(d3_behavior_dragTouchId, d32.touch, d3_identity, "touchmove", "touchend"); - function drag() { - this.on("mousedown.drag", mousedown).on("touchstart.drag", touchstart); - } - function dragstart(id, position, subject, move, end) { - return function() { - var that = this, target = d32.event.target.correspondingElement || d32.event.target, parent = that.parentNode, dispatch = event.of(that, arguments), dragged = 0, dragId = id(), dragName = ".drag" + (dragId == null ? "" : "-" + dragId), dragOffset, dragSubject = d32.select(subject(target)).on(move + dragName, moved).on(end + dragName, ended), dragRestore = d3_event_dragSuppress(target), position0 = position(parent, dragId); - if (origin) { - dragOffset = origin.apply(that, arguments); - dragOffset = [dragOffset.x - position0[0], dragOffset.y - position0[1]]; - } else { - dragOffset = [0, 0]; - } - dispatch({ - type: "dragstart" - }); - function moved() { - var position1 = position(parent, dragId), dx, dy; - if (!position1) return; - dx = position1[0] - position0[0]; - dy = position1[1] - position0[1]; - dragged |= dx | dy; - position0 = position1; - dispatch({ - type: "drag", - x: position1[0] + dragOffset[0], - y: position1[1] + dragOffset[1], - dx, - dy - }); - } - function ended() { - if (!position(parent, dragId)) return; - dragSubject.on(move + dragName, null).on(end + dragName, null); - dragRestore(dragged); - dispatch({ - type: "dragend" - }); - } - }; - } - drag.origin = function(x) { - if (!arguments.length) return origin; - origin = x; - return drag; - }; - return d32.rebind(drag, event, "on"); - }; - function d3_behavior_dragTouchId() { - return d32.event.changedTouches[0].identifier; - } - d32.touches = function(container, touches) { - if (arguments.length < 2) touches = d3_eventSource().touches; - return touches ? d3_array(touches).map(function(touch) { - var point = d3_mousePoint(container, touch); - point.identifier = touch.identifier; - return point; - }) : []; - }; - var ε = 1e-6, ε2 = ε * ε, π2 = Math.PI, τ = 2 * π2, τε = τ - ε, halfπ = π2 / 2, d3_radians = π2 / 180, d3_degrees = 180 / π2; - function d3_cross2d(a, b, c) { - return (b[0] - a[0]) * (c[1] - a[1]) - (b[1] - a[1]) * (c[0] - a[0]); - } - function d3_asin(x) { - return x > 1 ? halfπ : x < -1 ? -halfπ : Math.asin(x); - } - function d3_sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; - } - function d3_cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; - } - function d3_tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); - } - var ρ = Math.SQRT2, ρ2 = 2, ρ4 = 4; - d32.interpolateZoom = function(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; - if (d2 < ε2) { - S = Math.log(w1 / w0) / ρ; - i = function(t) { - return [ux0 + t * dx, uy0 + t * dy, w0 * Math.exp(ρ * t * S)]; - }; - } else { - var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + ρ4 * d2) / (2 * w0 * ρ2 * d1), b1 = (w1 * w1 - w0 * w0 - ρ4 * d2) / (2 * w1 * ρ2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); - S = (r1 - r0) / ρ; - i = function(t) { - var s = t * S, coshr0 = d3_cosh(r0), u = w0 / (ρ2 * d1) * (coshr0 * d3_tanh(ρ * s + r0) - d3_sinh(r0)); - return [ux0 + u * dx, uy0 + u * dy, w0 * coshr0 / d3_cosh(ρ * s + r0)]; - }; - } - i.duration = S * 1e3; - return i; - }; - d32.behavior.zoom = function() { - var view = { - x: 0, - y: 0, - k: 1 - }, translate0, center0, center, size = [960, 500], scaleExtent = d3_behavior_zoomInfinity, duration = 250, zooming = 0, mousedown = "mousedown.zoom", mousemove = "mousemove.zoom", mouseup = "mouseup.zoom", mousewheelTimer, touchstart = "touchstart.zoom", touchtime, event = d3_eventDispatch(zoom2, "zoomstart", "zoom", "zoomend"), x0, x1, y0, y1; - if (!d3_behavior_zoomWheel) { - d3_behavior_zoomWheel = "onwheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return -d32.event.deltaY * (d32.event.deltaMode ? 120 : 1); - }, "wheel") : "onmousewheel" in d3_document ? (d3_behavior_zoomDelta = function() { - return d32.event.wheelDelta; - }, "mousewheel") : (d3_behavior_zoomDelta = function() { - return -d32.event.detail; - }, "MozMousePixelScroll"); - } - function zoom2(g) { - g.on(mousedown, mousedowned).on(d3_behavior_zoomWheel + ".zoom", mousewheeled).on("dblclick.zoom", dblclicked).on(touchstart, touchstarted); - } - zoom2.event = function(g) { - g.each(function() { - var dispatch = event.of(this, arguments), view1 = view; - if (d3_transitionInheritId) { - d32.select(this).transition().each("start.zoom", function() { - view = this.__chart__ || { - x: 0, - y: 0, - k: 1 - }; - zoomstarted(dispatch); - }).tween("zoom:zoom", function() { - var dx = size[0], dy = size[1], cx = center0 ? center0[0] : dx / 2, cy = center0 ? center0[1] : dy / 2, i = d32.interpolateZoom([(cx - view.x) / view.k, (cy - view.y) / view.k, dx / view.k], [(cx - view1.x) / view1.k, (cy - view1.y) / view1.k, dx / view1.k]); - return function(t) { - var l = i(t), k = dx / l[2]; - this.__chart__ = view = { - x: cx - l[0] * k, - y: cy - l[1] * k, - k - }; - zoomed(dispatch); - }; - }).each("interrupt.zoom", function() { - zoomended(dispatch); - }).each("end.zoom", function() { - zoomended(dispatch); - }); - } else { - this.__chart__ = view; - zoomstarted(dispatch); - zoomed(dispatch); - zoomended(dispatch); - } - }); - }; - zoom2.translate = function(_2) { - if (!arguments.length) return [view.x, view.y]; - view = { - x: +_2[0], - y: +_2[1], - k: view.k - }; - rescale(); - return zoom2; - }; - zoom2.scale = function(_2) { - if (!arguments.length) return view.k; - view = { - x: view.x, - y: view.y, - k: null - }; - scaleTo(+_2); - rescale(); - return zoom2; - }; - zoom2.scaleExtent = function(_2) { - if (!arguments.length) return scaleExtent; - scaleExtent = _2 == null ? d3_behavior_zoomInfinity : [+_2[0], +_2[1]]; - return zoom2; - }; - zoom2.center = function(_2) { - if (!arguments.length) return center; - center = _2 && [+_2[0], +_2[1]]; - return zoom2; - }; - zoom2.size = function(_2) { - if (!arguments.length) return size; - size = _2 && [+_2[0], +_2[1]]; - return zoom2; - }; - zoom2.duration = function(_2) { - if (!arguments.length) return duration; - duration = +_2; - return zoom2; - }; - zoom2.x = function(z) { - if (!arguments.length) return x1; - x1 = z; - x0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom2; - }; - zoom2.y = function(z) { - if (!arguments.length) return y1; - y1 = z; - y0 = z.copy(); - view = { - x: 0, - y: 0, - k: 1 - }; - return zoom2; - }; - function location(p) { - return [(p[0] - view.x) / view.k, (p[1] - view.y) / view.k]; - } - function point(l) { - return [l[0] * view.k + view.x, l[1] * view.k + view.y]; - } - function scaleTo(s) { - view.k = Math.max(scaleExtent[0], Math.min(scaleExtent[1], s)); - } - function translateTo(p, l) { - l = point(l); - view.x += p[0] - l[0]; - view.y += p[1] - l[1]; - } - function zoomTo(that, p, l, k) { - that.__chart__ = { - x: view.x, - y: view.y, - k: view.k - }; - scaleTo(Math.pow(2, k)); - translateTo(center0 = p, l); - that = d32.select(that); - if (duration > 0) that = that.transition().duration(duration); - that.call(zoom2.event); - } - function rescale() { - if (x1) x1.domain(x0.range().map(function(x) { - return (x - view.x) / view.k; - }).map(x0.invert)); - if (y1) y1.domain(y0.range().map(function(y) { - return (y - view.y) / view.k; - }).map(y0.invert)); - } - function zoomstarted(dispatch) { - if (!zooming++) dispatch({ - type: "zoomstart" - }); - } - function zoomed(dispatch) { - rescale(); - dispatch({ - type: "zoom", - scale: view.k, - translate: [view.x, view.y] - }); - } - function zoomended(dispatch) { - if (!--zooming) dispatch({ - type: "zoomend" - }), center0 = null; - } - function mousedowned() { - var that = this, dispatch = event.of(that, arguments), dragged = 0, subject = d32.select(d3_window(that)).on(mousemove, moved).on(mouseup, ended), location0 = location(d32.mouse(that)), dragRestore = d3_event_dragSuppress(that); - d3_selection_interrupt.call(that); - zoomstarted(dispatch); - function moved() { - dragged = 1; - translateTo(d32.mouse(that), location0); - zoomed(dispatch); - } - function ended() { - subject.on(mousemove, null).on(mouseup, null); - dragRestore(dragged); - zoomended(dispatch); - } - } - function touchstarted() { - var that = this, dispatch = event.of(that, arguments), locations0 = {}, distance0 = 0, scale0, zoomName = ".zoom-" + d32.event.changedTouches[0].identifier, touchmove = "touchmove" + zoomName, touchend = "touchend" + zoomName, targets = [], subject = d32.select(that), dragRestore = d3_event_dragSuppress(that); - started(); - zoomstarted(dispatch); - subject.on(mousedown, null).on(touchstart, started); - function relocate() { - var touches = d32.touches(that); - scale0 = view.k; - touches.forEach(function(t) { - if (t.identifier in locations0) locations0[t.identifier] = location(t); - }); - return touches; - } - function started() { - var target = d32.event.target; - d32.select(target).on(touchmove, moved).on(touchend, ended); - targets.push(target); - var changed = d32.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - locations0[changed[i].identifier] = null; - } - var touches = relocate(), now = Date.now(); - if (touches.length === 1) { - if (now - touchtime < 500) { - var p = touches[0]; - zoomTo(that, p, locations0[p.identifier], Math.floor(Math.log(view.k) / Math.LN2) + 1); - d3_eventPreventDefault(); - } - touchtime = now; - } else if (touches.length > 1) { - var p = touches[0], q = touches[1], dx = p[0] - q[0], dy = p[1] - q[1]; - distance0 = dx * dx + dy * dy; - } - } - function moved() { - var touches = d32.touches(that), p0, l0, p1, l1; - d3_selection_interrupt.call(that); - for (var i = 0, n = touches.length; i < n; ++i, l1 = null) { - p1 = touches[i]; - if (l1 = locations0[p1.identifier]) { - if (l0) break; - p0 = p1, l0 = l1; - } - } - if (l1) { - var distance1 = (distance1 = p1[0] - p0[0]) * distance1 + (distance1 = p1[1] - p0[1]) * distance1, scale1 = distance0 && Math.sqrt(distance1 / distance0); - p0 = [(p0[0] + p1[0]) / 2, (p0[1] + p1[1]) / 2]; - l0 = [(l0[0] + l1[0]) / 2, (l0[1] + l1[1]) / 2]; - scaleTo(scale1 * scale0); - } - touchtime = null; - translateTo(p0, l0); - zoomed(dispatch); - } - function ended() { - if (d32.event.touches.length) { - var changed = d32.event.changedTouches; - for (var i = 0, n = changed.length; i < n; ++i) { - delete locations0[changed[i].identifier]; - } - for (var identifier in locations0) { - return void relocate(); - } - } - d32.selectAll(targets).on(zoomName, null); - subject.on(mousedown, mousedowned).on(touchstart, touchstarted); - dragRestore(); - zoomended(dispatch); - } - } - function mousewheeled() { - var dispatch = event.of(this, arguments); - if (mousewheelTimer) clearTimeout(mousewheelTimer); - else d3_selection_interrupt.call(this), translate0 = location(center0 = center || d32.mouse(this)), zoomstarted(dispatch); - mousewheelTimer = setTimeout(function() { - mousewheelTimer = null; - zoomended(dispatch); - }, 50); - d3_eventPreventDefault(); - scaleTo(Math.pow(2, d3_behavior_zoomDelta() * 2e-3) * view.k); - translateTo(center0, translate0); - zoomed(dispatch); - } - function dblclicked() { - var p = d32.mouse(this), k = Math.log(view.k) / Math.LN2; - zoomTo(this, p, location(p), d32.event.shiftKey ? Math.ceil(k) - 1 : Math.floor(k) + 1); - } - return d32.rebind(zoom2, event, "on"); - }; - var d3_behavior_zoomInfinity = [0, Infinity], d3_behavior_zoomDelta, d3_behavior_zoomWheel; - d32.color = d3_color; - function d3_color() { - } - d3_color.prototype.toString = function() { - return this.rgb() + ""; - }; - d32.hsl = d3_hsl; - function d3_hsl(h, s, l) { - return this instanceof d3_hsl ? void (this.h = +h, this.s = +s, this.l = +l) : arguments.length < 2 ? h instanceof d3_hsl ? new d3_hsl(h.h, h.s, h.l) : d3_rgb_parse("" + h, d3_rgb_hsl, d3_hsl) : new d3_hsl(h, s, l); - } - var d3_hslPrototype = d3_hsl.prototype = new d3_color(); - d3_hslPrototype.brighter = function(k) { - k = Math.pow(0.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, this.l / k); - }; - d3_hslPrototype.darker = function(k) { - k = Math.pow(0.7, arguments.length ? k : 1); - return new d3_hsl(this.h, this.s, k * this.l); - }; - d3_hslPrototype.rgb = function() { - return d3_hsl_rgb(this.h, this.s, this.l); - }; - function d3_hsl_rgb(h, s, l) { - var m1, m2; - h = isNaN(h) ? 0 : (h %= 360) < 0 ? h + 360 : h; - s = isNaN(s) ? 0 : s < 0 ? 0 : s > 1 ? 1 : s; - l = l < 0 ? 0 : l > 1 ? 1 : l; - m2 = l <= 0.5 ? l * (1 + s) : l + s - l * s; - m1 = 2 * l - m2; - function v(h2) { - if (h2 > 360) h2 -= 360; - else if (h2 < 0) h2 += 360; - if (h2 < 60) return m1 + (m2 - m1) * h2 / 60; - if (h2 < 180) return m2; - if (h2 < 240) return m1 + (m2 - m1) * (240 - h2) / 60; - return m1; - } - function vv(h2) { - return Math.round(v(h2) * 255); - } - return new d3_rgb(vv(h + 120), vv(h), vv(h - 120)); - } - d32.hcl = d3_hcl; - function d3_hcl(h, c, l) { - return this instanceof d3_hcl ? void (this.h = +h, this.c = +c, this.l = +l) : arguments.length < 2 ? h instanceof d3_hcl ? new d3_hcl(h.h, h.c, h.l) : h instanceof d3_lab ? d3_lab_hcl(h.l, h.a, h.b) : d3_lab_hcl((h = d3_rgb_lab((h = d32.rgb(h)).r, h.g, h.b)).l, h.a, h.b) : new d3_hcl(h, c, l); - } - var d3_hclPrototype = d3_hcl.prototype = new d3_color(); - d3_hclPrototype.brighter = function(k) { - return new d3_hcl(this.h, this.c, Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.darker = function(k) { - return new d3_hcl(this.h, this.c, Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1))); - }; - d3_hclPrototype.rgb = function() { - return d3_hcl_lab(this.h, this.c, this.l).rgb(); - }; - function d3_hcl_lab(h, c, l) { - if (isNaN(h)) h = 0; - if (isNaN(c)) c = 0; - return new d3_lab(l, Math.cos(h *= d3_radians) * c, Math.sin(h) * c); - } - d32.lab = d3_lab; - function d3_lab(l, a, b) { - return this instanceof d3_lab ? void (this.l = +l, this.a = +a, this.b = +b) : arguments.length < 2 ? l instanceof d3_lab ? new d3_lab(l.l, l.a, l.b) : l instanceof d3_hcl ? d3_hcl_lab(l.h, l.c, l.l) : d3_rgb_lab((l = d3_rgb(l)).r, l.g, l.b) : new d3_lab(l, a, b); - } - var d3_lab_K = 18; - var d3_lab_X = 0.95047, d3_lab_Y = 1, d3_lab_Z = 1.08883; - var d3_labPrototype = d3_lab.prototype = new d3_color(); - d3_labPrototype.brighter = function(k) { - return new d3_lab(Math.min(100, this.l + d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.darker = function(k) { - return new d3_lab(Math.max(0, this.l - d3_lab_K * (arguments.length ? k : 1)), this.a, this.b); - }; - d3_labPrototype.rgb = function() { - return d3_lab_rgb(this.l, this.a, this.b); - }; - function d3_lab_rgb(l, a, b) { - var y = (l + 16) / 116, x = y + a / 500, z = y - b / 200; - x = d3_lab_xyz(x) * d3_lab_X; - y = d3_lab_xyz(y) * d3_lab_Y; - z = d3_lab_xyz(z) * d3_lab_Z; - return new d3_rgb(d3_xyz_rgb(3.2404542 * x - 1.5371385 * y - 0.4985314 * z), d3_xyz_rgb(-0.969266 * x + 1.8760108 * y + 0.041556 * z), d3_xyz_rgb(0.0556434 * x - 0.2040259 * y + 1.0572252 * z)); - } - function d3_lab_hcl(l, a, b) { - return l > 0 ? new d3_hcl(Math.atan2(b, a) * d3_degrees, Math.sqrt(a * a + b * b), l) : new d3_hcl(NaN, NaN, l); - } - function d3_lab_xyz(x) { - return x > 0.206893034 ? x * x * x : (x - 4 / 29) / 7.787037; - } - function d3_xyz_lab(x) { - return x > 8856e-6 ? Math.pow(x, 1 / 3) : 7.787037 * x + 4 / 29; - } - function d3_xyz_rgb(r) { - return Math.round(255 * (r <= 304e-5 ? 12.92 * r : 1.055 * Math.pow(r, 1 / 2.4) - 0.055)); - } - d32.rgb = d3_rgb; - function d3_rgb(r, g, b) { - return this instanceof d3_rgb ? void (this.r = ~~r, this.g = ~~g, this.b = ~~b) : arguments.length < 2 ? r instanceof d3_rgb ? new d3_rgb(r.r, r.g, r.b) : d3_rgb_parse("" + r, d3_rgb, d3_hsl_rgb) : new d3_rgb(r, g, b); - } - function d3_rgbNumber(value2) { - return new d3_rgb(value2 >> 16, value2 >> 8 & 255, value2 & 255); - } - function d3_rgbString(value2) { - return d3_rgbNumber(value2) + ""; - } - var d3_rgbPrototype = d3_rgb.prototype = new d3_color(); - d3_rgbPrototype.brighter = function(k) { - k = Math.pow(0.7, arguments.length ? k : 1); - var r = this.r, g = this.g, b = this.b, i = 30; - if (!r && !g && !b) return new d3_rgb(i, i, i); - if (r && r < i) r = i; - if (g && g < i) g = i; - if (b && b < i) b = i; - return new d3_rgb(Math.min(255, r / k), Math.min(255, g / k), Math.min(255, b / k)); - }; - d3_rgbPrototype.darker = function(k) { - k = Math.pow(0.7, arguments.length ? k : 1); - return new d3_rgb(k * this.r, k * this.g, k * this.b); - }; - d3_rgbPrototype.hsl = function() { - return d3_rgb_hsl(this.r, this.g, this.b); - }; - d3_rgbPrototype.toString = function() { - return "#" + d3_rgb_hex(this.r) + d3_rgb_hex(this.g) + d3_rgb_hex(this.b); - }; - function d3_rgb_hex(v) { - return v < 16 ? "0" + Math.max(0, v).toString(16) : Math.min(255, v).toString(16); - } - function d3_rgb_parse(format2, rgb2, hsl2) { - var r = 0, g = 0, b = 0, m1, m2, color2; - m1 = /([a-z]+)\((.*)\)/.exec(format2 = format2.toLowerCase()); - if (m1) { - m2 = m1[2].split(","); - switch (m1[1]) { - case "hsl": { - return hsl2(parseFloat(m2[0]), parseFloat(m2[1]) / 100, parseFloat(m2[2]) / 100); - } - case "rgb": { - return rgb2(d3_rgb_parseNumber(m2[0]), d3_rgb_parseNumber(m2[1]), d3_rgb_parseNumber(m2[2])); - } - } - } - if (color2 = d3_rgb_names.get(format2)) { - return rgb2(color2.r, color2.g, color2.b); - } - if (format2 != null && format2.charAt(0) === "#" && !isNaN(color2 = parseInt(format2.slice(1), 16))) { - if (format2.length === 4) { - r = (color2 & 3840) >> 4; - r = r >> 4 | r; - g = color2 & 240; - g = g >> 4 | g; - b = color2 & 15; - b = b << 4 | b; - } else if (format2.length === 7) { - r = (color2 & 16711680) >> 16; - g = (color2 & 65280) >> 8; - b = color2 & 255; - } - } - return rgb2(r, g, b); - } - function d3_rgb_hsl(r, g, b) { - var min = Math.min(r /= 255, g /= 255, b /= 255), max = Math.max(r, g, b), d = max - min, h, s, l = (max + min) / 2; - if (d) { - s = l < 0.5 ? d / (max + min) : d / (2 - max - min); - if (r == max) h = (g - b) / d + (g < b ? 6 : 0); - else if (g == max) h = (b - r) / d + 2; - else h = (r - g) / d + 4; - h *= 60; - } else { - h = NaN; - s = l > 0 && l < 1 ? 0 : h; - } - return new d3_hsl(h, s, l); - } - function d3_rgb_lab(r, g, b) { - r = d3_rgb_xyz(r); - g = d3_rgb_xyz(g); - b = d3_rgb_xyz(b); - var x = d3_xyz_lab((0.4124564 * r + 0.3575761 * g + 0.1804375 * b) / d3_lab_X), y = d3_xyz_lab((0.2126729 * r + 0.7151522 * g + 0.072175 * b) / d3_lab_Y), z = d3_xyz_lab((0.0193339 * r + 0.119192 * g + 0.9503041 * b) / d3_lab_Z); - return d3_lab(116 * y - 16, 500 * (x - y), 200 * (y - z)); - } - function d3_rgb_xyz(r) { - return (r /= 255) <= 0.04045 ? r / 12.92 : Math.pow((r + 0.055) / 1.055, 2.4); - } - function d3_rgb_parseNumber(c) { - var f = parseFloat(c); - return c.charAt(c.length - 1) === "%" ? Math.round(f * 2.55) : f; - } - var d3_rgb_names = d32.map({ - aliceblue: 15792383, - antiquewhite: 16444375, - aqua: 65535, - aquamarine: 8388564, - azure: 15794175, - beige: 16119260, - bisque: 16770244, - black: 0, - blanchedalmond: 16772045, - blue: 255, - blueviolet: 9055202, - brown: 10824234, - burlywood: 14596231, - cadetblue: 6266528, - chartreuse: 8388352, - chocolate: 13789470, - coral: 16744272, - cornflowerblue: 6591981, - cornsilk: 16775388, - crimson: 14423100, - cyan: 65535, - darkblue: 139, - darkcyan: 35723, - darkgoldenrod: 12092939, - darkgray: 11119017, - darkgreen: 25600, - darkgrey: 11119017, - darkkhaki: 12433259, - darkmagenta: 9109643, - darkolivegreen: 5597999, - darkorange: 16747520, - darkorchid: 10040012, - darkred: 9109504, - darksalmon: 15308410, - darkseagreen: 9419919, - darkslateblue: 4734347, - darkslategray: 3100495, - darkslategrey: 3100495, - darkturquoise: 52945, - darkviolet: 9699539, - deeppink: 16716947, - deepskyblue: 49151, - dimgray: 6908265, - dimgrey: 6908265, - dodgerblue: 2003199, - firebrick: 11674146, - floralwhite: 16775920, - forestgreen: 2263842, - fuchsia: 16711935, - gainsboro: 14474460, - ghostwhite: 16316671, - gold: 16766720, - goldenrod: 14329120, - gray: 8421504, - green: 32768, - greenyellow: 11403055, - grey: 8421504, - honeydew: 15794160, - hotpink: 16738740, - indianred: 13458524, - indigo: 4915330, - ivory: 16777200, - khaki: 15787660, - lavender: 15132410, - lavenderblush: 16773365, - lawngreen: 8190976, - lemonchiffon: 16775885, - lightblue: 11393254, - lightcoral: 15761536, - lightcyan: 14745599, - lightgoldenrodyellow: 16448210, - lightgray: 13882323, - lightgreen: 9498256, - lightgrey: 13882323, - lightpink: 16758465, - lightsalmon: 16752762, - lightseagreen: 2142890, - lightskyblue: 8900346, - lightslategray: 7833753, - lightslategrey: 7833753, - lightsteelblue: 11584734, - lightyellow: 16777184, - lime: 65280, - limegreen: 3329330, - linen: 16445670, - magenta: 16711935, - maroon: 8388608, - mediumaquamarine: 6737322, - mediumblue: 205, - mediumorchid: 12211667, - mediumpurple: 9662683, - mediumseagreen: 3978097, - mediumslateblue: 8087790, - mediumspringgreen: 64154, - mediumturquoise: 4772300, - mediumvioletred: 13047173, - midnightblue: 1644912, - mintcream: 16121850, - mistyrose: 16770273, - moccasin: 16770229, - navajowhite: 16768685, - navy: 128, - oldlace: 16643558, - olive: 8421376, - olivedrab: 7048739, - orange: 16753920, - orangered: 16729344, - orchid: 14315734, - palegoldenrod: 15657130, - palegreen: 10025880, - paleturquoise: 11529966, - palevioletred: 14381203, - papayawhip: 16773077, - peachpuff: 16767673, - peru: 13468991, - pink: 16761035, - plum: 14524637, - powderblue: 11591910, - purple: 8388736, - rebeccapurple: 6697881, - red: 16711680, - rosybrown: 12357519, - royalblue: 4286945, - saddlebrown: 9127187, - salmon: 16416882, - sandybrown: 16032864, - seagreen: 3050327, - seashell: 16774638, - sienna: 10506797, - silver: 12632256, - skyblue: 8900331, - slateblue: 6970061, - slategray: 7372944, - slategrey: 7372944, - snow: 16775930, - springgreen: 65407, - steelblue: 4620980, - tan: 13808780, - teal: 32896, - thistle: 14204888, - tomato: 16737095, - turquoise: 4251856, - violet: 15631086, - wheat: 16113331, - white: 16777215, - whitesmoke: 16119285, - yellow: 16776960, - yellowgreen: 10145074 - }); - d3_rgb_names.forEach(function(key, value2) { - d3_rgb_names.set(key, d3_rgbNumber(value2)); - }); - function d3_functor(v) { - return typeof v === "function" ? v : function() { - return v; - }; - } - d32.functor = d3_functor; - d32.xhr = d3_xhrType(d3_identity); - function d3_xhrType(response) { - return function(url, mimeType, callback) { - if (arguments.length === 2 && typeof mimeType === "function") callback = mimeType, mimeType = null; - return d3_xhr(url, mimeType, response, callback); - }; - } - function d3_xhr(url, mimeType, response, callback) { - var xhr = {}, dispatch = d32.dispatch("beforesend", "progress", "load", "error"), headers = {}, request = new XMLHttpRequest(), responseType = null; - if (self.XDomainRequest && !("withCredentials" in request) && /^(http(s)?:)?\/\//.test(url)) request = new XDomainRequest(); - "onload" in request ? request.onload = request.onerror = respond : request.onreadystatechange = function() { - request.readyState > 3 && respond(); - }; - function respond() { - var status = request.status, result; - if (!status && d3_xhrHasResponse(request) || status >= 200 && status < 300 || status === 304) { - try { - result = response.call(xhr, request); - } catch (e) { - dispatch.error.call(xhr, e); - return; - } - dispatch.load.call(xhr, result); - } else { - dispatch.error.call(xhr, request); - } - } - request.onprogress = function(event) { - var o = d32.event; - d32.event = event; - try { - dispatch.progress.call(xhr, request); - } finally { - d32.event = o; - } - }; - xhr.header = function(name2, value2) { - name2 = (name2 + "").toLowerCase(); - if (arguments.length < 2) return headers[name2]; - if (value2 == null) delete headers[name2]; - else headers[name2] = value2 + ""; - return xhr; - }; - xhr.mimeType = function(value2) { - if (!arguments.length) return mimeType; - mimeType = value2 == null ? null : value2 + ""; - return xhr; - }; - xhr.responseType = function(value2) { - if (!arguments.length) return responseType; - responseType = value2; - return xhr; - }; - xhr.response = function(value2) { - response = value2; - return xhr; - }; - ["get", "post"].forEach(function(method) { - xhr[method] = function() { - return xhr.send.apply(xhr, [method].concat(d3_array(arguments))); - }; - }); - xhr.send = function(method, data, callback2) { - if (arguments.length === 2 && typeof data === "function") callback2 = data, data = null; - request.open(method, url, true); - if (mimeType != null && !("accept" in headers)) headers["accept"] = mimeType + ",*/*"; - if (request.setRequestHeader) for (var name2 in headers) request.setRequestHeader(name2, headers[name2]); - if (mimeType != null && request.overrideMimeType) request.overrideMimeType(mimeType); - if (responseType != null) request.responseType = responseType; - if (callback2 != null) xhr.on("error", callback2).on("load", function(request2) { - callback2(null, request2); - }); - dispatch.beforesend.call(xhr, request); - request.send(data == null ? null : data); - return xhr; - }; - xhr.abort = function() { - request.abort(); - return xhr; - }; - d32.rebind(xhr, dispatch, "on"); - return callback == null ? xhr : xhr.get(d3_xhr_fixCallback(callback)); - } - function d3_xhr_fixCallback(callback) { - return callback.length === 1 ? function(error, request) { - callback(error == null ? request : null); - } : callback; - } - function d3_xhrHasResponse(request) { - var type = request.responseType; - return type && type !== "text" ? request.response : request.responseText; - } - d32.dsv = function(delimiter, mimeType) { - var reFormat = new RegExp('["' + delimiter + "\n]"), delimiterCode = delimiter.charCodeAt(0); - function dsv(url, row, callback) { - if (arguments.length < 3) callback = row, row = null; - var xhr = d3_xhr(url, mimeType, row == null ? response : typedResponse(row), callback); - xhr.row = function(_2) { - return arguments.length ? xhr.response((row = _2) == null ? response : typedResponse(_2)) : row; - }; - return xhr; - } - function response(request) { - return dsv.parse(request.responseText); - } - function typedResponse(f) { - return function(request) { - return dsv.parse(request.responseText, f); - }; - } - dsv.parse = function(text, f) { - var o; - return dsv.parseRows(text, function(row, i) { - if (o) return o(row, i - 1); - var a = function(d) { - var obj = {}; - var len = row.length; - for (var k = 0; k < len; ++k) { - obj[row[k]] = d[k]; - } - return obj; - }; - o = f ? function(row2, i2) { - return f(a(row2), i2); - } : a; - }); - }; - dsv.parseRows = function(text, f) { - var EOL = {}, EOF = {}, rows = [], N = text.length, I = 0, n = 0, t, eol; - function token() { - if (I >= N) return EOF; - if (eol) return eol = false, EOL; - var j = I; - if (text.charCodeAt(j) === 34) { - var i = j; - while (i++ < N) { - if (text.charCodeAt(i) === 34) { - if (text.charCodeAt(i + 1) !== 34) break; - ++i; - } - } - I = i + 2; - var c = text.charCodeAt(i + 1); - if (c === 13) { - eol = true; - if (text.charCodeAt(i + 2) === 10) ++I; - } else if (c === 10) { - eol = true; - } - return text.slice(j + 1, i).replace(/""/g, '"'); - } - while (I < N) { - var c = text.charCodeAt(I++), k = 1; - if (c === 10) eol = true; - else if (c === 13) { - eol = true; - if (text.charCodeAt(I) === 10) ++I, ++k; - } else if (c !== delimiterCode) continue; - return text.slice(j, I - k); - } - return text.slice(j); - } - while ((t = token()) !== EOF) { - var a = []; - while (t !== EOL && t !== EOF) { - a.push(t); - t = token(); - } - if (f && (a = f(a, n++)) == null) continue; - rows.push(a); - } - return rows; - }; - dsv.format = function(rows) { - if (Array.isArray(rows[0])) return dsv.formatRows(rows); - var fieldSet = new d3_Set(), fields = []; - rows.forEach(function(row) { - for (var field in row) { - if (!fieldSet.has(field)) { - fields.push(fieldSet.add(field)); - } - } - }); - return [fields.map(formatValue2).join(delimiter)].concat(rows.map(function(row) { - return fields.map(function(field) { - return formatValue2(row[field]); - }).join(delimiter); - })).join("\n"); - }; - dsv.formatRows = function(rows) { - return rows.map(formatRow).join("\n"); - }; - function formatRow(row) { - return row.map(formatValue2).join(delimiter); - } - function formatValue2(text) { - return reFormat.test(text) ? '"' + text.replace(/\"/g, '""') + '"' : text; - } - return dsv; - }; - d32.csv = d32.dsv(",", "text/csv"); - d32.tsv = d32.dsv(" ", "text/tab-separated-values"); - var d3_timer_queueHead, d3_timer_queueTail, d3_timer_interval, d3_timer_timeout, d3_timer_frame = this[d3_vendorSymbol(this, "requestAnimationFrame")] || function(callback) { - setTimeout(callback, 17); - }; - d32.timer = function() { - d3_timer.apply(this, arguments); - }; - function d3_timer(callback, delay, then) { - var n = arguments.length; - if (n < 2) delay = 0; - if (n < 3) then = Date.now(); - var time = then + delay, timer = { - c: callback, - t: time, - n: null - }; - if (d3_timer_queueTail) d3_timer_queueTail.n = timer; - else d3_timer_queueHead = timer; - d3_timer_queueTail = timer; - if (!d3_timer_interval) { - d3_timer_timeout = clearTimeout(d3_timer_timeout); - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); - } - return timer; - } - function d3_timer_step() { - var now = d3_timer_mark(), delay = d3_timer_sweep() - now; - if (delay > 24) { - if (isFinite(delay)) { - clearTimeout(d3_timer_timeout); - d3_timer_timeout = setTimeout(d3_timer_step, delay); - } - d3_timer_interval = 0; - } else { - d3_timer_interval = 1; - d3_timer_frame(d3_timer_step); - } - } - d32.timer.flush = function() { - d3_timer_mark(); - d3_timer_sweep(); - }; - function d3_timer_mark() { - var now = Date.now(), timer = d3_timer_queueHead; - while (timer) { - if (now >= timer.t && timer.c(now - timer.t)) timer.c = null; - timer = timer.n; - } - return now; - } - function d3_timer_sweep() { - var t02, t12 = d3_timer_queueHead, time = Infinity; - while (t12) { - if (t12.c) { - if (t12.t < time) time = t12.t; - t12 = (t02 = t12).n; - } else { - t12 = t02 ? t02.n = t12.n : d3_timer_queueHead = t12.n; - } - } - d3_timer_queueTail = t02; - return time; - } - d32.round = function(x, n) { - return n ? Math.round(x * (n = Math.pow(10, n))) / n : Math.round(x); - }; - d32.geom = {}; - function d3_geom_pointX(d) { - return d[0]; - } - function d3_geom_pointY(d) { - return d[1]; - } - d32.geom.hull = function(vertices) { - var x = d3_geom_pointX, y = d3_geom_pointY; - if (arguments.length) return hull(vertices); - function hull(data) { - if (data.length < 3) return []; - var fx2 = d3_functor(x), fy = d3_functor(y), i, n = data.length, points = [], flippedPoints = []; - for (i = 0; i < n; i++) { - points.push([+fx2.call(this, data[i], i), +fy.call(this, data[i], i), i]); - } - points.sort(d3_geom_hullOrder); - for (i = 0; i < n; i++) flippedPoints.push([points[i][0], -points[i][1]]); - var upper = d3_geom_hullUpper(points), lower = d3_geom_hullUpper(flippedPoints); - var skipLeft = lower[0] === upper[0], skipRight = lower[lower.length - 1] === upper[upper.length - 1], polygon2 = []; - for (i = upper.length - 1; i >= 0; --i) polygon2.push(data[points[upper[i]][2]]); - for (i = +skipLeft; i < lower.length - skipRight; ++i) polygon2.push(data[points[lower[i]][2]]); - return polygon2; - } - hull.x = function(_2) { - return arguments.length ? (x = _2, hull) : x; - }; - hull.y = function(_2) { - return arguments.length ? (y = _2, hull) : y; - }; - return hull; - }; - function d3_geom_hullUpper(points) { - var n = points.length, hull = [0, 1], hs = 2; - for (var i = 2; i < n; i++) { - while (hs > 1 && d3_cross2d(points[hull[hs - 2]], points[hull[hs - 1]], points[i]) <= 0) --hs; - hull[hs++] = i; - } - return hull.slice(0, hs); - } - function d3_geom_hullOrder(a, b) { - return a[0] - b[0] || a[1] - b[1]; - } - d32.geom.polygon = function(coordinates) { - d3_subclass(coordinates, d3_geom_polygonPrototype); - return coordinates; - }; - var d3_geom_polygonPrototype = d32.geom.polygon.prototype = []; - d3_geom_polygonPrototype.area = function() { - var i = -1, n = this.length, a, b = this[n - 1], area2 = 0; - while (++i < n) { - a = b; - b = this[i]; - area2 += a[1] * b[0] - a[0] * b[1]; - } - return area2 * 0.5; - }; - d3_geom_polygonPrototype.centroid = function(k) { - var i = -1, n = this.length, x = 0, y = 0, a, b = this[n - 1], c; - if (!arguments.length) k = -1 / (6 * this.area()); - while (++i < n) { - a = b; - b = this[i]; - c = a[0] * b[1] - b[0] * a[1]; - x += (a[0] + b[0]) * c; - y += (a[1] + b[1]) * c; - } - return [x * k, y * k]; - }; - d3_geom_polygonPrototype.clip = function(subject) { - var input, closed = d3_geom_polygonClosed(subject), i = -1, n = this.length - d3_geom_polygonClosed(this), j, m, a = this[n - 1], b, c, d; - while (++i < n) { - input = subject.slice(); - subject.length = 0; - b = this[i]; - c = input[(m = input.length - closed) - 1]; - j = -1; - while (++j < m) { - d = input[j]; - if (d3_geom_polygonInside(d, a, b)) { - if (!d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - subject.push(d); - } else if (d3_geom_polygonInside(c, a, b)) { - subject.push(d3_geom_polygonIntersect(c, d, a, b)); - } - c = d; - } - if (closed) subject.push(subject[0]); - a = b; - } - return subject; - }; - function d3_geom_polygonInside(p, a, b) { - return (b[0] - a[0]) * (p[1] - a[1]) < (b[1] - a[1]) * (p[0] - a[0]); - } - function d3_geom_polygonIntersect(c, d, a, b) { - var x1 = c[0], x3 = a[0], x21 = d[0] - x1, x43 = b[0] - x3, y1 = c[1], y3 = a[1], y21 = d[1] - y1, y43 = b[1] - y3, ua = (x43 * (y1 - y3) - y43 * (x1 - x3)) / (y43 * x21 - x43 * y21); - return [x1 + ua * x21, y1 + ua * y21]; - } - function d3_geom_polygonClosed(coordinates) { - var a = coordinates[0], b = coordinates[coordinates.length - 1]; - return !(a[0] - b[0] || a[1] - b[1]); - } - var d3_geom_voronoiEdges, d3_geom_voronoiCells, d3_geom_voronoiBeaches, d3_geom_voronoiBeachPool = [], d3_geom_voronoiFirstCircle, d3_geom_voronoiCircles, d3_geom_voronoiCirclePool = []; - function d3_geom_voronoiBeach() { - d3_geom_voronoiRedBlackNode(this); - this.edge = this.site = this.circle = null; - } - function d3_geom_voronoiCreateBeach(site) { - var beach = d3_geom_voronoiBeachPool.pop() || new d3_geom_voronoiBeach(); - beach.site = site; - return beach; - } - function d3_geom_voronoiDetachBeach(beach) { - d3_geom_voronoiDetachCircle(beach); - d3_geom_voronoiBeaches.remove(beach); - d3_geom_voronoiBeachPool.push(beach); - d3_geom_voronoiRedBlackNode(beach); - } - function d3_geom_voronoiRemoveBeach(beach) { - var circle = beach.circle, x = circle.x, y = circle.cy, vertex = { - x, - y - }, previous = beach.P, next = beach.N, disappearing = [beach]; - d3_geom_voronoiDetachBeach(beach); - var lArc = previous; - while (lArc.circle && abs2(x - lArc.circle.x) < ε && abs2(y - lArc.circle.cy) < ε) { - previous = lArc.P; - disappearing.unshift(lArc); - d3_geom_voronoiDetachBeach(lArc); - lArc = previous; - } - disappearing.unshift(lArc); - d3_geom_voronoiDetachCircle(lArc); - var rArc = next; - while (rArc.circle && abs2(x - rArc.circle.x) < ε && abs2(y - rArc.circle.cy) < ε) { - next = rArc.N; - disappearing.push(rArc); - d3_geom_voronoiDetachBeach(rArc); - rArc = next; - } - disappearing.push(rArc); - d3_geom_voronoiDetachCircle(rArc); - var nArcs = disappearing.length, iArc; - for (iArc = 1; iArc < nArcs; ++iArc) { - rArc = disappearing[iArc]; - lArc = disappearing[iArc - 1]; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lArc.site, rArc.site, vertex); - } - lArc = disappearing[0]; - rArc = disappearing[nArcs - 1]; - rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, rArc.site, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiAddBeach(site) { - var x = site.x, directrix = site.y, lArc, rArc, dxl, dxr, node = d3_geom_voronoiBeaches._; - while (node) { - dxl = d3_geom_voronoiLeftBreakPoint(node, directrix) - x; - if (dxl > ε) node = node.L; - else { - dxr = x - d3_geom_voronoiRightBreakPoint(node, directrix); - if (dxr > ε) { - if (!node.R) { - lArc = node; - break; - } - node = node.R; - } else { - if (dxl > -1e-6) { - lArc = node.P; - rArc = node; - } else if (dxr > -1e-6) { - lArc = node; - rArc = node.N; - } else { - lArc = rArc = node; - } - break; - } - } - } - var newArc = d3_geom_voronoiCreateBeach(site); - d3_geom_voronoiBeaches.insert(lArc, newArc); - if (!lArc && !rArc) return; - if (lArc === rArc) { - d3_geom_voronoiDetachCircle(lArc); - rArc = d3_geom_voronoiCreateBeach(lArc.site); - d3_geom_voronoiBeaches.insert(newArc, rArc); - newArc.edge = rArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - return; - } - if (!rArc) { - newArc.edge = d3_geom_voronoiCreateEdge(lArc.site, newArc.site); - return; - } - d3_geom_voronoiDetachCircle(lArc); - d3_geom_voronoiDetachCircle(rArc); - var lSite = lArc.site, ax = lSite.x, ay = lSite.y, bx = site.x - ax, by = site.y - ay, rSite = rArc.site, cx = rSite.x - ax, cy = rSite.y - ay, d = 2 * (bx * cy - by * cx), hb = bx * bx + by * by, hc = cx * cx + cy * cy, vertex = { - x: (cy * hb - by * hc) / d + ax, - y: (bx * hc - cx * hb) / d + ay - }; - d3_geom_voronoiSetEdgeEnd(rArc.edge, lSite, rSite, vertex); - newArc.edge = d3_geom_voronoiCreateEdge(lSite, site, null, vertex); - rArc.edge = d3_geom_voronoiCreateEdge(site, rSite, null, vertex); - d3_geom_voronoiAttachCircle(lArc); - d3_geom_voronoiAttachCircle(rArc); - } - function d3_geom_voronoiLeftBreakPoint(arc2, directrix) { - var site = arc2.site, rfocx = site.x, rfocy = site.y, pby2 = rfocy - directrix; - if (!pby2) return rfocx; - var lArc = arc2.P; - if (!lArc) return -Infinity; - site = lArc.site; - var lfocx = site.x, lfocy = site.y, plby2 = lfocy - directrix; - if (!plby2) return lfocx; - var hl = lfocx - rfocx, aby2 = 1 / pby2 - 1 / plby2, b = hl / plby2; - if (aby2) return (-b + Math.sqrt(b * b - 2 * aby2 * (hl * hl / (-2 * plby2) - lfocy + plby2 / 2 + rfocy - pby2 / 2))) / aby2 + rfocx; - return (rfocx + lfocx) / 2; - } - function d3_geom_voronoiRightBreakPoint(arc2, directrix) { - var rArc = arc2.N; - if (rArc) return d3_geom_voronoiLeftBreakPoint(rArc, directrix); - var site = arc2.site; - return site.y === directrix ? site.x : Infinity; - } - function d3_geom_voronoiCell(site) { - this.site = site; - this.edges = []; - } - d3_geom_voronoiCell.prototype.prepare = function() { - var halfEdges = this.edges, iHalfEdge = halfEdges.length, edge; - while (iHalfEdge--) { - edge = halfEdges[iHalfEdge].edge; - if (!edge.b || !edge.a) halfEdges.splice(iHalfEdge, 1); - } - halfEdges.sort(d3_geom_voronoiHalfEdgeOrder); - return halfEdges.length; - }; - function d3_geom_voronoiCloseCells(extent2) { - var x0 = extent2[0][0], x1 = extent2[1][0], y0 = extent2[0][1], y1 = extent2[1][1], x2, y2, x3, y3, cells = d3_geom_voronoiCells, iCell = cells.length, cell, iHalfEdge, halfEdges, nHalfEdges, start, end; - while (iCell--) { - cell = cells[iCell]; - if (!cell || !cell.prepare()) continue; - halfEdges = cell.edges; - nHalfEdges = halfEdges.length; - iHalfEdge = 0; - while (iHalfEdge < nHalfEdges) { - end = halfEdges[iHalfEdge].end(), x3 = end.x, y3 = end.y; - start = halfEdges[++iHalfEdge % nHalfEdges].start(), x2 = start.x, y2 = start.y; - if (abs2(x3 - x2) > ε || abs2(y3 - y2) > ε) { - halfEdges.splice(iHalfEdge, 0, new d3_geom_voronoiHalfEdge(d3_geom_voronoiCreateBorderEdge(cell.site, end, abs2(x3 - x0) < ε && y1 - y3 > ε ? { - x: x0, - y: abs2(x2 - x0) < ε ? y2 : y1 - } : abs2(y3 - y1) < ε && x1 - x3 > ε ? { - x: abs2(y2 - y1) < ε ? x2 : x1, - y: y1 - } : abs2(x3 - x1) < ε && y3 - y0 > ε ? { - x: x1, - y: abs2(x2 - x1) < ε ? y2 : y0 - } : abs2(y3 - y0) < ε && x3 - x0 > ε ? { - x: abs2(y2 - y0) < ε ? x2 : x0, - y: y0 - } : null), cell.site, null)); - ++nHalfEdges; - } - } - } - } - function d3_geom_voronoiHalfEdgeOrder(a, b) { - return b.angle - a.angle; - } - function d3_geom_voronoiCircle() { - d3_geom_voronoiRedBlackNode(this); - this.x = this.y = this.arc = this.site = this.cy = null; - } - function d3_geom_voronoiAttachCircle(arc2) { - var lArc = arc2.P, rArc = arc2.N; - if (!lArc || !rArc) return; - var lSite = lArc.site, cSite = arc2.site, rSite = rArc.site; - if (lSite === rSite) return; - var bx = cSite.x, by = cSite.y, ax = lSite.x - bx, ay = lSite.y - by, cx = rSite.x - bx, cy = rSite.y - by; - var d = 2 * (ax * cy - ay * cx); - if (d >= -1e-12) return; - var ha = ax * ax + ay * ay, hc = cx * cx + cy * cy, x = (cy * ha - ay * hc) / d, y = (ax * hc - cx * ha) / d, cy = y + by; - var circle = d3_geom_voronoiCirclePool.pop() || new d3_geom_voronoiCircle(); - circle.arc = arc2; - circle.site = cSite; - circle.x = x + bx; - circle.y = cy + Math.sqrt(x * x + y * y); - circle.cy = cy; - arc2.circle = circle; - var before = null, node = d3_geom_voronoiCircles._; - while (node) { - if (circle.y < node.y || circle.y === node.y && circle.x <= node.x) { - if (node.L) node = node.L; - else { - before = node.P; - break; - } - } else { - if (node.R) node = node.R; - else { - before = node; - break; - } - } - } - d3_geom_voronoiCircles.insert(before, circle); - if (!before) d3_geom_voronoiFirstCircle = circle; - } - function d3_geom_voronoiDetachCircle(arc2) { - var circle = arc2.circle; - if (circle) { - if (!circle.P) d3_geom_voronoiFirstCircle = circle.N; - d3_geom_voronoiCircles.remove(circle); - d3_geom_voronoiCirclePool.push(circle); - d3_geom_voronoiRedBlackNode(circle); - arc2.circle = null; - } - } - function d3_geom_clipLine(x0, y0, x1, y1) { - return function(line2) { - var a = line2.a, b = line2.b, ax = a.x, ay = a.y, bx = b.x, by = b.y, t02 = 0, t12 = 1, dx = bx - ax, dy = by - ay, r; - r = x0 - ax; - if (!dx && r > 0) return; - r /= dx; - if (dx < 0) { - if (r < t02) return; - if (r < t12) t12 = r; - } else if (dx > 0) { - if (r > t12) return; - if (r > t02) t02 = r; - } - r = x1 - ax; - if (!dx && r < 0) return; - r /= dx; - if (dx < 0) { - if (r > t12) return; - if (r > t02) t02 = r; - } else if (dx > 0) { - if (r < t02) return; - if (r < t12) t12 = r; - } - r = y0 - ay; - if (!dy && r > 0) return; - r /= dy; - if (dy < 0) { - if (r < t02) return; - if (r < t12) t12 = r; - } else if (dy > 0) { - if (r > t12) return; - if (r > t02) t02 = r; - } - r = y1 - ay; - if (!dy && r < 0) return; - r /= dy; - if (dy < 0) { - if (r > t12) return; - if (r > t02) t02 = r; - } else if (dy > 0) { - if (r < t02) return; - if (r < t12) t12 = r; - } - if (t02 > 0) line2.a = { - x: ax + t02 * dx, - y: ay + t02 * dy - }; - if (t12 < 1) line2.b = { - x: ax + t12 * dx, - y: ay + t12 * dy - }; - return line2; - }; - } - function d3_geom_voronoiClipEdges(extent2) { - var edges = d3_geom_voronoiEdges, clip = d3_geom_clipLine(extent2[0][0], extent2[0][1], extent2[1][0], extent2[1][1]), i = edges.length, e; - while (i--) { - e = edges[i]; - if (!d3_geom_voronoiConnectEdge(e, extent2) || !clip(e) || abs2(e.a.x - e.b.x) < ε && abs2(e.a.y - e.b.y) < ε) { - e.a = e.b = null; - edges.splice(i, 1); - } - } - } - function d3_geom_voronoiConnectEdge(edge, extent2) { - var vb = edge.b; - if (vb) return true; - var va = edge.a, x0 = extent2[0][0], x1 = extent2[1][0], y0 = extent2[0][1], y1 = extent2[1][1], lSite = edge.l, rSite = edge.r, lx = lSite.x, ly = lSite.y, rx = rSite.x, ry = rSite.y, fx2 = (lx + rx) / 2, fy = (ly + ry) / 2, fm, fb; - if (ry === ly) { - if (fx2 < x0 || fx2 >= x1) return; - if (lx > rx) { - if (!va) va = { - x: fx2, - y: y0 - }; - else if (va.y >= y1) return; - vb = { - x: fx2, - y: y1 - }; - } else { - if (!va) va = { - x: fx2, - y: y1 - }; - else if (va.y < y0) return; - vb = { - x: fx2, - y: y0 - }; - } - } else { - fm = (lx - rx) / (ry - ly); - fb = fy - fm * fx2; - if (fm < -1 || fm > 1) { - if (lx > rx) { - if (!va) va = { - x: (y0 - fb) / fm, - y: y0 - }; - else if (va.y >= y1) return; - vb = { - x: (y1 - fb) / fm, - y: y1 - }; - } else { - if (!va) va = { - x: (y1 - fb) / fm, - y: y1 - }; - else if (va.y < y0) return; - vb = { - x: (y0 - fb) / fm, - y: y0 - }; - } - } else { - if (ly < ry) { - if (!va) va = { - x: x0, - y: fm * x0 + fb - }; - else if (va.x >= x1) return; - vb = { - x: x1, - y: fm * x1 + fb - }; - } else { - if (!va) va = { - x: x1, - y: fm * x1 + fb - }; - else if (va.x < x0) return; - vb = { - x: x0, - y: fm * x0 + fb - }; - } - } - } - edge.a = va; - edge.b = vb; - return true; - } - function d3_geom_voronoiEdge(lSite, rSite) { - this.l = lSite; - this.r = rSite; - this.a = this.b = null; - } - function d3_geom_voronoiCreateEdge(lSite, rSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, rSite); - d3_geom_voronoiEdges.push(edge); - if (va) d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, va); - if (vb) d3_geom_voronoiSetEdgeEnd(edge, rSite, lSite, vb); - d3_geom_voronoiCells[lSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, lSite, rSite)); - d3_geom_voronoiCells[rSite.i].edges.push(new d3_geom_voronoiHalfEdge(edge, rSite, lSite)); - return edge; - } - function d3_geom_voronoiCreateBorderEdge(lSite, va, vb) { - var edge = new d3_geom_voronoiEdge(lSite, null); - edge.a = va; - edge.b = vb; - d3_geom_voronoiEdges.push(edge); - return edge; - } - function d3_geom_voronoiSetEdgeEnd(edge, lSite, rSite, vertex) { - if (!edge.a && !edge.b) { - edge.a = vertex; - edge.l = lSite; - edge.r = rSite; - } else if (edge.l === rSite) { - edge.b = vertex; - } else { - edge.a = vertex; - } - } - function d3_geom_voronoiHalfEdge(edge, lSite, rSite) { - var va = edge.a, vb = edge.b; - this.edge = edge; - this.site = lSite; - this.angle = rSite ? Math.atan2(rSite.y - lSite.y, rSite.x - lSite.x) : edge.l === lSite ? Math.atan2(vb.x - va.x, va.y - vb.y) : Math.atan2(va.x - vb.x, vb.y - va.y); - } - d3_geom_voronoiHalfEdge.prototype = { - start: function() { - return this.edge.l === this.site ? this.edge.a : this.edge.b; - }, - end: function() { - return this.edge.l === this.site ? this.edge.b : this.edge.a; - } - }; - function d3_geom_voronoiRedBlackTree() { - this._ = null; - } - function d3_geom_voronoiRedBlackNode(node) { - node.U = node.C = node.L = node.R = node.P = node.N = null; - } - d3_geom_voronoiRedBlackTree.prototype = { - insert: function(after, node) { - var parent, grandpa, uncle; - if (after) { - node.P = after; - node.N = after.N; - if (after.N) after.N.P = node; - after.N = node; - if (after.R) { - after = after.R; - while (after.L) after = after.L; - after.L = node; - } else { - after.R = node; - } - parent = after; - } else if (this._) { - after = d3_geom_voronoiRedBlackFirst(this._); - node.P = null; - node.N = after; - after.P = after.L = node; - parent = after; - } else { - node.P = node.N = null; - this._ = node; - parent = null; - } - node.L = node.R = null; - node.U = parent; - node.C = true; - after = node; - while (parent && parent.C) { - grandpa = parent.U; - if (parent === grandpa.L) { - uncle = grandpa.R; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.R) { - d3_geom_voronoiRedBlackRotateLeft(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateRight(this, grandpa); - } - } else { - uncle = grandpa.L; - if (uncle && uncle.C) { - parent.C = uncle.C = false; - grandpa.C = true; - after = grandpa; - } else { - if (after === parent.L) { - d3_geom_voronoiRedBlackRotateRight(this, parent); - after = parent; - parent = after.U; - } - parent.C = false; - grandpa.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, grandpa); - } - } - parent = after.U; - } - this._.C = false; - }, - remove: function(node) { - if (node.N) node.N.P = node.P; - if (node.P) node.P.N = node.N; - node.N = node.P = null; - var parent = node.U, sibling, left = node.L, right = node.R, next, red; - if (!left) next = right; - else if (!right) next = left; - else next = d3_geom_voronoiRedBlackFirst(right); - if (parent) { - if (parent.L === node) parent.L = next; - else parent.R = next; - } else { - this._ = next; - } - if (left && right) { - red = next.C; - next.C = node.C; - next.L = left; - left.U = next; - if (next !== right) { - parent = next.U; - next.U = node.U; - node = next.R; - parent.L = node; - next.R = right; - right.U = next; - } else { - next.U = parent; - parent = next; - node = next.R; - } - } else { - red = node.C; - node = next; - } - if (node) node.U = parent; - if (red) return; - if (node && node.C) { - node.C = false; - return; - } - do { - if (node === this._) break; - if (node === parent.L) { - sibling = parent.R; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - sibling = parent.R; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.R || !sibling.R.C) { - sibling.L.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateRight(this, sibling); - sibling = parent.R; - } - sibling.C = parent.C; - parent.C = sibling.R.C = false; - d3_geom_voronoiRedBlackRotateLeft(this, parent); - node = this._; - break; - } - } else { - sibling = parent.L; - if (sibling.C) { - sibling.C = false; - parent.C = true; - d3_geom_voronoiRedBlackRotateRight(this, parent); - sibling = parent.L; - } - if (sibling.L && sibling.L.C || sibling.R && sibling.R.C) { - if (!sibling.L || !sibling.L.C) { - sibling.R.C = false; - sibling.C = true; - d3_geom_voronoiRedBlackRotateLeft(this, sibling); - sibling = parent.L; - } - sibling.C = parent.C; - parent.C = sibling.L.C = false; - d3_geom_voronoiRedBlackRotateRight(this, parent); - node = this._; - break; - } - } - sibling.C = true; - node = parent; - parent = parent.U; - } while (!node.C); - if (node) node.C = false; - } - }; - function d3_geom_voronoiRedBlackRotateLeft(tree2, node) { - var p = node, q = node.R, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; - else parent.R = q; - } else { - tree2._ = q; - } - q.U = parent; - p.U = q; - p.R = q.L; - if (p.R) p.R.U = p; - q.L = p; - } - function d3_geom_voronoiRedBlackRotateRight(tree2, node) { - var p = node, q = node.L, parent = p.U; - if (parent) { - if (parent.L === p) parent.L = q; - else parent.R = q; - } else { - tree2._ = q; - } - q.U = parent; - p.U = q; - p.L = q.R; - if (p.L) p.L.U = p; - q.R = p; - } - function d3_geom_voronoiRedBlackFirst(node) { - while (node.L) node = node.L; - return node; - } - function d3_geom_voronoi(sites, bbox) { - var site = sites.sort(d3_geom_voronoiVertexOrder).pop(), x0, y0, circle; - d3_geom_voronoiEdges = []; - d3_geom_voronoiCells = new Array(sites.length); - d3_geom_voronoiBeaches = new d3_geom_voronoiRedBlackTree(); - d3_geom_voronoiCircles = new d3_geom_voronoiRedBlackTree(); - while (true) { - circle = d3_geom_voronoiFirstCircle; - if (site && (!circle || site.y < circle.y || site.y === circle.y && site.x < circle.x)) { - if (site.x !== x0 || site.y !== y0) { - d3_geom_voronoiCells[site.i] = new d3_geom_voronoiCell(site); - d3_geom_voronoiAddBeach(site); - x0 = site.x, y0 = site.y; - } - site = sites.pop(); - } else if (circle) { - d3_geom_voronoiRemoveBeach(circle.arc); - } else { - break; - } - } - if (bbox) d3_geom_voronoiClipEdges(bbox), d3_geom_voronoiCloseCells(bbox); - var diagram = { - cells: d3_geom_voronoiCells, - edges: d3_geom_voronoiEdges - }; - d3_geom_voronoiBeaches = d3_geom_voronoiCircles = d3_geom_voronoiEdges = d3_geom_voronoiCells = null; - return diagram; - } - function d3_geom_voronoiVertexOrder(a, b) { - return b.y - a.y || b.x - a.x; - } - d32.geom.voronoi = function(points) { - var x = d3_geom_pointX, y = d3_geom_pointY, fx2 = x, fy = y, clipExtent = d3_geom_voronoiClipExtent; - if (points) return voronoi(points); - function voronoi(data) { - var polygons = new Array(data.length), x0 = clipExtent[0][0], y0 = clipExtent[0][1], x1 = clipExtent[1][0], y1 = clipExtent[1][1]; - d3_geom_voronoi(sites(data), clipExtent).cells.forEach(function(cell, i) { - var edges = cell.edges, site = cell.site, polygon2 = polygons[i] = edges.length ? edges.map(function(e) { - var s = e.start(); - return [s.x, s.y]; - }) : site.x >= x0 && site.x <= x1 && site.y >= y0 && site.y <= y1 ? [[x0, y1], [x1, y1], [x1, y0], [x0, y0]] : []; - polygon2.point = data[i]; - }); - return polygons; - } - function sites(data) { - return data.map(function(d, i) { - return { - x: Math.round(fx2(d, i) / ε) * ε, - y: Math.round(fy(d, i) / ε) * ε, - i - }; - }); - } - voronoi.links = function(data) { - return d3_geom_voronoi(sites(data)).edges.filter(function(edge) { - return edge.l && edge.r; - }).map(function(edge) { - return { - source: data[edge.l.i], - target: data[edge.r.i] - }; - }); - }; - voronoi.triangles = function(data) { - var triangles = []; - d3_geom_voronoi(sites(data)).cells.forEach(function(cell, i) { - var site = cell.site, edges = cell.edges.sort(d3_geom_voronoiHalfEdgeOrder), j = -1, m = edges.length, s0, e1 = edges[m - 1].edge, s1 = e1.l === site ? e1.r : e1.l; - while (++j < m) { - s0 = s1; - e1 = edges[j].edge; - s1 = e1.l === site ? e1.r : e1.l; - if (i < s0.i && i < s1.i && d3_geom_voronoiTriangleArea(site, s0, s1) < 0) { - triangles.push([data[i], data[s0.i], data[s1.i]]); - } - } - }); - return triangles; - }; - voronoi.x = function(_2) { - return arguments.length ? (fx2 = d3_functor(x = _2), voronoi) : x; - }; - voronoi.y = function(_2) { - return arguments.length ? (fy = d3_functor(y = _2), voronoi) : y; - }; - voronoi.clipExtent = function(_2) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent; - clipExtent = _2 == null ? d3_geom_voronoiClipExtent : _2; - return voronoi; - }; - voronoi.size = function(_2) { - if (!arguments.length) return clipExtent === d3_geom_voronoiClipExtent ? null : clipExtent && clipExtent[1]; - return voronoi.clipExtent(_2 && [[0, 0], _2]); - }; - return voronoi; - }; - var d3_geom_voronoiClipExtent = [[-1e6, -1e6], [1e6, 1e6]]; - function d3_geom_voronoiTriangleArea(a, b, c) { - return (a.x - c.x) * (b.y - a.y) - (a.x - b.x) * (c.y - a.y); - } - d32.geom.delaunay = function(vertices) { - return d32.geom.voronoi().triangles(vertices); - }; - d32.geom.quadtree = function(points, x1, y1, x2, y2) { - var x = d3_geom_pointX, y = d3_geom_pointY, compat; - if (compat = arguments.length) { - x = d3_geom_quadtreeCompatX; - y = d3_geom_quadtreeCompatY; - if (compat === 3) { - y2 = y1; - x2 = x1; - y1 = x1 = 0; - } - return quadtree(points); - } - function quadtree(data) { - var d, fx2 = d3_functor(x), fy = d3_functor(y), xs, ys, i, n, x1_, y1_, x2_, y2_; - if (x1 != null) { - x1_ = x1, y1_ = y1, x2_ = x2, y2_ = y2; - } else { - x2_ = y2_ = -(x1_ = y1_ = Infinity); - xs = [], ys = []; - n = data.length; - if (compat) for (i = 0; i < n; ++i) { - d = data[i]; - if (d.x < x1_) x1_ = d.x; - if (d.y < y1_) y1_ = d.y; - if (d.x > x2_) x2_ = d.x; - if (d.y > y2_) y2_ = d.y; - xs.push(d.x); - ys.push(d.y); - } - else for (i = 0; i < n; ++i) { - var x_ = +fx2(d = data[i], i), y_ = +fy(d, i); - if (x_ < x1_) x1_ = x_; - if (y_ < y1_) y1_ = y_; - if (x_ > x2_) x2_ = x_; - if (y_ > y2_) y2_ = y_; - xs.push(x_); - ys.push(y_); - } - } - var dx = x2_ - x1_, dy = y2_ - y1_; - if (dx > dy) y2_ = y1_ + dx; - else x2_ = x1_ + dy; - function insert(n2, d2, x3, y3, x12, y12, x22, y22) { - if (isNaN(x3) || isNaN(y3)) return; - if (n2.leaf) { - var nx = n2.x, ny = n2.y; - if (nx != null) { - if (abs2(nx - x3) + abs2(ny - y3) < 0.01) { - insertChild(n2, d2, x3, y3, x12, y12, x22, y22); - } else { - var nPoint = n2.point; - n2.x = n2.y = n2.point = null; - insertChild(n2, nPoint, nx, ny, x12, y12, x22, y22); - insertChild(n2, d2, x3, y3, x12, y12, x22, y22); - } - } else { - n2.x = x3, n2.y = y3, n2.point = d2; - } - } else { - insertChild(n2, d2, x3, y3, x12, y12, x22, y22); - } - } - function insertChild(n2, d2, x3, y3, x12, y12, x22, y22) { - var xm = (x12 + x22) * 0.5, ym = (y12 + y22) * 0.5, right = x3 >= xm, below = y3 >= ym, i2 = below << 1 | right; - n2.leaf = false; - n2 = n2.nodes[i2] || (n2.nodes[i2] = d3_geom_quadtreeNode()); - if (right) x12 = xm; - else x22 = xm; - if (below) y12 = ym; - else y22 = ym; - insert(n2, d2, x3, y3, x12, y12, x22, y22); - } - var root = d3_geom_quadtreeNode(); - root.add = function(d2) { - insert(root, d2, +fx2(d2, ++i), +fy(d2, i), x1_, y1_, x2_, y2_); - }; - root.visit = function(f) { - d3_geom_quadtreeVisit(f, root, x1_, y1_, x2_, y2_); - }; - root.find = function(point) { - return d3_geom_quadtreeFind(root, point[0], point[1], x1_, y1_, x2_, y2_); - }; - i = -1; - if (x1 == null) { - while (++i < n) { - insert(root, data[i], xs[i], ys[i], x1_, y1_, x2_, y2_); - } - --i; - } else data.forEach(root.add); - xs = ys = data = d = null; - return root; - } - quadtree.x = function(_2) { - return arguments.length ? (x = _2, quadtree) : x; - }; - quadtree.y = function(_2) { - return arguments.length ? (y = _2, quadtree) : y; - }; - quadtree.extent = function(_2) { - if (!arguments.length) return x1 == null ? null : [[x1, y1], [x2, y2]]; - if (_2 == null) x1 = y1 = x2 = y2 = null; - else x1 = +_2[0][0], y1 = +_2[0][1], x2 = +_2[1][0], y2 = +_2[1][1]; - return quadtree; - }; - quadtree.size = function(_2) { - if (!arguments.length) return x1 == null ? null : [x2 - x1, y2 - y1]; - if (_2 == null) x1 = y1 = x2 = y2 = null; - else x1 = y1 = 0, x2 = +_2[0], y2 = +_2[1]; - return quadtree; - }; - return quadtree; - }; - function d3_geom_quadtreeCompatX(d) { - return d.x; - } - function d3_geom_quadtreeCompatY(d) { - return d.y; - } - function d3_geom_quadtreeNode() { - return { - leaf: true, - nodes: [], - point: null, - x: null, - y: null - }; - } - function d3_geom_quadtreeVisit(f, node, x1, y1, x2, y2) { - if (!f(node, x1, y1, x2, y2)) { - var sx = (x1 + x2) * 0.5, sy = (y1 + y2) * 0.5, children = node.nodes; - if (children[0]) d3_geom_quadtreeVisit(f, children[0], x1, y1, sx, sy); - if (children[1]) d3_geom_quadtreeVisit(f, children[1], sx, y1, x2, sy); - if (children[2]) d3_geom_quadtreeVisit(f, children[2], x1, sy, sx, y2); - if (children[3]) d3_geom_quadtreeVisit(f, children[3], sx, sy, x2, y2); - } - } - function d3_geom_quadtreeFind(root, x, y, x0, y0, x3, y3) { - var minDistance2 = Infinity, closestPoint; - (function find(node, x1, y1, x2, y2) { - if (x1 > x3 || y1 > y3 || x2 < x0 || y2 < y0) return; - if (point = node.point) { - var point, dx = x - node.x, dy = y - node.y, distance2 = dx * dx + dy * dy; - if (distance2 < minDistance2) { - var distance = Math.sqrt(minDistance2 = distance2); - x0 = x - distance, y0 = y - distance; - x3 = x + distance, y3 = y + distance; - closestPoint = point; - } - } - var children = node.nodes, xm = (x1 + x2) * 0.5, ym = (y1 + y2) * 0.5, right = x >= xm, below = y >= ym; - for (var i = below << 1 | right, j = i + 4; i < j; ++i) { - if (node = children[i & 3]) switch (i & 3) { - case 0: - find(node, x1, y1, xm, ym); - break; - case 1: - find(node, xm, y1, x2, ym); - break; - case 2: - find(node, x1, ym, xm, y2); - break; - case 3: - find(node, xm, ym, x2, y2); - break; - } - } - })(root, x0, y0, x3, y3); - return closestPoint; - } - d32.interpolateRgb = d3_interpolateRgb; - function d3_interpolateRgb(a, b) { - a = d32.rgb(a); - b = d32.rgb(b); - var ar = a.r, ag = a.g, ab2 = a.b, br = b.r - ar, bg = b.g - ag, bb = b.b - ab2; - return function(t) { - return "#" + d3_rgb_hex(Math.round(ar + br * t)) + d3_rgb_hex(Math.round(ag + bg * t)) + d3_rgb_hex(Math.round(ab2 + bb * t)); - }; - } - d32.interpolateObject = d3_interpolateObject; - function d3_interpolateObject(a, b) { - var i = {}, c = {}, k; - for (k in a) { - if (k in b) { - i[k] = d3_interpolate(a[k], b[k]); - } else { - c[k] = a[k]; - } - } - for (k in b) { - if (!(k in a)) { - c[k] = b[k]; - } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; - } - d32.interpolateNumber = d3_interpolateNumber; - function d3_interpolateNumber(a, b) { - a = +a, b = +b; - return function(t) { - return a * (1 - t) + b * t; - }; - } - d32.interpolateString = d3_interpolateString; - function d3_interpolateString(a, b) { - var bi = d3_interpolate_numberA.lastIndex = d3_interpolate_numberB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = d3_interpolate_numberA.exec(a)) && (bm = d3_interpolate_numberB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; - else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; - else s[++i] = bm; - } else { - s[++i] = null; - q.push({ - i, - x: d3_interpolateNumber(am, bm) - }); - } - bi = d3_interpolate_numberB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; - else s[++i] = bs; - } - return s.length < 2 ? q[0] ? (b = q[0].x, function(t) { - return b(t) + ""; - }) : function() { - return b; - } : (b = q.length, function(t) { - for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t); - return s.join(""); - }); - } - var d3_interpolate_numberA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, d3_interpolate_numberB = new RegExp(d3_interpolate_numberA.source, "g"); - d32.interpolate = d3_interpolate; - function d3_interpolate(a, b) { - var i = d32.interpolators.length, f; - while (--i >= 0 && !(f = d32.interpolators[i](a, b))) ; - return f; - } - d32.interpolators = [function(a, b) { - var t = typeof b; - return (t === "string" ? d3_rgb_names.has(b.toLowerCase()) || /^(#|rgb\(|hsl\()/i.test(b) ? d3_interpolateRgb : d3_interpolateString : b instanceof d3_color ? d3_interpolateRgb : Array.isArray(b) ? d3_interpolateArray : t === "object" && isNaN(b) ? d3_interpolateObject : d3_interpolateNumber)(a, b); - }]; - d32.interpolateArray = d3_interpolateArray; - function d3_interpolateArray(a, b) { - var x = [], c = [], na = a.length, nb = b.length, n0 = Math.min(a.length, b.length), i; - for (i = 0; i < n0; ++i) x.push(d3_interpolate(a[i], b[i])); - for (; i < na; ++i) c[i] = a[i]; - for (; i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < n0; ++i) c[i] = x[i](t); - return c; - }; - } - var d3_ease_default = function() { - return d3_identity; - }; - var d3_ease = d32.map({ - linear: d3_ease_default, - poly: d3_ease_poly, - quad: function() { - return d3_ease_quad; - }, - cubic: function() { - return d3_ease_cubic; - }, - sin: function() { - return d3_ease_sin; - }, - exp: function() { - return d3_ease_exp; - }, - circle: function() { - return d3_ease_circle; - }, - elastic: d3_ease_elastic, - back: d3_ease_back, - bounce: function() { - return d3_ease_bounce; - } - }); - var d3_ease_mode = d32.map({ - "in": d3_identity, - out: d3_ease_reverse, - "in-out": d3_ease_reflect, - "out-in": function(f) { - return d3_ease_reflect(d3_ease_reverse(f)); - } - }); - d32.ease = function(name2) { - var i = name2.indexOf("-"), t = i >= 0 ? name2.slice(0, i) : name2, m = i >= 0 ? name2.slice(i + 1) : "in"; - t = d3_ease.get(t) || d3_ease_default; - m = d3_ease_mode.get(m) || d3_identity; - return d3_ease_clamp(m(t.apply(null, d3_arraySlice.call(arguments, 1)))); - }; - function d3_ease_clamp(f) { - return function(t) { - return t <= 0 ? 0 : t >= 1 ? 1 : f(t); - }; - } - function d3_ease_reverse(f) { - return function(t) { - return 1 - f(1 - t); - }; - } - function d3_ease_reflect(f) { - return function(t) { - return 0.5 * (t < 0.5 ? f(2 * t) : 2 - f(2 - 2 * t)); - }; - } - function d3_ease_quad(t) { - return t * t; - } - function d3_ease_cubic(t) { - return t * t * t; - } - function d3_ease_cubicInOut(t) { - if (t <= 0) return 0; - if (t >= 1) return 1; - var t22 = t * t, t32 = t22 * t; - return 4 * (t < 0.5 ? t32 : 3 * (t - t22) + t32 - 0.75); - } - function d3_ease_poly(e) { - return function(t) { - return Math.pow(t, e); - }; - } - function d3_ease_sin(t) { - return 1 - Math.cos(t * halfπ); - } - function d3_ease_exp(t) { - return Math.pow(2, 10 * (t - 1)); - } - function d3_ease_circle(t) { - return 1 - Math.sqrt(1 - t * t); - } - function d3_ease_elastic(a, p) { - var s; - if (arguments.length < 2) p = 0.45; - if (arguments.length) s = p / τ * Math.asin(1 / a); - else a = 1, s = p / 4; - return function(t) { - return 1 + a * Math.pow(2, -10 * t) * Math.sin((t - s) * τ / p); - }; - } - function d3_ease_back(s) { - if (!s) s = 1.70158; - return function(t) { - return t * t * ((s + 1) * t - s); - }; - } - function d3_ease_bounce(t) { - return t < 1 / 2.75 ? 7.5625 * t * t : t < 2 / 2.75 ? 7.5625 * (t -= 1.5 / 2.75) * t + 0.75 : t < 2.5 / 2.75 ? 7.5625 * (t -= 2.25 / 2.75) * t + 0.9375 : 7.5625 * (t -= 2.625 / 2.75) * t + 0.984375; - } - d32.interpolateHcl = d3_interpolateHcl; - function d3_interpolateHcl(a, b) { - a = d32.hcl(a); - b = d32.hcl(b); - var ah = a.h, ac = a.c, al = a.l, bh = b.h - ah, bc = b.c - ac, bl = b.l - al; - if (isNaN(bc)) bc = 0, ac = isNaN(ac) ? b.c : ac; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; - else if (bh > 180) bh -= 360; - else if (bh < -180) bh += 360; - return function(t) { - return d3_hcl_lab(ah + bh * t, ac + bc * t, al + bl * t) + ""; - }; - } - d32.interpolateHsl = d3_interpolateHsl; - function d3_interpolateHsl(a, b) { - a = d32.hsl(a); - b = d32.hsl(b); - var ah = a.h, as = a.s, al = a.l, bh = b.h - ah, bs = b.s - as, bl = b.l - al; - if (isNaN(bs)) bs = 0, as = isNaN(as) ? b.s : as; - if (isNaN(bh)) bh = 0, ah = isNaN(ah) ? b.h : ah; - else if (bh > 180) bh -= 360; - else if (bh < -180) bh += 360; - return function(t) { - return d3_hsl_rgb(ah + bh * t, as + bs * t, al + bl * t) + ""; - }; - } - d32.interpolateLab = d3_interpolateLab; - function d3_interpolateLab(a, b) { - a = d32.lab(a); - b = d32.lab(b); - var al = a.l, aa = a.a, ab2 = a.b, bl = b.l - al, ba = b.a - aa, bb = b.b - ab2; - return function(t) { - return d3_lab_rgb(al + bl * t, aa + ba * t, ab2 + bb * t) + ""; - }; - } - d32.interpolateRound = d3_interpolateRound; - function d3_interpolateRound(a, b) { - b -= a; - return function(t) { - return Math.round(a + b * t); - }; - } - d32.transform = function(string2) { - var g = d3_document.createElementNS(d32.ns.prefix.svg, "g"); - return (d32.transform = function(string3) { - if (string3 != null) { - g.setAttribute("transform", string3); - var t = g.transform.baseVal.consolidate(); - } - return new d3_transform(t ? t.matrix : d3_transformIdentity); - })(string2); - }; - function d3_transform(m) { - var r0 = [m.a, m.b], r1 = [m.c, m.d], kx = d3_transformNormalize(r0), kz = d3_transformDot(r0, r1), ky = d3_transformNormalize(d3_transformCombine(r1, r0, -kz)) || 0; - if (r0[0] * r1[1] < r1[0] * r0[1]) { - r0[0] *= -1; - r0[1] *= -1; - kx *= -1; - kz *= -1; - } - this.rotate = (kx ? Math.atan2(r0[1], r0[0]) : Math.atan2(-r1[0], r1[1])) * d3_degrees; - this.translate = [m.e, m.f]; - this.scale = [kx, ky]; - this.skew = ky ? Math.atan2(kz, ky) * d3_degrees : 0; - } - d3_transform.prototype.toString = function() { - return "translate(" + this.translate + ")rotate(" + this.rotate + ")skewX(" + this.skew + ")scale(" + this.scale + ")"; - }; - function d3_transformDot(a, b) { - return a[0] * b[0] + a[1] * b[1]; - } - function d3_transformNormalize(a) { - var k = Math.sqrt(d3_transformDot(a, a)); - if (k) { - a[0] /= k; - a[1] /= k; - } - return k; - } - function d3_transformCombine(a, b, k) { - a[0] += k * b[0]; - a[1] += k * b[1]; - return a; - } - var d3_transformIdentity = { - a: 1, - b: 0, - c: 0, - d: 1, - e: 0, - f: 0 - }; - d32.interpolateTransform = d3_interpolateTransform; - function d3_interpolateTransformPop(s) { - return s.length ? s.pop() + "," : ""; - } - function d3_interpolateTranslate(ta, tb, s, q) { - if (ta[0] !== tb[0] || ta[1] !== tb[1]) { - var i = s.push("translate(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ta[0], tb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ta[1], tb[1]) - }); - } else if (tb[0] || tb[1]) { - s.push("translate(" + tb + ")"); - } - } - function d3_interpolateRotate(ra, rb, s, q) { - if (ra !== rb) { - if (ra - rb > 180) rb += 360; - else if (rb - ra > 180) ra += 360; - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "rotate(", null, ")") - 2, - x: d3_interpolateNumber(ra, rb) - }); - } else if (rb) { - s.push(d3_interpolateTransformPop(s) + "rotate(" + rb + ")"); - } - } - function d3_interpolateSkew(wa, wb, s, q) { - if (wa !== wb) { - q.push({ - i: s.push(d3_interpolateTransformPop(s) + "skewX(", null, ")") - 2, - x: d3_interpolateNumber(wa, wb) - }); - } else if (wb) { - s.push(d3_interpolateTransformPop(s) + "skewX(" + wb + ")"); - } - } - function d3_interpolateScale(ka, kb, s, q) { - if (ka[0] !== kb[0] || ka[1] !== kb[1]) { - var i = s.push(d3_interpolateTransformPop(s) + "scale(", null, ",", null, ")"); - q.push({ - i: i - 4, - x: d3_interpolateNumber(ka[0], kb[0]) - }, { - i: i - 2, - x: d3_interpolateNumber(ka[1], kb[1]) - }); - } else if (kb[0] !== 1 || kb[1] !== 1) { - s.push(d3_interpolateTransformPop(s) + "scale(" + kb + ")"); - } - } - function d3_interpolateTransform(a, b) { - var s = [], q = []; - a = d32.transform(a), b = d32.transform(b); - d3_interpolateTranslate(a.translate, b.translate, s, q); - d3_interpolateRotate(a.rotate, b.rotate, s, q); - d3_interpolateSkew(a.skew, b.skew, s, q); - d3_interpolateScale(a.scale, b.scale, s, q); - a = b = null; - return function(t) { - var i = -1, n = q.length, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - } - function d3_uninterpolateNumber(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return (x - a) / b; - }; - } - function d3_uninterpolateClamp(a, b) { - b = (b -= a = +a) || 1 / b; - return function(x) { - return Math.max(0, Math.min(1, (x - a) / b)); - }; - } - d32.layout = {}; - d32.layout.bundle = function() { - return function(links) { - var paths = [], i = -1, n = links.length; - while (++i < n) paths.push(d3_layout_bundlePath(links[i])); - return paths; - }; - }; - function d3_layout_bundlePath(link) { - var start = link.source, end = link.target, lca = d3_layout_bundleLeastCommonAncestor(start, end), points = [start]; - while (start !== lca) { - start = start.parent; - points.push(start); - } - var k = points.length; - while (end !== lca) { - points.splice(k, 0, end); - end = end.parent; - } - return points; - } - function d3_layout_bundleAncestors(node) { - var ancestors = [], parent = node.parent; - while (parent != null) { - ancestors.push(node); - node = parent; - parent = parent.parent; - } - ancestors.push(node); - return ancestors; - } - function d3_layout_bundleLeastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = d3_layout_bundleAncestors(a), bNodes = d3_layout_bundleAncestors(b), aNode = aNodes.pop(), bNode = bNodes.pop(), sharedNode = null; - while (aNode === bNode) { - sharedNode = aNode; - aNode = aNodes.pop(); - bNode = bNodes.pop(); - } - return sharedNode; - } - d32.layout.chord = function() { - var chord = {}, chords, groups, matrix2, n, padding = 0, sortGroups, sortSubgroups, sortChords; - function relayout() { - var subgroups = {}, groupSums = [], groupIndex = d32.range(n), subgroupIndex = [], k, x, x0, i, j; - chords = []; - groups = []; - k = 0, i = -1; - while (++i < n) { - x = 0, j = -1; - while (++j < n) { - x += matrix2[i][j]; - } - groupSums.push(x); - subgroupIndex.push(d32.range(n)); - k += x; - } - if (sortGroups) { - groupIndex.sort(function(a, b) { - return sortGroups(groupSums[a], groupSums[b]); - }); - } - if (sortSubgroups) { - subgroupIndex.forEach(function(d, i2) { - d.sort(function(a, b) { - return sortSubgroups(matrix2[i2][a], matrix2[i2][b]); - }); - }); - } - k = (τ - padding * n) / k; - x = 0, i = -1; - while (++i < n) { - x0 = x, j = -1; - while (++j < n) { - var di = groupIndex[i], dj = subgroupIndex[di][j], v = matrix2[di][dj], a0 = x, a1 = x += v * k; - subgroups[di + "-" + dj] = { - index: di, - subindex: dj, - startAngle: a0, - endAngle: a1, - value: v - }; - } - groups[di] = { - index: di, - startAngle: x0, - endAngle: x, - value: groupSums[di] - }; - x += padding; - } - i = -1; - while (++i < n) { - j = i - 1; - while (++j < n) { - var source = subgroups[i + "-" + j], target = subgroups[j + "-" + i]; - if (source.value || target.value) { - chords.push(source.value < target.value ? { - source: target, - target: source - } : { - source, - target - }); - } - } - } - if (sortChords) resort(); - } - function resort() { - chords.sort(function(a, b) { - return sortChords((a.source.value + a.target.value) / 2, (b.source.value + b.target.value) / 2); - }); - } - chord.matrix = function(x) { - if (!arguments.length) return matrix2; - n = (matrix2 = x) && matrix2.length; - chords = groups = null; - return chord; - }; - chord.padding = function(x) { - if (!arguments.length) return padding; - padding = x; - chords = groups = null; - return chord; - }; - chord.sortGroups = function(x) { - if (!arguments.length) return sortGroups; - sortGroups = x; - chords = groups = null; - return chord; - }; - chord.sortSubgroups = function(x) { - if (!arguments.length) return sortSubgroups; - sortSubgroups = x; - chords = null; - return chord; - }; - chord.sortChords = function(x) { - if (!arguments.length) return sortChords; - sortChords = x; - if (chords) resort(); - return chord; - }; - chord.chords = function() { - if (!chords) relayout(); - return chords; - }; - chord.groups = function() { - if (!groups) relayout(); - return groups; - }; - return chord; - }; - d32.layout.force = function() { - var force = {}, event = d32.dispatch("start", "tick", "end"), timer, size = [1, 1], drag, alpha, friction = 0.9, linkDistance = d3_layout_forceLinkDistance, linkStrength = d3_layout_forceLinkStrength, charge = -30, chargeDistance2 = d3_layout_forceChargeDistance2, gravity = 0.1, theta2 = 0.64, nodes = [], links = [], distances, strengths, charges; - function repulse(node) { - return function(quad2, x1, _2, x2) { - if (quad2.point !== node) { - var dx = quad2.cx - node.x, dy = quad2.cy - node.y, dw = x2 - x1, dn = dx * dx + dy * dy; - if (dw * dw / theta2 < dn) { - if (dn < chargeDistance2) { - var k = quad2.charge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - return true; - } - if (quad2.point && dn && dn < chargeDistance2) { - var k = quad2.pointCharge / dn; - node.px -= dx * k; - node.py -= dy * k; - } - } - return !quad2.charge; - }; - } - force.tick = function() { - if ((alpha *= 0.99) < 5e-3) { - timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - return true; - } - var n = nodes.length, m = links.length, q, i, o, s, t, l, k, x, y; - for (i = 0; i < m; ++i) { - o = links[i]; - s = o.source; - t = o.target; - x = t.x - s.x; - y = t.y - s.y; - if (l = x * x + y * y) { - l = alpha * strengths[i] * ((l = Math.sqrt(l)) - distances[i]) / l; - x *= l; - y *= l; - t.x -= x * (k = s.weight + t.weight ? s.weight / (s.weight + t.weight) : 0.5); - t.y -= y * k; - s.x += x * (k = 1 - k); - s.y += y * k; - } - } - if (k = alpha * gravity) { - x = size[0] / 2; - y = size[1] / 2; - i = -1; - if (k) while (++i < n) { - o = nodes[i]; - o.x += (x - o.x) * k; - o.y += (y - o.y) * k; - } - } - if (charge) { - d3_layout_forceAccumulate(q = d32.geom.quadtree(nodes), alpha, charges); - i = -1; - while (++i < n) { - if (!(o = nodes[i]).fixed) { - q.visit(repulse(o)); - } - } - } - i = -1; - while (++i < n) { - o = nodes[i]; - if (o.fixed) { - o.x = o.px; - o.y = o.py; - } else { - o.x -= (o.px - (o.px = o.x)) * friction; - o.y -= (o.py - (o.py = o.y)) * friction; - } - } - event.tick({ - type: "tick", - alpha - }); - }; - force.nodes = function(x) { - if (!arguments.length) return nodes; - nodes = x; - return force; - }; - force.links = function(x) { - if (!arguments.length) return links; - links = x; - return force; - }; - force.size = function(x) { - if (!arguments.length) return size; - size = x; - return force; - }; - force.linkDistance = function(x) { - if (!arguments.length) return linkDistance; - linkDistance = typeof x === "function" ? x : +x; - return force; - }; - force.distance = force.linkDistance; - force.linkStrength = function(x) { - if (!arguments.length) return linkStrength; - linkStrength = typeof x === "function" ? x : +x; - return force; - }; - force.friction = function(x) { - if (!arguments.length) return friction; - friction = +x; - return force; - }; - force.charge = function(x) { - if (!arguments.length) return charge; - charge = typeof x === "function" ? x : +x; - return force; - }; - force.chargeDistance = function(x) { - if (!arguments.length) return Math.sqrt(chargeDistance2); - chargeDistance2 = x * x; - return force; - }; - force.gravity = function(x) { - if (!arguments.length) return gravity; - gravity = +x; - return force; - }; - force.theta = function(x) { - if (!arguments.length) return Math.sqrt(theta2); - theta2 = x * x; - return force; - }; - force.alpha = function(x) { - if (!arguments.length) return alpha; - x = +x; - if (alpha) { - if (x > 0) { - alpha = x; - } else { - timer.c = null, timer.t = NaN, timer = null; - event.end({ - type: "end", - alpha: alpha = 0 - }); - } - } else if (x > 0) { - event.start({ - type: "start", - alpha: alpha = x - }); - timer = d3_timer(force.tick); - } - return force; - }; - force.start = function() { - var i, n = nodes.length, m = links.length, w = size[0], h = size[1], neighbors, o; - for (i = 0; i < n; ++i) { - (o = nodes[i]).index = i; - o.weight = 0; - } - for (i = 0; i < m; ++i) { - o = links[i]; - if (typeof o.source == "number") o.source = nodes[o.source]; - if (typeof o.target == "number") o.target = nodes[o.target]; - ++o.source.weight; - ++o.target.weight; - } - for (i = 0; i < n; ++i) { - o = nodes[i]; - if (isNaN(o.x)) o.x = position("x", w); - if (isNaN(o.y)) o.y = position("y", h); - if (isNaN(o.px)) o.px = o.x; - if (isNaN(o.py)) o.py = o.y; - } - distances = []; - if (typeof linkDistance === "function") for (i = 0; i < m; ++i) distances[i] = +linkDistance.call(this, links[i], i); - else for (i = 0; i < m; ++i) distances[i] = linkDistance; - strengths = []; - if (typeof linkStrength === "function") for (i = 0; i < m; ++i) strengths[i] = +linkStrength.call(this, links[i], i); - else for (i = 0; i < m; ++i) strengths[i] = linkStrength; - charges = []; - if (typeof charge === "function") for (i = 0; i < n; ++i) charges[i] = +charge.call(this, nodes[i], i); - else for (i = 0; i < n; ++i) charges[i] = charge; - function position(dimension, size2) { - if (!neighbors) { - neighbors = new Array(n); - for (j = 0; j < n; ++j) { - neighbors[j] = []; - } - for (j = 0; j < m; ++j) { - var o2 = links[j]; - neighbors[o2.source.index].push(o2.target); - neighbors[o2.target.index].push(o2.source); - } - } - var candidates = neighbors[i], j = -1, l = candidates.length, x; - while (++j < l) if (!isNaN(x = candidates[j][dimension])) return x; - return Math.random() * size2; - } - return force.resume(); - }; - force.resume = function() { - return force.alpha(0.1); - }; - force.stop = function() { - return force.alpha(0); - }; - force.drag = function() { - if (!drag) drag = d32.behavior.drag().origin(d3_identity).on("dragstart.force", d3_layout_forceDragstart).on("drag.force", dragmove).on("dragend.force", d3_layout_forceDragend); - if (!arguments.length) return drag; - this.on("mouseover.force", d3_layout_forceMouseover).on("mouseout.force", d3_layout_forceMouseout).call(drag); - }; - function dragmove(d) { - d.px = d32.event.x, d.py = d32.event.y; - force.resume(); - } - return d32.rebind(force, event, "on"); - }; - function d3_layout_forceDragstart(d) { - d.fixed |= 2; - } - function d3_layout_forceDragend(d) { - d.fixed &= -7; - } - function d3_layout_forceMouseover(d) { - d.fixed |= 4; - d.px = d.x, d.py = d.y; - } - function d3_layout_forceMouseout(d) { - d.fixed &= -5; - } - function d3_layout_forceAccumulate(quad2, alpha, charges) { - var cx = 0, cy = 0; - quad2.charge = 0; - if (!quad2.leaf) { - var nodes = quad2.nodes, n = nodes.length, i = -1, c; - while (++i < n) { - c = nodes[i]; - if (c == null) continue; - d3_layout_forceAccumulate(c, alpha, charges); - quad2.charge += c.charge; - cx += c.charge * c.cx; - cy += c.charge * c.cy; - } - } - if (quad2.point) { - if (!quad2.leaf) { - quad2.point.x += Math.random() - 0.5; - quad2.point.y += Math.random() - 0.5; - } - var k = alpha * charges[quad2.point.index]; - quad2.charge += quad2.pointCharge = k; - cx += k * quad2.point.x; - cy += k * quad2.point.y; - } - quad2.cx = cx / quad2.charge; - quad2.cy = cy / quad2.charge; - } - var d3_layout_forceLinkDistance = 20, d3_layout_forceLinkStrength = 1, d3_layout_forceChargeDistance2 = Infinity; - d32.layout.hierarchy = function() { - var sort = d3_layout_hierarchySort, children = d3_layout_hierarchyChildren, value2 = d3_layout_hierarchyValue; - function hierarchy2(root) { - var stack = [root], nodes = [], node; - root.depth = 0; - while ((node = stack.pop()) != null) { - nodes.push(node); - if ((childs = children.call(hierarchy2, node, node.depth)) && (n = childs.length)) { - var n, childs, child; - while (--n >= 0) { - stack.push(child = childs[n]); - child.parent = node; - child.depth = node.depth + 1; - } - if (value2) node.value = 0; - node.children = childs; - } else { - if (value2) node.value = +value2.call(hierarchy2, node, node.depth) || 0; - delete node.children; - } - } - d3_layout_hierarchyVisitAfter(root, function(node2) { - var childs2, parent; - if (sort && (childs2 = node2.children)) childs2.sort(sort); - if (value2 && (parent = node2.parent)) parent.value += node2.value; - }); - return nodes; - } - hierarchy2.sort = function(x) { - if (!arguments.length) return sort; - sort = x; - return hierarchy2; - }; - hierarchy2.children = function(x) { - if (!arguments.length) return children; - children = x; - return hierarchy2; - }; - hierarchy2.value = function(x) { - if (!arguments.length) return value2; - value2 = x; - return hierarchy2; - }; - hierarchy2.revalue = function(root) { - if (value2) { - d3_layout_hierarchyVisitBefore(root, function(node) { - if (node.children) node.value = 0; - }); - d3_layout_hierarchyVisitAfter(root, function(node) { - var parent; - if (!node.children) node.value = +value2.call(hierarchy2, node, node.depth) || 0; - if (parent = node.parent) parent.value += node.value; - }); - } - return root; - }; - return hierarchy2; - }; - function d3_layout_hierarchyRebind(object2, hierarchy2) { - d32.rebind(object2, hierarchy2, "sort", "children", "value"); - object2.nodes = object2; - object2.links = d3_layout_hierarchyLinks; - return object2; - } - function d3_layout_hierarchyVisitBefore(node, callback) { - var nodes = [node]; - while ((node = nodes.pop()) != null) { - callback(node); - if ((children = node.children) && (n = children.length)) { - var n, children; - while (--n >= 0) nodes.push(children[n]); - } - } - } - function d3_layout_hierarchyVisitAfter(node, callback) { - var nodes = [node], nodes2 = []; - while ((node = nodes.pop()) != null) { - nodes2.push(node); - if ((children = node.children) && (n = children.length)) { - var i = -1, n, children; - while (++i < n) nodes.push(children[i]); - } - } - while ((node = nodes2.pop()) != null) { - callback(node); - } - } - function d3_layout_hierarchyChildren(d) { - return d.children; - } - function d3_layout_hierarchyValue(d) { - return d.value; - } - function d3_layout_hierarchySort(a, b) { - return b.value - a.value; - } - function d3_layout_hierarchyLinks(nodes) { - return d32.merge(nodes.map(function(parent) { - return (parent.children || []).map(function(child) { - return { - source: parent, - target: child - }; - }); - })); - } - d32.layout.partition = function() { - var hierarchy2 = d32.layout.hierarchy(), size = [1, 1]; - function position(node, x, dx, dy) { - var children = node.children; - node.x = x; - node.y = node.depth * dy; - node.dx = dx; - node.dy = dy; - if (children && (n = children.length)) { - var i = -1, n, c, d; - dx = node.value ? dx / node.value : 0; - while (++i < n) { - position(c = children[i], x, d = c.value * dx, dy); - x += d; - } - } - } - function depth(node) { - var children = node.children, d = 0; - if (children && (n = children.length)) { - var i = -1, n; - while (++i < n) d = Math.max(d, depth(children[i])); - } - return 1 + d; - } - function partition3(d, i) { - var nodes = hierarchy2.call(this, d, i); - position(nodes[0], 0, size[0], size[1] / depth(nodes[0])); - return nodes; - } - partition3.size = function(x) { - if (!arguments.length) return size; - size = x; - return partition3; - }; - return d3_layout_hierarchyRebind(partition3, hierarchy2); - }; - d32.layout.pie = function() { - var value2 = Number, sort = d3_layout_pieSortByValue, startAngle = 0, endAngle = τ, padAngle = 0; - function pie2(data) { - var n = data.length, values = data.map(function(d, i) { - return +value2.call(pie2, d, i); - }), a = +(typeof startAngle === "function" ? startAngle.apply(this, arguments) : startAngle), da = (typeof endAngle === "function" ? endAngle.apply(this, arguments) : endAngle) - a, p = Math.min(Math.abs(da) / n, +(typeof padAngle === "function" ? padAngle.apply(this, arguments) : padAngle)), pa = p * (da < 0 ? -1 : 1), sum = d32.sum(values), k = sum ? (da - n * pa) / sum : 0, index2 = d32.range(n), arcs = [], v; - if (sort != null) index2.sort(sort === d3_layout_pieSortByValue ? function(i, j) { - return values[j] - values[i]; - } : function(i, j) { - return sort(data[i], data[j]); - }); - index2.forEach(function(i) { - arcs[i] = { - data: data[i], - value: v = values[i], - startAngle: a, - endAngle: a += v * k + pa, - padAngle: p - }; - }); - return arcs; - } - pie2.value = function(_2) { - if (!arguments.length) return value2; - value2 = _2; - return pie2; - }; - pie2.sort = function(_2) { - if (!arguments.length) return sort; - sort = _2; - return pie2; - }; - pie2.startAngle = function(_2) { - if (!arguments.length) return startAngle; - startAngle = _2; - return pie2; - }; - pie2.endAngle = function(_2) { - if (!arguments.length) return endAngle; - endAngle = _2; - return pie2; - }; - pie2.padAngle = function(_2) { - if (!arguments.length) return padAngle; - padAngle = _2; - return pie2; - }; - return pie2; - }; - var d3_layout_pieSortByValue = {}; - d32.layout.stack = function() { - var values = d3_identity, order = d3_layout_stackOrderDefault, offset = d3_layout_stackOffsetZero, out = d3_layout_stackOut, x = d3_layout_stackX, y = d3_layout_stackY; - function stack(data, index2) { - if (!(n = data.length)) return data; - var series = data.map(function(d, i2) { - return values.call(stack, d, i2); - }); - var points = series.map(function(d) { - return d.map(function(v, i2) { - return [x.call(stack, v, i2), y.call(stack, v, i2)]; - }); - }); - var orders = order.call(stack, points, index2); - series = d32.permute(series, orders); - points = d32.permute(points, orders); - var offsets = offset.call(stack, points, index2); - var m = series[0].length, n, i, j, o; - for (j = 0; j < m; ++j) { - out.call(stack, series[0][j], o = offsets[j], points[0][j][1]); - for (i = 1; i < n; ++i) { - out.call(stack, series[i][j], o += points[i - 1][j][1], points[i][j][1]); - } - } - return data; - } - stack.values = function(x2) { - if (!arguments.length) return values; - values = x2; - return stack; - }; - stack.order = function(x2) { - if (!arguments.length) return order; - order = typeof x2 === "function" ? x2 : d3_layout_stackOrders.get(x2) || d3_layout_stackOrderDefault; - return stack; - }; - stack.offset = function(x2) { - if (!arguments.length) return offset; - offset = typeof x2 === "function" ? x2 : d3_layout_stackOffsets.get(x2) || d3_layout_stackOffsetZero; - return stack; - }; - stack.x = function(z) { - if (!arguments.length) return x; - x = z; - return stack; - }; - stack.y = function(z) { - if (!arguments.length) return y; - y = z; - return stack; - }; - stack.out = function(z) { - if (!arguments.length) return out; - out = z; - return stack; - }; - return stack; - }; - function d3_layout_stackX(d) { - return d.x; - } - function d3_layout_stackY(d) { - return d.y; - } - function d3_layout_stackOut(d, y0, y) { - d.y0 = y0; - d.y = y; - } - var d3_layout_stackOrders = d32.map({ - "inside-out": function(data) { - var n = data.length, i, j, max = data.map(d3_layout_stackMaxIndex), sums = data.map(d3_layout_stackReduceSum), index2 = d32.range(n).sort(function(a, b) { - return max[a] - max[b]; - }), top = 0, bottom = 0, tops = [], bottoms = []; - for (i = 0; i < n; ++i) { - j = index2[i]; - if (top < bottom) { - top += sums[j]; - tops.push(j); - } else { - bottom += sums[j]; - bottoms.push(j); - } - } - return bottoms.reverse().concat(tops); - }, - reverse: function(data) { - return d32.range(data.length).reverse(); - }, - "default": d3_layout_stackOrderDefault - }); - var d3_layout_stackOffsets = d32.map({ - silhouette: function(data) { - var n = data.length, m = data[0].length, sums = [], max = 0, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o > max) max = o; - sums.push(o); - } - for (j = 0; j < m; ++j) { - y0[j] = (max - sums[j]) / 2; - } - return y0; - }, - wiggle: function(data) { - var n = data.length, x = data[0], m = x.length, i, j, k, s1, s2, s3, dx, o, o0, y0 = []; - y0[0] = o = o0 = 0; - for (j = 1; j < m; ++j) { - for (i = 0, s1 = 0; i < n; ++i) s1 += data[i][j][1]; - for (i = 0, s2 = 0, dx = x[j][0] - x[j - 1][0]; i < n; ++i) { - for (k = 0, s3 = (data[i][j][1] - data[i][j - 1][1]) / (2 * dx); k < i; ++k) { - s3 += (data[k][j][1] - data[k][j - 1][1]) / dx; - } - s2 += s3 * data[i][j][1]; - } - y0[j] = o -= s1 ? s2 / s1 * dx : 0; - if (o < o0) o0 = o; - } - for (j = 0; j < m; ++j) y0[j] -= o0; - return y0; - }, - expand: function(data) { - var n = data.length, m = data[0].length, k = 1 / n, i, j, o, y0 = []; - for (j = 0; j < m; ++j) { - for (i = 0, o = 0; i < n; i++) o += data[i][j][1]; - if (o) for (i = 0; i < n; i++) data[i][j][1] /= o; - else for (i = 0; i < n; i++) data[i][j][1] = k; - } - for (j = 0; j < m; ++j) y0[j] = 0; - return y0; - }, - zero: d3_layout_stackOffsetZero - }); - function d3_layout_stackOrderDefault(data) { - return d32.range(data.length); - } - function d3_layout_stackOffsetZero(data) { - var j = -1, m = data[0].length, y0 = []; - while (++j < m) y0[j] = 0; - return y0; - } - function d3_layout_stackMaxIndex(array2) { - var i = 1, j = 0, v = array2[0][1], k, n = array2.length; - for (; i < n; ++i) { - if ((k = array2[i][1]) > v) { - j = i; - v = k; - } - } - return j; - } - function d3_layout_stackReduceSum(d) { - return d.reduce(d3_layout_stackSum, 0); - } - function d3_layout_stackSum(p, d) { - return p + d[1]; - } - d32.layout.histogram = function() { - var frequency = true, valuer = Number, ranger = d3_layout_histogramRange, binner = d3_layout_histogramBinSturges; - function histogram2(data, i) { - var bins = [], values = data.map(valuer, this), range = ranger.call(this, values, i), thresholds = binner.call(this, range, values, i), bin, i = -1, n = values.length, m = thresholds.length - 1, k = frequency ? 1 : 1 / n, x; - while (++i < m) { - bin = bins[i] = []; - bin.dx = thresholds[i + 1] - (bin.x = thresholds[i]); - bin.y = 0; - } - if (m > 0) { - i = -1; - while (++i < n) { - x = values[i]; - if (x >= range[0] && x <= range[1]) { - bin = bins[d32.bisect(thresholds, x, 1, m) - 1]; - bin.y += k; - bin.push(data[i]); - } - } - } - return bins; - } - histogram2.value = function(x) { - if (!arguments.length) return valuer; - valuer = x; - return histogram2; - }; - histogram2.range = function(x) { - if (!arguments.length) return ranger; - ranger = d3_functor(x); - return histogram2; - }; - histogram2.bins = function(x) { - if (!arguments.length) return binner; - binner = typeof x === "number" ? function(range) { - return d3_layout_histogramBinFixed(range, x); - } : d3_functor(x); - return histogram2; - }; - histogram2.frequency = function(x) { - if (!arguments.length) return frequency; - frequency = !!x; - return histogram2; - }; - return histogram2; - }; - function d3_layout_histogramBinSturges(range, values) { - return d3_layout_histogramBinFixed(range, Math.ceil(Math.log(values.length) / Math.LN2 + 1)); - } - function d3_layout_histogramBinFixed(range, n) { - var x = -1, b = +range[0], m = (range[1] - b) / n, f = []; - while (++x <= n) f[x] = m * x + b; - return f; - } - function d3_layout_histogramRange(values) { - return [d32.min(values), d32.max(values)]; - } - d32.layout.pack = function() { - var hierarchy2 = d32.layout.hierarchy().sort(d3_layout_packSort), padding = 0, size = [1, 1], radius; - function pack(d, i) { - var nodes = hierarchy2.call(this, d, i), root = nodes[0], w = size[0], h = size[1], r = radius == null ? Math.sqrt : typeof radius === "function" ? radius : function() { - return radius; - }; - root.x = root.y = 0; - d3_layout_hierarchyVisitAfter(root, function(d2) { - d2.r = +r(d2.value); - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - if (padding) { - var dr = padding * (radius ? 1 : Math.max(2 * root.r / w, 2 * root.r / h)) / 2; - d3_layout_hierarchyVisitAfter(root, function(d2) { - d2.r += dr; - }); - d3_layout_hierarchyVisitAfter(root, d3_layout_packSiblings); - d3_layout_hierarchyVisitAfter(root, function(d2) { - d2.r -= dr; - }); - } - d3_layout_packTransform(root, w / 2, h / 2, radius ? 1 : 1 / Math.max(2 * root.r / w, 2 * root.r / h)); - return nodes; - } - pack.size = function(_2) { - if (!arguments.length) return size; - size = _2; - return pack; - }; - pack.radius = function(_2) { - if (!arguments.length) return radius; - radius = _2 == null || typeof _2 === "function" ? _2 : +_2; - return pack; - }; - pack.padding = function(_2) { - if (!arguments.length) return padding; - padding = +_2; - return pack; - }; - return d3_layout_hierarchyRebind(pack, hierarchy2); - }; - function d3_layout_packSort(a, b) { - return a.value - b.value; - } - function d3_layout_packInsert(a, b) { - var c = a._pack_next; - a._pack_next = b; - b._pack_prev = a; - b._pack_next = c; - c._pack_prev = b; - } - function d3_layout_packSplice(a, b) { - a._pack_next = b; - b._pack_prev = a; - } - function d3_layout_packIntersects(a, b) { - var dx = b.x - a.x, dy = b.y - a.y, dr = a.r + b.r; - return 0.999 * dr * dr > dx * dx + dy * dy; - } - function d3_layout_packSiblings(node) { - if (!(nodes = node.children) || !(n = nodes.length)) return; - var nodes, xMin = Infinity, xMax = -Infinity, yMin = Infinity, yMax = -Infinity, a, b, c, i, j, k, n; - function bound(node2) { - xMin = Math.min(node2.x - node2.r, xMin); - xMax = Math.max(node2.x + node2.r, xMax); - yMin = Math.min(node2.y - node2.r, yMin); - yMax = Math.max(node2.y + node2.r, yMax); - } - nodes.forEach(d3_layout_packLink); - a = nodes[0]; - a.x = -a.r; - a.y = 0; - bound(a); - if (n > 1) { - b = nodes[1]; - b.x = b.r; - b.y = 0; - bound(b); - if (n > 2) { - c = nodes[2]; - d3_layout_packPlace(a, b, c); - bound(c); - d3_layout_packInsert(a, c); - a._pack_prev = c; - d3_layout_packInsert(c, b); - b = a._pack_next; - for (i = 3; i < n; i++) { - d3_layout_packPlace(a, b, c = nodes[i]); - var isect = 0, s1 = 1, s2 = 1; - for (j = b._pack_next; j !== b; j = j._pack_next, s1++) { - if (d3_layout_packIntersects(j, c)) { - isect = 1; - break; - } - } - if (isect == 1) { - for (k = a._pack_prev; k !== j._pack_prev; k = k._pack_prev, s2++) { - if (d3_layout_packIntersects(k, c)) { - break; - } - } - } - if (isect) { - if (s1 < s2 || s1 == s2 && b.r < a.r) d3_layout_packSplice(a, b = j); - else d3_layout_packSplice(a = k, b); - i--; - } else { - d3_layout_packInsert(a, c); - b = c; - bound(c); - } - } - } - } - var cx = (xMin + xMax) / 2, cy = (yMin + yMax) / 2, cr = 0; - for (i = 0; i < n; i++) { - c = nodes[i]; - c.x -= cx; - c.y -= cy; - cr = Math.max(cr, c.r + Math.sqrt(c.x * c.x + c.y * c.y)); - } - node.r = cr; - nodes.forEach(d3_layout_packUnlink); - } - function d3_layout_packLink(node) { - node._pack_next = node._pack_prev = node; - } - function d3_layout_packUnlink(node) { - delete node._pack_next; - delete node._pack_prev; - } - function d3_layout_packTransform(node, x, y, k) { - var children = node.children; - node.x = x += k * node.x; - node.y = y += k * node.y; - node.r *= k; - if (children) { - var i = -1, n = children.length; - while (++i < n) d3_layout_packTransform(children[i], x, y, k); - } - } - function d3_layout_packPlace(a, b, c) { - var db = a.r + c.r, dx = b.x - a.x, dy = b.y - a.y; - if (db && (dx || dy)) { - var da = b.r + c.r, dc = dx * dx + dy * dy; - da *= da; - db *= db; - var x = 0.5 + (db - da) / (2 * dc), y = Math.sqrt(Math.max(0, 2 * da * (db + dc) - (db -= dc) * db - da * da)) / (2 * dc); - c.x = a.x + x * dx + y * dy; - c.y = a.y + x * dy - y * dx; - } else { - c.x = a.x + db; - c.y = a.y; - } - } - d32.layout.tree = function() { - var hierarchy2 = d32.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = null; - function tree2(d, i) { - var nodes = hierarchy2.call(this, d, i), root0 = nodes[0], root1 = wrapTree(root0); - d3_layout_hierarchyVisitAfter(root1, firstWalk), root1.parent.m = -root1.z; - d3_layout_hierarchyVisitBefore(root1, secondWalk); - if (nodeSize) d3_layout_hierarchyVisitBefore(root0, sizeNode); - else { - var left = root0, right = root0, bottom = root0; - d3_layout_hierarchyVisitBefore(root0, function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var tx = separation(left, right) / 2 - left.x, kx = size[0] / (right.x + separation(right, left) / 2 + tx), ky = size[1] / (bottom.depth || 1); - d3_layout_hierarchyVisitBefore(root0, function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); - } - return nodes; - } - function wrapTree(root0) { - var root1 = { - A: null, - children: [root0] - }, queue2 = [root1], node1; - while ((node1 = queue2.pop()) != null) { - for (var children = node1.children, child, i = 0, n = children.length; i < n; ++i) { - queue2.push((children[i] = child = { - _: children[i], - parent: node1, - children: (child = children[i].children) && child.slice() || [], - A: null, - a: null, - z: 0, - m: 0, - c: 0, - s: 0, - t: null, - i - }).a = child); - } - } - return root1.children[0]; - } - function firstWalk(v) { - var children = v.children, siblings2 = v.parent.children, w = v.i ? siblings2[v.i - 1] : null; - if (children.length) { - d3_layout_treeShift(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; - } else { - v.z = midpoint; - } - } else if (w) { - v.z = w.z + separation(v._, w._); - } - v.parent.A = apportion(v, w, v.parent.A || siblings2[0]); - } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; - } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = d3_layout_treeRight(vim), vip = d3_layout_treeLeft(vip), vim && vip) { - vom = d3_layout_treeLeft(vom); - vop = d3_layout_treeRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - d3_layout_treeMove(d3_layout_treeAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !d3_layout_treeRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !d3_layout_treeLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; - } - } - return ancestor; - } - function sizeNode(node) { - node.x *= size[0]; - node.y = node.depth * size[1]; - } - tree2.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return tree2; - }; - tree2.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null ? sizeNode : null; - return tree2; - }; - tree2.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) == null ? null : sizeNode; - return tree2; - }; - return d3_layout_hierarchyRebind(tree2, hierarchy2); - }; - function d3_layout_treeSeparation(a, b) { - return a.parent == b.parent ? 1 : 2; - } - function d3_layout_treeLeft(v) { - var children = v.children; - return children.length ? children[0] : v.t; - } - function d3_layout_treeRight(v) { - var children = v.children, n; - return (n = children.length) ? children[n - 1] : v.t; - } - function d3_layout_treeMove(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; - } - function d3_layout_treeShift(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } - } - function d3_layout_treeAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; - } - d32.layout.cluster = function() { - var hierarchy2 = d32.layout.hierarchy().sort(null).value(null), separation = d3_layout_treeSeparation, size = [1, 1], nodeSize = false; - function cluster3(d, i) { - var nodes = hierarchy2.call(this, d, i), root = nodes[0], previousNode, x = 0; - d3_layout_hierarchyVisitAfter(root, function(node) { - var children = node.children; - if (children && children.length) { - node.x = d3_layout_clusterX(children); - node.y = d3_layout_clusterY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = d3_layout_clusterLeft(root), right = d3_layout_clusterRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - d3_layout_hierarchyVisitAfter(root, nodeSize ? function(node) { - node.x = (node.x - root.x) * size[0]; - node.y = (root.y - node.y) * size[1]; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * size[0]; - node.y = (1 - (root.y ? node.y / root.y : 1)) * size[1]; - }); - return nodes; - } - cluster3.separation = function(x) { - if (!arguments.length) return separation; - separation = x; - return cluster3; - }; - cluster3.size = function(x) { - if (!arguments.length) return nodeSize ? null : size; - nodeSize = (size = x) == null; - return cluster3; - }; - cluster3.nodeSize = function(x) { - if (!arguments.length) return nodeSize ? size : null; - nodeSize = (size = x) != null; - return cluster3; - }; - return d3_layout_hierarchyRebind(cluster3, hierarchy2); - }; - function d3_layout_clusterY(children) { - return 1 + d32.max(children, function(child) { - return child.y; - }); - } - function d3_layout_clusterX(children) { - return children.reduce(function(x, child) { - return x + child.x; - }, 0) / children.length; - } - function d3_layout_clusterLeft(node) { - var children = node.children; - return children && children.length ? d3_layout_clusterLeft(children[0]) : node; - } - function d3_layout_clusterRight(node) { - var children = node.children, n; - return children && (n = children.length) ? d3_layout_clusterRight(children[n - 1]) : node; - } - d32.layout.treemap = function() { - var hierarchy2 = d32.layout.hierarchy(), round2 = Math.round, size = [1, 1], padding = null, pad2 = d3_layout_treemapPadNull, sticky = false, stickies, mode = "squarify", ratio = 0.5 * (1 + Math.sqrt(5)); - function scale2(children, k) { - var i = -1, n = children.length, child, area2; - while (++i < n) { - area2 = (child = children[i]).value * (k < 0 ? 0 : k); - child.area = isNaN(area2) || area2 <= 0 ? 0 : area2; - } - } - function squarify2(node) { - var children = node.children; - if (children && children.length) { - var rect2 = pad2(node), row = [], remaining = children.slice(), child, best = Infinity, score2, u = mode === "slice" ? rect2.dx : mode === "dice" ? rect2.dy : mode === "slice-dice" ? node.depth & 1 ? rect2.dy : rect2.dx : Math.min(rect2.dx, rect2.dy), n; - scale2(remaining, rect2.dx * rect2.dy / node.value); - row.area = 0; - while ((n = remaining.length) > 0) { - row.push(child = remaining[n - 1]); - row.area += child.area; - if (mode !== "squarify" || (score2 = worst(row, u)) <= best) { - remaining.pop(); - best = score2; - } else { - row.area -= row.pop().area; - position(row, u, rect2, false); - u = Math.min(rect2.dx, rect2.dy); - row.length = row.area = 0; - best = Infinity; - } - } - if (row.length) { - position(row, u, rect2, true); - row.length = row.area = 0; - } - children.forEach(squarify2); - } - } - function stickify(node) { - var children = node.children; - if (children && children.length) { - var rect2 = pad2(node), remaining = children.slice(), child, row = []; - scale2(remaining, rect2.dx * rect2.dy / node.value); - row.area = 0; - while (child = remaining.pop()) { - row.push(child); - row.area += child.area; - if (child.z != null) { - position(row, child.z ? rect2.dx : rect2.dy, rect2, !remaining.length); - row.length = row.area = 0; - } - } - children.forEach(stickify); - } - } - function worst(row, u) { - var s = row.area, r, rmax = 0, rmin = Infinity, i = -1, n = row.length; - while (++i < n) { - if (!(r = row[i].area)) continue; - if (r < rmin) rmin = r; - if (r > rmax) rmax = r; - } - s *= s; - u *= u; - return s ? Math.max(u * rmax * ratio / s, s / (u * rmin * ratio)) : Infinity; - } - function position(row, u, rect2, flush) { - var i = -1, n = row.length, x = rect2.x, y = rect2.y, v = u ? round2(row.area / u) : 0, o; - if (u == rect2.dx) { - if (flush || v > rect2.dy) v = rect2.dy; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dy = v; - x += o.dx = Math.min(rect2.x + rect2.dx - x, v ? round2(o.area / v) : 0); - } - o.z = true; - o.dx += rect2.x + rect2.dx - x; - rect2.y += v; - rect2.dy -= v; - } else { - if (flush || v > rect2.dx) v = rect2.dx; - while (++i < n) { - o = row[i]; - o.x = x; - o.y = y; - o.dx = v; - y += o.dy = Math.min(rect2.y + rect2.dy - y, v ? round2(o.area / v) : 0); - } - o.z = false; - o.dy += rect2.y + rect2.dy - y; - rect2.x += v; - rect2.dx -= v; - } - } - function treemap2(d) { - var nodes = stickies || hierarchy2(d), root = nodes[0]; - root.x = root.y = 0; - if (root.value) root.dx = size[0], root.dy = size[1]; - else root.dx = root.dy = 0; - if (stickies) hierarchy2.revalue(root); - scale2([root], root.dx * root.dy / root.value); - (stickies ? stickify : squarify2)(root); - if (sticky) stickies = nodes; - return nodes; - } - treemap2.size = function(x) { - if (!arguments.length) return size; - size = x; - return treemap2; - }; - treemap2.padding = function(x) { - if (!arguments.length) return padding; - function padFunction(node) { - var p = x.call(treemap2, node, node.depth); - return p == null ? d3_layout_treemapPadNull(node) : d3_layout_treemapPad(node, typeof p === "number" ? [p, p, p, p] : p); - } - function padConstant(node) { - return d3_layout_treemapPad(node, x); - } - var type; - pad2 = (padding = x) == null ? d3_layout_treemapPadNull : (type = typeof x) === "function" ? padFunction : type === "number" ? (x = [x, x, x, x], padConstant) : padConstant; - return treemap2; - }; - treemap2.round = function(x) { - if (!arguments.length) return round2 != Number; - round2 = x ? Math.round : Number; - return treemap2; - }; - treemap2.sticky = function(x) { - if (!arguments.length) return sticky; - sticky = x; - stickies = null; - return treemap2; - }; - treemap2.ratio = function(x) { - if (!arguments.length) return ratio; - ratio = x; - return treemap2; - }; - treemap2.mode = function(x) { - if (!arguments.length) return mode; - mode = x + ""; - return treemap2; - }; - return d3_layout_hierarchyRebind(treemap2, hierarchy2); - }; - function d3_layout_treemapPadNull(node) { - return { - x: node.x, - y: node.y, - dx: node.dx, - dy: node.dy - }; - } - function d3_layout_treemapPad(node, padding) { - var x = node.x + padding[3], y = node.y + padding[0], dx = node.dx - padding[1] - padding[3], dy = node.dy - padding[0] - padding[2]; - if (dx < 0) { - x += dx / 2; - dx = 0; - } - if (dy < 0) { - y += dy / 2; - dy = 0; - } - return { - x, - y, - dx, - dy - }; - } - d32.random = { - normal: function(mu, sigma) { - var n = arguments.length; - if (n < 2) sigma = 1; - if (n < 1) mu = 0; - return function() { - var x, y, r; - do { - x = Math.random() * 2 - 1; - y = Math.random() * 2 - 1; - r = x * x + y * y; - } while (!r || r > 1); - return mu + sigma * x * Math.sqrt(-2 * Math.log(r) / r); - }; - }, - logNormal: function() { - var random = d32.random.normal.apply(d32, arguments); - return function() { - return Math.exp(random()); - }; - }, - bates: function(m) { - var random = d32.random.irwinHall(m); - return function() { - return random() / m; - }; - }, - irwinHall: function(m) { - return function() { - for (var s = 0, j = 0; j < m; j++) s += Math.random(); - return s; - }; - } - }; - d32.scale = {}; - function d3_scaleExtent(domain2) { - var start = domain2[0], stop = domain2[domain2.length - 1]; - return start < stop ? [start, stop] : [stop, start]; - } - function d3_scaleRange(scale2) { - return scale2.rangeExtent ? scale2.rangeExtent() : d3_scaleExtent(scale2.range()); - } - function d3_scale_bilinear(domain2, range, uninterpolate, interpolate2) { - var u = uninterpolate(domain2[0], domain2[1]), i = interpolate2(range[0], range[1]); - return function(x) { - return i(u(x)); - }; - } - function d3_scale_nice(domain2, nice) { - var i0 = 0, i1 = domain2.length - 1, x0 = domain2[i0], x1 = domain2[i1], dx; - if (x1 < x0) { - dx = i0, i0 = i1, i1 = dx; - dx = x0, x0 = x1, x1 = dx; - } - domain2[i0] = nice.floor(x0); - domain2[i1] = nice.ceil(x1); - return domain2; - } - function d3_scale_niceStep(step) { - return step ? { - floor: function(x) { - return Math.floor(x / step) * step; - }, - ceil: function(x) { - return Math.ceil(x / step) * step; - } - } : d3_scale_niceIdentity; - } - var d3_scale_niceIdentity = { - floor: d3_identity, - ceil: d3_identity - }; - function d3_scale_polylinear(domain2, range, uninterpolate, interpolate2) { - var u = [], i = [], j = 0, k = Math.min(domain2.length, range.length) - 1; - if (domain2[k] < domain2[0]) { - domain2 = domain2.slice().reverse(); - range = range.slice().reverse(); - } - while (++j <= k) { - u.push(uninterpolate(domain2[j - 1], domain2[j])); - i.push(interpolate2(range[j - 1], range[j])); - } - return function(x) { - var j2 = d32.bisect(domain2, x, 1, k) - 1; - return i[j2](u[j2](x)); - }; - } - d32.scale.linear = function() { - return d3_scale_linear([0, 1], [0, 1], d3_interpolate, false); - }; - function d3_scale_linear(domain2, range, interpolate2, clamp2) { - var output, input; - function rescale() { - var linear2 = Math.min(domain2.length, range.length) > 2 ? d3_scale_polylinear : d3_scale_bilinear, uninterpolate = clamp2 ? d3_uninterpolateClamp : d3_uninterpolateNumber; - output = linear2(domain2, range, uninterpolate, interpolate2); - input = linear2(range, domain2, uninterpolate, d3_interpolate); - return scale2; - } - function scale2(x) { - return output(x); - } - scale2.invert = function(y) { - return input(y); - }; - scale2.domain = function(x) { - if (!arguments.length) return domain2; - domain2 = x.map(Number); - return rescale(); - }; - scale2.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale2.rangeRound = function(x) { - return scale2.range(x).interpolate(d3_interpolateRound); - }; - scale2.clamp = function(x) { - if (!arguments.length) return clamp2; - clamp2 = x; - return rescale(); - }; - scale2.interpolate = function(x) { - if (!arguments.length) return interpolate2; - interpolate2 = x; - return rescale(); - }; - scale2.ticks = function(m) { - return d3_scale_linearTicks(domain2, m); - }; - scale2.tickFormat = function(m, format2) { - return d3_scale_linearTickFormat(domain2, m, format2); - }; - scale2.nice = function(m) { - d3_scale_linearNice(domain2, m); - return rescale(); - }; - scale2.copy = function() { - return d3_scale_linear(domain2, range, interpolate2, clamp2); - }; - return rescale(); - } - function d3_scale_linearRebind(scale2, linear2) { - return d32.rebind(scale2, linear2, "range", "rangeRound", "interpolate", "clamp"); - } - function d3_scale_linearNice(domain2, m) { - d3_scale_nice(domain2, d3_scale_niceStep(d3_scale_linearTickRange(domain2, m)[2])); - d3_scale_nice(domain2, d3_scale_niceStep(d3_scale_linearTickRange(domain2, m)[2])); - return domain2; - } - function d3_scale_linearTickRange(domain2, m) { - if (m == null) m = 10; - var extent2 = d3_scaleExtent(domain2), span = extent2[1] - extent2[0], step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)), err = m / span * step; - if (err <= 0.15) step *= 10; - else if (err <= 0.35) step *= 5; - else if (err <= 0.75) step *= 2; - extent2[0] = Math.ceil(extent2[0] / step) * step; - extent2[1] = Math.floor(extent2[1] / step) * step + step * 0.5; - extent2[2] = step; - return extent2; - } - function d3_scale_linearTicks(domain2, m) { - return d32.range.apply(d32, d3_scale_linearTickRange(domain2, m)); - } - d32.scale.log = function() { - return d3_scale_log(d32.scale.linear().domain([0, 1]), 10, true, [1, 10]); - }; - function d3_scale_log(linear2, base, positive, domain2) { - function log3(x) { - return (positive ? Math.log(x < 0 ? 0 : x) : -Math.log(x > 0 ? 0 : -x)) / Math.log(base); - } - function pow(x) { - return positive ? Math.pow(base, x) : -Math.pow(base, -x); - } - function scale2(x) { - return linear2(log3(x)); - } - scale2.invert = function(x) { - return pow(linear2.invert(x)); - }; - scale2.domain = function(x) { - if (!arguments.length) return domain2; - positive = x[0] >= 0; - linear2.domain((domain2 = x.map(Number)).map(log3)); - return scale2; - }; - scale2.base = function(_2) { - if (!arguments.length) return base; - base = +_2; - linear2.domain(domain2.map(log3)); - return scale2; - }; - scale2.nice = function() { - var niced = d3_scale_nice(domain2.map(log3), positive ? Math : d3_scale_logNiceNegative); - linear2.domain(niced); - domain2 = niced.map(pow); - return scale2; - }; - scale2.ticks = function() { - var extent2 = d3_scaleExtent(domain2), ticks2 = [], u = extent2[0], v = extent2[1], i = Math.floor(log3(u)), j = Math.ceil(log3(v)), n = base % 1 ? 2 : base; - if (isFinite(j - i)) { - if (positive) { - for (; i < j; i++) for (var k = 1; k < n; k++) ticks2.push(pow(i) * k); - ticks2.push(pow(i)); - } else { - ticks2.push(pow(i)); - for (; i++ < j; ) for (var k = n - 1; k > 0; k--) ticks2.push(pow(i) * k); - } - for (i = 0; ticks2[i] < u; i++) { - } - for (j = ticks2.length; ticks2[j - 1] > v; j--) { - } - ticks2 = ticks2.slice(i, j); - } - return ticks2; - }; - scale2.copy = function() { - return d3_scale_log(linear2.copy(), base, positive, domain2); - }; - return d3_scale_linearRebind(scale2, linear2); - } - var d3_scale_logNiceNegative = { - floor: function(x) { - return -Math.ceil(-x); - }, - ceil: function(x) { - return -Math.floor(-x); - } - }; - d32.scale.pow = function() { - return d3_scale_pow(d32.scale.linear(), 1, [0, 1]); - }; - function d3_scale_pow(linear2, exponent2, domain2) { - var powp = d3_scale_powPow(exponent2), powb = d3_scale_powPow(1 / exponent2); - function scale2(x) { - return linear2(powp(x)); - } - scale2.invert = function(x) { - return powb(linear2.invert(x)); - }; - scale2.domain = function(x) { - if (!arguments.length) return domain2; - linear2.domain((domain2 = x.map(Number)).map(powp)); - return scale2; - }; - scale2.ticks = function(m) { - return d3_scale_linearTicks(domain2, m); - }; - scale2.tickFormat = function(m, format2) { - return d3_scale_linearTickFormat(domain2, m, format2); - }; - scale2.nice = function(m) { - return scale2.domain(d3_scale_linearNice(domain2, m)); - }; - scale2.exponent = function(x) { - if (!arguments.length) return exponent2; - powp = d3_scale_powPow(exponent2 = x); - powb = d3_scale_powPow(1 / exponent2); - linear2.domain(domain2.map(powp)); - return scale2; - }; - scale2.copy = function() { - return d3_scale_pow(linear2.copy(), exponent2, domain2); - }; - return d3_scale_linearRebind(scale2, linear2); - } - function d3_scale_powPow(e) { - return function(x) { - return x < 0 ? -Math.pow(-x, e) : Math.pow(x, e); - }; - } - d32.scale.sqrt = function() { - return d32.scale.pow().exponent(0.5); - }; - d32.scale.ordinal = function() { - return d3_scale_ordinal([], { - t: "range", - a: [[]] - }); - }; - function d3_scale_ordinal(domain2, ranger) { - var index2, range, rangeBand; - function scale2(x) { - return range[((index2.get(x) || (ranger.t === "range" ? index2.set(x, domain2.push(x)) : NaN)) - 1) % range.length]; - } - function steps(start, step) { - return d32.range(domain2.length).map(function(i) { - return start + step * i; - }); - } - scale2.domain = function(x) { - if (!arguments.length) return domain2; - domain2 = []; - index2 = new d3_Map(); - var i = -1, n = x.length, xi; - while (++i < n) if (!index2.has(xi = x[i])) index2.set(xi, domain2.push(xi)); - return scale2[ranger.t].apply(scale2, ranger.a); - }; - scale2.range = function(x) { - if (!arguments.length) return range; - range = x; - rangeBand = 0; - ranger = { - t: "range", - a: arguments - }; - return scale2; - }; - scale2.rangePoints = function(x, padding) { - if (arguments.length < 2) padding = 0; - var start = x[0], stop = x[1], step = domain2.length < 2 ? (start = (start + stop) / 2, 0) : (stop - start) / (domain2.length - 1 + padding); - range = steps(start + step * padding / 2, step); - rangeBand = 0; - ranger = { - t: "rangePoints", - a: arguments - }; - return scale2; - }; - scale2.rangeRoundPoints = function(x, padding) { - if (arguments.length < 2) padding = 0; - var start = x[0], stop = x[1], step = domain2.length < 2 ? (start = stop = Math.round((start + stop) / 2), 0) : (stop - start) / (domain2.length - 1 + padding) | 0; - range = steps(start + Math.round(step * padding / 2 + (stop - start - (domain2.length - 1 + padding) * step) / 2), step); - rangeBand = 0; - ranger = { - t: "rangeRoundPoints", - a: arguments - }; - return scale2; - }; - scale2.rangeBands = function(x, padding, outerPadding) { - if (arguments.length < 2) padding = 0; - if (arguments.length < 3) outerPadding = padding; - var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = (stop - start) / (domain2.length - padding + 2 * outerPadding); - range = steps(start + step * outerPadding, step); - if (reverse) range.reverse(); - rangeBand = step * (1 - padding); - ranger = { - t: "rangeBands", - a: arguments - }; - return scale2; - }; - scale2.rangeRoundBands = function(x, padding, outerPadding) { - if (arguments.length < 2) padding = 0; - if (arguments.length < 3) outerPadding = padding; - var reverse = x[1] < x[0], start = x[reverse - 0], stop = x[1 - reverse], step = Math.floor((stop - start) / (domain2.length - padding + 2 * outerPadding)); - range = steps(start + Math.round((stop - start - (domain2.length - padding) * step) / 2), step); - if (reverse) range.reverse(); - rangeBand = Math.round(step * (1 - padding)); - ranger = { - t: "rangeRoundBands", - a: arguments - }; - return scale2; - }; - scale2.rangeBand = function() { - return rangeBand; - }; - scale2.rangeExtent = function() { - return d3_scaleExtent(ranger.a[0]); - }; - scale2.copy = function() { - return d3_scale_ordinal(domain2, ranger); - }; - return scale2.domain(domain2); - } - d32.scale.category10 = function() { - return d32.scale.ordinal().range(d3_category10); - }; - d32.scale.category20 = function() { - return d32.scale.ordinal().range(d3_category20); - }; - d32.scale.category20b = function() { - return d32.scale.ordinal().range(d3_category20b); - }; - d32.scale.category20c = function() { - return d32.scale.ordinal().range(d3_category20c); - }; - var d3_category10 = [2062260, 16744206, 2924588, 14034728, 9725885, 9197131, 14907330, 8355711, 12369186, 1556175].map(d3_rgbString); - var d3_category20 = [2062260, 11454440, 16744206, 16759672, 2924588, 10018698, 14034728, 16750742, 9725885, 12955861, 9197131, 12885140, 14907330, 16234194, 8355711, 13092807, 12369186, 14408589, 1556175, 10410725].map(d3_rgbString); - var d3_category20b = [3750777, 5395619, 7040719, 10264286, 6519097, 9216594, 11915115, 13556636, 9202993, 12426809, 15186514, 15190932, 8666169, 11356490, 14049643, 15177372, 8077683, 10834324, 13528509, 14589654].map(d3_rgbString); - var d3_category20c = [3244733, 7057110, 10406625, 13032431, 15095053, 16616764, 16625259, 16634018, 3253076, 7652470, 10607003, 13101504, 7695281, 10394312, 12369372, 14342891, 6513507, 9868950, 12434877, 14277081].map(d3_rgbString); - d32.scale.quantile = function() { - return d3_scale_quantile([], []); - }; - function d3_scale_quantile(domain2, range) { - var thresholds; - function rescale() { - var k = 0, q = range.length; - thresholds = []; - while (++k < q) thresholds[k - 1] = d32.quantile(domain2, k / q); - return scale2; - } - function scale2(x) { - if (!isNaN(x = +x)) return range[d32.bisect(thresholds, x)]; - } - scale2.domain = function(x) { - if (!arguments.length) return domain2; - domain2 = x.map(d3_number).filter(d3_numeric).sort(d3_ascending); - return rescale(); - }; - scale2.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale2.quantiles = function() { - return thresholds; - }; - scale2.invertExtent = function(y) { - y = range.indexOf(y); - return y < 0 ? [NaN, NaN] : [y > 0 ? thresholds[y - 1] : domain2[0], y < thresholds.length ? thresholds[y] : domain2[domain2.length - 1]]; - }; - scale2.copy = function() { - return d3_scale_quantile(domain2, range); - }; - return rescale(); - } - d32.scale.quantize = function() { - return d3_scale_quantize(0, 1, [0, 1]); - }; - function d3_scale_quantize(x0, x1, range) { - var kx, i; - function scale2(x) { - return range[Math.max(0, Math.min(i, Math.floor(kx * (x - x0))))]; - } - function rescale() { - kx = range.length / (x1 - x0); - i = range.length - 1; - return scale2; - } - scale2.domain = function(x) { - if (!arguments.length) return [x0, x1]; - x0 = +x[0]; - x1 = +x[x.length - 1]; - return rescale(); - }; - scale2.range = function(x) { - if (!arguments.length) return range; - range = x; - return rescale(); - }; - scale2.invertExtent = function(y) { - y = range.indexOf(y); - y = y < 0 ? NaN : y / kx + x0; - return [y, y + 1 / kx]; - }; - scale2.copy = function() { - return d3_scale_quantize(x0, x1, range); - }; - return rescale(); - } - d32.scale.threshold = function() { - return d3_scale_threshold([0.5], [0, 1]); - }; - function d3_scale_threshold(domain2, range) { - function scale2(x) { - if (x <= x) return range[d32.bisect(domain2, x)]; - } - scale2.domain = function(_2) { - if (!arguments.length) return domain2; - domain2 = _2; - return scale2; - }; - scale2.range = function(_2) { - if (!arguments.length) return range; - range = _2; - return scale2; - }; - scale2.invertExtent = function(y) { - y = range.indexOf(y); - return [domain2[y - 1], domain2[y]]; - }; - scale2.copy = function() { - return d3_scale_threshold(domain2, range); - }; - return scale2; - } - d32.scale.identity = function() { - return d3_scale_identity([0, 1]); - }; - function d3_scale_identity(domain2) { - function identity3(x) { - return +x; - } - identity3.invert = identity3; - identity3.domain = identity3.range = function(x) { - if (!arguments.length) return domain2; - domain2 = x.map(identity3); - return identity3; - }; - identity3.ticks = function(m) { - return d3_scale_linearTicks(domain2, m); - }; - identity3.tickFormat = function(m, format2) { - return d3_scale_linearTickFormat(domain2, m, format2); - }; - identity3.copy = function() { - return d3_scale_identity(domain2); - }; - return identity3; - } - d32.svg = {}; - function d3_zero() { - return 0; - } - d32.svg.arc = function() { - var innerRadius = d3_svg_arcInnerRadius, outerRadius = d3_svg_arcOuterRadius, cornerRadius = d3_zero, padRadius = d3_svg_arcAuto, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle, padAngle = d3_svg_arcPadAngle; - function arc2() { - var r0 = Math.max(0, +innerRadius.apply(this, arguments)), r1 = Math.max(0, +outerRadius.apply(this, arguments)), a0 = startAngle.apply(this, arguments) - halfπ, a1 = endAngle.apply(this, arguments) - halfπ, da = Math.abs(a1 - a0), cw = a0 > a1 ? 0 : 1; - if (r1 < r0) rc = r1, r1 = r0, r0 = rc; - if (da >= τε) return circleSegment(r1, cw) + (r0 ? circleSegment(r0, 1 - cw) : "") + "Z"; - var rc, cr, rp, ap, p0 = 0, p1 = 0, x0, y0, x1, y1, x2, y2, x3, y3, path = []; - if (ap = (+padAngle.apply(this, arguments) || 0) / 2) { - rp = padRadius === d3_svg_arcAuto ? Math.sqrt(r0 * r0 + r1 * r1) : +padRadius.apply(this, arguments); - if (!cw) p1 *= -1; - if (r1) p1 = d3_asin(rp / r1 * Math.sin(ap)); - if (r0) p0 = d3_asin(rp / r0 * Math.sin(ap)); - } - if (r1) { - x0 = r1 * Math.cos(a0 + p1); - y0 = r1 * Math.sin(a0 + p1); - x1 = r1 * Math.cos(a1 - p1); - y1 = r1 * Math.sin(a1 - p1); - var l1 = Math.abs(a1 - a0 - 2 * p1) <= π2 ? 0 : 1; - if (p1 && d3_svg_arcSweep(x0, y0, x1, y1) === cw ^ l1) { - var h1 = (a0 + a1) / 2; - x0 = r1 * Math.cos(h1); - y0 = r1 * Math.sin(h1); - x1 = y1 = null; - } - } else { - x0 = y0 = 0; - } - if (r0) { - x2 = r0 * Math.cos(a1 - p0); - y2 = r0 * Math.sin(a1 - p0); - x3 = r0 * Math.cos(a0 + p0); - y3 = r0 * Math.sin(a0 + p0); - var l0 = Math.abs(a0 - a1 + 2 * p0) <= π2 ? 0 : 1; - if (p0 && d3_svg_arcSweep(x2, y2, x3, y3) === 1 - cw ^ l0) { - var h0 = (a0 + a1) / 2; - x2 = r0 * Math.cos(h0); - y2 = r0 * Math.sin(h0); - x3 = y3 = null; - } - } else { - x2 = y2 = 0; - } - if (da > ε && (rc = Math.min(Math.abs(r1 - r0) / 2, +cornerRadius.apply(this, arguments))) > 1e-3) { - cr = r0 < r1 ^ cw ? 0 : 1; - var rc1 = rc, rc0 = rc; - if (da < π2) { - var oc = x3 == null ? [x2, y2] : x1 == null ? [x0, y0] : d3_geom_polygonIntersect([x0, y0], [x3, y3], [x1, y1], [x2, y2]), ax = x0 - oc[0], ay = y0 - oc[1], bx = x1 - oc[0], by = y1 - oc[1], kc = 1 / Math.sin(Math.acos((ax * bx + ay * by) / (Math.sqrt(ax * ax + ay * ay) * Math.sqrt(bx * bx + by * by))) / 2), lc = Math.sqrt(oc[0] * oc[0] + oc[1] * oc[1]); - rc0 = Math.min(rc, (r0 - lc) / (kc - 1)); - rc1 = Math.min(rc, (r1 - lc) / (kc + 1)); - } - if (x1 != null) { - var t30 = d3_svg_arcCornerTangents(x3 == null ? [x2, y2] : [x3, y3], [x0, y0], r1, rc1, cw), t12 = d3_svg_arcCornerTangents([x1, y1], [x2, y2], r1, rc1, cw); - if (rc === rc1) { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 0,", cr, " ", t30[1], "A", r1, ",", r1, " 0 ", 1 - cw ^ d3_svg_arcSweep(t30[1][0], t30[1][1], t12[1][0], t12[1][1]), ",", cw, " ", t12[1], "A", rc1, ",", rc1, " 0 0,", cr, " ", t12[0]); - } else { - path.push("M", t30[0], "A", rc1, ",", rc1, " 0 1,", cr, " ", t12[0]); - } - } else { - path.push("M", x0, ",", y0); - } - if (x3 != null) { - var t03 = d3_svg_arcCornerTangents([x0, y0], [x3, y3], r0, -rc0, cw), t21 = d3_svg_arcCornerTangents([x2, y2], x1 == null ? [x0, y0] : [x1, y1], r0, -rc0, cw); - if (rc === rc0) { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t21[1], "A", r0, ",", r0, " 0 ", cw ^ d3_svg_arcSweep(t21[1][0], t21[1][1], t03[1][0], t03[1][1]), ",", 1 - cw, " ", t03[1], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } else { - path.push("L", t21[0], "A", rc0, ",", rc0, " 0 0,", cr, " ", t03[0]); - } - } else { - path.push("L", x2, ",", y2); - } - } else { - path.push("M", x0, ",", y0); - if (x1 != null) path.push("A", r1, ",", r1, " 0 ", l1, ",", cw, " ", x1, ",", y1); - path.push("L", x2, ",", y2); - if (x3 != null) path.push("A", r0, ",", r0, " 0 ", l0, ",", 1 - cw, " ", x3, ",", y3); - } - path.push("Z"); - return path.join(""); - } - function circleSegment(r1, cw) { - return "M0," + r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + -r1 + "A" + r1 + "," + r1 + " 0 1," + cw + " 0," + r1; - } - arc2.innerRadius = function(v) { - if (!arguments.length) return innerRadius; - innerRadius = d3_functor(v); - return arc2; - }; - arc2.outerRadius = function(v) { - if (!arguments.length) return outerRadius; - outerRadius = d3_functor(v); - return arc2; - }; - arc2.cornerRadius = function(v) { - if (!arguments.length) return cornerRadius; - cornerRadius = d3_functor(v); - return arc2; - }; - arc2.padRadius = function(v) { - if (!arguments.length) return padRadius; - padRadius = v == d3_svg_arcAuto ? d3_svg_arcAuto : d3_functor(v); - return arc2; - }; - arc2.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return arc2; - }; - arc2.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return arc2; - }; - arc2.padAngle = function(v) { - if (!arguments.length) return padAngle; - padAngle = d3_functor(v); - return arc2; - }; - arc2.centroid = function() { - var r = (+innerRadius.apply(this, arguments) + +outerRadius.apply(this, arguments)) / 2, a = (+startAngle.apply(this, arguments) + +endAngle.apply(this, arguments)) / 2 - halfπ; - return [Math.cos(a) * r, Math.sin(a) * r]; - }; - return arc2; - }; - var d3_svg_arcAuto = "auto"; - function d3_svg_arcInnerRadius(d) { - return d.innerRadius; - } - function d3_svg_arcOuterRadius(d) { - return d.outerRadius; - } - function d3_svg_arcStartAngle(d) { - return d.startAngle; - } - function d3_svg_arcEndAngle(d) { - return d.endAngle; - } - function d3_svg_arcPadAngle(d) { - return d && d.padAngle; - } - function d3_svg_arcSweep(x0, y0, x1, y1) { - return (x0 - x1) * y0 - (y0 - y1) * x0 > 0 ? 0 : 1; - } - function d3_svg_arcCornerTangents(p0, p1, r1, rc, cw) { - var x01 = p0[0] - p1[0], y01 = p0[1] - p1[1], lo = (cw ? rc : -rc) / Math.sqrt(x01 * x01 + y01 * y01), ox = lo * y01, oy = -lo * x01, x1 = p0[0] + ox, y1 = p0[1] + oy, x2 = p1[0] + ox, y2 = p1[1] + oy, x3 = (x1 + x2) / 2, y3 = (y1 + y2) / 2, dx = x2 - x1, dy = y2 - y1, d2 = dx * dx + dy * dy, r = r1 - rc, D2 = x1 * y2 - x2 * y1, d = (dy < 0 ? -1 : 1) * Math.sqrt(Math.max(0, r * r * d2 - D2 * D2)), cx0 = (D2 * dy - dx * d) / d2, cy0 = (-D2 * dx - dy * d) / d2, cx1 = (D2 * dy + dx * d) / d2, cy1 = (-D2 * dx + dy * d) / d2, dx0 = cx0 - x3, dy0 = cy0 - y3, dx1 = cx1 - x3, dy1 = cy1 - y3; - if (dx0 * dx0 + dy0 * dy0 > dx1 * dx1 + dy1 * dy1) cx0 = cx1, cy0 = cy1; - return [[cx0 - ox, cy0 - oy], [cx0 * r1 / r, cy0 * r1 / r]]; - } - function d3_true() { - return true; - } - function d3_svg_line(projection) { - var x = d3_geom_pointX, y = d3_geom_pointY, defined3 = d3_true, interpolate2 = d3_svg_lineLinear, interpolateKey = interpolate2.key, tension = 0.7; - function line2(data) { - var segments = [], points = [], i = -1, n = data.length, d, fx2 = d3_functor(x), fy = d3_functor(y); - function segment2() { - segments.push("M", interpolate2(projection(points), tension)); - } - while (++i < n) { - if (defined3.call(this, d = data[i], i)) { - points.push([+fx2.call(this, d, i), +fy.call(this, d, i)]); - } else if (points.length) { - segment2(); - points = []; - } - } - if (points.length) segment2(); - return segments.length ? segments.join("") : null; - } - line2.x = function(_2) { - if (!arguments.length) return x; - x = _2; - return line2; - }; - line2.y = function(_2) { - if (!arguments.length) return y; - y = _2; - return line2; - }; - line2.defined = function(_2) { - if (!arguments.length) return defined3; - defined3 = _2; - return line2; - }; - line2.interpolate = function(_2) { - if (!arguments.length) return interpolateKey; - if (typeof _2 === "function") interpolateKey = interpolate2 = _2; - else interpolateKey = (interpolate2 = d3_svg_lineInterpolators.get(_2) || d3_svg_lineLinear).key; - return line2; - }; - line2.tension = function(_2) { - if (!arguments.length) return tension; - tension = _2; - return line2; - }; - return line2; - } - d32.svg.line = function() { - return d3_svg_line(d3_identity); - }; - var d3_svg_lineInterpolators = d32.map({ - linear: d3_svg_lineLinear, - "linear-closed": d3_svg_lineLinearClosed, - step: d3_svg_lineStep, - "step-before": d3_svg_lineStepBefore, - "step-after": d3_svg_lineStepAfter, - basis: d3_svg_lineBasis, - "basis-open": d3_svg_lineBasisOpen, - "basis-closed": d3_svg_lineBasisClosed, - bundle: d3_svg_lineBundle, - cardinal: d3_svg_lineCardinal, - "cardinal-open": d3_svg_lineCardinalOpen, - "cardinal-closed": d3_svg_lineCardinalClosed, - monotone: d3_svg_lineMonotone - }); - d3_svg_lineInterpolators.forEach(function(key, value2) { - value2.key = key; - value2.closed = /-closed$/.test(key); - }); - function d3_svg_lineLinear(points) { - return points.length > 1 ? points.join("L") : points + "Z"; - } - function d3_svg_lineLinearClosed(points) { - return points.join("L") + "Z"; - } - function d3_svg_lineStep(points) { - var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; - while (++i < n) path.push("H", (p[0] + (p = points[i])[0]) / 2, "V", p[1]); - if (n > 1) path.push("H", p[0]); - return path.join(""); - } - function d3_svg_lineStepBefore(points) { - var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; - while (++i < n) path.push("V", (p = points[i])[1], "H", p[0]); - return path.join(""); - } - function d3_svg_lineStepAfter(points) { - var i = 0, n = points.length, p = points[0], path = [p[0], ",", p[1]]; - while (++i < n) path.push("H", (p = points[i])[0], "V", p[1]); - return path.join(""); - } - function d3_svg_lineCardinalOpen(points, tension) { - return points.length < 4 ? d3_svg_lineLinear(points) : points[1] + d3_svg_lineHermite(points.slice(1, -1), d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineCardinalClosed(points, tension) { - return points.length < 3 ? d3_svg_lineLinearClosed(points) : points[0] + d3_svg_lineHermite((points.push(points[0]), points), d3_svg_lineCardinalTangents([points[points.length - 2]].concat(points, [points[1]]), tension)); - } - function d3_svg_lineCardinal(points, tension) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineCardinalTangents(points, tension)); - } - function d3_svg_lineHermite(points, tangents) { - if (tangents.length < 1 || points.length != tangents.length && points.length != tangents.length + 2) { - return d3_svg_lineLinear(points); - } - var quad2 = points.length != tangents.length, path = "", p0 = points[0], p = points[1], t02 = tangents[0], t = t02, pi = 1; - if (quad2) { - path += "Q" + (p[0] - t02[0] * 2 / 3) + "," + (p[1] - t02[1] * 2 / 3) + "," + p[0] + "," + p[1]; - p0 = points[1]; - pi = 2; - } - if (tangents.length > 1) { - t = tangents[1]; - p = points[pi]; - pi++; - path += "C" + (p0[0] + t02[0]) + "," + (p0[1] + t02[1]) + "," + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - for (var i = 2; i < tangents.length; i++, pi++) { - p = points[pi]; - t = tangents[i]; - path += "S" + (p[0] - t[0]) + "," + (p[1] - t[1]) + "," + p[0] + "," + p[1]; - } - } - if (quad2) { - var lp = points[pi]; - path += "Q" + (p[0] + t[0] * 2 / 3) + "," + (p[1] + t[1] * 2 / 3) + "," + lp[0] + "," + lp[1]; - } - return path; - } - function d3_svg_lineCardinalTangents(points, tension) { - var tangents = [], a = (1 - tension) / 2, p0, p1 = points[0], p2 = points[1], i = 1, n = points.length; - while (++i < n) { - p0 = p1; - p1 = p2; - p2 = points[i]; - tangents.push([a * (p2[0] - p0[0]), a * (p2[1] - p0[1])]); - } - return tangents; - } - function d3_svg_lineBasis(points) { - if (points.length < 3) return d3_svg_lineLinear(points); - var i = 1, n = points.length, pi = points[0], x0 = pi[0], y0 = pi[1], px2 = [x0, x0, x0, (pi = points[1])[0]], py = [y0, y0, y0, pi[1]], path = [x0, ",", y0, "L", d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)]; - points.push(points[n - 1]); - while (++i <= n) { - pi = points[i]; - px2.shift(); - px2.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px2, py); - } - points.pop(); - path.push("L", pi); - return path.join(""); - } - function d3_svg_lineBasisOpen(points) { - if (points.length < 4) return d3_svg_lineLinear(points); - var path = [], i = -1, n = points.length, pi, px2 = [0], py = [0]; - while (++i < 3) { - pi = points[i]; - px2.push(pi[0]); - py.push(pi[1]); - } - path.push(d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2) + "," + d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)); - --i; - while (++i < n) { - pi = points[i]; - px2.shift(); - px2.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px2, py); - } - return path.join(""); - } - function d3_svg_lineBasisClosed(points) { - var path, i = -1, n = points.length, m = n + 4, pi, px2 = [], py = []; - while (++i < 4) { - pi = points[i % n]; - px2.push(pi[0]); - py.push(pi[1]); - } - path = [d3_svg_lineDot4(d3_svg_lineBasisBezier3, px2), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, py)]; - --i; - while (++i < m) { - pi = points[i % n]; - px2.shift(); - px2.push(pi[0]); - py.shift(); - py.push(pi[1]); - d3_svg_lineBasisBezier(path, px2, py); - } - return path.join(""); - } - function d3_svg_lineBundle(points, tension) { - var n = points.length - 1; - if (n) { - var x0 = points[0][0], y0 = points[0][1], dx = points[n][0] - x0, dy = points[n][1] - y0, i = -1, p, t; - while (++i <= n) { - p = points[i]; - t = i / n; - p[0] = tension * p[0] + (1 - tension) * (x0 + t * dx); - p[1] = tension * p[1] + (1 - tension) * (y0 + t * dy); - } - } - return d3_svg_lineBasis(points); - } - function d3_svg_lineDot4(a, b) { - return a[0] * b[0] + a[1] * b[1] + a[2] * b[2] + a[3] * b[3]; - } - var d3_svg_lineBasisBezier1 = [0, 2 / 3, 1 / 3, 0], d3_svg_lineBasisBezier2 = [0, 1 / 3, 2 / 3, 0], d3_svg_lineBasisBezier3 = [0, 1 / 6, 2 / 3, 1 / 6]; - function d3_svg_lineBasisBezier(path, x, y) { - path.push("C", d3_svg_lineDot4(d3_svg_lineBasisBezier1, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier1, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier2, y), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, x), ",", d3_svg_lineDot4(d3_svg_lineBasisBezier3, y)); - } - function d3_svg_lineSlope(p0, p1) { - return (p1[1] - p0[1]) / (p1[0] - p0[0]); - } - function d3_svg_lineFiniteDifferences(points) { - var i = 0, j = points.length - 1, m = [], p0 = points[0], p1 = points[1], d = m[0] = d3_svg_lineSlope(p0, p1); - while (++i < j) { - m[i] = (d + (d = d3_svg_lineSlope(p0 = p1, p1 = points[i + 1]))) / 2; - } - m[i] = d; - return m; - } - function d3_svg_lineMonotoneTangents(points) { - var tangents = [], d, a, b, s, m = d3_svg_lineFiniteDifferences(points), i = -1, j = points.length - 1; - while (++i < j) { - d = d3_svg_lineSlope(points[i], points[i + 1]); - if (abs2(d) < ε) { - m[i] = m[i + 1] = 0; - } else { - a = m[i] / d; - b = m[i + 1] / d; - s = a * a + b * b; - if (s > 9) { - s = d * 3 / Math.sqrt(s); - m[i] = s * a; - m[i + 1] = s * b; - } - } - } - i = -1; - while (++i <= j) { - s = (points[Math.min(j, i + 1)][0] - points[Math.max(0, i - 1)][0]) / (6 * (1 + m[i] * m[i])); - tangents.push([s || 0, m[i] * s || 0]); - } - return tangents; - } - function d3_svg_lineMonotone(points) { - return points.length < 3 ? d3_svg_lineLinear(points) : points[0] + d3_svg_lineHermite(points, d3_svg_lineMonotoneTangents(points)); - } - d32.svg.line.radial = function() { - var line2 = d3_svg_line(d3_svg_lineRadial); - line2.radius = line2.x, delete line2.x; - line2.angle = line2.y, delete line2.y; - return line2; - }; - function d3_svg_lineRadial(points) { - var point, i = -1, n = points.length, r, a; - while (++i < n) { - point = points[i]; - r = point[0]; - a = point[1] - halfπ; - point[0] = r * Math.cos(a); - point[1] = r * Math.sin(a); - } - return points; - } - function d3_svg_area(projection) { - var x0 = d3_geom_pointX, x1 = d3_geom_pointX, y0 = 0, y1 = d3_geom_pointY, defined3 = d3_true, interpolate2 = d3_svg_lineLinear, interpolateKey = interpolate2.key, interpolateReverse = interpolate2, L = "L", tension = 0.7; - function area2(data) { - var segments = [], points0 = [], points1 = [], i = -1, n = data.length, d, fx0 = d3_functor(x0), fy0 = d3_functor(y0), fx1 = x0 === x1 ? function() { - return x; - } : d3_functor(x1), fy1 = y0 === y1 ? function() { - return y; - } : d3_functor(y1), x, y; - function segment2() { - segments.push("M", interpolate2(projection(points1), tension), L, interpolateReverse(projection(points0.reverse()), tension), "Z"); - } - while (++i < n) { - if (defined3.call(this, d = data[i], i)) { - points0.push([x = +fx0.call(this, d, i), y = +fy0.call(this, d, i)]); - points1.push([+fx1.call(this, d, i), +fy1.call(this, d, i)]); - } else if (points0.length) { - segment2(); - points0 = []; - points1 = []; - } - } - if (points0.length) segment2(); - return segments.length ? segments.join("") : null; - } - area2.x = function(_2) { - if (!arguments.length) return x1; - x0 = x1 = _2; - return area2; - }; - area2.x0 = function(_2) { - if (!arguments.length) return x0; - x0 = _2; - return area2; - }; - area2.x1 = function(_2) { - if (!arguments.length) return x1; - x1 = _2; - return area2; - }; - area2.y = function(_2) { - if (!arguments.length) return y1; - y0 = y1 = _2; - return area2; - }; - area2.y0 = function(_2) { - if (!arguments.length) return y0; - y0 = _2; - return area2; - }; - area2.y1 = function(_2) { - if (!arguments.length) return y1; - y1 = _2; - return area2; - }; - area2.defined = function(_2) { - if (!arguments.length) return defined3; - defined3 = _2; - return area2; - }; - area2.interpolate = function(_2) { - if (!arguments.length) return interpolateKey; - if (typeof _2 === "function") interpolateKey = interpolate2 = _2; - else interpolateKey = (interpolate2 = d3_svg_lineInterpolators.get(_2) || d3_svg_lineLinear).key; - interpolateReverse = interpolate2.reverse || interpolate2; - L = interpolate2.closed ? "M" : "L"; - return area2; - }; - area2.tension = function(_2) { - if (!arguments.length) return tension; - tension = _2; - return area2; - }; - return area2; - } - d3_svg_lineStepBefore.reverse = d3_svg_lineStepAfter; - d3_svg_lineStepAfter.reverse = d3_svg_lineStepBefore; - d32.svg.area = function() { - return d3_svg_area(d3_identity); - }; - d32.svg.area.radial = function() { - var area2 = d3_svg_area(d3_svg_lineRadial); - area2.radius = area2.x, delete area2.x; - area2.innerRadius = area2.x0, delete area2.x0; - area2.outerRadius = area2.x1, delete area2.x1; - area2.angle = area2.y, delete area2.y; - area2.startAngle = area2.y0, delete area2.y0; - area2.endAngle = area2.y1, delete area2.y1; - return area2; - }; - function d3_source(d) { - return d.source; - } - function d3_target(d) { - return d.target; - } - d32.svg.chord = function() { - var source = d3_source, target = d3_target, radius = d3_svg_chordRadius, startAngle = d3_svg_arcStartAngle, endAngle = d3_svg_arcEndAngle; - function chord(d, i) { - var s = subgroup(this, source, d, i), t = subgroup(this, target, d, i); - return "M" + s.p0 + arc2(s.r, s.p1, s.a1 - s.a0) + (equals2(s, t) ? curve(s.r, s.p1, s.r, s.p0) : curve(s.r, s.p1, t.r, t.p0) + arc2(t.r, t.p1, t.a1 - t.a0) + curve(t.r, t.p1, s.r, s.p0)) + "Z"; - } - function subgroup(self2, f, d, i) { - var subgroup2 = f.call(self2, d, i), r = radius.call(self2, subgroup2, i), a0 = startAngle.call(self2, subgroup2, i) - halfπ, a1 = endAngle.call(self2, subgroup2, i) - halfπ; - return { - r, - a0, - a1, - p0: [r * Math.cos(a0), r * Math.sin(a0)], - p1: [r * Math.cos(a1), r * Math.sin(a1)] - }; - } - function equals2(a, b) { - return a.a0 == b.a0 && a.a1 == b.a1; - } - function arc2(r, p, a) { - return "A" + r + "," + r + " 0 " + +(a > π2) + ",1 " + p; - } - function curve(r0, p0, r1, p1) { - return "Q 0,0 " + p1; - } - chord.radius = function(v) { - if (!arguments.length) return radius; - radius = d3_functor(v); - return chord; - }; - chord.source = function(v) { - if (!arguments.length) return source; - source = d3_functor(v); - return chord; - }; - chord.target = function(v) { - if (!arguments.length) return target; - target = d3_functor(v); - return chord; - }; - chord.startAngle = function(v) { - if (!arguments.length) return startAngle; - startAngle = d3_functor(v); - return chord; - }; - chord.endAngle = function(v) { - if (!arguments.length) return endAngle; - endAngle = d3_functor(v); - return chord; - }; - return chord; - }; - function d3_svg_chordRadius(d) { - return d.radius; - } - d32.svg.diagonal = function() { - var source = d3_source, target = d3_target, projection = d3_svg_diagonalProjection; - function diagonal(d, i) { - var p0 = source.call(this, d, i), p3 = target.call(this, d, i), m = (p0.y + p3.y) / 2, p = [p0, { - x: p0.x, - y: m - }, { - x: p3.x, - y: m - }, p3]; - p = p.map(projection); - return "M" + p[0] + "C" + p[1] + " " + p[2] + " " + p[3]; - } - diagonal.source = function(x) { - if (!arguments.length) return source; - source = d3_functor(x); - return diagonal; - }; - diagonal.target = function(x) { - if (!arguments.length) return target; - target = d3_functor(x); - return diagonal; - }; - diagonal.projection = function(x) { - if (!arguments.length) return projection; - projection = x; - return diagonal; - }; - return diagonal; - }; - function d3_svg_diagonalProjection(d) { - return [d.x, d.y]; - } - d32.svg.diagonal.radial = function() { - var diagonal = d32.svg.diagonal(), projection = d3_svg_diagonalProjection, projection_ = diagonal.projection; - diagonal.projection = function(x) { - return arguments.length ? projection_(d3_svg_diagonalRadialProjection(projection = x)) : projection; - }; - return diagonal; - }; - function d3_svg_diagonalRadialProjection(projection) { - return function() { - var d = projection.apply(this, arguments), r = d[0], a = d[1] - halfπ; - return [r * Math.cos(a), r * Math.sin(a)]; - }; - } - d32.svg.symbol = function() { - var type = d3_svg_symbolType, size = d3_svg_symbolSize; - function symbol(d, i) { - return (d3_svg_symbols.get(type.call(this, d, i)) || d3_svg_symbolCircle)(size.call(this, d, i)); - } - symbol.type = function(x) { - if (!arguments.length) return type; - type = d3_functor(x); - return symbol; - }; - symbol.size = function(x) { - if (!arguments.length) return size; - size = d3_functor(x); - return symbol; - }; - return symbol; - }; - function d3_svg_symbolSize() { - return 64; - } - function d3_svg_symbolType() { - return "circle"; - } - function d3_svg_symbolCircle(size) { - var r = Math.sqrt(size / π2); - return "M0," + r + "A" + r + "," + r + " 0 1,1 0," + -r + "A" + r + "," + r + " 0 1,1 0," + r + "Z"; - } - var d3_svg_symbols = d32.map({ - circle: d3_svg_symbolCircle, - cross: function(size) { - var r = Math.sqrt(size / 5) / 2; - return "M" + -3 * r + "," + -r + "H" + -r + "V" + -3 * r + "H" + r + "V" + -r + "H" + 3 * r + "V" + r + "H" + r + "V" + 3 * r + "H" + -r + "V" + r + "H" + -3 * r + "Z"; - }, - diamond: function(size) { - var ry = Math.sqrt(size / (2 * d3_svg_symbolTan30)), rx = ry * d3_svg_symbolTan30; - return "M0," + -ry + "L" + rx + ",0 0," + ry + " " + -rx + ",0Z"; - }, - square: function(size) { - var r = Math.sqrt(size) / 2; - return "M" + -r + "," + -r + "L" + r + "," + -r + " " + r + "," + r + " " + -r + "," + r + "Z"; - }, - "triangle-down": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + ry + "L" + rx + "," + -ry + " " + -rx + "," + -ry + "Z"; - }, - "triangle-up": function(size) { - var rx = Math.sqrt(size / d3_svg_symbolSqrt3), ry = rx * d3_svg_symbolSqrt3 / 2; - return "M0," + -ry + "L" + rx + "," + ry + " " + -rx + "," + ry + "Z"; - } - }); - d32.svg.symbolTypes = d3_svg_symbols.keys(); - var d3_svg_symbolSqrt3 = Math.sqrt(3), d3_svg_symbolTan30 = Math.tan(30 * d3_radians); - d3_selectionPrototype.transition = function(name2) { - var id = d3_transitionInheritId || ++d3_transitionId, ns = d3_transitionNamespace(name2), subgroups = [], subgroup, node, transition2 = d3_transitionInherit || { - time: Date.now(), - ease: d3_ease_cubicInOut, - delay: 0, - duration: 250 - }; - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) d3_transitionNode(node, i, ns, id, transition2); - subgroup.push(node); - } - } - return d3_transition(subgroups, ns, id); - }; - d3_selectionPrototype.interrupt = function(name2) { - return this.each(name2 == null ? d3_selection_interrupt : d3_selection_interruptNS(d3_transitionNamespace(name2))); - }; - var d3_selection_interrupt = d3_selection_interruptNS(d3_transitionNamespace()); - function d3_selection_interruptNS(ns) { - return function() { - var lock, activeId, active; - if ((lock = this[ns]) && (active = lock[activeId = lock.active])) { - active.timer.c = null; - active.timer.t = NaN; - if (--lock.count) delete lock[activeId]; - else delete this[ns]; - lock.active += 0.5; - active.event && active.event.interrupt.call(this, this.__data__, active.index); - } - }; - } - function d3_transition(groups, ns, id) { - d3_subclass(groups, d3_transitionPrototype); - groups.namespace = ns; - groups.id = id; - return groups; - } - var d3_transitionPrototype = [], d3_transitionId = 0, d3_transitionInheritId, d3_transitionInherit; - d3_transitionPrototype.call = d3_selectionPrototype.call; - d3_transitionPrototype.empty = d3_selectionPrototype.empty; - d3_transitionPrototype.node = d3_selectionPrototype.node; - d3_transitionPrototype.size = d3_selectionPrototype.size; - d32.transition = function(selection, name2) { - return selection && selection.transition ? d3_transitionInheritId ? selection.transition(name2) : selection : d32.selection().transition(selection); - }; - d32.transition.prototype = d3_transitionPrototype; - d3_transitionPrototype.select = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnode, node; - selector = d3_selection_selector(selector); - for (var j = -1, m = this.length; ++j < m; ) { - subgroups.push(subgroup = []); - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if ((node = group[i]) && (subnode = selector.call(node, node.__data__, i, j))) { - if ("__data__" in node) subnode.__data__ = node.__data__; - d3_transitionNode(subnode, i, ns, id, node[ns][id]); - subgroup.push(subnode); - } else { - subgroup.push(null); - } - } - } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.selectAll = function(selector) { - var id = this.id, ns = this.namespace, subgroups = [], subgroup, subnodes, node, subnode, transition2; - selector = d3_selection_selectorAll(selector); - for (var j = -1, m = this.length; ++j < m; ) { - for (var group = this[j], i = -1, n = group.length; ++i < n; ) { - if (node = group[i]) { - transition2 = node[ns][id]; - subnodes = selector.call(node, node.__data__, i, j); - subgroups.push(subgroup = []); - for (var k = -1, o = subnodes.length; ++k < o; ) { - if (subnode = subnodes[k]) d3_transitionNode(subnode, k, ns, id, transition2); - subgroup.push(subnode); - } - } - } - } - return d3_transition(subgroups, ns, id); - }; - d3_transitionPrototype.filter = function(filter2) { - var subgroups = [], subgroup, group, node; - if (typeof filter2 !== "function") filter2 = d3_selection_filter(filter2); - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if ((node = group[i]) && filter2.call(node, node.__data__, i, j)) { - subgroup.push(node); - } - } - } - return d3_transition(subgroups, this.namespace, this.id); - }; - d3_transitionPrototype.tween = function(name2, tween) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) return this.node()[ns][id].tween.get(name2); - return d3_selection_each(this, tween == null ? function(node) { - node[ns][id].tween.remove(name2); - } : function(node) { - node[ns][id].tween.set(name2, tween); - }); - }; - function d3_transition_tween(groups, name2, value2, tween) { - var id = groups.id, ns = groups.namespace; - return d3_selection_each(groups, typeof value2 === "function" ? function(node, i, j) { - node[ns][id].tween.set(name2, tween(value2.call(node, node.__data__, i, j))); - } : (value2 = tween(value2), function(node) { - node[ns][id].tween.set(name2, value2); - })); - } - d3_transitionPrototype.attr = function(nameNS, value2) { - if (arguments.length < 2) { - for (value2 in nameNS) this.attr(value2, nameNS[value2]); - return this; - } - var interpolate2 = nameNS == "transform" ? d3_interpolateTransform : d3_interpolate, name2 = d32.ns.qualify(nameNS); - function attrNull() { - this.removeAttribute(name2); - } - function attrNullNS() { - this.removeAttributeNS(name2.space, name2.local); - } - function attrTween(b) { - return b == null ? attrNull : (b += "", function() { - var a = this.getAttribute(name2), i; - return a !== b && (i = interpolate2(a, b), function(t) { - this.setAttribute(name2, i(t)); - }); - }); - } - function attrTweenNS(b) { - return b == null ? attrNullNS : (b += "", function() { - var a = this.getAttributeNS(name2.space, name2.local), i; - return a !== b && (i = interpolate2(a, b), function(t) { - this.setAttributeNS(name2.space, name2.local, i(t)); - }); - }); - } - return d3_transition_tween(this, "attr." + nameNS, value2, name2.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.attrTween = function(nameNS, tween) { - var name2 = d32.ns.qualify(nameNS); - function attrTween(d, i) { - var f = tween.call(this, d, i, this.getAttribute(name2)); - return f && function(t) { - this.setAttribute(name2, f(t)); - }; - } - function attrTweenNS(d, i) { - var f = tween.call(this, d, i, this.getAttributeNS(name2.space, name2.local)); - return f && function(t) { - this.setAttributeNS(name2.space, name2.local, f(t)); - }; - } - return this.tween("attr." + nameNS, name2.local ? attrTweenNS : attrTween); - }; - d3_transitionPrototype.style = function(name2, value2, priority) { - var n = arguments.length; - if (n < 3) { - if (typeof name2 !== "string") { - if (n < 2) value2 = ""; - for (priority in name2) this.style(priority, name2[priority], value2); - return this; - } - priority = ""; - } - function styleNull() { - this.style.removeProperty(name2); - } - function styleString(b) { - return b == null ? styleNull : (b += "", function() { - var a = d3_window(this).getComputedStyle(this, null).getPropertyValue(name2), i; - return a !== b && (i = d3_interpolate(a, b), function(t) { - this.style.setProperty(name2, i(t), priority); - }); - }); - } - return d3_transition_tween(this, "style." + name2, value2, styleString); - }; - d3_transitionPrototype.styleTween = function(name2, tween, priority) { - if (arguments.length < 3) priority = ""; - function styleTween(d, i) { - var f = tween.call(this, d, i, d3_window(this).getComputedStyle(this, null).getPropertyValue(name2)); - return f && function(t) { - this.style.setProperty(name2, f(t), priority); - }; - } - return this.tween("style." + name2, styleTween); - }; - d3_transitionPrototype.text = function(value2) { - return d3_transition_tween(this, "text", value2, d3_transition_text); - }; - function d3_transition_text(b) { - if (b == null) b = ""; - return function() { - this.textContent = b; - }; - } - d3_transitionPrototype.remove = function() { - var ns = this.namespace; - return this.each("end.transition", function() { - var p; - if (this[ns].count < 2 && (p = this.parentNode)) p.removeChild(this); - }); - }; - d3_transitionPrototype.ease = function(value2) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].ease; - if (typeof value2 !== "function") value2 = d32.ease.apply(d32, arguments); - return d3_selection_each(this, function(node) { - node[ns][id].ease = value2; - }); - }; - d3_transitionPrototype.delay = function(value2) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].delay; - return d3_selection_each(this, typeof value2 === "function" ? function(node, i, j) { - node[ns][id].delay = +value2.call(node, node.__data__, i, j); - } : (value2 = +value2, function(node) { - node[ns][id].delay = value2; - })); - }; - d3_transitionPrototype.duration = function(value2) { - var id = this.id, ns = this.namespace; - if (arguments.length < 1) return this.node()[ns][id].duration; - return d3_selection_each(this, typeof value2 === "function" ? function(node, i, j) { - node[ns][id].duration = Math.max(1, value2.call(node, node.__data__, i, j)); - } : (value2 = Math.max(1, value2), function(node) { - node[ns][id].duration = value2; - })); - }; - d3_transitionPrototype.each = function(type, listener) { - var id = this.id, ns = this.namespace; - if (arguments.length < 2) { - var inherit = d3_transitionInherit, inheritId = d3_transitionInheritId; - try { - d3_transitionInheritId = id; - d3_selection_each(this, function(node, i, j) { - d3_transitionInherit = node[ns][id]; - type.call(node, node.__data__, i, j); - }); - } finally { - d3_transitionInherit = inherit; - d3_transitionInheritId = inheritId; - } - } else { - d3_selection_each(this, function(node) { - var transition2 = node[ns][id]; - (transition2.event || (transition2.event = d32.dispatch("start", "end", "interrupt"))).on(type, listener); - }); - } - return this; - }; - d3_transitionPrototype.transition = function() { - var id0 = this.id, id1 = ++d3_transitionId, ns = this.namespace, subgroups = [], subgroup, group, node, transition2; - for (var j = 0, m = this.length; j < m; j++) { - subgroups.push(subgroup = []); - for (var group = this[j], i = 0, n = group.length; i < n; i++) { - if (node = group[i]) { - transition2 = node[ns][id0]; - d3_transitionNode(node, i, ns, id1, { - time: transition2.time, - ease: transition2.ease, - delay: transition2.delay + transition2.duration, - duration: transition2.duration - }); - } - subgroup.push(node); - } - } - return d3_transition(subgroups, ns, id1); - }; - function d3_transitionNamespace(name2) { - return name2 == null ? "__transition__" : "__transition_" + name2 + "__"; - } - function d3_transitionNode(node, i, ns, id, inherit) { - var lock = node[ns] || (node[ns] = { - active: 0, - count: 0 - }), transition2 = lock[id], time, timer, duration, ease, tweens; - function schedule(elapsed) { - var delay = transition2.delay; - timer.t = delay + time; - if (delay <= elapsed) return start(elapsed - delay); - timer.c = start; - } - function start(elapsed) { - var activeId = lock.active, active = lock[activeId]; - if (active) { - active.timer.c = null; - active.timer.t = NaN; - --lock.count; - delete lock[activeId]; - active.event && active.event.interrupt.call(node, node.__data__, active.index); - } - for (var cancelId in lock) { - if (+cancelId < id) { - var cancel = lock[cancelId]; - cancel.timer.c = null; - cancel.timer.t = NaN; - --lock.count; - delete lock[cancelId]; - } - } - timer.c = tick; - d3_timer(function() { - if (timer.c && tick(elapsed || 1)) { - timer.c = null; - timer.t = NaN; - } - return 1; - }, 0, time); - lock.active = id; - transition2.event && transition2.event.start.call(node, node.__data__, i); - tweens = []; - transition2.tween.forEach(function(key, value2) { - if (value2 = value2.call(node, node.__data__, i)) { - tweens.push(value2); - } - }); - ease = transition2.ease; - duration = transition2.duration; - } - function tick(elapsed) { - var t = elapsed / duration, e = ease(t), n = tweens.length; - while (n > 0) { - tweens[--n].call(node, e); - } - if (t >= 1) { - transition2.event && transition2.event.end.call(node, node.__data__, i); - if (--lock.count) delete lock[id]; - else delete node[ns]; - return 1; - } - } - if (!transition2) { - time = inherit.time; - timer = d3_timer(schedule, 0, time); - transition2 = lock[id] = { - tween: new d3_Map(), - time, - timer, - delay: inherit.delay, - duration: inherit.duration, - ease: inherit.ease, - index: i - }; - inherit = null; - ++lock.count; - } - } - d32.svg.axis = function() { - var scale2 = d32.scale.linear(), orient = d3_svg_axisDefaultOrient, innerTickSize = 6, outerTickSize = 6, tickPadding = 3, tickArguments_ = [10], tickValues = null, tickFormat_; - function axis(g) { - g.each(function() { - var g2 = d32.select(this); - var scale0 = this.__chart__ || scale2, scale1 = this.__chart__ = scale2.copy(); - var ticks2 = tickValues == null ? scale1.ticks ? scale1.ticks.apply(scale1, tickArguments_) : scale1.domain() : tickValues, tickFormat = tickFormat_ == null ? scale1.tickFormat ? scale1.tickFormat.apply(scale1, tickArguments_) : d3_identity : tickFormat_, tick = g2.selectAll(".tick").data(ticks2, scale1), tickEnter = tick.enter().insert("g", ".domain").attr("class", "tick").style("opacity", ε), tickExit = d32.transition(tick.exit()).style("opacity", ε).remove(), tickUpdate = d32.transition(tick.order()).style("opacity", 1), tickSpacing = Math.max(innerTickSize, 0) + tickPadding, tickTransform; - var range = d3_scaleRange(scale1), path = g2.selectAll(".domain").data([0]), pathUpdate = (path.enter().append("path").attr("class", "domain"), d32.transition(path)); - tickEnter.append("line"); - tickEnter.append("text"); - var lineEnter = tickEnter.select("line"), lineUpdate = tickUpdate.select("line"), text = tick.select("text").text(tickFormat), textEnter = tickEnter.select("text"), textUpdate = tickUpdate.select("text"), sign2 = orient === "top" || orient === "left" ? -1 : 1, x1, x2, y1, y2; - if (orient === "bottom" || orient === "top") { - tickTransform = d3_svg_axisX, x1 = "x", y1 = "y", x2 = "x2", y2 = "y2"; - text.attr("dy", sign2 < 0 ? "0em" : ".71em").style("text-anchor", "middle"); - pathUpdate.attr("d", "M" + range[0] + "," + sign2 * outerTickSize + "V0H" + range[1] + "V" + sign2 * outerTickSize); - } else { - tickTransform = d3_svg_axisY, x1 = "y", y1 = "x", x2 = "y2", y2 = "x2"; - text.attr("dy", ".32em").style("text-anchor", sign2 < 0 ? "end" : "start"); - pathUpdate.attr("d", "M" + sign2 * outerTickSize + "," + range[0] + "H0V" + range[1] + "H" + sign2 * outerTickSize); - } - lineEnter.attr(y2, sign2 * innerTickSize); - textEnter.attr(y1, sign2 * tickSpacing); - lineUpdate.attr(x2, 0).attr(y2, sign2 * innerTickSize); - textUpdate.attr(x1, 0).attr(y1, sign2 * tickSpacing); - if (scale1.rangeBand) { - var x = scale1, dx = x.rangeBand() / 2; - scale0 = scale1 = function(d) { - return x(d) + dx; - }; - } else if (scale0.rangeBand) { - scale0 = scale1; - } else { - tickExit.call(tickTransform, scale1, scale0); - } - tickEnter.call(tickTransform, scale0, scale1); - tickUpdate.call(tickTransform, scale1, scale1); - }); - } - axis.scale = function(x) { - if (!arguments.length) return scale2; - scale2 = x; - return axis; - }; - axis.orient = function(x) { - if (!arguments.length) return orient; - orient = x in d3_svg_axisOrients ? x + "" : d3_svg_axisDefaultOrient; - return axis; - }; - axis.ticks = function() { - if (!arguments.length) return tickArguments_; - tickArguments_ = d3_array(arguments); - return axis; - }; - axis.tickValues = function(x) { - if (!arguments.length) return tickValues; - tickValues = x; - return axis; - }; - axis.tickFormat = function(x) { - if (!arguments.length) return tickFormat_; - tickFormat_ = x; - return axis; - }; - axis.tickSize = function(x) { - var n = arguments.length; - if (!n) return innerTickSize; - innerTickSize = +x; - outerTickSize = +arguments[n - 1]; - return axis; - }; - axis.innerTickSize = function(x) { - if (!arguments.length) return innerTickSize; - innerTickSize = +x; - return axis; - }; - axis.outerTickSize = function(x) { - if (!arguments.length) return outerTickSize; - outerTickSize = +x; - return axis; - }; - axis.tickPadding = function(x) { - if (!arguments.length) return tickPadding; - tickPadding = +x; - return axis; - }; - axis.tickSubdivide = function() { - return arguments.length && axis; - }; - return axis; - }; - var d3_svg_axisDefaultOrient = "bottom", d3_svg_axisOrients = { - top: 1, - right: 1, - bottom: 1, - left: 1 - }; - function d3_svg_axisX(selection, x0, x1) { - selection.attr("transform", function(d) { - var v0 = x0(d); - return "translate(" + (isFinite(v0) ? v0 : x1(d)) + ",0)"; - }); - } - function d3_svg_axisY(selection, y0, y1) { - selection.attr("transform", function(d) { - var v0 = y0(d); - return "translate(0," + (isFinite(v0) ? v0 : y1(d)) + ")"; - }); - } - d32.svg.brush = function() { - var event = d3_eventDispatch(brush, "brushstart", "brush", "brushend"), x = null, y = null, xExtent = [0, 0], yExtent = [0, 0], xExtentDomain, yExtentDomain, xClamp = true, yClamp = true, resizes = d3_svg_brushResizes[0]; - function brush(g) { - g.each(function() { - var g2 = d32.select(this).style("pointer-events", "all").style("-webkit-tap-highlight-color", "rgba(0,0,0,0)").on("mousedown.brush", brushstart).on("touchstart.brush", brushstart); - var background2 = g2.selectAll(".background").data([0]); - background2.enter().append("rect").attr("class", "background").style("visibility", "hidden").style("cursor", "crosshair"); - g2.selectAll(".extent").data([0]).enter().append("rect").attr("class", "extent").style("cursor", "move"); - var resize2 = g2.selectAll(".resize").data(resizes, d3_identity); - resize2.exit().remove(); - resize2.enter().append("g").attr("class", function(d) { - return "resize " + d; - }).style("cursor", function(d) { - return d3_svg_brushCursor[d]; - }).append("rect").attr("x", function(d) { - return /[ew]$/.test(d) ? -3 : null; - }).attr("y", function(d) { - return /^[ns]/.test(d) ? -3 : null; - }).attr("width", 6).attr("height", 6).style("visibility", "hidden"); - resize2.style("display", brush.empty() ? "none" : null); - var gUpdate = d32.transition(g2), backgroundUpdate = d32.transition(background2), range; - if (x) { - range = d3_scaleRange(x); - backgroundUpdate.attr("x", range[0]).attr("width", range[1] - range[0]); - redrawX(gUpdate); - } - if (y) { - range = d3_scaleRange(y); - backgroundUpdate.attr("y", range[0]).attr("height", range[1] - range[0]); - redrawY(gUpdate); - } - redraw(gUpdate); - }); - } - brush.event = function(g) { - g.each(function() { - var event_ = event.of(this, arguments), extent1 = { - x: xExtent, - y: yExtent, - i: xExtentDomain, - j: yExtentDomain - }, extent0 = this.__chart__ || extent1; - this.__chart__ = extent1; - if (d3_transitionInheritId) { - d32.select(this).transition().each("start.brush", function() { - xExtentDomain = extent0.i; - yExtentDomain = extent0.j; - xExtent = extent0.x; - yExtent = extent0.y; - event_({ - type: "brushstart" - }); - }).tween("brush:brush", function() { - var xi = d3_interpolateArray(xExtent, extent1.x), yi = d3_interpolateArray(yExtent, extent1.y); - xExtentDomain = yExtentDomain = null; - return function(t) { - xExtent = extent1.x = xi(t); - yExtent = extent1.y = yi(t); - event_({ - type: "brush", - mode: "resize" - }); - }; - }).each("end.brush", function() { - xExtentDomain = extent1.i; - yExtentDomain = extent1.j; - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - }); - } else { - event_({ - type: "brushstart" - }); - event_({ - type: "brush", - mode: "resize" - }); - event_({ - type: "brushend" - }); - } - }); - }; - function redraw(g) { - g.selectAll(".resize").attr("transform", function(d) { - return "translate(" + xExtent[+/e$/.test(d)] + "," + yExtent[+/^s/.test(d)] + ")"; - }); - } - function redrawX(g) { - g.select(".extent").attr("x", xExtent[0]); - g.selectAll(".extent,.n>rect,.s>rect").attr("width", xExtent[1] - xExtent[0]); - } - function redrawY(g) { - g.select(".extent").attr("y", yExtent[0]); - g.selectAll(".extent,.e>rect,.w>rect").attr("height", yExtent[1] - yExtent[0]); - } - function brushstart() { - var target = this, eventTarget = d32.select(d32.event.target), event_ = event.of(target, arguments), g = d32.select(target), resizing = eventTarget.datum(), resizingX = !/^(n|s)$/.test(resizing) && x, resizingY = !/^(e|w)$/.test(resizing) && y, dragging = eventTarget.classed("extent"), dragRestore = d3_event_dragSuppress(target), center, origin = d32.mouse(target), offset; - var w = d32.select(d3_window(target)).on("keydown.brush", keydown).on("keyup.brush", keyup); - if (d32.event.changedTouches) { - w.on("touchmove.brush", brushmove).on("touchend.brush", brushend); - } else { - w.on("mousemove.brush", brushmove).on("mouseup.brush", brushend); - } - g.interrupt().selectAll("*").interrupt(); - if (dragging) { - origin[0] = xExtent[0] - origin[0]; - origin[1] = yExtent[0] - origin[1]; - } else if (resizing) { - var ex = +/w$/.test(resizing), ey = +/^n/.test(resizing); - offset = [xExtent[1 - ex] - origin[0], yExtent[1 - ey] - origin[1]]; - origin[0] = xExtent[ex]; - origin[1] = yExtent[ey]; - } else if (d32.event.altKey) center = origin.slice(); - g.style("pointer-events", "none").selectAll(".resize").style("display", null); - d32.select("body").style("cursor", eventTarget.style("cursor")); - event_({ - type: "brushstart" - }); - brushmove(); - function keydown() { - if (d32.event.keyCode == 32) { - if (!dragging) { - center = null; - origin[0] -= xExtent[1]; - origin[1] -= yExtent[1]; - dragging = 2; - } - d3_eventPreventDefault(); - } - } - function keyup() { - if (d32.event.keyCode == 32 && dragging == 2) { - origin[0] += xExtent[1]; - origin[1] += yExtent[1]; - dragging = 0; - d3_eventPreventDefault(); - } - } - function brushmove() { - var point = d32.mouse(target), moved = false; - if (offset) { - point[0] += offset[0]; - point[1] += offset[1]; - } - if (!dragging) { - if (d32.event.altKey) { - if (!center) center = [(xExtent[0] + xExtent[1]) / 2, (yExtent[0] + yExtent[1]) / 2]; - origin[0] = xExtent[+(point[0] < center[0])]; - origin[1] = yExtent[+(point[1] < center[1])]; - } else center = null; - } - if (resizingX && move1(point, x, 0)) { - redrawX(g); - moved = true; - } - if (resizingY && move1(point, y, 1)) { - redrawY(g); - moved = true; - } - if (moved) { - redraw(g); - event_({ - type: "brush", - mode: dragging ? "move" : "resize" - }); - } - } - function move1(point, scale2, i) { - var range = d3_scaleRange(scale2), r0 = range[0], r1 = range[1], position = origin[i], extent2 = i ? yExtent : xExtent, size = extent2[1] - extent2[0], min, max; - if (dragging) { - r0 -= position; - r1 -= size + position; - } - min = (i ? yClamp : xClamp) ? Math.max(r0, Math.min(r1, point[i])) : point[i]; - if (dragging) { - max = (min += position) + size; - } else { - if (center) position = Math.max(r0, Math.min(r1, 2 * center[i] - min)); - if (position < min) { - max = min; - min = position; - } else { - max = position; - } - } - if (extent2[0] != min || extent2[1] != max) { - if (i) yExtentDomain = null; - else xExtentDomain = null; - extent2[0] = min; - extent2[1] = max; - return true; - } - } - function brushend() { - brushmove(); - g.style("pointer-events", "all").selectAll(".resize").style("display", brush.empty() ? "none" : null); - d32.select("body").style("cursor", null); - w.on("mousemove.brush", null).on("mouseup.brush", null).on("touchmove.brush", null).on("touchend.brush", null).on("keydown.brush", null).on("keyup.brush", null); - dragRestore(); - event_({ - type: "brushend" - }); - } - } - brush.x = function(z) { - if (!arguments.length) return x; - x = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.y = function(z) { - if (!arguments.length) return y; - y = z; - resizes = d3_svg_brushResizes[!x << 1 | !y]; - return brush; - }; - brush.clamp = function(z) { - if (!arguments.length) return x && y ? [xClamp, yClamp] : x ? xClamp : y ? yClamp : null; - if (x && y) xClamp = !!z[0], yClamp = !!z[1]; - else if (x) xClamp = !!z; - else if (y) yClamp = !!z; - return brush; - }; - brush.extent = function(z) { - var x0, x1, y0, y1, t; - if (!arguments.length) { - if (x) { - if (xExtentDomain) { - x0 = xExtentDomain[0], x1 = xExtentDomain[1]; - } else { - x0 = xExtent[0], x1 = xExtent[1]; - if (x.invert) x0 = x.invert(x0), x1 = x.invert(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - } - } - if (y) { - if (yExtentDomain) { - y0 = yExtentDomain[0], y1 = yExtentDomain[1]; - } else { - y0 = yExtent[0], y1 = yExtent[1]; - if (y.invert) y0 = y.invert(y0), y1 = y.invert(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - } - } - return x && y ? [[x0, y0], [x1, y1]] : x ? [x0, x1] : y && [y0, y1]; - } - if (x) { - x0 = z[0], x1 = z[1]; - if (y) x0 = x0[0], x1 = x1[0]; - xExtentDomain = [x0, x1]; - if (x.invert) x0 = x(x0), x1 = x(x1); - if (x1 < x0) t = x0, x0 = x1, x1 = t; - if (x0 != xExtent[0] || x1 != xExtent[1]) xExtent = [x0, x1]; - } - if (y) { - y0 = z[0], y1 = z[1]; - if (x) y0 = y0[1], y1 = y1[1]; - yExtentDomain = [y0, y1]; - if (y.invert) y0 = y(y0), y1 = y(y1); - if (y1 < y0) t = y0, y0 = y1, y1 = t; - if (y0 != yExtent[0] || y1 != yExtent[1]) yExtent = [y0, y1]; - } - return brush; - }; - brush.clear = function() { - if (!brush.empty()) { - xExtent = [0, 0], yExtent = [0, 0]; - xExtentDomain = yExtentDomain = null; - } - return brush; - }; - brush.empty = function() { - return !!x && xExtent[0] == xExtent[1] || !!y && yExtent[0] == yExtent[1]; - }; - return d32.rebind(brush, event, "on"); - }; - var d3_svg_brushCursor = { - n: "ns-resize", - e: "ew-resize", - s: "ns-resize", - w: "ew-resize", - nw: "nwse-resize", - ne: "nesw-resize", - se: "nwse-resize", - sw: "nesw-resize" - }; - var d3_svg_brushResizes = [["n", "e", "s", "w", "nw", "ne", "se", "sw"], ["e", "w"], ["n", "s"], []]; - d32.text = d3_xhrType(function(request) { - return request.responseText; - }); - d32.json = function(url, callback) { - return d3_xhr(url, "application/json", d3_json, callback); - }; - function d3_json(request) { - return JSON.parse(request.responseText); - } - d32.html = function(url, callback) { - return d3_xhr(url, "text/html", d3_html, callback); - }; - function d3_html(request) { - var range = d3_document.createRange(); - range.selectNode(d3_document.body); - return range.createContextualFragment(request.responseText); - } - d32.xml = d3_xhrType(function(request) { - return request.responseXML; - }); - if (module2.exports) module2.exports = d32; - else this.d3 = d32; - }).apply(self); -})(d3$G); -var d3Exports = d3$G.exports; -var t0$1 = /* @__PURE__ */ new Date(), t1$1 = /* @__PURE__ */ new Date(); -function newInterval(floori, offseti, count2, field) { - function interval(date2) { - return floori(date2 = arguments.length === 0 ? /* @__PURE__ */ new Date() : /* @__PURE__ */ new Date(+date2)), date2; - } - interval.floor = function(date2) { - return floori(date2 = /* @__PURE__ */ new Date(+date2)), date2; - }; - interval.ceil = function(date2) { - return floori(date2 = new Date(date2 - 1)), offseti(date2, 1), floori(date2), date2; - }; - interval.round = function(date2) { - var d0 = interval(date2), d1 = interval.ceil(date2); - return date2 - d0 < d1 - date2 ? d0 : d1; - }; - interval.offset = function(date2, step) { - return offseti(date2 = /* @__PURE__ */ new Date(+date2), step == null ? 1 : Math.floor(step)), date2; - }; - interval.range = function(start, stop, step) { - var range = [], previous; - start = interval.ceil(start); - step = step == null ? 1 : Math.floor(step); - if (!(start < stop) || !(step > 0)) return range; - do - range.push(previous = /* @__PURE__ */ new Date(+start)), offseti(start, step), floori(start); - while (previous < start && start < stop); - return range; - }; - interval.filter = function(test) { - return newInterval(function(date2) { - if (date2 >= date2) while (floori(date2), !test(date2)) date2.setTime(date2 - 1); - }, function(date2, step) { - if (date2 >= date2) { - if (step < 0) while (++step <= 0) { - while (offseti(date2, -1), !test(date2)) { - } - } - else while (--step >= 0) { - while (offseti(date2, 1), !test(date2)) { - } - } - } - }); - }; - if (count2) { - interval.count = function(start, end) { - t0$1.setTime(+start), t1$1.setTime(+end); - floori(t0$1), floori(t1$1); - return Math.floor(count2(t0$1, t1$1)); - }; - interval.every = function(step) { - step = Math.floor(step); - return !isFinite(step) || !(step > 0) ? null : !(step > 1) ? interval : interval.filter(field ? function(d) { - return field(d) % step === 0; - } : function(d) { - return interval.count(0, d) % step === 0; - }); - }; - } - return interval; -} -var millisecond = newInterval(function() { -}, function(date2, step) { - date2.setTime(+date2 + step); -}, function(start, end) { - return end - start; -}); -millisecond.every = function(k) { - k = Math.floor(k); - if (!isFinite(k) || !(k > 0)) return null; - if (!(k > 1)) return millisecond; - return newInterval(function(date2) { - date2.setTime(Math.floor(date2 / k) * k); - }, function(date2, step) { - date2.setTime(+date2 + step * k); - }, function(start, end) { - return (end - start) / k; - }); -}; -var milliseconds = millisecond.range; -var durationSecond = 1e3; -var durationMinute = 6e4; -var durationHour = 36e5; -var durationDay = 864e5; -var durationWeek = 6048e5; -var second = newInterval(function(date2) { - date2.setTime(date2 - date2.getMilliseconds()); -}, function(date2, step) { - date2.setTime(+date2 + step * durationSecond); -}, function(start, end) { - return (end - start) / durationSecond; -}, function(date2) { - return date2.getUTCSeconds(); -}); -var seconds = second.range; -var minute = newInterval(function(date2) { - date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond); -}, function(date2, step) { - date2.setTime(+date2 + step * durationMinute); -}, function(start, end) { - return (end - start) / durationMinute; -}, function(date2) { - return date2.getMinutes(); -}); -var minutes = minute.range; -var hour = newInterval(function(date2) { - date2.setTime(date2 - date2.getMilliseconds() - date2.getSeconds() * durationSecond - date2.getMinutes() * durationMinute); -}, function(date2, step) { - date2.setTime(+date2 + step * durationHour); -}, function(start, end) { - return (end - start) / durationHour; -}, function(date2) { - return date2.getHours(); -}); -var hours = hour.range; -var day = newInterval(function(date2) { - date2.setHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setDate(date2.getDate() + step); -}, function(start, end) { - return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationDay; -}, function(date2) { - return date2.getDate() - 1; -}); -var days = day.range; -function weekday(i) { - return newInterval(function(date2) { - date2.setDate(date2.getDate() - (date2.getDay() + 7 - i) % 7); - date2.setHours(0, 0, 0, 0); - }, function(date2, step) { - date2.setDate(date2.getDate() + step * 7); - }, function(start, end) { - return (end - start - (end.getTimezoneOffset() - start.getTimezoneOffset()) * durationMinute) / durationWeek; - }); -} -var sunday = weekday(0); -var monday = weekday(1); -var tuesday = weekday(2); -var wednesday = weekday(3); -var thursday = weekday(4); -var friday = weekday(5); -var saturday = weekday(6); -var sundays = sunday.range; -var mondays = monday.range; -var tuesdays = tuesday.range; -var wednesdays = wednesday.range; -var thursdays = thursday.range; -var fridays = friday.range; -var saturdays = saturday.range; -var month = newInterval(function(date2) { - date2.setDate(1); - date2.setHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setMonth(date2.getMonth() + step); -}, function(start, end) { - return end.getMonth() - start.getMonth() + (end.getFullYear() - start.getFullYear()) * 12; -}, function(date2) { - return date2.getMonth(); -}); -var months = month.range; -var year = newInterval(function(date2) { - date2.setMonth(0, 1); - date2.setHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setFullYear(date2.getFullYear() + step); -}, function(start, end) { - return end.getFullYear() - start.getFullYear(); -}, function(date2) { - return date2.getFullYear(); -}); -year.every = function(k) { - return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date2) { - date2.setFullYear(Math.floor(date2.getFullYear() / k) * k); - date2.setMonth(0, 1); - date2.setHours(0, 0, 0, 0); - }, function(date2, step) { - date2.setFullYear(date2.getFullYear() + step * k); - }); -}; -var years = year.range; -var utcMinute = newInterval(function(date2) { - date2.setUTCSeconds(0, 0); -}, function(date2, step) { - date2.setTime(+date2 + step * durationMinute); -}, function(start, end) { - return (end - start) / durationMinute; -}, function(date2) { - return date2.getUTCMinutes(); -}); -var utcMinutes = utcMinute.range; -var utcHour = newInterval(function(date2) { - date2.setUTCMinutes(0, 0, 0); -}, function(date2, step) { - date2.setTime(+date2 + step * durationHour); -}, function(start, end) { - return (end - start) / durationHour; -}, function(date2) { - return date2.getUTCHours(); -}); -var utcHours = utcHour.range; -var utcDay = newInterval(function(date2) { - date2.setUTCHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setUTCDate(date2.getUTCDate() + step); -}, function(start, end) { - return (end - start) / durationDay; -}, function(date2) { - return date2.getUTCDate() - 1; -}); -var utcDays = utcDay.range; -function utcWeekday(i) { - return newInterval(function(date2) { - date2.setUTCDate(date2.getUTCDate() - (date2.getUTCDay() + 7 - i) % 7); - date2.setUTCHours(0, 0, 0, 0); - }, function(date2, step) { - date2.setUTCDate(date2.getUTCDate() + step * 7); - }, function(start, end) { - return (end - start) / durationWeek; - }); -} -var utcSunday = utcWeekday(0); -var utcMonday = utcWeekday(1); -var utcTuesday = utcWeekday(2); -var utcWednesday = utcWeekday(3); -var utcThursday = utcWeekday(4); -var utcFriday = utcWeekday(5); -var utcSaturday = utcWeekday(6); -var utcSundays = utcSunday.range; -var utcMondays = utcMonday.range; -var utcTuesdays = utcTuesday.range; -var utcWednesdays = utcWednesday.range; -var utcThursdays = utcThursday.range; -var utcFridays = utcFriday.range; -var utcSaturdays = utcSaturday.range; -var utcMonth = newInterval(function(date2) { - date2.setUTCDate(1); - date2.setUTCHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setUTCMonth(date2.getUTCMonth() + step); -}, function(start, end) { - return end.getUTCMonth() - start.getUTCMonth() + (end.getUTCFullYear() - start.getUTCFullYear()) * 12; -}, function(date2) { - return date2.getUTCMonth(); -}); -var utcMonths = utcMonth.range; -var utcYear = newInterval(function(date2) { - date2.setUTCMonth(0, 1); - date2.setUTCHours(0, 0, 0, 0); -}, function(date2, step) { - date2.setUTCFullYear(date2.getUTCFullYear() + step); -}, function(start, end) { - return end.getUTCFullYear() - start.getUTCFullYear(); -}, function(date2) { - return date2.getUTCFullYear(); -}); -utcYear.every = function(k) { - return !isFinite(k = Math.floor(k)) || !(k > 0) ? null : newInterval(function(date2) { - date2.setUTCFullYear(Math.floor(date2.getUTCFullYear() / k) * k); - date2.setUTCMonth(0, 1); - date2.setUTCHours(0, 0, 0, 0); - }, function(date2, step) { - date2.setUTCFullYear(date2.getUTCFullYear() + step * k); - }); -}; -var utcYears = utcYear.range; -const src$4 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - timeDay: day, - timeDays: days, - timeFriday: friday, - timeFridays: fridays, - timeHour: hour, - timeHours: hours, - timeInterval: newInterval, - timeMillisecond: millisecond, - timeMilliseconds: milliseconds, - timeMinute: minute, - timeMinutes: minutes, - timeMonday: monday, - timeMondays: mondays, - timeMonth: month, - timeMonths: months, - timeSaturday: saturday, - timeSaturdays: saturdays, - timeSecond: second, - timeSeconds: seconds, - timeSunday: sunday, - timeSundays: sundays, - timeThursday: thursday, - timeThursdays: thursdays, - timeTuesday: tuesday, - timeTuesdays: tuesdays, - timeWednesday: wednesday, - timeWednesdays: wednesdays, - timeWeek: sunday, - timeWeeks: sundays, - timeYear: year, - timeYears: years, - utcDay, - utcDays, - utcFriday, - utcFridays, - utcHour, - utcHours, - utcMillisecond: millisecond, - utcMilliseconds: milliseconds, - utcMinute, - utcMinutes, - utcMonday, - utcMondays, - utcMonth, - utcMonths, - utcSaturday, - utcSaturdays, - utcSecond: second, - utcSeconds: seconds, - utcSunday, - utcSundays, - utcThursday, - utcThursdays, - utcTuesday, - utcTuesdays, - utcWednesday, - utcWednesdays, - utcWeek: utcSunday, - utcWeeks: utcSundays, - utcYear, - utcYears -}, Symbol.toStringTag, { value: "Module" })); -function localDate(d) { - if (0 <= d.y && d.y < 100) { - var date2 = new Date(-1, d.m, d.d, d.H, d.M, d.S, d.L); - date2.setFullYear(d.y); - return date2; - } - return new Date(d.y, d.m, d.d, d.H, d.M, d.S, d.L); -} -function utcDate(d) { - if (0 <= d.y && d.y < 100) { - var date2 = new Date(Date.UTC(-1, d.m, d.d, d.H, d.M, d.S, d.L)); - date2.setUTCFullYear(d.y); - return date2; - } - return new Date(Date.UTC(d.y, d.m, d.d, d.H, d.M, d.S, d.L)); -} -function newDate(y, m, d) { - return { y, m, d, H: 0, M: 0, S: 0, L: 0 }; -} -function formatLocale$2(locale2) { - var locale_dateTime = locale2.dateTime, locale_date = locale2.date, locale_time = locale2.time, locale_periods = locale2.periods, locale_weekdays = locale2.days, locale_shortWeekdays = locale2.shortDays, locale_months = locale2.months, locale_shortMonths = locale2.shortMonths; - var periodRe = formatRe(locale_periods), periodLookup = formatLookup(locale_periods), weekdayRe = formatRe(locale_weekdays), weekdayLookup = formatLookup(locale_weekdays), shortWeekdayRe = formatRe(locale_shortWeekdays), shortWeekdayLookup = formatLookup(locale_shortWeekdays), monthRe = formatRe(locale_months), monthLookup = formatLookup(locale_months), shortMonthRe = formatRe(locale_shortMonths), shortMonthLookup = formatLookup(locale_shortMonths); - var formats = { - "a": formatShortWeekday, - "A": formatWeekday, - "b": formatShortMonth, - "B": formatMonth, - "c": null, - "d": formatDayOfMonth, - "e": formatDayOfMonth, - "f": formatMicroseconds, - "g": formatYearISO, - "G": formatFullYearISO, - "H": formatHour24, - "I": formatHour12, - "j": formatDayOfYear, - "L": formatMilliseconds, - "m": formatMonthNumber, - "M": formatMinutes, - "p": formatPeriod, - "q": formatQuarter, - "Q": formatUnixTimestamp, - "s": formatUnixTimestampSeconds, - "S": formatSeconds, - "u": formatWeekdayNumberMonday, - "U": formatWeekNumberSunday, - "V": formatWeekNumberISO, - "w": formatWeekdayNumberSunday, - "W": formatWeekNumberMonday, - "x": null, - "X": null, - "y": formatYear, - "Y": formatFullYear, - "Z": formatZone, - "%": formatLiteralPercent - }; - var utcFormats = { - "a": formatUTCShortWeekday, - "A": formatUTCWeekday, - "b": formatUTCShortMonth, - "B": formatUTCMonth, - "c": null, - "d": formatUTCDayOfMonth, - "e": formatUTCDayOfMonth, - "f": formatUTCMicroseconds, - "g": formatUTCYearISO, - "G": formatUTCFullYearISO, - "H": formatUTCHour24, - "I": formatUTCHour12, - "j": formatUTCDayOfYear, - "L": formatUTCMilliseconds, - "m": formatUTCMonthNumber, - "M": formatUTCMinutes, - "p": formatUTCPeriod, - "q": formatUTCQuarter, - "Q": formatUnixTimestamp, - "s": formatUnixTimestampSeconds, - "S": formatUTCSeconds, - "u": formatUTCWeekdayNumberMonday, - "U": formatUTCWeekNumberSunday, - "V": formatUTCWeekNumberISO, - "w": formatUTCWeekdayNumberSunday, - "W": formatUTCWeekNumberMonday, - "x": null, - "X": null, - "y": formatUTCYear, - "Y": formatUTCFullYear, - "Z": formatUTCZone, - "%": formatLiteralPercent - }; - var parses = { - "a": parseShortWeekday, - "A": parseWeekday, - "b": parseShortMonth, - "B": parseMonth, - "c": parseLocaleDateTime, - "d": parseDayOfMonth, - "e": parseDayOfMonth, - "f": parseMicroseconds, - "g": parseYear, - "G": parseFullYear, - "H": parseHour24, - "I": parseHour24, - "j": parseDayOfYear, - "L": parseMilliseconds, - "m": parseMonthNumber, - "M": parseMinutes, - "p": parsePeriod, - "q": parseQuarter, - "Q": parseUnixTimestamp, - "s": parseUnixTimestampSeconds, - "S": parseSeconds, - "u": parseWeekdayNumberMonday, - "U": parseWeekNumberSunday, - "V": parseWeekNumberISO, - "w": parseWeekdayNumberSunday, - "W": parseWeekNumberMonday, - "x": parseLocaleDate, - "X": parseLocaleTime, - "y": parseYear, - "Y": parseFullYear, - "Z": parseZone, - "%": parseLiteralPercent - }; - formats.x = newFormat(locale_date, formats); - formats.X = newFormat(locale_time, formats); - formats.c = newFormat(locale_dateTime, formats); - utcFormats.x = newFormat(locale_date, utcFormats); - utcFormats.X = newFormat(locale_time, utcFormats); - utcFormats.c = newFormat(locale_dateTime, utcFormats); - function newFormat(specifier, formats2) { - return function(date2) { - var string2 = [], i = -1, j = 0, n = specifier.length, c, pad2, format2; - if (!(date2 instanceof Date)) date2 = /* @__PURE__ */ new Date(+date2); - while (++i < n) { - if (specifier.charCodeAt(i) === 37) { - string2.push(specifier.slice(j, i)); - if ((pad2 = pads[c = specifier.charAt(++i)]) != null) c = specifier.charAt(++i); - else pad2 = c === "e" ? " " : "0"; - if (format2 = formats2[c]) c = format2(date2, pad2); - string2.push(c); - j = i + 1; - } - } - string2.push(specifier.slice(j, i)); - return string2.join(""); - }; - } - function newParse(specifier, Z) { - return function(string2) { - var d = newDate(1900, void 0, 1), i = parseSpecifier(d, specifier, string2 += "", 0), week, day$1; - if (i != string2.length) return null; - if ("Q" in d) return new Date(d.Q); - if ("s" in d) return new Date(d.s * 1e3 + ("L" in d ? d.L : 0)); - if (Z && !("Z" in d)) d.Z = 0; - if ("p" in d) d.H = d.H % 12 + d.p * 12; - if (d.m === void 0) d.m = "q" in d ? d.q : 0; - if ("V" in d) { - if (d.V < 1 || d.V > 53) return null; - if (!("w" in d)) d.w = 1; - if ("Z" in d) { - week = utcDate(newDate(d.y, 0, 1)), day$1 = week.getUTCDay(); - week = day$1 > 4 || day$1 === 0 ? utcMonday.ceil(week) : utcMonday(week); - week = utcDay.offset(week, (d.V - 1) * 7); - d.y = week.getUTCFullYear(); - d.m = week.getUTCMonth(); - d.d = week.getUTCDate() + (d.w + 6) % 7; - } else { - week = localDate(newDate(d.y, 0, 1)), day$1 = week.getDay(); - week = day$1 > 4 || day$1 === 0 ? monday.ceil(week) : monday(week); - week = day.offset(week, (d.V - 1) * 7); - d.y = week.getFullYear(); - d.m = week.getMonth(); - d.d = week.getDate() + (d.w + 6) % 7; - } - } else if ("W" in d || "U" in d) { - if (!("w" in d)) d.w = "u" in d ? d.u % 7 : "W" in d ? 1 : 0; - day$1 = "Z" in d ? utcDate(newDate(d.y, 0, 1)).getUTCDay() : localDate(newDate(d.y, 0, 1)).getDay(); - d.m = 0; - d.d = "W" in d ? (d.w + 6) % 7 + d.W * 7 - (day$1 + 5) % 7 : d.w + d.U * 7 - (day$1 + 6) % 7; - } - if ("Z" in d) { - d.H += d.Z / 100 | 0; - d.M += d.Z % 100; - return utcDate(d); - } - return localDate(d); - }; - } - function parseSpecifier(d, specifier, string2, j) { - var i = 0, n = specifier.length, m = string2.length, c, parse2; - while (i < n) { - if (j >= m) return -1; - c = specifier.charCodeAt(i++); - if (c === 37) { - c = specifier.charAt(i++); - parse2 = parses[c in pads ? specifier.charAt(i++) : c]; - if (!parse2 || (j = parse2(d, string2, j)) < 0) return -1; - } else if (c != string2.charCodeAt(j++)) { - return -1; - } - } - return j; - } - function parsePeriod(d, string2, i) { - var n = periodRe.exec(string2.slice(i)); - return n ? (d.p = periodLookup[n[0].toLowerCase()], i + n[0].length) : -1; - } - function parseShortWeekday(d, string2, i) { - var n = shortWeekdayRe.exec(string2.slice(i)); - return n ? (d.w = shortWeekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; - } - function parseWeekday(d, string2, i) { - var n = weekdayRe.exec(string2.slice(i)); - return n ? (d.w = weekdayLookup[n[0].toLowerCase()], i + n[0].length) : -1; - } - function parseShortMonth(d, string2, i) { - var n = shortMonthRe.exec(string2.slice(i)); - return n ? (d.m = shortMonthLookup[n[0].toLowerCase()], i + n[0].length) : -1; - } - function parseMonth(d, string2, i) { - var n = monthRe.exec(string2.slice(i)); - return n ? (d.m = monthLookup[n[0].toLowerCase()], i + n[0].length) : -1; - } - function parseLocaleDateTime(d, string2, i) { - return parseSpecifier(d, locale_dateTime, string2, i); - } - function parseLocaleDate(d, string2, i) { - return parseSpecifier(d, locale_date, string2, i); - } - function parseLocaleTime(d, string2, i) { - return parseSpecifier(d, locale_time, string2, i); - } - function formatShortWeekday(d) { - return locale_shortWeekdays[d.getDay()]; - } - function formatWeekday(d) { - return locale_weekdays[d.getDay()]; - } - function formatShortMonth(d) { - return locale_shortMonths[d.getMonth()]; - } - function formatMonth(d) { - return locale_months[d.getMonth()]; - } - function formatPeriod(d) { - return locale_periods[+(d.getHours() >= 12)]; - } - function formatQuarter(d) { - return 1 + ~~(d.getMonth() / 3); - } - function formatUTCShortWeekday(d) { - return locale_shortWeekdays[d.getUTCDay()]; - } - function formatUTCWeekday(d) { - return locale_weekdays[d.getUTCDay()]; - } - function formatUTCShortMonth(d) { - return locale_shortMonths[d.getUTCMonth()]; - } - function formatUTCMonth(d) { - return locale_months[d.getUTCMonth()]; - } - function formatUTCPeriod(d) { - return locale_periods[+(d.getUTCHours() >= 12)]; - } - function formatUTCQuarter(d) { - return 1 + ~~(d.getUTCMonth() / 3); - } - return { - format: function(specifier) { - var f = newFormat(specifier += "", formats); - f.toString = function() { - return specifier; - }; - return f; - }, - parse: function(specifier) { - var p = newParse(specifier += "", false); - p.toString = function() { - return specifier; - }; - return p; - }, - utcFormat: function(specifier) { - var f = newFormat(specifier += "", utcFormats); - f.toString = function() { - return specifier; - }; - return f; - }, - utcParse: function(specifier) { - var p = newParse(specifier += "", true); - p.toString = function() { - return specifier; - }; - return p; - } - }; -} -var pads = { "-": "", "_": " ", "0": "0" }, numberRe = /^\s*\d+/, percentRe = /^%/, requoteRe = /[\\^$*+?|[\]().{}]/g; -function pad(value2, fill, width) { - var sign2 = value2 < 0 ? "-" : "", string2 = (sign2 ? -value2 : value2) + "", length2 = string2.length; - return sign2 + (length2 < width ? new Array(width - length2 + 1).join(fill) + string2 : string2); -} -function requote(s) { - return s.replace(requoteRe, "\\$&"); -} -function formatRe(names2) { - return new RegExp("^(?:" + names2.map(requote).join("|") + ")", "i"); -} -function formatLookup(names2) { - var map2 = {}, i = -1, n = names2.length; - while (++i < n) map2[names2[i].toLowerCase()] = i; - return map2; -} -function parseWeekdayNumberSunday(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 1)); - return n ? (d.w = +n[0], i + n[0].length) : -1; -} -function parseWeekdayNumberMonday(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 1)); - return n ? (d.u = +n[0], i + n[0].length) : -1; -} -function parseWeekNumberSunday(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.U = +n[0], i + n[0].length) : -1; -} -function parseWeekNumberISO(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.V = +n[0], i + n[0].length) : -1; -} -function parseWeekNumberMonday(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.W = +n[0], i + n[0].length) : -1; -} -function parseFullYear(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 4)); - return n ? (d.y = +n[0], i + n[0].length) : -1; -} -function parseYear(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.y = +n[0] + (+n[0] > 68 ? 1900 : 2e3), i + n[0].length) : -1; -} -function parseZone(d, string2, i) { - var n = /^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(string2.slice(i, i + 6)); - return n ? (d.Z = n[1] ? 0 : -(n[2] + (n[3] || "00")), i + n[0].length) : -1; -} -function parseQuarter(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 1)); - return n ? (d.q = n[0] * 3 - 3, i + n[0].length) : -1; -} -function parseMonthNumber(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.m = n[0] - 1, i + n[0].length) : -1; -} -function parseDayOfMonth(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.d = +n[0], i + n[0].length) : -1; -} -function parseDayOfYear(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 3)); - return n ? (d.m = 0, d.d = +n[0], i + n[0].length) : -1; -} -function parseHour24(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.H = +n[0], i + n[0].length) : -1; -} -function parseMinutes(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.M = +n[0], i + n[0].length) : -1; -} -function parseSeconds(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 2)); - return n ? (d.S = +n[0], i + n[0].length) : -1; -} -function parseMilliseconds(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 3)); - return n ? (d.L = +n[0], i + n[0].length) : -1; -} -function parseMicroseconds(d, string2, i) { - var n = numberRe.exec(string2.slice(i, i + 6)); - return n ? (d.L = Math.floor(n[0] / 1e3), i + n[0].length) : -1; -} -function parseLiteralPercent(d, string2, i) { - var n = percentRe.exec(string2.slice(i, i + 1)); - return n ? i + n[0].length : -1; -} -function parseUnixTimestamp(d, string2, i) { - var n = numberRe.exec(string2.slice(i)); - return n ? (d.Q = +n[0], i + n[0].length) : -1; -} -function parseUnixTimestampSeconds(d, string2, i) { - var n = numberRe.exec(string2.slice(i)); - return n ? (d.s = +n[0], i + n[0].length) : -1; -} -function formatDayOfMonth(d, p) { - return pad(d.getDate(), p, 2); -} -function formatHour24(d, p) { - return pad(d.getHours(), p, 2); -} -function formatHour12(d, p) { - return pad(d.getHours() % 12 || 12, p, 2); -} -function formatDayOfYear(d, p) { - return pad(1 + day.count(year(d), d), p, 3); -} -function formatMilliseconds(d, p) { - return pad(d.getMilliseconds(), p, 3); -} -function formatMicroseconds(d, p) { - return formatMilliseconds(d, p) + "000"; -} -function formatMonthNumber(d, p) { - return pad(d.getMonth() + 1, p, 2); -} -function formatMinutes(d, p) { - return pad(d.getMinutes(), p, 2); -} -function formatSeconds(d, p) { - return pad(d.getSeconds(), p, 2); -} -function formatWeekdayNumberMonday(d) { - var day2 = d.getDay(); - return day2 === 0 ? 7 : day2; -} -function formatWeekNumberSunday(d, p) { - return pad(sunday.count(year(d) - 1, d), p, 2); -} -function dISO(d) { - var day2 = d.getDay(); - return day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d); -} -function formatWeekNumberISO(d, p) { - d = dISO(d); - return pad(thursday.count(year(d), d) + (year(d).getDay() === 4), p, 2); -} -function formatWeekdayNumberSunday(d) { - return d.getDay(); -} -function formatWeekNumberMonday(d, p) { - return pad(monday.count(year(d) - 1, d), p, 2); -} -function formatYear(d, p) { - return pad(d.getFullYear() % 100, p, 2); -} -function formatYearISO(d, p) { - d = dISO(d); - return pad(d.getFullYear() % 100, p, 2); -} -function formatFullYear(d, p) { - return pad(d.getFullYear() % 1e4, p, 4); -} -function formatFullYearISO(d, p) { - var day2 = d.getDay(); - d = day2 >= 4 || day2 === 0 ? thursday(d) : thursday.ceil(d); - return pad(d.getFullYear() % 1e4, p, 4); -} -function formatZone(d) { - var z = d.getTimezoneOffset(); - return (z > 0 ? "-" : (z *= -1, "+")) + pad(z / 60 | 0, "0", 2) + pad(z % 60, "0", 2); -} -function formatUTCDayOfMonth(d, p) { - return pad(d.getUTCDate(), p, 2); -} -function formatUTCHour24(d, p) { - return pad(d.getUTCHours(), p, 2); -} -function formatUTCHour12(d, p) { - return pad(d.getUTCHours() % 12 || 12, p, 2); -} -function formatUTCDayOfYear(d, p) { - return pad(1 + utcDay.count(utcYear(d), d), p, 3); -} -function formatUTCMilliseconds(d, p) { - return pad(d.getUTCMilliseconds(), p, 3); -} -function formatUTCMicroseconds(d, p) { - return formatUTCMilliseconds(d, p) + "000"; -} -function formatUTCMonthNumber(d, p) { - return pad(d.getUTCMonth() + 1, p, 2); -} -function formatUTCMinutes(d, p) { - return pad(d.getUTCMinutes(), p, 2); -} -function formatUTCSeconds(d, p) { - return pad(d.getUTCSeconds(), p, 2); -} -function formatUTCWeekdayNumberMonday(d) { - var dow = d.getUTCDay(); - return dow === 0 ? 7 : dow; -} -function formatUTCWeekNumberSunday(d, p) { - return pad(utcSunday.count(utcYear(d) - 1, d), p, 2); -} -function UTCdISO(d) { - var day2 = d.getUTCDay(); - return day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d); -} -function formatUTCWeekNumberISO(d, p) { - d = UTCdISO(d); - return pad(utcThursday.count(utcYear(d), d) + (utcYear(d).getUTCDay() === 4), p, 2); -} -function formatUTCWeekdayNumberSunday(d) { - return d.getUTCDay(); -} -function formatUTCWeekNumberMonday(d, p) { - return pad(utcMonday.count(utcYear(d) - 1, d), p, 2); -} -function formatUTCYear(d, p) { - return pad(d.getUTCFullYear() % 100, p, 2); -} -function formatUTCYearISO(d, p) { - d = UTCdISO(d); - return pad(d.getUTCFullYear() % 100, p, 2); -} -function formatUTCFullYear(d, p) { - return pad(d.getUTCFullYear() % 1e4, p, 4); -} -function formatUTCFullYearISO(d, p) { - var day2 = d.getUTCDay(); - d = day2 >= 4 || day2 === 0 ? utcThursday(d) : utcThursday.ceil(d); - return pad(d.getUTCFullYear() % 1e4, p, 4); -} -function formatUTCZone() { - return "+0000"; -} -function formatLiteralPercent() { - return "%"; -} -function formatUnixTimestamp(d) { - return +d; -} -function formatUnixTimestampSeconds(d) { - return Math.floor(+d / 1e3); -} -var locale$1; -var timeFormat; -var timeParse; -var utcFormat$2; -var utcParse; -defaultLocale$1({ - dateTime: "%x, %X", - date: "%-m/%-d/%Y", - time: "%-I:%M:%S %p", - periods: ["AM", "PM"], - days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], - shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], - months: ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"], - shortMonths: ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] -}); -function defaultLocale$1(definition) { - locale$1 = formatLocale$2(definition); - timeFormat = locale$1.format; - timeParse = locale$1.parse; - utcFormat$2 = locale$1.utcFormat; - utcParse = locale$1.utcParse; - return locale$1; -} -var isoSpecifier = "%Y-%m-%dT%H:%M:%S.%LZ"; -function formatIsoNative(date2) { - return date2.toISOString(); -} -var formatIso = Date.prototype.toISOString ? formatIsoNative : utcFormat$2(isoSpecifier); -function parseIsoNative(string2) { - var date2 = new Date(string2); - return isNaN(date2) ? null : date2; -} -var parseIso = +/* @__PURE__ */ new Date("2000-01-01T00:00:00.000Z") ? parseIsoNative : utcParse(isoSpecifier); -const src$3 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - isoFormat: formatIso, - isoParse: parseIso, - get timeFormat() { - return timeFormat; - }, - timeFormatDefaultLocale: defaultLocale$1, - timeFormatLocale: formatLocale$2, - get timeParse() { - return timeParse; - }, - get utcFormat() { - return utcFormat$2; - }, - get utcParse() { - return utcParse; - } -}, Symbol.toStringTag, { value: "Module" })); -const require$$1$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$3); -function formatDecimal(x) { - return Math.abs(x = Math.round(x)) >= 1e21 ? x.toLocaleString("en").replace(/,/g, "") : x.toString(10); -} -function formatDecimalParts(x, p) { - if ((i = (x = p ? x.toExponential(p - 1) : x.toExponential()).indexOf("e")) < 0) return null; - var i, coefficient = x.slice(0, i); - return [ - coefficient.length > 1 ? coefficient[0] + coefficient.slice(2) : coefficient, - +x.slice(i + 1) - ]; -} -function exponent(x) { - return x = formatDecimalParts(Math.abs(x)), x ? x[1] : NaN; -} -function formatGroup(grouping, thousands) { - return function(value2, width) { - var i = value2.length, t = [], j = 0, g = grouping[0], length2 = 0; - while (i > 0 && g > 0) { - if (length2 + g + 1 > width) g = Math.max(1, width - length2); - t.push(value2.substring(i -= g, i + g)); - if ((length2 += g + 1) > width) break; - g = grouping[j = (j + 1) % grouping.length]; - } - return t.reverse().join(thousands); - }; -} -function formatNumerals(numerals) { - return function(value2) { - return value2.replace(/[0-9]/g, function(i) { - return numerals[+i]; - }); - }; -} -var re = /^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i; -function formatSpecifier(specifier) { - if (!(match = re.exec(specifier))) throw new Error("invalid format: " + specifier); - var match; - return new FormatSpecifier({ - fill: match[1], - align: match[2], - sign: match[3], - symbol: match[4], - zero: match[5], - width: match[6], - comma: match[7], - precision: match[8] && match[8].slice(1), - trim: match[9], - type: match[10] - }); -} -formatSpecifier.prototype = FormatSpecifier.prototype; -function FormatSpecifier(specifier) { - this.fill = specifier.fill === void 0 ? " " : specifier.fill + ""; - this.align = specifier.align === void 0 ? ">" : specifier.align + ""; - this.sign = specifier.sign === void 0 ? "-" : specifier.sign + ""; - this.symbol = specifier.symbol === void 0 ? "" : specifier.symbol + ""; - this.zero = !!specifier.zero; - this.width = specifier.width === void 0 ? void 0 : +specifier.width; - this.comma = !!specifier.comma; - this.precision = specifier.precision === void 0 ? void 0 : +specifier.precision; - this.trim = !!specifier.trim; - this.type = specifier.type === void 0 ? "" : specifier.type + ""; -} -FormatSpecifier.prototype.toString = function() { - return this.fill + this.align + this.sign + this.symbol + (this.zero ? "0" : "") + (this.width === void 0 ? "" : Math.max(1, this.width | 0)) + (this.comma ? "," : "") + (this.precision === void 0 ? "" : "." + Math.max(0, this.precision | 0)) + (this.trim ? "~" : "") + this.type; -}; -function formatTrim(s) { - out: for (var n = s.length, i = 1, i0 = -1, i1; i < n; ++i) { - switch (s[i]) { - case ".": - i0 = i1 = i; - break; - case "0": - if (i0 === 0) i0 = i; - i1 = i; - break; - default: - if (!+s[i]) break out; - if (i0 > 0) i0 = 0; - break; - } - } - return i0 > 0 ? s.slice(0, i0) + s.slice(i1 + 1) : s; -} -var prefixExponent; -function formatPrefixAuto(x, p) { - var d = formatDecimalParts(x, p); - if (!d) return x + ""; - var coefficient = d[0], exponent2 = d[1], i = exponent2 - (prefixExponent = Math.max(-8, Math.min(8, Math.floor(exponent2 / 3))) * 3) + 1, n = coefficient.length; - return i === n ? coefficient : i > n ? coefficient + new Array(i - n + 1).join("0") : i > 0 ? coefficient.slice(0, i) + "." + coefficient.slice(i) : "0." + new Array(1 - i).join("0") + formatDecimalParts(x, Math.max(0, p + i - 1))[0]; -} -function formatRounded(x, p) { - var d = formatDecimalParts(x, p); - if (!d) return x + ""; - var coefficient = d[0], exponent2 = d[1]; - return exponent2 < 0 ? "0." + new Array(-exponent2).join("0") + coefficient : coefficient.length > exponent2 + 1 ? coefficient.slice(0, exponent2 + 1) + "." + coefficient.slice(exponent2 + 1) : coefficient + new Array(exponent2 - coefficient.length + 2).join("0"); -} -const formatTypes = { - "%": function(x, p) { - return (x * 100).toFixed(p); - }, - "b": function(x) { - return Math.round(x).toString(2); - }, - "c": function(x) { - return x + ""; - }, - "d": formatDecimal, - "e": function(x, p) { - return x.toExponential(p); - }, - "f": function(x, p) { - return x.toFixed(p); - }, - "g": function(x, p) { - return x.toPrecision(p); - }, - "o": function(x) { - return Math.round(x).toString(8); - }, - "p": function(x, p) { - return formatRounded(x * 100, p); - }, - "r": formatRounded, - "s": formatPrefixAuto, - "X": function(x) { - return Math.round(x).toString(16).toUpperCase(); - }, - "x": function(x) { - return Math.round(x).toString(16); - } -}; -function identity$5(x) { - return x; -} -var map = Array.prototype.map, prefixes = ["y", "z", "a", "f", "p", "n", "µ", "m", "", "k", "M", "G", "T", "P", "E", "Z", "Y"]; -function formatLocale$1(locale2) { - var group = locale2.grouping === void 0 || locale2.thousands === void 0 ? identity$5 : formatGroup(map.call(locale2.grouping, Number), locale2.thousands + ""), currencyPrefix = locale2.currency === void 0 ? "" : locale2.currency[0] + "", currencySuffix = locale2.currency === void 0 ? "" : locale2.currency[1] + "", decimal = locale2.decimal === void 0 ? "." : locale2.decimal + "", numerals = locale2.numerals === void 0 ? identity$5 : formatNumerals(map.call(locale2.numerals, String)), percent = locale2.percent === void 0 ? "%" : locale2.percent + "", minus = locale2.minus === void 0 ? "-" : locale2.minus + "", nan = locale2.nan === void 0 ? "NaN" : locale2.nan + ""; - function newFormat(specifier) { - specifier = formatSpecifier(specifier); - var fill = specifier.fill, align3 = specifier.align, sign2 = specifier.sign, symbol = specifier.symbol, zero2 = specifier.zero, width = specifier.width, comma = specifier.comma, precision = specifier.precision, trim = specifier.trim, type = specifier.type; - if (type === "n") comma = true, type = "g"; - else if (!formatTypes[type]) precision === void 0 && (precision = 12), trim = true, type = "g"; - if (zero2 || fill === "0" && align3 === "=") zero2 = true, fill = "0", align3 = "="; - var prefix = symbol === "$" ? currencyPrefix : symbol === "#" && /[boxX]/.test(type) ? "0" + type.toLowerCase() : "", suffix = symbol === "$" ? currencySuffix : /[%p]/.test(type) ? percent : ""; - var formatType = formatTypes[type], maybeSuffix = /[defgprs%]/.test(type); - precision = precision === void 0 ? 6 : /[gprs]/.test(type) ? Math.max(1, Math.min(21, precision)) : Math.max(0, Math.min(20, precision)); - function format2(value2) { - var valuePrefix = prefix, valueSuffix = suffix, i, n, c; - if (type === "c") { - valueSuffix = formatType(value2) + valueSuffix; - value2 = ""; - } else { - value2 = +value2; - var valueNegative = value2 < 0 || 1 / value2 < 0; - value2 = isNaN(value2) ? nan : formatType(Math.abs(value2), precision); - if (trim) value2 = formatTrim(value2); - if (valueNegative && +value2 === 0 && sign2 !== "+") valueNegative = false; - valuePrefix = (valueNegative ? sign2 === "(" ? sign2 : minus : sign2 === "-" || sign2 === "(" ? "" : sign2) + valuePrefix; - valueSuffix = (type === "s" ? prefixes[8 + prefixExponent / 3] : "") + valueSuffix + (valueNegative && sign2 === "(" ? ")" : ""); - if (maybeSuffix) { - i = -1, n = value2.length; - while (++i < n) { - if (c = value2.charCodeAt(i), 48 > c || c > 57) { - valueSuffix = (c === 46 ? decimal + value2.slice(i + 1) : value2.slice(i)) + valueSuffix; - value2 = value2.slice(0, i); - break; - } - } - } - } - if (comma && !zero2) value2 = group(value2, Infinity); - var length2 = valuePrefix.length + value2.length + valueSuffix.length, padding = length2 < width ? new Array(width - length2 + 1).join(fill) : ""; - if (comma && zero2) value2 = group(padding + value2, padding.length ? width - valueSuffix.length : Infinity), padding = ""; - switch (align3) { - case "<": - value2 = valuePrefix + value2 + valueSuffix + padding; - break; - case "=": - value2 = valuePrefix + padding + value2 + valueSuffix; - break; - case "^": - value2 = padding.slice(0, length2 = padding.length >> 1) + valuePrefix + value2 + valueSuffix + padding.slice(length2); - break; - default: - value2 = padding + valuePrefix + value2 + valueSuffix; - break; - } - return numerals(value2); - } - format2.toString = function() { - return specifier + ""; - }; - return format2; - } - function formatPrefix2(specifier, value2) { - var f = newFormat((specifier = formatSpecifier(specifier), specifier.type = "f", specifier)), e = Math.max(-8, Math.min(8, Math.floor(exponent(value2) / 3))) * 3, k = Math.pow(10, -e), prefix = prefixes[8 + e / 3]; - return function(value3) { - return f(k * value3) + prefix; - }; - } - return { - format: newFormat, - formatPrefix: formatPrefix2 - }; -} -var locale; -var format$2; -var formatPrefix; -defaultLocale({ - decimal: ".", - thousands: ",", - grouping: [3], - currency: ["$", ""], - minus: "-" -}); -function defaultLocale(definition) { - locale = formatLocale$1(definition); - format$2 = locale.format; - formatPrefix = locale.formatPrefix; - return locale; -} -function precisionFixed(step) { - return Math.max(0, -exponent(Math.abs(step))); -} -function precisionPrefix(step, value2) { - return Math.max(0, Math.max(-8, Math.min(8, Math.floor(exponent(value2) / 3))) * 3 - exponent(Math.abs(step))); -} -function precisionRound(step, max) { - step = Math.abs(step), max = Math.abs(max) - step; - return Math.max(0, exponent(max) - exponent(step)) + 1; -} -const src$2 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - FormatSpecifier, - get format() { - return format$2; - }, - formatDefaultLocale: defaultLocale, - formatLocale: formatLocale$1, - get formatPrefix() { - return formatPrefix; - }, - formatSpecifier, - precisionFixed, - precisionPrefix, - precisionRound -}, Symbol.toStringTag, { value: "Module" })); -const require$$2$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$2); -var isStringBlank = function(str2) { - var l = str2.length, a; - for (var i = 0; i < l; i++) { - a = str2.charCodeAt(i); - if ((a < 9 || a > 13) && a !== 32 && a !== 133 && a !== 160 && a !== 5760 && a !== 6158 && (a < 8192 || a > 8205) && a !== 8232 && a !== 8233 && a !== 8239 && a !== 8287 && a !== 8288 && a !== 12288 && a !== 65279) { - return false; - } - } - return true; -}; -var allBlankCharCodes = isStringBlank; -var fastIsnumeric = function(n) { - var type = typeof n; - if (type === "string") { - var original = n; - n = +n; - if (n === 0 && allBlankCharCodes(original)) return false; - } else if (type !== "number") return false; - return n - n < 1; -}; -var numerical = { - /** - * Standardize all missing data in calcdata to use undefined - * never null or NaN. - * That way we can use !==undefined, or !== BADNUM, - * to test for real data - */ - BADNUM: void 0, - /* - * Limit certain operations to well below floating point max value - * to avoid glitches: Make sure that even when you multiply it by the - * number of pixels on a giant screen it still works - */ - FP_SAFE: Number.MAX_VALUE * 1e-4, - /* - * conversion of date units to milliseconds - * year and month constants are marked "AVG" - * to remind us that not all years and months - * have the same length - */ - ONEMAXYEAR: 316224e5, - // 366 * ONEDAY - ONEAVGYEAR: 315576e5, - // 365.25 days - ONEMINYEAR: 31536e6, - // 365 * ONEDAY - ONEMAXQUARTER: 79488e5, - // 92 * ONEDAY - ONEAVGQUARTER: 78894e5, - // 1/4 of ONEAVGYEAR - ONEMINQUARTER: 76896e5, - // 89 * ONEDAY - ONEMAXMONTH: 26784e5, - // 31 * ONEDAY - ONEAVGMONTH: 26298e5, - // 1/12 of ONEAVGYEAR - ONEMINMONTH: 24192e5, - // 28 * ONEDAY - ONEWEEK: 6048e5, - // 7 * ONEDAY - ONEDAY: 864e5, - // 24 * ONEHOUR - ONEHOUR: 36e5, - ONEMIN: 6e4, - ONESEC: 1e3, - ONEMILLI: 1, - ONEMICROSEC: 1e-3, - /* - * For fast conversion btwn world calendars and epoch ms, the Julian Day Number - * of the unix epoch. From calendars.instance().newDate(1970, 1, 1).toJD() - */ - EPOCHJD: 24405875e-1, - /* - * Are two values nearly equal? Compare to 1PPM - */ - ALMOST_EQUAL: 1 - 1e-6, - /* - * If we're asked to clip a non-positive log value, how far off-screen - * do we put it? - */ - LOG_CLIP: 10, - /* - * not a number, but for displaying numbers: the "minus sign" symbol is - * wider than the regular ascii dash "-" - */ - MINUS_SIGN: "−" -}; -var array$2 = {}; -var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -var lookup$1 = typeof Uint8Array === "undefined" ? [] : new Uint8Array(256); -for (var i$1 = 0; i$1 < chars.length; i$1++) { - lookup$1[chars.charCodeAt(i$1)] = i$1; -} -var encode = function(arraybuffer) { - var bytes = new Uint8Array(arraybuffer), i, len = bytes.length, base64 = ""; - for (i = 0; i < len; i += 3) { - base64 += chars[bytes[i] >> 2]; - base64 += chars[(bytes[i] & 3) << 4 | bytes[i + 1] >> 4]; - base64 += chars[(bytes[i + 1] & 15) << 2 | bytes[i + 2] >> 6]; - base64 += chars[bytes[i + 2] & 63]; - } - if (len % 3 === 2) { - base64 = base64.substring(0, base64.length - 1) + "="; - } else if (len % 3 === 1) { - base64 = base64.substring(0, base64.length - 2) + "=="; - } - return base64; -}; -var decode = function(base64) { - var bufferLength = base64.length * 0.75, len = base64.length, i, p = 0, encoded1, encoded2, encoded3, encoded4; - if (base64[base64.length - 1] === "=") { - bufferLength--; - if (base64[base64.length - 2] === "=") { - bufferLength--; - } - } - var arraybuffer = new ArrayBuffer(bufferLength), bytes = new Uint8Array(arraybuffer); - for (i = 0; i < len; i += 4) { - encoded1 = lookup$1[base64.charCodeAt(i)]; - encoded2 = lookup$1[base64.charCodeAt(i + 1)]; - encoded3 = lookup$1[base64.charCodeAt(i + 2)]; - encoded4 = lookup$1[base64.charCodeAt(i + 3)]; - bytes[p++] = encoded1 << 2 | encoded2 >> 4; - bytes[p++] = (encoded2 & 15) << 4 | encoded3 >> 2; - bytes[p++] = (encoded3 & 3) << 6 | encoded4 & 63; - } - return arraybuffer; -}; -const base64Arraybuffer_es5 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - decode, - encode -}, Symbol.toStringTag, { value: "Module" })); -const require$$4$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(base64Arraybuffer_es5); -var is_plain_object = function isPlainObject(obj) { - if (window && window.process && window.process.versions) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } - return Object.prototype.toString.call(obj) === "[object Object]" && Object.getPrototypeOf(obj).hasOwnProperty("hasOwnProperty"); -}; -var b64decode = require$$4$1.decode; -var isPlainObject$6 = is_plain_object; -var isArray$2 = Array.isArray; -var ab = ArrayBuffer; -var dv = DataView; -function isTypedArray$1(a) { - return ab.isView(a) && !(a instanceof dv); -} -array$2.isTypedArray = isTypedArray$1; -function isArrayOrTypedArray$c(a) { - return isArray$2(a) || isTypedArray$1(a); -} -array$2.isArrayOrTypedArray = isArrayOrTypedArray$c; -function isArray1D(a) { - return !isArrayOrTypedArray$c(a[0]); -} -array$2.isArray1D = isArray1D; -array$2.ensureArray = function(out, n) { - if (!isArray$2(out)) out = []; - out.length = n; - return out; -}; -var typedArrays = { - u1c: typeof Uint8ClampedArray === "undefined" ? void 0 : Uint8ClampedArray, - // not supported in numpy? - i1: typeof Int8Array === "undefined" ? void 0 : Int8Array, - u1: typeof Uint8Array === "undefined" ? void 0 : Uint8Array, - i2: typeof Int16Array === "undefined" ? void 0 : Int16Array, - u2: typeof Uint16Array === "undefined" ? void 0 : Uint16Array, - i4: typeof Int32Array === "undefined" ? void 0 : Int32Array, - u4: typeof Uint32Array === "undefined" ? void 0 : Uint32Array, - f4: typeof Float32Array === "undefined" ? void 0 : Float32Array, - f8: typeof Float64Array === "undefined" ? void 0 : Float64Array - /* TODO: potentially add Big Int - - i8: typeof BigInt64Array === 'undefined' ? undefined : - BigInt64Array, - - u8: typeof BigUint64Array === 'undefined' ? undefined : - BigUint64Array, - */ -}; -typedArrays.uint8c = typedArrays.u1c; -typedArrays.uint8 = typedArrays.u1; -typedArrays.int8 = typedArrays.i1; -typedArrays.uint16 = typedArrays.u2; -typedArrays.int16 = typedArrays.i2; -typedArrays.uint32 = typedArrays.u4; -typedArrays.int32 = typedArrays.i4; -typedArrays.float32 = typedArrays.f4; -typedArrays.float64 = typedArrays.f8; -function isArrayBuffer(a) { - return a.constructor === ArrayBuffer; -} -array$2.isArrayBuffer = isArrayBuffer; -array$2.decodeTypedArraySpec = function(vIn) { - var out = []; - var v = coerceTypedArraySpec(vIn); - var dtype2 = v.dtype; - var T = typedArrays[dtype2]; - if (!T) throw new Error('Error in dtype: "' + dtype2 + '"'); - var BYTES_PER_ELEMENT = T.BYTES_PER_ELEMENT; - var buffer2 = v.bdata; - if (!isArrayBuffer(buffer2)) { - buffer2 = b64decode(buffer2); - } - var shape = v.shape === void 0 ? ( - // detect 1-d length - [buffer2.byteLength / BYTES_PER_ELEMENT] - ) : ( - // convert number to string and split to array - ("" + v.shape).split(",") - ); - shape.reverse(); - var ndim = shape.length; - var nj, j; - var ni = +shape[0]; - var rowBytes = BYTES_PER_ELEMENT * ni; - var pos = 0; - if (ndim === 1) { - out = new T(buffer2); - } else if (ndim === 2) { - nj = +shape[1]; - for (j = 0; j < nj; j++) { - out[j] = new T(buffer2, pos, ni); - pos += rowBytes; - } - } else if (ndim === 3) { - nj = +shape[1]; - var nk = +shape[2]; - for (var k = 0; k < nk; k++) { - out[k] = []; - for (j = 0; j < nj; j++) { - out[k][j] = new T(buffer2, pos, ni); - pos += rowBytes; - } - } - } else { - throw new Error("ndim: " + ndim + 'is not supported with the shape:"' + v.shape + '"'); - } - out.bdata = v.bdata; - out.dtype = v.dtype; - out.shape = shape.reverse().join(","); - vIn._inputArray = out; - return out; -}; -array$2.isTypedArraySpec = function(v) { - return isPlainObject$6(v) && v.hasOwnProperty("dtype") && typeof v.dtype === "string" && v.hasOwnProperty("bdata") && (typeof v.bdata === "string" || isArrayBuffer(v.bdata)) && (v.shape === void 0 || v.hasOwnProperty("shape") && (typeof v.shape === "string" || typeof v.shape === "number")); -}; -function coerceTypedArraySpec(v) { - return { - bdata: v.bdata, - dtype: v.dtype, - shape: v.shape - }; -} -array$2.concat = function() { - var args = []; - var allArray = true; - var totalLen = 0; - var _constructor, arg0, i, argi, posi, leni, out, j; - for (i = 0; i < arguments.length; i++) { - argi = arguments[i]; - leni = argi.length; - if (leni) { - if (arg0) args.push(argi); - else { - arg0 = argi; - posi = leni; - } - if (isArray$2(argi)) { - _constructor = false; - } else { - allArray = false; - if (!totalLen) { - _constructor = argi.constructor; - } else if (_constructor !== argi.constructor) { - _constructor = false; - } - } - totalLen += leni; - } - } - if (!totalLen) return []; - if (!args.length) return arg0; - if (allArray) return arg0.concat.apply(arg0, args); - if (_constructor) { - out = new _constructor(totalLen); - out.set(arg0); - for (i = 0; i < args.length; i++) { - argi = args[i]; - out.set(argi, posi); - posi += argi.length; - } - return out; - } - out = new Array(totalLen); - for (j = 0; j < arg0.length; j++) out[j] = arg0[j]; - for (i = 0; i < args.length; i++) { - argi = args[i]; - for (j = 0; j < argi.length; j++) out[posi + j] = argi[j]; - posi += j; - } - return out; -}; -array$2.maxRowLength = function(z) { - return _rowLength(z, Math.max, 0); -}; -array$2.minRowLength = function(z) { - return _rowLength(z, Math.min, Infinity); -}; -function _rowLength(z, fn, len0) { - if (isArrayOrTypedArray$c(z)) { - if (isArrayOrTypedArray$c(z[0])) { - var len = len0; - for (var i = 0; i < z.length; i++) { - len = fn(len, z[i].length); - } - return len; - } else { - return z.length; - } - } - return 0; -} -var isNumeric$B = fastIsnumeric; -var isArrayOrTypedArray$b = array$2.isArrayOrTypedArray; -var nested_property = function nestedProperty(container, propStr) { - if (isNumeric$B(propStr)) propStr = String(propStr); - else if (typeof propStr !== "string" || propStr.substr(propStr.length - 4) === "[-1]") { - throw "bad property string"; - } - var propParts = propStr.split("."); - var indexed; - var indices; - var i, j; - for (j = 0; j < propParts.length; j++) { - if (String(propParts[j]).slice(0, 2) === "__") { - throw "bad property string"; - } - } - j = 0; - while (j < propParts.length) { - indexed = String(propParts[j]).match(/^([^\[\]]*)((\[\-?[0-9]*\])+)$/); - if (indexed) { - if (indexed[1]) propParts[j] = indexed[1]; - else if (j === 0) propParts.splice(0, 1); - else throw "bad property string"; - indices = indexed[2].substr(1, indexed[2].length - 2).split("]["); - for (i = 0; i < indices.length; i++) { - j++; - propParts.splice(j, 0, Number(indices[i])); - } - } - j++; - } - if (typeof container !== "object") { - return badContainer(container, propStr, propParts); - } - return { - set: npSet(container, propParts, propStr), - get: npGet(container, propParts), - astr: propStr, - parts: propParts, - obj: container - }; -}; -function npGet(cont, parts) { - return function() { - var curCont = cont; - var curPart; - var allSame; - var out; - var i; - var j; - for (i = 0; i < parts.length - 1; i++) { - curPart = parts[i]; - if (curPart === -1) { - allSame = true; - out = []; - for (j = 0; j < curCont.length; j++) { - out[j] = npGet(curCont[j], parts.slice(i + 1))(); - if (out[j] !== out[0]) allSame = false; - } - return allSame ? out[0] : out; - } - if (typeof curPart === "number" && !isArrayOrTypedArray$b(curCont)) { - return void 0; - } - curCont = curCont[curPart]; - if (typeof curCont !== "object" || curCont === null) { - return void 0; - } - } - if (typeof curCont !== "object" || curCont === null) return void 0; - out = curCont[parts[i]]; - if (out === null) return void 0; - return out; - }; -} -var ARGS_PATTERN = /(^|\.)args\[/; -function isDeletable(val, propStr) { - return val === void 0 || val === null && !propStr.match(ARGS_PATTERN); -} -function npSet(cont, parts, propStr) { - return function(val) { - var curCont = cont; - var propPart = ""; - var toDelete = isDeletable(val, propStr); - var curPart; - var i; - for (i = 0; i < parts.length - 1; i++) { - curPart = parts[i]; - if (typeof curPart === "number" && !isArrayOrTypedArray$b(curCont)) { - throw "array index but container is not an array"; - } - if (curPart === -1) { - toDelete = !setArrayAll(curCont, parts.slice(i + 1), val, propStr); - if (toDelete) break; - else return; - } - if (!checkNewContainer(curCont, curPart, parts[i + 1], toDelete)) { - break; - } - curCont = curCont[curPart]; - if (typeof curCont !== "object" || curCont === null) { - throw "container is not an object"; - } - propPart = joinPropStr(propPart, curPart); - } - if (toDelete) { - if (i === parts.length - 1) { - delete curCont[parts[i]]; - if (Array.isArray(curCont) && +parts[i] === curCont.length - 1) { - while (curCont.length && curCont[curCont.length - 1] === void 0) { - curCont.pop(); - } - } - } - } else curCont[parts[i]] = val; - }; -} -function joinPropStr(propStr, newPart) { - var toAdd = newPart; - if (isNumeric$B(newPart)) toAdd = "[" + newPart + "]"; - else if (propStr) toAdd = "." + newPart; - return propStr + toAdd; -} -function setArrayAll(containerArray, innerParts, val, propStr) { - var arrayVal = isArrayOrTypedArray$b(val); - var allSet = true; - var thisVal = val; - var thisPropStr = propStr.replace("-1", 0); - var deleteThis = arrayVal ? false : isDeletable(val, thisPropStr); - var firstPart = innerParts[0]; - var i; - for (i = 0; i < containerArray.length; i++) { - thisPropStr = propStr.replace("-1", i); - if (arrayVal) { - thisVal = val[i % val.length]; - deleteThis = isDeletable(thisVal, thisPropStr); - } - if (deleteThis) allSet = false; - if (!checkNewContainer(containerArray, i, firstPart, deleteThis)) { - continue; - } - npSet(containerArray[i], innerParts, propStr.replace("-1", i))(thisVal); - } - return allSet; -} -function checkNewContainer(container, part, nextPart, toDelete) { - if (container[part] === void 0) { - if (toDelete) return false; - if (typeof nextPart === "number") container[part] = []; - else container[part] = {}; - } - return true; -} -function badContainer(container, propStr, propParts) { - return { - set: function() { - throw "bad container"; - }, - get: function() { - }, - astr: propStr, - parts: propParts, - obj: container - }; -} -var nestedProperty$1 = nested_property; -var SIMPLE_PROPERTY_REGEX$1 = /^\w*$/; -var NONE = 0; -var NAME = 1; -var VALUE = 2; -var BOTH = 3; -var UNSET = 4; -var keyed_container = function keyedContainer(baseObj, path, keyName, valueName) { - keyName = keyName || "name"; - valueName = valueName || "value"; - var i, arr, baseProp; - var changeTypes = {}; - if (path && path.length) { - baseProp = nestedProperty$1(baseObj, path); - arr = baseProp.get(); - } else { - arr = baseObj; - } - path = path || ""; - var indexLookup = {}; - if (arr) { - for (i = 0; i < arr.length; i++) { - indexLookup[arr[i][keyName]] = i; - } - } - var isSimpleValueProp = SIMPLE_PROPERTY_REGEX$1.test(valueName); - var obj = { - set: function(name2, value2) { - var changeType = value2 === null ? UNSET : NONE; - if (!arr) { - if (!baseProp || changeType === UNSET) return; - arr = []; - baseProp.set(arr); - } - var idx = indexLookup[name2]; - if (idx === void 0) { - if (changeType === UNSET) return; - changeType = changeType | BOTH; - idx = arr.length; - indexLookup[name2] = idx; - } else if (value2 !== (isSimpleValueProp ? arr[idx][valueName] : nestedProperty$1(arr[idx], valueName).get())) { - changeType = changeType | VALUE; - } - var newValue = arr[idx] = arr[idx] || {}; - newValue[keyName] = name2; - if (isSimpleValueProp) { - newValue[valueName] = value2; - } else { - nestedProperty$1(newValue, valueName).set(value2); - } - if (value2 !== null) { - changeType = changeType & -5; - } - changeTypes[idx] = changeTypes[idx] | changeType; - return obj; - }, - get: function(name2) { - if (!arr) return; - var idx = indexLookup[name2]; - if (idx === void 0) { - return void 0; - } else if (isSimpleValueProp) { - return arr[idx][valueName]; - } else { - return nestedProperty$1(arr[idx], valueName).get(); - } - }, - rename: function(name2, newName) { - var idx = indexLookup[name2]; - if (idx === void 0) return obj; - changeTypes[idx] = changeTypes[idx] | NAME; - indexLookup[newName] = idx; - delete indexLookup[name2]; - arr[idx][keyName] = newName; - return obj; - }, - remove: function(name2) { - var idx = indexLookup[name2]; - if (idx === void 0) return obj; - var object2 = arr[idx]; - if (Object.keys(object2).length > 2) { - changeTypes[idx] = changeTypes[idx] | VALUE; - return obj.set(name2, null); - } - if (isSimpleValueProp) { - for (i = idx; i < arr.length; i++) { - changeTypes[i] = changeTypes[i] | BOTH; - } - for (i = idx; i < arr.length; i++) { - indexLookup[arr[i][keyName]]--; - } - arr.splice(idx, 1); - delete indexLookup[name2]; - } else { - nestedProperty$1(object2, valueName).set(null); - changeTypes[idx] = changeTypes[idx] | VALUE | UNSET; - } - return obj; - }, - constructUpdate: function() { - var astr, idx; - var update2 = {}; - var changed = Object.keys(changeTypes); - for (var i2 = 0; i2 < changed.length; i2++) { - idx = changed[i2]; - astr = path + "[" + idx + "]"; - if (arr[idx]) { - if (changeTypes[idx] & NAME) { - update2[astr + "." + keyName] = arr[idx][keyName]; - } - if (changeTypes[idx] & VALUE) { - if (isSimpleValueProp) { - update2[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : arr[idx][valueName]; - } else { - update2[astr + "." + valueName] = changeTypes[idx] & UNSET ? null : nestedProperty$1(arr[idx], valueName).get(); - } - } - } else { - update2[astr] = null; - } - } - return update2; - } - }; - return obj; -}; -var ASCEND = /^(.*)(\.[^\.\[\]]+|\[\d\])$/; -var SIMPLEATTR = /^[^\.\[\]]+$/; -var relative_attr = function(baseAttr, relativeAttr) { - while (relativeAttr) { - var match = baseAttr.match(ASCEND); - if (match) baseAttr = match[1]; - else if (baseAttr.match(SIMPLEATTR)) baseAttr = ""; - else throw new Error("bad relativeAttr call:" + [baseAttr, relativeAttr]); - if (relativeAttr.charAt(0) === "^") relativeAttr = relativeAttr.slice(1); - else break; - } - if (baseAttr && relativeAttr.charAt(0) !== "[") { - return baseAttr + "." + relativeAttr; - } - return baseAttr + relativeAttr; -}; -var isNumeric$A = fastIsnumeric; -var to_log_range = function toLogRange(val, range) { - if (val > 0) return Math.log(val) / Math.LN10; - var newVal = Math.log(Math.min(range[0], range[1])) / Math.LN10; - if (!isNumeric$A(newVal)) newVal = Math.log(Math.max(range[0], range[1])) / Math.LN10 - 6; - return newVal; -}; -var isArrayOrTypedArray$a = array$2.isArrayOrTypedArray; -var isPlainObject$5 = is_plain_object; -var relink_private = function relinkPrivateKeys(toContainer, fromContainer) { - for (var k in fromContainer) { - var fromVal = fromContainer[k]; - var toVal = toContainer[k]; - if (toVal === fromVal) continue; - if (k.charAt(0) === "_" || typeof fromVal === "function") { - if (k in toContainer) continue; - toContainer[k] = fromVal; - } else if (isArrayOrTypedArray$a(fromVal) && isArrayOrTypedArray$a(toVal) && isPlainObject$5(fromVal[0])) { - if (k === "customdata" || k === "ids") continue; - var minLen = Math.min(fromVal.length, toVal.length); - for (var j = 0; j < minLen; j++) { - if (toVal[j] !== fromVal[j] && isPlainObject$5(fromVal[j]) && isPlainObject$5(toVal[j])) { - relinkPrivateKeys(toVal[j], fromVal[j]); - } - } - } else if (isPlainObject$5(fromVal) && isPlainObject$5(toVal)) { - relinkPrivateKeys(toVal, fromVal); - if (!Object.keys(toVal).length) delete toContainer[k]; - } - } -}; -function mod$2(v, d) { - var out = v % d; - return out < 0 ? out + d : out; -} -function modHalf$1(v, d) { - return Math.abs(v) > d / 2 ? v - Math.round(v / d) * d : v; -} -var mod_1 = { - mod: mod$2, - modHalf: modHalf$1 -}; -var coerce$1 = {}; -var tinycolor$8 = { exports: {} }; -(function(module2, exports2) { - (function(global, factory2) { - module2.exports = factory2(); - })(index$3.commonjsGlobal, function() { - function _typeof(obj) { - "@babel/helpers - typeof"; - return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function(obj2) { - return typeof obj2; - } : function(obj2) { - return obj2 && "function" == typeof Symbol && obj2.constructor === Symbol && obj2 !== Symbol.prototype ? "symbol" : typeof obj2; - }, _typeof(obj); - } - var trimLeft = /^\s+/; - var trimRight = /\s+$/; - function tinycolor2(color2, opts) { - color2 = color2 ? color2 : ""; - opts = opts || {}; - if (color2 instanceof tinycolor2) { - return color2; - } - if (!(this instanceof tinycolor2)) { - return new tinycolor2(color2, opts); - } - var rgb2 = inputToRGB(color2); - this._originalInput = color2, this._r = rgb2.r, this._g = rgb2.g, this._b = rgb2.b, this._a = rgb2.a, this._roundA = Math.round(100 * this._a) / 100, this._format = opts.format || rgb2.format; - this._gradientType = opts.gradientType; - if (this._r < 1) this._r = Math.round(this._r); - if (this._g < 1) this._g = Math.round(this._g); - if (this._b < 1) this._b = Math.round(this._b); - this._ok = rgb2.ok; - } - tinycolor2.prototype = { - isDark: function isDark() { - return this.getBrightness() < 128; - }, - isLight: function isLight() { - return !this.isDark(); - }, - isValid: function isValid() { - return this._ok; - }, - getOriginalInput: function getOriginalInput() { - return this._originalInput; - }, - getFormat: function getFormat() { - return this._format; - }, - getAlpha: function getAlpha() { - return this._a; - }, - getBrightness: function getBrightness() { - var rgb2 = this.toRgb(); - return (rgb2.r * 299 + rgb2.g * 587 + rgb2.b * 114) / 1e3; - }, - getLuminance: function getLuminance() { - var rgb2 = this.toRgb(); - var RsRGB, GsRGB, BsRGB, R2, G, B2; - RsRGB = rgb2.r / 255; - GsRGB = rgb2.g / 255; - BsRGB = rgb2.b / 255; - if (RsRGB <= 0.03928) R2 = RsRGB / 12.92; - else R2 = Math.pow((RsRGB + 0.055) / 1.055, 2.4); - if (GsRGB <= 0.03928) G = GsRGB / 12.92; - else G = Math.pow((GsRGB + 0.055) / 1.055, 2.4); - if (BsRGB <= 0.03928) B2 = BsRGB / 12.92; - else B2 = Math.pow((BsRGB + 0.055) / 1.055, 2.4); - return 0.2126 * R2 + 0.7152 * G + 0.0722 * B2; - }, - setAlpha: function setAlpha(value2) { - this._a = boundAlpha(value2); - this._roundA = Math.round(100 * this._a) / 100; - return this; - }, - toHsv: function toHsv() { - var hsv = rgbToHsv(this._r, this._g, this._b); - return { - h: hsv.h * 360, - s: hsv.s, - v: hsv.v, - a: this._a - }; - }, - toHsvString: function toHsvString() { - var hsv = rgbToHsv(this._r, this._g, this._b); - var h = Math.round(hsv.h * 360), s = Math.round(hsv.s * 100), v = Math.round(hsv.v * 100); - return this._a == 1 ? "hsv(" + h + ", " + s + "%, " + v + "%)" : "hsva(" + h + ", " + s + "%, " + v + "%, " + this._roundA + ")"; - }, - toHsl: function toHsl() { - var hsl2 = rgbToHsl(this._r, this._g, this._b); - return { - h: hsl2.h * 360, - s: hsl2.s, - l: hsl2.l, - a: this._a - }; - }, - toHslString: function toHslString() { - var hsl2 = rgbToHsl(this._r, this._g, this._b); - var h = Math.round(hsl2.h * 360), s = Math.round(hsl2.s * 100), l = Math.round(hsl2.l * 100); - return this._a == 1 ? "hsl(" + h + ", " + s + "%, " + l + "%)" : "hsla(" + h + ", " + s + "%, " + l + "%, " + this._roundA + ")"; - }, - toHex: function toHex(allow3Char) { - return rgbToHex(this._r, this._g, this._b, allow3Char); - }, - toHexString: function toHexString(allow3Char) { - return "#" + this.toHex(allow3Char); - }, - toHex8: function toHex8(allow4Char) { - return rgbaToHex(this._r, this._g, this._b, this._a, allow4Char); - }, - toHex8String: function toHex8String(allow4Char) { - return "#" + this.toHex8(allow4Char); - }, - toRgb: function toRgb() { - return { - r: Math.round(this._r), - g: Math.round(this._g), - b: Math.round(this._b), - a: this._a - }; - }, - toRgbString: function toRgbString() { - return this._a == 1 ? "rgb(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ")" : "rgba(" + Math.round(this._r) + ", " + Math.round(this._g) + ", " + Math.round(this._b) + ", " + this._roundA + ")"; - }, - toPercentageRgb: function toPercentageRgb() { - return { - r: Math.round(bound01(this._r, 255) * 100) + "%", - g: Math.round(bound01(this._g, 255) * 100) + "%", - b: Math.round(bound01(this._b, 255) * 100) + "%", - a: this._a - }; - }, - toPercentageRgbString: function toPercentageRgbString() { - return this._a == 1 ? "rgb(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%)" : "rgba(" + Math.round(bound01(this._r, 255) * 100) + "%, " + Math.round(bound01(this._g, 255) * 100) + "%, " + Math.round(bound01(this._b, 255) * 100) + "%, " + this._roundA + ")"; - }, - toName: function toName() { - if (this._a === 0) { - return "transparent"; - } - if (this._a < 1) { - return false; - } - return hexNames[rgbToHex(this._r, this._g, this._b, true)] || false; - }, - toFilter: function toFilter(secondColor) { - var hex8String = "#" + rgbaToArgbHex(this._r, this._g, this._b, this._a); - var secondHex8String = hex8String; - var gradientType = this._gradientType ? "GradientType = 1, " : ""; - if (secondColor) { - var s = tinycolor2(secondColor); - secondHex8String = "#" + rgbaToArgbHex(s._r, s._g, s._b, s._a); - } - return "progid:DXImageTransform.Microsoft.gradient(" + gradientType + "startColorstr=" + hex8String + ",endColorstr=" + secondHex8String + ")"; - }, - toString: function toString2(format2) { - var formatSet = !!format2; - format2 = format2 || this._format; - var formattedString = false; - var hasAlpha = this._a < 1 && this._a >= 0; - var needsAlphaFormat = !formatSet && hasAlpha && (format2 === "hex" || format2 === "hex6" || format2 === "hex3" || format2 === "hex4" || format2 === "hex8" || format2 === "name"); - if (needsAlphaFormat) { - if (format2 === "name" && this._a === 0) { - return this.toName(); - } - return this.toRgbString(); - } - if (format2 === "rgb") { - formattedString = this.toRgbString(); - } - if (format2 === "prgb") { - formattedString = this.toPercentageRgbString(); - } - if (format2 === "hex" || format2 === "hex6") { - formattedString = this.toHexString(); - } - if (format2 === "hex3") { - formattedString = this.toHexString(true); - } - if (format2 === "hex4") { - formattedString = this.toHex8String(true); - } - if (format2 === "hex8") { - formattedString = this.toHex8String(); - } - if (format2 === "name") { - formattedString = this.toName(); - } - if (format2 === "hsl") { - formattedString = this.toHslString(); - } - if (format2 === "hsv") { - formattedString = this.toHsvString(); - } - return formattedString || this.toHexString(); - }, - clone: function clone2() { - return tinycolor2(this.toString()); - }, - _applyModification: function _applyModification(fn, args) { - var color2 = fn.apply(null, [this].concat([].slice.call(args))); - this._r = color2._r; - this._g = color2._g; - this._b = color2._b; - this.setAlpha(color2._a); - return this; - }, - lighten: function lighten() { - return this._applyModification(_lighten, arguments); - }, - brighten: function brighten() { - return this._applyModification(_brighten, arguments); - }, - darken: function darken() { - return this._applyModification(_darken, arguments); - }, - desaturate: function desaturate() { - return this._applyModification(_desaturate, arguments); - }, - saturate: function saturate() { - return this._applyModification(_saturate, arguments); - }, - greyscale: function greyscale() { - return this._applyModification(_greyscale, arguments); - }, - spin: function spin() { - return this._applyModification(_spin, arguments); - }, - _applyCombination: function _applyCombination(fn, args) { - return fn.apply(null, [this].concat([].slice.call(args))); - }, - analogous: function analogous() { - return this._applyCombination(_analogous, arguments); - }, - complement: function complement() { - return this._applyCombination(_complement, arguments); - }, - monochromatic: function monochromatic() { - return this._applyCombination(_monochromatic, arguments); - }, - splitcomplement: function splitcomplement() { - return this._applyCombination(_splitcomplement, arguments); - }, - // Disabled until https://github.com/bgrins/TinyColor/issues/254 - // polyad: function (number) { - // return this._applyCombination(polyad, [number]); - // }, - triad: function triad() { - return this._applyCombination(polyad, [3]); - }, - tetrad: function tetrad() { - return this._applyCombination(polyad, [4]); - } - }; - tinycolor2.fromRatio = function(color2, opts) { - if (_typeof(color2) == "object") { - var newColor = {}; - for (var i in color2) { - if (color2.hasOwnProperty(i)) { - if (i === "a") { - newColor[i] = color2[i]; - } else { - newColor[i] = convertToPercentage(color2[i]); - } - } - } - color2 = newColor; - } - return tinycolor2(color2, opts); - }; - function inputToRGB(color2) { - var rgb2 = { - r: 0, - g: 0, - b: 0 - }; - var a = 1; - var s = null; - var v = null; - var l = null; - var ok = false; - var format2 = false; - if (typeof color2 == "string") { - color2 = stringInputToObject(color2); - } - if (_typeof(color2) == "object") { - if (isValidCSSUnit(color2.r) && isValidCSSUnit(color2.g) && isValidCSSUnit(color2.b)) { - rgb2 = rgbToRgb(color2.r, color2.g, color2.b); - ok = true; - format2 = String(color2.r).substr(-1) === "%" ? "prgb" : "rgb"; - } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.v)) { - s = convertToPercentage(color2.s); - v = convertToPercentage(color2.v); - rgb2 = hsvToRgb(color2.h, s, v); - ok = true; - format2 = "hsv"; - } else if (isValidCSSUnit(color2.h) && isValidCSSUnit(color2.s) && isValidCSSUnit(color2.l)) { - s = convertToPercentage(color2.s); - l = convertToPercentage(color2.l); - rgb2 = hslToRgb(color2.h, s, l); - ok = true; - format2 = "hsl"; - } - if (color2.hasOwnProperty("a")) { - a = color2.a; - } - } - a = boundAlpha(a); - return { - ok, - format: color2.format || format2, - r: Math.min(255, Math.max(rgb2.r, 0)), - g: Math.min(255, Math.max(rgb2.g, 0)), - b: Math.min(255, Math.max(rgb2.b, 0)), - a - }; - } - function rgbToRgb(r, g, b) { - return { - r: bound01(r, 255) * 255, - g: bound01(g, 255) * 255, - b: bound01(b, 255) * 255 - }; - } - function rgbToHsl(r, g, b) { - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); - var max = Math.max(r, g, b), min = Math.min(r, g, b); - var h, s, l = (max + min) / 2; - if (max == min) { - h = s = 0; - } else { - var d = max - min; - s = l > 0.5 ? d / (2 - max - min) : d / (max + min); - switch (max) { - case r: - h = (g - b) / d + (g < b ? 6 : 0); - break; - case g: - h = (b - r) / d + 2; - break; - case b: - h = (r - g) / d + 4; - break; - } - h /= 6; - } - return { - h, - s, - l - }; - } - function hslToRgb(h, s, l) { - var r, g, b; - h = bound01(h, 360); - s = bound01(s, 100); - l = bound01(l, 100); - function hue2rgb(p2, q2, t) { - if (t < 0) t += 1; - if (t > 1) t -= 1; - if (t < 1 / 6) return p2 + (q2 - p2) * 6 * t; - if (t < 1 / 2) return q2; - if (t < 2 / 3) return p2 + (q2 - p2) * (2 / 3 - t) * 6; - return p2; - } - if (s === 0) { - r = g = b = l; - } else { - var q = l < 0.5 ? l * (1 + s) : l + s - l * s; - var p = 2 * l - q; - r = hue2rgb(p, q, h + 1 / 3); - g = hue2rgb(p, q, h); - b = hue2rgb(p, q, h - 1 / 3); - } - return { - r: r * 255, - g: g * 255, - b: b * 255 - }; - } - function rgbToHsv(r, g, b) { - r = bound01(r, 255); - g = bound01(g, 255); - b = bound01(b, 255); - var max = Math.max(r, g, b), min = Math.min(r, g, b); - var h, s, v = max; - var d = max - min; - s = max === 0 ? 0 : d / max; - if (max == min) { - h = 0; - } else { - switch (max) { - case r: - h = (g - b) / d + (g < b ? 6 : 0); - break; - case g: - h = (b - r) / d + 2; - break; - case b: - h = (r - g) / d + 4; - break; - } - h /= 6; - } - return { - h, - s, - v - }; - } - function hsvToRgb(h, s, v) { - h = bound01(h, 360) * 6; - s = bound01(s, 100); - v = bound01(v, 100); - var i = Math.floor(h), f = h - i, p = v * (1 - s), q = v * (1 - f * s), t = v * (1 - (1 - f) * s), mod2 = i % 6, r = [v, q, p, p, t, v][mod2], g = [t, v, v, q, p, p][mod2], b = [p, p, t, v, v, q][mod2]; - return { - r: r * 255, - g: g * 255, - b: b * 255 - }; - } - function rgbToHex(r, g, b, allow3Char) { - var hex2 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; - if (allow3Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1)) { - return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0); - } - return hex2.join(""); - } - function rgbaToHex(r, g, b, a, allow4Char) { - var hex2 = [pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16)), pad2(convertDecimalToHex(a))]; - if (allow4Char && hex2[0].charAt(0) == hex2[0].charAt(1) && hex2[1].charAt(0) == hex2[1].charAt(1) && hex2[2].charAt(0) == hex2[2].charAt(1) && hex2[3].charAt(0) == hex2[3].charAt(1)) { - return hex2[0].charAt(0) + hex2[1].charAt(0) + hex2[2].charAt(0) + hex2[3].charAt(0); - } - return hex2.join(""); - } - function rgbaToArgbHex(r, g, b, a) { - var hex2 = [pad2(convertDecimalToHex(a)), pad2(Math.round(r).toString(16)), pad2(Math.round(g).toString(16)), pad2(Math.round(b).toString(16))]; - return hex2.join(""); - } - tinycolor2.equals = function(color1, color2) { - if (!color1 || !color2) return false; - return tinycolor2(color1).toRgbString() == tinycolor2(color2).toRgbString(); - }; - tinycolor2.random = function() { - return tinycolor2.fromRatio({ - r: Math.random(), - g: Math.random(), - b: Math.random() - }); - }; - function _desaturate(color2, amount) { - amount = amount === 0 ? 0 : amount || 10; - var hsl2 = tinycolor2(color2).toHsl(); - hsl2.s -= amount / 100; - hsl2.s = clamp01(hsl2.s); - return tinycolor2(hsl2); - } - function _saturate(color2, amount) { - amount = amount === 0 ? 0 : amount || 10; - var hsl2 = tinycolor2(color2).toHsl(); - hsl2.s += amount / 100; - hsl2.s = clamp01(hsl2.s); - return tinycolor2(hsl2); - } - function _greyscale(color2) { - return tinycolor2(color2).desaturate(100); - } - function _lighten(color2, amount) { - amount = amount === 0 ? 0 : amount || 10; - var hsl2 = tinycolor2(color2).toHsl(); - hsl2.l += amount / 100; - hsl2.l = clamp01(hsl2.l); - return tinycolor2(hsl2); - } - function _brighten(color2, amount) { - amount = amount === 0 ? 0 : amount || 10; - var rgb2 = tinycolor2(color2).toRgb(); - rgb2.r = Math.max(0, Math.min(255, rgb2.r - Math.round(255 * -(amount / 100)))); - rgb2.g = Math.max(0, Math.min(255, rgb2.g - Math.round(255 * -(amount / 100)))); - rgb2.b = Math.max(0, Math.min(255, rgb2.b - Math.round(255 * -(amount / 100)))); - return tinycolor2(rgb2); - } - function _darken(color2, amount) { - amount = amount === 0 ? 0 : amount || 10; - var hsl2 = tinycolor2(color2).toHsl(); - hsl2.l -= amount / 100; - hsl2.l = clamp01(hsl2.l); - return tinycolor2(hsl2); - } - function _spin(color2, amount) { - var hsl2 = tinycolor2(color2).toHsl(); - var hue2 = (hsl2.h + amount) % 360; - hsl2.h = hue2 < 0 ? 360 + hue2 : hue2; - return tinycolor2(hsl2); - } - function _complement(color2) { - var hsl2 = tinycolor2(color2).toHsl(); - hsl2.h = (hsl2.h + 180) % 360; - return tinycolor2(hsl2); - } - function polyad(color2, number2) { - if (isNaN(number2) || number2 <= 0) { - throw new Error("Argument to polyad must be a positive number"); - } - var hsl2 = tinycolor2(color2).toHsl(); - var result = [tinycolor2(color2)]; - var step = 360 / number2; - for (var i = 1; i < number2; i++) { - result.push(tinycolor2({ - h: (hsl2.h + i * step) % 360, - s: hsl2.s, - l: hsl2.l - })); - } - return result; - } - function _splitcomplement(color2) { - var hsl2 = tinycolor2(color2).toHsl(); - var h = hsl2.h; - return [tinycolor2(color2), tinycolor2({ - h: (h + 72) % 360, - s: hsl2.s, - l: hsl2.l - }), tinycolor2({ - h: (h + 216) % 360, - s: hsl2.s, - l: hsl2.l - })]; - } - function _analogous(color2, results, slices) { - results = results || 6; - slices = slices || 30; - var hsl2 = tinycolor2(color2).toHsl(); - var part = 360 / slices; - var ret = [tinycolor2(color2)]; - for (hsl2.h = (hsl2.h - (part * results >> 1) + 720) % 360; --results; ) { - hsl2.h = (hsl2.h + part) % 360; - ret.push(tinycolor2(hsl2)); - } - return ret; - } - function _monochromatic(color2, results) { - results = results || 6; - var hsv = tinycolor2(color2).toHsv(); - var h = hsv.h, s = hsv.s, v = hsv.v; - var ret = []; - var modification = 1 / results; - while (results--) { - ret.push(tinycolor2({ - h, - s, - v - })); - v = (v + modification) % 1; - } - return ret; - } - tinycolor2.mix = function(color1, color2, amount) { - amount = amount === 0 ? 0 : amount || 50; - var rgb1 = tinycolor2(color1).toRgb(); - var rgb2 = tinycolor2(color2).toRgb(); - var p = amount / 100; - var rgba3 = { - r: (rgb2.r - rgb1.r) * p + rgb1.r, - g: (rgb2.g - rgb1.g) * p + rgb1.g, - b: (rgb2.b - rgb1.b) * p + rgb1.b, - a: (rgb2.a - rgb1.a) * p + rgb1.a - }; - return tinycolor2(rgba3); - }; - tinycolor2.readability = function(color1, color2) { - var c1 = tinycolor2(color1); - var c2 = tinycolor2(color2); - return (Math.max(c1.getLuminance(), c2.getLuminance()) + 0.05) / (Math.min(c1.getLuminance(), c2.getLuminance()) + 0.05); - }; - tinycolor2.isReadable = function(color1, color2, wcag2) { - var readability = tinycolor2.readability(color1, color2); - var wcag2Parms, out; - out = false; - wcag2Parms = validateWCAG2Parms(wcag2); - switch (wcag2Parms.level + wcag2Parms.size) { - case "AAsmall": - case "AAAlarge": - out = readability >= 4.5; - break; - case "AAlarge": - out = readability >= 3; - break; - case "AAAsmall": - out = readability >= 7; - break; - } - return out; - }; - tinycolor2.mostReadable = function(baseColor, colorList, args) { - var bestColor = null; - var bestScore = 0; - var readability; - var includeFallbackColors, level, size; - args = args || {}; - includeFallbackColors = args.includeFallbackColors; - level = args.level; - size = args.size; - for (var i = 0; i < colorList.length; i++) { - readability = tinycolor2.readability(baseColor, colorList[i]); - if (readability > bestScore) { - bestScore = readability; - bestColor = tinycolor2(colorList[i]); - } - } - if (tinycolor2.isReadable(baseColor, bestColor, { - level, - size - }) || !includeFallbackColors) { - return bestColor; - } else { - args.includeFallbackColors = false; - return tinycolor2.mostReadable(baseColor, ["#fff", "#000"], args); - } - }; - var names2 = tinycolor2.names = { - aliceblue: "f0f8ff", - antiquewhite: "faebd7", - aqua: "0ff", - aquamarine: "7fffd4", - azure: "f0ffff", - beige: "f5f5dc", - bisque: "ffe4c4", - black: "000", - blanchedalmond: "ffebcd", - blue: "00f", - blueviolet: "8a2be2", - brown: "a52a2a", - burlywood: "deb887", - burntsienna: "ea7e5d", - cadetblue: "5f9ea0", - chartreuse: "7fff00", - chocolate: "d2691e", - coral: "ff7f50", - cornflowerblue: "6495ed", - cornsilk: "fff8dc", - crimson: "dc143c", - cyan: "0ff", - darkblue: "00008b", - darkcyan: "008b8b", - darkgoldenrod: "b8860b", - darkgray: "a9a9a9", - darkgreen: "006400", - darkgrey: "a9a9a9", - darkkhaki: "bdb76b", - darkmagenta: "8b008b", - darkolivegreen: "556b2f", - darkorange: "ff8c00", - darkorchid: "9932cc", - darkred: "8b0000", - darksalmon: "e9967a", - darkseagreen: "8fbc8f", - darkslateblue: "483d8b", - darkslategray: "2f4f4f", - darkslategrey: "2f4f4f", - darkturquoise: "00ced1", - darkviolet: "9400d3", - deeppink: "ff1493", - deepskyblue: "00bfff", - dimgray: "696969", - dimgrey: "696969", - dodgerblue: "1e90ff", - firebrick: "b22222", - floralwhite: "fffaf0", - forestgreen: "228b22", - fuchsia: "f0f", - gainsboro: "dcdcdc", - ghostwhite: "f8f8ff", - gold: "ffd700", - goldenrod: "daa520", - gray: "808080", - green: "008000", - greenyellow: "adff2f", - grey: "808080", - honeydew: "f0fff0", - hotpink: "ff69b4", - indianred: "cd5c5c", - indigo: "4b0082", - ivory: "fffff0", - khaki: "f0e68c", - lavender: "e6e6fa", - lavenderblush: "fff0f5", - lawngreen: "7cfc00", - lemonchiffon: "fffacd", - lightblue: "add8e6", - lightcoral: "f08080", - lightcyan: "e0ffff", - lightgoldenrodyellow: "fafad2", - lightgray: "d3d3d3", - lightgreen: "90ee90", - lightgrey: "d3d3d3", - lightpink: "ffb6c1", - lightsalmon: "ffa07a", - lightseagreen: "20b2aa", - lightskyblue: "87cefa", - lightslategray: "789", - lightslategrey: "789", - lightsteelblue: "b0c4de", - lightyellow: "ffffe0", - lime: "0f0", - limegreen: "32cd32", - linen: "faf0e6", - magenta: "f0f", - maroon: "800000", - mediumaquamarine: "66cdaa", - mediumblue: "0000cd", - mediumorchid: "ba55d3", - mediumpurple: "9370db", - mediumseagreen: "3cb371", - mediumslateblue: "7b68ee", - mediumspringgreen: "00fa9a", - mediumturquoise: "48d1cc", - mediumvioletred: "c71585", - midnightblue: "191970", - mintcream: "f5fffa", - mistyrose: "ffe4e1", - moccasin: "ffe4b5", - navajowhite: "ffdead", - navy: "000080", - oldlace: "fdf5e6", - olive: "808000", - olivedrab: "6b8e23", - orange: "ffa500", - orangered: "ff4500", - orchid: "da70d6", - palegoldenrod: "eee8aa", - palegreen: "98fb98", - paleturquoise: "afeeee", - palevioletred: "db7093", - papayawhip: "ffefd5", - peachpuff: "ffdab9", - peru: "cd853f", - pink: "ffc0cb", - plum: "dda0dd", - powderblue: "b0e0e6", - purple: "800080", - rebeccapurple: "663399", - red: "f00", - rosybrown: "bc8f8f", - royalblue: "4169e1", - saddlebrown: "8b4513", - salmon: "fa8072", - sandybrown: "f4a460", - seagreen: "2e8b57", - seashell: "fff5ee", - sienna: "a0522d", - silver: "c0c0c0", - skyblue: "87ceeb", - slateblue: "6a5acd", - slategray: "708090", - slategrey: "708090", - snow: "fffafa", - springgreen: "00ff7f", - steelblue: "4682b4", - tan: "d2b48c", - teal: "008080", - thistle: "d8bfd8", - tomato: "ff6347", - turquoise: "40e0d0", - violet: "ee82ee", - wheat: "f5deb3", - white: "fff", - whitesmoke: "f5f5f5", - yellow: "ff0", - yellowgreen: "9acd32" - }; - var hexNames = tinycolor2.hexNames = flip(names2); - function flip(o) { - var flipped = {}; - for (var i in o) { - if (o.hasOwnProperty(i)) { - flipped[o[i]] = i; - } - } - return flipped; - } - function boundAlpha(a) { - a = parseFloat(a); - if (isNaN(a) || a < 0 || a > 1) { - a = 1; - } - return a; - } - function bound01(n, max) { - if (isOnePointZero(n)) n = "100%"; - var processPercent = isPercentage(n); - n = Math.min(max, Math.max(0, parseFloat(n))); - if (processPercent) { - n = parseInt(n * max, 10) / 100; - } - if (Math.abs(n - max) < 1e-6) { - return 1; - } - return n % max / parseFloat(max); - } - function clamp01(val) { - return Math.min(1, Math.max(0, val)); - } - function parseIntFromHex(val) { - return parseInt(val, 16); - } - function isOnePointZero(n) { - return typeof n == "string" && n.indexOf(".") != -1 && parseFloat(n) === 1; - } - function isPercentage(n) { - return typeof n === "string" && n.indexOf("%") != -1; - } - function pad2(c) { - return c.length == 1 ? "0" + c : "" + c; - } - function convertToPercentage(n) { - if (n <= 1) { - n = n * 100 + "%"; - } - return n; - } - function convertDecimalToHex(d) { - return Math.round(parseFloat(d) * 255).toString(16); - } - function convertHexToDecimal(h) { - return parseIntFromHex(h) / 255; - } - var matchers = function() { - var CSS_INTEGER = "[-\\+]?\\d+%?"; - var CSS_NUMBER = "[-\\+]?\\d*\\.\\d+%?"; - var CSS_UNIT = "(?:" + CSS_NUMBER + ")|(?:" + CSS_INTEGER + ")"; - var PERMISSIVE_MATCH3 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - var PERMISSIVE_MATCH4 = "[\\s|\\(]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")[,|\\s]+(" + CSS_UNIT + ")\\s*\\)?"; - return { - CSS_UNIT: new RegExp(CSS_UNIT), - rgb: new RegExp("rgb" + PERMISSIVE_MATCH3), - rgba: new RegExp("rgba" + PERMISSIVE_MATCH4), - hsl: new RegExp("hsl" + PERMISSIVE_MATCH3), - hsla: new RegExp("hsla" + PERMISSIVE_MATCH4), - hsv: new RegExp("hsv" + PERMISSIVE_MATCH3), - hsva: new RegExp("hsva" + PERMISSIVE_MATCH4), - hex3: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex6: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/, - hex4: /^#?([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})([0-9a-fA-F]{1})$/, - hex8: /^#?([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})$/ - }; - }(); - function isValidCSSUnit(color2) { - return !!matchers.CSS_UNIT.exec(color2); - } - function stringInputToObject(color2) { - color2 = color2.replace(trimLeft, "").replace(trimRight, "").toLowerCase(); - var named2 = false; - if (names2[color2]) { - color2 = names2[color2]; - named2 = true; - } else if (color2 == "transparent") { - return { - r: 0, - g: 0, - b: 0, - a: 0, - format: "name" - }; - } - var match; - if (match = matchers.rgb.exec(color2)) { - return { - r: match[1], - g: match[2], - b: match[3] - }; - } - if (match = matchers.rgba.exec(color2)) { - return { - r: match[1], - g: match[2], - b: match[3], - a: match[4] - }; - } - if (match = matchers.hsl.exec(color2)) { - return { - h: match[1], - s: match[2], - l: match[3] - }; - } - if (match = matchers.hsla.exec(color2)) { - return { - h: match[1], - s: match[2], - l: match[3], - a: match[4] - }; - } - if (match = matchers.hsv.exec(color2)) { - return { - h: match[1], - s: match[2], - v: match[3] - }; - } - if (match = matchers.hsva.exec(color2)) { - return { - h: match[1], - s: match[2], - v: match[3], - a: match[4] - }; - } - if (match = matchers.hex8.exec(color2)) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - a: convertHexToDecimal(match[4]), - format: named2 ? "name" : "hex8" - }; - } - if (match = matchers.hex6.exec(color2)) { - return { - r: parseIntFromHex(match[1]), - g: parseIntFromHex(match[2]), - b: parseIntFromHex(match[3]), - format: named2 ? "name" : "hex" - }; - } - if (match = matchers.hex4.exec(color2)) { - return { - r: parseIntFromHex(match[1] + "" + match[1]), - g: parseIntFromHex(match[2] + "" + match[2]), - b: parseIntFromHex(match[3] + "" + match[3]), - a: convertHexToDecimal(match[4] + "" + match[4]), - format: named2 ? "name" : "hex8" - }; - } - if (match = matchers.hex3.exec(color2)) { - return { - r: parseIntFromHex(match[1] + "" + match[1]), - g: parseIntFromHex(match[2] + "" + match[2]), - b: parseIntFromHex(match[3] + "" + match[3]), - format: named2 ? "name" : "hex" - }; - } - return false; - } - function validateWCAG2Parms(parms) { - var level, size; - parms = parms || { - level: "AA", - size: "small" - }; - level = (parms.level || "AA").toUpperCase(); - size = (parms.size || "small").toLowerCase(); - if (level !== "AA" && level !== "AAA") { - level = "AA"; - } - if (size !== "small" && size !== "large") { - size = "small"; - } - return { - level, - size - }; - } - return tinycolor2; - }); -})(tinycolor$8); -var tinycolorExports = tinycolor$8.exports; -var extend$5 = {}; -var isPlainObject$4 = is_plain_object; -var isArray$1 = Array.isArray; -function primitivesLoopSplice(source, target) { - var i, value2; - for (i = 0; i < source.length; i++) { - value2 = source[i]; - if (value2 !== null && typeof value2 === "object") { - return false; - } - if (value2 !== void 0) { - target[i] = value2; - } - } - return true; -} -extend$5.extendFlat = function() { - return _extend(arguments, false, false, false); -}; -extend$5.extendDeep = function() { - return _extend(arguments, true, false, false); -}; -extend$5.extendDeepAll = function() { - return _extend(arguments, true, true, false); -}; -extend$5.extendDeepNoArrays = function() { - return _extend(arguments, true, false, true); -}; -function _extend(inputs, isDeep, keepAllKeys, noArrayCopies) { - var target = inputs[0]; - var length2 = inputs.length; - var input, key, src2, copy2, copyIsArray, clone2, allPrimitives; - if (length2 === 2 && isArray$1(target) && isArray$1(inputs[1]) && target.length === 0) { - allPrimitives = primitivesLoopSplice(inputs[1], target); - if (allPrimitives) { - return target; - } else { - target.splice(0, target.length); - } - } - for (var i = 1; i < length2; i++) { - input = inputs[i]; - for (key in input) { - src2 = target[key]; - copy2 = input[key]; - if (noArrayCopies && isArray$1(copy2)) { - target[key] = copy2; - } else if (isDeep && copy2 && (isPlainObject$4(copy2) || (copyIsArray = isArray$1(copy2)))) { - if (copyIsArray) { - copyIsArray = false; - clone2 = src2 && isArray$1(src2) ? src2 : []; - } else { - clone2 = src2 && isPlainObject$4(src2) ? src2 : {}; - } - target[key] = _extend([clone2, copy2], isDeep, keepAllKeys, noArrayCopies); - } else if (typeof copy2 !== "undefined" || keepAllKeys) { - target[key] = copy2; - } - } - } - return target; -} -var font_attributes = function(opts) { - var variantValues = opts.variantValues; - var editType = opts.editType; - var colorEditType = opts.colorEditType; - if (colorEditType === void 0) colorEditType = editType; - var weight = { - editType, - valType: "integer", - min: 1, - max: 1e3, - extras: ["normal", "bold"], - dflt: "normal", - description: [ - "Sets the weight (or boldness) of the font." - ].join(" ") - }; - if (opts.noNumericWeightValues) { - weight.valType = "enumerated"; - weight.values = weight.extras; - weight.extras = void 0; - weight.min = void 0; - weight.max = void 0; - } - var attrs2 = { - family: { - valType: "string", - noBlank: true, - strict: true, - editType, - description: [ - "HTML font family - the typeface that will be applied by the web browser.", - "The web browser will only be able to apply a font if it is available on the system", - "which it operates. Provide multiple font families, separated by commas, to indicate", - "the preference in which to apply fonts if they aren't available on the system.", - "The Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise) generates images on a server,", - "where only a select number of", - "fonts are installed and supported.", - "These include *Arial*, *Balto*, *Courier New*, *Droid Sans*, *Droid Serif*,", - "*Droid Sans Mono*, *Gravitas One*, *Old Standard TT*, *Open Sans*, *Overpass*,", - "*PT Sans Narrow*, *Raleway*, *Times New Roman*." - ].join(" ") - }, - size: { - valType: "number", - min: 1, - editType - }, - color: { - valType: "color", - editType: colorEditType - }, - weight, - style: { - editType, - valType: "enumerated", - values: ["normal", "italic"], - dflt: "normal", - description: [ - "Sets whether a font should be styled with a normal or italic face from its family." - ].join(" ") - }, - variant: opts.noFontVariant ? void 0 : { - editType, - valType: "enumerated", - values: variantValues || [ - "normal", - "small-caps", - "all-small-caps", - "all-petite-caps", - "petite-caps", - "unicase" - ], - dflt: "normal", - description: [ - "Sets the variant of the font." - ].join(" ") - }, - textcase: opts.noFontTextcase ? void 0 : { - editType, - valType: "enumerated", - values: ["normal", "word caps", "upper", "lower"], - dflt: "normal", - description: [ - "Sets capitalization of text.", - "It can be used to make text appear in all-uppercase or all-lowercase,", - "or with each word capitalized." - ].join(" ") - }, - lineposition: opts.noFontLineposition ? void 0 : { - editType, - valType: "flaglist", - flags: ["under", "over", "through"], - extras: ["none"], - dflt: "none", - description: [ - "Sets the kind of decoration line(s) with text,", - "such as an *under*, *over* or *through*", - "as well as combinations e.g. *under+over*, etc." - ].join(" ") - }, - shadow: opts.noFontShadow ? void 0 : { - editType, - valType: "string", - dflt: opts.autoShadowDflt ? "auto" : "none", - description: [ - "Sets the shape and color of the shadow behind text.", - "*auto* places minimal shadow and applies contrast text font color.", - "See https://developer.mozilla.org/en-US/docs/Web/CSS/text-shadow for additional options." - ].join(" ") - }, - editType, - // blank strings so compress_attributes can remove - // TODO - that's uber hacky... better solution? - description: "" + (opts.description || "") - }; - if (opts.autoSize) attrs2.size.dflt = "auto"; - if (opts.autoColor) attrs2.color.dflt = "auto"; - if (opts.arrayOk) { - attrs2.family.arrayOk = true; - attrs2.weight.arrayOk = true; - attrs2.style.arrayOk = true; - if (!opts.noFontVariant) { - attrs2.variant.arrayOk = true; - } - if (!opts.noFontTextcase) { - attrs2.textcase.arrayOk = true; - } - if (!opts.noFontLineposition) { - attrs2.lineposition.arrayOk = true; - } - if (!opts.noFontShadow) { - attrs2.shadow.arrayOk = true; - } - attrs2.size.arrayOk = true; - attrs2.color.arrayOk = true; - } - return attrs2; -}; -var constants$W = { - // hover labels for multiple horizontal bars get tilted by this angle - YANGLE: 60, - // size and display constants for hover text - // pixel size of hover arrows - HOVERARROWSIZE: 6, - // pixels padding around text - HOVERTEXTPAD: 3, - // hover font - HOVERFONTSIZE: 13, - HOVERFONT: "Arial, sans-serif", - // minimum time (msec) between hover calls - HOVERMINTIME: 50, - // ID suffix (with fullLayout._uid) for hover events in the throttle cache - HOVERID: "-hover" -}; -var constants$V = constants$W; -var fontAttrs$h = font_attributes; -var font = fontAttrs$h({ - editType: "none", - description: "Sets the default hover label font used by all traces on the graph." -}); -font.family.dflt = constants$V.HOVERFONT; -font.size.dflt = constants$V.HOVERFONTSIZE; -var layout_attributes$7 = { - clickmode: { - valType: "flaglist", - flags: ["event", "select"], - dflt: "event", - editType: "plot", - extras: ["none"], - description: [ - "Determines the mode of single click interactions.", - "*event* is the default value and emits the `plotly_click`", - "event. In addition this mode emits the `plotly_selected` event", - "in drag modes *lasso* and *select*, but with no event data attached", - "(kept for compatibility reasons).", - "The *select* flag enables selecting single", - "data points via click. This mode also supports persistent selections,", - "meaning that pressing Shift while clicking, adds to / subtracts from an", - "existing selection. *select* with `hovermode`: *x* can be confusing, consider", - "explicitly setting `hovermode`: *closest* when using this feature.", - "Selection events are sent accordingly as long as *event* flag is set as well.", - "When the *event* flag is missing, `plotly_click` and `plotly_selected`", - "events are not fired." - ].join(" ") - }, - dragmode: { - valType: "enumerated", - values: [ - "zoom", - "pan", - "select", - "lasso", - "drawclosedpath", - "drawopenpath", - "drawline", - "drawrect", - "drawcircle", - "orbit", - "turntable", - false - ], - dflt: "zoom", - editType: "modebar", - description: [ - "Determines the mode of drag interactions.", - "*select* and *lasso* apply only to scatter traces with", - "markers or text. *orbit* and *turntable* apply only to", - "3D scenes." - ].join(" ") - }, - hovermode: { - valType: "enumerated", - values: ["x", "y", "closest", false, "x unified", "y unified"], - dflt: "closest", - editType: "modebar", - description: [ - "Determines the mode of hover interactions.", - "If *closest*, a single hoverlabel will appear", - "for the *closest* point within the `hoverdistance`.", - "If *x* (or *y*), multiple hoverlabels will appear for multiple points", - "at the *closest* x- (or y-) coordinate within the `hoverdistance`,", - "with the caveat that no more than one hoverlabel will appear per trace.", - "If *x unified* (or *y unified*), a single hoverlabel will appear", - "multiple points at the closest x- (or y-) coordinate within the `hoverdistance`", - "with the caveat that no more than one hoverlabel will appear per trace.", - "In this mode, spikelines are enabled by default perpendicular to the specified axis.", - "If false, hover interactions are disabled." - ].join(" ") - }, - hoversubplots: { - valType: "enumerated", - values: ["single", "overlaying", "axis"], - dflt: "overlaying", - editType: "none", - description: [ - "Determines expansion of hover effects to other subplots", - "If *single* just the axis pair of the primary point is included without overlaying subplots.", - "If *overlaying* all subplots using the main axis and occupying the same space are included.", - "If *axis*, also include stacked subplots using the same axis", - "when `hovermode` is set to *x*, *x unified*, *y* or *y unified*." - ].join(" ") - }, - hoverdistance: { - valType: "integer", - min: -1, - dflt: 20, - editType: "none", - description: [ - "Sets the default distance (in pixels) to look for data", - "to add hover labels (-1 means no cutoff, 0 means no looking for data).", - "This is only a real distance for hovering on point-like objects,", - "like scatter points. For area-like objects (bars, scatter fills, etc)", - "hovering is on inside the area and off outside, but these objects", - "will not supersede hover on point-like objects in case of conflict." - ].join(" ") - }, - spikedistance: { - valType: "integer", - min: -1, - dflt: -1, - editType: "none", - description: [ - "Sets the default distance (in pixels) to look for data to draw", - "spikelines to (-1 means no cutoff, 0 means no looking for data).", - "As with hoverdistance, distance does not apply to area-like objects.", - "In addition, some objects can be hovered on but will not generate", - "spikelines, such as scatter fills." - ].join(" ") - }, - hoverlabel: { - bgcolor: { - valType: "color", - editType: "none", - description: [ - "Sets the background color of all hover labels on graph" - ].join(" ") - }, - bordercolor: { - valType: "color", - editType: "none", - description: [ - "Sets the border color of all hover labels on graph." - ].join(" ") - }, - font, - grouptitlefont: fontAttrs$h({ - editType: "none", - description: [ - "Sets the font for group titles in hover (unified modes).", - "Defaults to `hoverlabel.font`." - ].join(" ") - }), - align: { - valType: "enumerated", - values: ["left", "right", "auto"], - dflt: "auto", - editType: "none", - description: [ - "Sets the horizontal alignment of the text content within hover label box.", - "Has an effect only if the hover label text spans more two or more lines" - ].join(" ") - }, - namelength: { - valType: "integer", - min: -1, - dflt: 15, - editType: "none", - description: [ - "Sets the default length (in number of characters) of the trace name in", - "the hover labels for all traces. -1 shows the whole name", - "regardless of length. 0-3 shows the first 0-3 characters, and", - "an integer >3 will show the whole name if it is less than that", - "many characters, but if it is longer, will truncate to", - "`namelength - 3` characters and add an ellipsis." - ].join(" ") - }, - editType: "none" - }, - selectdirection: { - valType: "enumerated", - values: ["h", "v", "d", "any"], - dflt: "any", - description: [ - "When `dragmode` is set to *select*, this limits the selection of the drag to", - "horizontal, vertical or diagonal. *h* only allows horizontal selection,", - "*v* only vertical, *d* only diagonal and *any* sets no limit." - ].join(" "), - editType: "none" - } -}; -var fontAttrs$g = font_attributes; -var hoverLabelAttrs = layout_attributes$7.hoverlabel; -var extendFlat$l = extend$5.extendFlat; -var attributes$P = { - hoverlabel: { - bgcolor: extendFlat$l({}, hoverLabelAttrs.bgcolor, { - arrayOk: true, - description: "Sets the background color of the hover labels for this trace" - }), - bordercolor: extendFlat$l({}, hoverLabelAttrs.bordercolor, { - arrayOk: true, - description: "Sets the border color of the hover labels for this trace." - }), - font: fontAttrs$g({ - arrayOk: true, - editType: "none", - description: "Sets the font used in hover labels." - }), - align: extendFlat$l({}, hoverLabelAttrs.align, { arrayOk: true }), - namelength: extendFlat$l({}, hoverLabelAttrs.namelength, { arrayOk: true }), - editType: "none" - } -}; -var fontAttrs$f = font_attributes; -var fxAttrs$1 = attributes$P; -var attributes$O = { - type: { - valType: "enumerated", - values: [], - // listed dynamically - dflt: "scatter", - editType: "calc+clearAxisTypes", - _noTemplating: true - // we handle this at a higher level - }, - visible: { - valType: "enumerated", - values: [true, false, "legendonly"], - dflt: true, - editType: "calc", - description: [ - "Determines whether or not this trace is visible.", - "If *legendonly*, the trace is not drawn,", - "but can appear as a legend item", - "(provided that the legend itself is visible)." - ].join(" ") - }, - showlegend: { - valType: "boolean", - dflt: true, - editType: "style", - description: [ - "Determines whether or not an item corresponding to this", - "trace is shown in the legend." - ].join(" ") - }, - legend: { - valType: "subplotid", - dflt: "legend", - editType: "style", - description: [ - "Sets the reference to a legend to show this trace in.", - "References to these legends are *legend*, *legend2*, *legend3*, etc.", - "Settings for these legends are set in the layout, under", - "`layout.legend`, `layout.legend2`, etc." - ].join(" ") - }, - legendgroup: { - valType: "string", - dflt: "", - editType: "style", - description: [ - "Sets the legend group for this trace.", - "Traces and shapes part of the same legend group hide/show at the same time", - "when toggling legend items." - ].join(" ") - }, - legendgrouptitle: { - text: { - valType: "string", - dflt: "", - editType: "style", - description: [ - "Sets the title of the legend group." - ].join(" ") - }, - font: fontAttrs$f({ - editType: "style", - description: [ - "Sets this legend group's title font." - ].join(" ") - }), - editType: "style" - }, - legendrank: { - valType: "number", - dflt: 1e3, - editType: "style", - description: [ - "Sets the legend rank for this trace.", - "Items and groups with smaller ranks are presented on top/left side while", - "with *reversed* `legend.traceorder` they are on bottom/right side.", - "The default legendrank is 1000,", - "so that you can use ranks less than 1000 to place certain items before all unranked items,", - "and ranks greater than 1000 to go after all unranked items.", - "When having unranked or equal rank items shapes would be displayed after traces", - "i.e. according to their order in data and layout." - ].join(" ") - }, - legendwidth: { - valType: "number", - min: 0, - editType: "style", - description: "Sets the width (in px or fraction) of the legend for this trace." - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 1, - editType: "style", - description: "Sets the opacity of the trace." - }, - name: { - valType: "string", - editType: "style", - description: [ - "Sets the trace name.", - "The trace name appears as the legend item and on hover." - ].join(" ") - }, - uid: { - valType: "string", - editType: "plot", - anim: true, - description: [ - "Assign an id to this trace,", - "Use this to provide object constancy between traces during animations", - "and transitions." - ].join(" ") - }, - ids: { - valType: "data_array", - editType: "calc", - anim: true, - description: [ - "Assigns id labels to each datum.", - "These ids for object constancy of data points during animation.", - "Should be an array of strings, not numbers or any other type." - ].join(" ") - }, - customdata: { - valType: "data_array", - editType: "calc", - description: [ - "Assigns extra data each datum.", - "This may be useful when listening to hover, click and selection events.", - "Note that, *scatter* traces also appends customdata items in the markers", - "DOM elements" - ].join(" ") - }, - meta: { - valType: "any", - arrayOk: true, - editType: "plot", - description: [ - "Assigns extra meta information associated with this trace", - "that can be used in various text attributes.", - "Attributes such as trace `name`, graph, axis and colorbar `title.text`, annotation `text`", - "`rangeselector`, `updatemenues` and `sliders` `label` text", - "all support `meta`.", - "To access the trace `meta` values in an attribute in the same trace, simply use", - "`%{meta[i]}` where `i` is the index or key of the `meta`", - "item in question.", - "To access trace `meta` in layout attributes, use", - "`%{data[n[.meta[i]}` where `i` is the index or key of the `meta`", - "and `n` is the trace index." - ].join(" ") - }, - // N.B. these cannot be 'data_array' as they do not have the same length as - // other data arrays and arrayOk attributes in general - // - // Maybe add another valType: - // https://github.com/plotly/plotly.js/issues/1894 - selectedpoints: { - valType: "any", - editType: "calc", - description: [ - "Array containing integer indices of selected points.", - "Has an effect only for traces that support selections.", - "Note that an empty array means an empty selection where the `unselected`", - "are turned on for all points, whereas, any other non-array values means no", - "selection all where the `selected` and `unselected` styles have no effect." - ].join(" ") - }, - hoverinfo: { - valType: "flaglist", - flags: ["x", "y", "z", "text", "name"], - extras: ["all", "none", "skip"], - arrayOk: true, - dflt: "all", - editType: "none", - description: [ - "Determines which trace information appear on hover.", - "If `none` or `skip` are set, no information is displayed upon hovering.", - "But, if `none` is set, click and hover events are still fired." - ].join(" ") - }, - hoverlabel: fxAttrs$1.hoverlabel, - stream: { - token: { - valType: "string", - noBlank: true, - strict: true, - editType: "calc", - description: [ - "The stream id number links a data trace on a plot with a stream.", - "See https://chart-studio.plotly.com/settings for more details." - ].join(" ") - }, - maxpoints: { - valType: "number", - min: 0, - max: 1e4, - dflt: 500, - editType: "calc", - description: [ - "Sets the maximum number of points to keep on the plots from an", - "incoming stream.", - "If `maxpoints` is set to *50*, only the newest 50 points will", - "be displayed on the plot." - ].join(" ") - }, - editType: "calc" - }, - transforms: { - _isLinkedToArray: "transform", - editType: "calc", - description: [ - "WARNING: All transforms are deprecated and may be removed from the API in next major version.", - "An array of operations that manipulate the trace data,", - "for example filtering or sorting the data arrays." - ].join(" ") - }, - uirevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of some user-driven changes to the trace:", - "`constraintrange` in `parcoords` traces, as well as some", - "`editable: true` modifications such as `name` and `colorbar.title`.", - "Defaults to `layout.uirevision`.", - "Note that other user-driven trace attribute changes are controlled", - "by `layout` attributes:", - "`trace.visible` is controlled by `layout.legend.uirevision`,", - "`selectedpoints` is controlled by `layout.selectionrevision`,", - "and `colorbar.(x|y)` (accessible with `config: {editable: true}`)", - "is controlled by `layout.editrevision`.", - "Trace changes are tracked by `uid`, which only falls back on trace", - "index if no `uid` is provided. So if your app can add/remove traces", - "before the end of the `data` array, such that the same trace has a", - "different index, you can still preserve user-driven changes if you", - "give each trace a `uid` that stays with it as it moves." - ].join(" ") - } -}; -var tinycolor$7 = tinycolorExports; -var scales$2 = { - Greys: [ - [0, "rgb(0,0,0)"], - [1, "rgb(255,255,255)"] - ], - YlGnBu: [ - [0, "rgb(8,29,88)"], - [0.125, "rgb(37,52,148)"], - [0.25, "rgb(34,94,168)"], - [0.375, "rgb(29,145,192)"], - [0.5, "rgb(65,182,196)"], - [0.625, "rgb(127,205,187)"], - [0.75, "rgb(199,233,180)"], - [0.875, "rgb(237,248,217)"], - [1, "rgb(255,255,217)"] - ], - Greens: [ - [0, "rgb(0,68,27)"], - [0.125, "rgb(0,109,44)"], - [0.25, "rgb(35,139,69)"], - [0.375, "rgb(65,171,93)"], - [0.5, "rgb(116,196,118)"], - [0.625, "rgb(161,217,155)"], - [0.75, "rgb(199,233,192)"], - [0.875, "rgb(229,245,224)"], - [1, "rgb(247,252,245)"] - ], - YlOrRd: [ - [0, "rgb(128,0,38)"], - [0.125, "rgb(189,0,38)"], - [0.25, "rgb(227,26,28)"], - [0.375, "rgb(252,78,42)"], - [0.5, "rgb(253,141,60)"], - [0.625, "rgb(254,178,76)"], - [0.75, "rgb(254,217,118)"], - [0.875, "rgb(255,237,160)"], - [1, "rgb(255,255,204)"] - ], - Bluered: [ - [0, "rgb(0,0,255)"], - [1, "rgb(255,0,0)"] - ], - // modified RdBu based on - // http://www.kennethmoreland.com/color-maps/ - RdBu: [ - [0, "rgb(5,10,172)"], - [0.35, "rgb(106,137,247)"], - [0.5, "rgb(190,190,190)"], - [0.6, "rgb(220,170,132)"], - [0.7, "rgb(230,145,90)"], - [1, "rgb(178,10,28)"] - ], - // Scale for non-negative numeric values - Reds: [ - [0, "rgb(220,220,220)"], - [0.2, "rgb(245,195,157)"], - [0.4, "rgb(245,160,105)"], - [1, "rgb(178,10,28)"] - ], - // Scale for non-positive numeric values - Blues: [ - [0, "rgb(5,10,172)"], - [0.35, "rgb(40,60,190)"], - [0.5, "rgb(70,100,245)"], - [0.6, "rgb(90,120,245)"], - [0.7, "rgb(106,137,247)"], - [1, "rgb(220,220,220)"] - ], - Picnic: [ - [0, "rgb(0,0,255)"], - [0.1, "rgb(51,153,255)"], - [0.2, "rgb(102,204,255)"], - [0.3, "rgb(153,204,255)"], - [0.4, "rgb(204,204,255)"], - [0.5, "rgb(255,255,255)"], - [0.6, "rgb(255,204,255)"], - [0.7, "rgb(255,153,255)"], - [0.8, "rgb(255,102,204)"], - [0.9, "rgb(255,102,102)"], - [1, "rgb(255,0,0)"] - ], - Rainbow: [ - [0, "rgb(150,0,90)"], - [0.125, "rgb(0,0,200)"], - [0.25, "rgb(0,25,255)"], - [0.375, "rgb(0,152,255)"], - [0.5, "rgb(44,255,150)"], - [0.625, "rgb(151,255,0)"], - [0.75, "rgb(255,234,0)"], - [0.875, "rgb(255,111,0)"], - [1, "rgb(255,0,0)"] - ], - Portland: [ - [0, "rgb(12,51,131)"], - [0.25, "rgb(10,136,186)"], - [0.5, "rgb(242,211,56)"], - [0.75, "rgb(242,143,56)"], - [1, "rgb(217,30,30)"] - ], - Jet: [ - [0, "rgb(0,0,131)"], - [0.125, "rgb(0,60,170)"], - [0.375, "rgb(5,255,255)"], - [0.625, "rgb(255,255,0)"], - [0.875, "rgb(250,0,0)"], - [1, "rgb(128,0,0)"] - ], - Hot: [ - [0, "rgb(0,0,0)"], - [0.3, "rgb(230,0,0)"], - [0.6, "rgb(255,210,0)"], - [1, "rgb(255,255,255)"] - ], - Blackbody: [ - [0, "rgb(0,0,0)"], - [0.2, "rgb(230,0,0)"], - [0.4, "rgb(230,210,0)"], - [0.7, "rgb(255,255,255)"], - [1, "rgb(160,200,255)"] - ], - Earth: [ - [0, "rgb(0,0,130)"], - [0.1, "rgb(0,180,180)"], - [0.2, "rgb(40,210,40)"], - [0.4, "rgb(230,230,50)"], - [0.6, "rgb(120,70,20)"], - [1, "rgb(255,255,255)"] - ], - Electric: [ - [0, "rgb(0,0,0)"], - [0.15, "rgb(30,0,100)"], - [0.4, "rgb(120,0,100)"], - [0.6, "rgb(160,90,0)"], - [0.8, "rgb(230,200,0)"], - [1, "rgb(255,250,220)"] - ], - Viridis: [ - [0, "#440154"], - [0.06274509803921569, "#48186a"], - [0.12549019607843137, "#472d7b"], - [0.18823529411764706, "#424086"], - [0.25098039215686274, "#3b528b"], - [0.3137254901960784, "#33638d"], - [0.3764705882352941, "#2c728e"], - [0.4392156862745098, "#26828e"], - [0.5019607843137255, "#21918c"], - [0.5647058823529412, "#1fa088"], - [0.6274509803921569, "#28ae80"], - [0.6901960784313725, "#3fbc73"], - [0.7529411764705882, "#5ec962"], - [0.8156862745098039, "#84d44b"], - [0.8784313725490196, "#addc30"], - [0.9411764705882353, "#d8e219"], - [1, "#fde725"] - ], - Cividis: [ - [0, "rgb(0,32,76)"], - [0.058824, "rgb(0,42,102)"], - [0.117647, "rgb(0,52,110)"], - [0.176471, "rgb(39,63,108)"], - [0.235294, "rgb(60,74,107)"], - [0.294118, "rgb(76,85,107)"], - [0.352941, "rgb(91,95,109)"], - [0.411765, "rgb(104,106,112)"], - [0.470588, "rgb(117,117,117)"], - [0.529412, "rgb(131,129,120)"], - [0.588235, "rgb(146,140,120)"], - [0.647059, "rgb(161,152,118)"], - [0.705882, "rgb(176,165,114)"], - [0.764706, "rgb(192,177,109)"], - [0.823529, "rgb(209,191,102)"], - [0.882353, "rgb(225,204,92)"], - [0.941176, "rgb(243,219,79)"], - [1, "rgb(255,233,69)"] - ] -}; -var defaultScale = scales$2.RdBu; -function getScale(scl, dflt) { - if (!dflt) dflt = defaultScale; - if (!scl) return dflt; - function parseScale() { - try { - scl = scales$2[scl] || JSON.parse(scl); - } catch (e) { - scl = dflt; - } - } - if (typeof scl === "string") { - parseScale(); - if (typeof scl === "string") parseScale(); - } - if (!isValidScaleArray(scl)) return dflt; - return scl; -} -function isValidScaleArray(scl) { - var highestVal = 0; - if (!Array.isArray(scl) || scl.length < 2) return false; - if (!scl[0] || !scl[scl.length - 1]) return false; - if (+scl[0][0] !== 0 || +scl[scl.length - 1][0] !== 1) return false; - for (var i = 0; i < scl.length; i++) { - var si = scl[i]; - if (si.length !== 2 || +si[0] < highestVal || !tinycolor$7(si[1]).isValid()) { - return false; - } - highestVal = +si[0]; - } - return true; -} -function isValidScale$2(scl) { - if (scales$2[scl] !== void 0) return true; - else return isValidScaleArray(scl); -} -var scales_1 = { - scales: scales$2, - defaultScale, - get: getScale, - isValid: isValidScale$2 -}; -var color$2 = { exports: {} }; -var attributes$N = {}; -attributes$N.defaults = [ - "#1f77b4", - // muted blue - "#ff7f0e", - // safety orange - "#2ca02c", - // cooked asparagus green - "#d62728", - // brick red - "#9467bd", - // muted purple - "#8c564b", - // chestnut brown - "#e377c2", - // raspberry yogurt pink - "#7f7f7f", - // middle gray - "#bcbd22", - // curry yellow-green - "#17becf" - // blue-teal -]; -attributes$N.defaultLine = "#444"; -attributes$N.lightLine = "#eee"; -attributes$N.background = "#fff"; -attributes$N.borderLine = "#BEC8D9"; -attributes$N.lightFraction = 100 * (14 - 4) / (15 - 4); -var tinycolor$6 = tinycolorExports; -var isNumeric$z = fastIsnumeric; -var isTypedArray = array$2.isTypedArray; -var color$1 = color$2.exports = {}; -var colorAttrs$7 = attributes$N; -color$1.defaults = colorAttrs$7.defaults; -var defaultLine = color$1.defaultLine = colorAttrs$7.defaultLine; -color$1.lightLine = colorAttrs$7.lightLine; -var background = color$1.background = colorAttrs$7.background; -color$1.tinyRGB = function(tc) { - var c = tc.toRgb(); - return "rgb(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ")"; -}; -color$1.rgb = function(cstr) { - return color$1.tinyRGB(tinycolor$6(cstr)); -}; -color$1.opacity = function(cstr) { - return cstr ? tinycolor$6(cstr).getAlpha() : 0; -}; -color$1.addOpacity = function(cstr, op) { - var c = tinycolor$6(cstr).toRgb(); - return "rgba(" + Math.round(c.r) + ", " + Math.round(c.g) + ", " + Math.round(c.b) + ", " + op + ")"; -}; -color$1.combine = function(front, back) { - var fc = tinycolor$6(front).toRgb(); - if (fc.a === 1) return tinycolor$6(front).toRgbString(); - var bc = tinycolor$6(back || background).toRgb(); - var bcflat = bc.a === 1 ? bc : { - r: 255 * (1 - bc.a) + bc.r * bc.a, - g: 255 * (1 - bc.a) + bc.g * bc.a, - b: 255 * (1 - bc.a) + bc.b * bc.a - }; - var fcflat = { - r: bcflat.r * (1 - fc.a) + fc.r * fc.a, - g: bcflat.g * (1 - fc.a) + fc.g * fc.a, - b: bcflat.b * (1 - fc.a) + fc.b * fc.a - }; - return tinycolor$6(fcflat).toRgbString(); -}; -color$1.interpolate = function(first, second2, factor) { - var fc = tinycolor$6(first).toRgb(); - var sc = tinycolor$6(second2).toRgb(); - var ic = { - r: factor * fc.r + (1 - factor) * sc.r, - g: factor * fc.g + (1 - factor) * sc.g, - b: factor * fc.b + (1 - factor) * sc.b - }; - return tinycolor$6(ic).toRgbString(); -}; -color$1.contrast = function(cstr, lightAmount, darkAmount) { - var tc = tinycolor$6(cstr); - if (tc.getAlpha() !== 1) tc = tinycolor$6(color$1.combine(cstr, background)); - var newColor = tc.isDark() ? lightAmount ? tc.lighten(lightAmount) : background : darkAmount ? tc.darken(darkAmount) : defaultLine; - return newColor.toString(); -}; -color$1.stroke = function(s, c) { - var tc = tinycolor$6(c); - s.style({ stroke: color$1.tinyRGB(tc), "stroke-opacity": tc.getAlpha() }); -}; -color$1.fill = function(s, c) { - var tc = tinycolor$6(c); - s.style({ - fill: color$1.tinyRGB(tc), - "fill-opacity": tc.getAlpha() - }); -}; -color$1.clean = function(container) { - if (!container || typeof container !== "object") return; - var keys = Object.keys(container); - var i, j, key, val; - for (i = 0; i < keys.length; i++) { - key = keys[i]; - val = container[key]; - if (key.substr(key.length - 5) === "color") { - if (Array.isArray(val)) { - for (j = 0; j < val.length; j++) val[j] = cleanOne(val[j]); - } else container[key] = cleanOne(val); - } else if (key.substr(key.length - 10) === "colorscale" && Array.isArray(val)) { - for (j = 0; j < val.length; j++) { - if (Array.isArray(val[j])) val[j][1] = cleanOne(val[j][1]); - } - } else if (Array.isArray(val)) { - var el0 = val[0]; - if (!Array.isArray(el0) && el0 && typeof el0 === "object") { - for (j = 0; j < val.length; j++) color$1.clean(val[j]); - } - } else if (val && typeof val === "object" && !isTypedArray(val)) color$1.clean(val); - } -}; -function cleanOne(val) { - if (isNumeric$z(val) || typeof val !== "string") return val; - var valTrim = val.trim(); - if (valTrim.substr(0, 3) !== "rgb") return val; - var match = valTrim.match(/^rgba?\s*\(([^()]*)\)$/); - if (!match) return val; - var parts = match[1].trim().split(/\s*[\s,]\s*/); - var rgba3 = valTrim.charAt(3) === "a" && parts.length === 4; - if (!rgba3 && parts.length !== 3) return val; - for (var i = 0; i < parts.length; i++) { - if (!parts[i].length) return val; - parts[i] = Number(parts[i]); - if (!(parts[i] >= 0)) { - return val; - } - if (i === 3) { - if (parts[i] > 1) parts[i] = 1; - } else if (parts[i] >= 1) { - return val; - } - } - var rgbStr = Math.round(parts[0] * 255) + ", " + Math.round(parts[1] * 255) + ", " + Math.round(parts[2] * 255); - if (rgba3) return "rgba(" + rgbStr + ", " + parts[3] + ")"; - return "rgb(" + rgbStr + ")"; -} -var colorExports = color$2.exports; -var interactions = { - /** - * Timing information for interactive elements - */ - SHOW_PLACEHOLDER: 100, - HIDE_PLACEHOLDER: 1e3, - // opacity dimming fraction for points that are not in selection - DESELECTDIM: 0.2 -}; -var regex = {}; -regex.counter = function(head, tail, openEnded, matchBeginning) { - var fullTail = (tail || "") + (openEnded ? "" : "$"); - var startWithPrefix = matchBeginning === false ? "" : "^"; - if (head === "xy") { - return new RegExp(startWithPrefix + "x([2-9]|[1-9][0-9]+)?y([2-9]|[1-9][0-9]+)?" + fullTail); - } - return new RegExp(startWithPrefix + head + "([2-9]|[1-9][0-9]+)?" + fullTail); -}; -(function(exports2) { - var isNumeric2 = fastIsnumeric; - var tinycolor2 = tinycolorExports; - var extendFlat2 = extend$5.extendFlat; - var baseTraceAttrs = attributes$O; - var colorscales = scales_1; - var Color2 = colorExports; - var DESELECTDIM2 = interactions.DESELECTDIM; - var nestedProperty3 = nested_property; - var counterRegex2 = regex.counter; - var modHalf2 = mod_1.modHalf; - var isArrayOrTypedArray2 = array$2.isArrayOrTypedArray; - var isTypedArraySpec2 = array$2.isTypedArraySpec; - var decodeTypedArraySpec2 = array$2.decodeTypedArraySpec; - exports2.valObjectMeta = { - data_array: { - // You can use *dflt=[] to force said array to exist though. - description: [ - "An {array} of data.", - "The value must represent an {array} or it will be ignored,", - "but this array can be provided in several forms:", - "(1) a regular {array} object", - "(2) a typed array (e.g. Float32Array)", - "(3) an object with keys dtype, bdata, and optionally shape.", - "In this 3rd form, dtype is one of", - "*f8*, *f4*.", - "*i4*, *u4*,", - "*i2*, *u2*,", - "*i1*, *u1* or *u1c* for Uint8ClampedArray.", - "In addition to shorthand `dtype` above one could also use the following forms:", - "*float64*, *float32*,", - "*int32*, *uint32*,", - "*int16*, *uint16*,", - "*int8*, *uint8* or *uint8c* for Uint8ClampedArray.", - "`bdata` is either a base64-encoded string or the ArrayBuffer of", - "an integer or float typed array.", - "For either multi-dimensional arrays you must also", - "provide its dimensions separated by comma via `shape`.", - "For example using `dtype`: *f4* and `shape`: *5,100* you can", - "declare a 2-D array that has 5 rows and 100 columns", - "containing float32 values i.e. 4 bits per value.", - "`shape` is optional for one dimensional arrays." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt"], - coerceFunction: function(v, propOut, dflt) { - propOut.set( - isArrayOrTypedArray2(v) ? v : isTypedArraySpec2(v) ? decodeTypedArraySpec2(v) : dflt - ); - } - }, - enumerated: { - description: [ - "Enumerated value type. The available values are listed", - "in `values`." - ].join(" "), - requiredOpts: ["values"], - otherOpts: ["dflt", "coerceNumber", "arrayOk"], - coerceFunction: function(v, propOut, dflt, opts) { - if (opts.coerceNumber) v = +v; - if (opts.values.indexOf(v) === -1) propOut.set(dflt); - else propOut.set(v); - }, - validateFunction: function(v, opts) { - if (opts.coerceNumber) v = +v; - var values = opts.values; - for (var i = 0; i < values.length; i++) { - var k = String(values[i]); - if (k.charAt(0) === "/" && k.charAt(k.length - 1) === "/") { - var regex2 = new RegExp(k.substr(1, k.length - 2)); - if (regex2.test(v)) return true; - } else if (v === values[i]) return true; - } - return false; - } - }, - boolean: { - description: "A boolean (true/false) value.", - requiredOpts: [], - otherOpts: ["dflt"], - coerceFunction: function(v, propOut, dflt) { - if (v === true || v === false) propOut.set(v); - else propOut.set(dflt); - } - }, - number: { - description: [ - "A number or a numeric value", - "(e.g. a number inside a string).", - "When applicable, values greater (less) than `max` (`min`)", - "are coerced to the `dflt`." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt", "min", "max", "arrayOk"], - coerceFunction: function(v, propOut, dflt, opts) { - if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); - if (!isNumeric2(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) { - propOut.set(dflt); - } else propOut.set(+v); - } - }, - integer: { - description: [ - "An integer or an integer inside a string.", - "When applicable, values greater (less) than `max` (`min`)", - "are coerced to the `dflt`." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt", "min", "max", "arrayOk", "extras"], - coerceFunction: function(v, propOut, dflt, opts) { - if ((opts.extras || []).indexOf(v) !== -1) { - propOut.set(v); - return; - } - if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); - if (v % 1 || !isNumeric2(v) || opts.min !== void 0 && v < opts.min || opts.max !== void 0 && v > opts.max) { - propOut.set(dflt); - } else propOut.set(+v); - } - }, - string: { - description: [ - "A string value.", - "Numbers are converted to strings except for attributes with", - "`strict` set to true." - ].join(" "), - requiredOpts: [], - // TODO 'values shouldn't be in there (edge case: 'dash' in Scatter) - otherOpts: ["dflt", "noBlank", "strict", "arrayOk", "values"], - coerceFunction: function(v, propOut, dflt, opts) { - if (typeof v !== "string") { - var okToCoerce = typeof v === "number"; - if (opts.strict === true || !okToCoerce) propOut.set(dflt); - else propOut.set(String(v)); - } else if (opts.noBlank && !v) propOut.set(dflt); - else propOut.set(v); - } - }, - color: { - description: [ - "A string describing color.", - "Supported formats:", - "- hex (e.g. '#d3d3d3')", - "- rgb (e.g. 'rgb(255, 0, 0)')", - "- rgba (e.g. 'rgb(255, 0, 0, 0.5)')", - "- hsl (e.g. 'hsl(0, 100%, 50%)')", - "- hsv (e.g. 'hsv(0, 100%, 100%)')", - "- named colors (full list: http://www.w3.org/TR/css3-color/#svg-color)" - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt", "arrayOk"], - coerceFunction: function(v, propOut, dflt) { - if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); - if (tinycolor2(v).isValid()) propOut.set(v); - else propOut.set(dflt); - } - }, - colorlist: { - description: [ - "A list of colors.", - "Must be an {array} containing valid colors." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt"], - coerceFunction: function(v, propOut, dflt) { - function isColor(color2) { - return tinycolor2(color2).isValid(); - } - if (!Array.isArray(v) || !v.length) propOut.set(dflt); - else if (v.every(isColor)) propOut.set(v); - else propOut.set(dflt); - } - }, - colorscale: { - description: [ - "A Plotly colorscale either picked by a name:", - "(any of", - Object.keys(colorscales.scales).join(", "), - ")", - "customized as an {array} of 2-element {arrays} where", - "the first element is the normalized color level value", - "(starting at *0* and ending at *1*),", - "and the second item is a valid color string." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt"], - coerceFunction: function(v, propOut, dflt) { - propOut.set(colorscales.get(v, dflt)); - } - }, - angle: { - description: [ - "A number (in degree) between -180 and 180." - ].join(" "), - requiredOpts: [], - otherOpts: ["dflt", "arrayOk"], - coerceFunction: function(v, propOut, dflt) { - if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); - if (v === "auto") propOut.set("auto"); - else if (!isNumeric2(v)) propOut.set(dflt); - else propOut.set(modHalf2(+v, 360)); - } - }, - subplotid: { - description: [ - "An id string of a subplot type (given by dflt), optionally", - "followed by an integer >1. e.g. if dflt='geo', we can have", - "'geo', 'geo2', 'geo3', ..." - ].join(" "), - requiredOpts: ["dflt"], - otherOpts: ["regex"], - coerceFunction: function(v, propOut, dflt, opts) { - var regex2 = opts.regex || counterRegex2(dflt); - if (typeof v === "string" && regex2.test(v)) { - propOut.set(v); - return; - } - propOut.set(dflt); - }, - validateFunction: function(v, opts) { - var dflt = opts.dflt; - if (v === dflt) return true; - if (typeof v !== "string") return false; - if (counterRegex2(dflt).test(v)) return true; - return false; - } - }, - flaglist: { - description: [ - "A string representing a combination of flags", - "(order does not matter here).", - "Combine any of the available `flags` with *+*.", - "(e.g. ('lines+markers')).", - "Values in `extras` cannot be combined." - ].join(" "), - requiredOpts: ["flags"], - otherOpts: ["dflt", "extras", "arrayOk"], - coerceFunction: function(v, propOut, dflt, opts) { - if ((opts.extras || []).indexOf(v) !== -1) { - propOut.set(v); - return; - } - if (typeof v !== "string") { - propOut.set(dflt); - return; - } - var vParts = v.split("+"); - var i = 0; - while (i < vParts.length) { - var vi = vParts[i]; - if (opts.flags.indexOf(vi) === -1 || vParts.indexOf(vi) < i) { - vParts.splice(i, 1); - } else i++; - } - if (!vParts.length) propOut.set(dflt); - else propOut.set(vParts.join("+")); - } - }, - any: { - description: "Any type.", - requiredOpts: [], - otherOpts: ["dflt", "values", "arrayOk"], - coerceFunction: function(v, propOut, dflt) { - if (v === void 0) { - propOut.set(dflt); - } else { - propOut.set( - isTypedArraySpec2(v) ? decodeTypedArraySpec2(v) : v - ); - } - } - }, - info_array: { - description: [ - "An {array} of plot information." - ].join(" "), - requiredOpts: ["items"], - // set `dimensions=2` for a 2D array or '1-2' for either - // `items` may be a single object instead of an array, in which case - // `freeLength` must be true. - // if `dimensions='1-2'` and items is a 1D array, then the value can - // either be a matching 1D array or an array of such matching 1D arrays - otherOpts: ["dflt", "freeLength", "dimensions"], - coerceFunction: function(v, propOut, dflt, opts) { - function coercePart(v2, opts2, dflt2) { - var out; - var propPart = { set: function(v3) { - out = v3; - } }; - if (dflt2 === void 0) dflt2 = opts2.dflt; - exports2.valObjectMeta[opts2.valType].coerceFunction(v2, propPart, dflt2, opts2); - return out; - } - if (isTypedArraySpec2(v)) v = decodeTypedArraySpec2(v); - if (!isArrayOrTypedArray2(v)) { - propOut.set(dflt); - return; - } - var twoD = opts.dimensions === 2 || opts.dimensions === "1-2" && Array.isArray(v) && isArrayOrTypedArray2(v[0]); - var items = opts.items; - var vOut = []; - var arrayItems = Array.isArray(items); - var arrayItems2D = arrayItems && twoD && isArrayOrTypedArray2(items[0]); - var innerItemsOnly = twoD && arrayItems && !arrayItems2D; - var len = arrayItems && !innerItemsOnly ? items.length : v.length; - var i, j, row, item, len2, vNew; - dflt = Array.isArray(dflt) ? dflt : []; - if (twoD) { - for (i = 0; i < len; i++) { - vOut[i] = []; - row = isArrayOrTypedArray2(v[i]) ? v[i] : []; - if (innerItemsOnly) len2 = items.length; - else if (arrayItems) len2 = items[i].length; - else len2 = row.length; - for (j = 0; j < len2; j++) { - if (innerItemsOnly) item = items[j]; - else if (arrayItems) item = items[i][j]; - else item = items; - vNew = coercePart(row[j], item, (dflt[i] || [])[j]); - if (vNew !== void 0) vOut[i][j] = vNew; - } - } - } else { - for (i = 0; i < len; i++) { - vNew = coercePart(v[i], arrayItems ? items[i] : items, dflt[i]); - if (vNew !== void 0) vOut[i] = vNew; - } - } - propOut.set(vOut); - }, - validateFunction: function(v, opts) { - if (!isArrayOrTypedArray2(v)) return false; - var items = opts.items; - var arrayItems = Array.isArray(items); - var twoD = opts.dimensions === 2; - if (!opts.freeLength && v.length !== items.length) return false; - for (var i = 0; i < v.length; i++) { - if (twoD) { - if (!isArrayOrTypedArray2(v[i]) || !opts.freeLength && v[i].length !== items[i].length) { - return false; - } - for (var j = 0; j < v[i].length; j++) { - if (!validate3(v[i][j], arrayItems ? items[i][j] : items)) { - return false; - } - } - } else if (!validate3(v[i], arrayItems ? items[i] : items)) return false; - } - return true; - } - } - }; - exports2.coerce = function(containerIn, containerOut, attributes2, attribute, dflt) { - var opts = nestedProperty3(attributes2, attribute).get(); - var propIn = nestedProperty3(containerIn, attribute); - var propOut = nestedProperty3(containerOut, attribute); - var v = propIn.get(); - var template = containerOut._template; - if (v === void 0 && template) { - v = nestedProperty3(template, attribute).get(); - template = 0; - } - if (dflt === void 0) dflt = opts.dflt; - if (opts.arrayOk) { - if (isArrayOrTypedArray2(v)) { - propOut.set(v); - return v; - } else { - if (isTypedArraySpec2(v)) { - v = decodeTypedArraySpec2(v); - propOut.set(v); - return v; - } - } - } - var coerceFunction = exports2.valObjectMeta[opts.valType].coerceFunction; - coerceFunction(v, propOut, dflt, opts); - var out = propOut.get(); - if (template && out === dflt && !validate3(v, opts)) { - v = nestedProperty3(template, attribute).get(); - coerceFunction(v, propOut, dflt, opts); - out = propOut.get(); - } - return out; - }; - exports2.coerce2 = function(containerIn, containerOut, attributes2, attribute, dflt) { - var propIn = nestedProperty3(containerIn, attribute); - var propOut = exports2.coerce(containerIn, containerOut, attributes2, attribute, dflt); - var valIn = propIn.get(); - return valIn !== void 0 && valIn !== null ? propOut : false; - }; - exports2.coerceFont = function(coerce2, attr, dfltObj, opts) { - if (!opts) opts = {}; - dfltObj = extendFlat2({}, dfltObj); - dfltObj = extendFlat2(dfltObj, opts.overrideDflt || {}); - var out = { - family: coerce2(attr + ".family", dfltObj.family), - size: coerce2(attr + ".size", dfltObj.size), - color: coerce2(attr + ".color", dfltObj.color), - weight: coerce2(attr + ".weight", dfltObj.weight), - style: coerce2(attr + ".style", dfltObj.style) - }; - if (!opts.noFontVariant) out.variant = coerce2(attr + ".variant", dfltObj.variant); - if (!opts.noFontLineposition) out.lineposition = coerce2(attr + ".lineposition", dfltObj.lineposition); - if (!opts.noFontTextcase) out.textcase = coerce2(attr + ".textcase", dfltObj.textcase); - if (!opts.noFontShadow) { - var dfltShadow = dfltObj.shadow; - if (dfltShadow === "none" && opts.autoShadowDflt) { - dfltShadow = "auto"; - } - out.shadow = coerce2(attr + ".shadow", dfltShadow); - } - return out; - }; - exports2.coercePattern = function(coerce2, attr, markerColor, hasMarkerColorscale) { - var shape = coerce2(attr + ".shape"); - if (shape) { - coerce2(attr + ".solidity"); - coerce2(attr + ".size"); - var fillmode = coerce2(attr + ".fillmode"); - var isOverlay = fillmode === "overlay"; - if (!hasMarkerColorscale) { - var bgcolor = coerce2( - attr + ".bgcolor", - isOverlay ? markerColor : void 0 - ); - coerce2( - attr + ".fgcolor", - isOverlay ? Color2.contrast(bgcolor) : markerColor - ); - } - coerce2( - attr + ".fgopacity", - isOverlay ? 0.5 : 1 - ); - } - }; - exports2.coerceHoverinfo = function(traceIn, traceOut, layoutOut) { - var moduleAttrs = traceOut._module.attributes; - var attrs2 = moduleAttrs.hoverinfo ? moduleAttrs : baseTraceAttrs; - var valObj = attrs2.hoverinfo; - var dflt; - if (layoutOut._dataLength === 1) { - var flags = valObj.dflt === "all" ? valObj.flags.slice() : valObj.dflt.split("+"); - flags.splice(flags.indexOf("name"), 1); - dflt = flags.join("+"); - } - return exports2.coerce(traceIn, traceOut, attrs2, "hoverinfo", dflt); - }; - exports2.coerceSelectionMarkerOpacity = function(traceOut, coerce2) { - if (!traceOut.marker) return; - var mo = traceOut.marker.opacity; - if (mo === void 0) return; - var smoDflt; - var usmoDflt; - if (!isArrayOrTypedArray2(mo) && !traceOut.selected && !traceOut.unselected) { - smoDflt = mo; - usmoDflt = DESELECTDIM2 * mo; - } - coerce2("selected.marker.opacity", smoDflt); - coerce2("unselected.marker.opacity", usmoDflt); - }; - function validate3(value2, opts) { - var valObjectDef = exports2.valObjectMeta[opts.valType]; - if (opts.arrayOk && isArrayOrTypedArray2(value2)) return true; - if (valObjectDef.validateFunction) { - return valObjectDef.validateFunction(value2, opts); - } - var failed = {}; - var out = failed; - var propMock = { set: function(v) { - out = v; - } }; - valObjectDef.coerceFunction(value2, propMock, failed, opts); - return out !== failed; - } - exports2.validate = validate3; -})(coerce$1); -var dates = {}; -var loggers$2 = { exports: {} }; -var configAttributes = { - staticPlot: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether the graphs are interactive or not.", - "If *false*, no interactivity, for export or image generation." - ].join(" ") - }, - typesetMath: { - valType: "boolean", - dflt: true, - description: [ - "Determines whether math should be typeset or not,", - "when MathJax (either v2 or v3) is present on the page." - ].join(" ") - }, - plotlyServerURL: { - valType: "string", - dflt: "", - description: [ - "When set it determines base URL for", - "the 'Edit in Chart Studio' `showEditInChartStudio`/`showSendToCloud` mode bar button", - "and the showLink/sendData on-graph link.", - "To enable sending your data to Chart Studio Cloud, you need to", - "set both `plotlyServerURL` to 'https://chart-studio.plotly.com' and", - "also set `showSendToCloud` to true." - ].join(" ") - }, - editable: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether the graph is editable or not.", - "Sets all pieces of `edits`", - "unless a separate `edits` config item overrides individual parts." - ].join(" ") - }, - edits: { - annotationPosition: { - valType: "boolean", - dflt: false, - description: [ - "Determines if the main anchor of the annotation is editable.", - "The main anchor corresponds to the", - "text (if no arrow) or the arrow (which drags the whole thing leaving", - "the arrow length & direction unchanged)." - ].join(" ") - }, - annotationTail: { - valType: "boolean", - dflt: false, - description: [ - "Has only an effect for annotations with arrows.", - "Enables changing the length and direction of the arrow." - ].join(" ") - }, - annotationText: { - valType: "boolean", - dflt: false, - description: "Enables editing annotation text." - }, - axisTitleText: { - valType: "boolean", - dflt: false, - description: "Enables editing axis title text." - }, - colorbarPosition: { - valType: "boolean", - dflt: false, - description: "Enables moving colorbars." - }, - colorbarTitleText: { - valType: "boolean", - dflt: false, - description: "Enables editing colorbar title text." - }, - legendPosition: { - valType: "boolean", - dflt: false, - description: "Enables moving the legend." - }, - legendText: { - valType: "boolean", - dflt: false, - description: "Enables editing the trace name fields from the legend" - }, - shapePosition: { - valType: "boolean", - dflt: false, - description: "Enables moving shapes." - }, - titleText: { - valType: "boolean", - dflt: false, - description: "Enables editing the global layout title." - } - }, - editSelection: { - valType: "boolean", - dflt: true, - description: "Enables moving selections." - }, - autosizable: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether the graphs are plotted with respect to", - "layout.autosize:true and infer its container size." - ].join(" ") - }, - responsive: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether to change the layout size when window is resized.", - "In v3, this option will be removed and will always be true." - ].join(" ") - }, - fillFrame: { - valType: "boolean", - dflt: false, - description: [ - "When `layout.autosize` is turned on, determines whether the graph", - "fills the container (the default) or the screen (if set to *true*)." - ].join(" ") - }, - frameMargins: { - valType: "number", - dflt: 0, - min: 0, - max: 0.5, - description: [ - "When `layout.autosize` is turned on, set the frame margins", - "in fraction of the graph size." - ].join(" ") - }, - scrollZoom: { - valType: "flaglist", - flags: ["cartesian", "gl3d", "geo", "mapbox", "map"], - extras: [true, false], - dflt: "gl3d+geo+map", - description: [ - "Determines whether mouse wheel or two-finger scroll zooms is enable.", - "Turned on by default for gl3d, geo, mapbox and map subplots", - "(as these subplot types do not have zoombox via pan),", - "but turned off by default for cartesian subplots.", - "Set `scrollZoom` to *false* to disable scrolling for all subplots." - ].join(" ") - }, - doubleClick: { - valType: "enumerated", - values: [false, "reset", "autosize", "reset+autosize"], - dflt: "reset+autosize", - description: [ - "Sets the double click interaction mode.", - "Has an effect only in cartesian plots.", - "If *false*, double click is disable.", - "If *reset*, double click resets the axis ranges to their initial values.", - "If *autosize*, double click set the axis ranges to their autorange values.", - "If *reset+autosize*, the odd double clicks resets the axis ranges", - "to their initial values and even double clicks set the axis ranges", - "to their autorange values." - ].join(" ") - }, - doubleClickDelay: { - valType: "number", - dflt: 300, - min: 0, - description: [ - "Sets the delay for registering a double-click in ms.", - "This is the time interval (in ms) between first mousedown and", - "2nd mouseup to constitute a double-click.", - "This setting propagates to all on-subplot double clicks", - "(except for geo, mapbox and map) and on-legend double clicks." - ].join(" ") - }, - showAxisDragHandles: { - valType: "boolean", - dflt: true, - description: [ - "Set to *false* to omit cartesian axis pan/zoom drag handles." - ].join(" ") - }, - showAxisRangeEntryBoxes: { - valType: "boolean", - dflt: true, - description: [ - "Set to *false* to omit direct range entry at the pan/zoom drag points,", - "note that `showAxisDragHandles` must be enabled to have an effect." - ].join(" ") - }, - showTips: { - valType: "boolean", - dflt: true, - description: [ - "Determines whether or not tips are shown while interacting", - "with the resulting graphs." - ].join(" ") - }, - showLink: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether a link to Chart Studio Cloud is displayed", - "at the bottom right corner of resulting graphs.", - "Use with `sendData` and `linkText`." - ].join(" ") - }, - linkText: { - valType: "string", - dflt: "Edit chart", - noBlank: true, - description: [ - "Sets the text appearing in the `showLink` link." - ].join(" ") - }, - sendData: { - valType: "boolean", - dflt: true, - description: [ - "If *showLink* is true, does it contain data", - "just link to a Chart Studio Cloud file?" - ].join(" ") - }, - showSources: { - valType: "any", - dflt: false, - description: [ - "Adds a source-displaying function to show sources on", - "the resulting graphs." - ].join(" ") - }, - displayModeBar: { - valType: "enumerated", - values: ["hover", true, false], - dflt: "hover", - description: [ - "Determines the mode bar display mode.", - "If *true*, the mode bar is always visible.", - "If *false*, the mode bar is always hidden.", - "If *hover*, the mode bar is visible while the mouse cursor", - "is on the graph container." - ].join(" ") - }, - showSendToCloud: { - valType: "boolean", - dflt: false, - description: [ - 'Should we include a ModeBar button, labeled "Edit in Chart Studio",', - "that sends this chart to chart-studio.plotly.com (formerly plot.ly) or another plotly server", - "as specified by `plotlyServerURL` for editing, export, etc? Prior to version 1.43.0", - "this button was included by default, now it is opt-in using this flag.", - "Note that this button can (depending on `plotlyServerURL` being set) send your data", - "to an external server. However that server does not persist your data", - 'until you arrive at the Chart Studio and explicitly click "Save".' - ].join(" ") - }, - showEditInChartStudio: { - valType: "boolean", - dflt: false, - description: [ - "Same as `showSendToCloud`, but use a pencil icon instead of a floppy-disk.", - "Note that if both `showSendToCloud` and `showEditInChartStudio` are turned,", - "only `showEditInChartStudio` will be honored." - ].join(" ") - }, - modeBarButtonsToRemove: { - valType: "any", - dflt: [], - description: [ - "Remove mode bar buttons by name.", - "See ./components/modebar/buttons.js for the list of names." - ].join(" ") - }, - modeBarButtonsToAdd: { - valType: "any", - dflt: [], - description: [ - "Add mode bar button using config objects", - "See ./components/modebar/buttons.js for list of arguments.", - "To enable predefined modebar buttons e.g. shape drawing, hover and spikelines,", - "simply provide their string name(s). This could include:", - "*v1hovermode*, *hoverclosest*, *hovercompare*, *togglehover*, *togglespikelines*,", - "*drawline*, *drawopenpath*, *drawclosedpath*, *drawcircle*, *drawrect* and *eraseshape*.", - "Please note that these predefined buttons will only be shown if they are compatible", - "with all trace types used in a graph." - ].join(" ") - }, - modeBarButtons: { - valType: "any", - dflt: false, - description: [ - "Define fully custom mode bar buttons as nested array,", - "where the outer arrays represents button groups, and", - "the inner arrays have buttons config objects or names of default buttons", - "See ./components/modebar/buttons.js for more info." - ].join(" ") - }, - toImageButtonOptions: { - valType: "any", - dflt: {}, - description: [ - "Statically override options for toImage modebar button", - "allowed keys are format, filename, width, height, scale", - "see ../components/modebar/buttons.js" - ].join(" ") - }, - displaylogo: { - valType: "boolean", - dflt: true, - description: [ - "Determines whether or not the plotly logo is displayed", - "on the end of the mode bar." - ].join(" ") - }, - watermark: { - valType: "boolean", - dflt: false, - description: "watermark the images with the company's logo" - }, - plotGlPixelRatio: { - valType: "number", - dflt: 2, - min: 1, - max: 4, - description: [ - "Set the pixel ratio during WebGL image export.", - "This config option was formerly named `plot3dPixelRatio`", - "which is now deprecated." - ].join(" ") - }, - setBackground: { - valType: "any", - dflt: "transparent", - description: [ - "Set function to add the background color (i.e. `layout.paper_color`)", - "to a different container.", - "This function take the graph div as first argument and the current background", - "color as second argument.", - "Alternatively, set to string *opaque* to ensure there is white behind it." - ].join(" ") - }, - topojsonURL: { - valType: "string", - noBlank: true, - dflt: "https://cdn.plot.ly/", - description: [ - "Set the URL to topojson used in geo charts.", - "By default, the topojson files are fetched from cdn.plot.ly.", - "For example, set this option to:", - "/dist/topojson/", - "to render geographical feature using the topojson files", - "that ship with the plotly.js module." - ].join(" ") - }, - mapboxAccessToken: { - valType: "string", - dflt: null, - description: [ - "Mapbox access token (required to plot mapbox trace types)", - "If using an Mapbox Atlas server, set this option to ''", - "so that plotly.js won't attempt to authenticate to the public Mapbox server." - ].join(" ") - }, - logging: { - valType: "integer", - min: 0, - max: 2, - dflt: 1, - description: [ - "Turn all console logging on or off (errors will be thrown)", - "This should ONLY be set via Plotly.setPlotConfig", - "Available levels:", - "0: no logs", - "1: warnings and errors, but not informational messages", - "2: verbose logs" - ].join(" ") - }, - notifyOnLogging: { - valType: "integer", - min: 0, - max: 2, - dflt: 0, - description: [ - "Set on-graph logging (notifier) level", - "This should ONLY be set via Plotly.setPlotConfig", - "Available levels:", - "0: no on-graph logs", - "1: warnings and errors, but not informational messages", - "2: verbose logs" - ].join(" ") - }, - queueLength: { - valType: "integer", - min: 0, - dflt: 0, - description: "Sets the length of the undo/redo queue." - }, - globalTransforms: { - valType: "any", - dflt: [], - description: [ - "Set global transform to be applied to all traces with no", - "specification needed" - ].join(" ") - }, - locale: { - valType: "string", - dflt: "en-US", - description: [ - "Which localization should we use?", - "Should be a string like 'en' or 'en-US'." - ].join(" ") - }, - locales: { - valType: "any", - dflt: {}, - description: [ - "Localization definitions", - "Locales can be provided either here (specific to one chart) or globally", - "by registering them as modules.", - "Should be an object of objects {locale: {dictionary: {...}, format: {...}}}", - "{", - " da: {", - " dictionary: {'Reset axes': 'Nulstil aksler', ...},", - " format: {months: [...], shortMonths: [...]}", - " },", - " ...", - "}", - "All parts are optional. When looking for translation or format fields, we", - "look first for an exact match in a config locale, then in a registered", - "module. If those fail, we strip off any regionalization ('en-US' -> 'en')", - "and try each (config, registry) again. The final fallback for translation", - "is untranslated (which is US English) and for formats is the base English", - "(the only consequence being the last fallback date format %x is DD/MM/YYYY", - "instead of MM/DD/YYYY). Currently `grouping` and `currency` are ignored", - "for our automatic number formatting, but can be used in custom formats." - ].join(" ") - } -}; -var dfltConfig$4 = {}; -function crawl$1(src2, target) { - for (var k in src2) { - var obj = src2[k]; - if (obj.valType) { - target[k] = obj.dflt; - } else { - if (!target[k]) { - target[k] = {}; - } - crawl$1(obj, target[k]); - } - } -} -crawl$1(configAttributes, dfltConfig$4); -var plot_config = { - configAttributes, - dfltConfig: dfltConfig$4 -}; -var d3$F = d3Exports; -var isNumeric$y = fastIsnumeric; -var NOTEDATA = []; -var notifier$1 = function(text, displayLength) { - if (NOTEDATA.indexOf(text) !== -1) return; - NOTEDATA.push(text); - var ts = 1e3; - if (isNumeric$y(displayLength)) ts = displayLength; - else if (displayLength === "long") ts = 3e3; - var notifierContainer = d3$F.select("body").selectAll(".plotly-notifier").data([0]); - notifierContainer.enter().append("div").classed("plotly-notifier", true); - var notes = notifierContainer.selectAll(".notifier-note").data(NOTEDATA); - function killNote(transition2) { - transition2.duration(700).style("opacity", 0).each("end", function(thisText) { - var thisIndex = NOTEDATA.indexOf(thisText); - if (thisIndex !== -1) NOTEDATA.splice(thisIndex, 1); - d3$F.select(this).remove(); - }); - } - notes.enter().append("div").classed("notifier-note", true).style("opacity", 0).each(function(thisText) { - var note = d3$F.select(this); - note.append("button").classed("notifier-close", true).html("×").on("click", function() { - note.transition().call(killNote); - }); - var p = note.append("p"); - var lines = thisText.split(//g); - for (var i = 0; i < lines.length; i++) { - if (i) p.append("br"); - p.append("span").text(lines[i]); - } - if (displayLength === "stick") { - note.transition().duration(350).style("opacity", 1); - } else { - note.transition().duration(700).style("opacity", 1).transition().delay(ts).call(killNote); - } - }); -}; -var dfltConfig$3 = plot_config.dfltConfig; -var notifier = notifier$1; -var loggers$1 = loggers$2.exports = {}; -loggers$1.log = function() { - var i; - if (dfltConfig$3.logging > 1) { - var messages = ["LOG:"]; - for (i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - console.trace.apply(console, messages); - } - if (dfltConfig$3.notifyOnLogging > 1) { - var lines = []; - for (i = 0; i < arguments.length; i++) { - lines.push(arguments[i]); - } - notifier(lines.join("
"), "long"); - } -}; -loggers$1.warn = function() { - var i; - if (dfltConfig$3.logging > 0) { - var messages = ["WARN:"]; - for (i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - console.trace.apply(console, messages); - } - if (dfltConfig$3.notifyOnLogging > 0) { - var lines = []; - for (i = 0; i < arguments.length; i++) { - lines.push(arguments[i]); - } - notifier(lines.join("
"), "stick"); - } -}; -loggers$1.error = function() { - var i; - if (dfltConfig$3.logging > 0) { - var messages = ["ERROR:"]; - for (i = 0; i < arguments.length; i++) { - messages.push(arguments[i]); - } - console.error.apply(console, messages); - } - if (dfltConfig$3.notifyOnLogging > 0) { - var lines = []; - for (i = 0; i < arguments.length; i++) { - lines.push(arguments[i]); - } - notifier(lines.join("
"), "stick"); - } -}; -var loggersExports = loggers$2.exports; -var registry = {}; -var noop$2 = function noop() { -}; -var push_unique = function pushUnique(array2, item) { - if (item instanceof RegExp) { - var itemStr = item.toString(); - for (var i = 0; i < array2.length; i++) { - if (array2[i] instanceof RegExp && array2[i].toString() === itemStr) { - return array2; - } - } - array2.push(item); - } else if ((item || item === 0) && array2.indexOf(item) === -1) array2.push(item); - return array2; -}; -var matrix$1 = {}; -var create_1$1 = create; -function create() { - var out = new Float32Array(16); - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var clone_1 = clone; -function clone(a) { - var out = new Float32Array(16); - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -} -var copy_1 = copy$1; -function copy$1(out, a) { - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -} -var identity_1 = identity$4; -function identity$4(out) { - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var transpose_1 = transpose; -function transpose(out, a) { - if (out === a) { - var a01 = a[1], a02 = a[2], a03 = a[3], a12 = a[6], a13 = a[7], a23 = a[11]; - out[1] = a[4]; - out[2] = a[8]; - out[3] = a[12]; - out[4] = a01; - out[6] = a[9]; - out[7] = a[13]; - out[8] = a02; - out[9] = a12; - out[11] = a[14]; - out[12] = a03; - out[13] = a13; - out[14] = a23; - } else { - out[0] = a[0]; - out[1] = a[4]; - out[2] = a[8]; - out[3] = a[12]; - out[4] = a[1]; - out[5] = a[5]; - out[6] = a[9]; - out[7] = a[13]; - out[8] = a[2]; - out[9] = a[6]; - out[10] = a[10]; - out[11] = a[14]; - out[12] = a[3]; - out[13] = a[7]; - out[14] = a[11]; - out[15] = a[15]; - } - return out; -} -var invert_1 = invert; -function invert(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32, det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; - if (!det) { - return null; - } - det = 1 / det; - out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det; - out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det; - out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det; - out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det; - out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det; - out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det; - out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det; - out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det; - out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det; - out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det; - out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det; - out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det; - out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det; - out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det; - out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det; - out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det; - return out; -} -var adjoint_1 = adjoint; -function adjoint(out, a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - out[0] = a11 * (a22 * a33 - a23 * a32) - a21 * (a12 * a33 - a13 * a32) + a31 * (a12 * a23 - a13 * a22); - out[1] = -(a01 * (a22 * a33 - a23 * a32) - a21 * (a02 * a33 - a03 * a32) + a31 * (a02 * a23 - a03 * a22)); - out[2] = a01 * (a12 * a33 - a13 * a32) - a11 * (a02 * a33 - a03 * a32) + a31 * (a02 * a13 - a03 * a12); - out[3] = -(a01 * (a12 * a23 - a13 * a22) - a11 * (a02 * a23 - a03 * a22) + a21 * (a02 * a13 - a03 * a12)); - out[4] = -(a10 * (a22 * a33 - a23 * a32) - a20 * (a12 * a33 - a13 * a32) + a30 * (a12 * a23 - a13 * a22)); - out[5] = a00 * (a22 * a33 - a23 * a32) - a20 * (a02 * a33 - a03 * a32) + a30 * (a02 * a23 - a03 * a22); - out[6] = -(a00 * (a12 * a33 - a13 * a32) - a10 * (a02 * a33 - a03 * a32) + a30 * (a02 * a13 - a03 * a12)); - out[7] = a00 * (a12 * a23 - a13 * a22) - a10 * (a02 * a23 - a03 * a22) + a20 * (a02 * a13 - a03 * a12); - out[8] = a10 * (a21 * a33 - a23 * a31) - a20 * (a11 * a33 - a13 * a31) + a30 * (a11 * a23 - a13 * a21); - out[9] = -(a00 * (a21 * a33 - a23 * a31) - a20 * (a01 * a33 - a03 * a31) + a30 * (a01 * a23 - a03 * a21)); - out[10] = a00 * (a11 * a33 - a13 * a31) - a10 * (a01 * a33 - a03 * a31) + a30 * (a01 * a13 - a03 * a11); - out[11] = -(a00 * (a11 * a23 - a13 * a21) - a10 * (a01 * a23 - a03 * a21) + a20 * (a01 * a13 - a03 * a11)); - out[12] = -(a10 * (a21 * a32 - a22 * a31) - a20 * (a11 * a32 - a12 * a31) + a30 * (a11 * a22 - a12 * a21)); - out[13] = a00 * (a21 * a32 - a22 * a31) - a20 * (a01 * a32 - a02 * a31) + a30 * (a01 * a22 - a02 * a21); - out[14] = -(a00 * (a11 * a32 - a12 * a31) - a10 * (a01 * a32 - a02 * a31) + a30 * (a01 * a12 - a02 * a11)); - out[15] = a00 * (a11 * a22 - a12 * a21) - a10 * (a01 * a22 - a02 * a21) + a20 * (a01 * a12 - a02 * a11); - return out; -} -var determinant_1 = determinant; -function determinant(a) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15], b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10, b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11, b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12, b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30, b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31, b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32; - return b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06; -} -var multiply_1 = multiply; -function multiply(out, a, b) { - var a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11], a30 = a[12], a31 = a[13], a32 = a[14], a33 = a[15]; - var b0 = b[0], b1 = b[1], b2 = b[2], b3 = b[3]; - out[0] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[1] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[2] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[3] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[4]; - b1 = b[5]; - b2 = b[6]; - b3 = b[7]; - out[4] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[5] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[6] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[7] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[8]; - b1 = b[9]; - b2 = b[10]; - b3 = b[11]; - out[8] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[9] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[10] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[11] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - b0 = b[12]; - b1 = b[13]; - b2 = b[14]; - b3 = b[15]; - out[12] = b0 * a00 + b1 * a10 + b2 * a20 + b3 * a30; - out[13] = b0 * a01 + b1 * a11 + b2 * a21 + b3 * a31; - out[14] = b0 * a02 + b1 * a12 + b2 * a22 + b3 * a32; - out[15] = b0 * a03 + b1 * a13 + b2 * a23 + b3 * a33; - return out; -} -var translate_1 = translate; -function translate(out, a, v) { - var x = v[0], y = v[1], z = v[2], a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23; - if (a === out) { - out[12] = a[0] * x + a[4] * y + a[8] * z + a[12]; - out[13] = a[1] * x + a[5] * y + a[9] * z + a[13]; - out[14] = a[2] * x + a[6] * y + a[10] * z + a[14]; - out[15] = a[3] * x + a[7] * y + a[11] * z + a[15]; - } else { - a00 = a[0]; - a01 = a[1]; - a02 = a[2]; - a03 = a[3]; - a10 = a[4]; - a11 = a[5]; - a12 = a[6]; - a13 = a[7]; - a20 = a[8]; - a21 = a[9]; - a22 = a[10]; - a23 = a[11]; - out[0] = a00; - out[1] = a01; - out[2] = a02; - out[3] = a03; - out[4] = a10; - out[5] = a11; - out[6] = a12; - out[7] = a13; - out[8] = a20; - out[9] = a21; - out[10] = a22; - out[11] = a23; - out[12] = a00 * x + a10 * y + a20 * z + a[12]; - out[13] = a01 * x + a11 * y + a21 * z + a[13]; - out[14] = a02 * x + a12 * y + a22 * z + a[14]; - out[15] = a03 * x + a13 * y + a23 * z + a[15]; - } - return out; -} -var scale_1 = scale; -function scale(out, a, v) { - var x = v[0], y = v[1], z = v[2]; - out[0] = a[0] * x; - out[1] = a[1] * x; - out[2] = a[2] * x; - out[3] = a[3] * x; - out[4] = a[4] * y; - out[5] = a[5] * y; - out[6] = a[6] * y; - out[7] = a[7] * y; - out[8] = a[8] * z; - out[9] = a[9] * z; - out[10] = a[10] * z; - out[11] = a[11] * z; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - return out; -} -var rotate_1 = rotate$2; -function rotate$2(out, a, rad, axis) { - var x = axis[0], y = axis[1], z = axis[2], len = Math.sqrt(x * x + y * y + z * z), s, c, t, a00, a01, a02, a03, a10, a11, a12, a13, a20, a21, a22, a23, b00, b01, b02, b10, b11, b12, b20, b21, b22; - if (Math.abs(len) < 1e-6) { - return null; - } - len = 1 / len; - x *= len; - y *= len; - z *= len; - s = Math.sin(rad); - c = Math.cos(rad); - t = 1 - c; - a00 = a[0]; - a01 = a[1]; - a02 = a[2]; - a03 = a[3]; - a10 = a[4]; - a11 = a[5]; - a12 = a[6]; - a13 = a[7]; - a20 = a[8]; - a21 = a[9]; - a22 = a[10]; - a23 = a[11]; - b00 = x * x * t + c; - b01 = y * x * t + z * s; - b02 = z * x * t - y * s; - b10 = x * y * t - z * s; - b11 = y * y * t + c; - b12 = z * y * t + x * s; - b20 = x * z * t + y * s; - b21 = y * z * t - x * s; - b22 = z * z * t + c; - out[0] = a00 * b00 + a10 * b01 + a20 * b02; - out[1] = a01 * b00 + a11 * b01 + a21 * b02; - out[2] = a02 * b00 + a12 * b01 + a22 * b02; - out[3] = a03 * b00 + a13 * b01 + a23 * b02; - out[4] = a00 * b10 + a10 * b11 + a20 * b12; - out[5] = a01 * b10 + a11 * b11 + a21 * b12; - out[6] = a02 * b10 + a12 * b11 + a22 * b12; - out[7] = a03 * b10 + a13 * b11 + a23 * b12; - out[8] = a00 * b20 + a10 * b21 + a20 * b22; - out[9] = a01 * b20 + a11 * b21 + a21 * b22; - out[10] = a02 * b20 + a12 * b21 + a22 * b22; - out[11] = a03 * b20 + a13 * b21 + a23 * b22; - if (a !== out) { - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } - return out; -} -var rotateX_1 = rotateX; -function rotateX(out, a, rad) { - var s = Math.sin(rad), c = Math.cos(rad), a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; - if (a !== out) { - out[0] = a[0]; - out[1] = a[1]; - out[2] = a[2]; - out[3] = a[3]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } - out[4] = a10 * c + a20 * s; - out[5] = a11 * c + a21 * s; - out[6] = a12 * c + a22 * s; - out[7] = a13 * c + a23 * s; - out[8] = a20 * c - a10 * s; - out[9] = a21 * c - a11 * s; - out[10] = a22 * c - a12 * s; - out[11] = a23 * c - a13 * s; - return out; -} -var rotateY_1 = rotateY; -function rotateY(out, a, rad) { - var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a20 = a[8], a21 = a[9], a22 = a[10], a23 = a[11]; - if (a !== out) { - out[4] = a[4]; - out[5] = a[5]; - out[6] = a[6]; - out[7] = a[7]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } - out[0] = a00 * c - a20 * s; - out[1] = a01 * c - a21 * s; - out[2] = a02 * c - a22 * s; - out[3] = a03 * c - a23 * s; - out[8] = a00 * s + a20 * c; - out[9] = a01 * s + a21 * c; - out[10] = a02 * s + a22 * c; - out[11] = a03 * s + a23 * c; - return out; -} -var rotateZ_1 = rotateZ; -function rotateZ(out, a, rad) { - var s = Math.sin(rad), c = Math.cos(rad), a00 = a[0], a01 = a[1], a02 = a[2], a03 = a[3], a10 = a[4], a11 = a[5], a12 = a[6], a13 = a[7]; - if (a !== out) { - out[8] = a[8]; - out[9] = a[9]; - out[10] = a[10]; - out[11] = a[11]; - out[12] = a[12]; - out[13] = a[13]; - out[14] = a[14]; - out[15] = a[15]; - } - out[0] = a00 * c + a10 * s; - out[1] = a01 * c + a11 * s; - out[2] = a02 * c + a12 * s; - out[3] = a03 * c + a13 * s; - out[4] = a10 * c - a00 * s; - out[5] = a11 * c - a01 * s; - out[6] = a12 * c - a02 * s; - out[7] = a13 * c - a03 * s; - return out; -} -var fromRotation_1 = fromRotation; -function fromRotation(out, rad, axis) { - var s, c, t; - var x = axis[0]; - var y = axis[1]; - var z = axis[2]; - var len = Math.sqrt(x * x + y * y + z * z); - if (Math.abs(len) < 1e-6) { - return null; - } - len = 1 / len; - x *= len; - y *= len; - z *= len; - s = Math.sin(rad); - c = Math.cos(rad); - t = 1 - c; - out[0] = x * x * t + c; - out[1] = y * x * t + z * s; - out[2] = z * x * t - y * s; - out[3] = 0; - out[4] = x * y * t - z * s; - out[5] = y * y * t + c; - out[6] = z * y * t + x * s; - out[7] = 0; - out[8] = x * z * t + y * s; - out[9] = y * z * t - x * s; - out[10] = z * z * t + c; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var fromRotationTranslation_1 = fromRotationTranslation; -function fromRotationTranslation(out, q, v) { - var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, xy = x * y2, xz = x * z2, yy = y * y2, yz = y * z2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; - out[0] = 1 - (yy + zz); - out[1] = xy + wz; - out[2] = xz - wy; - out[3] = 0; - out[4] = xy - wz; - out[5] = 1 - (xx + zz); - out[6] = yz + wx; - out[7] = 0; - out[8] = xz + wy; - out[9] = yz - wx; - out[10] = 1 - (xx + yy); - out[11] = 0; - out[12] = v[0]; - out[13] = v[1]; - out[14] = v[2]; - out[15] = 1; - return out; -} -var fromScaling_1 = fromScaling; -function fromScaling(out, v) { - out[0] = v[0]; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = v[1]; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = v[2]; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var fromTranslation_1 = fromTranslation; -function fromTranslation(out, v) { - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = v[0]; - out[13] = v[1]; - out[14] = v[2]; - out[15] = 1; - return out; -} -var fromXRotation_1 = fromXRotation; -function fromXRotation(out, rad) { - var s = Math.sin(rad), c = Math.cos(rad); - out[0] = 1; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = c; - out[6] = s; - out[7] = 0; - out[8] = 0; - out[9] = -s; - out[10] = c; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var fromYRotation_1 = fromYRotation; -function fromYRotation(out, rad) { - var s = Math.sin(rad), c = Math.cos(rad); - out[0] = c; - out[1] = 0; - out[2] = -s; - out[3] = 0; - out[4] = 0; - out[5] = 1; - out[6] = 0; - out[7] = 0; - out[8] = s; - out[9] = 0; - out[10] = c; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var fromZRotation_1 = fromZRotation; -function fromZRotation(out, rad) { - var s = Math.sin(rad), c = Math.cos(rad); - out[0] = c; - out[1] = s; - out[2] = 0; - out[3] = 0; - out[4] = -s; - out[5] = c; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 1; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var fromQuat_1 = fromQuat; -function fromQuat(out, q) { - var x = q[0], y = q[1], z = q[2], w = q[3], x2 = x + x, y2 = y + y, z2 = z + z, xx = x * x2, yx = y * x2, yy = y * y2, zx = z * x2, zy = z * y2, zz = z * z2, wx = w * x2, wy = w * y2, wz = w * z2; - out[0] = 1 - yy - zz; - out[1] = yx + wz; - out[2] = zx - wy; - out[3] = 0; - out[4] = yx - wz; - out[5] = 1 - xx - zz; - out[6] = zy + wx; - out[7] = 0; - out[8] = zx + wy; - out[9] = zy - wx; - out[10] = 1 - xx - yy; - out[11] = 0; - out[12] = 0; - out[13] = 0; - out[14] = 0; - out[15] = 1; - return out; -} -var frustum_1 = frustum; -function frustum(out, left, right, bottom, top, near, far) { - var rl = 1 / (right - left), tb = 1 / (top - bottom), nf = 1 / (near - far); - out[0] = near * 2 * rl; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = near * 2 * tb; - out[6] = 0; - out[7] = 0; - out[8] = (right + left) * rl; - out[9] = (top + bottom) * tb; - out[10] = (far + near) * nf; - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = far * near * 2 * nf; - out[15] = 0; - return out; -} -var perspective_1 = perspective; -function perspective(out, fovy, aspect, near, far) { - var f = 1 / Math.tan(fovy / 2), nf = 1 / (near - far); - out[0] = f / aspect; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = f; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = (far + near) * nf; - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = 2 * far * near * nf; - out[15] = 0; - return out; -} -var perspectiveFromFieldOfView_1 = perspectiveFromFieldOfView; -function perspectiveFromFieldOfView(out, fov, near, far) { - var upTan = Math.tan(fov.upDegrees * Math.PI / 180), downTan = Math.tan(fov.downDegrees * Math.PI / 180), leftTan = Math.tan(fov.leftDegrees * Math.PI / 180), rightTan = Math.tan(fov.rightDegrees * Math.PI / 180), xScale = 2 / (leftTan + rightTan), yScale = 2 / (upTan + downTan); - out[0] = xScale; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = yScale; - out[6] = 0; - out[7] = 0; - out[8] = -((leftTan - rightTan) * xScale * 0.5); - out[9] = (upTan - downTan) * yScale * 0.5; - out[10] = far / (near - far); - out[11] = -1; - out[12] = 0; - out[13] = 0; - out[14] = far * near / (near - far); - out[15] = 0; - return out; -} -var ortho_1 = ortho; -function ortho(out, left, right, bottom, top, near, far) { - var lr = 1 / (left - right), bt = 1 / (bottom - top), nf = 1 / (near - far); - out[0] = -2 * lr; - out[1] = 0; - out[2] = 0; - out[3] = 0; - out[4] = 0; - out[5] = -2 * bt; - out[6] = 0; - out[7] = 0; - out[8] = 0; - out[9] = 0; - out[10] = 2 * nf; - out[11] = 0; - out[12] = (left + right) * lr; - out[13] = (top + bottom) * bt; - out[14] = (far + near) * nf; - out[15] = 1; - return out; -} -var identity$3 = identity_1; -var lookAt_1 = lookAt; -function lookAt(out, eye, center, up) { - var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, eyex = eye[0], eyey = eye[1], eyez = eye[2], upx = up[0], upy = up[1], upz = up[2], centerx = center[0], centery = center[1], centerz = center[2]; - if (Math.abs(eyex - centerx) < 1e-6 && Math.abs(eyey - centery) < 1e-6 && Math.abs(eyez - centerz) < 1e-6) { - return identity$3(out); - } - z0 = eyex - centerx; - z1 = eyey - centery; - z2 = eyez - centerz; - len = 1 / Math.sqrt(z0 * z0 + z1 * z1 + z2 * z2); - z0 *= len; - z1 *= len; - z2 *= len; - x0 = upy * z2 - upz * z1; - x1 = upz * z0 - upx * z2; - x2 = upx * z1 - upy * z0; - len = Math.sqrt(x0 * x0 + x1 * x1 + x2 * x2); - if (!len) { - x0 = 0; - x1 = 0; - x2 = 0; - } else { - len = 1 / len; - x0 *= len; - x1 *= len; - x2 *= len; - } - y0 = z1 * x2 - z2 * x1; - y1 = z2 * x0 - z0 * x2; - y2 = z0 * x1 - z1 * x0; - len = Math.sqrt(y0 * y0 + y1 * y1 + y2 * y2); - if (!len) { - y0 = 0; - y1 = 0; - y2 = 0; - } else { - len = 1 / len; - y0 *= len; - y1 *= len; - y2 *= len; - } - out[0] = x0; - out[1] = y0; - out[2] = z0; - out[3] = 0; - out[4] = x1; - out[5] = y1; - out[6] = z1; - out[7] = 0; - out[8] = x2; - out[9] = y2; - out[10] = z2; - out[11] = 0; - out[12] = -(x0 * eyex + x1 * eyey + x2 * eyez); - out[13] = -(y0 * eyex + y1 * eyey + y2 * eyez); - out[14] = -(z0 * eyex + z1 * eyey + z2 * eyez); - out[15] = 1; - return out; -} -var str_1 = str; -function str(a) { - return "mat4(" + a[0] + ", " + a[1] + ", " + a[2] + ", " + a[3] + ", " + a[4] + ", " + a[5] + ", " + a[6] + ", " + a[7] + ", " + a[8] + ", " + a[9] + ", " + a[10] + ", " + a[11] + ", " + a[12] + ", " + a[13] + ", " + a[14] + ", " + a[15] + ")"; -} -var glMat4 = { - create: create_1$1, - clone: clone_1, - copy: copy_1, - identity: identity_1, - transpose: transpose_1, - invert: invert_1, - adjoint: adjoint_1, - determinant: determinant_1, - multiply: multiply_1, - translate: translate_1, - scale: scale_1, - rotate: rotate_1, - rotateX: rotateX_1, - rotateY: rotateY_1, - rotateZ: rotateZ_1, - fromRotation: fromRotation_1, - fromRotationTranslation: fromRotationTranslation_1, - fromScaling: fromScaling_1, - fromTranslation: fromTranslation_1, - fromXRotation: fromXRotation_1, - fromYRotation: fromYRotation_1, - fromZRotation: fromZRotation_1, - fromQuat: fromQuat_1, - frustum: frustum_1, - perspective: perspective_1, - perspectiveFromFieldOfView: perspectiveFromFieldOfView_1, - ortho: ortho_1, - lookAt: lookAt_1, - str: str_1 -}; -(function(exports2) { - var mat4X42 = glMat4; - exports2.init2dArray = function(rowLength, colLength) { - var array2 = new Array(rowLength); - for (var i = 0; i < rowLength; i++) array2[i] = new Array(colLength); - return array2; - }; - exports2.transposeRagged = function(z) { - var maxlen = 0; - var zlen = z.length; - var i, j; - for (i = 0; i < zlen; i++) maxlen = Math.max(maxlen, z[i].length); - var t = new Array(maxlen); - for (i = 0; i < maxlen; i++) { - t[i] = new Array(zlen); - for (j = 0; j < zlen; j++) t[i][j] = z[j][i]; - } - return t; - }; - exports2.dot = function(x, y) { - if (!(x.length && y.length) || x.length !== y.length) return null; - var len = x.length; - var out; - var i; - if (x[0].length) { - out = new Array(len); - for (i = 0; i < len; i++) out[i] = exports2.dot(x[i], y); - } else if (y[0].length) { - var yTranspose = exports2.transposeRagged(y); - out = new Array(yTranspose.length); - for (i = 0; i < yTranspose.length; i++) out[i] = exports2.dot(x, yTranspose[i]); - } else { - out = 0; - for (i = 0; i < len; i++) out += x[i] * y[i]; - } - return out; - }; - exports2.translationMatrix = function(x, y) { - return [[1, 0, x], [0, 1, y], [0, 0, 1]]; - }; - exports2.rotationMatrix = function(alpha) { - var a = alpha * Math.PI / 180; - return [ - [Math.cos(a), -Math.sin(a), 0], - [Math.sin(a), Math.cos(a), 0], - [0, 0, 1] - ]; - }; - exports2.rotationXYMatrix = function(a, x, y) { - return exports2.dot( - exports2.dot( - exports2.translationMatrix(x, y), - exports2.rotationMatrix(a) - ), - exports2.translationMatrix(-x, -y) - ); - }; - exports2.apply3DTransform = function(transform) { - return function() { - var args = arguments; - var xyz = arguments.length === 1 ? args[0] : [args[0], args[1], args[2] || 0]; - return exports2.dot(transform, [xyz[0], xyz[1], xyz[2], 1]).slice(0, 3); - }; - }; - exports2.apply2DTransform = function(transform) { - return function() { - var args = arguments; - if (args.length === 3) { - args = args[0]; - } - var xy = arguments.length === 1 ? args[0] : [args[0], args[1]]; - return exports2.dot(transform, [xy[0], xy[1], 1]).slice(0, 2); - }; - }; - exports2.apply2DTransform2 = function(transform) { - var at = exports2.apply2DTransform(transform); - return function(xys) { - return at(xys.slice(0, 2)).concat(at(xys.slice(2, 4))); - }; - }; - exports2.convertCssMatrix = function(m) { - if (m) { - var len = m.length; - if (len === 16) return m; - if (len === 6) { - return [ - m[0], - m[1], - 0, - 0, - m[2], - m[3], - 0, - 0, - 0, - 0, - 1, - 0, - m[4], - m[5], - 0, - 1 - ]; - } - } - return [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1 - ]; - }; - exports2.inverseTransformMatrix = function(m) { - var out = []; - mat4X42.invert(out, m); - return [ - [out[0], out[1], out[2], out[3]], - [out[4], out[5], out[6], out[7]], - [out[8], out[9], out[10], out[11]], - [out[12], out[13], out[14], out[15]] - ]; - }; -})(matrix$1); -var d3$E = d3Exports; -var loggers = loggersExports; -var matrix = matrix$1; -var mat4X4 = glMat4; -function getGraphDiv$2(gd) { - var gdElement; - if (typeof gd === "string") { - gdElement = document.getElementById(gd); - if (gdElement === null) { - throw new Error("No DOM element with id '" + gd + "' exists on the page."); - } - return gdElement; - } else if (gd === null || gd === void 0) { - throw new Error("DOM element provided is null or undefined"); - } - return gd; -} -function isPlotDiv(el) { - var el3 = d3$E.select(el); - return el3.node() instanceof HTMLElement && el3.size() && el3.classed("js-plotly-plot"); -} -function removeElement$1(el) { - var elParent = el && el.parentNode; - if (elParent) elParent.removeChild(el); -} -function addStyleRule(selector, styleString) { - addRelatedStyleRule("global", selector, styleString); -} -function addRelatedStyleRule(uid, selector, styleString) { - var id = "plotly.js-style-" + uid; - var style5 = document.getElementById(id); - if (!style5) { - style5 = document.createElement("style"); - style5.setAttribute("id", id); - style5.appendChild(document.createTextNode("")); - document.head.appendChild(style5); - } - var styleSheet = style5.sheet; - if (styleSheet.insertRule) { - styleSheet.insertRule(selector + "{" + styleString + "}", 0); - } else if (styleSheet.addRule) { - styleSheet.addRule(selector, styleString, 0); - } else loggers.warn("addStyleRule failed"); -} -function deleteRelatedStyleRule(uid) { - var id = "plotly.js-style-" + uid; - var style5 = document.getElementById(id); - if (style5) removeElement$1(style5); -} -function getFullTransformMatrix(element) { - var allElements = getElementAndAncestors(element); - var out = [ - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1, - 0, - 0, - 0, - 0, - 1 - ]; - allElements.forEach(function(e) { - var t = getElementTransformMatrix(e); - if (t) { - var m = matrix.convertCssMatrix(t); - out = mat4X4.multiply(out, out, m); - } - }); - return out; -} -function getElementTransformMatrix(element) { - var style5 = window.getComputedStyle(element, null); - var transform = style5.getPropertyValue("-webkit-transform") || style5.getPropertyValue("-moz-transform") || style5.getPropertyValue("-ms-transform") || style5.getPropertyValue("-o-transform") || style5.getPropertyValue("transform"); - if (transform === "none") return null; - return transform.replace("matrix", "").replace("3d", "").slice(1, -1).split(",").map(function(n) { - return +n; - }); -} -function getElementAndAncestors(element) { - var allElements = []; - while (isTransformableElement(element)) { - allElements.push(element); - element = element.parentNode; - if (typeof ShadowRoot === "function" && element instanceof ShadowRoot) { - element = element.host; - } - } - return allElements; -} -function isTransformableElement(element) { - return element && (element instanceof Element || element instanceof HTMLElement); -} -function equalDomRects(a, b) { - return a && b && a.top === b.top && a.left === b.left && a.right === b.right && a.bottom === b.bottom; -} -var dom = { - getGraphDiv: getGraphDiv$2, - isPlotDiv, - removeElement: removeElement$1, - addStyleRule, - addRelatedStyleRule, - deleteRelatedStyleRule, - getFullTransformMatrix, - getElementTransformMatrix, - getElementAndAncestors, - equalDomRects -}; -var animation_attributes = { - mode: { - valType: "enumerated", - dflt: "afterall", - values: ["immediate", "next", "afterall"], - description: [ - "Describes how a new animate call interacts with currently-running", - "animations. If `immediate`, current animations are interrupted and", - "the new animation is started. If `next`, the current frame is allowed", - "to complete, after which the new animation is started. If `afterall`", - "all existing frames are animated to completion before the new animation", - "is started." - ].join(" ") - }, - direction: { - valType: "enumerated", - values: ["forward", "reverse"], - dflt: "forward", - description: [ - "The direction in which to play the frames triggered by the animation call" - ].join(" ") - }, - fromcurrent: { - valType: "boolean", - dflt: false, - description: [ - "Play frames starting at the current frame instead of the beginning." - ].join(" ") - }, - frame: { - duration: { - valType: "number", - min: 0, - dflt: 500, - description: [ - "The duration in milliseconds of each frame. If greater than the frame", - "duration, it will be limited to the frame duration." - ].join(" ") - }, - redraw: { - valType: "boolean", - dflt: true, - description: [ - "Redraw the plot at completion of the transition. This is desirable", - "for transitions that include properties that cannot be transitioned,", - "but may significantly slow down updates that do not require a full", - "redraw of the plot" - ].join(" ") - } - }, - transition: { - duration: { - valType: "number", - min: 0, - dflt: 500, - editType: "none", - description: [ - "The duration of the transition, in milliseconds. If equal to zero,", - "updates are synchronous." - ].join(" ") - }, - easing: { - valType: "enumerated", - dflt: "cubic-in-out", - values: [ - "linear", - "quad", - "cubic", - "sin", - "exp", - "circle", - "elastic", - "back", - "bounce", - "linear-in", - "quad-in", - "cubic-in", - "sin-in", - "exp-in", - "circle-in", - "elastic-in", - "back-in", - "bounce-in", - "linear-out", - "quad-out", - "cubic-out", - "sin-out", - "exp-out", - "circle-out", - "elastic-out", - "back-out", - "bounce-out", - "linear-in-out", - "quad-in-out", - "cubic-in-out", - "sin-in-out", - "exp-in-out", - "circle-in-out", - "elastic-in-out", - "back-in-out", - "bounce-in-out" - ], - editType: "none", - description: "The easing function used for the transition" - }, - ordering: { - valType: "enumerated", - values: ["layout first", "traces first"], - dflt: "layout first", - editType: "none", - description: [ - "Determines whether the figure's layout or traces smoothly transitions", - "during updates that make both traces and layout change." - ].join(" ") - } - } -}; -var extendFlat$k = extend$5.extendFlat; -var isPlainObject$3 = is_plain_object; -var traceOpts = { - valType: "flaglist", - extras: ["none"], - flags: ["calc", "clearAxisTypes", "plot", "style", "markerSize", "colorbars"], - description: [ - "trace attributes should include an `editType` string matching this flaglist.", - "*calc* is the most extensive: a full (re)plot starting by clearing `gd.calcdata`", - "to force it to be regenerated", - "*clearAxisTypes* resets the types of the axes this trace is on, because new data could", - "cause the automatic axis type detection to change. Log type will not be cleared, as that", - "is never automatically chosen so must have been user-specified.", - "*plot* (re)plots but without first clearing `gd.calcdata`.", - "*style* only calls `module.style` (or module.editStyle) for all trace modules and redraws the legend.", - "*markerSize* is like *style*, but propagate axis-range changes due to scatter `marker.size`", - "*colorbars* only redraws colorbars." - ].join(" ") -}; -var layoutOpts = { - valType: "flaglist", - extras: ["none"], - flags: [ - "calc", - "plot", - "legend", - "ticks", - "axrange", - "layoutstyle", - "modebar", - "camera", - "arraydraw", - "colorbars" - ], - description: [ - "layout attributes should include an `editType` string matching this flaglist.", - "*calc* is the most extensive: a full (re)plot starting by clearing `gd.calcdata`", - "to force it to be regenerated", - "*plot* (re)plots but without first clearing `gd.calcdata`.", - "*legend* only redraws the legend.", - "*ticks* only redraws axis ticks, labels, and gridlines.", - "*axrange* minimal sequence when updating axis ranges.", - "*layoutstyle* reapplies global and SVG cartesian axis styles.", - "*modebar* just updates the modebar.", - "*camera* just updates the camera settings for gl3d scenes.", - "*arraydraw* allows component arrays to invoke the redraw routines just for the", - "component(s) that changed.", - "*colorbars* only redraws colorbars." - ].join(" ") -}; -var traceEditTypeFlags = traceOpts.flags.slice().concat(["fullReplot"]); -var layoutEditTypeFlags = layoutOpts.flags.slice().concat("layoutReplot"); -var edit_types = { - traces: traceOpts, - layout: layoutOpts, - /* - * default (all false) edit flags for restyle (traces) - * creates a new object each call, so the caller can mutate freely - */ - traceFlags: function() { - return falseObj(traceEditTypeFlags); - }, - /* - * default (all false) edit flags for relayout - * creates a new object each call, so the caller can mutate freely - */ - layoutFlags: function() { - return falseObj(layoutEditTypeFlags); - }, - /* - * update `flags` with the `editType` values found in `attr` - */ - update: function(flags, attr) { - var editType = attr.editType; - if (editType && editType !== "none") { - var editTypeParts = editType.split("+"); - for (var i = 0; i < editTypeParts.length; i++) { - flags[editTypeParts[i]] = true; - } - } - }, - overrideAll: overrideAll$8 -}; -function falseObj(keys) { - var out = {}; - for (var i = 0; i < keys.length; i++) out[keys[i]] = false; - return out; -} -function overrideAll$8(attrs2, editTypeOverride, overrideContainers) { - var out = extendFlat$k({}, attrs2); - for (var key in out) { - var attr = out[key]; - if (isPlainObject$3(attr)) { - out[key] = overrideOne(attr, editTypeOverride, overrideContainers, key); - } - } - if (overrideContainers === "from-root") out.editType = editTypeOverride; - return out; -} -function overrideOne(attr, editTypeOverride, overrideContainers, key) { - if (attr.valType) { - var out = extendFlat$k({}, attr); - out.editType = editTypeOverride; - if (Array.isArray(attr.items)) { - out.items = new Array(attr.items.length); - for (var i = 0; i < attr.items.length; i++) { - out.items[i] = overrideOne(attr.items[i], editTypeOverride); - } - } - return out; - } else { - return overrideAll$8( - attr, - editTypeOverride, - key.charAt(0) === "_" ? "nested" : "from-root" - ); - } -} -var attributes$M = {}; -attributes$M.dash = { - valType: "string", - // string type usually doesn't take values... this one should really be - // a special type or at least a special coercion function, from the GUI - // you only get these values but elsewhere the user can supply a list of - // dash lengths in px, and it will be honored - values: ["solid", "dot", "dash", "longdash", "dashdot", "longdashdot"], - dflt: "solid", - editType: "style", - description: [ - "Sets the dash style of lines. Set to a dash type string", - "(*solid*, *dot*, *dash*, *longdash*, *dashdot*, or *longdashdot*)", - "or a dash length list in px (eg *5px,10px,2px,2px*)." - ].join(" ") -}; -attributes$M.pattern = { - shape: { - valType: "enumerated", - values: ["", "/", "\\", "x", "-", "|", "+", "."], - dflt: "", - arrayOk: true, - editType: "style", - description: [ - "Sets the shape of the pattern fill.", - "By default, no pattern is used for filling the area." - ].join(" ") - }, - fillmode: { - valType: "enumerated", - values: ["replace", "overlay"], - dflt: "replace", - editType: "style", - description: [ - "Determines whether `marker.color` should be used", - "as a default to `bgcolor` or a `fgcolor`." - ].join(" ") - }, - bgcolor: { - valType: "color", - arrayOk: true, - editType: "style", - description: [ - "When there is no colorscale sets the color of background pattern fill.", - "Defaults to a `marker.color` background when `fillmode` is *overlay*.", - "Otherwise, defaults to a transparent background." - ].join(" ") - }, - fgcolor: { - valType: "color", - arrayOk: true, - editType: "style", - description: [ - "When there is no colorscale sets the color of foreground pattern fill.", - "Defaults to a `marker.color` background when `fillmode` is *replace*.", - "Otherwise, defaults to dark grey or white", - "to increase contrast with the `bgcolor`." - ].join(" ") - }, - fgopacity: { - valType: "number", - editType: "style", - min: 0, - max: 1, - description: [ - "Sets the opacity of the foreground pattern fill.", - "Defaults to a 0.5 when `fillmode` is *overlay*.", - "Otherwise, defaults to 1." - ].join(" ") - }, - size: { - valType: "number", - min: 0, - dflt: 8, - arrayOk: true, - editType: "style", - description: [ - "Sets the size of unit squares of the pattern fill in pixels,", - "which corresponds to the interval of repetition of the pattern." - ].join(" ") - }, - solidity: { - valType: "number", - min: 0, - max: 1, - dflt: 0.3, - arrayOk: true, - editType: "style", - description: [ - "Sets the solidity of the pattern fill.", - "Solidity is roughly the fraction of the area filled by the pattern.", - "Solidity of 0 shows only the background color without pattern", - "and solidty of 1 shows only the foreground color without pattern." - ].join(" ") - }, - editType: "style", - description: [ - "Sets the pattern within the marker." - ].join(" ") -}; -var template_attributes = {}; -var docs$2 = { - FORMAT_LINK: "https://github.com/d3/d3-format/tree/v1.4.5#d3-format", - DATE_FORMAT_LINK: "https://github.com/d3/d3-time-format/tree/v2.2.3#locale_format" -}; -var docs$1 = docs$2; -var FORMAT_LINK$1 = docs$1.FORMAT_LINK; -var DATE_FORMAT_LINK$1 = docs$1.DATE_FORMAT_LINK; -function templateFormatStringDescription(opts) { - var supportOther = opts && opts.supportOther; - return [ - "Variables are inserted using %{variable},", - 'for example "y: %{y}"' + (supportOther ? " as well as %{xother}, {%_xother}, {%_xother_}, {%xother_}. When showing info for several points, *xother* will be added to those with different x positions from the first point. An underscore before or after *(x|y)other* will add a space on that side, only when this field is shown." : "."), - `Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{y:$.2f}".`, - FORMAT_LINK$1, - "for details on the formatting syntax.", - `Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{2019-01-01|%A}".`, - DATE_FORMAT_LINK$1, - "for details on the date formatting syntax." - ].join(" "); -} -function shapeTemplateFormatStringDescription() { - return [ - "Variables are inserted using %{variable},", - 'for example "x0: %{x0}".', - `Numbers are formatted using d3-format's syntax %{variable:d3-format}, for example "Price: %{x0:$.2f}". See`, - FORMAT_LINK$1, - "for details on the formatting syntax.", - `Dates are formatted using d3-time-format's syntax %{variable|d3-time-format}, for example "Day: %{x0|%m %b %Y}". See`, - DATE_FORMAT_LINK$1, - "for details on the date formatting syntax.", - "A single multiplication or division operation may be applied to numeric variables, and combined with", - 'd3 number formatting, for example "Length in cm: %{x0*2.54}", "%{slope*60:.1f} meters per second."', - "For log axes, variable values are given in log units.", - "For date axes, x/y coordinate variables and center variables use datetimes, while all other variable values use values in ms." - ].join(" "); -} -function describeVariables(extra) { - var descPart = extra.description ? " " + extra.description : ""; - var keys = extra.keys || []; - if (keys.length > 0) { - var quotedKeys = []; - for (var i = 0; i < keys.length; i++) { - quotedKeys[i] = "`" + keys[i] + "`"; - } - descPart = descPart + "Finally, the template string has access to "; - if (keys.length === 1) { - descPart = descPart + "variable " + quotedKeys[0]; - } else { - descPart = descPart + "variables " + quotedKeys.slice(0, -1).join(", ") + " and " + quotedKeys.slice(-1) + "."; - } - } - return descPart; -} -template_attributes.hovertemplateAttrs = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; - var descPart = describeVariables(extra); - var hovertemplate = { - valType: "string", - dflt: "", - editType: opts.editType || "none", - description: [ - "Template string used for rendering the information that appear on hover box.", - "Note that this will override `hoverinfo`.", - templateFormatStringDescription({ supportOther: true }), - "The variables available in `hovertemplate` are the ones emitted as event data described at this link https://plotly.com/javascript/plotlyjs-events/#event-data.", - "Additionally, every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available.", - descPart, - 'Anything contained in tag `` is displayed in the secondary box, for example "{fullData.name}".', - "To hide the secondary box completely, use an empty tag ``." - ].join(" ") - }; - if (opts.arrayOk !== false) { - hovertemplate.arrayOk = true; - } - return hovertemplate; -}; -template_attributes.texttemplateAttrs = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; - var descPart = describeVariables(extra); - var texttemplate = { - valType: "string", - dflt: "", - editType: opts.editType || "calc", - description: [ - "Template string used for rendering the information text that appear on points.", - "Note that this will override `textinfo`.", - templateFormatStringDescription(), - "Every attributes that can be specified per-point (the ones that are `arrayOk: true`) are available.", - descPart - ].join(" ") - }; - if (opts.arrayOk !== false) { - texttemplate.arrayOk = true; - } - return texttemplate; -}; -template_attributes.shapeTexttemplateAttrs = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; - var newStr = opts.newshape ? "new " : ""; - var descPart = describeVariables(extra); - var texttemplate = { - valType: "string", - dflt: "", - editType: opts.editType || "arraydraw", - description: [ - "Template string used for rendering the " + newStr + "shape's label.", - "Note that this will override `text`.", - shapeTemplateFormatStringDescription(), - descPart - ].join(" ") - }; - return texttemplate; -}; -function d2l(v, axis) { - return axis ? axis.d2l(v) : v; -} -function l2d(v, axis) { - return axis ? axis.l2d(v) : v; -} -function x0Fn(shape) { - return shape.x0; -} -function x1Fn(shape) { - return shape.x1; -} -function y0Fn(shape) { - return shape.y0; -} -function y1Fn(shape) { - return shape.y1; -} -function x0shiftFn(shape) { - return shape.x0shift || 0; -} -function x1shiftFn(shape) { - return shape.x1shift || 0; -} -function y0shiftFn(shape) { - return shape.y0shift || 0; -} -function y1shiftFn(shape) { - return shape.y1shift || 0; -} -function dxFn(shape, xa) { - return d2l(shape.x1, xa) + x1shiftFn(shape) - d2l(shape.x0, xa) - x0shiftFn(shape); -} -function dyFn(shape, xa, ya) { - return d2l(shape.y1, ya) + y1shiftFn(shape) - d2l(shape.y0, ya) - y0shiftFn(shape); -} -function widthFn(shape, xa) { - return Math.abs(dxFn(shape, xa)); -} -function heightFn(shape, xa, ya) { - return Math.abs(dyFn(shape, xa, ya)); -} -function lengthFn(shape, xa, ya) { - return shape.type !== "line" ? void 0 : Math.sqrt( - Math.pow(dxFn(shape, xa), 2) + Math.pow(dyFn(shape, xa, ya), 2) - ); -} -function xcenterFn(shape, xa) { - return l2d((d2l(shape.x1, xa) + x1shiftFn(shape) + d2l(shape.x0, xa) + x0shiftFn(shape)) / 2, xa); -} -function ycenterFn(shape, xa, ya) { - return l2d((d2l(shape.y1, ya) + y1shiftFn(shape) + d2l(shape.y0, ya) + y0shiftFn(shape)) / 2, ya); -} -function slopeFn(shape, xa, ya) { - return shape.type !== "line" ? void 0 : dyFn(shape, xa, ya) / dxFn(shape, xa); -} -var label_texttemplate = { - x0: x0Fn, - x1: x1Fn, - y0: y0Fn, - y1: y1Fn, - slope: slopeFn, - dx: dxFn, - dy: dyFn, - width: widthFn, - height: heightFn, - length: lengthFn, - xcenter: xcenterFn, - ycenter: ycenterFn -}; -var overrideAll$7 = edit_types.overrideAll; -var basePlotAttributes$1 = attributes$O; -var fontAttrs$e = font_attributes; -var dash$6 = attributes$M.dash; -var extendFlat$j = extend$5.extendFlat; -var shapeTexttemplateAttrs$1 = template_attributes.shapeTexttemplateAttrs; -var shapeLabelTexttemplateVars$2 = label_texttemplate; -var attributes$L = overrideAll$7({ - newshape: { - visible: extendFlat$j({}, basePlotAttributes$1.visible, { - description: [ - "Determines whether or not new shape is visible.", - "If *legendonly*, the shape is not drawn,", - "but can appear as a legend item", - "(provided that the legend itself is visible)." - ].join(" ") - }), - showlegend: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether or not new", - "shape is shown in the legend." - ].join(" ") - }, - legend: extendFlat$j({}, basePlotAttributes$1.legend, { - description: [ - "Sets the reference to a legend to show new shape in.", - "References to these legends are *legend*, *legend2*, *legend3*, etc.", - "Settings for these legends are set in the layout, under", - "`layout.legend`, `layout.legend2`, etc." - ].join(" ") - }), - legendgroup: extendFlat$j({}, basePlotAttributes$1.legendgroup, { - description: [ - "Sets the legend group for new shape.", - "Traces and shapes part of the same legend group hide/show at the same time", - "when toggling legend items." - ].join(" ") - }), - legendgrouptitle: { - text: extendFlat$j({}, basePlotAttributes$1.legendgrouptitle.text, {}), - font: fontAttrs$e({ - description: [ - "Sets this legend group's title font." - ].join(" ") - }) - }, - legendrank: extendFlat$j({}, basePlotAttributes$1.legendrank, { - description: [ - "Sets the legend rank for new shape.", - "Items and groups with smaller ranks are presented on top/left side while", - "with *reversed* `legend.traceorder` they are on bottom/right side.", - "The default legendrank is 1000,", - "so that you can use ranks less than 1000 to place certain items before all unranked items,", - "and ranks greater than 1000 to go after all unranked items." - ].join(" ") - }), - legendwidth: extendFlat$j({}, basePlotAttributes$1.legendwidth, { - description: "Sets the width (in px or fraction) of the legend for new shape." - }), - line: { - color: { - valType: "color", - description: [ - "Sets the line color.", - "By default uses either dark grey or white", - "to increase contrast with background color." - ].join(" ") - }, - width: { - valType: "number", - min: 0, - dflt: 4, - description: "Sets the line width (in px)." - }, - dash: extendFlat$j({}, dash$6, { - dflt: "solid" - }) - }, - fillcolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - description: [ - "Sets the color filling new shapes' interior.", - "Please note that if using a fillcolor with alpha greater than half,", - "drag inside the active shape starts moving the shape underneath,", - "otherwise a new shape could be started over." - ].join(" ") - }, - fillrule: { - valType: "enumerated", - values: ["evenodd", "nonzero"], - dflt: "evenodd", - description: [ - "Determines the path's interior.", - "For more info please visit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule" - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 1, - description: "Sets the opacity of new shapes." - }, - layer: { - valType: "enumerated", - values: ["below", "above", "between"], - dflt: "above", - description: [ - "Specifies whether new shapes are drawn below gridlines (*below*),", - "between gridlines and traces (*between*) or above traces (*above*)." - ].join(" ") - }, - drawdirection: { - valType: "enumerated", - values: ["ortho", "horizontal", "vertical", "diagonal"], - dflt: "diagonal", - description: [ - "When `dragmode` is set to *drawrect*, *drawline* or *drawcircle*", - "this limits the drag to be horizontal, vertical or diagonal.", - "Using *diagonal* there is no limit e.g. in drawing lines in any direction.", - "*ortho* limits the draw to be either horizontal or vertical.", - "*horizontal* allows horizontal extend.", - "*vertical* allows vertical extend." - ].join(" ") - }, - name: extendFlat$j({}, basePlotAttributes$1.name, { - description: [ - "Sets new shape name.", - "The name appears as the legend item." - ].join(" ") - }), - label: { - text: { - valType: "string", - dflt: "", - description: [ - "Sets the text to display with the new shape.", - "It is also used for legend item if `name` is not provided." - ].join(" ") - }, - texttemplate: shapeTexttemplateAttrs$1({ newshape: true }, { keys: Object.keys(shapeLabelTexttemplateVars$2) }), - font: fontAttrs$e({ - description: "Sets the new shape label text font." - }), - textposition: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right", - "start", - "middle", - "end" - ], - description: [ - "Sets the position of the label text relative to the new shape.", - "Supported values for rectangles, circles and paths are", - "*top left*, *top center*, *top right*, *middle left*,", - "*middle center*, *middle right*, *bottom left*, *bottom center*,", - "and *bottom right*.", - "Supported values for lines are *start*, *middle*, and *end*.", - "Default: *middle center* for rectangles, circles, and paths; *middle* for lines." - ].join(" ") - }, - textangle: { - valType: "angle", - dflt: "auto", - description: [ - "Sets the angle at which the label text is drawn", - "with respect to the horizontal. For lines, angle *auto*", - "is the same angle as the line. For all other shapes,", - "angle *auto* is horizontal." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "auto", - description: [ - "Sets the label's horizontal position anchor", - "This anchor binds the specified `textposition` to the *left*, *center*", - "or *right* of the label text.", - "For example, if `textposition` is set to *top right* and", - "`xanchor` to *right* then the right-most portion of the", - "label text lines up with the right-most edge of the", - "new shape." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - description: [ - "Sets the label's vertical position anchor", - "This anchor binds the specified `textposition` to the *top*, *middle*", - "or *bottom* of the label text.", - "For example, if `textposition` is set to *top right* and", - "`yanchor` to *top* then the top-most portion of the", - "label text lines up with the top-most edge of the", - "new shape." - ].join(" ") - }, - padding: { - valType: "number", - dflt: 3, - min: 0, - description: "Sets padding (in px) between edge of label and edge of new shape." - } - } - }, - activeshape: { - fillcolor: { - valType: "color", - dflt: "rgb(255,0,255)", - description: "Sets the color filling the active shape' interior." - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 0.5, - description: "Sets the opacity of the active shape." - } - } -}, "none", "from-root"); -var dash$5 = attributes$M.dash; -var extendFlat$i = extend$5.extendFlat; -var attributes$K = { - newselection: { - mode: { - valType: "enumerated", - values: ["immediate", "gradual"], - dflt: "immediate", - editType: "none", - description: [ - "Describes how a new selection is created.", - "If `immediate`, a new selection is created after first mouse up.", - "If `gradual`, a new selection is not created after first mouse.", - "By adding to and subtracting from the initial selection,", - "this option allows declaring extra outlines of the selection." - ].join(" ") - }, - line: { - color: { - valType: "color", - editType: "none", - description: [ - "Sets the line color.", - "By default uses either dark grey or white", - "to increase contrast with background color." - ].join(" ") - }, - width: { - valType: "number", - min: 1, - dflt: 1, - editType: "none", - description: "Sets the line width (in px)." - }, - dash: extendFlat$i({}, dash$5, { - dflt: "dot", - editType: "none" - }), - editType: "none" - }, - // no drawdirection here noting that layout.selectdirection is used instead. - editType: "none" - }, - activeselection: { - fillcolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - editType: "none", - description: "Sets the color filling the active selection' interior." - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 0.5, - editType: "none", - description: "Sets the opacity of the active selection." - }, - editType: "none" - } -}; -var pad_attributes = function(opts) { - var editType = opts.editType; - return { - t: { - valType: "number", - dflt: 0, - editType, - description: "The amount of padding (in px) along the top of the component." - }, - r: { - valType: "number", - dflt: 0, - editType, - description: "The amount of padding (in px) on the right side of the component." - }, - b: { - valType: "number", - dflt: 0, - editType, - description: "The amount of padding (in px) along the bottom of the component." - }, - l: { - valType: "number", - dflt: 0, - editType, - description: "The amount of padding (in px) on the left side of the component." - }, - editType - }; -}; -var fontAttrs$d = font_attributes; -var animationAttrs$2 = animation_attributes; -var colorAttrs$6 = attributes$N; -var drawNewShapeAttrs = attributes$L; -var drawNewSelectionAttrs = attributes$K; -var padAttrs$2 = pad_attributes; -var extendFlat$h = extend$5.extendFlat; -var globalFont = fontAttrs$d({ - editType: "calc", - description: [ - "Sets the global font.", - "Note that fonts used in traces and other", - "layout components inherit from the global font." - ].join(" ") -}); -globalFont.family.dflt = '"Open Sans", verdana, arial, sans-serif'; -globalFont.size.dflt = 12; -globalFont.color.dflt = colorAttrs$6.defaultLine; -var layout_attributes$6 = { - font: globalFont, - title: { - text: { - valType: "string", - editType: "layoutstyle", - description: [ - "Sets the plot's title.", - "Note that before the existence of `title.text`, the title's", - "contents used to be defined as the `title` attribute itself.", - "This behavior has been deprecated." - ].join(" ") - }, - font: fontAttrs$d({ - editType: "layoutstyle", - description: [ - "Sets the title font.", - "Note that the title's font used to be customized", - "by the now deprecated `titlefont` attribute." - ].join(" ") - }), - subtitle: { - text: { - valType: "string", - editType: "layoutstyle", - description: "Sets the plot's subtitle." - }, - font: fontAttrs$d({ - editType: "layoutstyle", - description: "Sets the subtitle font." - }), - editType: "layoutstyle" - }, - xref: { - valType: "enumerated", - dflt: "container", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `x` refers to.", - "*container* spans the entire `width` of the plot.", - "*paper* refers to the width of the plotting area only." - ].join(" ") - }, - yref: { - valType: "enumerated", - dflt: "container", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `y` refers to.", - "*container* spans the entire `height` of the plot.", - "*paper* refers to the height of the plotting area only." - ].join(" ") - }, - x: { - valType: "number", - min: 0, - max: 1, - dflt: 0.5, - editType: "layoutstyle", - description: [ - "Sets the x position with respect to `xref` in normalized", - "coordinates from *0* (left) to *1* (right)." - ].join(" ") - }, - y: { - valType: "number", - min: 0, - max: 1, - dflt: "auto", - editType: "layoutstyle", - description: [ - "Sets the y position with respect to `yref` in normalized", - "coordinates from *0* (bottom) to *1* (top).", - "*auto* places the baseline of the title onto the", - "vertical center of the top margin." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - dflt: "auto", - values: ["auto", "left", "center", "right"], - editType: "layoutstyle", - description: [ - "Sets the title's horizontal alignment with respect to its x position.", - "*left* means that the title starts at x,", - "*right* means that the title ends at x", - "and *center* means that the title's center is at x.", - "*auto* divides `xref` by three and calculates the `xanchor`", - "value automatically based on the value of `x`." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - dflt: "auto", - values: ["auto", "top", "middle", "bottom"], - editType: "layoutstyle", - description: [ - "Sets the title's vertical alignment with respect to its y position.", - "*top* means that the title's cap line is at y,", - "*bottom* means that the title's baseline is at y", - "and *middle* means that the title's midline is at y.", - "*auto* divides `yref` by three and calculates the `yanchor`", - "value automatically based on the value of `y`." - ].join(" ") - }, - pad: extendFlat$h(padAttrs$2({ editType: "layoutstyle" }), { - description: [ - "Sets the padding of the title.", - "Each padding value only applies when the corresponding", - "`xanchor`/`yanchor` value is set accordingly. E.g. for left", - "padding to take effect, `xanchor` must be set to *left*.", - "The same rule applies if `xanchor`/`yanchor` is determined automatically.", - "Padding is muted if the respective anchor value is *middle*/*center*." - ].join(" ") - }), - automargin: { - valType: "boolean", - dflt: false, - editType: "plot", - description: [ - "Determines whether the title can automatically push the figure margins.", - "If `yref='paper'` then the margin will expand to ensure that the title doesn’t", - "overlap with the edges of the container. If `yref='container'` then the margins", - "will ensure that the title doesn’t overlap with the plot area, tick labels,", - "and axis titles. If `automargin=true` and the margins need to be expanded,", - "then y will be set to a default 1 and yanchor will be set to an appropriate", - "default to ensure that minimal margin space is needed. Note that when `yref='paper'`,", - "only 1 or 0 are allowed y values. Invalid values will be reset to the default 1." - ].join(" ") - }, - editType: "layoutstyle" - }, - uniformtext: { - mode: { - valType: "enumerated", - values: [false, "hide", "show"], - dflt: false, - editType: "plot", - description: [ - "Determines how the font size for various text", - "elements are uniformed between each trace type.", - "If the computed text sizes were smaller than", - "the minimum size defined by `uniformtext.minsize`", - "using *hide* option hides the text; and", - "using *show* option shows the text without further downscaling.", - "Please note that if the size defined by `minsize` is greater than", - "the font size defined by trace, then the `minsize` is used." - ].join(" ") - }, - minsize: { - valType: "number", - min: 0, - dflt: 0, - editType: "plot", - description: [ - "Sets the minimum text size between traces of the same type." - ].join(" ") - }, - editType: "plot" - }, - autosize: { - valType: "boolean", - dflt: false, - // autosize, width, and height get special editType treatment in _relayout - // so we can handle noop resizes more efficiently - editType: "none", - description: [ - "Determines whether or not a layout width or height", - "that has been left undefined by the user", - "is initialized on each relayout.", - "Note that, regardless of this attribute,", - "an undefined layout width or height", - "is always initialized on the first call to plot." - ].join(" ") - }, - width: { - valType: "number", - min: 10, - dflt: 700, - editType: "plot", - description: [ - "Sets the plot's width (in px)." - ].join(" ") - }, - height: { - valType: "number", - min: 10, - dflt: 450, - editType: "plot", - description: [ - "Sets the plot's height (in px)." - ].join(" ") - }, - minreducedwidth: { - valType: "number", - min: 2, - dflt: 64, - editType: "plot", - description: "Minimum width of the plot with margin.automargin applied (in px)" - }, - minreducedheight: { - valType: "number", - min: 2, - dflt: 64, - editType: "plot", - description: "Minimum height of the plot with margin.automargin applied (in px)" - }, - margin: { - l: { - valType: "number", - min: 0, - dflt: 80, - editType: "plot", - description: "Sets the left margin (in px)." - }, - r: { - valType: "number", - min: 0, - dflt: 80, - editType: "plot", - description: "Sets the right margin (in px)." - }, - t: { - valType: "number", - min: 0, - dflt: 100, - editType: "plot", - description: "Sets the top margin (in px)." - }, - b: { - valType: "number", - min: 0, - dflt: 80, - editType: "plot", - description: "Sets the bottom margin (in px)." - }, - pad: { - valType: "number", - min: 0, - dflt: 0, - editType: "plot", - description: [ - "Sets the amount of padding (in px)", - "between the plotting area and the axis lines" - ].join(" ") - }, - autoexpand: { - valType: "boolean", - dflt: true, - editType: "plot", - description: [ - "Turns on/off margin expansion computations.", - "Legends, colorbars, updatemenus, sliders, axis rangeselector and rangeslider", - "are allowed to push the margins by defaults." - ].join(" ") - }, - editType: "plot" - }, - computed: { - valType: "any", - editType: "none", - description: [ - "Placeholder for exporting automargin-impacting values namely", - "`margin.t`, `margin.b`, `margin.l` and `margin.r` in *full-json* mode." - ].join(" ") - }, - paper_bgcolor: { - valType: "color", - dflt: colorAttrs$6.background, - editType: "plot", - description: "Sets the background color of the paper where the graph is drawn." - }, - plot_bgcolor: { - // defined here, but set in cartesian.supplyLayoutDefaults - // because it needs to know if there are (2D) axes or not - valType: "color", - dflt: colorAttrs$6.background, - editType: "layoutstyle", - description: [ - "Sets the background color of the plotting area in-between x and y axes." - ].join(" ") - }, - autotypenumbers: { - valType: "enumerated", - values: ["convert types", "strict"], - dflt: "convert types", - editType: "calc", - description: [ - "Using *strict* a numeric string in trace data is not converted to a number.", - "Using *convert types* a numeric string in trace data may be", - "treated as a number during automatic axis `type` detection.", - "This is the default value; however it could be overridden for individual axes." - ].join(" ") - }, - separators: { - valType: "string", - editType: "plot", - description: [ - "Sets the decimal and thousand separators.", - "For example, *. * puts a '.' before decimals and a space", - "between thousands. In English locales, dflt is *.,* but", - "other locales may alter this default." - ].join(" ") - }, - hidesources: { - valType: "boolean", - dflt: false, - editType: "plot", - description: [ - "Determines whether or not a text link citing the data source is", - "placed at the bottom-right cored of the figure.", - "Has only an effect only on graphs that have been generated via", - "forked graphs from the Chart Studio Cloud (at https://chart-studio.plotly.com or on-premise)." - ].join(" ") - }, - showlegend: { - // handled in legend.supplyLayoutDefaults - // but included here because it's not in the legend object - valType: "boolean", - editType: "legend", - description: [ - "Determines whether or not a legend is drawn.", - "Default is `true` if there is a trace to show and any of these:", - "a) Two or more traces would by default be shown in the legend.", - "b) One pie trace is shown in the legend.", - "c) One trace is explicitly given with `showlegend: true`." - ].join(" ") - }, - colorway: { - valType: "colorlist", - dflt: colorAttrs$6.defaults, - editType: "calc", - description: "Sets the default trace colors." - }, - datarevision: { - valType: "any", - editType: "calc", - description: [ - "If provided, a changed value tells `Plotly.react` that", - "one or more data arrays has changed. This way you can modify", - "arrays in-place rather than making a complete new copy for an", - "incremental change.", - "If NOT provided, `Plotly.react` assumes that data arrays are", - "being treated as immutable, thus any data array with a", - "different identity from its predecessor contains new data." - ].join(" ") - }, - uirevision: { - valType: "any", - editType: "none", - description: [ - "Used to allow user interactions with the plot to persist after", - "`Plotly.react` calls that are unaware of these interactions.", - "If `uirevision` is omitted, or if it is given and it changed from", - "the previous `Plotly.react` call, the exact new figure is used.", - "If `uirevision` is truthy and did NOT change, any attribute", - "that has been affected by user interactions and did not receive a", - "different value in the new figure will keep the interaction value.", - "`layout.uirevision` attribute serves as the default for", - "`uirevision` attributes in various sub-containers. For finer", - "control you can set these sub-attributes directly. For example,", - "if your app separately controls the data on the x and y axes you", - "might set `xaxis.uirevision=*time*` and `yaxis.uirevision=*cost*`.", - "Then if only the y data is changed, you can update", - "`yaxis.uirevision=*quantity*` and the y axis range will reset but", - "the x axis range will retain any user-driven zoom." - ].join(" ") - }, - editrevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of user-driven changes in `editable: true`", - "configuration, other than trace names and axis titles.", - "Defaults to `layout.uirevision`." - ].join(" ") - }, - selectionrevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of user-driven changes in selected points", - "from all traces." - ].join(" ") - }, - template: { - valType: "any", - editType: "calc", - description: [ - "Default attributes to be applied to the plot. Templates can be", - "created from existing plots using `Plotly.makeTemplate`, or", - "created manually. They should be objects with format:", - "`{layout: layoutTemplate, data: {[type]: [traceTemplate, ...]}, ...}`", - "`layoutTemplate` and `traceTemplate` are objects matching the", - "attribute structure of `layout` and a data trace. ", - "Trace templates are applied cyclically to traces of each type.", - "Container arrays (eg `annotations`) have special handling:", - "An object ending in `defaults` (eg `annotationdefaults`) is applied", - "to each array item. But if an item has a `templateitemname` key", - "we look in the template array for an item with matching `name` and", - "apply that instead. If no matching `name` is found we mark the item", - "invisible. Any named template item not referenced is appended to", - "the end of the array, so you can use this for a watermark annotation", - "or a logo image, for example. To omit one of these items on the plot,", - "make an item with matching `templateitemname` and `visible: false`." - ].join(" ") - }, - newshape: drawNewShapeAttrs.newshape, - activeshape: drawNewShapeAttrs.activeshape, - newselection: drawNewSelectionAttrs.newselection, - activeselection: drawNewSelectionAttrs.activeselection, - meta: { - valType: "any", - arrayOk: true, - editType: "plot", - description: [ - "Assigns extra meta information that can be used in various `text` attributes.", - "Attributes such as the graph, axis and colorbar `title.text`, annotation `text`", - "`trace.name` in legend items, `rangeselector`, `updatemenus` and `sliders` `label` text", - "all support `meta`. One can access `meta` fields using template strings:", - "`%{meta[i]}` where `i` is the index of the `meta`", - "item in question.", - "`meta` can also be an object for example `{key: value}` which can be accessed", - "%{meta[key]}." - ].join(" ") - }, - transition: extendFlat$h({}, animationAttrs$2.transition, { - description: [ - "Sets transition options used during Plotly.react updates." - ].join(" "), - editType: "none" - }), - _deprecated: { - title: { - valType: "string", - editType: "layoutstyle", - description: [ - "Value of `title` is no longer a simple *string* but a set of sub-attributes.", - "To set the contents of the title, please use `title.text` now." - ].join(" ") - }, - titlefont: fontAttrs$d({ - editType: "layoutstyle", - description: [ - "Former `titlefont` is now the sub-attribute `font` of `title`.", - "To customize title font properties, please use `title.font` now." - ].join(" ") - }) - } -}; -(function(exports2) { - var Loggers2 = loggersExports; - var noop3 = noop$2; - var pushUnique3 = push_unique; - var isPlainObject3 = is_plain_object; - var addStyleRule2 = dom.addStyleRule; - var ExtendModule = extend$5; - var basePlotAttributes2 = attributes$O; - var baseLayoutAttributes = layout_attributes$6; - var extendFlat2 = ExtendModule.extendFlat; - var extendDeepAll2 = ExtendModule.extendDeepAll; - exports2.modules = {}; - exports2.allCategories = {}; - exports2.allTypes = []; - exports2.subplotsRegistry = {}; - exports2.transformsRegistry = {}; - exports2.componentsRegistry = {}; - exports2.layoutArrayContainers = []; - exports2.layoutArrayRegexes = []; - exports2.traceLayoutAttributes = {}; - exports2.localeRegistry = {}; - exports2.apiMethodRegistry = {}; - exports2.collectableSubplotTypes = null; - exports2.register = function register(_modules) { - exports2.collectableSubplotTypes = null; - if (!_modules) { - throw new Error("No argument passed to Plotly.register."); - } else if (_modules && !Array.isArray(_modules)) { - _modules = [_modules]; - } - for (var i = 0; i < _modules.length; i++) { - var newModule = _modules[i]; - if (!newModule) { - throw new Error("Invalid module was attempted to be registered!"); - } - switch (newModule.moduleType) { - case "trace": - registerTraceModule(newModule); - break; - case "transform": - registerTransformModule(newModule); - break; - case "component": - registerComponentModule(newModule); - break; - case "locale": - registerLocale(newModule); - break; - case "apiMethod": - var name2 = newModule.name; - exports2.apiMethodRegistry[name2] = newModule.fn; - break; - default: - throw new Error("Invalid module was attempted to be registered!"); - } - } - }; - exports2.getModule = function(trace) { - var _module = exports2.modules[getTraceType(trace)]; - if (!_module) return false; - return _module._module; - }; - exports2.traceIs = function(traceType, category2) { - traceType = getTraceType(traceType); - if (traceType === "various") return false; - var _module = exports2.modules[traceType]; - if (!_module) { - if (traceType) { - Loggers2.log("Unrecognized trace type " + traceType + "."); - } - _module = exports2.modules[basePlotAttributes2.type.dflt]; - } - return !!_module.categories[category2]; - }; - exports2.getTransformIndices = function(data, type) { - var indices = []; - var transforms = data.transforms || []; - for (var i = 0; i < transforms.length; i++) { - if (transforms[i].type === type) { - indices.push(i); - } - } - return indices; - }; - exports2.hasTransform = function(data, type) { - var transforms = data.transforms || []; - for (var i = 0; i < transforms.length; i++) { - if (transforms[i].type === type) { - return true; - } - } - return false; - }; - exports2.getComponentMethod = function(name2, method) { - var _module = exports2.componentsRegistry[name2]; - if (!_module) return noop3; - return _module[method] || noop3; - }; - exports2.call = function() { - var name2 = arguments[0]; - var args = [].slice.call(arguments, 1); - return exports2.apiMethodRegistry[name2].apply(null, args); - }; - function registerTraceModule(_module) { - var thisType = _module.name; - var categoriesIn = _module.categories; - var meta = _module.meta; - if (exports2.modules[thisType]) { - Loggers2.log("Type " + thisType + " already registered"); - return; - } - if (!exports2.subplotsRegistry[_module.basePlotModule.name]) { - registerSubplot(_module.basePlotModule); - } - var categoryObj = {}; - for (var i = 0; i < categoriesIn.length; i++) { - categoryObj[categoriesIn[i]] = true; - exports2.allCategories[categoriesIn[i]] = true; - } - exports2.modules[thisType] = { - _module, - categories: categoryObj - }; - if (meta && Object.keys(meta).length) { - exports2.modules[thisType].meta = meta; - } - exports2.allTypes.push(thisType); - for (var componentName in exports2.componentsRegistry) { - mergeComponentAttrsToTrace(componentName, thisType); - } - if (_module.layoutAttributes) { - extendFlat2(exports2.traceLayoutAttributes, _module.layoutAttributes); - } - var basePlotModule = _module.basePlotModule; - var bpmName = basePlotModule.name; - if (bpmName === "mapbox") { - var styleRules = basePlotModule.constants.styleRules; - for (var k in styleRules) { - addStyleRule2(".js-plotly-plot .plotly .mapboxgl-" + k, styleRules[k]); - } - } - if ((bpmName === "geo" || bpmName === "mapbox" || bpmName === "map") && window.PlotlyGeoAssets === void 0) { - window.PlotlyGeoAssets = { topojson: {} }; - } - } - function registerSubplot(_module) { - var plotType = _module.name; - if (exports2.subplotsRegistry[plotType]) { - Loggers2.log("Plot type " + plotType + " already registered."); - return; - } - findArrayRegexps(_module); - exports2.subplotsRegistry[plotType] = _module; - for (var componentName in exports2.componentsRegistry) { - mergeComponentAttrsToSubplot(componentName, _module.name); - } - } - function registerComponentModule(_module) { - if (typeof _module.name !== "string") { - throw new Error("Component module *name* must be a string."); - } - var name2 = _module.name; - exports2.componentsRegistry[name2] = _module; - if (_module.layoutAttributes) { - if (_module.layoutAttributes._isLinkedToArray) { - pushUnique3(exports2.layoutArrayContainers, name2); - } - findArrayRegexps(_module); - } - for (var traceType in exports2.modules) { - mergeComponentAttrsToTrace(name2, traceType); - } - for (var subplotName in exports2.subplotsRegistry) { - mergeComponentAttrsToSubplot(name2, subplotName); - } - for (var transformType in exports2.transformsRegistry) { - mergeComponentAttrsToTransform(name2, transformType); - } - if (_module.schema && _module.schema.layout) { - extendDeepAll2(baseLayoutAttributes, _module.schema.layout); - } - } - function registerTransformModule(_module) { - if (typeof _module.name !== "string") { - throw new Error("Transform module *name* must be a string."); - } - var prefix = "Transform module " + _module.name; - var hasTransform = typeof _module.transform === "function"; - var hasCalcTransform = typeof _module.calcTransform === "function"; - if (!hasTransform && !hasCalcTransform) { - throw new Error(prefix + " is missing a *transform* or *calcTransform* method."); - } - if (hasTransform && hasCalcTransform) { - Loggers2.log([ - prefix + " has both a *transform* and *calcTransform* methods.", - "Please note that all *transform* methods are executed", - "before all *calcTransform* methods." - ].join(" ")); - } - if (!isPlainObject3(_module.attributes)) { - Loggers2.log(prefix + " registered without an *attributes* object."); - } - if (typeof _module.supplyDefaults !== "function") { - Loggers2.log(prefix + " registered without a *supplyDefaults* method."); - } - exports2.transformsRegistry[_module.name] = _module; - for (var componentName in exports2.componentsRegistry) { - mergeComponentAttrsToTransform(componentName, _module.name); - } - } - function registerLocale(_module) { - var locale2 = _module.name; - var baseLocale = locale2.split("-")[0]; - var newDict = _module.dictionary; - var newFormat = _module.format; - var hasDict = newDict && Object.keys(newDict).length; - var hasFormat = newFormat && Object.keys(newFormat).length; - var locales = exports2.localeRegistry; - var localeObj = locales[locale2]; - if (!localeObj) locales[locale2] = localeObj = {}; - if (baseLocale !== locale2) { - var baseLocaleObj = locales[baseLocale]; - if (!baseLocaleObj) locales[baseLocale] = baseLocaleObj = {}; - if (hasDict && baseLocaleObj.dictionary === localeObj.dictionary) { - baseLocaleObj.dictionary = newDict; - } - if (hasFormat && baseLocaleObj.format === localeObj.format) { - baseLocaleObj.format = newFormat; - } - } - if (hasDict) localeObj.dictionary = newDict; - if (hasFormat) localeObj.format = newFormat; - } - function findArrayRegexps(_module) { - if (_module.layoutAttributes) { - var arrayAttrRegexps = _module.layoutAttributes._arrayAttrRegexps; - if (arrayAttrRegexps) { - for (var i = 0; i < arrayAttrRegexps.length; i++) { - pushUnique3(exports2.layoutArrayRegexes, arrayAttrRegexps[i]); - } - } - } - } - function mergeComponentAttrsToTrace(componentName, traceType) { - var componentSchema = exports2.componentsRegistry[componentName].schema; - if (!componentSchema || !componentSchema.traces) return; - var traceAttrs = componentSchema.traces[traceType]; - if (traceAttrs) { - extendDeepAll2(exports2.modules[traceType]._module.attributes, traceAttrs); - } - } - function mergeComponentAttrsToTransform(componentName, transformType) { - var componentSchema = exports2.componentsRegistry[componentName].schema; - if (!componentSchema || !componentSchema.transforms) return; - var transformAttrs = componentSchema.transforms[transformType]; - if (transformAttrs) { - extendDeepAll2(exports2.transformsRegistry[transformType].attributes, transformAttrs); - } - } - function mergeComponentAttrsToSubplot(componentName, subplotName) { - var componentSchema = exports2.componentsRegistry[componentName].schema; - if (!componentSchema || !componentSchema.subplots) return; - var subplotModule = exports2.subplotsRegistry[subplotName]; - var subplotAttrs = subplotModule.layoutAttributes; - var subplotAttr = subplotModule.attr === "subplot" ? subplotModule.name : subplotModule.attr; - if (Array.isArray(subplotAttr)) subplotAttr = subplotAttr[0]; - var componentLayoutAttrs = componentSchema.subplots[subplotAttr]; - if (subplotAttrs && componentLayoutAttrs) { - extendDeepAll2(subplotAttrs, componentLayoutAttrs); - } - } - function getTraceType(traceType) { - if (typeof traceType === "object") traceType = traceType.type; - return traceType; - } -})(registry); -(function(exports2) { - var timeFormat2 = require$$1$1.timeFormat; - var isNumeric2 = fastIsnumeric; - var Loggers2 = loggersExports; - var mod2 = mod_1.mod; - var constants2 = numerical; - var BADNUM2 = constants2.BADNUM; - var ONEDAY2 = constants2.ONEDAY; - var ONEHOUR2 = constants2.ONEHOUR; - var ONEMIN2 = constants2.ONEMIN; - var ONESEC2 = constants2.ONESEC; - var EPOCHJD = constants2.EPOCHJD; - var Registry2 = registry; - var utcFormat2 = require$$1$1.utcFormat; - var DATETIME_REGEXP = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\d)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m; - var DATETIME_REGEXP_CN = /^\s*(-?\d\d\d\d|\d\d)(-(\d?\di?)(-(\d?\d)([ Tt]([01]?\d|2[0-3])(:([0-5]\d)(:([0-5]\d(\.\d+)?))?(Z|z|[+\-]\d\d(:?\d\d)?)?)?)?)?)?\s*$/m; - var YFIRST = (/* @__PURE__ */ new Date()).getFullYear() - 70; - function isWorldCalendar(calendar) { - return calendar && Registry2.componentsRegistry.calendars && typeof calendar === "string" && calendar !== "gregorian"; - } - exports2.dateTick0 = function(calendar, dayOfWeek) { - var tick02 = _dateTick0(calendar, !!dayOfWeek); - if (dayOfWeek < 2) return tick02; - var v = exports2.dateTime2ms(tick02, calendar); - v += ONEDAY2 * (dayOfWeek - 1); - return exports2.ms2DateTime(v, 0, calendar); - }; - function _dateTick0(calendar, sunday2) { - if (isWorldCalendar(calendar)) { - return sunday2 ? Registry2.getComponentMethod("calendars", "CANONICAL_SUNDAY")[calendar] : Registry2.getComponentMethod("calendars", "CANONICAL_TICK")[calendar]; - } else { - return sunday2 ? "2000-01-02" : "2000-01-01"; - } - } - exports2.dfltRange = function(calendar) { - if (isWorldCalendar(calendar)) { - return Registry2.getComponentMethod("calendars", "DFLTRANGE")[calendar]; - } else { - return ["2000-01-01", "2001-01-01"]; - } - }; - exports2.isJSDate = function(v) { - return typeof v === "object" && v !== null && typeof v.getTime === "function"; - }; - var MIN_MS, MAX_MS; - exports2.dateTime2ms = function(s, calendar) { - if (exports2.isJSDate(s)) { - var tzOffset = s.getTimezoneOffset() * ONEMIN2; - var offsetTweak = (s.getUTCMinutes() - s.getMinutes()) * ONEMIN2 + (s.getUTCSeconds() - s.getSeconds()) * ONESEC2 + (s.getUTCMilliseconds() - s.getMilliseconds()); - if (offsetTweak) { - var comb = 3 * ONEMIN2; - tzOffset = tzOffset - comb / 2 + mod2(offsetTweak - tzOffset + comb / 2, comb); - } - s = Number(s) - tzOffset; - if (s >= MIN_MS && s <= MAX_MS) return s; - return BADNUM2; - } - if (typeof s !== "string" && typeof s !== "number") return BADNUM2; - s = String(s); - var isWorld = isWorldCalendar(calendar); - var s0 = s.charAt(0); - if (isWorld && (s0 === "G" || s0 === "g")) { - s = s.substr(1); - calendar = ""; - } - var isChinese = isWorld && calendar.substr(0, 7) === "chinese"; - var match = s.match(isChinese ? DATETIME_REGEXP_CN : DATETIME_REGEXP); - if (!match) return BADNUM2; - var y = match[1]; - var m = match[3] || "1"; - var d = Number(match[5] || 1); - var H = Number(match[7] || 0); - var M = Number(match[9] || 0); - var S = Number(match[11] || 0); - if (isWorld) { - if (y.length === 2) return BADNUM2; - y = Number(y); - var cDate; - try { - var calInstance = Registry2.getComponentMethod("calendars", "getCal")(calendar); - if (isChinese) { - var isIntercalary = m.charAt(m.length - 1) === "i"; - m = parseInt(m, 10); - cDate = calInstance.newDate(y, calInstance.toMonthIndex(y, m, isIntercalary), d); - } else { - cDate = calInstance.newDate(y, Number(m), d); - } - } catch (e) { - return BADNUM2; - } - if (!cDate) return BADNUM2; - return (cDate.toJD() - EPOCHJD) * ONEDAY2 + H * ONEHOUR2 + M * ONEMIN2 + S * ONESEC2; - } - if (y.length === 2) { - y = (Number(y) + 2e3 - YFIRST) % 100 + YFIRST; - } else y = Number(y); - m -= 1; - var date2 = new Date(Date.UTC(2e3, m, d, H, M)); - date2.setUTCFullYear(y); - if (date2.getUTCMonth() !== m) return BADNUM2; - if (date2.getUTCDate() !== d) return BADNUM2; - return date2.getTime() + S * ONESEC2; - }; - MIN_MS = exports2.MIN_MS = exports2.dateTime2ms("-9999"); - MAX_MS = exports2.MAX_MS = exports2.dateTime2ms("9999-12-31 23:59:59.9999"); - exports2.isDateTime = function(s, calendar) { - return exports2.dateTime2ms(s, calendar) !== BADNUM2; - }; - function lpad(val, digits) { - return String(val + Math.pow(10, digits)).substr(1); - } - var NINETYDAYS = 90 * ONEDAY2; - var THREEHOURS = 3 * ONEHOUR2; - var FIVEMIN = 5 * ONEMIN2; - exports2.ms2DateTime = function(ms, r, calendar) { - if (typeof ms !== "number" || !(ms >= MIN_MS && ms <= MAX_MS)) return BADNUM2; - if (!r) r = 0; - var msecTenths = Math.floor(mod2(ms + 0.05, 1) * 10); - var msRounded = Math.round(ms - msecTenths / 10); - var dateStr, h, m, s, msec10, d; - if (isWorldCalendar(calendar)) { - var dateJD = Math.floor(msRounded / ONEDAY2) + EPOCHJD; - var timeMs = Math.floor(mod2(ms, ONEDAY2)); - try { - dateStr = Registry2.getComponentMethod("calendars", "getCal")(calendar).fromJD(dateJD).formatDate("yyyy-mm-dd"); - } catch (e) { - dateStr = utcFormat2("G%Y-%m-%d")(new Date(msRounded)); - } - if (dateStr.charAt(0) === "-") { - while (dateStr.length < 11) dateStr = "-0" + dateStr.substr(1); - } else { - while (dateStr.length < 10) dateStr = "0" + dateStr; - } - h = r < NINETYDAYS ? Math.floor(timeMs / ONEHOUR2) : 0; - m = r < NINETYDAYS ? Math.floor(timeMs % ONEHOUR2 / ONEMIN2) : 0; - s = r < THREEHOURS ? Math.floor(timeMs % ONEMIN2 / ONESEC2) : 0; - msec10 = r < FIVEMIN ? timeMs % ONESEC2 * 10 + msecTenths : 0; - } else { - d = new Date(msRounded); - dateStr = utcFormat2("%Y-%m-%d")(d); - h = r < NINETYDAYS ? d.getUTCHours() : 0; - m = r < NINETYDAYS ? d.getUTCMinutes() : 0; - s = r < THREEHOURS ? d.getUTCSeconds() : 0; - msec10 = r < FIVEMIN ? d.getUTCMilliseconds() * 10 + msecTenths : 0; - } - return includeTime(dateStr, h, m, s, msec10); - }; - exports2.ms2DateTimeLocal = function(ms) { - if (!(ms >= MIN_MS + ONEDAY2 && ms <= MAX_MS - ONEDAY2)) return BADNUM2; - var msecTenths = Math.floor(mod2(ms + 0.05, 1) * 10); - var d = new Date(Math.round(ms - msecTenths / 10)); - var dateStr = timeFormat2("%Y-%m-%d")(d); - var h = d.getHours(); - var m = d.getMinutes(); - var s = d.getSeconds(); - var msec10 = d.getUTCMilliseconds() * 10 + msecTenths; - return includeTime(dateStr, h, m, s, msec10); - }; - function includeTime(dateStr, h, m, s, msec10) { - if (h || m || s || msec10) { - dateStr += " " + lpad(h, 2) + ":" + lpad(m, 2); - if (s || msec10) { - dateStr += ":" + lpad(s, 2); - if (msec10) { - var digits = 4; - while (msec10 % 10 === 0) { - digits -= 1; - msec10 /= 10; - } - dateStr += "." + lpad(msec10, digits); - } - } - } - return dateStr; - } - exports2.cleanDate = function(v, dflt, calendar) { - if (v === BADNUM2) return dflt; - if (exports2.isJSDate(v) || typeof v === "number" && isFinite(v)) { - if (isWorldCalendar(calendar)) { - Loggers2.error("JS Dates and milliseconds are incompatible with world calendars", v); - return dflt; - } - v = exports2.ms2DateTimeLocal(+v); - if (!v && dflt !== void 0) return dflt; - } else if (!exports2.isDateTime(v, calendar)) { - Loggers2.error("unrecognized date", v); - return dflt; - } - return v; - }; - var fracMatch = /%\d?f/g; - var halfYearMatch = /%h/g; - var quarterToHalfYear = { - 1: "1", - 2: "1", - 3: "2", - 4: "2" - }; - function modDateFormat(fmt, x, formatter, calendar) { - fmt = fmt.replace(fracMatch, function(match) { - var digits = Math.min(+match.charAt(1) || 6, 6); - var fracSecs = (x / 1e3 % 1 + 2).toFixed(digits).substr(2).replace(/0+$/, "") || "0"; - return fracSecs; - }); - var d = new Date(Math.floor(x + 0.05)); - fmt = fmt.replace(halfYearMatch, function() { - return quarterToHalfYear[formatter("%q")(d)]; - }); - if (isWorldCalendar(calendar)) { - try { - fmt = Registry2.getComponentMethod("calendars", "worldCalFmt")(fmt, x, calendar); - } catch (e) { - return "Invalid"; - } - } - return formatter(fmt)(d); - } - var MAXSECONDS = [59, 59.9, 59.99, 59.999, 59.9999]; - function formatTime(x, tr) { - var timePart = mod2(x + 0.05, ONEDAY2); - var timeStr = lpad(Math.floor(timePart / ONEHOUR2), 2) + ":" + lpad(mod2(Math.floor(timePart / ONEMIN2), 60), 2); - if (tr !== "M") { - if (!isNumeric2(tr)) tr = 0; - var sec = Math.min(mod2(x / ONESEC2, 60), MAXSECONDS[tr]); - var secStr = (100 + sec).toFixed(tr).substr(1); - if (tr > 0) { - secStr = secStr.replace(/0+$/, "").replace(/[\.]$/, ""); - } - timeStr += ":" + secStr; - } - return timeStr; - } - exports2.formatDate = function(x, fmt, tr, formatter, calendar, extraFormat) { - calendar = isWorldCalendar(calendar) && calendar; - if (!fmt) { - if (tr === "y") fmt = extraFormat.year; - else if (tr === "m") fmt = extraFormat.month; - else if (tr === "d") { - fmt = extraFormat.dayMonth + "\n" + extraFormat.year; - } else { - return formatTime(x, tr) + "\n" + modDateFormat(extraFormat.dayMonthYear, x, formatter, calendar); - } - } - return modDateFormat(fmt, x, formatter, calendar); - }; - var THREEDAYS = 3 * ONEDAY2; - exports2.incrementMonth = function(ms, dMonth, calendar) { - calendar = isWorldCalendar(calendar) && calendar; - var timeMs = mod2(ms, ONEDAY2); - ms = Math.round(ms - timeMs); - if (calendar) { - try { - var dateJD = Math.round(ms / ONEDAY2) + EPOCHJD; - var calInstance = Registry2.getComponentMethod("calendars", "getCal")(calendar); - var cDate = calInstance.fromJD(dateJD); - if (dMonth % 12) calInstance.add(cDate, dMonth, "m"); - else calInstance.add(cDate, dMonth / 12, "y"); - return (cDate.toJD() - EPOCHJD) * ONEDAY2 + timeMs; - } catch (e) { - Loggers2.error("invalid ms " + ms + " in calendar " + calendar); - } - } - var y = new Date(ms + THREEDAYS); - return y.setUTCMonth(y.getUTCMonth() + dMonth) + timeMs - THREEDAYS; - }; - exports2.findExactDates = function(data, calendar) { - var exactYears = 0; - var exactMonths = 0; - var exactDays = 0; - var blankCount = 0; - var d; - var di; - var calInstance = isWorldCalendar(calendar) && Registry2.getComponentMethod("calendars", "getCal")(calendar); - for (var i = 0; i < data.length; i++) { - di = data[i]; - if (!isNumeric2(di)) { - blankCount++; - continue; - } - if (di % ONEDAY2) continue; - if (calInstance) { - try { - d = calInstance.fromJD(di / ONEDAY2 + EPOCHJD); - if (d.day() === 1) { - if (d.month() === 1) exactYears++; - else exactMonths++; - } else exactDays++; - } catch (e) { - } - } else { - d = new Date(di); - if (d.getUTCDate() === 1) { - if (d.getUTCMonth() === 0) exactYears++; - else exactMonths++; - } else exactDays++; - } - } - exactMonths += exactYears; - exactDays += exactMonths; - var dataCount = data.length - blankCount; - return { - exactYears: exactYears / dataCount, - exactMonths: exactMonths / dataCount, - exactDays: exactDays / dataCount - }; - }; -})(dates); -var search$1 = {}; -var identity$2 = function identity(d) { - return d; -}; -(function(exports2) { - var isNumeric2 = fastIsnumeric; - var loggers2 = loggersExports; - var identity3 = identity$2; - var BADNUM2 = numerical.BADNUM; - var roundingError = 1e-9; - exports2.findBin = function(val, bins, linelow) { - if (isNumeric2(bins.start)) { - return linelow ? Math.ceil((val - bins.start) / bins.size - roundingError) - 1 : Math.floor((val - bins.start) / bins.size + roundingError); - } else { - var n1 = 0; - var n2 = bins.length; - var c = 0; - var binSize = n2 > 1 ? (bins[n2 - 1] - bins[0]) / (n2 - 1) : 1; - var n, test; - if (binSize >= 0) { - test = linelow ? lessThan : lessOrEqual2; - } else { - test = linelow ? greaterOrEqual2 : greaterThan; - } - val += binSize * roundingError * (linelow ? -1 : 1) * (binSize >= 0 ? 1 : -1); - while (n1 < n2 && c++ < 100) { - n = Math.floor((n1 + n2) / 2); - if (test(bins[n], val)) n1 = n + 1; - else n2 = n; - } - if (c > 90) loggers2.log("Long binary search..."); - return n1 - 1; - } - }; - function lessThan(a, b) { - return a < b; - } - function lessOrEqual2(a, b) { - return a <= b; - } - function greaterThan(a, b) { - return a > b; - } - function greaterOrEqual2(a, b) { - return a >= b; - } - exports2.sorterAsc = function(a, b) { - return a - b; - }; - exports2.sorterDes = function(a, b) { - return b - a; - }; - exports2.distinctVals = function(valsIn) { - var vals = valsIn.slice(); - vals.sort(exports2.sorterAsc); - var last; - for (last = vals.length - 1; last > -1; last--) { - if (vals[last] !== BADNUM2) break; - } - var minDiff = vals[last] - vals[0] || 1; - var errDiff = minDiff / (last || 1) / 1e4; - var newVals = []; - var preV; - for (var i = 0; i <= last; i++) { - var v = vals[i]; - var diff = v - preV; - if (preV === void 0) { - newVals.push(v); - preV = v; - } else if (diff > errDiff) { - minDiff = Math.min(minDiff, diff); - newVals.push(v); - preV = v; - } - } - return { vals: newVals, minDiff }; - }; - exports2.roundUp = function(val, arrayIn, reverse) { - var low = 0; - var high = arrayIn.length - 1; - var mid; - var c = 0; - var dlow = reverse ? 0 : 1; - var dhigh = reverse ? 1 : 0; - var rounded = reverse ? Math.ceil : Math.floor; - while (low < high && c++ < 100) { - mid = rounded((low + high) / 2); - if (arrayIn[mid] <= val) low = mid + dlow; - else high = mid - dhigh; - } - return arrayIn[low]; - }; - exports2.sort = function(array2, sortFn) { - var notOrdered = 0; - var notReversed = 0; - for (var i = 1; i < array2.length; i++) { - var pairOrder = sortFn(array2[i], array2[i - 1]); - if (pairOrder < 0) notOrdered = 1; - else if (pairOrder > 0) notReversed = 1; - if (notOrdered && notReversed) return array2.sort(sortFn); - } - return notReversed ? array2 : array2.reverse(); - }; - exports2.findIndexOfMin = function(arr, fn) { - fn = fn || identity3; - var min = Infinity; - var ind; - for (var i = 0; i < arr.length; i++) { - var v = fn(arr[i]); - if (v < min) { - min = v; - ind = i; - } - } - return ind; - }; -})(search$1); -var sort_object_keys = function sortObjectKeys(obj) { - return Object.keys(obj).sort(); -}; -var stats = {}; -(function(exports2) { - var isNumeric2 = fastIsnumeric; - var isArrayOrTypedArray2 = array$2.isArrayOrTypedArray; - exports2.aggNums = function(f, v, a, len) { - var i, b; - if (!len || len > a.length) len = a.length; - if (!isNumeric2(v)) v = false; - if (isArrayOrTypedArray2(a[0])) { - b = new Array(len); - for (i = 0; i < len; i++) b[i] = exports2.aggNums(f, v, a[i]); - a = b; - } - for (i = 0; i < len; i++) { - if (!isNumeric2(v)) v = a[i]; - else if (isNumeric2(a[i])) v = f(+v, +a[i]); - } - return v; - }; - exports2.len = function(data) { - return exports2.aggNums(function(a) { - return a + 1; - }, 0, data); - }; - exports2.mean = function(data, len) { - if (!len) len = exports2.len(data); - return exports2.aggNums(function(a, b) { - return a + b; - }, 0, data) / len; - }; - exports2.geometricMean = function(data, len) { - if (!len) len = exports2.len(data); - return Math.pow(exports2.aggNums(function(a, b) { - return a * b; - }, 1, data), 1 / len); - }; - exports2.midRange = function(numArr) { - if (numArr === void 0 || numArr.length === 0) return void 0; - return (exports2.aggNums(Math.max, null, numArr) + exports2.aggNums(Math.min, null, numArr)) / 2; - }; - exports2.variance = function(data, len, mean) { - if (!len) len = exports2.len(data); - if (!isNumeric2(mean)) mean = exports2.mean(data, len); - return exports2.aggNums(function(a, b) { - return a + Math.pow(b - mean, 2); - }, 0, data) / len; - }; - exports2.stdev = function(data, len, mean) { - return Math.sqrt(exports2.variance(data, len, mean)); - }; - exports2.median = function(data) { - var b = data.slice().sort(); - return exports2.interp(b, 0.5); - }; - exports2.interp = function(arr, n) { - if (!isNumeric2(n)) throw "n should be a finite number"; - n = n * arr.length - 0.5; - if (n < 0) return arr[0]; - if (n > arr.length - 1) return arr[arr.length - 1]; - var frac = n % 1; - return frac * arr[Math.ceil(n)] + (1 - frac) * arr[Math.floor(n)]; - }; -})(stats); -var modModule$1 = mod_1; -var mod$1 = modModule$1.mod; -var modHalf = modModule$1.modHalf; -var PI = Math.PI; -var twoPI = 2 * PI; -function deg2rad(deg) { - return deg / 180 * PI; -} -function rad2deg(rad) { - return rad / PI * 180; -} -function isFullCircle(aBnds) { - return Math.abs(aBnds[1] - aBnds[0]) > twoPI - 1e-14; -} -function angleDelta(a, b) { - return modHalf(b - a, twoPI); -} -function angleDist(a, b) { - return Math.abs(angleDelta(a, b)); -} -function isAngleInsideSector(a, aBnds) { - if (isFullCircle(aBnds)) return true; - var s0, s1; - if (aBnds[0] < aBnds[1]) { - s0 = aBnds[0]; - s1 = aBnds[1]; - } else { - s0 = aBnds[1]; - s1 = aBnds[0]; - } - s0 = mod$1(s0, twoPI); - s1 = mod$1(s1, twoPI); - if (s0 > s1) s1 += twoPI; - var a0 = mod$1(a, twoPI); - var a1 = a0 + twoPI; - return a0 >= s0 && a0 <= s1 || a1 >= s0 && a1 <= s1; -} -function isPtInsideSector(r, a, rBnds, aBnds) { - if (!isAngleInsideSector(a, aBnds)) return false; - var r0, r1; - if (rBnds[0] < rBnds[1]) { - r0 = rBnds[0]; - r1 = rBnds[1]; - } else { - r0 = rBnds[1]; - r1 = rBnds[0]; - } - return r >= r0 && r <= r1; -} -function _path(r0, r1, a0, a1, cx, cy, isClosed) { - cx = cx || 0; - cy = cy || 0; - var isCircle = isFullCircle([a0, a1]); - var aStart, aMid, aEnd; - var rStart, rEnd; - if (isCircle) { - aStart = 0; - aMid = PI; - aEnd = twoPI; - } else { - if (a0 < a1) { - aStart = a0; - aEnd = a1; - } else { - aStart = a1; - aEnd = a0; - } - } - if (r0 < r1) { - rStart = r0; - rEnd = r1; - } else { - rStart = r1; - rEnd = r0; - } - function pt(r, a) { - return [r * Math.cos(a) + cx, cy - r * Math.sin(a)]; - } - var largeArc = Math.abs(aEnd - aStart) <= PI ? 0 : 1; - function arc2(r, a, cw) { - return "A" + [r, r] + " " + [0, largeArc, cw] + " " + pt(r, a); - } - var p; - if (isCircle) { - if (rStart === null) { - p = "M" + pt(rEnd, aStart) + arc2(rEnd, aMid, 0) + arc2(rEnd, aEnd, 0) + "Z"; - } else { - p = "M" + pt(rStart, aStart) + arc2(rStart, aMid, 0) + arc2(rStart, aEnd, 0) + "ZM" + pt(rEnd, aStart) + arc2(rEnd, aMid, 1) + arc2(rEnd, aEnd, 1) + "Z"; - } - } else { - if (rStart === null) { - p = "M" + pt(rEnd, aStart) + arc2(rEnd, aEnd, 0); - if (isClosed) p += "L0,0Z"; - } else { - p = "M" + pt(rStart, aStart) + "L" + pt(rEnd, aStart) + arc2(rEnd, aEnd, 0) + "L" + pt(rStart, aEnd) + arc2(rStart, aStart, 1) + "Z"; - } - } - return p; -} -function pathArc(r, a0, a1, cx, cy) { - return _path(null, r, a0, a1, cx, cy, 0); -} -function pathSector(r, a0, a1, cx, cy) { - return _path(null, r, a0, a1, cx, cy, 1); -} -function pathAnnulus(r0, r1, a0, a1, cx, cy) { - return _path(r0, r1, a0, a1, cx, cy, 1); -} -var angles = { - deg2rad, - rad2deg, - angleDelta, - angleDist, - isFullCircle, - isAngleInsideSector, - isPtInsideSector, - pathArc, - pathSector, - pathAnnulus -}; -var anchor_utils = {}; -anchor_utils.isLeftAnchor = function isLeftAnchor(opts) { - return opts.xanchor === "left" || opts.xanchor === "auto" && opts.x <= 1 / 3; -}; -anchor_utils.isCenterAnchor = function isCenterAnchor(opts) { - return opts.xanchor === "center" || opts.xanchor === "auto" && opts.x > 1 / 3 && opts.x < 2 / 3; -}; -anchor_utils.isRightAnchor = function isRightAnchor(opts) { - return opts.xanchor === "right" || opts.xanchor === "auto" && opts.x >= 2 / 3; -}; -anchor_utils.isTopAnchor = function isTopAnchor(opts) { - return opts.yanchor === "top" || opts.yanchor === "auto" && opts.y >= 2 / 3; -}; -anchor_utils.isMiddleAnchor = function isMiddleAnchor(opts) { - return opts.yanchor === "middle" || opts.yanchor === "auto" && opts.y > 1 / 3 && opts.y < 2 / 3; -}; -anchor_utils.isBottomAnchor = function isBottomAnchor(opts) { - return opts.yanchor === "bottom" || opts.yanchor === "auto" && opts.y <= 1 / 3; -}; -var geometry2d = {}; -var mod = mod_1.mod; -geometry2d.segmentsIntersect = segmentsIntersect$1; -function segmentsIntersect$1(x1, y1, x2, y2, x3, y3, x4, y4) { - var a = x2 - x1; - var b = x3 - x1; - var c = x4 - x3; - var d = y2 - y1; - var e = y3 - y1; - var f = y4 - y3; - var det = a * f - c * d; - if (det === 0) return null; - var t = (b * f - c * e) / det; - var u = (b * d - a * e) / det; - if (u < 0 || u > 1 || t < 0 || t > 1) return null; - return { x: x1 + a * t, y: y1 + d * t }; -} -geometry2d.segmentDistance = function segmentDistance(x1, y1, x2, y2, x3, y3, x4, y4) { - if (segmentsIntersect$1(x1, y1, x2, y2, x3, y3, x4, y4)) return 0; - var x12 = x2 - x1; - var y12 = y2 - y1; - var x34 = x4 - x3; - var y34 = y4 - y3; - var ll12 = x12 * x12 + y12 * y12; - var ll34 = x34 * x34 + y34 * y34; - var dist2 = Math.min( - perpDistance2(x12, y12, ll12, x3 - x1, y3 - y1), - perpDistance2(x12, y12, ll12, x4 - x1, y4 - y1), - perpDistance2(x34, y34, ll34, x1 - x3, y1 - y3), - perpDistance2(x34, y34, ll34, x2 - x3, y2 - y3) - ); - return Math.sqrt(dist2); -}; -function perpDistance2(xab, yab, llab, xac, yac) { - var fcAB = xac * xab + yac * yab; - if (fcAB < 0) { - return xac * xac + yac * yac; - } else if (fcAB > llab) { - var xbc = xac - xab; - var ybc = yac - yab; - return xbc * xbc + ybc * ybc; - } else { - var crossProduct = xac * yab - yac * xab; - return crossProduct * crossProduct / llab; - } -} -var locationCache, workingPath, workingTextWidth; -geometry2d.getTextLocation = function getTextLocation(path, totalPathLen, positionOnPath, textWidth) { - if (path !== workingPath || textWidth !== workingTextWidth) { - locationCache = {}; - workingPath = path; - workingTextWidth = textWidth; - } - if (locationCache[positionOnPath]) { - return locationCache[positionOnPath]; - } - var p0 = path.getPointAtLength(mod(positionOnPath - textWidth / 2, totalPathLen)); - var p1 = path.getPointAtLength(mod(positionOnPath + textWidth / 2, totalPathLen)); - var theta = Math.atan((p1.y - p0.y) / (p1.x - p0.x)); - var pCenter = path.getPointAtLength(mod(positionOnPath, totalPathLen)); - var x = (pCenter.x * 4 + p0.x + p1.x) / 6; - var y = (pCenter.y * 4 + p0.y + p1.y) / 6; - var out = { x, y, theta }; - locationCache[positionOnPath] = out; - return out; -}; -geometry2d.clearLocationCache = function() { - workingPath = null; -}; -geometry2d.getVisibleSegment = function getVisibleSegment(path, bounds, buffer2) { - var left = bounds.left; - var right = bounds.right; - var top = bounds.top; - var bottom = bounds.bottom; - var pMin = 0; - var pTotal = path.getTotalLength(); - var pMax = pTotal; - var pt0, ptTotal; - function getDistToPlot(len) { - var pt = path.getPointAtLength(len); - if (len === 0) pt0 = pt; - else if (len === pTotal) ptTotal = pt; - var dx = pt.x < left ? left - pt.x : pt.x > right ? pt.x - right : 0; - var dy = pt.y < top ? top - pt.y : pt.y > bottom ? pt.y - bottom : 0; - return Math.sqrt(dx * dx + dy * dy); - } - var distToPlot = getDistToPlot(pMin); - while (distToPlot) { - pMin += distToPlot + buffer2; - if (pMin > pMax) return; - distToPlot = getDistToPlot(pMin); - } - distToPlot = getDistToPlot(pMax); - while (distToPlot) { - pMax -= distToPlot + buffer2; - if (pMin > pMax) return; - distToPlot = getDistToPlot(pMax); - } - return { - min: pMin, - max: pMax, - len: pMax - pMin, - total: pTotal, - isClosed: pMin === 0 && pMax === pTotal && Math.abs(pt0.x - ptTotal.x) < 0.1 && Math.abs(pt0.y - ptTotal.y) < 0.1 - }; -}; -geometry2d.findPointOnPath = function findPointOnPath(path, val, coord, opts) { - opts = opts || {}; - var pathLength = opts.pathLength || path.getTotalLength(); - var tolerance = opts.tolerance || 1e-3; - var iterationLimit = opts.iterationLimit || 30; - var mul = path.getPointAtLength(0)[coord] > path.getPointAtLength(pathLength)[coord] ? -1 : 1; - var i = 0; - var b0 = 0; - var b1 = pathLength; - var mid; - var pt; - var diff; - while (i < iterationLimit) { - mid = (b0 + b1) / 2; - pt = path.getPointAtLength(mid); - diff = pt[coord] - val; - if (Math.abs(diff) < tolerance) { - return pt; - } else { - if (mul * diff > 0) { - b1 = mid; - } else { - b0 = mid; - } - i++; - } - } - return pt; -}; -var throttle$2 = {}; -(function(exports2) { - var timerCache = {}; - exports2.throttle = function throttle2(id, minInterval, callback) { - var cache2 = timerCache[id]; - var now = Date.now(); - if (!cache2) { - for (var idi in timerCache) { - if (timerCache[idi].ts < now - 6e4) { - delete timerCache[idi]; - } - } - cache2 = timerCache[id] = { ts: 0, timer: null }; - } - _clearTimeout(cache2); - function exec() { - callback(); - cache2.ts = Date.now(); - if (cache2.onDone) { - cache2.onDone(); - cache2.onDone = null; - } - } - if (now > cache2.ts + minInterval) { - exec(); - return; - } - cache2.timer = setTimeout(function() { - exec(); - cache2.timer = null; - }, minInterval); - }; - exports2.done = function(id) { - var cache2 = timerCache[id]; - if (!cache2 || !cache2.timer) return Promise.resolve(); - return new Promise(function(resolve) { - var previousOnDone = cache2.onDone; - cache2.onDone = function onDone() { - if (previousOnDone) previousOnDone(); - resolve(); - cache2.onDone = null; - }; - }); - }; - exports2.clear = function(id) { - if (id) { - _clearTimeout(timerCache[id]); - delete timerCache[id]; - } else { - for (var idi in timerCache) exports2.clear(idi); - } - }; - function _clearTimeout(cache2) { - if (cache2 && cache2.timer !== null) { - clearTimeout(cache2.timer); - cache2.timer = null; - } - } -})(throttle$2); -var clear_responsive = function clearResponsive(gd) { - if (gd._responsiveChartHandler) { - window.removeEventListener("resize", gd._responsiveChartHandler); - delete gd._responsiveChartHandler; - } -}; -var isMobile$1 = { exports: {} }; -isMobile$1.exports = isMobile; -isMobile$1.exports.isMobile = isMobile; -isMobile$1.exports.default = isMobile; -const mobileRE = /(android|bb\d+|meego).+mobile|armv7l|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series[46]0|samsungbrowser.*mobile|symbian|treo|up\.(browser|link)|vodafone|wap|windows (ce|phone)|xda|xiino/i; -const notMobileRE = /CrOS/; -const tabletRE = /android|ipad|playbook|silk/i; -function isMobile(opts) { - if (!opts) opts = {}; - let ua = opts.ua; - if (!ua && typeof navigator !== "undefined") ua = navigator.userAgent; - if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") { - ua = ua.headers["user-agent"]; - } - if (typeof ua !== "string") return false; - let result = mobileRE.test(ua) && !notMobileRE.test(ua) || !!opts.tablet && tabletRE.test(ua); - if (!result && opts.tablet && opts.featureDetect && navigator && navigator.maxTouchPoints > 1 && ua.indexOf("Macintosh") !== -1 && ua.indexOf("Safari") !== -1) { - result = true; - } - return result; -} -var isMobileExports = isMobile$1.exports; -var isNumeric$x = fastIsnumeric; -var isMobileOrTablet = isMobileExports; -var preserve_drawing_buffer = function preserveDrawingBuffer(opts) { - var ua; - if (opts && opts.hasOwnProperty("userAgent")) { - ua = opts.userAgent; - } else { - ua = getUserAgent(); - } - if (typeof ua !== "string") return true; - var enable2 = isMobileOrTablet({ - ua: { headers: { "user-agent": ua } }, - tablet: true, - featureDetect: false - }); - if (!enable2) { - var allParts = ua.split(" "); - for (var i = 1; i < allParts.length; i++) { - var part = allParts[i]; - if (part.indexOf("Safari") !== -1) { - for (var k = i - 1; k > -1; k--) { - var prevPart = allParts[k]; - if (prevPart.substr(0, 8) === "Version/") { - var v = prevPart.substr(8).split(".")[0]; - if (isNumeric$x(v)) v = +v; - if (v >= 13) return true; - } - } - } - } - } - return enable2; -}; -function getUserAgent() { - var ua; - if (typeof navigator !== "undefined") { - ua = navigator.userAgent; - } - if (ua && ua.headers && typeof ua.headers["user-agent"] === "string") { - ua = ua.headers["user-agent"]; - } - return ua; -} -var d3$D = d3Exports; -var make_trace_groups = function makeTraceGroups(traceLayer, cdModule, cls) { - var traces = traceLayer.selectAll("g." + cls.replace(/\s/g, ".")).data(cdModule, function(cd) { - return cd[0].trace.uid; - }); - traces.exit().remove(); - traces.enter().append("g").attr("class", cls); - traces.order(); - var k = traceLayer.classed("rangeplot") ? "nodeRangePlot3" : "node3"; - traces.each(function(cd) { - cd[0][k] = d3$D.select(this); - }); - return traces; -}; -var Registry$O = registry; -var localize = function localize2(gd, s) { - var locale2 = gd._context.locale; - for (var i = 0; i < 2; i++) { - var locales = gd._context.locales; - for (var j = 0; j < 2; j++) { - var dict = (locales[locale2] || {}).dictionary; - if (dict) { - var out = dict[s]; - if (out) return out; - } - locales = Registry$O.localeRegistry; - } - var baseLocale = locale2.split("-")[0]; - if (baseLocale === locale2) break; - locale2 = baseLocale; - } - return s; -}; -var filter_unique = function filterUnique(array2) { - var seen = {}; - var out = []; - var j = 0; - for (var i = 0; i < array2.length; i++) { - var item = array2[i]; - if (seen[item] !== 1) { - seen[item] = 1; - out[j++] = item; - } - } - return out; -}; -var filter_visible = function filterVisible(container) { - var filterFn = isCalcData(container) ? calcDataFilter : baseFilter; - var out = []; - for (var i = 0; i < container.length; i++) { - var item = container[i]; - if (filterFn(item)) out.push(item); - } - return out; -}; -function baseFilter(item) { - return item.visible === true; -} -function calcDataFilter(item) { - var trace = item[0].trace; - return trace.visible === true && trace._length !== 0; -} -function isCalcData(cont) { - return Array.isArray(cont) && Array.isArray(cont[0]) && cont[0][0] && cont[0][0].trace; -} -var increment = function incrementNumeric(x, delta2) { - if (!delta2) return x; - var scale2 = 1 / Math.abs(delta2); - var newX = scale2 > 1 ? (scale2 * x + scale2 * delta2) / scale2 : x + delta2; - var lenX1 = String(newX).length; - if (lenX1 > 16) { - var lenDt = String(delta2).length; - var lenX0 = String(x).length; - if (lenX1 >= lenX0 + lenDt) { - var s = parseFloat(newX).toPrecision(12); - if (s.indexOf("e+") === -1) newX = +s; - } - } - return newX; -}; -var isNumeric$w = fastIsnumeric; -var BADNUM$c = numerical.BADNUM; -var JUNK = /^['"%,$#\s']+|[, ]|['"%,$#\s']+$/g; -var clean_number = function cleanNumber(v) { - if (typeof v === "string") { - v = v.replace(JUNK, ""); - } - if (isNumeric$w(v)) return Number(v); - return BADNUM$c; -}; -var d3$C = d3Exports; -var utcFormat$1 = require$$1$1.utcFormat; -var d3Format = require$$2$2.format; -var isNumeric$v = fastIsnumeric; -var numConstants$4 = numerical; -var MAX_SAFE = numConstants$4.FP_SAFE; -var MIN_SAFE = -MAX_SAFE; -var BADNUM$b = numConstants$4.BADNUM; -var lib = lib$1.exports = {}; -lib.adjustFormat = function adjustFormat(formatStr) { - if (!formatStr || /^\d[.]\df/.test(formatStr) || /[.]\d%/.test(formatStr)) return formatStr; - if (formatStr === "0.f") return "~f"; - if (/^\d%/.test(formatStr)) return "~%"; - if (/^\ds/.test(formatStr)) return "~s"; - if (!/^[~,.0$]/.test(formatStr) && /[&fps]/.test(formatStr)) return "~" + formatStr; - return formatStr; -}; -var seenBadFormats = {}; -lib.warnBadFormat = function(f) { - var key = String(f); - if (!seenBadFormats[key]) { - seenBadFormats[key] = 1; - lib.warn('encountered bad format: "' + key + '"'); - } -}; -lib.noFormat = function(value2) { - return String(value2); -}; -lib.numberFormat = function(formatStr) { - var fn; - try { - fn = d3Format(lib.adjustFormat(formatStr)); - } catch (e) { - lib.warnBadFormat(formatStr); - return lib.noFormat; - } - return fn; -}; -lib.nestedProperty = nested_property; -lib.keyedContainer = keyed_container; -lib.relativeAttr = relative_attr; -lib.isPlainObject = is_plain_object; -lib.toLogRange = to_log_range; -lib.relinkPrivateKeys = relink_private; -var arrayModule = array$2; -lib.isArrayBuffer = arrayModule.isArrayBuffer; -lib.isTypedArray = arrayModule.isTypedArray; -lib.isArrayOrTypedArray = arrayModule.isArrayOrTypedArray; -lib.isArray1D = arrayModule.isArray1D; -lib.ensureArray = arrayModule.ensureArray; -lib.concat = arrayModule.concat; -lib.maxRowLength = arrayModule.maxRowLength; -lib.minRowLength = arrayModule.minRowLength; -var modModule = mod_1; -lib.mod = modModule.mod; -lib.modHalf = modModule.modHalf; -var coerceModule = coerce$1; -lib.valObjectMeta = coerceModule.valObjectMeta; -lib.coerce = coerceModule.coerce; -lib.coerce2 = coerceModule.coerce2; -lib.coerceFont = coerceModule.coerceFont; -lib.coercePattern = coerceModule.coercePattern; -lib.coerceHoverinfo = coerceModule.coerceHoverinfo; -lib.coerceSelectionMarkerOpacity = coerceModule.coerceSelectionMarkerOpacity; -lib.validate = coerceModule.validate; -var datesModule = dates; -lib.dateTime2ms = datesModule.dateTime2ms; -lib.isDateTime = datesModule.isDateTime; -lib.ms2DateTime = datesModule.ms2DateTime; -lib.ms2DateTimeLocal = datesModule.ms2DateTimeLocal; -lib.cleanDate = datesModule.cleanDate; -lib.isJSDate = datesModule.isJSDate; -lib.formatDate = datesModule.formatDate; -lib.incrementMonth = datesModule.incrementMonth; -lib.dateTick0 = datesModule.dateTick0; -lib.dfltRange = datesModule.dfltRange; -lib.findExactDates = datesModule.findExactDates; -lib.MIN_MS = datesModule.MIN_MS; -lib.MAX_MS = datesModule.MAX_MS; -var searchModule = search$1; -lib.findBin = searchModule.findBin; -lib.sorterAsc = searchModule.sorterAsc; -lib.sorterDes = searchModule.sorterDes; -lib.distinctVals = searchModule.distinctVals; -lib.roundUp = searchModule.roundUp; -lib.sort = searchModule.sort; -lib.findIndexOfMin = searchModule.findIndexOfMin; -lib.sortObjectKeys = sort_object_keys; -var statsModule = stats; -lib.aggNums = statsModule.aggNums; -lib.len = statsModule.len; -lib.mean = statsModule.mean; -lib.geometricMean = statsModule.geometricMean; -lib.median = statsModule.median; -lib.midRange = statsModule.midRange; -lib.variance = statsModule.variance; -lib.stdev = statsModule.stdev; -lib.interp = statsModule.interp; -var matrixModule = matrix$1; -lib.init2dArray = matrixModule.init2dArray; -lib.transposeRagged = matrixModule.transposeRagged; -lib.dot = matrixModule.dot; -lib.translationMatrix = matrixModule.translationMatrix; -lib.rotationMatrix = matrixModule.rotationMatrix; -lib.rotationXYMatrix = matrixModule.rotationXYMatrix; -lib.apply3DTransform = matrixModule.apply3DTransform; -lib.apply2DTransform = matrixModule.apply2DTransform; -lib.apply2DTransform2 = matrixModule.apply2DTransform2; -lib.convertCssMatrix = matrixModule.convertCssMatrix; -lib.inverseTransformMatrix = matrixModule.inverseTransformMatrix; -var anglesModule = angles; -lib.deg2rad = anglesModule.deg2rad; -lib.rad2deg = anglesModule.rad2deg; -lib.angleDelta = anglesModule.angleDelta; -lib.angleDist = anglesModule.angleDist; -lib.isFullCircle = anglesModule.isFullCircle; -lib.isAngleInsideSector = anglesModule.isAngleInsideSector; -lib.isPtInsideSector = anglesModule.isPtInsideSector; -lib.pathArc = anglesModule.pathArc; -lib.pathSector = anglesModule.pathSector; -lib.pathAnnulus = anglesModule.pathAnnulus; -var anchorUtils = anchor_utils; -lib.isLeftAnchor = anchorUtils.isLeftAnchor; -lib.isCenterAnchor = anchorUtils.isCenterAnchor; -lib.isRightAnchor = anchorUtils.isRightAnchor; -lib.isTopAnchor = anchorUtils.isTopAnchor; -lib.isMiddleAnchor = anchorUtils.isMiddleAnchor; -lib.isBottomAnchor = anchorUtils.isBottomAnchor; -var geom2dModule = geometry2d; -lib.segmentsIntersect = geom2dModule.segmentsIntersect; -lib.segmentDistance = geom2dModule.segmentDistance; -lib.getTextLocation = geom2dModule.getTextLocation; -lib.clearLocationCache = geom2dModule.clearLocationCache; -lib.getVisibleSegment = geom2dModule.getVisibleSegment; -lib.findPointOnPath = geom2dModule.findPointOnPath; -var extendModule = extend$5; -lib.extendFlat = extendModule.extendFlat; -lib.extendDeep = extendModule.extendDeep; -lib.extendDeepAll = extendModule.extendDeepAll; -lib.extendDeepNoArrays = extendModule.extendDeepNoArrays; -var loggersModule = loggersExports; -lib.log = loggersModule.log; -lib.warn = loggersModule.warn; -lib.error = loggersModule.error; -var regexModule = regex; -lib.counterRegex = regexModule.counter; -var throttleModule = throttle$2; -lib.throttle = throttleModule.throttle; -lib.throttleDone = throttleModule.done; -lib.clearThrottle = throttleModule.clear; -var domModule = dom; -lib.getGraphDiv = domModule.getGraphDiv; -lib.isPlotDiv = domModule.isPlotDiv; -lib.removeElement = domModule.removeElement; -lib.addStyleRule = domModule.addStyleRule; -lib.addRelatedStyleRule = domModule.addRelatedStyleRule; -lib.deleteRelatedStyleRule = domModule.deleteRelatedStyleRule; -lib.getFullTransformMatrix = domModule.getFullTransformMatrix; -lib.getElementTransformMatrix = domModule.getElementTransformMatrix; -lib.getElementAndAncestors = domModule.getElementAndAncestors; -lib.equalDomRects = domModule.equalDomRects; -lib.clearResponsive = clear_responsive; -lib.preserveDrawingBuffer = preserve_drawing_buffer; -lib.makeTraceGroups = make_trace_groups; -lib._ = localize; -lib.notifier = notifier$1; -lib.filterUnique = filter_unique; -lib.filterVisible = filter_visible; -lib.pushUnique = push_unique; -lib.increment = increment; -lib.cleanNumber = clean_number; -lib.ensureNumber = function ensureNumber(v) { - if (!isNumeric$v(v)) return BADNUM$b; - v = Number(v); - return v > MAX_SAFE || v < MIN_SAFE ? BADNUM$b : v; -}; -lib.isIndex = function(v, len) { - if (len !== void 0 && v >= len) return false; - return isNumeric$v(v) && v >= 0 && v % 1 === 0; -}; -lib.noop = noop$2; -lib.identity = identity$2; -lib.repeat = function(v, cnt) { - var out = new Array(cnt); - for (var i = 0; i < cnt; i++) { - out[i] = v; - } - return out; -}; -lib.swapAttrs = function(cont, attrList, part1, part2) { - if (!part1) part1 = "x"; - if (!part2) part2 = "y"; - for (var i = 0; i < attrList.length; i++) { - var attr = attrList[i]; - var xp = lib.nestedProperty(cont, attr.replace("?", part1)); - var yp = lib.nestedProperty(cont, attr.replace("?", part2)); - var temp = xp.get(); - xp.set(yp.get()); - yp.set(temp); - } -}; -lib.raiseToTop = function raiseToTop(elem) { - elem.parentNode.appendChild(elem); -}; -lib.cancelTransition = function(selection) { - return selection.transition().duration(0); -}; -lib.constrain = function(v, v0, v1) { - if (v0 > v1) return Math.max(v1, Math.min(v0, v)); - return Math.max(v0, Math.min(v1, v)); -}; -lib.bBoxIntersect = function(a, b, pad2) { - pad2 = pad2 || 0; - return a.left <= b.right + pad2 && b.left <= a.right + pad2 && a.top <= b.bottom + pad2 && b.top <= a.bottom + pad2; -}; -lib.simpleMap = function(array2, func, x1, x2, opts) { - var len = array2.length; - var out = new Array(len); - for (var i = 0; i < len; i++) out[i] = func(array2[i], x1, x2, opts); - return out; -}; -lib.randstr = function randstr(existing, bits2, base, _recursion) { - if (!base) base = 16; - if (bits2 === void 0) bits2 = 24; - if (bits2 <= 0) return "0"; - var digits = Math.log(Math.pow(2, bits2)) / Math.log(base); - var res = ""; - var i, b, x; - for (i = 2; digits === Infinity; i *= 2) { - digits = Math.log(Math.pow(2, bits2 / i)) / Math.log(base) * i; - } - var rem = digits - Math.floor(digits); - for (i = 0; i < Math.floor(digits); i++) { - x = Math.floor(Math.random() * base).toString(base); - res = x + res; - } - if (rem) { - b = Math.pow(base, rem); - x = Math.floor(Math.random() * b).toString(base); - res = x + res; - } - var parsed = parseInt(res, base); - if (existing && existing[res] || parsed !== Infinity && parsed >= Math.pow(2, bits2)) { - if (_recursion > 10) { - lib.warn("randstr failed uniqueness"); - return res; - } - return randstr(existing, bits2, base, (_recursion || 0) + 1); - } else return res; -}; -lib.OptionControl = function(opt, optname) { - if (!opt) opt = {}; - if (!optname) optname = "opt"; - var self2 = {}; - self2.optionList = []; - self2._newoption = function(optObj) { - optObj[optname] = opt; - self2[optObj.name] = optObj; - self2.optionList.push(optObj); - }; - self2["_" + optname] = opt; - return self2; -}; -lib.smooth = function(arrayIn, FWHM) { - FWHM = Math.round(FWHM) || 0; - if (FWHM < 2) return arrayIn; - var alen = arrayIn.length; - var alen2 = 2 * alen; - var wlen = 2 * FWHM - 1; - var w = new Array(wlen); - var arrayOut = new Array(alen); - var i; - var j; - var k; - var v; - for (i = 0; i < wlen; i++) { - w[i] = (1 - Math.cos(Math.PI * (i + 1) / FWHM)) / (2 * FWHM); - } - for (i = 0; i < alen; i++) { - v = 0; - for (j = 0; j < wlen; j++) { - k = i + j + 1 - FWHM; - if (k < -alen) k -= alen2 * Math.round(k / alen2); - else if (k >= alen2) k -= alen2 * Math.floor(k / alen2); - if (k < 0) k = -1 - k; - else if (k >= alen) k = alen2 - 1 - k; - v += arrayIn[k] * w[j]; - } - arrayOut[i] = v; - } - return arrayOut; -}; -lib.syncOrAsync = function(sequence, arg, finalStep) { - var ret, fni; - function continueAsync() { - return lib.syncOrAsync(sequence, arg, finalStep); - } - while (sequence.length) { - fni = sequence.splice(0, 1)[0]; - ret = fni(arg); - if (ret && ret.then) { - return ret.then(continueAsync); - } - } - return finalStep && finalStep(arg); -}; -lib.stripTrailingSlash = function(str2) { - if (str2.substr(-1) === "/") return str2.substr(0, str2.length - 1); - return str2; -}; -lib.noneOrAll = function(containerIn, containerOut, attrList) { - if (!containerIn) return; - var hasAny = false; - var hasAll = true; - var i; - var val; - for (i = 0; i < attrList.length; i++) { - val = containerIn[attrList[i]]; - if (val !== void 0 && val !== null) hasAny = true; - else hasAll = false; - } - if (hasAny && !hasAll) { - for (i = 0; i < attrList.length; i++) { - containerIn[attrList[i]] = containerOut[attrList[i]]; - } - } -}; -lib.mergeArray = function(traceAttr, cd, cdAttr, fn) { - var hasFn = typeof fn === "function"; - if (lib.isArrayOrTypedArray(traceAttr)) { - var imax = Math.min(traceAttr.length, cd.length); - for (var i = 0; i < imax; i++) { - var v = traceAttr[i]; - cd[i][cdAttr] = hasFn ? fn(v) : v; - } - } -}; -lib.mergeArrayCastPositive = function(traceAttr, cd, cdAttr) { - return lib.mergeArray(traceAttr, cd, cdAttr, function(v) { - var w = +v; - return !isFinite(w) ? 0 : w > 0 ? w : 0; - }); -}; -lib.fillArray = function(traceAttr, cd, cdAttr, fn) { - fn = fn || lib.identity; - if (lib.isArrayOrTypedArray(traceAttr)) { - for (var i = 0; i < cd.length; i++) { - cd[i][cdAttr] = fn(traceAttr[i]); - } - } -}; -lib.castOption = function(trace, ptNumber, astr, fn) { - fn = fn || lib.identity; - var val = lib.nestedProperty(trace, astr).get(); - if (lib.isArrayOrTypedArray(val)) { - if (Array.isArray(ptNumber) && lib.isArrayOrTypedArray(val[ptNumber[0]])) { - return fn(val[ptNumber[0]][ptNumber[1]]); - } else { - return fn(val[ptNumber]); - } - } else { - return val; - } -}; -lib.extractOption = function(calcPt, trace, calcKey, traceKey) { - if (calcKey in calcPt) return calcPt[calcKey]; - var traceVal = lib.nestedProperty(trace, traceKey).get(); - if (!Array.isArray(traceVal)) return traceVal; -}; -function makePtIndex2PtNumber(indexToPoints) { - var ptIndex2ptNumber = {}; - for (var k in indexToPoints) { - var pts = indexToPoints[k]; - for (var j = 0; j < pts.length; j++) { - ptIndex2ptNumber[pts[j]] = +k; - } - } - return ptIndex2ptNumber; -} -lib.tagSelected = function(calcTrace, trace, ptNumber2cdIndex) { - var selectedpoints = trace.selectedpoints; - var indexToPoints = trace._indexToPoints; - var ptIndex2ptNumber; - if (indexToPoints) { - ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints); - } - function isCdIndexValid(v) { - return v !== void 0 && v < calcTrace.length; - } - for (var i = 0; i < selectedpoints.length; i++) { - var ptIndex = selectedpoints[i]; - if (lib.isIndex(ptIndex) || lib.isArrayOrTypedArray(ptIndex) && lib.isIndex(ptIndex[0]) && lib.isIndex(ptIndex[1])) { - var ptNumber = ptIndex2ptNumber ? ptIndex2ptNumber[ptIndex] : ptIndex; - var cdIndex = ptNumber2cdIndex ? ptNumber2cdIndex[ptNumber] : ptNumber; - if (isCdIndexValid(cdIndex)) { - calcTrace[cdIndex].selected = 1; - } - } - } -}; -lib.selIndices2selPoints = function(trace) { - var selectedpoints = trace.selectedpoints; - var indexToPoints = trace._indexToPoints; - if (indexToPoints) { - var ptIndex2ptNumber = makePtIndex2PtNumber(indexToPoints); - var out = []; - for (var i = 0; i < selectedpoints.length; i++) { - var ptIndex = selectedpoints[i]; - if (lib.isIndex(ptIndex)) { - var ptNumber = ptIndex2ptNumber[ptIndex]; - if (lib.isIndex(ptNumber)) { - out.push(ptNumber); - } - } - } - return out; - } else { - return selectedpoints; - } -}; -lib.getTargetArray = function(trace, transformOpts) { - var target = transformOpts.target; - if (typeof target === "string" && target) { - var array2 = lib.nestedProperty(trace, target).get(); - return lib.isArrayOrTypedArray(array2) ? array2 : false; - } else if (lib.isArrayOrTypedArray(target)) { - return target; - } - return false; -}; -function minExtend(obj1, obj2, opt) { - var objOut = {}; - if (typeof obj2 !== "object") obj2 = {}; - var arrayLen = opt === "pieLike" ? -1 : 3; - var keys = Object.keys(obj1); - var i, k, v; - for (i = 0; i < keys.length; i++) { - k = keys[i]; - v = obj1[k]; - if (k.charAt(0) === "_" || typeof v === "function") continue; - else if (k === "module") objOut[k] = v; - else if (Array.isArray(v)) { - if (k === "colorscale" || arrayLen === -1) { - objOut[k] = v.slice(); - } else { - objOut[k] = v.slice(0, arrayLen); - } - } else if (lib.isTypedArray(v)) { - if (arrayLen === -1) { - objOut[k] = v.subarray(); - } else { - objOut[k] = v.subarray(0, arrayLen); - } - } else if (v && typeof v === "object") objOut[k] = minExtend(obj1[k], obj2[k], opt); - else objOut[k] = v; - } - keys = Object.keys(obj2); - for (i = 0; i < keys.length; i++) { - k = keys[i]; - v = obj2[k]; - if (typeof v !== "object" || !(k in objOut) || typeof objOut[k] !== "object") { - objOut[k] = v; - } - } - return objOut; -} -lib.minExtend = minExtend; -lib.titleCase = function(s) { - return s.charAt(0).toUpperCase() + s.substr(1); -}; -lib.containsAny = function(s, fragments) { - for (var i = 0; i < fragments.length; i++) { - if (s.indexOf(fragments[i]) !== -1) return true; - } - return false; -}; -lib.isIE = function() { - return typeof window.navigator.msSaveBlob !== "undefined"; -}; -var IS_SAFARI_REGEX = /Version\/[\d\.]+.*Safari/; -lib.isSafari = function() { - return IS_SAFARI_REGEX.test(window.navigator.userAgent); -}; -var IS_IOS_REGEX = /iPad|iPhone|iPod/; -lib.isIOS = function() { - return IS_IOS_REGEX.test(window.navigator.userAgent); -}; -var FIREFOX_VERSION_REGEX = /Firefox\/(\d+)\.\d+/; -lib.getFirefoxVersion = function() { - var match = FIREFOX_VERSION_REGEX.exec(window.navigator.userAgent); - if (match && match.length === 2) { - var versionInt = parseInt(match[1]); - if (!isNaN(versionInt)) { - return versionInt; - } - } - return null; -}; -lib.isD3Selection = function(obj) { - return obj instanceof d3$C.selection; -}; -lib.ensureSingle = function(parent, nodeType, className, enterFn) { - var sel = parent.select(nodeType + (className ? "." + className : "")); - if (sel.size()) return sel; - var layer = parent.append(nodeType); - if (className) layer.classed(className, true); - if (enterFn) layer.call(enterFn); - return layer; -}; -lib.ensureSingleById = function(parent, nodeType, id, enterFn) { - var sel = parent.select(nodeType + "#" + id); - if (sel.size()) return sel; - var layer = parent.append(nodeType).attr("id", id); - if (enterFn) layer.call(enterFn); - return layer; -}; -lib.objectFromPath = function(path, value2) { - var keys = path.split("."); - var tmpObj; - var obj = tmpObj = {}; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var el = null; - var parts = keys[i].match(/(.*)\[([0-9]+)\]/); - if (parts) { - key = parts[1]; - el = parts[2]; - tmpObj = tmpObj[key] = []; - if (i === keys.length - 1) { - tmpObj[el] = value2; - } else { - tmpObj[el] = {}; - } - tmpObj = tmpObj[el]; - } else { - if (i === keys.length - 1) { - tmpObj[key] = value2; - } else { - tmpObj[key] = {}; - } - tmpObj = tmpObj[key]; - } - } - return obj; -}; -var dottedPropertyRegex = /^([^\[\.]+)\.(.+)?/; -var indexedPropertyRegex = /^([^\.]+)\[([0-9]+)\](\.)?(.+)?/; -function notValid(prop) { - return prop.slice(0, 2) === "__"; -} -lib.expandObjectPaths = function(data) { - var match, key, prop, datum, idx, dest, trailingPath; - if (typeof data === "object" && !Array.isArray(data)) { - for (key in data) { - if (data.hasOwnProperty(key)) { - if (match = key.match(dottedPropertyRegex)) { - datum = data[key]; - prop = match[1]; - if (notValid(prop)) continue; - delete data[key]; - data[prop] = lib.extendDeepNoArrays(data[prop] || {}, lib.objectFromPath(key, lib.expandObjectPaths(datum))[prop]); - } else if (match = key.match(indexedPropertyRegex)) { - datum = data[key]; - prop = match[1]; - if (notValid(prop)) continue; - idx = parseInt(match[2]); - delete data[key]; - data[prop] = data[prop] || []; - if (match[3] === ".") { - trailingPath = match[4]; - dest = data[prop][idx] = data[prop][idx] || {}; - lib.extendDeepNoArrays(dest, lib.objectFromPath(trailingPath, lib.expandObjectPaths(datum))); - } else { - if (notValid(prop)) continue; - data[prop][idx] = lib.expandObjectPaths(datum); - } - } else { - if (notValid(key)) continue; - data[key] = lib.expandObjectPaths(data[key]); - } - } - } - } - return data; -}; -lib.numSeparate = function(value2, separators, separatethousands) { - if (!separatethousands) separatethousands = false; - if (typeof separators !== "string" || separators.length === 0) { - throw new Error("Separator string required for formatting!"); - } - if (typeof value2 === "number") { - value2 = String(value2); - } - var thousandsRe = /(\d+)(\d{3})/; - var decimalSep = separators.charAt(0); - var thouSep = separators.charAt(1); - var x = value2.split("."); - var x1 = x[0]; - var x2 = x.length > 1 ? decimalSep + x[1] : ""; - if (thouSep && (x.length > 1 || x1.length > 4 || separatethousands)) { - while (thousandsRe.test(x1)) { - x1 = x1.replace(thousandsRe, "$1" + thouSep + "$2"); - } - } - return x1 + x2; -}; -lib.TEMPLATE_STRING_REGEX = /%{([^\s%{}:]*)([:|\|][^}]*)?}/g; -var SIMPLE_PROPERTY_REGEX = /^\w*$/; -lib.templateString = function(string2, obj) { - var getterCache = {}; - return string2.replace(lib.TEMPLATE_STRING_REGEX, function(dummy, key) { - var v; - if (SIMPLE_PROPERTY_REGEX.test(key)) { - v = obj[key]; - } else { - getterCache[key] = getterCache[key] || lib.nestedProperty(obj, key).get; - v = getterCache[key](); - } - return lib.isValidTextValue(v) ? v : ""; - }); -}; -var hovertemplateWarnings = { - max: 10, - count: 0, - name: "hovertemplate" -}; -lib.hovertemplateString = function() { - return templateFormatString.apply(hovertemplateWarnings, arguments); -}; -var texttemplateWarnings = { - max: 10, - count: 0, - name: "texttemplate" -}; -lib.texttemplateString = function() { - return templateFormatString.apply(texttemplateWarnings, arguments); -}; -var MULT_DIV_REGEX = /^(\S+)([\*\/])(-?\d+(\.\d+)?)$/; -function multDivParser(inputStr) { - var match = inputStr.match(MULT_DIV_REGEX); - if (match) return { key: match[1], op: match[2], number: Number(match[3]) }; - return { key: inputStr, op: null, number: null }; -} -var texttemplateWarningsForShapes = { - max: 10, - count: 0, - name: "texttemplate", - parseMultDiv: true -}; -lib.texttemplateStringForShapes = function() { - return templateFormatString.apply(texttemplateWarningsForShapes, arguments); -}; -var TEMPLATE_STRING_FORMAT_SEPARATOR = /^[:|\|]/; -function templateFormatString(string2, labels, d3locale) { - var opts = this; - var args = arguments; - if (!labels) labels = {}; - var getterCache = {}; - return string2.replace(lib.TEMPLATE_STRING_REGEX, function(match, rawKey, format2) { - var isOther = rawKey === "xother" || rawKey === "yother"; - var isSpaceOther = rawKey === "_xother" || rawKey === "_yother"; - var isSpaceOtherSpace = rawKey === "_xother_" || rawKey === "_yother_"; - var isOtherSpace = rawKey === "xother_" || rawKey === "yother_"; - var hasOther = isOther || isSpaceOther || isOtherSpace || isSpaceOtherSpace; - var key = rawKey; - if (isSpaceOther || isSpaceOtherSpace) key = key.substring(1); - if (isOtherSpace || isSpaceOtherSpace) key = key.substring(0, key.length - 1); - var parsedOp = null; - var parsedNumber = null; - if (opts.parseMultDiv) { - var _match = multDivParser(key); - key = _match.key; - parsedOp = _match.op; - parsedNumber = _match.number; - } - var value2; - if (hasOther) { - value2 = labels[key]; - if (value2 === void 0) return ""; - } else { - var obj, i; - for (i = 3; i < args.length; i++) { - obj = args[i]; - if (!obj) continue; - if (obj.hasOwnProperty(key)) { - value2 = obj[key]; - break; - } - if (!SIMPLE_PROPERTY_REGEX.test(key)) { - value2 = lib.nestedProperty(obj, key).get(); - value2 = getterCache[key] || lib.nestedProperty(obj, key).get(); - if (value2) getterCache[key] = value2; - } - if (value2 !== void 0) break; - } - } - if (value2 !== void 0) { - if (parsedOp === "*") value2 *= parsedNumber; - if (parsedOp === "/") value2 /= parsedNumber; - } - if (value2 === void 0 && opts) { - if (opts.count < opts.max) { - lib.warn("Variable '" + key + "' in " + opts.name + " could not be found!"); - value2 = match; - } - if (opts.count === opts.max) { - lib.warn("Too many " + opts.name + " warnings - additional warnings will be suppressed"); - } - opts.count++; - return match; - } - if (format2) { - var fmt; - if (format2[0] === ":") { - fmt = d3locale ? d3locale.numberFormat : lib.numberFormat; - if (value2 !== "") { - value2 = fmt(format2.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""))(value2); - } - } - if (format2[0] === "|") { - fmt = d3locale ? d3locale.timeFormat : utcFormat$1; - var ms = lib.dateTime2ms(value2); - value2 = lib.formatDate(ms, format2.replace(TEMPLATE_STRING_FORMAT_SEPARATOR, ""), false, fmt); - } - } else { - var keyLabel = key + "Label"; - if (labels.hasOwnProperty(keyLabel)) value2 = labels[keyLabel]; - } - if (hasOther) { - value2 = "(" + value2 + ")"; - if (isSpaceOther || isSpaceOtherSpace) value2 = " " + value2; - if (isOtherSpace || isSpaceOtherSpace) value2 = value2 + " "; - } - return value2; - }); -} -var char0 = 48; -var char9 = 57; -lib.subplotSort = function(a, b) { - var l = Math.min(a.length, b.length) + 1; - var numA = 0; - var numB = 0; - for (var i = 0; i < l; i++) { - var charA = a.charCodeAt(i) || 0; - var charB = b.charCodeAt(i) || 0; - var isNumA = charA >= char0 && charA <= char9; - var isNumB = charB >= char0 && charB <= char9; - if (isNumA) numA = 10 * numA + charA - char0; - if (isNumB) numB = 10 * numB + charB - char0; - if (!isNumA || !isNumB) { - if (numA !== numB) return numA - numB; - if (charA !== charB) return charA - charB; - } - } - return numB - numA; -}; -var randSeed = 2e9; -lib.seedPseudoRandom = function() { - randSeed = 2e9; -}; -lib.pseudoRandom = function() { - var lastVal = randSeed; - randSeed = (69069 * randSeed + 1) % 4294967296; - if (Math.abs(randSeed - lastVal) < 429496729) return lib.pseudoRandom(); - return randSeed / 4294967296; -}; -lib.fillText = function(calcPt, trace, contOut) { - var fill = Array.isArray(contOut) ? function(v) { - contOut.push(v); - } : function(v) { - contOut.text = v; - }; - var htx = lib.extractOption(calcPt, trace, "htx", "hovertext"); - if (lib.isValidTextValue(htx)) return fill(htx); - var tx = lib.extractOption(calcPt, trace, "tx", "text"); - if (lib.isValidTextValue(tx)) return fill(tx); -}; -lib.isValidTextValue = function(v) { - return v || v === 0; -}; -lib.formatPercent = function(ratio, n) { - n = n || 0; - var str2 = (Math.round(100 * ratio * Math.pow(10, n)) * Math.pow(0.1, n)).toFixed(n) + "%"; - for (var i = 0; i < n; i++) { - if (str2.indexOf(".") !== -1) { - str2 = str2.replace("0%", "%"); - str2 = str2.replace(".%", "%"); - } - } - return str2; -}; -lib.isHidden = function(gd) { - var display = window.getComputedStyle(gd).display; - return !display || display === "none"; -}; -lib.strTranslate = function(x, y) { - return x || y ? "translate(" + x + "," + y + ")" : ""; -}; -lib.strRotate = function(a) { - return a ? "rotate(" + a + ")" : ""; -}; -lib.strScale = function(s) { - return s !== 1 ? "scale(" + s + ")" : ""; -}; -lib.getTextTransform = function(transform) { - var noCenter = transform.noCenter; - var textX = transform.textX; - var textY = transform.textY; - var targetX = transform.targetX; - var targetY = transform.targetY; - var anchorX = transform.anchorX || 0; - var anchorY = transform.anchorY || 0; - var rotate2 = transform.rotate; - var scale2 = transform.scale; - if (!scale2) scale2 = 0; - else if (scale2 > 1) scale2 = 1; - return lib.strTranslate( - targetX - scale2 * (textX + anchorX), - targetY - scale2 * (textY + anchorY) - ) + lib.strScale(scale2) + (rotate2 ? "rotate(" + rotate2 + (noCenter ? "" : " " + textX + " " + textY) + ")" : ""); -}; -lib.setTransormAndDisplay = function(s, transform) { - s.attr("transform", lib.getTextTransform(transform)); - s.style("display", transform.scale ? null : "none"); -}; -lib.ensureUniformFontSize = function(gd, baseFont) { - var out = lib.extendFlat({}, baseFont); - out.size = Math.max( - baseFont.size, - gd._fullLayout.uniformtext.minsize || 0 - ); - return out; -}; -lib.join2 = function(arr, mainSeparator, lastSeparator) { - var len = arr.length; - if (len > 1) { - return arr.slice(0, -1).join(mainSeparator) + lastSeparator + arr[len - 1]; - } - return arr.join(mainSeparator); -}; -lib.bigFont = function(size) { - return Math.round(1.2 * size); -}; -var firefoxVersion = lib.getFirefoxVersion(); -var isProblematicFirefox = firefoxVersion !== null && firefoxVersion < 86; -lib.getPositionFromD3Event = function() { - if (isProblematicFirefox) { - return [ - d3$C.event.layerX, - d3$C.event.layerY - ]; - } else { - return [ - d3$C.event.offsetX, - d3$C.event.offsetY - ]; - } -}; -var libExports = lib$1.exports; -var Lib$1Z = libExports; -var rules = { - "X,X div": 'direction:ltr;font-family:"Open Sans",verdana,arial,sans-serif;margin:0;padding:0;', - "X input,X button": 'font-family:"Open Sans",verdana,arial,sans-serif;', - "X input:focus,X button:focus": "outline:none;", - "X a": "text-decoration:none;", - "X a:hover": "text-decoration:none;", - "X .crisp": "shape-rendering:crispEdges;", - "X .user-select-none": "-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;-o-user-select:none;user-select:none;", - "X svg": "overflow:hidden;", - "X svg a": "fill:#447adb;", - "X svg a:hover": "fill:#3c6dc5;", - "X .main-svg": "position:absolute;top:0;left:0;pointer-events:none;", - "X .main-svg .draglayer": "pointer-events:all;", - "X .cursor-default": "cursor:default;", - "X .cursor-pointer": "cursor:pointer;", - "X .cursor-crosshair": "cursor:crosshair;", - "X .cursor-move": "cursor:move;", - "X .cursor-col-resize": "cursor:col-resize;", - "X .cursor-row-resize": "cursor:row-resize;", - "X .cursor-ns-resize": "cursor:ns-resize;", - "X .cursor-ew-resize": "cursor:ew-resize;", - "X .cursor-sw-resize": "cursor:sw-resize;", - "X .cursor-s-resize": "cursor:s-resize;", - "X .cursor-se-resize": "cursor:se-resize;", - "X .cursor-w-resize": "cursor:w-resize;", - "X .cursor-e-resize": "cursor:e-resize;", - "X .cursor-nw-resize": "cursor:nw-resize;", - "X .cursor-n-resize": "cursor:n-resize;", - "X .cursor-ne-resize": "cursor:ne-resize;", - "X .cursor-grab": "cursor:-webkit-grab;cursor:grab;", - "X .modebar": "position:absolute;top:2px;right:2px;", - "X .ease-bg": "-webkit-transition:background-color .3s ease 0s;-moz-transition:background-color .3s ease 0s;-ms-transition:background-color .3s ease 0s;-o-transition:background-color .3s ease 0s;transition:background-color .3s ease 0s;", - "X .modebar--hover>:not(.watermark)": "opacity:0;-webkit-transition:opacity .3s ease 0s;-moz-transition:opacity .3s ease 0s;-ms-transition:opacity .3s ease 0s;-o-transition:opacity .3s ease 0s;transition:opacity .3s ease 0s;", - "X:hover .modebar--hover .modebar-group": "opacity:1;", - "X .modebar-group": "float:left;display:inline-block;box-sizing:border-box;padding-left:8px;position:relative;vertical-align:middle;white-space:nowrap;", - "X .modebar-btn": "position:relative;font-size:16px;padding:3px 4px;height:22px;cursor:pointer;line-height:normal;box-sizing:border-box;", - "X .modebar-btn svg": "position:relative;top:2px;", - "X .modebar.vertical": "display:flex;flex-direction:column;flex-wrap:wrap;align-content:flex-end;max-height:100%;", - "X .modebar.vertical svg": "top:-1px;", - "X .modebar.vertical .modebar-group": "display:block;float:none;padding-left:0px;padding-bottom:8px;", - "X .modebar.vertical .modebar-group .modebar-btn": "display:block;text-align:center;", - "X [data-title]:before,X [data-title]:after": "position:absolute;-webkit-transform:translate3d(0, 0, 0);-moz-transform:translate3d(0, 0, 0);-ms-transform:translate3d(0, 0, 0);-o-transform:translate3d(0, 0, 0);transform:translate3d(0, 0, 0);display:none;opacity:0;z-index:1001;pointer-events:none;top:110%;right:50%;", - "X [data-title]:hover:before,X [data-title]:hover:after": "display:block;opacity:1;", - "X [data-title]:before": 'content:"";position:absolute;background:rgba(0,0,0,0);border:6px solid rgba(0,0,0,0);z-index:1002;margin-top:-12px;border-bottom-color:#69738a;margin-right:-6px;', - "X [data-title]:after": "content:attr(data-title);background:#69738a;color:#fff;padding:8px 10px;font-size:12px;line-height:12px;white-space:nowrap;margin-right:-18px;border-radius:2px;", - "X .vertical [data-title]:before,X .vertical [data-title]:after": "top:0%;right:200%;", - "X .vertical [data-title]:before": "border:6px solid rgba(0,0,0,0);border-left-color:#69738a;margin-top:8px;margin-right:-30px;", - Y: 'font-family:"Open Sans",verdana,arial,sans-serif;position:fixed;top:50px;right:20px;z-index:10000;font-size:10pt;max-width:180px;', - "Y p": "margin:0;", - "Y .notifier-note": "min-width:180px;max-width:250px;border:1px solid #fff;z-index:3000;margin:0;background-color:#8c97af;background-color:rgba(140,151,175,.9);color:#fff;padding:10px;overflow-wrap:break-word;word-wrap:break-word;-ms-hyphens:auto;-webkit-hyphens:auto;hyphens:auto;", - "Y .notifier-close": "color:#fff;opacity:.8;float:right;padding:0 5px;background:none;border:none;font-size:20px;font-weight:bold;line-height:20px;", - "Y .notifier-close:hover": "color:#444;text-decoration:none;cursor:pointer;" -}; -for (var selector in rules) { - var fullSelector = selector.replace(/^,/, " ,").replace(/X/g, ".js-plotly-plot .plotly").replace(/Y/g, ".plotly-notifier"); - Lib$1Z.addStyleRule(fullSelector, rules[selector]); -} -var plot_api$1 = {}; -var plot_api = {}; -var client = true; -var isBrowser = client; -var hasHover$1; -if (typeof index$3.commonjsGlobal.matchMedia === "function") { - hasHover$1 = !index$3.commonjsGlobal.matchMedia("(hover: none)").matches; -} else { - hasHover$1 = isBrowser; -} -var hasHover_1 = hasHover$1; -var events$1 = { exports: {} }; -var R = typeof Reflect === "object" ? Reflect : null; -var ReflectApply = R && typeof R.apply === "function" ? R.apply : function ReflectApply2(target, receiver, args) { - return Function.prototype.apply.call(target, receiver, args); -}; -var ReflectOwnKeys; -if (R && typeof R.ownKeys === "function") { - ReflectOwnKeys = R.ownKeys; -} else if (Object.getOwnPropertySymbols) { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target).concat(Object.getOwnPropertySymbols(target)); - }; -} else { - ReflectOwnKeys = function ReflectOwnKeys2(target) { - return Object.getOwnPropertyNames(target); - }; -} -function ProcessEmitWarning(warning) { - if (console && console.warn) console.warn(warning); -} -var NumberIsNaN = Number.isNaN || function NumberIsNaN2(value2) { - return value2 !== value2; -}; -function EventEmitter$3() { - EventEmitter$3.init.call(this); -} -events$1.exports = EventEmitter$3; -events$1.exports.once = once2; -EventEmitter$3.EventEmitter = EventEmitter$3; -EventEmitter$3.prototype._events = void 0; -EventEmitter$3.prototype._eventsCount = 0; -EventEmitter$3.prototype._maxListeners = void 0; -var defaultMaxListeners = 10; -function checkListener(listener) { - if (typeof listener !== "function") { - throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); - } -} -Object.defineProperty(EventEmitter$3, "defaultMaxListeners", { - enumerable: true, - get: function() { - return defaultMaxListeners; - }, - set: function(arg) { - if (typeof arg !== "number" || arg < 0 || NumberIsNaN(arg)) { - throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + "."); - } - defaultMaxListeners = arg; - } -}); -EventEmitter$3.init = function() { - if (this._events === void 0 || this._events === Object.getPrototypeOf(this)._events) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } - this._maxListeners = this._maxListeners || void 0; -}; -EventEmitter$3.prototype.setMaxListeners = function setMaxListeners(n) { - if (typeof n !== "number" || n < 0 || NumberIsNaN(n)) { - throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + "."); - } - this._maxListeners = n; - return this; -}; -function _getMaxListeners(that) { - if (that._maxListeners === void 0) - return EventEmitter$3.defaultMaxListeners; - return that._maxListeners; -} -EventEmitter$3.prototype.getMaxListeners = function getMaxListeners() { - return _getMaxListeners(this); -}; -EventEmitter$3.prototype.emit = function emit(type) { - var args = []; - for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); - var doError = type === "error"; - var events2 = this._events; - if (events2 !== void 0) - doError = doError && events2.error === void 0; - else if (!doError) - return false; - if (doError) { - var er; - if (args.length > 0) - er = args[0]; - if (er instanceof Error) { - throw er; - } - var err = new Error("Unhandled error." + (er ? " (" + er.message + ")" : "")); - err.context = er; - throw err; - } - var handler = events2[type]; - if (handler === void 0) - return false; - if (typeof handler === "function") { - ReflectApply(handler, this, args); - } else { - var len = handler.length; - var listeners2 = arrayClone(handler, len); - for (var i = 0; i < len; ++i) - ReflectApply(listeners2[i], this, args); - } - return true; -}; -function _addListener(target, type, listener, prepend) { - var m; - var events2; - var existing; - checkListener(listener); - events2 = target._events; - if (events2 === void 0) { - events2 = target._events = /* @__PURE__ */ Object.create(null); - target._eventsCount = 0; - } else { - if (events2.newListener !== void 0) { - target.emit( - "newListener", - type, - listener.listener ? listener.listener : listener - ); - events2 = target._events; - } - existing = events2[type]; - } - if (existing === void 0) { - existing = events2[type] = listener; - ++target._eventsCount; - } else { - if (typeof existing === "function") { - existing = events2[type] = prepend ? [listener, existing] : [existing, listener]; - } else if (prepend) { - existing.unshift(listener); - } else { - existing.push(listener); - } - m = _getMaxListeners(target); - if (m > 0 && existing.length > m && !existing.warned) { - existing.warned = true; - var w = new Error("Possible EventEmitter memory leak detected. " + existing.length + " " + String(type) + " listeners added. Use emitter.setMaxListeners() to increase limit"); - w.name = "MaxListenersExceededWarning"; - w.emitter = target; - w.type = type; - w.count = existing.length; - ProcessEmitWarning(w); - } - } - return target; -} -EventEmitter$3.prototype.addListener = function addListener(type, listener) { - return _addListener(this, type, listener, false); -}; -EventEmitter$3.prototype.on = EventEmitter$3.prototype.addListener; -EventEmitter$3.prototype.prependListener = function prependListener(type, listener) { - return _addListener(this, type, listener, true); -}; -function onceWrapper() { - if (!this.fired) { - this.target.removeListener(this.type, this.wrapFn); - this.fired = true; - if (arguments.length === 0) - return this.listener.call(this.target); - return this.listener.apply(this.target, arguments); - } -} -function _onceWrap(target, type, listener) { - var state = { fired: false, wrapFn: void 0, target, type, listener }; - var wrapped = onceWrapper.bind(state); - wrapped.listener = listener; - state.wrapFn = wrapped; - return wrapped; -} -EventEmitter$3.prototype.once = function once(type, listener) { - checkListener(listener); - this.on(type, _onceWrap(this, type, listener)); - return this; -}; -EventEmitter$3.prototype.prependOnceListener = function prependOnceListener(type, listener) { - checkListener(listener); - this.prependListener(type, _onceWrap(this, type, listener)); - return this; -}; -EventEmitter$3.prototype.removeListener = function removeListener(type, listener) { - var list, events2, position, i, originalListener; - checkListener(listener); - events2 = this._events; - if (events2 === void 0) - return this; - list = events2[type]; - if (list === void 0) - return this; - if (list === listener || list.listener === listener) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else { - delete events2[type]; - if (events2.removeListener) - this.emit("removeListener", type, list.listener || listener); - } - } else if (typeof list !== "function") { - position = -1; - for (i = list.length - 1; i >= 0; i--) { - if (list[i] === listener || list[i].listener === listener) { - originalListener = list[i].listener; - position = i; - break; - } - } - if (position < 0) - return this; - if (position === 0) - list.shift(); - else { - spliceOne(list, position); - } - if (list.length === 1) - events2[type] = list[0]; - if (events2.removeListener !== void 0) - this.emit("removeListener", type, originalListener || listener); - } - return this; -}; -EventEmitter$3.prototype.off = EventEmitter$3.prototype.removeListener; -EventEmitter$3.prototype.removeAllListeners = function removeAllListeners(type) { - var listeners2, events2, i; - events2 = this._events; - if (events2 === void 0) - return this; - if (events2.removeListener === void 0) { - if (arguments.length === 0) { - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - } else if (events2[type] !== void 0) { - if (--this._eventsCount === 0) - this._events = /* @__PURE__ */ Object.create(null); - else - delete events2[type]; - } - return this; - } - if (arguments.length === 0) { - var keys = Object.keys(events2); - var key; - for (i = 0; i < keys.length; ++i) { - key = keys[i]; - if (key === "removeListener") continue; - this.removeAllListeners(key); - } - this.removeAllListeners("removeListener"); - this._events = /* @__PURE__ */ Object.create(null); - this._eventsCount = 0; - return this; - } - listeners2 = events2[type]; - if (typeof listeners2 === "function") { - this.removeListener(type, listeners2); - } else if (listeners2 !== void 0) { - for (i = listeners2.length - 1; i >= 0; i--) { - this.removeListener(type, listeners2[i]); - } - } - return this; -}; -function _listeners(target, type, unwrap) { - var events2 = target._events; - if (events2 === void 0) - return []; - var evlistener = events2[type]; - if (evlistener === void 0) - return []; - if (typeof evlistener === "function") - return unwrap ? [evlistener.listener || evlistener] : [evlistener]; - return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); -} -EventEmitter$3.prototype.listeners = function listeners(type) { - return _listeners(this, type, true); -}; -EventEmitter$3.prototype.rawListeners = function rawListeners(type) { - return _listeners(this, type, false); -}; -EventEmitter$3.listenerCount = function(emitter, type) { - if (typeof emitter.listenerCount === "function") { - return emitter.listenerCount(type); - } else { - return listenerCount.call(emitter, type); - } -}; -EventEmitter$3.prototype.listenerCount = listenerCount; -function listenerCount(type) { - var events2 = this._events; - if (events2 !== void 0) { - var evlistener = events2[type]; - if (typeof evlistener === "function") { - return 1; - } else if (evlistener !== void 0) { - return evlistener.length; - } - } - return 0; -} -EventEmitter$3.prototype.eventNames = function eventNames() { - return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; -}; -function arrayClone(arr, n) { - var copy2 = new Array(n); - for (var i = 0; i < n; ++i) - copy2[i] = arr[i]; - return copy2; -} -function spliceOne(list, index2) { - for (; index2 + 1 < list.length; index2++) - list[index2] = list[index2 + 1]; - list.pop(); -} -function unwrapListeners(arr) { - var ret = new Array(arr.length); - for (var i = 0; i < ret.length; ++i) { - ret[i] = arr[i].listener || arr[i]; - } - return ret; -} -function once2(emitter, name2) { - return new Promise(function(resolve, reject) { - function errorListener(err) { - emitter.removeListener(name2, resolver); - reject(err); - } - function resolver() { - if (typeof emitter.removeListener === "function") { - emitter.removeListener("error", errorListener); - } - resolve([].slice.call(arguments)); - } - eventTargetAgnosticAddListener(emitter, name2, resolver, { once: true }); - if (name2 !== "error") { - addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); - } - }); -} -function addErrorHandlerIfEventEmitter(emitter, handler, flags) { - if (typeof emitter.on === "function") { - eventTargetAgnosticAddListener(emitter, "error", handler, flags); - } -} -function eventTargetAgnosticAddListener(emitter, name2, listener, flags) { - if (typeof emitter.on === "function") { - if (flags.once) { - emitter.once(name2, listener); - } else { - emitter.on(name2, listener); - } - } else if (typeof emitter.addEventListener === "function") { - emitter.addEventListener(name2, function wrapListener(arg) { - if (flags.once) { - emitter.removeEventListener(name2, wrapListener); - } - listener(arg); - }); - } else { - throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); - } -} -var eventsExports = events$1.exports; -var EventEmitter$2 = eventsExports.EventEmitter; -var Events$4 = { - init: function(plotObj) { - if (plotObj._ev instanceof EventEmitter$2) return plotObj; - var ev = new EventEmitter$2(); - var internalEv = new EventEmitter$2(); - plotObj._ev = ev; - plotObj._internalEv = internalEv; - plotObj.on = ev.on.bind(ev); - plotObj.once = ev.once.bind(ev); - plotObj.removeListener = ev.removeListener.bind(ev); - plotObj.removeAllListeners = ev.removeAllListeners.bind(ev); - plotObj._internalOn = internalEv.on.bind(internalEv); - plotObj._internalOnce = internalEv.once.bind(internalEv); - plotObj._removeInternalListener = internalEv.removeListener.bind(internalEv); - plotObj._removeAllInternalListeners = internalEv.removeAllListeners.bind(internalEv); - plotObj.emit = function(event, data) { - if (typeof jQuery !== "undefined") { - jQuery(plotObj).trigger(event, data); - } - ev.emit(event, data); - internalEv.emit(event, data); - }; - return plotObj; - }, - /* - * This function behaves like jQuery's triggerHandler. It calls - * all handlers for a particular event and returns the return value - * of the LAST handler. This function also triggers jQuery's - * triggerHandler for backwards compatibility. - */ - triggerHandler: function(plotObj, event, data) { - var jQueryHandlerValue; - var nodeEventHandlerValue; - if (typeof jQuery !== "undefined") { - jQueryHandlerValue = jQuery(plotObj).triggerHandler(event, data); - } - var ev = plotObj._ev; - if (!ev) return jQueryHandlerValue; - var handlers = ev._events[event]; - if (!handlers) return jQueryHandlerValue; - function apply(handler) { - if (handler.listener) { - ev.removeListener(event, handler.listener); - if (!handler.fired) { - handler.fired = true; - return handler.listener.apply(ev, [data]); - } - } else { - return handler.apply(ev, [data]); - } - } - handlers = Array.isArray(handlers) ? handlers : [handlers]; - var i; - for (i = 0; i < handlers.length - 1; i++) { - apply(handlers[i]); - } - nodeEventHandlerValue = apply(handlers[i]); - return jQueryHandlerValue !== void 0 ? jQueryHandlerValue : nodeEventHandlerValue; - }, - purge: function(plotObj) { - delete plotObj._ev; - delete plotObj.on; - delete plotObj.once; - delete plotObj.removeListener; - delete plotObj.removeAllListeners; - delete plotObj.emit; - delete plotObj._ev; - delete plotObj._internalEv; - delete plotObj._internalOn; - delete plotObj._internalOnce; - delete plotObj._removeInternalListener; - delete plotObj._removeAllInternalListeners; - return plotObj; - } -}; -var events = Events$4; -var Lib$1Y = libExports; -var dfltConfig$2 = plot_config.dfltConfig; -function copyArgArray(gd, args) { - var copy2 = []; - var arg; - for (var i = 0; i < args.length; i++) { - arg = args[i]; - if (arg === gd) copy2[i] = arg; - else if (typeof arg === "object") { - copy2[i] = Array.isArray(arg) ? Lib$1Y.extendDeep([], arg) : Lib$1Y.extendDeepAll({}, arg); - } else copy2[i] = arg; - } - return copy2; -} -var queue = {}; -queue.add = function(gd, undoFunc, undoArgs, redoFunc, redoArgs) { - var queueObj, queueIndex; - gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; - queueIndex = gd.undoQueue.index; - if (gd.autoplay) { - if (!gd.undoQueue.inSequence) gd.autoplay = false; - return; - } - if (!gd.undoQueue.sequence || gd.undoQueue.beginSequence) { - queueObj = { undo: { calls: [], args: [] }, redo: { calls: [], args: [] } }; - gd.undoQueue.queue.splice(queueIndex, gd.undoQueue.queue.length - queueIndex, queueObj); - gd.undoQueue.index += 1; - } else { - queueObj = gd.undoQueue.queue[queueIndex - 1]; - } - gd.undoQueue.beginSequence = false; - if (queueObj) { - queueObj.undo.calls.unshift(undoFunc); - queueObj.undo.args.unshift(undoArgs); - queueObj.redo.calls.push(redoFunc); - queueObj.redo.args.push(redoArgs); - } - if (gd.undoQueue.queue.length > dfltConfig$2.queueLength) { - gd.undoQueue.queue.shift(); - gd.undoQueue.index--; - } -}; -queue.startSequence = function(gd) { - gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; - gd.undoQueue.sequence = true; - gd.undoQueue.beginSequence = true; -}; -queue.stopSequence = function(gd) { - gd.undoQueue = gd.undoQueue || { index: 0, queue: [], sequence: false }; - gd.undoQueue.sequence = false; - gd.undoQueue.beginSequence = false; -}; -queue.undo = function undo(gd) { - var queueObj, i; - if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index <= 0) { - return; - } - gd.undoQueue.index--; - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - gd.undoQueue.inSequence = true; - for (i = 0; i < queueObj.undo.calls.length; i++) { - queue.plotDo(gd, queueObj.undo.calls[i], queueObj.undo.args[i]); - } - gd.undoQueue.inSequence = false; - gd.autoplay = false; -}; -queue.redo = function redo(gd) { - var queueObj, i; - if (gd.undoQueue === void 0 || isNaN(gd.undoQueue.index) || gd.undoQueue.index >= gd.undoQueue.queue.length) { - return; - } - queueObj = gd.undoQueue.queue[gd.undoQueue.index]; - gd.undoQueue.inSequence = true; - for (i = 0; i < queueObj.redo.calls.length; i++) { - queue.plotDo(gd, queueObj.redo.calls[i], queueObj.redo.args[i]); - } - gd.undoQueue.inSequence = false; - gd.autoplay = false; - gd.undoQueue.index++; -}; -queue.plotDo = function(gd, func, args) { - gd.autoplay = true; - args = copyArgArray(gd, args); - func.apply(null, args); -}; -var queue_1 = queue; -var plot_schema = {}; -var frame_attributes = { - _isLinkedToArray: "frames_entry", - group: { - valType: "string", - description: [ - "An identifier that specifies the group to which the frame belongs,", - "used by animate to select a subset of frames." - ].join(" ") - }, - name: { - valType: "string", - description: "A label by which to identify the frame" - }, - traces: { - valType: "any", - description: [ - "A list of trace indices that identify the respective traces in the", - "data attribute" - ].join(" ") - }, - baseframe: { - valType: "string", - description: [ - "The name of the frame into which this frame's properties are merged", - "before applying. This is used to unify properties and avoid needing", - "to specify the same values for the same properties in multiple frames." - ].join(" ") - }, - data: { - valType: "any", - description: [ - "A list of traces this frame modifies. The format is identical to the", - "normal trace definition." - ].join(" ") - }, - layout: { - valType: "any", - description: [ - "Layout properties which this frame modifies. The format is identical", - "to the normal layout definition." - ].join(" ") - } -}; -(function(exports2) { - var Registry2 = registry; - var Lib2 = libExports; - var baseAttributes = attributes$O; - var baseLayoutAttributes = layout_attributes$6; - var frameAttributes = frame_attributes; - var animationAttributes = animation_attributes; - var configAttributes2 = plot_config.configAttributes; - var editTypes = edit_types; - var extendDeepAll2 = Lib2.extendDeepAll; - var isPlainObject3 = Lib2.isPlainObject; - var isArrayOrTypedArray2 = Lib2.isArrayOrTypedArray; - var nestedProperty3 = Lib2.nestedProperty; - var valObjectMeta = Lib2.valObjectMeta; - var IS_SUBPLOT_OBJ = "_isSubplotObj"; - var IS_LINKED_TO_ARRAY = "_isLinkedToArray"; - var ARRAY_ATTR_REGEXPS = "_arrayAttrRegexps"; - var DEPRECATED = "_deprecated"; - var UNDERSCORE_ATTRS = [IS_SUBPLOT_OBJ, IS_LINKED_TO_ARRAY, ARRAY_ATTR_REGEXPS, DEPRECATED]; - exports2.IS_SUBPLOT_OBJ = IS_SUBPLOT_OBJ; - exports2.IS_LINKED_TO_ARRAY = IS_LINKED_TO_ARRAY; - exports2.DEPRECATED = DEPRECATED; - exports2.UNDERSCORE_ATTRS = UNDERSCORE_ATTRS; - exports2.get = function() { - var traces = {}; - Registry2.allTypes.forEach(function(type) { - traces[type] = getTraceAttributes(type); - }); - var transforms = {}; - Object.keys(Registry2.transformsRegistry).forEach(function(type) { - transforms[type] = getTransformAttributes(type); - }); - return { - defs: { - valObjects: valObjectMeta, - metaKeys: UNDERSCORE_ATTRS.concat(["description", "role", "editType", "impliedEdits"]), - editType: { - traces: editTypes.traces, - layout: editTypes.layout - }, - impliedEdits: { - description: [ - "Sometimes when an attribute is changed, other attributes", - "must be altered as well in order to achieve the intended", - "result. For example, when `range` is specified, it is", - "important to set `autorange` to `false` or the new `range`", - "value would be lost in the redraw. `impliedEdits` is the", - "mechanism to do this: `impliedEdits: {autorange: false}`.", - "Each key is a relative paths to the attribute string to", - "change, using *^* to ascend into the parent container,", - "for example `range[0]` has `impliedEdits: {*^autorange*: false}`.", - "A value of `undefined` means that the attribute will not be", - "changed, but its previous value should be recorded in case", - "we want to reverse this change later. For example, `autorange`", - "has `impliedEdits: {*range[0]*: undefined, *range[1]*:undefined}", - "because the range will likely be changed by redraw." - ].join(" ") - } - }, - traces, - layout: getLayoutAttributes(), - transforms, - frames: getFramesAttributes(), - animation: formatAttributes(animationAttributes), - config: formatAttributes(configAttributes2) - }; - }; - exports2.crawl = function(attrs2, callback, specifiedLevel, attrString) { - var level = specifiedLevel || 0; - attrString = attrString || ""; - Object.keys(attrs2).forEach(function(attrName) { - var attr = attrs2[attrName]; - if (UNDERSCORE_ATTRS.indexOf(attrName) !== -1) return; - var fullAttrString = (attrString ? attrString + "." : "") + attrName; - callback(attr, attrName, attrs2, level, fullAttrString); - if (exports2.isValObject(attr)) return; - if (isPlainObject3(attr) && attrName !== "impliedEdits") { - exports2.crawl(attr, callback, level + 1, fullAttrString); - } - }); - }; - exports2.isValObject = function(obj) { - return obj && obj.valType !== void 0; - }; - exports2.findArrayAttributes = function(trace) { - var arrayAttributes = []; - var stack = []; - var isArrayStack = []; - var baseContainer, baseAttrName; - function callback(attr, attrName, attrs2, level) { - stack = stack.slice(0, level).concat([attrName]); - isArrayStack = isArrayStack.slice(0, level).concat([attr && attr._isLinkedToArray]); - var splittableAttr = attr && (attr.valType === "data_array" || attr.arrayOk === true) && !(stack[level - 1] === "colorbar" && (attrName === "ticktext" || attrName === "tickvals")); - if (!splittableAttr) return; - crawlIntoTrace(baseContainer, 0, ""); - } - function crawlIntoTrace(container, i2, astrPartial) { - var item = container[stack[i2]]; - var newAstrPartial = astrPartial + stack[i2]; - if (i2 === stack.length - 1) { - if (isArrayOrTypedArray2(item)) { - arrayAttributes.push(baseAttrName + newAstrPartial); - } - } else { - if (isArrayStack[i2]) { - if (Array.isArray(item)) { - for (var j = 0; j < item.length; j++) { - if (isPlainObject3(item[j])) { - crawlIntoTrace(item[j], i2 + 1, newAstrPartial + "[" + j + "]."); - } - } - } - } else if (isPlainObject3(item)) { - crawlIntoTrace(item, i2 + 1, newAstrPartial + "."); - } - } - } - baseContainer = trace; - baseAttrName = ""; - exports2.crawl(baseAttributes, callback); - if (trace._module && trace._module.attributes) { - exports2.crawl(trace._module.attributes, callback); - } - var transforms = trace.transforms; - if (transforms) { - for (var i = 0; i < transforms.length; i++) { - var transform = transforms[i]; - var module2 = transform._module; - if (module2) { - baseAttrName = "transforms[" + i + "]."; - baseContainer = transform; - exports2.crawl(module2.attributes, callback); - } - } - } - return arrayAttributes; - }; - exports2.getTraceValObject = function(trace, parts) { - var head = parts[0]; - var i = 1; - var moduleAttrs, valObject; - if (head === "transforms") { - if (parts.length === 1) { - return baseAttributes.transforms; - } - var transforms = trace.transforms; - if (!Array.isArray(transforms) || !transforms.length) return false; - var tNum = parts[1]; - if (!isIndex(tNum) || tNum >= transforms.length) { - return false; - } - moduleAttrs = (Registry2.transformsRegistry[transforms[tNum].type] || {}).attributes; - valObject = moduleAttrs && moduleAttrs[parts[2]]; - i = 3; - } else { - var _module = trace._module; - if (!_module) _module = (Registry2.modules[trace.type || baseAttributes.type.dflt] || {})._module; - if (!_module) return false; - moduleAttrs = _module.attributes; - valObject = moduleAttrs && moduleAttrs[head]; - if (!valObject) { - var subplotModule = _module.basePlotModule; - if (subplotModule && subplotModule.attributes) { - valObject = subplotModule.attributes[head]; - } - } - if (!valObject) valObject = baseAttributes[head]; - } - return recurseIntoValObject(valObject, parts, i); - }; - exports2.getLayoutValObject = function(fullLayout, parts) { - var valObject = layoutHeadAttr(fullLayout, parts[0]); - return recurseIntoValObject(valObject, parts, 1); - }; - function layoutHeadAttr(fullLayout, head) { - var i, key, _module, attributes2; - var basePlotModules = fullLayout._basePlotModules; - if (basePlotModules) { - var out; - for (i = 0; i < basePlotModules.length; i++) { - _module = basePlotModules[i]; - if (_module.attrRegex && _module.attrRegex.test(head)) { - if (_module.layoutAttrOverrides) return _module.layoutAttrOverrides; - if (!out && _module.layoutAttributes) out = _module.layoutAttributes; - } - var baseOverrides = _module.baseLayoutAttrOverrides; - if (baseOverrides && head in baseOverrides) return baseOverrides[head]; - } - if (out) return out; - } - var modules2 = fullLayout._modules; - if (modules2) { - for (i = 0; i < modules2.length; i++) { - attributes2 = modules2[i].layoutAttributes; - if (attributes2 && head in attributes2) { - return attributes2[head]; - } - } - } - for (key in Registry2.componentsRegistry) { - _module = Registry2.componentsRegistry[key]; - if (_module.name === "colorscale" && head.indexOf("coloraxis") === 0) { - return _module.layoutAttributes[head]; - } else if (!_module.schema && head === _module.name) { - return _module.layoutAttributes; - } - } - if (head in baseLayoutAttributes) return baseLayoutAttributes[head]; - return false; - } - function recurseIntoValObject(valObject, parts, i) { - if (!valObject) return false; - if (valObject._isLinkedToArray) { - if (isIndex(parts[i])) i++; - else if (i < parts.length) return false; - } - for (; i < parts.length; i++) { - var newValObject = valObject[parts[i]]; - if (isPlainObject3(newValObject)) valObject = newValObject; - else break; - if (i === parts.length - 1) break; - if (valObject._isLinkedToArray) { - i++; - if (!isIndex(parts[i])) return false; - } else if (valObject.valType === "info_array") { - i++; - var index2 = parts[i]; - if (!isIndex(index2)) return false; - var items = valObject.items; - if (Array.isArray(items)) { - if (index2 >= items.length) return false; - if (valObject.dimensions === 2) { - i++; - if (parts.length === i) return valObject; - var index22 = parts[i]; - if (!isIndex(index22)) return false; - valObject = items[index2][index22]; - } else valObject = items[index2]; - } else { - valObject = items; - } - } - } - return valObject; - } - function isIndex(val) { - return val === Math.round(val) && val >= 0; - } - function getTraceAttributes(type) { - var _module, basePlotModule; - _module = Registry2.modules[type]._module, basePlotModule = _module.basePlotModule; - var attributes2 = {}; - attributes2.type = null; - var copyBaseAttributes = extendDeepAll2({}, baseAttributes); - var copyModuleAttributes = extendDeepAll2({}, _module.attributes); - exports2.crawl(copyModuleAttributes, function(attr, attrName, attrs2, level, fullAttrString) { - nestedProperty3(copyBaseAttributes, fullAttrString).set(void 0); - if (attr === void 0) nestedProperty3(copyModuleAttributes, fullAttrString).set(void 0); - }); - extendDeepAll2(attributes2, copyBaseAttributes); - if (Registry2.traceIs(type, "noOpacity")) { - delete attributes2.opacity; - } - if (!Registry2.traceIs(type, "showLegend")) { - delete attributes2.showlegend; - delete attributes2.legendgroup; - } - if (Registry2.traceIs(type, "noHover")) { - delete attributes2.hoverinfo; - delete attributes2.hoverlabel; - } - if (!_module.selectPoints) { - delete attributes2.selectedpoints; - } - extendDeepAll2(attributes2, copyModuleAttributes); - if (basePlotModule.attributes) { - extendDeepAll2(attributes2, basePlotModule.attributes); - } - attributes2.type = type; - var out = { - meta: _module.meta || {}, - categories: _module.categories || {}, - animatable: Boolean(_module.animatable), - type, - attributes: formatAttributes(attributes2) - }; - if (_module.layoutAttributes) { - var layoutAttributes2 = {}; - extendDeepAll2(layoutAttributes2, _module.layoutAttributes); - out.layoutAttributes = formatAttributes(layoutAttributes2); - } - if (!_module.animatable) { - exports2.crawl(out, function(attr) { - if (exports2.isValObject(attr) && "anim" in attr) { - delete attr.anim; - } - }); - } - return out; - } - function getLayoutAttributes() { - var layoutAttributes2 = {}; - var key, _module; - extendDeepAll2(layoutAttributes2, baseLayoutAttributes); - for (key in Registry2.subplotsRegistry) { - _module = Registry2.subplotsRegistry[key]; - if (!_module.layoutAttributes) continue; - if (Array.isArray(_module.attr)) { - for (var i = 0; i < _module.attr.length; i++) { - handleBasePlotModule(layoutAttributes2, _module, _module.attr[i]); - } - } else { - var astr = _module.attr === "subplot" ? _module.name : _module.attr; - handleBasePlotModule(layoutAttributes2, _module, astr); - } - } - for (key in Registry2.componentsRegistry) { - _module = Registry2.componentsRegistry[key]; - var schema = _module.schema; - if (schema && (schema.subplots || schema.layout)) { - var subplots = schema.subplots; - if (subplots && subplots.xaxis && !subplots.yaxis) { - for (var xkey in subplots.xaxis) { - delete layoutAttributes2.yaxis[xkey]; - } - } - delete layoutAttributes2.xaxis.shift; - delete layoutAttributes2.xaxis.autoshift; - } else if (_module.name === "colorscale") { - extendDeepAll2(layoutAttributes2, _module.layoutAttributes); - } else if (_module.layoutAttributes) { - insertAttrs(layoutAttributes2, _module.layoutAttributes, _module.name); - } - } - return { - layoutAttributes: formatAttributes(layoutAttributes2) - }; - } - function getTransformAttributes(type) { - var _module = Registry2.transformsRegistry[type]; - var attributes2 = extendDeepAll2({}, _module.attributes); - Object.keys(Registry2.componentsRegistry).forEach(function(k) { - var _module2 = Registry2.componentsRegistry[k]; - if (_module2.schema && _module2.schema.transforms && _module2.schema.transforms[type]) { - Object.keys(_module2.schema.transforms[type]).forEach(function(v) { - insertAttrs(attributes2, _module2.schema.transforms[type][v], v); - }); - } - }); - return { - attributes: formatAttributes(attributes2) - }; - } - function getFramesAttributes() { - var attrs2 = { - frames: extendDeepAll2({}, frameAttributes) - }; - formatAttributes(attrs2); - return attrs2.frames; - } - function formatAttributes(attrs2) { - mergeValTypeAndRole(attrs2); - formatArrayContainers(attrs2); - stringify2(attrs2); - return attrs2; - } - function mergeValTypeAndRole(attrs2) { - function makeSrcAttr(attrName) { - return { - valType: "string", - description: "Sets the source reference on Chart Studio Cloud for `" + attrName + "`.", - editType: "none" - }; - } - function callback(attr, attrName, attrs3) { - if (exports2.isValObject(attr)) { - if (attr.arrayOk === true || attr.valType === "data_array") { - attrs3[attrName + "src"] = makeSrcAttr(attrName); - } - } else if (isPlainObject3(attr)) { - attr.role = "object"; - } - } - exports2.crawl(attrs2, callback); - } - function formatArrayContainers(attrs2) { - function callback(attr, attrName, attrs3) { - if (!attr) return; - var itemName = attr[IS_LINKED_TO_ARRAY]; - if (!itemName) return; - delete attr[IS_LINKED_TO_ARRAY]; - attrs3[attrName] = { items: {} }; - attrs3[attrName].items[itemName] = attr; - attrs3[attrName].role = "object"; - } - exports2.crawl(attrs2, callback); - } - function stringify2(attrs2) { - function walk(attr) { - for (var k in attr) { - if (isPlainObject3(attr[k])) { - walk(attr[k]); - } else if (Array.isArray(attr[k])) { - for (var i = 0; i < attr[k].length; i++) { - walk(attr[k][i]); - } - } else { - if (attr[k] instanceof RegExp) { - attr[k] = attr[k].toString(); - } - } - } - } - walk(attrs2); - } - function handleBasePlotModule(layoutAttributes2, _module, astr) { - var np = nestedProperty3(layoutAttributes2, astr); - var attrs2 = extendDeepAll2({}, _module.layoutAttributes); - attrs2[IS_SUBPLOT_OBJ] = true; - np.set(attrs2); - } - function insertAttrs(baseAttrs2, newAttrs, astr) { - var np = nestedProperty3(baseAttrs2, astr); - np.set(extendDeepAll2(np.get() || {}, newAttrs)); - } -})(plot_schema); -var plots$2 = { exports: {} }; -var plot_template = {}; -var Lib$1X = libExports; -var plotAttributes$1 = attributes$O; -var TEMPLATEITEMNAME = "templateitemname"; -var templateAttrs = { - name: { - valType: "string", - editType: "none", - description: [ - "When used in a template, named items are created in the output figure", - "in addition to any items the figure already has in this array.", - "You can modify these items in the output figure by making your own", - "item with `templateitemname` matching this `name`", - "alongside your modifications (including `visible: false` or", - "`enabled: false` to hide it).", - "Has no effect outside of a template." - ].join(" ") - } -}; -templateAttrs[TEMPLATEITEMNAME] = { - valType: "string", - editType: "calc", - description: [ - "Used to refer to a named item in this array in the template. Named", - "items from the template will be created even without a matching item", - "in the input figure, but you can modify one by making an item with", - "`templateitemname` matching its `name`, alongside your modifications", - "(including `visible: false` or `enabled: false` to hide it).", - "If there is no template or no matching item, this item will be", - "hidden unless you explicitly show it with `visible: true`." - ].join(" ") -}; -plot_template.templatedArray = function(name2, attrs2) { - attrs2._isLinkedToArray = name2; - attrs2.name = templateAttrs.name; - attrs2[TEMPLATEITEMNAME] = templateAttrs[TEMPLATEITEMNAME]; - return attrs2; -}; -plot_template.traceTemplater = function(dataTemplate) { - var traceCounts = {}; - var traceType, typeTemplates; - for (traceType in dataTemplate) { - typeTemplates = dataTemplate[traceType]; - if (Array.isArray(typeTemplates) && typeTemplates.length) { - traceCounts[traceType] = 0; - } - } - function newTrace(traceIn) { - traceType = Lib$1X.coerce(traceIn, {}, plotAttributes$1, "type"); - var traceOut = { type: traceType, _template: null }; - if (traceType in traceCounts) { - typeTemplates = dataTemplate[traceType]; - var typei = traceCounts[traceType] % typeTemplates.length; - traceCounts[traceType]++; - traceOut._template = typeTemplates[typei]; - } - return traceOut; - } - return { - newTrace - // TODO: function to figure out what's left & what didn't work - }; -}; -plot_template.newContainer = function(container, name2, baseName) { - var template = container._template; - var part = template && (template[name2] || baseName && template[baseName]); - if (!Lib$1X.isPlainObject(part)) part = null; - var out = container[name2] = { _template: part }; - return out; -}; -plot_template.arrayTemplater = function(container, name2, inclusionAttr) { - var template = container._template; - var defaultsTemplate = template && template[arrayDefaultKey(name2)]; - var templateItems = template && template[name2]; - if (!Array.isArray(templateItems) || !templateItems.length) { - templateItems = []; - } - var usedNames = {}; - function newItem(itemIn) { - var out = { name: itemIn.name, _input: itemIn }; - var templateItemName = out[TEMPLATEITEMNAME] = itemIn[TEMPLATEITEMNAME]; - if (!validItemName(templateItemName)) { - out._template = defaultsTemplate; - return out; - } - for (var i = 0; i < templateItems.length; i++) { - var templateItem = templateItems[i]; - if (templateItem.name === templateItemName) { - usedNames[templateItemName] = 1; - out._template = templateItem; - return out; - } - } - out[inclusionAttr] = itemIn[inclusionAttr] || false; - out._template = false; - return out; - } - function defaultItems() { - var out = []; - for (var i = 0; i < templateItems.length; i++) { - var templateItem = templateItems[i]; - var name3 = templateItem.name; - if (validItemName(name3) && !usedNames[name3]) { - var outi = { - _template: templateItem, - name: name3, - _input: { _templateitemname: name3 } - }; - outi[TEMPLATEITEMNAME] = templateItem[TEMPLATEITEMNAME]; - out.push(outi); - usedNames[name3] = 1; - } - } - return out; - } - return { - newItem, - defaultItems - }; -}; -function validItemName(name2) { - return name2 && typeof name2 === "string"; -} -function arrayDefaultKey(name2) { - var lastChar = name2.length - 1; - if (name2.charAt(lastChar) !== "s") { - Lib$1X.warn("bad argument to arrayDefaultKey: " + name2); - } - return name2.substr(0, name2.length - 1) + "defaults"; -} -plot_template.arrayDefaultKey = arrayDefaultKey; -plot_template.arrayEditor = function(parentIn, containerStr, itemOut) { - var lengthIn = (Lib$1X.nestedProperty(parentIn, containerStr).get() || []).length; - var index2 = itemOut._index; - var templateItemName = index2 >= lengthIn && (itemOut._input || {})._templateitemname; - if (templateItemName) index2 = lengthIn; - var itemStr = containerStr + "[" + index2 + "]"; - var update2; - function resetUpdate() { - update2 = {}; - if (templateItemName) { - update2[itemStr] = {}; - update2[itemStr][TEMPLATEITEMNAME] = templateItemName; - } - } - resetUpdate(); - function modifyBase(attr, value2) { - update2[attr] = value2; - } - function modifyItem(attr, value2) { - if (templateItemName) { - Lib$1X.nestedProperty(update2[itemStr], attr).set(value2); - } else { - update2[itemStr + "." + attr] = value2; - } - } - function getUpdateObj() { - var updateOut = update2; - resetUpdate(); - return updateOut; - } - function applyUpdate(attr, value2) { - if (attr) modifyItem(attr, value2); - var updateToApply = getUpdateObj(); - for (var key in updateToApply) { - Lib$1X.nestedProperty(parentIn, key).set(updateToApply[key]); - } - } - return { - modifyBase, - modifyItem, - getUpdateObj, - applyUpdate - }; -}; -var axis_ids = {}; -var counterRegex$2 = regex.counter; -var constants$U = { - idRegex: { - x: counterRegex$2("x", "( domain)?"), - y: counterRegex$2("y", "( domain)?") - }, - attrRegex: counterRegex$2("[xy]axis"), - // axis match regular expression - xAxisMatch: counterRegex$2("xaxis"), - yAxisMatch: counterRegex$2("yaxis"), - // pattern matching axis ids and names - // note that this is more permissive than counterRegex, as - // id2name, name2id, and cleanId accept "x1" etc - AX_ID_PATTERN: /^[xyz][0-9]*( domain)?$/, - AX_NAME_PATTERN: /^[xyz]axis[0-9]*$/, - // and for 2D subplots - SUBPLOT_PATTERN: /^x([0-9]*)y([0-9]*)$/, - HOUR_PATTERN: "hour", - WEEKDAY_PATTERN: "day of week", - // pixels to move mouse before you stop clamping to starting point - MINDRAG: 8, - // smallest dimension allowed for a zoombox - MINZOOM: 20, - // width of axis drag regions - DRAGGERSIZE: 20, - // delay before a redraw (relayout) after smooth panning and zooming - REDRAWDELAY: 50, - // last resort axis ranges for x and y axes if we have no data - DFLTRANGEX: [-1, 6], - DFLTRANGEY: [-1, 4], - // Layers to keep trace types in the right order - // N.B. each 'unique' plot method must have its own layer - traceLayerClasses: [ - "imagelayer", - "heatmaplayer", - "contourcarpetlayer", - "contourlayer", - "funnellayer", - "waterfalllayer", - "barlayer", - "carpetlayer", - "violinlayer", - "boxlayer", - "ohlclayer", - "scattercarpetlayer", - "scatterlayer" - ], - clipOnAxisFalseQuery: [ - ".scatterlayer", - ".barlayer", - ".funnellayer", - ".waterfalllayer" - ], - layerValue2layerClass: { - "above traces": "above", - "below traces": "below" - }, - zindexSeparator: "z" - // used for zindex of cartesian subplots e.g. xy, xyz2, xyz3, etc. -}; -(function(exports2) { - var Registry2 = registry; - var constants2 = constants$U; - exports2.id2name = function id2name2(id) { - if (typeof id !== "string" || !id.match(constants2.AX_ID_PATTERN)) return; - var axNum = id.split(" ")[0].substr(1); - if (axNum === "1") axNum = ""; - return id.charAt(0) + "axis" + axNum; - }; - exports2.name2id = function name2id(name2) { - if (!name2.match(constants2.AX_NAME_PATTERN)) return; - var axNum = name2.substr(5); - if (axNum === "1") axNum = ""; - return name2.charAt(0) + axNum; - }; - exports2.cleanId = function cleanId(id, axLetter, domainId) { - var domainTest = /( domain)$/.test(id); - if (typeof id !== "string" || !id.match(constants2.AX_ID_PATTERN)) return; - if (axLetter && id.charAt(0) !== axLetter) return; - if (domainTest && !domainId) return; - var axNum = id.split(" ")[0].substr(1).replace(/^0+/, ""); - if (axNum === "1") axNum = ""; - return id.charAt(0) + axNum + (domainTest && domainId ? " domain" : ""); - }; - exports2.list = function(gd, axLetter, only2d) { - var fullLayout = gd._fullLayout; - if (!fullLayout) return []; - var idList = exports2.listIds(gd, axLetter); - var out = new Array(idList.length); - var i; - for (i = 0; i < idList.length; i++) { - var idi = idList[i]; - out[i] = fullLayout[idi.charAt(0) + "axis" + idi.substr(1)]; - } - if (!only2d) { - var sceneIds3D = fullLayout._subplots.gl3d || []; - for (i = 0; i < sceneIds3D.length; i++) { - var scene = fullLayout[sceneIds3D[i]]; - if (axLetter) out.push(scene[axLetter + "axis"]); - else out.push(scene.xaxis, scene.yaxis, scene.zaxis); - } - } - return out; - }; - exports2.listIds = function(gd, axLetter) { - var fullLayout = gd._fullLayout; - if (!fullLayout) return []; - var subplotLists = fullLayout._subplots; - if (axLetter) return subplotLists[axLetter + "axis"]; - return subplotLists.xaxis.concat(subplotLists.yaxis); - }; - exports2.getFromId = function(gd, id, type) { - var fullLayout = gd._fullLayout; - id = id === void 0 || typeof id !== "string" ? id : id.replace(" domain", ""); - if (type === "x") id = id.replace(/y[0-9]*/, ""); - else if (type === "y") id = id.replace(/x[0-9]*/, ""); - return fullLayout[exports2.id2name(id)]; - }; - exports2.getFromTrace = function(gd, fullTrace, type) { - var fullLayout = gd._fullLayout; - var ax = null; - if (Registry2.traceIs(fullTrace, "gl3d")) { - var scene = fullTrace.scene; - if (scene.substr(0, 5) === "scene") { - ax = fullLayout[scene][type + "axis"]; - } - } else { - ax = exports2.getFromId(gd, fullTrace[type + "axis"] || type); - } - return ax; - }; - exports2.idSort = function(id1, id2) { - var letter1 = id1.charAt(0); - var letter2 = id2.charAt(0); - if (letter1 !== letter2) return letter1 > letter2 ? 1 : -1; - return +(id1.substr(1) || 1) - +(id2.substr(1) || 1); - }; - exports2.ref2id = function(ar) { - return /^[xyz]/.test(ar) ? ar.split(" ")[0] : false; - }; - function isFound(axId, list) { - if (list && list.length) { - for (var i = 0; i < list.length; i++) { - if (list[i][axId]) return true; - } - } - return false; - } - exports2.isLinked = function(fullLayout, axId) { - return isFound(axId, fullLayout._axisMatchGroups) || isFound(axId, fullLayout._axisConstraintGroups); - }; -})(axis_ids); -function clearOutlineControllers$3(gd) { - var zoomLayer = gd._fullLayout._zoomlayer; - if (zoomLayer) { - zoomLayer.selectAll(".outline-controllers").remove(); - } -} -function clearOutline$4(gd) { - var zoomLayer = gd._fullLayout._zoomlayer; - if (zoomLayer) { - zoomLayer.selectAll(".select-outline").remove(); - } - gd._fullLayout._outlining = false; -} -var handle_outline = { - clearOutlineControllers: clearOutlineControllers$3, - clearOutline: clearOutline$4 -}; -var layout_attributes$5 = { - scattermode: { - valType: "enumerated", - values: ["group", "overlay"], - dflt: "overlay", - editType: "calc", - description: [ - "Determines how scatter points at the same location coordinate", - "are displayed on the graph.", - "With *group*, the scatter points are plotted next to one another", - "centered around the shared location.", - "With *overlay*, the scatter points are plotted over one another,", - "you might need to reduce *opacity* to see multiple scatter points." - ].join(" ") - }, - scattergap: { - valType: "number", - min: 0, - max: 1, - editType: "calc", - description: [ - "Sets the gap (in plot fraction) between scatter points of", - "adjacent location coordinates.", - "Defaults to `bargap`." - ].join(" ") - } -}; -var get_data = {}; -var Registry$N = registry; -var SUBPLOT_PATTERN = constants$U.SUBPLOT_PATTERN; -get_data.getSubplotCalcData = function(calcData, type, subplotId) { - var basePlotModule = Registry$N.subplotsRegistry[type]; - if (!basePlotModule) return []; - var attr = basePlotModule.attr; - var subplotCalcData = []; - for (var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; - if (trace[attr] === subplotId) subplotCalcData.push(calcTrace); - } - return subplotCalcData; -}; -get_data.getModuleCalcData = function(calcdata, arg1, arg2) { - var moduleCalcData = []; - var remainingCalcData = []; - var plotMethod; - if (typeof arg1 === "string") { - plotMethod = Registry$N.getModule(arg1).plot; - } else if (typeof arg1 === "function") { - plotMethod = arg1; - } else { - plotMethod = arg1.plot; - } - if (!plotMethod) { - return [moduleCalcData, calcdata]; - } - var zorder = arg2; - for (var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - var filterByZ = trace.zorder !== void 0; - if (trace.visible !== true || trace._length === 0) continue; - if (trace._module && trace._module.plot === plotMethod && (!filterByZ || trace.zorder === zorder)) { - moduleCalcData.push(cd); - } else { - remainingCalcData.push(cd); - } - } - return [moduleCalcData, remainingCalcData]; -}; -get_data.getSubplotData = function getSubplotData(data, type, subplotId) { - if (!Registry$N.subplotsRegistry[type]) return []; - var attr = Registry$N.subplotsRegistry[type].attr; - var subplotData = []; - var trace, subplotX, subplotY; - if (type === "gl2d") { - var spmatch = subplotId.match(SUBPLOT_PATTERN); - subplotX = "x" + spmatch[1]; - subplotY = "y" + spmatch[2]; - } - for (var i = 0; i < data.length; i++) { - trace = data[i]; - if (type === "gl2d" && Registry$N.traceIs(trace, "gl2d")) { - if (trace[attr[0]] === subplotX && trace[attr[1]] === subplotY) { - subplotData.push(trace); - } - } else { - if (trace[attr] === subplotId) subplotData.push(trace); - } - } - return subplotData; -}; -var command = {}; -var hasRequiredCommand; -function requireCommand() { - if (hasRequiredCommand) return command; - hasRequiredCommand = 1; - (function(exports2) { - var Registry2 = registry; - var Lib2 = libExports; - exports2.manageCommandObserver = function(gd, container, commandList, onchange) { - var ret = {}; - var enabled = true; - if (container && container._commandObserver) { - ret = container._commandObserver; - } - if (!ret.cache) { - ret.cache = {}; - } - ret.lookupTable = {}; - var binding = exports2.hasSimpleAPICommandBindings(gd, commandList, ret.lookupTable); - if (container && container._commandObserver) { - if (!binding) { - if (container._commandObserver.remove) { - container._commandObserver.remove(); - container._commandObserver = null; - return ret; - } - } else { - return ret; - } - } - if (binding) { - bindingValueHasChanged(gd, binding, ret.cache); - ret.check = function check() { - if (!enabled) return; - var update2 = bindingValueHasChanged(gd, binding, ret.cache); - if (update2.changed && onchange) { - if (ret.lookupTable[update2.value] !== void 0) { - ret.disable(); - Promise.resolve(onchange({ - value: update2.value, - type: binding.type, - prop: binding.prop, - traces: binding.traces, - index: ret.lookupTable[update2.value] - })).then(ret.enable, ret.enable); - } - } - return update2.changed; - }; - var checkEvents = [ - "plotly_relayout", - "plotly_redraw", - "plotly_restyle", - "plotly_update", - "plotly_animatingframe", - "plotly_afterplot" - ]; - for (var i = 0; i < checkEvents.length; i++) { - gd._internalOn(checkEvents[i], ret.check); - } - ret.remove = function() { - for (var i2 = 0; i2 < checkEvents.length; i2++) { - gd._removeInternalListener(checkEvents[i2], ret.check); - } - }; - } else { - Lib2.log("Unable to automatically bind plot updates to API command"); - ret.lookupTable = {}; - ret.remove = function() { - }; - } - ret.disable = function disable2() { - enabled = false; - }; - ret.enable = function enable2() { - enabled = true; - }; - if (container) { - container._commandObserver = ret; - } - return ret; - }; - exports2.hasSimpleAPICommandBindings = function(gd, commandList, bindingsByValue) { - var i; - var n = commandList.length; - var refBinding; - for (i = 0; i < n; i++) { - var binding; - var command2 = commandList[i]; - var method = command2.method; - var args = command2.args; - if (!Array.isArray(args)) args = []; - if (!method) { - return false; - } - var bindings = exports2.computeAPICommandBindings(gd, method, args); - if (bindings.length !== 1) { - return false; - } - if (!refBinding) { - refBinding = bindings[0]; - if (Array.isArray(refBinding.traces)) { - refBinding.traces.sort(); - } - } else { - binding = bindings[0]; - if (binding.type !== refBinding.type) { - return false; - } - if (binding.prop !== refBinding.prop) { - return false; - } - if (Array.isArray(refBinding.traces)) { - if (Array.isArray(binding.traces)) { - binding.traces.sort(); - for (var j = 0; j < refBinding.traces.length; j++) { - if (refBinding.traces[j] !== binding.traces[j]) { - return false; - } - } - } else { - return false; - } - } else { - if (binding.prop !== refBinding.prop) { - return false; - } - } - } - binding = bindings[0]; - var value2 = binding.value; - if (Array.isArray(value2)) { - if (value2.length === 1) { - value2 = value2[0]; - } else { - return false; - } - } - if (bindingsByValue) { - bindingsByValue[value2] = i; - } - } - return refBinding; - }; - function bindingValueHasChanged(gd, binding, cache2) { - var container, value2, obj; - var changed = false; - if (binding.type === "data") { - container = gd._fullData[binding.traces !== null ? binding.traces[0] : 0]; - } else if (binding.type === "layout") { - container = gd._fullLayout; - } else { - return false; - } - value2 = Lib2.nestedProperty(container, binding.prop).get(); - obj = cache2[binding.type] = cache2[binding.type] || {}; - if (obj.hasOwnProperty(binding.prop)) { - if (obj[binding.prop] !== value2) { - changed = true; - } - } - obj[binding.prop] = value2; - return { - changed, - value: value2 - }; - } - exports2.executeAPICommand = function(gd, method, args) { - if (method === "skip") return Promise.resolve(); - var _method = Registry2.apiMethodRegistry[method]; - var allArgs = [gd]; - if (!Array.isArray(args)) args = []; - for (var i = 0; i < args.length; i++) { - allArgs.push(args[i]); - } - return _method.apply(null, allArgs).catch(function(err) { - Lib2.warn("API call to Plotly." + method + " rejected.", err); - return Promise.reject(err); - }); - }; - exports2.computeAPICommandBindings = function(gd, method, args) { - var bindings; - if (!Array.isArray(args)) args = []; - switch (method) { - case "restyle": - bindings = computeDataBindings(gd, args); - break; - case "relayout": - bindings = computeLayoutBindings(gd, args); - break; - case "update": - bindings = computeDataBindings(gd, [args[0], args[2]]).concat(computeLayoutBindings(gd, [args[1]])); - break; - case "animate": - bindings = computeAnimateBindings(gd, args); - break; - default: - bindings = []; - } - return bindings; - }; - function computeAnimateBindings(gd, args) { - if (Array.isArray(args[0]) && args[0].length === 1 && ["string", "number"].indexOf(typeof args[0][0]) !== -1) { - return [{ type: "layout", prop: "_currentFrame", value: args[0][0].toString() }]; - } else { - return []; - } - } - function computeLayoutBindings(gd, args) { - var bindings = []; - var astr = args[0]; - var aobj = {}; - if (typeof astr === "string") { - aobj[astr] = args[1]; - } else if (Lib2.isPlainObject(astr)) { - aobj = astr; - } else { - return bindings; - } - crawl2(aobj, function(path, attrName, attr) { - bindings.push({ type: "layout", prop: path, value: attr }); - }, "", 0); - return bindings; - } - function computeDataBindings(gd, args) { - var traces, astr, val, aobj; - var bindings = []; - astr = args[0]; - val = args[1]; - traces = args[2]; - aobj = {}; - if (typeof astr === "string") { - aobj[astr] = val; - } else if (Lib2.isPlainObject(astr)) { - aobj = astr; - if (traces === void 0) { - traces = val; - } - } else { - return bindings; - } - if (traces === void 0) { - traces = null; - } - crawl2(aobj, function(path, attrName, _attr) { - var thisTraces; - var attr; - if (Array.isArray(_attr)) { - attr = _attr.slice(); - var nAttr = Math.min(attr.length, gd.data.length); - if (traces) { - nAttr = Math.min(nAttr, traces.length); - } - thisTraces = []; - for (var j = 0; j < nAttr; j++) { - thisTraces[j] = traces ? traces[j] : j; - } - } else { - attr = _attr; - thisTraces = traces ? traces.slice() : null; - } - if (thisTraces === null) { - if (Array.isArray(attr)) { - attr = attr[0]; - } - } else if (Array.isArray(thisTraces)) { - if (!Array.isArray(attr)) { - var tmp = attr; - attr = []; - for (var i = 0; i < thisTraces.length; i++) { - attr[i] = tmp; - } - } - attr.length = Math.min(thisTraces.length, attr.length); - } - bindings.push({ - type: "data", - prop: path, - traces: thisTraces, - value: attr - }); - }, "", 0); - return bindings; - } - function crawl2(attrs2, callback, path, depth) { - Object.keys(attrs2).forEach(function(attrName) { - var attr = attrs2[attrName]; - if (attrName[0] === "_") return; - var thisPath = path + (depth > 0 ? "." : "") + attrName; - if (Lib2.isPlainObject(attr)) { - crawl2(attr, callback, thisPath, depth + 1); - } else { - callback(thisPath, attrName, attr); - } - }); - } - })(command); - return command; -} -var d3$B = d3Exports; -var timeFormatLocale = require$$1$1.timeFormatLocale; -var formatLocale = require$$2$2.formatLocale; -var isNumeric$u = fastIsnumeric; -var b64encode = require$$4$1; -var Registry$M = registry; -var PlotSchema$2 = plot_schema; -var Template$9 = plot_template; -var Lib$1W = libExports; -var Color$L = colorExports; -var BADNUM$a = numerical.BADNUM; -var axisIDs$1 = axis_ids; -var clearOutline$3 = handle_outline.clearOutline; -var scatterAttrs$3 = layout_attributes$5; -var animationAttrs$1 = animation_attributes; -var frameAttrs = frame_attributes; -var getModuleCalcData$1 = get_data.getModuleCalcData; -var relinkPrivateKeys2 = Lib$1W.relinkPrivateKeys; -var _$2 = Lib$1W._; -var plots$1 = plots$2.exports = {}; -Lib$1W.extendFlat(plots$1, Registry$M); -plots$1.attributes = attributes$O; -plots$1.attributes.type.values = plots$1.allTypes; -plots$1.fontAttrs = font_attributes; -plots$1.layoutAttributes = layout_attributes$6; -var transformsRegistry = plots$1.transformsRegistry; -var commandModule = requireCommand(); -plots$1.executeAPICommand = commandModule.executeAPICommand; -plots$1.computeAPICommandBindings = commandModule.computeAPICommandBindings; -plots$1.manageCommandObserver = commandModule.manageCommandObserver; -plots$1.hasSimpleAPICommandBindings = commandModule.hasSimpleAPICommandBindings; -plots$1.redrawText = function(gd) { - gd = Lib$1W.getGraphDiv(gd); - return new Promise(function(resolve) { - setTimeout(function() { - if (!gd._fullLayout) return; - Registry$M.getComponentMethod("annotations", "draw")(gd); - Registry$M.getComponentMethod("legend", "draw")(gd); - Registry$M.getComponentMethod("colorbar", "draw")(gd); - resolve(plots$1.previousPromises(gd)); - }, 300); - }); -}; -plots$1.resize = function(gd) { - gd = Lib$1W.getGraphDiv(gd); - var resolveLastResize; - var p = new Promise(function(resolve, reject) { - if (!gd || Lib$1W.isHidden(gd)) { - reject(new Error("Resize must be passed a displayed plot div element.")); - } - if (gd._redrawTimer) clearTimeout(gd._redrawTimer); - if (gd._resolveResize) resolveLastResize = gd._resolveResize; - gd._resolveResize = resolve; - gd._redrawTimer = setTimeout(function() { - if (!gd.layout || gd.layout.width && gd.layout.height || Lib$1W.isHidden(gd)) { - resolve(gd); - return; - } - delete gd.layout.width; - delete gd.layout.height; - var oldchanged = gd.changed; - gd.autoplay = true; - Registry$M.call("relayout", gd, { autosize: true }).then(function() { - gd.changed = oldchanged; - if (gd._resolveResize === resolve) { - delete gd._resolveResize; - resolve(gd); - } - }); - }, 100); - }); - if (resolveLastResize) resolveLastResize(p); - return p; -}; -plots$1.previousPromises = function(gd) { - if ((gd._promises || []).length) { - return Promise.all(gd._promises).then(function() { - gd._promises = []; - }); - } -}; -plots$1.addLinks = function(gd) { - if (!gd._context.showLink && !gd._context.showSources) return; - var fullLayout = gd._fullLayout; - var linkContainer = Lib$1W.ensureSingle(fullLayout._paper, "text", "js-plot-link-container", function(s) { - s.style({ - "font-family": '"Open Sans", Arial, sans-serif', - "font-size": "12px", - fill: Color$L.defaultLine, - "pointer-events": "all" - }).each(function() { - var links = d3$B.select(this); - links.append("tspan").classed("js-link-to-tool", true); - links.append("tspan").classed("js-link-spacer", true); - links.append("tspan").classed("js-sourcelinks", true); - }); - }); - var text = linkContainer.node(); - var attrs2 = { y: fullLayout._paper.attr("height") - 9 }; - if (document.body.contains(text) && text.getComputedTextLength() >= fullLayout.width - 20) { - attrs2["text-anchor"] = "start"; - attrs2.x = 5; - } else { - attrs2["text-anchor"] = "end"; - attrs2.x = fullLayout._paper.attr("width") - 7; - } - linkContainer.attr(attrs2); - var toolspan = linkContainer.select(".js-link-to-tool"); - var spacespan = linkContainer.select(".js-link-spacer"); - var sourcespan = linkContainer.select(".js-sourcelinks"); - if (gd._context.showSources) gd._context.showSources(gd); - if (gd._context.showLink) positionPlayWithData(gd, toolspan); - spacespan.text(toolspan.text() && sourcespan.text() ? " - " : ""); -}; -function positionPlayWithData(gd, container) { - container.text(""); - var link = container.append("a").attr({ - "xlink:xlink:href": "#", - class: "link--impt link--embedview", - "font-weight": "bold" - }).text(gd._context.linkText + " " + String.fromCharCode(187)); - if (gd._context.sendData) { - link.on("click", function() { - plots$1.sendDataToCloud(gd); - }); - } else { - var path = window.location.pathname.split("/"); - var query = window.location.search; - link.attr({ - "xlink:xlink:show": "new", - "xlink:xlink:href": "/" + path[2].split(".")[0] + "/" + path[1] + query - }); - } -} -plots$1.sendDataToCloud = function(gd) { - var baseUrl = (window.PLOTLYENV || {}).BASE_URL || gd._context.plotlyServerURL; - if (!baseUrl) return; - gd.emit("plotly_beforeexport"); - var hiddenformDiv = d3$B.select(gd).append("div").attr("id", "hiddenform").style("display", "none"); - var hiddenform = hiddenformDiv.append("form").attr({ - action: baseUrl + "/external", - method: "post", - target: "_blank" - }); - var hiddenformInput = hiddenform.append("input").attr({ - type: "text", - name: "data" - }); - hiddenformInput.node().value = plots$1.graphJson(gd, false, "keepdata"); - hiddenform.node().submit(); - hiddenformDiv.remove(); - gd.emit("plotly_afterexport"); - return false; -}; -var d3FormatKeys = [ - "days", - "shortDays", - "months", - "shortMonths", - "periods", - "dateTime", - "date", - "time", - "decimal", - "thousands", - "grouping", - "currency" -]; -var extraFormatKeys = [ - "year", - "month", - "dayMonth", - "dayMonthYear" -]; -plots$1.supplyDefaults = function(gd, opts) { - var skipUpdateCalc = opts && opts.skipUpdateCalc; - var oldFullLayout = gd._fullLayout || {}; - if (oldFullLayout._skipDefaults) { - delete oldFullLayout._skipDefaults; - return; - } - var newFullLayout = gd._fullLayout = {}; - var newLayout = gd.layout || {}; - var oldFullData = gd._fullData || []; - var newFullData = gd._fullData = []; - var newData = gd.data || []; - var oldCalcdata = gd.calcdata || []; - var context2 = gd._context || {}; - var i; - if (!gd._transitionData) plots$1.createTransitionData(gd); - newFullLayout._dfltTitle = { - plot: _$2(gd, "Click to enter Plot title"), - subtitle: _$2(gd, "Click to enter Plot subtitle"), - x: _$2(gd, "Click to enter X axis title"), - y: _$2(gd, "Click to enter Y axis title"), - colorbar: _$2(gd, "Click to enter Colorscale title"), - annotation: _$2(gd, "new text") - }; - newFullLayout._traceWord = _$2(gd, "trace"); - var formatObj = getFormatObj(gd, d3FormatKeys); - newFullLayout._mapboxAccessToken = context2.mapboxAccessToken; - if (oldFullLayout._initialAutoSizeIsDone) { - var oldWidth = oldFullLayout.width; - var oldHeight = oldFullLayout.height; - plots$1.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj); - if (!newLayout.width) newFullLayout.width = oldWidth; - if (!newLayout.height) newFullLayout.height = oldHeight; - plots$1.sanitizeMargins(newFullLayout); - } else { - plots$1.supplyLayoutGlobalDefaults(newLayout, newFullLayout, formatObj); - var missingWidthOrHeight = !newLayout.width || !newLayout.height; - var autosize = newFullLayout.autosize; - var autosizable = context2.autosizable; - var initialAutoSize = missingWidthOrHeight && (autosize || autosizable); - if (initialAutoSize) plots$1.plotAutoSize(gd, newLayout, newFullLayout); - else if (missingWidthOrHeight) plots$1.sanitizeMargins(newFullLayout); - if (!autosize && missingWidthOrHeight) { - newLayout.width = newFullLayout.width; - newLayout.height = newFullLayout.height; - } - } - newFullLayout._d3locale = getFormatter(formatObj, newFullLayout.separators); - newFullLayout._extraFormat = getFormatObj(gd, extraFormatKeys); - newFullLayout._initialAutoSizeIsDone = true; - newFullLayout._dataLength = newData.length; - newFullLayout._modules = []; - newFullLayout._visibleModules = []; - newFullLayout._basePlotModules = []; - var subplots = newFullLayout._subplots = emptySubplotLists(); - var splomAxes = newFullLayout._splomAxes = { x: {}, y: {} }; - var splomSubplots = newFullLayout._splomSubplots = {}; - newFullLayout._splomGridDflt = {}; - newFullLayout._scatterStackOpts = {}; - newFullLayout._firstScatter = {}; - newFullLayout._alignmentOpts = {}; - newFullLayout._colorAxes = {}; - newFullLayout._requestRangeslider = {}; - newFullLayout._traceUids = getTraceUids(oldFullData, newData); - newFullLayout._globalTransforms = (gd._context || {}).globalTransforms; - plots$1.supplyDataDefaults(newData, newFullData, newLayout, newFullLayout); - var splomXa = Object.keys(splomAxes.x); - var splomYa = Object.keys(splomAxes.y); - if (splomXa.length > 1 && splomYa.length > 1) { - Registry$M.getComponentMethod("grid", "sizeDefaults")(newLayout, newFullLayout); - for (i = 0; i < splomXa.length; i++) { - Lib$1W.pushUnique(subplots.xaxis, splomXa[i]); - } - for (i = 0; i < splomYa.length; i++) { - Lib$1W.pushUnique(subplots.yaxis, splomYa[i]); - } - for (var k in splomSubplots) { - Lib$1W.pushUnique(subplots.cartesian, k); - } - } - newFullLayout._has = plots$1._hasPlotType.bind(newFullLayout); - if (oldFullData.length === newFullData.length) { - for (i = 0; i < newFullData.length; i++) { - relinkPrivateKeys2(newFullData[i], oldFullData[i]); - } - } - plots$1.supplyLayoutModuleDefaults(newLayout, newFullLayout, newFullData, gd._transitionData); - var _modules = newFullLayout._visibleModules; - var crossTraceDefaultsFuncs = []; - for (i = 0; i < _modules.length; i++) { - var funci = _modules[i].crossTraceDefaults; - if (funci) Lib$1W.pushUnique(crossTraceDefaultsFuncs, funci); - } - for (i = 0; i < crossTraceDefaultsFuncs.length; i++) { - crossTraceDefaultsFuncs[i](newFullData, newFullLayout); - } - newFullLayout._hasOnlyLargeSploms = newFullLayout._basePlotModules.length === 1 && newFullLayout._basePlotModules[0].name === "splom" && splomXa.length > 15 && splomYa.length > 15 && newFullLayout.shapes.length === 0 && newFullLayout.images.length === 0; - plots$1.linkSubplots(newFullData, newFullLayout, oldFullData, oldFullLayout); - plots$1.cleanPlot(newFullData, newFullLayout, oldFullData, oldFullLayout); - var hadGL2D = !!(oldFullLayout._has && oldFullLayout._has("gl2d")); - var hasGL2D = !!(newFullLayout._has && newFullLayout._has("gl2d")); - var hadCartesian = !!(oldFullLayout._has && oldFullLayout._has("cartesian")); - var hasCartesian = !!(newFullLayout._has && newFullLayout._has("cartesian")); - var hadBgLayer = hadCartesian || hadGL2D; - var hasBgLayer = hasCartesian || hasGL2D; - if (hadBgLayer && !hasBgLayer) { - oldFullLayout._bgLayer.remove(); - } else if (hasBgLayer && !hadBgLayer) { - newFullLayout._shouldCreateBgLayer = true; - } - if (oldFullLayout._zoomlayer && !gd._dragging) { - clearOutline$3({ - // mock old gd - _fullLayout: oldFullLayout - }); - } - fillMetaTextHelpers(newFullData, newFullLayout); - relinkPrivateKeys2(newFullLayout, oldFullLayout); - Registry$M.getComponentMethod("colorscale", "crossTraceDefaults")(newFullData, newFullLayout); - if (!newFullLayout._preGUI) newFullLayout._preGUI = {}; - if (!newFullLayout._tracePreGUI) newFullLayout._tracePreGUI = {}; - var tracePreGUI = newFullLayout._tracePreGUI; - var uids = {}; - var uid; - for (uid in tracePreGUI) uids[uid] = "old"; - for (i = 0; i < newFullData.length; i++) { - uid = newFullData[i]._fullInput.uid; - if (!uids[uid]) tracePreGUI[uid] = {}; - uids[uid] = "new"; - } - for (uid in uids) { - if (uids[uid] === "old") delete tracePreGUI[uid]; - } - initMargins(newFullLayout); - Registry$M.getComponentMethod("rangeslider", "makeData")(newFullLayout); - if (!skipUpdateCalc && oldCalcdata.length === newFullData.length) { - plots$1.supplyDefaultsUpdateCalc(oldCalcdata, newFullData); - } -}; -plots$1.supplyDefaultsUpdateCalc = function(oldCalcdata, newFullData) { - for (var i = 0; i < newFullData.length; i++) { - var newTrace = newFullData[i]; - var cd0 = (oldCalcdata[i] || [])[0]; - if (cd0 && cd0.trace) { - var oldTrace = cd0.trace; - if (oldTrace._hasCalcTransform) { - var arrayAttrs = oldTrace._arrayAttrs; - var j, astr, oldArrayVal; - for (j = 0; j < arrayAttrs.length; j++) { - astr = arrayAttrs[j]; - oldArrayVal = Lib$1W.nestedProperty(oldTrace, astr).get().slice(); - Lib$1W.nestedProperty(newTrace, astr).set(oldArrayVal); - } - } - cd0.trace = newTrace; - } - } -}; -function getTraceUids(oldFullData, newData) { - var len = newData.length; - var oldFullInput = []; - var i, prevFullInput; - for (i = 0; i < oldFullData.length; i++) { - var thisFullInput = oldFullData[i]._fullInput; - if (thisFullInput !== prevFullInput) oldFullInput.push(thisFullInput); - prevFullInput = thisFullInput; - } - var oldLen = oldFullInput.length; - var out = new Array(len); - var seenUids = {}; - function setUid(uid, i2) { - out[i2] = uid; - seenUids[uid] = 1; - } - function tryUid(uid, i2) { - if (uid && typeof uid === "string" && !seenUids[uid]) { - setUid(uid, i2); - return true; - } - } - for (i = 0; i < len; i++) { - var newUid = newData[i].uid; - if (typeof newUid === "number") newUid = String(newUid); - if (tryUid(newUid, i)) continue; - if (i < oldLen && tryUid(oldFullInput[i].uid, i)) continue; - setUid(Lib$1W.randstr(seenUids), i); - } - return out; -} -function emptySubplotLists() { - var collectableSubplotTypes = Registry$M.collectableSubplotTypes; - var out = {}; - var i, j; - if (!collectableSubplotTypes) { - collectableSubplotTypes = []; - var subplotsRegistry = Registry$M.subplotsRegistry; - for (var subplotType in subplotsRegistry) { - var subplotModule = subplotsRegistry[subplotType]; - var subplotAttr = subplotModule.attr; - if (subplotAttr) { - collectableSubplotTypes.push(subplotType); - if (Array.isArray(subplotAttr)) { - for (j = 0; j < subplotAttr.length; j++) { - Lib$1W.pushUnique(collectableSubplotTypes, subplotAttr[j]); - } - } - } - } - } - for (i = 0; i < collectableSubplotTypes.length; i++) { - out[collectableSubplotTypes[i]] = []; - } - return out; -} -function getFormatObj(gd, formatKeys) { - var locale2 = gd._context.locale; - if (!locale2) locale2 = "en-US"; - var formatDone = false; - var formatObj = {}; - function includeFormat(newFormat) { - var formatFinished = true; - for (var i2 = 0; i2 < formatKeys.length; i2++) { - var formatKey = formatKeys[i2]; - if (!formatObj[formatKey]) { - if (newFormat[formatKey]) { - formatObj[formatKey] = newFormat[formatKey]; - } else formatFinished = false; - } - } - if (formatFinished) formatDone = true; - } - for (var i = 0; i < 2; i++) { - var locales = gd._context.locales; - for (var j = 0; j < 2; j++) { - var formatj = (locales[locale2] || {}).format; - if (formatj) { - includeFormat(formatj); - if (formatDone) break; - } - locales = Registry$M.localeRegistry; - } - var baseLocale = locale2.split("-")[0]; - if (formatDone || baseLocale === locale2) break; - locale2 = baseLocale; - } - if (!formatDone) includeFormat(Registry$M.localeRegistry.en.format); - return formatObj; -} -function getFormatter(formatObj, separators) { - formatObj.decimal = separators.charAt(0); - formatObj.thousands = separators.charAt(1); - return { - numberFormat: function(formatStr) { - try { - formatStr = formatLocale(formatObj).format( - Lib$1W.adjustFormat(formatStr) - ); - } catch (e) { - Lib$1W.warnBadFormat(formatStr); - return Lib$1W.noFormat; - } - return formatStr; - }, - timeFormat: timeFormatLocale(formatObj).utcFormat - }; -} -function fillMetaTextHelpers(newFullData, newFullLayout) { - var _meta; - var meta4data = []; - if (newFullLayout.meta) { - _meta = newFullLayout._meta = { - meta: newFullLayout.meta, - layout: { meta: newFullLayout.meta } - }; - } - for (var i = 0; i < newFullData.length; i++) { - var trace = newFullData[i]; - if (trace.meta) { - meta4data[trace.index] = trace._meta = { meta: trace.meta }; - } else if (newFullLayout.meta) { - trace._meta = { meta: newFullLayout.meta }; - } - if (newFullLayout.meta) { - trace._meta.layout = { meta: newFullLayout.meta }; - } - } - if (meta4data.length) { - if (!_meta) { - _meta = newFullLayout._meta = {}; - } - _meta.data = meta4data; - } -} -plots$1.createTransitionData = function(gd) { - if (!gd._transitionData) { - gd._transitionData = {}; - } - if (!gd._transitionData._frames) { - gd._transitionData._frames = []; - } - if (!gd._transitionData._frameHash) { - gd._transitionData._frameHash = {}; - } - if (!gd._transitionData._counter) { - gd._transitionData._counter = 0; - } - if (!gd._transitionData._interruptCallbacks) { - gd._transitionData._interruptCallbacks = []; - } -}; -plots$1._hasPlotType = function(category2) { - var i; - var basePlotModules = this._basePlotModules || []; - for (i = 0; i < basePlotModules.length; i++) { - if (basePlotModules[i].name === category2) return true; - } - var modules2 = this._modules || []; - for (i = 0; i < modules2.length; i++) { - var name2 = modules2[i].name; - if (name2 === category2) return true; - var _module = Registry$M.modules[name2]; - if (_module && _module.categories[category2]) return true; - } - return false; -}; -plots$1.cleanPlot = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var i, j; - var basePlotModules = oldFullLayout._basePlotModules || []; - for (i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - if (_module.clean) { - _module.clean(newFullData, newFullLayout, oldFullData, oldFullLayout); - } - } - var hadGl = oldFullLayout._has && oldFullLayout._has("gl"); - var hasGl = newFullLayout._has && newFullLayout._has("gl"); - if (hadGl && !hasGl) { - if (oldFullLayout._glcontainer !== void 0) { - oldFullLayout._glcontainer.selectAll(".gl-canvas").remove(); - oldFullLayout._glcontainer.selectAll(".no-webgl").remove(); - oldFullLayout._glcanvas = null; - } - } - var hasInfoLayer = !!oldFullLayout._infolayer; - oldLoop: - for (i = 0; i < oldFullData.length; i++) { - var oldTrace = oldFullData[i]; - var oldUid = oldTrace.uid; - for (j = 0; j < newFullData.length; j++) { - var newTrace = newFullData[j]; - if (oldUid === newTrace.uid) continue oldLoop; - } - if (hasInfoLayer) { - oldFullLayout._infolayer.select(".cb" + oldUid).remove(); - } - } -}; -plots$1.linkSubplots = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var i, j; - var oldSubplots = oldFullLayout._plots || {}; - var newSubplots = newFullLayout._plots = {}; - var newSubplotList = newFullLayout._subplots; - var mockGd = { - _fullData: newFullData, - _fullLayout: newFullLayout - }; - var ids = newSubplotList.cartesian.concat(newSubplotList.gl2d || []); - for (i = 0; i < ids.length; i++) { - var id = ids[i]; - var oldSubplot = oldSubplots[id]; - var xaxis = axisIDs$1.getFromId(mockGd, id, "x"); - var yaxis = axisIDs$1.getFromId(mockGd, id, "y"); - var plotinfo; - if (oldSubplot) { - plotinfo = newSubplots[id] = oldSubplot; - } else { - plotinfo = newSubplots[id] = {}; - plotinfo.id = id; - } - xaxis._counterAxes.push(yaxis._id); - yaxis._counterAxes.push(xaxis._id); - xaxis._subplotsWith.push(id); - yaxis._subplotsWith.push(id); - plotinfo.xaxis = xaxis; - plotinfo.yaxis = yaxis; - plotinfo._hasClipOnAxisFalse = false; - for (j = 0; j < newFullData.length; j++) { - var trace = newFullData[j]; - if (trace.xaxis === plotinfo.xaxis._id && trace.yaxis === plotinfo.yaxis._id && trace.cliponaxis === false) { - plotinfo._hasClipOnAxisFalse = true; - break; - } - } - } - var axList = axisIDs$1.list(mockGd, null, true); - var ax; - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - var mainAx = null; - if (ax.overlaying) { - mainAx = axisIDs$1.getFromId(mockGd, ax.overlaying); - if (mainAx && mainAx.overlaying) { - ax.overlaying = false; - mainAx = null; - } - } - ax._mainAxis = mainAx || ax; - if (mainAx) ax.domain = mainAx.domain.slice(); - ax._anchorAxis = ax.anchor === "free" ? null : axisIDs$1.getFromId(mockGd, ax.anchor); - } - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - ax._counterAxes.sort(axisIDs$1.idSort); - ax._subplotsWith.sort(Lib$1W.subplotSort); - ax._mainSubplot = findMainSubplot(ax, newFullLayout); - if (ax._counterAxes.length && (ax.spikemode && ax.spikemode.indexOf("across") !== -1 || ax.automargin && ax.mirror && ax.anchor !== "free" || Registry$M.getComponentMethod("rangeslider", "isVisible")(ax))) { - var min = 1; - var max = 0; - for (j = 0; j < ax._counterAxes.length; j++) { - var ax2 = axisIDs$1.getFromId(mockGd, ax._counterAxes[j]); - min = Math.min(min, ax2.domain[0]); - max = Math.max(max, ax2.domain[1]); - } - if (min < max) { - ax._counterDomainMin = min; - ax._counterDomainMax = max; - } - } - } -}; -function findMainSubplot(ax, fullLayout) { - var mockGd = { _fullLayout: fullLayout }; - var isX = ax._id.charAt(0) === "x"; - var anchorAx = ax._mainAxis._anchorAxis; - var mainSubplotID = ""; - var nextBestMainSubplotID = ""; - var anchorID = ""; - if (anchorAx) { - anchorID = anchorAx._mainAxis._id; - mainSubplotID = isX ? ax._id + anchorID : anchorID + ax._id; - } - if (!mainSubplotID || !fullLayout._plots[mainSubplotID]) { - mainSubplotID = ""; - var counterIDs = ax._counterAxes; - for (var j = 0; j < counterIDs.length; j++) { - var counterPart = counterIDs[j]; - var id = isX ? ax._id + counterPart : counterPart + ax._id; - if (!nextBestMainSubplotID) nextBestMainSubplotID = id; - var counterAx = axisIDs$1.getFromId(mockGd, counterPart); - if (anchorID && counterAx.overlaying === anchorID) { - mainSubplotID = id; - break; - } - } - } - return mainSubplotID || nextBestMainSubplotID; -} -plots$1.clearExpandedTraceDefaultColors = function(trace) { - var colorAttrs2, path, i; - function locateColorAttrs(attr, attrName, attrs2, level) { - path[level] = attrName; - path.length = level + 1; - if (attr.valType === "color" && attr.dflt === void 0) { - colorAttrs2.push(path.join(".")); - } - } - path = []; - colorAttrs2 = trace._module._colorAttrs; - if (!colorAttrs2) { - trace._module._colorAttrs = colorAttrs2 = []; - PlotSchema$2.crawl( - trace._module.attributes, - locateColorAttrs - ); - } - for (i = 0; i < colorAttrs2.length; i++) { - var origprop = Lib$1W.nestedProperty(trace, "_input." + colorAttrs2[i]); - if (!origprop.get()) { - Lib$1W.nestedProperty(trace, colorAttrs2[i]).set(null); - } - } -}; -plots$1.supplyDataDefaults = function(dataIn, dataOut, layout, fullLayout) { - var modules2 = fullLayout._modules; - var visibleModules = fullLayout._visibleModules; - var basePlotModules = fullLayout._basePlotModules; - var cnt = 0; - var colorCnt = 0; - var i, fullTrace, trace; - fullLayout._transformModules = []; - function pushModule(fullTrace2) { - dataOut.push(fullTrace2); - var _module = fullTrace2._module; - if (!_module) return; - Lib$1W.pushUnique(modules2, _module); - if (fullTrace2.visible === true) Lib$1W.pushUnique(visibleModules, _module); - Lib$1W.pushUnique(basePlotModules, fullTrace2._module.basePlotModule); - cnt++; - if (fullTrace2._input.visible !== false) colorCnt++; - } - var carpetIndex = {}; - var carpetDependents = []; - var dataTemplate = (layout.template || {}).data || {}; - var templater = Template$9.traceTemplater(dataTemplate); - for (i = 0; i < dataIn.length; i++) { - trace = dataIn[i]; - fullTrace = templater.newTrace(trace); - fullTrace.uid = fullLayout._traceUids[i]; - plots$1.supplyTraceDefaults(trace, fullTrace, colorCnt, fullLayout, i); - fullTrace.index = i; - fullTrace._input = trace; - fullTrace._expandedIndex = cnt; - if (fullTrace.transforms && fullTrace.transforms.length) { - var sdInvisible = trace.visible !== false && fullTrace.visible === false; - var expandedTraces = applyTransforms(fullTrace, dataOut, layout, fullLayout); - for (var j = 0; j < expandedTraces.length; j++) { - var expandedTrace = expandedTraces[j]; - var fullExpandedTrace = { - _template: fullTrace._template, - type: fullTrace.type, - // set uid using parent uid and expanded index - // to promote consistency between update calls - uid: fullTrace.uid + j - }; - if (sdInvisible && expandedTrace.visible === false) { - delete expandedTrace.visible; - } - plots$1.supplyTraceDefaults(expandedTrace, fullExpandedTrace, cnt, fullLayout, i); - relinkPrivateKeys2(fullExpandedTrace, expandedTrace); - fullExpandedTrace.index = i; - fullExpandedTrace._input = trace; - fullExpandedTrace._fullInput = fullTrace; - fullExpandedTrace._expandedIndex = cnt; - fullExpandedTrace._expandedInput = expandedTrace; - pushModule(fullExpandedTrace); - } - } else { - fullTrace._fullInput = fullTrace; - fullTrace._expandedInput = fullTrace; - pushModule(fullTrace); - } - if (Registry$M.traceIs(fullTrace, "carpetAxis")) { - carpetIndex[fullTrace.carpet] = fullTrace; - } - if (Registry$M.traceIs(fullTrace, "carpetDependent")) { - carpetDependents.push(i); - } - } - for (i = 0; i < carpetDependents.length; i++) { - fullTrace = dataOut[carpetDependents[i]]; - if (!fullTrace.visible) continue; - var carpetAxis = carpetIndex[fullTrace.carpet]; - fullTrace._carpet = carpetAxis; - if (!carpetAxis || !carpetAxis.visible) { - fullTrace.visible = false; - continue; - } - fullTrace.xaxis = carpetAxis.xaxis; - fullTrace.yaxis = carpetAxis.yaxis; - } -}; -plots$1.supplyAnimationDefaults = function(opts) { - opts = opts || {}; - var i; - var optsOut = {}; - function coerce2(attr, dflt) { - return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1, attr, dflt); - } - coerce2("mode"); - coerce2("direction"); - coerce2("fromcurrent"); - if (Array.isArray(opts.frame)) { - optsOut.frame = []; - for (i = 0; i < opts.frame.length; i++) { - optsOut.frame[i] = plots$1.supplyAnimationFrameDefaults(opts.frame[i] || {}); - } - } else { - optsOut.frame = plots$1.supplyAnimationFrameDefaults(opts.frame || {}); - } - if (Array.isArray(opts.transition)) { - optsOut.transition = []; - for (i = 0; i < opts.transition.length; i++) { - optsOut.transition[i] = plots$1.supplyAnimationTransitionDefaults(opts.transition[i] || {}); - } - } else { - optsOut.transition = plots$1.supplyAnimationTransitionDefaults(opts.transition || {}); - } - return optsOut; -}; -plots$1.supplyAnimationFrameDefaults = function(opts) { - var optsOut = {}; - function coerce2(attr, dflt) { - return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1.frame, attr, dflt); - } - coerce2("duration"); - coerce2("redraw"); - return optsOut; -}; -plots$1.supplyAnimationTransitionDefaults = function(opts) { - var optsOut = {}; - function coerce2(attr, dflt) { - return Lib$1W.coerce(opts || {}, optsOut, animationAttrs$1.transition, attr, dflt); - } - coerce2("duration"); - coerce2("easing"); - return optsOut; -}; -plots$1.supplyFrameDefaults = function(frameIn) { - var frameOut = {}; - function coerce2(attr, dflt) { - return Lib$1W.coerce(frameIn, frameOut, frameAttrs, attr, dflt); - } - coerce2("group"); - coerce2("name"); - coerce2("traces"); - coerce2("baseframe"); - coerce2("data"); - coerce2("layout"); - return frameOut; -}; -plots$1.supplyTraceDefaults = function(traceIn, traceOut, colorIndex, layout, traceInIndex) { - var colorway = layout.colorway || Color$L.defaults; - var defaultColor = colorway[colorIndex % colorway.length]; - var i; - function coerce2(attr, dflt) { - return Lib$1W.coerce(traceIn, traceOut, plots$1.attributes, attr, dflt); - } - var visible = coerce2("visible"); - coerce2("type"); - coerce2("name", layout._traceWord + " " + traceInIndex); - coerce2("uirevision", layout.uirevision); - var _module = plots$1.getModule(traceOut); - traceOut._module = _module; - if (_module) { - var basePlotModule = _module.basePlotModule; - var subplotAttr = basePlotModule.attr; - var subplotAttrs = basePlotModule.attributes; - if (subplotAttr && subplotAttrs) { - var subplots = layout._subplots; - var subplotId = ""; - if (visible || basePlotModule.name !== "gl2d") { - if (Array.isArray(subplotAttr)) { - for (i = 0; i < subplotAttr.length; i++) { - var attri = subplotAttr[i]; - var vali = Lib$1W.coerce(traceIn, traceOut, subplotAttrs, attri); - if (subplots[attri]) Lib$1W.pushUnique(subplots[attri], vali); - subplotId += vali; - } - } else { - subplotId = Lib$1W.coerce(traceIn, traceOut, subplotAttrs, subplotAttr); - } - if (subplots[basePlotModule.name]) { - Lib$1W.pushUnique(subplots[basePlotModule.name], subplotId); - } - } - } - } - if (visible) { - coerce2("customdata"); - coerce2("ids"); - coerce2("meta"); - if (Registry$M.traceIs(traceOut, "showLegend")) { - Lib$1W.coerce( - traceIn, - traceOut, - _module.attributes.showlegend ? _module.attributes : plots$1.attributes, - "showlegend" - ); - coerce2("legend"); - coerce2("legendwidth"); - coerce2("legendgroup"); - coerce2("legendgrouptitle.text"); - coerce2("legendrank"); - traceOut._dfltShowLegend = true; - } else { - traceOut._dfltShowLegend = false; - } - if (_module) { - _module.supplyDefaults(traceIn, traceOut, defaultColor, layout); - } - if (!Registry$M.traceIs(traceOut, "noOpacity")) { - coerce2("opacity"); - } - if (Registry$M.traceIs(traceOut, "notLegendIsolatable")) { - traceOut.visible = !!traceOut.visible; - } - if (!Registry$M.traceIs(traceOut, "noHover")) { - if (!traceOut.hovertemplate) Lib$1W.coerceHoverinfo(traceIn, traceOut, layout); - if (traceOut.type !== "parcats") { - Registry$M.getComponentMethod("fx", "supplyDefaults")(traceIn, traceOut, defaultColor, layout); - } - } - if (_module && _module.selectPoints) { - var selectedpoints = coerce2("selectedpoints"); - if (Lib$1W.isTypedArray(selectedpoints)) { - traceOut.selectedpoints = Array.from(selectedpoints); - } - } - plots$1.supplyTransformDefaults(traceIn, traceOut, layout); - } - return traceOut; -}; -function hasMakesDataTransform(trace) { - var transforms = trace.transforms; - if (Array.isArray(transforms) && transforms.length) { - for (var i = 0; i < transforms.length; i++) { - var ti = transforms[i]; - var _module = ti._module || transformsRegistry[ti.type]; - if (_module && _module.makesData) return true; - } - } - return false; -} -plots$1.hasMakesDataTransform = hasMakesDataTransform; -plots$1.supplyTransformDefaults = function(traceIn, traceOut, layout) { - if (!(traceOut._length || hasMakesDataTransform(traceIn))) return; - var globalTransforms = layout._globalTransforms || []; - var transformModules = layout._transformModules || []; - if (!Array.isArray(traceIn.transforms) && globalTransforms.length === 0) return; - var containerIn = traceIn.transforms || []; - var transformList = globalTransforms.concat(containerIn); - var containerOut = traceOut.transforms = []; - for (var i = 0; i < transformList.length; i++) { - var transformIn = transformList[i]; - var type = transformIn.type; - var _module = transformsRegistry[type]; - var transformOut; - var isFirstStage = !(transformIn._module && transformIn._module === _module); - var doLaterStages = _module && typeof _module.transform === "function"; - if (!_module) Lib$1W.warn("Unrecognized transform type " + type + "."); - if (_module && _module.supplyDefaults && (isFirstStage || doLaterStages)) { - transformOut = _module.supplyDefaults(transformIn, traceOut, layout, traceIn); - transformOut.type = type; - transformOut._module = _module; - Lib$1W.pushUnique(transformModules, _module); - } else { - transformOut = Lib$1W.extendFlat({}, transformIn); - } - containerOut.push(transformOut); - } -}; -function applyTransforms(fullTrace, fullData, layout, fullLayout) { - var container = fullTrace.transforms; - var dataOut = [fullTrace]; - for (var i = 0; i < container.length; i++) { - var transform = container[i]; - var _module = transformsRegistry[transform.type]; - if (_module && _module.transform) { - dataOut = _module.transform(dataOut, { - transform, - fullTrace, - fullData, - layout, - fullLayout, - transformIndex: i - }); - } - } - return dataOut; -} -plots$1.supplyLayoutGlobalDefaults = function(layoutIn, layoutOut, formatObj) { - function coerce2(attr, dflt) { - return Lib$1W.coerce(layoutIn, layoutOut, plots$1.layoutAttributes, attr, dflt); - } - var template = layoutIn.template; - if (Lib$1W.isPlainObject(template)) { - layoutOut.template = template; - layoutOut._template = template.layout; - layoutOut._dataTemplate = template.data; - } - coerce2("autotypenumbers"); - var font2 = Lib$1W.coerceFont(coerce2, "font"); - var fontSize = font2.size; - Lib$1W.coerceFont(coerce2, "title.font", font2, { overrideDflt: { - size: Math.round(fontSize * 1.4) - } }); - coerce2("title.text", layoutOut._dfltTitle.plot); - coerce2("title.xref"); - var titleYref = coerce2("title.yref"); - coerce2("title.pad.t"); - coerce2("title.pad.r"); - coerce2("title.pad.b"); - coerce2("title.pad.l"); - var titleAutomargin = coerce2("title.automargin"); - coerce2("title.x"); - coerce2("title.xanchor"); - coerce2("title.y"); - coerce2("title.yanchor"); - coerce2("title.subtitle.text", layoutOut._dfltTitle.subtitle); - Lib$1W.coerceFont(coerce2, "title.subtitle.font", font2, { - overrideDflt: { - size: Math.round(layoutOut.title.font.size * 0.7) - } - }); - if (titleAutomargin) { - if (titleYref === "paper") { - if (layoutOut.title.y !== 0) layoutOut.title.y = 1; - if (layoutOut.title.yanchor === "auto") { - layoutOut.title.yanchor = layoutOut.title.y === 0 ? "top" : "bottom"; - } - } - if (titleYref === "container") { - if (layoutOut.title.y === "auto") layoutOut.title.y = 1; - if (layoutOut.title.yanchor === "auto") { - layoutOut.title.yanchor = layoutOut.title.y < 0.5 ? "bottom" : "top"; - } - } - } - var uniformtextMode = coerce2("uniformtext.mode"); - if (uniformtextMode) { - coerce2("uniformtext.minsize"); - } - coerce2("autosize", !(layoutIn.width && layoutIn.height)); - coerce2("width"); - coerce2("height"); - coerce2("minreducedwidth"); - coerce2("minreducedheight"); - coerce2("margin.l"); - coerce2("margin.r"); - coerce2("margin.t"); - coerce2("margin.b"); - coerce2("margin.pad"); - coerce2("margin.autoexpand"); - if (layoutIn.width && layoutIn.height) plots$1.sanitizeMargins(layoutOut); - Registry$M.getComponentMethod("grid", "sizeDefaults")(layoutIn, layoutOut); - coerce2("paper_bgcolor"); - coerce2("separators", formatObj.decimal + formatObj.thousands); - coerce2("hidesources"); - coerce2("colorway"); - coerce2("datarevision"); - var uirevision = coerce2("uirevision"); - coerce2("editrevision", uirevision); - coerce2("selectionrevision", uirevision); - Registry$M.getComponentMethod( - "modebar", - "supplyLayoutDefaults" - )(layoutIn, layoutOut); - Registry$M.getComponentMethod( - "shapes", - "supplyDrawNewShapeDefaults" - )(layoutIn, layoutOut, coerce2); - Registry$M.getComponentMethod( - "selections", - "supplyDrawNewSelectionDefaults" - )(layoutIn, layoutOut, coerce2); - coerce2("meta"); - if (Lib$1W.isPlainObject(layoutIn.transition)) { - coerce2("transition.duration"); - coerce2("transition.easing"); - coerce2("transition.ordering"); - } - Registry$M.getComponentMethod( - "calendars", - "handleDefaults" - )(layoutIn, layoutOut, "calendar"); - Registry$M.getComponentMethod( - "fx", - "supplyLayoutGlobalDefaults" - )(layoutIn, layoutOut, coerce2); - Lib$1W.coerce(layoutIn, layoutOut, scatterAttrs$3, "scattermode"); -}; -function getComputedSize(attr) { - return typeof attr === "string" && attr.substr(attr.length - 2) === "px" && parseFloat(attr); -} -plots$1.plotAutoSize = function plotAutoSize(gd, layout, fullLayout) { - var context2 = gd._context || {}; - var frameMargins = context2.frameMargins; - var newWidth; - var newHeight; - var isPlotDiv2 = Lib$1W.isPlotDiv(gd); - if (isPlotDiv2) gd.emit("plotly_autosize"); - if (context2.fillFrame) { - newWidth = window.innerWidth; - newHeight = window.innerHeight; - document.body.style.overflow = "hidden"; - } else { - var computedStyle = isPlotDiv2 ? window.getComputedStyle(gd) : {}; - newWidth = getComputedSize(computedStyle.width) || getComputedSize(computedStyle.maxWidth) || fullLayout.width; - newHeight = getComputedSize(computedStyle.height) || getComputedSize(computedStyle.maxHeight) || fullLayout.height; - if (isNumeric$u(frameMargins) && frameMargins > 0) { - var factor = 1 - 2 * frameMargins; - newWidth = Math.round(factor * newWidth); - newHeight = Math.round(factor * newHeight); - } - } - var minWidth = plots$1.layoutAttributes.width.min; - var minHeight = plots$1.layoutAttributes.height.min; - if (newWidth < minWidth) newWidth = minWidth; - if (newHeight < minHeight) newHeight = minHeight; - var widthHasChanged = !layout.width && Math.abs(fullLayout.width - newWidth) > 1; - var heightHasChanged = !layout.height && Math.abs(fullLayout.height - newHeight) > 1; - if (heightHasChanged || widthHasChanged) { - if (widthHasChanged) fullLayout.width = newWidth; - if (heightHasChanged) fullLayout.height = newHeight; - } - if (!gd._initialAutoSize) { - gd._initialAutoSize = { width: newWidth, height: newHeight }; - } - plots$1.sanitizeMargins(fullLayout); -}; -plots$1.supplyLayoutModuleDefaults = function(layoutIn, layoutOut, fullData, transitionData) { - var componentsRegistry = Registry$M.componentsRegistry; - var basePlotModules = layoutOut._basePlotModules; - var component, i, _module; - var Cartesian = Registry$M.subplotsRegistry.cartesian; - for (component in componentsRegistry) { - _module = componentsRegistry[component]; - if (_module.includeBasePlot) { - _module.includeBasePlot(layoutIn, layoutOut); - } - } - if (!basePlotModules.length) { - basePlotModules.push(Cartesian); - } - if (layoutOut._has("cartesian")) { - Registry$M.getComponentMethod("grid", "contentDefaults")(layoutIn, layoutOut); - Cartesian.finalizeSubplots(layoutIn, layoutOut); - } - for (var subplotType in layoutOut._subplots) { - layoutOut._subplots[subplotType].sort(Lib$1W.subplotSort); - } - for (i = 0; i < basePlotModules.length; i++) { - _module = basePlotModules[i]; - if (_module.supplyLayoutDefaults) { - _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); - } - } - var modules2 = layoutOut._modules; - for (i = 0; i < modules2.length; i++) { - _module = modules2[i]; - if (_module.supplyLayoutDefaults) { - _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); - } - } - var transformModules = layoutOut._transformModules; - for (i = 0; i < transformModules.length; i++) { - _module = transformModules[i]; - if (_module.supplyLayoutDefaults) { - _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData, transitionData); - } - } - for (component in componentsRegistry) { - _module = componentsRegistry[component]; - if (_module.supplyLayoutDefaults) { - _module.supplyLayoutDefaults(layoutIn, layoutOut, fullData); - } - } -}; -plots$1.purge = function(gd) { - var fullLayout = gd._fullLayout || {}; - if (fullLayout._glcontainer !== void 0) { - fullLayout._glcontainer.selectAll(".gl-canvas").remove(); - fullLayout._glcontainer.remove(); - fullLayout._glcanvas = null; - } - if (fullLayout._modeBar) fullLayout._modeBar.destroy(); - if (gd._transitionData) { - if (gd._transitionData._interruptCallbacks) { - gd._transitionData._interruptCallbacks.length = 0; - } - if (gd._transitionData._animationRaf) { - window.cancelAnimationFrame(gd._transitionData._animationRaf); - } - } - Lib$1W.clearThrottle(); - Lib$1W.clearResponsive(gd); - delete gd.data; - delete gd.layout; - delete gd._fullData; - delete gd._fullLayout; - delete gd.calcdata; - delete gd.empty; - delete gd.fid; - delete gd.undoqueue; - delete gd.undonum; - delete gd.autoplay; - delete gd.changed; - delete gd._promises; - delete gd._redrawTimer; - delete gd._hmlumcount; - delete gd._hmpixcount; - delete gd._transitionData; - delete gd._transitioning; - delete gd._initialAutoSize; - delete gd._transitioningWithDuration; - delete gd._dragging; - delete gd._dragged; - delete gd._dragdata; - delete gd._hoverdata; - delete gd._snapshotInProgress; - delete gd._editing; - delete gd._mouseDownTime; - delete gd._legendMouseDownTime; - if (gd.removeAllListeners) gd.removeAllListeners(); -}; -plots$1.style = function(gd) { - var _modules = gd._fullLayout._visibleModules; - var styleModules = []; - var i; - for (i = 0; i < _modules.length; i++) { - var _module = _modules[i]; - if (_module.style) { - Lib$1W.pushUnique(styleModules, _module.style); - } - } - for (i = 0; i < styleModules.length; i++) { - styleModules[i](gd); - } -}; -plots$1.sanitizeMargins = function(fullLayout) { - if (!fullLayout || !fullLayout.margin) return; - var width = fullLayout.width; - var height = fullLayout.height; - var margin = fullLayout.margin; - var plotWidth = width - (margin.l + margin.r); - var plotHeight = height - (margin.t + margin.b); - var correction; - if (plotWidth < 0) { - correction = (width - 1) / (margin.l + margin.r); - margin.l = Math.floor(correction * margin.l); - margin.r = Math.floor(correction * margin.r); - } - if (plotHeight < 0) { - correction = (height - 1) / (margin.t + margin.b); - margin.t = Math.floor(correction * margin.t); - margin.b = Math.floor(correction * margin.b); - } -}; -plots$1.clearAutoMarginIds = function(gd) { - gd._fullLayout._pushmarginIds = {}; -}; -plots$1.allowAutoMargin = function(gd, id) { - gd._fullLayout._pushmarginIds[id] = 1; -}; -function initMargins(fullLayout) { - var margin = fullLayout.margin; - if (!fullLayout._size) { - var gs = fullLayout._size = { - l: Math.round(margin.l), - r: Math.round(margin.r), - t: Math.round(margin.t), - b: Math.round(margin.b), - p: Math.round(margin.pad) - }; - gs.w = Math.round(fullLayout.width) - gs.l - gs.r; - gs.h = Math.round(fullLayout.height) - gs.t - gs.b; - } - if (!fullLayout._pushmargin) fullLayout._pushmargin = {}; - if (!fullLayout._pushmarginIds) fullLayout._pushmarginIds = {}; - if (!fullLayout._reservedMargin) fullLayout._reservedMargin = {}; -} -var MIN_SPECIFIED_WIDTH = 2; -var MIN_SPECIFIED_HEIGHT = 2; -plots$1.autoMargin = function(gd, id, o) { - var fullLayout = gd._fullLayout; - var width = fullLayout.width; - var height = fullLayout.height; - var margin = fullLayout.margin; - var minreducedwidth = fullLayout.minreducedwidth; - var minreducedheight = fullLayout.minreducedheight; - var minFinalWidth = Lib$1W.constrain( - width - margin.l - margin.r, - MIN_SPECIFIED_WIDTH, - minreducedwidth - ); - var minFinalHeight = Lib$1W.constrain( - height - margin.t - margin.b, - MIN_SPECIFIED_HEIGHT, - minreducedheight - ); - var maxSpaceW = Math.max(0, width - minFinalWidth); - var maxSpaceH = Math.max(0, height - minFinalHeight); - var pushMargin = fullLayout._pushmargin; - var pushMarginIds = fullLayout._pushmarginIds; - if (margin.autoexpand !== false) { - if (!o) { - delete pushMargin[id]; - delete pushMarginIds[id]; - } else { - var pad2 = o.pad; - if (pad2 === void 0) { - pad2 = Math.min(12, margin.l, margin.r, margin.t, margin.b); - } - if (maxSpaceW) { - var rW = (o.l + o.r) / maxSpaceW; - if (rW > 1) { - o.l /= rW; - o.r /= rW; - } - } - if (maxSpaceH) { - var rH = (o.t + o.b) / maxSpaceH; - if (rH > 1) { - o.t /= rH; - o.b /= rH; - } - } - var xl = o.xl !== void 0 ? o.xl : o.x; - var xr = o.xr !== void 0 ? o.xr : o.x; - var yt = o.yt !== void 0 ? o.yt : o.y; - var yb = o.yb !== void 0 ? o.yb : o.y; - pushMargin[id] = { - l: { val: xl, size: o.l + pad2 }, - r: { val: xr, size: o.r + pad2 }, - b: { val: yb, size: o.b + pad2 }, - t: { val: yt, size: o.t + pad2 } - }; - pushMarginIds[id] = 1; - } - if (!fullLayout._replotting) { - return plots$1.doAutoMargin(gd); - } - } -}; -function needsRedrawForShift(gd) { - if ("_redrawFromAutoMarginCount" in gd._fullLayout) { - return false; - } - var axList = axisIDs$1.list(gd, "", true); - for (var ax in axList) { - if (axList[ax].autoshift || axList[ax].shift) return true; - } - return false; -} -plots$1.doAutoMargin = function(gd) { - var fullLayout = gd._fullLayout; - var width = fullLayout.width; - var height = fullLayout.height; - if (!fullLayout._size) fullLayout._size = {}; - initMargins(fullLayout); - var gs = fullLayout._size; - var margin = fullLayout.margin; - var reservedMargins = { t: 0, b: 0, l: 0, r: 0 }; - var oldMargins = Lib$1W.extendFlat({}, gs); - var ml = margin.l; - var mr = margin.r; - var mt = margin.t; - var mb = margin.b; - var pushMargin = fullLayout._pushmargin; - var pushMarginIds = fullLayout._pushmarginIds; - var minreducedwidth = fullLayout.minreducedwidth; - var minreducedheight = fullLayout.minreducedheight; - if (margin.autoexpand !== false) { - for (var k in pushMargin) { - if (!pushMarginIds[k]) delete pushMargin[k]; - } - var margins = gd._fullLayout._reservedMargin; - for (var key in margins) { - for (var side in margins[key]) { - var val = margins[key][side]; - reservedMargins[side] = Math.max(reservedMargins[side], val); - } - } - pushMargin.base = { - l: { val: 0, size: ml }, - r: { val: 1, size: mr }, - t: { val: 1, size: mt }, - b: { val: 0, size: mb } - }; - for (var s in reservedMargins) { - var autoMarginPush = 0; - for (var m in pushMargin) { - if (m !== "base") { - if (isNumeric$u(pushMargin[m][s].size)) { - autoMarginPush = pushMargin[m][s].size > autoMarginPush ? pushMargin[m][s].size : autoMarginPush; - } - } - } - var extraMargin = Math.max(0, margin[s] - autoMarginPush); - reservedMargins[s] = Math.max(0, reservedMargins[s] - extraMargin); - } - for (var k1 in pushMargin) { - var pushleft = pushMargin[k1].l || {}; - var pushbottom = pushMargin[k1].b || {}; - var fl = pushleft.val; - var pl = pushleft.size; - var fb = pushbottom.val; - var pb = pushbottom.size; - var availableWidth = width - reservedMargins.r - reservedMargins.l; - var availableHeight = height - reservedMargins.t - reservedMargins.b; - for (var k2 in pushMargin) { - if (isNumeric$u(pl) && pushMargin[k2].r) { - var fr = pushMargin[k2].r.val; - var pr = pushMargin[k2].r.size; - if (fr > fl) { - var newL = (pl * fr + (pr - availableWidth) * fl) / (fr - fl); - var newR = (pr * (1 - fl) + (pl - availableWidth) * (1 - fr)) / (fr - fl); - if (newL + newR > ml + mr) { - ml = newL; - mr = newR; - } - } - } - if (isNumeric$u(pb) && pushMargin[k2].t) { - var ft = pushMargin[k2].t.val; - var pt = pushMargin[k2].t.size; - if (ft > fb) { - var newB = (pb * ft + (pt - availableHeight) * fb) / (ft - fb); - var newT = (pt * (1 - fb) + (pb - availableHeight) * (1 - ft)) / (ft - fb); - if (newB + newT > mb + mt) { - mb = newB; - mt = newT; - } - } - } - } - } - } - var minFinalWidth = Lib$1W.constrain( - width - margin.l - margin.r, - MIN_SPECIFIED_WIDTH, - minreducedwidth - ); - var minFinalHeight = Lib$1W.constrain( - height - margin.t - margin.b, - MIN_SPECIFIED_HEIGHT, - minreducedheight - ); - var maxSpaceW = Math.max(0, width - minFinalWidth); - var maxSpaceH = Math.max(0, height - minFinalHeight); - if (maxSpaceW) { - var rW = (ml + mr) / maxSpaceW; - if (rW > 1) { - ml /= rW; - mr /= rW; - } - } - if (maxSpaceH) { - var rH = (mb + mt) / maxSpaceH; - if (rH > 1) { - mb /= rH; - mt /= rH; - } - } - gs.l = Math.round(ml) + reservedMargins.l; - gs.r = Math.round(mr) + reservedMargins.r; - gs.t = Math.round(mt) + reservedMargins.t; - gs.b = Math.round(mb) + reservedMargins.b; - gs.p = Math.round(margin.pad); - gs.w = Math.round(width) - gs.l - gs.r; - gs.h = Math.round(height) - gs.t - gs.b; - if (!fullLayout._replotting && (plots$1.didMarginChange(oldMargins, gs) || needsRedrawForShift(gd))) { - if ("_redrawFromAutoMarginCount" in fullLayout) { - fullLayout._redrawFromAutoMarginCount++; - } else { - fullLayout._redrawFromAutoMarginCount = 1; - } - var maxNumberOfRedraws = 3 * (1 + Object.keys(pushMarginIds).length); - if (fullLayout._redrawFromAutoMarginCount < maxNumberOfRedraws) { - return Registry$M.call("_doPlot", gd); - } else { - fullLayout._size = oldMargins; - Lib$1W.warn("Too many auto-margin redraws."); - } - } - refineTicks(gd); -}; -function refineTicks(gd) { - var axList = axisIDs$1.list(gd, "", true); - [ - "_adjustTickLabelsOverflow", - "_hideCounterAxisInsideTickLabels" - ].forEach(function(k) { - for (var i = 0; i < axList.length; i++) { - var hideFn = axList[i][k]; - if (hideFn) hideFn(); - } - }); -} -var marginKeys = ["l", "r", "t", "b", "p", "w", "h"]; -plots$1.didMarginChange = function(margin0, margin1) { - for (var i = 0; i < marginKeys.length; i++) { - var k = marginKeys[i]; - var m0 = margin0[k]; - var m1 = margin1[k]; - if (!isNumeric$u(m0) || Math.abs(m1 - m0) > 1) { - return true; - } - } - return false; -}; -plots$1.graphJson = function(gd, dataonly, mode, output, useDefaults, includeConfig) { - if (useDefaults && dataonly && !gd._fullData || useDefaults && !dataonly && !gd._fullLayout) { - plots$1.supplyDefaults(gd); - } - var data = useDefaults ? gd._fullData : gd.data; - var layout = useDefaults ? gd._fullLayout : gd.layout; - var frames = (gd._transitionData || {})._frames; - function stripObj(d, keepFunction) { - if (typeof d === "function") { - return keepFunction ? "_function_" : null; - } - if (Lib$1W.isPlainObject(d)) { - var o = {}; - var src2; - Object.keys(d).sort().forEach(function(v) { - if (["_", "["].indexOf(v.charAt(0)) !== -1) return; - if (typeof d[v] === "function") { - if (keepFunction) o[v] = "_function"; - return; - } - if (mode === "keepdata") { - if (v.substr(v.length - 3) === "src") { - return; - } - } else if (mode === "keepstream") { - src2 = d[v + "src"]; - if (typeof src2 === "string" && src2.indexOf(":") > 0) { - if (!Lib$1W.isPlainObject(d.stream)) { - return; - } - } - } else if (mode !== "keepall") { - src2 = d[v + "src"]; - if (typeof src2 === "string" && src2.indexOf(":") > 0) { - return; - } - } - o[v] = stripObj(d[v], keepFunction); - }); - return o; - } - var dIsArray = Array.isArray(d); - var dIsTypedArray = Lib$1W.isTypedArray(d); - if ((dIsArray || dIsTypedArray) && d.dtype && d.shape) { - var bdata = d.bdata; - return stripObj({ - dtype: d.dtype, - shape: d.shape, - bdata: ( - // case of ArrayBuffer - Lib$1W.isArrayBuffer(bdata) ? b64encode.encode(bdata) : ( - // case of b64 string - bdata - ) - ) - }, keepFunction); - } - if (dIsArray) { - return d.map(function(x) { - return stripObj(x, keepFunction); - }); - } - if (dIsTypedArray) { - return Lib$1W.simpleMap(d, Lib$1W.identity); - } - if (Lib$1W.isJSDate(d)) return Lib$1W.ms2DateTimeLocal(+d); - return d; - } - var obj = { - data: (data || []).map(function(v) { - var d = stripObj(v); - if (dataonly) { - delete d.fit; - } - return d; - }) - }; - if (!dataonly) { - obj.layout = stripObj(layout); - if (useDefaults) { - var gs = layout._size; - obj.layout.computed = { - margin: { - b: gs.b, - l: gs.l, - r: gs.r, - t: gs.t - } - }; - } - } - if (frames) obj.frames = stripObj(frames); - if (includeConfig) obj.config = stripObj(gd._context, true); - return output === "object" ? obj : JSON.stringify(obj); -}; -plots$1.modifyFrames = function(gd, operations) { - var i, op, frame; - var _frames = gd._transitionData._frames; - var _frameHash = gd._transitionData._frameHash; - for (i = 0; i < operations.length; i++) { - op = operations[i]; - switch (op.type) { - case "replace": - frame = op.value; - var oldName = (_frames[op.index] || {}).name; - var newName = frame.name; - _frames[op.index] = _frameHash[newName] = frame; - if (newName !== oldName) { - delete _frameHash[oldName]; - _frameHash[newName] = frame; - } - break; - case "insert": - frame = op.value; - _frameHash[frame.name] = frame; - _frames.splice(op.index, 0, frame); - break; - case "delete": - frame = _frames[op.index]; - delete _frameHash[frame.name]; - _frames.splice(op.index, 1); - break; - } - } - return Promise.resolve(); -}; -plots$1.computeFrame = function(gd, frameName) { - var frameLookup = gd._transitionData._frameHash; - var i, traceIndices, traceIndex, destIndex; - if (!frameName) { - throw new Error("computeFrame must be given a string frame name"); - } - var framePtr = frameLookup[frameName.toString()]; - if (!framePtr) { - return false; - } - var frameStack = [framePtr]; - var frameNameStack = [framePtr.name]; - while (framePtr.baseframe && (framePtr = frameLookup[framePtr.baseframe.toString()])) { - if (frameNameStack.indexOf(framePtr.name) !== -1) break; - frameStack.push(framePtr); - frameNameStack.push(framePtr.name); - } - var result = {}; - while (framePtr = frameStack.pop()) { - if (framePtr.layout) { - result.layout = plots$1.extendLayout(result.layout, framePtr.layout); - } - if (framePtr.data) { - if (!result.data) { - result.data = []; - } - traceIndices = framePtr.traces; - if (!traceIndices) { - traceIndices = []; - for (i = 0; i < framePtr.data.length; i++) { - traceIndices[i] = i; - } - } - if (!result.traces) { - result.traces = []; - } - for (i = 0; i < framePtr.data.length; i++) { - traceIndex = traceIndices[i]; - if (traceIndex === void 0 || traceIndex === null) { - continue; - } - destIndex = result.traces.indexOf(traceIndex); - if (destIndex === -1) { - destIndex = result.data.length; - result.traces[destIndex] = traceIndex; - } - result.data[destIndex] = plots$1.extendTrace(result.data[destIndex], framePtr.data[i]); - } - } - } - return result; -}; -plots$1.recomputeFrameHash = function(gd) { - var hash = gd._transitionData._frameHash = {}; - var frames = gd._transitionData._frames; - for (var i = 0; i < frames.length; i++) { - var frame = frames[i]; - if (frame && frame.name) { - hash[frame.name] = frame; - } - } -}; -plots$1.extendObjectWithContainers = function(dest, src2, containerPaths) { - var containerProp, containerVal, i, j, srcProp, destProp, srcContainer, destContainer; - var copy2 = Lib$1W.extendDeepNoArrays({}, src2 || {}); - var expandedObj = Lib$1W.expandObjectPaths(copy2); - var containerObj = {}; - if (containerPaths && containerPaths.length) { - for (i = 0; i < containerPaths.length; i++) { - containerProp = Lib$1W.nestedProperty(expandedObj, containerPaths[i]); - containerVal = containerProp.get(); - if (containerVal === void 0) { - Lib$1W.nestedProperty(containerObj, containerPaths[i]).set(null); - } else { - containerProp.set(null); - Lib$1W.nestedProperty(containerObj, containerPaths[i]).set(containerVal); - } - } - } - dest = Lib$1W.extendDeepNoArrays(dest || {}, expandedObj); - if (containerPaths && containerPaths.length) { - for (i = 0; i < containerPaths.length; i++) { - srcProp = Lib$1W.nestedProperty(containerObj, containerPaths[i]); - srcContainer = srcProp.get(); - if (!srcContainer) continue; - destProp = Lib$1W.nestedProperty(dest, containerPaths[i]); - destContainer = destProp.get(); - if (!Array.isArray(destContainer)) { - destContainer = []; - destProp.set(destContainer); - } - for (j = 0; j < srcContainer.length; j++) { - var srcObj = srcContainer[j]; - if (srcObj === null) destContainer[j] = null; - else { - destContainer[j] = plots$1.extendObjectWithContainers(destContainer[j], srcObj); - } - } - destProp.set(destContainer); - } - } - return dest; -}; -plots$1.dataArrayContainers = ["transforms", "dimensions"]; -plots$1.layoutArrayContainers = Registry$M.layoutArrayContainers; -plots$1.extendTrace = function(destTrace, srcTrace) { - return plots$1.extendObjectWithContainers(destTrace, srcTrace, plots$1.dataArrayContainers); -}; -plots$1.extendLayout = function(destLayout, srcLayout) { - return plots$1.extendObjectWithContainers(destLayout, srcLayout, plots$1.layoutArrayContainers); -}; -plots$1.transition = function(gd, data, layout, traces, frameOpts, transitionOpts) { - var opts = { redraw: frameOpts.redraw }; - var transitionedTraces = {}; - var axEdits = []; - opts.prepareFn = function() { - var dataLength = Array.isArray(data) ? data.length : 0; - var traceIndices = traces.slice(0, dataLength); - for (var i = 0; i < traceIndices.length; i++) { - var traceIdx = traceIndices[i]; - var trace = gd._fullData[traceIdx]; - var _module = trace._module; - if (!_module) continue; - if (_module.animatable) { - var n = _module.basePlotModule.name; - if (!transitionedTraces[n]) transitionedTraces[n] = []; - transitionedTraces[n].push(traceIdx); - } - gd.data[traceIndices[i]] = plots$1.extendTrace(gd.data[traceIndices[i]], data[i]); - } - var layoutUpdate = Lib$1W.expandObjectPaths(Lib$1W.extendDeepNoArrays({}, layout)); - var axisAttrRe = /^[xy]axis[0-9]*$/; - for (var attr in layoutUpdate) { - if (!axisAttrRe.test(attr)) continue; - delete layoutUpdate[attr].range; - } - plots$1.extendLayout(gd.layout, layoutUpdate); - delete gd.calcdata; - plots$1.supplyDefaults(gd); - plots$1.doCalcdata(gd); - var newLayout = Lib$1W.expandObjectPaths(layout); - if (newLayout) { - var subplots = gd._fullLayout._plots; - for (var k in subplots) { - var plotinfo = subplots[k]; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xr0 = xa.range.slice(); - var yr0 = ya.range.slice(); - var xr1 = null; - var yr1 = null; - var editX = null; - var editY = null; - if (Array.isArray(newLayout[xa._name + ".range"])) { - xr1 = newLayout[xa._name + ".range"].slice(); - } else if (Array.isArray((newLayout[xa._name] || {}).range)) { - xr1 = newLayout[xa._name].range.slice(); - } - if (Array.isArray(newLayout[ya._name + ".range"])) { - yr1 = newLayout[ya._name + ".range"].slice(); - } else if (Array.isArray((newLayout[ya._name] || {}).range)) { - yr1 = newLayout[ya._name].range.slice(); - } - if (xr0 && xr1 && (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1]))) { - editX = { xr0, xr1 }; - } - if (yr0 && yr1 && (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1]))) { - editY = { yr0, yr1 }; - } - if (editX || editY) { - axEdits.push(Lib$1W.extendFlat({ plotinfo }, editX, editY)); - } - } - } - return Promise.resolve(); - }; - opts.runFn = function(makeCallback) { - var traceTransitionOpts; - var basePlotModules = gd._fullLayout._basePlotModules; - var hasAxisTransition = axEdits.length; - var i; - if (layout) { - for (i = 0; i < basePlotModules.length; i++) { - if (basePlotModules[i].transitionAxes) { - basePlotModules[i].transitionAxes(gd, axEdits, transitionOpts, makeCallback); - } - } - } - if (hasAxisTransition) { - traceTransitionOpts = Lib$1W.extendFlat({}, transitionOpts); - traceTransitionOpts.duration = 0; - delete transitionedTraces.cartesian; - } else { - traceTransitionOpts = transitionOpts; - } - for (var n in transitionedTraces) { - var traceIndices = transitionedTraces[n]; - var _module = gd._fullData[traceIndices[0]]._module; - _module.basePlotModule.plot(gd, traceIndices, traceTransitionOpts, makeCallback); - } - }; - return _transition(gd, transitionOpts, opts); -}; -plots$1.transitionFromReact = function(gd, restyleFlags, relayoutFlags, oldFullLayout) { - var fullLayout = gd._fullLayout; - var transitionOpts = fullLayout.transition; - var opts = {}; - var axEdits = []; - opts.prepareFn = function() { - var subplots = fullLayout._plots; - opts.redraw = false; - if (restyleFlags.anim === "some") opts.redraw = true; - if (relayoutFlags.anim === "some") opts.redraw = true; - for (var k in subplots) { - var plotinfo = subplots[k]; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xr0 = oldFullLayout[xa._name].range.slice(); - var yr0 = oldFullLayout[ya._name].range.slice(); - var xr1 = xa.range.slice(); - var yr1 = ya.range.slice(); - xa.setScale(); - ya.setScale(); - var editX = null; - var editY = null; - if (xa.r2l(xr0[0]) !== xa.r2l(xr1[0]) || xa.r2l(xr0[1]) !== xa.r2l(xr1[1])) { - editX = { xr0, xr1 }; - } - if (ya.r2l(yr0[0]) !== ya.r2l(yr1[0]) || ya.r2l(yr0[1]) !== ya.r2l(yr1[1])) { - editY = { yr0, yr1 }; - } - if (editX || editY) { - axEdits.push(Lib$1W.extendFlat({ plotinfo }, editX, editY)); - } - } - return Promise.resolve(); - }; - opts.runFn = function(makeCallback) { - var fullData = gd._fullData; - var fullLayout2 = gd._fullLayout; - var basePlotModules = fullLayout2._basePlotModules; - var axisTransitionOpts; - var traceTransitionOpts; - var transitionedTraces; - var allTraceIndices = []; - for (var i = 0; i < fullData.length; i++) { - allTraceIndices.push(i); - } - function transitionAxes() { - if (!gd._fullLayout) return; - for (var j = 0; j < basePlotModules.length; j++) { - if (basePlotModules[j].transitionAxes) { - basePlotModules[j].transitionAxes(gd, axEdits, axisTransitionOpts, makeCallback); - } - } - } - function transitionTraces() { - if (!gd._fullLayout) return; - for (var j = 0; j < basePlotModules.length; j++) { - basePlotModules[j].plot(gd, transitionedTraces, traceTransitionOpts, makeCallback); - } - } - if (axEdits.length && restyleFlags.anim) { - if (transitionOpts.ordering === "traces first") { - axisTransitionOpts = Lib$1W.extendFlat({}, transitionOpts, { duration: 0 }); - transitionedTraces = allTraceIndices; - traceTransitionOpts = transitionOpts; - setTimeout(transitionAxes, transitionOpts.duration); - transitionTraces(); - } else { - axisTransitionOpts = transitionOpts; - transitionedTraces = null; - traceTransitionOpts = Lib$1W.extendFlat({}, transitionOpts, { duration: 0 }); - setTimeout(transitionTraces, axisTransitionOpts.duration); - transitionAxes(); - } - } else if (axEdits.length) { - axisTransitionOpts = transitionOpts; - transitionAxes(); - } else if (restyleFlags.anim) { - transitionedTraces = allTraceIndices; - traceTransitionOpts = transitionOpts; - transitionTraces(); - } - }; - return _transition(gd, transitionOpts, opts); -}; -function _transition(gd, transitionOpts, opts) { - var aborted = false; - function executeCallbacks(list) { - var p = Promise.resolve(); - if (!list) return p; - while (list.length) { - p = p.then(list.shift()); - } - return p; - } - function flushCallbacks(list) { - if (!list) return; - while (list.length) { - list.shift(); - } - } - function executeTransitions() { - gd.emit("plotly_transitioning", []); - return new Promise(function(resolve) { - gd._transitioning = true; - if (transitionOpts.duration > 0) { - gd._transitioningWithDuration = true; - } - gd._transitionData._interruptCallbacks.push(function() { - aborted = true; - }); - if (opts.redraw) { - gd._transitionData._interruptCallbacks.push(function() { - return Registry$M.call("redraw", gd); - }); - } - gd._transitionData._interruptCallbacks.push(function() { - gd.emit("plotly_transitioninterrupted", []); - }); - var numCallbacks = 0; - var numCompleted = 0; - function makeCallback() { - numCallbacks++; - return function() { - numCompleted++; - if (!aborted && numCompleted === numCallbacks) { - completeTransition(resolve); - } - }; - } - opts.runFn(makeCallback); - setTimeout(makeCallback()); - }); - } - function completeTransition(callback) { - if (!gd._transitionData) return; - flushCallbacks(gd._transitionData._interruptCallbacks); - return Promise.resolve().then(function() { - if (opts.redraw) { - return Registry$M.call("redraw", gd); - } - }).then(function() { - gd._transitioning = false; - gd._transitioningWithDuration = false; - gd.emit("plotly_transitioned", []); - }).then(callback); - } - function interruptPreviousTransitions() { - if (!gd._transitionData) return; - gd._transitioning = false; - return executeCallbacks(gd._transitionData._interruptCallbacks); - } - var seq = [ - plots$1.previousPromises, - interruptPreviousTransitions, - opts.prepareFn, - plots$1.rehover, - plots$1.reselect, - executeTransitions - ]; - var transitionStarting = Lib$1W.syncOrAsync(seq, gd); - if (!transitionStarting || !transitionStarting.then) { - transitionStarting = Promise.resolve(); - } - return transitionStarting.then(function() { - return gd; - }); -} -plots$1.doCalcdata = function(gd, traces) { - var axList = axisIDs$1.list(gd); - var fullData = gd._fullData; - var fullLayout = gd._fullLayout; - var trace, _module, i, j; - var calcdata = new Array(fullData.length); - var oldCalcdata = (gd.calcdata || []).slice(); - gd.calcdata = calcdata; - fullLayout._numBoxes = 0; - fullLayout._numViolins = 0; - fullLayout._violinScaleGroupStats = {}; - gd._hmpixcount = 0; - gd._hmlumcount = 0; - fullLayout._piecolormap = {}; - fullLayout._sunburstcolormap = {}; - fullLayout._treemapcolormap = {}; - fullLayout._iciclecolormap = {}; - fullLayout._funnelareacolormap = {}; - for (i = 0; i < fullData.length; i++) { - if (Array.isArray(traces) && traces.indexOf(i) === -1) { - calcdata[i] = oldCalcdata[i]; - continue; - } - } - for (i = 0; i < fullData.length; i++) { - trace = fullData[i]; - trace._arrayAttrs = PlotSchema$2.findArrayAttributes(trace); - trace._extremes = {}; - } - var polarIds = fullLayout._subplots.polar || []; - for (i = 0; i < polarIds.length; i++) { - axList.push( - fullLayout[polarIds[i]].radialaxis, - fullLayout[polarIds[i]].angularaxis - ); - } - for (var k in fullLayout._colorAxes) { - var cOpts = fullLayout[k]; - if (cOpts.cauto !== false) { - delete cOpts.cmin; - delete cOpts.cmax; - } - } - var hasCalcTransform = false; - function transformCalci(i2) { - trace = fullData[i2]; - _module = trace._module; - if (trace.visible === true && trace.transforms) { - if (_module && _module.calc) { - var cdi = _module.calc(gd, trace); - if (cdi[0] && cdi[0].t && cdi[0].t._scene) { - delete cdi[0].t._scene.dirty; - } - } - for (j = 0; j < trace.transforms.length; j++) { - var transform = trace.transforms[j]; - _module = transformsRegistry[transform.type]; - if (_module && _module.calcTransform) { - trace._hasCalcTransform = true; - hasCalcTransform = true; - _module.calcTransform(gd, trace, transform); - } - } - } - } - function calci(i2, isContainer) { - trace = fullData[i2]; - _module = trace._module; - if (!!_module.isContainer !== isContainer) return; - var cd = []; - if (trace.visible === true && trace._length !== 0) { - delete trace._indexToPoints; - var transforms = trace.transforms || []; - for (j = transforms.length - 1; j >= 0; j--) { - if (transforms[j].enabled) { - trace._indexToPoints = transforms[j]._indexToPoints; - break; - } - } - if (_module && _module.calc) { - cd = _module.calc(gd, trace); - } - } - if (!Array.isArray(cd) || !cd[0]) { - cd = [{ x: BADNUM$a, y: BADNUM$a }]; - } - if (!cd[0].t) cd[0].t = {}; - cd[0].trace = trace; - calcdata[i2] = cd; - } - setupAxisCategories(axList, fullData, fullLayout); - for (i = 0; i < fullData.length; i++) calci(i, true); - for (i = 0; i < fullData.length; i++) transformCalci(i); - if (hasCalcTransform) setupAxisCategories(axList, fullData, fullLayout); - for (i = 0; i < fullData.length; i++) calci(i, true); - for (i = 0; i < fullData.length; i++) calci(i, false); - doCrossTraceCalc(gd); - var sorted = sortAxisCategoriesByValue(axList, gd); - if (sorted.length) { - fullLayout._numBoxes = 0; - fullLayout._numViolins = 0; - for (i = 0; i < sorted.length; i++) calci(sorted[i], true); - for (i = 0; i < sorted.length; i++) calci(sorted[i], false); - doCrossTraceCalc(gd); - } - Registry$M.getComponentMethod("fx", "calc")(gd); - Registry$M.getComponentMethod("errorbars", "calc")(gd); -}; -var sortAxisCategoriesByValueRegex = /(total|sum|min|max|mean|geometric mean|median) (ascending|descending)/; -function sortAxisCategoriesByValue(axList, gd) { - var affectedTraces = []; - var i, j, k, l, o; - function zMapCategory(type2, ax2, value3) { - var axLetter2 = ax2._id.charAt(0); - if (type2 === "histogram2dcontour") { - var counterAxLetter = ax2._counterAxes[0]; - var counterAx = axisIDs$1.getFromId(gd, counterAxLetter); - var xCategorical = axLetter2 === "x" || counterAxLetter === "x" && counterAx.type === "category"; - var yCategorical = axLetter2 === "y" || counterAxLetter === "y" && counterAx.type === "category"; - return function(o2, l2) { - if (o2 === 0 || l2 === 0) return -1; - if (xCategorical && o2 === value3[l2].length - 1) return -1; - if (yCategorical && l2 === value3.length - 1) return -1; - return (axLetter2 === "y" ? l2 : o2) - 1; - }; - } else { - return function(o2, l2) { - return axLetter2 === "y" ? l2 : o2; - }; - } - } - var aggFn = { - min: function(values) { - return Lib$1W.aggNums(Math.min, null, values); - }, - max: function(values) { - return Lib$1W.aggNums(Math.max, null, values); - }, - sum: function(values) { - return Lib$1W.aggNums(function(a, b) { - return a + b; - }, null, values); - }, - total: function(values) { - return Lib$1W.aggNums(function(a, b) { - return a + b; - }, null, values); - }, - mean: function(values) { - return Lib$1W.mean(values); - }, - "geometric mean": function(values) { - return Lib$1W.geometricMean(values); - }, - median: function(values) { - return Lib$1W.median(values); - } - }; - function sortAscending(a, b) { - return a[1] - b[1]; - } - function sortDescending(a, b) { - return b[1] - a[1]; - } - for (i = 0; i < axList.length; i++) { - var ax = axList[i]; - if (ax.type !== "category") continue; - var match = ax.categoryorder.match(sortAxisCategoriesByValueRegex); - if (match) { - var aggregator = match[1]; - var order = match[2]; - var axLetter = ax._id.charAt(0); - var isX = axLetter === "x"; - var categoriesValue = []; - for (j = 0; j < ax._categories.length; j++) { - categoriesValue.push([ax._categories[j], []]); - } - for (j = 0; j < ax._traceIndices.length; j++) { - var traceIndex = ax._traceIndices[j]; - var fullTrace = gd._fullData[traceIndex]; - if (fullTrace.visible !== true) continue; - var type = fullTrace.type; - if (Registry$M.traceIs(fullTrace, "histogram")) { - delete fullTrace._xautoBinFinished; - delete fullTrace._yautoBinFinished; - } - var isSplom = type === "splom"; - var isScattergl = type === "scattergl"; - var cd = gd.calcdata[traceIndex]; - for (k = 0; k < cd.length; k++) { - var cdi = cd[k]; - var catIndex, value2; - if (isSplom) { - var currentDimensionIndex = fullTrace._axesDim[ax._id]; - if (!isX) { - var associatedXAxisID = fullTrace._diag[currentDimensionIndex][0]; - if (associatedXAxisID) ax = gd._fullLayout[axisIDs$1.id2name(associatedXAxisID)]; - } - var categories = cdi.trace.dimensions[currentDimensionIndex].values; - for (l = 0; l < categories.length; l++) { - catIndex = ax._categoriesMap[categories[l]]; - for (o = 0; o < cdi.trace.dimensions.length; o++) { - if (o === currentDimensionIndex) continue; - var dimension = cdi.trace.dimensions[o]; - categoriesValue[catIndex][1].push(dimension.values[l]); - } - } - } else if (isScattergl) { - for (l = 0; l < cdi.t.x.length; l++) { - if (isX) { - catIndex = cdi.t.x[l]; - value2 = cdi.t.y[l]; - } else { - catIndex = cdi.t.y[l]; - value2 = cdi.t.x[l]; - } - categoriesValue[catIndex][1].push(value2); - } - if (cdi.t && cdi.t._scene) { - delete cdi.t._scene.dirty; - } - } else if (cdi.hasOwnProperty("z")) { - value2 = cdi.z; - var mapping = zMapCategory(fullTrace.type, ax, value2); - for (l = 0; l < value2.length; l++) { - for (o = 0; o < value2[l].length; o++) { - catIndex = mapping(o, l); - if (catIndex + 1) categoriesValue[catIndex][1].push(value2[l][o]); - } - } - } else { - catIndex = cdi.p; - if (catIndex === void 0) catIndex = cdi[axLetter]; - value2 = cdi.s; - if (value2 === void 0) value2 = cdi.v; - if (value2 === void 0) value2 = isX ? cdi.y : cdi.x; - if (!Array.isArray(value2)) { - if (value2 === void 0) value2 = []; - else value2 = [value2]; - } - for (l = 0; l < value2.length; l++) { - categoriesValue[catIndex][1].push(value2[l]); - } - } - } - } - ax._categoriesValue = categoriesValue; - var categoriesAggregatedValue = []; - for (j = 0; j < categoriesValue.length; j++) { - categoriesAggregatedValue.push([ - categoriesValue[j][0], - aggFn[aggregator](categoriesValue[j][1]) - ]); - } - categoriesAggregatedValue.sort(order === "descending" ? sortDescending : sortAscending); - ax._categoriesAggregatedValue = categoriesAggregatedValue; - ax._initialCategories = categoriesAggregatedValue.map(function(c) { - return c[0]; - }); - affectedTraces = affectedTraces.concat(ax.sortByInitialCategories()); - } - } - return affectedTraces; -} -function setupAxisCategories(axList, fullData, fullLayout) { - var axLookup = {}; - function setupOne(ax) { - ax.clearCalc(); - if (ax.type === "multicategory") { - ax.setupMultiCategory(fullData); - } - axLookup[ax._id] = 1; - } - Lib$1W.simpleMap(axList, setupOne); - var matchGroups = fullLayout._axisMatchGroups || []; - for (var i = 0; i < matchGroups.length; i++) { - for (var axId in matchGroups[i]) { - if (!axLookup[axId]) { - setupOne(fullLayout[axisIDs$1.id2name(axId)]); - } - } - } -} -function doCrossTraceCalc(gd) { - var fullLayout = gd._fullLayout; - var modules2 = fullLayout._visibleModules; - var hash = {}; - var i, j, k; - for (j = 0; j < modules2.length; j++) { - var _module = modules2[j]; - var fn = _module.crossTraceCalc; - if (fn) { - var spType = _module.basePlotModule.name; - if (hash[spType]) { - Lib$1W.pushUnique(hash[spType], fn); - } else { - hash[spType] = [fn]; - } - } - } - for (k in hash) { - var methods2 = hash[k]; - var subplots = fullLayout._subplots[k]; - if (Array.isArray(subplots)) { - for (i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - var spInfo = k === "cartesian" ? fullLayout._plots[sp] : fullLayout[sp]; - for (j = 0; j < methods2.length; j++) { - methods2[j](gd, spInfo, sp); - } - } - } else { - for (j = 0; j < methods2.length; j++) { - methods2[j](gd); - } - } - } -} -plots$1.rehover = function(gd) { - if (gd._fullLayout._rehover) { - gd._fullLayout._rehover(); - } -}; -plots$1.redrag = function(gd) { - if (gd._fullLayout._redrag) { - gd._fullLayout._redrag(); - } -}; -plots$1.reselect = function(gd) { - var fullLayout = gd._fullLayout; - var A2 = (gd.layout || {}).selections; - var B2 = fullLayout._previousSelections; - fullLayout._previousSelections = A2; - var mayEmitSelected = fullLayout._reselect || JSON.stringify(A2) !== JSON.stringify(B2); - Registry$M.getComponentMethod("selections", "reselect")(gd, mayEmitSelected); -}; -plots$1.generalUpdatePerTraceModule = function(gd, subplot, subplotCalcData, subplotLayout) { - var traceHashOld = subplot.traceHash; - var traceHash = {}; - var i; - for (i = 0; i < subplotCalcData.length; i++) { - var calcTraces = subplotCalcData[i]; - var trace = calcTraces[0].trace; - if (trace.visible) { - traceHash[trace.type] = traceHash[trace.type] || []; - traceHash[trace.type].push(calcTraces); - } - } - for (var moduleNameOld in traceHashOld) { - if (!traceHash[moduleNameOld]) { - var fakeCalcTrace = traceHashOld[moduleNameOld][0]; - var fakeTrace = fakeCalcTrace[0].trace; - fakeTrace.visible = false; - traceHash[moduleNameOld] = [fakeCalcTrace]; - } - } - for (var moduleName in traceHash) { - var moduleCalcData = traceHash[moduleName]; - var _module = moduleCalcData[0][0].trace._module; - _module.plot(gd, subplot, Lib$1W.filterVisible(moduleCalcData), subplotLayout); - } - subplot.traceHash = traceHash; -}; -plots$1.plotBasePlot = function(desiredType, gd, traces, transitionOpts, makeOnCompleteCallback) { - var _module = Registry$M.getModule(desiredType); - var cdmodule = getModuleCalcData$1(gd.calcdata, _module)[0]; - _module.plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback); -}; -plots$1.cleanBasePlot = function(desiredType, newFullData, newFullLayout, oldFullData, oldFullLayout) { - var had = oldFullLayout._has && oldFullLayout._has(desiredType); - var has = newFullLayout._has && newFullLayout._has(desiredType); - if (had && !has) { - oldFullLayout["_" + desiredType + "layer"].selectAll("g.trace").remove(); - } -}; -var plotsExports = plots$2.exports; -var axes$1 = { exports: {} }; -var svg_text_utils = {}; -var xmlns_namespaces = {}; -(function(exports2) { - exports2.xmlns = "http://www.w3.org/2000/xmlns/"; - exports2.svg = "http://www.w3.org/2000/svg"; - exports2.xlink = "http://www.w3.org/1999/xlink"; - exports2.svgAttrs = { - xmlns: exports2.svg, - "xmlns:xlink": exports2.xlink - }; -})(xmlns_namespaces); -var alignment$1 = { - // from bottom left: this is the origin of our paper-reference - // positioning system - FROM_BL: { - left: 0, - center: 0.5, - right: 1, - bottom: 0, - middle: 0.5, - top: 1 - }, - // from top left: this is the screen pixel positioning origin - FROM_TL: { - left: 0, - center: 0.5, - right: 1, - bottom: 1, - middle: 0.5, - top: 0 - }, - // from bottom right: sometimes you just need the opposite of ^^ - FROM_BR: { - left: 1, - center: 0.5, - right: 0, - bottom: 0, - middle: 0.5, - top: 1 - }, - // multiple of fontSize to get the vertical offset between lines - LINE_SPACING: 1.3, - // multiple of fontSize to shift from the baseline - // to the cap (captical letter) line - // (to use when we don't calculate this shift from Drawing.bBox) - // This is an approximation since in reality cap height can differ - // from font to font. However, according to Wikipedia - // an "average" font might have a cap height of 70% of the em - // https://en.wikipedia.org/wiki/Em_(typography)#History - CAP_SHIFT: 0.7, - // half the cap height (distance between baseline and cap line) - // of an "average" font (for more info see above). - MID_SHIFT: 0.35, - OPPOSITE_SIDE: { - left: "right", - right: "left", - top: "bottom", - bottom: "top" - } -}; -(function(exports2) { - var d32 = d3Exports; - var Lib2 = libExports; - var strTranslate2 = Lib2.strTranslate; - var xmlnsNamespaces2 = xmlns_namespaces; - var LINE_SPACING2 = alignment$1.LINE_SPACING; - var FIND_TEX = /([^$]*)([$]+[^$]*[$]+)([^$]*)/; - exports2.convertToTspans = function(_context, gd, _callback) { - var str2 = _context.text(); - var tex = !_context.attr("data-notex") && gd && gd._context.typesetMath && typeof MathJax !== "undefined" && str2.match(FIND_TEX); - var parent = d32.select(_context.node().parentNode); - if (parent.empty()) return; - var svgClass = _context.attr("class") ? _context.attr("class").split(" ")[0] : "text"; - svgClass += "-math"; - parent.selectAll("svg." + svgClass).remove(); - parent.selectAll("g." + svgClass + "-group").remove(); - _context.style("display", null).attr({ - // some callers use data-unformatted *from the element* in 'cancel' - // so we need it here even if we're going to turn it into math - // these two (plus style and text-anchor attributes) form the key we're - // going to use for Drawing.bBox - "data-unformatted": str2, - "data-math": "N" - }); - function showText() { - if (!parent.empty()) { - svgClass = _context.attr("class") + "-math"; - parent.select("svg." + svgClass).remove(); - } - _context.text("").style("white-space", "pre"); - var hasLink = buildSVGText(_context.node(), str2); - if (hasLink) { - _context.style("pointer-events", "all"); - } - exports2.positionText(_context); - if (_callback) _callback.call(_context); - } - if (tex) { - (gd && gd._promises || []).push(new Promise(function(resolve) { - _context.style("display", "none"); - var fontSize = parseInt(_context.node().style.fontSize, 10); - var config = { fontSize }; - texToSVG(tex[2], config, function(_svgEl, _glyphDefs, _svgBBox) { - parent.selectAll("svg." + svgClass).remove(); - parent.selectAll("g." + svgClass + "-group").remove(); - var newSvg = _svgEl && _svgEl.select("svg"); - if (!newSvg || !newSvg.node()) { - showText(); - resolve(); - return; - } - var mathjaxGroup = parent.append("g").classed(svgClass + "-group", true).attr({ - "pointer-events": "none", - "data-unformatted": str2, - "data-math": "Y" - }); - mathjaxGroup.node().appendChild(newSvg.node()); - if (_glyphDefs && _glyphDefs.node()) { - newSvg.node().insertBefore( - _glyphDefs.node().cloneNode(true), - newSvg.node().firstChild - ); - } - var w0 = _svgBBox.width; - var h0 = _svgBBox.height; - newSvg.attr({ - class: svgClass, - height: h0, - preserveAspectRatio: "xMinYMin meet" - }).style({ overflow: "visible", "pointer-events": "none" }); - var fill = _context.node().style.fill || "black"; - var g = newSvg.select("g"); - g.attr({ fill, stroke: fill }); - var bb = g.node().getBoundingClientRect(); - var w = bb.width; - var h = bb.height; - if (w > w0 || h > h0) { - newSvg.style("overflow", "hidden"); - bb = newSvg.node().getBoundingClientRect(); - w = bb.width; - h = bb.height; - } - var x = +_context.attr("x"); - var y = +_context.attr("y"); - var textHeight = fontSize || _context.node().getBoundingClientRect().height; - var dy = -textHeight / 4; - if (svgClass[0] === "y") { - mathjaxGroup.attr({ - transform: "rotate(" + [-90, x, y] + ")" + strTranslate2(-w / 2, dy - h / 2) - }); - } else if (svgClass[0] === "l") { - y = dy - h / 2; - } else if (svgClass[0] === "a" && svgClass.indexOf("atitle") !== 0) { - x = 0; - y = dy; - } else { - var anchor = _context.attr("text-anchor"); - x = x - w * (anchor === "middle" ? 0.5 : anchor === "end" ? 1 : 0); - y = y + dy - h / 2; - } - newSvg.attr({ - x, - y - }); - if (_callback) _callback.call(_context, mathjaxGroup); - resolve(mathjaxGroup); - }); - })); - } else showText(); - return _context; - }; - var LT_MATCH = /(<|<|<)/g; - var GT_MATCH = /(>|>|>)/g; - function cleanEscapesForTex(s) { - return s.replace(LT_MATCH, "\\lt ").replace(GT_MATCH, "\\gt "); - } - var inlineMath = [["$", "$"], ["\\(", "\\)"]]; - function texToSVG(_texString, _config, _callback) { - var MathJaxVersion = parseInt( - (MathJax.version || "").split(".")[0] - ); - if (MathJaxVersion !== 2 && MathJaxVersion !== 3) { - Lib2.warn("No MathJax version:", MathJax.version); - return; - } - var originalRenderer, originalConfig, originalProcessSectionDelay, tmpDiv; - var setConfig2 = function() { - originalConfig = Lib2.extendDeepAll({}, MathJax.Hub.config); - originalProcessSectionDelay = MathJax.Hub.processSectionDelay; - if (MathJax.Hub.processSectionDelay !== void 0) { - MathJax.Hub.processSectionDelay = 0; - } - return MathJax.Hub.Config({ - messageStyle: "none", - tex2jax: { - inlineMath - }, - displayAlign: "left" - }); - }; - var setConfig3 = function() { - originalConfig = Lib2.extendDeepAll({}, MathJax.config); - if (!MathJax.config.tex) { - MathJax.config.tex = {}; - } - MathJax.config.tex.inlineMath = inlineMath; - }; - var setRenderer2 = function() { - originalRenderer = MathJax.Hub.config.menuSettings.renderer; - if (originalRenderer !== "SVG") { - return MathJax.Hub.setRenderer("SVG"); - } - }; - var setRenderer3 = function() { - originalRenderer = MathJax.config.startup.output; - if (originalRenderer !== "svg") { - MathJax.config.startup.output = "svg"; - } - }; - var initiateMathJax = function() { - var randomID = "math-output-" + Lib2.randstr({}, 64); - tmpDiv = d32.select("body").append("div").attr({ id: randomID }).style({ - visibility: "hidden", - position: "absolute", - "font-size": _config.fontSize + "px" - }).text(cleanEscapesForTex(_texString)); - var tmpNode = tmpDiv.node(); - return MathJaxVersion === 2 ? MathJax.Hub.Typeset(tmpNode) : MathJax.typeset([tmpNode]); - }; - var finalizeMathJax = function() { - var sel = tmpDiv.select( - MathJaxVersion === 2 ? ".MathJax_SVG" : ".MathJax" - ); - var node = !sel.empty() && tmpDiv.select("svg").node(); - if (!node) { - Lib2.log("There was an error in the tex syntax.", _texString); - _callback(); - } else { - var nodeBBox = node.getBoundingClientRect(); - var glyphDefs; - if (MathJaxVersion === 2) { - glyphDefs = d32.select("body").select("#MathJax_SVG_glyphs"); - } else { - glyphDefs = sel.select("defs"); - } - _callback(sel, glyphDefs, nodeBBox); - } - tmpDiv.remove(); - }; - var resetRenderer2 = function() { - if (originalRenderer !== "SVG") { - return MathJax.Hub.setRenderer(originalRenderer); - } - }; - var resetRenderer3 = function() { - if (originalRenderer !== "svg") { - MathJax.config.startup.output = originalRenderer; - } - }; - var resetConfig2 = function() { - if (originalProcessSectionDelay !== void 0) { - MathJax.Hub.processSectionDelay = originalProcessSectionDelay; - } - return MathJax.Hub.Config(originalConfig); - }; - var resetConfig3 = function() { - MathJax.config = originalConfig; - }; - if (MathJaxVersion === 2) { - MathJax.Hub.Queue( - setConfig2, - setRenderer2, - initiateMathJax, - finalizeMathJax, - resetRenderer2, - resetConfig2 - ); - } else if (MathJaxVersion === 3) { - setConfig3(); - setRenderer3(); - MathJax.startup.defaultReady(); - MathJax.startup.promise.then(function() { - initiateMathJax(); - finalizeMathJax(); - resetRenderer3(); - resetConfig3(); - }); - } - } - var TAG_STYLES = { - // would like to use baseline-shift for sub/sup but FF doesn't support it - // so we need to use dy along with the uber hacky shift-back-to - // baseline below - sup: "font-size:70%", - sub: "font-size:70%", - s: "text-decoration:line-through", - u: "text-decoration:underline", - b: "font-weight:bold", - i: "font-style:italic", - a: "cursor:pointer", - span: "", - em: "font-style:italic;font-weight:bold" - }; - var SHIFT_DY = { - sub: "0.3em", - sup: "-0.6em" - }; - var RESET_DY = { - sub: "-0.21em", - sup: "0.42em" - }; - var ZERO_WIDTH_SPACE = "​"; - var PROTOCOLS = ["http:", "https:", "mailto:", "", void 0, ":"]; - var NEWLINES = exports2.NEWLINES = /(\r\n?|\n)/g; - var SPLIT_TAGS = /(<[^<>]*>)/; - var ONE_TAG = /<(\/?)([^ >]*)(\s+(.*))?>/i; - var BR_TAG = //i; - exports2.BR_TAG_ALL = //gi; - var STYLEMATCH = /(^|[\s"'])style\s*=\s*("([^"]*);?"|'([^']*);?')/i; - var HREFMATCH = /(^|[\s"'])href\s*=\s*("([^"]*)"|'([^']*)')/i; - var TARGETMATCH = /(^|[\s"'])target\s*=\s*("([^"\s]*)"|'([^'\s]*)')/i; - var POPUPMATCH = /(^|[\s"'])popup\s*=\s*("([\w=,]*)"|'([\w=,]*)')/i; - function getQuotedMatch(_str, re2) { - if (!_str) return null; - var match = _str.match(re2); - var result = match && (match[3] || match[4]); - return result && convertEntities(result); - } - var COLORMATCH = /(^|;)\s*color:/; - exports2.plainText = function(_str, opts) { - opts = opts || {}; - var len = opts.len !== void 0 && opts.len !== -1 ? opts.len : Infinity; - var allowedTags = opts.allowedTags !== void 0 ? opts.allowedTags : ["br"]; - var ellipsis = "..."; - var eLen = ellipsis.length; - var oldParts = _str.split(SPLIT_TAGS); - var newParts = []; - var prevTag = ""; - var l = 0; - for (var i = 0; i < oldParts.length; i++) { - var p = oldParts[i]; - var match = p.match(ONE_TAG); - var tagType = match && match[2].toLowerCase(); - if (tagType) { - if (allowedTags.indexOf(tagType) !== -1) { - newParts.push(p); - prevTag = tagType; - } - } else { - var pLen = p.length; - if (l + pLen < len) { - newParts.push(p); - l += pLen; - } else if (l < len) { - var pLen2 = len - l; - if (prevTag && (prevTag !== "br" || pLen2 <= eLen || pLen <= eLen)) { - newParts.pop(); - } - if (len > eLen) { - newParts.push(p.substr(0, pLen2 - eLen) + ellipsis); - } else { - newParts.push(p.substr(0, pLen2)); - } - break; - } - prevTag = ""; - } - } - return newParts.join(""); - }; - var entityToUnicode = { - mu: "μ", - amp: "&", - lt: "<", - gt: ">", - nbsp: " ", - times: "×", - plusmn: "±", - deg: "°" - }; - var ENTITY_MATCH = /&(#\d+|#x[\da-fA-F]+|[a-z]+);/g; - function convertEntities(_str) { - return _str.replace(ENTITY_MATCH, function(fullMatch, innerMatch) { - var outChar; - if (innerMatch.charAt(0) === "#") { - outChar = fromCodePoint( - innerMatch.charAt(1) === "x" ? parseInt(innerMatch.substr(2), 16) : parseInt(innerMatch.substr(1), 10) - ); - } else outChar = entityToUnicode[innerMatch]; - return outChar || fullMatch; - }); - } - exports2.convertEntities = convertEntities; - function fromCodePoint(code2) { - if (code2 > 1114111) return; - var stringFromCodePoint = String.fromCodePoint; - if (stringFromCodePoint) return stringFromCodePoint(code2); - var stringFromCharCode = String.fromCharCode; - if (code2 <= 65535) return stringFromCharCode(code2); - return stringFromCharCode( - (code2 >> 10) + 55232, - code2 % 1024 + 56320 - ); - } - function buildSVGText(containerNode, str2) { - str2 = str2.replace(NEWLINES, " "); - var hasLink = false; - var nodeStack = []; - var currentNode; - var currentLine = -1; - function newLine() { - currentLine++; - var lineNode = document.createElementNS(xmlnsNamespaces2.svg, "tspan"); - d32.select(lineNode).attr({ - class: "line", - dy: currentLine * LINE_SPACING2 + "em" - }); - containerNode.appendChild(lineNode); - currentNode = lineNode; - var oldNodeStack = nodeStack; - nodeStack = [{ node: lineNode }]; - if (oldNodeStack.length > 1) { - for (var i2 = 1; i2 < oldNodeStack.length; i2++) { - enterNode(oldNodeStack[i2]); - } - } - } - function enterNode(nodeSpec2) { - var type = nodeSpec2.type; - var nodeAttrs = {}; - var nodeType; - if (type === "a") { - nodeType = "a"; - var target = nodeSpec2.target; - var href2 = nodeSpec2.href; - var popup = nodeSpec2.popup; - if (href2) { - nodeAttrs = { - "xlink:xlink:show": target === "_blank" || target.charAt(0) !== "_" ? "new" : "replace", - target, - "xlink:xlink:href": href2 - }; - if (popup) { - nodeAttrs.onclick = 'window.open(this.href.baseVal,this.target.baseVal,"' + popup + '");return false;'; - } - } - } else nodeType = "tspan"; - if (nodeSpec2.style) nodeAttrs.style = nodeSpec2.style; - var newNode = document.createElementNS(xmlnsNamespaces2.svg, nodeType); - if (type === "sup" || type === "sub") { - addTextNode(currentNode, ZERO_WIDTH_SPACE); - currentNode.appendChild(newNode); - var resetter = document.createElementNS(xmlnsNamespaces2.svg, "tspan"); - addTextNode(resetter, ZERO_WIDTH_SPACE); - d32.select(resetter).attr("dy", RESET_DY[type]); - nodeAttrs.dy = SHIFT_DY[type]; - currentNode.appendChild(newNode); - currentNode.appendChild(resetter); - } else { - currentNode.appendChild(newNode); - } - d32.select(newNode).attr(nodeAttrs); - currentNode = nodeSpec2.node = newNode; - nodeStack.push(nodeSpec2); - } - function addTextNode(node, text) { - node.appendChild(document.createTextNode(text)); - } - function exitNode(type) { - if (nodeStack.length === 1) { - Lib2.log("Ignoring unexpected end tag .", str2); - return; - } - var innerNode = nodeStack.pop(); - if (type !== innerNode.type) { - Lib2.log("Start tag <" + innerNode.type + "> doesnt match end tag <" + type + ">. Pretending it did match.", str2); - } - currentNode = nodeStack[nodeStack.length - 1].node; - } - var hasLines = BR_TAG.test(str2); - if (hasLines) newLine(); - else { - currentNode = containerNode; - nodeStack = [{ node: containerNode }]; - } - var parts = str2.split(SPLIT_TAGS); - for (var i = 0; i < parts.length; i++) { - var parti = parts[i]; - var match = parti.match(ONE_TAG); - var tagType = match && match[2].toLowerCase(); - var tagStyle = TAG_STYLES[tagType]; - if (tagType === "br") { - newLine(); - } else if (tagStyle === void 0) { - addTextNode(currentNode, convertEntities(parti)); - } else { - if (match[1]) { - exitNode(tagType); - } else { - var extra = match[4]; - var nodeSpec = { type: tagType }; - var css = getQuotedMatch(extra, STYLEMATCH); - if (css) { - css = css.replace(COLORMATCH, "$1 fill:"); - if (tagStyle) css += ";" + tagStyle; - } else if (tagStyle) css = tagStyle; - if (css) nodeSpec.style = css; - if (tagType === "a") { - hasLink = true; - var href = getQuotedMatch(extra, HREFMATCH); - if (href) { - var safeHref = sanitizeHref(href); - if (safeHref) { - nodeSpec.href = safeHref; - nodeSpec.target = getQuotedMatch(extra, TARGETMATCH) || "_blank"; - nodeSpec.popup = getQuotedMatch(extra, POPUPMATCH); - } - } - } - enterNode(nodeSpec); - } - } - } - return hasLink; - } - function sanitizeHref(href) { - var decodedHref = encodeURI(decodeURI(href)); - var dummyAnchor1 = document.createElement("a"); - var dummyAnchor2 = document.createElement("a"); - dummyAnchor1.href = href; - dummyAnchor2.href = decodedHref; - var p1 = dummyAnchor1.protocol; - var p2 = dummyAnchor2.protocol; - if (PROTOCOLS.indexOf(p1) !== -1 && PROTOCOLS.indexOf(p2) !== -1) { - return decodedHref; - } else { - return ""; - } - } - exports2.sanitizeHTML = function sanitizeHTML(str2) { - str2 = str2.replace(NEWLINES, " "); - var rootNode = document.createElement("p"); - var currentNode = rootNode; - var nodeStack = []; - var parts = str2.split(SPLIT_TAGS); - for (var i = 0; i < parts.length; i++) { - var parti = parts[i]; - var match = parti.match(ONE_TAG); - var tagType = match && match[2].toLowerCase(); - if (tagType in TAG_STYLES) { - if (match[1]) { - if (nodeStack.length) { - currentNode = nodeStack.pop(); - } - } else { - var extra = match[4]; - var css = getQuotedMatch(extra, STYLEMATCH); - var nodeAttrs = css ? { style: css } : {}; - if (tagType === "a") { - var href = getQuotedMatch(extra, HREFMATCH); - if (href) { - var safeHref = sanitizeHref(href); - if (safeHref) { - nodeAttrs.href = safeHref; - var target = getQuotedMatch(extra, TARGETMATCH); - if (target) { - nodeAttrs.target = target; - } - } - } - } - var newNode = document.createElement(tagType); - currentNode.appendChild(newNode); - d32.select(newNode).attr(nodeAttrs); - currentNode = newNode; - nodeStack.push(newNode); - } - } else { - currentNode.appendChild( - document.createTextNode(convertEntities(parti)) - ); - } - } - var key = "innerHTML"; - return rootNode[key]; - }; - exports2.lineCount = function lineCount(s) { - return s.selectAll("tspan.line").size() || 1; - }; - exports2.positionText = function positionText(s, x, y) { - return s.each(function() { - var text = d32.select(this); - function setOrGet(attr, val) { - if (val === void 0) { - val = text.attr(attr); - if (val === null) { - text.attr(attr, 0); - val = 0; - } - } else text.attr(attr, val); - return val; - } - var thisX = setOrGet("x", x); - var thisY = setOrGet("y", y); - if (this.nodeName === "text") { - text.selectAll("tspan.line").attr({ x: thisX, y: thisY }); - } - }); - }; - function alignHTMLWith(_base, container, options) { - var alignH = options.horizontalAlign; - var alignV = options.verticalAlign || "top"; - var bRect = _base.node().getBoundingClientRect(); - var cRect = container.node().getBoundingClientRect(); - var thisRect; - var getTop; - var getLeft; - if (alignV === "bottom") { - getTop = function() { - return bRect.bottom - thisRect.height; - }; - } else if (alignV === "middle") { - getTop = function() { - return bRect.top + (bRect.height - thisRect.height) / 2; - }; - } else { - getTop = function() { - return bRect.top; - }; - } - if (alignH === "right") { - getLeft = function() { - return bRect.right - thisRect.width; - }; - } else if (alignH === "center") { - getLeft = function() { - return bRect.left + (bRect.width - thisRect.width) / 2; - }; - } else { - getLeft = function() { - return bRect.left; - }; - } - return function() { - thisRect = this.node().getBoundingClientRect(); - var x0 = getLeft() - cRect.left; - var y0 = getTop() - cRect.top; - var gd = options.gd || {}; - if (options.gd) { - gd._fullLayout._calcInverseTransform(gd); - var transformedCoords = Lib2.apply3DTransform(gd._fullLayout._invTransform)(x0, y0); - x0 = transformedCoords[0]; - y0 = transformedCoords[1]; - } - this.style({ - top: y0 + "px", - left: x0 + "px", - "z-index": 1e3 - }); - return this; - }; - } - var onePx = "1px "; - exports2.makeTextShadow = function(color2) { - var x = onePx; - var y = onePx; - var b = onePx; - return x + y + b + color2 + ", -" + x + "-" + y + b + color2 + ", " + x + "-" + y + b + color2 + ", -" + x + y + b + color2; - }; - exports2.makeEditable = function(context2, options) { - var gd = options.gd; - var _delegate = options.delegate; - var dispatch = d32.dispatch("edit", "input", "cancel"); - var handlerElement = _delegate || context2; - context2.style({ "pointer-events": _delegate ? "none" : "all" }); - if (context2.size() !== 1) throw new Error("boo"); - function handleClick3() { - appendEditable(); - context2.style({ opacity: 0 }); - var svgClass = handlerElement.attr("class"); - var mathjaxClass; - if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group"; - else mathjaxClass = "[class*=-math-group]"; - if (mathjaxClass) { - d32.select(context2.node().parentNode).select(mathjaxClass).style({ opacity: 0 }); - } - } - function selectElementContents(_el) { - var el = _el.node(); - var range = document.createRange(); - range.selectNodeContents(el); - var sel = window.getSelection(); - sel.removeAllRanges(); - sel.addRange(range); - el.focus(); - } - function appendEditable() { - var plotDiv = d32.select(gd); - var container = plotDiv.select(".svg-container"); - var div = container.append("div"); - var cStyle = context2.node().style; - var fontSize = parseFloat(cStyle.fontSize || 12); - var initialText = options.text; - if (initialText === void 0) initialText = context2.attr("data-unformatted"); - div.classed("plugin-editable editable", true).style({ - position: "absolute", - "font-family": cStyle.fontFamily || "Arial", - "font-size": fontSize, - color: options.fill || cStyle.fill || "black", - opacity: 1, - "background-color": options.background || "transparent", - outline: "#ffffff33 1px solid", - margin: [-fontSize / 8 + 1, 0, 0, -1].join("px ") + "px", - padding: "0", - "box-sizing": "border-box" - }).attr({ contenteditable: true }).text(initialText).call(alignHTMLWith(context2, container, options)).on("blur", function() { - gd._editing = false; - context2.text(this.textContent).style({ opacity: 1 }); - var svgClass = d32.select(this).attr("class"); - var mathjaxClass; - if (svgClass) mathjaxClass = "." + svgClass.split(" ")[0] + "-math-group"; - else mathjaxClass = "[class*=-math-group]"; - if (mathjaxClass) { - d32.select(context2.node().parentNode).select(mathjaxClass).style({ opacity: 0 }); - } - var text = this.textContent; - d32.select(this).transition().duration(0).remove(); - d32.select(document).on("mouseup", null); - dispatch.edit.call(context2, text); - }).on("focus", function() { - var editDiv = this; - gd._editing = true; - d32.select(document).on("mouseup", function() { - if (d32.event.target === editDiv) return false; - if (document.activeElement === div.node()) div.node().blur(); - }); - }).on("keyup", function() { - if (d32.event.which === 27) { - gd._editing = false; - context2.style({ opacity: 1 }); - d32.select(this).style({ opacity: 0 }).on("blur", function() { - return false; - }).transition().remove(); - dispatch.cancel.call(context2, this.textContent); - } else { - dispatch.input.call(context2, this.textContent); - d32.select(this).call(alignHTMLWith(context2, container, options)); - } - }).on("keydown", function() { - if (d32.event.which === 13) this.blur(); - }).call(selectElementContents); - } - if (options.immediate) handleClick3(); - else handlerElement.on("click", handleClick3); - return d32.rebind(context2, dispatch, "on"); - }; -})(svg_text_utils); -var drawing$1 = { exports: {} }; -var d3$A = d3Exports; -var tinycolor$5 = tinycolorExports; -var isNumeric$t = fastIsnumeric; -var Lib$1V = libExports; -var Color$K = colorExports; -var isValidScale$1 = scales_1.isValid; -function hasColorscale$7(trace, containerStr, colorKey) { - var container = containerStr ? Lib$1V.nestedProperty(trace, containerStr).get() || {} : trace; - var color2 = container[colorKey || "color"]; - if (color2 && color2._inputArray) color2 = color2._inputArray; - var isArrayWithOneNumber = false; - if (Lib$1V.isArrayOrTypedArray(color2)) { - for (var i = 0; i < color2.length; i++) { - if (isNumeric$t(color2[i])) { - isArrayWithOneNumber = true; - break; - } - } - } - return Lib$1V.isPlainObject(container) && (isArrayWithOneNumber || container.showscale === true || isNumeric$t(container.cmin) && isNumeric$t(container.cmax) || isValidScale$1(container.colorscale) || Lib$1V.isPlainObject(container.colorbar)); -} -var constantAttrs = ["showscale", "autocolorscale", "colorscale", "reversescale", "colorbar"]; -var letterAttrs = ["min", "max", "mid", "auto"]; -function extractOpts$3(cont) { - var colorAx = cont._colorAx; - var cont2 = colorAx ? colorAx : cont; - var out = {}; - var cLetter; - var i, k; - for (i = 0; i < constantAttrs.length; i++) { - k = constantAttrs[i]; - out[k] = cont2[k]; - } - if (colorAx) { - cLetter = "c"; - for (i = 0; i < letterAttrs.length; i++) { - k = letterAttrs[i]; - out[k] = cont2["c" + k]; - } - } else { - var k2; - for (i = 0; i < letterAttrs.length; i++) { - k = letterAttrs[i]; - k2 = "c" + k; - if (k2 in cont2) { - out[k] = cont2[k2]; - continue; - } - k2 = "z" + k; - if (k2 in cont2) { - out[k] = cont2[k2]; - } - } - cLetter = k2.charAt(0); - } - out._sync = function(k3, v) { - var k22 = letterAttrs.indexOf(k3) !== -1 ? cLetter + k3 : k3; - cont2[k22] = cont2["_" + k22] = v; - }; - return out; -} -function extractScale(cont) { - var cOpts = extractOpts$3(cont); - var cmin = cOpts.min; - var cmax = cOpts.max; - var scl = cOpts.reversescale ? flipScale$1(cOpts.colorscale) : cOpts.colorscale; - var N = scl.length; - var domain2 = new Array(N); - var range = new Array(N); - for (var i = 0; i < N; i++) { - var si = scl[i]; - domain2[i] = cmin + si[0] * (cmax - cmin); - range[i] = si[1]; - } - return { domain: domain2, range }; -} -function flipScale$1(scl) { - var N = scl.length; - var sclNew = new Array(N); - for (var i = N - 1, j = 0; i >= 0; i--, j++) { - var si = scl[i]; - sclNew[j] = [1 - si[0], si[1]]; - } - return sclNew; -} -function makeColorScaleFunc(specs, opts) { - opts = opts || {}; - var domain2 = specs.domain; - var range = specs.range; - var N = range.length; - var _range = new Array(N); - for (var i = 0; i < N; i++) { - var rgba3 = tinycolor$5(range[i]).toRgb(); - _range[i] = [rgba3.r, rgba3.g, rgba3.b, rgba3.a]; - } - var _sclFunc = d3$A.scale.linear().domain(domain2).range(_range).clamp(true); - var noNumericCheck = opts.noNumericCheck; - var returnArray = opts.returnArray; - var sclFunc; - if (noNumericCheck && returnArray) { - sclFunc = _sclFunc; - } else if (noNumericCheck) { - sclFunc = function(v) { - return colorArray2rbga(_sclFunc(v)); - }; - } else if (returnArray) { - sclFunc = function(v) { - if (isNumeric$t(v)) return _sclFunc(v); - else if (tinycolor$5(v).isValid()) return v; - else return Color$K.defaultLine; - }; - } else { - sclFunc = function(v) { - if (isNumeric$t(v)) return colorArray2rbga(_sclFunc(v)); - else if (tinycolor$5(v).isValid()) return v; - else return Color$K.defaultLine; - }; - } - sclFunc.domain = _sclFunc.domain; - sclFunc.range = function() { - return range; - }; - return sclFunc; -} -function makeColorScaleFuncFromTrace(trace, opts) { - return makeColorScaleFunc(extractScale(trace), opts); -} -function colorArray2rbga(colorArray) { - var colorObj = { - r: colorArray[0], - g: colorArray[1], - b: colorArray[2], - a: colorArray[3] - }; - return tinycolor$5(colorObj).toRgbString(); -} -var helpers$L = { - hasColorscale: hasColorscale$7, - extractOpts: extractOpts$3, - extractScale, - flipScale: flipScale$1, - makeColorScaleFunc, - makeColorScaleFuncFromTrace -}; -var docs = docs$2; -var FORMAT_LINK = docs.FORMAT_LINK; -var DATE_FORMAT_LINK = docs.DATE_FORMAT_LINK; -function axisHoverFormat$5(x, noDates) { - return { - valType: "string", - dflt: "", - editType: "none", - description: (noDates ? descriptionOnlyNumbers : descriptionWithDates$1)("hover text", x) + [ - "By default the values are formatted using " + (noDates ? "generic number format" : "`" + x + "axis.hoverformat`") + "." - ].join(" ") - }; -} -function descriptionOnlyNumbers(label, x) { - return [ - "Sets the " + label + " formatting rule" + (x ? "for `" + x + "` " : ""), - "using d3 formatting mini-languages", - "which are very similar to those in Python. For numbers, see: " + FORMAT_LINK + "." - ].join(" "); -} -function descriptionWithDates$1(label, x) { - return descriptionOnlyNumbers(label, x) + [ - " And for dates see: " + DATE_FORMAT_LINK + ".", - "We add two items to d3's date formatter:", - "*%h* for half of the year as a decimal number as well as", - "*%{n}f* for fractional seconds", - "with n digits. For example, *2016-10-13 09:15:23.456* with tickformat", - "*%H~%M~%S.%2f* would display *09~15~23.46*" - ].join(" "); -} -var axis_format_attributes = { - axisHoverFormat: axisHoverFormat$5, - descriptionWithDates: descriptionWithDates$1 -}; -var fontAttrs$c = font_attributes; -var colorAttrs$5 = attributes$N; -var dash$4 = attributes$M.dash; -var extendFlat$g = extend$5.extendFlat; -var templatedArray$8 = plot_template.templatedArray; -var descriptionWithDates = axis_format_attributes.descriptionWithDates; -var ONEDAY$3 = numerical.ONEDAY; -var constants$T = constants$U; -var HOUR$1 = constants$T.HOUR_PATTERN; -var DAY_OF_WEEK$1 = constants$T.WEEKDAY_PATTERN; -var minorTickmode = { - valType: "enumerated", - values: ["auto", "linear", "array"], - editType: "ticks", - impliedEdits: { tick0: void 0, dtick: void 0 }, - description: [ - "Sets the tick mode for this axis.", - "If *auto*, the number of ticks is set via `nticks`.", - "If *linear*, the placement of the ticks is determined by", - "a starting position `tick0` and a tick step `dtick`", - "(*linear* is the default value if `tick0` and `dtick` are provided).", - "If *array*, the placement of the ticks is set via `tickvals`", - "and the tick text is `ticktext`.", - "(*array* is the default value if `tickvals` is provided)." - ].join(" ") -}; -var tickmode = extendFlat$g({}, minorTickmode, { - values: minorTickmode.values.slice().concat(["sync"]), - description: [ - minorTickmode.description, - "If *sync*, the number of ticks will sync with the overlayed axis", - "set by `overlaying` property." - ].join(" ") -}); -function makeNticks(minor) { - return { - valType: "integer", - min: 0, - dflt: minor ? 5 : 0, - editType: "ticks", - description: [ - "Specifies the maximum number of ticks for the particular axis.", - "The actual number of ticks will be chosen automatically to be", - "less than or equal to `nticks`.", - "Has an effect only if `tickmode` is set to *auto*." - ].join(" ") - }; -} -var tick0 = { - valType: "any", - editType: "ticks", - impliedEdits: { tickmode: "linear" }, - description: [ - "Sets the placement of the first tick on this axis.", - "Use with `dtick`.", - "If the axis `type` is *log*, then you must take the log of your starting tick", - "(e.g. to set the starting tick to 100, set the `tick0` to 2)", - "except when `dtick`=*L* (see `dtick` for more info).", - "If the axis `type` is *date*, it should be a date string, like date data.", - "If the axis `type` is *category*, it should be a number, using the scale where", - "each category is assigned a serial number from zero in the order it appears." - ].join(" ") -}; -var dtick = { - valType: "any", - editType: "ticks", - impliedEdits: { tickmode: "linear" }, - description: [ - "Sets the step in-between ticks on this axis. Use with `tick0`.", - "Must be a positive number, or special strings available to *log* and *date* axes.", - "If the axis `type` is *log*, then ticks are set every 10^(n*dtick) where n", - "is the tick number. For example,", - "to set a tick mark at 1, 10, 100, 1000, ... set dtick to 1.", - "To set tick marks at 1, 100, 10000, ... set dtick to 2.", - "To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), or 0.69897000433.", - "*log* has several special values; *L*, where `f` is a positive number,", - "gives ticks linearly spaced in value (but not position).", - "For example `tick0` = 0.1, `dtick` = *L0.5* will put ticks at 0.1, 0.6, 1.1, 1.6 etc.", - "To show powers of 10 plus small digits between, use *D1* (all digits) or *D2* (only 2 and 5).", - "`tick0` is ignored for *D1* and *D2*.", - "If the axis `type` is *date*, then you must convert the time to milliseconds.", - "For example, to set the interval between ticks to one day,", - "set `dtick` to 86400000.0.", - "*date* also has special values *M* gives ticks spaced by a number of months.", - "`n` must be a positive integer.", - "To set ticks on the 15th of every third month, set `tick0` to *2000-01-15* and `dtick` to *M3*.", - "To set ticks every 4 years, set `dtick` to *M48*" - ].join(" ") -}; -var tickvals = { - valType: "data_array", - editType: "ticks", - description: [ - "Sets the values at which ticks on this axis appear.", - "Only has an effect if `tickmode` is set to *array*.", - "Used with `ticktext`." - ].join(" ") -}; -var ticks = { - valType: "enumerated", - values: ["outside", "inside", ""], - editType: "ticks", - description: [ - "Determines whether ticks are drawn or not.", - "If **, this axis' ticks are not drawn.", - "If *outside* (*inside*), this axis' are drawn outside (inside)", - "the axis lines." - ].join(" ") -}; -function makeTicklen(minor) { - var obj = { - valType: "number", - min: 0, - editType: "ticks", - description: "Sets the tick length (in px)." - }; - if (!minor) obj.dflt = 5; - return obj; -} -function makeTickwidth(minor) { - var obj = { - valType: "number", - min: 0, - editType: "ticks", - description: "Sets the tick width (in px)." - }; - if (!minor) obj.dflt = 1; - return obj; -} -var tickcolor = { - valType: "color", - dflt: colorAttrs$5.defaultLine, - editType: "ticks", - description: "Sets the tick color." -}; -var gridcolor = { - valType: "color", - dflt: colorAttrs$5.lightLine, - editType: "ticks", - description: "Sets the color of the grid lines." -}; -function makeGridwidth(minor) { - var obj = { - valType: "number", - min: 0, - editType: "ticks", - description: "Sets the width (in px) of the grid lines." - }; - if (!minor) obj.dflt = 1; - return obj; -} -var griddash = extendFlat$g({}, dash$4, { editType: "ticks" }); -var showgrid = { - valType: "boolean", - editType: "ticks", - description: [ - "Determines whether or not grid lines are drawn.", - "If *true*, the grid lines are drawn at every tick mark." - ].join(" ") -}; -var layout_attributes$4 = { - visible: { - valType: "boolean", - editType: "plot", - description: [ - "A single toggle to hide the axis while preserving interaction like dragging.", - "Default is true when a cheater plot is present on the axis, otherwise", - "false" - ].join(" ") - }, - color: { - valType: "color", - dflt: colorAttrs$5.defaultLine, - editType: "ticks", - description: [ - "Sets default for all colors associated with this axis", - "all at once: line, font, tick, and grid colors.", - "Grid color is lightened by blending this with the plot background", - "Individual pieces can override this." - ].join(" ") - }, - title: { - text: { - valType: "string", - editType: "ticks", - description: [ - "Sets the title of this axis.", - "Note that before the existence of `title.text`, the title's", - "contents used to be defined as the `title` attribute itself.", - "This behavior has been deprecated." - ].join(" ") - }, - font: fontAttrs$c({ - editType: "ticks", - description: [ - "Sets this axis' title font.", - "Note that the title's font used to be customized", - "by the now deprecated `titlefont` attribute." - ].join(" ") - }), - standoff: { - valType: "number", - min: 0, - editType: "ticks", - description: [ - "Sets the standoff distance (in px) between the axis labels and the title text", - "The default value is a function of the axis tick labels, the title `font.size`", - "and the axis `linewidth`.", - "Note that the axis title position is always constrained within the margins,", - "so the actual standoff distance is always less than the set or default value.", - "By setting `standoff` and turning on `automargin`, plotly.js will push the", - "margins to fit the axis title at given standoff distance." - ].join(" ") - }, - editType: "ticks" - }, - type: { - valType: "enumerated", - // '-' means we haven't yet run autotype or couldn't find any data - // it gets turned into linear in gd._fullLayout but not copied back - // to gd.data like the others are. - values: ["-", "linear", "log", "date", "category", "multicategory"], - dflt: "-", - editType: "calc", - // we forget when an axis has been autotyped, just writing the auto - // value back to the input - so it doesn't make sense to template this. - // Note: we do NOT prohibit this in `coerce`, so if someone enters a - // type in the template explicitly it will be honored as the default. - _noTemplating: true, - description: [ - "Sets the axis type.", - "By default, plotly attempts to determined the axis type", - "by looking into the data of the traces that referenced", - "the axis in question." - ].join(" ") - }, - autotypenumbers: { - valType: "enumerated", - values: ["convert types", "strict"], - dflt: "convert types", - editType: "calc", - description: [ - "Using *strict* a numeric string in trace data is not converted to a number.", - "Using *convert types* a numeric string in trace data may be", - "treated as a number during automatic axis `type` detection.", - "Defaults to layout.autotypenumbers." - ].join(" ") - }, - autorange: { - valType: "enumerated", - values: [true, false, "reversed", "min reversed", "max reversed", "min", "max"], - dflt: true, - editType: "axrange", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Determines whether or not the range of this axis is", - "computed in relation to the input data.", - "See `rangemode` for more info.", - "If `range` is provided and it has a value for both the", - "lower and upper bound, `autorange` is set to *false*.", - "Using *min* applies autorange only to set the minimum.", - "Using *max* applies autorange only to set the maximum.", - "Using *min reversed* applies autorange only to set the minimum on a reversed axis.", - "Using *max reversed* applies autorange only to set the maximum on a reversed axis.", - "Using *reversed* applies autorange on both ends and reverses the axis direction." - ].join(" ") - }, - autorangeoptions: { - minallowed: { - valType: "any", - editType: "plot", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Use this value exactly as autorange minimum." - ].join(" ") - }, - maxallowed: { - valType: "any", - editType: "plot", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Use this value exactly as autorange maximum." - ].join(" ") - }, - clipmin: { - valType: "any", - editType: "plot", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Clip autorange minimum if it goes beyond this value.", - "Has no effect when `autorangeoptions.minallowed` is provided." - ].join(" ") - }, - clipmax: { - valType: "any", - editType: "plot", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Clip autorange maximum if it goes beyond this value.", - "Has no effect when `autorangeoptions.maxallowed` is provided." - ].join(" ") - }, - include: { - valType: "any", - arrayOk: true, - editType: "plot", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Ensure this value is included in autorange." - ].join(" ") - }, - editType: "plot" - }, - rangemode: { - valType: "enumerated", - values: ["normal", "tozero", "nonnegative"], - dflt: "normal", - editType: "plot", - description: [ - "If *normal*, the range is computed in relation to the extrema", - "of the input data.", - "If *tozero*`, the range extends to 0,", - "regardless of the input data", - "If *nonnegative*, the range is non-negative,", - "regardless of the input data.", - "Applies only to linear axes." - ].join(" ") - }, - range: { - valType: "info_array", - items: [ - { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true }, - { valType: "any", editType: "axrange", impliedEdits: { "^autorange": false }, anim: true } - ], - editType: "axrange", - impliedEdits: { autorange: false }, - anim: true, - description: [ - "Sets the range of this axis.", - "If the axis `type` is *log*, then you must take the log of your", - "desired range (e.g. to set the range from 1 to 100,", - "set the range from 0 to 2).", - "If the axis `type` is *date*, it should be date strings,", - "like date data, though Date objects and unix milliseconds", - "will be accepted and converted to strings.", - "If the axis `type` is *category*, it should be numbers,", - "using the scale where each category is assigned a serial", - "number from zero in the order it appears.", - "Leaving either or both elements `null` impacts the default `autorange`." - ].join(" ") - }, - minallowed: { - valType: "any", - editType: "plot", - impliedEdits: { "^autorange": false }, - description: [ - "Determines the minimum range of this axis." - ].join(" ") - }, - maxallowed: { - valType: "any", - editType: "plot", - impliedEdits: { "^autorange": false }, - description: [ - "Determines the maximum range of this axis." - ].join(" ") - }, - fixedrange: { - valType: "boolean", - dflt: false, - editType: "calc", - description: [ - "Determines whether or not this axis is zoom-able.", - "If true, then zoom is disabled." - ].join(" ") - }, - insiderange: { - valType: "info_array", - items: [ - { valType: "any", editType: "plot" }, - { valType: "any", editType: "plot" } - ], - editType: "plot", - description: [ - "Could be used to set the desired inside range of this axis", - "(excluding the labels) when `ticklabelposition` of", - "the anchored axis has *inside*.", - "Not implemented for axes with `type` *log*.", - "This would be ignored when `range` is provided." - ].join(" ") - }, - // scaleanchor: not used directly, just put here for reference - // values are any opposite-letter axis id, or `false`. - scaleanchor: { - valType: "enumerated", - values: [ - constants$T.idRegex.x.toString(), - constants$T.idRegex.y.toString(), - false - ], - editType: "plot", - description: [ - "If set to another axis id (e.g. `x2`, `y`), the range of this axis", - "changes together with the range of the corresponding axis", - "such that the scale of pixels per unit is in a constant ratio.", - "Both axes are still zoomable, but when you zoom one, the other will", - "zoom the same amount, keeping a fixed midpoint.", - "`constrain` and `constraintoward` determine how we enforce the constraint.", - "You can chain these, ie `yaxis: {scaleanchor: *x*}, xaxis2: {scaleanchor: *y*}`", - "but you can only link axes of the same `type`.", - "The linked axis can have the opposite letter (to constrain the aspect ratio)", - "or the same letter (to match scales across subplots).", - "Loops (`yaxis: {scaleanchor: *x*}, xaxis: {scaleanchor: *y*}` or longer) are redundant", - "and the last constraint encountered will be ignored to avoid possible", - "inconsistent constraints via `scaleratio`.", - "Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint", - "is currently forbidden.", - "Setting `false` allows to remove a default constraint (occasionally,", - "you may need to prevent a default `scaleanchor` constraint from", - 'being applied, eg. when having an image trace `yaxis: {scaleanchor: "x"}`', - "is set automatically in order for pixels to be rendered as squares,", - "setting `yaxis: {scaleanchor: false}` allows to remove the constraint)." - ].join(" ") - }, - scaleratio: { - valType: "number", - min: 0, - dflt: 1, - editType: "plot", - description: [ - "If this axis is linked to another by `scaleanchor`, this determines the pixel", - "to unit scale ratio. For example, if this value is 10, then every unit on", - "this axis spans 10 times the number of pixels as a unit on the linked axis.", - "Use this for example to create an elevation profile where the vertical scale", - "is exaggerated a fixed amount with respect to the horizontal." - ].join(" ") - }, - constrain: { - valType: "enumerated", - values: ["range", "domain"], - editType: "plot", - description: [ - "If this axis needs to be compressed (either due to its own `scaleanchor` and", - "`scaleratio` or those of the other axis), determines how that happens:", - "by increasing the *range*, or by decreasing the *domain*.", - "Default is *domain* for axes containing image traces, *range* otherwise." - ].join(" ") - }, - // constraintoward: not used directly, just put here for reference - constraintoward: { - valType: "enumerated", - values: ["left", "center", "right", "top", "middle", "bottom"], - editType: "plot", - description: [ - "If this axis needs to be compressed (either due to its own `scaleanchor` and", - "`scaleratio` or those of the other axis), determines which direction we push", - "the originally specified plot area. Options are *left*, *center* (default),", - "and *right* for x axes, and *top*, *middle* (default), and *bottom* for y axes." - ].join(" ") - }, - matches: { - valType: "enumerated", - values: [ - constants$T.idRegex.x.toString(), - constants$T.idRegex.y.toString() - ], - editType: "calc", - description: [ - "If set to another axis id (e.g. `x2`, `y`), the range of this axis", - "will match the range of the corresponding axis in data-coordinates space.", - "Moreover, matching axes share auto-range values, category lists and", - "histogram auto-bins.", - "Note that setting axes simultaneously in both a `scaleanchor` and a `matches` constraint", - "is currently forbidden.", - "Moreover, note that matching axes must have the same `type`." - ].join(" ") - }, - rangebreaks: templatedArray$8("rangebreak", { - enabled: { - valType: "boolean", - dflt: true, - editType: "calc", - description: [ - "Determines whether this axis rangebreak is enabled or disabled.", - "Please note that `rangebreaks` only work for *date* axis type." - ].join(" ") - }, - bounds: { - valType: "info_array", - items: [ - { valType: "any", editType: "calc" }, - { valType: "any", editType: "calc" } - ], - editType: "calc", - description: [ - "Sets the lower and upper bounds of this axis rangebreak.", - "Can be used with `pattern`." - ].join(" ") - }, - pattern: { - valType: "enumerated", - values: [DAY_OF_WEEK$1, HOUR$1, ""], - editType: "calc", - description: [ - "Determines a pattern on the time line that generates breaks.", - "If *" + DAY_OF_WEEK$1 + "* - days of the week in English e.g. 'Sunday' or `sun`", - "(matching is case-insensitive and considers only the first three characters),", - "as well as Sunday-based integers between 0 and 6.", - "If *" + HOUR$1 + "* - hour (24-hour clock) as decimal numbers between 0 and 24.", - "for more info.", - "Examples:", - "- { pattern: '" + DAY_OF_WEEK$1 + "', bounds: [6, 1] }", - " or simply { bounds: ['sat', 'mon'] }", - " breaks from Saturday to Monday (i.e. skips the weekends).", - "- { pattern: '" + HOUR$1 + "', bounds: [17, 8] }", - " breaks from 5pm to 8am (i.e. skips non-work hours)." - ].join(" ") - }, - values: { - valType: "info_array", - freeLength: true, - editType: "calc", - items: { - valType: "any", - editType: "calc" - }, - description: [ - "Sets the coordinate values corresponding to the rangebreaks.", - "An alternative to `bounds`.", - "Use `dvalue` to set the size of the values along the axis." - ].join(" ") - }, - dvalue: { - // TODO could become 'any' to add support for 'months', 'years' - valType: "number", - editType: "calc", - min: 0, - dflt: ONEDAY$3, - description: [ - "Sets the size of each `values` item.", - "The default is one day in milliseconds." - ].join(" ") - }, - /* - gap: { - valType: 'number', - min: 0, - dflt: 0, // for *date* axes, maybe something else for *linear* - editType: 'calc', - description: [ - 'Sets the gap distance between the start and the end of this rangebreak.', - 'Use with `gapmode` to set the unit of measurement.' - ].join(' ') - }, - gapmode: { - valType: 'enumerated', - values: ['pixels', 'fraction'], - dflt: 'pixels', - editType: 'calc', - description: [ - 'Determines if the `gap` value corresponds to a pixel length', - 'or a fraction of the plot area.' - ].join(' ') - }, - */ - // To complete https://github.com/plotly/plotly.js/issues/4210 - // we additionally need `gap` and make this work on *linear*, and - // possibly all other cartesian axis types. We possibly would also need - // some style attributes controlling the zig-zag on the corresponding - // axis. - editType: "calc" - }), - // ticks - tickmode, - nticks: makeNticks(), - tick0, - dtick, - ticklabelstep: { - valType: "integer", - min: 1, - dflt: 1, - editType: "ticks", - description: [ - "Sets the spacing between tick labels as compared to the spacing between ticks.", - "A value of 1 (default) means each tick gets a label.", - "A value of 2 means shows every 2nd label.", - "A larger value n means only every nth tick is labeled.", - "`tick0` determines which labels are shown.", - "Not implemented for axes with `type` *log* or *multicategory*, or when `tickmode` is *array*." - ].join(" ") - }, - tickvals, - ticktext: { - valType: "data_array", - editType: "ticks", - description: [ - "Sets the text displayed at the ticks position via `tickvals`.", - "Only has an effect if `tickmode` is set to *array*.", - "Used with `tickvals`." - ].join(" ") - }, - ticks, - tickson: { - valType: "enumerated", - values: ["labels", "boundaries"], - dflt: "labels", - editType: "ticks", - description: [ - "Determines where ticks and grid lines are drawn with respect to their", - "corresponding tick labels.", - "Only has an effect for axes of `type` *category* or *multicategory*.", - "When set to *boundaries*, ticks and grid lines are drawn half a category", - "to the left/bottom of labels." - ].join(" ") - }, - ticklabelmode: { - valType: "enumerated", - values: ["instant", "period"], - dflt: "instant", - editType: "ticks", - description: [ - "Determines where tick labels are drawn with respect to their", - "corresponding ticks and grid lines.", - "Only has an effect for axes of `type` *date*", - "When set to *period*, tick labels are drawn in the middle of the period", - "between ticks." - ].join(" ") - }, - // ticklabelposition: not used directly, as values depend on direction (similar to side) - // left/right options are for x axes, and top/bottom options are for y axes - ticklabelposition: { - valType: "enumerated", - values: [ - "outside", - "inside", - "outside top", - "inside top", - "outside left", - "inside left", - "outside right", - "inside right", - "outside bottom", - "inside bottom" - ], - dflt: "outside", - editType: "calc", - description: [ - "Determines where tick labels are drawn with respect to the axis", - "Please note that", - "top or bottom has no effect on x axes or when `ticklabelmode` is set to *period*.", - "Similarly", - "left or right has no effect on y axes or when `ticklabelmode` is set to *period*.", - "Has no effect on *multicategory* axes or when `tickson` is set to *boundaries*.", - "When used on axes linked by `matches` or `scaleanchor`,", - "no extra padding for inside labels would be added by autorange,", - "so that the scales could match." - ].join(" ") - }, - ticklabeloverflow: { - valType: "enumerated", - values: [ - "allow", - "hide past div", - "hide past domain" - ], - editType: "calc", - description: [ - "Determines how we handle tick labels that would overflow either the graph div or the domain of the axis.", - "The default value for inside tick labels is *hide past domain*.", - "Otherwise on *category* and *multicategory* axes the default is *allow*.", - "In other cases the default is *hide past div*." - ].join(" ") - }, - ticklabelshift: { - valType: "integer", - dflt: 0, - editType: "ticks", - description: [ - "Shifts the tick labels by the specified number of pixels in parallel to the axis.", - "Positive values move the labels in the positive direction of the axis." - ].join(" ") - }, - ticklabelstandoff: { - valType: "integer", - dflt: 0, - editType: "ticks", - description: [ - "Sets the standoff distance (in px) between the axis tick labels and their default position.", - "A positive `ticklabelstandoff` moves the labels farther away from the plot area", - "if `ticklabelposition` is *outside*, and deeper into the plot area if", - "`ticklabelposition` is *inside*. A negative `ticklabelstandoff` works in the opposite", - "direction, moving outside ticks towards the plot area and inside ticks towards", - "the outside. If the negative value is large enough, inside ticks can even end up", - "outside and vice versa." - ].join(" ") - }, - ticklabelindex: { - // in the future maybe add `extras: ['all', 'minor']` to allow showing labels for all ticks - // or for all minor ticks. - valType: "integer", - arrayOk: true, - editType: "calc", - description: [ - "Only for axes with `type` *date* or *linear*.", - "Instead of drawing the major tick label, draw the label for the minor tick", - "that is n positions away from the major tick. E.g. to always draw the label for the", - "minor tick before each major tick, choose `ticklabelindex` -1. This is useful for date", - "axes with `ticklabelmode` *period* if you want to label the period that ends with each", - "major tick instead of the period that begins there." - ].join(" ") - }, - mirror: { - valType: "enumerated", - values: [true, "ticks", false, "all", "allticks"], - dflt: false, - editType: "ticks+layoutstyle", - description: [ - "Determines if the axis lines or/and ticks are mirrored to", - "the opposite side of the plotting area.", - "If *true*, the axis lines are mirrored.", - "If *ticks*, the axis lines and ticks are mirrored.", - "If *false*, mirroring is disable.", - "If *all*, axis lines are mirrored on all shared-axes subplots.", - "If *allticks*, axis lines and ticks are mirrored", - "on all shared-axes subplots." - ].join(" ") - }, - ticklen: makeTicklen(), - tickwidth: makeTickwidth(), - tickcolor, - showticklabels: { - valType: "boolean", - dflt: true, - editType: "ticks", - description: "Determines whether or not the tick labels are drawn." - }, - labelalias: { - valType: "any", - dflt: false, - editType: "ticks", - description: [ - "Replacement text for specific tick or hover labels.", - "For example using {US: 'USA', CA: 'Canada'} changes US to USA", - "and CA to Canada. The labels we would have shown must match", - "the keys exactly, after adding any tickprefix or ticksuffix.", - "For negative numbers the minus sign symbol used (U+2212) is wider than the regular ascii dash.", - "That means you need to use −1 instead of -1.", - "labelalias can be used with any axis type, and both keys (if needed)", - "and values (if desired) can include html-like tags or MathJax." - ].join(" ") - }, - automargin: { - valType: "flaglist", - flags: ["height", "width", "left", "right", "top", "bottom"], - extras: [true, false], - dflt: false, - editType: "ticks", - description: [ - "Determines whether long tick labels automatically grow the figure", - "margins." - ].join(" ") - }, - showspikes: { - valType: "boolean", - dflt: false, - editType: "modebar", - description: [ - "Determines whether or not spikes (aka droplines) are drawn for this axis.", - "Note: This only takes affect when hovermode = closest" - ].join(" ") - }, - spikecolor: { - valType: "color", - dflt: null, - editType: "none", - description: "Sets the spike color. If undefined, will use the series color" - }, - spikethickness: { - valType: "number", - dflt: 3, - editType: "none", - description: "Sets the width (in px) of the zero line." - }, - spikedash: extendFlat$g({}, dash$4, { dflt: "dash", editType: "none" }), - spikemode: { - valType: "flaglist", - flags: ["toaxis", "across", "marker"], - dflt: "toaxis", - editType: "none", - description: [ - "Determines the drawing mode for the spike line", - "If *toaxis*, the line is drawn from the data point to the axis the ", - "series is plotted on.", - "If *across*, the line is drawn across the entire plot area, and", - "supercedes *toaxis*.", - "If *marker*, then a marker dot is drawn on the axis the series is", - "plotted on" - ].join(" ") - }, - spikesnap: { - valType: "enumerated", - values: ["data", "cursor", "hovered data"], - dflt: "hovered data", - editType: "none", - description: "Determines whether spikelines are stuck to the cursor or to the closest datapoints." - }, - tickfont: fontAttrs$c({ - editType: "ticks", - description: "Sets the tick font." - }), - tickangle: { - valType: "angle", - dflt: "auto", - editType: "ticks", - description: [ - "Sets the angle of the tick labels with respect to the horizontal.", - "For example, a `tickangle` of -90 draws the tick labels", - "vertically." - ].join(" ") - }, - autotickangles: { - valType: "info_array", - freeLength: true, - items: { - valType: "angle" - }, - dflt: [0, 30, 90], - editType: "ticks", - description: [ - "When `tickangle` is set to *auto*, it will be set to the first", - "angle in this array that is large enough to prevent label", - "overlap." - ].join(" ") - }, - tickprefix: { - valType: "string", - dflt: "", - editType: "ticks", - description: "Sets a tick label prefix." - }, - showtickprefix: { - valType: "enumerated", - values: ["all", "first", "last", "none"], - dflt: "all", - editType: "ticks", - description: [ - "If *all*, all tick labels are displayed with a prefix.", - "If *first*, only the first tick is displayed with a prefix.", - "If *last*, only the last tick is displayed with a suffix.", - "If *none*, tick prefixes are hidden." - ].join(" ") - }, - ticksuffix: { - valType: "string", - dflt: "", - editType: "ticks", - description: "Sets a tick label suffix." - }, - showticksuffix: { - valType: "enumerated", - values: ["all", "first", "last", "none"], - dflt: "all", - editType: "ticks", - description: "Same as `showtickprefix` but for tick suffixes." - }, - showexponent: { - valType: "enumerated", - values: ["all", "first", "last", "none"], - dflt: "all", - editType: "ticks", - description: [ - "If *all*, all exponents are shown besides their significands.", - "If *first*, only the exponent of the first tick is shown.", - "If *last*, only the exponent of the last tick is shown.", - "If *none*, no exponents appear." - ].join(" ") - }, - exponentformat: { - valType: "enumerated", - values: ["none", "e", "E", "power", "SI", "B"], - dflt: "B", - editType: "ticks", - description: [ - "Determines a formatting rule for the tick exponents.", - "For example, consider the number 1,000,000,000.", - "If *none*, it appears as 1,000,000,000.", - "If *e*, 1e+9.", - "If *E*, 1E+9.", - "If *power*, 1x10^9 (with 9 in a super script).", - "If *SI*, 1G.", - "If *B*, 1B." - ].join(" ") - }, - minexponent: { - valType: "number", - dflt: 3, - min: 0, - editType: "ticks", - description: [ - "Hide SI prefix for 10^n if |n| is below this number.", - "This only has an effect when `tickformat` is *SI* or *B*." - ].join(" ") - }, - separatethousands: { - valType: "boolean", - dflt: false, - editType: "ticks", - description: [ - 'If "true", even 4-digit integers are separated' - ].join(" ") - }, - tickformat: { - valType: "string", - dflt: "", - editType: "ticks", - description: descriptionWithDates("tick label") - }, - tickformatstops: templatedArray$8("tickformatstop", { - enabled: { - valType: "boolean", - dflt: true, - editType: "ticks", - description: [ - "Determines whether or not this stop is used.", - "If `false`, this stop is ignored even within its `dtickrange`." - ].join(" ") - }, - dtickrange: { - valType: "info_array", - items: [ - { valType: "any", editType: "ticks" }, - { valType: "any", editType: "ticks" } - ], - editType: "ticks", - description: [ - "range [*min*, *max*], where *min*, *max* - dtick values", - "which describe some zoom level, it is possible to omit *min*", - "or *max* value by passing *null*" - ].join(" ") - }, - value: { - valType: "string", - dflt: "", - editType: "ticks", - description: [ - "string - dtickformat for described zoom level, the same as *tickformat*" - ].join(" ") - }, - editType: "ticks" - }), - hoverformat: { - valType: "string", - dflt: "", - editType: "none", - description: descriptionWithDates("hover text") - }, - // lines and grids - showline: { - valType: "boolean", - dflt: false, - editType: "ticks+layoutstyle", - description: [ - "Determines whether or not a line bounding this axis is drawn." - ].join(" ") - }, - linecolor: { - valType: "color", - dflt: colorAttrs$5.defaultLine, - editType: "layoutstyle", - description: "Sets the axis line color." - }, - linewidth: { - valType: "number", - min: 0, - dflt: 1, - editType: "ticks+layoutstyle", - description: "Sets the width (in px) of the axis line." - }, - showgrid, - gridcolor, - gridwidth: makeGridwidth(), - griddash, - zeroline: { - valType: "boolean", - editType: "ticks", - description: [ - "Determines whether or not a line is drawn at along the 0 value", - "of this axis.", - "If *true*, the zero line is drawn on top of the grid lines." - ].join(" ") - }, - zerolinecolor: { - valType: "color", - dflt: colorAttrs$5.defaultLine, - editType: "ticks", - description: "Sets the line color of the zero line." - }, - zerolinewidth: { - valType: "number", - dflt: 1, - editType: "ticks", - description: "Sets the width (in px) of the zero line." - }, - showdividers: { - valType: "boolean", - dflt: true, - editType: "ticks", - description: [ - "Determines whether or not a dividers are drawn", - "between the category levels of this axis.", - "Only has an effect on *multicategory* axes." - ].join(" ") - }, - dividercolor: { - valType: "color", - dflt: colorAttrs$5.defaultLine, - editType: "ticks", - description: [ - "Sets the color of the dividers", - "Only has an effect on *multicategory* axes." - ].join(" ") - }, - dividerwidth: { - valType: "number", - dflt: 1, - editType: "ticks", - description: [ - "Sets the width (in px) of the dividers", - "Only has an effect on *multicategory* axes." - ].join(" ") - }, - // TODO dividerlen: that would override "to label base" length? - // positioning attributes - // anchor: not used directly, just put here for reference - // values are any opposite-letter axis id - anchor: { - valType: "enumerated", - values: [ - "free", - constants$T.idRegex.x.toString(), - constants$T.idRegex.y.toString() - ], - editType: "plot", - description: [ - "If set to an opposite-letter axis id (e.g. `x2`, `y`), this axis is bound to", - "the corresponding opposite-letter axis.", - "If set to *free*, this axis' position is determined by `position`." - ].join(" ") - }, - // side: not used directly, as values depend on direction - // values are top, bottom for x axes, and left, right for y - side: { - valType: "enumerated", - values: ["top", "bottom", "left", "right"], - editType: "plot", - description: [ - "Determines whether a x (y) axis is positioned", - "at the *bottom* (*left*) or *top* (*right*)", - "of the plotting area." - ].join(" ") - }, - // overlaying: not used directly, just put here for reference - // values are false and any other same-letter axis id that's not - // itself overlaying anything - overlaying: { - valType: "enumerated", - values: [ - "free", - constants$T.idRegex.x.toString(), - constants$T.idRegex.y.toString() - ], - editType: "plot", - description: [ - "If set a same-letter axis id, this axis is overlaid on top of", - "the corresponding same-letter axis, with traces and axes visible for both", - "axes.", - "If *false*, this axis does not overlay any same-letter axes.", - "In this case, for axes with overlapping domains only the highest-numbered", - "axis will be visible." - ].join(" ") - }, - minor: { - tickmode: minorTickmode, - nticks: makeNticks("minor"), - tick0, - dtick, - tickvals, - ticks, - ticklen: makeTicklen("minor"), - tickwidth: makeTickwidth("minor"), - tickcolor, - gridcolor, - gridwidth: makeGridwidth("minor"), - griddash, - showgrid, - editType: "ticks" - }, - layer: { - valType: "enumerated", - values: ["above traces", "below traces"], - dflt: "above traces", - editType: "plot", - description: [ - "Sets the layer on which this axis is displayed.", - "If *above traces*, this axis is displayed above all the subplot's traces", - "If *below traces*, this axis is displayed below all the subplot's traces,", - "but above the grid lines.", - "Useful when used together with scatter-like traces with `cliponaxis`", - "set to *false* to show markers and/or text nodes above this axis." - ].join(" ") - }, - domain: { - valType: "info_array", - items: [ - { valType: "number", min: 0, max: 1, editType: "plot" }, - { valType: "number", min: 0, max: 1, editType: "plot" } - ], - dflt: [0, 1], - editType: "plot", - description: [ - "Sets the domain of this axis (in plot fraction)." - ].join(" ") - }, - position: { - valType: "number", - min: 0, - max: 1, - dflt: 0, - editType: "plot", - description: [ - "Sets the position of this axis in the plotting space", - "(in normalized coordinates).", - "Only has an effect if `anchor` is set to *free*." - ].join(" ") - }, - autoshift: { - valType: "boolean", - dflt: false, - editType: "plot", - description: [ - "Automatically reposition the axis to avoid", - "overlap with other axes with the same `overlaying` value.", - "This repositioning will account for any `shift` amount applied to other", - "axes on the same side with `autoshift` is set to true.", - "Only has an effect if `anchor` is set to *free*." - ].join(" ") - }, - shift: { - valType: "number", - editType: "plot", - description: [ - "Moves the axis a given number of pixels from where it would have been otherwise.", - "Accepts both positive and negative values, which will shift the axis either right", - "or left, respectively.", - "If `autoshift` is set to true, then this defaults to a padding of -3 if `side` is set to *left*.", - "and defaults to +3 if `side` is set to *right*. Defaults to 0 if `autoshift` is set to false.", - "Only has an effect if `anchor` is set to *free*." - ].join(" ") - }, - categoryorder: { - valType: "enumerated", - values: [ - "trace", - "category ascending", - "category descending", - "array", - "total ascending", - "total descending", - "min ascending", - "min descending", - "max ascending", - "max descending", - "sum ascending", - "sum descending", - "mean ascending", - "mean descending", - "geometric mean ascending", - "geometric mean descending", - "median ascending", - "median descending" - ], - dflt: "trace", - editType: "calc", - description: [ - "Specifies the ordering logic for the case of categorical variables.", - "By default, plotly uses *trace*, which specifies the order that is present in the data supplied.", - "Set `categoryorder` to *category ascending* or *category descending* if order should be determined by", - "the alphanumerical order of the category names.", - "Set `categoryorder` to *array* to derive the ordering from the attribute `categoryarray`. If a category", - "is not found in the `categoryarray` array, the sorting behavior for that attribute will be identical to", - "the *trace* mode. The unspecified categories will follow the categories in `categoryarray`.", - "Set `categoryorder` to *total ascending* or *total descending* if order should be determined by the", - "numerical order of the values.", - "Similarly, the order can be determined by the min, max, sum, mean, geometric mean or median of all the values." - ].join(" ") - }, - categoryarray: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the order in which categories on this axis appear.", - "Only has an effect if `categoryorder` is set to *array*.", - "Used with `categoryorder`." - ].join(" ") - }, - uirevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of user-driven changes in axis `range`,", - "`autorange`, and `title` if in `editable: true` configuration.", - "Defaults to `layout.uirevision`." - ].join(" ") - }, - editType: "calc", - _deprecated: { - autotick: { - valType: "boolean", - editType: "ticks", - description: [ - "Obsolete.", - "Set `tickmode` to *auto* for old `autotick` *true* behavior.", - "Set `tickmode` to *linear* for `autotick` *false*." - ].join(" ") - }, - title: { - valType: "string", - editType: "ticks", - description: [ - "Value of `title` is no longer a simple *string* but a set of sub-attributes.", - "To set the axis' title, please use `title.text` now." - ].join(" ") - }, - titlefont: fontAttrs$c({ - editType: "ticks", - description: [ - "Former `titlefont` is now the sub-attribute `font` of `title`.", - "To customize title font properties, please use `title.font` now." - ].join(" ") - }) - } -}; -var axesAttrs = layout_attributes$4; -var fontAttrs$b = font_attributes; -var extendFlat$f = extend$5.extendFlat; -var overrideAll$6 = edit_types.overrideAll; -var attributes$J = overrideAll$6({ - orientation: { - valType: "enumerated", - values: ["h", "v"], - dflt: "v", - description: "Sets the orientation of the colorbar." - }, - thicknessmode: { - valType: "enumerated", - values: ["fraction", "pixels"], - dflt: "pixels", - description: [ - "Determines whether this color bar's thickness", - "(i.e. the measure in the constant color direction)", - "is set in units of plot *fraction* or in *pixels*.", - "Use `thickness` to set the value." - ].join(" ") - }, - thickness: { - valType: "number", - min: 0, - dflt: 30, - description: [ - "Sets the thickness of the color bar", - "This measure excludes the size of the padding, ticks and labels." - ].join(" ") - }, - lenmode: { - valType: "enumerated", - values: ["fraction", "pixels"], - dflt: "fraction", - description: [ - "Determines whether this color bar's length", - "(i.e. the measure in the color variation direction)", - "is set in units of plot *fraction* or in *pixels.", - "Use `len` to set the value." - ].join(" ") - }, - len: { - valType: "number", - min: 0, - dflt: 1, - description: [ - "Sets the length of the color bar", - "This measure excludes the padding of both ends.", - "That is, the color bar length is this length minus the", - "padding on both ends." - ].join(" ") - }, - x: { - valType: "number", - description: [ - "Sets the x position with respect to `xref` of the color bar (in plot fraction).", - "When `xref` is *paper*, defaults to 1.02 when `orientation` is *v* and", - "0.5 when `orientation` is *h*.", - "When `xref` is *container*, defaults to *1* when `orientation` is *v* and", - "0.5 when `orientation` is *h*.", - "Must be between *0* and *1* if `xref` is *container*", - "and between *-2* and *3* if `xref` is *paper*." - ].join(" ") - }, - xref: { - valType: "enumerated", - dflt: "paper", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `x` refers to.", - "*container* spans the entire `width` of the plot.", - "*paper* refers to the width of the plotting area only." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["left", "center", "right"], - description: [ - "Sets this color bar's horizontal position anchor.", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the color bar.", - "Defaults to *left* when `orientation` is *v* and", - "*center* when `orientation` is *h*." - ].join(" ") - }, - xpad: { - valType: "number", - min: 0, - dflt: 10, - description: "Sets the amount of padding (in px) along the x direction." - }, - y: { - valType: "number", - description: [ - "Sets the y position with respect to `yref` of the color bar (in plot fraction).", - "When `yref` is *paper*, defaults to 0.5 when `orientation` is *v* and", - "1.02 when `orientation` is *h*.", - "When `yref` is *container*, defaults to 0.5 when `orientation` is *v* and", - "1 when `orientation` is *h*.", - "Must be between *0* and *1* if `yref` is *container*", - "and between *-2* and *3* if `yref` is *paper*." - ].join(" ") - }, - yref: { - valType: "enumerated", - dflt: "paper", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `y` refers to.", - "*container* spans the entire `height` of the plot.", - "*paper* refers to the height of the plotting area only." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - description: [ - "Sets this color bar's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the color bar.", - "Defaults to *middle* when `orientation` is *v* and", - "*bottom* when `orientation` is *h*." - ].join(" ") - }, - ypad: { - valType: "number", - min: 0, - dflt: 10, - description: "Sets the amount of padding (in px) along the y direction." - }, - // a possible line around the bar itself - outlinecolor: axesAttrs.linecolor, - outlinewidth: axesAttrs.linewidth, - // Should outlinewidth have {dflt: 0} ? - // another possible line outside the padding and tick labels - bordercolor: axesAttrs.linecolor, - borderwidth: { - valType: "number", - min: 0, - dflt: 0, - description: [ - "Sets the width (in px) or the border enclosing this color bar." - ].join(" ") - }, - bgcolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - description: "Sets the color of padded area." - }, - // tick and title properties named and function exactly as in axes - tickmode: axesAttrs.minor.tickmode, - nticks: axesAttrs.nticks, - tick0: axesAttrs.tick0, - dtick: axesAttrs.dtick, - tickvals: axesAttrs.tickvals, - ticktext: axesAttrs.ticktext, - ticks: extendFlat$f({}, axesAttrs.ticks, { dflt: "" }), - ticklabeloverflow: extendFlat$f({}, axesAttrs.ticklabeloverflow, { - description: [ - "Determines how we handle tick labels that would overflow either the graph div or the domain of the axis.", - "The default value for inside tick labels is *hide past domain*.", - "In other cases the default is *hide past div*." - ].join(" ") - }), - // ticklabelposition: not used directly, as values depend on orientation - // left/right options are for x axes, and top/bottom options are for y axes - ticklabelposition: { - valType: "enumerated", - values: [ - "outside", - "inside", - "outside top", - "inside top", - "outside left", - "inside left", - "outside right", - "inside right", - "outside bottom", - "inside bottom" - ], - dflt: "outside", - description: [ - "Determines where tick labels are drawn relative to the ticks.", - "Left and right options are used when `orientation` is *h*,", - "top and bottom when `orientation` is *v*." - ].join(" ") - }, - ticklen: axesAttrs.ticklen, - tickwidth: axesAttrs.tickwidth, - tickcolor: axesAttrs.tickcolor, - ticklabelstep: axesAttrs.ticklabelstep, - showticklabels: axesAttrs.showticklabels, - labelalias: axesAttrs.labelalias, - tickfont: fontAttrs$b({ - description: "Sets the color bar's tick label font" - }), - tickangle: axesAttrs.tickangle, - tickformat: axesAttrs.tickformat, - tickformatstops: axesAttrs.tickformatstops, - tickprefix: axesAttrs.tickprefix, - showtickprefix: axesAttrs.showtickprefix, - ticksuffix: axesAttrs.ticksuffix, - showticksuffix: axesAttrs.showticksuffix, - separatethousands: axesAttrs.separatethousands, - exponentformat: axesAttrs.exponentformat, - minexponent: axesAttrs.minexponent, - showexponent: axesAttrs.showexponent, - title: { - text: { - valType: "string", - description: [ - "Sets the title of the color bar.", - "Note that before the existence of `title.text`, the title's", - "contents used to be defined as the `title` attribute itself.", - "This behavior has been deprecated." - ].join(" ") - }, - font: fontAttrs$b({ - description: [ - "Sets this color bar's title font.", - "Note that the title's font used to be set", - "by the now deprecated `titlefont` attribute." - ].join(" ") - }), - side: { - valType: "enumerated", - values: ["right", "top", "bottom"], - description: [ - "Determines the location of color bar's title", - "with respect to the color bar.", - "Defaults to *top* when `orientation` if *v* and ", - "defaults to *right* when `orientation` if *h*.", - "Note that the title's location used to be set", - "by the now deprecated `titleside` attribute." - ].join(" ") - } - }, - _deprecated: { - title: { - valType: "string", - description: [ - "Deprecated in favor of color bar's `title.text`.", - "Note that value of color bar's `title` is no longer a simple", - "*string* but a set of sub-attributes." - ].join(" ") - }, - titlefont: fontAttrs$b({ - description: "Deprecated in favor of color bar's `title.font`." - }), - titleside: { - valType: "enumerated", - values: ["right", "top", "bottom"], - dflt: "top", - description: "Deprecated in favor of color bar's `title.side`." - } - } -}, "colorbars", "from-root"); -var colorbarAttrs = attributes$J; -var counterRegex$1 = regex.counter; -var sortObjectKeys$1 = sort_object_keys; -var palettes = scales_1.scales; -var paletteStr = sortObjectKeys$1(palettes); -function code$1(s) { - return "`" + s + "`"; -} -var attributes$I = function colorScaleAttrs(context2, opts) { - context2 = context2 || ""; - opts = opts || {}; - var cLetter = opts.cLetter || "c"; - var onlyIfNumerical = "onlyIfNumerical" in opts ? opts.onlyIfNumerical : Boolean(context2); - var noScale = "noScale" in opts ? opts.noScale : context2 === "marker.line"; - var showScaleDflt = "showScaleDflt" in opts ? opts.showScaleDflt : cLetter === "z"; - var colorscaleDflt = typeof opts.colorscaleDflt === "string" ? palettes[opts.colorscaleDflt] : null; - var editTypeOverride = opts.editTypeOverride || ""; - var contextHead = context2 ? context2 + "." : ""; - var colorAttr, colorAttrFull; - if ("colorAttr" in opts) { - colorAttr = opts.colorAttr; - colorAttrFull = opts.colorAttr; - } else { - colorAttr = { z: "z", c: "color" }[cLetter]; - colorAttrFull = "in " + code$1(contextHead + colorAttr); - } - var effectDesc = onlyIfNumerical ? " Has an effect only if " + colorAttrFull + " is set to a numerical array." : ""; - var auto = cLetter + "auto"; - var min = cLetter + "min"; - var max = cLetter + "max"; - var mid = cLetter + "mid"; - var autoFull = code$1(contextHead + auto); - var minFull = code$1(contextHead + min); - var maxFull = code$1(contextHead + max); - var minmaxFull = minFull + " and " + maxFull; - var autoImpliedEdits = {}; - autoImpliedEdits[min] = autoImpliedEdits[max] = void 0; - var minmaxImpliedEdits = {}; - minmaxImpliedEdits[auto] = false; - var attrs2 = {}; - if (colorAttr === "color") { - attrs2.color = { - valType: "color", - arrayOk: true, - editType: editTypeOverride || "style", - description: [ - "Sets the", - context2, - "color.", - "It accepts either a specific color", - "or an array of numbers that are mapped to the colorscale", - "relative to the max and min values of the array or relative to", - minmaxFull, - "if set." - ].join(" ") - }; - if (opts.anim) { - attrs2.color.anim = true; - } - } - attrs2[auto] = { - valType: "boolean", - dflt: true, - editType: "calc", - impliedEdits: autoImpliedEdits, - description: [ - "Determines whether or not the color domain is computed", - "with respect to the input data (here " + colorAttrFull + ") or the bounds set in", - minmaxFull + effectDesc, - "Defaults to `false` when", - minmaxFull, - "are set by the user." - ].join(" ") - }; - attrs2[min] = { - valType: "number", - dflt: null, - editType: editTypeOverride || "plot", - impliedEdits: minmaxImpliedEdits, - description: [ - "Sets the lower bound of the color domain." + effectDesc, - "Value should have the same units as", - colorAttrFull, - "and if set,", - maxFull, - "must be set as well." - ].join(" ") - }; - attrs2[max] = { - valType: "number", - dflt: null, - editType: editTypeOverride || "plot", - impliedEdits: minmaxImpliedEdits, - description: [ - "Sets the upper bound of the color domain." + effectDesc, - "Value should have the same units as", - colorAttrFull, - "and if set,", - minFull, - "must be set as well." - ].join(" ") - }; - attrs2[mid] = { - valType: "number", - dflt: null, - editType: "calc", - impliedEdits: autoImpliedEdits, - description: [ - "Sets the mid-point of the color domain by scaling", - minFull, - "and/or", - maxFull, - "to be equidistant to this point." + effectDesc, - "Value should have the same units as", - colorAttrFull + ".", - "Has no effect when", - autoFull, - "is `false`." - ].join(" ") - }; - attrs2.colorscale = { - valType: "colorscale", - editType: "calc", - dflt: colorscaleDflt, - impliedEdits: { autocolorscale: false }, - description: [ - "Sets the colorscale." + effectDesc, - "The colorscale must be an array containing", - "arrays mapping a normalized value to an", - "rgb, rgba, hex, hsl, hsv, or named color string.", - "At minimum, a mapping for the lowest (0) and highest (1)", - "values are required. For example,", - "`[[0, 'rgb(0,0,255)'], [1, 'rgb(255,0,0)']]`.", - "To control the bounds of the colorscale in color space,", - "use", - minmaxFull + ".", - "Alternatively, `colorscale` may be a palette name string", - "of the following list: " + paletteStr + "." - ].join(" ") - }; - attrs2.autocolorscale = { - valType: "boolean", - // gets overrode in 'heatmap' & 'surface' for backwards comp. - dflt: opts.autoColorDflt === false ? false : true, - editType: "calc", - impliedEdits: { colorscale: void 0 }, - description: [ - "Determines whether the colorscale is a default palette (`autocolorscale: true`)", - "or the palette determined by", - code$1(contextHead + "colorscale") + "." + effectDesc, - "In case `colorscale` is unspecified or `autocolorscale` is true, the default", - "palette will be chosen according to whether numbers in the `color` array are", - "all positive, all negative or mixed." - ].join(" ") - }; - attrs2.reversescale = { - valType: "boolean", - dflt: false, - editType: "plot", - description: [ - "Reverses the color mapping if true." + effectDesc, - "If true,", - minFull, - "will correspond to the last color", - "in the array and", - maxFull, - "will correspond to the first color." - ].join(" ") - }; - if (!noScale) { - attrs2.showscale = { - valType: "boolean", - dflt: showScaleDflt, - editType: "calc", - description: [ - "Determines whether or not a colorbar is displayed for this trace." + effectDesc - ].join(" ") - }; - attrs2.colorbar = colorbarAttrs; - } - if (!opts.noColorAxis) { - attrs2.coloraxis = { - valType: "subplotid", - regex: counterRegex$1("coloraxis"), - dflt: null, - editType: "calc", - description: [ - "Sets a reference to a shared color axis.", - "References to these shared color axes are *coloraxis*, *coloraxis2*, *coloraxis3*, etc.", - "Settings for these shared color axes are set in the layout, under", - "`layout.coloraxis`, `layout.coloraxis2`, etc.", - "Note that multiple color scales can be linked to the same color axis." - ].join(" ") - }; - } - return attrs2; -}; -var extendFlat$e = extend$5.extendFlat; -var colorScaleAttrs$6 = attributes$I; -var scales$1 = scales_1.scales; -var msg = "Note that `autocolorscale` must be true for this attribute to work."; -var layout_attributes$3 = { - editType: "calc", - colorscale: { - editType: "calc", - sequential: { - valType: "colorscale", - dflt: scales$1.Reds, - editType: "calc", - description: [ - "Sets the default sequential colorscale for positive values.", - msg - ].join(" ") - }, - sequentialminus: { - valType: "colorscale", - dflt: scales$1.Blues, - editType: "calc", - description: [ - "Sets the default sequential colorscale for negative values.", - msg - ].join(" ") - }, - diverging: { - valType: "colorscale", - dflt: scales$1.RdBu, - editType: "calc", - description: [ - "Sets the default diverging colorscale.", - msg - ].join(" ") - } - }, - coloraxis: extendFlat$e({ - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, - editType: "calc", - description: [ - "" - ].join(" ") - }, colorScaleAttrs$6("", { - colorAttr: "corresponding trace color array(s)", - noColorAxis: true, - showScaleDflt: true - })) -}; -var Lib$1U = libExports; -var has_colorbar = function hasColorbar(container) { - return Lib$1U.isPlainObject(container.colorbar); -}; -var clean_ticks = {}; -var isNumeric$s = fastIsnumeric; -var Lib$1T = libExports; -var constants$S = numerical; -var ONEDAY$2 = constants$S.ONEDAY; -var ONEWEEK$3 = constants$S.ONEWEEK; -clean_ticks.dtick = function(dtick2, axType) { - var isLog = axType === "log"; - var isDate = axType === "date"; - var isCat = axType === "category"; - var dtickDflt = isDate ? ONEDAY$2 : 1; - if (!dtick2) return dtickDflt; - if (isNumeric$s(dtick2)) { - dtick2 = Number(dtick2); - if (dtick2 <= 0) return dtickDflt; - if (isCat) { - return Math.max(1, Math.round(dtick2)); - } - if (isDate) { - return Math.max(0.1, dtick2); - } - return dtick2; - } - if (typeof dtick2 !== "string" || !(isDate || isLog)) { - return dtickDflt; - } - var prefix = dtick2.charAt(0); - var dtickNum = dtick2.substr(1); - dtickNum = isNumeric$s(dtickNum) ? Number(dtickNum) : 0; - if (dtickNum <= 0 || !// "M" gives ticks every (integer) n months - (isDate && prefix === "M" && dtickNum === Math.round(dtickNum) || // "L" gives ticks linearly spaced in data (not in position) every (float) f - isLog && prefix === "L" || // "D1" gives powers of 10 with all small digits between, "D2" gives only 2 and 5 - isLog && prefix === "D" && (dtickNum === 1 || dtickNum === 2))) { - return dtickDflt; - } - return dtick2; -}; -clean_ticks.tick0 = function(tick02, axType, calendar, dtick2) { - if (axType === "date") { - return Lib$1T.cleanDate( - tick02, - Lib$1T.dateTick0(calendar, dtick2 % ONEWEEK$3 === 0 ? 1 : 0) - ); - } - if (dtick2 === "D1" || dtick2 === "D2") { - return void 0; - } - return isNumeric$s(tick02) ? Number(tick02) : 0; -}; -var cleanTicks$1 = clean_ticks; -var isArrayOrTypedArray$9 = libExports.isArrayOrTypedArray; -var isTypedArraySpec$2 = array$2.isTypedArraySpec; -var decodeTypedArraySpec = array$2.decodeTypedArraySpec; -var tick_value_defaults = function handleTickValueDefaults(containerIn, containerOut, coerce2, axType, opts) { - if (!opts) opts = {}; - var isMinor = opts.isMinor; - var cIn = isMinor ? containerIn.minor || {} : containerIn; - var cOut = isMinor ? containerOut.minor : containerOut; - var prefix = isMinor ? "minor." : ""; - function readInput(attr) { - var v = cIn[attr]; - if (isTypedArraySpec$2(v)) v = decodeTypedArraySpec(v); - return v !== void 0 ? v : (cOut._template || {})[attr]; - } - var _tick0 = readInput("tick0"); - var _dtick = readInput("dtick"); - var _tickvals = readInput("tickvals"); - var tickmodeDefault = isArrayOrTypedArray$9(_tickvals) ? "array" : _dtick ? "linear" : "auto"; - var tickmode2 = coerce2(prefix + "tickmode", tickmodeDefault); - if (tickmode2 === "auto" || tickmode2 === "sync") { - coerce2(prefix + "nticks"); - } else if (tickmode2 === "linear") { - var dtick2 = cOut.dtick = cleanTicks$1.dtick( - _dtick, - axType - ); - cOut.tick0 = cleanTicks$1.tick0( - _tick0, - axType, - containerOut.calendar, - dtick2 - ); - } else if (axType !== "multicategory") { - var tickvals2 = coerce2(prefix + "tickvals"); - if (tickvals2 === void 0) cOut.tickmode = "auto"; - else if (!isMinor) coerce2("ticktext"); - } -}; -var Lib$1S = libExports; -var layoutAttributes$b = layout_attributes$4; -var tick_mark_defaults = function handleTickMarkDefaults(containerIn, containerOut, coerce2, options) { - var isMinor = options.isMinor; - var cIn = isMinor ? containerIn.minor || {} : containerIn; - var cOut = isMinor ? containerOut.minor : containerOut; - var lAttr = isMinor ? layoutAttributes$b.minor : layoutAttributes$b; - var prefix = isMinor ? "minor." : ""; - var tickLen = Lib$1S.coerce2(cIn, cOut, lAttr, "ticklen", isMinor ? (containerOut.ticklen || 5) * 0.6 : void 0); - var tickWidth = Lib$1S.coerce2(cIn, cOut, lAttr, "tickwidth", isMinor ? containerOut.tickwidth || 1 : void 0); - var tickColor = Lib$1S.coerce2(cIn, cOut, lAttr, "tickcolor", (isMinor ? containerOut.tickcolor : void 0) || cOut.color); - var showTicks = coerce2(prefix + "ticks", !isMinor && options.outerTicks || tickLen || tickWidth || tickColor ? "outside" : ""); - if (!showTicks) { - delete cOut.ticklen; - delete cOut.tickwidth; - delete cOut.tickcolor; - } -}; -var show_dflt = function getShowAttrDflt(containerIn) { - var showAttrsAll = ["showexponent", "showtickprefix", "showticksuffix"]; - var showAttrs = showAttrsAll.filter(function(a) { - return containerIn[a] !== void 0; - }); - var sameVal = function(a) { - return containerIn[a] === containerIn[showAttrs[0]]; - }; - if (showAttrs.every(sameVal) || showAttrs.length === 1) { - return containerIn[showAttrs[0]]; - } -}; -var Lib$1R = libExports; -var Template$8 = plot_template; -var array_container_defaults = function handleArrayContainerDefaults(parentObjIn, parentObjOut, opts) { - var name2 = opts.name; - var inclusionAttr = opts.inclusionAttr || "visible"; - var previousContOut = parentObjOut[name2]; - var contIn = Lib$1R.isArrayOrTypedArray(parentObjIn[name2]) ? parentObjIn[name2] : []; - var contOut = parentObjOut[name2] = []; - var templater = Template$8.arrayTemplater(parentObjOut, name2, inclusionAttr); - var i, itemOut; - for (i = 0; i < contIn.length; i++) { - var itemIn = contIn[i]; - if (!Lib$1R.isPlainObject(itemIn)) { - itemOut = templater.newItem({}); - itemOut[inclusionAttr] = false; - } else { - itemOut = templater.newItem(itemIn); - } - itemOut._index = i; - if (itemOut[inclusionAttr] !== false) { - opts.handleItemDefaults(itemIn, itemOut, parentObjOut, opts); - } - contOut.push(itemOut); - } - var defaultItems = templater.defaultItems(); - for (i = 0; i < defaultItems.length; i++) { - itemOut = defaultItems[i]; - itemOut._index = contOut.length; - opts.handleItemDefaults({}, itemOut, parentObjOut, opts, {}); - contOut.push(itemOut); - } - if (Lib$1R.isArrayOrTypedArray(previousContOut)) { - var len = Math.min(previousContOut.length, contOut.length); - for (i = 0; i < len; i++) { - Lib$1R.relinkPrivateKeys(contOut[i], previousContOut[i]); - } - } - return contOut; -}; -var Lib$1Q = libExports; -var contrast = colorExports.contrast; -var layoutAttributes$a = layout_attributes$4; -var getShowAttrDflt$1 = show_dflt; -var handleArrayContainerDefaults$9 = array_container_defaults; -var tick_label_defaults = function handleTickLabelDefaults(containerIn, containerOut, coerce2, axType, options) { - if (!options) options = {}; - var labelalias = coerce2("labelalias"); - if (!Lib$1Q.isPlainObject(labelalias)) delete containerOut.labelalias; - var showAttrDflt = getShowAttrDflt$1(containerIn); - var showTickLabels = coerce2("showticklabels"); - if (showTickLabels) { - if (!options.noTicklabelshift) { - coerce2("ticklabelshift"); - } - if (!options.noTicklabelstandoff) { - coerce2("ticklabelstandoff"); - } - var font2 = options.font || {}; - var contColor = containerOut.color; - var position = containerOut.ticklabelposition || ""; - var dfltFontColor = position.indexOf("inside") !== -1 ? contrast(options.bgColor) : ( - // as with titlefont.color, inherit axis.color only if one was - // explicitly provided - contColor && contColor !== layoutAttributes$a.color.dflt ? contColor : font2.color - ); - Lib$1Q.coerceFont(coerce2, "tickfont", font2, { overrideDflt: { - color: dfltFontColor - } }); - if (!options.noTicklabelstep && axType !== "multicategory" && axType !== "log") { - coerce2("ticklabelstep"); - } - if (!options.noAng) { - var tickAngle = coerce2("tickangle"); - if (!options.noAutotickangles && tickAngle === "auto") { - coerce2("autotickangles"); - } - } - if (axType !== "category") { - var tickFormat = coerce2("tickformat"); - handleArrayContainerDefaults$9(containerIn, containerOut, { - name: "tickformatstops", - inclusionAttr: "enabled", - handleItemDefaults: tickformatstopDefaults - }); - if (!containerOut.tickformatstops.length) { - delete containerOut.tickformatstops; - } - if (!options.noExp && !tickFormat && axType !== "date") { - coerce2("showexponent", showAttrDflt); - coerce2("exponentformat"); - coerce2("minexponent"); - coerce2("separatethousands"); - } - } - } -}; -function tickformatstopDefaults(valueIn, valueOut) { - function coerce2(attr, dflt) { - return Lib$1Q.coerce(valueIn, valueOut, layoutAttributes$a.tickformatstops, attr, dflt); - } - var enabled = coerce2("enabled"); - if (enabled) { - coerce2("dtickrange"); - coerce2("value"); - } -} -var getShowAttrDflt2 = show_dflt; -var prefix_suffix_defaults = function handlePrefixSuffixDefaults(containerIn, containerOut, coerce2, axType, options) { - if (!options) options = {}; - var tickSuffixDflt = options.tickSuffixDflt; - var showAttrDflt = getShowAttrDflt2(containerIn); - var tickPrefix = coerce2("tickprefix"); - if (tickPrefix) coerce2("showtickprefix", showAttrDflt); - var tickSuffix = coerce2("ticksuffix", tickSuffixDflt); - if (tickSuffix) coerce2("showticksuffix", showAttrDflt); -}; -var Lib$1P = libExports; -var Template$7 = plot_template; -var handleTickValueDefaults$1 = tick_value_defaults; -var handleTickMarkDefaults$1 = tick_mark_defaults; -var handleTickLabelDefaults$1 = tick_label_defaults; -var handlePrefixSuffixDefaults$1 = prefix_suffix_defaults; -var attributes$H = attributes$J; -var defaults$o = function colorbarDefaults(containerIn, containerOut, layout) { - var colorbarOut = Template$7.newContainer(containerOut, "colorbar"); - var colorbarIn = containerIn.colorbar || {}; - function coerce2(attr, dflt) { - return Lib$1P.coerce(colorbarIn, colorbarOut, attributes$H, attr, dflt); - } - var margin = layout.margin || { t: 0, b: 0, l: 0, r: 0 }; - var w = layout.width - margin.l - margin.r; - var h = layout.height - margin.t - margin.b; - var orientation = coerce2("orientation"); - var isVertical2 = orientation === "v"; - var thicknessmode = coerce2("thicknessmode"); - coerce2( - "thickness", - thicknessmode === "fraction" ? 30 / (isVertical2 ? w : h) : 30 - ); - var lenmode = coerce2("lenmode"); - coerce2( - "len", - lenmode === "fraction" ? 1 : isVertical2 ? h : w - ); - var yref = coerce2("yref"); - var xref = coerce2("xref"); - var isPaperY = yref === "paper"; - var isPaperX = xref === "paper"; - var defaultX, defaultY, defaultYAnchor; - var defaultXAnchor = "left"; - if (isVertical2) { - defaultYAnchor = "middle"; - defaultXAnchor = isPaperX ? "left" : "right"; - defaultX = isPaperX ? 1.02 : 1; - defaultY = 0.5; - } else { - defaultYAnchor = isPaperY ? "bottom" : "top"; - defaultXAnchor = "center"; - defaultX = 0.5; - defaultY = isPaperY ? 1.02 : 1; - } - Lib$1P.coerce(colorbarIn, colorbarOut, { - x: { - valType: "number", - min: isPaperX ? -2 : 0, - max: isPaperX ? 3 : 1, - dflt: defaultX - } - }, "x"); - Lib$1P.coerce(colorbarIn, colorbarOut, { - y: { - valType: "number", - min: isPaperY ? -2 : 0, - max: isPaperY ? 3 : 1, - dflt: defaultY - } - }, "y"); - coerce2("xanchor", defaultXAnchor); - coerce2("xpad"); - coerce2("yanchor", defaultYAnchor); - coerce2("ypad"); - Lib$1P.noneOrAll(colorbarIn, colorbarOut, ["x", "y"]); - coerce2("outlinecolor"); - coerce2("outlinewidth"); - coerce2("bordercolor"); - coerce2("borderwidth"); - coerce2("bgcolor"); - var ticklabelposition = Lib$1P.coerce(colorbarIn, colorbarOut, { - ticklabelposition: { - valType: "enumerated", - dflt: "outside", - values: isVertical2 ? [ - "outside", - "inside", - "outside top", - "inside top", - "outside bottom", - "inside bottom" - ] : [ - "outside", - "inside", - "outside left", - "inside left", - "outside right", - "inside right" - ] - } - }, "ticklabelposition"); - coerce2("ticklabeloverflow", ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : "hide past div"); - handleTickValueDefaults$1(colorbarIn, colorbarOut, coerce2, "linear"); - var font2 = layout.font; - var opts = { - noAutotickangles: true, - noTicklabelshift: true, - noTicklabelstandoff: true, - font: font2 - }; - if (ticklabelposition.indexOf("inside") !== -1) { - opts.bgColor = "black"; - } - handlePrefixSuffixDefaults$1(colorbarIn, colorbarOut, coerce2, "linear", opts); - handleTickLabelDefaults$1(colorbarIn, colorbarOut, coerce2, "linear", opts); - handleTickMarkDefaults$1(colorbarIn, colorbarOut, coerce2, "linear"); - coerce2("title.text", layout._dfltTitle.colorbar); - var tickFont = colorbarOut.showticklabels ? colorbarOut.tickfont : font2; - var dfltTitleFont = Lib$1P.extendFlat({}, font2, { - family: tickFont.family, - size: Lib$1P.bigFont(tickFont.size) - }); - Lib$1P.coerceFont(coerce2, "title.font", dfltTitleFont); - coerce2("title.side", isVertical2 ? "top" : "right"); -}; -var isNumeric$r = fastIsnumeric; -var Lib$1O = libExports; -var hasColorbar2 = has_colorbar; -var colorbarDefaults2 = defaults$o; -var isValidScale = scales_1.isValid; -var traceIs$1 = registry.traceIs; -function npMaybe(parentCont, prefix) { - var containerStr = prefix.slice(0, prefix.length - 1); - return prefix ? Lib$1O.nestedProperty(parentCont, containerStr).get() || {} : parentCont; -} -var defaults$n = function colorScaleDefaults(parentContIn, parentContOut, layout, coerce2, opts) { - var prefix = opts.prefix; - var cLetter = opts.cLetter; - var inTrace = "_module" in parentContOut; - var containerIn = npMaybe(parentContIn, prefix); - var containerOut = npMaybe(parentContOut, prefix); - var template = npMaybe(parentContOut._template || {}, prefix) || {}; - var thisFn = function() { - delete parentContIn.coloraxis; - delete parentContOut.coloraxis; - return colorScaleDefaults(parentContIn, parentContOut, layout, coerce2, opts); - }; - if (inTrace) { - var colorAxes = layout._colorAxes || {}; - var colorAx = coerce2(prefix + "coloraxis"); - if (colorAx) { - var colorbarVisuals = traceIs$1(parentContOut, "contour") && Lib$1O.nestedProperty(parentContOut, "contours.coloring").get() || "heatmap"; - var stash = colorAxes[colorAx]; - if (stash) { - stash[2].push(thisFn); - if (stash[0] !== colorbarVisuals) { - stash[0] = false; - Lib$1O.warn([ - "Ignoring coloraxis:", - colorAx, - "setting", - "as it is linked to incompatible colorscales." - ].join(" ")); - } - } else { - colorAxes[colorAx] = [colorbarVisuals, parentContOut, [thisFn]]; - } - return; - } - } - var minIn = containerIn[cLetter + "min"]; - var maxIn = containerIn[cLetter + "max"]; - var validMinMax = isNumeric$r(minIn) && isNumeric$r(maxIn) && minIn < maxIn; - var auto = coerce2(prefix + cLetter + "auto", !validMinMax); - if (auto) { - coerce2(prefix + cLetter + "mid"); - } else { - coerce2(prefix + cLetter + "min"); - coerce2(prefix + cLetter + "max"); - } - var sclIn = containerIn.colorscale; - var sclTemplate = template.colorscale; - var autoColorscaleDflt; - if (sclIn !== void 0) autoColorscaleDflt = !isValidScale(sclIn); - if (sclTemplate !== void 0) autoColorscaleDflt = !isValidScale(sclTemplate); - coerce2(prefix + "autocolorscale", autoColorscaleDflt); - coerce2(prefix + "colorscale"); - coerce2(prefix + "reversescale"); - if (prefix !== "marker.line.") { - var showScaleDflt; - if (prefix && inTrace) showScaleDflt = hasColorbar2(containerIn); - var showScale = coerce2(prefix + "showscale", showScaleDflt); - if (showScale) { - if (prefix && template) containerOut._template = template; - colorbarDefaults2(containerIn, containerOut, layout); - } - } -}; -var Lib$1N = libExports; -var Template$6 = plot_template; -var colorScaleAttrs$5 = layout_attributes$3; -var colorScaleDefaults2 = defaults$n; -var layout_defaults$6 = function supplyLayoutDefaults(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$1N.coerce(layoutIn, layoutOut, colorScaleAttrs$5, attr, dflt); - } - coerce2("colorscale.sequential"); - coerce2("colorscale.sequentialminus"); - coerce2("colorscale.diverging"); - var colorAxes = layoutOut._colorAxes; - var colorAxIn, colorAxOut; - function coerceAx(attr, dflt) { - return Lib$1N.coerce(colorAxIn, colorAxOut, colorScaleAttrs$5.coloraxis, attr, dflt); - } - for (var k in colorAxes) { - var stash = colorAxes[k]; - if (stash[0]) { - colorAxIn = layoutIn[k] || {}; - colorAxOut = Template$6.newContainer(layoutOut, k, "coloraxis"); - colorAxOut._name = k; - colorScaleDefaults2(colorAxIn, colorAxOut, layoutOut, coerceAx, { prefix: "", cLetter: "c" }); - } else { - for (var i = 0; i < stash[2].length; i++) { - stash[2][i](); - } - delete layoutOut._colorAxes[k]; - } - } -}; -var Lib$1M = libExports; -var hasColorscale$6 = helpers$L.hasColorscale; -var extractOpts$2 = helpers$L.extractOpts; -var cross_trace_defaults$2 = function crossTraceDefaults(fullData, fullLayout) { - function replace(cont, k2) { - var val = cont["_" + k2]; - if (val !== void 0) { - cont[k2] = val; - } - } - function relinkColorAttrs(outerCont, cbOpt) { - var cont = cbOpt.container ? Lib$1M.nestedProperty(outerCont, cbOpt.container).get() : outerCont; - if (cont) { - if (cont.coloraxis) { - cont._colorAx = fullLayout[cont.coloraxis]; - } else { - var cOpts = extractOpts$2(cont); - var isAuto = cOpts.auto; - if (isAuto || cOpts.min === void 0) { - replace(cont, cbOpt.min); - } - if (isAuto || cOpts.max === void 0) { - replace(cont, cbOpt.max); - } - if (cOpts.autocolorscale) { - replace(cont, "colorscale"); - } - } - } - } - for (var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - var cbOpts = trace._module.colorbar; - if (cbOpts) { - if (Array.isArray(cbOpts)) { - for (var j = 0; j < cbOpts.length; j++) { - relinkColorAttrs(trace, cbOpts[j]); - } - } else { - relinkColorAttrs(trace, cbOpts); - } - } - if (hasColorscale$6(trace, "marker.line")) { - relinkColorAttrs(trace, { - container: "marker.line", - min: "cmin", - max: "cmax" - }); - } - } - for (var k in fullLayout._colorAxes) { - relinkColorAttrs(fullLayout[k], { min: "cmin", max: "cmax" }); - } -}; -var isNumeric$q = fastIsnumeric; -var Lib$1L = libExports; -var extractOpts$1 = helpers$L.extractOpts; -var calc$c = function calc(gd, trace, opts) { - var fullLayout = gd._fullLayout; - var vals = opts.vals; - var containerStr = opts.containerStr; - var container = containerStr ? Lib$1L.nestedProperty(trace, containerStr).get() : trace; - var cOpts = extractOpts$1(container); - var auto = cOpts.auto !== false; - var min = cOpts.min; - var max = cOpts.max; - var mid = cOpts.mid; - var minVal = function() { - return Lib$1L.aggNums(Math.min, null, vals); - }; - var maxVal = function() { - return Lib$1L.aggNums(Math.max, null, vals); - }; - if (min === void 0) { - min = minVal(); - } else if (auto) { - if (container._colorAx && isNumeric$q(min)) { - min = Math.min(min, minVal()); - } else { - min = minVal(); - } - } - if (max === void 0) { - max = maxVal(); - } else if (auto) { - if (container._colorAx && isNumeric$q(max)) { - max = Math.max(max, maxVal()); - } else { - max = maxVal(); - } - } - if (auto && mid !== void 0) { - if (max - mid > mid - min) { - min = mid - (max - mid); - } else if (max - mid < mid - min) { - max = mid + (mid - min); - } - } - if (min === max) { - min -= 0.5; - max += 0.5; - } - cOpts._sync("min", min); - cOpts._sync("max", max); - if (cOpts.autocolorscale) { - var scl; - if (min * max < 0) scl = fullLayout.colorscale.diverging; - else if (min >= 0) scl = fullLayout.colorscale.sequential; - else scl = fullLayout.colorscale.sequentialminus; - cOpts._sync("colorscale", scl); - } -}; -var scales = scales_1; -var helpers$K = helpers$L; -var colorscale = { - moduleType: "component", - name: "colorscale", - attributes: attributes$I, - layoutAttributes: layout_attributes$3, - supplyLayoutDefaults: layout_defaults$6, - handleDefaults: defaults$n, - crossTraceDefaults: cross_trace_defaults$2, - calc: calc$c, - // ./scales.js is required in lib/coerce.js ; - // it needs to be a separate module to avoid a circular dependency - scales: scales.scales, - defaultScale: scales.defaultScale, - getScale: scales.get, - isValidScale: scales.isValid, - hasColorscale: helpers$K.hasColorscale, - extractOpts: helpers$K.extractOpts, - extractScale: helpers$K.extractScale, - flipScale: helpers$K.flipScale, - makeColorScaleFunc: helpers$K.makeColorScaleFunc, - makeColorScaleFuncFromTrace: helpers$K.makeColorScaleFuncFromTrace -}; -var Lib$1K = libExports; -var isTypedArraySpec$1 = array$2.isTypedArraySpec; -var subtypes$3 = { - hasLines: function(trace) { - return trace.visible && trace.mode && trace.mode.indexOf("lines") !== -1; - }, - hasMarkers: function(trace) { - return trace.visible && (trace.mode && trace.mode.indexOf("markers") !== -1 || // until splom implements 'mode' - trace.type === "splom"); - }, - hasText: function(trace) { - return trace.visible && trace.mode && trace.mode.indexOf("text") !== -1; - }, - isBubble: function(trace) { - var marker2 = trace.marker; - return Lib$1K.isPlainObject(marker2) && (Lib$1K.isArrayOrTypedArray(marker2.size) || isTypedArraySpec$1(marker2.size)); - } -}; -var isNumeric$p = fastIsnumeric; -var make_bubble_size_func = function makeBubbleSizeFn(trace, factor) { - if (!factor) { - factor = 2; - } - var marker2 = trace.marker; - var sizeRef = marker2.sizeref || 1; - var sizeMin = marker2.sizemin || 0; - var baseFn = marker2.sizemode === "area" ? function(v) { - return Math.sqrt(v / sizeRef); - } : function(v) { - return v / sizeRef; - }; - return function(v) { - var baseSize = baseFn(v / factor); - return isNumeric$p(baseSize) && baseSize > 0 ? Math.max(baseSize, sizeMin) : 0; - }; -}; -var helpers$J = {}; -(function(exports2) { - var Lib2 = libExports; - exports2.getSubplot = function(trace) { - return trace.subplot || trace.xaxis + trace.yaxis || trace.geo; - }; - exports2.isTraceInSubplots = function(trace, subplots) { - if (trace.type === "splom") { - var xaxes = trace.xaxes || []; - var yaxes = trace.yaxes || []; - for (var i = 0; i < xaxes.length; i++) { - for (var j = 0; j < yaxes.length; j++) { - if (subplots.indexOf(xaxes[i] + yaxes[j]) !== -1) { - return true; - } - } - } - return false; - } - return subplots.indexOf(exports2.getSubplot(trace)) !== -1; - }; - exports2.flat = function(subplots, v) { - var out = new Array(subplots.length); - for (var i = 0; i < subplots.length; i++) { - out[i] = v; - } - return out; - }; - exports2.p2c = function(axArray, v) { - var out = new Array(axArray.length); - for (var i = 0; i < axArray.length; i++) { - out[i] = axArray[i].p2c(v); - } - return out; - }; - exports2.getDistanceFunction = function(mode, dx, dy, dxy) { - if (mode === "closest") return dxy || exports2.quadrature(dx, dy); - return mode.charAt(0) === "x" ? dx : dy; - }; - exports2.getClosest = function(cd, distfn, pointData) { - if (pointData.index !== false) { - if (pointData.index >= 0 && pointData.index < cd.length) { - pointData.distance = 0; - } else pointData.index = false; - } else { - for (var i = 0; i < cd.length; i++) { - var newDistance = distfn(cd[i]); - if (newDistance <= pointData.distance) { - pointData.index = i; - pointData.distance = newDistance; - } - } - } - return pointData; - }; - exports2.inbox = function(v0, v1, passVal) { - return v0 * v1 < 0 || v0 === 0 ? passVal : Infinity; - }; - exports2.quadrature = function(dx, dy) { - return function(di) { - var x = dx(di); - var y = dy(di); - return Math.sqrt(x * x + y * y); - }; - }; - exports2.makeEventData = function(pt, trace, cd) { - var pointNumber = "index" in pt ? pt.index : pt.pointNumber; - var out = { - data: trace._input, - fullData: trace, - curveNumber: trace.index, - pointNumber - }; - if (trace._indexToPoints) { - var pointIndices = trace._indexToPoints[pointNumber]; - if (pointIndices.length === 1) { - out.pointIndex = pointIndices[0]; - } else { - out.pointIndices = pointIndices; - } - } else { - out.pointIndex = pointNumber; - } - if (trace._module.eventData) { - out = trace._module.eventData(out, pt, trace, cd, pointNumber); - } else { - if ("xVal" in pt) out.x = pt.xVal; - else if ("x" in pt) out.x = pt.x; - if ("yVal" in pt) out.y = pt.yVal; - else if ("y" in pt) out.y = pt.y; - if (pt.xa) out.xaxis = pt.xa; - if (pt.ya) out.yaxis = pt.ya; - if (pt.zLabelVal !== void 0) out.z = pt.zLabelVal; - } - exports2.appendArrayPointValue(out, trace, pointNumber); - return out; - }; - exports2.appendArrayPointValue = function(pointData, trace, pointNumber) { - var arrayAttrs = trace._arrayAttrs; - if (!arrayAttrs) { - return; - } - for (var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); - if (pointData[key] === void 0) { - var val = Lib2.nestedProperty(trace, astr).get(); - var pointVal = getPointData(val, pointNumber); - if (pointVal !== void 0) pointData[key] = pointVal; - } - } - }; - exports2.appendArrayMultiPointValues = function(pointData, trace, pointNumbers) { - var arrayAttrs = trace._arrayAttrs; - if (!arrayAttrs) { - return; - } - for (var i = 0; i < arrayAttrs.length; i++) { - var astr = arrayAttrs[i]; - var key = getPointKey(astr); - if (pointData[key] === void 0) { - var val = Lib2.nestedProperty(trace, astr).get(); - var keyVal = new Array(pointNumbers.length); - for (var j = 0; j < pointNumbers.length; j++) { - keyVal[j] = getPointData(val, pointNumbers[j]); - } - pointData[key] = keyVal; - } - } - }; - var pointKeyMap = { - ids: "id", - locations: "location", - labels: "label", - values: "value", - "marker.colors": "color", - parents: "parent" - }; - function getPointKey(astr) { - return pointKeyMap[astr] || astr; - } - function getPointData(val, pointNumber) { - if (Array.isArray(pointNumber)) { - if (Array.isArray(val) && Array.isArray(val[pointNumber[0]])) { - return val[pointNumber[0]][pointNumber[1]]; - } - } else { - return val[pointNumber]; - } - } - var xyHoverMode = { - x: true, - y: true - }; - var unifiedHoverMode = { - "x unified": true, - "y unified": true - }; - exports2.isUnifiedHover = function(hovermode) { - if (typeof hovermode !== "string") return false; - return !!unifiedHoverMode[hovermode]; - }; - exports2.isXYhover = function(hovermode) { - if (typeof hovermode !== "string") return false; - return !!xyHoverMode[hovermode]; - }; -})(helpers$J); -var parseSvgPath = parse$5; -var length = { a: 7, c: 6, h: 1, l: 2, m: 2, q: 4, s: 4, t: 2, v: 1, z: 0 }; -var segment = /([astvzqmhlc])([^astvzqmhlc]*)/ig; -function parse$5(path) { - var data = []; - path.replace(segment, function(_2, command2, args) { - var type = command2.toLowerCase(); - args = parseValues(args); - if (type == "m" && args.length > 2) { - data.push([command2].concat(args.splice(0, 2))); - type = "l"; - command2 = command2 == "m" ? "l" : "L"; - } - while (true) { - if (args.length == length[type]) { - args.unshift(command2); - return data.push(args); - } - if (args.length < length[type]) throw new Error("malformed path data"); - data.push([command2].concat(args.splice(0, length[type]))); - } - }); - return data; -} -var number$1 = /-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig; -function parseValues(args) { - var numbers = args.match(number$1); - return numbers ? numbers.map(Number) : []; -} -var symbol_defs; -var hasRequiredSymbol_defs; -function requireSymbol_defs() { - if (hasRequiredSymbol_defs) return symbol_defs; - hasRequiredSymbol_defs = 1; - var parseSvgPath$1 = parseSvgPath; - var round2 = d3Exports.round; - var emptyPath = "M0,0Z"; - var sqrt2 = Math.sqrt(2); - var sqrt3 = Math.sqrt(3); - var PI2 = Math.PI; - var cos2 = Math.cos; - var sin2 = Math.sin; - symbol_defs = { - circle: { - n: 0, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - var circle = "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"; - return standoff ? align3(angle, standoff, circle) : circle; - } - }, - square: { - n: 1, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); - } - }, - diamond: { - n: 2, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rd = round2(r * 1.3, 2); - return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "Z"); - } - }, - cross: { - n: 3, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rc = round2(r * 0.4, 2); - var rc2 = round2(r * 1.2, 2); - return align3(angle, standoff, "M" + rc2 + "," + rc + "H" + rc + "V" + rc2 + "H-" + rc + "V" + rc + "H-" + rc2 + "V-" + rc + "H-" + rc + "V-" + rc2 + "H" + rc + "V-" + rc + "H" + rc2 + "Z"); - } - }, - x: { - n: 4, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r * 0.8 / sqrt2, 2); - var ne = "l" + rx + "," + rx; - var se = "l" + rx + ",-" + rx; - var sw = "l-" + rx + ",-" + rx; - var nw = "l-" + rx + "," + rx; - return align3(angle, standoff, "M0," + rx + ne + se + sw + se + sw + nw + sw + nw + ne + nw + ne + "Z"); - } - }, - "triangle-up": { - n: 5, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rt = round2(r * 2 / sqrt3, 2); - var r2 = round2(r / 2, 2); - var rs = round2(r, 2); - return align3(angle, standoff, "M-" + rt + "," + r2 + "H" + rt + "L0,-" + rs + "Z"); - } - }, - "triangle-down": { - n: 6, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rt = round2(r * 2 / sqrt3, 2); - var r2 = round2(r / 2, 2); - var rs = round2(r, 2); - return align3(angle, standoff, "M-" + rt + ",-" + r2 + "H" + rt + "L0," + rs + "Z"); - } - }, - "triangle-left": { - n: 7, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rt = round2(r * 2 / sqrt3, 2); - var r2 = round2(r / 2, 2); - var rs = round2(r, 2); - return align3(angle, standoff, "M" + r2 + ",-" + rt + "V" + rt + "L-" + rs + ",0Z"); - } - }, - "triangle-right": { - n: 8, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rt = round2(r * 2 / sqrt3, 2); - var r2 = round2(r / 2, 2); - var rs = round2(r, 2); - return align3(angle, standoff, "M-" + r2 + ",-" + rt + "V" + rt + "L" + rs + ",0Z"); - } - }, - "triangle-ne": { - n: 9, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var r1 = round2(r * 0.6, 2); - var r2 = round2(r * 1.2, 2); - return align3(angle, standoff, "M-" + r2 + ",-" + r1 + "H" + r1 + "V" + r2 + "Z"); - } - }, - "triangle-se": { - n: 10, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var r1 = round2(r * 0.6, 2); - var r2 = round2(r * 1.2, 2); - return align3(angle, standoff, "M" + r1 + ",-" + r2 + "V" + r1 + "H-" + r2 + "Z"); - } - }, - "triangle-sw": { - n: 11, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var r1 = round2(r * 0.6, 2); - var r2 = round2(r * 1.2, 2); - return align3(angle, standoff, "M" + r2 + "," + r1 + "H-" + r1 + "V-" + r2 + "Z"); - } - }, - "triangle-nw": { - n: 12, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var r1 = round2(r * 0.6, 2); - var r2 = round2(r * 1.2, 2); - return align3(angle, standoff, "M-" + r1 + "," + r2 + "V-" + r1 + "H" + r2 + "Z"); - } - }, - pentagon: { - n: 13, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x1 = round2(r * 0.951, 2); - var x2 = round2(r * 0.588, 2); - var y0 = round2(-r, 2); - var y1 = round2(r * -0.309, 2); - var y2 = round2(r * 0.809, 2); - return align3(angle, standoff, "M" + x1 + "," + y1 + "L" + x2 + "," + y2 + "H-" + x2 + "L-" + x1 + "," + y1 + "L0," + y0 + "Z"); - } - }, - hexagon: { - n: 14, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var y0 = round2(r, 2); - var y1 = round2(r / 2, 2); - var x = round2(r * sqrt3 / 2, 2); - return align3(angle, standoff, "M" + x + ",-" + y1 + "V" + y1 + "L0," + y0 + "L-" + x + "," + y1 + "V-" + y1 + "L0,-" + y0 + "Z"); - } - }, - hexagon2: { - n: 15, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x0 = round2(r, 2); - var x1 = round2(r / 2, 2); - var y = round2(r * sqrt3 / 2, 2); - return align3(angle, standoff, "M-" + x1 + "," + y + "H" + x1 + "L" + x0 + ",0L" + x1 + ",-" + y + "H-" + x1 + "L-" + x0 + ",0Z"); - } - }, - octagon: { - n: 16, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var a = round2(r * 0.924, 2); - var b = round2(r * 0.383, 2); - return align3(angle, standoff, "M-" + b + ",-" + a + "H" + b + "L" + a + ",-" + b + "V" + b + "L" + b + "," + a + "H-" + b + "L-" + a + "," + b + "V-" + b + "Z"); - } - }, - star: { - n: 17, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = r * 1.4; - var x1 = round2(rs * 0.225, 2); - var x2 = round2(rs * 0.951, 2); - var x3 = round2(rs * 0.363, 2); - var x4 = round2(rs * 0.588, 2); - var y0 = round2(-rs, 2); - var y1 = round2(rs * -0.309, 2); - var y3 = round2(rs * 0.118, 2); - var y4 = round2(rs * 0.809, 2); - var y5 = round2(rs * 0.382, 2); - return align3(angle, standoff, "M" + x1 + "," + y1 + "H" + x2 + "L" + x3 + "," + y3 + "L" + x4 + "," + y4 + "L0," + y5 + "L-" + x4 + "," + y4 + "L-" + x3 + "," + y3 + "L-" + x2 + "," + y1 + "H-" + x1 + "L0," + y0 + "Z"); - } - }, - hexagram: { - n: 18, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var y = round2(r * 0.66, 2); - var x1 = round2(r * 0.38, 2); - var x2 = round2(r * 0.76, 2); - return align3(angle, standoff, "M-" + x2 + ",0l-" + x1 + ",-" + y + "h" + x2 + "l" + x1 + ",-" + y + "l" + x1 + "," + y + "h" + x2 + "l-" + x1 + "," + y + "l" + x1 + "," + y + "h-" + x2 + "l-" + x1 + "," + y + "l-" + x1 + ",-" + y + "h-" + x2 + "Z"); - } - }, - "star-triangle-up": { - n: 19, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * sqrt3 * 0.8, 2); - var y1 = round2(r * 0.8, 2); - var y2 = round2(r * 1.6, 2); - var rc = round2(r * 4, 2); - var aPart = "A " + rc + "," + rc + " 0 0 1 "; - return align3(angle, standoff, "M-" + x + "," + y1 + aPart + x + "," + y1 + aPart + "0,-" + y2 + aPart + "-" + x + "," + y1 + "Z"); - } - }, - "star-triangle-down": { - n: 20, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * sqrt3 * 0.8, 2); - var y1 = round2(r * 0.8, 2); - var y2 = round2(r * 1.6, 2); - var rc = round2(r * 4, 2); - var aPart = "A " + rc + "," + rc + " 0 0 1 "; - return align3(angle, standoff, "M" + x + ",-" + y1 + aPart + "-" + x + ",-" + y1 + aPart + "0," + y2 + aPart + x + ",-" + y1 + "Z"); - } - }, - "star-square": { - n: 21, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rp = round2(r * 1.1, 2); - var rc = round2(r * 2, 2); - var aPart = "A " + rc + "," + rc + " 0 0 1 "; - return align3(angle, standoff, "M-" + rp + ",-" + rp + aPart + "-" + rp + "," + rp + aPart + rp + "," + rp + aPart + rp + ",-" + rp + aPart + "-" + rp + ",-" + rp + "Z"); - } - }, - "star-diamond": { - n: 22, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rp = round2(r * 1.4, 2); - var rc = round2(r * 1.9, 2); - var aPart = "A " + rc + "," + rc + " 0 0 1 "; - return align3(angle, standoff, "M-" + rp + ",0" + aPart + "0," + rp + aPart + rp + ",0" + aPart + "0,-" + rp + aPart + "-" + rp + ",0Z"); - } - }, - "diamond-tall": { - n: 23, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * 0.7, 2); - var y = round2(r * 1.4, 2); - return align3(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z"); - } - }, - "diamond-wide": { - n: 24, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * 1.4, 2); - var y = round2(r * 0.7, 2); - return align3(angle, standoff, "M0," + y + "L" + x + ",0L0,-" + y + "L-" + x + ",0Z"); - } - }, - hourglass: { - n: 25, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M" + rs + "," + rs + "H-" + rs + "L" + rs + ",-" + rs + "H-" + rs + "Z"); - }, - noDot: true - }, - bowtie: { - n: 26, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M" + rs + "," + rs + "V-" + rs + "L-" + rs + "," + rs + "V-" + rs + "Z"); - }, - noDot: true - }, - "circle-cross": { - n: 27, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"); - }, - needLine: true, - noDot: true - }, - "circle-x": { - n: 28, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - var rc = round2(r / sqrt2, 2); - return align3(angle, standoff, "M" + rc + "," + rc + "L-" + rc + ",-" + rc + "M" + rc + ",-" + rc + "L-" + rc + "," + rc + "M" + rs + ",0A" + rs + "," + rs + " 0 1,1 0,-" + rs + "A" + rs + "," + rs + " 0 0,1 " + rs + ",0Z"); - }, - needLine: true, - noDot: true - }, - "square-cross": { - n: 29, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M0," + rs + "V-" + rs + "M" + rs + ",0H-" + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); - }, - needLine: true, - noDot: true - }, - "square-x": { - n: 30, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rs = round2(r, 2); - return align3(angle, standoff, "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs + "M" + rs + "," + rs + "H-" + rs + "V-" + rs + "H" + rs + "Z"); - }, - needLine: true, - noDot: true - }, - "diamond-cross": { - n: 31, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rd = round2(r * 1.3, 2); - return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM0,-" + rd + "V" + rd + "M-" + rd + ",0H" + rd); - }, - needLine: true, - noDot: true - }, - "diamond-x": { - n: 32, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rd = round2(r * 1.3, 2); - var r2 = round2(r * 0.65, 2); - return align3(angle, standoff, "M" + rd + ",0L0," + rd + "L-" + rd + ",0L0,-" + rd + "ZM-" + r2 + ",-" + r2 + "L" + r2 + "," + r2 + "M-" + r2 + "," + r2 + "L" + r2 + ",-" + r2); - }, - needLine: true, - noDot: true - }, - "cross-thin": { - n: 33, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rc = round2(r * 1.4, 2); - return align3(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc); - }, - needLine: true, - noDot: true, - noFill: true - }, - "x-thin": { - n: 34, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - return align3(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx + "M" + rx + ",-" + rx + "L-" + rx + "," + rx); - }, - needLine: true, - noDot: true, - noFill: true - }, - asterisk: { - n: 35, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rc = round2(r * 1.2, 2); - var rs = round2(r * 0.85, 2); - return align3(angle, standoff, "M0," + rc + "V-" + rc + "M" + rc + ",0H-" + rc + "M" + rs + "," + rs + "L-" + rs + ",-" + rs + "M" + rs + ",-" + rs + "L-" + rs + "," + rs); - }, - needLine: true, - noDot: true, - noFill: true - }, - hash: { - n: 36, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var r1 = round2(r / 2, 2); - var r2 = round2(r, 2); - return align3(angle, standoff, "M" + r1 + "," + r2 + "V-" + r2 + "M" + (r1 - r2) + ",-" + r2 + "V" + r2 + "M" + r2 + "," + r1 + "H-" + r2 + "M-" + r2 + "," + (r1 - r2) + "H" + r2); - }, - needLine: true, - noFill: true - }, - "y-up": { - n: 37, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * 1.2, 2); - var y0 = round2(r * 1.6, 2); - var y1 = round2(r * 0.8, 2); - return align3(angle, standoff, "M-" + x + "," + y1 + "L0,0M" + x + "," + y1 + "L0,0M0,-" + y0 + "L0,0"); - }, - needLine: true, - noDot: true, - noFill: true - }, - "y-down": { - n: 38, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var x = round2(r * 1.2, 2); - var y0 = round2(r * 1.6, 2); - var y1 = round2(r * 0.8, 2); - return align3(angle, standoff, "M-" + x + ",-" + y1 + "L0,0M" + x + ",-" + y1 + "L0,0M0," + y0 + "L0,0"); - }, - needLine: true, - noDot: true, - noFill: true - }, - "y-left": { - n: 39, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var y = round2(r * 1.2, 2); - var x0 = round2(r * 1.6, 2); - var x1 = round2(r * 0.8, 2); - return align3(angle, standoff, "M" + x1 + "," + y + "L0,0M" + x1 + ",-" + y + "L0,0M-" + x0 + ",0L0,0"); - }, - needLine: true, - noDot: true, - noFill: true - }, - "y-right": { - n: 40, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var y = round2(r * 1.2, 2); - var x0 = round2(r * 1.6, 2); - var x1 = round2(r * 0.8, 2); - return align3(angle, standoff, "M-" + x1 + "," + y + "L0,0M-" + x1 + ",-" + y + "L0,0M" + x0 + ",0L0,0"); - }, - needLine: true, - noDot: true, - noFill: true - }, - "line-ew": { - n: 41, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rc = round2(r * 1.4, 2); - return align3(angle, standoff, "M" + rc + ",0H-" + rc); - }, - needLine: true, - noDot: true, - noFill: true - }, - "line-ns": { - n: 42, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rc = round2(r * 1.4, 2); - return align3(angle, standoff, "M0," + rc + "V-" + rc); - }, - needLine: true, - noDot: true, - noFill: true - }, - "line-ne": { - n: 43, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - return align3(angle, standoff, "M" + rx + ",-" + rx + "L-" + rx + "," + rx); - }, - needLine: true, - noDot: true, - noFill: true - }, - "line-nw": { - n: 44, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - return align3(angle, standoff, "M" + rx + "," + rx + "L-" + rx + ",-" + rx); - }, - needLine: true, - noDot: true, - noFill: true - }, - "arrow-up": { - n: 45, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - var ry = round2(r * 2, 2); - return align3(angle, standoff, "M0,0L-" + rx + "," + ry + "H" + rx + "Z"); - }, - backoff: 1, - noDot: true - }, - "arrow-down": { - n: 46, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - var ry = round2(r * 2, 2); - return align3(angle, standoff, "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z"); - }, - noDot: true - }, - "arrow-left": { - n: 47, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r * 2, 2); - var ry = round2(r, 2); - return align3(angle, standoff, "M0,0L" + rx + ",-" + ry + "V" + ry + "Z"); - }, - noDot: true - }, - "arrow-right": { - n: 48, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r * 2, 2); - var ry = round2(r, 2); - return align3(angle, standoff, "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z"); - }, - noDot: true - }, - "arrow-bar-up": { - n: 49, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - var ry = round2(r * 2, 2); - return align3(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + "," + ry + "H" + rx + "Z"); - }, - backoff: 1, - needLine: true, - noDot: true - }, - "arrow-bar-down": { - n: 50, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r, 2); - var ry = round2(r * 2, 2); - return align3(angle, standoff, "M-" + rx + ",0H" + rx + "M0,0L-" + rx + ",-" + ry + "H" + rx + "Z"); - }, - needLine: true, - noDot: true - }, - "arrow-bar-left": { - n: 51, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r * 2, 2); - var ry = round2(r, 2); - return align3(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L" + rx + ",-" + ry + "V" + ry + "Z"); - }, - needLine: true, - noDot: true - }, - "arrow-bar-right": { - n: 52, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var rx = round2(r * 2, 2); - var ry = round2(r, 2); - return align3(angle, standoff, "M0,-" + ry + "V" + ry + "M0,0L-" + rx + ",-" + ry + "V" + ry + "Z"); - }, - needLine: true, - noDot: true - }, - arrow: { - n: 53, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var headAngle = PI2 / 2.5; - var x = 2 * r * cos2(headAngle); - var y = 2 * r * sin2(headAngle); - return align3( - angle, - standoff, - "M0,0L" + -x + "," + y + "L" + x + "," + y + "Z" - ); - }, - backoff: 0.9, - noDot: true - }, - "arrow-wide": { - n: 54, - f: function(r, angle, standoff) { - if (skipAngle(angle)) return emptyPath; - var headAngle = PI2 / 4; - var x = 2 * r * cos2(headAngle); - var y = 2 * r * sin2(headAngle); - return align3( - angle, - standoff, - "M0,0L" + -x + "," + y + "A " + 2 * r + "," + 2 * r + " 0 0 1 " + x + "," + y + "Z" - ); - }, - backoff: 0.4, - noDot: true - } - }; - function skipAngle(angle) { - return angle === null; - } - var lastPathIn, lastPathOut; - var lastAngle, lastStandoff; - function align3(angle, standoff, path) { - if ((!angle || angle % 360 === 0) && !standoff) return path; - if (lastAngle === angle && lastStandoff === standoff && lastPathIn === path) return lastPathOut; - lastAngle = angle; - lastStandoff = standoff; - lastPathIn = path; - function rotate2(t4, xy) { - var cosT = cos2(t4); - var sinT = sin2(t4); - var x2 = xy[0]; - var y2 = xy[1] + (standoff || 0); - return [ - x2 * cosT - y2 * sinT, - x2 * sinT + y2 * cosT - ]; - } - var t = angle / 180 * PI2; - var x = 0; - var y = 0; - var cmd = parseSvgPath$1(path); - var str2 = ""; - for (var i = 0; i < cmd.length; i++) { - var cmdI = cmd[i]; - var op = cmdI[0]; - var x0 = x; - var y0 = y; - if (op === "M" || op === "L") { - x = +cmdI[1]; - y = +cmdI[2]; - } else if (op === "m" || op === "l") { - x += +cmdI[1]; - y += +cmdI[2]; - } else if (op === "H") { - x = +cmdI[1]; - } else if (op === "h") { - x += +cmdI[1]; - } else if (op === "V") { - y = +cmdI[1]; - } else if (op === "v") { - y += +cmdI[1]; - } else if (op === "A") { - x = +cmdI[1]; - y = +cmdI[2]; - var E2 = rotate2(t, [+cmdI[6], +cmdI[7]]); - cmdI[6] = E2[0]; - cmdI[7] = E2[1]; - cmdI[3] = +cmdI[3] + angle; - } - if (op === "H" || op === "V") op = "L"; - if (op === "h" || op === "v") op = "l"; - if (op === "m" || op === "l") { - x -= x0; - y -= y0; - } - var B2 = rotate2(t, [x, y]); - if (op === "H" || op === "V") op = "L"; - if (op === "M" || op === "L" || op === "m" || op === "l") { - cmdI[1] = B2[0]; - cmdI[2] = B2[1]; - } - cmdI[0] = op; - str2 += cmdI[0] + cmdI.slice(1).join(","); - } - lastPathOut = str2; - return str2; - } - return symbol_defs; -} -var d3$z = d3Exports; -var Lib$1J = libExports; -var numberFormat$1 = Lib$1J.numberFormat; -var isNumeric$o = fastIsnumeric; -var tinycolor$4 = tinycolorExports; -var Registry$L = registry; -var Color$J = colorExports; -var Colorscale$2 = colorscale; -var strTranslate$c = Lib$1J.strTranslate; -var svgTextUtils$f = svg_text_utils; -var xmlnsNamespaces$3 = xmlns_namespaces; -var alignment = alignment$1; -var LINE_SPACING$7 = alignment.LINE_SPACING; -var DESELECTDIM$2 = interactions.DESELECTDIM; -var subTypes$a = subtypes$3; -var makeBubbleSizeFn$1 = make_bubble_size_func; -var appendArrayPointValue$3 = helpers$J.appendArrayPointValue; -var drawing = drawing$1.exports = {}; -drawing.font = function(s, font2) { - var variant = font2.variant; - var style5 = font2.style; - var weight = font2.weight; - var color2 = font2.color; - var size = font2.size; - var family = font2.family; - var shadow = font2.shadow; - var lineposition = font2.lineposition; - var textcase = font2.textcase; - if (family) s.style("font-family", family); - if (size + 1) s.style("font-size", size + "px"); - if (color2) s.call(Color$J.fill, color2); - if (weight) s.style("font-weight", weight); - if (style5) s.style("font-style", style5); - if (variant) s.style("font-variant", variant); - if (textcase) s.style("text-transform", dropNone(textcase2transform(textcase))); - if (shadow) s.style("text-shadow", shadow === "auto" ? svgTextUtils$f.makeTextShadow(Color$J.contrast(color2)) : dropNone(shadow)); - if (lineposition) s.style("text-decoration-line", dropNone(lineposition2decorationLine(lineposition))); -}; -function dropNone(a) { - return a === "none" ? void 0 : a; -} -var textcase2transformOptions = { - normal: "none", - lower: "lowercase", - upper: "uppercase", - "word caps": "capitalize" -}; -function textcase2transform(textcase) { - return textcase2transformOptions[textcase]; -} -function lineposition2decorationLine(lineposition) { - return lineposition.replace("under", "underline").replace("over", "overline").replace("through", "line-through").split("+").join(" "); -} -drawing.setPosition = function(s, x, y) { - s.attr("x", x).attr("y", y); -}; -drawing.setSize = function(s, w, h) { - s.attr("width", w).attr("height", h); -}; -drawing.setRect = function(s, x, y, w, h) { - s.call(drawing.setPosition, x, y).call(drawing.setSize, w, h); -}; -drawing.translatePoint = function(d, sel, xa, ya) { - var x = xa.c2p(d.x); - var y = ya.c2p(d.y); - if (isNumeric$o(x) && isNumeric$o(y) && sel.node()) { - if (sel.node().nodeName === "text") { - sel.attr("x", x).attr("y", y); - } else { - sel.attr("transform", strTranslate$c(x, y)); - } - } else { - return false; - } - return true; -}; -drawing.translatePoints = function(s, xa, ya) { - s.each(function(d) { - var sel = d3$z.select(this); - drawing.translatePoint(d, sel, xa, ya); - }); -}; -drawing.hideOutsideRangePoint = function(d, sel, xa, ya, xcalendar, ycalendar) { - sel.attr( - "display", - xa.isPtWithinRange(d, xcalendar) && ya.isPtWithinRange(d, ycalendar) ? null : "none" - ); -}; -drawing.hideOutsideRangePoints = function(traceGroups, subplot) { - if (!subplot._hasClipOnAxisFalse) return; - var xa = subplot.xaxis; - var ya = subplot.yaxis; - traceGroups.each(function(d) { - var trace = d[0].trace; - var xcalendar = trace.xcalendar; - var ycalendar = trace.ycalendar; - var selector = Registry$L.traceIs(trace, "bar-like") ? ".bartext" : ".point,.textpoint"; - traceGroups.selectAll(selector).each(function(d2) { - drawing.hideOutsideRangePoint(d2, d3$z.select(this), xa, ya, xcalendar, ycalendar); - }); - }); -}; -drawing.crispRound = function(gd, lineWidth, dflt) { - if (!lineWidth || !isNumeric$o(lineWidth)) return dflt || 0; - if (gd._context.staticPlot) return lineWidth; - if (lineWidth < 1) return 1; - return Math.round(lineWidth); -}; -drawing.singleLineStyle = function(d, s, lw, lc, ld) { - s.style("fill", "none"); - var line2 = (((d || [])[0] || {}).trace || {}).line || {}; - var lw1 = lw || line2.width || 0; - var dash2 = ld || line2.dash || ""; - Color$J.stroke(s, lc || line2.color); - drawing.dashLine(s, dash2, lw1); -}; -drawing.lineGroupStyle = function(s, lw, lc, ld) { - s.style("fill", "none").each(function(d) { - var line2 = (((d || [])[0] || {}).trace || {}).line || {}; - var lw1 = lw || line2.width || 0; - var dash2 = ld || line2.dash || ""; - d3$z.select(this).call(Color$J.stroke, lc || line2.color).call(drawing.dashLine, dash2, lw1); - }); -}; -drawing.dashLine = function(s, dash2, lineWidth) { - lineWidth = +lineWidth || 0; - dash2 = drawing.dashStyle(dash2, lineWidth); - s.style({ - "stroke-dasharray": dash2, - "stroke-width": lineWidth + "px" - }); -}; -drawing.dashStyle = function(dash2, lineWidth) { - lineWidth = +lineWidth || 1; - var dlw = Math.max(lineWidth, 3); - if (dash2 === "solid") dash2 = ""; - else if (dash2 === "dot") dash2 = dlw + "px," + dlw + "px"; - else if (dash2 === "dash") dash2 = 3 * dlw + "px," + 3 * dlw + "px"; - else if (dash2 === "longdash") dash2 = 5 * dlw + "px," + 5 * dlw + "px"; - else if (dash2 === "dashdot") { - dash2 = 3 * dlw + "px," + dlw + "px," + dlw + "px," + dlw + "px"; - } else if (dash2 === "longdashdot") { - dash2 = 5 * dlw + "px," + 2 * dlw + "px," + dlw + "px," + 2 * dlw + "px"; - } - return dash2; -}; -function setFillStyle(sel, trace, gd, forLegend) { - var markerPattern = trace.fillpattern; - var fillgradient = trace.fillgradient; - var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, 0, ""); - if (patternShape) { - var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, 0, null); - var patternFGColor = drawing.getPatternAttr(markerPattern.fgcolor, 0, null); - var patternFGOpacity = markerPattern.fgopacity; - var patternSize = drawing.getPatternAttr(markerPattern.size, 0, 8); - var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, 0, 0.3); - var patternID = trace.uid; - drawing.pattern( - sel, - "point", - gd, - patternID, - patternShape, - patternSize, - patternSolidity, - void 0, - markerPattern.fillmode, - patternBGColor, - patternFGColor, - patternFGOpacity - ); - } else if (fillgradient && fillgradient.type !== "none") { - var direction = fillgradient.type; - var gradientID = "scatterfill-" + trace.uid; - if (forLegend) { - gradientID = "legendfill-" + trace.uid; - } - if (!forLegend && (fillgradient.start !== void 0 || fillgradient.stop !== void 0)) { - var start, stop; - if (direction === "horizontal") { - start = { - x: fillgradient.start, - y: 0 - }; - stop = { - x: fillgradient.stop, - y: 0 - }; - } else if (direction === "vertical") { - start = { - x: 0, - y: fillgradient.start - }; - stop = { - x: 0, - y: fillgradient.stop - }; - } - start.x = trace._xA.c2p( - start.x === void 0 ? trace._extremes.x.min[0].val : start.x, - true - ); - start.y = trace._yA.c2p( - start.y === void 0 ? trace._extremes.y.min[0].val : start.y, - true - ); - stop.x = trace._xA.c2p( - stop.x === void 0 ? trace._extremes.x.max[0].val : stop.x, - true - ); - stop.y = trace._yA.c2p( - stop.y === void 0 ? trace._extremes.y.max[0].val : stop.y, - true - ); - sel.call(gradientWithBounds, gd, gradientID, "linear", fillgradient.colorscale, "fill", start, stop, true, false); - } else { - if (direction === "horizontal") { - direction = direction + "reversed"; - } - sel.call(drawing.gradient, gd, gradientID, direction, fillgradient.colorscale, "fill"); - } - } else if (trace.fillcolor) { - sel.call(Color$J.fill, trace.fillcolor); - } -} -drawing.singleFillStyle = function(sel, gd) { - var node = d3$z.select(sel.node()); - var data = node.data(); - var trace = ((data[0] || [])[0] || {}).trace || {}; - setFillStyle(sel, trace, gd, false); -}; -drawing.fillGroupStyle = function(s, gd, forLegend) { - s.style("stroke-width", 0).each(function(d) { - var shape = d3$z.select(this); - if (d[0].trace) { - setFillStyle(shape, d[0].trace, gd, forLegend); - } - }); -}; -var SYMBOLDEFS = requireSymbol_defs(); -drawing.symbolNames = []; -drawing.symbolFuncs = []; -drawing.symbolBackOffs = []; -drawing.symbolNeedLines = {}; -drawing.symbolNoDot = {}; -drawing.symbolNoFill = {}; -drawing.symbolList = []; -Object.keys(SYMBOLDEFS).forEach(function(k) { - var symDef = SYMBOLDEFS[k]; - var n = symDef.n; - drawing.symbolList.push( - n, - String(n), - k, - n + 100, - String(n + 100), - k + "-open" - ); - drawing.symbolNames[n] = k; - drawing.symbolFuncs[n] = symDef.f; - drawing.symbolBackOffs[n] = symDef.backoff || 0; - if (symDef.needLine) { - drawing.symbolNeedLines[n] = true; - } - if (symDef.noDot) { - drawing.symbolNoDot[n] = true; - } else { - drawing.symbolList.push( - n + 200, - String(n + 200), - k + "-dot", - n + 300, - String(n + 300), - k + "-open-dot" - ); - } - if (symDef.noFill) { - drawing.symbolNoFill[n] = true; - } -}); -var MAXSYMBOL = drawing.symbolNames.length; -var DOTPATH = "M0,0.5L0.5,0L0,-0.5L-0.5,0Z"; -drawing.symbolNumber = function(v) { - if (isNumeric$o(v)) { - v = +v; - } else if (typeof v === "string") { - var vbase = 0; - if (v.indexOf("-open") > 0) { - vbase = 100; - v = v.replace("-open", ""); - } - if (v.indexOf("-dot") > 0) { - vbase += 200; - v = v.replace("-dot", ""); - } - v = drawing.symbolNames.indexOf(v); - if (v >= 0) { - v += vbase; - } - } - return v % 100 >= MAXSYMBOL || v >= 400 ? 0 : Math.floor(Math.max(v, 0)); -}; -function makePointPath(symbolNumber, r, t, s) { - var base = symbolNumber % 100; - return drawing.symbolFuncs[base](r, t, s) + (symbolNumber >= 200 ? DOTPATH : ""); -} -var stopFormatter = numberFormat$1("~f"); -var gradientInfo = { - radial: { type: "radial" }, - radialreversed: { type: "radial", reversed: true }, - horizontal: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 } }, - horizontalreversed: { type: "linear", start: { x: 1, y: 0 }, stop: { x: 0, y: 0 }, reversed: true }, - vertical: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 } }, - verticalreversed: { type: "linear", start: { x: 0, y: 1 }, stop: { x: 0, y: 0 }, reversed: true } -}; -drawing.gradient = function(sel, gd, gradientID, type, colorscale2, prop) { - var info = gradientInfo[type]; - return gradientWithBounds( - sel, - gd, - gradientID, - info.type, - colorscale2, - prop, - info.start, - info.stop, - false, - info.reversed - ); -}; -function gradientWithBounds(sel, gd, gradientID, type, colorscale2, prop, start, stop, inUserSpace, reversed) { - var len = colorscale2.length; - var info; - if (type === "linear") { - info = { - node: "linearGradient", - attrs: { - x1: start.x, - y1: start.y, - x2: stop.x, - y2: stop.y, - gradientUnits: inUserSpace ? "userSpaceOnUse" : "objectBoundingBox" - }, - reversed - }; - } else if (type === "radial") { - info = { - node: "radialGradient", - reversed - }; - } - var colorStops = new Array(len); - for (var i = 0; i < len; i++) { - if (info.reversed) { - colorStops[len - 1 - i] = [stopFormatter((1 - colorscale2[i][0]) * 100), colorscale2[i][1]]; - } else { - colorStops[i] = [stopFormatter(colorscale2[i][0] * 100), colorscale2[i][1]]; - } - } - var fullLayout = gd._fullLayout; - var fullID = "g" + fullLayout._uid + "-" + gradientID; - var gradient = fullLayout._defs.select(".gradients").selectAll("#" + fullID).data([type + colorStops.join(";")], Lib$1J.identity); - gradient.exit().remove(); - gradient.enter().append(info.node).each(function() { - var el = d3$z.select(this); - if (info.attrs) el.attr(info.attrs); - el.attr("id", fullID); - var stops = el.selectAll("stop").data(colorStops); - stops.exit().remove(); - stops.enter().append("stop"); - stops.each(function(d) { - var tc = tinycolor$4(d[1]); - d3$z.select(this).attr({ - offset: d[0] + "%", - "stop-color": Color$J.tinyRGB(tc), - "stop-opacity": tc.getAlpha() - }); - }); - }); - sel.style(prop, getFullUrl(fullID, gd)).style(prop + "-opacity", null); - sel.classed("gradient_filled", true); -} -drawing.pattern = function(sel, calledBy, gd, patternID, shape, size, solidity, mcc, fillmode, bgcolor, fgcolor, fgopacity) { - var isLegend = calledBy === "legend"; - if (mcc) { - if (fillmode === "overlay") { - bgcolor = mcc; - fgcolor = Color$J.contrast(bgcolor); - } else { - bgcolor = void 0; - fgcolor = mcc; - } - } - var fullLayout = gd._fullLayout; - var fullID = "p" + fullLayout._uid + "-" + patternID; - var width, height; - var linearFn = function(x, x0, x1, y0, y1) { - return y0 + (y1 - y0) * (x - x0) / (x1 - x0); - }; - var path, linewidth, radius; - var patternTag; - var patternAttrs = {}; - var fgC = tinycolor$4(fgcolor); - var fgRGB = Color$J.tinyRGB(fgC); - var fgAlpha = fgC.getAlpha(); - var opacity = fgopacity * fgAlpha; - switch (shape) { - case "/": - width = size * Math.sqrt(2); - height = size * Math.sqrt(2); - path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2; - linewidth = solidity * size; - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case "\\": - width = size * Math.sqrt(2); - height = size * Math.sqrt(2); - path = "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2; - linewidth = solidity * size; - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case "x": - width = size * Math.sqrt(2); - height = size * Math.sqrt(2); - path = "M-" + width / 4 + "," + height / 4 + "l" + width / 2 + ",-" + height / 2 + "M0," + height + "L" + width + ",0M" + width / 4 * 3 + "," + height / 4 * 5 + "l" + width / 2 + ",-" + height / 2 + "M" + width / 4 * 3 + ",-" + height / 4 + "l" + width / 2 + "," + height / 2 + "M0,0L" + width + "," + height + "M-" + width / 4 + "," + height / 4 * 3 + "l" + width / 2 + "," + height / 2; - linewidth = size - size * Math.sqrt(1 - solidity); - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case "|": - width = size; - height = size; - patternTag = "path"; - path = "M" + width / 2 + ",0L" + width / 2 + "," + height; - linewidth = solidity * size; - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case "-": - width = size; - height = size; - patternTag = "path"; - path = "M0," + height / 2 + "L" + width + "," + height / 2; - linewidth = solidity * size; - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case "+": - width = size; - height = size; - patternTag = "path"; - path = "M" + width / 2 + ",0L" + width / 2 + "," + height + "M0," + height / 2 + "L" + width + "," + height / 2; - linewidth = size - size * Math.sqrt(1 - solidity); - patternTag = "path"; - patternAttrs = { - d: path, - opacity, - stroke: fgRGB, - "stroke-width": linewidth + "px" - }; - break; - case ".": - width = size; - height = size; - if (solidity < Math.PI / 4) { - radius = Math.sqrt(solidity * size * size / Math.PI); - } else { - radius = linearFn(solidity, Math.PI / 4, 1, size / 2, size / Math.sqrt(2)); - } - patternTag = "circle"; - patternAttrs = { - cx: width / 2, - cy: height / 2, - r: radius, - opacity, - fill: fgRGB - }; - break; - } - var str2 = [ - shape || "noSh", - bgcolor || "noBg", - fgcolor || "noFg", - size, - solidity - ].join(";"); - var pattern2 = fullLayout._defs.select(".patterns").selectAll("#" + fullID).data([str2], Lib$1J.identity); - pattern2.exit().remove(); - pattern2.enter().append("pattern").each(function() { - var el = d3$z.select(this); - el.attr({ - id: fullID, - width: width + "px", - height: height + "px", - patternUnits: "userSpaceOnUse", - // for legends scale down patterns just a bit so that default size (i.e 8) nicely fit in small icons - patternTransform: isLegend ? "scale(0.8)" : "" - }); - if (bgcolor) { - var bgC = tinycolor$4(bgcolor); - var bgRGB = Color$J.tinyRGB(bgC); - var bgAlpha = bgC.getAlpha(); - var rects = el.selectAll("rect").data([0]); - rects.exit().remove(); - rects.enter().append("rect").attr({ - width: width + "px", - height: height + "px", - fill: bgRGB, - "fill-opacity": bgAlpha - }); - } - var patterns = el.selectAll(patternTag).data([0]); - patterns.exit().remove(); - patterns.enter().append(patternTag).attr(patternAttrs); - }); - sel.style("fill", getFullUrl(fullID, gd)).style("fill-opacity", null); - sel.classed("pattern_filled", true); -}; -drawing.initGradients = function(gd) { - var fullLayout = gd._fullLayout; - var gradientsGroup = Lib$1J.ensureSingle(fullLayout._defs, "g", "gradients"); - gradientsGroup.selectAll("linearGradient,radialGradient").remove(); - d3$z.select(gd).selectAll(".gradient_filled").classed("gradient_filled", false); -}; -drawing.initPatterns = function(gd) { - var fullLayout = gd._fullLayout; - var patternsGroup = Lib$1J.ensureSingle(fullLayout._defs, "g", "patterns"); - patternsGroup.selectAll("pattern").remove(); - d3$z.select(gd).selectAll(".pattern_filled").classed("pattern_filled", false); -}; -drawing.getPatternAttr = function(mp, i, dflt) { - if (mp && Lib$1J.isArrayOrTypedArray(mp)) { - return i < mp.length ? mp[i] : dflt; - } - return mp; -}; -drawing.pointStyle = function(s, trace, gd, pt) { - if (!s.size()) return; - var fns = drawing.makePointStyleFns(trace); - s.each(function(d) { - drawing.singlePointStyle(d, d3$z.select(this), trace, fns, gd, pt); - }); -}; -drawing.singlePointStyle = function(d, sel, trace, fns, gd, pt) { - var marker2 = trace.marker; - var markerLine2 = marker2.line; - if (pt && pt.i >= 0 && d.i === void 0) d.i = pt.i; - sel.style( - "opacity", - fns.selectedOpacityFn ? fns.selectedOpacityFn(d) : d.mo === void 0 ? marker2.opacity : d.mo - ); - if (fns.ms2mrc) { - var r; - if (d.ms === "various" || marker2.size === "various") { - r = 3; - } else { - r = fns.ms2mrc(d.ms); - } - d.mrc = r; - if (fns.selectedSizeFn) { - r = d.mrc = fns.selectedSizeFn(d); - } - var x = drawing.symbolNumber(d.mx || marker2.symbol) || 0; - d.om = x % 200 >= 100; - var angle = getMarkerAngle(d, trace); - var standoff = getMarkerStandoff(d, trace); - sel.attr("d", makePointPath(x, r, angle, standoff)); - } - var perPointGradient = false; - var fillColor, lineColor, lineWidth; - if (d.so) { - lineWidth = markerLine2.outlierwidth; - lineColor = markerLine2.outliercolor; - fillColor = marker2.outliercolor; - } else { - var markerLineWidth2 = (markerLine2 || {}).width; - lineWidth = (d.mlw + 1 || markerLineWidth2 + 1 || // TODO: we need the latter for legends... can we get rid of it? - (d.trace ? (d.trace.marker.line || {}).width : 0) + 1) - 1 || 0; - if ("mlc" in d) lineColor = d.mlcc = fns.lineScale(d.mlc); - else if (Lib$1J.isArrayOrTypedArray(markerLine2.color)) lineColor = Color$J.defaultLine; - else lineColor = markerLine2.color; - if (Lib$1J.isArrayOrTypedArray(marker2.color)) { - fillColor = Color$J.defaultLine; - perPointGradient = true; - } - if ("mc" in d) { - fillColor = d.mcc = fns.markerScale(d.mc); - } else { - fillColor = marker2.color || marker2.colors || "rgba(0,0,0,0)"; - } - if (fns.selectedColorFn) { - fillColor = fns.selectedColorFn(d); - } - } - if (d.om) { - sel.call(Color$J.stroke, fillColor).style({ - "stroke-width": (lineWidth || 1) + "px", - fill: "none" - }); - } else { - sel.style("stroke-width", (d.isBlank ? 0 : lineWidth) + "px"); - var markerGradient = marker2.gradient; - var gradientType = d.mgt; - if (gradientType) perPointGradient = true; - else gradientType = markerGradient && markerGradient.type; - if (Lib$1J.isArrayOrTypedArray(gradientType)) { - gradientType = gradientType[0]; - if (!gradientInfo[gradientType]) gradientType = 0; - } - var markerPattern = marker2.pattern; - var patternShape = markerPattern && drawing.getPatternAttr(markerPattern.shape, d.i, ""); - if (gradientType && gradientType !== "none") { - var gradientColor = d.mgc; - if (gradientColor) perPointGradient = true; - else gradientColor = markerGradient.color; - var gradientID = trace.uid; - if (perPointGradient) gradientID += "-" + d.i; - drawing.gradient( - sel, - gd, - gradientID, - gradientType, - [[0, gradientColor], [1, fillColor]], - "fill" - ); - } else if (patternShape) { - var perPointPattern = false; - var fgcolor = markerPattern.fgcolor; - if (!fgcolor && pt && pt.color) { - fgcolor = pt.color; - perPointPattern = true; - } - var patternFGColor = drawing.getPatternAttr(fgcolor, d.i, pt && pt.color || null); - var patternBGColor = drawing.getPatternAttr(markerPattern.bgcolor, d.i, null); - var patternFGOpacity = markerPattern.fgopacity; - var patternSize = drawing.getPatternAttr(markerPattern.size, d.i, 8); - var patternSolidity = drawing.getPatternAttr(markerPattern.solidity, d.i, 0.3); - perPointPattern = perPointPattern || d.mcc || Lib$1J.isArrayOrTypedArray(markerPattern.shape) || Lib$1J.isArrayOrTypedArray(markerPattern.bgcolor) || Lib$1J.isArrayOrTypedArray(markerPattern.fgcolor) || Lib$1J.isArrayOrTypedArray(markerPattern.size) || Lib$1J.isArrayOrTypedArray(markerPattern.solidity); - var patternID = trace.uid; - if (perPointPattern) patternID += "-" + d.i; - drawing.pattern( - sel, - "point", - gd, - patternID, - patternShape, - patternSize, - patternSolidity, - d.mcc, - markerPattern.fillmode, - patternBGColor, - patternFGColor, - patternFGOpacity - ); - } else { - Lib$1J.isArrayOrTypedArray(fillColor) ? Color$J.fill(sel, fillColor[d.i]) : Color$J.fill(sel, fillColor); - } - if (lineWidth) { - Color$J.stroke(sel, lineColor); - } - } -}; -drawing.makePointStyleFns = function(trace) { - var out = {}; - var marker2 = trace.marker; - out.markerScale = drawing.tryColorscale(marker2, ""); - out.lineScale = drawing.tryColorscale(marker2, "line"); - if (Registry$L.traceIs(trace, "symbols")) { - out.ms2mrc = subTypes$a.isBubble(trace) ? makeBubbleSizeFn$1(trace) : function() { - return (marker2.size || 6) / 2; - }; - } - if (trace.selectedpoints) { - Lib$1J.extendFlat(out, drawing.makeSelectedPointStyleFns(trace)); - } - return out; -}; -drawing.makeSelectedPointStyleFns = function(trace) { - var out = {}; - var selectedAttrs = trace.selected || {}; - var unselectedAttrs = trace.unselected || {}; - var marker2 = trace.marker || {}; - var selectedMarker = selectedAttrs.marker || {}; - var unselectedMarker = unselectedAttrs.marker || {}; - var mo = marker2.opacity; - var smo = selectedMarker.opacity; - var usmo = unselectedMarker.opacity; - var smoIsDefined = smo !== void 0; - var usmoIsDefined = usmo !== void 0; - if (Lib$1J.isArrayOrTypedArray(mo) || smoIsDefined || usmoIsDefined) { - out.selectedOpacityFn = function(d) { - var base = d.mo === void 0 ? marker2.opacity : d.mo; - if (d.selected) { - return smoIsDefined ? smo : base; - } else { - return usmoIsDefined ? usmo : DESELECTDIM$2 * base; - } - }; - } - var mc = marker2.color; - var smc = selectedMarker.color; - var usmc = unselectedMarker.color; - if (smc || usmc) { - out.selectedColorFn = function(d) { - var base = d.mcc || mc; - if (d.selected) { - return smc || base; - } else { - return usmc || base; - } - }; - } - var ms = marker2.size; - var sms = selectedMarker.size; - var usms = unselectedMarker.size; - var smsIsDefined = sms !== void 0; - var usmsIsDefined = usms !== void 0; - if (Registry$L.traceIs(trace, "symbols") && (smsIsDefined || usmsIsDefined)) { - out.selectedSizeFn = function(d) { - var base = d.mrc || ms / 2; - if (d.selected) { - return smsIsDefined ? sms / 2 : base; - } else { - return usmsIsDefined ? usms / 2 : base; - } - }; - } - return out; -}; -drawing.makeSelectedTextStyleFns = function(trace) { - var out = {}; - var selectedAttrs = trace.selected || {}; - var unselectedAttrs = trace.unselected || {}; - var textFont = trace.textfont || {}; - var selectedTextFont = selectedAttrs.textfont || {}; - var unselectedTextFont = unselectedAttrs.textfont || {}; - var tc = textFont.color; - var stc = selectedTextFont.color; - var utc = unselectedTextFont.color; - out.selectedTextColorFn = function(d) { - var base = d.tc || tc; - if (d.selected) { - return stc || base; - } else { - if (utc) return utc; - else return stc ? base : Color$J.addOpacity(base, DESELECTDIM$2); - } - }; - return out; -}; -drawing.selectedPointStyle = function(s, trace) { - if (!s.size() || !trace.selectedpoints) return; - var fns = drawing.makeSelectedPointStyleFns(trace); - var marker2 = trace.marker || {}; - var seq = []; - if (fns.selectedOpacityFn) { - seq.push(function(pt, d) { - pt.style("opacity", fns.selectedOpacityFn(d)); - }); - } - if (fns.selectedColorFn) { - seq.push(function(pt, d) { - Color$J.fill(pt, fns.selectedColorFn(d)); - }); - } - if (fns.selectedSizeFn) { - seq.push(function(pt, d) { - var mx = d.mx || marker2.symbol || 0; - var mrc2 = fns.selectedSizeFn(d); - pt.attr("d", makePointPath(drawing.symbolNumber(mx), mrc2, getMarkerAngle(d, trace), getMarkerStandoff(d, trace))); - d.mrc2 = mrc2; - }); - } - if (seq.length) { - s.each(function(d) { - var pt = d3$z.select(this); - for (var i = 0; i < seq.length; i++) { - seq[i](pt, d); - } - }); - } -}; -drawing.tryColorscale = function(marker2, prefix) { - var cont = prefix ? Lib$1J.nestedProperty(marker2, prefix).get() : marker2; - if (cont) { - var colorArray = cont.color; - if ((cont.colorscale || cont._colorAx) && Lib$1J.isArrayOrTypedArray(colorArray)) { - return Colorscale$2.makeColorScaleFuncFromTrace(cont); - } - } - return Lib$1J.identity; -}; -var TEXTOFFSETSIGN$1 = { - start: 1, - end: -1, - middle: 0, - bottom: 1, - top: -1 -}; -function textPointPosition(s, textPosition, fontSize, markerRadius, dontTouchParent) { - var group = d3$z.select(s.node().parentNode); - var v = textPosition.indexOf("top") !== -1 ? "top" : textPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; - var h = textPosition.indexOf("left") !== -1 ? "end" : textPosition.indexOf("right") !== -1 ? "start" : "middle"; - var r = markerRadius ? markerRadius / 0.8 + 1 : 0; - var numLines = (svgTextUtils$f.lineCount(s) - 1) * LINE_SPACING$7 + 1; - var dx = TEXTOFFSETSIGN$1[h] * r; - var dy = fontSize * 0.75 + TEXTOFFSETSIGN$1[v] * r + (TEXTOFFSETSIGN$1[v] - 1) * numLines * fontSize / 2; - s.attr("text-anchor", h); - if (!dontTouchParent) { - group.attr("transform", strTranslate$c(dx, dy)); - } -} -function extracTextFontSize(d, trace) { - var fontSize = d.ts || trace.textfont.size; - return isNumeric$o(fontSize) && fontSize > 0 ? fontSize : 0; -} -drawing.textPointStyle = function(s, trace, gd) { - if (!s.size()) return; - var selectedTextColorFn; - if (trace.selectedpoints) { - var fns = drawing.makeSelectedTextStyleFns(trace); - selectedTextColorFn = fns.selectedTextColorFn; - } - var texttemplate = trace.texttemplate; - var fullLayout = gd._fullLayout; - s.each(function(d) { - var p = d3$z.select(this); - var text = texttemplate ? Lib$1J.extractOption(d, trace, "txt", "texttemplate") : Lib$1J.extractOption(d, trace, "tx", "text"); - if (!text && text !== 0) { - p.remove(); - return; - } - if (texttemplate) { - var fn = trace._module.formatLabels; - var labels = fn ? fn(d, trace, fullLayout) : {}; - var pointValues = {}; - appendArrayPointValue$3(pointValues, trace, d.i); - var meta = trace._meta || {}; - text = Lib$1J.texttemplateString(text, labels, fullLayout._d3locale, pointValues, d, meta); - } - var pos = d.tp || trace.textposition; - var fontSize = extracTextFontSize(d, trace); - var fontColor = selectedTextColorFn ? selectedTextColorFn(d) : d.tc || trace.textfont.color; - p.call(drawing.font, { - family: d.tf || trace.textfont.family, - weight: d.tw || trace.textfont.weight, - style: d.ty || trace.textfont.style, - variant: d.tv || trace.textfont.variant, - textcase: d.tC || trace.textfont.textcase, - lineposition: d.tE || trace.textfont.lineposition, - shadow: d.tS || trace.textfont.shadow, - size: fontSize, - color: fontColor - }).text(text).call(svgTextUtils$f.convertToTspans, gd).call(textPointPosition, pos, fontSize, d.mrc); - }); -}; -drawing.selectedTextStyle = function(s, trace) { - if (!s.size() || !trace.selectedpoints) return; - var fns = drawing.makeSelectedTextStyleFns(trace); - s.each(function(d) { - var tx = d3$z.select(this); - var tc = fns.selectedTextColorFn(d); - var tp = d.tp || trace.textposition; - var fontSize = extracTextFontSize(d, trace); - Color$J.fill(tx, tc); - var dontTouchParent = Registry$L.traceIs(trace, "bar-like"); - textPointPosition(tx, tp, fontSize, d.mrc2 || d.mrc, dontTouchParent); - }); -}; -var CatmullRomExp = 0.5; -drawing.smoothopen = function(pts, smoothness) { - if (pts.length < 3) { - return "M" + pts.join("L"); - } - var path = "M" + pts[0]; - var tangents = []; - var i; - for (i = 1; i < pts.length - 1; i++) { - tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness)); - } - path += "Q" + tangents[0][0] + " " + pts[1]; - for (i = 2; i < pts.length - 1; i++) { - path += "C" + tangents[i - 2][1] + " " + tangents[i - 1][0] + " " + pts[i]; - } - path += "Q" + tangents[pts.length - 3][1] + " " + pts[pts.length - 1]; - return path; -}; -drawing.smoothclosed = function(pts, smoothness) { - if (pts.length < 3) { - return "M" + pts.join("L") + "Z"; - } - var path = "M" + pts[0]; - var pLast = pts.length - 1; - var tangents = [makeTangent(pts[pLast], pts[0], pts[1], smoothness)]; - var i; - for (i = 1; i < pLast; i++) { - tangents.push(makeTangent(pts[i - 1], pts[i], pts[i + 1], smoothness)); - } - tangents.push( - makeTangent(pts[pLast - 1], pts[pLast], pts[0], smoothness) - ); - for (i = 1; i <= pLast; i++) { - path += "C" + tangents[i - 1][1] + " " + tangents[i][0] + " " + pts[i]; - } - path += "C" + tangents[pLast][1] + " " + tangents[0][0] + " " + pts[0] + "Z"; - return path; -}; -var lastDrawnX, lastDrawnY; -function roundEnd(pt, isY, isLastPoint) { - if (isLastPoint) pt = applyBackoff(pt); - return isY ? roundY(pt[1]) : roundX(pt[0]); -} -function roundX(p) { - var v = d3$z.round(p, 2); - lastDrawnX = v; - return v; -} -function roundY(p) { - var v = d3$z.round(p, 2); - lastDrawnY = v; - return v; -} -function makeTangent(prevpt, thispt, nextpt, smoothness) { - var d1x = prevpt[0] - thispt[0]; - var d1y = prevpt[1] - thispt[1]; - var d2x = nextpt[0] - thispt[0]; - var d2y = nextpt[1] - thispt[1]; - var d1a = Math.pow(d1x * d1x + d1y * d1y, CatmullRomExp / 2); - var d2a = Math.pow(d2x * d2x + d2y * d2y, CatmullRomExp / 2); - var numx = (d2a * d2a * d1x - d1a * d1a * d2x) * smoothness; - var numy = (d2a * d2a * d1y - d1a * d1a * d2y) * smoothness; - var denom1 = 3 * d2a * (d1a + d2a); - var denom2 = 3 * d1a * (d1a + d2a); - return [ - [ - roundX(thispt[0] + (denom1 && numx / denom1)), - roundY(thispt[1] + (denom1 && numy / denom1)) - ], - [ - roundX(thispt[0] - (denom2 && numx / denom2)), - roundY(thispt[1] - (denom2 && numy / denom2)) - ] - ]; -} -var STEPPATH = { - hv: function(p0, p1, isLastPoint) { - return "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint); - }, - vh: function(p0, p1, isLastPoint) { - return "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint); - }, - hvh: function(p0, p1, isLastPoint) { - return "H" + roundX((p0[0] + p1[0]) / 2) + "V" + roundY(p1[1]) + "H" + roundEnd(p1, 0, isLastPoint); - }, - vhv: function(p0, p1, isLastPoint) { - return "V" + roundY((p0[1] + p1[1]) / 2) + "H" + roundX(p1[0]) + "V" + roundEnd(p1, 1, isLastPoint); - } -}; -var STEPLINEAR = function(p0, p1, isLastPoint) { - return "L" + roundEnd(p1, 0, isLastPoint) + "," + roundEnd(p1, 1, isLastPoint); -}; -drawing.steps = function(shape) { - var onestep = STEPPATH[shape] || STEPLINEAR; - return function(pts) { - var path = "M" + roundX(pts[0][0]) + "," + roundY(pts[0][1]); - var len = pts.length; - for (var i = 1; i < len; i++) { - path += onestep(pts[i - 1], pts[i], i === len - 1); - } - return path; - }; -}; -function applyBackoff(pt, start) { - var backoff = pt.backoff; - var trace = pt.trace; - var d = pt.d; - var i = pt.i; - if (backoff && trace && trace.marker && trace.marker.angle % 360 === 0 && trace.line && trace.line.shape !== "spline") { - var arrayBackoff = Lib$1J.isArrayOrTypedArray(backoff); - var end = pt; - var x1 = start ? start[0] : lastDrawnX || 0; - var y1 = start ? start[1] : lastDrawnY || 0; - var x2 = end[0]; - var y2 = end[1]; - var dx = x2 - x1; - var dy = y2 - y1; - var t = Math.atan2(dy, dx); - var b = arrayBackoff ? backoff[i] : backoff; - if (b === "auto") { - var endI = end.i; - if (trace.type === "scatter") endI--; - var endMarker = end.marker; - var endMarkerSymbol = endMarker.symbol; - if (Lib$1J.isArrayOrTypedArray(endMarkerSymbol)) endMarkerSymbol = endMarkerSymbol[endI]; - var endMarkerSize = endMarker.size; - if (Lib$1J.isArrayOrTypedArray(endMarkerSize)) endMarkerSize = endMarkerSize[endI]; - b = endMarker ? drawing.symbolBackOffs[drawing.symbolNumber(endMarkerSymbol)] * endMarkerSize : 0; - b += drawing.getMarkerStandoff(d[endI], trace) || 0; - } - var x = x2 - b * Math.cos(t); - var y = y2 - b * Math.sin(t); - if ((x <= x2 && x >= x1 || x >= x2 && x <= x1) && (y <= y2 && y >= y1 || y >= y2 && y <= y1)) { - pt = [x, y]; - } - } - return pt; -} -drawing.applyBackoff = applyBackoff; -drawing.makeTester = function() { - var tester2 = Lib$1J.ensureSingleById(d3$z.select("body"), "svg", "js-plotly-tester", function(s) { - s.attr(xmlnsNamespaces$3.svgAttrs).style({ - position: "absolute", - left: "-10000px", - top: "-10000px", - width: "9000px", - height: "9000px", - "z-index": "1" - }); - }); - var testref = Lib$1J.ensureSingle(tester2, "path", "js-reference-point", function(s) { - s.attr("d", "M0,0H1V1H0Z").style({ - "stroke-width": 0, - fill: "black" - }); - }); - drawing.tester = tester2; - drawing.testref = testref; -}; -drawing.savedBBoxes = {}; -var savedBBoxesCount = 0; -var maxSavedBBoxes = 1e4; -drawing.bBox = function(node, inTester, hash) { - if (!hash) hash = nodeHash(node); - var out; - if (hash) { - out = drawing.savedBBoxes[hash]; - if (out) return Lib$1J.extendFlat({}, out); - } else if (node.childNodes.length === 1) { - var innerNode = node.childNodes[0]; - hash = nodeHash(innerNode); - if (hash) { - var x = +innerNode.getAttribute("x") || 0; - var y = +innerNode.getAttribute("y") || 0; - var transform = innerNode.getAttribute("transform"); - if (!transform) { - var innerBB = drawing.bBox(innerNode, false, hash); - if (x) { - innerBB.left += x; - innerBB.right += x; - } - if (y) { - innerBB.top += y; - innerBB.bottom += y; - } - return innerBB; - } - hash += "~" + x + "~" + y + "~" + transform; - out = drawing.savedBBoxes[hash]; - if (out) return Lib$1J.extendFlat({}, out); - } - } - var testNode, tester2; - if (inTester) { - testNode = node; - } else { - tester2 = drawing.tester.node(); - testNode = node.cloneNode(true); - tester2.appendChild(testNode); - } - d3$z.select(testNode).attr("transform", null).call(svgTextUtils$f.positionText, 0, 0); - var testRect = testNode.getBoundingClientRect(); - var refRect = drawing.testref.node().getBoundingClientRect(); - if (!inTester) tester2.removeChild(testNode); - var bb = { - height: testRect.height, - width: testRect.width, - left: testRect.left - refRect.left, - top: testRect.top - refRect.top, - right: testRect.right - refRect.left, - bottom: testRect.bottom - refRect.top - }; - if (savedBBoxesCount >= maxSavedBBoxes) { - drawing.savedBBoxes = {}; - savedBBoxesCount = 0; - } - if (hash) drawing.savedBBoxes[hash] = bb; - savedBBoxesCount++; - return Lib$1J.extendFlat({}, bb); -}; -function nodeHash(node) { - var inputText = node.getAttribute("data-unformatted"); - if (inputText === null) return; - return inputText + node.getAttribute("data-math") + node.getAttribute("text-anchor") + node.getAttribute("style"); -} -drawing.setClipUrl = function(s, localId, gd) { - s.attr("clip-path", getFullUrl(localId, gd)); -}; -function getFullUrl(localId, gd) { - if (!localId) return null; - var context2 = gd._context; - var baseUrl = context2._exportedPlot ? "" : context2._baseUrl || ""; - return baseUrl ? "url('" + baseUrl + "#" + localId + "')" : "url(#" + localId + ")"; -} -drawing.getTranslate = function(element) { - var re2 = /.*\btranslate\((-?\d*\.?\d*)[^-\d]*(-?\d*\.?\d*)[^\d].*/; - var getter = element.attr ? "attr" : "getAttribute"; - var transform = element[getter]("transform") || ""; - var translate2 = transform.replace(re2, function(match, p1, p2) { - return [p1, p2].join(" "); - }).split(" "); - return { - x: +translate2[0] || 0, - y: +translate2[1] || 0 - }; -}; -drawing.setTranslate = function(element, x, y) { - var re2 = /(\btranslate\(.*?\);?)/; - var getter = element.attr ? "attr" : "getAttribute"; - var setter = element.attr ? "attr" : "setAttribute"; - var transform = element[getter]("transform") || ""; - x = x || 0; - y = y || 0; - transform = transform.replace(re2, "").trim(); - transform += strTranslate$c(x, y); - transform = transform.trim(); - element[setter]("transform", transform); - return transform; -}; -drawing.getScale = function(element) { - var re2 = /.*\bscale\((\d*\.?\d*)[^\d]*(\d*\.?\d*)[^\d].*/; - var getter = element.attr ? "attr" : "getAttribute"; - var transform = element[getter]("transform") || ""; - var translate2 = transform.replace(re2, function(match, p1, p2) { - return [p1, p2].join(" "); - }).split(" "); - return { - x: +translate2[0] || 1, - y: +translate2[1] || 1 - }; -}; -drawing.setScale = function(element, x, y) { - var re2 = /(\bscale\(.*?\);?)/; - var getter = element.attr ? "attr" : "getAttribute"; - var setter = element.attr ? "attr" : "setAttribute"; - var transform = element[getter]("transform") || ""; - x = x || 1; - y = y || 1; - transform = transform.replace(re2, "").trim(); - transform += "scale(" + x + "," + y + ")"; - transform = transform.trim(); - element[setter]("transform", transform); - return transform; -}; -var SCALE_RE = /\s*sc.*/; -drawing.setPointGroupScale = function(selection, xScale, yScale) { - xScale = xScale || 1; - yScale = yScale || 1; - if (!selection) return; - var scale2 = xScale === 1 && yScale === 1 ? "" : "scale(" + xScale + "," + yScale + ")"; - selection.each(function() { - var t = (this.getAttribute("transform") || "").replace(SCALE_RE, ""); - t += scale2; - t = t.trim(); - this.setAttribute("transform", t); - }); -}; -var TEXT_POINT_LAST_TRANSLATION_RE = /translate\([^)]*\)\s*$/; -drawing.setTextPointsScale = function(selection, xScale, yScale) { - if (!selection) return; - selection.each(function() { - var transforms; - var el = d3$z.select(this); - var text = el.select("text"); - if (!text.node()) return; - var x = parseFloat(text.attr("x") || 0); - var y = parseFloat(text.attr("y") || 0); - var existingTransform = (el.attr("transform") || "").match(TEXT_POINT_LAST_TRANSLATION_RE); - if (xScale === 1 && yScale === 1) { - transforms = []; - } else { - transforms = [ - strTranslate$c(x, y), - "scale(" + xScale + "," + yScale + ")", - strTranslate$c(-x, -y) - ]; - } - if (existingTransform) { - transforms.push(existingTransform); - } - el.attr("transform", transforms.join("")); - }); -}; -function getMarkerStandoff(d, trace) { - var standoff; - if (d) standoff = d.mf; - if (standoff === void 0) { - standoff = trace.marker ? trace.marker.standoff || 0 : 0; - } - if (!trace._geo && !trace._xA) { - return -standoff; - } - return standoff; -} -drawing.getMarkerStandoff = getMarkerStandoff; -var atan2 = Math.atan2; -var cos = Math.cos; -var sin = Math.sin; -function rotate$1(t, xy) { - var x = xy[0]; - var y = xy[1]; - return [ - x * cos(t) - y * sin(t), - x * sin(t) + y * cos(t) - ]; -} -var previousLon; -var previousLat; -var previousX; -var previousY; -var previousI; -var previousTraceUid; -function getMarkerAngle(d, trace) { - var angle = d.ma; - if (angle === void 0) { - angle = trace.marker.angle; - if (!angle || Lib$1J.isArrayOrTypedArray(angle)) { - angle = 0; - } - } - var x, y; - var ref2 = trace.marker.angleref; - if (ref2 === "previous" || ref2 === "north") { - if (trace._geo) { - var p = trace._geo.project(d.lonlat); - x = p[0]; - y = p[1]; - } else { - var xa = trace._xA; - var ya = trace._yA; - if (xa && ya) { - x = xa.c2p(d.x); - y = ya.c2p(d.y); - } else { - return 90; - } - } - if (trace._geo) { - var lon = d.lonlat[0]; - var lat = d.lonlat[1]; - var north = trace._geo.project([ - lon, - lat + 1e-5 - // epsilon - ]); - var east = trace._geo.project([ - lon + 1e-5, - // epsilon - lat - ]); - var u = atan2( - east[1] - y, - east[0] - x - ); - var v = atan2( - north[1] - y, - north[0] - x - ); - var t; - if (ref2 === "north") { - t = angle / 180 * Math.PI; - } else if (ref2 === "previous") { - var lon1 = lon / 180 * Math.PI; - var lat1 = lat / 180 * Math.PI; - var lon2 = previousLon / 180 * Math.PI; - var lat2 = previousLat / 180 * Math.PI; - var dLon = lon2 - lon1; - var deltaY = cos(lat2) * sin(dLon); - var deltaX = sin(lat2) * cos(lat1) - cos(lat2) * sin(lat1) * cos(dLon); - t = -atan2( - deltaY, - deltaX - ) - Math.PI; - previousLon = lon; - previousLat = lat; - } - var A2 = rotate$1(u, [cos(t), 0]); - var B2 = rotate$1(v, [sin(t), 0]); - angle = atan2( - A2[1] + B2[1], - A2[0] + B2[0] - ) / Math.PI * 180; - if (ref2 === "previous" && !(previousTraceUid === trace.uid && d.i === previousI + 1)) { - angle = null; - } - } - if (ref2 === "previous" && !trace._geo) { - if (previousTraceUid === trace.uid && d.i === previousI + 1 && isNumeric$o(x) && isNumeric$o(y)) { - var dX = x - previousX; - var dY = y - previousY; - var shape = trace.line ? trace.line.shape || "" : ""; - var lastShapeChar = shape.slice(shape.length - 1); - if (lastShapeChar === "h") dY = 0; - if (lastShapeChar === "v") dX = 0; - angle += atan2(dY, dX) / Math.PI * 180 + 90; - } else { - angle = null; - } - } - } - previousX = x; - previousY = y; - previousI = d.i; - previousTraceUid = trace.uid; - return angle; -} -drawing.getMarkerAngle = getMarkerAngle; -var drawingExports = drawing$1.exports; -var d3$y = d3Exports; -var isNumeric$n = fastIsnumeric; -var Plots$c = plotsExports; -var Registry$K = registry; -var Lib$1I = libExports; -var strTranslate$b = Lib$1I.strTranslate; -var Drawing$u = drawingExports; -var Color$I = colorExports; -var svgTextUtils$e = svg_text_utils; -var interactConstants = interactions; -var OPPOSITE_SIDE$1 = alignment$1.OPPOSITE_SIDE; -var numStripRE = / [XY][0-9]* /; -var SUBTITLE_PADDING_MATHJAX_EM = 1.6; -var SUBTITLE_PADDING_EM = 1.6; -function draw$e(gd, titleClass, options) { - var fullLayout = gd._fullLayout; - var cont = options.propContainer; - var prop = options.propName; - var placeholder = options.placeholder; - var traceIndex = options.traceIndex; - var avoid = options.avoid || {}; - var attributes2 = options.attributes; - var transform = options.transform; - var group = options.containerGroup; - var opacity = 1; - var title = cont.title; - var txt = (title && title.text ? title.text : "").trim(); - var titleIsPlaceholder = false; - var font2 = title && title.font ? title.font : {}; - var fontFamily = font2.family; - var fontSize = font2.size; - var fontColor = font2.color; - var fontWeight = font2.weight; - var fontStyle = font2.style; - var fontVariant = font2.variant; - var fontTextcase = font2.textcase; - var fontLineposition = font2.lineposition; - var fontShadow = font2.shadow; - var subtitleProp = options.subtitlePropName; - var subtitleEnabled = !!subtitleProp; - var subtitlePlaceholder = options.subtitlePlaceholder; - var subtitle = (cont.title || {}).subtitle || { text: "", font: {} }; - var subtitleTxt = subtitle.text.trim(); - var subtitleIsPlaceholder = false; - var subtitleOpacity = 1; - var subtitleFont = subtitle.font; - var subFontFamily = subtitleFont.family; - var subFontSize = subtitleFont.size; - var subFontColor = subtitleFont.color; - var subFontWeight = subtitleFont.weight; - var subFontStyle = subtitleFont.style; - var subFontVariant = subtitleFont.variant; - var subFontTextcase = subtitleFont.textcase; - var subFontLineposition = subtitleFont.lineposition; - var subFontShadow = subtitleFont.shadow; - var editAttr; - if (prop === "title.text") editAttr = "titleText"; - else if (prop.indexOf("axis") !== -1) editAttr = "axisTitleText"; - else if (prop.indexOf("colorbar" !== -1)) editAttr = "colorbarTitleText"; - var editable = gd._context.edits[editAttr]; - function matchesPlaceholder(text, placeholder2) { - if (text === void 0 || placeholder2 === void 0) return false; - return text.replace(numStripRE, " % ") === placeholder2.replace(numStripRE, " % "); - } - if (txt === "") opacity = 0; - else if (matchesPlaceholder(txt, placeholder)) { - if (!editable) txt = ""; - opacity = 0.2; - titleIsPlaceholder = true; - } - if (subtitleEnabled) { - if (subtitleTxt === "") subtitleOpacity = 0; - else if (matchesPlaceholder(subtitleTxt, subtitlePlaceholder)) { - if (!editable) subtitleTxt = ""; - subtitleOpacity = 0.2; - subtitleIsPlaceholder = true; - } - } - if (options._meta) { - txt = Lib$1I.templateString(txt, options._meta); - } else if (fullLayout._meta) { - txt = Lib$1I.templateString(txt, fullLayout._meta); - } - var elShouldExist = txt || subtitleTxt || editable; - var hColorbarMoveTitle; - if (!group) { - group = Lib$1I.ensureSingle(fullLayout._infolayer, "g", "g-" + titleClass); - hColorbarMoveTitle = fullLayout._hColorbarMoveTitle; - } - var el = group.selectAll("text." + titleClass).data(elShouldExist ? [0] : []); - el.enter().append("text"); - el.text(txt).attr("class", titleClass); - el.exit().remove(); - var subtitleEl = null; - var subtitleClass = titleClass + "-subtitle"; - var subtitleElShouldExist = subtitleTxt || editable; - if (subtitleEnabled && subtitleElShouldExist) { - subtitleEl = group.selectAll("text." + subtitleClass).data(subtitleElShouldExist ? [0] : []); - subtitleEl.enter().append("text"); - subtitleEl.text(subtitleTxt).attr("class", subtitleClass); - subtitleEl.exit().remove(); - } - if (!elShouldExist) return group; - function titleLayout(titleEl, subtitleEl2) { - Lib$1I.syncOrAsync([drawTitle2, scootTitle], { title: titleEl, subtitle: subtitleEl2 }); - } - function drawTitle2(titleAndSubtitleEls) { - var titleEl = titleAndSubtitleEls.title; - var subtitleEl2 = titleAndSubtitleEls.subtitle; - var transformVal; - if (!transform && hColorbarMoveTitle) { - transform = {}; - } - if (transform) { - transformVal = ""; - if (transform.rotate) { - transformVal += "rotate(" + [transform.rotate, attributes2.x, attributes2.y] + ")"; - } - if (transform.offset || hColorbarMoveTitle) { - transformVal += strTranslate$b(0, (transform.offset || 0) - (hColorbarMoveTitle || 0)); - } - } else { - transformVal = null; - } - titleEl.attr("transform", transformVal); - function adjustSubtitlePosition(titleElMathGroup2) { - if (!titleElMathGroup2) return; - var subtitleElement = d3$y.select(titleElMathGroup2.node().parentNode).select("." + subtitleClass); - if (!subtitleElement.empty()) { - var titleElMathBbox2 = titleElMathGroup2.node().getBBox(); - if (titleElMathBbox2.height) { - var subtitleY3 = titleElMathBbox2.y + titleElMathBbox2.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize; - subtitleElement.attr("y", subtitleY3); - } - } - } - titleEl.style("opacity", opacity * Color$I.opacity(fontColor)).call(Drawing$u.font, { - color: Color$I.rgb(fontColor), - size: d3$y.round(fontSize, 2), - family: fontFamily, - weight: fontWeight, - style: fontStyle, - variant: fontVariant, - textcase: fontTextcase, - shadow: fontShadow, - lineposition: fontLineposition - }).attr(attributes2).call(svgTextUtils$e.convertToTspans, gd, adjustSubtitlePosition); - if (subtitleEl2) { - var titleElMathGroup = group.select("." + titleClass + "-math-group"); - var titleElBbox2 = titleEl.node().getBBox(); - var titleElMathBbox = titleElMathGroup.node() ? titleElMathGroup.node().getBBox() : void 0; - var subtitleY2 = titleElMathBbox ? titleElMathBbox.y + titleElMathBbox.height + SUBTITLE_PADDING_MATHJAX_EM * subFontSize : titleElBbox2.y + titleElBbox2.height + SUBTITLE_PADDING_EM * subFontSize; - var subtitleAttributes = Lib$1I.extendFlat({}, attributes2, { - y: subtitleY2 - }); - subtitleEl2.attr("transform", transformVal); - subtitleEl2.style("opacity", subtitleOpacity * Color$I.opacity(subFontColor)).call(Drawing$u.font, { - color: Color$I.rgb(subFontColor), - size: d3$y.round(subFontSize, 2), - family: subFontFamily, - weight: subFontWeight, - style: subFontStyle, - variant: subFontVariant, - textcase: subFontTextcase, - shadow: subFontShadow, - lineposition: subFontLineposition - }).attr(subtitleAttributes).call(svgTextUtils$e.convertToTspans, gd); - } - return Plots$c.previousPromises(gd); - } - function scootTitle(titleAndSubtitleEls) { - var titleElIn = titleAndSubtitleEls.title; - var titleGroup = d3$y.select(titleElIn.node().parentNode); - if (avoid && avoid.selection && avoid.side && txt) { - titleGroup.attr("transform", null); - var backside = OPPOSITE_SIDE$1[avoid.side]; - var shiftSign = avoid.side === "left" || avoid.side === "top" ? -1 : 1; - var pad2 = isNumeric$n(avoid.pad) ? avoid.pad : 2; - var titlebb = Drawing$u.bBox(titleGroup.node()); - var reservedMargins = { t: 0, b: 0, l: 0, r: 0 }; - var margins = gd._fullLayout._reservedMargin; - for (var key in margins) { - for (var side in margins[key]) { - var val = margins[key][side]; - reservedMargins[side] = Math.max(reservedMargins[side], val); - } - } - var paperbb = { - left: reservedMargins.l, - top: reservedMargins.t, - right: fullLayout.width - reservedMargins.r, - bottom: fullLayout.height - reservedMargins.b - }; - var maxshift = avoid.maxShift || shiftSign * (paperbb[avoid.side] - titlebb[avoid.side]); - var shift = 0; - if (maxshift < 0) { - shift = maxshift; - } else { - var offsetLeft = avoid.offsetLeft || 0; - var offsetTop = avoid.offsetTop || 0; - titlebb.left -= offsetLeft; - titlebb.right -= offsetLeft; - titlebb.top -= offsetTop; - titlebb.bottom -= offsetTop; - avoid.selection.each(function() { - var avoidbb = Drawing$u.bBox(this); - if (Lib$1I.bBoxIntersect(titlebb, avoidbb, pad2)) { - shift = Math.max(shift, shiftSign * (avoidbb[avoid.side] - titlebb[backside]) + pad2); - } - }); - shift = Math.min(maxshift, shift); - cont._titleScoot = Math.abs(shift); - } - if (shift > 0 || maxshift < 0) { - var shiftTemplate = { - left: [-shift, 0], - right: [shift, 0], - top: [0, -shift], - bottom: [0, shift] - }[avoid.side]; - titleGroup.attr("transform", strTranslate$b(shiftTemplate[0], shiftTemplate[1])); - } - } - } - el.call(titleLayout, subtitleEl); - function setPlaceholder(element, placeholderText) { - element.text(placeholderText).on("mouseover.opacity", function() { - d3$y.select(this).transition().duration(interactConstants.SHOW_PLACEHOLDER).style("opacity", 1); - }).on("mouseout.opacity", function() { - d3$y.select(this).transition().duration(interactConstants.HIDE_PLACEHOLDER).style("opacity", 0); - }); - } - if (editable) { - if (!txt) { - setPlaceholder(el, placeholder); - titleIsPlaceholder = true; - } else el.on(".opacity", null); - el.call(svgTextUtils$e.makeEditable, { gd }).on("edit", function(text) { - if (traceIndex !== void 0) { - Registry$K.call("_guiRestyle", gd, prop, text, traceIndex); - } else { - Registry$K.call("_guiRelayout", gd, prop, text); - } - }).on("cancel", function() { - this.text(this.attr("data-unformatted")).call(titleLayout); - }).on("input", function(d) { - this.text(d || " ").call(svgTextUtils$e.positionText, attributes2.x, attributes2.y); - }); - if (subtitleEnabled) { - if (subtitleEnabled && !txt) { - var titleElBbox = el.node().getBBox(); - var subtitleY = titleElBbox.y + titleElBbox.height + SUBTITLE_PADDING_EM * subFontSize; - subtitleEl.attr("y", subtitleY); - } - if (!subtitleTxt) { - setPlaceholder(subtitleEl, subtitlePlaceholder); - subtitleIsPlaceholder = true; - } else subtitleEl.on(".opacity", null); - subtitleEl.call(svgTextUtils$e.makeEditable, { gd }).on("edit", function(text) { - Registry$K.call("_guiRelayout", gd, "title.subtitle.text", text); - }).on("cancel", function() { - this.text(this.attr("data-unformatted")).call(titleLayout); - }).on("input", function(d) { - this.text(d || " ").call(svgTextUtils$e.positionText, subtitleEl.attr("x"), subtitleEl.attr("y")); - }); - } - } - el.classed("js-placeholder", titleIsPlaceholder); - if (subtitleEl) subtitleEl.classed("js-placeholder", subtitleIsPlaceholder); - return group; -} -var titles = { - draw: draw$e, - SUBTITLE_PADDING_EM, - SUBTITLE_PADDING_MATHJAX_EM -}; -var d3$x = d3Exports; -var utcFormat = require$$1$1.utcFormat; -var Lib$1H = libExports; -var numberFormat = Lib$1H.numberFormat; -var isNumeric$m = fastIsnumeric; -var cleanNumber$1 = Lib$1H.cleanNumber; -var ms2DateTime = Lib$1H.ms2DateTime; -var dateTime2ms$1 = Lib$1H.dateTime2ms; -var ensureNumber2 = Lib$1H.ensureNumber; -var isArrayOrTypedArray$8 = Lib$1H.isArrayOrTypedArray; -var numConstants$3 = numerical; -var FP_SAFE$1 = numConstants$3.FP_SAFE; -var BADNUM$9 = numConstants$3.BADNUM; -var LOG_CLIP$1 = numConstants$3.LOG_CLIP; -var ONEWEEK$2 = numConstants$3.ONEWEEK; -var ONEDAY$1 = numConstants$3.ONEDAY; -var ONEHOUR$1 = numConstants$3.ONEHOUR; -var ONEMIN$1 = numConstants$3.ONEMIN; -var ONESEC$1 = numConstants$3.ONESEC; -var axisIds$8 = axis_ids; -var constants$R = constants$U; -var HOUR_PATTERN = constants$R.HOUR_PATTERN; -var WEEKDAY_PATTERN = constants$R.WEEKDAY_PATTERN; -function fromLog(v) { - return Math.pow(10, v); -} -function isValidCategory(v) { - return v !== null && v !== void 0; -} -var set_convert = function setConvert(ax, fullLayout) { - fullLayout = fullLayout || {}; - var axId = ax._id || "x"; - var axLetter = axId.charAt(0); - function toLog(v, clip) { - if (v > 0) return Math.log(v) / Math.LN10; - else if (v <= 0 && clip && ax.range && ax.range.length === 2) { - var r0 = ax.range[0]; - var r1 = ax.range[1]; - return 0.5 * (r0 + r1 - 2 * LOG_CLIP$1 * Math.abs(r0 - r1)); - } else return BADNUM$9; - } - function dt2ms(v, _2, calendar, opts) { - if ((opts || {}).msUTC && isNumeric$m(v)) { - return +v; - } - var ms = dateTime2ms$1(v, calendar || ax.calendar); - if (ms === BADNUM$9) { - if (isNumeric$m(v)) { - v = +v; - var msecTenths = Math.floor(Lib$1H.mod(v + 0.05, 1) * 10); - var msRounded = Math.round(v - msecTenths / 10); - ms = dateTime2ms$1(new Date(msRounded)) + msecTenths / 10; - } else return BADNUM$9; - } - return ms; - } - function ms2dt(v, r, calendar) { - return ms2DateTime(v, r, calendar || ax.calendar); - } - function getCategoryName(v) { - return ax._categories[Math.round(v)]; - } - function setCategoryIndex(v) { - if (isValidCategory(v)) { - if (ax._categoriesMap === void 0) { - ax._categoriesMap = {}; - } - if (ax._categoriesMap[v] !== void 0) { - return ax._categoriesMap[v]; - } else { - ax._categories.push(typeof v === "number" ? String(v) : v); - var curLength = ax._categories.length - 1; - ax._categoriesMap[v] = curLength; - return curLength; - } - } - return BADNUM$9; - } - function setMultiCategoryIndex(arrayIn, len) { - var arrayOut = new Array(len); - for (var i = 0; i < len; i++) { - var v0 = (arrayIn[0] || [])[i]; - var v1 = (arrayIn[1] || [])[i]; - arrayOut[i] = getCategoryIndex([v0, v1]); - } - return arrayOut; - } - function getCategoryIndex(v) { - if (ax._categoriesMap) { - return ax._categoriesMap[v]; - } - } - function getCategoryPosition(v) { - var index2 = getCategoryIndex(v); - if (index2 !== void 0) return index2; - if (isNumeric$m(v)) return +v; - } - function getRangePosition(v) { - return isNumeric$m(v) ? +v : getCategoryIndex(v); - } - function _l2p(v, m, b) { - return d3$x.round(b + m * v, 2); - } - function _p2l(px2, m, b) { - return (px2 - b) / m; - } - var l2p = function l2p2(v) { - if (!isNumeric$m(v)) return BADNUM$9; - return _l2p(v, ax._m, ax._b); - }; - var p2l = function(px2) { - return _p2l(px2, ax._m, ax._b); - }; - if (ax.rangebreaks) { - var isY = axLetter === "y"; - l2p = function(v) { - if (!isNumeric$m(v)) return BADNUM$9; - var len = ax._rangebreaks.length; - if (!len) return _l2p(v, ax._m, ax._b); - var flip = isY; - if (ax.range[0] > ax.range[1]) flip = !flip; - var signAx = flip ? -1 : 1; - var pos = signAx * v; - var q = 0; - for (var i = 0; i < len; i++) { - var min = signAx * ax._rangebreaks[i].min; - var max = signAx * ax._rangebreaks[i].max; - if (pos < min) break; - if (pos > max) q = i + 1; - else { - q = pos < (min + max) / 2 ? i : i + 1; - break; - } - } - var b2 = ax._B[q] || 0; - if (!isFinite(b2)) return 0; - return _l2p(v, ax._m2, b2); - }; - p2l = function(px2) { - var len = ax._rangebreaks.length; - if (!len) return _p2l(px2, ax._m, ax._b); - var q = 0; - for (var i = 0; i < len; i++) { - if (px2 < ax._rangebreaks[i].pmin) break; - if (px2 > ax._rangebreaks[i].pmax) q = i + 1; - } - return _p2l(px2, ax._m2, ax._B[q]); - }; - } - ax.c2l = ax.type === "log" ? toLog : ensureNumber2; - ax.l2c = ax.type === "log" ? fromLog : ensureNumber2; - ax.l2p = l2p; - ax.p2l = p2l; - ax.c2p = ax.type === "log" ? function(v, clip) { - return l2p(toLog(v, clip)); - } : l2p; - ax.p2c = ax.type === "log" ? function(px2) { - return fromLog(p2l(px2)); - } : p2l; - if (["linear", "-"].indexOf(ax.type) !== -1) { - ax.d2r = ax.r2d = ax.d2c = ax.r2c = ax.d2l = ax.r2l = cleanNumber$1; - ax.c2d = ax.c2r = ax.l2d = ax.l2r = ensureNumber2; - ax.d2p = ax.r2p = function(v) { - return ax.l2p(cleanNumber$1(v)); - }; - ax.p2d = ax.p2r = p2l; - ax.cleanPos = ensureNumber2; - } else if (ax.type === "log") { - ax.d2r = ax.d2l = function(v, clip) { - return toLog(cleanNumber$1(v), clip); - }; - ax.r2d = ax.r2c = function(v) { - return fromLog(cleanNumber$1(v)); - }; - ax.d2c = ax.r2l = cleanNumber$1; - ax.c2d = ax.l2r = ensureNumber2; - ax.c2r = toLog; - ax.l2d = fromLog; - ax.d2p = function(v, clip) { - return ax.l2p(ax.d2r(v, clip)); - }; - ax.p2d = function(px2) { - return fromLog(p2l(px2)); - }; - ax.r2p = function(v) { - return ax.l2p(cleanNumber$1(v)); - }; - ax.p2r = p2l; - ax.cleanPos = ensureNumber2; - } else if (ax.type === "date") { - ax.d2r = ax.r2d = Lib$1H.identity; - ax.d2c = ax.r2c = ax.d2l = ax.r2l = dt2ms; - ax.c2d = ax.c2r = ax.l2d = ax.l2r = ms2dt; - ax.d2p = ax.r2p = function(v, _2, calendar) { - return ax.l2p(dt2ms(v, 0, calendar)); - }; - ax.p2d = ax.p2r = function(px2, r, calendar) { - return ms2dt(p2l(px2), r, calendar); - }; - ax.cleanPos = function(v) { - return Lib$1H.cleanDate(v, BADNUM$9, ax.calendar); - }; - } else if (ax.type === "category") { - ax.d2c = ax.d2l = setCategoryIndex; - ax.r2d = ax.c2d = ax.l2d = getCategoryName; - ax.d2r = ax.d2l_noadd = getCategoryPosition; - ax.r2c = function(v) { - var index2 = getRangePosition(v); - return index2 !== void 0 ? index2 : ax.fraction2r(0.5); - }; - ax.l2r = ax.c2r = ensureNumber2; - ax.r2l = getRangePosition; - ax.d2p = function(v) { - return ax.l2p(ax.r2c(v)); - }; - ax.p2d = function(px2) { - return getCategoryName(p2l(px2)); - }; - ax.r2p = ax.d2p; - ax.p2r = p2l; - ax.cleanPos = function(v) { - if (typeof v === "string" && v !== "") return v; - return ensureNumber2(v); - }; - } else if (ax.type === "multicategory") { - ax.r2d = ax.c2d = ax.l2d = getCategoryName; - ax.d2r = ax.d2l_noadd = getCategoryPosition; - ax.r2c = function(v) { - var index2 = getCategoryPosition(v); - return index2 !== void 0 ? index2 : ax.fraction2r(0.5); - }; - ax.r2c_just_indices = getCategoryIndex; - ax.l2r = ax.c2r = ensureNumber2; - ax.r2l = getCategoryPosition; - ax.d2p = function(v) { - return ax.l2p(ax.r2c(v)); - }; - ax.p2d = function(px2) { - return getCategoryName(p2l(px2)); - }; - ax.r2p = ax.d2p; - ax.p2r = p2l; - ax.cleanPos = function(v) { - if (Array.isArray(v) || typeof v === "string" && v !== "") return v; - return ensureNumber2(v); - }; - ax.setupMultiCategory = function(fullData) { - var traceIndices = ax._traceIndices; - var i, j; - var group = ax._matchGroup; - if (group && ax._categories.length === 0) { - for (var axId2 in group) { - if (axId2 !== axId) { - var ax2 = fullLayout[axisIds$8.id2name(axId2)]; - traceIndices = traceIndices.concat(ax2._traceIndices); - } - } - } - var seen = [[0, {}], [0, {}]]; - var list = []; - for (i = 0; i < traceIndices.length; i++) { - var trace = fullData[traceIndices[i]]; - if (axLetter in trace) { - var arrayIn = trace[axLetter]; - var len = trace._length || Lib$1H.minRowLength(arrayIn); - if (isArrayOrTypedArray$8(arrayIn[0]) && isArrayOrTypedArray$8(arrayIn[1])) { - for (j = 0; j < len; j++) { - var v0 = arrayIn[0][j]; - var v1 = arrayIn[1][j]; - if (isValidCategory(v0) && isValidCategory(v1)) { - list.push([v0, v1]); - if (!(v0 in seen[0][1])) { - seen[0][1][v0] = seen[0][0]++; - } - if (!(v1 in seen[1][1])) { - seen[1][1][v1] = seen[1][0]++; - } - } - } - } - } - } - list.sort(function(a, b) { - var ind0 = seen[0][1]; - var d = ind0[a[0]] - ind0[b[0]]; - if (d) return d; - var ind1 = seen[1][1]; - return ind1[a[1]] - ind1[b[1]]; - }); - for (i = 0; i < list.length; i++) { - setCategoryIndex(list[i]); - } - }; - } - ax.fraction2r = function(v) { - var rl0 = ax.r2l(ax.range[0]); - var rl1 = ax.r2l(ax.range[1]); - return ax.l2r(rl0 + v * (rl1 - rl0)); - }; - ax.r2fraction = function(v) { - var rl0 = ax.r2l(ax.range[0]); - var rl1 = ax.r2l(ax.range[1]); - return (ax.r2l(v) - rl0) / (rl1 - rl0); - }; - ax.limitRange = function(rangeAttr) { - var minallowed = ax.minallowed; - var maxallowed = ax.maxallowed; - if (minallowed === void 0 && maxallowed === void 0) return; - if (!rangeAttr) rangeAttr = "range"; - var range = Lib$1H.nestedProperty(ax, rangeAttr).get(); - var rng = Lib$1H.simpleMap(range, ax.r2l); - var axrev = rng[1] < rng[0]; - if (axrev) rng.reverse(); - var bounds = Lib$1H.simpleMap([minallowed, maxallowed], ax.r2l); - if (minallowed !== void 0 && rng[0] < bounds[0]) range[axrev ? 1 : 0] = minallowed; - if (maxallowed !== void 0 && rng[1] > bounds[1]) range[axrev ? 0 : 1] = maxallowed; - if (range[0] === range[1]) { - var minL = ax.l2r(minallowed); - var maxL = ax.l2r(maxallowed); - if (minallowed !== void 0) { - var _max = minL + 1; - if (maxallowed !== void 0) _max = Math.min(_max, maxL); - range[axrev ? 1 : 0] = _max; - } - if (maxallowed !== void 0) { - var _min = maxL + 1; - if (minallowed !== void 0) _min = Math.max(_min, minL); - range[axrev ? 0 : 1] = _min; - } - } - }; - ax.cleanRange = function(rangeAttr, opts) { - ax._cleanRange(rangeAttr, opts); - ax.limitRange(rangeAttr); - }; - ax._cleanRange = function(rangeAttr, opts) { - if (!opts) opts = {}; - if (!rangeAttr) rangeAttr = "range"; - var range = Lib$1H.nestedProperty(ax, rangeAttr).get(); - var i, dflt; - if (ax.type === "date") dflt = Lib$1H.dfltRange(ax.calendar); - else if (axLetter === "y") dflt = constants$R.DFLTRANGEY; - else if (ax._name === "realaxis") dflt = [0, 1]; - else dflt = opts.dfltRange || constants$R.DFLTRANGEX; - dflt = dflt.slice(); - if (ax.rangemode === "tozero" || ax.rangemode === "nonnegative") { - dflt[0] = 0; - } - if (!range || range.length !== 2) { - Lib$1H.nestedProperty(ax, rangeAttr).set(dflt); - return; - } - var nullRange0 = range[0] === null; - var nullRange1 = range[1] === null; - if (ax.type === "date" && !ax.autorange) { - range[0] = Lib$1H.cleanDate(range[0], BADNUM$9, ax.calendar); - range[1] = Lib$1H.cleanDate(range[1], BADNUM$9, ax.calendar); - } - for (i = 0; i < 2; i++) { - if (ax.type === "date") { - if (!Lib$1H.isDateTime(range[i], ax.calendar)) { - ax[rangeAttr] = dflt; - break; - } - if (ax.r2l(range[0]) === ax.r2l(range[1])) { - var linCenter = Lib$1H.constrain( - ax.r2l(range[0]), - Lib$1H.MIN_MS + 1e3, - Lib$1H.MAX_MS - 1e3 - ); - range[0] = ax.l2r(linCenter - 1e3); - range[1] = ax.l2r(linCenter + 1e3); - break; - } - } else { - if (!isNumeric$m(range[i])) { - if (!(nullRange0 || nullRange1) && isNumeric$m(range[1 - i])) { - range[i] = range[1 - i] * (i ? 10 : 0.1); - } else { - ax[rangeAttr] = dflt; - break; - } - } - if (range[i] < -FP_SAFE$1) range[i] = -FP_SAFE$1; - else if (range[i] > FP_SAFE$1) range[i] = FP_SAFE$1; - if (range[0] === range[1]) { - var inc = Math.max(1, Math.abs(range[0] * 1e-6)); - range[0] -= inc; - range[1] += inc; - } - } - } - }; - ax.setScale = function(usePrivateRange) { - var gs = fullLayout._size; - if (ax.overlaying) { - var ax2 = axisIds$8.getFromId({ _fullLayout: fullLayout }, ax.overlaying); - ax.domain = ax2.domain; - } - var rangeAttr = usePrivateRange && ax._r ? "_r" : "range"; - var calendar = ax.calendar; - ax.cleanRange(rangeAttr); - var rl0 = ax.r2l(ax[rangeAttr][0], calendar); - var rl1 = ax.r2l(ax[rangeAttr][1], calendar); - var isY2 = axLetter === "y"; - if (isY2) { - ax._offset = gs.t + (1 - ax.domain[1]) * gs.h; - ax._length = gs.h * (ax.domain[1] - ax.domain[0]); - ax._m = ax._length / (rl0 - rl1); - ax._b = -ax._m * rl1; - } else { - ax._offset = gs.l + ax.domain[0] * gs.w; - ax._length = gs.w * (ax.domain[1] - ax.domain[0]); - ax._m = ax._length / (rl1 - rl0); - ax._b = -ax._m * rl0; - } - ax._rangebreaks = []; - ax._lBreaks = 0; - ax._m2 = 0; - ax._B = []; - if (ax.rangebreaks) { - var i, brk; - ax._rangebreaks = ax.locateBreaks( - Math.min(rl0, rl1), - Math.max(rl0, rl1) - ); - if (ax._rangebreaks.length) { - for (i = 0; i < ax._rangebreaks.length; i++) { - brk = ax._rangebreaks[i]; - ax._lBreaks += Math.abs(brk.max - brk.min); - } - var flip = isY2; - if (rl0 > rl1) flip = !flip; - if (flip) ax._rangebreaks.reverse(); - var sign2 = flip ? -1 : 1; - ax._m2 = sign2 * ax._length / (Math.abs(rl1 - rl0) - ax._lBreaks); - ax._B.push(-ax._m2 * (isY2 ? rl1 : rl0)); - for (i = 0; i < ax._rangebreaks.length; i++) { - brk = ax._rangebreaks[i]; - ax._B.push( - ax._B[ax._B.length - 1] - sign2 * ax._m2 * (brk.max - brk.min) - ); - } - for (i = 0; i < ax._rangebreaks.length; i++) { - brk = ax._rangebreaks[i]; - brk.pmin = l2p(brk.min); - brk.pmax = l2p(brk.max); - } - } - } - if (!isFinite(ax._m) || !isFinite(ax._b) || ax._length < 0) { - fullLayout._replotting = false; - throw new Error("Something went wrong with axis scaling"); - } - }; - ax.maskBreaks = function(v) { - var rangebreaksIn = ax.rangebreaks || []; - var bnds, b0, b1, vb, vDate; - if (!rangebreaksIn._cachedPatterns) { - rangebreaksIn._cachedPatterns = rangebreaksIn.map(function(brk2) { - return brk2.enabled && brk2.bounds ? Lib$1H.simpleMap( - brk2.bounds, - brk2.pattern ? cleanNumber$1 : ax.d2c - // case of pattern: '' - ) : null; - }); - } - if (!rangebreaksIn._cachedValues) { - rangebreaksIn._cachedValues = rangebreaksIn.map(function(brk2) { - return brk2.enabled && brk2.values ? Lib$1H.simpleMap(brk2.values, ax.d2c).sort(Lib$1H.sorterAsc) : null; - }); - } - for (var i = 0; i < rangebreaksIn.length; i++) { - var brk = rangebreaksIn[i]; - if (brk.enabled) { - if (brk.bounds) { - var pattern2 = brk.pattern; - bnds = rangebreaksIn._cachedPatterns[i]; - b0 = bnds[0]; - b1 = bnds[1]; - switch (pattern2) { - case WEEKDAY_PATTERN: - vDate = new Date(v); - vb = vDate.getUTCDay(); - if (b0 > b1) { - b1 += 7; - if (vb < b0) vb += 7; - } - break; - case HOUR_PATTERN: - vDate = new Date(v); - var hours2 = vDate.getUTCHours(); - var minutes2 = vDate.getUTCMinutes(); - var seconds2 = vDate.getUTCSeconds(); - var milliseconds2 = vDate.getUTCMilliseconds(); - vb = hours2 + (minutes2 / 60 + seconds2 / 3600 + milliseconds2 / 36e5); - if (b0 > b1) { - b1 += 24; - if (vb < b0) vb += 24; - } - break; - case "": - vb = v; - break; - } - if (vb >= b0 && vb < b1) return BADNUM$9; - } else { - var vals = rangebreaksIn._cachedValues[i]; - for (var j = 0; j < vals.length; j++) { - b0 = vals[j]; - b1 = b0 + brk.dvalue; - if (v >= b0 && v < b1) return BADNUM$9; - } - } - } - } - return v; - }; - ax.locateBreaks = function(r0, r1) { - var i, bnds, b0, b1; - var rangebreaksOut = []; - if (!ax.rangebreaks) return rangebreaksOut; - var rangebreaksIn = ax.rangebreaks.slice().sort(function(a, b) { - if (a.pattern === WEEKDAY_PATTERN && b.pattern === HOUR_PATTERN) return -1; - if (b.pattern === WEEKDAY_PATTERN && a.pattern === HOUR_PATTERN) return 1; - return 0; - }); - var addBreak = function(min, max) { - min = Lib$1H.constrain(min, r0, r1); - max = Lib$1H.constrain(max, r0, r1); - if (min === max) return; - var isNewBreak = true; - for (var j2 = 0; j2 < rangebreaksOut.length; j2++) { - var brkj = rangebreaksOut[j2]; - if (min < brkj.max && max >= brkj.min) { - if (min < brkj.min) { - brkj.min = min; - } - if (max > brkj.max) { - brkj.max = max; - } - isNewBreak = false; - } - } - if (isNewBreak) { - rangebreaksOut.push({ min, max }); - } - }; - for (i = 0; i < rangebreaksIn.length; i++) { - var brk = rangebreaksIn[i]; - if (brk.enabled) { - if (brk.bounds) { - var t02 = r0; - var t12 = r1; - if (brk.pattern) { - t02 = Math.floor(t02); - } - bnds = Lib$1H.simpleMap(brk.bounds, brk.pattern ? cleanNumber$1 : ax.r2l); - b0 = bnds[0]; - b1 = bnds[1]; - var t0Date = new Date(t02); - var bndDelta; - var step; - switch (brk.pattern) { - case WEEKDAY_PATTERN: - step = ONEWEEK$2; - bndDelta = ((b1 < b0 ? 7 : 0) + (b1 - b0)) * ONEDAY$1; - t02 += b0 * ONEDAY$1 - (t0Date.getUTCDay() * ONEDAY$1 + t0Date.getUTCHours() * ONEHOUR$1 + t0Date.getUTCMinutes() * ONEMIN$1 + t0Date.getUTCSeconds() * ONESEC$1 + t0Date.getUTCMilliseconds()); - break; - case HOUR_PATTERN: - step = ONEDAY$1; - bndDelta = ((b1 < b0 ? 24 : 0) + (b1 - b0)) * ONEHOUR$1; - t02 += b0 * ONEHOUR$1 - (t0Date.getUTCHours() * ONEHOUR$1 + t0Date.getUTCMinutes() * ONEMIN$1 + t0Date.getUTCSeconds() * ONESEC$1 + t0Date.getUTCMilliseconds()); - break; - default: - t02 = Math.min(bnds[0], bnds[1]); - t12 = Math.max(bnds[0], bnds[1]); - step = t12 - t02; - bndDelta = step; - } - for (var t = t02; t < t12; t += step) { - addBreak(t, t + bndDelta); - } - } else { - var vals = Lib$1H.simpleMap(brk.values, ax.d2c); - for (var j = 0; j < vals.length; j++) { - b0 = vals[j]; - b1 = b0 + brk.dvalue; - addBreak(b0, b1); - } - } - } - } - rangebreaksOut.sort(function(a, b) { - return a.min - b.min; - }); - return rangebreaksOut; - }; - ax.makeCalcdata = function(trace, axLetter2, opts) { - var arrayIn, arrayOut, i, len; - var axType = ax.type; - var cal = axType === "date" && trace[axLetter2 + "calendar"]; - if (axLetter2 in trace) { - arrayIn = trace[axLetter2]; - len = trace._length || Lib$1H.minRowLength(arrayIn); - if (Lib$1H.isTypedArray(arrayIn) && (axType === "linear" || axType === "log")) { - if (len === arrayIn.length) { - return arrayIn; - } else if (arrayIn.subarray) { - return arrayIn.subarray(0, len); - } - } - if (axType === "multicategory") { - return setMultiCategoryIndex(arrayIn, len); - } - arrayOut = new Array(len); - for (i = 0; i < len; i++) { - arrayOut[i] = ax.d2c(arrayIn[i], 0, cal, opts); - } - } else { - var v0 = axLetter2 + "0" in trace ? ax.d2c(trace[axLetter2 + "0"], 0, cal) : 0; - var dv2 = trace["d" + axLetter2] ? Number(trace["d" + axLetter2]) : 1; - arrayIn = trace[{ x: "y", y: "x" }[axLetter2]]; - len = trace._length || arrayIn.length; - arrayOut = new Array(len); - for (i = 0; i < len; i++) { - arrayOut[i] = v0 + i * dv2; - } - } - if (ax.rangebreaks) { - for (i = 0; i < len; i++) { - arrayOut[i] = ax.maskBreaks(arrayOut[i]); - } - } - return arrayOut; - }; - ax.isValidRange = function(range, nullOk) { - return Array.isArray(range) && range.length === 2 && (nullOk && range[0] === null || isNumeric$m(ax.r2l(range[0]))) && (nullOk && range[1] === null || isNumeric$m(ax.r2l(range[1]))); - }; - ax.getAutorangeDflt = function(range, options) { - var autorangeDflt = !ax.isValidRange(range, "nullOk"); - if (autorangeDflt && options && options.reverseDflt) autorangeDflt = "reversed"; - else if (range) { - if (range[0] === null && range[1] === null) { - autorangeDflt = true; - } else if (range[0] === null && range[1] !== null) { - autorangeDflt = "min"; - } else if (range[0] !== null && range[1] === null) { - autorangeDflt = "max"; - } - } - return autorangeDflt; - }; - ax.isReversed = function() { - var autorange2 = ax.autorange; - return autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; - }; - ax.isPtWithinRange = function(d, calendar) { - var coord = ax.c2l(d[axLetter], null, calendar); - var r0 = ax.r2l(ax.range[0]); - var r1 = ax.r2l(ax.range[1]); - if (r0 < r1) { - return r0 <= coord && coord <= r1; - } else { - return r1 <= coord && coord <= r0; - } - }; - ax._emptyCategories = function() { - ax._categories = []; - ax._categoriesMap = {}; - }; - ax.clearCalc = function() { - var group = ax._matchGroup; - if (group) { - var categories = null; - var categoriesMap = null; - for (var axId2 in group) { - var ax2 = fullLayout[axisIds$8.id2name(axId2)]; - if (ax2._categories) { - categories = ax2._categories; - categoriesMap = ax2._categoriesMap; - break; - } - } - if (categories && categoriesMap) { - ax._categories = categories; - ax._categoriesMap = categoriesMap; - } else { - ax._emptyCategories(); - } - } else { - ax._emptyCategories(); - } - if (ax._initialCategories) { - for (var j = 0; j < ax._initialCategories.length; j++) { - setCategoryIndex(ax._initialCategories[j]); - } - } - }; - ax.sortByInitialCategories = function() { - var affectedTraces = []; - ax._emptyCategories(); - if (ax._initialCategories) { - for (var j = 0; j < ax._initialCategories.length; j++) { - setCategoryIndex(ax._initialCategories[j]); - } - } - affectedTraces = affectedTraces.concat(ax._traceIndices); - var group = ax._matchGroup; - for (var axId2 in group) { - if (axId === axId2) continue; - var ax2 = fullLayout[axisIds$8.id2name(axId2)]; - ax2._categories = ax._categories; - ax2._categoriesMap = ax._categoriesMap; - affectedTraces = affectedTraces.concat(ax2._traceIndices); - } - return affectedTraces; - }; - var locale2 = fullLayout._d3locale; - if (ax.type === "date") { - ax._dateFormat = locale2 ? locale2.timeFormat : utcFormat; - ax._extraFormat = fullLayout._extraFormat; - } - ax._separators = fullLayout.separators; - ax._numFormat = locale2 ? locale2.numberFormat : numberFormat; - delete ax._minDtick; - delete ax._forceTick0; -}; -var isNumeric$l = fastIsnumeric; -var Lib$1G = libExports; -var BADNUM$8 = numerical.BADNUM; -var isArrayOrTypedArray$7 = Lib$1G.isArrayOrTypedArray; -var isDateTime = Lib$1G.isDateTime; -var cleanNumber2 = Lib$1G.cleanNumber; -var round$1 = Math.round; -var axis_autotype = function autoType(array2, calendar, opts) { - var a = array2; - var noMultiCategory = opts.noMultiCategory; - if (isArrayOrTypedArray$7(a) && !a.length) return "-"; - if (!noMultiCategory && multiCategory(a)) return "multicategory"; - if (noMultiCategory && Array.isArray(a[0])) { - var b = []; - for (var i = 0; i < a.length; i++) { - if (isArrayOrTypedArray$7(a[i])) { - for (var j = 0; j < a[i].length; j++) { - b.push(a[i][j]); - } - } - } - a = b; - } - if (moreDates(a, calendar)) return "date"; - var convertNumeric = opts.autotypenumbers !== "strict"; - if (category(a, convertNumeric)) return "category"; - if (linearOK(a, convertNumeric)) return "linear"; - return "-"; -}; -function hasTypeNumber(v, convertNumeric) { - return convertNumeric ? isNumeric$l(v) : typeof v === "number"; -} -function linearOK(a, convertNumeric) { - var len = a.length; - for (var i = 0; i < len; i++) { - if (hasTypeNumber(a[i], convertNumeric)) return true; - } - return false; -} -function moreDates(a, calendar) { - var len = a.length; - var inc = getIncrement(len); - var dats = 0; - var nums = 0; - var seen = {}; - for (var f = 0; f < len; f += inc) { - var i = round$1(f); - var ai = a[i]; - var stri = String(ai); - if (seen[stri]) continue; - seen[stri] = 1; - if (isDateTime(ai, calendar)) dats++; - if (isNumeric$l(ai)) nums++; - } - return dats > nums * 2; -} -function getIncrement(len) { - return Math.max(1, (len - 1) / 1e3); -} -function category(a, convertNumeric) { - var len = a.length; - var inc = getIncrement(len); - var nums = 0; - var cats = 0; - var seen = {}; - for (var f = 0; f < len; f += inc) { - var i = round$1(f); - var ai = a[i]; - var stri = String(ai); - if (seen[stri]) continue; - seen[stri] = 1; - var t = typeof ai; - if (t === "boolean") cats++; - else if (convertNumeric ? cleanNumber2(ai) !== BADNUM$8 : t === "number") nums++; - else if (t === "string") cats++; - } - return cats > nums * 2; -} -function multiCategory(a) { - return isArrayOrTypedArray$7(a[0]) && isArrayOrTypedArray$7(a[1]); -} -var d3$w = d3Exports; -var isNumeric$k = fastIsnumeric; -var Lib$1F = libExports; -var FP_SAFE = numerical.FP_SAFE; -var Registry$J = registry; -var Drawing$t = drawingExports; -var axIds = axis_ids; -var getFromId$1 = axIds.getFromId; -var isLinked$1 = axIds.isLinked; -var autorange$2 = { - applyAutorangeOptions, - getAutoRange, - makePadFn, - doAutoRange, - findExtremes: findExtremes$1, - concatExtremes -}; -function getAutoRange(gd, ax) { - var i, j; - var newRange = []; - var fullLayout = gd._fullLayout; - var getPadMin = makePadFn(fullLayout, ax, 0); - var getPadMax = makePadFn(fullLayout, ax, 1); - var extremes = concatExtremes(gd, ax); - var minArray = extremes.min; - var maxArray = extremes.max; - if (minArray.length === 0 || maxArray.length === 0) { - return Lib$1F.simpleMap(ax.range, ax.r2l); - } - var minmin = minArray[0].val; - var maxmax = maxArray[0].val; - for (i = 1; i < minArray.length; i++) { - if (minmin !== maxmax) break; - minmin = Math.min(minmin, minArray[i].val); - } - for (i = 1; i < maxArray.length; i++) { - if (minmin !== maxmax) break; - maxmax = Math.max(maxmax, maxArray[i].val); - } - var autorange2 = ax.autorange; - var axReverse = autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; - if (!axReverse && ax.range) { - var rng = Lib$1F.simpleMap(ax.range, ax.r2l); - axReverse = rng[1] < rng[0]; - } - if (ax.autorange === "reversed") { - ax.autorange = true; - } - var rangeMode = ax.rangemode; - var toZero = rangeMode === "tozero"; - var nonNegative = rangeMode === "nonnegative"; - var axLen = ax._length; - var minSpan = axLen / 10; - var mbest = 0; - var minpt, maxpt, minbest, maxbest, dp, dv2; - for (i = 0; i < minArray.length; i++) { - minpt = minArray[i]; - for (j = 0; j < maxArray.length; j++) { - maxpt = maxArray[j]; - dv2 = maxpt.val - minpt.val - calcBreaksLength(ax, minpt.val, maxpt.val); - if (dv2 > 0) { - dp = axLen - getPadMin(minpt) - getPadMax(maxpt); - if (dp > minSpan) { - if (dv2 / dp > mbest) { - minbest = minpt; - maxbest = maxpt; - mbest = dv2 / dp; - } - } else if (dv2 / axLen > mbest) { - minbest = { val: minpt.val, nopad: 1 }; - maxbest = { val: maxpt.val, nopad: 1 }; - mbest = dv2 / axLen; - } - } - } - } - function maximumPad(prev, pt) { - return Math.max(prev, getPadMax(pt)); - } - if (minmin === maxmax) { - var lower = minmin - 1; - var upper = minmin + 1; - if (toZero) { - if (minmin === 0) { - newRange = [0, 1]; - } else { - var maxPad = (minmin > 0 ? maxArray : minArray).reduce(maximumPad, 0); - var rangeEnd = minmin / (1 - Math.min(0.5, maxPad / axLen)); - newRange = minmin > 0 ? [0, rangeEnd] : [rangeEnd, 0]; - } - } else if (nonNegative) { - newRange = [Math.max(0, lower), Math.max(1, upper)]; - } else { - newRange = [lower, upper]; - } - } else { - if (toZero) { - if (minbest.val >= 0) { - minbest = { val: 0, nopad: 1 }; - } - if (maxbest.val <= 0) { - maxbest = { val: 0, nopad: 1 }; - } - } else if (nonNegative) { - if (minbest.val - mbest * getPadMin(minbest) < 0) { - minbest = { val: 0, nopad: 1 }; - } - if (maxbest.val <= 0) { - maxbest = { val: 1, nopad: 1 }; - } - } - mbest = (maxbest.val - minbest.val - calcBreaksLength(ax, minpt.val, maxpt.val)) / (axLen - getPadMin(minbest) - getPadMax(maxbest)); - newRange = [ - minbest.val - mbest * getPadMin(minbest), - maxbest.val + mbest * getPadMax(maxbest) - ]; - } - newRange = applyAutorangeOptions(newRange, ax); - if (ax.limitRange) ax.limitRange(); - if (axReverse) newRange.reverse(); - return Lib$1F.simpleMap(newRange, ax.l2r || Number); -} -function calcBreaksLength(ax, v0, v1) { - var lBreaks = 0; - if (ax.rangebreaks) { - var rangebreaksOut = ax.locateBreaks(v0, v1); - for (var i = 0; i < rangebreaksOut.length; i++) { - var brk = rangebreaksOut[i]; - lBreaks += brk.max - brk.min; - } - } - return lBreaks; -} -function makePadFn(fullLayout, ax, max) { - var extrappad = 0.05 * ax._length; - var anchorAxis = ax._anchorAxis || {}; - if ((ax.ticklabelposition || "").indexOf("inside") !== -1 || (anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) { - var axReverse = ax.isReversed(); - if (!axReverse) { - var rng = Lib$1F.simpleMap(ax.range, ax.r2l); - axReverse = rng[1] < rng[0]; - } - if (axReverse) max = !max; - } - var zero2 = 0; - if (!isLinked$1(fullLayout, ax._id)) { - zero2 = padInsideLabelsOnAnchorAxis(fullLayout, ax, max); - } - extrappad = Math.max(zero2, extrappad); - if (ax.constrain === "domain" && ax._inputDomain) { - extrappad *= (ax._inputDomain[1] - ax._inputDomain[0]) / (ax.domain[1] - ax.domain[0]); - } - return function getPad(pt) { - if (pt.nopad) return 0; - return pt.pad + (pt.extrapad ? extrappad : zero2); - }; -} -var TEXTPAD$5 = 3; -function padInsideLabelsOnAnchorAxis(fullLayout, ax, max) { - var pad2 = 0; - var isX = ax._id.charAt(0) === "x"; - for (var subplot in fullLayout._plots) { - var plotinfo = fullLayout._plots[subplot]; - if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; - var anchorAxis = (isX ? plotinfo.yaxis : plotinfo.xaxis) || {}; - if ((anchorAxis.ticklabelposition || "").indexOf("inside") !== -1) { - if (!max && (anchorAxis.side === "left" || anchorAxis.side === "bottom") || max && (anchorAxis.side === "top" || anchorAxis.side === "right")) { - if (anchorAxis._vals) { - var rad = Lib$1F.deg2rad(anchorAxis._tickAngles[anchorAxis._id + "tick"] || 0); - var cosA = Math.abs(Math.cos(rad)); - var sinA = Math.abs(Math.sin(rad)); - if (!anchorAxis._vals[0].bb) { - var cls = anchorAxis._id + "tick"; - var tickLabels = anchorAxis._selections[cls]; - tickLabels.each(function(d) { - var thisLabel = d3$w.select(this); - var mathjaxGroup = thisLabel.select(".text-math-group"); - if (mathjaxGroup.empty()) { - d.bb = Drawing$t.bBox(thisLabel.node()); - } - }); - } - for (var i = 0; i < anchorAxis._vals.length; i++) { - var t = anchorAxis._vals[i]; - var bb = t.bb; - if (bb) { - var w = 2 * TEXTPAD$5 + bb.width; - var h = 2 * TEXTPAD$5 + bb.height; - pad2 = Math.max( - pad2, - isX ? Math.max(w * cosA, h * sinA) : Math.max(h * cosA, w * sinA) - ); - } - } - } - if (anchorAxis.ticks === "inside" && anchorAxis.ticklabelposition === "inside") { - pad2 += anchorAxis.ticklen || 0; - } - } - } - } - return pad2; -} -function concatExtremes(gd, ax, noMatch) { - var axId = ax._id; - var fullData = gd._fullData; - var fullLayout = gd._fullLayout; - var minArray = []; - var maxArray = []; - var i, j, d; - function _concat(cont, indices) { - for (i = 0; i < indices.length; i++) { - var item = cont[indices[i]]; - var extremes = (item._extremes || {})[axId]; - if (item.visible === true && extremes) { - for (j = 0; j < extremes.min.length; j++) { - d = extremes.min[j]; - collapseMinArray(minArray, d.val, d.pad, { extrapad: d.extrapad }); - } - for (j = 0; j < extremes.max.length; j++) { - d = extremes.max[j]; - collapseMaxArray(maxArray, d.val, d.pad, { extrapad: d.extrapad }); - } - } - } - } - _concat(fullData, ax._traceIndices); - _concat(fullLayout.annotations || [], ax._annIndices || []); - _concat(fullLayout.shapes || [], ax._shapeIndices || []); - if (ax._matchGroup && !noMatch) { - for (var axId2 in ax._matchGroup) { - if (axId2 !== ax._id) { - var ax2 = getFromId$1(gd, axId2); - var extremes2 = concatExtremes(gd, ax2, true); - var lenRatio = ax._length / ax2._length; - for (j = 0; j < extremes2.min.length; j++) { - d = extremes2.min[j]; - collapseMinArray(minArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad }); - } - for (j = 0; j < extremes2.max.length; j++) { - d = extremes2.max[j]; - collapseMaxArray(maxArray, d.val, d.pad * lenRatio, { extrapad: d.extrapad }); - } - } - } - } - return { min: minArray, max: maxArray }; -} -function doAutoRange(gd, ax, presetRange) { - ax.setScale(); - if (ax.autorange) { - ax.range = presetRange ? presetRange.slice() : getAutoRange(gd, ax); - ax._r = ax.range.slice(); - ax._rl = Lib$1F.simpleMap(ax._r, ax.r2l); - var axIn = ax._input; - var edits = {}; - edits[ax._attr + ".range"] = ax.range; - edits[ax._attr + ".autorange"] = ax.autorange; - Registry$J.call("_storeDirectGUIEdit", gd.layout, gd._fullLayout._preGUI, edits); - axIn.range = ax.range.slice(); - axIn.autorange = ax.autorange; - } - var anchorAx = ax._anchorAxis; - if (anchorAx && anchorAx.rangeslider) { - var axeRangeOpts = anchorAx.rangeslider[ax._name]; - if (axeRangeOpts) { - if (axeRangeOpts.rangemode === "auto") { - axeRangeOpts.range = getAutoRange(gd, ax); - } - } - anchorAx._input.rangeslider[ax._name] = Lib$1F.extendFlat({}, axeRangeOpts); - } -} -function findExtremes$1(ax, data, opts) { - if (!opts) opts = {}; - if (!ax._m) ax.setScale(); - var minArray = []; - var maxArray = []; - var len = data.length; - var extrapad = opts.padded || false; - var tozero = opts.tozero && (ax.type === "linear" || ax.type === "-"); - var isLog = ax.type === "log"; - var hasArrayOption = false; - var vpadLinearized = opts.vpadLinearized || false; - var i, v, di, dmin, dmax, ppadiplus, ppadiminus, vmin, vmax; - function makePadAccessor(item) { - if (Array.isArray(item)) { - hasArrayOption = true; - return function(i2) { - return Math.max(Number(item[i2] || 0), 0); - }; - } else { - var v2 = Math.max(Number(item || 0), 0); - return function() { - return v2; - }; - } - } - var ppadplus = makePadAccessor((ax._m > 0 ? opts.ppadplus : opts.ppadminus) || opts.ppad || 0); - var ppadminus = makePadAccessor((ax._m > 0 ? opts.ppadminus : opts.ppadplus) || opts.ppad || 0); - var vpadplus = makePadAccessor(opts.vpadplus || opts.vpad); - var vpadminus = makePadAccessor(opts.vpadminus || opts.vpad); - if (!hasArrayOption) { - vmin = Infinity; - vmax = -Infinity; - if (isLog) { - for (i = 0; i < len; i++) { - v = data[i]; - if (v < vmin && v > 0) vmin = v; - if (v > vmax && v < FP_SAFE) vmax = v; - } - } else { - for (i = 0; i < len; i++) { - v = data[i]; - if (v < vmin && v > -FP_SAFE) vmin = v; - if (v > vmax && v < FP_SAFE) vmax = v; - } - } - data = [vmin, vmax]; - len = 2; - } - var collapseOpts = { tozero, extrapad }; - function addItem(i2) { - di = data[i2]; - if (!isNumeric$k(di)) return; - ppadiplus = ppadplus(i2); - ppadiminus = ppadminus(i2); - if (vpadLinearized) { - dmin = ax.c2l(di) - vpadminus(i2); - dmax = ax.c2l(di) + vpadplus(i2); - } else { - vmin = di - vpadminus(i2); - vmax = di + vpadplus(i2); - if (isLog && vmin < vmax / 10) vmin = vmax / 10; - dmin = ax.c2l(vmin); - dmax = ax.c2l(vmax); - } - if (tozero) { - dmin = Math.min(0, dmin); - dmax = Math.max(0, dmax); - } - if (goodNumber(dmin)) { - collapseMinArray(minArray, dmin, ppadiminus, collapseOpts); - } - if (goodNumber(dmax)) { - collapseMaxArray(maxArray, dmax, ppadiplus, collapseOpts); - } - } - var iMax = Math.min(6, len); - for (i = 0; i < iMax; i++) addItem(i); - for (i = len - 1; i >= iMax; i--) addItem(i); - return { - min: minArray, - max: maxArray, - opts - }; -} -function collapseMinArray(array2, newVal, newPad, opts) { - collapseArray(array2, newVal, newPad, opts, lessOrEqual); -} -function collapseMaxArray(array2, newVal, newPad, opts) { - collapseArray(array2, newVal, newPad, opts, greaterOrEqual); -} -function collapseArray(array2, newVal, newPad, opts, atLeastAsExtreme) { - var tozero = opts.tozero; - var extrapad = opts.extrapad; - var includeThis = true; - for (var j = 0; j < array2.length && includeThis; j++) { - var v = array2[j]; - if (atLeastAsExtreme(v.val, newVal) && v.pad >= newPad && (v.extrapad || !extrapad)) { - includeThis = false; - break; - } else if (atLeastAsExtreme(newVal, v.val) && v.pad <= newPad && (extrapad || !v.extrapad)) { - array2.splice(j, 1); - j--; - } - } - if (includeThis) { - var clipAtZero = tozero && newVal === 0; - array2.push({ - val: newVal, - pad: clipAtZero ? 0 : newPad, - extrapad: clipAtZero ? false : extrapad - }); - } -} -function goodNumber(v) { - return isNumeric$k(v) && Math.abs(v) < FP_SAFE; -} -function lessOrEqual(v0, v1) { - return v0 <= v1; -} -function greaterOrEqual(v0, v1) { - return v0 >= v1; -} -function applyAutorangeMinOptions(v, ax) { - var autorangeoptions = ax.autorangeoptions; - if (autorangeoptions && autorangeoptions.minallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) { - return autorangeoptions.minallowed; - } - if (autorangeoptions && autorangeoptions.clipmin !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) { - return Math.max(v, ax.d2l(autorangeoptions.clipmin)); - } - return v; -} -function applyAutorangeMaxOptions(v, ax) { - var autorangeoptions = ax.autorangeoptions; - if (autorangeoptions && autorangeoptions.maxallowed !== void 0 && hasValidMinAndMax(ax, autorangeoptions.minallowed, autorangeoptions.maxallowed)) { - return autorangeoptions.maxallowed; - } - if (autorangeoptions && autorangeoptions.clipmax !== void 0 && hasValidMinAndMax(ax, autorangeoptions.clipmin, autorangeoptions.clipmax)) { - return Math.min(v, ax.d2l(autorangeoptions.clipmax)); - } - return v; -} -function hasValidMinAndMax(ax, min, max) { - if (min !== void 0 && max !== void 0) { - min = ax.d2l(min); - max = ax.d2l(max); - return min < max; - } - return true; -} -function applyAutorangeOptions(range, ax) { - if (!ax || !ax.autorangeoptions) return range; - var min = range[0]; - var max = range[1]; - var include = ax.autorangeoptions.include; - if (include !== void 0) { - var lMin = ax.d2l(min); - var lMax = ax.d2l(max); - if (!Lib$1F.isArrayOrTypedArray(include)) include = [include]; - for (var i = 0; i < include.length; i++) { - var v = ax.d2l(include[i]); - if (lMin >= v) { - lMin = v; - min = v; - } - if (lMax <= v) { - lMax = v; - max = v; - } - } - } - min = applyAutorangeMinOptions(min, ax); - max = applyAutorangeMaxOptions(max, ax); - return [min, max]; -} -var d3$v = d3Exports; -var isNumeric$j = fastIsnumeric; -var Plots$b = plotsExports; -var Registry$I = registry; -var Lib$1E = libExports; -var strTranslate$a = Lib$1E.strTranslate; -var svgTextUtils$d = svg_text_utils; -var Titles$1 = titles; -var Color$H = colorExports; -var Drawing$s = drawingExports; -var axAttrs = layout_attributes$4; -var cleanTicks = clean_ticks; -var constants$Q = numerical; -var ONEMAXYEAR = constants$Q.ONEMAXYEAR; -var ONEAVGYEAR = constants$Q.ONEAVGYEAR; -var ONEMINYEAR = constants$Q.ONEMINYEAR; -var ONEMAXQUARTER = constants$Q.ONEMAXQUARTER; -var ONEAVGQUARTER = constants$Q.ONEAVGQUARTER; -var ONEMINQUARTER = constants$Q.ONEMINQUARTER; -var ONEMAXMONTH = constants$Q.ONEMAXMONTH; -var ONEAVGMONTH$1 = constants$Q.ONEAVGMONTH; -var ONEMINMONTH = constants$Q.ONEMINMONTH; -var ONEWEEK$1 = constants$Q.ONEWEEK; -var ONEDAY = constants$Q.ONEDAY; -var HALFDAY = ONEDAY / 2; -var ONEHOUR = constants$Q.ONEHOUR; -var ONEMIN = constants$Q.ONEMIN; -var ONESEC = constants$Q.ONESEC; -var ONEMILLI = constants$Q.ONEMILLI; -var ONEMICROSEC = constants$Q.ONEMICROSEC; -var MINUS_SIGN = constants$Q.MINUS_SIGN; -var BADNUM$7 = constants$Q.BADNUM; -var ZERO_PATH = { K: "zeroline" }; -var GRID_PATH = { K: "gridline", L: "path" }; -var MINORGRID_PATH = { K: "minor-gridline", L: "path" }; -var TICK_PATH = { K: "tick", L: "path" }; -var TICK_TEXT = { K: "tick", L: "text" }; -var MARGIN_MAPPING = { - width: ["x", "r", "l", "xl", "xr"], - height: ["y", "t", "b", "yt", "yb"], - right: ["r", "xr"], - left: ["l", "xl"], - top: ["t", "yt"], - bottom: ["b", "yb"] -}; -var alignmentConstants$4 = alignment$1; -var MID_SHIFT = alignmentConstants$4.MID_SHIFT; -var CAP_SHIFT = alignmentConstants$4.CAP_SHIFT; -var LINE_SPACING$6 = alignmentConstants$4.LINE_SPACING; -var OPPOSITE_SIDE = alignmentConstants$4.OPPOSITE_SIDE; -var TEXTPAD$4 = 3; -var axes = axes$1.exports = {}; -axes.setConvert = set_convert; -var autoType2 = axis_autotype; -var axisIds$7 = axis_ids; -var idSort = axisIds$7.idSort; -var isLinked = axisIds$7.isLinked; -axes.id2name = axisIds$7.id2name; -axes.name2id = axisIds$7.name2id; -axes.cleanId = axisIds$7.cleanId; -axes.list = axisIds$7.list; -axes.listIds = axisIds$7.listIds; -axes.getFromId = axisIds$7.getFromId; -axes.getFromTrace = axisIds$7.getFromTrace; -var autorange$1 = autorange$2; -axes.getAutoRange = autorange$1.getAutoRange; -axes.findExtremes = autorange$1.findExtremes; -var epsilon$2 = 1e-4; -function expandRange(range) { - var delta2 = (range[1] - range[0]) * epsilon$2; - return [ - range[0] - delta2, - range[1] + delta2 - ]; -} -axes.coerceRef = function(containerIn, containerOut, gd, attr, dflt, extraOption) { - var axLetter = attr.charAt(attr.length - 1); - var axlist = gd._fullLayout._subplots[axLetter + "axis"]; - var refAttr = attr + "ref"; - var attrDef = {}; - if (!dflt) dflt = axlist[0] || (typeof extraOption === "string" ? extraOption : extraOption[0]); - if (!extraOption) extraOption = dflt; - axlist = axlist.concat(axlist.map(function(x) { - return x + " domain"; - })); - attrDef[refAttr] = { - valType: "enumerated", - values: axlist.concat(extraOption ? typeof extraOption === "string" ? [extraOption] : extraOption : []), - dflt - }; - return Lib$1E.coerce(containerIn, containerOut, attrDef, refAttr); -}; -axes.getRefType = function(ar) { - if (ar === void 0) { - return ar; - } - if (ar === "paper") { - return "paper"; - } - if (ar === "pixel") { - return "pixel"; - } - if (/( domain)$/.test(ar)) { - return "domain"; - } else { - return "range"; - } -}; -axes.coercePosition = function(containerOut, gd, coerce2, axRef, attr, dflt) { - var cleanPos, pos; - var axRefType = axes.getRefType(axRef); - if (axRefType !== "range") { - cleanPos = Lib$1E.ensureNumber; - pos = coerce2(attr, dflt); - } else { - var ax = axes.getFromId(gd, axRef); - dflt = ax.fraction2r(dflt); - pos = coerce2(attr, dflt); - cleanPos = ax.cleanPos; - } - containerOut[attr] = cleanPos(pos); -}; -axes.cleanPosition = function(pos, gd, axRef) { - var cleanPos = axRef === "paper" || axRef === "pixel" ? Lib$1E.ensureNumber : axes.getFromId(gd, axRef).cleanPos; - return cleanPos(pos); -}; -axes.redrawComponents = function(gd, axIds2) { - axIds2 = axIds2 ? axIds2 : axes.listIds(gd); - var fullLayout = gd._fullLayout; - function _redrawOneComp(moduleName, methodName, stashName, shortCircuit) { - var method = Registry$I.getComponentMethod(moduleName, methodName); - var stash = {}; - for (var i = 0; i < axIds2.length; i++) { - var ax = fullLayout[axes.id2name(axIds2[i])]; - var indices = ax[stashName]; - for (var j = 0; j < indices.length; j++) { - var ind = indices[j]; - if (!stash[ind]) { - method(gd, ind); - stash[ind] = 1; - if (shortCircuit) return; - } - } - } - } - _redrawOneComp("annotations", "drawOne", "_annIndices"); - _redrawOneComp("shapes", "drawOne", "_shapeIndices"); - _redrawOneComp("images", "draw", "_imgIndices", true); - _redrawOneComp("selections", "drawOne", "_selectionIndices"); -}; -var getDataConversions = axes.getDataConversions = function(gd, trace, target, targetArray) { - var ax; - var d2cTarget = target === "x" || target === "y" || target === "z" ? target : targetArray; - if (Lib$1E.isArrayOrTypedArray(d2cTarget)) { - ax = { - type: autoType2(targetArray, void 0, { - autotypenumbers: gd._fullLayout.autotypenumbers - }), - _categories: [] - }; - axes.setConvert(ax); - if (ax.type === "category") { - for (var i = 0; i < targetArray.length; i++) { - ax.d2c(targetArray[i]); - } - } - } else { - ax = axes.getFromTrace(gd, trace, d2cTarget); - } - if (ax) return { d2c: ax.d2c, c2d: ax.c2d }; - if (d2cTarget === "ids") return { d2c: toString$1, c2d: toString$1 }; - return { d2c: toNum, c2d: toNum }; -}; -function toNum(v) { - return +v; -} -function toString$1(v) { - return String(v); -} -axes.getDataToCoordFunc = function(gd, trace, target, targetArray) { - return getDataConversions(gd, trace, target, targetArray).d2c; -}; -axes.counterLetter = function(id) { - var axLetter = id.charAt(0); - if (axLetter === "x") return "y"; - if (axLetter === "y") return "x"; -}; -axes.minDtick = function(ax, newDiff, newFirst, allow) { - if (["log", "category", "multicategory"].indexOf(ax.type) !== -1 || !allow) { - ax._minDtick = 0; - } else if (ax._minDtick === void 0) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } else if (ax._minDtick) { - if ((ax._minDtick / newDiff + 1e-6) % 1 < 2e-6 && // existing minDtick is an integer multiple of newDiff - // (within rounding err) - // and forceTick0 can be shifted to newFirst - ((newFirst - ax._forceTick0) / newDiff % 1 + 1.000001) % 1 < 2e-6) { - ax._minDtick = newDiff; - ax._forceTick0 = newFirst; - } else if ((newDiff / ax._minDtick + 1e-6) % 1 > 2e-6 || // if the converse is true (newDiff is a multiple of minDtick and - // newFirst can be shifted to forceTick0) then do nothing - same - // forcing stands. Otherwise, cancel forced minimum - ((newFirst - ax._forceTick0) / ax._minDtick % 1 + 1.000001) % 1 > 2e-6) { - ax._minDtick = 0; - } - } -}; -axes.saveRangeInitial = function(gd, overwrite) { - var axList = axes.list(gd, "", true); - var hasOneAxisChanged = false; - for (var i = 0; i < axList.length; i++) { - var ax = axList[i]; - var isNew = ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0; - var hasChanged = isNew || (ax.range[0] !== ax._rangeInitial0 || ax.range[1] !== ax._rangeInitial1); - var autorange2 = ax.autorange; - if (isNew && autorange2 !== true || overwrite && hasChanged) { - ax._rangeInitial0 = autorange2 === "min" || autorange2 === "max reversed" ? void 0 : ax.range[0]; - ax._rangeInitial1 = autorange2 === "max" || autorange2 === "min reversed" ? void 0 : ax.range[1]; - ax._autorangeInitial = autorange2; - hasOneAxisChanged = true; - } - } - return hasOneAxisChanged; -}; -axes.saveShowSpikeInitial = function(gd, overwrite) { - var axList = axes.list(gd, "", true); - var hasOneAxisChanged = false; - var allSpikesEnabled = "on"; - for (var i = 0; i < axList.length; i++) { - var ax = axList[i]; - var isNew = ax._showSpikeInitial === void 0; - var hasChanged = isNew || !(ax.showspikes === ax._showspikes); - if (isNew || overwrite && hasChanged) { - ax._showSpikeInitial = ax.showspikes; - hasOneAxisChanged = true; - } - if (allSpikesEnabled === "on" && !ax.showspikes) { - allSpikesEnabled = "off"; - } - } - gd._fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - return hasOneAxisChanged; -}; -axes.autoBin = function(data, ax, nbins, is2d, calendar, size) { - var dataMin = Lib$1E.aggNums(Math.min, null, data); - var dataMax = Lib$1E.aggNums(Math.max, null, data); - if (ax.type === "category" || ax.type === "multicategory") { - return { - start: dataMin - 0.5, - end: dataMax + 0.5, - size: Math.max(1, Math.round(size) || 1), - _dataSpan: dataMax - dataMin - }; - } - if (!calendar) calendar = ax.calendar; - var dummyAx; - if (ax.type === "log") { - dummyAx = { - type: "linear", - range: [dataMin, dataMax] - }; - } else { - dummyAx = { - type: ax.type, - range: Lib$1E.simpleMap([dataMin, dataMax], ax.c2r, 0, calendar), - calendar - }; - } - axes.setConvert(dummyAx); - size = size && cleanTicks.dtick(size, dummyAx.type); - if (size) { - dummyAx.dtick = size; - dummyAx.tick0 = cleanTicks.tick0(void 0, dummyAx.type, calendar); - } else { - var size0; - if (nbins) size0 = (dataMax - dataMin) / nbins; - else { - var distinctData = Lib$1E.distinctVals(data); - var msexp = Math.pow(10, Math.floor( - Math.log(distinctData.minDiff) / Math.LN10 - )); - var minSize = msexp * Lib$1E.roundUp( - distinctData.minDiff / msexp, - [0.9, 1.9, 4.9, 9.9], - true - ); - size0 = Math.max(minSize, 2 * Lib$1E.stdev(data) / Math.pow(data.length, is2d ? 0.25 : 0.4)); - if (!isNumeric$j(size0)) size0 = 1; - } - axes.autoTicks(dummyAx, size0); - } - var finalSize = dummyAx.dtick; - var binStart = axes.tickIncrement( - axes.tickFirst(dummyAx), - finalSize, - "reverse", - calendar - ); - var binEnd, bincount; - if (typeof finalSize === "number") { - binStart = autoShiftNumericBins(binStart, data, dummyAx, dataMin, dataMax); - bincount = 1 + Math.floor((dataMax - binStart) / finalSize); - binEnd = binStart + bincount * finalSize; - } else { - if (dummyAx.dtick.charAt(0) === "M") { - binStart = autoShiftMonthBins(binStart, data, finalSize, dataMin, calendar); - } - binEnd = binStart; - bincount = 0; - while (binEnd <= dataMax) { - binEnd = axes.tickIncrement(binEnd, finalSize, false, calendar); - bincount++; - } - } - return { - start: ax.c2r(binStart, 0, calendar), - end: ax.c2r(binEnd, 0, calendar), - size: finalSize, - _dataSpan: dataMax - dataMin - }; -}; -function autoShiftNumericBins(binStart, data, ax, dataMin, dataMax) { - var edgecount = 0; - var midcount = 0; - var intcount = 0; - var blankCount = 0; - function nearEdge(v) { - return (1 + (v - binStart) * 100 / ax.dtick) % 100 < 2; - } - for (var i = 0; i < data.length; i++) { - if (data[i] % 1 === 0) intcount++; - else if (!isNumeric$j(data[i])) blankCount++; - if (nearEdge(data[i])) edgecount++; - if (nearEdge(data[i] + ax.dtick / 2)) midcount++; - } - var dataCount = data.length - blankCount; - if (intcount === dataCount && ax.type !== "date") { - if (ax.dtick < 1) { - binStart = dataMin - 0.5 * ax.dtick; - } else { - binStart -= 0.5; - if (binStart + ax.dtick < dataMin) binStart += ax.dtick; - } - } else if (midcount < dataCount * 0.1) { - if (edgecount > dataCount * 0.3 || nearEdge(dataMin) || nearEdge(dataMax)) { - var binshift = ax.dtick / 2; - binStart += binStart + binshift < dataMin ? binshift : -binshift; - } - } - return binStart; -} -function autoShiftMonthBins(binStart, data, dtick2, dataMin, calendar) { - var stats2 = Lib$1E.findExactDates(data, calendar); - var threshold = 0.8; - if (stats2.exactDays > threshold) { - var numMonths = Number(dtick2.substr(1)); - if (stats2.exactYears > threshold && numMonths % 12 === 0) { - binStart = axes.tickIncrement(binStart, "M6", "reverse") + ONEDAY * 1.5; - } else if (stats2.exactMonths > threshold) { - binStart = axes.tickIncrement(binStart, "M1", "reverse") + ONEDAY * 15.5; - } else { - binStart -= HALFDAY; - } - var nextBinStart = axes.tickIncrement(binStart, dtick2); - if (nextBinStart <= dataMin) return nextBinStart; - } - return binStart; -} -axes.prepMinorTicks = function(mockAx, ax, opts) { - if (!ax.minor.dtick) { - delete mockAx.dtick; - var hasMajor = ax.dtick && isNumeric$j(ax._tmin); - var mockMinorRange; - if (hasMajor) { - var tick2 = axes.tickIncrement(ax._tmin, ax.dtick, true); - mockMinorRange = [ax._tmin, tick2 * 0.99 + ax._tmin * 0.01]; - } else { - var rl = Lib$1E.simpleMap(ax.range, ax.r2l); - mockMinorRange = [rl[0], 0.8 * rl[0] + 0.2 * rl[1]]; - } - mockAx.range = Lib$1E.simpleMap(mockMinorRange, ax.l2r); - mockAx._isMinor = true; - axes.prepTicks(mockAx, opts); - if (hasMajor) { - var numericMajor = isNumeric$j(ax.dtick); - var numericMinor = isNumeric$j(mockAx.dtick); - var majorNum = numericMajor ? ax.dtick : +ax.dtick.substring(1); - var minorNum = numericMinor ? mockAx.dtick : +mockAx.dtick.substring(1); - if (numericMajor && numericMinor) { - if (!isMultiple(majorNum, minorNum)) { - if (majorNum === 2 * ONEWEEK$1 && minorNum === 3 * ONEDAY) { - mockAx.dtick = ONEWEEK$1; - } else if (majorNum === ONEWEEK$1 && !(ax._input.minor || {}).nticks) { - mockAx.dtick = ONEDAY; - } else if (isClose(majorNum / minorNum, 2.5)) { - mockAx.dtick = majorNum / 2; - } else { - mockAx.dtick = majorNum; - } - } else if (majorNum === 2 * ONEWEEK$1 && minorNum === 2 * ONEDAY) { - mockAx.dtick = ONEWEEK$1; - } - } else if (String(ax.dtick).charAt(0) === "M") { - if (numericMinor) { - mockAx.dtick = "M1"; - } else { - if (!isMultiple(majorNum, minorNum)) { - mockAx.dtick = ax.dtick; - } else if (majorNum >= 12 && minorNum === 2) { - mockAx.dtick = "M3"; - } - } - } else if (String(mockAx.dtick).charAt(0) === "L") { - if (String(ax.dtick).charAt(0) === "L") { - if (!isMultiple(majorNum, minorNum)) { - mockAx.dtick = isClose(majorNum / minorNum, 2.5) ? ax.dtick / 2 : ax.dtick; - } - } else { - mockAx.dtick = "D1"; - } - } else if (mockAx.dtick === "D2" && +ax.dtick > 1) { - mockAx.dtick = 1; - } - } - mockAx.range = ax.range; - } - if (ax.minor._tick0Init === void 0) { - mockAx.tick0 = ax.tick0; - } -}; -function isMultiple(bigger, smaller) { - return Math.abs((bigger / smaller + 0.5) % 1 - 0.5) < 1e-3; -} -function isClose(a, b) { - return Math.abs(a / b - 1) < 1e-3; -} -axes.prepTicks = function(ax, opts) { - var rng = Lib$1E.simpleMap(ax.range, ax.r2l, void 0, void 0, opts); - if (ax.tickmode === "auto" || !ax.dtick) { - var nt = ax.nticks; - var minPx; - if (!nt) { - if (ax.type === "category" || ax.type === "multicategory") { - minPx = ax.tickfont ? Lib$1E.bigFont(ax.tickfont.size || 12) : 15; - nt = ax._length / minPx; - } else { - minPx = ax._id.charAt(0) === "y" ? 40 : 80; - nt = Lib$1E.constrain(ax._length / minPx, 4, 9) + 1; - } - if (ax._name === "radialaxis") nt *= 2; - } - if (!(ax.minor && ax.minor.tickmode !== "array")) { - if (ax.tickmode === "array") nt *= 100; - } - ax._roughDTick = Math.abs(rng[1] - rng[0]) / nt; - axes.autoTicks(ax, ax._roughDTick); - if (ax._minDtick > 0 && ax.dtick < ax._minDtick * 2) { - ax.dtick = ax._minDtick; - ax.tick0 = ax.l2r(ax._forceTick0); - } - } - if (ax.ticklabelmode === "period") { - adjustPeriodDelta(ax); - } - if (!ax.tick0) { - ax.tick0 = ax.type === "date" ? "2000-01-01" : 0; - } - if (ax.type === "date" && ax.dtick < 0.1) ax.dtick = 0.1; - autoTickRound(ax); -}; -function nMonths(dtick2) { - return +dtick2.substring(1); -} -function adjustPeriodDelta(ax) { - var definedDelta; - function mDate() { - return !(isNumeric$j(ax.dtick) || ax.dtick.charAt(0) !== "M"); - } - var isMDate = mDate(); - var tickformat = axes.getTickFormat(ax); - if (tickformat) { - var noDtick = ax._dtickInit !== ax.dtick; - if (!/%[fLQsSMX]/.test(tickformat)) { - if (/%[HI]/.test(tickformat)) { - definedDelta = ONEHOUR; - if (noDtick && !isMDate && ax.dtick < ONEHOUR) ax.dtick = ONEHOUR; - } else if (/%p/.test(tickformat)) { - definedDelta = HALFDAY; - if (noDtick && !isMDate && ax.dtick < HALFDAY) ax.dtick = HALFDAY; - } else if (/%[Aadejuwx]/.test(tickformat)) { - definedDelta = ONEDAY; - if (noDtick && !isMDate && ax.dtick < ONEDAY) ax.dtick = ONEDAY; - } else if (/%[UVW]/.test(tickformat)) { - definedDelta = ONEWEEK$1; - if (noDtick && !isMDate && ax.dtick < ONEWEEK$1) ax.dtick = ONEWEEK$1; - } else if (/%[Bbm]/.test(tickformat)) { - definedDelta = ONEAVGMONTH$1; - if (noDtick && (isMDate ? nMonths(ax.dtick) < 1 : ax.dtick < ONEMINMONTH)) ax.dtick = "M1"; - } else if (/%[q]/.test(tickformat)) { - definedDelta = ONEAVGQUARTER; - if (noDtick && (isMDate ? nMonths(ax.dtick) < 3 : ax.dtick < ONEMINQUARTER)) ax.dtick = "M3"; - } else if (/%[Yy]/.test(tickformat)) { - definedDelta = ONEAVGYEAR; - if (noDtick && (isMDate ? nMonths(ax.dtick) < 12 : ax.dtick < ONEMINYEAR)) ax.dtick = "M12"; - } - } - } - isMDate = mDate(); - if (isMDate && ax.tick0 === ax._dowTick0) { - ax.tick0 = ax._rawTick0; - } - ax._definedDelta = definedDelta; -} -function positionPeriodTicks(tickVals, ax, definedDelta) { - for (var i = 0; i < tickVals.length; i++) { - var v = tickVals[i].value; - var a = i; - var b = i + 1; - if (i < tickVals.length - 1) { - a = i; - b = i + 1; - } else if (i > 0) { - a = i - 1; - b = i; - } else { - a = i; - b = i; - } - var A2 = tickVals[a].value; - var B2 = tickVals[b].value; - var actualDelta = Math.abs(B2 - A2); - var delta2 = definedDelta || actualDelta; - var periodLength = 0; - if (delta2 >= ONEMINYEAR) { - if (actualDelta >= ONEMINYEAR && actualDelta <= ONEMAXYEAR) { - periodLength = actualDelta; - } else { - periodLength = ONEAVGYEAR; - } - } else if (definedDelta === ONEAVGQUARTER && delta2 >= ONEMINQUARTER) { - if (actualDelta >= ONEMINQUARTER && actualDelta <= ONEMAXQUARTER) { - periodLength = actualDelta; - } else { - periodLength = ONEAVGQUARTER; - } - } else if (delta2 >= ONEMINMONTH) { - if (actualDelta >= ONEMINMONTH && actualDelta <= ONEMAXMONTH) { - periodLength = actualDelta; - } else { - periodLength = ONEAVGMONTH$1; - } - } else if (definedDelta === ONEWEEK$1 && delta2 >= ONEWEEK$1) { - periodLength = ONEWEEK$1; - } else if (delta2 >= ONEDAY) { - periodLength = ONEDAY; - } else if (definedDelta === HALFDAY && delta2 >= HALFDAY) { - periodLength = HALFDAY; - } else if (definedDelta === ONEHOUR && delta2 >= ONEHOUR) { - periodLength = ONEHOUR; - } - var inBetween; - if (periodLength >= actualDelta) { - periodLength = actualDelta; - inBetween = true; - } - var endPeriod = v + periodLength; - if (ax.rangebreaks && periodLength > 0) { - var nAll = 84; - var n = 0; - for (var c = 0; c < nAll; c++) { - var r = (c + 0.5) / nAll; - if (ax.maskBreaks(v * (1 - r) + r * endPeriod) !== BADNUM$7) n++; - } - periodLength *= n / nAll; - if (!periodLength) { - tickVals[i].drop = true; - } - if (inBetween && actualDelta > ONEWEEK$1) periodLength = actualDelta; - } - if (periodLength > 0 || // not instant - i === 0) { - tickVals[i].periodX = v + periodLength / 2; - } - } -} -axes.calcTicks = function calcTicks(ax, opts) { - var type = ax.type; - var calendar = ax.calendar; - var ticklabelstep = ax.ticklabelstep; - var isPeriod = ax.ticklabelmode === "period"; - var isReversed2 = ax.range[0] > ax.range[1]; - var ticklabelIndex = !ax.ticklabelindex || Lib$1E.isArrayOrTypedArray(ax.ticklabelindex) ? ax.ticklabelindex : [ax.ticklabelindex]; - var rng = Lib$1E.simpleMap(ax.range, ax.r2l, void 0, void 0, opts); - var axrev = rng[1] < rng[0]; - var minRange = Math.min(rng[0], rng[1]); - var maxRange = Math.max(rng[0], rng[1]); - var maxTicks = Math.max(1e3, ax._length || 0); - var ticksOut = []; - var minorTicks = []; - var tickVals = []; - var minorTickVals = []; - var allTicklabelVals = []; - var hasMinor = ax.minor && (ax.minor.ticks || ax.minor.showgrid); - for (var major = 1; major >= (hasMinor ? 0 : 1); major--) { - var isMinor = !major; - if (major) { - ax._dtickInit = ax.dtick; - ax._tick0Init = ax.tick0; - } else { - ax.minor._dtickInit = ax.minor.dtick; - ax.minor._tick0Init = ax.minor.tick0; - } - var mockAx = major ? ax : Lib$1E.extendFlat({}, ax, ax.minor); - if (isMinor) { - axes.prepMinorTicks(mockAx, ax, opts); - } else { - axes.prepTicks(mockAx, opts); - } - if (mockAx.tickmode === "array") { - if (major) { - tickVals = []; - ticksOut = arrayTicks(ax, !isMinor); - } else { - minorTickVals = []; - minorTicks = arrayTicks(ax, !isMinor); - } - continue; - } - if (mockAx.tickmode === "sync") { - tickVals = []; - ticksOut = syncTicks(ax); - continue; - } - var exRng = expandRange(rng); - var startTick = exRng[0]; - var endTick = exRng[1]; - var numDtick = isNumeric$j(mockAx.dtick); - var isDLog = type === "log" && !(numDtick || mockAx.dtick.charAt(0) === "L"); - var x0 = axes.tickFirst(mockAx, opts); - if (major) { - ax._tmin = x0; - if (x0 < startTick !== axrev) break; - if (type === "category" || type === "multicategory") { - endTick = axrev ? Math.max(-0.5, endTick) : Math.min(ax._categories.length - 0.5, endTick); - } - } - var prevX = null; - var x = x0; - var majorId; - if (major) { - var _dTick; - if (numDtick) { - _dTick = ax.dtick; - } else { - if (type === "date") { - if (typeof ax.dtick === "string" && ax.dtick.charAt(0) === "M") { - _dTick = ONEAVGMONTH$1 * ax.dtick.substring(1); - } - } else { - _dTick = ax._roughDTick; - } - } - majorId = Math.round((ax.r2l(x) - ax.r2l(ax.tick0)) / _dTick) - 1; - } - var dtick2 = mockAx.dtick; - if (mockAx.rangebreaks && mockAx._tick0Init !== mockAx.tick0) { - x = moveOutsideBreak(x, ax); - if (!axrev) { - x = axes.tickIncrement(x, dtick2, !axrev, calendar); - } - } - if (major && isPeriod) { - x = axes.tickIncrement(x, dtick2, !axrev, calendar); - majorId--; - } - for (; axrev ? x >= endTick : x <= endTick; x = axes.tickIncrement( - x, - dtick2, - axrev, - calendar - )) { - if (major) majorId++; - if (mockAx.rangebreaks) { - if (!axrev) { - if (x < startTick) continue; - if (mockAx.maskBreaks(x) === BADNUM$7 && moveOutsideBreak(x, mockAx) >= maxRange) break; - } - } - if (tickVals.length > maxTicks || x === prevX) break; - prevX = x; - var obj = { value: x }; - if (major) { - if (isDLog && x !== (x | 0)) { - obj.simpleLabel = true; - } - if (ticklabelstep > 1 && majorId % ticklabelstep) { - obj.skipLabel = true; - } - tickVals.push(obj); - } else { - obj.minor = true; - minorTickVals.push(obj); - } - } - } - if (!minorTickVals || minorTickVals.length < 2) { - ticklabelIndex = false; - } else { - var diff = (minorTickVals[1].value - minorTickVals[0].value) * (isReversed2 ? -1 : 1); - if (!periodCompatibleWithTickformat(diff, ax.tickformat)) { - ticklabelIndex = false; - } - } - if (!ticklabelIndex) { - allTicklabelVals = tickVals; - } else { - var allTickVals = tickVals.concat(minorTickVals); - if (isPeriod && tickVals.length) { - allTickVals = allTickVals.slice(1); - } - allTickVals = allTickVals.sort(function(a, b) { - return a.value - b.value; - }).filter(function(tick, index2, self2) { - return index2 === 0 || tick.value !== self2[index2 - 1].value; - }); - var majorTickIndices = allTickVals.map(function(item, index2) { - return item.minor === void 0 && !item.skipLabel ? index2 : null; - }).filter(function(index2) { - return index2 !== null; - }); - majorTickIndices.forEach(function(majorIdx) { - ticklabelIndex.map(function(nextLabelIdx) { - var minorIdx = majorIdx + nextLabelIdx; - if (minorIdx >= 0 && minorIdx < allTickVals.length) { - Lib$1E.pushUnique(allTicklabelVals, allTickVals[minorIdx]); - } - }); - }); - } - if (hasMinor) { - var canOverlap = ax.minor.ticks === "inside" && ax.ticks === "outside" || ax.minor.ticks === "outside" && ax.ticks === "inside"; - if (!canOverlap) { - var majorValues = tickVals.map(function(d) { - return d.value; - }); - var list = []; - for (var k = 0; k < minorTickVals.length; k++) { - var T = minorTickVals[k]; - var v = T.value; - if (majorValues.indexOf(v) !== -1) { - continue; - } - var found = false; - for (var q = 0; !found && q < tickVals.length; q++) { - if ( - // add 10e6 to eliminate problematic digits - 1e7 + tickVals[q].value === 1e7 + v - ) { - found = true; - } - } - if (!found) list.push(T); - } - minorTickVals = list; - } - } - if (isPeriod) positionPeriodTicks(allTicklabelVals, ax, ax._definedDelta); - var i; - if (ax.rangebreaks) { - var flip = ax._id.charAt(0) === "y"; - var fontSize = 1; - if (ax.tickmode === "auto") { - fontSize = ax.tickfont ? ax.tickfont.size : 12; - } - var prevL = NaN; - for (i = tickVals.length - 1; i > -1; i--) { - if (tickVals[i].drop) { - tickVals.splice(i, 1); - continue; - } - tickVals[i].value = moveOutsideBreak(tickVals[i].value, ax); - var l = ax.c2p(tickVals[i].value); - if (flip ? prevL > l - fontSize : prevL < l + fontSize) { - tickVals.splice(axrev ? i + 1 : i, 1); - } else { - prevL = l; - } - } - } - if (isAngular(ax) && Math.abs(rng[1] - rng[0]) === 360) { - tickVals.pop(); - } - ax._tmax = (tickVals[tickVals.length - 1] || {}).value; - ax._prevDateHead = ""; - ax._inCalcTicks = true; - var lastVisibleHead; - var hideLabel = function(tick) { - tick.text = ""; - ax._prevDateHead = lastVisibleHead; - }; - tickVals = tickVals.concat(minorTickVals); - function setTickLabel(ax2, tickVal) { - var text = axes.tickText( - ax2, - tickVal.value, - false, - // hover - tickVal.simpleLabel - // noSuffixPrefix - ); - var p = tickVal.periodX; - if (p !== void 0) { - text.periodX = p; - if (p > maxRange || p < minRange) { - if (p > maxRange) text.periodX = maxRange; - if (p < minRange) text.periodX = minRange; - hideLabel(text); - } - } - return text; - } - var t; - for (i = 0; i < tickVals.length; i++) { - var _minor = tickVals[i].minor; - var _value = tickVals[i].value; - if (_minor) { - if (ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) !== -1) { - t = setTickLabel(ax, tickVals[i]); - } else { - t = { x: _value }; - } - t.minor = true; - minorTicks.push(t); - } else { - lastVisibleHead = ax._prevDateHead; - t = setTickLabel(ax, tickVals[i]); - if (tickVals[i].skipLabel || ticklabelIndex && allTicklabelVals.indexOf(tickVals[i]) === -1) { - hideLabel(t); - } - ticksOut.push(t); - } - } - ticksOut = ticksOut.concat(minorTicks); - ax._inCalcTicks = false; - if (isPeriod && ticksOut.length) { - ticksOut[0].noTick = true; - } - return ticksOut; -}; -function filterRangeBreaks(ax, ticksOut) { - if (ax.rangebreaks) { - ticksOut = ticksOut.filter(function(d) { - return ax.maskBreaks(d.x) !== BADNUM$7; - }); - } - return ticksOut; -} -function syncTicks(ax) { - var baseAxis = ax._mainAxis; - var ticksOut = []; - if (baseAxis._vals) { - for (var i = 0; i < baseAxis._vals.length; i++) { - if (baseAxis._vals[i].noTick) { - continue; - } - var pos = baseAxis.l2p(baseAxis._vals[i].x); - var vali = ax.p2l(pos); - var obj = axes.tickText(ax, vali); - if (baseAxis._vals[i].minor) { - obj.minor = true; - obj.text = ""; - } - ticksOut.push(obj); - } - } - ticksOut = filterRangeBreaks(ax, ticksOut); - return ticksOut; -} -function arrayTicks(ax, majorOnly) { - var rng = Lib$1E.simpleMap(ax.range, ax.r2l); - var exRng = expandRange(rng); - var tickMin = Math.min(exRng[0], exRng[1]); - var tickMax = Math.max(exRng[0], exRng[1]); - var tickVal2l = ax.type === "category" ? ax.d2l_noadd : ax.d2l; - if (ax.type === "log" && String(ax.dtick).charAt(0) !== "L") { - ax.dtick = "L" + Math.pow(10, Math.floor(Math.min(ax.range[0], ax.range[1])) - 1); - } - var ticksOut = []; - for (var isMinor = 0; isMinor <= 1; isMinor++) { - if (majorOnly !== void 0 && (majorOnly && isMinor || majorOnly === false && !isMinor)) continue; - if (isMinor && !ax.minor) continue; - var vals = !isMinor ? ax.tickvals : ax.minor.tickvals; - var text = !isMinor ? ax.ticktext : []; - if (!vals) continue; - if (!Lib$1E.isArrayOrTypedArray(text)) text = []; - for (var i = 0; i < vals.length; i++) { - var vali = tickVal2l(vals[i]); - if (vali > tickMin && vali < tickMax) { - var obj = axes.tickText(ax, vali, false, String(text[i])); - if (isMinor) { - obj.minor = true; - obj.text = ""; - } - ticksOut.push(obj); - } - } - } - ticksOut = filterRangeBreaks(ax, ticksOut); - return ticksOut; -} -var roundBase10 = [2, 5, 10]; -var roundBase24 = [1, 2, 3, 6, 12]; -var roundBase60 = [1, 2, 5, 10, 15, 30]; -var roundDays = [1, 2, 3, 7, 14]; -var roundLog1 = [-0.046, 0, 0.301, 0.477, 0.602, 0.699, 0.778, 0.845, 0.903, 0.954, 1]; -var roundLog2 = [-0.301, 0, 0.301, 0.699, 1]; -var roundAngles = [15, 30, 45, 90, 180]; -function roundDTick(roughDTick, base, roundingSet) { - return base * Lib$1E.roundUp(roughDTick / base, roundingSet); -} -axes.autoTicks = function(ax, roughDTick, isMinor) { - var base; - function getBase(v) { - return Math.pow(v, Math.floor(Math.log(roughDTick) / Math.LN10)); - } - if (ax.type === "date") { - ax.tick0 = Lib$1E.dateTick0(ax.calendar, 0); - var roughX2 = 2 * roughDTick; - if (roughX2 > ONEAVGYEAR) { - roughDTick /= ONEAVGYEAR; - base = getBase(10); - ax.dtick = "M" + 12 * roundDTick(roughDTick, base, roundBase10); - } else if (roughX2 > ONEAVGMONTH$1) { - roughDTick /= ONEAVGMONTH$1; - ax.dtick = "M" + roundDTick(roughDTick, 1, roundBase24); - } else if (roughX2 > ONEDAY) { - ax.dtick = roundDTick(roughDTick, ONEDAY, ax._hasDayOfWeekBreaks ? [1, 2, 7, 14] : roundDays); - if (!isMinor) { - var tickformat = axes.getTickFormat(ax); - var isPeriod = ax.ticklabelmode === "period"; - if (isPeriod) ax._rawTick0 = ax.tick0; - if (/%[uVW]/.test(tickformat)) { - ax.tick0 = Lib$1E.dateTick0(ax.calendar, 2); - } else { - ax.tick0 = Lib$1E.dateTick0(ax.calendar, 1); - } - if (isPeriod) ax._dowTick0 = ax.tick0; - } - } else if (roughX2 > ONEHOUR) { - ax.dtick = roundDTick(roughDTick, ONEHOUR, roundBase24); - } else if (roughX2 > ONEMIN) { - ax.dtick = roundDTick(roughDTick, ONEMIN, roundBase60); - } else if (roughX2 > ONESEC) { - ax.dtick = roundDTick(roughDTick, ONESEC, roundBase60); - } else { - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - } else if (ax.type === "log") { - ax.tick0 = 0; - var rng = Lib$1E.simpleMap(ax.range, ax.r2l); - if (ax._isMinor) { - roughDTick *= 1.5; - } - if (roughDTick > 0.7) { - ax.dtick = Math.ceil(roughDTick); - } else if (Math.abs(rng[1] - rng[0]) < 1) { - var nt = 1.5 * Math.abs((rng[1] - rng[0]) / roughDTick); - roughDTick = Math.abs(Math.pow(10, rng[1]) - Math.pow(10, rng[0])) / nt; - base = getBase(10); - ax.dtick = "L" + roundDTick(roughDTick, base, roundBase10); - } else { - ax.dtick = roughDTick > 0.3 ? "D2" : "D1"; - } - } else if (ax.type === "category" || ax.type === "multicategory") { - ax.tick0 = 0; - ax.dtick = Math.ceil(Math.max(roughDTick, 1)); - } else if (isAngular(ax)) { - ax.tick0 = 0; - base = 1; - ax.dtick = roundDTick(roughDTick, base, roundAngles); - } else { - ax.tick0 = 0; - base = getBase(10); - ax.dtick = roundDTick(roughDTick, base, roundBase10); - } - if (ax.dtick === 0) ax.dtick = 1; - if (!isNumeric$j(ax.dtick) && typeof ax.dtick !== "string") { - var olddtick = ax.dtick; - ax.dtick = 1; - throw "ax.dtick error: " + String(olddtick); - } -}; -function autoTickRound(ax) { - var dtick2 = ax.dtick; - ax._tickexponent = 0; - if (!isNumeric$j(dtick2) && typeof dtick2 !== "string") { - dtick2 = 1; - } - if (ax.type === "category" || ax.type === "multicategory") { - ax._tickround = null; - } - if (ax.type === "date") { - var tick0ms = ax.r2l(ax.tick0); - var tick0str = ax.l2r(tick0ms).replace(/(^-|i)/g, ""); - var tick0len = tick0str.length; - if (String(dtick2).charAt(0) === "M") { - if (tick0len > 10 || tick0str.substr(5) !== "01-01") ax._tickround = "d"; - else ax._tickround = +dtick2.substr(1) % 12 === 0 ? "y" : "m"; - } else if (dtick2 >= ONEDAY && tick0len <= 10 || dtick2 >= ONEDAY * 15) ax._tickround = "d"; - else if (dtick2 >= ONEMIN && tick0len <= 16 || dtick2 >= ONEHOUR) ax._tickround = "M"; - else if (dtick2 >= ONESEC && tick0len <= 19 || dtick2 >= ONEMIN) ax._tickround = "S"; - else { - var tick1len = ax.l2r(tick0ms + dtick2).replace(/^-/, "").length; - ax._tickround = Math.max(tick0len, tick1len) - 20; - if (ax._tickround < 0) ax._tickround = 4; - } - } else if (isNumeric$j(dtick2) || dtick2.charAt(0) === "L") { - var rng = ax.range.map(ax.r2d || Number); - if (!isNumeric$j(dtick2)) dtick2 = Number(dtick2.substr(1)); - ax._tickround = 2 - Math.floor(Math.log(dtick2) / Math.LN10 + 0.01); - var maxend = Math.max(Math.abs(rng[0]), Math.abs(rng[1])); - var rangeexp = Math.floor(Math.log(maxend) / Math.LN10 + 0.01); - var minexponent = ax.minexponent === void 0 ? 3 : ax.minexponent; - if (Math.abs(rangeexp) > minexponent) { - if (isSIFormat(ax.exponentformat) && !beyondSI(rangeexp)) { - ax._tickexponent = 3 * Math.round((rangeexp - 1) / 3); - } else ax._tickexponent = rangeexp; - } - } else { - ax._tickround = null; - } -} -axes.tickIncrement = function(x, dtick2, axrev, calendar) { - var axSign = axrev ? -1 : 1; - if (isNumeric$j(dtick2)) return Lib$1E.increment(x, axSign * dtick2); - var tType = dtick2.charAt(0); - var dtSigned = axSign * Number(dtick2.substr(1)); - if (tType === "M") return Lib$1E.incrementMonth(x, dtSigned, calendar); - if (tType === "L") return Math.log(Math.pow(10, x) + dtSigned) / Math.LN10; - if (tType === "D") { - var tickset = dtick2 === "D2" ? roundLog2 : roundLog1; - var x2 = x + axSign * 0.01; - var frac = Lib$1E.roundUp(Lib$1E.mod(x2, 1), tickset, axrev); - return Math.floor(x2) + Math.log(d3$v.round(Math.pow(10, frac), 1)) / Math.LN10; - } - throw "unrecognized dtick " + String(dtick2); -}; -axes.tickFirst = function(ax, opts) { - var r2l = ax.r2l || Number; - var rng = Lib$1E.simpleMap(ax.range, r2l, void 0, void 0, opts); - var axrev = rng[1] < rng[0]; - var sRound = axrev ? Math.floor : Math.ceil; - var r0 = expandRange(rng)[0]; - var dtick2 = ax.dtick; - var tick02 = r2l(ax.tick0); - if (isNumeric$j(dtick2)) { - var tmin = sRound((r0 - tick02) / dtick2) * dtick2 + tick02; - if (ax.type === "category" || ax.type === "multicategory") { - tmin = Lib$1E.constrain(tmin, 0, ax._categories.length - 1); - } - return tmin; - } - var tType = dtick2.charAt(0); - var dtNum = Number(dtick2.substr(1)); - if (tType === "M") { - var cnt = 0; - var t02 = tick02; - var t12, mult, newDTick; - while (cnt < 10) { - t12 = axes.tickIncrement(t02, dtick2, axrev, ax.calendar); - if ((t12 - r0) * (t02 - r0) <= 0) { - if (axrev) return Math.min(t02, t12); - return Math.max(t02, t12); - } - mult = (r0 - (t02 + t12) / 2) / (t12 - t02); - newDTick = tType + (Math.abs(Math.round(mult)) || 1) * dtNum; - t02 = axes.tickIncrement(t02, newDTick, mult < 0 ? !axrev : axrev, ax.calendar); - cnt++; - } - Lib$1E.error("tickFirst did not converge", ax); - return t02; - } else if (tType === "L") { - return Math.log(sRound( - (Math.pow(10, r0) - tick02) / dtNum - ) * dtNum + tick02) / Math.LN10; - } else if (tType === "D") { - var tickset = dtick2 === "D2" ? roundLog2 : roundLog1; - var frac = Lib$1E.roundUp(Lib$1E.mod(r0, 1), tickset, axrev); - return Math.floor(r0) + Math.log(d3$v.round(Math.pow(10, frac), 1)) / Math.LN10; - } else throw "unrecognized dtick " + String(dtick2); -}; -axes.tickText = function(ax, x, hover3, noSuffixPrefix) { - var out = tickTextObj(ax, x); - var arrayMode = ax.tickmode === "array"; - var extraPrecision = hover3 || arrayMode; - var axType = ax.type; - var tickVal2l = axType === "category" ? ax.d2l_noadd : ax.d2l; - var i; - var inbounds = function(v) { - var p = ax.l2p(v); - return p >= 0 && p <= ax._length ? v : null; - }; - if (arrayMode && Lib$1E.isArrayOrTypedArray(ax.ticktext)) { - var rng = Lib$1E.simpleMap(ax.range, ax.r2l); - var minDiff = (Math.abs(rng[1] - rng[0]) - (ax._lBreaks || 0)) / 1e4; - for (i = 0; i < ax.ticktext.length; i++) { - if (Math.abs(x - tickVal2l(ax.tickvals[i])) < minDiff) break; - } - if (i < ax.ticktext.length) { - out.text = String(ax.ticktext[i]); - out.xbnd = [ - inbounds(out.x - 0.5), - inbounds(out.x + ax.dtick - 0.5) - ]; - return out; - } - } - function isHidden(showAttr) { - if (showAttr === void 0) return true; - if (hover3) return showAttr === "none"; - var firstOrLast = { - first: ax._tmin, - last: ax._tmax - }[showAttr]; - return showAttr !== "all" && x !== firstOrLast; - } - var hideexp = hover3 ? "never" : ax.exponentformat !== "none" && isHidden(ax.showexponent) ? "hide" : ""; - if (axType === "date") formatDate(ax, out, hover3, extraPrecision); - else if (axType === "log") formatLog(ax, out, hover3, extraPrecision, hideexp); - else if (axType === "category") formatCategory(ax, out); - else if (axType === "multicategory") formatMultiCategory(ax, out, hover3); - else if (isAngular(ax)) formatAngle(ax, out, hover3, extraPrecision, hideexp); - else formatLinear(ax, out, hover3, extraPrecision, hideexp); - if (!noSuffixPrefix) { - if (ax.tickprefix && !isHidden(ax.showtickprefix)) out.text = ax.tickprefix + out.text; - if (ax.ticksuffix && !isHidden(ax.showticksuffix)) out.text += ax.ticksuffix; - } - if (ax.labelalias && ax.labelalias.hasOwnProperty(out.text)) { - var t = ax.labelalias[out.text]; - if (typeof t === "string") out.text = t; - } - if (ax.tickson === "boundaries" || ax.showdividers) { - out.xbnd = [ - inbounds(out.x - 0.5), - inbounds(out.x + ax.dtick - 0.5) - ]; - } - return out; -}; -axes.hoverLabelText = function(ax, values, hoverformat) { - if (hoverformat) ax = Lib$1E.extendFlat({}, ax, { hoverformat }); - var val = Lib$1E.isArrayOrTypedArray(values) ? values[0] : values; - var val2 = Lib$1E.isArrayOrTypedArray(values) ? values[1] : void 0; - if (val2 !== void 0 && val2 !== val) { - return axes.hoverLabelText(ax, val, hoverformat) + " - " + axes.hoverLabelText(ax, val2, hoverformat); - } - var logOffScale = ax.type === "log" && val <= 0; - var tx = axes.tickText(ax, ax.c2l(logOffScale ? -val : val), "hover").text; - if (logOffScale) { - return val === 0 ? "0" : MINUS_SIGN + tx; - } - return tx; -}; -function tickTextObj(ax, x, text) { - var tf = ax.tickfont || {}; - return { - x, - dx: 0, - dy: 0, - text: text || "", - fontSize: tf.size, - font: tf.family, - fontWeight: tf.weight, - fontStyle: tf.style, - fontVariant: tf.variant, - fontTextcase: tf.textcase, - fontLineposition: tf.lineposition, - fontShadow: tf.shadow, - fontColor: tf.color - }; -} -function formatDate(ax, out, hover3, extraPrecision) { - var tr = ax._tickround; - var fmt = hover3 && ax.hoverformat || axes.getTickFormat(ax); - extraPrecision = !fmt && extraPrecision; - if (extraPrecision) { - if (isNumeric$j(tr)) tr = 4; - else tr = { y: "m", m: "d", d: "M", M: "S", S: 4 }[tr]; - } - var dateStr = Lib$1E.formatDate(out.x, fmt, tr, ax._dateFormat, ax.calendar, ax._extraFormat); - var headStr; - var splitIndex = dateStr.indexOf("\n"); - if (splitIndex !== -1) { - headStr = dateStr.substr(splitIndex + 1); - dateStr = dateStr.substr(0, splitIndex); - } - if (extraPrecision) { - if (headStr !== void 0 && (dateStr === "00:00:00" || dateStr === "00:00")) { - dateStr = headStr; - headStr = ""; - } else if (dateStr.length === 8) { - dateStr = dateStr.replace(/:00$/, ""); - } - } - if (headStr) { - if (hover3) { - if (tr === "d") dateStr += ", " + headStr; - else dateStr = headStr + (dateStr ? ", " + dateStr : ""); - } else { - if (!ax._inCalcTicks || ax._prevDateHead !== headStr) { - ax._prevDateHead = headStr; - dateStr += "
" + headStr; - } else { - var isInside = insideTicklabelposition(ax); - var side = ax._trueSide || ax.side; - if (!isInside && side === "top" || isInside && side === "bottom") { - dateStr += "
"; - } - } - } - } - out.text = dateStr; -} -function formatLog(ax, out, hover3, extraPrecision, hideexp) { - var dtick2 = ax.dtick; - var x = out.x; - var tickformat = ax.tickformat; - var dtChar0 = typeof dtick2 === "string" && dtick2.charAt(0); - if (hideexp === "never") { - hideexp = ""; - } - if (extraPrecision && dtChar0 !== "L") { - dtick2 = "L3"; - dtChar0 = "L"; - } - if (tickformat || dtChar0 === "L") { - out.text = numFormat(Math.pow(10, x), ax, hideexp, extraPrecision); - } else if (isNumeric$j(dtick2) || dtChar0 === "D" && Lib$1E.mod(x + 0.01, 1) < 0.1) { - var p = Math.round(x); - var absP = Math.abs(p); - var exponentFormat = ax.exponentformat; - if (exponentFormat === "power" || isSIFormat(exponentFormat) && beyondSI(p)) { - if (p === 0) out.text = 1; - else if (p === 1) out.text = "10"; - else out.text = "10" + (p > 1 ? "" : MINUS_SIGN) + absP + ""; - out.fontSize *= 1.25; - } else if ((exponentFormat === "e" || exponentFormat === "E") && absP > 2) { - out.text = "1" + exponentFormat + (p > 0 ? "+" : MINUS_SIGN) + absP; - } else { - out.text = numFormat(Math.pow(10, x), ax, "", "fakehover"); - if (dtick2 === "D1" && ax._id.charAt(0) === "y") { - out.dy -= out.fontSize / 6; - } - } - } else if (dtChar0 === "D") { - out.text = String(Math.round(Math.pow(10, Lib$1E.mod(x, 1)))); - out.fontSize *= 0.75; - } else throw "unrecognized dtick " + String(dtick2); - if (ax.dtick === "D1") { - var firstChar = String(out.text).charAt(0); - if (firstChar === "0" || firstChar === "1") { - if (ax._id.charAt(0) === "y") { - out.dx -= out.fontSize / 4; - } else { - out.dy += out.fontSize / 2; - out.dx += (ax.range[1] > ax.range[0] ? 1 : -1) * out.fontSize * (x < 0 ? 0.5 : 0.25); - } - } - } -} -function formatCategory(ax, out) { - var tt = ax._categories[Math.round(out.x)]; - if (tt === void 0) tt = ""; - out.text = String(tt); -} -function formatMultiCategory(ax, out, hover3) { - var v = Math.round(out.x); - var cats = ax._categories[v] || []; - var tt = cats[1] === void 0 ? "" : String(cats[1]); - var tt2 = cats[0] === void 0 ? "" : String(cats[0]); - if (hover3) { - out.text = tt2 + " - " + tt; - } else { - out.text = tt; - out.text2 = tt2; - } -} -function formatLinear(ax, out, hover3, extraPrecision, hideexp) { - if (hideexp === "never") { - hideexp = ""; - } else if (ax.showexponent === "all" && Math.abs(out.x / ax.dtick) < 1e-6) { - hideexp = "hide"; - } - out.text = numFormat(out.x, ax, hideexp, extraPrecision); -} -function formatAngle(ax, out, hover3, extraPrecision, hideexp) { - if (ax.thetaunit === "radians" && !hover3) { - var num = out.x / 180; - if (num === 0) { - out.text = "0"; - } else { - var frac = num2frac(num); - if (frac[1] >= 100) { - out.text = numFormat(Lib$1E.deg2rad(out.x), ax, hideexp, extraPrecision); - } else { - var isNeg = out.x < 0; - if (frac[1] === 1) { - if (frac[0] === 1) out.text = "π"; - else out.text = frac[0] + "π"; - } else { - out.text = [ - "", - frac[0], - "", - "⁄", - "", - frac[1], - "", - "π" - ].join(""); - } - if (isNeg) out.text = MINUS_SIGN + out.text; - } - } - } else { - out.text = numFormat(out.x, ax, hideexp, extraPrecision); - } -} -function num2frac(num) { - function almostEq(a, b) { - return Math.abs(a - b) <= 1e-6; - } - function findGCD(a, b) { - return almostEq(b, 0) ? a : findGCD(b, a % b); - } - function findPrecision(n) { - var e = 1; - while (!almostEq(Math.round(n * e) / e, n)) { - e *= 10; - } - return e; - } - var precision = findPrecision(num); - var number2 = num * precision; - var gcd = Math.abs(findGCD(number2, precision)); - return [ - // numerator - Math.round(number2 / gcd), - // denominator - Math.round(precision / gcd) - ]; -} -var SIPREFIXES = ["f", "p", "n", "μ", "m", "", "k", "M", "G", "T"]; -function isSIFormat(exponentFormat) { - return exponentFormat === "SI" || exponentFormat === "B"; -} -function beyondSI(exponent2) { - return exponent2 > 14 || exponent2 < -15; -} -function numFormat(v, ax, fmtoverride, hover3) { - var isNeg = v < 0; - var tickRound = ax._tickround; - var exponentFormat = fmtoverride || ax.exponentformat || "B"; - var exponent2 = ax._tickexponent; - var tickformat = axes.getTickFormat(ax); - var separatethousands = ax.separatethousands; - if (hover3) { - var ah = { - exponentformat: exponentFormat, - minexponent: ax.minexponent, - dtick: ax.showexponent === "none" ? ax.dtick : isNumeric$j(v) ? Math.abs(v) || 1 : 1, - // if not showing any exponents, don't change the exponent - // from what we calculate - range: ax.showexponent === "none" ? ax.range.map(ax.r2d) : [0, v || 1] - }; - autoTickRound(ah); - tickRound = (Number(ah._tickround) || 0) + 4; - exponent2 = ah._tickexponent; - if (ax.hoverformat) tickformat = ax.hoverformat; - } - if (tickformat) return ax._numFormat(tickformat)(v).replace(/-/g, MINUS_SIGN); - var e = Math.pow(10, -tickRound) / 2; - if (exponentFormat === "none") exponent2 = 0; - v = Math.abs(v); - if (v < e) { - v = "0"; - isNeg = false; - } else { - v += e; - if (exponent2) { - v *= Math.pow(10, -exponent2); - tickRound += exponent2; - } - if (tickRound === 0) v = String(Math.floor(v)); - else if (tickRound < 0) { - v = String(Math.round(v)); - v = v.substr(0, v.length + tickRound); - for (var i = tickRound; i < 0; i++) v += "0"; - } else { - v = String(v); - var dp = v.indexOf(".") + 1; - if (dp) v = v.substr(0, dp + tickRound).replace(/\.?0+$/, ""); - } - v = Lib$1E.numSeparate(v, ax._separators, separatethousands); - } - if (exponent2 && exponentFormat !== "hide") { - if (isSIFormat(exponentFormat) && beyondSI(exponent2)) exponentFormat = "power"; - var signedExponent; - if (exponent2 < 0) signedExponent = MINUS_SIGN + -exponent2; - else if (exponentFormat !== "power") signedExponent = "+" + exponent2; - else signedExponent = String(exponent2); - if (exponentFormat === "e" || exponentFormat === "E") { - v += exponentFormat + signedExponent; - } else if (exponentFormat === "power") { - v += "×10" + signedExponent + ""; - } else if (exponentFormat === "B" && exponent2 === 9) { - v += "B"; - } else if (isSIFormat(exponentFormat)) { - v += SIPREFIXES[exponent2 / 3 + 5]; - } - } - if (isNeg) return MINUS_SIGN + v; - return v; -} -axes.getTickFormat = function(ax) { - var i; - function convertToMs(dtick2) { - return typeof dtick2 !== "string" ? dtick2 : Number(dtick2.replace("M", "")) * ONEAVGMONTH$1; - } - function compareLogTicks(left, right) { - var priority = ["L", "D"]; - if (typeof left === typeof right) { - if (typeof left === "number") { - return left - right; - } else { - var leftPriority = priority.indexOf(left.charAt(0)); - var rightPriority = priority.indexOf(right.charAt(0)); - if (leftPriority === rightPriority) { - return Number(left.replace(/(L|D)/g, "")) - Number(right.replace(/(L|D)/g, "")); - } else { - return leftPriority - rightPriority; - } - } - } else { - return typeof left === "number" ? 1 : -1; - } - } - function isProperStop(dtick2, range, convert3) { - var convertFn = convert3 || function(x) { - return x; - }; - var leftDtick = range[0]; - var rightDtick = range[1]; - return (!leftDtick && typeof leftDtick !== "number" || convertFn(leftDtick) <= convertFn(dtick2)) && (!rightDtick && typeof rightDtick !== "number" || convertFn(rightDtick) >= convertFn(dtick2)); - } - function isProperLogStop(dtick2, range) { - var isLeftDtickNull = range[0] === null; - var isRightDtickNull = range[1] === null; - var isDtickInRangeLeft = compareLogTicks(dtick2, range[0]) >= 0; - var isDtickInRangeRight = compareLogTicks(dtick2, range[1]) <= 0; - return (isLeftDtickNull || isDtickInRangeLeft) && (isRightDtickNull || isDtickInRangeRight); - } - var tickstop, stopi; - if (ax.tickformatstops && ax.tickformatstops.length > 0) { - switch (ax.type) { - case "date": - case "linear": { - for (i = 0; i < ax.tickformatstops.length; i++) { - stopi = ax.tickformatstops[i]; - if (stopi.enabled && isProperStop(ax.dtick, stopi.dtickrange, convertToMs)) { - tickstop = stopi; - break; - } - } - break; - } - case "log": { - for (i = 0; i < ax.tickformatstops.length; i++) { - stopi = ax.tickformatstops[i]; - if (stopi.enabled && isProperLogStop(ax.dtick, stopi.dtickrange)) { - tickstop = stopi; - break; - } - } - break; - } - } - } - return tickstop ? tickstop.value : ax.tickformat; -}; -axes.getSubplots = function(gd, ax) { - var subplotObj = gd._fullLayout._subplots; - var allSubplots = subplotObj.cartesian.concat(subplotObj.gl2d || []); - var out = ax ? axes.findSubplotsWithAxis(allSubplots, ax) : allSubplots; - out.sort(function(a, b) { - var aParts = a.substr(1).split("y"); - var bParts = b.substr(1).split("y"); - if (aParts[0] === bParts[0]) return +aParts[1] - +bParts[1]; - return +aParts[0] - +bParts[0]; - }); - return out; -}; -axes.findSubplotsWithAxis = function(subplots, ax) { - var axMatch = new RegExp( - ax._id.charAt(0) === "x" ? "^" + ax._id + "y" : ax._id + "$" - ); - var subplotsWithAx = []; - for (var i = 0; i < subplots.length; i++) { - var sp = subplots[i]; - if (axMatch.test(sp)) subplotsWithAx.push(sp); - } - return subplotsWithAx; -}; -axes.makeClipPaths = function(gd) { - var fullLayout = gd._fullLayout; - if (fullLayout._hasOnlyLargeSploms) return; - var fullWidth = { _offset: 0, _length: fullLayout.width, _id: "" }; - var fullHeight = { _offset: 0, _length: fullLayout.height, _id: "" }; - var xaList = axes.list(gd, "x", true); - var yaList = axes.list(gd, "y", true); - var clipList = []; - var i, j; - for (i = 0; i < xaList.length; i++) { - clipList.push({ x: xaList[i], y: fullHeight }); - for (j = 0; j < yaList.length; j++) { - if (i === 0) clipList.push({ x: fullWidth, y: yaList[j] }); - clipList.push({ x: xaList[i], y: yaList[j] }); - } - } - var axClips = fullLayout._clips.selectAll(".axesclip").data(clipList, function(d) { - return d.x._id + d.y._id; - }); - axClips.enter().append("clipPath").classed("axesclip", true).attr("id", function(d) { - return "clip" + fullLayout._uid + d.x._id + d.y._id; - }).append("rect"); - axClips.exit().remove(); - axClips.each(function(d) { - d3$v.select(this).select("rect").attr({ - x: d.x._offset || 0, - y: d.y._offset || 0, - width: d.x._length || 1, - height: d.y._length || 1 - }); - }); -}; -axes.draw = function(gd, arg, opts) { - var fullLayout = gd._fullLayout; - if (arg === "redraw") { - fullLayout._paper.selectAll("g.subplot").each(function(d) { - var id = d[0]; - var plotinfo = fullLayout._plots[id]; - if (plotinfo) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - plotinfo.xaxislayer.selectAll("." + xa._id + "tick").remove(); - plotinfo.yaxislayer.selectAll("." + ya._id + "tick").remove(); - plotinfo.xaxislayer.selectAll("." + xa._id + "tick2").remove(); - plotinfo.yaxislayer.selectAll("." + ya._id + "tick2").remove(); - plotinfo.xaxislayer.selectAll("." + xa._id + "divider").remove(); - plotinfo.yaxislayer.selectAll("." + ya._id + "divider").remove(); - if (plotinfo.minorGridlayer) plotinfo.minorGridlayer.selectAll("path").remove(); - if (plotinfo.gridlayer) plotinfo.gridlayer.selectAll("path").remove(); - if (plotinfo.zerolinelayer) plotinfo.zerolinelayer.selectAll("path").remove(); - fullLayout._infolayer.select(".g-" + xa._id + "title").remove(); - fullLayout._infolayer.select(".g-" + ya._id + "title").remove(); - } - }); - } - var axList = !arg || arg === "redraw" ? axes.listIds(gd) : arg; - var fullAxList = axes.list(gd); - var overlayingShiftedAx = fullAxList.filter(function(ax) { - return ax.autoshift; - }).map(function(ax) { - return ax.overlaying; - }); - axList.map(function(axId) { - var ax = axes.getFromId(gd, axId); - if (ax.tickmode === "sync" && ax.overlaying) { - var overlayingIndex = axList.findIndex(function(axis) { - return axis === ax.overlaying; - }); - if (overlayingIndex >= 0) { - axList.unshift(axList.splice(overlayingIndex, 1).shift()); - } - } - }); - var axShifts = { false: { left: 0, right: 0 } }; - return Lib$1E.syncOrAsync(axList.map(function(axId) { - return function() { - if (!axId) return; - var ax = axes.getFromId(gd, axId); - if (!opts) opts = {}; - opts.axShifts = axShifts; - opts.overlayingShiftedAx = overlayingShiftedAx; - var axDone = axes.drawOne(gd, ax, opts); - if (ax._shiftPusher) { - incrementShift(ax, ax._fullDepth || 0, axShifts, true); - } - ax._r = ax.range.slice(); - ax._rl = Lib$1E.simpleMap(ax._r, ax.r2l); - return axDone; - }; - })); -}; -axes.drawOne = function(gd, ax, opts) { - opts = opts || {}; - var axShifts = opts.axShifts || {}; - var overlayingShiftedAx = opts.overlayingShiftedAx || []; - var i, sp, plotinfo; - ax.setScale(); - var fullLayout = gd._fullLayout; - var axId = ax._id; - var axLetter = axId.charAt(0); - var counterLetter = axes.counterLetter(axId); - var mainPlotinfo = fullLayout._plots[ax._mainSubplot]; - if (!mainPlotinfo) return; - ax._shiftPusher = ax.autoshift || overlayingShiftedAx.indexOf(ax._id) !== -1 || overlayingShiftedAx.indexOf(ax.overlaying) !== -1; - if (ax._shiftPusher & ax.anchor === "free") { - var selfPush = ax.linewidth / 2 || 0; - if (ax.ticks === "inside") { - selfPush += ax.ticklen; - } - incrementShift(ax, selfPush, axShifts, true); - incrementShift(ax, ax.shift || 0, axShifts, false); - } - if (opts.skipTitle !== true || ax._shift === void 0) ax._shift = setShiftVal(ax, axShifts); - var mainAxLayer = mainPlotinfo[axLetter + "axislayer"]; - var mainLinePosition = ax._mainLinePosition; - var mainLinePositionShift = mainLinePosition += ax._shift; - var mainMirrorPosition = ax._mainMirrorPosition; - var vals = ax._vals = axes.calcTicks(ax); - var axInfo = [ax.mirror, mainLinePositionShift, mainMirrorPosition].join("_"); - for (i = 0; i < vals.length; i++) { - vals[i].axInfo = axInfo; - } - ax._selections = {}; - if (ax._tickAngles) ax._prevTickAngles = ax._tickAngles; - ax._tickAngles = {}; - ax._depth = null; - var llbboxes = {}; - function getLabelLevelBbox(suffix) { - var cls = axId + (suffix || "tick"); - if (!llbboxes[cls]) llbboxes[cls] = calcLabelLevelBbox(ax, cls, mainLinePositionShift); - return llbboxes[cls]; - } - if (!ax.visible) return; - var transTickFn = axes.makeTransTickFn(ax); - var transTickLabelFn = axes.makeTransTickLabelFn(ax); - var tickVals; - var valsClipped; - var insideTicks = ax.ticks === "inside"; - var outsideTicks = ax.ticks === "outside"; - if (ax.tickson === "boundaries") { - var boundaryVals = getBoundaryVals(ax, vals); - valsClipped = axes.clipEnds(ax, boundaryVals); - tickVals = insideTicks ? valsClipped : boundaryVals; - } else { - valsClipped = axes.clipEnds(ax, vals); - tickVals = insideTicks && ax.ticklabelmode !== "period" ? valsClipped : vals; - } - var gridVals = ax._gridVals = valsClipped; - var dividerVals = getDividerVals(ax, vals); - if (!fullLayout._hasOnlyLargeSploms) { - var subplotsWithAx = ax._subplotsWith; - var finishedGrids = {}; - for (i = 0; i < subplotsWithAx.length; i++) { - sp = subplotsWithAx[i]; - plotinfo = fullLayout._plots[sp]; - var counterAxis = plotinfo[counterLetter + "axis"]; - var mainCounterID = counterAxis._mainAxis._id; - if (finishedGrids[mainCounterID]) continue; - finishedGrids[mainCounterID] = 1; - var gridPath = axLetter === "x" ? "M0," + counterAxis._offset + "v" + counterAxis._length : "M" + counterAxis._offset + ",0h" + counterAxis._length; - axes.drawGrid(gd, ax, { - vals: gridVals, - counterAxis, - layer: plotinfo.gridlayer.select("." + axId), - minorLayer: plotinfo.minorGridlayer.select("." + axId), - path: gridPath, - transFn: transTickFn - }); - axes.drawZeroLine(gd, ax, { - counterAxis, - layer: plotinfo.zerolinelayer, - path: gridPath, - transFn: transTickFn - }); - } - } - var tickPath; - var majorTickSigns = axes.getTickSigns(ax); - var minorTickSigns = axes.getTickSigns(ax, "minor"); - if (ax.ticks || ax.minor && ax.minor.ticks) { - var majorTickPath = axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[2]); - var minorTickPath = axes.makeTickPath(ax, mainLinePositionShift, minorTickSigns[2], { minor: true }); - var mirrorMajorTickPath; - var mirrorMinorTickPath; - var fullMajorTickPath; - var fullMinorTickPath; - if (ax._anchorAxis && ax.mirror && ax.mirror !== true) { - mirrorMajorTickPath = axes.makeTickPath(ax, mainMirrorPosition, majorTickSigns[3]); - mirrorMinorTickPath = axes.makeTickPath(ax, mainMirrorPosition, minorTickSigns[3], { minor: true }); - fullMajorTickPath = majorTickPath + mirrorMajorTickPath; - fullMinorTickPath = minorTickPath + mirrorMinorTickPath; - } else { - mirrorMajorTickPath = ""; - mirrorMinorTickPath = ""; - fullMajorTickPath = majorTickPath; - fullMinorTickPath = minorTickPath; - } - if (ax.showdividers && outsideTicks && ax.tickson === "boundaries") { - var dividerLookup = {}; - for (i = 0; i < dividerVals.length; i++) { - dividerLookup[dividerVals[i].x] = 1; - } - tickPath = function(d) { - return dividerLookup[d.x] ? mirrorMajorTickPath : fullMajorTickPath; - }; - } else { - tickPath = function(d) { - return d.minor ? fullMinorTickPath : fullMajorTickPath; - }; - } - } - axes.drawTicks(gd, ax, { - vals: tickVals, - layer: mainAxLayer, - path: tickPath, - transFn: transTickFn - }); - if (ax.mirror === "allticks") { - var tickSubplots = Object.keys(ax._linepositions || {}); - for (i = 0; i < tickSubplots.length; i++) { - sp = tickSubplots[i]; - plotinfo = fullLayout._plots[sp]; - var linepositions = ax._linepositions[sp] || []; - var p0 = linepositions[0]; - var p1 = linepositions[1]; - var isMinor = linepositions[2]; - var spTickPath = axes.makeTickPath( - ax, - p0, - isMinor ? majorTickSigns[0] : minorTickSigns[0], - { minor: isMinor } - ) + axes.makeTickPath( - ax, - p1, - isMinor ? majorTickSigns[1] : minorTickSigns[1], - { minor: isMinor } - ); - axes.drawTicks(gd, ax, { - vals: tickVals, - layer: plotinfo[axLetter + "axislayer"], - path: spTickPath, - transFn: transTickFn - }); - } - } - var seq = []; - seq.push(function() { - return axes.drawLabels(gd, ax, { - vals, - layer: mainAxLayer, - plotinfo, - transFn: transTickLabelFn, - labelFns: axes.makeLabelFns(ax, mainLinePositionShift) - }); - }); - if (ax.type === "multicategory") { - var pad2 = { x: 2, y: 10 }[axLetter]; - seq.push(function() { - var bboxKey = { x: "height", y: "width" }[axLetter]; - var standoff = getLabelLevelBbox()[bboxKey] + pad2 + (ax._tickAngles[axId + "tick"] ? ax.tickfont.size * LINE_SPACING$6 : 0); - return axes.drawLabels(gd, ax, { - vals: getSecondaryLabelVals(ax, vals), - layer: mainAxLayer, - cls: axId + "tick2", - repositionOnUpdate: true, - secondary: true, - transFn: transTickFn, - labelFns: axes.makeLabelFns(ax, mainLinePositionShift + standoff * majorTickSigns[4]) - }); - }); - seq.push(function() { - ax._depth = majorTickSigns[4] * (getLabelLevelBbox("tick2")[ax.side] - mainLinePositionShift); - return drawDividers(gd, ax, { - vals: dividerVals, - layer: mainAxLayer, - path: axes.makeTickPath(ax, mainLinePositionShift, majorTickSigns[4], { len: ax._depth }), - transFn: transTickFn - }); - }); - } else if (ax.title.hasOwnProperty("standoff")) { - seq.push(function() { - ax._depth = majorTickSigns[4] * (getLabelLevelBbox()[ax.side] - mainLinePositionShift); - }); - } - var hasRangeSlider = Registry$I.getComponentMethod("rangeslider", "isVisible")(ax); - if (!opts.skipTitle && !(hasRangeSlider && ax.side === "bottom")) { - seq.push(function() { - return drawTitle(gd, ax); - }); - } - seq.push(function() { - var s = ax.side.charAt(0); - var sMirror = OPPOSITE_SIDE[ax.side].charAt(0); - var pos = axes.getPxPosition(gd, ax); - var outsideTickLen = outsideTicks ? ax.ticklen : 0; - var llbbox; - var push; - var mirrorPush; - var rangeSliderPush; - if (ax.automargin || hasRangeSlider || ax._shiftPusher) { - if (ax.type === "multicategory") { - llbbox = getLabelLevelBbox("tick2"); - } else { - llbbox = getLabelLevelBbox(); - if (axLetter === "x" && s === "b") { - ax._depth = Math.max(llbbox.width > 0 ? llbbox.bottom - pos : 0, outsideTickLen); - } - } - } - var axDepth = 0; - var titleDepth = 0; - if (ax._shiftPusher) { - axDepth = Math.max( - outsideTickLen, - llbbox.height > 0 ? s === "l" ? pos - llbbox.left : llbbox.right - pos : 0 - ); - if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { - titleDepth = (ax._titleStandoff || 0) + (ax._titleScoot || 0); - if (s === "l") { - titleDepth += approxTitleDepth(ax); - } - } - ax._fullDepth = Math.max(axDepth, titleDepth); - } - if (ax.automargin) { - push = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 }; - var domainIndices = [0, 1]; - var shift = typeof ax._shift === "number" ? ax._shift : 0; - if (axLetter === "x") { - if (s === "b") { - push[s] = ax._depth; - } else { - push[s] = ax._depth = Math.max(llbbox.width > 0 ? pos - llbbox.top : 0, outsideTickLen); - domainIndices.reverse(); - } - if (llbbox.width > 0) { - var rExtra = llbbox.right - (ax._offset + ax._length); - if (rExtra > 0) { - push.xr = 1; - push.r = rExtra; - } - var lExtra = ax._offset - llbbox.left; - if (lExtra > 0) { - push.xl = 0; - push.l = lExtra; - } - } - } else { - if (s === "l") { - ax._depth = Math.max(llbbox.height > 0 ? pos - llbbox.left : 0, outsideTickLen); - push[s] = ax._depth - shift; - } else { - ax._depth = Math.max(llbbox.height > 0 ? llbbox.right - pos : 0, outsideTickLen); - push[s] = ax._depth + shift; - domainIndices.reverse(); - } - if (llbbox.height > 0) { - var bExtra = llbbox.bottom - (ax._offset + ax._length); - if (bExtra > 0) { - push.yb = 0; - push.b = bExtra; - } - var tExtra = ax._offset - llbbox.top; - if (tExtra > 0) { - push.yt = 1; - push.t = tExtra; - } - } - } - push[counterLetter] = ax.anchor === "free" ? ax.position : ax._anchorAxis.domain[domainIndices[0]]; - if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { - push[s] += approxTitleDepth(ax) + (ax.title.standoff || 0); - } - if (ax.mirror && ax.anchor !== "free") { - mirrorPush = { x: 0, y: 0, r: 0, l: 0, t: 0, b: 0 }; - mirrorPush[sMirror] = ax.linewidth; - if (ax.mirror && ax.mirror !== true) mirrorPush[sMirror] += outsideTickLen; - if (ax.mirror === true || ax.mirror === "ticks") { - mirrorPush[counterLetter] = ax._anchorAxis.domain[domainIndices[1]]; - } else if (ax.mirror === "all" || ax.mirror === "allticks") { - mirrorPush[counterLetter] = [ax._counterDomainMin, ax._counterDomainMax][domainIndices[1]]; - } - } - } - if (hasRangeSlider) { - rangeSliderPush = Registry$I.getComponentMethod("rangeslider", "autoMarginOpts")(gd, ax); - } - if (typeof ax.automargin === "string") { - filterPush(push, ax.automargin); - filterPush(mirrorPush, ax.automargin); - } - Plots$b.autoMargin(gd, axAutoMarginID(ax), push); - Plots$b.autoMargin(gd, axMirrorAutoMarginID(ax), mirrorPush); - Plots$b.autoMargin(gd, rangeSliderAutoMarginID(ax), rangeSliderPush); - }); - return Lib$1E.syncOrAsync(seq); -}; -function filterPush(push, automargin) { - if (!push) return; - var keepMargin = Object.keys(MARGIN_MAPPING).reduce(function(data, nextKey) { - if (automargin.indexOf(nextKey) !== -1) { - MARGIN_MAPPING[nextKey].forEach(function(key) { - data[key] = 1; - }); - } - return data; - }, {}); - Object.keys(push).forEach(function(key) { - if (!keepMargin[key]) { - if (key.length === 1) push[key] = 0; - else delete push[key]; - } - }); -} -function getBoundaryVals(ax, vals) { - var out = []; - var i; - var _push = function(d, bndIndex) { - var xb = d.xbnd[bndIndex]; - if (xb !== null) { - out.push(Lib$1E.extendFlat({}, d, { x: xb })); - } - }; - if (vals.length) { - for (i = 0; i < vals.length; i++) { - _push(vals[i], 0); - } - _push(vals[i - 1], 1); - } - return out; -} -function getSecondaryLabelVals(ax, vals) { - var out = []; - var lookup2 = {}; - for (var i = 0; i < vals.length; i++) { - var d = vals[i]; - if (lookup2[d.text2]) { - lookup2[d.text2].push(d.x); - } else { - lookup2[d.text2] = [d.x]; - } - } - for (var k in lookup2) { - out.push(tickTextObj(ax, Lib$1E.interp(lookup2[k], 0.5), k)); - } - return out; -} -function getDividerVals(ax, vals) { - var out = []; - var i, current; - var reversed = vals.length && vals[vals.length - 1].x < vals[0].x; - var _push = function(d2, bndIndex) { - var xb = d2.xbnd[bndIndex]; - if (xb !== null) { - out.push(Lib$1E.extendFlat({}, d2, { x: xb })); - } - }; - if (ax.showdividers && vals.length) { - for (i = 0; i < vals.length; i++) { - var d = vals[i]; - if (d.text2 !== current) { - _push(d, reversed ? 1 : 0); - } - current = d.text2; - } - _push(vals[i - 1], reversed ? 0 : 1); - } - return out; -} -function calcLabelLevelBbox(ax, cls, mainLinePositionShift) { - var top, bottom; - var left, right; - if (ax._selections[cls].size()) { - top = Infinity; - bottom = -Infinity; - left = Infinity; - right = -Infinity; - ax._selections[cls].each(function() { - var thisLabel = selectTickLabel(this); - var bb = Drawing$s.bBox(thisLabel.node().parentNode); - top = Math.min(top, bb.top); - bottom = Math.max(bottom, bb.bottom); - left = Math.min(left, bb.left); - right = Math.max(right, bb.right); - }); - } else { - var dummyCalc = axes.makeLabelFns(ax, mainLinePositionShift); - top = bottom = dummyCalc.yFn({ dx: 0, dy: 0, fontSize: 0 }); - left = right = dummyCalc.xFn({ dx: 0, dy: 0, fontSize: 0 }); - } - return { - top, - bottom, - left, - right, - height: bottom - top, - width: right - left - }; -} -axes.getTickSigns = function(ax, minor) { - var axLetter = ax._id.charAt(0); - var sideOpposite = { x: "top", y: "right" }[axLetter]; - var main2 = ax.side === sideOpposite ? 1 : -1; - var out = [-1, 1, main2, -main2]; - var ticks2 = minor ? (ax.minor || {}).ticks : ax.ticks; - if (ticks2 !== "inside" === (axLetter === "x")) { - out = out.map(function(v) { - return -v; - }); - } - if (ax.side) { - out.push({ l: -1, t: -1, r: 1, b: 1 }[ax.side.charAt(0)]); - } - return out; -}; -axes.makeTransTickFn = function(ax) { - return ax._id.charAt(0) === "x" ? function(d) { - return strTranslate$a(ax._offset + ax.l2p(d.x), 0); - } : function(d) { - return strTranslate$a(0, ax._offset + ax.l2p(d.x)); - }; -}; -axes.makeTransTickLabelFn = function(ax) { - var uv = getTickLabelUV(ax); - var shift = ax.ticklabelshift || 0; - var standoff = ax.ticklabelstandoff || 0; - var u = uv[0]; - var v = uv[1]; - var isReversed2 = ax.range[0] > ax.range[1]; - var labelsInside = ax.ticklabelposition && ax.ticklabelposition.indexOf("inside") !== -1; - var labelsOutside = !labelsInside; - if (shift) { - var shiftSign = isReversed2 ? -1 : 1; - shift = shift * shiftSign; - } - if (standoff) { - var side = ax.side; - var standoffSign = labelsInside && (side === "top" || side === "left") || labelsOutside && (side === "bottom" || side === "right") ? 1 : -1; - standoff = standoff * standoffSign; - } - return ax._id.charAt(0) === "x" ? function(d) { - return strTranslate$a( - u + ax._offset + ax.l2p(getPosX(d)) + shift, - v + standoff - ); - } : function(d) { - return strTranslate$a( - v + standoff, - u + ax._offset + ax.l2p(getPosX(d)) + shift - ); - }; -}; -function getPosX(d) { - return d.periodX !== void 0 ? d.periodX : d.x; -} -function getTickLabelUV(ax) { - var ticklabelposition = ax.ticklabelposition || ""; - var has = function(str2) { - return ticklabelposition.indexOf(str2) !== -1; - }; - var isTop = has("top"); - var isLeft = has("left"); - var isRight = has("right"); - var isBottom = has("bottom"); - var isInside = has("inside"); - var isAligned = isBottom || isLeft || isTop || isRight; - if (!isAligned && !isInside) return [0, 0]; - var side = ax.side; - var u = isAligned ? (ax.tickwidth || 0) / 2 : 0; - var v = TEXTPAD$4; - var fontSize = ax.tickfont ? ax.tickfont.size : 12; - if (isBottom || isTop) { - u += fontSize * CAP_SHIFT; - v += (ax.linewidth || 0) / 2; - } - if (isLeft || isRight) { - u += (ax.linewidth || 0) / 2; - v += TEXTPAD$4; - } - if (isInside && side === "top") { - v -= fontSize * (1 - CAP_SHIFT); - } - if (isLeft || isTop) u = -u; - if (side === "bottom" || side === "right") v = -v; - return [ - isAligned ? u : 0, - isInside ? v : 0 - ]; -} -axes.makeTickPath = function(ax, shift, sgn, opts) { - if (!opts) opts = {}; - var minor = opts.minor; - if (minor && !ax.minor) return ""; - var len = opts.len !== void 0 ? opts.len : minor ? ax.minor.ticklen : ax.ticklen; - var axLetter = ax._id.charAt(0); - var pad2 = (ax.linewidth || 1) / 2; - return axLetter === "x" ? "M0," + (shift + pad2 * sgn) + "v" + len * sgn : "M" + (shift + pad2 * sgn) + ",0h" + len * sgn; -}; -axes.makeLabelFns = function(ax, shift, angle) { - var ticklabelposition = ax.ticklabelposition || ""; - var has = function(str2) { - return ticklabelposition.indexOf(str2) !== -1; - }; - var isTop = has("top"); - var isLeft = has("left"); - var isRight = has("right"); - var isBottom = has("bottom"); - var isAligned = isBottom || isLeft || isTop || isRight; - var insideTickLabels = has("inside"); - var labelsOverTicks = ticklabelposition === "inside" && ax.ticks === "inside" || !insideTickLabels && ax.ticks === "outside" && ax.tickson !== "boundaries"; - var labelStandoff = 0; - var labelShift = 0; - var tickLen = labelsOverTicks ? ax.ticklen : 0; - if (insideTickLabels) { - tickLen *= -1; - } else if (isAligned) { - tickLen = 0; - } - if (labelsOverTicks) { - labelStandoff += tickLen; - if (angle) { - var rad = Lib$1E.deg2rad(angle); - labelStandoff = tickLen * Math.cos(rad) + 1; - labelShift = tickLen * Math.sin(rad); - } - } - if (ax.showticklabels && (labelsOverTicks || ax.showline)) { - labelStandoff += 0.2 * ax.tickfont.size; - } - labelStandoff += (ax.linewidth || 1) / 2 * (insideTickLabels ? -1 : 1); - var out = { - labelStandoff, - labelShift - }; - var x0, y0, ff, flipIt; - var xQ = 0; - var side = ax.side; - var axLetter = ax._id.charAt(0); - var tickangle = ax.tickangle; - var endSide; - if (axLetter === "x") { - endSide = !insideTickLabels && side === "bottom" || insideTickLabels && side === "top"; - flipIt = endSide ? 1 : -1; - if (insideTickLabels) flipIt *= -1; - x0 = labelShift * flipIt; - y0 = shift + labelStandoff * flipIt; - ff = endSide ? 1 : -0.2; - if (Math.abs(tickangle) === 90) { - if (insideTickLabels) { - ff += MID_SHIFT; - } else { - if (tickangle === -90 && side === "bottom") { - ff = CAP_SHIFT; - } else if (tickangle === 90 && side === "top") { - ff = MID_SHIFT; - } else { - ff = 0.5; - } - } - xQ = MID_SHIFT / 2 * (tickangle / 90); - } - out.xFn = function(d) { - return d.dx + x0 + xQ * d.fontSize; - }; - out.yFn = function(d) { - return d.dy + y0 + d.fontSize * ff; - }; - out.anchorFn = function(d, a) { - if (isAligned) { - if (isLeft) return "end"; - if (isRight) return "start"; - } - if (!isNumeric$j(a) || a === 0 || a === 180) { - return "middle"; - } - return a * flipIt < 0 !== insideTickLabels ? "end" : "start"; - }; - out.heightFn = function(d, a, h) { - return a < -60 || a > 60 ? -0.5 * h : ax.side === "top" !== insideTickLabels ? -h : 0; - }; - } else if (axLetter === "y") { - endSide = !insideTickLabels && side === "left" || insideTickLabels && side === "right"; - flipIt = endSide ? 1 : -1; - if (insideTickLabels) flipIt *= -1; - x0 = labelStandoff; - y0 = labelShift * flipIt; - ff = 0; - if (!insideTickLabels && Math.abs(tickangle) === 90) { - if (tickangle === -90 && side === "left" || tickangle === 90 && side === "right") { - ff = CAP_SHIFT; - } else { - ff = 0.5; - } - } - if (insideTickLabels) { - var ang = isNumeric$j(tickangle) ? +tickangle : 0; - if (ang !== 0) { - var rA = Lib$1E.deg2rad(ang); - xQ = Math.abs(Math.sin(rA)) * CAP_SHIFT * flipIt; - ff = 0; - } - } - out.xFn = function(d) { - return d.dx + shift - (x0 + d.fontSize * ff) * flipIt + xQ * d.fontSize; - }; - out.yFn = function(d) { - return d.dy + y0 + d.fontSize * MID_SHIFT; - }; - out.anchorFn = function(d, a) { - if (isNumeric$j(a) && Math.abs(a) === 90) { - return "middle"; - } - return endSide ? "end" : "start"; - }; - out.heightFn = function(d, a, h) { - if (ax.side === "right") a *= -1; - return a < -30 ? -h : a < 30 ? -0.5 * h : 0; - }; - } - return out; -}; -function tickDataFn(d) { - return [d.text, d.x, d.axInfo, d.font, d.fontSize, d.fontColor].join("_"); -} -axes.drawTicks = function(gd, ax, opts) { - opts = opts || {}; - var cls = ax._id + "tick"; - var vals = [].concat( - ax.minor && ax.minor.ticks ? ( - // minor vals - opts.vals.filter(function(d) { - return d.minor && !d.noTick; - }) - ) : [] - ).concat( - ax.ticks ? ( - // major vals - opts.vals.filter(function(d) { - return !d.minor && !d.noTick; - }) - ) : [] - ); - var ticks2 = opts.layer.selectAll("path." + cls).data(vals, tickDataFn); - ticks2.exit().remove(); - ticks2.enter().append("path").classed(cls, 1).classed("ticks", 1).classed("crisp", opts.crisp !== false).each(function(d) { - return Color$H.stroke(d3$v.select(this), d.minor ? ax.minor.tickcolor : ax.tickcolor); - }).style("stroke-width", function(d) { - return Drawing$s.crispRound( - gd, - d.minor ? ax.minor.tickwidth : ax.tickwidth, - 1 - ) + "px"; - }).attr("d", opts.path).style("display", null); - hideCounterAxisInsideTickLabels(ax, [TICK_PATH]); - ticks2.attr("transform", opts.transFn); -}; -axes.drawGrid = function(gd, ax, opts) { - opts = opts || {}; - if (ax.tickmode === "sync") { - return; - } - var cls = ax._id + "grid"; - var hasMinor = ax.minor && ax.minor.showgrid; - var minorVals = hasMinor ? opts.vals.filter(function(d) { - return d.minor; - }) : []; - var majorVals = ax.showgrid ? opts.vals.filter(function(d) { - return !d.minor; - }) : []; - var counterAx = opts.counterAxis; - if (counterAx && axes.shouldShowZeroLine(gd, ax, counterAx)) { - var isArrayMode = ax.tickmode === "array"; - for (var i = 0; i < majorVals.length; i++) { - var xi = majorVals[i].x; - if (isArrayMode ? !xi : Math.abs(xi) < ax.dtick / 100) { - majorVals = majorVals.slice(0, i).concat(majorVals.slice(i + 1)); - if (isArrayMode) i--; - else break; - } - } - } - ax._gw = Drawing$s.crispRound(gd, ax.gridwidth, 1); - var wMinor = !hasMinor ? 0 : Drawing$s.crispRound(gd, ax.minor.gridwidth, 1); - var majorLayer = opts.layer; - var minorLayer = opts.minorLayer; - for (var major = 1; major >= 0; major--) { - var layer = major ? majorLayer : minorLayer; - if (!layer) continue; - var grid2 = layer.selectAll("path." + cls).data(major ? majorVals : minorVals, tickDataFn); - grid2.exit().remove(); - grid2.enter().append("path").classed(cls, 1).classed("crisp", opts.crisp !== false); - grid2.attr("transform", opts.transFn).attr("d", opts.path).each(function(d) { - return Color$H.stroke( - d3$v.select(this), - d.minor ? ax.minor.gridcolor : ax.gridcolor || "#ddd" - ); - }).style("stroke-dasharray", function(d) { - return Drawing$s.dashStyle( - d.minor ? ax.minor.griddash : ax.griddash, - d.minor ? ax.minor.gridwidth : ax.gridwidth - ); - }).style("stroke-width", function(d) { - return (d.minor ? wMinor : ax._gw) + "px"; - }).style("display", null); - if (typeof opts.path === "function") grid2.attr("d", opts.path); - } - hideCounterAxisInsideTickLabels(ax, [GRID_PATH, MINORGRID_PATH]); -}; -axes.drawZeroLine = function(gd, ax, opts) { - opts = opts || opts; - var cls = ax._id + "zl"; - var show = axes.shouldShowZeroLine(gd, ax, opts.counterAxis); - var zl = opts.layer.selectAll("path." + cls).data(show ? [{ x: 0, id: ax._id }] : []); - zl.exit().remove(); - zl.enter().append("path").classed(cls, 1).classed("zl", 1).classed("crisp", opts.crisp !== false).each(function() { - opts.layer.selectAll("path").sort(function(da, db) { - return idSort(da.id, db.id); - }); - }); - zl.attr("transform", opts.transFn).attr("d", opts.path).call(Color$H.stroke, ax.zerolinecolor || Color$H.defaultLine).style("stroke-width", Drawing$s.crispRound(gd, ax.zerolinewidth, ax._gw || 1) + "px").style("display", null); - hideCounterAxisInsideTickLabels(ax, [ZERO_PATH]); -}; -axes.drawLabels = function(gd, ax, opts) { - opts = opts || {}; - var fullLayout = gd._fullLayout; - var axId = ax._id; - var cls = opts.cls || axId + "tick"; - var vals = opts.vals.filter(function(d) { - return d.text; - }); - var labelFns = opts.labelFns; - var tickAngle = opts.secondary ? 0 : ax.tickangle; - var prevAngle = (ax._prevTickAngles || {})[cls]; - var tickLabels = opts.layer.selectAll("g." + cls).data(ax.showticklabels ? vals : [], tickDataFn); - var labelsReady = []; - tickLabels.enter().append("g").classed(cls, 1).append("text").attr("text-anchor", "middle").each(function(d) { - var thisLabel = d3$v.select(this); - var newPromise = gd._promises.length; - thisLabel.call(svgTextUtils$d.positionText, labelFns.xFn(d), labelFns.yFn(d)).call(Drawing$s.font, { - family: d.font, - size: d.fontSize, - color: d.fontColor, - weight: d.fontWeight, - style: d.fontStyle, - variant: d.fontVariant, - textcase: d.fontTextcase, - lineposition: d.fontLineposition, - shadow: d.fontShadow - }).text(d.text).call(svgTextUtils$d.convertToTspans, gd); - if (gd._promises[newPromise]) { - labelsReady.push(gd._promises.pop().then(function() { - positionLabels(thisLabel, tickAngle); - })); - } else { - positionLabels(thisLabel, tickAngle); - } - }); - hideCounterAxisInsideTickLabels(ax, [TICK_TEXT]); - tickLabels.exit().remove(); - if (opts.repositionOnUpdate) { - tickLabels.each(function(d) { - d3$v.select(this).select("text").call(svgTextUtils$d.positionText, labelFns.xFn(d), labelFns.yFn(d)); - }); - } - function positionLabels(s, angle) { - s.each(function(d) { - var thisLabel = d3$v.select(this); - var mathjaxGroup = thisLabel.select(".text-math-group"); - var anchor = labelFns.anchorFn(d, angle); - var transform = opts.transFn.call(thisLabel.node(), d) + (isNumeric$j(angle) && +angle !== 0 ? " rotate(" + angle + "," + labelFns.xFn(d) + "," + (labelFns.yFn(d) - d.fontSize / 2) + ")" : ""); - var nLines = svgTextUtils$d.lineCount(thisLabel); - var lineHeight = LINE_SPACING$6 * d.fontSize; - var anchorHeight = labelFns.heightFn(d, isNumeric$j(angle) ? +angle : 0, (nLines - 1) * lineHeight); - if (anchorHeight) { - transform += strTranslate$a(0, anchorHeight); - } - if (mathjaxGroup.empty()) { - var thisText = thisLabel.select("text"); - thisText.attr({ - transform, - "text-anchor": anchor - }); - thisText.style("opacity", 1); - if (ax._adjustTickLabelsOverflow) { - ax._adjustTickLabelsOverflow(); - } - } else { - var mjWidth = Drawing$s.bBox(mathjaxGroup.node()).width; - var mjShift = mjWidth * { end: -0.5, start: 0.5 }[anchor]; - mathjaxGroup.attr("transform", transform + strTranslate$a(mjShift, 0)); - } - }); - } - ax._adjustTickLabelsOverflow = function() { - var ticklabeloverflow = ax.ticklabeloverflow; - if (!ticklabeloverflow || ticklabeloverflow === "allow") return; - var hideOverflow = ticklabeloverflow.indexOf("hide") !== -1; - var isX = ax._id.charAt(0) === "x"; - var p02 = 0; - var p12 = isX ? gd._fullLayout.width : gd._fullLayout.height; - if (ticklabeloverflow.indexOf("domain") !== -1) { - var rl = Lib$1E.simpleMap(ax.range, ax.r2l); - p02 = ax.l2p(rl[0]) + ax._offset; - p12 = ax.l2p(rl[1]) + ax._offset; - } - var min = Math.min(p02, p12); - var max = Math.max(p02, p12); - var side = ax.side; - var visibleLabelMin = Infinity; - var visibleLabelMax = -Infinity; - tickLabels.each(function(d) { - var thisLabel = d3$v.select(this); - var mathjaxGroup = thisLabel.select(".text-math-group"); - if (mathjaxGroup.empty()) { - var bb = Drawing$s.bBox(thisLabel.node()); - var adjust = 0; - if (isX) { - if (bb.right > max) adjust = 1; - else if (bb.left < min) adjust = 1; - } else { - if (bb.bottom > max) adjust = 1; - else if (bb.top + (ax.tickangle ? 0 : d.fontSize / 4) < min) adjust = 1; - } - var t = thisLabel.select("text"); - if (adjust) { - if (hideOverflow) t.style("opacity", 0); - } else { - t.style("opacity", 1); - if (side === "bottom" || side === "right") { - visibleLabelMin = Math.min(visibleLabelMin, isX ? bb.top : bb.left); - } else { - visibleLabelMin = -Infinity; - } - if (side === "top" || side === "left") { - visibleLabelMax = Math.max(visibleLabelMax, isX ? bb.bottom : bb.right); - } else { - visibleLabelMax = Infinity; - } - } - } - }); - for (var subplot in fullLayout._plots) { - var plotinfo = fullLayout._plots[subplot]; - if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; - var anchorAx2 = isX ? plotinfo.yaxis : plotinfo.xaxis; - if (anchorAx2) { - anchorAx2["_visibleLabelMin_" + ax._id] = visibleLabelMin; - anchorAx2["_visibleLabelMax_" + ax._id] = visibleLabelMax; - } - } - }; - ax._hideCounterAxisInsideTickLabels = function(partialOpts) { - var isX = ax._id.charAt(0) === "x"; - var anchoredAxes = []; - for (var subplot in fullLayout._plots) { - var plotinfo = fullLayout._plots[subplot]; - if (ax._id !== plotinfo.xaxis._id && ax._id !== plotinfo.yaxis._id) continue; - anchoredAxes.push(isX ? plotinfo.yaxis : plotinfo.xaxis); - } - anchoredAxes.forEach(function(anchorAx2, idx) { - if (anchorAx2 && insideTicklabelposition(anchorAx2)) { - (partialOpts || [ - ZERO_PATH, - MINORGRID_PATH, - GRID_PATH, - TICK_PATH, - TICK_TEXT - ]).forEach(function(e) { - var isPeriodLabel = e.K === "tick" && e.L === "text" && ax.ticklabelmode === "period"; - var mainPlotinfo = fullLayout._plots[ax._mainSubplot]; - var sel; - if (e.K === ZERO_PATH.K) sel = mainPlotinfo.zerolinelayer.selectAll("." + ax._id + "zl"); - else if (e.K === MINORGRID_PATH.K) sel = mainPlotinfo.minorGridlayer.selectAll("." + ax._id); - else if (e.K === GRID_PATH.K) sel = mainPlotinfo.gridlayer.selectAll("." + ax._id); - else sel = mainPlotinfo[ax._id.charAt(0) + "axislayer"]; - sel.each(function() { - var w = d3$v.select(this); - if (e.L) w = w.selectAll(e.L); - w.each(function(d) { - var q = ax.l2p( - isPeriodLabel ? getPosX(d) : d.x - ) + ax._offset; - var t = d3$v.select(this); - if (q < ax["_visibleLabelMax_" + anchorAx2._id] && q > ax["_visibleLabelMin_" + anchorAx2._id]) { - t.style("display", "none"); - } else if (e.K === "tick" && !idx) { - t.style("display", null); - } - }); - }); - }); - } - }); - }; - positionLabels(tickLabels, prevAngle + 1 ? prevAngle : tickAngle); - function allLabelsReady() { - return labelsReady.length && Promise.all(labelsReady); - } - var autoangle = null; - function fixLabelOverlaps() { - positionLabels(tickLabels, tickAngle); - if (vals.length && ax.autotickangles && (ax.type !== "log" || String(ax.dtick).charAt(0) !== "D")) { - autoangle = ax.autotickangles[0]; - var maxFontSize = 0; - var lbbArray = []; - var i; - var maxLines = 1; - tickLabels.each(function(d) { - maxFontSize = Math.max(maxFontSize, d.fontSize); - var x = ax.l2p(d.x); - var thisLabel = selectTickLabel(this); - var bb = Drawing$s.bBox(thisLabel.node()); - maxLines = Math.max(maxLines, svgTextUtils$d.lineCount(thisLabel)); - lbbArray.push({ - // ignore about y, just deal with x overlaps - top: 0, - bottom: 10, - height: 10, - left: x - bb.width / 2, - // impose a 2px gap - right: x + bb.width / 2 + 2, - width: bb.width + 2 - }); - }); - var preventOverlapWithTick = (ax.tickson === "boundaries" || ax.showdividers) && !opts.secondary; - var vLen = vals.length; - var tickSpacing = Math.abs((vals[vLen - 1].x - vals[0].x) * ax._m) / (vLen - 1); - var adjacent = preventOverlapWithTick ? tickSpacing / 2 : tickSpacing; - var opposite = preventOverlapWithTick ? ax.ticklen : maxFontSize * 1.25 * maxLines; - var hypotenuse = Math.sqrt(Math.pow(adjacent, 2) + Math.pow(opposite, 2)); - var maxCos = adjacent / hypotenuse; - var autoTickAnglesRadians = ax.autotickangles.map( - function(degrees2) { - return degrees2 * Math.PI / 180; - } - ); - var angleRadians = autoTickAnglesRadians.find( - function(angle) { - return Math.abs(Math.cos(angle)) <= maxCos; - } - ); - if (angleRadians === void 0) { - angleRadians = autoTickAnglesRadians.reduce( - function(currentMax, nextAngle) { - return Math.abs(Math.cos(currentMax)) < Math.abs(Math.cos(nextAngle)) ? currentMax : nextAngle; - }, - autoTickAnglesRadians[0] - ); - } - var newAngle = angleRadians * (180 / Math.PI); - if (preventOverlapWithTick) { - var gap = 2; - if (ax.ticks) gap += ax.tickwidth / 2; - for (i = 0; i < lbbArray.length; i++) { - var xbnd = vals[i].xbnd; - var lbb = lbbArray[i]; - if (xbnd[0] !== null && lbb.left - ax.l2p(xbnd[0]) < gap || xbnd[1] !== null && ax.l2p(xbnd[1]) - lbb.right < gap) { - autoangle = newAngle; - break; - } - } - } else { - var ticklabelposition = ax.ticklabelposition || ""; - var has = function(str2) { - return ticklabelposition.indexOf(str2) !== -1; - }; - var isTop = has("top"); - var isLeft = has("left"); - var isRight = has("right"); - var isBottom = has("bottom"); - var isAligned = isBottom || isLeft || isTop || isRight; - var pad2 = !isAligned ? 0 : (ax.tickwidth || 0) + 2 * TEXTPAD$4; - for (i = 0; i < lbbArray.length - 1; i++) { - if (Lib$1E.bBoxIntersect(lbbArray[i], lbbArray[i + 1], pad2)) { - autoangle = newAngle; - break; - } - } - } - if (autoangle) { - positionLabels(tickLabels, autoangle); - } - } - } - if (ax._selections) { - ax._selections[cls] = tickLabels; - } - var seq = [allLabelsReady]; - if (ax.automargin && fullLayout._redrawFromAutoMarginCount && prevAngle === 90) { - autoangle = prevAngle; - seq.push(function() { - positionLabels(tickLabels, prevAngle); - }); - } else { - seq.push(fixLabelOverlaps); - } - if (ax._tickAngles) { - seq.push(function() { - ax._tickAngles[cls] = autoangle === null ? isNumeric$j(tickAngle) ? tickAngle : 0 : autoangle; - }); - } - var computeTickLabelBoundingBoxes = function() { - var labelsMaxW = 0; - var labelsMaxH = 0; - tickLabels.each(function(d, i) { - var thisLabel = selectTickLabel(this); - var mathjaxGroup = thisLabel.select(".text-math-group"); - if (mathjaxGroup.empty()) { - var bb; - if (ax._vals[i]) { - bb = ax._vals[i].bb || Drawing$s.bBox(thisLabel.node()); - ax._vals[i].bb = bb; - } - labelsMaxW = Math.max(labelsMaxW, bb.width); - labelsMaxH = Math.max(labelsMaxH, bb.height); - } - }); - return { - labelsMaxW, - labelsMaxH - }; - }; - var anchorAx = ax._anchorAxis; - if (anchorAx && (anchorAx.autorange || anchorAx.insiderange) && insideTicklabelposition(ax) && !isLinked(fullLayout, ax._id)) { - if (!fullLayout._insideTickLabelsUpdaterange) { - fullLayout._insideTickLabelsUpdaterange = {}; - } - if (anchorAx.autorange) { - fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".autorange"] = anchorAx.autorange; - seq.push(computeTickLabelBoundingBoxes); - } - if (anchorAx.insiderange) { - var BBs = computeTickLabelBoundingBoxes(); - var move = ax._id.charAt(0) === "y" ? BBs.labelsMaxW : BBs.labelsMaxH; - move += 2 * TEXTPAD$4; - if (ax.ticklabelposition === "inside") { - move += ax.ticklen || 0; - } - var sgn = ax.side === "right" || ax.side === "top" ? 1 : -1; - var index2 = sgn === 1 ? 1 : 0; - var otherIndex = sgn === 1 ? 0 : 1; - var newRange = []; - newRange[otherIndex] = anchorAx.range[otherIndex]; - var anchorAxRange = anchorAx.range; - var p0 = anchorAx.r2p(anchorAxRange[index2]); - var p1 = anchorAx.r2p(anchorAxRange[otherIndex]); - var _tempNewRange = fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"]; - if (_tempNewRange) { - var q0 = anchorAx.r2p(_tempNewRange[index2]); - var q1 = anchorAx.r2p(_tempNewRange[otherIndex]); - var dir = sgn * (ax._id.charAt(0) === "y" ? 1 : -1); - if (dir * p0 < dir * q0) { - p0 = q0; - newRange[index2] = anchorAxRange[index2] = _tempNewRange[index2]; - } - if (dir * p1 > dir * q1) { - p1 = q1; - newRange[otherIndex] = anchorAxRange[otherIndex] = _tempNewRange[otherIndex]; - } - } - var dist2 = Math.abs(p1 - p0); - if (dist2 - move > 0) { - dist2 -= move; - move *= 1 + move / dist2; - } else { - move = 0; - } - if (ax._id.charAt(0) !== "y") move = -move; - newRange[index2] = anchorAx.p2r( - anchorAx.r2p(anchorAxRange[index2]) + sgn * move - ); - if (anchorAx.autorange === "min" || anchorAx.autorange === "max reversed") { - newRange[0] = null; - anchorAx._rangeInitial0 = void 0; - anchorAx._rangeInitial1 = void 0; - } else if (anchorAx.autorange === "max" || anchorAx.autorange === "min reversed") { - newRange[1] = null; - anchorAx._rangeInitial0 = void 0; - anchorAx._rangeInitial1 = void 0; - } - fullLayout._insideTickLabelsUpdaterange[anchorAx._name + ".range"] = newRange; - } - } - var done = Lib$1E.syncOrAsync(seq); - if (done && done.then) gd._promises.push(done); - return done; -}; -function drawDividers(gd, ax, opts) { - var cls = ax._id + "divider"; - var vals = opts.vals; - var dividers = opts.layer.selectAll("path." + cls).data(vals, tickDataFn); - dividers.exit().remove(); - dividers.enter().insert("path", ":first-child").classed(cls, 1).classed("crisp", 1).call(Color$H.stroke, ax.dividercolor).style("stroke-width", Drawing$s.crispRound(gd, ax.dividerwidth, 1) + "px"); - dividers.attr("transform", opts.transFn).attr("d", opts.path); -} -axes.getPxPosition = function(gd, ax) { - var gs = gd._fullLayout._size; - var axLetter = ax._id.charAt(0); - var side = ax.side; - var anchorAxis; - if (ax.anchor !== "free") { - anchorAxis = ax._anchorAxis; - } else if (axLetter === "x") { - anchorAxis = { - _offset: gs.t + (1 - (ax.position || 0)) * gs.h, - _length: 0 - }; - } else if (axLetter === "y") { - anchorAxis = { - _offset: gs.l + (ax.position || 0) * gs.w + ax._shift, - _length: 0 - }; - } - if (side === "top" || side === "left") { - return anchorAxis._offset; - } else if (side === "bottom" || side === "right") { - return anchorAxis._offset + anchorAxis._length; - } -}; -function approxTitleDepth(ax) { - var fontSize = ax.title.font.size; - var extraLines = (ax.title.text.match(svgTextUtils$d.BR_TAG_ALL) || []).length; - if (ax.title.hasOwnProperty("standoff")) { - return fontSize * (CAP_SHIFT + extraLines * LINE_SPACING$6); - } else { - return extraLines ? fontSize * (extraLines + 1) * LINE_SPACING$6 : fontSize; - } -} -function drawTitle(gd, ax) { - var fullLayout = gd._fullLayout; - var axId = ax._id; - var axLetter = axId.charAt(0); - var fontSize = ax.title.font.size; - var titleStandoff; - var extraLines = (ax.title.text.match(svgTextUtils$d.BR_TAG_ALL) || []).length; - if (ax.title.hasOwnProperty("standoff")) { - if (ax.side === "bottom" || ax.side === "right") { - titleStandoff = ax._depth + ax.title.standoff + fontSize * CAP_SHIFT; - } else if (ax.side === "top" || ax.side === "left") { - titleStandoff = ax._depth + ax.title.standoff + fontSize * (MID_SHIFT + extraLines * LINE_SPACING$6); - } - } else { - var isInside = insideTicklabelposition(ax); - if (ax.type === "multicategory") { - titleStandoff = ax._depth; - } else { - var offsetBase = 1.5 * fontSize; - if (isInside) { - offsetBase = 0.5 * fontSize; - if (ax.ticks === "outside") { - offsetBase += ax.ticklen; - } - } - titleStandoff = 10 + offsetBase + (ax.linewidth ? ax.linewidth - 1 : 0); - } - if (!isInside) { - if (axLetter === "x") { - titleStandoff += ax.side === "top" ? fontSize * (ax.showticklabels ? 1 : 0) : fontSize * (ax.showticklabels ? 1.5 : 0.5); - } else { - titleStandoff += ax.side === "right" ? fontSize * (ax.showticklabels ? 1 : 0.5) : fontSize * (ax.showticklabels ? 0.5 : 0); - } - } - } - var pos = axes.getPxPosition(gd, ax); - var transform, x, y; - if (axLetter === "x") { - x = ax._offset + ax._length / 2; - y = ax.side === "top" ? pos - titleStandoff : pos + titleStandoff; - } else { - y = ax._offset + ax._length / 2; - x = ax.side === "right" ? pos + titleStandoff : pos - titleStandoff; - transform = { rotate: "-90", offset: 0 }; - } - var avoid; - if (ax.type !== "multicategory") { - var tickLabels = ax._selections[ax._id + "tick"]; - avoid = { - selection: tickLabels, - side: ax.side - }; - if (tickLabels && tickLabels.node() && tickLabels.node().parentNode) { - var translation = Drawing$s.getTranslate(tickLabels.node().parentNode); - avoid.offsetLeft = translation.x; - avoid.offsetTop = translation.y; - } - if (ax.title.hasOwnProperty("standoff")) { - avoid.pad = 0; - } - } - ax._titleStandoff = titleStandoff; - return Titles$1.draw(gd, axId + "title", { - propContainer: ax, - propName: ax._name + ".title.text", - placeholder: fullLayout._dfltTitle[axLetter], - avoid, - transform, - attributes: { x, y, "text-anchor": "middle" } - }); -} -axes.shouldShowZeroLine = function(gd, ax, counterAxis) { - var rng = Lib$1E.simpleMap(ax.range, ax.r2l); - return rng[0] * rng[1] <= 0 && ax.zeroline && (ax.type === "linear" || ax.type === "-") && !(ax.rangebreaks && ax.maskBreaks(0) === BADNUM$7) && (clipEnds(ax, 0) || !anyCounterAxLineAtZero(gd, ax, counterAxis, rng) || hasBarsOrFill(gd, ax)); -}; -axes.clipEnds = function(ax, vals) { - return vals.filter(function(d) { - return clipEnds(ax, d.x); - }); -}; -function clipEnds(ax, l) { - var p = ax.l2p(l); - return p > 1 && p < ax._length - 1; -} -function anyCounterAxLineAtZero(gd, ax, counterAxis, rng) { - var mainCounterAxis = counterAxis._mainAxis; - if (!mainCounterAxis) return; - var fullLayout = gd._fullLayout; - var axLetter = ax._id.charAt(0); - var counterLetter = axes.counterLetter(ax._id); - var zeroPosition = ax._offset + (Math.abs(rng[0]) < Math.abs(rng[1]) === (axLetter === "x") ? 0 : ax._length); - function lineNearZero(ax2) { - if (!ax2.showline || !ax2.linewidth) return false; - var tolerance = Math.max((ax2.linewidth + ax.zerolinewidth) / 2, 1); - function closeEnough(pos2) { - return typeof pos2 === "number" && Math.abs(pos2 - zeroPosition) < tolerance; - } - if (closeEnough(ax2._mainLinePosition) || closeEnough(ax2._mainMirrorPosition)) { - return true; - } - var linePositions = ax2._linepositions || {}; - for (var k in linePositions) { - if (closeEnough(linePositions[k][0]) || closeEnough(linePositions[k][1])) { - return true; - } - } - } - var plotinfo = fullLayout._plots[counterAxis._mainSubplot]; - if (!(plotinfo.mainplotinfo || plotinfo).overlays.length) { - return lineNearZero(counterAxis); - } - var counterLetterAxes = axes.list(gd, counterLetter); - for (var i = 0; i < counterLetterAxes.length; i++) { - var counterAxis2 = counterLetterAxes[i]; - if (counterAxis2._mainAxis === mainCounterAxis && lineNearZero(counterAxis2)) { - return true; - } - } -} -function hasBarsOrFill(gd, ax) { - var fullData = gd._fullData; - var subplot = ax._mainSubplot; - var axLetter = ax._id.charAt(0); - for (var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if (trace.visible === true && trace.xaxis + trace.yaxis === subplot) { - if (Registry$I.traceIs(trace, "bar-like") && trace.orientation === { x: "h", y: "v" }[axLetter]) return true; - if (trace.fill && trace.fill.charAt(trace.fill.length - 1) === axLetter) return true; - } - } - return false; -} -function selectTickLabel(gTick) { - var s = d3$v.select(gTick); - var mj = s.select(".text-math-group"); - return mj.empty() ? s.select("text") : mj; -} -axes.allowAutoMargin = function(gd) { - var axList = axes.list(gd, "", true); - for (var i = 0; i < axList.length; i++) { - var ax = axList[i]; - if (ax.automargin) { - Plots$b.allowAutoMargin(gd, axAutoMarginID(ax)); - if (ax.mirror) { - Plots$b.allowAutoMargin(gd, axMirrorAutoMarginID(ax)); - } - } - if (Registry$I.getComponentMethod("rangeslider", "isVisible")(ax)) { - Plots$b.allowAutoMargin(gd, rangeSliderAutoMarginID(ax)); - } - } -}; -function axAutoMarginID(ax) { - return ax._id + ".automargin"; -} -function axMirrorAutoMarginID(ax) { - return axAutoMarginID(ax) + ".mirror"; -} -function rangeSliderAutoMarginID(ax) { - return ax._id + ".rangeslider"; -} -axes.swap = function(gd, traces) { - var axGroups = makeAxisGroups(gd, traces); - for (var i = 0; i < axGroups.length; i++) { - swapAxisGroup(gd, axGroups[i].x, axGroups[i].y); - } -}; -function makeAxisGroups(gd, traces) { - var groups = []; - var i, j; - for (i = 0; i < traces.length; i++) { - var groupsi = []; - var xi = gd._fullData[traces[i]].xaxis; - var yi = gd._fullData[traces[i]].yaxis; - if (!xi || !yi) continue; - for (j = 0; j < groups.length; j++) { - if (groups[j].x.indexOf(xi) !== -1 || groups[j].y.indexOf(yi) !== -1) { - groupsi.push(j); - } - } - if (!groupsi.length) { - groups.push({ x: [xi], y: [yi] }); - continue; - } - var group0 = groups[groupsi[0]]; - var groupj; - if (groupsi.length > 1) { - for (j = 1; j < groupsi.length; j++) { - groupj = groups[groupsi[j]]; - mergeAxisGroups(group0.x, groupj.x); - mergeAxisGroups(group0.y, groupj.y); - } - } - mergeAxisGroups(group0.x, [xi]); - mergeAxisGroups(group0.y, [yi]); - } - return groups; -} -function mergeAxisGroups(intoSet, fromSet) { - for (var i = 0; i < fromSet.length; i++) { - if (intoSet.indexOf(fromSet[i]) === -1) intoSet.push(fromSet[i]); - } -} -function swapAxisGroup(gd, xIds, yIds) { - var xFullAxes = []; - var yFullAxes = []; - var layout = gd.layout; - var i, j; - for (i = 0; i < xIds.length; i++) xFullAxes.push(axes.getFromId(gd, xIds[i])); - for (i = 0; i < yIds.length; i++) yFullAxes.push(axes.getFromId(gd, yIds[i])); - var allAxKeys = Object.keys(axAttrs); - var noSwapAttrs = [ - "anchor", - "domain", - "overlaying", - "position", - "side", - "tickangle", - "editType" - ]; - var numericTypes = ["linear", "log"]; - for (i = 0; i < allAxKeys.length; i++) { - var keyi = allAxKeys[i]; - var xVal = xFullAxes[0][keyi]; - var yVal = yFullAxes[0][keyi]; - var allEqual = true; - var coerceLinearX = false; - var coerceLinearY = false; - if (keyi.charAt(0) === "_" || typeof xVal === "function" || noSwapAttrs.indexOf(keyi) !== -1) { - continue; - } - for (j = 1; j < xFullAxes.length && allEqual; j++) { - var xVali = xFullAxes[j][keyi]; - if (keyi === "type" && numericTypes.indexOf(xVal) !== -1 && numericTypes.indexOf(xVali) !== -1 && xVal !== xVali) { - coerceLinearX = true; - } else if (xVali !== xVal) allEqual = false; - } - for (j = 1; j < yFullAxes.length && allEqual; j++) { - var yVali = yFullAxes[j][keyi]; - if (keyi === "type" && numericTypes.indexOf(yVal) !== -1 && numericTypes.indexOf(yVali) !== -1 && yVal !== yVali) { - coerceLinearY = true; - } else if (yFullAxes[j][keyi] !== yVal) allEqual = false; - } - if (allEqual) { - if (coerceLinearX) layout[xFullAxes[0]._name].type = "linear"; - if (coerceLinearY) layout[yFullAxes[0]._name].type = "linear"; - swapAxisAttrs(layout, keyi, xFullAxes, yFullAxes, gd._fullLayout._dfltTitle); - } - } - for (i = 0; i < gd._fullLayout.annotations.length; i++) { - var ann = gd._fullLayout.annotations[i]; - if (xIds.indexOf(ann.xref) !== -1 && yIds.indexOf(ann.yref) !== -1) { - Lib$1E.swapAttrs(layout.annotations[i], ["?"]); - } - } -} -function swapAxisAttrs(layout, key, xFullAxes, yFullAxes, dfltTitle) { - var np = Lib$1E.nestedProperty; - var xVal = np(layout[xFullAxes[0]._name], key).get(); - var yVal = np(layout[yFullAxes[0]._name], key).get(); - var i; - if (key === "title") { - if (xVal && xVal.text === dfltTitle.x) { - xVal.text = dfltTitle.y; - } - if (yVal && yVal.text === dfltTitle.y) { - yVal.text = dfltTitle.x; - } - } - for (i = 0; i < xFullAxes.length; i++) { - np(layout, xFullAxes[i]._name + "." + key).set(yVal); - } - for (i = 0; i < yFullAxes.length; i++) { - np(layout, yFullAxes[i]._name + "." + key).set(xVal); - } -} -function isAngular(ax) { - return ax._id === "angularaxis"; -} -function moveOutsideBreak(v, ax) { - var len = ax._rangebreaks.length; - for (var k = 0; k < len; k++) { - var brk = ax._rangebreaks[k]; - if (v >= brk.min && v < brk.max) { - return brk.max; - } - } - return v; -} -function insideTicklabelposition(ax) { - return (ax.ticklabelposition || "").indexOf("inside") !== -1; -} -function hideCounterAxisInsideTickLabels(ax, opts) { - if (insideTicklabelposition(ax._anchorAxis || {})) { - if (ax._hideCounterAxisInsideTickLabels) { - ax._hideCounterAxisInsideTickLabels(opts); - } - } -} -function incrementShift(ax, shiftVal, axShifts, normalize3) { - var overlay = ax.anchor !== "free" && (ax.overlaying === void 0 || ax.overlaying === false) ? ax._id : ax.overlaying; - var shiftValAdj; - if (normalize3) { - shiftValAdj = ax.side === "right" ? shiftVal : -shiftVal; - } else { - shiftValAdj = shiftVal; - } - if (!(overlay in axShifts)) { - axShifts[overlay] = {}; - } - if (!(ax.side in axShifts[overlay])) { - axShifts[overlay][ax.side] = 0; - } - axShifts[overlay][ax.side] += shiftValAdj; -} -function setShiftVal(ax, axShifts) { - return ax.autoshift ? axShifts[ax.overlaying][ax.side] : ax.shift || 0; -} -function periodCompatibleWithTickformat(period, tickformat) { - return /%f/.test(tickformat) ? period >= ONEMICROSEC : /%L/.test(tickformat) ? period >= ONEMILLI : /%[SX]/.test(tickformat) ? period >= ONESEC : /%M/.test(tickformat) ? period >= ONEMIN : /%[HI]/.test(tickformat) ? period >= ONEHOUR : /%p/.test(tickformat) ? period >= HALFDAY : /%[Aadejuwx]/.test(tickformat) ? period >= ONEDAY : /%[UVW]/.test(tickformat) ? period >= ONEWEEK$1 : /%[Bbm]/.test(tickformat) ? period >= ONEMINMONTH : /%[q]/.test(tickformat) ? period >= ONEMINQUARTER : /%[Yy]/.test(tickformat) ? period >= ONEMINYEAR : true; -} -var axesExports = axes$1.exports; -var autorange_options_defaults = function handleAutorangeOptionsDefaults(coerce2, autorange2, range) { - var minRange, maxRange; - if (range) { - var isReversed2 = autorange2 === "reversed" || autorange2 === "min reversed" || autorange2 === "max reversed"; - minRange = range[isReversed2 ? 1 : 0]; - maxRange = range[isReversed2 ? 0 : 1]; - } - var minallowed = coerce2("autorangeoptions.minallowed", maxRange === null ? minRange : void 0); - var maxallowed = coerce2("autorangeoptions.maxallowed", minRange === null ? maxRange : void 0); - if (minallowed === void 0) coerce2("autorangeoptions.clipmin"); - if (maxallowed === void 0) coerce2("autorangeoptions.clipmax"); - coerce2("autorangeoptions.include"); -}; -var handleAutorangeOptionsDefaults2 = autorange_options_defaults; -var range_defaults = function handleRangeDefaults(containerIn, containerOut, coerce2, options) { - var axTemplate = containerOut._template || {}; - var axType = containerOut.type || axTemplate.type || "-"; - coerce2("minallowed"); - coerce2("maxallowed"); - var range = coerce2("range"); - if (!range) { - var insiderange; - if (!options.noInsiderange && axType !== "log") { - insiderange = coerce2("insiderange"); - if (insiderange && (insiderange[0] === null || insiderange[1] === null)) { - containerOut.insiderange = false; - insiderange = void 0; - } - if (insiderange) range = coerce2("range", insiderange); - } - } - var autorangeDflt = containerOut.getAutorangeDflt(range, options); - var autorange2 = coerce2("autorange", autorangeDflt); - var shouldAutorange; - if (range && (range[0] === null && range[1] === null || (range[0] === null || range[1] === null) && (autorange2 === "reversed" || autorange2 === true) || range[0] !== null && (autorange2 === "min" || autorange2 === "max reversed") || range[1] !== null && (autorange2 === "max" || autorange2 === "min reversed"))) { - range = void 0; - delete containerOut.range; - containerOut.autorange = true; - shouldAutorange = true; - } - if (!shouldAutorange) { - autorangeDflt = containerOut.getAutorangeDflt(range, options); - autorange2 = coerce2("autorange", autorangeDflt); - } - if (autorange2) { - handleAutorangeOptionsDefaults2(coerce2, autorange2, range); - if (axType === "linear" || axType === "-") coerce2("rangemode"); - } - containerOut.cleanRange(); -}; -var graph_interact = {}; -var dragelement = { exports: {} }; -var rootPosition = { left: 0, top: 0 }; -var mouseEventOffset_1 = mouseEventOffset; -function mouseEventOffset(ev, target, out) { - target = target || ev.currentTarget || ev.srcElement; - if (!Array.isArray(out)) { - out = [0, 0]; - } - var cx = ev.clientX || 0; - var cy = ev.clientY || 0; - var rect2 = getBoundingClientOffset(target); - out[0] = cx - rect2.left; - out[1] = cy - rect2.top; - return out; -} -function getBoundingClientOffset(element) { - if (element === window || element === document || element === document.body) { - return rootPosition; - } else { - return element.getBoundingClientRect(); - } -} -function detect() { - var supported = false; - try { - var opts = Object.defineProperty({}, "passive", { - get: function() { - supported = true; - } - }); - window.addEventListener("test", null, opts); - window.removeEventListener("test", null, opts); - } catch (e) { - supported = false; - } - return supported; -} -var hasPassiveEvents = detect(); -var align = function align2(v, dv2, v0, v1, anchor) { - var vmin = (v - v0) / (v1 - v0); - var vmax = vmin + dv2 / (v1 - v0); - var vc = (vmin + vmax) / 2; - if (anchor === "left" || anchor === "bottom") return vmin; - if (anchor === "center" || anchor === "middle") return vc; - if (anchor === "right" || anchor === "top") return vmax; - if (vmin < 2 / 3 - vc) return vmin; - if (vmax > 4 / 3 - vc) return vmax; - return vc; -}; -var Lib$1D = libExports; -var cursorset = [ - ["sw-resize", "s-resize", "se-resize"], - ["w-resize", "move", "e-resize"], - ["nw-resize", "n-resize", "ne-resize"] -]; -var cursor = function getCursor(x, y, xanchor, yanchor) { - if (xanchor === "left") x = 0; - else if (xanchor === "center") x = 1; - else if (xanchor === "right") x = 2; - else x = Lib$1D.constrain(Math.floor(x * 3), 0, 2); - if (yanchor === "bottom") y = 0; - else if (yanchor === "middle") y = 1; - else if (yanchor === "top") y = 2; - else y = Lib$1D.constrain(Math.floor(y * 3), 0, 2); - return cursorset[y][x]; -}; -var unhover$2 = { exports: {} }; -var Events$3 = events; -var throttle$1 = throttle$2; -var getGraphDiv$1 = dom.getGraphDiv; -var hoverConstants = constants$W; -var unhover$1 = unhover$2.exports = {}; -unhover$1.wrapped = function(gd, evt, subplot) { - gd = getGraphDiv$1(gd); - if (gd._fullLayout) { - throttle$1.clear(gd._fullLayout._uid + hoverConstants.HOVERID); - } - unhover$1.raw(gd, evt, subplot); -}; -unhover$1.raw = function raw(gd, evt) { - var fullLayout = gd._fullLayout; - var oldhoverdata = gd._hoverdata; - if (!evt) evt = {}; - if (evt.target && !gd._dragged && Events$3.triggerHandler(gd, "plotly_beforehover", evt) === false) { - return; - } - fullLayout._hoverlayer.selectAll("g").remove(); - fullLayout._hoverlayer.selectAll("line").remove(); - fullLayout._hoverlayer.selectAll("circle").remove(); - gd._hoverdata = void 0; - if (evt.target && oldhoverdata) { - gd.emit("plotly_unhover", { - event: evt, - points: oldhoverdata - }); - } -}; -var unhoverExports = unhover$2.exports; -var mouseOffset = mouseEventOffset_1; -var hasHover = hasHover_1; -var supportsPassive = hasPassiveEvents; -var removeElement = libExports.removeElement; -var constants$P = constants$U; -var dragElement$7 = dragelement.exports = {}; -dragElement$7.align = align; -dragElement$7.getCursor = cursor; -var unhover = unhoverExports; -dragElement$7.unhover = unhover.wrapped; -dragElement$7.unhoverRaw = unhover.raw; -dragElement$7.init = function init(options) { - var gd = options.gd; - var numClicks = 1; - var doubleClickDelay = gd._context.doubleClickDelay; - var element = options.element; - var startX, startY, newMouseDownTime, cursor2, dragCover, initialEvent, initialTarget, rightClick; - if (!gd._mouseDownTime) gd._mouseDownTime = 0; - element.style.pointerEvents = "all"; - element.onmousedown = onStart; - if (!supportsPassive) { - element.ontouchstart = onStart; - } else { - if (element._ontouchstart) { - element.removeEventListener("touchstart", element._ontouchstart); - } - element._ontouchstart = onStart; - element.addEventListener("touchstart", onStart, { passive: false }); - } - function _clampFn(dx, dy, minDrag) { - if (Math.abs(dx) < minDrag) dx = 0; - if (Math.abs(dy) < minDrag) dy = 0; - return [dx, dy]; - } - var clampFn = options.clampFn || _clampFn; - function onStart(e) { - gd._dragged = false; - gd._dragging = true; - var offset = pointerOffset(e); - startX = offset[0]; - startY = offset[1]; - initialTarget = e.target; - initialEvent = e; - rightClick = e.buttons === 2 || e.ctrlKey; - if (typeof e.clientX === "undefined" && typeof e.clientY === "undefined") { - e.clientX = startX; - e.clientY = startY; - } - newMouseDownTime = (/* @__PURE__ */ new Date()).getTime(); - if (newMouseDownTime - gd._mouseDownTime < doubleClickDelay) { - numClicks += 1; - } else { - numClicks = 1; - gd._mouseDownTime = newMouseDownTime; - } - if (options.prepFn) options.prepFn(e, startX, startY); - if (hasHover && !rightClick) { - dragCover = coverSlip(); - dragCover.style.cursor = window.getComputedStyle(element).cursor; - } else if (!hasHover) { - dragCover = document; - cursor2 = window.getComputedStyle(document.documentElement).cursor; - document.documentElement.style.cursor = window.getComputedStyle(element).cursor; - } - document.addEventListener("mouseup", onDone); - document.addEventListener("touchend", onDone); - if (options.dragmode !== false) { - e.preventDefault(); - document.addEventListener("mousemove", onMove); - document.addEventListener("touchmove", onMove, { passive: false }); - } - return; - } - function onMove(e) { - e.preventDefault(); - var offset = pointerOffset(e); - var minDrag = options.minDrag || constants$P.MINDRAG; - var dxdy = clampFn(offset[0] - startX, offset[1] - startY, minDrag); - var dx = dxdy[0]; - var dy = dxdy[1]; - if (dx || dy) { - gd._dragged = true; - dragElement$7.unhover(gd, e); - } - if (gd._dragged && options.moveFn && !rightClick) { - gd._dragdata = { - element, - dx, - dy - }; - options.moveFn(dx, dy); - } - return; - } - function onDone(e) { - delete gd._dragdata; - if (options.dragmode !== false) { - e.preventDefault(); - document.removeEventListener("mousemove", onMove); - document.removeEventListener("touchmove", onMove); - } - document.removeEventListener("mouseup", onDone); - document.removeEventListener("touchend", onDone); - if (hasHover) { - removeElement(dragCover); - } else if (cursor2) { - dragCover.documentElement.style.cursor = cursor2; - cursor2 = null; - } - if (!gd._dragging) { - gd._dragged = false; - return; - } - gd._dragging = false; - if ((/* @__PURE__ */ new Date()).getTime() - gd._mouseDownTime > doubleClickDelay) { - numClicks = Math.max(numClicks - 1, 1); - } - if (gd._dragged) { - if (options.doneFn) options.doneFn(); - } else { - if (options.clickFn) options.clickFn(numClicks, initialEvent); - if (!rightClick) { - var e2; - try { - e2 = new MouseEvent("click", e); - } catch (err) { - var offset = pointerOffset(e); - e2 = document.createEvent("MouseEvents"); - e2.initMouseEvent( - "click", - e.bubbles, - e.cancelable, - e.view, - e.detail, - e.screenX, - e.screenY, - offset[0], - offset[1], - e.ctrlKey, - e.altKey, - e.shiftKey, - e.metaKey, - e.button, - e.relatedTarget - ); - } - initialTarget.dispatchEvent(e2); - } - } - gd._dragging = false; - gd._dragged = false; - return; - } -}; -function coverSlip() { - var cover = document.createElement("div"); - cover.className = "dragcover"; - var cStyle = cover.style; - cStyle.position = "fixed"; - cStyle.left = 0; - cStyle.right = 0; - cStyle.top = 0; - cStyle.bottom = 0; - cStyle.zIndex = 999999999; - cStyle.background = "none"; - document.body.appendChild(cover); - return cover; -} -dragElement$7.coverSlip = coverSlip; -function pointerOffset(e) { - return mouseOffset( - e.changedTouches ? e.changedTouches[0] : e, - document.body - ); -} -var dragelementExports = dragelement.exports; -var hover$7 = {}; -var setcursor = function setCursor(el3, csr) { - (el3.attr("class") || "").split(" ").forEach(function(cls) { - if (cls.indexOf("cursor-") === 0) el3.classed(cls, false); - }); - if (csr) el3.classed("cursor-" + csr, true); -}; -var setCursor$3 = setcursor; -var STASHATTR = "data-savedcursor"; -var NO_CURSOR = "!!"; -var override_cursor = function overrideCursor(el3, csr) { - var savedCursor = el3.attr(STASHATTR); - if (csr) { - if (!savedCursor) { - var classes = (el3.attr("class") || "").split(" "); - for (var i = 0; i < classes.length; i++) { - var cls = classes[i]; - if (cls.indexOf("cursor-") === 0) { - el3.attr(STASHATTR, cls.substr(7)).classed(cls, false); - } - } - if (!el3.attr(STASHATTR)) { - el3.attr(STASHATTR, NO_CURSOR); - } - } - setCursor$3(el3, csr); - } else if (savedCursor) { - el3.attr(STASHATTR, null); - if (savedCursor === NO_CURSOR) setCursor$3(el3); - else setCursor$3(el3, savedCursor); - } -}; -var fontAttrs$a = font_attributes; -var colorAttrs$4 = attributes$N; -var attributes$G = { - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, - visible: { - valType: "boolean", - dflt: true, - editType: "legend", - description: [ - "Determines whether or not this legend is visible." - ].join(" ") - }, - bgcolor: { - valType: "color", - editType: "legend", - description: [ - "Sets the legend background color.", - "Defaults to `layout.paper_bgcolor`." - ].join(" ") - }, - bordercolor: { - valType: "color", - dflt: colorAttrs$4.defaultLine, - editType: "legend", - description: "Sets the color of the border enclosing the legend." - }, - borderwidth: { - valType: "number", - min: 0, - dflt: 0, - editType: "legend", - description: "Sets the width (in px) of the border enclosing the legend." - }, - font: fontAttrs$a({ - editType: "legend", - description: "Sets the font used to text the legend items." - }), - grouptitlefont: fontAttrs$a({ - editType: "legend", - description: [ - "Sets the font for group titles in legend.", - "Defaults to `legend.font` with its size increased about 10%." - ].join(" ") - }), - orientation: { - valType: "enumerated", - values: ["v", "h"], - dflt: "v", - editType: "legend", - description: "Sets the orientation of the legend." - }, - traceorder: { - valType: "flaglist", - flags: ["reversed", "grouped"], - extras: ["normal"], - editType: "legend", - description: [ - "Determines the order at which the legend items are displayed.", - "If *normal*, the items are displayed top-to-bottom in the same", - "order as the input data.", - "If *reversed*, the items are displayed in the opposite order", - "as *normal*.", - "If *grouped*, the items are displayed in groups", - "(when a trace `legendgroup` is provided).", - "if *grouped+reversed*, the items are displayed in the opposite order", - "as *grouped*." - ].join(" ") - }, - tracegroupgap: { - valType: "number", - min: 0, - dflt: 10, - editType: "legend", - description: [ - "Sets the amount of vertical space (in px) between legend groups." - ].join(" ") - }, - entrywidth: { - valType: "number", - min: 0, - editType: "legend", - description: [ - "Sets the width (in px or fraction) of the legend.", - "Use 0 to size the entry based on the text width,", - "when `entrywidthmode` is set to *pixels*." - ].join(" ") - }, - entrywidthmode: { - valType: "enumerated", - values: ["fraction", "pixels"], - dflt: "pixels", - editType: "legend", - description: "Determines what entrywidth means." - }, - indentation: { - valType: "number", - min: -15, - dflt: 0, - editType: "legend", - description: "Sets the indentation (in px) of the legend entries." - }, - itemsizing: { - valType: "enumerated", - values: ["trace", "constant"], - dflt: "trace", - editType: "legend", - description: [ - "Determines if the legend items symbols scale with their corresponding *trace* attributes", - "or remain *constant* independent of the symbol size on the graph." - ].join(" ") - }, - itemwidth: { - valType: "number", - min: 30, - dflt: 30, - editType: "legend", - description: "Sets the width (in px) of the legend item symbols (the part other than the title.text)." - }, - itemclick: { - valType: "enumerated", - values: ["toggle", "toggleothers", false], - dflt: "toggle", - editType: "legend", - description: [ - "Determines the behavior on legend item click.", - "*toggle* toggles the visibility of the item clicked on the graph.", - "*toggleothers* makes the clicked item the sole visible item on the graph.", - "*false* disables legend item click interactions." - ].join(" ") - }, - itemdoubleclick: { - valType: "enumerated", - values: ["toggle", "toggleothers", false], - dflt: "toggleothers", - editType: "legend", - description: [ - "Determines the behavior on legend item double-click.", - "*toggle* toggles the visibility of the item clicked on the graph.", - "*toggleothers* makes the clicked item the sole visible item on the graph.", - "*false* disables legend item double-click interactions." - ].join(" ") - }, - groupclick: { - valType: "enumerated", - values: ["toggleitem", "togglegroup"], - dflt: "togglegroup", - editType: "legend", - description: [ - "Determines the behavior on legend group item click.", - "*toggleitem* toggles the visibility of the individual item clicked on the graph.", - "*togglegroup* toggles the visibility of all items in the same legendgroup as the item clicked on the graph." - ].join(" ") - }, - x: { - valType: "number", - editType: "legend", - description: [ - "Sets the x position with respect to `xref` (in normalized coordinates) of the legend.", - "When `xref` is *paper*, defaults to *1.02* for vertical legends and", - "defaults to *0* for horizontal legends.", - "When `xref` is *container*, defaults to *1* for vertical legends and", - "defaults to *0* for horizontal legends.", - "Must be between *0* and *1* if `xref` is *container*.", - "and between *-2* and *3* if `xref` is *paper*." - ].join(" ") - }, - xref: { - valType: "enumerated", - dflt: "paper", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `x` refers to.", - "*container* spans the entire `width` of the plot.", - "*paper* refers to the width of the plotting area only." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "left", - editType: "legend", - description: [ - "Sets the legend's horizontal position anchor.", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the legend.", - "Value *auto* anchors legends to the right for `x` values greater than or equal to 2/3,", - "anchors legends to the left for `x` values less than or equal to 1/3 and", - "anchors legends with respect to their center otherwise." - ].join(" ") - }, - y: { - valType: "number", - editType: "legend", - description: [ - "Sets the y position with respect to `yref` (in normalized coordinates) of the legend.", - "When `yref` is *paper*, defaults to *1* for vertical legends,", - "defaults to *-0.1* for horizontal legends on graphs w/o range sliders and", - "defaults to *1.1* for horizontal legends on graph with one or multiple range sliders.", - "When `yref` is *container*, defaults to *1*.", - "Must be between *0* and *1* if `yref` is *container*", - "and between *-2* and *3* if `yref` is *paper*." - ].join(" ") - }, - yref: { - valType: "enumerated", - dflt: "paper", - values: ["container", "paper"], - editType: "layoutstyle", - description: [ - "Sets the container `y` refers to.", - "*container* spans the entire `height` of the plot.", - "*paper* refers to the height of the plotting area only." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - values: ["auto", "top", "middle", "bottom"], - editType: "legend", - description: [ - "Sets the legend's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the legend.", - "Value *auto* anchors legends at their bottom for `y` values less than or equal to 1/3,", - "anchors legends to at their top for `y` values greater than or equal to 2/3 and", - "anchors legends with respect to their middle otherwise." - ].join(" ") - }, - uirevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of legend-driven changes in trace and pie label", - "visibility. Defaults to `layout.uirevision`." - ].join(" ") - }, - valign: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - dflt: "middle", - editType: "legend", - description: [ - "Sets the vertical alignment of the symbols with respect to their associated text." - ].join(" ") - }, - title: { - text: { - valType: "string", - dflt: "", - editType: "legend", - description: [ - "Sets the title of the legend." - ].join(" ") - }, - font: fontAttrs$a({ - editType: "legend", - description: [ - "Sets this legend's title font.", - "Defaults to `legend.font` with its size increased about 20%." - ].join(" ") - }), - side: { - valType: "enumerated", - values: ["top", "left", "top left", "top center", "top right"], - editType: "legend", - description: [ - "Determines the location of legend's title", - "with respect to the legend items.", - "Defaulted to *top* with `orientation` is *h*.", - "Defaulted to *left* with `orientation` is *v*.", - "The *top left* options could be used to expand", - "top center and top right are for horizontal alignment", - "legend area in both x and y sides." - ].join(" ") - }, - editType: "legend" - }, - editType: "legend" -}; -var helpers$I = {}; -helpers$I.isGrouped = function isGrouped(legendLayout) { - return (legendLayout.traceorder || "").indexOf("grouped") !== -1; -}; -helpers$I.isVertical = function isVertical(legendLayout) { - return legendLayout.orientation !== "h"; -}; -helpers$I.isReversed = function isReversed(legendLayout) { - return (legendLayout.traceorder || "").indexOf("reversed") !== -1; -}; -var Registry$H = registry; -var Lib$1C = libExports; -var Template$5 = plot_template; -var plotsAttrs = attributes$O; -var attributes$F = attributes$G; -var basePlotLayoutAttributes = layout_attributes$6; -var helpers$H = helpers$I; -function groupDefaults(legendId, layoutIn, layoutOut, fullData) { - var containerIn = layoutIn[legendId] || {}; - var containerOut = Template$5.newContainer(layoutOut, legendId); - function coerce2(attr, dflt) { - return Lib$1C.coerce(containerIn, containerOut, attributes$F, attr, dflt); - } - var itemFont = Lib$1C.coerceFont(coerce2, "font", layoutOut.font); - coerce2("bgcolor", layoutOut.paper_bgcolor); - coerce2("bordercolor"); - var visible = coerce2("visible"); - if (!visible) return; - var trace; - var traceCoerce = function(attr, dflt) { - var traceIn = trace._input; - var traceOut = trace; - return Lib$1C.coerce(traceIn, traceOut, plotsAttrs, attr, dflt); - }; - var globalFont2 = layoutOut.font || {}; - var grouptitlefont = Lib$1C.coerceFont(coerce2, "grouptitlefont", globalFont2, { overrideDflt: { - size: Math.round(globalFont2.size * 1.1) - } }); - var legendTraceCount = 0; - var legendReallyHasATrace = false; - var defaultOrder = "normal"; - var shapesWithLegend = (layoutOut.shapes || []).filter(function(d) { - return d.showlegend; - }); - var allLegendItems = fullData.concat(shapesWithLegend).filter(function(d) { - return legendId === (d.legend || "legend"); - }); - for (var i = 0; i < allLegendItems.length; i++) { - trace = allLegendItems[i]; - if (!trace.visible) continue; - var isShape = trace._isShape; - if (trace.showlegend || trace._dfltShowLegend && !(trace._module && trace._module.attributes && trace._module.attributes.showlegend && trace._module.attributes.showlegend.dflt === false)) { - legendTraceCount++; - if (trace.showlegend) { - legendReallyHasATrace = true; - if (!isShape && Registry$H.traceIs(trace, "pie-like") || trace._input.showlegend === true) { - legendTraceCount++; - } - } - Lib$1C.coerceFont(traceCoerce, "legendgrouptitle.font", grouptitlefont); - } - if (!isShape && Registry$H.traceIs(trace, "bar") && layoutOut.barmode === "stack" || ["tonextx", "tonexty"].indexOf(trace.fill) !== -1) { - defaultOrder = helpers$H.isGrouped({ traceorder: defaultOrder }) ? "grouped+reversed" : "reversed"; - } - if (trace.legendgroup !== void 0 && trace.legendgroup !== "") { - defaultOrder = helpers$H.isReversed({ traceorder: defaultOrder }) ? "reversed+grouped" : "grouped"; - } - } - var showLegend = Lib$1C.coerce( - layoutIn, - layoutOut, - basePlotLayoutAttributes, - "showlegend", - legendReallyHasATrace && legendTraceCount > (legendId === "legend" ? 1 : 0) - ); - if (showLegend === false) layoutOut[legendId] = void 0; - if (showLegend === false && !containerIn.uirevision) return; - coerce2("uirevision", layoutOut.uirevision); - if (showLegend === false) return; - coerce2("borderwidth"); - var orientation = coerce2("orientation"); - var yref = coerce2("yref"); - var xref = coerce2("xref"); - var isHorizontal = orientation === "h"; - var isPaperY = yref === "paper"; - var isPaperX = xref === "paper"; - var defaultX, defaultY, defaultYAnchor; - var defaultXAnchor = "left"; - if (isHorizontal) { - defaultX = 0; - if (Registry$H.getComponentMethod("rangeslider", "isVisible")(layoutIn.xaxis)) { - if (isPaperY) { - defaultY = 1.1; - defaultYAnchor = "bottom"; - } else { - defaultY = 1; - defaultYAnchor = "top"; - } - } else { - if (isPaperY) { - defaultY = -0.1; - defaultYAnchor = "top"; - } else { - defaultY = 0; - defaultYAnchor = "bottom"; - } - } - } else { - defaultY = 1; - defaultYAnchor = "auto"; - if (isPaperX) { - defaultX = 1.02; - } else { - defaultX = 1; - defaultXAnchor = "right"; - } - } - Lib$1C.coerce(containerIn, containerOut, { - x: { - valType: "number", - editType: "legend", - min: isPaperX ? -2 : 0, - max: isPaperX ? 3 : 1, - dflt: defaultX - } - }, "x"); - Lib$1C.coerce(containerIn, containerOut, { - y: { - valType: "number", - editType: "legend", - min: isPaperY ? -2 : 0, - max: isPaperY ? 3 : 1, - dflt: defaultY - } - }, "y"); - coerce2("traceorder", defaultOrder); - if (helpers$H.isGrouped(layoutOut[legendId])) coerce2("tracegroupgap"); - coerce2("entrywidth"); - coerce2("entrywidthmode"); - coerce2("indentation"); - coerce2("itemsizing"); - coerce2("itemwidth"); - coerce2("itemclick"); - coerce2("itemdoubleclick"); - coerce2("groupclick"); - coerce2("xanchor", defaultXAnchor); - coerce2("yanchor", defaultYAnchor); - coerce2("valign"); - Lib$1C.noneOrAll(containerIn, containerOut, ["x", "y"]); - var titleText = coerce2("title.text"); - if (titleText) { - coerce2("title.side", isHorizontal ? "left" : "top"); - var dfltTitleFont = Lib$1C.extendFlat({}, itemFont, { - size: Lib$1C.bigFont(itemFont.size) - }); - Lib$1C.coerceFont(coerce2, "title.font", dfltTitleFont); - } -} -var defaults$m = function legendDefaults(layoutIn, layoutOut, fullData) { - var i; - var allLegendsData = fullData.slice(); - var shapes2 = layoutOut.shapes; - if (shapes2) { - for (i = 0; i < shapes2.length; i++) { - var shape = shapes2[i]; - if (!shape.showlegend) continue; - var mockTrace = { - _input: shape._input, - visible: shape.visible, - showlegend: shape.showlegend, - legend: shape.legend - }; - allLegendsData.push(mockTrace); - } - } - var legends = ["legend"]; - for (i = 0; i < allLegendsData.length; i++) { - Lib$1C.pushUnique(legends, allLegendsData[i].legend); - } - layoutOut._legends = []; - for (i = 0; i < legends.length; i++) { - var legendId = legends[i]; - groupDefaults(legendId, layoutIn, layoutOut, allLegendsData); - if (layoutOut[legendId] && layoutOut[legendId].visible) { - layoutOut[legendId]._id = legendId; - } - layoutOut._legends.push(legendId); - } -}; -var Registry$G = registry; -var Lib$1B = libExports; -var pushUnique$1 = Lib$1B.pushUnique; -var SHOWISOLATETIP = true; -var handle_click = function handleClick(g, gd, numClicks) { - var fullLayout = gd._fullLayout; - if (gd._dragged || gd._editing) return; - var itemClick = fullLayout.legend.itemclick; - var itemDoubleClick = fullLayout.legend.itemdoubleclick; - var groupClick = fullLayout.legend.groupclick; - if (numClicks === 1 && itemClick === "toggle" && itemDoubleClick === "toggleothers" && SHOWISOLATETIP && gd.data && gd._context.showTips) { - Lib$1B.notifier(Lib$1B._(gd, "Double-click on legend to isolate one trace"), "long"); - SHOWISOLATETIP = false; - } else { - SHOWISOLATETIP = false; - } - var mode; - if (numClicks === 1) mode = itemClick; - else if (numClicks === 2) mode = itemDoubleClick; - if (!mode) return; - var toggleGroup = groupClick === "togglegroup"; - var hiddenSlices = fullLayout.hiddenlabels ? fullLayout.hiddenlabels.slice() : []; - var legendItem = g.data()[0][0]; - if (legendItem.groupTitle && legendItem.noClick) return; - var fullData = gd._fullData; - var shapesWithLegend = (fullLayout.shapes || []).filter(function(d2) { - return d2.showlegend; - }); - var allLegendItems = fullData.concat(shapesWithLegend); - var fullTrace = legendItem.trace; - if (fullTrace._isShape) { - fullTrace = fullTrace._fullInput; - } - var legendgroup = fullTrace.legendgroup; - var i, j, kcont, key, keys, val; - var dataUpdate = {}; - var dataIndices = []; - var carrs = []; - var carrIdx = []; - function insertDataUpdate(traceIndex, value2) { - var attrIndex = dataIndices.indexOf(traceIndex); - var valueArray = dataUpdate.visible; - if (!valueArray) { - valueArray = dataUpdate.visible = []; - } - if (dataIndices.indexOf(traceIndex) === -1) { - dataIndices.push(traceIndex); - attrIndex = dataIndices.length - 1; - } - valueArray[attrIndex] = value2; - return attrIndex; - } - var updatedShapes = (fullLayout.shapes || []).map(function(d2) { - return d2._input; - }); - var shapesUpdated = false; - function insertShapesUpdate(shapeIndex, value2) { - updatedShapes[shapeIndex].visible = value2; - shapesUpdated = true; - } - function setVisibility(fullTrace2, visibility) { - if (legendItem.groupTitle && !toggleGroup) return; - var fullInput2 = fullTrace2._fullInput || fullTrace2; - var isShape2 = fullInput2._isShape; - var index2 = fullInput2.index; - if (index2 === void 0) index2 = fullInput2._index; - if (Registry$G.hasTransform(fullInput2, "groupby")) { - var kcont2 = carrs[index2]; - if (!kcont2) { - var groupbyIndices = Registry$G.getTransformIndices(fullInput2, "groupby"); - var lastGroupbyIndex = groupbyIndices[groupbyIndices.length - 1]; - kcont2 = Lib$1B.keyedContainer(fullInput2, "transforms[" + lastGroupbyIndex + "].styles", "target", "value.visible"); - carrs[index2] = kcont2; - } - var curState = kcont2.get(fullTrace2._group); - if (curState === void 0) { - curState = true; - } - if (curState !== false) { - kcont2.set(fullTrace2._group, visibility); - } - carrIdx[index2] = insertDataUpdate(index2, fullInput2.visible === false ? false : true); - } else { - var nextVisibility2 = fullInput2.visible === false ? false : visibility; - if (isShape2) { - insertShapesUpdate(index2, nextVisibility2); - } else { - insertDataUpdate(index2, nextVisibility2); - } - } - } - var thisLegend = fullTrace.legend; - var fullInput = fullTrace._fullInput; - var isShape = fullInput && fullInput._isShape; - if (!isShape && Registry$G.traceIs(fullTrace, "pie-like")) { - var thisLabel = legendItem.label; - var thisLabelIndex = hiddenSlices.indexOf(thisLabel); - if (mode === "toggle") { - if (thisLabelIndex === -1) hiddenSlices.push(thisLabel); - else hiddenSlices.splice(thisLabelIndex, 1); - } else if (mode === "toggleothers") { - var changed = thisLabelIndex !== -1; - var unhideList = []; - for (i = 0; i < gd.calcdata.length; i++) { - var cdi = gd.calcdata[i]; - for (j = 0; j < cdi.length; j++) { - var d = cdi[j]; - var dLabel = d.label; - if (thisLegend === cdi[0].trace.legend) { - if (thisLabel !== dLabel) { - if (hiddenSlices.indexOf(dLabel) === -1) changed = true; - pushUnique$1(hiddenSlices, dLabel); - unhideList.push(dLabel); - } - } - } - } - if (!changed) { - for (var q = 0; q < unhideList.length; q++) { - var pos = hiddenSlices.indexOf(unhideList[q]); - if (pos !== -1) { - hiddenSlices.splice(pos, 1); - } - } - } - } - Registry$G.call("_guiRelayout", gd, "hiddenlabels", hiddenSlices); - } else { - var hasLegendgroup = legendgroup && legendgroup.length; - var traceIndicesInGroup = []; - var tracei; - if (hasLegendgroup) { - for (i = 0; i < allLegendItems.length; i++) { - tracei = allLegendItems[i]; - if (!tracei.visible) continue; - if (tracei.legendgroup === legendgroup) { - traceIndicesInGroup.push(i); - } - } - } - if (mode === "toggle") { - var nextVisibility; - switch (fullTrace.visible) { - case true: - nextVisibility = "legendonly"; - break; - case false: - nextVisibility = false; - break; - case "legendonly": - nextVisibility = true; - break; - } - if (hasLegendgroup) { - if (toggleGroup) { - for (i = 0; i < allLegendItems.length; i++) { - var item = allLegendItems[i]; - if (item.visible !== false && item.legendgroup === legendgroup) { - setVisibility(item, nextVisibility); - } - } - } else { - setVisibility(fullTrace, nextVisibility); - } - } else { - setVisibility(fullTrace, nextVisibility); - } - } else if (mode === "toggleothers") { - var isClicked, isInGroup, notInLegend, otherState, _item; - var isIsolated = true; - for (i = 0; i < allLegendItems.length; i++) { - _item = allLegendItems[i]; - isClicked = _item === fullTrace; - notInLegend = _item.showlegend !== true; - if (isClicked || notInLegend) continue; - isInGroup = hasLegendgroup && _item.legendgroup === legendgroup; - if (!isInGroup && _item.legend === thisLegend && _item.visible === true && !Registry$G.traceIs(_item, "notLegendIsolatable")) { - isIsolated = false; - break; - } - } - for (i = 0; i < allLegendItems.length; i++) { - _item = allLegendItems[i]; - if (_item.visible === false || _item.legend !== thisLegend) continue; - if (Registry$G.traceIs(_item, "notLegendIsolatable")) { - continue; - } - switch (fullTrace.visible) { - case "legendonly": - setVisibility(_item, true); - break; - case true: - otherState = isIsolated ? true : "legendonly"; - isClicked = _item === fullTrace; - notInLegend = _item.showlegend !== true && !_item.legendgroup; - isInGroup = isClicked || hasLegendgroup && _item.legendgroup === legendgroup; - setVisibility(_item, isInGroup || notInLegend ? true : otherState); - break; - } - } - } - for (i = 0; i < carrs.length; i++) { - kcont = carrs[i]; - if (!kcont) continue; - var update2 = kcont.constructUpdate(); - var updateKeys = Object.keys(update2); - for (j = 0; j < updateKeys.length; j++) { - key = updateKeys[j]; - val = dataUpdate[key] = dataUpdate[key] || []; - val[carrIdx[i]] = update2[key]; - } - } - keys = Object.keys(dataUpdate); - for (i = 0; i < keys.length; i++) { - key = keys[i]; - for (j = 0; j < dataIndices.length; j++) { - if (!dataUpdate[key].hasOwnProperty(j)) { - dataUpdate[key][j] = void 0; - } - } - } - if (shapesUpdated) { - Registry$G.call("_guiUpdate", gd, dataUpdate, { shapes: updatedShapes }, dataIndices); - } else { - Registry$G.call("_guiRestyle", gd, dataUpdate, dataIndices); - } - } -}; -var constants$O = { - scrollBarWidth: 6, - scrollBarMinHeight: 20, - scrollBarColor: "#808BA4", - scrollBarMargin: 4, - scrollBarEnterAttrs: { rx: 20, ry: 3, width: 0, height: 0 }, - // number of px between legend title and (left) side of legend (always in x direction and from inner border) - titlePad: 2, - // number of px between each legend item (x and/or y direction) - itemGap: 5 -}; -var Registry$F = registry; -var helpers$G = helpers$I; -var get_legend_data = function getLegendData(calcdata, opts, hasMultipleLegends) { - var inHover = opts._inHover; - var grouped = helpers$G.isGrouped(opts); - var reversed = helpers$G.isReversed(opts); - var lgroupToTraces = {}; - var lgroups = []; - var hasOneNonBlankGroup = false; - var slicesShown = {}; - var lgroupi = 0; - var maxNameLength = 0; - var i, j; - function addOneItem(legendId, legendGroup, legendItem) { - if (opts.visible === false) return; - if (hasMultipleLegends && legendId !== opts._id) return; - if (legendGroup === "" || !helpers$G.isGrouped(opts)) { - var uniqueGroup = "~~i" + lgroupi; - lgroups.push(uniqueGroup); - lgroupToTraces[uniqueGroup] = [legendItem]; - lgroupi++; - } else if (lgroups.indexOf(legendGroup) === -1) { - lgroups.push(legendGroup); - hasOneNonBlankGroup = true; - lgroupToTraces[legendGroup] = [legendItem]; - } else { - lgroupToTraces[legendGroup].push(legendItem); - } - } - for (i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var cd0 = cd[0]; - var trace = cd0.trace; - var lid = trace.legend; - var lgroup = trace.legendgroup; - if (!inHover && (!trace.visible || !trace.showlegend)) continue; - if (Registry$F.traceIs(trace, "pie-like")) { - if (!slicesShown[lgroup]) slicesShown[lgroup] = {}; - for (j = 0; j < cd.length; j++) { - var labelj = cd[j].label; - if (!slicesShown[lgroup][labelj]) { - addOneItem(lid, lgroup, { - label: labelj, - color: cd[j].color, - i: cd[j].i, - trace, - pts: cd[j].pts - }); - slicesShown[lgroup][labelj] = true; - maxNameLength = Math.max(maxNameLength, (labelj || "").length); - } - } - } else { - addOneItem(lid, lgroup, cd0); - maxNameLength = Math.max(maxNameLength, (trace.name || "").length); - } - } - if (!lgroups.length) return []; - var shouldCollapse = !hasOneNonBlankGroup || !grouped; - var legendData = []; - for (i = 0; i < lgroups.length; i++) { - var t = lgroupToTraces[lgroups[i]]; - if (shouldCollapse) { - legendData.push(t[0]); - } else { - legendData.push(t); - } - } - if (shouldCollapse) legendData = [legendData]; - for (i = 0; i < legendData.length; i++) { - var groupMinRank = Infinity; - for (j = 0; j < legendData[i].length; j++) { - var rank = legendData[i][j].trace.legendrank; - if (groupMinRank > rank) groupMinRank = rank; - } - legendData[i][0]._groupMinRank = groupMinRank; - legendData[i][0]._preGroupSort = i; - } - var orderFn1 = function(a, b) { - return a[0]._groupMinRank - b[0]._groupMinRank || a[0]._preGroupSort - b[0]._preGroupSort; - }; - var orderFn2 = function(a, b) { - return a.trace.legendrank - b.trace.legendrank || a._preSort - b._preSort; - }; - legendData.forEach(function(a, k) { - a[0]._preGroupSort = k; - }); - legendData.sort(orderFn1); - for (i = 0; i < legendData.length; i++) { - legendData[i].forEach(function(a, k) { - a._preSort = k; - }); - legendData[i].sort(orderFn2); - var firstItemTrace = legendData[i][0].trace; - var groupTitle = null; - for (j = 0; j < legendData[i].length; j++) { - var gt2 = legendData[i][j].trace.legendgrouptitle; - if (gt2 && gt2.text) { - groupTitle = gt2; - if (inHover) gt2.font = opts._groupTitleFont; - break; - } - } - if (reversed) legendData[i].reverse(); - if (groupTitle) { - var hasPieLike = false; - for (j = 0; j < legendData[i].length; j++) { - if (Registry$F.traceIs(legendData[i][j].trace, "pie-like")) { - hasPieLike = true; - break; - } - } - legendData[i].unshift({ - i: -1, - groupTitle, - noClick: hasPieLike, - trace: { - showlegend: firstItemTrace.showlegend, - legendgroup: firstItemTrace.legendgroup, - visible: opts.groupclick === "toggleitem" ? true : firstItemTrace.visible - } - }); - } - for (j = 0; j < legendData[i].length; j++) { - legendData[i][j] = [ - legendData[i][j] - ]; - } - } - opts._lgroupsLength = legendData.length; - opts._maxNameLength = maxNameLength; - return legendData; -}; -var helpers$F = {}; -(function(exports2) { - var Lib2 = libExports; - function format2(vRounded) { - return vRounded.indexOf("e") !== -1 ? vRounded.replace(/[.]?0+e/, "e") : vRounded.indexOf(".") !== -1 ? vRounded.replace(/[.]?0+$/, "") : vRounded; - } - exports2.formatPiePercent = function formatPiePercent(v, separators) { - var vRounded = format2((v * 100).toPrecision(3)); - return Lib2.numSeparate(vRounded, separators) + "%"; - }; - exports2.formatPieValue = function formatPieValue(v, separators) { - var vRounded = format2(v.toPrecision(10)); - return Lib2.numSeparate(vRounded, separators); - }; - exports2.getFirstFilled = function getFirstFilled(array2, indices) { - if (!Lib2.isArrayOrTypedArray(array2)) return; - for (var i = 0; i < indices.length; i++) { - var v = array2[indices[i]]; - if (v || v === 0 || v === "") return v; - } - }; - exports2.castOption = function castOption2(item, indices) { - if (Lib2.isArrayOrTypedArray(item)) return exports2.getFirstFilled(item, indices); - else if (item) return item; - }; - exports2.getRotationAngle = function(rotation) { - return (rotation === "auto" ? 0 : rotation) * Math.PI / 180; - }; -})(helpers$F); -var Drawing$r = drawingExports; -var Color$G = colorExports; -var fill_one$1 = function fillOne(s, pt, trace, gd) { - var pattern2 = trace.marker.pattern; - if (pattern2 && pattern2.shape) { - Drawing$r.pointStyle(s, trace, gd, pt); - } else { - Color$G.fill(s, pt.color); - } -}; -var Color$F = colorExports; -var castOption = helpers$F.castOption; -var fillOne$2 = fill_one$1; -var style_one = function styleOne(s, pt, trace, gd) { - var line2 = trace.marker.line; - var lineColor = castOption(line2.color, pt.pts) || Color$F.defaultLine; - var lineWidth = castOption(line2.width, pt.pts) || 0; - s.call(fillOne$2, pt, trace, gd).style("stroke-width", lineWidth).call(Color$F.stroke, lineColor); -}; -var d3$u = d3Exports; -var Registry$E = registry; -var Lib$1A = libExports; -var strTranslate$9 = Lib$1A.strTranslate; -var Drawing$q = drawingExports; -var Color$E = colorExports; -var extractOpts = helpers$L.extractOpts; -var subTypes$9 = subtypes$3; -var stylePie = style_one; -var pieCastOption = helpers$F.castOption; -var constants$N = constants$O; -var CST_MARKER_SIZE = 12; -var CST_LINE_WIDTH = 5; -var CST_MARKER_LINE_WIDTH = 2; -var MAX_LINE_WIDTH = 10; -var MAX_MARKER_LINE_WIDTH = 5; -var style$8 = function style(s, gd, legend2) { - var fullLayout = gd._fullLayout; - if (!legend2) legend2 = fullLayout.legend; - var constantItemSizing = legend2.itemsizing === "constant"; - var itemWidth = legend2.itemwidth; - var centerPos = (itemWidth + constants$N.itemGap * 2) / 2; - var centerTransform = strTranslate$9(centerPos, 0); - var boundLineWidth = function(mlw, cont, max, cst) { - var v; - if (mlw + 1) { - v = mlw; - } else if (cont && cont.width > 0) { - v = cont.width; - } else { - return 0; - } - return constantItemSizing ? cst : Math.min(v, max); - }; - s.each(function(d) { - var traceGroup = d3$u.select(this); - var layers = Lib$1A.ensureSingle(traceGroup, "g", "layers"); - layers.style("opacity", d[0].trace.opacity); - var indentation = legend2.indentation; - var valign = legend2.valign; - var lineHeight = d[0].lineHeight; - var height = d[0].height; - if (valign === "middle" && indentation === 0 || !lineHeight || !height) { - layers.attr("transform", null); - } else { - var factor = { top: 1, bottom: -1 }[valign]; - var markerOffsetY = factor * (0.5 * (lineHeight - height + 3)) || 0; - var markerOffsetX = legend2.indentation; - layers.attr("transform", strTranslate$9(markerOffsetX, markerOffsetY)); - } - var fill = layers.selectAll("g.legendfill").data([d]); - fill.enter().append("g").classed("legendfill", true); - var line2 = layers.selectAll("g.legendlines").data([d]); - line2.enter().append("g").classed("legendlines", true); - var symbol = layers.selectAll("g.legendsymbols").data([d]); - symbol.enter().append("g").classed("legendsymbols", true); - symbol.selectAll("g.legendpoints").data([d]).enter().append("g").classed("legendpoints", true); - }).each(styleSpatial).each(styleWaterfalls).each(styleFunnels).each(styleBars).each(styleBoxes).each(styleFunnelareas).each(stylePies).each(styleLines).each(stylePoints2).each(styleCandles).each(styleOHLC); - function styleLines(d) { - var styleGuide = getStyleGuide(d); - var showFill = styleGuide.showFill; - var showLine = styleGuide.showLine; - var showGradientLine = styleGuide.showGradientLine; - var showGradientFill = styleGuide.showGradientFill; - var anyFill = styleGuide.anyFill; - var anyLine = styleGuide.anyLine; - var d0 = d[0]; - var trace = d0.trace; - var dMod, tMod; - var cOpts = extractOpts(trace); - var colorscale2 = cOpts.colorscale; - var reversescale = cOpts.reversescale; - var fillStyle = function(s2) { - if (s2.size()) { - if (showFill) { - Drawing$q.fillGroupStyle(s2, gd, true); - } else { - var gradientID = "legendfill-" + trace.uid; - Drawing$q.gradient( - s2, - gd, - gradientID, - getGradientDirection(reversescale), - colorscale2, - "fill" - ); - } - } - }; - var lineGradient = function(s2) { - if (s2.size()) { - var gradientID = "legendline-" + trace.uid; - Drawing$q.lineGroupStyle(s2); - Drawing$q.gradient( - s2, - gd, - gradientID, - getGradientDirection(reversescale), - colorscale2, - "stroke" - ); - } - }; - var pathStart = subTypes$9.hasMarkers(trace) || !anyFill ? "M5,0" : ( - // with a line leave it slightly below center, to leave room for the - // line thickness and because the line is usually more prominent - anyLine ? "M5,-2" : "M5,-3" - ); - var this3 = d3$u.select(this); - var fill = this3.select(".legendfill").selectAll("path").data(showFill || showGradientFill ? [d] : []); - fill.enter().append("path").classed("js-fill", true); - fill.exit().remove(); - fill.attr("d", pathStart + "h" + itemWidth + "v6h-" + itemWidth + "z").call(fillStyle); - if (showLine || showGradientLine) { - var lw = boundLineWidth(void 0, trace.line, MAX_LINE_WIDTH, CST_LINE_WIDTH); - tMod = Lib$1A.minExtend(trace, { line: { width: lw } }); - dMod = [Lib$1A.minExtend(d0, { trace: tMod })]; - } - var line2 = this3.select(".legendlines").selectAll("path").data(showLine || showGradientLine ? [dMod] : []); - line2.enter().append("path").classed("js-line", true); - line2.exit().remove(); - line2.attr("d", pathStart + (showGradientLine ? "l" + itemWidth + ",0.0001" : "h" + itemWidth)).call(showLine ? Drawing$q.lineGroupStyle : lineGradient); - } - function stylePoints2(d) { - var styleGuide = getStyleGuide(d); - var anyFill = styleGuide.anyFill; - var anyLine = styleGuide.anyLine; - var showLine = styleGuide.showLine; - var showMarker = styleGuide.showMarker; - var d0 = d[0]; - var trace = d0.trace; - var showText = !showMarker && !anyLine && !anyFill && subTypes$9.hasText(trace); - var dMod, tMod; - function boundVal(attrIn, arrayToValFn, bounds, cst) { - var valIn = Lib$1A.nestedProperty(trace, attrIn).get(); - var valToBound = Lib$1A.isArrayOrTypedArray(valIn) && arrayToValFn ? arrayToValFn(valIn) : valIn; - if (constantItemSizing && valToBound && cst !== void 0) { - valToBound = cst; - } - if (bounds) { - if (valToBound < bounds[0]) return bounds[0]; - else if (valToBound > bounds[1]) return bounds[1]; - } - return valToBound; - } - function pickFirst(array2) { - if (d0._distinct && d0.index && array2[d0.index]) return array2[d0.index]; - return array2[0]; - } - if (showMarker || showText || showLine) { - var dEdit = {}; - var tEdit = {}; - if (showMarker) { - dEdit.mc = boundVal("marker.color", pickFirst); - dEdit.mx = boundVal("marker.symbol", pickFirst); - dEdit.mo = boundVal("marker.opacity", Lib$1A.mean, [0.2, 1]); - dEdit.mlc = boundVal("marker.line.color", pickFirst); - dEdit.mlw = boundVal("marker.line.width", Lib$1A.mean, [0, 5], CST_MARKER_LINE_WIDTH); - tEdit.marker = { - sizeref: 1, - sizemin: 1, - sizemode: "diameter" - }; - var ms = boundVal("marker.size", Lib$1A.mean, [2, 16], CST_MARKER_SIZE); - dEdit.ms = ms; - tEdit.marker.size = ms; - } - if (showLine) { - tEdit.line = { - width: boundVal("line.width", pickFirst, [0, 10], CST_LINE_WIDTH) - }; - } - if (showText) { - dEdit.tx = "Aa"; - dEdit.tp = boundVal("textposition", pickFirst); - dEdit.ts = 10; - dEdit.tc = boundVal("textfont.color", pickFirst); - dEdit.tf = boundVal("textfont.family", pickFirst); - dEdit.tw = boundVal("textfont.weight", pickFirst); - dEdit.ty = boundVal("textfont.style", pickFirst); - dEdit.tv = boundVal("textfont.variant", pickFirst); - dEdit.tC = boundVal("textfont.textcase", pickFirst); - dEdit.tE = boundVal("textfont.lineposition", pickFirst); - dEdit.tS = boundVal("textfont.shadow", pickFirst); - } - dMod = [Lib$1A.minExtend(d0, dEdit)]; - tMod = Lib$1A.minExtend(trace, tEdit); - tMod.selectedpoints = null; - tMod.texttemplate = null; - } - var ptgroup = d3$u.select(this).select("g.legendpoints"); - var pts = ptgroup.selectAll("path.scatterpts").data(showMarker ? dMod : []); - pts.enter().insert("path", ":first-child").classed("scatterpts", true).attr("transform", centerTransform); - pts.exit().remove(); - pts.call(Drawing$q.pointStyle, tMod, gd); - if (showMarker) dMod[0].mrc = 3; - var txt = ptgroup.selectAll("g.pointtext").data(showText ? dMod : []); - txt.enter().append("g").classed("pointtext", true).append("text").attr("transform", centerTransform); - txt.exit().remove(); - txt.selectAll("text").call(Drawing$q.textPointStyle, tMod, gd); - } - function styleWaterfalls(d) { - var trace = d[0].trace; - var isWaterfall = trace.type === "waterfall"; - if (d[0]._distinct && isWaterfall) { - var cont = d[0].trace[d[0].dir].marker; - d[0].mc = cont.color; - d[0].mlw = cont.line.width; - d[0].mlc = cont.line.color; - return styleBarLike(d, this, "waterfall"); - } - var ptsData = []; - if (trace.visible && isWaterfall) { - ptsData = d[0].hasTotals ? [["increasing", "M-6,-6V6H0Z"], ["totals", "M6,6H0L-6,-6H-0Z"], ["decreasing", "M6,6V-6H0Z"]] : [["increasing", "M-6,-6V6H6Z"], ["decreasing", "M6,6V-6H-6Z"]]; - } - var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendwaterfall").data(ptsData); - pts.enter().append("path").classed("legendwaterfall", true).attr("transform", centerTransform).style("stroke-miterlimit", 1); - pts.exit().remove(); - pts.each(function(dd) { - var pt = d3$u.select(this); - var cont2 = trace[dd[0]].marker; - var lw = boundLineWidth(void 0, cont2.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - pt.attr("d", dd[1]).style("stroke-width", lw + "px").call(Color$E.fill, cont2.color); - if (lw) { - pt.call(Color$E.stroke, cont2.line.color); - } - }); - } - function styleBars(d) { - styleBarLike(d, this); - } - function styleFunnels(d) { - styleBarLike(d, this, "funnel"); - } - function styleBarLike(d, lThis, desiredType) { - var trace = d[0].trace; - var marker2 = trace.marker || {}; - var markerLine2 = marker2.line || {}; - var pathStr = marker2.cornerradius ? "M6,3a3,3,0,0,1-3,3H-3a3,3,0,0,1-3-3V-3a3,3,0,0,1,3-3H3a3,3,0,0,1,3,3Z" : ( - // Square with rounded corners - "M6,6H-6V-6H6Z" - ); - var isVisible2 = !desiredType ? Registry$E.traceIs(trace, "bar") : trace.visible && trace.type === desiredType; - var barpath = d3$u.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible2 ? [d] : []); - barpath.enter().append("path").classed("legend" + desiredType, true).attr("d", pathStr).attr("transform", centerTransform); - barpath.exit().remove(); - barpath.each(function(d2) { - var p = d3$u.select(this); - var d0 = d2[0]; - var w = boundLineWidth(d0.mlw, marker2.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - p.style("stroke-width", w + "px"); - var mcc = d0.mcc; - if (!legend2._inHover && "mc" in d0) { - var cOpts = extractOpts(marker2); - var mid = cOpts.mid; - if (mid === void 0) mid = (cOpts.max + cOpts.min) / 2; - mcc = Drawing$q.tryColorscale(marker2, "")(mid); - } - var fillColor = mcc || d0.mc || marker2.color; - var markerPattern = marker2.pattern; - var patternShape = markerPattern && Drawing$q.getPatternAttr(markerPattern.shape, 0, ""); - if (patternShape) { - var patternBGColor = Drawing$q.getPatternAttr(markerPattern.bgcolor, 0, null); - var patternFGColor = Drawing$q.getPatternAttr(markerPattern.fgcolor, 0, null); - var patternFGOpacity = markerPattern.fgopacity; - var patternSize = dimAttr(markerPattern.size, 8, 10); - var patternSolidity = dimAttr(markerPattern.solidity, 0.5, 1); - var patternID = "legend-" + trace.uid; - p.call( - Drawing$q.pattern, - "legend", - gd, - patternID, - patternShape, - patternSize, - patternSolidity, - mcc, - markerPattern.fillmode, - patternBGColor, - patternFGColor, - patternFGOpacity - ); - } else { - p.call(Color$E.fill, fillColor); - } - if (w) Color$E.stroke(p, d0.mlc || markerLine2.color); - }); - } - function styleBoxes(d) { - var trace = d[0].trace; - var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendbox").data(trace.visible && Registry$E.traceIs(trace, "box-violin") ? [d] : []); - pts.enter().append("path").classed("legendbox", true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform); - pts.exit().remove(); - pts.each(function() { - var p = d3$u.select(this); - if ((trace.boxpoints === "all" || trace.points === "all") && Color$E.opacity(trace.fillcolor) === 0 && Color$E.opacity((trace.line || {}).color) === 0) { - var tMod = Lib$1A.minExtend(trace, { - marker: { - size: constantItemSizing ? CST_MARKER_SIZE : Lib$1A.constrain(trace.marker.size, 2, 16), - sizeref: 1, - sizemin: 1, - sizemode: "diameter" - } - }); - pts.call(Drawing$q.pointStyle, tMod, gd); - } else { - var w = boundLineWidth(void 0, trace.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - p.style("stroke-width", w + "px").call(Color$E.fill, trace.fillcolor); - if (w) Color$E.stroke(p, trace.line.color); - } - }); - } - function styleCandles(d) { - var trace = d[0].trace; - var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendcandle").data(trace.visible && trace.type === "candlestick" ? [d, d] : []); - pts.enter().append("path").classed("legendcandle", true).attr("d", function(_2, i) { - if (i) return "M-15,0H-8M-8,6V-6H8Z"; - return "M15,0H8M8,-6V6H-8Z"; - }).attr("transform", centerTransform).style("stroke-miterlimit", 1); - pts.exit().remove(); - pts.each(function(_2, i) { - var p = d3$u.select(this); - var cont = trace[i ? "increasing" : "decreasing"]; - var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - p.style("stroke-width", w + "px").call(Color$E.fill, cont.fillcolor); - if (w) Color$E.stroke(p, cont.line.color); - }); - } - function styleOHLC(d) { - var trace = d[0].trace; - var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legendohlc").data(trace.visible && trace.type === "ohlc" ? [d, d] : []); - pts.enter().append("path").classed("legendohlc", true).attr("d", function(_2, i) { - if (i) return "M-15,0H0M-8,-6V0"; - return "M15,0H0M8,6V0"; - }).attr("transform", centerTransform).style("stroke-miterlimit", 1); - pts.exit().remove(); - pts.each(function(_2, i) { - var p = d3$u.select(this); - var cont = trace[i ? "increasing" : "decreasing"]; - var w = boundLineWidth(void 0, cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - p.style("fill", "none").call(Drawing$q.dashLine, cont.line.dash, w); - if (w) Color$E.stroke(p, cont.line.color); - }); - } - function stylePies(d) { - stylePieLike(d, this, "pie"); - } - function styleFunnelareas(d) { - stylePieLike(d, this, "funnelarea"); - } - function stylePieLike(d, lThis, desiredType) { - var d0 = d[0]; - var trace = d0.trace; - var isVisible2 = !desiredType ? Registry$E.traceIs(trace, desiredType) : trace.visible && trace.type === desiredType; - var pts = d3$u.select(lThis).select("g.legendpoints").selectAll("path.legend" + desiredType).data(isVisible2 ? [d] : []); - pts.enter().append("path").classed("legend" + desiredType, true).attr("d", "M6,6H-6V-6H6Z").attr("transform", centerTransform); - pts.exit().remove(); - if (pts.size()) { - var cont = trace.marker || {}; - var lw = boundLineWidth(pieCastOption(cont.line.width, d0.pts), cont.line, MAX_MARKER_LINE_WIDTH, CST_MARKER_LINE_WIDTH); - var opt = "pieLike"; - var tMod = Lib$1A.minExtend(trace, { marker: { line: { width: lw } } }, opt); - var d0Mod = Lib$1A.minExtend(d0, { trace: tMod }, opt); - stylePie(pts, d0Mod, tMod, gd); - } - } - function styleSpatial(d) { - var trace = d[0].trace; - var useGradient; - var ptsData = []; - if (trace.visible) { - switch (trace.type) { - case "histogram2d": - case "heatmap": - ptsData = [ - ["M-15,-2V4H15V-2Z"] - // similar to contour - ]; - useGradient = true; - break; - case "choropleth": - case "choroplethmapbox": - case "choroplethmap": - ptsData = [ - ["M-6,-6V6H6V-6Z"] - ]; - useGradient = true; - break; - case "densitymapbox": - case "densitymap": - ptsData = [ - ["M-6,0 a6,6 0 1,0 12,0 a 6,6 0 1,0 -12,0"] - ]; - useGradient = "radial"; - break; - case "cone": - ptsData = [ - ["M-6,2 A2,2 0 0,0 -6,6 V6L6,4Z"], - ["M-6,-6 A2,2 0 0,0 -6,-2 L6,-4Z"], - ["M-6,-2 A2,2 0 0,0 -6,2 L6,0Z"] - ]; - useGradient = false; - break; - case "streamtube": - ptsData = [ - ["M-6,2 A2,2 0 0,0 -6,6 H6 A2,2 0 0,1 6,2 Z"], - ["M-6,-6 A2,2 0 0,0 -6,-2 H6 A2,2 0 0,1 6,-6 Z"], - ["M-6,-2 A2,2 0 0,0 -6,2 H6 A2,2 0 0,1 6,-2 Z"] - ]; - useGradient = false; - break; - case "surface": - ptsData = [ - ["M-6,-6 A2,3 0 0,0 -6,0 H6 A2,3 0 0,1 6,-6 Z"], - ["M-6,1 A2,3 0 0,1 -6,6 H6 A2,3 0 0,0 6,0 Z"] - ]; - useGradient = true; - break; - case "mesh3d": - ptsData = [ - ["M-6,6H0L-6,-6Z"], - ["M6,6H0L6,-6Z"], - ["M-6,-6H6L0,6Z"] - ]; - useGradient = false; - break; - case "volume": - ptsData = [ - ["M-6,6H0L-6,-6Z"], - ["M6,6H0L6,-6Z"], - ["M-6,-6H6L0,6Z"] - ]; - useGradient = true; - break; - case "isosurface": - ptsData = [ - ["M-6,6H0L-6,-6Z"], - ["M6,6H0L6,-6Z"], - ["M-6,-6 A12,24 0 0,0 6,-6 L0,6Z"] - ]; - useGradient = false; - break; - } - } - var pts = d3$u.select(this).select("g.legendpoints").selectAll("path.legend3dandfriends").data(ptsData); - pts.enter().append("path").classed("legend3dandfriends", true).attr("transform", centerTransform).style("stroke-miterlimit", 1); - pts.exit().remove(); - pts.each(function(dd, i) { - var pt = d3$u.select(this); - var cOpts = extractOpts(trace); - var colorscale2 = cOpts.colorscale; - var reversescale = cOpts.reversescale; - var fillGradient = function(s2) { - if (s2.size()) { - var gradientID = "legendfill-" + trace.uid; - Drawing$q.gradient( - s2, - gd, - gradientID, - getGradientDirection(reversescale, useGradient === "radial"), - colorscale2, - "fill" - ); - } - }; - var fillColor; - if (!colorscale2) { - var color2 = trace.vertexcolor || trace.facecolor || trace.color; - fillColor = Lib$1A.isArrayOrTypedArray(color2) ? color2[i] || color2[0] : color2; - } else { - if (!useGradient) { - var len = colorscale2.length; - fillColor = i === 0 ? colorscale2[reversescale ? len - 1 : 0][1] : ( - // minimum - i === 1 ? colorscale2[reversescale ? 0 : len - 1][1] : ( - // maximum - colorscale2[Math.floor((len - 1) / 2)][1] - ) - ); - } - } - pt.attr("d", dd[0]); - if (fillColor) { - pt.call(Color$E.fill, fillColor); - } else { - pt.call(fillGradient); - } - }); - } -}; -function getGradientDirection(reversescale, isRadial) { - var str2 = isRadial ? "radial" : "horizontal"; - return str2 + (reversescale ? "" : "reversed"); -} -function getStyleGuide(d) { - var trace = d[0].trace; - var contours = trace.contours; - var showLine = subTypes$9.hasLines(trace); - var showMarker = subTypes$9.hasMarkers(trace); - var showFill = trace.visible && trace.fill && trace.fill !== "none"; - var showGradientLine = false; - var showGradientFill = false; - if (contours) { - var coloring = contours.coloring; - if (coloring === "lines") { - showGradientLine = true; - } else { - showLine = coloring === "none" || coloring === "heatmap" || contours.showlines; - } - if (contours.type === "constraint") { - showFill = contours._operation !== "="; - } else if (coloring === "fill" || coloring === "heatmap") { - showGradientFill = true; - } - } - return { - showMarker, - showLine, - showFill, - showGradientLine, - showGradientFill, - anyLine: showLine || showGradientLine, - anyFill: showFill || showGradientFill - }; -} -function dimAttr(v, dflt, max) { - if (v && Lib$1A.isArrayOrTypedArray(v)) return dflt; - if (v > max) return max; - return v; -} -var d3$t = d3Exports; -var Lib$1z = libExports; -var Plots$a = plotsExports; -var Registry$D = registry; -var Events$2 = events; -var dragElement$6 = dragelementExports; -var Drawing$p = drawingExports; -var Color$D = colorExports; -var svgTextUtils$c = svg_text_utils; -var handleClick2 = handle_click; -var constants$M = constants$O; -var alignmentConstants$3 = alignment$1; -var LINE_SPACING$5 = alignmentConstants$3.LINE_SPACING; -var FROM_TL$4 = alignmentConstants$3.FROM_TL; -var FROM_BR$3 = alignmentConstants$3.FROM_BR; -var getLegendData2 = get_legend_data; -var style$7 = style$8; -var helpers$E = helpers$I; -var MAIN_TITLE = 1; -var LEGEND_PATTERN = /^legend[0-9]*$/; -var draw$d = function draw(gd, opts) { - if (opts) { - drawOne$3(gd, opts); - } else { - var fullLayout = gd._fullLayout; - var newLegends = fullLayout._legends; - var oldLegends = fullLayout._infolayer.selectAll('[class^="legend"]'); - oldLegends.each(function() { - var el = d3$t.select(this); - var classes = el.attr("class"); - var cls = classes.split(" ")[0]; - if (cls.match(LEGEND_PATTERN) && newLegends.indexOf(cls) === -1) { - el.remove(); - } - }); - for (var i = 0; i < newLegends.length; i++) { - var legendId = newLegends[i]; - var legendObj = gd._fullLayout[legendId]; - drawOne$3(gd, legendObj); - } - } -}; -function horizontalAlignTitle(titleEl, legendObj, bw) { - if (legendObj.title.side !== "top center" && legendObj.title.side !== "top right") return; - var font2 = legendObj.title.font; - var lineHeight = font2.size * LINE_SPACING$5; - var titleOffset = 0; - var textNode = titleEl.node(); - var width = Drawing$p.bBox(textNode).width; - if (legendObj.title.side === "top center") { - titleOffset = 0.5 * (legendObj._width - 2 * bw - 2 * constants$M.titlePad - width); - } else if (legendObj.title.side === "top right") { - titleOffset = legendObj._width - 2 * bw - 2 * constants$M.titlePad - width; - } - svgTextUtils$c.positionText( - titleEl, - bw + constants$M.titlePad + titleOffset, - bw + lineHeight - ); -} -function drawOne$3(gd, opts) { - var legendObj = opts || {}; - var fullLayout = gd._fullLayout; - var legendId = getId(legendObj); - var clipId, layer; - var inHover = legendObj._inHover; - if (inHover) { - layer = legendObj.layer; - clipId = "hover"; - } else { - layer = fullLayout._infolayer; - clipId = legendId; - } - if (!layer) return; - clipId += fullLayout._uid; - if (!gd._legendMouseDownTime) gd._legendMouseDownTime = 0; - var legendData; - if (!inHover) { - var calcdata = (gd.calcdata || []).slice(); - var shapes2 = fullLayout.shapes; - for (var i = 0; i < shapes2.length; i++) { - var shape = shapes2[i]; - if (!shape.showlegend) continue; - var shapeLegend = { - _isShape: true, - _fullInput: shape, - index: shape._index, - name: shape.name || shape.label.text || "shape " + shape._index, - legend: shape.legend, - legendgroup: shape.legendgroup, - legendgrouptitle: shape.legendgrouptitle, - legendrank: shape.legendrank, - legendwidth: shape.legendwidth, - showlegend: shape.showlegend, - visible: shape.visible, - opacity: shape.opacity, - mode: shape.type === "line" ? "lines" : "markers", - line: shape.line, - marker: { - line: shape.line, - color: shape.fillcolor, - size: 12, - symbol: shape.type === "rect" ? "square" : shape.type === "circle" ? "circle" : ( - // case of path - "hexagon2" - ) - } - }; - calcdata.push([{ trace: shapeLegend }]); - } - legendData = fullLayout.showlegend && getLegendData2(calcdata, legendObj, fullLayout._legends.length > 1); - } else { - if (!legendObj.entries) return; - legendData = getLegendData2(legendObj.entries, legendObj); - } - var hiddenSlices = fullLayout.hiddenlabels || []; - if (!inHover && (!fullLayout.showlegend || !legendData.length)) { - layer.selectAll("." + legendId).remove(); - fullLayout._topdefs.select("#" + clipId).remove(); - return Plots$a.autoMargin(gd, legendId); - } - var legend2 = Lib$1z.ensureSingle(layer, "g", legendId, function(s) { - if (!inHover) s.attr("pointer-events", "all"); - }); - var clipPath = Lib$1z.ensureSingleById(fullLayout._topdefs, "clipPath", clipId, function(s) { - s.append("rect"); - }); - var bg = Lib$1z.ensureSingle(legend2, "rect", "bg", function(s) { - s.attr("shape-rendering", "crispEdges"); - }); - bg.call(Color$D.stroke, legendObj.bordercolor).call(Color$D.fill, legendObj.bgcolor).style("stroke-width", legendObj.borderwidth + "px"); - var scrollBox = Lib$1z.ensureSingle(legend2, "g", "scrollbox"); - var title = legendObj.title; - legendObj._titleWidth = 0; - legendObj._titleHeight = 0; - var titleEl; - if (title.text) { - titleEl = Lib$1z.ensureSingle(scrollBox, "text", legendId + "titletext"); - titleEl.attr("text-anchor", "start").call(Drawing$p.font, title.font).text(title.text); - textLayout(titleEl, scrollBox, gd, legendObj, MAIN_TITLE); - } else { - scrollBox.selectAll("." + legendId + "titletext").remove(); - } - var scrollBar = Lib$1z.ensureSingle(legend2, "rect", "scrollbar", function(s) { - s.attr(constants$M.scrollBarEnterAttrs).call(Color$D.fill, constants$M.scrollBarColor); - }); - var groups = scrollBox.selectAll("g.groups").data(legendData); - groups.enter().append("g").attr("class", "groups"); - groups.exit().remove(); - var traces = groups.selectAll("g.traces").data(Lib$1z.identity); - traces.enter().append("g").attr("class", "traces"); - traces.exit().remove(); - traces.style("opacity", function(d) { - var trace = d[0].trace; - if (Registry$D.traceIs(trace, "pie-like")) { - return hiddenSlices.indexOf(d[0].label) !== -1 ? 0.5 : 1; - } else { - return trace.visible === "legendonly" ? 0.5 : 1; - } - }).each(function() { - d3$t.select(this).call(drawTexts, gd, legendObj); - }).call(style$7, gd, legendObj).each(function() { - if (!inHover) d3$t.select(this).call(setupTraceToggle, gd, legendId); - }); - Lib$1z.syncOrAsync([ - Plots$a.previousPromises, - function() { - return computeLegendDimensions(gd, groups, traces, legendObj); - }, - function() { - var gs = fullLayout._size; - var bw = legendObj.borderwidth; - var isPaperX = legendObj.xref === "paper"; - var isPaperY = legendObj.yref === "paper"; - if (title.text) { - horizontalAlignTitle(titleEl, legendObj, bw); - } - if (!inHover) { - var lx, ly; - if (isPaperX) { - lx = gs.l + gs.w * legendObj.x - FROM_TL$4[getXanchor(legendObj)] * legendObj._width; - } else { - lx = fullLayout.width * legendObj.x - FROM_TL$4[getXanchor(legendObj)] * legendObj._width; - } - if (isPaperY) { - ly = gs.t + gs.h * (1 - legendObj.y) - FROM_TL$4[getYanchor(legendObj)] * legendObj._effHeight; - } else { - ly = fullLayout.height * (1 - legendObj.y) - FROM_TL$4[getYanchor(legendObj)] * legendObj._effHeight; - } - var expMargin = expandMargin(gd, legendId, lx, ly); - if (expMargin) return; - if (fullLayout.margin.autoexpand) { - var lx0 = lx; - var ly0 = ly; - lx = isPaperX ? Lib$1z.constrain(lx, 0, fullLayout.width - legendObj._width) : lx0; - ly = isPaperY ? Lib$1z.constrain(ly, 0, fullLayout.height - legendObj._effHeight) : ly0; - if (lx !== lx0) { - Lib$1z.log("Constrain " + legendId + ".x to make legend fit inside graph"); - } - if (ly !== ly0) { - Lib$1z.log("Constrain " + legendId + ".y to make legend fit inside graph"); - } - } - Drawing$p.setTranslate(legend2, lx, ly); - } - scrollBar.on(".drag", null); - legend2.on("wheel", null); - if (inHover || legendObj._height <= legendObj._maxHeight || gd._context.staticPlot) { - var height = legendObj._effHeight; - if (inHover) height = legendObj._height; - bg.attr({ - width: legendObj._width - bw, - height: height - bw, - x: bw / 2, - y: bw / 2 - }); - Drawing$p.setTranslate(scrollBox, 0, 0); - clipPath.select("rect").attr({ - width: legendObj._width - 2 * bw, - height: height - 2 * bw, - x: bw, - y: bw - }); - Drawing$p.setClipUrl(scrollBox, clipId, gd); - Drawing$p.setRect(scrollBar, 0, 0, 0, 0); - delete legendObj._scrollY; - } else { - var scrollBarHeight = Math.max( - constants$M.scrollBarMinHeight, - legendObj._effHeight * legendObj._effHeight / legendObj._height - ); - var scrollBarYMax = legendObj._effHeight - scrollBarHeight - 2 * constants$M.scrollBarMargin; - var scrollBoxYMax = legendObj._height - legendObj._effHeight; - var scrollRatio = scrollBarYMax / scrollBoxYMax; - var scrollBoxY = Math.min(legendObj._scrollY || 0, scrollBoxYMax); - bg.attr({ - width: legendObj._width - 2 * bw + constants$M.scrollBarWidth + constants$M.scrollBarMargin, - height: legendObj._effHeight - bw, - x: bw / 2, - y: bw / 2 - }); - clipPath.select("rect").attr({ - width: legendObj._width - 2 * bw + constants$M.scrollBarWidth + constants$M.scrollBarMargin, - height: legendObj._effHeight - 2 * bw, - x: bw, - y: bw + scrollBoxY - }); - Drawing$p.setClipUrl(scrollBox, clipId, gd); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - legend2.on("wheel", function() { - scrollBoxY = Lib$1z.constrain( - legendObj._scrollY + d3$t.event.deltaY / scrollBarYMax * scrollBoxYMax, - 0, - scrollBoxYMax - ); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - if (scrollBoxY !== 0 && scrollBoxY !== scrollBoxYMax) { - d3$t.event.preventDefault(); - } - }); - var eventY0, eventY1, scrollBoxY0; - var getScrollBarDragY = function(scrollBoxY02, eventY02, eventY12) { - var y = (eventY12 - eventY02) / scrollRatio + scrollBoxY02; - return Lib$1z.constrain(y, 0, scrollBoxYMax); - }; - var getNaturalDragY = function(scrollBoxY02, eventY02, eventY12) { - var y = (eventY02 - eventY12) / scrollRatio + scrollBoxY02; - return Lib$1z.constrain(y, 0, scrollBoxYMax); - }; - var scrollBarDrag = d3$t.behavior.drag().on("dragstart", function() { - var e = d3$t.event.sourceEvent; - if (e.type === "touchstart") { - eventY0 = e.changedTouches[0].clientY; - } else { - eventY0 = e.clientY; - } - scrollBoxY0 = scrollBoxY; - }).on("drag", function() { - var e = d3$t.event.sourceEvent; - if (e.buttons === 2 || e.ctrlKey) return; - if (e.type === "touchmove") { - eventY1 = e.changedTouches[0].clientY; - } else { - eventY1 = e.clientY; - } - scrollBoxY = getScrollBarDragY(scrollBoxY0, eventY0, eventY1); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - }); - scrollBar.call(scrollBarDrag); - var scrollBoxTouchDrag = d3$t.behavior.drag().on("dragstart", function() { - var e = d3$t.event.sourceEvent; - if (e.type === "touchstart") { - eventY0 = e.changedTouches[0].clientY; - scrollBoxY0 = scrollBoxY; - } - }).on("drag", function() { - var e = d3$t.event.sourceEvent; - if (e.type === "touchmove") { - eventY1 = e.changedTouches[0].clientY; - scrollBoxY = getNaturalDragY(scrollBoxY0, eventY0, eventY1); - scrollHandler(scrollBoxY, scrollBarHeight, scrollRatio); - } - }); - scrollBox.call(scrollBoxTouchDrag); - } - function scrollHandler(scrollBoxY2, scrollBarHeight2, scrollRatio2) { - legendObj._scrollY = gd._fullLayout[legendId]._scrollY = scrollBoxY2; - Drawing$p.setTranslate(scrollBox, 0, -scrollBoxY2); - Drawing$p.setRect( - scrollBar, - legendObj._width, - constants$M.scrollBarMargin + scrollBoxY2 * scrollRatio2, - constants$M.scrollBarWidth, - scrollBarHeight2 - ); - clipPath.select("rect").attr("y", bw + scrollBoxY2); - } - if (gd._context.edits.legendPosition) { - var xf, yf, x0, y0; - legend2.classed("cursor-move", true); - dragElement$6.init({ - element: legend2.node(), - gd, - prepFn: function(e) { - if (e.target === scrollBar.node()) { - return; - } - var transform = Drawing$p.getTranslate(legend2); - x0 = transform.x; - y0 = transform.y; - }, - moveFn: function(dx, dy) { - if (x0 !== void 0 && y0 !== void 0) { - var newX = x0 + dx; - var newY = y0 + dy; - Drawing$p.setTranslate(legend2, newX, newY); - xf = dragElement$6.align(newX, legendObj._width, gs.l, gs.l + gs.w, legendObj.xanchor); - yf = dragElement$6.align(newY + legendObj._height, -legendObj._height, gs.t + gs.h, gs.t, legendObj.yanchor); - } - }, - doneFn: function() { - if (xf !== void 0 && yf !== void 0) { - var obj = {}; - obj[legendId + ".x"] = xf; - obj[legendId + ".y"] = yf; - Registry$D.call("_guiRelayout", gd, obj); - } - }, - clickFn: function(numClicks, e) { - var clickedTrace = layer.selectAll("g.traces").filter(function() { - var bbox = this.getBoundingClientRect(); - return e.clientX >= bbox.left && e.clientX <= bbox.right && e.clientY >= bbox.top && e.clientY <= bbox.bottom; - }); - if (clickedTrace.size() > 0) { - clickOrDoubleClick(gd, legend2, clickedTrace, numClicks, e); - } - } - }); - } - } - ], gd); -} -function getTraceWidth(d, legendObj, textGap) { - var legendItem = d[0]; - var legendWidth = legendItem.width; - var mode = legendObj.entrywidthmode; - var traceLegendWidth = legendItem.trace.legendwidth || legendObj.entrywidth; - if (mode === "fraction") return legendObj._maxWidth * traceLegendWidth; - return textGap + (traceLegendWidth || legendWidth); -} -function clickOrDoubleClick(gd, legend2, legendItem, numClicks, evt) { - var trace = legendItem.data()[0][0].trace; - var evtData = { - event: evt, - node: legendItem.node(), - curveNumber: trace.index, - expandedIndex: trace._expandedIndex, - data: gd.data, - layout: gd.layout, - frames: gd._transitionData._frames, - config: gd._context, - fullData: gd._fullData, - fullLayout: gd._fullLayout - }; - if (trace._group) { - evtData.group = trace._group; - } - if (Registry$D.traceIs(trace, "pie-like")) { - evtData.label = legendItem.datum()[0].label; - } - var clickVal = Events$2.triggerHandler(gd, "plotly_legendclick", evtData); - if (numClicks === 1) { - if (clickVal === false) return; - legend2._clickTimeout = setTimeout(function() { - if (!gd._fullLayout) return; - handleClick2(legendItem, gd, numClicks); - }, gd._context.doubleClickDelay); - } else if (numClicks === 2) { - if (legend2._clickTimeout) clearTimeout(legend2._clickTimeout); - gd._legendMouseDownTime = 0; - var dblClickVal = Events$2.triggerHandler(gd, "plotly_legenddoubleclick", evtData); - if (dblClickVal !== false && clickVal !== false) handleClick2(legendItem, gd, numClicks); - } -} -function drawTexts(g, gd, legendObj) { - var legendId = getId(legendObj); - var legendItem = g.data()[0][0]; - var trace = legendItem.trace; - var isPieLike = Registry$D.traceIs(trace, "pie-like"); - var isEditable = !legendObj._inHover && gd._context.edits.legendText && !isPieLike; - var maxNameLength = legendObj._maxNameLength; - var name2, font2; - if (legendItem.groupTitle) { - name2 = legendItem.groupTitle.text; - font2 = legendItem.groupTitle.font; - } else { - font2 = legendObj.font; - if (!legendObj.entries) { - name2 = isPieLike ? legendItem.label : trace.name; - if (trace._meta) { - name2 = Lib$1z.templateString(name2, trace._meta); - } - } else { - name2 = legendItem.text; - } - } - var textEl = Lib$1z.ensureSingle(g, "text", legendId + "text"); - textEl.attr("text-anchor", "start").call(Drawing$p.font, font2).text(isEditable ? ensureLength(name2, maxNameLength) : name2); - var textGap = legendObj.indentation + legendObj.itemwidth + constants$M.itemGap * 2; - svgTextUtils$c.positionText(textEl, textGap, 0); - if (isEditable) { - textEl.call(svgTextUtils$c.makeEditable, { gd, text: name2 }).call(textLayout, g, gd, legendObj).on("edit", function(newName) { - this.text(ensureLength(newName, maxNameLength)).call(textLayout, g, gd, legendObj); - var fullInput = legendItem.trace._fullInput || {}; - var update2 = {}; - if (Registry$D.hasTransform(fullInput, "groupby")) { - var groupbyIndices = Registry$D.getTransformIndices(fullInput, "groupby"); - var _index = groupbyIndices[groupbyIndices.length - 1]; - var kcont = Lib$1z.keyedContainer(fullInput, "transforms[" + _index + "].styles", "target", "value.name"); - kcont.set(legendItem.trace._group, newName); - update2 = kcont.constructUpdate(); - } else { - update2.name = newName; - } - if (fullInput._isShape) { - return Registry$D.call("_guiRelayout", gd, "shapes[" + trace.index + "].name", update2.name); - } else { - return Registry$D.call("_guiRestyle", gd, update2, trace.index); - } - }); - } else { - textLayout(textEl, g, gd, legendObj); - } -} -function ensureLength(str2, maxLength) { - var targetLength = Math.max(4, maxLength); - if (str2 && str2.trim().length >= targetLength / 2) return str2; - str2 = str2 || ""; - for (var i = targetLength - str2.length; i > 0; i--) str2 += " "; - return str2; -} -function setupTraceToggle(g, gd, legendId) { - var doubleClickDelay = gd._context.doubleClickDelay; - var newMouseDownTime; - var numClicks = 1; - var traceToggle = Lib$1z.ensureSingle(g, "rect", legendId + "toggle", function(s) { - if (!gd._context.staticPlot) { - s.style("cursor", "pointer").attr("pointer-events", "all"); - } - s.call(Color$D.fill, "rgba(0,0,0,0)"); - }); - if (gd._context.staticPlot) return; - traceToggle.on("mousedown", function() { - newMouseDownTime = (/* @__PURE__ */ new Date()).getTime(); - if (newMouseDownTime - gd._legendMouseDownTime < doubleClickDelay) { - numClicks += 1; - } else { - numClicks = 1; - gd._legendMouseDownTime = newMouseDownTime; - } - }); - traceToggle.on("mouseup", function() { - if (gd._dragged || gd._editing) return; - var legend2 = gd._fullLayout[legendId]; - if ((/* @__PURE__ */ new Date()).getTime() - gd._legendMouseDownTime > doubleClickDelay) { - numClicks = Math.max(numClicks - 1, 1); - } - clickOrDoubleClick(gd, legend2, g, numClicks, d3$t.event); - }); -} -function textLayout(s, g, gd, legendObj, aTitle) { - if (legendObj._inHover) s.attr("data-notex", true); - svgTextUtils$c.convertToTspans(s, gd, function() { - computeTextDimensions(g, gd, legendObj, aTitle); - }); -} -function computeTextDimensions(g, gd, legendObj, aTitle) { - var legendItem = g.data()[0][0]; - if (!legendObj._inHover && legendItem && !legendItem.trace.showlegend) { - g.remove(); - return; - } - var mathjaxGroup = g.select("g[class*=math-group]"); - var mathjaxNode = mathjaxGroup.node(); - var legendId = getId(legendObj); - if (!legendObj) { - legendObj = gd._fullLayout[legendId]; - } - var bw = legendObj.borderwidth; - var font2; - if (aTitle === MAIN_TITLE) { - font2 = legendObj.title.font; - } else if (legendItem.groupTitle) { - font2 = legendItem.groupTitle.font; - } else { - font2 = legendObj.font; - } - var lineHeight = font2.size * LINE_SPACING$5; - var height, width; - if (mathjaxNode) { - var mathjaxBB = Drawing$p.bBox(mathjaxNode); - height = mathjaxBB.height; - width = mathjaxBB.width; - if (aTitle === MAIN_TITLE) { - Drawing$p.setTranslate(mathjaxGroup, bw, bw + height * 0.75); - } else { - Drawing$p.setTranslate(mathjaxGroup, 0, height * 0.25); - } - } else { - var cls = "." + legendId + (aTitle === MAIN_TITLE ? "title" : "") + "text"; - var textEl = g.select(cls); - var textLines = svgTextUtils$c.lineCount(textEl); - var textNode = textEl.node(); - height = lineHeight * textLines; - width = textNode ? Drawing$p.bBox(textNode).width : 0; - if (aTitle === MAIN_TITLE) { - if (legendObj.title.side === "left") { - width += constants$M.itemGap * 2; - } - svgTextUtils$c.positionText( - textEl, - bw + constants$M.titlePad, - bw + lineHeight - ); - } else { - var x = constants$M.itemGap * 2 + legendObj.indentation + legendObj.itemwidth; - if (legendItem.groupTitle) { - x = constants$M.itemGap; - width -= legendObj.indentation + legendObj.itemwidth; - } - svgTextUtils$c.positionText( - textEl, - x, - -lineHeight * ((textLines - 1) / 2 - 0.3) - ); - } - } - if (aTitle === MAIN_TITLE) { - legendObj._titleWidth = width; - legendObj._titleHeight = height; - } else { - legendItem.lineHeight = lineHeight; - legendItem.height = Math.max(height, 16) + 3; - legendItem.width = width; - } -} -function getTitleSize(legendObj) { - var w = 0; - var h = 0; - var side = legendObj.title.side; - if (side) { - if (side.indexOf("left") !== -1) { - w = legendObj._titleWidth; - } - if (side.indexOf("top") !== -1) { - h = legendObj._titleHeight; - } - } - return [w, h]; -} -function computeLegendDimensions(gd, groups, traces, legendObj) { - var fullLayout = gd._fullLayout; - var legendId = getId(legendObj); - if (!legendObj) { - legendObj = fullLayout[legendId]; - } - var gs = fullLayout._size; - var isVertical2 = helpers$E.isVertical(legendObj); - var isGrouped2 = helpers$E.isGrouped(legendObj); - var isFraction = legendObj.entrywidthmode === "fraction"; - var bw = legendObj.borderwidth; - var bw2 = 2 * bw; - var itemGap = constants$M.itemGap; - var textGap = legendObj.indentation + legendObj.itemwidth + itemGap * 2; - var endPad = 2 * (bw + itemGap); - var yanchor = getYanchor(legendObj); - var isBelowPlotArea = legendObj.y < 0 || legendObj.y === 0 && yanchor === "top"; - var isAbovePlotArea = legendObj.y > 1 || legendObj.y === 1 && yanchor === "bottom"; - var traceGroupGap = legendObj.tracegroupgap; - var legendGroupWidths = {}; - legendObj._maxHeight = Math.max( - isBelowPlotArea || isAbovePlotArea ? fullLayout.height / 2 : gs.h, - 30 - ); - var toggleRectWidth = 0; - legendObj._width = 0; - legendObj._height = 0; - var titleSize = getTitleSize(legendObj); - if (isVertical2) { - traces.each(function(d) { - var h = d[0].height; - Drawing$p.setTranslate( - this, - bw + titleSize[0], - bw + titleSize[1] + legendObj._height + h / 2 + itemGap - ); - legendObj._height += h; - legendObj._width = Math.max(legendObj._width, d[0].width); - }); - toggleRectWidth = textGap + legendObj._width; - legendObj._width += itemGap + textGap + bw2; - legendObj._height += endPad; - if (isGrouped2) { - groups.each(function(d, i) { - Drawing$p.setTranslate(this, 0, i * legendObj.tracegroupgap); - }); - legendObj._height += (legendObj._lgroupsLength - 1) * legendObj.tracegroupgap; - } - } else { - var xanchor = getXanchor(legendObj); - var isLeftOfPlotArea = legendObj.x < 0 || legendObj.x === 0 && xanchor === "right"; - var isRightOfPlotArea = legendObj.x > 1 || legendObj.x === 1 && xanchor === "left"; - var isBeyondPlotAreaY = isAbovePlotArea || isBelowPlotArea; - var hw = fullLayout.width / 2; - legendObj._maxWidth = Math.max( - isLeftOfPlotArea ? isBeyondPlotAreaY && xanchor === "left" ? gs.l + gs.w : hw : isRightOfPlotArea ? isBeyondPlotAreaY && xanchor === "right" ? gs.r + gs.w : hw : gs.w, - 2 * textGap - ); - var maxItemWidth = 0; - var combinedItemWidth = 0; - traces.each(function(d) { - var w = getTraceWidth(d, legendObj, textGap); - maxItemWidth = Math.max(maxItemWidth, w); - combinedItemWidth += w; - }); - toggleRectWidth = null; - var maxRowWidth = 0; - if (isGrouped2) { - var maxGroupHeightInRow = 0; - var groupOffsetX = 0; - var groupOffsetY = 0; - groups.each(function() { - var maxWidthInGroup = 0; - var offsetY2 = 0; - d3$t.select(this).selectAll("g.traces").each(function(d) { - var w = getTraceWidth(d, legendObj, textGap); - var h = d[0].height; - Drawing$p.setTranslate( - this, - titleSize[0], - titleSize[1] + bw + itemGap + h / 2 + offsetY2 - ); - offsetY2 += h; - maxWidthInGroup = Math.max(maxWidthInGroup, w); - legendGroupWidths[d[0].trace.legendgroup] = maxWidthInGroup; - }); - var next = maxWidthInGroup + itemGap; - if ( - // not on the first column already - groupOffsetX > 0 && // goes beyound limit - next + bw + groupOffsetX > legendObj._maxWidth - ) { - maxRowWidth = Math.max(maxRowWidth, groupOffsetX); - groupOffsetX = 0; - groupOffsetY += maxGroupHeightInRow + traceGroupGap; - maxGroupHeightInRow = offsetY2; - } else { - maxGroupHeightInRow = Math.max(maxGroupHeightInRow, offsetY2); - } - Drawing$p.setTranslate(this, groupOffsetX, groupOffsetY); - groupOffsetX += next; - }); - legendObj._width = Math.max(maxRowWidth, groupOffsetX) + bw; - legendObj._height = groupOffsetY + maxGroupHeightInRow + endPad; - } else { - var nTraces = traces.size(); - var oneRowLegend = combinedItemWidth + bw2 + (nTraces - 1) * itemGap < legendObj._maxWidth; - var maxItemHeightInRow = 0; - var offsetX = 0; - var offsetY = 0; - var rowWidth = 0; - traces.each(function(d) { - var h = d[0].height; - var w = getTraceWidth(d, legendObj, textGap); - var next = oneRowLegend ? w : maxItemWidth; - if (!isFraction) { - next += itemGap; - } - if (next + bw + offsetX - itemGap >= legendObj._maxWidth) { - maxRowWidth = Math.max(maxRowWidth, rowWidth); - offsetX = 0; - offsetY += maxItemHeightInRow; - legendObj._height += maxItemHeightInRow; - maxItemHeightInRow = 0; - } - Drawing$p.setTranslate( - this, - titleSize[0] + bw + offsetX, - titleSize[1] + bw + offsetY + h / 2 + itemGap - ); - rowWidth = offsetX + w + itemGap; - offsetX += next; - maxItemHeightInRow = Math.max(maxItemHeightInRow, h); - }); - if (oneRowLegend) { - legendObj._width = offsetX + bw2; - legendObj._height = maxItemHeightInRow + endPad; - } else { - legendObj._width = Math.max(maxRowWidth, rowWidth) + bw2; - legendObj._height += maxItemHeightInRow + endPad; - } - } - } - legendObj._width = Math.ceil( - Math.max( - legendObj._width + titleSize[0], - legendObj._titleWidth + 2 * (bw + constants$M.titlePad) - ) - ); - legendObj._height = Math.ceil( - Math.max( - legendObj._height + titleSize[1], - legendObj._titleHeight + 2 * (bw + constants$M.itemGap) - ) - ); - legendObj._effHeight = Math.min(legendObj._height, legendObj._maxHeight); - var edits = gd._context.edits; - var isEditable = edits.legendText || edits.legendPosition; - traces.each(function(d) { - var traceToggle = d3$t.select(this).select("." + legendId + "toggle"); - var h = d[0].height; - var legendgroup = d[0].trace.legendgroup; - var traceWidth = getTraceWidth(d, legendObj, textGap); - if (isGrouped2 && legendgroup !== "") { - traceWidth = legendGroupWidths[legendgroup]; - } - var w = isEditable ? textGap : toggleRectWidth || traceWidth; - if (!isVertical2 && !isFraction) { - w += itemGap / 2; - } - Drawing$p.setRect(traceToggle, 0, -h / 2, w, h); - }); -} -function expandMargin(gd, legendId, lx, ly) { - var fullLayout = gd._fullLayout; - var legendObj = fullLayout[legendId]; - var xanchor = getXanchor(legendObj); - var yanchor = getYanchor(legendObj); - var isPaperX = legendObj.xref === "paper"; - var isPaperY = legendObj.yref === "paper"; - gd._fullLayout._reservedMargin[legendId] = {}; - var sideY = legendObj.y < 0.5 ? "b" : "t"; - var sideX = legendObj.x < 0.5 ? "l" : "r"; - var possibleReservedMargins = { - r: fullLayout.width - lx, - l: lx + legendObj._width, - b: fullLayout.height - ly, - t: ly + legendObj._effHeight - }; - if (isPaperX && isPaperY) { - return Plots$a.autoMargin(gd, legendId, { - x: legendObj.x, - y: legendObj.y, - l: legendObj._width * FROM_TL$4[xanchor], - r: legendObj._width * FROM_BR$3[xanchor], - b: legendObj._effHeight * FROM_BR$3[yanchor], - t: legendObj._effHeight * FROM_TL$4[yanchor] - }); - } else if (isPaperX) { - gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY]; - } else if (isPaperY) { - gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX]; - } else { - if (legendObj.orientation === "v") { - gd._fullLayout._reservedMargin[legendId][sideX] = possibleReservedMargins[sideX]; - } else { - gd._fullLayout._reservedMargin[legendId][sideY] = possibleReservedMargins[sideY]; - } - } -} -function getXanchor(legendObj) { - return Lib$1z.isRightAnchor(legendObj) ? "right" : Lib$1z.isCenterAnchor(legendObj) ? "center" : "left"; -} -function getYanchor(legendObj) { - return Lib$1z.isBottomAnchor(legendObj) ? "bottom" : Lib$1z.isMiddleAnchor(legendObj) ? "middle" : "top"; -} -function getId(legendObj) { - return legendObj._id || "legend"; -} -var d3$s = d3Exports; -var isNumeric$i = fastIsnumeric; -var tinycolor$3 = tinycolorExports; -var Lib$1y = libExports; -var pushUnique2 = Lib$1y.pushUnique; -var strTranslate$8 = Lib$1y.strTranslate; -var strRotate$1 = Lib$1y.strRotate; -var Events$1 = events; -var svgTextUtils$b = svg_text_utils; -var overrideCursor2 = override_cursor; -var Drawing$o = drawingExports; -var Color$C = colorExports; -var dragElement$5 = dragelementExports; -var Axes$l = axesExports; -var zindexSeparator$1 = constants$U.zindexSeparator; -var Registry$C = registry; -var helpers$D = helpers$J; -var constants$L = constants$W; -var legendSupplyDefaults = defaults$m; -var legendDraw = draw$d; -var YANGLE = constants$L.YANGLE; -var YA_RADIANS = Math.PI * YANGLE / 180; -var YFACTOR = 1 / Math.sin(YA_RADIANS); -var YSHIFTX = Math.cos(YA_RADIANS); -var YSHIFTY = Math.sin(YA_RADIANS); -var HOVERARROWSIZE = constants$L.HOVERARROWSIZE; -var HOVERTEXTPAD = constants$L.HOVERTEXTPAD; -var multipleHoverPoints = { - box: true, - ohlc: true, - violin: true, - candlestick: true -}; -var cartesianScatterPoints = { - scatter: true, - scattergl: true, - splom: true -}; -function distanceSort(a, b) { - return a.distance - b.distance; -} -hover$7.hover = function hover(gd, evt, subplot, noHoverEvent) { - gd = Lib$1y.getGraphDiv(gd); - var eventTarget = evt.target; - Lib$1y.throttle( - gd._fullLayout._uid + constants$L.HOVERID, - constants$L.HOVERMINTIME, - function() { - _hover(gd, evt, subplot, noHoverEvent, eventTarget); - } - ); -}; -hover$7.loneHover = function loneHover(hoverItems, opts) { - var multiHover = true; - if (!Array.isArray(hoverItems)) { - multiHover = false; - hoverItems = [hoverItems]; - } - var gd = opts.gd; - var gTop = getTopOffset(gd); - var gLeft = getLeftOffset(gd); - var pointsData = hoverItems.map(function(hoverItem) { - var _x0 = hoverItem._x0 || hoverItem.x0 || hoverItem.x || 0; - var _x1 = hoverItem._x1 || hoverItem.x1 || hoverItem.x || 0; - var _y0 = hoverItem._y0 || hoverItem.y0 || hoverItem.y || 0; - var _y1 = hoverItem._y1 || hoverItem.y1 || hoverItem.y || 0; - var eventData5 = hoverItem.eventData; - if (eventData5) { - var x0 = Math.min(_x0, _x1); - var x1 = Math.max(_x0, _x1); - var y0 = Math.min(_y0, _y1); - var y1 = Math.max(_y0, _y1); - var trace = hoverItem.trace; - if (Registry$C.traceIs(trace, "gl3d")) { - var container = gd._fullLayout[trace.scene]._scene.container; - var dx = container.offsetLeft; - var dy = container.offsetTop; - x0 += dx; - x1 += dx; - y0 += dy; - y1 += dy; - } - eventData5.bbox = { - x0: x0 + gLeft, - x1: x1 + gLeft, - y0: y0 + gTop, - y1: y1 + gTop - }; - if (opts.inOut_bbox) { - opts.inOut_bbox.push(eventData5.bbox); - } - } else { - eventData5 = false; - } - return { - color: hoverItem.color || Color$C.defaultLine, - x0: hoverItem.x0 || hoverItem.x || 0, - x1: hoverItem.x1 || hoverItem.x || 0, - y0: hoverItem.y0 || hoverItem.y || 0, - y1: hoverItem.y1 || hoverItem.y || 0, - xLabel: hoverItem.xLabel, - yLabel: hoverItem.yLabel, - zLabel: hoverItem.zLabel, - text: hoverItem.text, - name: hoverItem.name, - idealAlign: hoverItem.idealAlign, - // optional extra bits of styling - borderColor: hoverItem.borderColor, - fontFamily: hoverItem.fontFamily, - fontSize: hoverItem.fontSize, - fontColor: hoverItem.fontColor, - fontWeight: hoverItem.fontWeight, - fontStyle: hoverItem.fontStyle, - fontVariant: hoverItem.fontVariant, - nameLength: hoverItem.nameLength, - textAlign: hoverItem.textAlign, - // filler to make createHoverText happy - trace: hoverItem.trace || { - index: 0, - hoverinfo: "" - }, - xa: { _offset: 0 }, - ya: { _offset: 0 }, - index: 0, - hovertemplate: hoverItem.hovertemplate || false, - hovertemplateLabels: hoverItem.hovertemplateLabels || false, - eventData: eventData5 - }; - }); - var rotateLabels = false; - var hoverText = createHoverText(pointsData, { - gd, - hovermode: "closest", - rotateLabels, - bgColor: opts.bgColor || Color$C.background, - container: d3$s.select(opts.container), - outerContainer: opts.outerContainer || opts.container - }); - var hoverLabel = hoverText.hoverLabels; - var tooltipSpacing = 5; - var lastBottomY = 0; - var anchor = 0; - hoverLabel.sort(function(a, b) { - return a.y0 - b.y0; - }).each(function(d, i) { - var topY = d.y0 - d.by / 2; - if (topY - tooltipSpacing < lastBottomY) { - d.offset = lastBottomY - topY + tooltipSpacing; - } else { - d.offset = 0; - } - lastBottomY = topY + d.by + d.offset; - if (i === opts.anchorIndex || 0) anchor = d.offset; - }).each(function(d) { - d.offset -= anchor; - }); - var scaleX = gd._fullLayout._invScaleX; - var scaleY = gd._fullLayout._invScaleY; - alignHoverText(hoverLabel, rotateLabels, scaleX, scaleY); - return multiHover ? hoverLabel : hoverLabel.node(); -}; -function _hover(gd, evt, subplot, noHoverEvent, eventTarget) { - if (!subplot) subplot = "xy"; - if (typeof subplot === "string") { - subplot = subplot.split(zindexSeparator$1)[0]; - } - var subplots = Array.isArray(subplot) ? subplot : [subplot]; - var spId; - var fullLayout = gd._fullLayout; - var hoversubplots = fullLayout.hoversubplots; - var plots2 = fullLayout._plots || []; - var plotinfo = plots2[subplot]; - var hasCartesian = fullLayout._has("cartesian"); - var hovermode = evt.hovermode || fullLayout.hovermode; - var hovermodeHasX = (hovermode || "").charAt(0) === "x"; - var hovermodeHasY = (hovermode || "").charAt(0) === "y"; - var firstXaxis; - var firstYaxis; - if (hasCartesian && (hovermodeHasX || hovermodeHasY) && hoversubplots === "axis") { - var subplotsLength = subplots.length; - for (var p = 0; p < subplotsLength; p++) { - spId = subplots[p]; - if (plots2[spId]) { - firstXaxis = Axes$l.getFromId(gd, spId, "x"); - firstYaxis = Axes$l.getFromId(gd, spId, "y"); - var subplotsWith = (hovermodeHasX ? firstXaxis : firstYaxis)._subplotsWith; - if (subplotsWith && subplotsWith.length) { - for (var q = 0; q < subplotsWith.length; q++) { - pushUnique2(subplots, subplotsWith[q]); - } - } - } - } - } - if (plotinfo && hoversubplots !== "single") { - var overlayedSubplots = plotinfo.overlays.map(function(pi) { - return pi.id; - }); - subplots = subplots.concat(overlayedSubplots); - } - var len = subplots.length; - var xaArray = new Array(len); - var yaArray = new Array(len); - var supportsCompare = false; - for (var i = 0; i < len; i++) { - spId = subplots[i]; - if (plots2[spId]) { - supportsCompare = true; - xaArray[i] = plots2[spId].xaxis; - yaArray[i] = plots2[spId].yaxis; - } else if (fullLayout[spId] && fullLayout[spId]._subplot) { - var _subplot = fullLayout[spId]._subplot; - xaArray[i] = _subplot.xaxis; - yaArray[i] = _subplot.yaxis; - } else { - Lib$1y.warn("Unrecognized subplot: " + spId); - return; - } - } - if (hovermode && !supportsCompare) hovermode = "closest"; - if (["x", "y", "closest", "x unified", "y unified"].indexOf(hovermode) === -1 || !gd.calcdata || gd.querySelector(".zoombox") || gd._dragging) { - return dragElement$5.unhoverRaw(gd, evt); - } - var hoverdistance = fullLayout.hoverdistance; - if (hoverdistance === -1) hoverdistance = Infinity; - var spikedistance = fullLayout.spikedistance; - if (spikedistance === -1) spikedistance = Infinity; - var hoverData = []; - var searchData = []; - var xvalArray, yvalArray; - var itemnum, curvenum, cd, trace, subplotId, subploti, _mode, xval, yval, pointData, closedataPreviousLength; - var spikePoints = { - hLinePoint: null, - vLinePoint: null - }; - var hasOneHorizontalTrace = false; - if (Array.isArray(evt)) { - hovermode = "array"; - for (itemnum = 0; itemnum < evt.length; itemnum++) { - cd = gd.calcdata[evt[itemnum].curveNumber || 0]; - if (cd) { - trace = cd[0].trace; - if (cd[0].trace.hoverinfo !== "skip") { - searchData.push(cd); - if (trace.orientation === "h") { - hasOneHorizontalTrace = true; - } - } - } - } - } else { - var zorderedCalcdata = gd.calcdata.slice(); - zorderedCalcdata.sort(function(a, b) { - var aZorder = a[0].trace.zorder || 0; - var bZorder = b[0].trace.zorder || 0; - return aZorder - bZorder; - }); - for (curvenum = 0; curvenum < zorderedCalcdata.length; curvenum++) { - cd = zorderedCalcdata[curvenum]; - trace = cd[0].trace; - if (trace.hoverinfo !== "skip" && helpers$D.isTraceInSubplots(trace, subplots)) { - searchData.push(cd); - if (trace.orientation === "h") { - hasOneHorizontalTrace = true; - } - } - } - var hasUserCalledHover = !eventTarget; - var xpx, ypx; - if (hasUserCalledHover) { - if ("xpx" in evt) xpx = evt.xpx; - else xpx = xaArray[0]._length / 2; - if ("ypx" in evt) ypx = evt.ypx; - else ypx = yaArray[0]._length / 2; - } else { - if (Events$1.triggerHandler(gd, "plotly_beforehover", evt) === false) { - return; - } - var dbb = eventTarget.getBoundingClientRect(); - xpx = evt.clientX - dbb.left; - ypx = evt.clientY - dbb.top; - fullLayout._calcInverseTransform(gd); - var transformedCoords = Lib$1y.apply3DTransform(fullLayout._invTransform)(xpx, ypx); - xpx = transformedCoords[0]; - ypx = transformedCoords[1]; - if (xpx < 0 || xpx > xaArray[0]._length || ypx < 0 || ypx > yaArray[0]._length) { - return dragElement$5.unhoverRaw(gd, evt); - } - } - evt.pointerX = xpx + xaArray[0]._offset; - evt.pointerY = ypx + yaArray[0]._offset; - if ("xval" in evt) xvalArray = helpers$D.flat(subplots, evt.xval); - else xvalArray = helpers$D.p2c(xaArray, xpx); - if ("yval" in evt) yvalArray = helpers$D.flat(subplots, evt.yval); - else yvalArray = helpers$D.p2c(yaArray, ypx); - if (!isNumeric$i(xvalArray[0]) || !isNumeric$i(yvalArray[0])) { - Lib$1y.warn("Fx.hover failed", evt, gd); - return dragElement$5.unhoverRaw(gd, evt); - } - } - var distance = Infinity; - function findHoverPoints(customXVal, customYVal) { - for (curvenum = 0; curvenum < searchData.length; curvenum++) { - cd = searchData[curvenum]; - if (!cd || !cd[0] || !cd[0].trace) continue; - trace = cd[0].trace; - if (trace.visible !== true || trace._length === 0) continue; - if (["carpet", "contourcarpet"].indexOf(trace._module.name) !== -1) continue; - _mode = hovermode; - if (helpers$D.isUnifiedHover(_mode)) { - _mode = _mode.charAt(0); - } - if (trace.type === "splom") { - subploti = 0; - subplotId = subplots[subploti]; - } else { - subplotId = helpers$D.getSubplot(trace); - subploti = subplots.indexOf(subplotId); - } - pointData = { - // trace properties - cd, - trace, - xa: xaArray[subploti], - ya: yaArray[subploti], - // max distances for hover and spikes - for points that want to show but do not - // want to override other points, set distance/spikeDistance equal to max*Distance - // and it will not get filtered out but it will be guaranteed to have a greater - // distance than any point that calculated a real distance. - maxHoverDistance: hoverdistance, - maxSpikeDistance: spikedistance, - // point properties - override all of these - index: false, - // point index in trace - only used by plotly.js hoverdata consumers - distance: Math.min(distance, hoverdistance), - // pixel distance or pseudo-distance - // distance/pseudo-distance for spikes. This distance should always be calculated - // as if in "closest" mode, and should only be set if this point should - // generate a spike. - spikeDistance: Infinity, - // in some cases the spikes have different positioning from the hover label - // they don't need x0/x1, just one position - xSpike: void 0, - ySpike: void 0, - // where and how to display the hover label - color: Color$C.defaultLine, - // trace color - name: trace.name, - x0: void 0, - x1: void 0, - y0: void 0, - y1: void 0, - xLabelVal: void 0, - yLabelVal: void 0, - zLabelVal: void 0, - text: void 0 - }; - if (fullLayout[subplotId]) { - pointData.subplot = fullLayout[subplotId]._subplot; - } - if (fullLayout._splomScenes && fullLayout._splomScenes[trace.uid]) { - pointData.scene = fullLayout._splomScenes[trace.uid]; - } - if (_mode === "array") { - var selection = evt[curvenum]; - if ("pointNumber" in selection) { - pointData.index = selection.pointNumber; - _mode = "closest"; - } else { - _mode = ""; - if ("xval" in selection) { - xval = selection.xval; - _mode = "x"; - } - if ("yval" in selection) { - yval = selection.yval; - _mode = _mode ? "closest" : "y"; - } - } - } else if (customXVal !== void 0 && customYVal !== void 0) { - xval = customXVal; - yval = customYVal; - } else { - xval = xvalArray[subploti]; - yval = yvalArray[subploti]; - } - closedataPreviousLength = hoverData.length; - if (hoverdistance !== 0) { - if (trace._module && trace._module.hoverPoints) { - var newPoints = trace._module.hoverPoints(pointData, xval, yval, _mode, { - finiteRange: true, - hoverLayer: fullLayout._hoverlayer, - // options for splom when hovering on same axis - hoversubplots, - gd - }); - if (newPoints) { - var newPoint; - for (var newPointNum = 0; newPointNum < newPoints.length; newPointNum++) { - newPoint = newPoints[newPointNum]; - if (isNumeric$i(newPoint.x0) && isNumeric$i(newPoint.y0)) { - hoverData.push(cleanPoint(newPoint, hovermode)); - } - } - } - } else { - Lib$1y.log("Unrecognized trace type in hover:", trace); - } - } - if (hovermode === "closest" && hoverData.length > closedataPreviousLength) { - hoverData.splice(0, closedataPreviousLength); - distance = hoverData[0].distance; - } - if (hasCartesian && spikedistance !== 0) { - if (hoverData.length === 0) { - pointData.distance = spikedistance; - pointData.index = false; - var closestPoints = trace._module.hoverPoints(pointData, xval, yval, "closest", { - hoverLayer: fullLayout._hoverlayer - }); - if (closestPoints) { - closestPoints = closestPoints.filter(function(point) { - return point.spikeDistance <= spikedistance; - }); - } - if (closestPoints && closestPoints.length) { - var tmpPoint; - var closestVPoints = closestPoints.filter(function(point) { - return point.xa.showspikes && point.xa.spikesnap !== "hovered data"; - }); - if (closestVPoints.length) { - var closestVPt = closestVPoints[0]; - if (isNumeric$i(closestVPt.x0) && isNumeric$i(closestVPt.y0)) { - tmpPoint = fillSpikePoint(closestVPt); - if (!spikePoints.vLinePoint || spikePoints.vLinePoint.spikeDistance > tmpPoint.spikeDistance) { - spikePoints.vLinePoint = tmpPoint; - } - } - } - var closestHPoints = closestPoints.filter(function(point) { - return point.ya.showspikes && point.ya.spikesnap !== "hovered data"; - }); - if (closestHPoints.length) { - var closestHPt = closestHPoints[0]; - if (isNumeric$i(closestHPt.x0) && isNumeric$i(closestHPt.y0)) { - tmpPoint = fillSpikePoint(closestHPt); - if (!spikePoints.hLinePoint || spikePoints.hLinePoint.spikeDistance > tmpPoint.spikeDistance) { - spikePoints.hLinePoint = tmpPoint; - } - } - } - } - } - } - } - } - findHoverPoints(); - function selectClosestPoint(pointsData, spikedistance2, spikeOnWinning2) { - var resultPoint = null; - var minDistance = Infinity; - var thisSpikeDistance; - for (var i2 = 0; i2 < pointsData.length; i2++) { - if (firstXaxis && firstXaxis._id !== pointsData[i2].xa._id) continue; - if (firstYaxis && firstYaxis._id !== pointsData[i2].ya._id) continue; - thisSpikeDistance = pointsData[i2].spikeDistance; - if (spikeOnWinning2 && i2 === 0) thisSpikeDistance = -Infinity; - if (thisSpikeDistance <= minDistance && thisSpikeDistance <= spikedistance2) { - resultPoint = pointsData[i2]; - minDistance = thisSpikeDistance; - } - } - return resultPoint; - } - function fillSpikePoint(point) { - if (!point) return null; - return { - xa: point.xa, - ya: point.ya, - x: point.xSpike !== void 0 ? point.xSpike : (point.x0 + point.x1) / 2, - y: point.ySpike !== void 0 ? point.ySpike : (point.y0 + point.y1) / 2, - distance: point.distance, - spikeDistance: point.spikeDistance, - curveNumber: point.trace.index, - color: point.color, - pointNumber: point.index - }; - } - var spikelineOpts = { - fullLayout, - container: fullLayout._hoverlayer, - event: evt - }; - gd._spikepoints; - var newspikepoints = { - vLinePoint: spikePoints.vLinePoint, - hLinePoint: spikePoints.hLinePoint - }; - gd._spikepoints = newspikepoints; - var sortHoverData = function() { - var hoverDataInSubplot = hoverData.filter(function(a) { - return firstXaxis && firstXaxis._id === a.xa._id && (firstYaxis && firstYaxis._id === a.ya._id); - }); - var hoverDataOutSubplot = hoverData.filter(function(a) { - return !(firstXaxis && firstXaxis._id === a.xa._id && (firstYaxis && firstYaxis._id === a.ya._id)); - }); - hoverDataInSubplot.sort(distanceSort); - hoverDataOutSubplot.sort(distanceSort); - hoverData = hoverDataInSubplot.concat(hoverDataOutSubplot); - hoverData = orderRangePoints(hoverData, hovermode); - }; - sortHoverData(); - var axLetter = hovermode.charAt(0); - var spikeOnWinning = (axLetter === "x" || axLetter === "y") && hoverData[0] && cartesianScatterPoints[hoverData[0].trace.type]; - if (hasCartesian && spikedistance !== 0) { - if (hoverData.length !== 0) { - var tmpHPointData = hoverData.filter(function(point) { - return point.ya.showspikes; - }); - var tmpHPoint = selectClosestPoint(tmpHPointData, spikedistance, spikeOnWinning); - spikePoints.hLinePoint = fillSpikePoint(tmpHPoint); - var tmpVPointData = hoverData.filter(function(point) { - return point.xa.showspikes; - }); - var tmpVPoint = selectClosestPoint(tmpVPointData, spikedistance, spikeOnWinning); - spikePoints.vLinePoint = fillSpikePoint(tmpVPoint); - } - } - if (hoverData.length === 0) { - var result = dragElement$5.unhoverRaw(gd, evt); - if (hasCartesian && (spikePoints.hLinePoint !== null || spikePoints.vLinePoint !== null)) { - if (spikesChanged()) { - createSpikelines(gd, spikePoints, spikelineOpts); - } - } - return result; - } - if (hasCartesian) { - if (spikesChanged()) { - createSpikelines(gd, spikePoints, spikelineOpts); - } - } - if (helpers$D.isXYhover(_mode) && hoverData[0].length !== 0 && hoverData[0].trace.type !== "splom") { - var winningPoint = hoverData[0]; - if (multipleHoverPoints[winningPoint.trace.type]) { - hoverData = hoverData.filter(function(d) { - return d.trace.index === winningPoint.trace.index; - }); - } else { - hoverData = [winningPoint]; - } - var initLen = hoverData.length; - var winX = getCoord("x", winningPoint, fullLayout); - var winY = getCoord("y", winningPoint, fullLayout); - findHoverPoints(winX, winY); - var finalPoints = []; - var seen = {}; - var id = 0; - var insert = function(newHd) { - var key = multipleHoverPoints[newHd.trace.type] ? hoverDataKey(newHd) : newHd.trace.index; - if (!seen[key]) { - id++; - seen[key] = id; - finalPoints.push(newHd); - } else { - var oldId = seen[key] - 1; - var oldHd = finalPoints[oldId]; - if (oldId > 0 && Math.abs(newHd.distance) < Math.abs(oldHd.distance)) { - finalPoints[oldId] = newHd; - } - } - }; - var k; - for (k = 0; k < initLen; k++) { - insert(hoverData[k]); - } - for (k = hoverData.length - 1; k > initLen - 1; k--) { - insert(hoverData[k]); - } - hoverData = finalPoints; - sortHoverData(); - } - var oldhoverdata = gd._hoverdata; - var newhoverdata = []; - var gTop = getTopOffset(gd); - var gLeft = getLeftOffset(gd); - for (itemnum = 0; itemnum < hoverData.length; itemnum++) { - var pt = hoverData[itemnum]; - var eventData5 = helpers$D.makeEventData(pt, pt.trace, pt.cd); - if (pt.hovertemplate !== false) { - var ht = false; - if (pt.cd[pt.index] && pt.cd[pt.index].ht) { - ht = pt.cd[pt.index].ht; - } - pt.hovertemplate = ht || pt.trace.hovertemplate || false; - } - if (pt.xa && pt.ya) { - var _x0 = pt.x0 + pt.xa._offset; - var _x1 = pt.x1 + pt.xa._offset; - var _y0 = pt.y0 + pt.ya._offset; - var _y1 = pt.y1 + pt.ya._offset; - var x0 = Math.min(_x0, _x1); - var x1 = Math.max(_x0, _x1); - var y0 = Math.min(_y0, _y1); - var y1 = Math.max(_y0, _y1); - eventData5.bbox = { - x0: x0 + gLeft, - x1: x1 + gLeft, - y0: y0 + gTop, - y1: y1 + gTop - }; - } - pt.eventData = [eventData5]; - newhoverdata.push(eventData5); - } - gd._hoverdata = newhoverdata; - var rotateLabels = hovermode === "y" && (searchData.length > 1 || hoverData.length > 1) || hovermode === "closest" && hasOneHorizontalTrace && hoverData.length > 1; - var bgColor = Color$C.combine( - fullLayout.plot_bgcolor || Color$C.background, - fullLayout.paper_bgcolor - ); - var hoverText = createHoverText(hoverData, { - gd, - hovermode, - rotateLabels, - bgColor, - container: fullLayout._hoverlayer, - outerContainer: fullLayout._paper.node(), - commonLabelOpts: fullLayout.hoverlabel, - hoverdistance: fullLayout.hoverdistance - }); - var hoverLabels = hoverText.hoverLabels; - if (!helpers$D.isUnifiedHover(hovermode)) { - hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, hoverText.commonLabelBoundingBox); - alignHoverText(hoverLabels, rotateLabels, fullLayout._invScaleX, fullLayout._invScaleY); - } - if (eventTarget && eventTarget.tagName) { - var hasClickToShow2 = Registry$C.getComponentMethod("annotations", "hasClickToShow")(gd, newhoverdata); - overrideCursor2(d3$s.select(eventTarget), hasClickToShow2 ? "pointer" : ""); - } - if (!eventTarget || noHoverEvent || !hoverChanged(gd, evt, oldhoverdata)) return; - if (oldhoverdata) { - gd.emit("plotly_unhover", { - event: evt, - points: oldhoverdata - }); - } - gd.emit("plotly_hover", { - event: evt, - points: gd._hoverdata, - xaxes: xaArray, - yaxes: yaArray, - xvals: xvalArray, - yvals: yvalArray - }); -} -function hoverDataKey(d) { - return [d.trace.index, d.index, d.x0, d.y0, d.name, d.attr, d.xa ? d.xa._id : "", d.ya ? d.ya._id : ""].join(","); -} -var EXTRA_STRING_REGEX = /([\s\S]*)<\/extra>/; -function createHoverText(hoverData, opts) { - var gd = opts.gd; - var fullLayout = gd._fullLayout; - var hovermode = opts.hovermode; - var rotateLabels = opts.rotateLabels; - var bgColor = opts.bgColor; - var container = opts.container; - var outerContainer = opts.outerContainer; - var commonLabelOpts = opts.commonLabelOpts || {}; - if (hoverData.length === 0) return [[]]; - var fontFamily = opts.fontFamily || constants$L.HOVERFONT; - var fontSize = opts.fontSize || constants$L.HOVERFONTSIZE; - var fontWeight = opts.fontWeight || fullLayout.font.weight; - var fontStyle = opts.fontStyle || fullLayout.font.style; - var fontVariant = opts.fontVariant || fullLayout.font.variant; - var fontTextcase = opts.fontTextcase || fullLayout.font.textcase; - var fontLineposition = opts.fontLineposition || fullLayout.font.lineposition; - var fontShadow = opts.fontShadow || fullLayout.font.shadow; - var c0 = hoverData[0]; - var xa = c0.xa; - var ya = c0.ya; - var axLetter = hovermode.charAt(0); - var axLabel = axLetter + "Label"; - var t02 = c0[axLabel]; - if (t02 === void 0 && xa.type === "multicategory") { - for (var q = 0; q < hoverData.length; q++) { - t02 = hoverData[q][axLabel]; - if (t02 !== void 0) break; - } - } - var outerContainerBB = getBoundingClientRect(gd, outerContainer); - var outerTop = outerContainerBB.top; - var outerWidth = outerContainerBB.width; - var outerHeight = outerContainerBB.height; - var showCommonLabel = t02 !== void 0 && c0.distance <= opts.hoverdistance && (hovermode === "x" || hovermode === "y"); - if (showCommonLabel) { - var allHaveZ = true; - var i, traceHoverinfo; - for (i = 0; i < hoverData.length; i++) { - if (allHaveZ && hoverData[i].zLabel === void 0) allHaveZ = false; - traceHoverinfo = hoverData[i].hoverinfo || hoverData[i].trace.hoverinfo; - if (traceHoverinfo) { - var parts = Array.isArray(traceHoverinfo) ? traceHoverinfo : traceHoverinfo.split("+"); - if (parts.indexOf("all") === -1 && parts.indexOf(hovermode) === -1) { - showCommonLabel = false; - break; - } - } - } - if (allHaveZ) showCommonLabel = false; - } - var commonLabel = container.selectAll("g.axistext").data(showCommonLabel ? [0] : []); - commonLabel.enter().append("g").classed("axistext", true); - commonLabel.exit().remove(); - var commonLabelRect = { - minX: 0, - maxX: 0, - minY: 0, - maxY: 0 - }; - commonLabel.each(function() { - var label = d3$s.select(this); - var lpath = Lib$1y.ensureSingle(label, "path", "", function(s) { - s.style({ "stroke-width": "1px" }); - }); - var ltext = Lib$1y.ensureSingle(label, "text", "", function(s) { - s.attr("data-notex", 1); - }); - var commonBgColor = commonLabelOpts.bgcolor || Color$C.defaultLine; - var commonStroke = commonLabelOpts.bordercolor || Color$C.contrast(commonBgColor); - var contrastColor = Color$C.contrast(commonBgColor); - var commonLabelOptsFont = commonLabelOpts.font; - var commonLabelFont = { - weight: commonLabelOptsFont.weight || fontWeight, - style: commonLabelOptsFont.style || fontStyle, - variant: commonLabelOptsFont.variant || fontVariant, - textcase: commonLabelOptsFont.textcase || fontTextcase, - lineposition: commonLabelOptsFont.lineposition || fontLineposition, - shadow: commonLabelOptsFont.shadow || fontShadow, - family: commonLabelOptsFont.family || fontFamily, - size: commonLabelOptsFont.size || fontSize, - color: commonLabelOptsFont.color || contrastColor - }; - lpath.style({ - fill: commonBgColor, - stroke: commonStroke - }); - ltext.text(t02).call(Drawing$o.font, commonLabelFont).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); - label.attr("transform", ""); - var tbb2 = getBoundingClientRect(gd, ltext.node()); - var lx2, ly2; - if (hovermode === "x") { - var topsign = xa.side === "top" ? "-" : ""; - ltext.attr("text-anchor", "middle").call(svgTextUtils$b.positionText, 0, xa.side === "top" ? outerTop - tbb2.bottom - HOVERARROWSIZE - HOVERTEXTPAD : outerTop - tbb2.top + HOVERARROWSIZE + HOVERTEXTPAD); - lx2 = xa._offset + (c0.x0 + c0.x1) / 2; - ly2 = ya._offset + (xa.side === "top" ? 0 : ya._length); - var halfWidth = tbb2.width / 2 + HOVERTEXTPAD; - var tooltipMidX = lx2; - if (lx2 < halfWidth) { - tooltipMidX = halfWidth; - } else if (lx2 > fullLayout.width - halfWidth) { - tooltipMidX = fullLayout.width - halfWidth; - } - lpath.attr("d", "M" + (lx2 - tooltipMidX) + ",0L" + (lx2 - tooltipMidX + HOVERARROWSIZE) + "," + topsign + HOVERARROWSIZE + "H" + halfWidth + "v" + topsign + (HOVERTEXTPAD * 2 + tbb2.height) + "H" + -halfWidth + "V" + topsign + HOVERARROWSIZE + "H" + (lx2 - tooltipMidX - HOVERARROWSIZE) + "Z"); - lx2 = tooltipMidX; - commonLabelRect.minX = lx2 - halfWidth; - commonLabelRect.maxX = lx2 + halfWidth; - if (xa.side === "top") { - commonLabelRect.minY = ly2 - (HOVERTEXTPAD * 2 + tbb2.height); - commonLabelRect.maxY = ly2 - HOVERTEXTPAD; - } else { - commonLabelRect.minY = ly2 + HOVERTEXTPAD; - commonLabelRect.maxY = ly2 + (HOVERTEXTPAD * 2 + tbb2.height); - } - } else { - var anchor; - var sgn; - var leftsign; - if (ya.side === "right") { - anchor = "start"; - sgn = 1; - leftsign = ""; - lx2 = xa._offset + xa._length; - } else { - anchor = "end"; - sgn = -1; - leftsign = "-"; - lx2 = xa._offset; - } - ly2 = ya._offset + (c0.y0 + c0.y1) / 2; - ltext.attr("text-anchor", anchor); - lpath.attr("d", "M0,0L" + leftsign + HOVERARROWSIZE + "," + HOVERARROWSIZE + "V" + (HOVERTEXTPAD + tbb2.height / 2) + "h" + leftsign + (HOVERTEXTPAD * 2 + tbb2.width) + "V-" + (HOVERTEXTPAD + tbb2.height / 2) + "H" + leftsign + HOVERARROWSIZE + "V-" + HOVERARROWSIZE + "Z"); - commonLabelRect.minY = ly2 - (HOVERTEXTPAD + tbb2.height / 2); - commonLabelRect.maxY = ly2 + (HOVERTEXTPAD + tbb2.height / 2); - if (ya.side === "right") { - commonLabelRect.minX = lx2 + HOVERARROWSIZE; - commonLabelRect.maxX = lx2 + HOVERARROWSIZE + (HOVERTEXTPAD * 2 + tbb2.width); - } else { - commonLabelRect.minX = lx2 - HOVERARROWSIZE - (HOVERTEXTPAD * 2 + tbb2.width); - commonLabelRect.maxX = lx2 - HOVERARROWSIZE; - } - var halfHeight = tbb2.height / 2; - var lty = outerTop - tbb2.top - halfHeight; - var clipId = "clip" + fullLayout._uid + "commonlabel" + ya._id; - var clipPath; - if (lx2 < tbb2.width + 2 * HOVERTEXTPAD + HOVERARROWSIZE) { - clipPath = "M-" + (HOVERARROWSIZE + HOVERTEXTPAD) + "-" + halfHeight + "h-" + (tbb2.width - HOVERTEXTPAD) + "V" + halfHeight + "h" + (tbb2.width - HOVERTEXTPAD) + "Z"; - var ltx = tbb2.width - lx2 + HOVERTEXTPAD; - svgTextUtils$b.positionText(ltext, ltx, lty); - if (anchor === "end") { - ltext.selectAll("tspan").each(function() { - var s = d3$s.select(this); - var dummy = Drawing$o.tester.append("text").text(s.text()).call(Drawing$o.font, commonLabelFont); - var dummyBB = getBoundingClientRect(gd, dummy.node()); - if (Math.round(dummyBB.width) < Math.round(tbb2.width)) { - s.attr("x", ltx - dummyBB.width); - } - dummy.remove(); - }); - } - } else { - svgTextUtils$b.positionText(ltext, sgn * (HOVERTEXTPAD + HOVERARROWSIZE), lty); - clipPath = null; - } - var textClip = fullLayout._topclips.selectAll("#" + clipId).data(clipPath ? [0] : []); - textClip.enter().append("clipPath").attr("id", clipId).append("path"); - textClip.exit().remove(); - textClip.select("path").attr("d", clipPath); - Drawing$o.setClipUrl(ltext, clipPath ? clipId : null, gd); - } - label.attr("transform", strTranslate$8(lx2, ly2)); - }); - if (helpers$D.isUnifiedHover(hovermode)) { - container.selectAll("g.hovertext").remove(); - var groupedHoverData = hoverData.filter(function(data) { - return data.hoverinfo !== "none"; - }); - if (groupedHoverData.length === 0) return []; - var hoverlabel = fullLayout.hoverlabel; - var font2 = hoverlabel.font; - var mockLayoutIn = { - showlegend: true, - legend: { - title: { text: t02, font: font2 }, - font: font2, - bgcolor: hoverlabel.bgcolor, - bordercolor: hoverlabel.bordercolor, - borderwidth: 1, - tracegroupgap: 7, - traceorder: fullLayout.legend ? fullLayout.legend.traceorder : void 0, - orientation: "v" - } - }; - var mockLayoutOut = { - font: font2 - }; - legendSupplyDefaults(mockLayoutIn, mockLayoutOut, gd._fullData); - var mockLegend = mockLayoutOut.legend; - mockLegend.entries = []; - for (var j = 0; j < groupedHoverData.length; j++) { - var pt = groupedHoverData[j]; - if (pt.hoverinfo === "none") continue; - var texts = getHoverLabelText(pt, true, hovermode, fullLayout, t02); - var text = texts[0]; - var name2 = texts[1]; - pt.name = name2; - if (name2 !== "") { - pt.text = name2 + " : " + text; - } else { - pt.text = text; - } - var cd = pt.cd[pt.index]; - if (cd) { - if (cd.mc) pt.mc = cd.mc; - if (cd.mcc) pt.mc = cd.mcc; - if (cd.mlc) pt.mlc = cd.mlc; - if (cd.mlcc) pt.mlc = cd.mlcc; - if (cd.mlw) pt.mlw = cd.mlw; - if (cd.mrc) pt.mrc = cd.mrc; - if (cd.dir) pt.dir = cd.dir; - } - pt._distinct = true; - mockLegend.entries.push([pt]); - } - mockLegend.entries.sort(function(a, b) { - return a[0].trace.index - b[0].trace.index; - }); - mockLegend.layer = container; - mockLegend._inHover = true; - mockLegend._groupTitleFont = hoverlabel.grouptitlefont; - legendDraw(gd, mockLegend); - var legendContainer = container.select("g.legend"); - var tbb = getBoundingClientRect(gd, legendContainer.node()); - var tWidth = tbb.width + 2 * HOVERTEXTPAD; - var tHeight = tbb.height + 2 * HOVERTEXTPAD; - var winningPoint = groupedHoverData[0]; - var avgX = (winningPoint.x0 + winningPoint.x1) / 2; - var avgY = (winningPoint.y0 + winningPoint.y1) / 2; - var pointWon = !(Registry$C.traceIs(winningPoint.trace, "bar-like") || Registry$C.traceIs(winningPoint.trace, "box-violin")); - var lyBottom, lyTop; - if (axLetter === "y") { - if (pointWon) { - lyTop = avgY - HOVERTEXTPAD; - lyBottom = avgY + HOVERTEXTPAD; - } else { - lyTop = Math.min.apply(null, groupedHoverData.map(function(c) { - return Math.min(c.y0, c.y1); - })); - lyBottom = Math.max.apply(null, groupedHoverData.map(function(c) { - return Math.max(c.y0, c.y1); - })); - } - } else { - lyTop = lyBottom = Lib$1y.mean(groupedHoverData.map(function(c) { - return (c.y0 + c.y1) / 2; - })) - tHeight / 2; - } - var lxRight, lxLeft; - if (axLetter === "x") { - if (pointWon) { - lxRight = avgX + HOVERTEXTPAD; - lxLeft = avgX - HOVERTEXTPAD; - } else { - lxRight = Math.max.apply(null, groupedHoverData.map(function(c) { - return Math.max(c.x0, c.x1); - })); - lxLeft = Math.min.apply(null, groupedHoverData.map(function(c) { - return Math.min(c.x0, c.x1); - })); - } - } else { - lxRight = lxLeft = Lib$1y.mean(groupedHoverData.map(function(c) { - return (c.x0 + c.x1) / 2; - })) - tWidth / 2; - } - var xOffset = xa._offset; - var yOffset = ya._offset; - lyBottom += yOffset; - lxRight += xOffset; - lxLeft += xOffset - tWidth; - lyTop += yOffset - tHeight; - var lx, ly; - if (lxRight + tWidth < outerWidth && lxRight >= 0) { - lx = lxRight; - } else if (lxLeft + tWidth < outerWidth && lxLeft >= 0) { - lx = lxLeft; - } else if (xOffset + tWidth < outerWidth) { - lx = xOffset; - } else { - if (lxRight - avgX < avgX - lxLeft + tWidth) { - lx = outerWidth - tWidth; - } else { - lx = 0; - } - } - lx += HOVERTEXTPAD; - if (lyBottom + tHeight < outerHeight && lyBottom >= 0) { - ly = lyBottom; - } else if (lyTop + tHeight < outerHeight && lyTop >= 0) { - ly = lyTop; - } else if (yOffset + tHeight < outerHeight) { - ly = yOffset; - } else { - if (lyBottom - avgY < avgY - lyTop + tHeight) { - ly = outerHeight - tHeight; - } else { - ly = 0; - } - } - ly += HOVERTEXTPAD; - legendContainer.attr("transform", strTranslate$8(lx - 1, ly - 1)); - return legendContainer; - } - var hoverLabels = container.selectAll("g.hovertext").data(hoverData, function(d) { - return hoverDataKey(d); - }); - hoverLabels.enter().append("g").classed("hovertext", true).each(function() { - var g = d3$s.select(this); - g.append("rect").call(Color$C.fill, Color$C.addOpacity(bgColor, 0.8)); - g.append("text").classed("name", true); - g.append("path").style("stroke-width", "1px"); - g.append("text").classed("nums", true).call(Drawing$o.font, { - weight: fontWeight, - style: fontStyle, - variant: fontVariant, - textcase: fontTextcase, - lineposition: fontLineposition, - shadow: fontShadow, - family: fontFamily, - size: fontSize - }); - }); - hoverLabels.exit().remove(); - hoverLabels.each(function(d) { - var g = d3$s.select(this).attr("transform", ""); - var dColor = d.color; - if (Array.isArray(dColor)) { - dColor = dColor[d.eventData[0].pointNumber]; - } - var color0 = d.bgcolor || dColor; - var numsColor = Color$C.combine( - Color$C.opacity(color0) ? color0 : Color$C.defaultLine, - bgColor - ); - var nameColor = Color$C.combine( - Color$C.opacity(dColor) ? dColor : Color$C.defaultLine, - bgColor - ); - var contrastColor = d.borderColor || Color$C.contrast(numsColor); - var texts2 = getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g); - var text2 = texts2[0]; - var name3 = texts2[1]; - var tx = g.select("text.nums").call(Drawing$o.font, { - family: d.fontFamily || fontFamily, - size: d.fontSize || fontSize, - color: d.fontColor || contrastColor, - weight: d.fontWeight || fontWeight, - style: d.fontStyle || fontStyle, - variant: d.fontVariant || fontVariant, - textcase: d.fontTextcase || fontTextcase, - lineposition: d.fontLineposition || fontLineposition, - shadow: d.fontShadow || fontShadow - }).text(text2).attr("data-notex", 1).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); - var tx2 = g.select("text.name"); - var tx2width = 0; - var tx2height = 0; - if (name3 && name3 !== text2) { - tx2.call(Drawing$o.font, { - family: d.fontFamily || fontFamily, - size: d.fontSize || fontSize, - color: nameColor, - weight: d.fontWeight || fontWeight, - style: d.fontStyle || fontStyle, - variant: d.fontVariant || fontVariant, - textcase: d.fontTextcase || fontTextcase, - lineposition: d.fontLineposition || fontLineposition, - shadow: d.fontShadow || fontShadow - }).text(name3).attr("data-notex", 1).call(svgTextUtils$b.positionText, 0, 0).call(svgTextUtils$b.convertToTspans, gd); - var t2bb = getBoundingClientRect(gd, tx2.node()); - tx2width = t2bb.width + 2 * HOVERTEXTPAD; - tx2height = t2bb.height + 2 * HOVERTEXTPAD; - } else { - tx2.remove(); - g.select("rect").remove(); - } - g.select("path").style({ - fill: numsColor, - stroke: contrastColor - }); - var htx = d.xa._offset + (d.x0 + d.x1) / 2; - var hty = d.ya._offset + (d.y0 + d.y1) / 2; - var dx = Math.abs(d.x1 - d.x0); - var dy = Math.abs(d.y1 - d.y0); - var tbb2 = getBoundingClientRect(gd, tx.node()); - var tbbWidth = tbb2.width / fullLayout._invScaleX; - var tbbHeight = tbb2.height / fullLayout._invScaleY; - d.ty0 = (outerTop - tbb2.top) / fullLayout._invScaleY; - d.bx = tbbWidth + 2 * HOVERTEXTPAD; - d.by = Math.max(tbbHeight + 2 * HOVERTEXTPAD, tx2height); - d.anchor = "start"; - d.txwidth = tbbWidth; - d.tx2width = tx2width; - d.offset = 0; - var txTotalWidth = (tbbWidth + HOVERARROWSIZE + HOVERTEXTPAD + tx2width) * fullLayout._invScaleX; - var anchorStartOK, anchorEndOK; - if (rotateLabels) { - d.pos = htx; - anchorStartOK = hty + dy / 2 + txTotalWidth <= outerHeight; - anchorEndOK = hty - dy / 2 - txTotalWidth >= 0; - if ((d.idealAlign === "top" || !anchorStartOK) && anchorEndOK) { - hty -= dy / 2; - d.anchor = "end"; - } else if (anchorStartOK) { - hty += dy / 2; - d.anchor = "start"; - } else { - d.anchor = "middle"; - } - d.crossPos = hty; - } else { - d.pos = hty; - anchorStartOK = htx + dx / 2 + txTotalWidth <= outerWidth; - anchorEndOK = htx - dx / 2 - txTotalWidth >= 0; - if ((d.idealAlign === "left" || !anchorStartOK) && anchorEndOK) { - htx -= dx / 2; - d.anchor = "end"; - } else if (anchorStartOK) { - htx += dx / 2; - d.anchor = "start"; - } else { - d.anchor = "middle"; - var txHalfWidth = txTotalWidth / 2; - var overflowR = htx + txHalfWidth - outerWidth; - var overflowL = htx - txHalfWidth; - if (overflowR > 0) htx -= overflowR; - if (overflowL < 0) htx += -overflowL; - } - d.crossPos = htx; - } - tx.attr("text-anchor", d.anchor); - if (tx2width) tx2.attr("text-anchor", d.anchor); - g.attr("transform", strTranslate$8(htx, hty) + (rotateLabels ? strRotate$1(YANGLE) : "")); - }); - return { - hoverLabels, - commonLabelBoundingBox: commonLabelRect - }; -} -function getHoverLabelText(d, showCommonLabel, hovermode, fullLayout, t02, g) { - var name2 = ""; - var text = ""; - if (d.nameOverride !== void 0) d.name = d.nameOverride; - if (d.name) { - if (d.trace._meta) { - d.name = Lib$1y.templateString(d.name, d.trace._meta); - } - name2 = plainText(d.name, d.nameLength); - } - var h0 = hovermode.charAt(0); - var h1 = h0 === "x" ? "y" : "x"; - if (d.zLabel !== void 0) { - if (d.xLabel !== void 0) text += "x: " + d.xLabel + "
"; - if (d.yLabel !== void 0) text += "y: " + d.yLabel + "
"; - if (d.trace.type !== "choropleth" && d.trace.type !== "choroplethmapbox" && d.trace.type !== "choroplethmap") { - text += (text ? "z: " : "") + d.zLabel; - } - } else if (showCommonLabel && d[h0 + "Label"] === t02) { - text = d[h1 + "Label"] || ""; - } else if (d.xLabel === void 0) { - if (d.yLabel !== void 0 && d.trace.type !== "scattercarpet") { - text = d.yLabel; - } - } else if (d.yLabel === void 0) text = d.xLabel; - else text = "(" + d.xLabel + ", " + d.yLabel + ")"; - if ((d.text || d.text === 0) && !Array.isArray(d.text)) { - text += (text ? "
" : "") + d.text; - } - if (d.extraText !== void 0) text += (text ? "
" : "") + d.extraText; - if (g && text === "" && !d.hovertemplate) { - if (name2 === "") g.remove(); - text = name2; - } - var hovertemplate = d.hovertemplate || false; - if (hovertemplate) { - var labels = d.hovertemplateLabels || d; - if (d[h0 + "Label"] !== t02) { - labels[h0 + "other"] = labels[h0 + "Val"]; - labels[h0 + "otherLabel"] = labels[h0 + "Label"]; - } - text = Lib$1y.hovertemplateString( - hovertemplate, - labels, - fullLayout._d3locale, - d.eventData[0] || {}, - d.trace._meta - ); - text = text.replace(EXTRA_STRING_REGEX, function(match, extra) { - name2 = plainText(extra, d.nameLength); - return ""; - }); - } - return [text, name2]; -} -function hoverAvoidOverlaps(hoverLabels, rotateLabels, fullLayout, commonLabelBoundingBox) { - var axKey = rotateLabels ? "xa" : "ya"; - var crossAxKey = rotateLabels ? "ya" : "xa"; - var nummoves = 0; - var axSign = 1; - var nLabels = hoverLabels.size(); - var pointgroups = new Array(nLabels); - var k = 0; - var axisLabelMinX = commonLabelBoundingBox.minX; - var axisLabelMaxX = commonLabelBoundingBox.maxX; - var axisLabelMinY = commonLabelBoundingBox.minY; - var axisLabelMaxY = commonLabelBoundingBox.maxY; - var pX = function(x) { - return x * fullLayout._invScaleX; - }; - var pY = function(y) { - return y * fullLayout._invScaleY; - }; - hoverLabels.each(function(d) { - var ax = d[axKey]; - var crossAx = d[crossAxKey]; - var axIsX = ax._id.charAt(0) === "x"; - var rng = ax.range; - if (k === 0 && rng && rng[0] > rng[1] !== axIsX) { - axSign = -1; - } - var pmin = 0; - var pmax = axIsX ? fullLayout.width : fullLayout.height; - if (fullLayout.hovermode === "x" || fullLayout.hovermode === "y") { - var offsets = getHoverLabelOffsets(d, rotateLabels); - var anchor = d.anchor; - var horzSign = anchor === "end" ? -1 : 1; - var labelMin; - var labelMax; - if (anchor === "middle") { - labelMin = d.crossPos + (axIsX ? pY(offsets.y - d.by / 2) : pX(d.bx / 2 + d.tx2width / 2)); - labelMax = labelMin + (axIsX ? pY(d.by) : pX(d.bx)); - } else { - if (axIsX) { - labelMin = d.crossPos + pY(HOVERARROWSIZE + offsets.y) - pY(d.by / 2 - HOVERARROWSIZE); - labelMax = labelMin + pY(d.by); - } else { - var startX = pX(horzSign * HOVERARROWSIZE + offsets.x); - var endX = startX + pX(horzSign * d.bx); - labelMin = d.crossPos + Math.min(startX, endX); - labelMax = d.crossPos + Math.max(startX, endX); - } - } - if (axIsX) { - if (axisLabelMinY !== void 0 && axisLabelMaxY !== void 0 && Math.min(labelMax, axisLabelMaxY) - Math.max(labelMin, axisLabelMinY) > 1) { - if (crossAx.side === "left") { - pmin = crossAx._mainLinePosition; - pmax = fullLayout.width; - } else { - pmax = crossAx._mainLinePosition; - } - } - } else { - if (axisLabelMinX !== void 0 && axisLabelMaxX !== void 0 && Math.min(labelMax, axisLabelMaxX) - Math.max(labelMin, axisLabelMinX) > 1) { - if (crossAx.side === "top") { - pmin = crossAx._mainLinePosition; - pmax = fullLayout.height; - } else { - pmax = crossAx._mainLinePosition; - } - } - } - } - pointgroups[k++] = [{ - datum: d, - traceIndex: d.trace.index, - dp: 0, - pos: d.pos, - posref: d.posref, - size: d.by * (axIsX ? YFACTOR : 1) / 2, - pmin, - pmax - }]; - }); - pointgroups.sort(function(a, b) { - return a[0].posref - b[0].posref || // for equal positions, sort trace indices increasing or decreasing - // depending on whether the axis is reversed or not... so stacked - // traces will generally keep their order even if one trace adds - // nothing to the stack. - axSign * (b[0].traceIndex - a[0].traceIndex); - }); - var donepositioning, topOverlap, bottomOverlap, i, j, pti, sumdp; - function constrainGroup(grp2) { - var minPt = grp2[0]; - var maxPt = grp2[grp2.length - 1]; - topOverlap = minPt.pmin - minPt.pos - minPt.dp + minPt.size; - bottomOverlap = maxPt.pos + maxPt.dp + maxPt.size - minPt.pmax; - if (topOverlap > 0.01) { - for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp += topOverlap; - donepositioning = false; - } - if (bottomOverlap < 0.01) return; - if (topOverlap < -0.01) { - for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap; - donepositioning = false; - } - if (!donepositioning) return; - var deleteCount = 0; - for (i = 0; i < grp2.length; i++) { - pti = grp2[i]; - if (pti.pos + pti.dp + pti.size > minPt.pmax) deleteCount++; - } - for (i = grp2.length - 1; i >= 0; i--) { - if (deleteCount <= 0) break; - pti = grp2[i]; - if (pti.pos > minPt.pmax - 1) { - pti.del = true; - deleteCount--; - } - } - for (i = 0; i < grp2.length; i++) { - if (deleteCount <= 0) break; - pti = grp2[i]; - if (pti.pos < minPt.pmin + 1) { - pti.del = true; - deleteCount--; - bottomOverlap = pti.size * 2; - for (j = grp2.length - 1; j >= 0; j--) grp2[j].dp -= bottomOverlap; - } - } - for (i = grp2.length - 1; i >= 0; i--) { - if (deleteCount <= 0) break; - pti = grp2[i]; - if (pti.pos + pti.dp + pti.size > minPt.pmax) { - pti.del = true; - deleteCount--; - } - } - } - while (!donepositioning && nummoves <= nLabels) { - nummoves++; - donepositioning = true; - i = 0; - while (i < pointgroups.length - 1) { - var g0 = pointgroups[i]; - var g1 = pointgroups[i + 1]; - var p0 = g0[g0.length - 1]; - var p1 = g1[0]; - topOverlap = p0.pos + p0.dp + p0.size - p1.pos - p1.dp + p1.size; - if (topOverlap > 0.01) { - for (j = g1.length - 1; j >= 0; j--) g1[j].dp += topOverlap; - g0.push.apply(g0, g1); - pointgroups.splice(i + 1, 1); - sumdp = 0; - for (j = g0.length - 1; j >= 0; j--) sumdp += g0[j].dp; - bottomOverlap = sumdp / g0.length; - for (j = g0.length - 1; j >= 0; j--) g0[j].dp -= bottomOverlap; - donepositioning = false; - } else i++; - } - pointgroups.forEach(constrainGroup); - } - for (i = pointgroups.length - 1; i >= 0; i--) { - var grp = pointgroups[i]; - for (j = grp.length - 1; j >= 0; j--) { - var pt = grp[j]; - var hoverPt = pt.datum; - hoverPt.offset = pt.dp; - hoverPt.del = pt.del; - } - } -} -function getHoverLabelOffsets(hoverLabel, rotateLabels) { - var offsetX = 0; - var offsetY = hoverLabel.offset; - if (rotateLabels) { - offsetY *= -YSHIFTY; - offsetX = hoverLabel.offset * YSHIFTX; - } - return { - x: offsetX, - y: offsetY - }; -} -function getTextShiftX(hoverLabel) { - var alignShift = { start: 1, end: -1, middle: 0 }[hoverLabel.anchor]; - var textShiftX = alignShift * (HOVERARROWSIZE + HOVERTEXTPAD); - var text2ShiftX = textShiftX + alignShift * (hoverLabel.txwidth + HOVERTEXTPAD); - var isMiddle = hoverLabel.anchor === "middle"; - if (isMiddle) { - textShiftX -= hoverLabel.tx2width / 2; - text2ShiftX += hoverLabel.txwidth / 2 + HOVERTEXTPAD; - } - return { - alignShift, - textShiftX, - text2ShiftX - }; -} -function alignHoverText(hoverLabels, rotateLabels, scaleX, scaleY) { - var pX = function(x) { - return x * scaleX; - }; - var pY = function(y) { - return y * scaleY; - }; - hoverLabels.each(function(d) { - var g = d3$s.select(this); - if (d.del) return g.remove(); - var tx = g.select("text.nums"); - var anchor = d.anchor; - var horzSign = anchor === "end" ? -1 : 1; - var shiftX = getTextShiftX(d); - var offsets = getHoverLabelOffsets(d, rotateLabels); - var offsetX = offsets.x; - var offsetY = offsets.y; - var isMiddle = anchor === "middle"; - g.select("path").attr("d", isMiddle ? ( - // middle aligned: rect centered on data - "M-" + pX(d.bx / 2 + d.tx2width / 2) + "," + pY(offsetY - d.by / 2) + "h" + pX(d.bx) + "v" + pY(d.by) + "h-" + pX(d.bx) + "Z" - ) : ( - // left or right aligned: side rect with arrow to data - "M0,0L" + pX(horzSign * HOVERARROWSIZE + offsetX) + "," + pY(HOVERARROWSIZE + offsetY) + "v" + pY(d.by / 2 - HOVERARROWSIZE) + "h" + pX(horzSign * d.bx) + "v-" + pY(d.by) + "H" + pX(horzSign * HOVERARROWSIZE + offsetX) + "V" + pY(offsetY - HOVERARROWSIZE) + "Z" - )); - var posX = offsetX + shiftX.textShiftX; - var posY = offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD; - var textAlign = d.textAlign || "auto"; - if (textAlign !== "auto") { - if (textAlign === "left" && anchor !== "start") { - tx.attr("text-anchor", "start"); - posX = isMiddle ? -d.bx / 2 - d.tx2width / 2 + HOVERTEXTPAD : -d.bx - HOVERTEXTPAD; - } else if (textAlign === "right" && anchor !== "end") { - tx.attr("text-anchor", "end"); - posX = isMiddle ? d.bx / 2 - d.tx2width / 2 - HOVERTEXTPAD : d.bx + HOVERTEXTPAD; - } - } - tx.call(svgTextUtils$b.positionText, pX(posX), pY(posY)); - if (d.tx2width) { - g.select("text.name").call( - svgTextUtils$b.positionText, - pX(shiftX.text2ShiftX + shiftX.alignShift * HOVERTEXTPAD + offsetX), - pY(offsetY + d.ty0 - d.by / 2 + HOVERTEXTPAD) - ); - g.select("rect").call( - Drawing$o.setRect, - pX(shiftX.text2ShiftX + (shiftX.alignShift - 1) * d.tx2width / 2 + offsetX), - pY(offsetY - d.by / 2 - 1), - pX(d.tx2width), - pY(d.by + 2) - ); - } - }); -} -function cleanPoint(d, hovermode) { - var index2 = d.index; - var trace = d.trace || {}; - var cd0 = d.cd[0]; - var cd = d.cd[index2] || {}; - function pass(v) { - return v || isNumeric$i(v) && v === 0; - } - var getVal = Array.isArray(index2) ? function(calcKey, traceKey) { - var v = Lib$1y.castOption(cd0, index2, calcKey); - return pass(v) ? v : Lib$1y.extractOption({}, trace, "", traceKey); - } : function(calcKey, traceKey) { - return Lib$1y.extractOption(cd, trace, calcKey, traceKey); - }; - function fill(key, calcKey, traceKey) { - var val = getVal(calcKey, traceKey); - if (pass(val)) d[key] = val; - } - fill("hoverinfo", "hi", "hoverinfo"); - fill("bgcolor", "hbg", "hoverlabel.bgcolor"); - fill("borderColor", "hbc", "hoverlabel.bordercolor"); - fill("fontFamily", "htf", "hoverlabel.font.family"); - fill("fontSize", "hts", "hoverlabel.font.size"); - fill("fontColor", "htc", "hoverlabel.font.color"); - fill("fontWeight", "htw", "hoverlabel.font.weight"); - fill("fontStyle", "hty", "hoverlabel.font.style"); - fill("fontVariant", "htv", "hoverlabel.font.variant"); - fill("nameLength", "hnl", "hoverlabel.namelength"); - fill("textAlign", "hta", "hoverlabel.align"); - d.posref = hovermode === "y" || hovermode === "closest" && trace.orientation === "h" ? d.xa._offset + (d.x0 + d.x1) / 2 : d.ya._offset + (d.y0 + d.y1) / 2; - d.x0 = Lib$1y.constrain(d.x0, 0, d.xa._length); - d.x1 = Lib$1y.constrain(d.x1, 0, d.xa._length); - d.y0 = Lib$1y.constrain(d.y0, 0, d.ya._length); - d.y1 = Lib$1y.constrain(d.y1, 0, d.ya._length); - if (d.xLabelVal !== void 0) { - d.xLabel = "xLabel" in d ? d.xLabel : Axes$l.hoverLabelText(d.xa, d.xLabelVal, trace.xhoverformat); - d.xVal = d.xa.c2d(d.xLabelVal); - } - if (d.yLabelVal !== void 0) { - d.yLabel = "yLabel" in d ? d.yLabel : Axes$l.hoverLabelText(d.ya, d.yLabelVal, trace.yhoverformat); - d.yVal = d.ya.c2d(d.yLabelVal); - } - if (d.zLabelVal !== void 0 && d.zLabel === void 0) { - d.zLabel = String(d.zLabelVal); - } - if (!isNaN(d.xerr) && !(d.xa.type === "log" && d.xerr <= 0)) { - var xeText = Axes$l.tickText(d.xa, d.xa.c2l(d.xerr), "hover").text; - if (d.xerrneg !== void 0) { - d.xLabel += " +" + xeText + " / -" + Axes$l.tickText(d.xa, d.xa.c2l(d.xerrneg), "hover").text; - } else d.xLabel += " ± " + xeText; - if (hovermode === "x") d.distance += 1; - } - if (!isNaN(d.yerr) && !(d.ya.type === "log" && d.yerr <= 0)) { - var yeText = Axes$l.tickText(d.ya, d.ya.c2l(d.yerr), "hover").text; - if (d.yerrneg !== void 0) { - d.yLabel += " +" + yeText + " / -" + Axes$l.tickText(d.ya, d.ya.c2l(d.yerrneg), "hover").text; - } else d.yLabel += " ± " + yeText; - if (hovermode === "y") d.distance += 1; - } - var infomode = d.hoverinfo || d.trace.hoverinfo; - if (infomode && infomode !== "all") { - infomode = Array.isArray(infomode) ? infomode : infomode.split("+"); - if (infomode.indexOf("x") === -1) d.xLabel = void 0; - if (infomode.indexOf("y") === -1) d.yLabel = void 0; - if (infomode.indexOf("z") === -1) d.zLabel = void 0; - if (infomode.indexOf("text") === -1) d.text = void 0; - if (infomode.indexOf("name") === -1) d.name = void 0; - } - return d; -} -function createSpikelines(gd, closestPoints, opts) { - var container = opts.container; - var fullLayout = opts.fullLayout; - var gs = fullLayout._size; - var evt = opts.event; - var showY = !!closestPoints.hLinePoint; - var showX = !!closestPoints.vLinePoint; - var xa, ya; - container.selectAll(".spikeline").remove(); - if (!(showX || showY)) return; - var contrastColor = Color$C.combine(fullLayout.plot_bgcolor, fullLayout.paper_bgcolor); - if (showY) { - var hLinePoint = closestPoints.hLinePoint; - var hLinePointX, hLinePointY; - xa = hLinePoint && hLinePoint.xa; - ya = hLinePoint && hLinePoint.ya; - var ySnap = ya.spikesnap; - if (ySnap === "cursor") { - hLinePointX = evt.pointerX; - hLinePointY = evt.pointerY; - } else { - hLinePointX = xa._offset + hLinePoint.x; - hLinePointY = ya._offset + hLinePoint.y; - } - var dfltHLineColor = tinycolor$3.readability(hLinePoint.color, contrastColor) < 1.5 ? Color$C.contrast(contrastColor) : hLinePoint.color; - var yMode = ya.spikemode; - var yThickness = ya.spikethickness; - var yColor = ya.spikecolor || dfltHLineColor; - var xEdge = Axes$l.getPxPosition(gd, ya); - var xBase, xEndSpike; - if (yMode.indexOf("toaxis") !== -1 || yMode.indexOf("across") !== -1) { - if (yMode.indexOf("toaxis") !== -1) { - xBase = xEdge; - xEndSpike = hLinePointX; - } - if (yMode.indexOf("across") !== -1) { - var xAcross0 = ya._counterDomainMin; - var xAcross1 = ya._counterDomainMax; - if (ya.anchor === "free") { - xAcross0 = Math.min(xAcross0, ya.position); - xAcross1 = Math.max(xAcross1, ya.position); - } - xBase = gs.l + xAcross0 * gs.w; - xEndSpike = gs.l + xAcross1 * gs.w; - } - container.insert("line", ":first-child").attr({ - x1: xBase, - x2: xEndSpike, - y1: hLinePointY, - y2: hLinePointY, - "stroke-width": yThickness, - stroke: yColor, - "stroke-dasharray": Drawing$o.dashStyle(ya.spikedash, yThickness) - }).classed("spikeline", true).classed("crisp", true); - container.insert("line", ":first-child").attr({ - x1: xBase, - x2: xEndSpike, - y1: hLinePointY, - y2: hLinePointY, - "stroke-width": yThickness + 2, - stroke: contrastColor - }).classed("spikeline", true).classed("crisp", true); - } - if (yMode.indexOf("marker") !== -1) { - container.insert("circle", ":first-child").attr({ - cx: xEdge + (ya.side !== "right" ? yThickness : -yThickness), - cy: hLinePointY, - r: yThickness, - fill: yColor - }).classed("spikeline", true); - } - } - if (showX) { - var vLinePoint = closestPoints.vLinePoint; - var vLinePointX, vLinePointY; - xa = vLinePoint && vLinePoint.xa; - ya = vLinePoint && vLinePoint.ya; - var xSnap = xa.spikesnap; - if (xSnap === "cursor") { - vLinePointX = evt.pointerX; - vLinePointY = evt.pointerY; - } else { - vLinePointX = xa._offset + vLinePoint.x; - vLinePointY = ya._offset + vLinePoint.y; - } - var dfltVLineColor = tinycolor$3.readability(vLinePoint.color, contrastColor) < 1.5 ? Color$C.contrast(contrastColor) : vLinePoint.color; - var xMode = xa.spikemode; - var xThickness = xa.spikethickness; - var xColor = xa.spikecolor || dfltVLineColor; - var yEdge = Axes$l.getPxPosition(gd, xa); - var yBase, yEndSpike; - if (xMode.indexOf("toaxis") !== -1 || xMode.indexOf("across") !== -1) { - if (xMode.indexOf("toaxis") !== -1) { - yBase = yEdge; - yEndSpike = vLinePointY; - } - if (xMode.indexOf("across") !== -1) { - var yAcross0 = xa._counterDomainMin; - var yAcross1 = xa._counterDomainMax; - if (xa.anchor === "free") { - yAcross0 = Math.min(yAcross0, xa.position); - yAcross1 = Math.max(yAcross1, xa.position); - } - yBase = gs.t + (1 - yAcross1) * gs.h; - yEndSpike = gs.t + (1 - yAcross0) * gs.h; - } - container.insert("line", ":first-child").attr({ - x1: vLinePointX, - x2: vLinePointX, - y1: yBase, - y2: yEndSpike, - "stroke-width": xThickness, - stroke: xColor, - "stroke-dasharray": Drawing$o.dashStyle(xa.spikedash, xThickness) - }).classed("spikeline", true).classed("crisp", true); - container.insert("line", ":first-child").attr({ - x1: vLinePointX, - x2: vLinePointX, - y1: yBase, - y2: yEndSpike, - "stroke-width": xThickness + 2, - stroke: contrastColor - }).classed("spikeline", true).classed("crisp", true); - } - if (xMode.indexOf("marker") !== -1) { - container.insert("circle", ":first-child").attr({ - cx: vLinePointX, - cy: yEdge - (xa.side !== "top" ? xThickness : -xThickness), - r: xThickness, - fill: xColor - }).classed("spikeline", true); - } - } -} -function hoverChanged(gd, evt, oldhoverdata) { - if (!oldhoverdata || oldhoverdata.length !== gd._hoverdata.length) return true; - for (var i = oldhoverdata.length - 1; i >= 0; i--) { - var oldPt = oldhoverdata[i]; - var newPt = gd._hoverdata[i]; - if (oldPt.curveNumber !== newPt.curveNumber || String(oldPt.pointNumber) !== String(newPt.pointNumber) || String(oldPt.pointNumbers) !== String(newPt.pointNumbers)) { - return true; - } - } - return false; -} -function spikesChanged(gd, oldspikepoints) { - return true; -} -function plainText(s, len) { - return svgTextUtils$b.plainText(s || "", { - len, - allowedTags: ["br", "sub", "sup", "b", "i", "em", "s", "u"] - }); -} -function orderRangePoints(hoverData, hovermode) { - var axLetter = hovermode.charAt(0); - var first = []; - var second2 = []; - var last = []; - for (var i = 0; i < hoverData.length; i++) { - var d = hoverData[i]; - if (Registry$C.traceIs(d.trace, "bar-like") || Registry$C.traceIs(d.trace, "box-violin")) { - last.push(d); - } else if (d.trace[axLetter + "period"]) { - second2.push(d); - } else { - first.push(d); - } - } - return first.concat(second2).concat(last); -} -function getCoord(axLetter, winningPoint, fullLayout) { - var ax = winningPoint[axLetter + "a"]; - var val = winningPoint[axLetter + "Val"]; - var cd0 = winningPoint.cd[0]; - if (ax.type === "category" || ax.type === "multicategory") val = ax._categoriesMap[val]; - else if (ax.type === "date") { - var periodalignment = winningPoint.trace[axLetter + "periodalignment"]; - if (periodalignment) { - var d = winningPoint.cd[winningPoint.index]; - var start = d[axLetter + "Start"]; - if (start === void 0) start = d[axLetter]; - var end = d[axLetter + "End"]; - if (end === void 0) end = d[axLetter]; - var diff = end - start; - if (periodalignment === "end") { - val += diff; - } else if (periodalignment === "middle") { - val += diff / 2; - } - } - val = ax.d2c(val); - } - if (cd0 && cd0.t && cd0.t.posLetter === ax._id) { - if (fullLayout.boxmode === "group" || fullLayout.violinmode === "group") { - val += cd0.t.dPos; - } - } - return val; -} -function getTopOffset(gd) { - return gd.offsetTop + gd.clientTop; -} -function getLeftOffset(gd) { - return gd.offsetLeft + gd.clientLeft; -} -function getBoundingClientRect(gd, node) { - var fullLayout = gd._fullLayout; - var rect2 = node.getBoundingClientRect(); - var x0 = rect2.left; - var y0 = rect2.top; - var x1 = x0 + rect2.width; - var y1 = y0 + rect2.height; - var A2 = Lib$1y.apply3DTransform(fullLayout._invTransform)(x0, y0); - var B2 = Lib$1y.apply3DTransform(fullLayout._invTransform)(x1, y1); - var Ax = A2[0]; - var Ay = A2[1]; - var Bx = B2[0]; - var By = B2[1]; - return { - x: Ax, - y: Ay, - width: Bx - Ax, - height: By - Ay, - top: Math.min(Ay, By), - left: Math.min(Ax, Bx), - right: Math.max(Ax, Bx), - bottom: Math.max(Ay, By) - }; -} -var Lib$1x = libExports; -var Color$B = colorExports; -var isUnifiedHover$1 = helpers$J.isUnifiedHover; -var hoverlabel_defaults = function handleHoverLabelDefaults(contIn, contOut, coerce2, opts) { - opts = opts || {}; - var hasLegend = contOut.legend; - function inheritFontAttr(attr) { - if (!opts.font[attr]) { - opts.font[attr] = hasLegend ? contOut.legend.font[attr] : contOut.font[attr]; - } - } - if (contOut && isUnifiedHover$1(contOut.hovermode)) { - if (!opts.font) opts.font = {}; - inheritFontAttr("size"); - inheritFontAttr("family"); - inheritFontAttr("color"); - inheritFontAttr("weight"); - inheritFontAttr("style"); - inheritFontAttr("variant"); - if (hasLegend) { - if (!opts.bgcolor) opts.bgcolor = Color$B.combine(contOut.legend.bgcolor, contOut.paper_bgcolor); - if (!opts.bordercolor) opts.bordercolor = contOut.legend.bordercolor; - } else { - if (!opts.bgcolor) opts.bgcolor = contOut.paper_bgcolor; - } - } - coerce2("hoverlabel.bgcolor", opts.bgcolor); - coerce2("hoverlabel.bordercolor", opts.bordercolor); - coerce2("hoverlabel.namelength", opts.namelength); - Lib$1x.coerceFont(coerce2, "hoverlabel.font", opts.font); - coerce2("hoverlabel.align", opts.align); -}; -var Lib$1w = libExports; -var handleHoverLabelDefaults$2 = hoverlabel_defaults; -var layoutAttributes$9 = layout_attributes$7; -var layout_global_defaults = function supplyLayoutGlobalDefaults(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$1w.coerce(layoutIn, layoutOut, layoutAttributes$9, attr, dflt); - } - handleHoverLabelDefaults$2(layoutIn, layoutOut, coerce2); -}; -var Lib$1v = libExports; -var attributes$E = attributes$P; -var handleHoverLabelDefaults$1 = hoverlabel_defaults; -var defaults$l = function supplyDefaults(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$1v.coerce(traceIn, traceOut, attributes$E, attr, dflt); - } - var opts = Lib$1v.extendFlat({}, layout.hoverlabel); - if (traceOut.hovertemplate) opts.namelength = -1; - handleHoverLabelDefaults$1(traceIn, traceOut, coerce2, opts); -}; -var Lib$1u = libExports; -var layoutAttributes$8 = layout_attributes$7; -var hovermode_defaults = function handleHoverModeDefaults(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - if (layoutOut[attr] !== void 0) return layoutOut[attr]; - return Lib$1u.coerce(layoutIn, layoutOut, layoutAttributes$8, attr, dflt); - } - coerce2("clickmode"); - coerce2("hoversubplots"); - return coerce2("hovermode"); -}; -var Lib$1t = libExports; -var layoutAttributes$7 = layout_attributes$7; -var handleHoverModeDefaults2 = hovermode_defaults; -var handleHoverLabelDefaults2 = hoverlabel_defaults; -var layout_defaults$5 = function supplyLayoutDefaults2(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$1t.coerce(layoutIn, layoutOut, layoutAttributes$7, attr, dflt); - } - var hoverMode = handleHoverModeDefaults2(layoutIn, layoutOut); - if (hoverMode) { - coerce2("hoverdistance"); - coerce2("spikedistance"); - } - var dragMode = coerce2("dragmode"); - if (dragMode === "select") coerce2("selectdirection"); - var hasMapbox = layoutOut._has("mapbox"); - var hasMap = layoutOut._has("map"); - var hasGeo = layoutOut._has("geo"); - var len = layoutOut._basePlotModules.length; - if (layoutOut.dragmode === "zoom" && ((hasMapbox || hasMap || hasGeo) && len === 1 || (hasMapbox || hasMap) && hasGeo && len === 2)) { - layoutOut.dragmode = "pan"; - } - handleHoverLabelDefaults2(layoutIn, layoutOut, coerce2); - Lib$1t.coerceFont(coerce2, "hoverlabel.grouptitlefont", layoutOut.hoverlabel.font); -}; -var Lib$1s = libExports; -var Registry$B = registry; -var calc$b = function calc2(gd) { - var calcdata = gd.calcdata; - var fullLayout = gd._fullLayout; - function makeCoerceHoverInfo(trace2) { - return function(val) { - return Lib$1s.coerceHoverinfo({ hoverinfo: val }, { _module: trace2._module }, fullLayout); - }; - } - for (var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var trace = cd[0].trace; - if (Registry$B.traceIs(trace, "pie-like")) continue; - var fillFn = Registry$B.traceIs(trace, "2dMap") ? paste : Lib$1s.fillArray; - fillFn(trace.hoverinfo, cd, "hi", makeCoerceHoverInfo(trace)); - if (trace.hovertemplate) fillFn(trace.hovertemplate, cd, "ht"); - if (!trace.hoverlabel) continue; - fillFn(trace.hoverlabel.bgcolor, cd, "hbg"); - fillFn(trace.hoverlabel.bordercolor, cd, "hbc"); - fillFn(trace.hoverlabel.font.size, cd, "hts"); - fillFn(trace.hoverlabel.font.color, cd, "htc"); - fillFn(trace.hoverlabel.font.family, cd, "htf"); - fillFn(trace.hoverlabel.font.weight, cd, "htw"); - fillFn(trace.hoverlabel.font.style, cd, "hty"); - fillFn(trace.hoverlabel.font.variant, cd, "htv"); - fillFn(trace.hoverlabel.namelength, cd, "hnl"); - fillFn(trace.hoverlabel.align, cd, "hta"); - } -}; -function paste(traceAttr, cd, cdAttr, fn) { - fn = fn || Lib$1s.identity; - if (Array.isArray(traceAttr)) { - cd[0][cdAttr] = fn(traceAttr); - } -} -var Registry$A = registry; -var hover$6 = hover$7.hover; -var click$1 = function click(gd, evt, subplot) { - var annotationsDone = Registry$A.getComponentMethod("annotations", "onClick")(gd, gd._hoverdata); - if (subplot !== void 0) { - hover$6(gd, evt, subplot, true); - } - function emitClick() { - gd.emit("plotly_click", { points: gd._hoverdata, event: evt }); - } - if (gd._hoverdata && evt && evt.target) { - if (annotationsDone && annotationsDone.then) { - annotationsDone.then(emitClick); - } else emitClick(); - if (evt.stopImmediatePropagation) evt.stopImmediatePropagation(); - } -}; -var d3$r = d3Exports; -var Lib$1r = libExports; -var dragElement$4 = dragelementExports; -var helpers$C = helpers$J; -var layoutAttributes$6 = layout_attributes$7; -var hoverModule = hover$7; -var fx$1 = { - moduleType: "component", - name: "fx", - constants: constants$W, - schema: { - layout: layoutAttributes$6 - }, - attributes: attributes$P, - layoutAttributes: layoutAttributes$6, - supplyLayoutGlobalDefaults: layout_global_defaults, - supplyDefaults: defaults$l, - supplyLayoutDefaults: layout_defaults$5, - calc: calc$b, - getDistanceFunction: helpers$C.getDistanceFunction, - getClosest: helpers$C.getClosest, - inbox: helpers$C.inbox, - quadrature: helpers$C.quadrature, - appendArrayPointValue: helpers$C.appendArrayPointValue, - castHoverOption, - castHoverinfo, - hover: hoverModule.hover, - unhover: dragElement$4.unhover, - loneHover: hoverModule.loneHover, - loneUnhover, - click: click$1 -}; -function loneUnhover(containerOrSelection) { - var selection = Lib$1r.isD3Selection(containerOrSelection) ? containerOrSelection : d3$r.select(containerOrSelection); - selection.selectAll("g.hovertext").remove(); - selection.selectAll(".spikeline").remove(); -} -function castHoverOption(trace, ptNumber, attr) { - return Lib$1r.castOption(trace, ptNumber, "hoverlabel." + attr); -} -function castHoverinfo(trace, fullLayout, ptNumber) { - function _coerce(val) { - return Lib$1r.coerceHoverinfo({ hoverinfo: val }, { _module: trace._module }, fullLayout); - } - return Lib$1r.castOption(trace, ptNumber, "hoverinfo", _coerce); -} -var helpers$B = {}; -(function(exports2) { - exports2.selectMode = function(dragmode) { - return dragmode === "lasso" || dragmode === "select"; - }; - exports2.drawMode = function(dragmode) { - return dragmode === "drawclosedpath" || dragmode === "drawopenpath" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle"; - }; - exports2.openMode = function(dragmode) { - return dragmode === "drawline" || dragmode === "drawopenpath"; - }; - exports2.rectMode = function(dragmode) { - return dragmode === "select" || dragmode === "drawline" || dragmode === "drawrect" || dragmode === "drawcircle"; - }; - exports2.freeMode = function(dragmode) { - return dragmode === "lasso" || dragmode === "drawclosedpath" || dragmode === "drawopenpath"; - }; - exports2.selectingOrDrawing = function(dragmode) { - return exports2.freeMode(dragmode) || exports2.rectMode(dragmode); - }; -})(helpers$B); -var clear_gl_canvases = function clearGlCanvases(gd) { - var fullLayout = gd._fullLayout; - if (fullLayout._glcanvas && fullLayout._glcanvas.size()) { - fullLayout._glcanvas.each(function(d) { - if (d.regl) d.regl.clear({ color: true, depth: true }); - }); - } -}; -var subroutines = {}; -var buttons = { exports: {} }; -var ploticon = { - undo: { - width: 857.1, - height: 1e3, - path: "m857 350q0-87-34-166t-91-137-137-92-166-34q-96 0-183 41t-147 114q-4 6-4 13t5 11l76 77q6 5 14 5 9-1 13-7 41-53 100-82t126-29q58 0 110 23t92 61 61 91 22 111-22 111-61 91-92 61-110 23q-55 0-105-20t-90-57l77-77q17-16 8-38-10-23-33-23h-250q-15 0-25 11t-11 25v250q0 24 22 33 22 10 39-8l72-72q60 57 137 88t159 31q87 0 166-34t137-92 91-137 34-166z", - transform: "matrix(1 0 0 -1 0 850)" - }, - home: { - width: 928.6, - height: 1e3, - path: "m786 296v-267q0-15-11-26t-25-10h-214v214h-143v-214h-214q-15 0-25 10t-11 26v267q0 1 0 2t0 2l321 264 321-264q1-1 1-4z m124 39l-34-41q-5-5-12-6h-2q-7 0-12 3l-386 322-386-322q-7-4-13-4-7 2-12 7l-35 41q-4 5-3 13t6 12l401 334q18 15 42 15t43-15l136-114v109q0 8 5 13t13 5h107q8 0 13-5t5-13v-227l122-102q5-5 6-12t-4-13z", - transform: "matrix(1 0 0 -1 0 850)" - }, - "camera-retro": { - width: 1e3, - height: 1e3, - path: "m518 386q0 8-5 13t-13 5q-37 0-63-27t-26-63q0-8 5-13t13-5 12 5 5 13q0 23 16 38t38 16q8 0 13 5t5 13z m125-73q0-59-42-101t-101-42-101 42-42 101 42 101 101 42 101-42 42-101z m-572-320h858v71h-858v-71z m643 320q0 89-62 152t-152 62-151-62-63-152 63-151 151-63 152 63 62 151z m-571 358h214v72h-214v-72z m-72-107h858v143h-462l-36-71h-360v-72z m929 143v-714q0-30-21-51t-50-21h-858q-29 0-50 21t-21 51v714q0 30 21 51t50 21h858q29 0 50-21t21-51z", - transform: "matrix(1 0 0 -1 0 850)" - }, - zoombox: { - width: 1e3, - height: 1e3, - path: "m1000-25l-250 251c40 63 63 138 63 218 0 224-182 406-407 406-224 0-406-182-406-406s183-406 407-406c80 0 155 22 218 62l250-250 125 125z m-812 250l0 438 437 0 0-438-437 0z m62 375l313 0 0-312-313 0 0 312z", - transform: "matrix(1 0 0 -1 0 850)" - }, - pan: { - width: 1e3, - height: 1e3, - path: "m1000 350l-187 188 0-125-250 0 0 250 125 0-188 187-187-187 125 0 0-250-250 0 0 125-188-188 186-187 0 125 252 0 0-250-125 0 187-188 188 188-125 0 0 250 250 0 0-126 187 188z", - transform: "matrix(1 0 0 -1 0 850)" - }, - zoom_plus: { - width: 875, - height: 1e3, - path: "m1 787l0-875 875 0 0 875-875 0z m687-500l-187 0 0-187-125 0 0 187-188 0 0 125 188 0 0 187 125 0 0-187 187 0 0-125z", - transform: "matrix(1 0 0 -1 0 850)" - }, - zoom_minus: { - width: 875, - height: 1e3, - path: "m0 788l0-876 875 0 0 876-875 0z m688-500l-500 0 0 125 500 0 0-125z", - transform: "matrix(1 0 0 -1 0 850)" - }, - autoscale: { - width: 1e3, - height: 1e3, - path: "m250 850l-187 0-63 0 0-62 0-188 63 0 0 188 187 0 0 62z m688 0l-188 0 0-62 188 0 0-188 62 0 0 188 0 62-62 0z m-875-938l0 188-63 0 0-188 0-62 63 0 187 0 0 62-187 0z m875 188l0-188-188 0 0-62 188 0 62 0 0 62 0 188-62 0z m-125 188l-1 0-93-94-156 156 156 156 92-93 2 0 0 250-250 0 0-2 93-92-156-156-156 156 94 92 0 2-250 0 0-250 0 0 93 93 157-156-157-156-93 94 0 0 0-250 250 0 0 0-94 93 156 157 156-157-93-93 0 0 250 0 0 250z", - transform: "matrix(1 0 0 -1 0 850)" - }, - tooltip_basic: { - width: 1500, - height: 1e3, - path: "m375 725l0 0-375-375 375-374 0-1 1125 0 0 750-1125 0z", - transform: "matrix(1 0 0 -1 0 850)" - }, - tooltip_compare: { - width: 1125, - height: 1e3, - path: "m187 786l0 2-187-188 188-187 0 0 937 0 0 373-938 0z m0-499l0 1-187-188 188-188 0 0 937 0 0 376-938-1z", - transform: "matrix(1 0 0 -1 0 850)" - }, - plotlylogo: { - width: 1542, - height: 1e3, - path: "m0-10h182v-140h-182v140z m228 146h183v-286h-183v286z m225 714h182v-1000h-182v1000z m225-285h182v-715h-182v715z m225 142h183v-857h-183v857z m231-428h182v-429h-182v429z m225-291h183v-138h-183v138z", - transform: "matrix(1 0 0 -1 0 850)" - }, - "z-axis": { - width: 1e3, - height: 1e3, - path: "m833 5l-17 108v41l-130-65 130-66c0 0 0 38 0 39 0-1 36-14 39-25 4-15-6-22-16-30-15-12-39-16-56-20-90-22-187-23-279-23-261 0-341 34-353 59 3 60 228 110 228 110-140-8-351-35-351-116 0-120 293-142 474-142 155 0 477 22 477 142 0 50-74 79-163 96z m-374 94c-58-5-99-21-99-40 0-24 65-43 144-43 79 0 143 19 143 43 0 19-42 34-98 40v216h87l-132 135-133-135h88v-216z m167 515h-136v1c16 16 31 34 46 52l84 109v54h-230v-71h124v-1c-16-17-28-32-44-51l-89-114v-51h245v72z", - transform: "matrix(1 0 0 -1 0 850)" - }, - "3d_rotate": { - width: 1e3, - height: 1e3, - path: "m922 660c-5 4-9 7-14 11-359 263-580-31-580-31l-102 28 58-400c0 1 1 1 2 2 118 108 351 249 351 249s-62 27-100 42c88 83 222 183 347 122 16-8 30-17 44-27-2 1-4 2-6 4z m36-329c0 0 64 229-88 296-62 27-124 14-175-11 157-78 225-208 249-266 8-19 11-31 11-31 2 5 6 15 11 32-5-13-8-20-8-20z m-775-239c70-31 117-50 198-32-121 80-199 346-199 346l-96-15-58-12c0 0 55-226 155-287z m603 133l-317-139c0 0 4-4 19-14 7-5 24-15 24-15s-177-147-389 4c235-287 536-112 536-112l31-22 100 299-4-1z m-298-153c6-4 14-9 24-15 0 0-17 10-24 15z", - transform: "matrix(1 0 0 -1 0 850)" - }, - camera: { - width: 1e3, - height: 1e3, - path: "m500 450c-83 0-150-67-150-150 0-83 67-150 150-150 83 0 150 67 150 150 0 83-67 150-150 150z m400 150h-120c-16 0-34 13-39 29l-31 93c-6 15-23 28-40 28h-340c-16 0-34-13-39-28l-31-94c-6-15-23-28-40-28h-120c-55 0-100-45-100-100v-450c0-55 45-100 100-100h800c55 0 100 45 100 100v450c0 55-45 100-100 100z m-400-550c-138 0-250 112-250 250 0 138 112 250 250 250 138 0 250-112 250-250 0-138-112-250-250-250z m365 380c-19 0-35 16-35 35 0 19 16 35 35 35 19 0 35-16 35-35 0-19-16-35-35-35z", - transform: "matrix(1 0 0 -1 0 850)" - }, - movie: { - width: 1e3, - height: 1e3, - path: "m938 413l-188-125c0 37-17 71-44 94 64 38 107 107 107 187 0 121-98 219-219 219-121 0-219-98-219-219 0-61 25-117 66-156h-115c30 33 49 76 49 125 0 103-84 187-187 187s-188-84-188-187c0-57 26-107 65-141-38-22-65-62-65-109v-250c0-70 56-126 125-126h500c69 0 125 56 125 126l188-126c34 0 62 28 62 63v375c0 35-28 63-62 63z m-750 0c-69 0-125 56-125 125s56 125 125 125 125-56 125-125-56-125-125-125z m406-1c-87 0-157 70-157 157 0 86 70 156 157 156s156-70 156-156-70-157-156-157z", - transform: "matrix(1 0 0 -1 0 850)" - }, - question: { - width: 857.1, - height: 1e3, - path: "m500 82v107q0 8-5 13t-13 5h-107q-8 0-13-5t-5-13v-107q0-8 5-13t13-5h107q8 0 13 5t5 13z m143 375q0 49-31 91t-77 65-95 23q-136 0-207-119-9-14 4-24l74-55q4-4 10-4 9 0 14 7 30 38 48 51 19 14 48 14 27 0 48-15t21-33q0-21-11-34t-38-25q-35-16-65-48t-29-70v-20q0-8 5-13t13-5h107q8 0 13 5t5 13q0 10 12 27t30 28q18 10 28 16t25 19 25 27 16 34 7 45z m214-107q0-117-57-215t-156-156-215-58-216 58-155 156-58 215 58 215 155 156 216 58 215-58 156-156 57-215z", - transform: "matrix(1 0 0 -1 0 850)" - }, - disk: { - width: 857.1, - height: 1e3, - path: "m214-7h429v214h-429v-214z m500 0h72v500q0 8-6 21t-11 20l-157 156q-5 6-19 12t-22 5v-232q0-22-15-38t-38-16h-322q-22 0-37 16t-16 38v232h-72v-714h72v232q0 22 16 38t37 16h465q22 0 38-16t15-38v-232z m-214 518v178q0 8-5 13t-13 5h-107q-7 0-13-5t-5-13v-178q0-8 5-13t13-5h107q7 0 13 5t5 13z m357-18v-518q0-22-15-38t-38-16h-750q-23 0-38 16t-16 38v750q0 22 16 38t38 16h517q23 0 50-12t42-26l156-157q16-15 27-42t11-49z", - transform: "matrix(1 0 0 -1 0 850)" - }, - drawopenpath: { - width: 70, - height: 70, - path: "M33.21,85.65a7.31,7.31,0,0,1-2.59-.48c-8.16-3.11-9.27-19.8-9.88-41.3-.1-3.58-.19-6.68-.35-9-.15-2.1-.67-3.48-1.43-3.79-2.13-.88-7.91,2.32-12,5.86L3,32.38c1.87-1.64,11.55-9.66,18.27-6.9,2.13.87,4.75,3.14,5.17,9,.17,2.43.26,5.59.36,9.25a224.17,224.17,0,0,0,1.5,23.4c1.54,10.76,4,12.22,4.48,12.4.84.32,2.79-.46,5.76-3.59L43,80.07C41.53,81.57,37.68,85.64,33.21,85.65ZM74.81,69a11.34,11.34,0,0,0,6.09-6.72L87.26,44.5,74.72,32,56.9,38.35c-2.37.86-5.57,3.42-6.61,6L38.65,72.14l8.42,8.43ZM55,46.27a7.91,7.91,0,0,1,3.64-3.17l14.8-5.3,8,8L76.11,60.6l-.06.19a6.37,6.37,0,0,1-3,3.43L48.25,74.59,44.62,71Zm16.57,7.82A6.9,6.9,0,1,0,64.64,61,6.91,6.91,0,0,0,71.54,54.09Zm-4.05,0a2.85,2.85,0,1,1-2.85-2.85A2.86,2.86,0,0,1,67.49,54.09Zm-4.13,5.22L60.5,56.45,44.26,72.7l2.86,2.86ZM97.83,35.67,84.14,22l-8.57,8.57L89.26,44.24Zm-13.69-8,8,8-2.85,2.85-8-8Z", - transform: "matrix(1 0 0 1 -15 -15)" - }, - drawclosedpath: { - width: 90, - height: 90, - path: "M88.41,21.12a26.56,26.56,0,0,0-36.18,0l-2.07,2-2.07-2a26.57,26.57,0,0,0-36.18,0,23.74,23.74,0,0,0,0,34.8L48,90.12a3.22,3.22,0,0,0,4.42,0l36-34.21a23.73,23.73,0,0,0,0-34.79ZM84,51.24,50.16,83.35,16.35,51.25a17.28,17.28,0,0,1,0-25.47,20,20,0,0,1,27.3,0l4.29,4.07a3.23,3.23,0,0,0,4.44,0l4.29-4.07a20,20,0,0,1,27.3,0,17.27,17.27,0,0,1,0,25.46ZM66.76,47.68h-33v6.91h33ZM53.35,35H46.44V68h6.91Z", - transform: "matrix(1 0 0 1 -5 -5)" - }, - lasso: { - width: 1031, - height: 1e3, - path: "m1018 538c-36 207-290 336-568 286-277-48-473-256-436-463 10-57 36-108 76-151-13-66 11-137 68-183 34-28 75-41 114-42l-55-70 0 0c-2-1-3-2-4-3-10-14-8-34 5-45 14-11 34-8 45 4 1 1 2 3 2 5l0 0 113 140c16 11 31 24 45 40 4 3 6 7 8 11 48-3 100 0 151 9 278 48 473 255 436 462z m-624-379c-80 14-149 48-197 96 42 42 109 47 156 9 33-26 47-66 41-105z m-187-74c-19 16-33 37-39 60 50-32 109-55 174-68-42-25-95-24-135 8z m360 75c-34-7-69-9-102-8 8 62-16 128-68 170-73 59-175 54-244-5-9 20-16 40-20 61-28 159 121 317 333 354s407-60 434-217c28-159-121-318-333-355z", - transform: "matrix(1 0 0 -1 0 850)" - }, - selectbox: { - width: 1e3, - height: 1e3, - path: "m0 850l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-285l0-143 143 0 0 143-143 0z m857 0l0-143 143 0 0 143-143 0z m-857-286l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z m285 0l0-143 143 0 0 143-143 0z m286 0l0-143 143 0 0 143-143 0z", - transform: "matrix(1 0 0 -1 0 850)" - }, - drawline: { - width: 70, - height: 70, - path: "M60.64,62.3a11.29,11.29,0,0,0,6.09-6.72l6.35-17.72L60.54,25.31l-17.82,6.4c-2.36.86-5.57,3.41-6.6,6L24.48,65.5l8.42,8.42ZM40.79,39.63a7.89,7.89,0,0,1,3.65-3.17l14.79-5.31,8,8L61.94,54l-.06.19a6.44,6.44,0,0,1-3,3.43L34.07,68l-3.62-3.63Zm16.57,7.81a6.9,6.9,0,1,0-6.89,6.9A6.9,6.9,0,0,0,57.36,47.44Zm-4,0a2.86,2.86,0,1,1-2.85-2.85A2.86,2.86,0,0,1,53.32,47.44Zm-4.13,5.22L46.33,49.8,30.08,66.05l2.86,2.86ZM83.65,29,70,15.34,61.4,23.9,75.09,37.59ZM70,21.06l8,8-2.84,2.85-8-8ZM87,80.49H10.67V87H87Z", - transform: "matrix(1 0 0 1 -15 -15)" - }, - drawrect: { - width: 80, - height: 80, - path: "M78,22V79H21V22H78m9-9H12V88H87V13ZM68,46.22H31V54H68ZM53,32H45.22V69H53Z", - transform: "matrix(1 0 0 1 -10 -10)" - }, - drawcircle: { - width: 80, - height: 80, - path: "M50,84.72C26.84,84.72,8,69.28,8,50.3S26.84,15.87,50,15.87,92,31.31,92,50.3,73.16,84.72,50,84.72Zm0-60.59c-18.6,0-33.74,11.74-33.74,26.17S31.4,76.46,50,76.46,83.74,64.72,83.74,50.3,68.6,24.13,50,24.13Zm17.15,22h-34v7.11h34Zm-13.8-13H46.24v34h7.11Z", - transform: "matrix(1 0 0 1 -10 -10)" - }, - eraseshape: { - width: 80, - height: 80, - path: "M82.77,78H31.85L6,49.57,31.85,21.14H82.77a8.72,8.72,0,0,1,8.65,8.77V69.24A8.72,8.72,0,0,1,82.77,78ZM35.46,69.84H82.77a.57.57,0,0,0,.49-.6V29.91a.57.57,0,0,0-.49-.61H35.46L17,49.57Zm32.68-34.7-24,24,5,5,24-24Zm-19,.53-5,5,24,24,5-5Z", - transform: "matrix(1 0 0 1 -10 -10)" - }, - spikeline: { - width: 1e3, - height: 1e3, - path: "M512 409c0-57-46-104-103-104-57 0-104 47-104 104 0 57 47 103 104 103 57 0 103-46 103-103z m-327-39l92 0 0 92-92 0z m-185 0l92 0 0 92-92 0z m370-186l92 0 0 93-92 0z m0-184l92 0 0 92-92 0z", - transform: "matrix(1.5 0 0 -1.5 0 850)" - }, - pencil: { - width: 1792, - height: 1792, - path: "M491 1536l91-91-235-235-91 91v107h128v128h107zm523-928q0-22-22-22-10 0-17 7l-542 542q-7 7-7 17 0 22 22 22 10 0 17-7l542-542q7-7 7-17zm-54-192l416 416-832 832h-416v-416zm683 96q0 53-37 90l-166 166-416-416 166-165q36-38 90-38 53 0 91 38l235 234q37 39 37 91z", - transform: "matrix(1 0 0 1 0 1)" - }, - newplotlylogo: { - name: "newplotlylogo", - svg: [ - "", - "", - " ", - "", - " plotly-logomark", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - " ", - "" - ].join("") - } -}; -var helpers$A = {}; -var CIRCLE_SIDES = 32; -var constants$K = { - CIRCLE_SIDES, - i000: 0, - i090: CIRCLE_SIDES / 4, - i180: CIRCLE_SIDES / 2, - i270: CIRCLE_SIDES / 4 * 3, - cos45: Math.cos(Math.PI / 4), - sin45: Math.sin(Math.PI / 4), - SQRT2: Math.sqrt(2) -}; -var strTranslate$7 = libExports.strTranslate; -function p2r$2(ax, v) { - switch (ax.type) { - case "log": - return ax.p2d(v); - case "date": - return ax.p2r(v, 0, ax.calendar); - default: - return ax.p2r(v); - } -} -function r2p$1(ax, v) { - switch (ax.type) { - case "log": - return ax.d2p(v); - case "date": - return ax.r2p(v, 0, ax.calendar); - default: - return ax.r2p(v); - } -} -function axValue$1(ax) { - var index2 = ax._id.charAt(0) === "y" ? 1 : 0; - return function(v) { - return p2r$2(ax, v[index2]); - }; -} -function getTransform$1(plotinfo) { - return strTranslate$7( - plotinfo.xaxis._offset, - plotinfo.yaxis._offset - ); -} -var helpers$z = { - p2r: p2r$2, - r2p: r2p$1, - axValue: axValue$1, - getTransform: getTransform$1 -}; -(function(exports2) { - var parseSvgPath$1 = parseSvgPath; - var constants2 = constants$K; - var CIRCLE_SIDES2 = constants2.CIRCLE_SIDES; - var SQRT2 = constants2.SQRT2; - var cartesianHelpers2 = helpers$z; - var p2r2 = cartesianHelpers2.p2r; - var r2p2 = cartesianHelpers2.r2p; - var iC = [0, 3, 4, 5, 6, 1, 2]; - var iQS = [0, 3, 4, 1, 2]; - exports2.writePaths = function(polygons) { - var nI = polygons.length; - if (!nI) return "M0,0Z"; - var str2 = ""; - for (var i = 0; i < nI; i++) { - var nJ = polygons[i].length; - for (var j = 0; j < nJ; j++) { - var w = polygons[i][j][0]; - if (w === "Z") { - str2 += "Z"; - } else { - var nK = polygons[i][j].length; - for (var k = 0; k < nK; k++) { - var realK = k; - if (w === "Q" || w === "S") { - realK = iQS[k]; - } else if (w === "C") { - realK = iC[k]; - } - str2 += polygons[i][j][realK]; - if (k > 0 && k < nK - 1) { - str2 += ","; - } - } - } - } - } - return str2; - }; - exports2.readPaths = function(str2, gd, plotinfo, isActiveShape) { - var cmd = parseSvgPath$1(str2); - var polys = []; - var n = -1; - var newPoly = function() { - n++; - polys[n] = []; - }; - var k; - var x = 0; - var y = 0; - var initX; - var initY; - var recStart = function() { - initX = x; - initY = y; - }; - recStart(); - for (var i = 0; i < cmd.length; i++) { - var newPos = []; - var x1, x2, y1, y2; - var c = cmd[i][0]; - var w = c; - switch (c) { - case "M": - newPoly(); - x = +cmd[i][1]; - y = +cmd[i][2]; - newPos.push([w, x, y]); - recStart(); - break; - case "Q": - case "S": - x1 = +cmd[i][1]; - y1 = +cmd[i][2]; - x = +cmd[i][3]; - y = +cmd[i][4]; - newPos.push([w, x, y, x1, y1]); - break; - case "C": - x1 = +cmd[i][1]; - y1 = +cmd[i][2]; - x2 = +cmd[i][3]; - y2 = +cmd[i][4]; - x = +cmd[i][5]; - y = +cmd[i][6]; - newPos.push([w, x, y, x1, y1, x2, y2]); - break; - case "T": - case "L": - x = +cmd[i][1]; - y = +cmd[i][2]; - newPos.push([w, x, y]); - break; - case "H": - w = "L"; - x = +cmd[i][1]; - newPos.push([w, x, y]); - break; - case "V": - w = "L"; - y = +cmd[i][1]; - newPos.push([w, x, y]); - break; - case "A": - w = "L"; - var rx = +cmd[i][1]; - var ry = +cmd[i][2]; - if (!+cmd[i][4]) { - rx = -rx; - ry = -ry; - } - var cenX = x - rx; - var cenY = y; - for (k = 1; k <= CIRCLE_SIDES2 / 2; k++) { - var t = 2 * Math.PI * k / CIRCLE_SIDES2; - newPos.push([ - w, - cenX + rx * Math.cos(t), - cenY + ry * Math.sin(t) - ]); - } - break; - case "Z": - if (x !== initX || y !== initY) { - x = initX; - y = initY; - newPos.push([w, x, y]); - } - break; - } - var domain2 = (plotinfo || {}).domain; - var size = gd._fullLayout._size; - var xPixelSized = plotinfo && plotinfo.xsizemode === "pixel"; - var yPixelSized = plotinfo && plotinfo.ysizemode === "pixel"; - var noOffset = isActiveShape === false; - for (var j = 0; j < newPos.length; j++) { - for (k = 0; k + 2 < 7; k += 2) { - var _x = newPos[j][k + 1]; - var _y = newPos[j][k + 2]; - if (_x === void 0 || _y === void 0) continue; - x = _x; - y = _y; - if (plotinfo) { - if (plotinfo.xaxis && plotinfo.xaxis.p2r) { - if (noOffset) _x -= plotinfo.xaxis._offset; - if (xPixelSized) { - _x = r2p2(plotinfo.xaxis, plotinfo.xanchor) + _x; - } else { - _x = p2r2(plotinfo.xaxis, _x); - } - } else { - if (noOffset) _x -= size.l; - if (domain2) _x = domain2.x[0] + _x / size.w; - else _x = _x / size.w; - } - if (plotinfo.yaxis && plotinfo.yaxis.p2r) { - if (noOffset) _y -= plotinfo.yaxis._offset; - if (yPixelSized) { - _y = r2p2(plotinfo.yaxis, plotinfo.yanchor) - _y; - } else { - _y = p2r2(plotinfo.yaxis, _y); - } - } else { - if (noOffset) _y -= size.t; - if (domain2) _y = domain2.y[1] - _y / size.h; - else _y = 1 - _y / size.h; - } - } - newPos[j][k + 1] = _x; - newPos[j][k + 2] = _y; - } - polys[n].push( - newPos[j].slice() - ); - } - } - return polys; - }; - function almostEq(a, b) { - return Math.abs(a - b) <= 1e-6; - } - function dist2(a, b) { - var dx = b[1] - a[1]; - var dy = b[2] - a[2]; - return Math.sqrt( - dx * dx + dy * dy - ); - } - exports2.pointsOnRectangle = function(cell) { - var len = cell.length; - if (len !== 5) return false; - for (var j = 1; j < 3; j++) { - var e01 = cell[0][j] - cell[1][j]; - var e32 = cell[3][j] - cell[2][j]; - if (!almostEq(e01, e32)) return false; - var e03 = cell[0][j] - cell[3][j]; - var e12 = cell[1][j] - cell[2][j]; - if (!almostEq(e03, e12)) return false; - } - if (!almostEq(cell[0][1], cell[1][1]) && !almostEq(cell[0][1], cell[3][1])) return false; - return !!(dist2(cell[0], cell[1]) * dist2(cell[0], cell[3])); - }; - exports2.pointsOnEllipse = function(cell) { - var len = cell.length; - if (len !== CIRCLE_SIDES2 + 1) return false; - len = CIRCLE_SIDES2; - for (var i = 0; i < len; i++) { - var k = (len * 2 - i) % len; - var k2 = (len / 2 + k) % len; - var i2 = (len / 2 + i) % len; - if (!almostEq( - dist2(cell[i], cell[i2]), - dist2(cell[k], cell[k2]) - )) return false; - } - return true; - }; - exports2.handleEllipse = function(isEllipse, start, end) { - if (!isEllipse) return [start, end]; - var pos = exports2.ellipseOver({ - x0: start[0], - y0: start[1], - x1: end[0], - y1: end[1] - }); - var cx = (pos.x1 + pos.x0) / 2; - var cy = (pos.y1 + pos.y0) / 2; - var rx = (pos.x1 - pos.x0) / 2; - var ry = (pos.y1 - pos.y0) / 2; - if (!rx) rx = ry = ry / SQRT2; - if (!ry) ry = rx = rx / SQRT2; - var cell = []; - for (var i = 0; i < CIRCLE_SIDES2; i++) { - var t = i * 2 * Math.PI / CIRCLE_SIDES2; - cell.push([ - cx + rx * Math.cos(t), - cy + ry * Math.sin(t) - ]); - } - return cell; - }; - exports2.ellipseOver = function(pos) { - var x0 = pos.x0; - var y0 = pos.y0; - var x1 = pos.x1; - var y1 = pos.y1; - var dx = x1 - x0; - var dy = y1 - y0; - x0 -= dx; - y0 -= dy; - var cx = (x0 + x1) / 2; - var cy = (y0 + y1) / 2; - var scale2 = SQRT2; - dx *= scale2; - dy *= scale2; - return { - x0: cx - dx, - y0: cy - dy, - x1: cx + dx, - y1: cy + dy - }; - }; - exports2.fixDatesForPaths = function(polygons, xaxis, yaxis) { - var xIsDate = xaxis.type === "date"; - var yIsDate = yaxis.type === "date"; - if (!xIsDate && !yIsDate) return polygons; - for (var i = 0; i < polygons.length; i++) { - for (var j = 0; j < polygons[i].length; j++) { - for (var k = 0; k + 2 < polygons[i][j].length; k += 2) { - if (xIsDate) polygons[i][j][k + 1] = polygons[i][j][k + 1].replace(" ", "_"); - if (yIsDate) polygons[i][j][k + 2] = polygons[i][j][k + 2].replace(" ", "_"); - } - } - } - return polygons; - }; -})(helpers$A); -var dragHelpers$3 = helpers$B; -var drawMode$2 = dragHelpers$3.drawMode; -var openMode$1 = dragHelpers$3.openMode; -var constants$J = constants$K; -var i000$1 = constants$J.i000; -var i090$1 = constants$J.i090; -var i180$1 = constants$J.i180; -var i270$1 = constants$J.i270; -var cos45 = constants$J.cos45; -var sin45 = constants$J.sin45; -var cartesianHelpers = helpers$z; -var p2r$1 = cartesianHelpers.p2r; -var r2p = cartesianHelpers.r2p; -var handleOutline$2 = handle_outline; -var clearOutline$2 = handleOutline$2.clearOutline; -var helpers$y = helpers$A; -var readPaths$5 = helpers$y.readPaths; -var writePaths$2 = helpers$y.writePaths; -var ellipseOver = helpers$y.ellipseOver; -var fixDatesForPaths$1 = helpers$y.fixDatesForPaths; -function newShapes$2(outlines, dragOptions) { - if (!outlines.length) return; - var e = outlines[0][0]; - if (!e) return; - var gd = dragOptions.gd; - var isActiveShape = dragOptions.isActiveShape; - var dragmode = dragOptions.dragmode; - var shapes2 = (gd.layout || {}).shapes || []; - if (!drawMode$2(dragmode) && isActiveShape !== void 0) { - var id = gd._fullLayout._activeShapeIndex; - if (id < shapes2.length) { - switch (gd._fullLayout.shapes[id].type) { - case "rect": - dragmode = "drawrect"; - break; - case "circle": - dragmode = "drawcircle"; - break; - case "line": - dragmode = "drawline"; - break; - case "path": - var path = shapes2[id].path || ""; - if (path[path.length - 1] === "Z") { - dragmode = "drawclosedpath"; - } else { - dragmode = "drawopenpath"; - } - break; - } - } - } - var newShape = createShapeObj$1(outlines, dragOptions, dragmode); - clearOutline$2(gd); - var editHelpers = dragOptions.editHelpers; - var modifyItem = (editHelpers || {}).modifyItem; - var allShapes = []; - for (var q = 0; q < shapes2.length; q++) { - var beforeEdit = gd._fullLayout.shapes[q]; - allShapes[q] = beforeEdit._input; - if (isActiveShape !== void 0 && q === gd._fullLayout._activeShapeIndex) { - var afterEdit = newShape; - switch (beforeEdit.type) { - case "line": - case "rect": - case "circle": - modifyItem("x0", afterEdit.x0 - (beforeEdit.x0shift || 0)); - modifyItem("x1", afterEdit.x1 - (beforeEdit.x1shift || 0)); - modifyItem("y0", afterEdit.y0 - (beforeEdit.y0shift || 0)); - modifyItem("y1", afterEdit.y1 - (beforeEdit.y1shift || 0)); - break; - case "path": - modifyItem("path", afterEdit.path); - break; - } - } - } - if (isActiveShape === void 0) { - allShapes.push(newShape); - return allShapes; - } - return editHelpers ? editHelpers.getUpdateObj() : {}; -} -function createShapeObj$1(outlines, dragOptions, dragmode) { - var e = outlines[0][0]; - var gd = dragOptions.gd; - var d = e.getAttribute("d"); - var newStyle = gd._fullLayout.newshape; - var plotinfo = dragOptions.plotinfo; - var isActiveShape = dragOptions.isActiveShape; - var xaxis = plotinfo.xaxis; - var yaxis = plotinfo.yaxis; - var xPaper = !!plotinfo.domain || !plotinfo.xaxis; - var yPaper = !!plotinfo.domain || !plotinfo.yaxis; - var isOpenMode = openMode$1(dragmode); - var polygons = readPaths$5(d, gd, plotinfo, isActiveShape); - var newShape = { - editable: true, - visible: newStyle.visible, - name: newStyle.name, - showlegend: newStyle.showlegend, - legend: newStyle.legend, - legendwidth: newStyle.legendwidth, - legendgroup: newStyle.legendgroup, - legendgrouptitle: { - text: newStyle.legendgrouptitle.text, - font: newStyle.legendgrouptitle.font - }, - legendrank: newStyle.legendrank, - label: newStyle.label, - xref: xPaper ? "paper" : xaxis._id, - yref: yPaper ? "paper" : yaxis._id, - layer: newStyle.layer, - opacity: newStyle.opacity, - line: { - color: newStyle.line.color, - width: newStyle.line.width, - dash: newStyle.line.dash - } - }; - if (!isOpenMode) { - newShape.fillcolor = newStyle.fillcolor; - newShape.fillrule = newStyle.fillrule; - } - var cell; - if (polygons.length === 1) cell = polygons[0]; - if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect - dragmode === "drawrect") { - newShape.type = "rect"; - newShape.x0 = cell[0][1]; - newShape.y0 = cell[0][2]; - newShape.x1 = cell[2][1]; - newShape.y1 = cell[2][2]; - } else if (cell && dragmode === "drawline") { - newShape.type = "line"; - newShape.x0 = cell[0][1]; - newShape.y0 = cell[0][2]; - newShape.x1 = cell[1][1]; - newShape.y1 = cell[1][2]; - } else if (cell && dragmode === "drawcircle") { - newShape.type = "circle"; - var xA = cell[i000$1][1]; - var xB = cell[i090$1][1]; - var xC = cell[i180$1][1]; - var xD = cell[i270$1][1]; - var yA = cell[i000$1][2]; - var yB = cell[i090$1][2]; - var yC = cell[i180$1][2]; - var yD = cell[i270$1][2]; - var xDateOrLog = plotinfo.xaxis && (plotinfo.xaxis.type === "date" || plotinfo.xaxis.type === "log"); - var yDateOrLog = plotinfo.yaxis && (plotinfo.yaxis.type === "date" || plotinfo.yaxis.type === "log"); - if (xDateOrLog) { - xA = r2p(plotinfo.xaxis, xA); - xB = r2p(plotinfo.xaxis, xB); - xC = r2p(plotinfo.xaxis, xC); - xD = r2p(plotinfo.xaxis, xD); - } - if (yDateOrLog) { - yA = r2p(plotinfo.yaxis, yA); - yB = r2p(plotinfo.yaxis, yB); - yC = r2p(plotinfo.yaxis, yC); - yD = r2p(plotinfo.yaxis, yD); - } - var x0 = (xB + xD) / 2; - var y0 = (yA + yC) / 2; - var rx = (xD - xB + xC - xA) / 2; - var ry = (yD - yB + yC - yA) / 2; - var pos = ellipseOver({ - x0, - y0, - x1: x0 + rx * cos45, - y1: y0 + ry * sin45 - }); - if (xDateOrLog) { - pos.x0 = p2r$1(plotinfo.xaxis, pos.x0); - pos.x1 = p2r$1(plotinfo.xaxis, pos.x1); - } - if (yDateOrLog) { - pos.y0 = p2r$1(plotinfo.yaxis, pos.y0); - pos.y1 = p2r$1(plotinfo.yaxis, pos.y1); - } - newShape.x0 = pos.x0; - newShape.y0 = pos.y0; - newShape.x1 = pos.x1; - newShape.y1 = pos.y1; - } else { - newShape.type = "path"; - if (xaxis && yaxis) fixDatesForPaths$1(polygons, xaxis, yaxis); - newShape.path = writePaths$2(polygons); - cell = null; - } - return newShape; -} -var newshapes = { - newShapes: newShapes$2, - createShapeObj: createShapeObj$1 -}; -var dragHelpers$2 = helpers$B; -var selectMode$3 = dragHelpers$2.selectMode; -var handleOutline$1 = handle_outline; -var clearOutline$1 = handleOutline$1.clearOutline; -var helpers$x = helpers$A; -var readPaths$4 = helpers$x.readPaths; -var writePaths$1 = helpers$x.writePaths; -var fixDatesForPaths = helpers$x.fixDatesForPaths; -var newselections = function newSelections(outlines, dragOptions) { - if (!outlines.length) return; - var e = outlines[0][0]; - if (!e) return; - var d = e.getAttribute("d"); - var gd = dragOptions.gd; - var newStyle = gd._fullLayout.newselection; - var plotinfo = dragOptions.plotinfo; - var xaxis = plotinfo.xaxis; - var yaxis = plotinfo.yaxis; - var isActiveSelection = dragOptions.isActiveSelection; - var dragmode = dragOptions.dragmode; - var selections2 = (gd.layout || {}).selections || []; - if (!selectMode$3(dragmode) && isActiveSelection !== void 0) { - var id = gd._fullLayout._activeSelectionIndex; - if (id < selections2.length) { - switch (gd._fullLayout.selections[id].type) { - case "rect": - dragmode = "select"; - break; - case "path": - dragmode = "lasso"; - break; - } - } - } - var polygons = readPaths$4(d, gd, plotinfo, isActiveSelection); - var newSelection = { - xref: xaxis._id, - yref: yaxis._id, - opacity: newStyle.opacity, - line: { - color: newStyle.line.color, - width: newStyle.line.width, - dash: newStyle.line.dash - } - }; - var cell; - if (polygons.length === 1) cell = polygons[0]; - if (cell && cell.length === 5 && // ensure we only have 4 corners for a rect - dragmode === "select") { - newSelection.type = "rect"; - newSelection.x0 = cell[0][1]; - newSelection.y0 = cell[0][2]; - newSelection.x1 = cell[2][1]; - newSelection.y1 = cell[2][2]; - } else { - newSelection.type = "path"; - if (xaxis && yaxis) fixDatesForPaths(polygons, xaxis, yaxis); - newSelection.path = writePaths$1(polygons); - cell = null; - } - clearOutline$1(gd); - var editHelpers = dragOptions.editHelpers; - var modifyItem = (editHelpers || {}).modifyItem; - var allSelections = []; - for (var q = 0; q < selections2.length; q++) { - var beforeEdit = gd._fullLayout.selections[q]; - if (!beforeEdit) { - allSelections[q] = beforeEdit; - continue; - } - allSelections[q] = beforeEdit._input; - if (isActiveSelection !== void 0 && q === gd._fullLayout._activeSelectionIndex) { - var afterEdit = newSelection; - switch (beforeEdit.type) { - case "rect": - modifyItem("x0", afterEdit.x0); - modifyItem("x1", afterEdit.x1); - modifyItem("y0", afterEdit.y0); - modifyItem("y1", afterEdit.y1); - break; - case "path": - modifyItem("path", afterEdit.path); - break; - } - } - } - if (isActiveSelection === void 0) { - allSelections.push(newSelection); - return allSelections; - } - return editHelpers ? editHelpers.getUpdateObj() : {}; -}; -var helpers$w = {}; -var constants$I = { - segmentRE: /[MLHVQCTSZ][^MLHVQCTSZ]*/g, - paramRE: /[^\s,]+/g, - // which numbers in each path segment are x (or y) values - // drawn is which param is a drawn point, as opposed to a - // control point (which doesn't count toward autorange. - // TODO: this means curved paths could extend beyond the - // autorange bounds. This is a bit tricky to get right - // unless we revert to bounding boxes, but perhaps there's - // a calculation we could do...) - paramIsX: { - M: { 0: true, drawn: 0 }, - L: { 0: true, drawn: 0 }, - H: { 0: true, drawn: 0 }, - V: {}, - Q: { 0: true, 2: true, drawn: 2 }, - C: { 0: true, 2: true, 4: true, drawn: 4 }, - T: { 0: true, drawn: 0 }, - S: { 0: true, 2: true, drawn: 2 }, - // A: {0: true, 5: true}, - Z: {} - }, - paramIsY: { - M: { 1: true, drawn: 1 }, - L: { 1: true, drawn: 1 }, - H: {}, - V: { 0: true, drawn: 0 }, - Q: { 1: true, 3: true, drawn: 3 }, - C: { 1: true, 3: true, 5: true, drawn: 5 }, - T: { 1: true, drawn: 1 }, - S: { 1: true, 3: true, drawn: 5 }, - // A: {1: true, 6: true}, - Z: {} - }, - numParams: { - M: 2, - L: 2, - H: 1, - V: 1, - Q: 4, - C: 6, - T: 2, - S: 4, - // A: 7, - Z: 0 - } -}; -(function(exports2) { - var constants2 = constants$I; - var Lib2 = libExports; - var Axes2 = axesExports; - exports2.rangeToShapePosition = function(ax) { - return ax.type === "log" ? ax.r2d : function(v) { - return v; - }; - }; - exports2.shapePositionToRange = function(ax) { - return ax.type === "log" ? ax.d2r : function(v) { - return v; - }; - }; - exports2.decodeDate = function(convertToPx) { - return function(v) { - if (v.replace) v = v.replace("_", " "); - return convertToPx(v); - }; - }; - exports2.encodeDate = function(convertToDate) { - return function(v) { - return convertToDate(v).replace(" ", "_"); - }; - }; - exports2.extractPathCoords = function(path, paramsToUse, isRaw) { - var extractedCoordinates = []; - var segments = path.match(constants2.segmentRE); - segments.forEach(function(segment2) { - var relevantParamIdx = paramsToUse[segment2.charAt(0)].drawn; - if (relevantParamIdx === void 0) return; - var params = segment2.substr(1).match(constants2.paramRE); - if (!params || params.length < relevantParamIdx) return; - var str2 = params[relevantParamIdx]; - var pos = isRaw ? str2 : Lib2.cleanNumber(str2); - extractedCoordinates.push(pos); - }); - return extractedCoordinates; - }; - exports2.getDataToPixel = function(gd, axis, shift, isVertical2, refType) { - var gs = gd._fullLayout._size; - var dataToPixel; - if (axis) { - if (refType === "domain") { - dataToPixel = function(v) { - return axis._length * (isVertical2 ? 1 - v : v) + axis._offset; - }; - } else { - var d2r = exports2.shapePositionToRange(axis); - dataToPixel = function(v) { - var shiftPixels = getPixelShift(axis, shift); - return axis._offset + axis.r2p(d2r(v, true)) + shiftPixels; - }; - if (axis.type === "date") dataToPixel = exports2.decodeDate(dataToPixel); - } - } else if (isVertical2) { - dataToPixel = function(v) { - return gs.t + gs.h * (1 - v); - }; - } else { - dataToPixel = function(v) { - return gs.l + gs.w * v; - }; - } - return dataToPixel; - }; - exports2.getPixelToData = function(gd, axis, isVertical2, opt) { - var gs = gd._fullLayout._size; - var pixelToData; - if (axis) { - if (opt === "domain") { - pixelToData = function(p) { - var q = (p - axis._offset) / axis._length; - return isVertical2 ? 1 - q : q; - }; - } else { - var r2d = exports2.rangeToShapePosition(axis); - pixelToData = function(p) { - return r2d(axis.p2r(p - axis._offset)); - }; - } - } else if (isVertical2) { - pixelToData = function(p) { - return 1 - (p - gs.t) / gs.h; - }; - } else { - pixelToData = function(p) { - return (p - gs.l) / gs.w; - }; - } - return pixelToData; - }; - exports2.roundPositionForSharpStrokeRendering = function(pos, strokeWidth) { - var strokeWidthIsOdd = Math.round(strokeWidth % 2) === 1; - var posValAsInt = Math.round(pos); - return strokeWidthIsOdd ? posValAsInt + 0.5 : posValAsInt; - }; - exports2.makeShapesOptionsAndPlotinfo = function(gd, index2) { - var options = gd._fullLayout.shapes[index2] || {}; - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - var hasPlotinfo = !!plotinfo; - if (hasPlotinfo) { - plotinfo._hadPlotinfo = true; - } else { - plotinfo = {}; - if (options.xref && options.xref !== "paper") plotinfo.xaxis = gd._fullLayout[options.xref + "axis"]; - if (options.yref && options.yref !== "paper") plotinfo.yaxis = gd._fullLayout[options.yref + "axis"]; - } - plotinfo.xsizemode = options.xsizemode; - plotinfo.ysizemode = options.ysizemode; - plotinfo.xanchor = options.xanchor; - plotinfo.yanchor = options.yanchor; - return { - options, - plotinfo - }; - }; - exports2.makeSelectionsOptionsAndPlotinfo = function(gd, index2) { - var options = gd._fullLayout.selections[index2] || {}; - var plotinfo = gd._fullLayout._plots[options.xref + options.yref]; - var hasPlotinfo = !!plotinfo; - if (hasPlotinfo) { - plotinfo._hadPlotinfo = true; - } else { - plotinfo = {}; - if (options.xref) plotinfo.xaxis = gd._fullLayout[options.xref + "axis"]; - if (options.yref) plotinfo.yaxis = gd._fullLayout[options.yref + "axis"]; - } - return { - options, - plotinfo - }; - }; - exports2.getPathString = function(gd, options) { - var type = options.type; - var xRefType = Axes2.getRefType(options.xref); - var yRefType = Axes2.getRefType(options.yref); - var xa = Axes2.getFromId(gd, options.xref); - var ya = Axes2.getFromId(gd, options.yref); - var gs = gd._fullLayout._size; - var x2r, x2p, y2r, y2p; - var xShiftStart = getPixelShift(xa, options.x0shift); - var xShiftEnd = getPixelShift(xa, options.x1shift); - var yShiftStart = getPixelShift(ya, options.y0shift); - var yShiftEnd = getPixelShift(ya, options.y1shift); - var x0, x1, y0, y1; - if (xa) { - if (xRefType === "domain") { - x2p = function(v) { - return xa._offset + xa._length * v; - }; - } else { - x2r = exports2.shapePositionToRange(xa); - x2p = function(v) { - return xa._offset + xa.r2p(x2r(v, true)); - }; - } - } else { - x2p = function(v) { - return gs.l + gs.w * v; - }; - } - if (ya) { - if (yRefType === "domain") { - y2p = function(v) { - return ya._offset + ya._length * (1 - v); - }; - } else { - y2r = exports2.shapePositionToRange(ya); - y2p = function(v) { - return ya._offset + ya.r2p(y2r(v, true)); - }; - } - } else { - y2p = function(v) { - return gs.t + gs.h * (1 - v); - }; - } - if (type === "path") { - if (xa && xa.type === "date") x2p = exports2.decodeDate(x2p); - if (ya && ya.type === "date") y2p = exports2.decodeDate(y2p); - return convertPath(options, x2p, y2p); - } - if (options.xsizemode === "pixel") { - var xAnchorPos = x2p(options.xanchor); - x0 = xAnchorPos + options.x0 + xShiftStart; - x1 = xAnchorPos + options.x1 + xShiftEnd; - } else { - x0 = x2p(options.x0) + xShiftStart; - x1 = x2p(options.x1) + xShiftEnd; - } - if (options.ysizemode === "pixel") { - var yAnchorPos = y2p(options.yanchor); - y0 = yAnchorPos - options.y0 + yShiftStart; - y1 = yAnchorPos - options.y1 + yShiftEnd; - } else { - y0 = y2p(options.y0) + yShiftStart; - y1 = y2p(options.y1) + yShiftEnd; - } - if (type === "line") return "M" + x0 + "," + y0 + "L" + x1 + "," + y1; - if (type === "rect") return "M" + x0 + "," + y0 + "H" + x1 + "V" + y1 + "H" + x0 + "Z"; - var cx = (x0 + x1) / 2; - var cy = (y0 + y1) / 2; - var rx = Math.abs(cx - x0); - var ry = Math.abs(cy - y0); - var rArc = "A" + rx + "," + ry; - var rightPt = cx + rx + "," + cy; - var topPt = cx + "," + (cy - ry); - return "M" + rightPt + rArc + " 0 1,1 " + topPt + rArc + " 0 0,1 " + rightPt + "Z"; - }; - function convertPath(options, x2p, y2p) { - var pathIn = options.path; - var xSizemode = options.xsizemode; - var ySizemode = options.ysizemode; - var xAnchor = options.xanchor; - var yAnchor = options.yanchor; - return pathIn.replace(constants2.segmentRE, function(segment2) { - var paramNumber = 0; - var segmentType = segment2.charAt(0); - var xParams = constants2.paramIsX[segmentType]; - var yParams = constants2.paramIsY[segmentType]; - var nParams = constants2.numParams[segmentType]; - var paramString = segment2.substr(1).replace(constants2.paramRE, function(param) { - if (xParams[paramNumber]) { - if (xSizemode === "pixel") param = x2p(xAnchor) + Number(param); - else param = x2p(param); - } else if (yParams[paramNumber]) { - if (ySizemode === "pixel") param = y2p(yAnchor) - Number(param); - else param = y2p(param); - } - paramNumber++; - if (paramNumber > nParams) param = "X"; - return param; - }); - if (paramNumber > nParams) { - paramString = paramString.replace(/[\s,]*X.*/, ""); - Lib2.log("Ignoring extra params in segment " + segment2); - } - return segmentType + paramString; - }); - } - function getPixelShift(axis, shift) { - shift = shift || 0; - var shiftPixels = 0; - if (shift && axis && (axis.type === "category" || axis.type === "multicategory")) { - shiftPixels = (axis.r2p(1) - axis.r2p(0)) * shift; - } - return shiftPixels; - } -})(helpers$w); -var Lib$1q = libExports; -var Axes$k = axesExports; -var svgTextUtils$a = svg_text_utils; -var Drawing$n = drawingExports; -var readPaths$3 = helpers$A.readPaths; -var helpers$v = helpers$w; -var getPathString$2 = helpers$v.getPathString; -var shapeLabelTexttemplateVars$1 = label_texttemplate; -var FROM_TL$3 = alignment$1.FROM_TL; -var display_labels = function drawLabel(gd, index2, options, shapeGroup) { - shapeGroup.selectAll(".shape-label").remove(); - if (!(options.label.text || options.label.texttemplate)) return; - var text; - if (options.label.texttemplate) { - var templateValues = {}; - if (options.type !== "path") { - var _xa = Axes$k.getFromId(gd, options.xref); - var _ya = Axes$k.getFromId(gd, options.yref); - for (var key in shapeLabelTexttemplateVars$1) { - var val = shapeLabelTexttemplateVars$1[key](options, _xa, _ya); - if (val !== void 0) templateValues[key] = val; - } - } - text = Lib$1q.texttemplateStringForShapes( - options.label.texttemplate, - {}, - gd._fullLayout._d3locale, - templateValues - ); - } else { - text = options.label.text; - } - var labelGroupAttrs = { - "data-index": index2 - }; - var font2 = options.label.font; - var labelTextAttrs = { - "data-notex": 1 - }; - var labelGroup = shapeGroup.append("g").attr(labelGroupAttrs).classed("shape-label", true); - var labelText = labelGroup.append("text").attr(labelTextAttrs).classed("shape-label-text", true).text(text); - var shapex0, shapex1, shapey0, shapey1; - if (options.path) { - var d = getPathString$2(gd, options); - var polygons = readPaths$3(d, gd); - shapex0 = Infinity; - shapey0 = Infinity; - shapex1 = -Infinity; - shapey1 = -Infinity; - for (var i = 0; i < polygons.length; i++) { - for (var j = 0; j < polygons[i].length; j++) { - var p = polygons[i][j]; - for (var k = 1; k < p.length; k += 2) { - var _x = p[k]; - var _y = p[k + 1]; - shapex0 = Math.min(shapex0, _x); - shapex1 = Math.max(shapex1, _x); - shapey0 = Math.min(shapey0, _y); - shapey1 = Math.max(shapey1, _y); - } - } - } - } else { - var xa = Axes$k.getFromId(gd, options.xref); - var xShiftStart = options.x0shift; - var xShiftEnd = options.x1shift; - var xRefType = Axes$k.getRefType(options.xref); - var ya = Axes$k.getFromId(gd, options.yref); - var yShiftStart = options.y0shift; - var yShiftEnd = options.y1shift; - var yRefType = Axes$k.getRefType(options.yref); - var x2p = function(v, shift) { - var dataToPixel = helpers$v.getDataToPixel(gd, xa, shift, false, xRefType); - return dataToPixel(v); - }; - var y2p = function(v, shift) { - var dataToPixel = helpers$v.getDataToPixel(gd, ya, shift, true, yRefType); - return dataToPixel(v); - }; - shapex0 = x2p(options.x0, xShiftStart); - shapex1 = x2p(options.x1, xShiftEnd); - shapey0 = y2p(options.y0, yShiftStart); - shapey1 = y2p(options.y1, yShiftEnd); - } - var textangle = options.label.textangle; - if (textangle === "auto") { - if (options.type === "line") { - textangle = calcTextAngle(shapex0, shapey0, shapex1, shapey1); - } else { - textangle = 0; - } - } - labelText.call(function(s) { - s.call(Drawing$n.font, font2).attr({}); - svgTextUtils$a.convertToTspans(s, gd); - return s; - }); - var textBB = Drawing$n.bBox(labelText.node()); - var textPos = calcTextPosition(shapex0, shapey0, shapex1, shapey1, options, textangle, textBB); - var textx = textPos.textx; - var texty = textPos.texty; - var xanchor = textPos.xanchor; - labelText.attr({ - "text-anchor": { - left: "start", - center: "middle", - right: "end" - }[xanchor], - y: texty, - x: textx, - transform: "rotate(" + textangle + "," + textx + "," + texty + ")" - }).call(svgTextUtils$a.positionText, textx, texty); -}; -function calcTextAngle(shapex0, shapey0, shapex1, shapey1) { - var dy, dx; - dx = Math.abs(shapex1 - shapex0); - if (shapex1 >= shapex0) { - dy = shapey0 - shapey1; - } else { - dy = shapey1 - shapey0; - } - return -180 / Math.PI * Math.atan2(dy, dx); -} -function calcTextPosition(shapex0, shapey0, shapex1, shapey1, shapeOptions, actualTextAngle, textBB) { - var textPosition = shapeOptions.label.textposition; - var textAngle = shapeOptions.label.textangle; - var textPadding = shapeOptions.label.padding; - var shapeType = shapeOptions.type; - var textAngleRad = Math.PI / 180 * actualTextAngle; - var sinA = Math.sin(textAngleRad); - var cosA = Math.cos(textAngleRad); - var xanchor = shapeOptions.label.xanchor; - var yanchor = shapeOptions.label.yanchor; - var textx, texty, paddingX, paddingY; - if (shapeType === "line") { - if (textPosition === "start") { - textx = shapex0; - texty = shapey0; - } else if (textPosition === "end") { - textx = shapex1; - texty = shapey1; - } else { - textx = (shapex0 + shapex1) / 2; - texty = (shapey0 + shapey1) / 2; - } - if (xanchor === "auto") { - if (textPosition === "start") { - if (textAngle === "auto") { - if (shapex1 > shapex0) xanchor = "left"; - else if (shapex1 < shapex0) xanchor = "right"; - else xanchor = "center"; - } else { - if (shapex1 > shapex0) xanchor = "right"; - else if (shapex1 < shapex0) xanchor = "left"; - else xanchor = "center"; - } - } else if (textPosition === "end") { - if (textAngle === "auto") { - if (shapex1 > shapex0) xanchor = "right"; - else if (shapex1 < shapex0) xanchor = "left"; - else xanchor = "center"; - } else { - if (shapex1 > shapex0) xanchor = "left"; - else if (shapex1 < shapex0) xanchor = "right"; - else xanchor = "center"; - } - } else { - xanchor = "center"; - } - } - var paddingConstantsX = { left: 1, center: 0, right: -1 }; - var paddingConstantsY = { bottom: -1, middle: 0, top: 1 }; - if (textAngle === "auto") { - var paddingDirection = paddingConstantsY[yanchor]; - paddingX = -textPadding * sinA * paddingDirection; - paddingY = textPadding * cosA * paddingDirection; - } else { - var paddingDirectionX = paddingConstantsX[xanchor]; - var paddingDirectionY = paddingConstantsY[yanchor]; - paddingX = textPadding * paddingDirectionX; - paddingY = textPadding * paddingDirectionY; - } - textx = textx + paddingX; - texty = texty + paddingY; - } else { - paddingX = textPadding + 3; - if (textPosition.indexOf("right") !== -1) { - textx = Math.max(shapex0, shapex1) - paddingX; - if (xanchor === "auto") xanchor = "right"; - } else if (textPosition.indexOf("left") !== -1) { - textx = Math.min(shapex0, shapex1) + paddingX; - if (xanchor === "auto") xanchor = "left"; - } else { - textx = (shapex0 + shapex1) / 2; - if (xanchor === "auto") xanchor = "center"; - } - if (textPosition.indexOf("top") !== -1) { - texty = Math.min(shapey0, shapey1); - } else if (textPosition.indexOf("bottom") !== -1) { - texty = Math.max(shapey0, shapey1); - } else { - texty = (shapey0 + shapey1) / 2; - } - paddingY = textPadding; - if (yanchor === "bottom") { - texty = texty - paddingY; - } else if (yanchor === "top") { - texty = texty + paddingY; - } - } - var shiftFraction = FROM_TL$3[yanchor]; - var baselineAdjust = shapeOptions.label.font.size; - var textHeight = textBB.height; - var xshift = (textHeight * shiftFraction - baselineAdjust) * sinA; - var yshift = -(textHeight * shiftFraction - baselineAdjust) * cosA; - return { textx: textx + xshift, texty: texty + yshift, xanchor }; -} -var Lib$1p = libExports; -var strTranslate$6 = Lib$1p.strTranslate; -var dragElement$3 = dragelementExports; -var dragHelpers$1 = helpers$B; -var drawMode$1 = dragHelpers$1.drawMode; -var selectMode$2 = dragHelpers$1.selectMode; -var Registry$z = registry; -var Color$A = colorExports; -var constants$H = constants$K; -var i000 = constants$H.i000; -var i090 = constants$H.i090; -var i180 = constants$H.i180; -var i270 = constants$H.i270; -var handleOutline = handle_outline; -var clearOutlineControllers$2 = handleOutline.clearOutlineControllers; -var helpers$u = helpers$A; -var pointsOnRectangle = helpers$u.pointsOnRectangle; -var pointsOnEllipse = helpers$u.pointsOnEllipse; -var writePaths = helpers$u.writePaths; -var newShapes$1 = newshapes.newShapes; -var createShapeObj = newshapes.createShapeObj; -var newSelections$1 = newselections; -var drawLabel$2 = display_labels; -var display_outlines = function displayOutlines(polygons, outlines, dragOptions, nCalls) { - if (!nCalls) nCalls = 0; - var gd = dragOptions.gd; - function redraw() { - displayOutlines(polygons, outlines, dragOptions, nCalls++); - if (pointsOnEllipse(polygons[0]) || dragOptions.hasText) { - update2({ redrawing: true }); - } - } - function update2(opts) { - var updateObject = {}; - if (dragOptions.isActiveShape !== void 0) { - dragOptions.isActiveShape = false; - updateObject = newShapes$1(outlines, dragOptions); - } - if (dragOptions.isActiveSelection !== void 0) { - dragOptions.isActiveSelection = false; - updateObject = newSelections$1(outlines, dragOptions); - gd._fullLayout._reselect = true; - } - if (Object.keys(updateObject).length) { - Registry$z.call((opts || {}).redrawing ? "relayout" : "_guiRelayout", gd, updateObject); - } - } - var fullLayout = gd._fullLayout; - var zoomLayer = fullLayout._zoomlayer; - var dragmode = dragOptions.dragmode; - var isDrawMode = drawMode$1(dragmode); - var isSelectMode = selectMode$2(dragmode); - if (isDrawMode || isSelectMode) { - gd._fullLayout._outlining = true; - } - clearOutlineControllers$2(gd); - outlines.attr("d", writePaths(polygons)); - var vertexDragOptions; - var groupDragOptions; - var indexI; - var indexJ; - var copyPolygons; - if (!nCalls && (dragOptions.isActiveShape || dragOptions.isActiveSelection)) { - copyPolygons = recordPositions([], polygons); - var g = zoomLayer.append("g").attr("class", "outline-controllers"); - addVertexControllers(g); - addGroupControllers(); - } - if (isDrawMode && dragOptions.hasText) { - var shapeGroup = zoomLayer.select(".label-temp"); - var shapeOptions = createShapeObj(outlines, dragOptions, dragOptions.dragmode); - drawLabel$2(gd, "label-temp", shapeOptions, shapeGroup); - } - function startDragVertex(evt) { - indexI = +evt.srcElement.getAttribute("data-i"); - indexJ = +evt.srcElement.getAttribute("data-j"); - vertexDragOptions[indexI][indexJ].moveFn = moveVertexController; - } - function moveVertexController(dx, dy) { - if (!polygons.length) return; - var x0 = copyPolygons[indexI][indexJ][1]; - var y0 = copyPolygons[indexI][indexJ][2]; - var cell = polygons[indexI]; - var len = cell.length; - if (pointsOnRectangle(cell)) { - var _dx = dx; - var _dy = dy; - if (dragOptions.isActiveSelection) { - var nextPoint = getNextPoint(cell, indexJ); - if (nextPoint[1] === cell[indexJ][1]) { - _dy = 0; - } else { - _dx = 0; - } - } - for (var q = 0; q < len; q++) { - if (q === indexJ) continue; - var pos = cell[q]; - if (pos[1] === cell[indexJ][1]) { - pos[1] = x0 + _dx; - } - if (pos[2] === cell[indexJ][2]) { - pos[2] = y0 + _dy; - } - } - cell[indexJ][1] = x0 + _dx; - cell[indexJ][2] = y0 + _dy; - if (!pointsOnRectangle(cell)) { - for (var j = 0; j < len; j++) { - for (var k = 0; k < cell[j].length; k++) { - cell[j][k] = copyPolygons[indexI][j][k]; - } - } - } - } else { - cell[indexJ][1] = x0 + dx; - cell[indexJ][2] = y0 + dy; - } - redraw(); - } - function endDragVertexController() { - update2(); - } - function removeVertex() { - if (!polygons.length) return; - if (!polygons[indexI]) return; - if (!polygons[indexI].length) return; - var newPolygon = []; - for (var j = 0; j < polygons[indexI].length; j++) { - if (j !== indexJ) { - newPolygon.push( - polygons[indexI][j] - ); - } - } - if (newPolygon.length > 1 && !(newPolygon.length === 2 && newPolygon[1][0] === "Z")) { - if (indexJ === 0) { - newPolygon[0][0] = "M"; - } - polygons[indexI] = newPolygon; - redraw(); - update2(); - } - } - function clickVertexController(numClicks, evt) { - if (numClicks === 2) { - indexI = +evt.srcElement.getAttribute("data-i"); - indexJ = +evt.srcElement.getAttribute("data-j"); - var cell = polygons[indexI]; - if (!pointsOnRectangle(cell) && !pointsOnEllipse(cell)) { - removeVertex(); - } - } - } - function addVertexControllers(g2) { - vertexDragOptions = []; - for (var i = 0; i < polygons.length; i++) { - var cell = polygons[i]; - var onRect = pointsOnRectangle(cell); - var onEllipse = !onRect && pointsOnEllipse(cell); - vertexDragOptions[i] = []; - var len = cell.length; - for (var j = 0; j < len; j++) { - if (cell[j][0] === "Z") continue; - if (onEllipse && j !== i000 && j !== i090 && j !== i180 && j !== i270) { - continue; - } - var rectSelection = onRect && dragOptions.isActiveSelection; - var nextPoint; - if (rectSelection) nextPoint = getNextPoint(cell, j); - var x = cell[j][1]; - var y = cell[j][2]; - var vertex = g2.append(rectSelection ? "rect" : "circle").attr("data-i", i).attr("data-j", j).style({ - fill: Color$A.background, - stroke: Color$A.defaultLine, - "stroke-width": 1, - "shape-rendering": "crispEdges" - }); - if (rectSelection) { - var dx = nextPoint[1] - x; - var dy = nextPoint[2] - y; - var width = dy ? 5 : Math.max(Math.min(25, Math.abs(dx) - 5), 5); - var height = dx ? 5 : Math.max(Math.min(25, Math.abs(dy) - 5), 5); - vertex.classed(dy ? "cursor-ew-resize" : "cursor-ns-resize", true).attr("width", width).attr("height", height).attr("x", x - width / 2).attr("y", y - height / 2).attr("transform", strTranslate$6(dx / 2, dy / 2)); - } else { - vertex.classed("cursor-grab", true).attr("r", 5).attr("cx", x).attr("cy", y); - } - vertexDragOptions[i][j] = { - element: vertex.node(), - gd, - prepFn: startDragVertex, - doneFn: endDragVertexController, - clickFn: clickVertexController - }; - dragElement$3.init(vertexDragOptions[i][j]); - } - } - } - function moveGroup(dx, dy) { - if (!polygons.length) return; - for (var i = 0; i < polygons.length; i++) { - for (var j = 0; j < polygons[i].length; j++) { - for (var k = 0; k + 2 < polygons[i][j].length; k += 2) { - polygons[i][j][k + 1] = copyPolygons[i][j][k + 1] + dx; - polygons[i][j][k + 2] = copyPolygons[i][j][k + 2] + dy; - } - } - } - } - function moveGroupController(dx, dy) { - moveGroup(dx, dy); - redraw(); - } - function startDragGroupController(evt) { - indexI = +evt.srcElement.getAttribute("data-i"); - if (!indexI) indexI = 0; - groupDragOptions[indexI].moveFn = moveGroupController; - } - function endDragGroupController() { - update2(); - } - function clickGroupController(numClicks) { - if (numClicks === 2) { - eraseActiveSelection(gd); - } - } - function addGroupControllers() { - groupDragOptions = []; - if (!polygons.length) return; - var i = 0; - groupDragOptions[i] = { - element: outlines[0][0], - gd, - prepFn: startDragGroupController, - doneFn: endDragGroupController, - clickFn: clickGroupController - }; - dragElement$3.init(groupDragOptions[i]); - } -}; -function recordPositions(polygonsOut, polygonsIn) { - for (var i = 0; i < polygonsIn.length; i++) { - var cell = polygonsIn[i]; - polygonsOut[i] = []; - for (var j = 0; j < cell.length; j++) { - polygonsOut[i][j] = []; - for (var k = 0; k < cell[j].length; k++) { - polygonsOut[i][j][k] = cell[j][k]; - } - } - } - return polygonsOut; -} -function getNextPoint(cell, j) { - var x = cell[j][1]; - var y = cell[j][2]; - var len = cell.length; - var nextJ, nextX, nextY; - nextJ = (j + 1) % len; - nextX = cell[nextJ][1]; - nextY = cell[nextJ][2]; - if (nextX === x && nextY === y) { - nextJ = (j + 2) % len; - nextX = cell[nextJ][1]; - nextY = cell[nextJ][2]; - } - return [nextJ, nextX, nextY]; -} -function eraseActiveSelection(gd) { - if (!selectMode$2(gd._fullLayout.dragmode)) return; - clearOutlineControllers$2(gd); - var id = gd._fullLayout._activeSelectionIndex; - var selections2 = (gd.layout || {}).selections || []; - if (id < selections2.length) { - var list = []; - for (var q = 0; q < selections2.length; q++) { - if (q !== id) { - list.push(selections2[q]); - } - } - delete gd._fullLayout._activeSelectionIndex; - var erasedSelection = gd._fullLayout.selections[id]; - gd._fullLayout._deselect = { - xref: erasedSelection.xref, - yref: erasedSelection.yref - }; - Registry$z.call("_guiRelayout", gd, { - selections: list - }); - } -} -var d3$q = d3Exports; -var Registry$y = registry; -var Lib$1o = libExports; -var Axes$j = axesExports; -var readPaths$2 = helpers$A.readPaths; -var displayOutlines$2 = display_outlines; -var drawLabel$1 = display_labels; -var clearOutlineControllers$1 = handle_outline.clearOutlineControllers; -var Color$z = colorExports; -var Drawing$m = drawingExports; -var arrayEditor$5 = plot_template.arrayEditor; -var dragElement$2 = dragelementExports; -var setCursor$2 = setcursor; -var constants$G = constants$I; -var helpers$t = helpers$w; -var getPathString$1 = helpers$t.getPathString; -var draw_1$3 = { - draw: draw$c, - drawOne: drawOne$2, - eraseActiveShape: eraseActiveShape$2 -}; -function draw$c(gd) { - var fullLayout = gd._fullLayout; - fullLayout._shapeUpperLayer.selectAll("path").remove(); - fullLayout._shapeLowerLayer.selectAll("path").remove(); - fullLayout._shapeUpperLayer.selectAll("text").remove(); - fullLayout._shapeLowerLayer.selectAll("text").remove(); - for (var k in fullLayout._plots) { - var shapelayer = fullLayout._plots[k].shapelayer; - if (shapelayer) { - shapelayer.selectAll("path").remove(); - shapelayer.selectAll("text").remove(); - } - } - for (var i = 0; i < fullLayout.shapes.length; i++) { - if (fullLayout.shapes[i].visible === true) { - drawOne$2(gd, i); - } - } -} -function shouldSkipEdits(gd) { - return !!gd._fullLayout._outlining; -} -function couldHaveActiveShape(gd) { - return !gd._context.edits.shapePosition; -} -function drawOne$2(gd, index2) { - gd._fullLayout._paperdiv.selectAll('.shapelayer [data-index="' + index2 + '"]').remove(); - var o = helpers$t.makeShapesOptionsAndPlotinfo(gd, index2); - var options = o.options; - var plotinfo = o.plotinfo; - if (!options._input || options.visible !== true) return; - if (options.layer === "above") { - drawShape(gd._fullLayout._shapeUpperLayer); - } else if (options.xref === "paper" || options.yref === "paper") { - drawShape(gd._fullLayout._shapeLowerLayer); - } else if (options.layer === "between") { - drawShape(plotinfo.shapelayerBetween); - } else { - if (plotinfo._hadPlotinfo) { - var mainPlot = plotinfo.mainplotinfo || plotinfo; - drawShape(mainPlot.shapelayer); - } else { - drawShape(gd._fullLayout._shapeLowerLayer); - } - } - function drawShape(shapeLayer) { - var d = getPathString$1(gd, options); - var attrs2 = { - "data-index": index2, - "fill-rule": options.fillrule, - d - }; - var opacity = options.opacity; - var fillColor = options.fillcolor; - var lineColor = options.line.width ? options.line.color : "rgba(0,0,0,0)"; - var lineWidth = options.line.width; - var lineDash = options.line.dash; - if (!lineWidth && options.editable === true) { - lineWidth = 5; - lineDash = "solid"; - } - var isOpen = d[d.length - 1] !== "Z"; - var isActiveShape = couldHaveActiveShape(gd) && options.editable && gd._fullLayout._activeShapeIndex === index2; - if (isActiveShape) { - fillColor = isOpen ? "rgba(0,0,0,0)" : gd._fullLayout.activeshape.fillcolor; - opacity = gd._fullLayout.activeshape.opacity; - } - var shapeGroup = shapeLayer.append("g").classed("shape-group", true).attr({ "data-index": index2 }); - var path = shapeGroup.append("path").attr(attrs2).style("opacity", opacity).call(Color$z.stroke, lineColor).call(Color$z.fill, fillColor).call(Drawing$m.dashLine, lineDash, lineWidth); - setClipPath$1(shapeGroup, gd, options); - drawLabel$1(gd, index2, options, shapeGroup); - var editHelpers; - if (isActiveShape || gd._context.edits.shapePosition) editHelpers = arrayEditor$5(gd.layout, "shapes", options); - if (isActiveShape) { - path.style({ - cursor: "move" - }); - var dragOptions = { - element: path.node(), - plotinfo, - gd, - editHelpers, - hasText: options.label.text || options.label.texttemplate, - isActiveShape: true - // i.e. to enable controllers - }; - var polygons = readPaths$2(d, gd); - displayOutlines$2(polygons, path, dragOptions); - } else { - if (gd._context.edits.shapePosition) { - setupDragElement(gd, path, options, index2, shapeLayer, editHelpers); - } else if (options.editable === true) { - path.style( - "pointer-events", - isOpen || Color$z.opacity(fillColor) * opacity <= 0.5 ? "stroke" : "all" - ); - } - } - path.node().addEventListener("click", function() { - return activateShape(gd, path); - }); - } -} -function setClipPath$1(shapePath, gd, shapeOptions) { - var clipAxes = (shapeOptions.xref + shapeOptions.yref).replace(/paper/g, "").replace(/[xyz][1-9]* *domain/g, ""); - Drawing$m.setClipUrl( - shapePath, - clipAxes ? "clip" + gd._fullLayout._uid + clipAxes : null, - gd - ); -} -function setupDragElement(gd, shapePath, shapeOptions, index2, shapeLayer, editHelpers) { - var MINWIDTH = 10; - var MINHEIGHT = 10; - var xPixelSized = shapeOptions.xsizemode === "pixel"; - var yPixelSized = shapeOptions.ysizemode === "pixel"; - var isLine = shapeOptions.type === "line"; - var isPath2 = shapeOptions.type === "path"; - var modifyItem = editHelpers.modifyItem; - var x0, y0, x1, y1, xAnchor, yAnchor; - var n0, s0, w0, e0, optN, optS, optW, optE; - var pathIn; - var shapeGroup = d3$q.select(shapePath.node().parentNode); - var xa = Axes$j.getFromId(gd, shapeOptions.xref); - var xRefType = Axes$j.getRefType(shapeOptions.xref); - var ya = Axes$j.getFromId(gd, shapeOptions.yref); - var yRefType = Axes$j.getRefType(shapeOptions.yref); - var shiftXStart = shapeOptions.x0shift; - var shiftXEnd = shapeOptions.x1shift; - var shiftYStart = shapeOptions.y0shift; - var shiftYEnd = shapeOptions.y1shift; - var x2p = function(v, shift) { - var dataToPixel = helpers$t.getDataToPixel(gd, xa, shift, false, xRefType); - return dataToPixel(v); - }; - var y2p = function(v, shift) { - var dataToPixel = helpers$t.getDataToPixel(gd, ya, shift, true, yRefType); - return dataToPixel(v); - }; - var p2x = helpers$t.getPixelToData(gd, xa, false, xRefType); - var p2y = helpers$t.getPixelToData(gd, ya, true, yRefType); - var sensoryElement = obtainSensoryElement(); - var dragOptions = { - element: sensoryElement.node(), - gd, - prepFn: startDrag, - doneFn: endDrag, - clickFn: abortDrag - }; - var dragMode; - dragElement$2.init(dragOptions); - sensoryElement.node().onmousemove = updateDragMode; - function obtainSensoryElement() { - return isLine ? createLineDragHandles() : shapePath; - } - function createLineDragHandles() { - var minSensoryWidth = 10; - var sensoryWidth = Math.max(shapeOptions.line.width, minSensoryWidth); - var g = shapeLayer.append("g").attr("data-index", index2).attr("drag-helper", true); - g.append("path").attr("d", shapePath.attr("d")).style({ - cursor: "move", - "stroke-width": sensoryWidth, - "stroke-opacity": "0" - // ensure not visible - }); - var circleStyle = { - "fill-opacity": "0" - // ensure not visible - }; - var circleRadius = Math.max(sensoryWidth / 2, minSensoryWidth); - g.append("circle").attr({ - "data-line-point": "start-point", - cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x0 : x2p(shapeOptions.x0, shiftXStart), - cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y0 : y2p(shapeOptions.y0, shiftYStart), - r: circleRadius - }).style(circleStyle).classed("cursor-grab", true); - g.append("circle").attr({ - "data-line-point": "end-point", - cx: xPixelSized ? x2p(shapeOptions.xanchor) + shapeOptions.x1 : x2p(shapeOptions.x1, shiftXEnd), - cy: yPixelSized ? y2p(shapeOptions.yanchor) - shapeOptions.y1 : y2p(shapeOptions.y1, shiftYEnd), - r: circleRadius - }).style(circleStyle).classed("cursor-grab", true); - return g; - } - function updateDragMode(evt) { - if (shouldSkipEdits(gd)) { - dragMode = null; - return; - } - if (isLine) { - if (evt.target.tagName === "path") { - dragMode = "move"; - } else { - dragMode = evt.target.attributes["data-line-point"].value === "start-point" ? "resize-over-start-point" : "resize-over-end-point"; - } - } else { - var dragBBox = dragOptions.element.getBoundingClientRect(); - var w = dragBBox.right - dragBBox.left; - var h = dragBBox.bottom - dragBBox.top; - var x = evt.clientX - dragBBox.left; - var y = evt.clientY - dragBBox.top; - var cursor2 = !isPath2 && w > MINWIDTH && h > MINHEIGHT && !evt.shiftKey ? dragElement$2.getCursor(x / w, 1 - y / h) : "move"; - setCursor$2(shapePath, cursor2); - dragMode = cursor2.split("-")[0]; - } - } - function startDrag(evt) { - if (shouldSkipEdits(gd)) return; - if (xPixelSized) { - xAnchor = x2p(shapeOptions.xanchor); - } - if (yPixelSized) { - yAnchor = y2p(shapeOptions.yanchor); - } - if (shapeOptions.type === "path") { - pathIn = shapeOptions.path; - } else { - x0 = xPixelSized ? shapeOptions.x0 : x2p(shapeOptions.x0); - y0 = yPixelSized ? shapeOptions.y0 : y2p(shapeOptions.y0); - x1 = xPixelSized ? shapeOptions.x1 : x2p(shapeOptions.x1); - y1 = yPixelSized ? shapeOptions.y1 : y2p(shapeOptions.y1); - } - if (x0 < x1) { - w0 = x0; - optW = "x0"; - e0 = x1; - optE = "x1"; - } else { - w0 = x1; - optW = "x1"; - e0 = x0; - optE = "x0"; - } - if (!yPixelSized && y0 < y1 || yPixelSized && y0 > y1) { - n0 = y0; - optN = "y0"; - s0 = y1; - optS = "y1"; - } else { - n0 = y1; - optN = "y1"; - s0 = y0; - optS = "y0"; - } - updateDragMode(evt); - renderVisualCues(shapeLayer, shapeOptions); - deactivateClipPathTemporarily(shapePath, shapeOptions, gd); - dragOptions.moveFn = dragMode === "move" ? moveShape : resizeShape; - dragOptions.altKey = evt.altKey; - } - function endDrag() { - if (shouldSkipEdits(gd)) return; - setCursor$2(shapePath); - removeVisualCues(shapeLayer); - setClipPath$1(shapePath, gd, shapeOptions); - Registry$y.call("_guiRelayout", gd, editHelpers.getUpdateObj()); - } - function abortDrag() { - if (shouldSkipEdits(gd)) return; - removeVisualCues(shapeLayer); - } - function moveShape(dx, dy) { - if (shapeOptions.type === "path") { - var noOp = function(coord) { - return coord; - }; - var moveX = noOp; - var moveY = noOp; - if (xPixelSized) { - modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); - } else { - moveX = function moveX2(x) { - return p2x(x2p(x) + dx); - }; - if (xa && xa.type === "date") moveX = helpers$t.encodeDate(moveX); - } - if (yPixelSized) { - modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); - } else { - moveY = function moveY2(y) { - return p2y(y2p(y) + dy); - }; - if (ya && ya.type === "date") moveY = helpers$t.encodeDate(moveY); - } - modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY)); - } else { - if (xPixelSized) { - modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); - } else { - modifyItem("x0", shapeOptions.x0 = p2x(x0 + dx)); - modifyItem("x1", shapeOptions.x1 = p2x(x1 + dx)); - } - if (yPixelSized) { - modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); - } else { - modifyItem("y0", shapeOptions.y0 = p2y(y0 + dy)); - modifyItem("y1", shapeOptions.y1 = p2y(y1 + dy)); - } - } - shapePath.attr("d", getPathString$1(gd, shapeOptions)); - renderVisualCues(shapeLayer, shapeOptions); - drawLabel$1(gd, index2, shapeOptions, shapeGroup); - } - function resizeShape(dx, dy) { - if (isPath2) { - var noOp = function(coord) { - return coord; - }; - var moveX = noOp; - var moveY = noOp; - if (xPixelSized) { - modifyItem("xanchor", shapeOptions.xanchor = p2x(xAnchor + dx)); - } else { - moveX = function moveX2(x) { - return p2x(x2p(x) + dx); - }; - if (xa && xa.type === "date") moveX = helpers$t.encodeDate(moveX); - } - if (yPixelSized) { - modifyItem("yanchor", shapeOptions.yanchor = p2y(yAnchor + dy)); - } else { - moveY = function moveY2(y) { - return p2y(y2p(y) + dy); - }; - if (ya && ya.type === "date") moveY = helpers$t.encodeDate(moveY); - } - modifyItem("path", shapeOptions.path = movePath(pathIn, moveX, moveY)); - } else if (isLine) { - if (dragMode === "resize-over-start-point") { - var newX0 = x0 + dx; - var newY0 = yPixelSized ? y0 - dy : y0 + dy; - modifyItem("x0", shapeOptions.x0 = xPixelSized ? newX0 : p2x(newX0)); - modifyItem("y0", shapeOptions.y0 = yPixelSized ? newY0 : p2y(newY0)); - } else if (dragMode === "resize-over-end-point") { - var newX1 = x1 + dx; - var newY1 = yPixelSized ? y1 - dy : y1 + dy; - modifyItem("x1", shapeOptions.x1 = xPixelSized ? newX1 : p2x(newX1)); - modifyItem("y1", shapeOptions.y1 = yPixelSized ? newY1 : p2y(newY1)); - } - } else { - var has = function(str2) { - return dragMode.indexOf(str2) !== -1; - }; - var hasN = has("n"); - var hasS = has("s"); - var hasW = has("w"); - var hasE = has("e"); - var newN = hasN ? n0 + dy : n0; - var newS = hasS ? s0 + dy : s0; - var newW = hasW ? w0 + dx : w0; - var newE = hasE ? e0 + dx : e0; - if (yPixelSized) { - if (hasN) newN = n0 - dy; - if (hasS) newS = s0 - dy; - } - if (!yPixelSized && newS - newN > MINHEIGHT || yPixelSized && newN - newS > MINHEIGHT) { - modifyItem(optN, shapeOptions[optN] = yPixelSized ? newN : p2y(newN)); - modifyItem(optS, shapeOptions[optS] = yPixelSized ? newS : p2y(newS)); - } - if (newE - newW > MINWIDTH) { - modifyItem(optW, shapeOptions[optW] = xPixelSized ? newW : p2x(newW)); - modifyItem(optE, shapeOptions[optE] = xPixelSized ? newE : p2x(newE)); - } - } - shapePath.attr("d", getPathString$1(gd, shapeOptions)); - renderVisualCues(shapeLayer, shapeOptions); - drawLabel$1(gd, index2, shapeOptions, shapeGroup); - } - function renderVisualCues(shapeLayer2, shapeOptions2) { - if (xPixelSized || yPixelSized) { - renderAnchor(); - } - function renderAnchor() { - var isNotPath = shapeOptions2.type !== "path"; - var visualCues = shapeLayer2.selectAll(".visual-cue").data([0]); - var strokeWidth = 1; - visualCues.enter().append("path").attr({ - fill: "#fff", - "fill-rule": "evenodd", - stroke: "#000", - "stroke-width": strokeWidth - }).classed("visual-cue", true); - var posX = x2p( - xPixelSized ? shapeOptions2.xanchor : Lib$1o.midRange( - isNotPath ? [shapeOptions2.x0, shapeOptions2.x1] : helpers$t.extractPathCoords(shapeOptions2.path, constants$G.paramIsX) - ) - ); - var posY = y2p( - yPixelSized ? shapeOptions2.yanchor : Lib$1o.midRange( - isNotPath ? [shapeOptions2.y0, shapeOptions2.y1] : helpers$t.extractPathCoords(shapeOptions2.path, constants$G.paramIsY) - ) - ); - posX = helpers$t.roundPositionForSharpStrokeRendering(posX, strokeWidth); - posY = helpers$t.roundPositionForSharpStrokeRendering(posY, strokeWidth); - if (xPixelSized && yPixelSized) { - var crossPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h-8v2h8 v8h2v-8 h8v-2h-8 v-8h-2 Z"; - visualCues.attr("d", crossPath); - } else if (xPixelSized) { - var vBarPath = "M" + (posX - 1 - strokeWidth) + "," + (posY - 9 - strokeWidth) + "v18 h2 v-18 Z"; - visualCues.attr("d", vBarPath); - } else { - var hBarPath = "M" + (posX - 9 - strokeWidth) + "," + (posY - 1 - strokeWidth) + "h18 v2 h-18 Z"; - visualCues.attr("d", hBarPath); - } - } - } - function removeVisualCues(shapeLayer2) { - shapeLayer2.selectAll(".visual-cue").remove(); - } - function deactivateClipPathTemporarily(shapePath2, shapeOptions2, gd2) { - var xref = shapeOptions2.xref; - var yref = shapeOptions2.yref; - var xa2 = Axes$j.getFromId(gd2, xref); - var ya2 = Axes$j.getFromId(gd2, yref); - var clipAxes = ""; - if (xref !== "paper" && !xa2.autorange) clipAxes += xref; - if (yref !== "paper" && !ya2.autorange) clipAxes += yref; - Drawing$m.setClipUrl( - shapePath2, - clipAxes ? "clip" + gd2._fullLayout._uid + clipAxes : null, - gd2 - ); - } -} -function movePath(pathIn, moveX, moveY) { - return pathIn.replace(constants$G.segmentRE, function(segment2) { - var paramNumber = 0; - var segmentType = segment2.charAt(0); - var xParams = constants$G.paramIsX[segmentType]; - var yParams = constants$G.paramIsY[segmentType]; - var nParams = constants$G.numParams[segmentType]; - var paramString = segment2.substr(1).replace(constants$G.paramRE, function(param) { - if (paramNumber >= nParams) return param; - if (xParams[paramNumber]) param = moveX(param); - else if (yParams[paramNumber]) param = moveY(param); - paramNumber++; - return param; - }); - return segmentType + paramString; - }); -} -function activateShape(gd, path) { - if (!couldHaveActiveShape(gd)) return; - var element = path.node(); - var id = +element.getAttribute("data-index"); - if (id >= 0) { - if (id === gd._fullLayout._activeShapeIndex) { - deactivateShape(gd); - return; - } - gd._fullLayout._activeShapeIndex = id; - gd._fullLayout._deactivateShape = deactivateShape; - draw$c(gd); - } -} -function deactivateShape(gd) { - if (!couldHaveActiveShape(gd)) return; - var id = gd._fullLayout._activeShapeIndex; - if (id >= 0) { - clearOutlineControllers$1(gd); - delete gd._fullLayout._activeShapeIndex; - draw$c(gd); - } -} -function eraseActiveShape$2(gd) { - if (!couldHaveActiveShape(gd)) return; - clearOutlineControllers$1(gd); - var id = gd._fullLayout._activeShapeIndex; - var shapes2 = (gd.layout || {}).shapes || []; - if (id < shapes2.length) { - var list = []; - for (var q = 0; q < shapes2.length; q++) { - if (q !== id) { - list.push(shapes2[q]); - } - } - delete gd._fullLayout._activeShapeIndex; - return Registry$y.call("_guiRelayout", gd, { - shapes: list - }); - } -} -var Registry$x = registry; -var Plots$9 = plotsExports; -var axisIds$6 = axis_ids; -var Icons$1 = ploticon; -var eraseActiveShape$1 = draw_1$3.eraseActiveShape; -var Lib$1n = libExports; -var _$1 = Lib$1n._; -var modeBarButtons$2 = buttons.exports = {}; -modeBarButtons$2.toImage = { - name: "toImage", - title: function(gd) { - var opts = gd._context.toImageButtonOptions || {}; - var format2 = opts.format || "png"; - return format2 === "png" ? _$1(gd, "Download plot as a png") : ( - // legacy text - _$1(gd, "Download plot") - ); - }, - icon: Icons$1.camera, - click: function(gd) { - var toImageButtonOptions = gd._context.toImageButtonOptions; - var opts = { format: toImageButtonOptions.format || "png" }; - Lib$1n.notifier(_$1(gd, "Taking snapshot - this may take a few seconds"), "long"); - if (opts.format !== "svg" && Lib$1n.isIE()) { - Lib$1n.notifier(_$1(gd, "IE only supports svg. Changing format to svg."), "long"); - opts.format = "svg"; - } - ["filename", "width", "height", "scale"].forEach(function(key) { - if (key in toImageButtonOptions) { - opts[key] = toImageButtonOptions[key]; - } - }); - Registry$x.call("downloadImage", gd, opts).then(function(filename) { - Lib$1n.notifier(_$1(gd, "Snapshot succeeded") + " - " + filename, "long"); - }).catch(function() { - Lib$1n.notifier(_$1(gd, "Sorry, there was a problem downloading your snapshot!"), "long"); - }); - } -}; -modeBarButtons$2.sendDataToCloud = { - name: "sendDataToCloud", - title: function(gd) { - return _$1(gd, "Edit in Chart Studio"); - }, - icon: Icons$1.disk, - click: function(gd) { - Plots$9.sendDataToCloud(gd); - } -}; -modeBarButtons$2.editInChartStudio = { - name: "editInChartStudio", - title: function(gd) { - return _$1(gd, "Edit in Chart Studio"); - }, - icon: Icons$1.pencil, - click: function(gd) { - Plots$9.sendDataToCloud(gd); - } -}; -modeBarButtons$2.zoom2d = { - name: "zoom2d", - _cat: "zoom", - title: function(gd) { - return _$1(gd, "Zoom"); - }, - attr: "dragmode", - val: "zoom", - icon: Icons$1.zoombox, - click: handleCartesian -}; -modeBarButtons$2.pan2d = { - name: "pan2d", - _cat: "pan", - title: function(gd) { - return _$1(gd, "Pan"); - }, - attr: "dragmode", - val: "pan", - icon: Icons$1.pan, - click: handleCartesian -}; -modeBarButtons$2.select2d = { - name: "select2d", - _cat: "select", - title: function(gd) { - return _$1(gd, "Box Select"); - }, - attr: "dragmode", - val: "select", - icon: Icons$1.selectbox, - click: handleCartesian -}; -modeBarButtons$2.lasso2d = { - name: "lasso2d", - _cat: "lasso", - title: function(gd) { - return _$1(gd, "Lasso Select"); - }, - attr: "dragmode", - val: "lasso", - icon: Icons$1.lasso, - click: handleCartesian -}; -modeBarButtons$2.drawclosedpath = { - name: "drawclosedpath", - title: function(gd) { - return _$1(gd, "Draw closed freeform"); - }, - attr: "dragmode", - val: "drawclosedpath", - icon: Icons$1.drawclosedpath, - click: handleCartesian -}; -modeBarButtons$2.drawopenpath = { - name: "drawopenpath", - title: function(gd) { - return _$1(gd, "Draw open freeform"); - }, - attr: "dragmode", - val: "drawopenpath", - icon: Icons$1.drawopenpath, - click: handleCartesian -}; -modeBarButtons$2.drawline = { - name: "drawline", - title: function(gd) { - return _$1(gd, "Draw line"); - }, - attr: "dragmode", - val: "drawline", - icon: Icons$1.drawline, - click: handleCartesian -}; -modeBarButtons$2.drawrect = { - name: "drawrect", - title: function(gd) { - return _$1(gd, "Draw rectangle"); - }, - attr: "dragmode", - val: "drawrect", - icon: Icons$1.drawrect, - click: handleCartesian -}; -modeBarButtons$2.drawcircle = { - name: "drawcircle", - title: function(gd) { - return _$1(gd, "Draw circle"); - }, - attr: "dragmode", - val: "drawcircle", - icon: Icons$1.drawcircle, - click: handleCartesian -}; -modeBarButtons$2.eraseshape = { - name: "eraseshape", - title: function(gd) { - return _$1(gd, "Erase active shape"); - }, - icon: Icons$1.eraseshape, - click: eraseActiveShape$1 -}; -modeBarButtons$2.zoomIn2d = { - name: "zoomIn2d", - _cat: "zoomin", - title: function(gd) { - return _$1(gd, "Zoom in"); - }, - attr: "zoom", - val: "in", - icon: Icons$1.zoom_plus, - click: handleCartesian -}; -modeBarButtons$2.zoomOut2d = { - name: "zoomOut2d", - _cat: "zoomout", - title: function(gd) { - return _$1(gd, "Zoom out"); - }, - attr: "zoom", - val: "out", - icon: Icons$1.zoom_minus, - click: handleCartesian -}; -modeBarButtons$2.autoScale2d = { - name: "autoScale2d", - _cat: "autoscale", - title: function(gd) { - return _$1(gd, "Autoscale"); - }, - attr: "zoom", - val: "auto", - icon: Icons$1.autoscale, - click: handleCartesian -}; -modeBarButtons$2.resetScale2d = { - name: "resetScale2d", - _cat: "resetscale", - title: function(gd) { - return _$1(gd, "Reset axes"); - }, - attr: "zoom", - val: "reset", - icon: Icons$1.home, - click: handleCartesian -}; -modeBarButtons$2.hoverClosestCartesian = { - name: "hoverClosestCartesian", - _cat: "hoverclosest", - title: function(gd) { - return _$1(gd, "Show closest data on hover"); - }, - attr: "hovermode", - val: "closest", - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: handleCartesian -}; -modeBarButtons$2.hoverCompareCartesian = { - name: "hoverCompareCartesian", - _cat: "hoverCompare", - title: function(gd) { - return _$1(gd, "Compare data on hover"); - }, - attr: "hovermode", - val: function(gd) { - return gd._fullLayout._isHoriz ? "y" : "x"; - }, - icon: Icons$1.tooltip_compare, - gravity: "ne", - click: handleCartesian -}; -function handleCartesian(gd, ev) { - var button = ev.currentTarget; - var astr = button.getAttribute("data-attr"); - var val = button.getAttribute("data-val") || true; - var fullLayout = gd._fullLayout; - var aobj = {}; - var axList = axisIds$6.list(gd, null, true); - var allSpikesEnabled = fullLayout._cartesianSpikesEnabled; - var ax, i; - if (astr === "zoom") { - var mag = val === "in" ? 0.5 : 2; - var r0 = (1 + mag) / 2; - var r1 = (1 - mag) / 2; - var axName; - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - if (!ax.fixedrange) { - axName = ax._name; - if (val === "auto") { - aobj[axName + ".autorange"] = true; - } else if (val === "reset") { - if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) { - aobj[axName + ".autorange"] = true; - } else if (ax._rangeInitial0 === void 0) { - aobj[axName + ".autorange"] = ax._autorangeInitial; - aobj[axName + ".range"] = [null, ax._rangeInitial1]; - } else if (ax._rangeInitial1 === void 0) { - aobj[axName + ".range"] = [ax._rangeInitial0, null]; - aobj[axName + ".autorange"] = ax._autorangeInitial; - } else { - aobj[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1]; - } - if (ax._showSpikeInitial !== void 0) { - aobj[axName + ".showspikes"] = ax._showSpikeInitial; - if (allSpikesEnabled === "on" && !ax._showSpikeInitial) { - allSpikesEnabled = "off"; - } - } - } else { - var rangeNow = [ - ax.r2l(ax.range[0]), - ax.r2l(ax.range[1]) - ]; - var rangeNew = [ - r0 * rangeNow[0] + r1 * rangeNow[1], - r0 * rangeNow[1] + r1 * rangeNow[0] - ]; - aobj[axName + ".range[0]"] = ax.l2r(rangeNew[0]); - aobj[axName + ".range[1]"] = ax.l2r(rangeNew[1]); - } - } - } - } else { - if (astr === "hovermode" && (val === "x" || val === "y")) { - val = fullLayout._isHoriz ? "y" : "x"; - button.setAttribute("data-val", val); - } - aobj[astr] = val; - } - fullLayout._cartesianSpikesEnabled = allSpikesEnabled; - Registry$x.call("_guiRelayout", gd, aobj); -} -modeBarButtons$2.zoom3d = { - name: "zoom3d", - _cat: "zoom", - title: function(gd) { - return _$1(gd, "Zoom"); - }, - attr: "scene.dragmode", - val: "zoom", - icon: Icons$1.zoombox, - click: handleDrag3d -}; -modeBarButtons$2.pan3d = { - name: "pan3d", - _cat: "pan", - title: function(gd) { - return _$1(gd, "Pan"); - }, - attr: "scene.dragmode", - val: "pan", - icon: Icons$1.pan, - click: handleDrag3d -}; -modeBarButtons$2.orbitRotation = { - name: "orbitRotation", - title: function(gd) { - return _$1(gd, "Orbital rotation"); - }, - attr: "scene.dragmode", - val: "orbit", - icon: Icons$1["3d_rotate"], - click: handleDrag3d -}; -modeBarButtons$2.tableRotation = { - name: "tableRotation", - title: function(gd) { - return _$1(gd, "Turntable rotation"); - }, - attr: "scene.dragmode", - val: "turntable", - icon: Icons$1["z-axis"], - click: handleDrag3d -}; -function handleDrag3d(gd, ev) { - var button = ev.currentTarget; - var attr = button.getAttribute("data-attr"); - var val = button.getAttribute("data-val") || true; - var sceneIds = gd._fullLayout._subplots.gl3d || []; - var layoutUpdate = {}; - var parts = attr.split("."); - for (var i = 0; i < sceneIds.length; i++) { - layoutUpdate[sceneIds[i] + "." + parts[1]] = val; - } - var val2d = val === "pan" ? val : "zoom"; - layoutUpdate.dragmode = val2d; - Registry$x.call("_guiRelayout", gd, layoutUpdate); -} -modeBarButtons$2.resetCameraDefault3d = { - name: "resetCameraDefault3d", - _cat: "resetCameraDefault", - title: function(gd) { - return _$1(gd, "Reset camera to default"); - }, - attr: "resetDefault", - icon: Icons$1.home, - click: handleCamera3d -}; -modeBarButtons$2.resetCameraLastSave3d = { - name: "resetCameraLastSave3d", - _cat: "resetCameraLastSave", - title: function(gd) { - return _$1(gd, "Reset camera to last save"); - }, - attr: "resetLastSave", - icon: Icons$1.movie, - click: handleCamera3d -}; -function handleCamera3d(gd, ev) { - var button = ev.currentTarget; - var attr = button.getAttribute("data-attr"); - var resetLastSave = attr === "resetLastSave"; - var resetDefault = attr === "resetDefault"; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d || []; - var aobj = {}; - for (var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i]; - var camera = sceneId + ".camera"; - var aspectratio = sceneId + ".aspectratio"; - var aspectmode = sceneId + ".aspectmode"; - var scene = fullLayout[sceneId]._scene; - var didUpdate; - if (resetLastSave) { - aobj[camera + ".up"] = scene.viewInitial.up; - aobj[camera + ".eye"] = scene.viewInitial.eye; - aobj[camera + ".center"] = scene.viewInitial.center; - didUpdate = true; - } else if (resetDefault) { - aobj[camera + ".up"] = null; - aobj[camera + ".eye"] = null; - aobj[camera + ".center"] = null; - didUpdate = true; - } - if (didUpdate) { - aobj[aspectratio + ".x"] = scene.viewInitial.aspectratio.x; - aobj[aspectratio + ".y"] = scene.viewInitial.aspectratio.y; - aobj[aspectratio + ".z"] = scene.viewInitial.aspectratio.z; - aobj[aspectmode] = scene.viewInitial.aspectmode; - } - } - Registry$x.call("_guiRelayout", gd, aobj); -} -modeBarButtons$2.hoverClosest3d = { - name: "hoverClosest3d", - _cat: "hoverclosest", - title: function(gd) { - return _$1(gd, "Toggle show closest data on hover"); - }, - attr: "hovermode", - val: null, - toggle: true, - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: handleHover3d -}; -function getNextHover3d(gd, ev) { - var button = ev.currentTarget; - var val = button._previousVal; - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d || []; - var axes2 = ["xaxis", "yaxis", "zaxis"]; - var currentSpikes = {}; - var layoutUpdate = {}; - if (val) { - layoutUpdate = val; - button._previousVal = null; - } else { - for (var i = 0; i < sceneIds.length; i++) { - var sceneId = sceneIds[i]; - var sceneLayout = fullLayout[sceneId]; - var hovermodeAStr = sceneId + ".hovermode"; - currentSpikes[hovermodeAStr] = sceneLayout.hovermode; - layoutUpdate[hovermodeAStr] = false; - for (var j = 0; j < 3; j++) { - var axis = axes2[j]; - var spikeAStr = sceneId + "." + axis + ".showspikes"; - layoutUpdate[spikeAStr] = false; - currentSpikes[spikeAStr] = sceneLayout[axis].showspikes; - } - } - button._previousVal = currentSpikes; - } - return layoutUpdate; -} -function handleHover3d(gd, ev) { - var layoutUpdate = getNextHover3d(gd, ev); - Registry$x.call("_guiRelayout", gd, layoutUpdate); -} -modeBarButtons$2.zoomInGeo = { - name: "zoomInGeo", - _cat: "zoomin", - title: function(gd) { - return _$1(gd, "Zoom in"); - }, - attr: "zoom", - val: "in", - icon: Icons$1.zoom_plus, - click: handleGeo -}; -modeBarButtons$2.zoomOutGeo = { - name: "zoomOutGeo", - _cat: "zoomout", - title: function(gd) { - return _$1(gd, "Zoom out"); - }, - attr: "zoom", - val: "out", - icon: Icons$1.zoom_minus, - click: handleGeo -}; -modeBarButtons$2.resetGeo = { - name: "resetGeo", - _cat: "reset", - title: function(gd) { - return _$1(gd, "Reset"); - }, - attr: "reset", - val: null, - icon: Icons$1.autoscale, - click: handleGeo -}; -modeBarButtons$2.hoverClosestGeo = { - name: "hoverClosestGeo", - _cat: "hoverclosest", - title: function(gd) { - return _$1(gd, "Toggle show closest data on hover"); - }, - attr: "hovermode", - val: null, - toggle: true, - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: toggleHover -}; -function handleGeo(gd, ev) { - var button = ev.currentTarget; - var attr = button.getAttribute("data-attr"); - var val = button.getAttribute("data-val") || true; - var fullLayout = gd._fullLayout; - var geoIds = fullLayout._subplots.geo || []; - for (var i = 0; i < geoIds.length; i++) { - var id = geoIds[i]; - var geoLayout = fullLayout[id]; - if (attr === "zoom") { - var scale2 = geoLayout.projection.scale; - var newScale = val === "in" ? 2 * scale2 : 0.5 * scale2; - Registry$x.call("_guiRelayout", gd, id + ".projection.scale", newScale); - } - } - if (attr === "reset") { - resetView(gd, "geo"); - } -} -modeBarButtons$2.hoverClosestGl2d = { - name: "hoverClosestGl2d", - _cat: "hoverclosest", - title: function(gd) { - return _$1(gd, "Toggle show closest data on hover"); - }, - attr: "hovermode", - val: null, - toggle: true, - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: toggleHover -}; -modeBarButtons$2.hoverClosestPie = { - name: "hoverClosestPie", - _cat: "hoverclosest", - title: function(gd) { - return _$1(gd, "Toggle show closest data on hover"); - }, - attr: "hovermode", - val: "closest", - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: toggleHover -}; -function getNextHover(gd) { - var fullLayout = gd._fullLayout; - if (fullLayout.hovermode) return false; - if (fullLayout._has("cartesian")) { - return fullLayout._isHoriz ? "y" : "x"; - } - return "closest"; -} -function toggleHover(gd) { - var newHover = getNextHover(gd); - Registry$x.call("_guiRelayout", gd, "hovermode", newHover); -} -modeBarButtons$2.resetViewSankey = { - name: "resetSankeyGroup", - title: function(gd) { - return _$1(gd, "Reset view"); - }, - icon: Icons$1.home, - click: function(gd) { - var aObj = { - "node.groups": [], - "node.x": [], - "node.y": [] - }; - for (var i = 0; i < gd._fullData.length; i++) { - var viewInitial = gd._fullData[i]._viewInitial; - aObj["node.groups"].push(viewInitial.node.groups.slice()); - aObj["node.x"].push(viewInitial.node.x.slice()); - aObj["node.y"].push(viewInitial.node.y.slice()); - } - Registry$x.call("restyle", gd, aObj); - } -}; -modeBarButtons$2.toggleHover = { - name: "toggleHover", - title: function(gd) { - return _$1(gd, "Toggle show closest data on hover"); - }, - attr: "hovermode", - val: null, - toggle: true, - icon: Icons$1.tooltip_basic, - gravity: "ne", - click: function(gd, ev) { - var layoutUpdate = getNextHover3d(gd, ev); - layoutUpdate.hovermode = getNextHover(gd); - Registry$x.call("_guiRelayout", gd, layoutUpdate); - } -}; -modeBarButtons$2.resetViews = { - name: "resetViews", - title: function(gd) { - return _$1(gd, "Reset views"); - }, - icon: Icons$1.home, - click: function(gd, ev) { - var button = ev.currentTarget; - button.setAttribute("data-attr", "zoom"); - button.setAttribute("data-val", "reset"); - handleCartesian(gd, ev); - button.setAttribute("data-attr", "resetLastSave"); - handleCamera3d(gd, ev); - resetView(gd, "geo"); - resetView(gd, "mapbox"); - resetView(gd, "map"); - } -}; -modeBarButtons$2.toggleSpikelines = { - name: "toggleSpikelines", - title: function(gd) { - return _$1(gd, "Toggle Spike Lines"); - }, - icon: Icons$1.spikeline, - attr: "_cartesianSpikesEnabled", - val: "on", - click: function(gd) { - var fullLayout = gd._fullLayout; - var allSpikesEnabled = fullLayout._cartesianSpikesEnabled; - fullLayout._cartesianSpikesEnabled = allSpikesEnabled === "on" ? "off" : "on"; - Registry$x.call("_guiRelayout", gd, setSpikelineVisibility(gd)); - } -}; -function setSpikelineVisibility(gd) { - var fullLayout = gd._fullLayout; - var areSpikesOn = fullLayout._cartesianSpikesEnabled === "on"; - var axList = axisIds$6.list(gd, null, true); - var aobj = {}; - for (var i = 0; i < axList.length; i++) { - var ax = axList[i]; - aobj[ax._name + ".showspikes"] = areSpikesOn ? true : ax._showSpikeInitial; - } - return aobj; -} -modeBarButtons$2.resetViewMapbox = { - name: "resetViewMapbox", - _cat: "resetView", - title: function(gd) { - return _$1(gd, "Reset view"); - }, - attr: "reset", - icon: Icons$1.home, - click: function(gd) { - resetView(gd, "mapbox"); - } -}; -modeBarButtons$2.resetViewMap = { - name: "resetViewMap", - _cat: "resetView", - title: function(gd) { - return _$1(gd, "Reset view"); - }, - attr: "reset", - icon: Icons$1.home, - click: function(gd) { - resetView(gd, "map"); - } -}; -modeBarButtons$2.zoomInMapbox = { - name: "zoomInMapbox", - _cat: "zoomin", - title: function(gd) { - return _$1(gd, "Zoom in"); - }, - attr: "zoom", - val: "in", - icon: Icons$1.zoom_plus, - click: handleMapboxZoom -}; -modeBarButtons$2.zoomInMap = { - name: "zoomInMap", - _cat: "zoomin", - title: function(gd) { - return _$1(gd, "Zoom in"); - }, - attr: "zoom", - val: "in", - icon: Icons$1.zoom_plus, - click: handleMapZoom -}; -modeBarButtons$2.zoomOutMapbox = { - name: "zoomOutMapbox", - _cat: "zoomout", - title: function(gd) { - return _$1(gd, "Zoom out"); - }, - attr: "zoom", - val: "out", - icon: Icons$1.zoom_minus, - click: handleMapboxZoom -}; -modeBarButtons$2.zoomOutMap = { - name: "zoomOutMap", - _cat: "zoomout", - title: function(gd) { - return _$1(gd, "Zoom out"); - }, - attr: "zoom", - val: "out", - icon: Icons$1.zoom_minus, - click: handleMapZoom -}; -function handleMapboxZoom(gd, ev) { - _handleMapZoom(gd, ev, "mapbox"); -} -function handleMapZoom(gd, ev) { - _handleMapZoom(gd, ev, "map"); -} -function _handleMapZoom(gd, ev, mapType) { - var button = ev.currentTarget; - var val = button.getAttribute("data-val"); - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[mapType] || []; - var scalar = 1.05; - var aObj = {}; - for (var i = 0; i < subplotIds.length; i++) { - var id = subplotIds[i]; - var current = fullLayout[id].zoom; - var next = val === "in" ? scalar * current : current / scalar; - aObj[id + ".zoom"] = next; - } - Registry$x.call("_guiRelayout", gd, aObj); -} -function resetView(gd, subplotType) { - var fullLayout = gd._fullLayout; - var subplotIds = fullLayout._subplots[subplotType] || []; - var aObj = {}; - for (var i = 0; i < subplotIds.length; i++) { - var id = subplotIds[i]; - var subplotObj = fullLayout[id]._subplot; - var viewInitial = subplotObj.viewInitial; - var viewKeys = Object.keys(viewInitial); - for (var j = 0; j < viewKeys.length; j++) { - var key = viewKeys[j]; - aObj[id + "." + key] = viewInitial[key]; - } - } - Registry$x.call("_guiRelayout", gd, aObj); -} -var buttonsExports = buttons.exports; -var modeBarButtons$1 = buttonsExports; -var buttonList = Object.keys(modeBarButtons$1); -var DRAW_MODES$1 = [ - "drawline", - "drawopenpath", - "drawclosedpath", - "drawcircle", - "drawrect", - "eraseshape" -]; -var backButtons = [ - "v1hovermode", - "hoverclosest", - "hovercompare", - "togglehover", - "togglespikelines" -].concat(DRAW_MODES$1); -var foreButtons = []; -var addToForeButtons = function(b) { - if (backButtons.indexOf(b._cat || b.name) !== -1) return; - var name2 = b.name; - var _cat = (b._cat || b.name).toLowerCase(); - if (foreButtons.indexOf(name2) === -1) foreButtons.push(name2); - if (foreButtons.indexOf(_cat) === -1) foreButtons.push(_cat); -}; -buttonList.forEach(function(k) { - addToForeButtons(modeBarButtons$1[k]); -}); -foreButtons.sort(); -var constants$F = { - DRAW_MODES: DRAW_MODES$1, - backButtons, - foreButtons -}; -var constants$E = constants$F; -var attributes$D = { - editType: "modebar", - orientation: { - valType: "enumerated", - values: ["v", "h"], - dflt: "h", - editType: "modebar", - description: "Sets the orientation of the modebar." - }, - bgcolor: { - valType: "color", - editType: "modebar", - description: "Sets the background color of the modebar." - }, - color: { - valType: "color", - editType: "modebar", - description: "Sets the color of the icons in the modebar." - }, - activecolor: { - valType: "color", - editType: "modebar", - description: "Sets the color of the active or hovered on icons in the modebar." - }, - uirevision: { - valType: "any", - editType: "none", - description: [ - "Controls persistence of user-driven changes related to the modebar,", - "including `hovermode`, `dragmode`, and `showspikes` at both the", - "root level and inside subplots. Defaults to `layout.uirevision`." - ].join(" ") - }, - add: { - valType: "string", - arrayOk: true, - dflt: "", - editType: "modebar", - description: [ - "Determines which predefined modebar buttons to add.", - "Please note that these buttons will only be shown if they are", - "compatible with all trace types used in a graph.", - "Similar to `config.modeBarButtonsToAdd` option.", - "This may include *" + constants$E.backButtons.join("*, *") + "*." - ].join(" ") - }, - remove: { - valType: "string", - arrayOk: true, - dflt: "", - editType: "modebar", - description: [ - "Determines which predefined modebar buttons to remove.", - "Similar to `config.modeBarButtonsToRemove` option.", - "This may include *" + constants$E.foreButtons.join("*, *") + "*." - ].join(" ") - } -}; -var Lib$1m = libExports; -var Color$y = colorExports; -var Template$4 = plot_template; -var attributes$C = attributes$D; -var defaults$k = function supplyLayoutDefaults3(layoutIn, layoutOut) { - var containerIn = layoutIn.modebar || {}; - var containerOut = Template$4.newContainer(layoutOut, "modebar"); - function coerce2(attr, dflt) { - return Lib$1m.coerce(containerIn, containerOut, attributes$C, attr, dflt); - } - coerce2("orientation"); - coerce2("bgcolor", Color$y.addOpacity(layoutOut.paper_bgcolor, 0.5)); - var defaultColor = Color$y.contrast(Color$y.rgb(layoutOut.modebar.bgcolor)); - coerce2("color", Color$y.addOpacity(defaultColor, 0.3)); - coerce2("activecolor", Color$y.addOpacity(defaultColor, 0.7)); - coerce2("uirevision", layoutOut.uirevision); - coerce2("add"); - coerce2("remove"); -}; -var d3$p = d3Exports; -var isNumeric$h = fastIsnumeric; -var Lib$1l = libExports; -var Icons = ploticon; -var version$1 = version$2.version; -var Parser = new DOMParser(); -function ModeBar(opts) { - this.container = opts.container; - this.element = document.createElement("div"); - this.update(opts.graphInfo, opts.buttons); - this.container.appendChild(this.element); -} -var proto = ModeBar.prototype; -proto.update = function(graphInfo, buttons2) { - this.graphInfo = graphInfo; - var context2 = this.graphInfo._context; - var fullLayout = this.graphInfo._fullLayout; - var modeBarId = "modebar-" + fullLayout._uid; - this.element.setAttribute("id", modeBarId); - this._uid = modeBarId; - this.element.className = "modebar"; - if (context2.displayModeBar === "hover") this.element.className += " modebar--hover ease-bg"; - if (fullLayout.modebar.orientation === "v") { - this.element.className += " vertical"; - buttons2 = buttons2.reverse(); - } - var style5 = fullLayout.modebar; - var bgSelector = context2.displayModeBar === "hover" ? ".js-plotly-plot .plotly:hover " : ""; - Lib$1l.deleteRelatedStyleRule(modeBarId); - Lib$1l.addRelatedStyleRule(modeBarId, bgSelector + "#" + modeBarId + " .modebar-group", "background-color: " + style5.bgcolor); - Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn .icon path", "fill: " + style5.color); - Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn:hover .icon path", "fill: " + style5.activecolor); - Lib$1l.addRelatedStyleRule(modeBarId, "#" + modeBarId + " .modebar-btn.active .icon path", "fill: " + style5.activecolor); - var needsNewButtons = !this.hasButtons(buttons2); - var needsNewLogo = this.hasLogo !== context2.displaylogo; - var needsNewLocale = this.locale !== context2.locale; - this.locale = context2.locale; - if (needsNewButtons || needsNewLogo || needsNewLocale) { - this.removeAllButtons(); - this.updateButtons(buttons2); - if (context2.watermark || context2.displaylogo) { - var logoGroup = this.getLogo(); - if (context2.watermark) { - logoGroup.className = logoGroup.className + " watermark"; - } - if (fullLayout.modebar.orientation === "v") { - this.element.insertBefore(logoGroup, this.element.childNodes[0]); - } else { - this.element.appendChild(logoGroup); - } - this.hasLogo = true; - } - } - this.updateActiveButton(); -}; -proto.updateButtons = function(buttons2) { - var _this = this; - this.buttons = buttons2; - this.buttonElements = []; - this.buttonsNames = []; - this.buttons.forEach(function(buttonGroup) { - var group = _this.createGroup(); - buttonGroup.forEach(function(buttonConfig) { - var buttonName = buttonConfig.name; - if (!buttonName) { - throw new Error("must provide button 'name' in button config"); - } - if (_this.buttonsNames.indexOf(buttonName) !== -1) { - throw new Error("button name '" + buttonName + "' is taken"); - } - _this.buttonsNames.push(buttonName); - var button = _this.createButton(buttonConfig); - _this.buttonElements.push(button); - group.appendChild(button); - }); - _this.element.appendChild(group); - }); -}; -proto.createGroup = function() { - var group = document.createElement("div"); - group.className = "modebar-group"; - return group; -}; -proto.createButton = function(config) { - var _this = this; - var button = document.createElement("a"); - button.setAttribute("rel", "tooltip"); - button.className = "modebar-btn"; - var title = config.title; - if (title === void 0) title = config.name; - else if (typeof title === "function") title = title(this.graphInfo); - if (title || title === 0) button.setAttribute("data-title", title); - if (config.attr !== void 0) button.setAttribute("data-attr", config.attr); - var val = config.val; - if (val !== void 0) { - if (typeof val === "function") val = val(this.graphInfo); - button.setAttribute("data-val", val); - } - var click3 = config.click; - if (typeof click3 !== "function") { - throw new Error("must provide button 'click' function in button config"); - } else { - button.addEventListener("click", function(ev) { - config.click(_this.graphInfo, ev); - _this.updateActiveButton(ev.currentTarget); - }); - } - button.setAttribute("data-toggle", config.toggle || false); - if (config.toggle) d3$p.select(button).classed("active", true); - var icon = config.icon; - if (typeof icon === "function") { - button.appendChild(icon()); - } else { - button.appendChild(this.createIcon(icon || Icons.question)); - } - button.setAttribute("data-gravity", config.gravity || "n"); - return button; -}; -proto.createIcon = function(thisIcon) { - var iconHeight = isNumeric$h(thisIcon.height) ? Number(thisIcon.height) : thisIcon.ascent - thisIcon.descent; - var svgNS = "http://www.w3.org/2000/svg"; - var icon; - if (thisIcon.path) { - icon = document.createElementNS(svgNS, "svg"); - icon.setAttribute("viewBox", [0, 0, thisIcon.width, iconHeight].join(" ")); - icon.setAttribute("class", "icon"); - var path = document.createElementNS(svgNS, "path"); - path.setAttribute("d", thisIcon.path); - if (thisIcon.transform) { - path.setAttribute("transform", thisIcon.transform); - } else if (thisIcon.ascent !== void 0) { - path.setAttribute("transform", "matrix(1 0 0 -1 0 " + thisIcon.ascent + ")"); - } - icon.appendChild(path); - } - if (thisIcon.svg) { - var svgDoc = Parser.parseFromString(thisIcon.svg, "application/xml"); - icon = svgDoc.childNodes[0]; - } - icon.setAttribute("height", "1em"); - icon.setAttribute("width", "1em"); - return icon; -}; -proto.updateActiveButton = function(buttonClicked) { - var fullLayout = this.graphInfo._fullLayout; - var dataAttrClicked = buttonClicked !== void 0 ? buttonClicked.getAttribute("data-attr") : null; - this.buttonElements.forEach(function(button) { - var thisval = button.getAttribute("data-val") || true; - var dataAttr = button.getAttribute("data-attr"); - var isToggleButton = button.getAttribute("data-toggle") === "true"; - var button3 = d3$p.select(button); - if (isToggleButton) { - if (dataAttr === dataAttrClicked) { - button3.classed("active", !button3.classed("active")); - } - } else { - var val = dataAttr === null ? dataAttr : Lib$1l.nestedProperty(fullLayout, dataAttr).get(); - button3.classed("active", val === thisval); - } - }); -}; -proto.hasButtons = function(buttons2) { - var currentButtons = this.buttons; - if (!currentButtons) return false; - if (buttons2.length !== currentButtons.length) return false; - for (var i = 0; i < buttons2.length; ++i) { - if (buttons2[i].length !== currentButtons[i].length) return false; - for (var j = 0; j < buttons2[i].length; j++) { - if (buttons2[i][j].name !== currentButtons[i][j].name) return false; - } - } - return true; -}; -function jsVersion(str2) { - return str2 + " (v" + version$1 + ")"; -} -proto.getLogo = function() { - var group = this.createGroup(); - var a = document.createElement("a"); - a.href = "https://plotly.com/"; - a.target = "_blank"; - a.setAttribute("data-title", jsVersion(Lib$1l._(this.graphInfo, "Produced with Plotly.js"))); - a.className = "modebar-btn plotlyjsicon modebar-btn--logo"; - a.appendChild(this.createIcon(Icons.newplotlylogo)); - group.appendChild(a); - return group; -}; -proto.removeAllButtons = function() { - while (this.element.firstChild) { - this.element.removeChild(this.element.firstChild); - } - this.hasLogo = false; -}; -proto.destroy = function() { - Lib$1l.removeElement(this.container.querySelector(".modebar")); - Lib$1l.deleteRelatedStyleRule(this._uid); -}; -function createModeBar$1(gd, buttons2) { - var fullLayout = gd._fullLayout; - var modeBar = new ModeBar({ - graphInfo: gd, - container: fullLayout._modebardiv.node(), - buttons: buttons2 - }); - if (fullLayout._privateplot) { - d3$p.select(modeBar.element).append("span").classed("badge-private float--left", true).text("PRIVATE"); - } - return modeBar; -} -var modebar$1 = createModeBar$1; -var axisIds$5 = axis_ids; -var scatterSubTypes = subtypes$3; -var Registry$w = registry; -var isUnifiedHover = helpers$J.isUnifiedHover; -var createModeBar = modebar$1; -var modeBarButtons = buttonsExports; -var DRAW_MODES = constants$F.DRAW_MODES; -var extendDeep$1 = libExports.extendDeep; -var manage = function manageModeBar(gd) { - var fullLayout = gd._fullLayout; - var context2 = gd._context; - var modeBar = fullLayout._modeBar; - if (!context2.displayModeBar && !context2.watermark) { - if (modeBar) { - modeBar.destroy(); - delete fullLayout._modeBar; - } - return; - } - if (!Array.isArray(context2.modeBarButtonsToRemove)) { - throw new Error([ - "*modeBarButtonsToRemove* configuration options", - "must be an array." - ].join(" ")); - } - if (!Array.isArray(context2.modeBarButtonsToAdd)) { - throw new Error([ - "*modeBarButtonsToAdd* configuration options", - "must be an array." - ].join(" ")); - } - var customButtons = context2.modeBarButtons; - var buttonGroups; - if (Array.isArray(customButtons) && customButtons.length) { - buttonGroups = fillCustomButton(customButtons); - } else if (!context2.displayModeBar && context2.watermark) { - buttonGroups = []; - } else { - buttonGroups = getButtonGroups(gd); - } - if (modeBar) modeBar.update(gd, buttonGroups); - else fullLayout._modeBar = createModeBar(gd, buttonGroups); -}; -function getButtonGroups(gd) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; - var context2 = gd._context; - function match(name2, B2) { - if (typeof B2 === "string") { - if (B2.toLowerCase() === name2.toLowerCase()) return true; - } else { - var v0 = B2.name; - var v1 = B2._cat || B2.name; - if (v0 === name2 || v1 === name2.toLowerCase()) return true; - } - return false; - } - var layoutAdd = fullLayout.modebar.add; - if (typeof layoutAdd === "string") layoutAdd = [layoutAdd]; - var layoutRemove = fullLayout.modebar.remove; - if (typeof layoutRemove === "string") layoutRemove = [layoutRemove]; - var buttonsToAdd = context2.modeBarButtonsToAdd.concat( - layoutAdd.filter(function(e) { - for (var i2 = 0; i2 < context2.modeBarButtonsToRemove.length; i2++) { - if (match(e, context2.modeBarButtonsToRemove[i2])) return false; - } - return true; - }) - ); - var buttonsToRemove = context2.modeBarButtonsToRemove.concat( - layoutRemove.filter(function(e) { - for (var i2 = 0; i2 < context2.modeBarButtonsToAdd.length; i2++) { - if (match(e, context2.modeBarButtonsToAdd[i2])) return false; - } - return true; - }) - ); - var hasCartesian = fullLayout._has("cartesian"); - var hasGL3D = fullLayout._has("gl3d"); - var hasGeo = fullLayout._has("geo"); - var hasPie = fullLayout._has("pie"); - var hasFunnelarea = fullLayout._has("funnelarea"); - var hasGL2D = fullLayout._has("gl2d"); - var hasTernary = fullLayout._has("ternary"); - var hasMapbox = fullLayout._has("mapbox"); - var hasMap = fullLayout._has("map"); - var hasPolar = fullLayout._has("polar"); - var hasSmith = fullLayout._has("smith"); - var hasSankey = fullLayout._has("sankey"); - var allAxesFixed = areAllAxesFixed(fullLayout); - var hasUnifiedHoverLabel = isUnifiedHover(fullLayout.hovermode); - var groups = []; - function addGroup(newGroup) { - if (!newGroup.length) return; - var out = []; - for (var i2 = 0; i2 < newGroup.length; i2++) { - var name2 = newGroup[i2]; - var B2 = modeBarButtons[name2]; - var v0 = B2.name.toLowerCase(); - var v1 = (B2._cat || B2.name).toLowerCase(); - var found = false; - for (var q = 0; q < buttonsToRemove.length; q++) { - var t = buttonsToRemove[q].toLowerCase(); - if (t === v0 || t === v1) { - found = true; - break; - } - } - if (found) continue; - out.push(modeBarButtons[name2]); - } - groups.push(out); - } - var commonGroup = ["toImage"]; - if (context2.showEditInChartStudio) commonGroup.push("editInChartStudio"); - else if (context2.showSendToCloud) commonGroup.push("sendDataToCloud"); - addGroup(commonGroup); - var zoomGroup = []; - var hoverGroup = []; - var resetGroup = []; - var dragModeGroup = []; - if ((hasCartesian || hasGL2D || hasPie || hasFunnelarea || hasTernary) + hasGeo + hasGL3D + hasMapbox + hasMap + hasPolar + hasSmith > 1) { - hoverGroup = ["toggleHover"]; - resetGroup = ["resetViews"]; - } else if (hasGeo) { - zoomGroup = ["zoomInGeo", "zoomOutGeo"]; - hoverGroup = ["hoverClosestGeo"]; - resetGroup = ["resetGeo"]; - } else if (hasGL3D) { - hoverGroup = ["hoverClosest3d"]; - resetGroup = ["resetCameraDefault3d", "resetCameraLastSave3d"]; - } else if (hasMapbox) { - zoomGroup = ["zoomInMapbox", "zoomOutMapbox"]; - hoverGroup = ["toggleHover"]; - resetGroup = ["resetViewMapbox"]; - } else if (hasMap) { - zoomGroup = ["zoomInMap", "zoomOutMap"]; - hoverGroup = ["toggleHover"]; - resetGroup = ["resetViewMap"]; - } else if (hasGL2D) { - hoverGroup = ["hoverClosestGl2d"]; - } else if (hasPie) { - hoverGroup = ["hoverClosestPie"]; - } else if (hasSankey) { - hoverGroup = ["hoverClosestCartesian", "hoverCompareCartesian"]; - resetGroup = ["resetViewSankey"]; - } else { - hoverGroup = ["toggleHover"]; - } - if (hasCartesian) { - hoverGroup.push("toggleSpikelines", "hoverClosestCartesian", "hoverCompareCartesian"); - } - if (hasNoHover(fullData) || hasUnifiedHoverLabel) { - hoverGroup = []; - } - if ((hasCartesian || hasGL2D) && !allAxesFixed) { - zoomGroup = ["zoomIn2d", "zoomOut2d", "autoScale2d"]; - if (resetGroup[0] !== "resetViews") resetGroup = ["resetScale2d"]; - } - if (hasGL3D) { - dragModeGroup = ["zoom3d", "pan3d", "orbitRotation", "tableRotation"]; - } else if ((hasCartesian || hasGL2D) && !allAxesFixed || hasTernary) { - dragModeGroup = ["zoom2d", "pan2d"]; - } else if (hasMapbox || hasMap || hasGeo) { - dragModeGroup = ["pan2d"]; - } else if (hasPolar) { - dragModeGroup = ["zoom2d"]; - } - if (isSelectable(fullData)) { - dragModeGroup.push("select2d", "lasso2d"); - } - var enabledHoverGroup = []; - var enableHover = function(a) { - if (enabledHoverGroup.indexOf(a) !== -1) return; - if (hoverGroup.indexOf(a) !== -1) { - enabledHoverGroup.push(a); - } - }; - if (Array.isArray(buttonsToAdd)) { - var newList = []; - for (var i = 0; i < buttonsToAdd.length; i++) { - var b = buttonsToAdd[i]; - if (typeof b === "string") { - b = b.toLowerCase(); - if (DRAW_MODES.indexOf(b) !== -1) { - if (fullLayout._has("mapbox") || fullLayout._has("map") || // draw shapes in paper coordinate (could be improved in future to support data coordinate, when there is no pitch) - fullLayout._has("cartesian")) { - dragModeGroup.push(b); - } - } else if (b === "togglespikelines") { - enableHover("toggleSpikelines"); - } else if (b === "togglehover") { - enableHover("toggleHover"); - } else if (b === "hovercompare") { - enableHover("hoverCompareCartesian"); - } else if (b === "hoverclosest") { - enableHover("hoverClosestCartesian"); - enableHover("hoverClosestGeo"); - enableHover("hoverClosest3d"); - enableHover("hoverClosestGl2d"); - enableHover("hoverClosestPie"); - } else if (b === "v1hovermode") { - enableHover("hoverClosestCartesian"); - enableHover("hoverCompareCartesian"); - enableHover("hoverClosestGeo"); - enableHover("hoverClosest3d"); - enableHover("hoverClosestGl2d"); - enableHover("hoverClosestPie"); - } - } else newList.push(b); - } - buttonsToAdd = newList; - } - addGroup(dragModeGroup); - addGroup(zoomGroup.concat(resetGroup)); - addGroup(enabledHoverGroup); - return appendButtonsToGroups(groups, buttonsToAdd); -} -function areAllAxesFixed(fullLayout) { - var axList = axisIds$5.list({ _fullLayout: fullLayout }, null, true); - for (var i = 0; i < axList.length; i++) { - if (!axList[i].fixedrange) { - return false; - } - } - return true; -} -function isSelectable(fullData) { - var selectable = false; - for (var i = 0; i < fullData.length; i++) { - if (selectable) break; - var trace = fullData[i]; - if (!trace._module || !trace._module.selectPoints) continue; - if (Registry$w.traceIs(trace, "scatter-like")) { - if (scatterSubTypes.hasMarkers(trace) || scatterSubTypes.hasText(trace)) { - selectable = true; - } - } else if (Registry$w.traceIs(trace, "box-violin")) { - if (trace.boxpoints === "all" || trace.points === "all") { - selectable = true; - } - } else { - selectable = true; - } - } - return selectable; -} -function hasNoHover(fullData) { - for (var i = 0; i < fullData.length; i++) { - if (!Registry$w.traceIs(fullData[i], "noHover")) return false; - } - return true; -} -function appendButtonsToGroups(groups, buttons2) { - if (buttons2.length) { - if (Array.isArray(buttons2[0])) { - for (var i = 0; i < buttons2.length; i++) { - groups.push(buttons2[i]); - } - } else groups.push(buttons2); - } - return groups; -} -function fillCustomButton(originalModeBarButtons) { - var customButtons = extendDeep$1([], originalModeBarButtons); - for (var i = 0; i < customButtons.length; i++) { - var buttonGroup = customButtons[i]; - for (var j = 0; j < buttonGroup.length; j++) { - var button = buttonGroup[j]; - if (typeof button === "string") { - if (modeBarButtons[button] !== void 0) { - customButtons[i][j] = modeBarButtons[button]; - } else { - throw new Error([ - "*modeBarButtons* configuration options", - "invalid button name" - ].join(" ")); - } - } - } - } - return customButtons; -} -var modebar = { - moduleType: "component", - name: "modebar", - layoutAttributes: attributes$D, - supplyLayoutDefaults: defaults$k, - manage -}; -var constraints = {}; -var FROM_BL$1 = alignment$1.FROM_BL; -var scale_zoom = function scaleZoom(ax, factor, centerFraction) { - if (centerFraction === void 0) { - centerFraction = FROM_BL$1[ax.constraintoward || "center"]; - } - var rangeLinear = [ax.r2l(ax.range[0]), ax.r2l(ax.range[1])]; - var center = rangeLinear[0] + (rangeLinear[1] - rangeLinear[0]) * centerFraction; - ax.range = ax._input.range = [ - ax.l2r(center + (rangeLinear[0] - center) * factor), - ax.l2r(center + (rangeLinear[1] - center) * factor) - ]; - ax.setScale(); -}; -var Lib$1k = libExports; -var autorange = autorange$2; -var id2name = axis_ids.id2name; -var layoutAttributes$5 = layout_attributes$4; -var scaleZoom2 = scale_zoom; -var setConvert$1 = set_convert; -var ALMOST_EQUAL = numerical.ALMOST_EQUAL; -var FROM_BL = alignment$1.FROM_BL; -constraints.handleDefaults = function(layoutIn, layoutOut, opts) { - var axIds2 = opts.axIds; - var axHasImage = opts.axHasImage; - var constraintGroups = layoutOut._axisConstraintGroups = []; - var matchGroups = layoutOut._axisMatchGroups = []; - var i, group, axId, axName, axIn, axOut, attr, val; - for (i = 0; i < axIds2.length; i++) { - axName = id2name(axIds2[i]); - axIn = layoutIn[axName]; - axOut = layoutOut[axName]; - handleOneAxDefaults(axIn, axOut, { - axIds: axIds2, - layoutOut, - hasImage: axHasImage[axName] - }); - } - function stash(groups, stashAttr) { - for (i = 0; i < groups.length; i++) { - group = groups[i]; - for (axId in group) { - layoutOut[id2name(axId)][stashAttr] = group; - } - } - } - stash(matchGroups, "_matchGroup"); - for (i = 0; i < constraintGroups.length; i++) { - group = constraintGroups[i]; - for (axId in group) { - axOut = layoutOut[id2name(axId)]; - if (axOut.fixedrange) { - for (var axId2 in group) { - var axName2 = id2name(axId2); - if ((layoutIn[axName2] || {}).fixedrange === false) { - Lib$1k.warn( - "fixedrange was specified as false for axis " + axName2 + " but was overridden because another axis in its constraint group has fixedrange true" - ); - } - layoutOut[axName2].fixedrange = true; - } - break; - } - } - } - i = 0; - while (i < constraintGroups.length) { - group = constraintGroups[i]; - for (axId in group) { - axOut = layoutOut[id2name(axId)]; - if (axOut._matchGroup && Object.keys(axOut._matchGroup).length === Object.keys(group).length) { - constraintGroups.splice(i, 1); - i--; - } - break; - } - i++; - } - stash(constraintGroups, "_constraintGroup"); - var matchAttrs = [ - "constrain", - "range", - "autorange", - "rangemode", - "rangebreaks", - "categoryorder", - "categoryarray" - ]; - var hasRange = false; - var hasDayOfWeekBreaks = false; - function setAttrVal() { - val = axOut[attr]; - if (attr === "rangebreaks") { - hasDayOfWeekBreaks = axOut._hasDayOfWeekBreaks; - } - } - for (i = 0; i < matchGroups.length; i++) { - group = matchGroups[i]; - for (var j = 0; j < matchAttrs.length; j++) { - attr = matchAttrs[j]; - val = null; - var baseAx; - for (axId in group) { - axName = id2name(axId); - axIn = layoutIn[axName]; - axOut = layoutOut[axName]; - if (!(attr in axOut)) { - continue; - } - if (!axOut.matches) { - baseAx = axOut; - if (attr in axIn) { - setAttrVal(); - break; - } - } - if (val === null && attr in axIn) { - setAttrVal(); - } - } - if (attr === "range" && val && axIn.range && axIn.range.length === 2 && axIn.range[0] !== null && axIn.range[1] !== null) { - hasRange = true; - } - if (attr === "autorange" && val === null && hasRange) { - val = false; - } - if (val === null && attr in baseAx) { - val = baseAx[attr]; - } - if (val !== null) { - for (axId in group) { - axOut = layoutOut[id2name(axId)]; - axOut[attr] = attr === "range" ? val.slice() : val; - if (attr === "rangebreaks") { - axOut._hasDayOfWeekBreaks = hasDayOfWeekBreaks; - setConvert$1(axOut, layoutOut); - } - } - } - } - } -}; -function handleOneAxDefaults(axIn, axOut, opts) { - var axIds2 = opts.axIds; - var layoutOut = opts.layoutOut; - var hasImage = opts.hasImage; - var constraintGroups = layoutOut._axisConstraintGroups; - var matchGroups = layoutOut._axisMatchGroups; - var axId = axOut._id; - var axLetter = axId.charAt(0); - var splomStash = ((layoutOut._splomAxes || {})[axLetter] || {})[axId] || {}; - var thisID = axOut._id; - var isX = thisID.charAt(0) === "x"; - axOut._matchGroup = null; - axOut._constraintGroup = null; - function coerce2(attr, dflt) { - return Lib$1k.coerce(axIn, axOut, layoutAttributes$5, attr, dflt); - } - coerce2("constrain", hasImage ? "domain" : "range"); - Lib$1k.coerce(axIn, axOut, { - constraintoward: { - valType: "enumerated", - values: isX ? ["left", "center", "right"] : ["bottom", "middle", "top"], - dflt: isX ? "center" : "middle" - } - }, "constraintoward"); - var thisType = axOut.type; - var i, idi; - var linkableAxes = []; - for (i = 0; i < axIds2.length; i++) { - idi = axIds2[i]; - if (idi === thisID) continue; - var axi = layoutOut[id2name(idi)]; - if (axi.type === thisType) { - linkableAxes.push(idi); - } - } - var thisGroup = getConstraintGroup(constraintGroups, thisID); - if (thisGroup) { - var linkableAxesNoLoops = []; - for (i = 0; i < linkableAxes.length; i++) { - idi = linkableAxes[i]; - if (!thisGroup[idi]) linkableAxesNoLoops.push(idi); - } - linkableAxes = linkableAxesNoLoops; - } - var canLink = linkableAxes.length; - var matches, scaleanchor; - if (canLink && (axIn.matches || splomStash.matches)) { - matches = Lib$1k.coerce(axIn, axOut, { - matches: { - valType: "enumerated", - values: linkableAxes, - dflt: linkableAxes.indexOf(splomStash.matches) !== -1 ? splomStash.matches : void 0 - } - }, "matches"); - } - var scaleanchorDflt = hasImage && !isX ? axOut.anchor : void 0; - if (canLink && !matches && (axIn.scaleanchor || scaleanchorDflt)) { - scaleanchor = Lib$1k.coerce(axIn, axOut, { - scaleanchor: { - valType: "enumerated", - values: linkableAxes.concat([false]) - } - }, "scaleanchor", scaleanchorDflt); - } - if (matches) { - axOut._matchGroup = updateConstraintGroups(matchGroups, thisID, matches, 1); - var matchedAx = layoutOut[id2name(matches)]; - var matchRatio = extent(layoutOut, axOut) / extent(layoutOut, matchedAx); - if (isX !== (matches.charAt(0) === "x")) { - matchRatio = (isX ? "x" : "y") + matchRatio; - } - updateConstraintGroups(constraintGroups, thisID, matches, matchRatio); - } else if (axIn.matches && axIds2.indexOf(axIn.matches) !== -1) { - Lib$1k.warn("ignored " + axOut._name + '.matches: "' + axIn.matches + '" to avoid an infinite loop'); - } - if (scaleanchor) { - var scaleratio = coerce2("scaleratio"); - if (!scaleratio) scaleratio = axOut.scaleratio = 1; - updateConstraintGroups(constraintGroups, thisID, scaleanchor, scaleratio); - } else if (axIn.scaleanchor && axIds2.indexOf(axIn.scaleanchor) !== -1) { - Lib$1k.warn("ignored " + axOut._name + '.scaleanchor: "' + axIn.scaleanchor + '" to avoid either an infinite loop and possibly inconsistent scaleratios, or because this axis declares a *matches* constraint.'); - } -} -function extent(layoutOut, ax) { - var domain2 = ax.domain; - if (!domain2) { - domain2 = layoutOut[id2name(ax.overlaying)].domain; - } - return domain2[1] - domain2[0]; -} -function getConstraintGroup(groups, thisID) { - for (var i = 0; i < groups.length; i++) { - if (groups[i][thisID]) { - return groups[i]; - } - } - return null; -} -function updateConstraintGroups(constraintGroups, thisID, thatID, scaleratio) { - var i, j, groupi, keyj, thisGroupIndex; - var thisGroup = getConstraintGroup(constraintGroups, thisID); - if (thisGroup === null) { - thisGroup = {}; - thisGroup[thisID] = 1; - thisGroupIndex = constraintGroups.length; - constraintGroups.push(thisGroup); - } else { - thisGroupIndex = constraintGroups.indexOf(thisGroup); - } - var thisGroupKeys = Object.keys(thisGroup); - for (i = 0; i < constraintGroups.length; i++) { - groupi = constraintGroups[i]; - if (i !== thisGroupIndex && groupi[thatID]) { - var baseScale = groupi[thatID]; - for (j = 0; j < thisGroupKeys.length; j++) { - keyj = thisGroupKeys[j]; - groupi[keyj] = multiplyScales(baseScale, multiplyScales(scaleratio, thisGroup[keyj])); - } - constraintGroups.splice(thisGroupIndex, 1); - return; - } - } - if (scaleratio !== 1) { - for (j = 0; j < thisGroupKeys.length; j++) { - var key = thisGroupKeys[j]; - thisGroup[key] = multiplyScales(scaleratio, thisGroup[key]); - } - } - thisGroup[thatID] = 1; -} -function multiplyScales(a, b) { - var aPrefix = ""; - var bPrefix = ""; - var aLen, bLen; - if (typeof a === "string") { - aPrefix = a.match(/^[xy]*/)[0]; - aLen = aPrefix.length; - a = +a.substr(aLen); - } - if (typeof b === "string") { - bPrefix = b.match(/^[xy]*/)[0]; - bLen = bPrefix.length; - b = +b.substr(bLen); - } - var c = a * b; - if (!aLen && !bLen) { - return c; - } - if (!aLen || !bLen || aPrefix.charAt(0) === bPrefix.charAt(0)) { - return aPrefix + bPrefix + a * b; - } - if (aLen === bLen) { - return c; - } - return (aLen > bLen ? aPrefix.substr(bLen) : bPrefix.substr(aLen)) + c; -} -function finalRatios(group, fullLayout) { - var size = fullLayout._size; - var yRatio = size.h / size.w; - var out = {}; - var keys = Object.keys(group); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - var val = group[key]; - if (typeof val === "string") { - var prefix = val.match(/^[xy]*/)[0]; - var pLen = prefix.length; - val = +val.substr(pLen); - var mult = prefix.charAt(0) === "y" ? yRatio : 1 / yRatio; - for (var j = 0; j < pLen; j++) { - val *= mult; - } - } - out[key] = val; - } - return out; -} -constraints.enforce = function enforce(gd) { - var fullLayout = gd._fullLayout; - var constraintGroups = fullLayout._axisConstraintGroups || []; - var i, j, group, axisID, ax, normScale, mode, factor; - for (i = 0; i < constraintGroups.length; i++) { - group = finalRatios(constraintGroups[i], fullLayout); - var axisIDs2 = Object.keys(group); - var minScale = Infinity; - var maxScale = 0; - var matchScale = Infinity; - var normScales = {}; - var axes2 = {}; - var hasAnyDomainConstraint = false; - for (j = 0; j < axisIDs2.length; j++) { - axisID = axisIDs2[j]; - axes2[axisID] = ax = fullLayout[id2name(axisID)]; - if (ax._inputDomain) ax.domain = ax._inputDomain.slice(); - else ax._inputDomain = ax.domain.slice(); - if (!ax._inputRange) ax._inputRange = ax.range.slice(); - ax.setScale(); - normScales[axisID] = normScale = Math.abs(ax._m) / group[axisID]; - minScale = Math.min(minScale, normScale); - if (ax.constrain === "domain" || !ax._constraintShrinkable) { - matchScale = Math.min(matchScale, normScale); - } - delete ax._constraintShrinkable; - maxScale = Math.max(maxScale, normScale); - if (ax.constrain === "domain") hasAnyDomainConstraint = true; - } - if (minScale > ALMOST_EQUAL * maxScale && !hasAnyDomainConstraint) continue; - for (j = 0; j < axisIDs2.length; j++) { - axisID = axisIDs2[j]; - normScale = normScales[axisID]; - ax = axes2[axisID]; - mode = ax.constrain; - if (normScale !== matchScale || mode === "domain") { - factor = normScale / matchScale; - if (mode === "range") { - scaleZoom2(ax, factor); - } else { - var inputDomain = ax._inputDomain; - var domainShrunk = (ax.domain[1] - ax.domain[0]) / (inputDomain[1] - inputDomain[0]); - var rangeShrunk = (ax.r2l(ax.range[1]) - ax.r2l(ax.range[0])) / (ax.r2l(ax._inputRange[1]) - ax.r2l(ax._inputRange[0])); - factor /= domainShrunk; - if (factor * rangeShrunk < 1) { - ax.domain = ax._input.domain = inputDomain.slice(); - scaleZoom2(ax, factor); - continue; - } - if (rangeShrunk < 1) { - ax.range = ax._input.range = ax._inputRange.slice(); - factor *= rangeShrunk; - } - if (ax.autorange) { - var rl0 = ax.r2l(ax.range[0]); - var rl1 = ax.r2l(ax.range[1]); - var rangeCenter = (rl0 + rl1) / 2; - var rangeMin = rangeCenter; - var rangeMax = rangeCenter; - var halfRange = Math.abs(rl1 - rangeCenter); - var outerMin = rangeCenter - halfRange * factor * 1.0001; - var outerMax = rangeCenter + halfRange * factor * 1.0001; - var getPadMin = autorange.makePadFn(fullLayout, ax, 0); - var getPadMax = autorange.makePadFn(fullLayout, ax, 1); - updateDomain(ax, factor); - var m = Math.abs(ax._m); - var extremes = autorange.concatExtremes(gd, ax); - var minArray = extremes.min; - var maxArray = extremes.max; - var newVal; - var k; - for (k = 0; k < minArray.length; k++) { - newVal = minArray[k].val - getPadMin(minArray[k]) / m; - if (newVal > outerMin && newVal < rangeMin) { - rangeMin = newVal; - } - } - for (k = 0; k < maxArray.length; k++) { - newVal = maxArray[k].val + getPadMax(maxArray[k]) / m; - if (newVal < outerMax && newVal > rangeMax) { - rangeMax = newVal; - } - } - var domainExpand = (rangeMax - rangeMin) / (2 * halfRange); - factor /= domainExpand; - rangeMin = ax.l2r(rangeMin); - rangeMax = ax.l2r(rangeMax); - ax.range = ax._input.range = rl0 < rl1 ? [rangeMin, rangeMax] : [rangeMax, rangeMin]; - } - updateDomain(ax, factor); - } - } - } - } -}; -constraints.getAxisGroup = function getAxisGroup(fullLayout, axId) { - var matchGroups = fullLayout._axisMatchGroups; - for (var i = 0; i < matchGroups.length; i++) { - var group = matchGroups[i]; - if (group[axId]) return "g" + i; - } - return axId; -}; -constraints.clean = function clean(gd, ax) { - if (ax._inputDomain) { - var isConstrained = false; - var axId = ax._id; - var constraintGroups = gd._fullLayout._axisConstraintGroups; - for (var j = 0; j < constraintGroups.length; j++) { - if (constraintGroups[j][axId]) { - isConstrained = true; - break; - } - } - if (!isConstrained || ax.constrain !== "domain") { - ax._input.domain = ax.domain = ax._inputDomain; - delete ax._inputDomain; - } - } -}; -function updateDomain(ax, factor) { - var inputDomain = ax._inputDomain; - var centerFraction = FROM_BL[ax.constraintoward]; - var center = inputDomain[0] + (inputDomain[1] - inputDomain[0]) * centerFraction; - ax.domain = ax._input.domain = [ - center + (inputDomain[0] - center) / factor, - center + (inputDomain[1] - center) / factor - ]; - ax.setScale(); -} -(function(exports2) { - var d32 = d3Exports; - var Registry2 = registry; - var Plots2 = plotsExports; - var Lib2 = libExports; - var svgTextUtils2 = svg_text_utils; - var clearGlCanvases3 = clear_gl_canvases; - var Color2 = colorExports; - var Drawing2 = drawingExports; - var Titles2 = titles; - var ModeBar2 = modebar; - var Axes2 = axesExports; - var alignmentConstants2 = alignment$1; - var axisConstraints = constraints; - var enforceAxisConstraints = axisConstraints.enforce; - var cleanAxisConstraints = axisConstraints.clean; - var doAutoRange2 = autorange$2.doAutoRange; - var SVG_TEXT_ANCHOR_START = "start"; - var SVG_TEXT_ANCHOR_MIDDLE = "middle"; - var SVG_TEXT_ANCHOR_END = "end"; - var zindexSeparator2 = constants$U.zindexSeparator; - exports2.layoutStyles = function(gd) { - return Lib2.syncOrAsync([Plots2.doAutoMargin, lsInner], gd); - }; - function overlappingDomain(xDomain, yDomain, domains) { - for (var i = 0; i < domains.length; i++) { - var existingX = domains[i][0]; - var existingY = domains[i][1]; - if (existingX[0] >= xDomain[1] || existingX[1] <= xDomain[0]) { - continue; - } - if (existingY[0] < yDomain[1] && existingY[1] > yDomain[0]) { - return true; - } - } - return false; - } - function lsInner(gd) { - var fullLayout = gd._fullLayout; - var gs = fullLayout._size; - var pad2 = gs.p; - var axList = Axes2.list(gd, "", true); - var i, subplot, plotinfo, ax, xa, ya; - fullLayout._paperdiv.style({ - width: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroWidth && !gd.layout.width ? "100%" : fullLayout.width + "px", - height: gd._context.responsive && fullLayout.autosize && !gd._context._hasZeroHeight && !gd.layout.height ? "100%" : fullLayout.height + "px" - }).selectAll(".main-svg").call(Drawing2.setSize, fullLayout.width, fullLayout.height); - gd._context.setBackground(gd, fullLayout.paper_bgcolor); - exports2.drawMainTitle(gd); - ModeBar2.manage(gd); - if (!fullLayout._has("cartesian")) { - return Plots2.previousPromises(gd); - } - function getLinePosition(ax2, counterAx2, side) { - var lwHalf = ax2._lw / 2; - if (ax2._id.charAt(0) === "x") { - if (!counterAx2) return gs.t + gs.h * (1 - (ax2.position || 0)) + lwHalf % 1; - else if (side === "top") return counterAx2._offset - pad2 - lwHalf; - return counterAx2._offset + counterAx2._length + pad2 + lwHalf; - } - if (!counterAx2) return gs.l + gs.w * (ax2.position || 0) + lwHalf % 1; - else if (side === "right") return counterAx2._offset + counterAx2._length + pad2 + lwHalf; - return counterAx2._offset - pad2 - lwHalf; - } - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - var counterAx = ax._anchorAxis; - ax._linepositions = {}; - ax._lw = Drawing2.crispRound(gd, ax.linewidth, 1); - ax._mainLinePosition = getLinePosition(ax, counterAx, ax.side); - ax._mainMirrorPosition = ax.mirror && counterAx ? getLinePosition( - ax, - counterAx, - alignmentConstants2.OPPOSITE_SIDE[ax.side] - ) : null; - } - var lowerBackgroundIDs = []; - var backgroundIds = []; - var lowerDomains = []; - var noNeedForBg = Color2.opacity(fullLayout.paper_bgcolor) === 1 && Color2.opacity(fullLayout.plot_bgcolor) === 1 && fullLayout.paper_bgcolor === fullLayout.plot_bgcolor; - for (subplot in fullLayout._plots) { - plotinfo = fullLayout._plots[subplot]; - if (plotinfo.mainplot) { - if (plotinfo.bg) { - plotinfo.bg.remove(); - } - plotinfo.bg = void 0; - } else { - var xDomain = plotinfo.xaxis.domain; - var yDomain = plotinfo.yaxis.domain; - var plotgroup = plotinfo.plotgroup; - if (overlappingDomain(xDomain, yDomain, lowerDomains) && subplot.indexOf(zindexSeparator2) === -1) { - var pgNode = plotgroup.node(); - var plotgroupBg = plotinfo.bg = Lib2.ensureSingle(plotgroup, "rect", "bg"); - pgNode.insertBefore(plotgroupBg.node(), pgNode.childNodes[0]); - backgroundIds.push(subplot); - } else { - plotgroup.select("rect.bg").remove(); - lowerDomains.push([xDomain, yDomain]); - if (!noNeedForBg) { - lowerBackgroundIDs.push(subplot); - backgroundIds.push(subplot); - } - } - } - } - var lowerBackgrounds = fullLayout._bgLayer.selectAll(".bg").data(lowerBackgroundIDs); - lowerBackgrounds.enter().append("rect").classed("bg", true); - lowerBackgrounds.exit().remove(); - lowerBackgrounds.each(function(subplot2) { - fullLayout._plots[subplot2].bg = d32.select(this); - }); - for (i = 0; i < backgroundIds.length; i++) { - plotinfo = fullLayout._plots[backgroundIds[i]]; - xa = plotinfo.xaxis; - ya = plotinfo.yaxis; - if (plotinfo.bg && xa._offset !== void 0 && ya._offset !== void 0) { - plotinfo.bg.call( - Drawing2.setRect, - xa._offset - pad2, - ya._offset - pad2, - xa._length + 2 * pad2, - ya._length + 2 * pad2 - ).call(Color2.fill, fullLayout.plot_bgcolor).style("stroke-width", 0); - } - } - if (!fullLayout._hasOnlyLargeSploms) { - for (subplot in fullLayout._plots) { - plotinfo = fullLayout._plots[subplot]; - xa = plotinfo.xaxis; - ya = plotinfo.yaxis; - var clipId = plotinfo.clipId = "clip" + fullLayout._uid + subplot + "plot"; - var plotClip = Lib2.ensureSingleById(fullLayout._clips, "clipPath", clipId, function(s) { - s.classed("plotclip", true).append("rect"); - }); - plotinfo.clipRect = plotClip.select("rect").attr({ - width: xa._length, - height: ya._length - }); - Drawing2.setTranslate(plotinfo.plot, xa._offset, ya._offset); - var plotClipId; - var layerClipId; - if (plotinfo._hasClipOnAxisFalse) { - plotClipId = null; - layerClipId = clipId; - } else { - plotClipId = clipId; - layerClipId = null; - } - Drawing2.setClipUrl(plotinfo.plot, plotClipId, gd); - plotinfo.layerClipId = layerClipId; - } - } - var xLinesXLeft, xLinesXRight, xLinesYBottom, xLinesYTop, leftYLineWidth, rightYLineWidth; - var yLinesYBottom, yLinesYTop, yLinesXLeft, yLinesXRight, connectYBottom, connectYTop; - var extraSubplot; - function xLinePath(y) { - return "M" + xLinesXLeft + "," + y + "H" + xLinesXRight; - } - function xLinePathFree(y) { - return "M" + xa._offset + "," + y + "h" + xa._length; - } - function yLinePath(x) { - return "M" + x + "," + yLinesYTop + "V" + yLinesYBottom; - } - function yLinePathFree(x) { - if (ya._shift !== void 0) { - x += ya._shift; - } - return "M" + x + "," + ya._offset + "v" + ya._length; - } - function mainPath(ax2, pathFn, pathFnFree) { - if (!ax2.showline || subplot !== ax2._mainSubplot) return ""; - if (!ax2._anchorAxis) return pathFnFree(ax2._mainLinePosition); - var out = pathFn(ax2._mainLinePosition); - if (ax2.mirror) out += pathFn(ax2._mainMirrorPosition); - return out; - } - for (subplot in fullLayout._plots) { - plotinfo = fullLayout._plots[subplot]; - xa = plotinfo.xaxis; - ya = plotinfo.yaxis; - var xPath = "M0,0"; - if (shouldShowLinesOrTicks(xa, subplot)) { - leftYLineWidth = findCounterAxisLineWidth(xa, "left", ya, axList); - xLinesXLeft = xa._offset - (leftYLineWidth ? pad2 + leftYLineWidth : 0); - rightYLineWidth = findCounterAxisLineWidth(xa, "right", ya, axList); - xLinesXRight = xa._offset + xa._length + (rightYLineWidth ? pad2 + rightYLineWidth : 0); - xLinesYBottom = getLinePosition(xa, ya, "bottom"); - xLinesYTop = getLinePosition(xa, ya, "top"); - extraSubplot = !xa._anchorAxis || subplot !== xa._mainSubplot; - if (extraSubplot && (xa.mirror === "allticks" || xa.mirror === "all")) { - xa._linepositions[subplot] = [xLinesYBottom, xLinesYTop]; - } - xPath = mainPath(xa, xLinePath, xLinePathFree); - if (extraSubplot && xa.showline && (xa.mirror === "all" || xa.mirror === "allticks")) { - xPath += xLinePath(xLinesYBottom) + xLinePath(xLinesYTop); - } - plotinfo.xlines.style("stroke-width", xa._lw + "px").call(Color2.stroke, xa.showline ? xa.linecolor : "rgba(0,0,0,0)"); - } - plotinfo.xlines.attr("d", xPath); - var yPath = "M0,0"; - if (shouldShowLinesOrTicks(ya, subplot)) { - connectYBottom = findCounterAxisLineWidth(ya, "bottom", xa, axList); - yLinesYBottom = ya._offset + ya._length + (connectYBottom ? pad2 : 0); - connectYTop = findCounterAxisLineWidth(ya, "top", xa, axList); - yLinesYTop = ya._offset - (connectYTop ? pad2 : 0); - yLinesXLeft = getLinePosition(ya, xa, "left"); - yLinesXRight = getLinePosition(ya, xa, "right"); - extraSubplot = !ya._anchorAxis || subplot !== ya._mainSubplot; - if (extraSubplot && (ya.mirror === "allticks" || ya.mirror === "all")) { - ya._linepositions[subplot] = [yLinesXLeft, yLinesXRight]; - } - yPath = mainPath(ya, yLinePath, yLinePathFree); - if (extraSubplot && ya.showline && (ya.mirror === "all" || ya.mirror === "allticks")) { - yPath += yLinePath(yLinesXLeft) + yLinePath(yLinesXRight); - } - plotinfo.ylines.style("stroke-width", ya._lw + "px").call(Color2.stroke, ya.showline ? ya.linecolor : "rgba(0,0,0,0)"); - } - plotinfo.ylines.attr("d", yPath); - } - Axes2.makeClipPaths(gd); - return Plots2.previousPromises(gd); - } - function shouldShowLinesOrTicks(ax, subplot) { - return (ax.ticks || ax.showline) && (subplot === ax._mainSubplot || ax.mirror === "all" || ax.mirror === "allticks"); - } - function shouldShowLineThisSide(ax, side, counterAx) { - if (!counterAx.showline || !counterAx._lw) return false; - if (counterAx.mirror === "all" || counterAx.mirror === "allticks") return true; - var anchorAx = counterAx._anchorAxis; - if (!anchorAx) return false; - var sideIndex = alignmentConstants2.FROM_BL[side]; - if (counterAx.side === side) { - return anchorAx.domain[sideIndex] === ax.domain[sideIndex]; - } - return counterAx.mirror && anchorAx.domain[1 - sideIndex] === ax.domain[1 - sideIndex]; - } - function findCounterAxisLineWidth(ax, side, counterAx, axList) { - if (shouldShowLineThisSide(ax, side, counterAx)) { - return counterAx._lw; - } - for (var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if (axi._mainAxis === counterAx._mainAxis && shouldShowLineThisSide(ax, side, axi)) { - return axi._lw; - } - } - return 0; - } - exports2.drawMainTitle = function(gd) { - var title = gd._fullLayout.title; - var fullLayout = gd._fullLayout; - var textAnchor = getMainTitleTextAnchor(fullLayout); - var dy = getMainTitleDy(fullLayout); - var y = getMainTitleY(fullLayout, dy); - var x = getMainTitleX(fullLayout, textAnchor); - Titles2.draw(gd, "gtitle", { - propContainer: fullLayout, - propName: "title.text", - subtitlePropName: "title.subtitle.text", - placeholder: fullLayout._dfltTitle.plot, - subtitlePlaceholder: fullLayout._dfltTitle.subtitle, - attributes: { - x, - y, - "text-anchor": textAnchor, - dy - } - }); - if (title.text && title.automargin) { - var titleObj = d32.selectAll(".gtitle"); - var titleHeight = Drawing2.bBox(d32.selectAll(".g-gtitle").node()).height; - var pushMargin = needsMarginPush(gd, title, titleHeight); - if (pushMargin > 0) { - applyTitleAutoMargin(gd, y, pushMargin, titleHeight); - titleObj.attr({ - x, - y, - "text-anchor": textAnchor, - dy: getMainTitleDyAdj(title.yanchor) - }).call(svgTextUtils2.positionText, x, y); - var extraLines = (title.text.match(svgTextUtils2.BR_TAG_ALL) || []).length; - if (extraLines) { - var delta2 = alignmentConstants2.LINE_SPACING * extraLines + alignmentConstants2.MID_SHIFT; - if (title.y === 0) { - delta2 = -delta2; - } - titleObj.selectAll(".line").each(function() { - var newDy = +this.getAttribute("dy").slice(0, -2) - delta2 + "em"; - this.setAttribute("dy", newDy); - }); - } - var subtitleObj = d32.selectAll(".gtitle-subtitle"); - if (subtitleObj.node()) { - var titleBB = titleObj.node().getBBox(); - var titleBottom = titleBB.y + titleBB.height; - var subtitleY = titleBottom + Titles2.SUBTITLE_PADDING_EM * title.subtitle.font.size; - subtitleObj.attr({ - x, - y: subtitleY, - "text-anchor": textAnchor, - dy: getMainTitleDyAdj(title.yanchor) - }).call(svgTextUtils2.positionText, x, subtitleY); - } - } - } - }; - function isOutsideContainer(gd, title, position, y, titleHeight) { - var plotHeight = title.yref === "paper" ? gd._fullLayout._size.h : gd._fullLayout.height; - var yPosTop = Lib2.isTopAnchor(title) ? y : y - titleHeight; - var yPosRel = position === "b" ? plotHeight - yPosTop : yPosTop; - if (Lib2.isTopAnchor(title) && position === "t" || Lib2.isBottomAnchor(title) && position === "b") { - return false; - } else { - return yPosRel < titleHeight; - } - } - function containerPushVal(position, titleY, titleYanchor, height, titleDepth) { - var push = 0; - if (titleYanchor === "middle") { - push += titleDepth / 2; - } - if (position === "t") { - if (titleYanchor === "top") { - push += titleDepth; - } - push += height - titleY * height; - } else { - if (titleYanchor === "bottom") { - push += titleDepth; - } - push += titleY * height; - } - return push; - } - function needsMarginPush(gd, title, titleHeight) { - var titleY = title.y; - var titleYanchor = title.yanchor; - var position = titleY > 0.5 ? "t" : "b"; - var curMargin = gd._fullLayout.margin[position]; - var pushMargin = 0; - if (title.yref === "paper") { - pushMargin = titleHeight + title.pad.t + title.pad.b; - } else if (title.yref === "container") { - pushMargin = containerPushVal(position, titleY, titleYanchor, gd._fullLayout.height, titleHeight) + title.pad.t + title.pad.b; - } - if (pushMargin > curMargin) { - return pushMargin; - } - return 0; - } - function applyTitleAutoMargin(gd, y, pushMargin, titleHeight) { - var titleID = "title.automargin"; - var title = gd._fullLayout.title; - var position = title.y > 0.5 ? "t" : "b"; - var push = { - x: title.x, - y: title.y, - t: 0, - b: 0 - }; - var reservedPush = {}; - if (title.yref === "paper" && isOutsideContainer(gd, title, position, y, titleHeight)) { - push[position] = pushMargin; - } else if (title.yref === "container") { - reservedPush[position] = pushMargin; - gd._fullLayout._reservedMargin[titleID] = reservedPush; - } - Plots2.allowAutoMargin(gd, titleID); - Plots2.autoMargin(gd, titleID, push); - } - function getMainTitleX(fullLayout, textAnchor) { - var title = fullLayout.title; - var gs = fullLayout._size; - var hPadShift = 0; - if (textAnchor === SVG_TEXT_ANCHOR_START) { - hPadShift = title.pad.l; - } else if (textAnchor === SVG_TEXT_ANCHOR_END) { - hPadShift = -title.pad.r; - } - switch (title.xref) { - case "paper": - return gs.l + gs.w * title.x + hPadShift; - case "container": - default: - return fullLayout.width * title.x + hPadShift; - } - } - function getMainTitleY(fullLayout, dy) { - var title = fullLayout.title; - var gs = fullLayout._size; - var vPadShift = 0; - if (dy === "0em" || !dy) { - vPadShift = -title.pad.b; - } else if (dy === alignmentConstants2.CAP_SHIFT + "em") { - vPadShift = title.pad.t; - } - if (title.y === "auto") { - return gs.t / 2; - } else { - switch (title.yref) { - case "paper": - return gs.t + gs.h - gs.h * title.y + vPadShift; - case "container": - default: - return fullLayout.height - fullLayout.height * title.y + vPadShift; - } - } - } - function getMainTitleDyAdj(yanchor) { - if (yanchor === "top") { - return alignmentConstants2.CAP_SHIFT + 0.3 + "em"; - } else if (yanchor === "bottom") { - return "-0.3em"; - } else { - return alignmentConstants2.MID_SHIFT + "em"; - } - } - function getMainTitleTextAnchor(fullLayout) { - var title = fullLayout.title; - var textAnchor = SVG_TEXT_ANCHOR_MIDDLE; - if (Lib2.isRightAnchor(title)) { - textAnchor = SVG_TEXT_ANCHOR_END; - } else if (Lib2.isLeftAnchor(title)) { - textAnchor = SVG_TEXT_ANCHOR_START; - } - return textAnchor; - } - function getMainTitleDy(fullLayout) { - var title = fullLayout.title; - var dy = "0em"; - if (Lib2.isTopAnchor(title)) { - dy = alignmentConstants2.CAP_SHIFT + "em"; - } else if (Lib2.isMiddleAnchor(title)) { - dy = alignmentConstants2.MID_SHIFT + "em"; - } - return dy; - } - exports2.doTraceStyle = function(gd) { - var calcdata = gd.calcdata; - var editStyleCalls = []; - var i; - for (i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var cd0 = cd[0] || {}; - var trace = cd0.trace || {}; - var _module = trace._module || {}; - var arraysToCalcdata4 = _module.arraysToCalcdata; - if (arraysToCalcdata4) arraysToCalcdata4(cd, trace); - var editStyle = _module.editStyle; - if (editStyle) editStyleCalls.push({ fn: editStyle, cd0 }); - } - if (editStyleCalls.length) { - for (i = 0; i < editStyleCalls.length; i++) { - var edit = editStyleCalls[i]; - edit.fn(gd, edit.cd0); - } - clearGlCanvases3(gd); - exports2.redrawReglTraces(gd); - } - Plots2.style(gd); - Registry2.getComponentMethod("legend", "draw")(gd); - return Plots2.previousPromises(gd); - }; - exports2.doColorBars = function(gd) { - Registry2.getComponentMethod("colorbar", "draw")(gd); - return Plots2.previousPromises(gd); - }; - exports2.layoutReplot = function(gd) { - var layout = gd.layout; - gd.layout = void 0; - return Registry2.call("_doPlot", gd, "", layout); - }; - exports2.doLegend = function(gd) { - Registry2.getComponentMethod("legend", "draw")(gd); - return Plots2.previousPromises(gd); - }; - exports2.doTicksRelayout = function(gd) { - Axes2.draw(gd, "redraw"); - if (gd._fullLayout._hasOnlyLargeSploms) { - Registry2.subplotsRegistry.splom.updateGrid(gd); - clearGlCanvases3(gd); - exports2.redrawReglTraces(gd); - } - exports2.drawMainTitle(gd); - return Plots2.previousPromises(gd); - }; - exports2.doModeBar = function(gd) { - var fullLayout = gd._fullLayout; - ModeBar2.manage(gd); - for (var i = 0; i < fullLayout._basePlotModules.length; i++) { - var updateFx = fullLayout._basePlotModules[i].updateFx; - if (updateFx) updateFx(gd); - } - return Plots2.previousPromises(gd); - }; - exports2.doCamera = function(gd) { - var fullLayout = gd._fullLayout; - var sceneIds = fullLayout._subplots.gl3d; - for (var i = 0; i < sceneIds.length; i++) { - var sceneLayout = fullLayout[sceneIds[i]]; - var scene = sceneLayout._scene; - scene.setViewport(sceneLayout); - } - }; - exports2.drawData = function(gd) { - var fullLayout = gd._fullLayout; - clearGlCanvases3(gd); - var basePlotModules = fullLayout._basePlotModules; - for (var i = 0; i < basePlotModules.length; i++) { - basePlotModules[i].plot(gd); - } - exports2.redrawReglTraces(gd); - Plots2.style(gd); - Registry2.getComponentMethod("selections", "draw")(gd); - Registry2.getComponentMethod("shapes", "draw")(gd); - Registry2.getComponentMethod("annotations", "draw")(gd); - Registry2.getComponentMethod("images", "draw")(gd); - fullLayout._replotting = false; - return Plots2.previousPromises(gd); - }; - exports2.redrawReglTraces = function(gd) { - var fullLayout = gd._fullLayout; - if (fullLayout._has("regl")) { - var fullData = gd._fullData; - var cartesianIds = []; - var polarIds = []; - var i, sp; - if (fullLayout._hasOnlyLargeSploms) { - fullLayout._splomGrid.draw(); - } - for (i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if (trace.visible === true && trace._length !== 0) { - if (trace.type === "splom") { - fullLayout._splomScenes[trace.uid].draw(); - } else if (trace.type === "scattergl") { - Lib2.pushUnique(cartesianIds, trace.xaxis + trace.yaxis); - } else if (trace.type === "scatterpolargl") { - Lib2.pushUnique(polarIds, trace.subplot); - } - } - } - for (i = 0; i < cartesianIds.length; i++) { - sp = fullLayout._plots[cartesianIds[i]]; - if (sp._scene) sp._scene.draw(); - } - for (i = 0; i < polarIds.length; i++) { - sp = fullLayout[polarIds[i]]._subplot; - if (sp._scene) sp._scene.draw(); - } - } - }; - exports2.doAutoRangeAndConstraints = function(gd) { - var axList = Axes2.list(gd, "", true); - var ax; - var autoRangeDone = {}; - for (var i = 0; i < axList.length; i++) { - ax = axList[i]; - if (!autoRangeDone[ax._id]) { - autoRangeDone[ax._id] = 1; - cleanAxisConstraints(gd, ax); - doAutoRange2(gd, ax); - var matchGroup = ax._matchGroup; - if (matchGroup) { - for (var id2 in matchGroup) { - var ax2 = Axes2.getFromId(gd, id2); - doAutoRange2(gd, ax2, ax.range); - autoRangeDone[id2] = 1; - } - } - } - } - enforceAxisConstraints(gd); - }; - exports2.finalDraw = function(gd) { - Registry2.getComponentMethod("rangeslider", "draw")(gd); - Registry2.getComponentMethod("rangeselector", "draw")(gd); - }; - exports2.drawMarginPushers = function(gd) { - Registry2.getComponentMethod("legend", "draw")(gd); - Registry2.getComponentMethod("rangeselector", "draw")(gd); - Registry2.getComponentMethod("sliders", "draw")(gd); - Registry2.getComponentMethod("updatemenus", "draw")(gd); - Registry2.getComponentMethod("colorbar", "draw")(gd); - }; -})(subroutines); -var readPaths$1 = helpers$A.readPaths; -var displayOutlines$1 = display_outlines; -var clearOutlineControllers = handle_outline.clearOutlineControllers; -var Color$x = colorExports; -var Drawing$l = drawingExports; -var arrayEditor$4 = plot_template.arrayEditor; -var helpers$s = helpers$w; -var getPathString = helpers$s.getPathString; -var draw_1$2 = { - draw: draw$b, - drawOne: drawOne$1, - activateLastSelection: activateLastSelection$1 -}; -function draw$b(gd) { - var fullLayout = gd._fullLayout; - clearOutlineControllers(gd); - fullLayout._selectionLayer.selectAll("path").remove(); - for (var k in fullLayout._plots) { - var selectionLayer = fullLayout._plots[k].selectionLayer; - if (selectionLayer) selectionLayer.selectAll("path").remove(); - } - for (var i = 0; i < fullLayout.selections.length; i++) { - drawOne$1(gd, i); - } -} -function couldHaveActiveSelection(gd) { - return gd._context.editSelection; -} -function drawOne$1(gd, index2) { - gd._fullLayout._paperdiv.selectAll('.selectionlayer [data-index="' + index2 + '"]').remove(); - var o = helpers$s.makeSelectionsOptionsAndPlotinfo(gd, index2); - var options = o.options; - var plotinfo = o.plotinfo; - if (!options._input) return; - drawSelection(gd._fullLayout._selectionLayer); - function drawSelection(selectionLayer) { - var d = getPathString(gd, options); - var attrs2 = { - "data-index": index2, - "fill-rule": "evenodd", - d - }; - var opacity = options.opacity; - var fillColor = "rgba(0,0,0,0)"; - var lineColor = options.line.color || Color$x.contrast(gd._fullLayout.plot_bgcolor); - var lineWidth = options.line.width; - var lineDash = options.line.dash; - if (!lineWidth) { - lineWidth = 5; - lineDash = "solid"; - } - var isActiveSelection = couldHaveActiveSelection(gd) && gd._fullLayout._activeSelectionIndex === index2; - if (isActiveSelection) { - fillColor = gd._fullLayout.activeselection.fillcolor; - opacity = gd._fullLayout.activeselection.opacity; - } - var allPaths = []; - for (var sensory = 1; sensory >= 0; sensory--) { - var path = selectionLayer.append("path").attr(attrs2).style("opacity", sensory ? 0.1 : opacity).call(Color$x.stroke, lineColor).call(Color$x.fill, fillColor).call( - Drawing$l.dashLine, - sensory ? "solid" : lineDash, - sensory ? 4 + lineWidth : lineWidth - ); - setClipPath(path, gd, options); - if (isActiveSelection) { - var editHelpers = arrayEditor$4(gd.layout, "selections", options); - path.style({ - cursor: "move" - }); - var dragOptions = { - element: path.node(), - plotinfo, - gd, - editHelpers, - isActiveSelection: true - // i.e. to enable controllers - }; - var polygons = readPaths$1(d, gd); - displayOutlines$1(polygons, path, dragOptions); - } else { - path.style("pointer-events", sensory ? "all" : "none"); - } - allPaths[sensory] = path; - } - var forePath = allPaths[0]; - var backPath = allPaths[1]; - backPath.node().addEventListener("click", function() { - return activateSelection(gd, forePath); - }); - } -} -function setClipPath(selectionPath, gd, selectionOptions) { - var clipAxes = selectionOptions.xref + selectionOptions.yref; - Drawing$l.setClipUrl( - selectionPath, - "clip" + gd._fullLayout._uid + clipAxes, - gd - ); -} -function activateSelection(gd, path) { - if (!couldHaveActiveSelection(gd)) return; - var element = path.node(); - var id = +element.getAttribute("data-index"); - if (id >= 0) { - if (id === gd._fullLayout._activeSelectionIndex) { - deactivateSelection(gd); - return; - } - gd._fullLayout._activeSelectionIndex = id; - gd._fullLayout._deactivateSelection = deactivateSelection; - draw$b(gd); - } -} -function activateLastSelection$1(gd) { - if (!couldHaveActiveSelection(gd)) return; - var id = gd._fullLayout.selections.length - 1; - gd._fullLayout._activeSelectionIndex = id; - gd._fullLayout._deactivateSelection = deactivateSelection; - draw$b(gd); -} -function deactivateSelection(gd) { - if (!couldHaveActiveSelection(gd)) return; - var id = gd._fullLayout._activeSelectionIndex; - if (id >= 0) { - clearOutlineControllers(gd); - delete gd._fullLayout._activeSelectionIndex; - draw$b(gd); - } -} -function BuildLog$1() { - var my; - var nextSegmentId = 0; - var curVert = false; - function push(type, data) { - my.list.push({ - type, - data: data ? JSON.parse(JSON.stringify(data)) : void 0 - }); - return my; - } - my = { - list: [], - segmentId: function() { - return nextSegmentId++; - }, - checkIntersection: function(seg1, seg2) { - return push("check", { seg1, seg2 }); - }, - segmentChop: function(seg, end) { - push("div_seg", { seg, pt: end }); - return push("chop", { seg, pt: end }); - }, - statusRemove: function(seg) { - return push("pop_seg", { seg }); - }, - segmentUpdate: function(seg) { - return push("seg_update", { seg }); - }, - segmentNew: function(seg, primary) { - return push("new_seg", { seg, primary }); - }, - segmentRemove: function(seg) { - return push("rem_seg", { seg }); - }, - tempStatus: function(seg, above, below) { - return push("temp_status", { seg, above, below }); - }, - rewind: function(seg) { - return push("rewind", { seg }); - }, - status: function(seg, above, below) { - return push("status", { seg, above, below }); - }, - vert: function(x) { - if (x === curVert) - return my; - curVert = x; - return push("vert", { x }); - }, - log: function(data) { - if (typeof data !== "string") - data = JSON.stringify(data, false, " "); - return push("log", { txt: data }); - }, - reset: function() { - return push("reset"); - }, - selected: function(segs) { - return push("selected", { segs }); - }, - chainStart: function(seg) { - return push("chain_start", { seg }); - }, - chainRemoveHead: function(index2, pt) { - return push("chain_rem_head", { index: index2, pt }); - }, - chainRemoveTail: function(index2, pt) { - return push("chain_rem_tail", { index: index2, pt }); - }, - chainNew: function(pt1, pt2) { - return push("chain_new", { pt1, pt2 }); - }, - chainMatch: function(index2) { - return push("chain_match", { index: index2 }); - }, - chainClose: function(index2) { - return push("chain_close", { index: index2 }); - }, - chainAddHead: function(index2, pt) { - return push("chain_add_head", { index: index2, pt }); - }, - chainAddTail: function(index2, pt) { - return push("chain_add_tail", { index: index2, pt }); - }, - chainConnect: function(index1, index2) { - return push("chain_con", { index1, index2 }); - }, - chainReverse: function(index2) { - return push("chain_rev", { index: index2 }); - }, - chainJoin: function(index1, index2) { - return push("chain_join", { index1, index2 }); - }, - done: function() { - return push("done"); - } - }; - return my; -} -var buildLog$1 = BuildLog$1; -function Epsilon$1(eps) { - if (typeof eps !== "number") - eps = 1e-10; - var my = { - epsilon: function(v) { - if (typeof v === "number") - eps = v; - return eps; - }, - pointAboveOrOnLine: function(pt, left, right) { - var Ax = left[0]; - var Ay = left[1]; - var Bx = right[0]; - var By = right[1]; - var Cx = pt[0]; - var Cy = pt[1]; - return (Bx - Ax) * (Cy - Ay) - (By - Ay) * (Cx - Ax) >= -eps; - }, - pointBetween: function(p, left, right) { - var d_py_ly = p[1] - left[1]; - var d_rx_lx = right[0] - left[0]; - var d_px_lx = p[0] - left[0]; - var d_ry_ly = right[1] - left[1]; - var dot2 = d_px_lx * d_rx_lx + d_py_ly * d_ry_ly; - if (dot2 < eps) - return false; - var sqlen = d_rx_lx * d_rx_lx + d_ry_ly * d_ry_ly; - if (dot2 - sqlen > -eps) - return false; - return true; - }, - pointsSameX: function(p1, p2) { - return Math.abs(p1[0] - p2[0]) < eps; - }, - pointsSameY: function(p1, p2) { - return Math.abs(p1[1] - p2[1]) < eps; - }, - pointsSame: function(p1, p2) { - return my.pointsSameX(p1, p2) && my.pointsSameY(p1, p2); - }, - pointsCompare: function(p1, p2) { - if (my.pointsSameX(p1, p2)) - return my.pointsSameY(p1, p2) ? 0 : p1[1] < p2[1] ? -1 : 1; - return p1[0] < p2[0] ? -1 : 1; - }, - pointsCollinear: function(pt1, pt2, pt3) { - var dx1 = pt1[0] - pt2[0]; - var dy1 = pt1[1] - pt2[1]; - var dx2 = pt2[0] - pt3[0]; - var dy2 = pt2[1] - pt3[1]; - return Math.abs(dx1 * dy2 - dx2 * dy1) < eps; - }, - linesIntersect: function(a0, a1, b0, b1) { - var adx = a1[0] - a0[0]; - var ady = a1[1] - a0[1]; - var bdx = b1[0] - b0[0]; - var bdy = b1[1] - b0[1]; - var axb = adx * bdy - ady * bdx; - if (Math.abs(axb) < eps) - return false; - var dx = a0[0] - b0[0]; - var dy = a0[1] - b0[1]; - var A2 = (bdx * dy - bdy * dx) / axb; - var B2 = (adx * dy - ady * dx) / axb; - var ret = { - alongA: 0, - alongB: 0, - pt: [ - a0[0] + A2 * adx, - a0[1] + A2 * ady - ] - }; - if (A2 <= -eps) - ret.alongA = -2; - else if (A2 < eps) - ret.alongA = -1; - else if (A2 - 1 <= -eps) - ret.alongA = 0; - else if (A2 - 1 < eps) - ret.alongA = 1; - else - ret.alongA = 2; - if (B2 <= -eps) - ret.alongB = -2; - else if (B2 < eps) - ret.alongB = -1; - else if (B2 - 1 <= -eps) - ret.alongB = 0; - else if (B2 - 1 < eps) - ret.alongB = 1; - else - ret.alongB = 2; - return ret; - }, - pointInsideRegion: function(pt, region) { - var x = pt[0]; - var y = pt[1]; - var last_x = region[region.length - 1][0]; - var last_y = region[region.length - 1][1]; - var inside = false; - for (var i = 0; i < region.length; i++) { - var curr_x = region[i][0]; - var curr_y = region[i][1]; - if (curr_y - y > eps != last_y - y > eps && (last_x - curr_x) * (y - curr_y) / (last_y - curr_y) + curr_x - x > eps) - inside = !inside; - last_x = curr_x; - last_y = curr_y; - } - return inside; - } - }; - return my; -} -var epsilon$1 = Epsilon$1; -var LinkedList$1 = { - create: function() { - var my = { - root: { root: true, next: null }, - exists: function(node) { - if (node === null || node === my.root) - return false; - return true; - }, - isEmpty: function() { - return my.root.next === null; - }, - getHead: function() { - return my.root.next; - }, - insertBefore: function(node, check) { - var last = my.root; - var here = my.root.next; - while (here !== null) { - if (check(here)) { - node.prev = here.prev; - node.next = here; - here.prev.next = node; - here.prev = node; - return; - } - last = here; - here = here.next; - } - last.next = node; - node.prev = last; - node.next = null; - }, - findTransition: function(check) { - var prev = my.root; - var here = my.root.next; - while (here !== null) { - if (check(here)) - break; - prev = here; - here = here.next; - } - return { - before: prev === my.root ? null : prev, - after: here, - insert: function(node) { - node.prev = prev; - node.next = here; - prev.next = node; - if (here !== null) - here.prev = node; - return node; - } - }; - } - }; - return my; - }, - node: function(data) { - data.prev = null; - data.next = null; - data.remove = function() { - data.prev.next = data.next; - if (data.next) - data.next.prev = data.prev; - data.prev = null; - data.next = null; - }; - return data; - } -}; -var linkedList$1 = LinkedList$1; -var LinkedList = linkedList$1; -function Intersecter$1(selfIntersection, eps, buildLog2) { - function segmentNew(start, end) { - return { - id: buildLog2 ? buildLog2.segmentId() : -1, - start, - end, - myFill: { - above: null, - // is there fill above us? - below: null - // is there fill below us? - }, - otherFill: null - }; - } - function segmentCopy(start, end, seg) { - return { - id: buildLog2 ? buildLog2.segmentId() : -1, - start, - end, - myFill: { - above: seg.myFill.above, - below: seg.myFill.below - }, - otherFill: null - }; - } - var event_root = LinkedList.create(); - function eventCompare(p1_isStart, p1_1, p1_2, p2_isStart, p2_1, p2_2) { - var comp = eps.pointsCompare(p1_1, p2_1); - if (comp !== 0) - return comp; - if (eps.pointsSame(p1_2, p2_2)) - return 0; - if (p1_isStart !== p2_isStart) - return p1_isStart ? 1 : -1; - return eps.pointAboveOrOnLine( - p1_2, - p2_isStart ? p2_1 : p2_2, - // order matters - p2_isStart ? p2_2 : p2_1 - ) ? 1 : -1; - } - function eventAdd(ev, other_pt) { - event_root.insertBefore(ev, function(here) { - var comp = eventCompare( - ev.isStart, - ev.pt, - other_pt, - here.isStart, - here.pt, - here.other.pt - ); - return comp < 0; - }); - } - function eventAddSegmentStart(seg, primary) { - var ev_start = LinkedList.node({ - isStart: true, - pt: seg.start, - seg, - primary, - other: null, - status: null - }); - eventAdd(ev_start, seg.end); - return ev_start; - } - function eventAddSegmentEnd(ev_start, seg, primary) { - var ev_end = LinkedList.node({ - isStart: false, - pt: seg.end, - seg, - primary, - other: ev_start, - status: null - }); - ev_start.other = ev_end; - eventAdd(ev_end, ev_start.pt); - } - function eventAddSegment(seg, primary) { - var ev_start = eventAddSegmentStart(seg, primary); - eventAddSegmentEnd(ev_start, seg, primary); - return ev_start; - } - function eventUpdateEnd(ev, end) { - if (buildLog2) - buildLog2.segmentChop(ev.seg, end); - ev.other.remove(); - ev.seg.end = end; - ev.other.pt = end; - eventAdd(ev.other, ev.pt); - } - function eventDivide(ev, pt) { - var ns = segmentCopy(pt, ev.seg.end, ev.seg); - eventUpdateEnd(ev, pt); - return eventAddSegment(ns, ev.primary); - } - function calculate(primaryPolyInverted, secondaryPolyInverted) { - var status_root = LinkedList.create(); - function statusCompare(ev1, ev2) { - var a1 = ev1.seg.start; - var a2 = ev1.seg.end; - var b1 = ev2.seg.start; - var b2 = ev2.seg.end; - if (eps.pointsCollinear(a1, b1, b2)) { - if (eps.pointsCollinear(a2, b1, b2)) - return 1; - return eps.pointAboveOrOnLine(a2, b1, b2) ? 1 : -1; - } - return eps.pointAboveOrOnLine(a1, b1, b2) ? 1 : -1; - } - function statusFindSurrounding(ev2) { - return status_root.findTransition(function(here) { - var comp = statusCompare(ev2, here.ev); - return comp > 0; - }); - } - function checkIntersection(ev1, ev2) { - var seg1 = ev1.seg; - var seg2 = ev2.seg; - var a1 = seg1.start; - var a2 = seg1.end; - var b1 = seg2.start; - var b2 = seg2.end; - if (buildLog2) - buildLog2.checkIntersection(seg1, seg2); - var i = eps.linesIntersect(a1, a2, b1, b2); - if (i === false) { - if (!eps.pointsCollinear(a1, a2, b1)) - return false; - if (eps.pointsSame(a1, b2) || eps.pointsSame(a2, b1)) - return false; - var a1_equ_b1 = eps.pointsSame(a1, b1); - var a2_equ_b2 = eps.pointsSame(a2, b2); - if (a1_equ_b1 && a2_equ_b2) - return ev2; - var a1_between = !a1_equ_b1 && eps.pointBetween(a1, b1, b2); - var a2_between = !a2_equ_b2 && eps.pointBetween(a2, b1, b2); - if (a1_equ_b1) { - if (a2_between) { - eventDivide(ev2, a2); - } else { - eventDivide(ev1, b2); - } - return ev2; - } else if (a1_between) { - if (!a2_equ_b2) { - if (a2_between) { - eventDivide(ev2, a2); - } else { - eventDivide(ev1, b2); - } - } - eventDivide(ev2, a1); - } - } else { - if (i.alongA === 0) { - if (i.alongB === -1) - eventDivide(ev1, b1); - else if (i.alongB === 0) - eventDivide(ev1, i.pt); - else if (i.alongB === 1) - eventDivide(ev1, b2); - } - if (i.alongB === 0) { - if (i.alongA === -1) - eventDivide(ev2, a1); - else if (i.alongA === 0) - eventDivide(ev2, i.pt); - else if (i.alongA === 1) - eventDivide(ev2, a2); - } - } - return false; - } - var segments = []; - while (!event_root.isEmpty()) { - var ev = event_root.getHead(); - if (buildLog2) - buildLog2.vert(ev.pt[0]); - if (ev.isStart) { - let checkBothIntersections = function() { - if (above) { - var eve2 = checkIntersection(ev, above); - if (eve2) - return eve2; - } - if (below) - return checkIntersection(ev, below); - return false; - }; - if (buildLog2) - buildLog2.segmentNew(ev.seg, ev.primary); - var surrounding = statusFindSurrounding(ev); - var above = surrounding.before ? surrounding.before.ev : null; - var below = surrounding.after ? surrounding.after.ev : null; - if (buildLog2) { - buildLog2.tempStatus( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } - var eve = checkBothIntersections(); - if (eve) { - if (selfIntersection) { - var toggle; - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - if (toggle) - eve.seg.myFill.above = !eve.seg.myFill.above; - } else { - eve.seg.otherFill = ev.seg.myFill; - } - if (buildLog2) - buildLog2.segmentUpdate(eve.seg); - ev.other.remove(); - ev.remove(); - } - if (event_root.getHead() !== ev) { - if (buildLog2) - buildLog2.rewind(ev.seg); - continue; - } - if (selfIntersection) { - var toggle; - if (ev.seg.myFill.below === null) - toggle = true; - else - toggle = ev.seg.myFill.above !== ev.seg.myFill.below; - if (!below) { - ev.seg.myFill.below = primaryPolyInverted; - } else { - ev.seg.myFill.below = below.seg.myFill.above; - } - if (toggle) - ev.seg.myFill.above = !ev.seg.myFill.below; - else - ev.seg.myFill.above = ev.seg.myFill.below; - } else { - if (ev.seg.otherFill === null) { - var inside; - if (!below) { - inside = ev.primary ? secondaryPolyInverted : primaryPolyInverted; - } else { - if (ev.primary === below.primary) - inside = below.seg.otherFill.above; - else - inside = below.seg.myFill.above; - } - ev.seg.otherFill = { - above: inside, - below: inside - }; - } - } - if (buildLog2) { - buildLog2.status( - ev.seg, - above ? above.seg : false, - below ? below.seg : false - ); - } - ev.other.status = surrounding.insert(LinkedList.node({ ev })); - } else { - var st = ev.status; - if (st === null) { - throw new Error("PolyBool: Zero-length segment detected; your epsilon is probably too small or too large"); - } - if (status_root.exists(st.prev) && status_root.exists(st.next)) - checkIntersection(st.prev.ev, st.next.ev); - if (buildLog2) - buildLog2.statusRemove(st.ev.seg); - st.remove(); - if (!ev.primary) { - var s = ev.seg.myFill; - ev.seg.myFill = ev.seg.otherFill; - ev.seg.otherFill = s; - } - segments.push(ev.seg); - } - event_root.getHead().remove(); - } - if (buildLog2) - buildLog2.done(); - return segments; - } - if (!selfIntersection) { - return { - calculate: function(segments1, inverted1, segments2, inverted2) { - segments1.forEach(function(seg) { - eventAddSegment(segmentCopy(seg.start, seg.end, seg), true); - }); - segments2.forEach(function(seg) { - eventAddSegment(segmentCopy(seg.start, seg.end, seg), false); - }); - return calculate(inverted1, inverted2); - } - }; - } - return { - addRegion: function(region) { - var pt1; - var pt2 = region[region.length - 1]; - for (var i = 0; i < region.length; i++) { - pt1 = pt2; - pt2 = region[i]; - var forward = eps.pointsCompare(pt1, pt2); - if (forward === 0) - continue; - eventAddSegment( - segmentNew( - forward < 0 ? pt1 : pt2, - forward < 0 ? pt2 : pt1 - ), - true - ); - } - }, - calculate: function(inverted) { - return calculate(inverted, false); - } - }; -} -var intersecter = Intersecter$1; -function SegmentChainer$1(segments, eps, buildLog2) { - var chains = []; - var regions = []; - segments.forEach(function(seg) { - var pt1 = seg.start; - var pt2 = seg.end; - if (eps.pointsSame(pt1, pt2)) { - console.warn("PolyBool: Warning: Zero-length segment detected; your epsilon is probably too small or too large"); - return; - } - if (buildLog2) - buildLog2.chainStart(seg); - var first_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var second_match = { - index: 0, - matches_head: false, - matches_pt1: false - }; - var next_match = first_match; - function setMatch(index3, matches_head, matches_pt1) { - next_match.index = index3; - next_match.matches_head = matches_head; - next_match.matches_pt1 = matches_pt1; - if (next_match === first_match) { - next_match = second_match; - return false; - } - next_match = null; - return true; - } - for (var i = 0; i < chains.length; i++) { - var chain = chains[i]; - var head = chain[0]; - chain[1]; - var tail = chain[chain.length - 1]; - chain[chain.length - 2]; - if (eps.pointsSame(head, pt1)) { - if (setMatch(i, true, true)) - break; - } else if (eps.pointsSame(head, pt2)) { - if (setMatch(i, true, false)) - break; - } else if (eps.pointsSame(tail, pt1)) { - if (setMatch(i, false, true)) - break; - } else if (eps.pointsSame(tail, pt2)) { - if (setMatch(i, false, false)) - break; - } - } - if (next_match === first_match) { - chains.push([pt1, pt2]); - if (buildLog2) - buildLog2.chainNew(pt1, pt2); - return; - } - if (next_match === second_match) { - if (buildLog2) - buildLog2.chainMatch(first_match.index); - var index2 = first_match.index; - var pt = first_match.matches_pt1 ? pt2 : pt1; - var addToHead = first_match.matches_head; - var chain = chains[index2]; - var grow = addToHead ? chain[0] : chain[chain.length - 1]; - var grow2 = addToHead ? chain[1] : chain[chain.length - 2]; - var oppo = addToHead ? chain[chain.length - 1] : chain[0]; - var oppo2 = addToHead ? chain[chain.length - 2] : chain[1]; - if (eps.pointsCollinear(grow2, grow, pt)) { - if (addToHead) { - if (buildLog2) - buildLog2.chainRemoveHead(first_match.index, pt); - chain.shift(); - } else { - if (buildLog2) - buildLog2.chainRemoveTail(first_match.index, pt); - chain.pop(); - } - grow = grow2; - } - if (eps.pointsSame(oppo, pt)) { - chains.splice(index2, 1); - if (eps.pointsCollinear(oppo2, oppo, grow)) { - if (addToHead) { - if (buildLog2) - buildLog2.chainRemoveTail(first_match.index, grow); - chain.pop(); - } else { - if (buildLog2) - buildLog2.chainRemoveHead(first_match.index, grow); - chain.shift(); - } - } - if (buildLog2) - buildLog2.chainClose(first_match.index); - regions.push(chain); - return; - } - if (addToHead) { - if (buildLog2) - buildLog2.chainAddHead(first_match.index, pt); - chain.unshift(pt); - } else { - if (buildLog2) - buildLog2.chainAddTail(first_match.index, pt); - chain.push(pt); - } - return; - } - function reverseChain(index3) { - if (buildLog2) - buildLog2.chainReverse(index3); - chains[index3].reverse(); - } - function appendChain(index1, index22) { - var chain1 = chains[index1]; - var chain2 = chains[index22]; - var tail2 = chain1[chain1.length - 1]; - var tail22 = chain1[chain1.length - 2]; - var head2 = chain2[0]; - var head22 = chain2[1]; - if (eps.pointsCollinear(tail22, tail2, head2)) { - if (buildLog2) - buildLog2.chainRemoveTail(index1, tail2); - chain1.pop(); - tail2 = tail22; - } - if (eps.pointsCollinear(tail2, head2, head22)) { - if (buildLog2) - buildLog2.chainRemoveHead(index22, head2); - chain2.shift(); - } - if (buildLog2) - buildLog2.chainJoin(index1, index22); - chains[index1] = chain1.concat(chain2); - chains.splice(index22, 1); - } - var F = first_match.index; - var S = second_match.index; - if (buildLog2) - buildLog2.chainConnect(F, S); - var reverseF = chains[F].length < chains[S].length; - if (first_match.matches_head) { - if (second_match.matches_head) { - if (reverseF) { - reverseChain(F); - appendChain(F, S); - } else { - reverseChain(S); - appendChain(S, F); - } - } else { - appendChain(S, F); - } - } else { - if (second_match.matches_head) { - appendChain(F, S); - } else { - if (reverseF) { - reverseChain(F); - appendChain(S, F); - } else { - reverseChain(S); - appendChain(F, S); - } - } - } - }); - return regions; -} -var segmentChainer = SegmentChainer$1; -function select$6(segments, selection, buildLog2) { - var result = []; - segments.forEach(function(seg) { - var index2 = (seg.myFill.above ? 8 : 0) + (seg.myFill.below ? 4 : 0) + (seg.otherFill && seg.otherFill.above ? 2 : 0) + (seg.otherFill && seg.otherFill.below ? 1 : 0); - if (selection[index2] !== 0) { - result.push({ - id: buildLog2 ? buildLog2.segmentId() : -1, - start: seg.start, - end: seg.end, - myFill: { - above: selection[index2] === 1, - // 1 if filled above - below: selection[index2] === 2 - // 2 if filled below - }, - otherFill: null - }); - } - }); - if (buildLog2) - buildLog2.selected(result); - return result; -} -var SegmentSelector$1 = { - union: function(segments, buildLog2) { - return select$6(segments, [ - 0, - 2, - 1, - 0, - 2, - 2, - 0, - 0, - 1, - 0, - 1, - 0, - 0, - 0, - 0, - 0 - ], buildLog2); - }, - intersect: function(segments, buildLog2) { - return select$6(segments, [ - 0, - 0, - 0, - 0, - 0, - 2, - 0, - 2, - 0, - 0, - 1, - 1, - 0, - 2, - 1, - 0 - ], buildLog2); - }, - difference: function(segments, buildLog2) { - return select$6(segments, [ - 0, - 0, - 0, - 0, - 2, - 0, - 2, - 0, - 1, - 1, - 0, - 0, - 0, - 1, - 2, - 0 - ], buildLog2); - }, - differenceRev: function(segments, buildLog2) { - return select$6(segments, [ - 0, - 2, - 1, - 0, - 0, - 0, - 1, - 1, - 0, - 2, - 0, - 2, - 0, - 0, - 0, - 0 - ], buildLog2); - }, - xor: function(segments, buildLog2) { - return select$6(segments, [ - 0, - 2, - 1, - 0, - 2, - 0, - 0, - 1, - 1, - 0, - 0, - 2, - 0, - 1, - 2, - 0 - ], buildLog2); - } -}; -var segmentSelector = SegmentSelector$1; -var GeoJSON$1 = { - // convert a GeoJSON object to a PolyBool polygon - toPolygon: function(PolyBool2, geojson2) { - function GeoPoly(coords) { - if (coords.length <= 0) - return PolyBool2.segments({ inverted: false, regions: [] }); - function LineString(ls) { - var reg2 = ls.slice(0, ls.length - 1); - return PolyBool2.segments({ inverted: false, regions: [reg2] }); - } - var out2 = LineString(coords[0]); - for (var i2 = 1; i2 < coords.length; i2++) - out2 = PolyBool2.selectDifference(PolyBool2.combine(out2, LineString(coords[i2]))); - return out2; - } - if (geojson2.type === "Polygon") { - return PolyBool2.polygon(GeoPoly(geojson2.coordinates)); - } else if (geojson2.type === "MultiPolygon") { - var out = PolyBool2.segments({ inverted: false, regions: [] }); - for (var i = 0; i < geojson2.coordinates.length; i++) - out = PolyBool2.selectUnion(PolyBool2.combine(out, GeoPoly(geojson2.coordinates[i]))); - return PolyBool2.polygon(out); - } - throw new Error("PolyBool: Cannot convert GeoJSON object to PolyBool polygon"); - }, - // convert a PolyBool polygon to a GeoJSON object - fromPolygon: function(PolyBool2, eps, poly) { - poly = PolyBool2.polygon(PolyBool2.segments(poly)); - function regionInsideRegion(r1, r2) { - return eps.pointInsideRegion([ - (r1[0][0] + r1[1][0]) * 0.5, - (r1[0][1] + r1[1][1]) * 0.5 - ], r2); - } - function newNode(region2) { - return { - region: region2, - children: [] - }; - } - var roots = newNode(null); - function addChild(root, region2) { - for (var i2 = 0; i2 < root.children.length; i2++) { - var child = root.children[i2]; - if (regionInsideRegion(region2, child.region)) { - addChild(child, region2); - return; - } - } - var node = newNode(region2); - for (var i2 = 0; i2 < root.children.length; i2++) { - var child = root.children[i2]; - if (regionInsideRegion(child.region, region2)) { - node.children.push(child); - root.children.splice(i2, 1); - i2--; - } - } - root.children.push(node); - } - for (var i = 0; i < poly.regions.length; i++) { - var region = poly.regions[i]; - if (region.length < 3) - continue; - addChild(roots, region); - } - function forceWinding(region2, clockwise) { - var winding = 0; - var last_x = region2[region2.length - 1][0]; - var last_y = region2[region2.length - 1][1]; - var copy2 = []; - for (var i2 = 0; i2 < region2.length; i2++) { - var curr_x = region2[i2][0]; - var curr_y = region2[i2][1]; - copy2.push([curr_x, curr_y]); - winding += curr_y * last_x - curr_x * last_y; - last_x = curr_x; - last_y = curr_y; - } - var isclockwise = winding < 0; - if (isclockwise !== clockwise) - copy2.reverse(); - copy2.push([copy2[0][0], copy2[0][1]]); - return copy2; - } - var geopolys = []; - function addExterior(node) { - var poly2 = [forceWinding(node.region, false)]; - geopolys.push(poly2); - for (var i2 = 0; i2 < node.children.length; i2++) - poly2.push(getInterior(node.children[i2])); - } - function getInterior(node) { - for (var i2 = 0; i2 < node.children.length; i2++) - addExterior(node.children[i2]); - return forceWinding(node.region, true); - } - for (var i = 0; i < roots.children.length; i++) - addExterior(roots.children[i]); - if (geopolys.length <= 0) - return { type: "Polygon", coordinates: [] }; - if (geopolys.length == 1) - return { type: "Polygon", coordinates: geopolys[0] }; - return { - // otherwise, use a GeoJSON MultiPolygon - type: "MultiPolygon", - coordinates: geopolys - }; - } -}; -var geojson = GeoJSON$1; -/* - * @copyright 2016 Sean Connelly (@voidqk), http://syntheti.cc - * @license MIT - * @preserve Project Home: https://github.com/voidqk/polybooljs - */ -var BuildLog = buildLog$1; -var Epsilon = epsilon$1; -var Intersecter = intersecter; -var SegmentChainer = segmentChainer; -var SegmentSelector = segmentSelector; -var GeoJSON = geojson; -var buildLog = false; -var epsilon = Epsilon(); -var PolyBool; -PolyBool = { - // getter/setter for buildLog - buildLog: function(bl) { - if (bl === true) - buildLog = BuildLog(); - else if (bl === false) - buildLog = false; - return buildLog === false ? false : buildLog.list; - }, - // getter/setter for epsilon - epsilon: function(v) { - return epsilon.epsilon(v); - }, - // core API - segments: function(poly) { - var i = Intersecter(true, epsilon, buildLog); - poly.regions.forEach(i.addRegion); - return { - segments: i.calculate(poly.inverted), - inverted: poly.inverted - }; - }, - combine: function(segments1, segments2) { - var i3 = Intersecter(false, epsilon, buildLog); - return { - combined: i3.calculate( - segments1.segments, - segments1.inverted, - segments2.segments, - segments2.inverted - ), - inverted1: segments1.inverted, - inverted2: segments2.inverted - }; - }, - selectUnion: function(combined) { - return { - segments: SegmentSelector.union(combined.combined, buildLog), - inverted: combined.inverted1 || combined.inverted2 - }; - }, - selectIntersect: function(combined) { - return { - segments: SegmentSelector.intersect(combined.combined, buildLog), - inverted: combined.inverted1 && combined.inverted2 - }; - }, - selectDifference: function(combined) { - return { - segments: SegmentSelector.difference(combined.combined, buildLog), - inverted: combined.inverted1 && !combined.inverted2 - }; - }, - selectDifferenceRev: function(combined) { - return { - segments: SegmentSelector.differenceRev(combined.combined, buildLog), - inverted: !combined.inverted1 && combined.inverted2 - }; - }, - selectXor: function(combined) { - return { - segments: SegmentSelector.xor(combined.combined, buildLog), - inverted: combined.inverted1 !== combined.inverted2 - }; - }, - polygon: function(segments) { - return { - regions: SegmentChainer(segments.segments, epsilon, buildLog), - inverted: segments.inverted - }; - }, - // GeoJSON converters - polygonFromGeoJSON: function(geojson2) { - return GeoJSON.toPolygon(PolyBool, geojson2); - }, - polygonToGeoJSON: function(poly) { - return GeoJSON.fromPolygon(PolyBool, epsilon, poly); - }, - // helper functions for common operations - union: function(poly1, poly2) { - return operate(poly1, poly2, PolyBool.selectUnion); - }, - intersect: function(poly1, poly2) { - return operate(poly1, poly2, PolyBool.selectIntersect); - }, - difference: function(poly1, poly2) { - return operate(poly1, poly2, PolyBool.selectDifference); - }, - differenceRev: function(poly1, poly2) { - return operate(poly1, poly2, PolyBool.selectDifferenceRev); - }, - xor: function(poly1, poly2) { - return operate(poly1, poly2, PolyBool.selectXor); - } -}; -function operate(poly1, poly2, selector) { - var seg1 = PolyBool.segments(poly1); - var seg2 = PolyBool.segments(poly2); - var comb = PolyBool.combine(seg1, seg2); - var seg3 = selector(comb); - return PolyBool.polygon(seg3); -} -if (typeof window === "object") - window.PolyBool = PolyBool; -var polybooljs = PolyBool; -var nested = function pointInPolygonNested(point, vs, start, end) { - var x = point[0], y = point[1]; - var inside = false; - if (start === void 0) start = 0; - if (end === void 0) end = vs.length; - var len = end - start; - for (var i = 0, j = len - 1; i < len; j = i++) { - var xi = vs[i + start][0], yi = vs[i + start][1]; - var xj = vs[j + start][0], yj = vs[j + start][1]; - var intersect = yi > y !== yj > y && x < (xj - xi) * (y - yi) / (yj - yi) + xi; - if (intersect) inside = !inside; - } - return inside; -}; -var polygon$1 = { exports: {} }; -var dot = matrix$1.dot; -var BADNUM$6 = numerical.BADNUM; -var polygon = polygon$1.exports = {}; -polygon.tester = function tester(ptsIn) { - var pts = ptsIn.slice(); - var xmin = pts[0][0]; - var xmax = xmin; - var ymin = pts[0][1]; - var ymax = ymin; - var i; - if (pts[pts.length - 1][0] !== pts[0][0] || pts[pts.length - 1][1] !== pts[0][1]) { - pts.push(pts[0]); - } - for (i = 1; i < pts.length; i++) { - xmin = Math.min(xmin, pts[i][0]); - xmax = Math.max(xmax, pts[i][0]); - ymin = Math.min(ymin, pts[i][1]); - ymax = Math.max(ymax, pts[i][1]); - } - var isRect = false; - var rectFirstEdgeTest; - if (pts.length === 5) { - if (pts[0][0] === pts[1][0]) { - if (pts[2][0] === pts[3][0] && pts[0][1] === pts[3][1] && pts[1][1] === pts[2][1]) { - isRect = true; - rectFirstEdgeTest = function(pt) { - return pt[0] === pts[0][0]; - }; - } - } else if (pts[0][1] === pts[1][1]) { - if (pts[2][1] === pts[3][1] && pts[0][0] === pts[3][0] && pts[1][0] === pts[2][0]) { - isRect = true; - rectFirstEdgeTest = function(pt) { - return pt[1] === pts[0][1]; - }; - } - } - } - function rectContains(pt, omitFirstEdge) { - var x = pt[0]; - var y = pt[1]; - if (x === BADNUM$6 || x < xmin || x > xmax || y === BADNUM$6 || y < ymin || y > ymax) { - return false; - } - if (omitFirstEdge && rectFirstEdgeTest(pt)) return false; - return true; - } - function contains(pt, omitFirstEdge) { - var x = pt[0]; - var y = pt[1]; - if (x === BADNUM$6 || x < xmin || x > xmax || y === BADNUM$6 || y < ymin || y > ymax) { - return false; - } - var imax = pts.length; - var x1 = pts[0][0]; - var y1 = pts[0][1]; - var crossings = 0; - var i2; - var x0; - var y0; - var xmini; - var ycross; - for (i2 = 1; i2 < imax; i2++) { - x0 = x1; - y0 = y1; - x1 = pts[i2][0]; - y1 = pts[i2][1]; - xmini = Math.min(x0, x1); - if (x < xmini || x > Math.max(x0, x1) || y > Math.max(y0, y1)) { - continue; - } else if (y < Math.min(y0, y1)) { - if (x !== xmini) crossings++; - } else { - if (x1 === x0) ycross = y; - else ycross = y0 + (x - x0) * (y1 - y0) / (x1 - x0); - if (y === ycross) { - if (i2 === 1 && omitFirstEdge) return false; - return true; - } - if (y <= ycross && x !== xmini) crossings++; - } - } - return crossings % 2 === 1; - } - var degenerate = true; - var lastPt = pts[0]; - for (i = 1; i < pts.length; i++) { - if (lastPt[0] !== pts[i][0] || lastPt[1] !== pts[i][1]) { - degenerate = false; - break; - } - } - return { - xmin, - xmax, - ymin, - ymax, - pts, - contains: isRect ? rectContains : contains, - isRect, - degenerate - }; -}; -polygon.isSegmentBent = function isSegmentBent(pts, start, end, tolerance) { - var startPt = pts[start]; - var segment2 = [pts[end][0] - startPt[0], pts[end][1] - startPt[1]]; - var segmentSquared = dot(segment2, segment2); - var segmentLen = Math.sqrt(segmentSquared); - var unitPerp = [-segment2[1] / segmentLen, segment2[0] / segmentLen]; - var i; - var part; - var partParallel; - for (i = start + 1; i < end; i++) { - part = [pts[i][0] - startPt[0], pts[i][1] - startPt[1]]; - partParallel = dot(part, segment2); - if (partParallel < 0 || partParallel > segmentSquared || Math.abs(dot(part, unitPerp)) > tolerance) return true; - } - return false; -}; -polygon.filter = function filter(pts, tolerance) { - var ptsFiltered = [pts[0]]; - var doneRawIndex = 0; - var doneFilteredIndex = 0; - function addPt(pt) { - pts.push(pt); - var prevFilterLen = ptsFiltered.length; - var iLast = doneRawIndex; - ptsFiltered.splice(doneFilteredIndex + 1); - for (var i = iLast + 1; i < pts.length; i++) { - if (i === pts.length - 1 || polygon.isSegmentBent(pts, iLast, i + 1, tolerance)) { - ptsFiltered.push(pts[i]); - if (ptsFiltered.length < prevFilterLen - 2) { - doneRawIndex = i; - doneFilteredIndex = ptsFiltered.length - 1; - } - iLast = i; - } - } - } - if (pts.length > 1) { - var lastPt = pts.pop(); - addPt(lastPt); - } - return { - addPt, - raw: pts, - filtered: ptsFiltered - }; -}; -var polygonExports = polygon$1.exports; -var constants$D = { - // max pixels off straight before a lasso select line counts as bent - BENDPX: 1.5, - // smallest dimension allowed for a select box - MINSELECT: 12, - // throttling limit (ms) for selectPoints calls - SELECTDELAY: 100, - // cache ID suffix for throttle - SELECTID: "-select" -}; -var polybool = polybooljs; -var pointInPolygon = nested; -var Registry$v = registry; -var dashStyle = drawingExports.dashStyle; -var Color$w = colorExports; -var Fx$6 = fx$1; -var makeEventData$1 = helpers$J.makeEventData; -var dragHelpers = helpers$B; -var freeMode = dragHelpers.freeMode; -var rectMode = dragHelpers.rectMode; -var drawMode = dragHelpers.drawMode; -var openMode = dragHelpers.openMode; -var selectMode$1 = dragHelpers.selectMode; -var shapeHelpers = helpers$w; -var shapeConstants = constants$I; -var displayOutlines2 = display_outlines; -var clearOutline = handle_outline.clearOutline; -var newShapeHelpers = helpers$A; -var handleEllipse = newShapeHelpers.handleEllipse; -var readPaths = newShapeHelpers.readPaths; -var newShapes = newshapes.newShapes; -var newSelections2 = newselections; -var activateLastSelection = draw_1$2.activateLastSelection; -var Lib$1j = libExports; -var ascending = Lib$1j.sorterAsc; -var libPolygon = polygonExports; -var throttle = throttle$2; -var getFromId = axis_ids.getFromId; -var clearGlCanvases2 = clear_gl_canvases; -var redrawReglTraces = subroutines.redrawReglTraces; -var constants$C = constants$D; -var MINSELECT = constants$C.MINSELECT; -var filteredPolygon = libPolygon.filter; -var polygonTester$1 = libPolygon.tester; -var helpers$r = helpers$z; -var p2r = helpers$r.p2r; -var axValue = helpers$r.axValue; -var getTransform = helpers$r.getTransform; -function hasSubplot(dragOptions) { - return dragOptions.subplot !== void 0; -} -function prepSelect(evt, startX, startY, dragOptions, mode) { - var isCartesian = !hasSubplot(dragOptions); - var isFreeMode = freeMode(mode); - var isRectMode = rectMode(mode); - var isOpenMode = openMode(mode); - var isDrawMode = drawMode(mode); - var isSelectMode = selectMode$1(mode); - var isLine = mode === "drawline"; - var isEllipse = mode === "drawcircle"; - var isLineOrEllipse = isLine || isEllipse; - var gd = dragOptions.gd; - var fullLayout = gd._fullLayout; - var immediateSelect = isSelectMode && fullLayout.newselection.mode === "immediate" && isCartesian; - var zoomLayer = fullLayout._zoomlayer; - var dragBBox = dragOptions.element.getBoundingClientRect(); - var plotinfo = dragOptions.plotinfo; - var transform = getTransform(plotinfo); - var x0 = startX - dragBBox.left; - var y0 = startY - dragBBox.top; - fullLayout._calcInverseTransform(gd); - var transformedCoords = Lib$1j.apply3DTransform(fullLayout._invTransform)(x0, y0); - x0 = transformedCoords[0]; - y0 = transformedCoords[1]; - var scaleX = fullLayout._invScaleX; - var scaleY = fullLayout._invScaleY; - var x1 = x0; - var y1 = y0; - var path0 = "M" + x0 + "," + y0; - var xAxis = dragOptions.xaxes[0]; - var yAxis = dragOptions.yaxes[0]; - var pw = xAxis._length; - var ph = yAxis._length; - var subtract = evt.altKey && !(drawMode(mode) && isOpenMode); - var filterPoly, selectionTesters, mergedPolygons, currentPolygon; - var i, searchInfo, eventData5; - coerceSelectionsCache(evt, gd, dragOptions); - if (isFreeMode) { - filterPoly = filteredPolygon([[x0, y0]], constants$C.BENDPX); - } - var outlines = zoomLayer.selectAll("path.select-outline-" + plotinfo.id).data([1]); - var newStyle = isDrawMode ? fullLayout.newshape : fullLayout.newselection; - if (isDrawMode) { - dragOptions.hasText = newStyle.label.text || newStyle.label.texttemplate; - } - var fillC = isDrawMode && !isOpenMode ? newStyle.fillcolor : "rgba(0,0,0,0)"; - var strokeC = newStyle.line.color || (isCartesian ? Color$w.contrast(gd._fullLayout.plot_bgcolor) : "#7f7f7f"); - outlines.enter().append("path").attr("class", "select-outline select-outline-" + plotinfo.id).style({ - opacity: isDrawMode ? newStyle.opacity / 2 : 1, - "stroke-dasharray": dashStyle(newStyle.line.dash, newStyle.line.width), - "stroke-width": newStyle.line.width + "px", - "shape-rendering": "crispEdges" - }).call(Color$w.stroke, strokeC).call(Color$w.fill, fillC).attr("fill-rule", "evenodd").classed("cursor-move", isDrawMode ? true : false).attr("transform", transform).attr("d", path0 + "Z"); - var corners = zoomLayer.append("path").attr("class", "zoombox-corners").style({ - fill: Color$w.background, - stroke: Color$w.defaultLine, - "stroke-width": 1 - }).attr("transform", transform).attr("d", "M0,0Z"); - if (isDrawMode && dragOptions.hasText) { - var shapeGroup = zoomLayer.select(".label-temp"); - if (shapeGroup.empty()) { - shapeGroup = zoomLayer.append("g").classed("label-temp", true).classed("select-outline", true).style({ opacity: 0.8 }); - } - } - var throttleID = fullLayout._uid + constants$C.SELECTID; - var selection = []; - var searchTraces = determineSearchTraces( - gd, - dragOptions.xaxes, - dragOptions.yaxes, - dragOptions.subplot - ); - if (immediateSelect && !evt.shiftKey) { - dragOptions._clearSubplotSelections = function() { - if (!isCartesian) return; - var xRef = xAxis._id; - var yRef = yAxis._id; - deselectSubplot(gd, xRef, yRef, searchTraces); - var selections2 = (gd.layout || {}).selections || []; - var list = []; - var selectionErased = false; - for (var q = 0; q < selections2.length; q++) { - var s = fullLayout.selections[q]; - if (s.xref !== xRef || s.yref !== yRef) { - list.push(selections2[q]); - } else { - selectionErased = true; - } - } - if (selectionErased) { - gd._fullLayout._noEmitSelectedAtStart = true; - Registry$v.call("_guiRelayout", gd, { - selections: list - }); - } - }; - } - var fillRangeItems = getFillRangeItems(dragOptions); - dragOptions.moveFn = function(dx0, dy0) { - if (dragOptions._clearSubplotSelections) { - dragOptions._clearSubplotSelections(); - dragOptions._clearSubplotSelections = void 0; - } - x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0)); - y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0)); - var dx = Math.abs(x1 - x0); - var dy = Math.abs(y1 - y0); - if (isRectMode) { - var direction; - var start, end; - if (isSelectMode) { - var q = fullLayout.selectdirection; - if (q === "any") { - if (dy < Math.min(dx * 0.6, MINSELECT)) { - direction = "h"; - } else if (dx < Math.min(dy * 0.6, MINSELECT)) { - direction = "v"; - } else { - direction = "d"; - } - } else { - direction = q; - } - switch (direction) { - case "h": - start = isEllipse ? ph / 2 : 0; - end = ph; - break; - case "v": - start = isEllipse ? pw / 2 : 0; - end = pw; - break; - } - } - if (isDrawMode) { - switch (fullLayout.newshape.drawdirection) { - case "vertical": - direction = "h"; - start = isEllipse ? ph / 2 : 0; - end = ph; - break; - case "horizontal": - direction = "v"; - start = isEllipse ? pw / 2 : 0; - end = pw; - break; - case "ortho": - if (dx < dy) { - direction = "h"; - start = y0; - end = y1; - } else { - direction = "v"; - start = x0; - end = x1; - } - break; - default: - direction = "d"; - } - } - if (direction === "h") { - currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x1, start], [x1, end]) : ( - // using x1 instead of x0 allows adjusting the line while drawing - [[x0, start], [x0, end], [x1, end], [x1, start]] - ); - currentPolygon.xmin = isLineOrEllipse ? x1 : Math.min(x0, x1); - currentPolygon.xmax = isLineOrEllipse ? x1 : Math.max(x0, x1); - currentPolygon.ymin = Math.min(start, end); - currentPolygon.ymax = Math.max(start, end); - corners.attr("d", "M" + currentPolygon.xmin + "," + (y0 - MINSELECT) + "h-4v" + 2 * MINSELECT + "h4ZM" + (currentPolygon.xmax - 1) + "," + (y0 - MINSELECT) + "h4v" + 2 * MINSELECT + "h-4Z"); - } else if (direction === "v") { - currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [start, y1], [end, y1]) : ( - // using y1 instead of y0 allows adjusting the line while drawing - [[start, y0], [start, y1], [end, y1], [end, y0]] - ); - currentPolygon.xmin = Math.min(start, end); - currentPolygon.xmax = Math.max(start, end); - currentPolygon.ymin = isLineOrEllipse ? y1 : Math.min(y0, y1); - currentPolygon.ymax = isLineOrEllipse ? y1 : Math.max(y0, y1); - corners.attr("d", "M" + (x0 - MINSELECT) + "," + currentPolygon.ymin + "v-4h" + 2 * MINSELECT + "v4ZM" + (x0 - MINSELECT) + "," + (currentPolygon.ymax - 1) + "v4h" + 2 * MINSELECT + "v-4Z"); - } else if (direction === "d") { - currentPolygon = isLineOrEllipse ? handleEllipse(isEllipse, [x0, y0], [x1, y1]) : [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]; - currentPolygon.xmin = Math.min(x0, x1); - currentPolygon.xmax = Math.max(x0, x1); - currentPolygon.ymin = Math.min(y0, y1); - currentPolygon.ymax = Math.max(y0, y1); - corners.attr("d", "M0,0Z"); - } - } else if (isFreeMode) { - filterPoly.addPt([x1, y1]); - currentPolygon = filterPoly.filtered; - } - if (dragOptions.selectionDefs && dragOptions.selectionDefs.length) { - mergedPolygons = mergePolygons(dragOptions.mergedPolygons, currentPolygon, subtract); - currentPolygon.subtract = subtract; - selectionTesters = multiTester(dragOptions.selectionDefs.concat([currentPolygon])); - } else { - mergedPolygons = [currentPolygon]; - selectionTesters = polygonTester$1(currentPolygon); - } - displayOutlines2(convertPoly(mergedPolygons, isOpenMode), outlines, dragOptions); - if (isSelectMode) { - var _res = reselect(gd, false); - var extraPoints = _res.eventData ? _res.eventData.points.slice() : []; - _res = reselect(gd, false, selectionTesters, searchTraces, dragOptions); - selectionTesters = _res.selectionTesters; - eventData5 = _res.eventData; - var poly; - if (filterPoly) { - poly = filterPoly.filtered; - } else { - poly = castMultiPolygon(mergedPolygons); - } - throttle.throttle( - throttleID, - constants$C.SELECTDELAY, - function() { - selection = _doSelect(selectionTesters, searchTraces); - var newPoints = selection.slice(); - for (var w = 0; w < extraPoints.length; w++) { - var p = extraPoints[w]; - var found = false; - for (var u = 0; u < newPoints.length; u++) { - if (newPoints[u].curveNumber === p.curveNumber && newPoints[u].pointNumber === p.pointNumber) { - found = true; - break; - } - } - if (!found) newPoints.push(p); - } - if (newPoints.length) { - if (!eventData5) eventData5 = {}; - eventData5.points = newPoints; - } - fillRangeItems(eventData5, poly); - emitSelecting(gd, eventData5); - } - ); - } - }; - dragOptions.clickFn = function(numClicks, evt2) { - corners.remove(); - if (gd._fullLayout._activeShapeIndex >= 0) { - gd._fullLayout._deactivateShape(gd); - return; - } - if (isDrawMode) return; - var clickmode = fullLayout.clickmode; - throttle.done(throttleID).then(function() { - throttle.clear(throttleID); - if (numClicks === 2) { - outlines.remove(); - for (i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo._module.selectPoints(searchInfo, false); - } - updateSelectedState(gd, searchTraces); - clearSelectionsCache(dragOptions); - emitDeselect(gd); - if (searchTraces.length) { - var clickedXaxis = searchTraces[0].xaxis; - var clickedYaxis = searchTraces[0].yaxis; - if (clickedXaxis && clickedYaxis) { - var subSelections = []; - var allSelections = gd._fullLayout.selections; - for (var k = 0; k < allSelections.length; k++) { - var s = allSelections[k]; - if (!s) continue; - if (s.xref !== clickedXaxis._id || s.yref !== clickedYaxis._id) { - subSelections.push(s); - } - } - if (subSelections.length < allSelections.length) { - gd._fullLayout._noEmitSelectedAtStart = true; - Registry$v.call("_guiRelayout", gd, { - selections: subSelections - }); - } - } - } - } else { - if (clickmode.indexOf("select") > -1) { - selectOnClick( - evt2, - gd, - dragOptions.xaxes, - dragOptions.yaxes, - dragOptions.subplot, - dragOptions, - outlines - ); - } - if (clickmode === "event") { - emitSelected(gd, void 0); - } - } - Fx$6.click(gd, evt2, plotinfo.id); - }).catch(Lib$1j.error); - }; - dragOptions.doneFn = function() { - corners.remove(); - throttle.done(throttleID).then(function() { - throttle.clear(throttleID); - if (!immediateSelect && currentPolygon && dragOptions.selectionDefs) { - currentPolygon.subtract = subtract; - dragOptions.selectionDefs.push(currentPolygon); - dragOptions.mergedPolygons.length = 0; - [].push.apply(dragOptions.mergedPolygons, mergedPolygons); - } - if (immediateSelect || isDrawMode) { - clearSelectionsCache(dragOptions, immediateSelect); - } - if (dragOptions.doneFnCompleted) { - dragOptions.doneFnCompleted(selection); - } - if (isSelectMode) { - emitSelected(gd, eventData5); - } - }).catch(Lib$1j.error); - }; -} -function selectOnClick(evt, gd, xAxes, yAxes, subplot, dragOptions, polygonOutlines) { - var hoverData = gd._hoverdata; - var fullLayout = gd._fullLayout; - var clickmode = fullLayout.clickmode; - var sendEvents = clickmode.indexOf("event") > -1; - var selection = []; - var searchTraces, searchInfo, currentSelectionDef, selectionTesters, traceSelection; - var thisTracesSelection, pointOrBinSelected, subtract, eventData5, i; - if (isHoverDataSet(hoverData)) { - coerceSelectionsCache(evt, gd, dragOptions); - searchTraces = determineSearchTraces(gd, xAxes, yAxes, subplot); - var clickedPtInfo = extractClickedPtInfo(hoverData, searchTraces); - var isBinnedTrace = clickedPtInfo.pointNumbers.length > 0; - if (isBinnedTrace ? isOnlyThisBinSelected(searchTraces, clickedPtInfo) : isOnlyOnePointSelected(searchTraces) && (pointOrBinSelected = isPointOrBinSelected(clickedPtInfo))) { - if (polygonOutlines) polygonOutlines.remove(); - for (i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - searchInfo._module.selectPoints(searchInfo, false); - } - updateSelectedState(gd, searchTraces); - clearSelectionsCache(dragOptions); - if (sendEvents) { - emitDeselect(gd); - } - } else { - subtract = evt.shiftKey && (pointOrBinSelected !== void 0 ? pointOrBinSelected : isPointOrBinSelected(clickedPtInfo)); - currentSelectionDef = newPointSelectionDef(clickedPtInfo.pointNumber, clickedPtInfo.searchInfo, subtract); - var allSelectionDefs = dragOptions.selectionDefs.concat([currentSelectionDef]); - selectionTesters = multiTester(allSelectionDefs); - for (i = 0; i < searchTraces.length; i++) { - traceSelection = searchTraces[i]._module.selectPoints(searchTraces[i], selectionTesters); - thisTracesSelection = fillSelectionItem(traceSelection, searchTraces[i]); - if (selection.length) { - for (var j = 0; j < thisTracesSelection.length; j++) { - selection.push(thisTracesSelection[j]); - } - } else selection = thisTracesSelection; - } - eventData5 = { points: selection }; - updateSelectedState(gd, searchTraces, eventData5); - if (currentSelectionDef && dragOptions) { - dragOptions.selectionDefs.push(currentSelectionDef); - } - if (polygonOutlines) { - var polygons = dragOptions.mergedPolygons; - var isOpenMode = openMode(dragOptions.dragmode); - displayOutlines2(convertPoly(polygons, isOpenMode), polygonOutlines, dragOptions); - } - if (sendEvents) { - emitSelected(gd, eventData5); - } - } - } -} -function newPointSelectionDef(pointNumber, searchInfo, subtract) { - return { - pointNumber, - searchInfo, - subtract: !!subtract - }; -} -function isPointSelectionDef(o) { - return "pointNumber" in o && "searchInfo" in o; -} -function newPointNumTester(pointSelectionDef) { - return { - xmin: 0, - xmax: 0, - ymin: 0, - ymax: 0, - pts: [], - contains: function(pt, omitFirstEdge, pointNumber, searchInfo) { - var idxWantedTrace = pointSelectionDef.searchInfo.cd[0].trace._expandedIndex; - var idxActualTrace = searchInfo.cd[0].trace._expandedIndex; - return idxActualTrace === idxWantedTrace && pointNumber === pointSelectionDef.pointNumber; - }, - isRect: false, - degenerate: false, - subtract: !!pointSelectionDef.subtract - }; -} -function multiTester(list) { - if (!list.length) return; - var testers = []; - var xmin = isPointSelectionDef(list[0]) ? 0 : list[0][0][0]; - var xmax = xmin; - var ymin = isPointSelectionDef(list[0]) ? 0 : list[0][0][1]; - var ymax = ymin; - for (var i = 0; i < list.length; i++) { - if (isPointSelectionDef(list[i])) { - testers.push(newPointNumTester(list[i])); - } else { - var tester2 = polygonTester$1(list[i]); - tester2.subtract = !!list[i].subtract; - testers.push(tester2); - xmin = Math.min(xmin, tester2.xmin); - xmax = Math.max(xmax, tester2.xmax); - ymin = Math.min(ymin, tester2.ymin); - ymax = Math.max(ymax, tester2.ymax); - } - } - function contains(pt, arg, pointNumber, searchInfo) { - var contained = false; - for (var i2 = 0; i2 < testers.length; i2++) { - if (testers[i2].contains(pt, arg, pointNumber, searchInfo)) { - contained = !testers[i2].subtract; - } - } - return contained; - } - return { - xmin, - xmax, - ymin, - ymax, - pts: [], - contains, - isRect: false, - degenerate: false - }; -} -function coerceSelectionsCache(evt, gd, dragOptions) { - var fullLayout = gd._fullLayout; - var plotinfo = dragOptions.plotinfo; - var dragmode = dragOptions.dragmode; - var selectingOnSameSubplot = fullLayout._lastSelectedSubplot && fullLayout._lastSelectedSubplot === plotinfo.id; - var hasModifierKey = (evt.shiftKey || evt.altKey) && !(drawMode(dragmode) && openMode(dragmode)); - if (selectingOnSameSubplot && hasModifierKey && plotinfo.selection && plotinfo.selection.selectionDefs && !dragOptions.selectionDefs) { - dragOptions.selectionDefs = plotinfo.selection.selectionDefs; - dragOptions.mergedPolygons = plotinfo.selection.mergedPolygons; - } else if (!hasModifierKey || !plotinfo.selection) { - clearSelectionsCache(dragOptions); - } - if (!selectingOnSameSubplot) { - clearOutline(gd); - fullLayout._lastSelectedSubplot = plotinfo.id; - } -} -function hasActiveShape(gd) { - return gd._fullLayout._activeShapeIndex >= 0; -} -function hasActiveSelection(gd) { - return gd._fullLayout._activeSelectionIndex >= 0; -} -function clearSelectionsCache(dragOptions, immediateSelect) { - var dragmode = dragOptions.dragmode; - var plotinfo = dragOptions.plotinfo; - var gd = dragOptions.gd; - if (hasActiveShape(gd)) { - gd._fullLayout._deactivateShape(gd); - } - if (hasActiveSelection(gd)) { - gd._fullLayout._deactivateSelection(gd); - } - var fullLayout = gd._fullLayout; - var zoomLayer = fullLayout._zoomlayer; - var isDrawMode = drawMode(dragmode); - var isSelectMode = selectMode$1(dragmode); - if (isDrawMode || isSelectMode) { - var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id); - if (outlines && gd._fullLayout._outlining) { - var shapes2; - if (isDrawMode) { - shapes2 = newShapes(outlines, dragOptions); - } - if (shapes2) { - Registry$v.call("_guiRelayout", gd, { - shapes: shapes2 - }); - } - var selections2; - if (isSelectMode && !hasSubplot(dragOptions)) { - selections2 = newSelections2(outlines, dragOptions); - } - if (selections2) { - gd._fullLayout._noEmitSelectedAtStart = true; - Registry$v.call("_guiRelayout", gd, { - selections: selections2 - }).then(function() { - if (immediateSelect) { - activateLastSelection(gd); - } - }); - } - gd._fullLayout._outlining = false; - } - } - plotinfo.selection = {}; - plotinfo.selection.selectionDefs = dragOptions.selectionDefs = []; - plotinfo.selection.mergedPolygons = dragOptions.mergedPolygons = []; -} -function getAxId(ax) { - return ax._id; -} -function determineSearchTraces(gd, xAxes, yAxes, subplot) { - if (!gd.calcdata) return []; - var searchTraces = []; - var xAxisIds = xAxes.map(getAxId); - var yAxisIds = yAxes.map(getAxId); - var cd, trace, i; - for (i = 0; i < gd.calcdata.length; i++) { - cd = gd.calcdata[i]; - trace = cd[0].trace; - if (trace.visible !== true || !trace._module || !trace._module.selectPoints) continue; - if (hasSubplot({ subplot }) && (trace.subplot === subplot || trace.geo === subplot)) { - searchTraces.push(createSearchInfo(trace._module, cd, xAxes[0], yAxes[0])); - } else if (trace.type === "splom") { - if (trace._xaxes[xAxisIds[0]] && trace._yaxes[yAxisIds[0]]) { - var info = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]); - info.scene = gd._fullLayout._splomScenes[trace.uid]; - searchTraces.push(info); - } - } else if (trace.type === "sankey") { - var sankeyInfo = createSearchInfo(trace._module, cd, xAxes[0], yAxes[0]); - searchTraces.push(sankeyInfo); - } else { - if (xAxisIds.indexOf(trace.xaxis) === -1 && (!trace._xA || !trace._xA.overlaying)) continue; - if (yAxisIds.indexOf(trace.yaxis) === -1 && (!trace._yA || !trace._yA.overlaying)) continue; - searchTraces.push(createSearchInfo( - trace._module, - cd, - getFromId(gd, trace.xaxis), - getFromId(gd, trace.yaxis) - )); - } - } - return searchTraces; -} -function createSearchInfo(module2, calcData, xaxis, yaxis) { - return { - _module: module2, - cd: calcData, - xaxis, - yaxis - }; -} -function isHoverDataSet(hoverData) { - return hoverData && Array.isArray(hoverData) && hoverData[0].hoverOnBox !== true; -} -function extractClickedPtInfo(hoverData, searchTraces) { - var hoverDatum = hoverData[0]; - var pointNumber = -1; - var pointNumbers = []; - var searchInfo, i; - for (i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if (hoverDatum.fullData._expandedIndex === searchInfo.cd[0].trace._expandedIndex) { - if (hoverDatum.hoverOnBox === true) { - break; - } - if (hoverDatum.pointNumber !== void 0) { - pointNumber = hoverDatum.pointNumber; - } else if (hoverDatum.binNumber !== void 0) { - pointNumber = hoverDatum.binNumber; - pointNumbers = hoverDatum.pointNumbers; - } - break; - } - } - return { - pointNumber, - pointNumbers, - searchInfo - }; -} -function isPointOrBinSelected(clickedPtInfo) { - var trace = clickedPtInfo.searchInfo.cd[0].trace; - var ptNum = clickedPtInfo.pointNumber; - var ptNums = clickedPtInfo.pointNumbers; - var ptNumsSet = ptNums.length > 0; - var ptNumToTest = ptNumsSet ? ptNums[0] : ptNum; - return trace.selectedpoints ? trace.selectedpoints.indexOf(ptNumToTest) > -1 : false; -} -function isOnlyThisBinSelected(searchTraces, clickedPtInfo) { - var tracesWithSelectedPts = []; - var searchInfo, trace, isSameTrace, i; - for (i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - if (searchInfo.cd[0].trace.selectedpoints && searchInfo.cd[0].trace.selectedpoints.length > 0) { - tracesWithSelectedPts.push(searchInfo); - } - } - if (tracesWithSelectedPts.length === 1) { - isSameTrace = tracesWithSelectedPts[0] === clickedPtInfo.searchInfo; - if (isSameTrace) { - trace = clickedPtInfo.searchInfo.cd[0].trace; - if (trace.selectedpoints.length === clickedPtInfo.pointNumbers.length) { - for (i = 0; i < clickedPtInfo.pointNumbers.length; i++) { - if (trace.selectedpoints.indexOf(clickedPtInfo.pointNumbers[i]) < 0) { - return false; - } - } - return true; - } - } - } - return false; -} -function isOnlyOnePointSelected(searchTraces) { - var len = 0; - var searchInfo, trace, i; - for (i = 0; i < searchTraces.length; i++) { - searchInfo = searchTraces[i]; - trace = searchInfo.cd[0].trace; - if (trace.selectedpoints) { - if (trace.selectedpoints.length > 1) return false; - len += trace.selectedpoints.length; - if (len > 1) return false; - } - } - return len === 1; -} -function updateSelectedState(gd, searchTraces, eventData5) { - var i; - for (i = 0; i < searchTraces.length; i++) { - var fullInputTrace = searchTraces[i].cd[0].trace._fullInput; - var tracePreGUI = gd._fullLayout._tracePreGUI[fullInputTrace.uid] || {}; - if (tracePreGUI.selectedpoints === void 0) { - tracePreGUI.selectedpoints = fullInputTrace._input.selectedpoints || null; - } - } - var trace; - if (eventData5) { - var pts = eventData5.points || []; - for (i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - trace._input.selectedpoints = trace._fullInput.selectedpoints = []; - if (trace._fullInput !== trace) trace.selectedpoints = []; - } - for (var k = 0; k < pts.length; k++) { - var pt = pts[k]; - var data = pt.data; - var fullData = pt.fullData; - var pointIndex = pt.pointIndex; - var pointIndices = pt.pointIndices; - if (pointIndices) { - [].push.apply(data.selectedpoints, pointIndices); - if (trace._fullInput !== trace) { - [].push.apply(fullData.selectedpoints, pointIndices); - } - } else { - data.selectedpoints.push(pointIndex); - if (trace._fullInput !== trace) { - fullData.selectedpoints.push(pointIndex); - } - } - } - } else { - for (i = 0; i < searchTraces.length; i++) { - trace = searchTraces[i].cd[0].trace; - delete trace.selectedpoints; - delete trace._input.selectedpoints; - if (trace._fullInput !== trace) { - delete trace._fullInput.selectedpoints; - } - } - } - updateReglSelectedState(gd, searchTraces); -} -function updateReglSelectedState(gd, searchTraces) { - var hasRegl = false; - for (var i = 0; i < searchTraces.length; i++) { - var searchInfo = searchTraces[i]; - var cd = searchInfo.cd; - if (Registry$v.traceIs(cd[0].trace, "regl")) { - hasRegl = true; - } - var _module = searchInfo._module; - var fn = _module.styleOnSelect || _module.style; - if (fn) { - fn(gd, cd, cd[0].node3); - if (cd[0].nodeRangePlot3) fn(gd, cd, cd[0].nodeRangePlot3); - } - } - if (hasRegl) { - clearGlCanvases2(gd); - redrawReglTraces(gd); - } -} -function mergePolygons(list, poly, subtract) { - var fn = subtract ? polybool.difference : polybool.union; - var res = fn({ - regions: list - }, { - regions: [poly] - }); - var allPolygons = res.regions.reverse(); - for (var i = 0; i < allPolygons.length; i++) { - var polygon2 = allPolygons[i]; - polygon2.subtract = getSubtract(polygon2, allPolygons.slice(0, i)); - } - return allPolygons; -} -function fillSelectionItem(selection, searchInfo) { - if (Array.isArray(selection)) { - var cd = searchInfo.cd; - var trace = searchInfo.cd[0].trace; - for (var i = 0; i < selection.length; i++) { - selection[i] = makeEventData$1(selection[i], trace, cd); - } - } - return selection; -} -function convertPoly(polygonsIn, isOpenMode) { - var polygonsOut = []; - for (var i = 0; i < polygonsIn.length; i++) { - polygonsOut[i] = []; - for (var j = 0; j < polygonsIn[i].length; j++) { - polygonsOut[i][j] = []; - polygonsOut[i][j][0] = j ? "L" : "M"; - for (var k = 0; k < polygonsIn[i][j].length; k++) { - polygonsOut[i][j].push( - polygonsIn[i][j][k] - ); - } - } - if (!isOpenMode) { - polygonsOut[i].push([ - "Z", - polygonsOut[i][0][1], - // initial x - polygonsOut[i][0][2] - // initial y - ]); - } - } - return polygonsOut; -} -function _doSelect(selectionTesters, searchTraces) { - var allSelections = []; - var thisSelection; - var traceSelection; - for (var i = 0; i < searchTraces.length; i++) { - var searchInfo = searchTraces[i]; - traceSelection = searchInfo._module.selectPoints(searchInfo, selectionTesters); - thisSelection = fillSelectionItem(traceSelection, searchInfo); - allSelections = allSelections.concat(thisSelection); - } - return allSelections; -} -function reselect(gd, mayEmitSelected, selectionTesters, searchTraces, dragOptions) { - var hadSearchTraces = !!searchTraces; - var plotinfo, xRef, yRef; - if (dragOptions) { - plotinfo = dragOptions.plotinfo; - xRef = dragOptions.xaxes[0]._id; - yRef = dragOptions.yaxes[0]._id; - } - var allSelections = []; - var allSearchTraces = []; - var layoutPolygons = getLayoutPolygons(gd); - var fullLayout = gd._fullLayout; - if (plotinfo) { - var zoomLayer = fullLayout._zoomlayer; - var mode = fullLayout.dragmode; - var isDrawMode = drawMode(mode); - var isSelectMode = selectMode$1(mode); - if (isDrawMode || isSelectMode) { - var xaxis = getFromId(gd, xRef, "x"); - var yaxis = getFromId(gd, yRef, "y"); - if (xaxis && yaxis) { - var outlines = zoomLayer.selectAll(".select-outline-" + plotinfo.id); - if (outlines && gd._fullLayout._outlining) { - if (outlines.length) { - var e = outlines[0][0]; - var d = e.getAttribute("d"); - var outlinePolys = readPaths(d, gd, plotinfo); - var draftPolygons = []; - for (var u = 0; u < outlinePolys.length; u++) { - var p = outlinePolys[u]; - var polygon2 = []; - for (var t = 0; t < p.length; t++) { - polygon2.push([ - convert$3(xaxis, p[t][1]), - convert$3(yaxis, p[t][2]) - ]); - } - polygon2.xref = xRef; - polygon2.yref = yRef; - polygon2.subtract = getSubtract(polygon2, draftPolygons); - draftPolygons.push(polygon2); - } - layoutPolygons = layoutPolygons.concat(draftPolygons); - } - } - } - } - } - var subplots = xRef && yRef ? [xRef + yRef] : fullLayout._subplots.cartesian; - epmtySplomSelectionBatch(gd); - var seenSplom = {}; - for (var i = 0; i < subplots.length; i++) { - var subplot = subplots[i]; - var yAt = subplot.indexOf("y"); - var _xRef = subplot.slice(0, yAt); - var _yRef = subplot.slice(yAt); - var _selectionTesters = xRef && yRef ? selectionTesters : void 0; - _selectionTesters = addTester(layoutPolygons, _xRef, _yRef, _selectionTesters); - if (_selectionTesters) { - var _searchTraces = searchTraces; - if (!hadSearchTraces) { - var _xA = getFromId(gd, _xRef, "x"); - var _yA = getFromId(gd, _yRef, "y"); - _searchTraces = determineSearchTraces( - gd, - [_xA], - [_yA], - subplot - ); - for (var w = 0; w < _searchTraces.length; w++) { - var s = _searchTraces[w]; - var cd0 = s.cd[0]; - var trace = cd0.trace; - if (s._module.name === "scattergl" && !cd0.t.xpx) { - var x = trace.x; - var y = trace.y; - var len = trace._length; - cd0.t.xpx = []; - cd0.t.ypx = []; - for (var j = 0; j < len; j++) { - cd0.t.xpx[j] = _xA.c2p(x[j]); - cd0.t.ypx[j] = _yA.c2p(y[j]); - } - } - if (s._module.name === "splom") { - if (!seenSplom[trace.uid]) { - seenSplom[trace.uid] = true; - } - } - } - } - var selection = _doSelect(_selectionTesters, _searchTraces); - allSelections = allSelections.concat(selection); - allSearchTraces = allSearchTraces.concat(_searchTraces); - } - } - var eventData5 = { points: allSelections }; - updateSelectedState(gd, allSearchTraces, eventData5); - var clickmode = fullLayout.clickmode; - var sendEvents = clickmode.indexOf("event") > -1 && mayEmitSelected; - if (!plotinfo && // get called from plot_api & plots - mayEmitSelected) { - var activePolygons = getLayoutPolygons(gd, true); - if (activePolygons.length) { - var xref = activePolygons[0].xref; - var yref = activePolygons[0].yref; - if (xref && yref) { - var poly = castMultiPolygon(activePolygons); - var fillRangeItems = makeFillRangeItems([ - getFromId(gd, xref, "x"), - getFromId(gd, yref, "y") - ]); - fillRangeItems(eventData5, poly); - } - } - if (gd._fullLayout._noEmitSelectedAtStart) { - gd._fullLayout._noEmitSelectedAtStart = false; - } else { - if (sendEvents) emitSelected(gd, eventData5); - } - fullLayout._reselect = false; - } - if (!plotinfo && // get called from plot_api & plots - fullLayout._deselect) { - var deselect = fullLayout._deselect; - xRef = deselect.xref; - yRef = deselect.yref; - if (!subplotSelected(xRef, yRef, allSearchTraces)) { - deselectSubplot(gd, xRef, yRef, searchTraces); - } - if (sendEvents) { - if (eventData5.points.length) { - emitSelected(gd, eventData5); - } else { - emitDeselect(gd); - } - } - fullLayout._deselect = false; - } - return { - eventData: eventData5, - selectionTesters - }; -} -function epmtySplomSelectionBatch(gd) { - var cd = gd.calcdata; - if (!cd) return; - for (var i = 0; i < cd.length; i++) { - var cd0 = cd[i][0]; - var trace = cd0.trace; - var splomScenes = gd._fullLayout._splomScenes; - if (splomScenes) { - var scene = splomScenes[trace.uid]; - if (scene) { - scene.selectBatch = []; - } - } - } -} -function subplotSelected(xRef, yRef, searchTraces) { - for (var i = 0; i < searchTraces.length; i++) { - var s = searchTraces[i]; - if (s.xaxis && s.xaxis._id === xRef && (s.yaxis && s.yaxis._id === yRef)) { - return true; - } - } - return false; -} -function deselectSubplot(gd, xRef, yRef, searchTraces) { - searchTraces = determineSearchTraces( - gd, - [getFromId(gd, xRef, "x")], - [getFromId(gd, yRef, "y")], - xRef + yRef - ); - for (var k = 0; k < searchTraces.length; k++) { - var searchInfo = searchTraces[k]; - searchInfo._module.selectPoints(searchInfo, false); - } - updateSelectedState(gd, searchTraces); -} -function addTester(layoutPolygons, xRef, yRef, selectionTesters) { - var mergedPolygons; - for (var i = 0; i < layoutPolygons.length; i++) { - var currentPolygon = layoutPolygons[i]; - if (xRef !== currentPolygon.xref || yRef !== currentPolygon.yref) continue; - if (mergedPolygons) { - var subtract = !!currentPolygon.subtract; - mergedPolygons = mergePolygons(mergedPolygons, currentPolygon, subtract); - selectionTesters = multiTester(mergedPolygons); - } else { - mergedPolygons = [currentPolygon]; - selectionTesters = polygonTester$1(currentPolygon); - } - } - return selectionTesters; -} -function getLayoutPolygons(gd, onlyActiveOnes) { - var allPolygons = []; - var fullLayout = gd._fullLayout; - var allSelections = fullLayout.selections; - var len = allSelections.length; - for (var i = 0; i < len; i++) { - if (onlyActiveOnes && i !== fullLayout._activeSelectionIndex) continue; - var selection = allSelections[i]; - if (!selection) continue; - var xref = selection.xref; - var yref = selection.yref; - var xaxis = getFromId(gd, xref, "x"); - var yaxis = getFromId(gd, yref, "y"); - var xmin, xmax, ymin, ymax; - var polygon2; - if (selection.type === "rect") { - polygon2 = []; - var x0 = convert$3(xaxis, selection.x0); - var x1 = convert$3(xaxis, selection.x1); - var y0 = convert$3(yaxis, selection.y0); - var y1 = convert$3(yaxis, selection.y1); - polygon2 = [[x0, y0], [x0, y1], [x1, y1], [x1, y0]]; - xmin = Math.min(x0, x1); - xmax = Math.max(x0, x1); - ymin = Math.min(y0, y1); - ymax = Math.max(y0, y1); - polygon2.xmin = xmin; - polygon2.xmax = xmax; - polygon2.ymin = ymin; - polygon2.ymax = ymax; - polygon2.xref = xref; - polygon2.yref = yref; - polygon2.subtract = false; - polygon2.isRect = true; - allPolygons.push(polygon2); - } else if (selection.type === "path") { - var segments = selection.path.split("Z"); - var multiPolygons = []; - for (var j = 0; j < segments.length; j++) { - var path = segments[j]; - if (!path) continue; - path += "Z"; - var allX = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsX, "raw"); - var allY = shapeHelpers.extractPathCoords(path, shapeConstants.paramIsY, "raw"); - xmin = Infinity; - xmax = -Infinity; - ymin = Infinity; - ymax = -Infinity; - polygon2 = []; - for (var k = 0; k < allX.length; k++) { - var x = convert$3(xaxis, allX[k]); - var y = convert$3(yaxis, allY[k]); - polygon2.push([x, y]); - xmin = Math.min(x, xmin); - xmax = Math.max(x, xmax); - ymin = Math.min(y, ymin); - ymax = Math.max(y, ymax); - } - polygon2.xmin = xmin; - polygon2.xmax = xmax; - polygon2.ymin = ymin; - polygon2.ymax = ymax; - polygon2.xref = xref; - polygon2.yref = yref; - polygon2.subtract = getSubtract(polygon2, multiPolygons); - multiPolygons.push(polygon2); - allPolygons.push(polygon2); - } - } - } - return allPolygons; -} -function getSubtract(polygon2, previousPolygons) { - var subtract = false; - for (var i = 0; i < previousPolygons.length; i++) { - var previousPolygon = previousPolygons[i]; - for (var k = 0; k < polygon2.length; k++) { - if (pointInPolygon(polygon2[k], previousPolygon)) { - subtract = !subtract; - break; - } - } - } - return subtract; -} -function convert$3(ax, d) { - if (ax.type === "date") d = d.replace("_", " "); - return ax.type === "log" ? ax.c2p(d) : ax.r2p(d, null, ax.calendar); -} -function castMultiPolygon(allPolygons) { - var len = allPolygons.length; - var p = []; - for (var i = 0; i < len; i++) { - var polygon2 = allPolygons[i]; - p = p.concat(polygon2); - p = p.concat([polygon2[0]]); - } - return computeRectAndRanges(p); -} -function computeRectAndRanges(poly) { - poly.isRect = poly.length === 5 && poly[0][0] === poly[4][0] && poly[0][1] === poly[4][1] && (poly[0][0] === poly[1][0] && poly[2][0] === poly[3][0] && poly[0][1] === poly[3][1] && poly[1][1] === poly[2][1]) || poly[0][1] === poly[1][1] && poly[2][1] === poly[3][1] && poly[0][0] === poly[3][0] && poly[1][0] === poly[2][0]; - if (poly.isRect) { - poly.xmin = Math.min(poly[0][0], poly[2][0]); - poly.xmax = Math.max(poly[0][0], poly[2][0]); - poly.ymin = Math.min(poly[0][1], poly[2][1]); - poly.ymax = Math.max(poly[0][1], poly[2][1]); - } - return poly; -} -function makeFillRangeItems(allAxes) { - return function(eventData5, poly) { - var range; - var lassoPoints; - for (var i = 0; i < allAxes.length; i++) { - var ax = allAxes[i]; - var id = ax._id; - var axLetter = id.charAt(0); - if (poly.isRect) { - if (!range) range = {}; - var min = poly[axLetter + "min"]; - var max = poly[axLetter + "max"]; - if (min !== void 0 && max !== void 0) { - range[id] = [ - p2r(ax, min), - p2r(ax, max) - ].sort(ascending); - } - } else { - if (!lassoPoints) lassoPoints = {}; - lassoPoints[id] = poly.map(axValue(ax)); - } - } - if (range) { - eventData5.range = range; - } - if (lassoPoints) { - eventData5.lassoPoints = lassoPoints; - } - }; -} -function getFillRangeItems(dragOptions) { - var plotinfo = dragOptions.plotinfo; - return plotinfo.fillRangeItems || // allow subplots (i.e. geo, mapbox, map, sankey) to override fillRangeItems routine - makeFillRangeItems(dragOptions.xaxes.concat(dragOptions.yaxes)); -} -function emitSelecting(gd, eventData5) { - gd.emit("plotly_selecting", eventData5); -} -function emitSelected(gd, eventData5) { - if (eventData5) { - eventData5.selections = (gd.layout || {}).selections || []; - } - gd.emit("plotly_selected", eventData5); -} -function emitDeselect(gd) { - gd.emit("plotly_deselect", null); -} -var select$5 = { - reselect, - prepSelect, - clearOutline, - clearSelectionsCache, - selectOnClick -}; -var arrow_paths = [ - // no arrow - { - path: "", - backoff: 0 - }, - // wide with flat back - { - path: "M-2.4,-3V3L0.6,0Z", - backoff: 0.6 - }, - // narrower with flat back - { - path: "M-3.7,-2.5V2.5L1.3,0Z", - backoff: 1.3 - }, - // barbed - { - path: "M-4.45,-3L-1.65,-0.2V0.2L-4.45,3L1.55,0Z", - backoff: 1.55 - }, - // wide line-drawn - { - path: "M-2.2,-2.2L-0.2,-0.2V0.2L-2.2,2.2L-1.4,3L1.6,0L-1.4,-3Z", - backoff: 1.6 - }, - // narrower line-drawn - { - path: "M-4.4,-2.1L-0.6,-0.2V0.2L-4.4,2.1L-4,3L2,0L-4,-3Z", - backoff: 2 - }, - // circle - { - path: "M2,0A2,2 0 1,1 0,-2A2,2 0 0,1 2,0Z", - backoff: 0, - noRotate: true - }, - // square - { - path: "M2,2V-2H-2V2Z", - backoff: 0, - noRotate: true - } -]; -var axis_placeable_objects = { - axisRefDescription: function(axisname, lower, upper) { - return [ - "If set to a", - axisname, - "axis id (e.g. *" + axisname + "* or", - "*" + axisname + "2*), the `" + axisname + "` position refers to a", - axisname, - "coordinate. If set to *paper*, the `" + axisname + "`", - "position refers to the distance from the", - lower, - "of the plotting", - "area in normalized coordinates where *0* (*1*) corresponds to the", - lower, - "(" + upper + "). If set to a", - axisname, - "axis ID followed by", - "*domain* (separated by a space), the position behaves like for", - "*paper*, but refers to the distance in fractions of the domain", - "length from the", - lower, - "of the domain of that axis: e.g.,", - "*" + axisname + "2 domain* refers to the domain of the second", - axisname, - " axis and a", - axisname, - "position of 0.5 refers to the", - "point between the", - lower, - "and the", - upper, - "of the domain of the", - "second", - axisname, - "axis." - ].join(" "); - } -}; -var ARROWPATHS$1 = arrow_paths; -var fontAttrs$9 = font_attributes; -var cartesianConstants$1 = constants$U; -var templatedArray$7 = plot_template.templatedArray; -var axisPlaceableObjs$3 = axis_placeable_objects; -function arrowAxisRefDescription(axis) { - return [ - "In order for absolute positioning of the arrow to work, *a" + axis + "ref* must be exactly the same as *" + axis + "ref*, otherwise *a" + axis + "ref* will revert to *pixel* (explained next).", - "For relative positioning, *a" + axis + "ref* can be set to *pixel*,", - "in which case the *a" + axis + "* value is specified in pixels", - "relative to *" + axis + "*.", - "Absolute positioning is useful", - "for trendline annotations which should continue to indicate", - "the correct trend when zoomed. Relative positioning is useful", - "for specifying the text offset for an annotated point." - ].join(" "); -} -function arrowCoordinateDescription(axis, lower, upper) { - return [ - "Sets the", - axis, - "component of the arrow tail about the arrow head.", - "If `a" + axis + "ref` is `pixel`, a positive (negative)", - "component corresponds to an arrow pointing", - "from", - upper, - "to", - lower, - "(" + lower, - "to", - upper + ").", - "If `a" + axis + "ref` is not `pixel` and is exactly the same as `" + axis + "ref`,", - "this is an absolute value on that axis,", - "like `" + axis + "`, specified in the same coordinates as `" + axis + "ref`." - ].join(" "); -} -var attributes$B = templatedArray$7("annotation", { - visible: { - valType: "boolean", - dflt: true, - editType: "calc+arraydraw", - description: [ - "Determines whether or not this annotation is visible." - ].join(" ") - }, - text: { - valType: "string", - editType: "calc+arraydraw", - description: [ - "Sets the text associated with this annotation.", - "Plotly uses a subset of HTML tags to do things like", - "newline (
), bold (), italics (),", - "hyperlinks (). Tags , , , , ", - " are also supported." - ].join(" ") - }, - textangle: { - valType: "angle", - dflt: 0, - editType: "calc+arraydraw", - description: [ - "Sets the angle at which the `text` is drawn", - "with respect to the horizontal." - ].join(" ") - }, - font: fontAttrs$9({ - editType: "calc+arraydraw", - colorEditType: "arraydraw", - description: "Sets the annotation text font." - }), - width: { - valType: "number", - min: 1, - dflt: null, - editType: "calc+arraydraw", - description: [ - "Sets an explicit width for the text box. null (default) lets the", - "text set the box width. Wider text will be clipped.", - "There is no automatic wrapping; use
to start a new line." - ].join(" ") - }, - height: { - valType: "number", - min: 1, - dflt: null, - editType: "calc+arraydraw", - description: [ - "Sets an explicit height for the text box. null (default) lets the", - "text set the box height. Taller text will be clipped." - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 1, - editType: "arraydraw", - description: "Sets the opacity of the annotation (text + arrow)." - }, - align: { - valType: "enumerated", - values: ["left", "center", "right"], - dflt: "center", - editType: "arraydraw", - description: [ - "Sets the horizontal alignment of the `text` within the box.", - "Has an effect only if `text` spans two or more lines", - "(i.e. `text` contains one or more
HTML tags) or if an", - "explicit width is set to override the text width." - ].join(" ") - }, - valign: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - dflt: "middle", - editType: "arraydraw", - description: [ - "Sets the vertical alignment of the `text` within the box.", - "Has an effect only if an explicit height is set to override", - "the text height." - ].join(" ") - }, - bgcolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - editType: "arraydraw", - description: "Sets the background color of the annotation." - }, - bordercolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - editType: "arraydraw", - description: [ - "Sets the color of the border enclosing the annotation `text`." - ].join(" ") - }, - borderpad: { - valType: "number", - min: 0, - dflt: 1, - editType: "calc+arraydraw", - description: [ - "Sets the padding (in px) between the `text`", - "and the enclosing border." - ].join(" ") - }, - borderwidth: { - valType: "number", - min: 0, - dflt: 1, - editType: "calc+arraydraw", - description: [ - "Sets the width (in px) of the border enclosing", - "the annotation `text`." - ].join(" ") - }, - // arrow - showarrow: { - valType: "boolean", - dflt: true, - editType: "calc+arraydraw", - description: [ - "Determines whether or not the annotation is drawn with an arrow.", - "If *true*, `text` is placed near the arrow's tail.", - "If *false*, `text` lines up with the `x` and `y` provided." - ].join(" ") - }, - arrowcolor: { - valType: "color", - editType: "arraydraw", - description: "Sets the color of the annotation arrow." - }, - arrowhead: { - valType: "integer", - min: 0, - max: ARROWPATHS$1.length, - dflt: 1, - editType: "arraydraw", - description: "Sets the end annotation arrow head style." - }, - startarrowhead: { - valType: "integer", - min: 0, - max: ARROWPATHS$1.length, - dflt: 1, - editType: "arraydraw", - description: "Sets the start annotation arrow head style." - }, - arrowside: { - valType: "flaglist", - flags: ["end", "start"], - extras: ["none"], - dflt: "end", - editType: "arraydraw", - description: "Sets the annotation arrow head position." - }, - arrowsize: { - valType: "number", - min: 0.3, - dflt: 1, - editType: "calc+arraydraw", - description: [ - "Sets the size of the end annotation arrow head, relative to `arrowwidth`.", - "A value of 1 (default) gives a head about 3x as wide as the line." - ].join(" ") - }, - startarrowsize: { - valType: "number", - min: 0.3, - dflt: 1, - editType: "calc+arraydraw", - description: [ - "Sets the size of the start annotation arrow head, relative to `arrowwidth`.", - "A value of 1 (default) gives a head about 3x as wide as the line." - ].join(" ") - }, - arrowwidth: { - valType: "number", - min: 0.1, - editType: "calc+arraydraw", - description: "Sets the width (in px) of annotation arrow line." - }, - standoff: { - valType: "number", - min: 0, - dflt: 0, - editType: "calc+arraydraw", - description: [ - "Sets a distance, in pixels, to move the end arrowhead away from the", - "position it is pointing at, for example to point at the edge of", - "a marker independent of zoom. Note that this shortens the arrow", - "from the `ax` / `ay` vector, in contrast to `xshift` / `yshift`", - "which moves everything by this amount." - ].join(" ") - }, - startstandoff: { - valType: "number", - min: 0, - dflt: 0, - editType: "calc+arraydraw", - description: [ - "Sets a distance, in pixels, to move the start arrowhead away from the", - "position it is pointing at, for example to point at the edge of", - "a marker independent of zoom. Note that this shortens the arrow", - "from the `ax` / `ay` vector, in contrast to `xshift` / `yshift`", - "which moves everything by this amount." - ].join(" ") - }, - ax: { - valType: "any", - editType: "calc+arraydraw", - description: [ - arrowCoordinateDescription("x", "left", "right") - ].join(" ") - }, - ay: { - valType: "any", - editType: "calc+arraydraw", - description: [ - arrowCoordinateDescription("y", "top", "bottom") - ].join(" ") - }, - axref: { - valType: "enumerated", - dflt: "pixel", - values: [ - "pixel", - cartesianConstants$1.idRegex.x.toString() - ], - editType: "calc", - description: [ - "Indicates in what coordinates the tail of the", - "annotation (ax,ay) is specified.", - axisPlaceableObjs$3.axisRefDescription("x", "left", "right"), - arrowAxisRefDescription("x") - ].join(" ") - }, - ayref: { - valType: "enumerated", - dflt: "pixel", - values: [ - "pixel", - cartesianConstants$1.idRegex.y.toString() - ], - editType: "calc", - description: [ - "Indicates in what coordinates the tail of the", - "annotation (ax,ay) is specified.", - axisPlaceableObjs$3.axisRefDescription("y", "bottom", "top"), - arrowAxisRefDescription("y") - ].join(" ") - }, - // positioning - xref: { - valType: "enumerated", - values: [ - "paper", - cartesianConstants$1.idRegex.x.toString() - ], - editType: "calc", - description: [ - "Sets the annotation's x coordinate axis.", - axisPlaceableObjs$3.axisRefDescription("x", "left", "right") - ].join(" ") - }, - x: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the annotation's x position.", - "If the axis `type` is *log*, then you must take the", - "log of your desired range.", - "If the axis `type` is *date*, it should be date strings,", - "like date data, though Date objects and unix milliseconds", - "will be accepted and converted to strings.", - "If the axis `type` is *category*, it should be numbers,", - "using the scale where each category is assigned a serial", - "number from zero in the order it appears." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "auto", - editType: "calc+arraydraw", - description: [ - "Sets the text box's horizontal position anchor", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the annotation.", - "For example, if `x` is set to 1, `xref` to *paper* and", - "`xanchor` to *right* then the right-most portion of the", - "annotation lines up with the right-most edge of the", - "plotting area.", - "If *auto*, the anchor is equivalent to *center* for", - "data-referenced annotations or if there is an arrow,", - "whereas for paper-referenced with no arrow, the anchor picked", - "corresponds to the closest side." - ].join(" ") - }, - xshift: { - valType: "number", - dflt: 0, - editType: "calc+arraydraw", - description: [ - "Shifts the position of the whole annotation and arrow to the", - "right (positive) or left (negative) by this many pixels." - ].join(" ") - }, - yref: { - valType: "enumerated", - values: [ - "paper", - cartesianConstants$1.idRegex.y.toString() - ], - editType: "calc", - description: [ - "Sets the annotation's y coordinate axis.", - axisPlaceableObjs$3.axisRefDescription("y", "bottom", "top") - ].join(" ") - }, - y: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the annotation's y position.", - "If the axis `type` is *log*, then you must take the", - "log of your desired range.", - "If the axis `type` is *date*, it should be date strings,", - "like date data, though Date objects and unix milliseconds", - "will be accepted and converted to strings.", - "If the axis `type` is *category*, it should be numbers,", - "using the scale where each category is assigned a serial", - "number from zero in the order it appears." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - values: ["auto", "top", "middle", "bottom"], - dflt: "auto", - editType: "calc+arraydraw", - description: [ - "Sets the text box's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the annotation.", - "For example, if `y` is set to 1, `yref` to *paper* and", - "`yanchor` to *top* then the top-most portion of the", - "annotation lines up with the top-most edge of the", - "plotting area.", - "If *auto*, the anchor is equivalent to *middle* for", - "data-referenced annotations or if there is an arrow,", - "whereas for paper-referenced with no arrow, the anchor picked", - "corresponds to the closest side." - ].join(" ") - }, - yshift: { - valType: "number", - dflt: 0, - editType: "calc+arraydraw", - description: [ - "Shifts the position of the whole annotation and arrow up", - "(positive) or down (negative) by this many pixels." - ].join(" ") - }, - clicktoshow: { - valType: "enumerated", - values: [false, "onoff", "onout"], - dflt: false, - editType: "arraydraw", - description: [ - "Makes this annotation respond to clicks on the plot.", - "If you click a data point that exactly matches the `x` and `y`", - "values of this annotation, and it is hidden (visible: false),", - "it will appear. In *onoff* mode, you must click the same point", - "again to make it disappear, so if you click multiple points,", - "you can show multiple annotations. In *onout* mode, a click", - "anywhere else in the plot (on another data point or not) will", - "hide this annotation.", - "If you need to show/hide this annotation in response to different", - "`x` or `y` values, you can set `xclick` and/or `yclick`. This is", - "useful for example to label the side of a bar. To label markers", - "though, `standoff` is preferred over `xclick` and `yclick`." - ].join(" ") - }, - xclick: { - valType: "any", - editType: "arraydraw", - description: [ - "Toggle this annotation when clicking a data point whose `x` value", - "is `xclick` rather than the annotation's `x` value." - ].join(" ") - }, - yclick: { - valType: "any", - editType: "arraydraw", - description: [ - "Toggle this annotation when clicking a data point whose `y` value", - "is `yclick` rather than the annotation's `y` value." - ].join(" ") - }, - hovertext: { - valType: "string", - editType: "arraydraw", - description: [ - "Sets text to appear when hovering over this annotation.", - "If omitted or blank, no hover label will appear." - ].join(" ") - }, - hoverlabel: { - bgcolor: { - valType: "color", - editType: "arraydraw", - description: [ - "Sets the background color of the hover label.", - "By default uses the annotation's `bgcolor` made opaque,", - "or white if it was transparent." - ].join(" ") - }, - bordercolor: { - valType: "color", - editType: "arraydraw", - description: [ - "Sets the border color of the hover label.", - "By default uses either dark grey or white, for maximum", - "contrast with `hoverlabel.bgcolor`." - ].join(" ") - }, - font: fontAttrs$9({ - editType: "arraydraw", - description: [ - "Sets the hover label text font.", - "By default uses the global hover font and size,", - "with color from `hoverlabel.bordercolor`." - ].join(" ") - }), - editType: "arraydraw" - }, - captureevents: { - valType: "boolean", - editType: "arraydraw", - description: [ - "Determines whether the annotation text box captures mouse move", - "and click events, or allows those events to pass through to data", - "points in the plot that may be behind the annotation. By default", - "`captureevents` is *false* unless `hovertext` is provided.", - "If you use the event `plotly_clickannotation` without `hovertext`", - "you must explicitly enable `captureevents`." - ].join(" ") - }, - editType: "calc", - _deprecated: { - ref: { - valType: "string", - editType: "calc", - description: [ - "Obsolete. Set `xref` and `yref` separately instead." - ].join(" ") - } - } -}); -var constants$B = { - PTS_LINESONLY: 20, - // fixed parameters of clustering and clipping algorithms - // fraction of clustering tolerance "so close we don't even consider it a new point" - minTolerance: 0.2, - // how fast does clustering tolerance increase as you get away from the visible region - toleranceGrowth: 10, - // number of viewport sizes away from the visible region - // at which we clip all lines to the perimeter - maxScreensAway: 20, - eventDataKeys: [] -}; -var fillcolor_attribute = function makeFillcolorAttr(hasFillgradient) { - return { - valType: "color", - editType: "style", - anim: true, - description: [ - "Sets the fill color.", - "Defaults to a half-transparent variant of the line color,", - "marker color, or marker line color, whichever is available." + (hasFillgradient ? " If fillgradient is specified, fillcolor is ignored except for setting the background color of the hover label, if any." : "") - ].join(" ") - }; -}; -var axisHoverFormat$4 = axis_format_attributes.axisHoverFormat; -var texttemplateAttrs$5 = template_attributes.texttemplateAttrs; -var hovertemplateAttrs$5 = template_attributes.hovertemplateAttrs; -var colorScaleAttrs$4 = attributes$I; -var fontAttrs$8 = font_attributes; -var dash$3 = attributes$M.dash; -var pattern$4 = attributes$M.pattern; -var Drawing$k = drawingExports; -var constants$A = constants$B; -var extendFlat$d = extend$5.extendFlat; -var makeFillcolorAttr$1 = fillcolor_attribute; -function axisPeriod(axis) { - return { - valType: "any", - dflt: 0, - editType: "calc", - description: [ - "Only relevant when the axis `type` is *date*.", - "Sets the period positioning in milliseconds or *M* on the " + axis + " axis.", - "Special values in the form of *M* could be used to declare", - "the number of months. In this case `n` must be a positive integer." - ].join(" ") - }; -} -function axisPeriod0(axis) { - return { - valType: "any", - editType: "calc", - description: [ - "Only relevant when the axis `type` is *date*.", - "Sets the base for period positioning in milliseconds or date string on the " + axis + " axis.", - "When `" + axis + "period` is round number of weeks,", - "the `" + axis + "period0` by default would be on a Sunday i.e. 2000-01-02,", - "otherwise it would be at 2000-01-01." - ].join(" ") - }; -} -function axisPeriodAlignment(axis) { - return { - valType: "enumerated", - values: [ - "start", - "middle", - "end" - ], - dflt: "middle", - editType: "calc", - description: [ - "Only relevant when the axis `type` is *date*.", - "Sets the alignment of data points on the " + axis + " axis." - ].join(" ") - }; -} -var attributes$A = { - x: { - valType: "data_array", - editType: "calc+clearAxisTypes", - anim: true, - description: "Sets the x coordinates." - }, - x0: { - valType: "any", - dflt: 0, - editType: "calc+clearAxisTypes", - anim: true, - description: [ - "Alternate to `x`.", - "Builds a linear space of x coordinates.", - "Use with `dx`", - "where `x0` is the starting coordinate and `dx` the step." - ].join(" ") - }, - dx: { - valType: "number", - dflt: 1, - editType: "calc", - anim: true, - description: [ - "Sets the x coordinate step.", - "See `x0` for more info." - ].join(" ") - }, - y: { - valType: "data_array", - editType: "calc+clearAxisTypes", - anim: true, - description: "Sets the y coordinates." - }, - y0: { - valType: "any", - dflt: 0, - editType: "calc+clearAxisTypes", - anim: true, - description: [ - "Alternate to `y`.", - "Builds a linear space of y coordinates.", - "Use with `dy`", - "where `y0` is the starting coordinate and `dy` the step." - ].join(" ") - }, - dy: { - valType: "number", - dflt: 1, - editType: "calc", - anim: true, - description: [ - "Sets the y coordinate step.", - "See `y0` for more info." - ].join(" ") - }, - xperiod: axisPeriod("x"), - yperiod: axisPeriod("y"), - xperiod0: axisPeriod0("x0"), - yperiod0: axisPeriod0("y0"), - xperiodalignment: axisPeriodAlignment("x"), - yperiodalignment: axisPeriodAlignment("y"), - xhoverformat: axisHoverFormat$4("x"), - yhoverformat: axisHoverFormat$4("y"), - offsetgroup: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "Set several traces linked to the same position axis", - "or matching axes to the same", - "offsetgroup where bars of the same position coordinate will line up." - ].join(" ") - }, - alignmentgroup: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "Set several traces linked to the same position axis", - "or matching axes to the same", - "alignmentgroup. This controls whether bars compute their positional", - "range dependently or independently." - ].join(" ") - }, - stackgroup: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "Set several scatter traces (on the same subplot) to the same", - "stackgroup in order to add their y values (or their x values if", - "`orientation` is *h*). If blank or omitted this trace will not be", - "stacked. Stacking also turns `fill` on by default, using *tonexty*", - "(*tonextx*) if `orientation` is *h* (*v*) and sets the default", - "`mode` to *lines* irrespective of point count.", - "You can only stack on a numeric (linear or log) axis.", - "Traces in a `stackgroup` will only fill to (or be filled to) other", - "traces in the same group. With multiple `stackgroup`s or some", - "traces stacked and some not, if fill-linked traces are not already", - "consecutive, the later ones will be pushed down in the drawing order." - ].join(" ") - }, - orientation: { - valType: "enumerated", - values: ["v", "h"], - editType: "calc", - description: [ - "Only relevant in the following cases:", - "1. when `scattermode` is set to *group*.", - "2. when `stackgroup` is used, and only the first", - "`orientation` found in the `stackgroup` will be used - including", - "if `visible` is *legendonly* but not if it is `false`. Sets the", - "stacking direction. With *v* (*h*), the y (x) values of subsequent", - "traces are added. Also affects the default value of `fill`." - ].join(" ") - }, - groupnorm: { - valType: "enumerated", - values: ["", "fraction", "percent"], - dflt: "", - editType: "calc", - description: [ - "Only relevant when `stackgroup` is used, and only the first", - "`groupnorm` found in the `stackgroup` will be used - including", - "if `visible` is *legendonly* but not if it is `false`.", - "Sets the normalization for the sum of this `stackgroup`.", - "With *fraction*, the value of each trace at each location is", - "divided by the sum of all trace values at that location.", - "*percent* is the same but multiplied by 100 to show percentages.", - "If there are multiple subplots, or multiple `stackgroup`s on one", - "subplot, each will be normalized within its own set." - ].join(" ") - }, - stackgaps: { - valType: "enumerated", - values: ["infer zero", "interpolate"], - dflt: "infer zero", - editType: "calc", - description: [ - "Only relevant when `stackgroup` is used, and only the first", - "`stackgaps` found in the `stackgroup` will be used - including", - "if `visible` is *legendonly* but not if it is `false`.", - "Determines how we handle locations at which other traces in this", - "group have data but this one does not.", - "With *infer zero* we insert a zero at these locations.", - "With *interpolate* we linearly interpolate between existing", - "values, and extrapolate a constant beyond the existing values." - // TODO - implement interrupt mode - // '*interrupt* omits this trace from the stack at this location by', - // 'dropping abruptly, midway between the existing and missing locations.' - ].join(" ") - }, - text: { - valType: "string", - dflt: "", - arrayOk: true, - editType: "calc", - description: [ - "Sets text elements associated with each (x,y) pair.", - "If a single string, the same string appears over", - "all the data points.", - "If an array of string, the items are mapped in order to the", - "this trace's (x,y) coordinates.", - "If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,", - "these elements will be seen in the hover labels." - ].join(" ") - }, - texttemplate: texttemplateAttrs$5({}, {}), - hovertext: { - valType: "string", - dflt: "", - arrayOk: true, - editType: "style", - description: [ - "Sets hover text elements associated with each (x,y) pair.", - "If a single string, the same string appears over", - "all the data points.", - "If an array of string, the items are mapped in order to the", - "this trace's (x,y) coordinates.", - "To be seen, trace `hoverinfo` must contain a *text* flag." - ].join(" ") - }, - mode: { - valType: "flaglist", - flags: ["lines", "markers", "text"], - extras: ["none"], - editType: "calc", - description: [ - "Determines the drawing mode for this scatter trace.", - "If the provided `mode` includes *text* then the `text` elements", - "appear at the coordinates. Otherwise, the `text` elements", - "appear on hover.", - "If there are less than " + constants$A.PTS_LINESONLY + " points", - "and the trace is not stacked", - "then the default is *lines+markers*. Otherwise, *lines*." - ].join(" ") - }, - hoveron: { - valType: "flaglist", - flags: ["points", "fills"], - editType: "style", - description: [ - "Do the hover effects highlight individual points (markers or", - "line points) or do they highlight filled regions?", - "If the fill is *toself* or *tonext* and there are no markers", - "or text, then the default is *fills*, otherwise it is *points*." - ].join(" ") - }, - hovertemplate: hovertemplateAttrs$5({}, { - keys: constants$A.eventDataKeys - }), - line: { - color: { - valType: "color", - editType: "style", - anim: true, - description: "Sets the line color." - }, - width: { - valType: "number", - min: 0, - dflt: 2, - editType: "style", - anim: true, - description: "Sets the line width (in px)." - }, - shape: { - valType: "enumerated", - values: ["linear", "spline", "hv", "vh", "hvh", "vhv"], - dflt: "linear", - editType: "plot", - description: [ - "Determines the line shape.", - "With *spline* the lines are drawn using spline interpolation.", - "The other available values correspond to step-wise line shapes." - ].join(" ") - }, - smoothing: { - valType: "number", - min: 0, - max: 1.3, - dflt: 1, - editType: "plot", - description: [ - "Has an effect only if `shape` is set to *spline*", - "Sets the amount of smoothing.", - "*0* corresponds to no smoothing (equivalent to a *linear* shape)." - ].join(" ") - }, - dash: extendFlat$d({}, dash$3, { editType: "style" }), - backoff: { - // we want to have a similar option for the start of the line - valType: "number", - min: 0, - dflt: "auto", - arrayOk: true, - editType: "plot", - description: [ - "Sets the line back off from the end point of the nth line segment (in px).", - "This option is useful e.g. to avoid overlap with arrowhead markers.", - "With *auto* the lines would trim before markers if `marker.angleref` is set to *previous*." - ].join(" ") - }, - simplify: { - valType: "boolean", - dflt: true, - editType: "plot", - description: [ - "Simplifies lines by removing nearly-collinear points. When transitioning", - "lines, it may be desirable to disable this so that the number of points", - "along the resulting SVG path is unaffected." - ].join(" ") - }, - editType: "plot" - }, - connectgaps: { - valType: "boolean", - dflt: false, - editType: "calc", - description: [ - "Determines whether or not gaps", - "(i.e. {nan} or missing values)", - "in the provided data arrays are connected." - ].join(" ") - }, - cliponaxis: { - valType: "boolean", - dflt: true, - editType: "plot", - description: [ - "Determines whether or not markers and text nodes", - "are clipped about the subplot axes.", - "To show markers and text nodes above axis lines and tick labels,", - "make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." - ].join(" ") - }, - fill: { - valType: "enumerated", - values: ["none", "tozeroy", "tozerox", "tonexty", "tonextx", "toself", "tonext"], - editType: "calc", - description: [ - "Sets the area to fill with a solid color.", - "Defaults to *none* unless this trace is stacked, then it gets", - "*tonexty* (*tonextx*) if `orientation` is *v* (*h*)", - "Use with `fillcolor` if not *none*.", - "*tozerox* and *tozeroy* fill to x=0 and y=0 respectively.", - "*tonextx* and *tonexty* fill between the endpoints of this", - "trace and the endpoints of the trace before it, connecting those", - "endpoints with straight lines (to make a stacked area graph);", - "if there is no trace before it, they behave like *tozerox* and", - "*tozeroy*.", - "*toself* connects the endpoints of the trace (or each segment", - "of the trace if it has gaps) into a closed shape.", - "*tonext* fills the space between two traces if one completely", - "encloses the other (eg consecutive contour lines), and behaves like", - "*toself* if there is no trace before it. *tonext* should not be", - "used if one trace does not enclose the other.", - "Traces in a `stackgroup` will only fill to (or be filled to) other", - "traces in the same group. With multiple `stackgroup`s or some", - "traces stacked and some not, if fill-linked traces are not already", - "consecutive, the later ones will be pushed down in the drawing order." - ].join(" ") - }, - fillcolor: makeFillcolorAttr$1(true), - fillgradient: extendFlat$d({ - type: { - valType: "enumerated", - values: ["radial", "horizontal", "vertical", "none"], - dflt: "none", - editType: "calc", - description: [ - "Sets the type/orientation of the color gradient for the fill.", - "Defaults to *none*." - ].join(" ") - }, - start: { - valType: "number", - editType: "calc", - description: [ - "Sets the gradient start value.", - "It is given as the absolute position on the axis determined by", - "the orientiation. E.g., if orientation is *horizontal*, the", - "gradient will be horizontal and start from the x-position", - "given by start. If omitted, the gradient starts at the lowest", - "value of the trace along the respective axis.", - "Ignored if orientation is *radial*." - ].join(" ") - }, - stop: { - valType: "number", - editType: "calc", - description: [ - "Sets the gradient end value.", - "It is given as the absolute position on the axis determined by", - "the orientiation. E.g., if orientation is *horizontal*, the", - "gradient will be horizontal and end at the x-position", - "given by end. If omitted, the gradient ends at the highest", - "value of the trace along the respective axis.", - "Ignored if orientation is *radial*." - ].join(" ") - }, - colorscale: { - valType: "colorscale", - editType: "style", - description: [ - "Sets the fill gradient colors as a color scale.", - "The color scale is interpreted as a gradient", - "applied in the direction specified by *orientation*,", - "from the lowest to the highest value of the scatter", - "plot along that axis, or from the center to the most", - "distant point from it, if orientation is *radial*." - ].join(" ") - }, - editType: "calc", - description: [ - "Sets a fill gradient.", - "If not specified, the fillcolor is used instead." - ].join(" ") - }), - fillpattern: pattern$4, - marker: extendFlat$d( - { - symbol: { - valType: "enumerated", - values: Drawing$k.symbolList, - dflt: "circle", - arrayOk: true, - editType: "style", - description: [ - "Sets the marker symbol type.", - "Adding 100 is equivalent to appending *-open* to a symbol name.", - "Adding 200 is equivalent to appending *-dot* to a symbol name.", - "Adding 300 is equivalent to appending *-open-dot*", - "or *dot-open* to a symbol name." - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - arrayOk: true, - editType: "style", - anim: true, - description: "Sets the marker opacity." - }, - angle: { - valType: "angle", - dflt: 0, - arrayOk: true, - editType: "plot", - anim: false, - // TODO: possibly set to true in future - description: [ - "Sets the marker angle in respect to `angleref`." - ].join(" ") - }, - angleref: { - valType: "enumerated", - values: ["previous", "up"], - dflt: "up", - editType: "plot", - anim: false, - description: [ - "Sets the reference for marker angle.", - "With *previous*, angle 0 points along the line from the previous point to this one.", - "With *up*, angle 0 points toward the top of the screen." - ].join(" ") - }, - standoff: { - valType: "number", - min: 0, - dflt: 0, - arrayOk: true, - editType: "plot", - anim: true, - description: [ - "Moves the marker away from the data point in the direction of `angle` (in px).", - "This can be useful for example if you have another marker at this", - "location and you want to point an arrowhead marker at it." - ].join(" ") - }, - size: { - valType: "number", - min: 0, - dflt: 6, - arrayOk: true, - editType: "calc", - anim: true, - description: "Sets the marker size (in px)." - }, - maxdisplayed: { - valType: "number", - min: 0, - dflt: 0, - editType: "plot", - description: [ - "Sets a maximum number of points to be drawn on the graph.", - "*0* corresponds to no limit." - ].join(" ") - }, - sizeref: { - valType: "number", - dflt: 1, - editType: "calc", - description: [ - "Has an effect only if `marker.size` is set to a numerical array.", - "Sets the scale factor used to determine the rendered size of", - "marker points. Use with `sizemin` and `sizemode`." - ].join(" ") - }, - sizemin: { - valType: "number", - min: 0, - dflt: 0, - editType: "calc", - description: [ - "Has an effect only if `marker.size` is set to a numerical array.", - "Sets the minimum size (in px) of the rendered marker points." - ].join(" ") - }, - sizemode: { - valType: "enumerated", - values: ["diameter", "area"], - dflt: "diameter", - editType: "calc", - description: [ - "Has an effect only if `marker.size` is set to a numerical array.", - "Sets the rule for which the data in `size` is converted", - "to pixels." - ].join(" ") - }, - line: extendFlat$d( - { - width: { - valType: "number", - min: 0, - arrayOk: true, - editType: "style", - anim: true, - description: "Sets the width (in px) of the lines bounding the marker points." - }, - editType: "calc" - }, - colorScaleAttrs$4("marker.line", { anim: true }) - ), - gradient: { - type: { - valType: "enumerated", - values: ["radial", "horizontal", "vertical", "none"], - arrayOk: true, - dflt: "none", - editType: "calc", - description: [ - "Sets the type of gradient used to fill the markers" - ].join(" ") - }, - color: { - valType: "color", - arrayOk: true, - editType: "calc", - description: [ - "Sets the final color of the gradient fill:", - "the center color for radial, the right for horizontal,", - "or the bottom for vertical." - ].join(" ") - }, - editType: "calc" - }, - editType: "calc" - }, - colorScaleAttrs$4("marker", { anim: true }) - ), - selected: { - marker: { - opacity: { - valType: "number", - min: 0, - max: 1, - editType: "style", - description: "Sets the marker opacity of selected points." - }, - color: { - valType: "color", - editType: "style", - description: "Sets the marker color of selected points." - }, - size: { - valType: "number", - min: 0, - editType: "style", - description: "Sets the marker size of selected points." - }, - editType: "style" - }, - textfont: { - color: { - valType: "color", - editType: "style", - description: "Sets the text font color of selected points." - }, - editType: "style" - }, - editType: "style" - }, - unselected: { - marker: { - opacity: { - valType: "number", - min: 0, - max: 1, - editType: "style", - description: "Sets the marker opacity of unselected points, applied only when a selection exists." - }, - color: { - valType: "color", - editType: "style", - description: "Sets the marker color of unselected points, applied only when a selection exists." - }, - size: { - valType: "number", - min: 0, - editType: "style", - description: "Sets the marker size of unselected points, applied only when a selection exists." - }, - editType: "style" - }, - textfont: { - color: { - valType: "color", - editType: "style", - description: "Sets the text font color of unselected points, applied only when a selection exists." - }, - editType: "style" - }, - editType: "style" - }, - textposition: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" - ], - dflt: "middle center", - arrayOk: true, - editType: "calc", - description: [ - "Sets the positions of the `text` elements", - "with respects to the (x,y) coordinates." - ].join(" ") - }, - textfont: fontAttrs$8({ - editType: "calc", - colorEditType: "style", - arrayOk: true, - description: "Sets the text font." - }), - zorder: { - valType: "integer", - dflt: 0, - editType: "plot", - description: [ - "Sets the layer on which this trace is displayed, relative to", - "other SVG traces on the same subplot. SVG traces with higher `zorder`", - "appear in front of those with lower `zorder`." - ].join(" ") - } -}; -var annAttrs$2 = attributes$B; -var scatterLineAttrs$2 = attributes$A.line; -var dash$2 = attributes$M.dash; -var extendFlat$c = extend$5.extendFlat; -var overrideAll$5 = edit_types.overrideAll; -var templatedArray$6 = plot_template.templatedArray; -var axisPlaceableObjs$2 = axis_placeable_objects; -var attributes$z = overrideAll$5(templatedArray$6("selection", { - type: { - valType: "enumerated", - values: ["rect", "path"], - description: [ - "Specifies the selection type to be drawn.", - "If *rect*, a rectangle is drawn linking", - "(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`) and (`x0`,`y1`).", - "If *path*, draw a custom SVG path using `path`." - ].join(" ") - }, - xref: extendFlat$c({}, annAttrs$2.xref, { - description: [ - "Sets the selection's x coordinate axis.", - axisPlaceableObjs$2.axisRefDescription("x", "left", "right") - ].join(" ") - }), - yref: extendFlat$c({}, annAttrs$2.yref, { - description: [ - "Sets the selection's x coordinate axis.", - axisPlaceableObjs$2.axisRefDescription("y", "bottom", "top") - ].join(" ") - }), - x0: { - valType: "any", - description: "Sets the selection's starting x position." - }, - x1: { - valType: "any", - description: "Sets the selection's end x position." - }, - y0: { - valType: "any", - description: "Sets the selection's starting y position." - }, - y1: { - valType: "any", - description: "Sets the selection's end y position." - }, - path: { - valType: "string", - editType: "arraydraw", - description: [ - "For `type` *path* - a valid SVG path similar to `shapes.path` in data coordinates.", - "Allowed segments are: M, L and Z." - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 0.7, - editType: "arraydraw", - description: "Sets the opacity of the selection." - }, - line: { - color: scatterLineAttrs$2.color, - width: extendFlat$c({}, scatterLineAttrs$2.width, { - min: 1, - dflt: 1 - }), - dash: extendFlat$c({}, dash$2, { - dflt: "dot" - }) - } -}), "arraydraw", "from-root"); -var Lib$1i = libExports; -var Axes$i = axesExports; -var handleArrayContainerDefaults$8 = array_container_defaults; -var attributes$y = attributes$z; -var helpers$q = helpers$w; -var defaults$j = function supplyLayoutDefaults4(layoutIn, layoutOut) { - handleArrayContainerDefaults$8(layoutIn, layoutOut, { - name: "selections", - handleItemDefaults: handleSelectionDefaults - }); - var selections2 = layoutOut.selections; - for (var i = 0; i < selections2.length; i++) { - var selection = selections2[i]; - if (!selection) continue; - if (selection.path === void 0) { - if (selection.x0 === void 0 || selection.x1 === void 0 || selection.y0 === void 0 || selection.y1 === void 0) { - layoutOut.selections[i] = null; - } - } - } -}; -function handleSelectionDefaults(selectionIn, selectionOut, fullLayout) { - function coerce2(attr, dflt) { - return Lib$1i.coerce(selectionIn, selectionOut, attributes$y, attr, dflt); - } - var path = coerce2("path"); - var dfltType = path ? "path" : "rect"; - var selectionType = coerce2("type", dfltType); - var noPath = selectionType !== "path"; - if (noPath) delete selectionOut.path; - coerce2("opacity"); - coerce2("line.color"); - coerce2("line.width"); - coerce2("line.dash"); - var axLetters2 = ["x", "y"]; - for (var i = 0; i < 2; i++) { - var axLetter = axLetters2[i]; - var gdMock = { _fullLayout: fullLayout }; - var ax; - var pos2r; - var r2pos; - var axRef = Axes$i.coerceRef(selectionIn, selectionOut, gdMock, axLetter); - ax = Axes$i.getFromId(gdMock, axRef); - ax._selectionIndices.push(selectionOut._index); - r2pos = helpers$q.rangeToShapePosition(ax); - pos2r = helpers$q.shapePositionToRange(ax); - if (noPath) { - var attr0 = axLetter + "0"; - var attr1 = axLetter + "1"; - var in0 = selectionIn[attr0]; - var in1 = selectionIn[attr1]; - selectionIn[attr0] = pos2r(selectionIn[attr0], true); - selectionIn[attr1] = pos2r(selectionIn[attr1], true); - Axes$i.coercePosition(selectionOut, gdMock, coerce2, axRef, attr0); - Axes$i.coercePosition(selectionOut, gdMock, coerce2, axRef, attr1); - var p0 = selectionOut[attr0]; - var p1 = selectionOut[attr1]; - if (p0 !== void 0 && p1 !== void 0) { - selectionOut[attr0] = r2pos(p0); - selectionOut[attr1] = r2pos(p1); - selectionIn[attr0] = in0; - selectionIn[attr1] = in1; - } - } - } - if (noPath) { - Lib$1i.noneOrAll(selectionIn, selectionOut, ["x0", "x1", "y0", "y1"]); - } -} -var defaults$i = function supplyDrawNewSelectionDefaults(layoutIn, layoutOut, coerce2) { - coerce2("newselection.mode"); - var newselectionLineWidth = coerce2("newselection.line.width"); - if (newselectionLineWidth) { - coerce2("newselection.line.color"); - coerce2("newselection.line.dash"); - } - coerce2("activeselection.fillcolor"); - coerce2("activeselection.opacity"); -}; -var Registry$u = registry; -var Lib$1h = libExports; -var axisIds$4 = axis_ids; -var include_components = function makeIncludeComponents(containerArrayName) { - return function includeComponents(layoutIn, layoutOut) { - var array2 = layoutIn[containerArrayName]; - if (!Array.isArray(array2)) return; - var Cartesian = Registry$u.subplotsRegistry.cartesian; - var idRegex2 = Cartesian.idRegex; - var subplots = layoutOut._subplots; - var xaList = subplots.xaxis; - var yaList = subplots.yaxis; - var cartesianList = subplots.cartesian; - var hasCartesianOrGL2D = layoutOut._has("cartesian") || layoutOut._has("gl2d"); - for (var i = 0; i < array2.length; i++) { - var itemi = array2[i]; - if (!Lib$1h.isPlainObject(itemi)) continue; - var xref = axisIds$4.cleanId(itemi.xref, "x", false); - var yref = axisIds$4.cleanId(itemi.yref, "y", false); - var hasXref = idRegex2.x.test(xref); - var hasYref = idRegex2.y.test(yref); - if (hasXref || hasYref) { - if (!hasCartesianOrGL2D) Lib$1h.pushUnique(layoutOut._basePlotModules, Cartesian); - var newAxis = false; - if (hasXref && xaList.indexOf(xref) === -1) { - xaList.push(xref); - newAxis = true; - } - if (hasYref && yaList.indexOf(yref) === -1) { - yaList.push(yref); - newAxis = true; - } - if (newAxis && hasXref && hasYref) { - cartesianList.push(xref + yref); - } - } - } - }; -}; -var drawModule$2 = draw_1$2; -var select$4 = select$5; -var selections = { - moduleType: "component", - name: "selections", - layoutAttributes: attributes$z, - supplyLayoutDefaults: defaults$j, - supplyDrawNewSelectionDefaults: defaults$i, - includeBasePlot: include_components("selections"), - draw: drawModule$2.draw, - drawOne: drawModule$2.drawOne, - reselect: select$4.reselect, - prepSelect: select$4.prepSelect, - clearOutline: select$4.clearOutline, - clearSelectionsCache: select$4.clearSelectionsCache, - selectOnClick: select$4.selectOnClick -}; -var dragbox; -var hasRequiredDragbox; -function requireDragbox() { - if (hasRequiredDragbox) return dragbox; - hasRequiredDragbox = 1; - var d32 = d3Exports; - var Lib2 = libExports; - var numberFormat2 = Lib2.numberFormat; - var tinycolor2 = tinycolorExports; - var supportsPassive2 = hasPassiveEvents; - var Registry2 = registry; - var strTranslate2 = Lib2.strTranslate; - var svgTextUtils2 = svg_text_utils; - var Color2 = colorExports; - var Drawing2 = drawingExports; - var Fx2 = fx$1; - var Axes2 = axesExports; - var setCursor3 = setcursor; - var dragElement2 = dragelementExports; - var helpers2 = helpers$B; - var selectingOrDrawing = helpers2.selectingOrDrawing; - var freeMode2 = helpers2.freeMode; - var FROM_TL2 = alignment$1.FROM_TL; - var clearGlCanvases3 = clear_gl_canvases; - var redrawReglTraces2 = subroutines.redrawReglTraces; - var Plots2 = plotsExports; - var getFromId2 = axis_ids.getFromId; - var prepSelect2 = selections.prepSelect; - var clearOutline2 = selections.clearOutline; - var selectOnClick2 = selections.selectOnClick; - var scaleZoom3 = scale_zoom; - var constants2 = constants$U; - var MINDRAG = constants2.MINDRAG; - var MINZOOM = constants2.MINZOOM; - var SHOWZOOMOUTTIP = true; - function makeDragBox(gd, plotinfo, x, y, w, h, ns, ew) { - var zoomlayer = gd._fullLayout._zoomlayer; - var isMainDrag = ns + ew === "nsew"; - var singleEnd = (ns + ew).length === 1; - var xa0, ya0; - var xaHash, yaHash; - var xaxes, yaxes; - var xs, ys; - var pw, ph; - var links; - var matches; - var xActive, yActive; - var allFixedRanges; - var editX, editY; - var hasScatterGl, hasSplom, hasSVG; - var updates; - var scaleX; - var scaleY; - x += plotinfo.yaxis._shift; - function recomputeAxisLists() { - xa0 = plotinfo.xaxis; - ya0 = plotinfo.yaxis; - pw = xa0._length; - ph = ya0._length; - xs = xa0._offset; - ys = ya0._offset; - xaHash = {}; - xaHash[xa0._id] = xa0; - yaHash = {}; - yaHash[ya0._id] = ya0; - if (ns && ew) { - var overlays = plotinfo.overlays; - for (var i = 0; i < overlays.length; i++) { - var xa = overlays[i].xaxis; - xaHash[xa._id] = xa; - var ya = overlays[i].yaxis; - yaHash[ya._id] = ya; - } - } - xaxes = hashValues(xaHash); - yaxes = hashValues(yaHash); - xActive = isDirectionActive(xaxes, ew); - yActive = isDirectionActive(yaxes, ns); - allFixedRanges = !yActive && !xActive; - matches = calcLinks(gd, gd._fullLayout._axisMatchGroups, xaHash, yaHash); - links = calcLinks(gd, gd._fullLayout._axisConstraintGroups, xaHash, yaHash, matches); - var spConstrained = links.isSubplotConstrained || matches.isSubplotConstrained; - editX = ew || spConstrained; - editY = ns || spConstrained; - var fullLayout = gd._fullLayout; - hasScatterGl = fullLayout._has("scattergl"); - hasSplom = fullLayout._has("splom"); - hasSVG = fullLayout._has("svg"); - } - recomputeAxisLists(); - var cursor2 = getDragCursor(yActive + xActive, gd._fullLayout.dragmode, isMainDrag); - var dragger = makeRectDragger(plotinfo, ns + ew + "drag", cursor2, x, y, w, h); - if (allFixedRanges && !isMainDrag) { - dragger.onmousedown = null; - dragger.style.pointerEvents = "none"; - return dragger; - } - var dragOptions = { - element: dragger, - gd, - plotinfo - }; - dragOptions.prepFn = function(e, startX, startY) { - var dragModePrev = dragOptions.dragmode; - var dragModeNow = gd._fullLayout.dragmode; - if (dragModeNow !== dragModePrev) { - dragOptions.dragmode = dragModeNow; - } - recomputeAxisLists(); - scaleX = gd._fullLayout._invScaleX; - scaleY = gd._fullLayout._invScaleY; - if (!allFixedRanges) { - if (isMainDrag) { - if (e.shiftKey) { - if (dragModeNow === "pan") dragModeNow = "zoom"; - else if (!selectingOrDrawing(dragModeNow)) dragModeNow = "pan"; - } else if (e.ctrlKey) { - dragModeNow = "pan"; - } - } else { - dragModeNow = "pan"; - } - } - if (freeMode2(dragModeNow)) dragOptions.minDrag = 1; - else dragOptions.minDrag = void 0; - if (selectingOrDrawing(dragModeNow)) { - dragOptions.xaxes = xaxes; - dragOptions.yaxes = yaxes; - prepSelect2(e, startX, startY, dragOptions, dragModeNow); - } else { - dragOptions.clickFn = clickFn; - if (selectingOrDrawing(dragModePrev)) { - clearAndResetSelect(); - } - if (!allFixedRanges) { - if (dragModeNow === "zoom") { - dragOptions.moveFn = zoomMove; - dragOptions.doneFn = zoomDone; - dragOptions.minDrag = 1; - zoomPrep(e, startX, startY); - } else if (dragModeNow === "pan") { - dragOptions.moveFn = plotDrag; - dragOptions.doneFn = dragTail; - } - } - } - gd._fullLayout._redrag = function() { - var dragDataNow = gd._dragdata; - if (dragDataNow && dragDataNow.element === dragger) { - var dragModeNow2 = gd._fullLayout.dragmode; - if (!selectingOrDrawing(dragModeNow2)) { - recomputeAxisLists(); - updateSubplots([0, 0, pw, ph]); - dragOptions.moveFn(dragDataNow.dx, dragDataNow.dy); - } - } - }; - }; - function clearAndResetSelect() { - dragOptions.plotinfo.selection = false; - clearOutline2(gd); - } - function clickFn(numClicks, evt) { - var gd2 = dragOptions.gd; - if (gd2._fullLayout._activeShapeIndex >= 0) { - gd2._fullLayout._deactivateShape(gd2); - return; - } - var clickmode = gd2._fullLayout.clickmode; - removeZoombox(gd2); - if (numClicks === 2 && !singleEnd) doubleClick(); - if (isMainDrag) { - if (clickmode.indexOf("select") > -1) { - selectOnClick2(evt, gd2, xaxes, yaxes, plotinfo.id, dragOptions); - } - if (clickmode.indexOf("event") > -1) { - Fx2.click(gd2, evt, plotinfo.id); - } - } else if (numClicks === 1 && singleEnd) { - var ax = ns ? ya0 : xa0; - var end = ns === "s" || ew === "w" ? 0 : 1; - var attrStr = ax._name + ".range[" + end + "]"; - var initialText = getEndText(ax, end); - var hAlign = "left"; - var vAlign = "middle"; - if (ax.fixedrange) return; - if (ns) { - vAlign = ns === "n" ? "top" : "bottom"; - if (ax.side === "right") hAlign = "right"; - } else if (ew === "e") hAlign = "right"; - if (gd2._context.showAxisRangeEntryBoxes) { - d32.select(dragger).call(svgTextUtils2.makeEditable, { - gd: gd2, - immediate: true, - background: gd2._fullLayout.paper_bgcolor, - text: String(initialText), - fill: ax.tickfont ? ax.tickfont.color : "#444", - horizontalAlign: hAlign, - verticalAlign: vAlign - }).on("edit", function(text) { - var v = ax.d2r(text); - if (v !== void 0) { - Registry2.call("_guiRelayout", gd2, attrStr, v); - } - }); - } - } - } - dragElement2.init(dragOptions); - var x0, y0; - var box; - var lum; - var path0; - var dimmed; - var zoomMode; - var zb; - var corners; - var zoomDragged; - function zoomPrep(e, startX, startY) { - var dragBBox = dragger.getBoundingClientRect(); - x0 = startX - dragBBox.left; - y0 = startY - dragBBox.top; - gd._fullLayout._calcInverseTransform(gd); - var transformedCoords = Lib2.apply3DTransform(gd._fullLayout._invTransform)(x0, y0); - x0 = transformedCoords[0]; - y0 = transformedCoords[1]; - box = { l: x0, r: x0, w: 0, t: y0, b: y0, h: 0 }; - lum = gd._hmpixcount ? gd._hmlumcount / gd._hmpixcount : tinycolor2(gd._fullLayout.plot_bgcolor).getLuminance(); - path0 = "M0,0H" + pw + "V" + ph + "H0V0"; - dimmed = false; - zoomMode = "xy"; - zoomDragged = false; - zb = makeZoombox(zoomlayer, lum, xs, ys, path0); - corners = makeCorners(zoomlayer, xs, ys); - } - function zoomMove(dx0, dy0) { - if (gd._transitioningWithDuration) { - return false; - } - var x1 = Math.max(0, Math.min(pw, scaleX * dx0 + x0)); - var y1 = Math.max(0, Math.min(ph, scaleY * dy0 + y0)); - var dx = Math.abs(x1 - x0); - var dy = Math.abs(y1 - y0); - box.l = Math.min(x0, x1); - box.r = Math.max(x0, x1); - box.t = Math.min(y0, y1); - box.b = Math.max(y0, y1); - function noZoom() { - zoomMode = ""; - box.r = box.l; - box.t = box.b; - corners.attr("d", "M0,0Z"); - } - if (links.isSubplotConstrained) { - if (dx > MINZOOM || dy > MINZOOM) { - zoomMode = "xy"; - if (dx / pw > dy / ph) { - dy = dx * ph / pw; - if (y0 > y1) box.t = y0 - dy; - else box.b = y0 + dy; - } else { - dx = dy * pw / ph; - if (x0 > x1) box.l = x0 - dx; - else box.r = x0 + dx; - } - corners.attr("d", xyCorners(box)); - } else { - noZoom(); - } - } else if (matches.isSubplotConstrained) { - if (dx > MINZOOM || dy > MINZOOM) { - zoomMode = "xy"; - var r0 = Math.min(box.l / pw, (ph - box.b) / ph); - var r1 = Math.max(box.r / pw, (ph - box.t) / ph); - box.l = r0 * pw; - box.r = r1 * pw; - box.b = (1 - r0) * ph; - box.t = (1 - r1) * ph; - corners.attr("d", xyCorners(box)); - } else { - noZoom(); - } - } else if (!yActive || dy < Math.min(Math.max(dx * 0.6, MINDRAG), MINZOOM)) { - if (dx < MINDRAG || !xActive) { - noZoom(); - } else { - box.t = 0; - box.b = ph; - zoomMode = "x"; - corners.attr("d", xCorners(box, y0)); - } - } else if (!xActive || dx < Math.min(dy * 0.6, MINZOOM)) { - box.l = 0; - box.r = pw; - zoomMode = "y"; - corners.attr("d", yCorners(box, x0)); - } else { - zoomMode = "xy"; - corners.attr("d", xyCorners(box)); - } - box.w = box.r - box.l; - box.h = box.b - box.t; - if (zoomMode) zoomDragged = true; - gd._dragged = zoomDragged; - updateZoombox(zb, corners, box, path0, dimmed, lum); - computeZoomUpdates(); - gd.emit("plotly_relayouting", updates); - dimmed = true; - } - function computeZoomUpdates() { - updates = {}; - if (zoomMode === "xy" || zoomMode === "x") { - zoomAxRanges(xaxes, box.l / pw, box.r / pw, updates, links.xaxes); - updateMatchedAxRange("x", updates); - } - if (zoomMode === "xy" || zoomMode === "y") { - zoomAxRanges(yaxes, (ph - box.b) / ph, (ph - box.t) / ph, updates, links.yaxes); - updateMatchedAxRange("y", updates); - } - } - function zoomDone() { - computeZoomUpdates(); - removeZoombox(gd); - dragTail(); - showDoubleClickNotifier(gd); - } - var scrollViewBox = [0, 0, pw, ph]; - var redrawTimer = null; - var REDRAWDELAY = constants2.REDRAWDELAY; - var mainplot = plotinfo.mainplot ? gd._fullLayout._plots[plotinfo.mainplot] : plotinfo; - function zoomWheel(e) { - if (!gd._context._scrollZoom.cartesian && !gd._fullLayout._enablescrollzoom) { - return; - } - clearAndResetSelect(); - if (gd._transitioningWithDuration) { - e.preventDefault(); - e.stopPropagation(); - return; - } - recomputeAxisLists(); - clearTimeout(redrawTimer); - var wheelDelta = -e.deltaY; - if (!isFinite(wheelDelta)) wheelDelta = e.wheelDelta / 10; - if (!isFinite(wheelDelta)) { - Lib2.log("Did not find wheel motion attributes: ", e); - return; - } - var zoom2 = Math.exp(-Math.min(Math.max(wheelDelta, -20), 20) / 200); - var gbb = mainplot.draglayer.select(".nsewdrag").node().getBoundingClientRect(); - var xfrac = (e.clientX - gbb.left) / gbb.width; - var yfrac = (gbb.bottom - e.clientY) / gbb.height; - var i; - function zoomWheelOneAxis(ax, centerFraction, zoom3) { - if (ax.fixedrange) return; - var axRange = Lib2.simpleMap(ax.range, ax.r2l); - var v0 = axRange[0] + (axRange[1] - axRange[0]) * centerFraction; - function doZoom(v) { - return ax.l2r(v0 + (v - v0) * zoom3); - } - ax.range = axRange.map(doZoom); - } - if (editX) { - if (!ew) xfrac = 0.5; - for (i = 0; i < xaxes.length; i++) { - zoomWheelOneAxis(xaxes[i], xfrac, zoom2); - } - updateMatchedAxRange("x"); - scrollViewBox[2] *= zoom2; - scrollViewBox[0] += scrollViewBox[2] * xfrac * (1 / zoom2 - 1); - } - if (editY) { - if (!ns) yfrac = 0.5; - for (i = 0; i < yaxes.length; i++) { - zoomWheelOneAxis(yaxes[i], yfrac, zoom2); - } - updateMatchedAxRange("y"); - scrollViewBox[3] *= zoom2; - scrollViewBox[1] += scrollViewBox[3] * (1 - yfrac) * (1 / zoom2 - 1); - } - updateSubplots(scrollViewBox); - ticksAndAnnotations(); - gd.emit("plotly_relayouting", updates); - redrawTimer = setTimeout(function() { - if (!gd._fullLayout) return; - scrollViewBox = [0, 0, pw, ph]; - dragTail(); - }, REDRAWDELAY); - e.preventDefault(); - return; - } - if (ns.length * ew.length !== 1) { - attachWheelEventHandler(dragger, zoomWheel); - } - function plotDrag(dx, dy) { - dx = dx * scaleX; - dy = dy * scaleY; - if (gd._transitioningWithDuration) { - return; - } - gd._fullLayout._replotting = true; - if (xActive === "ew" || yActive === "ns") { - var spDx = xActive ? -dx : 0; - var spDy = yActive ? -dy : 0; - if (matches.isSubplotConstrained) { - if (xActive && yActive) { - var frac = (dx / pw - dy / ph) / 2; - dx = frac * pw; - dy = -frac * ph; - spDx = -dx; - spDy = -dy; - } - if (yActive) { - spDx = -spDy * pw / ph; - } else { - spDy = -spDx * ph / pw; - } - } - if (xActive) { - dragAxList(xaxes, dx); - updateMatchedAxRange("x"); - } - if (yActive) { - dragAxList(yaxes, dy); - updateMatchedAxRange("y"); - } - updateSubplots([spDx, spDy, pw, ph]); - ticksAndAnnotations(); - gd.emit("plotly_relayouting", updates); - return; - } - function dz(axArray, end, d) { - var otherEnd = 1 - end; - var movedAx; - var newLinearizedEnd; - for (var i2 = 0; i2 < axArray.length; i2++) { - var axi = axArray[i2]; - if (axi.fixedrange) continue; - movedAx = axi; - newLinearizedEnd = axi._rl[otherEnd] + (axi._rl[end] - axi._rl[otherEnd]) / dZoom(d / axi._length); - var newEnd = axi.l2r(newLinearizedEnd); - if (newEnd !== false && newEnd !== void 0) axi.range[end] = newEnd; - } - return movedAx._length * (movedAx._rl[end] - newLinearizedEnd) / (movedAx._rl[end] - movedAx._rl[otherEnd]); - } - var dxySign = xActive === "w" === (yActive === "n") ? 1 : -1; - if (xActive && yActive && (links.isSubplotConstrained || matches.isSubplotConstrained)) { - var dxyFraction = (dx / pw + dxySign * dy / ph) / 2; - dx = dxyFraction * pw; - dy = dxySign * dxyFraction * ph; - } - var xStart, yStart; - if (xActive === "w") dx = dz(xaxes, 0, dx); - else if (xActive === "e") dx = dz(xaxes, 1, -dx); - else if (!xActive) dx = 0; - if (yActive === "n") dy = dz(yaxes, 1, dy); - else if (yActive === "s") dy = dz(yaxes, 0, -dy); - else if (!yActive) dy = 0; - xStart = xActive === "w" ? dx : 0; - yStart = yActive === "n" ? dy : 0; - if (links.isSubplotConstrained && !matches.isSubplotConstrained || // NW or SE on matching axes - create a symmetric zoom - matches.isSubplotConstrained && xActive && yActive && dxySign > 0) { - var i; - if (matches.isSubplotConstrained || !xActive && yActive.length === 1) { - for (i = 0; i < xaxes.length; i++) { - xaxes[i].range = xaxes[i]._r.slice(); - scaleZoom3(xaxes[i], 1 - dy / ph); - } - dx = dy * pw / ph; - xStart = dx / 2; - } - if (matches.isSubplotConstrained || !yActive && xActive.length === 1) { - for (i = 0; i < yaxes.length; i++) { - yaxes[i].range = yaxes[i]._r.slice(); - scaleZoom3(yaxes[i], 1 - dx / pw); - } - dy = dx * ph / pw; - yStart = dy / 2; - } - } - if (!matches.isSubplotConstrained || !yActive) { - updateMatchedAxRange("x"); - } - if (!matches.isSubplotConstrained || !xActive) { - updateMatchedAxRange("y"); - } - var xSize = pw - dx; - var ySize = ph - dy; - if (matches.isSubplotConstrained && !(xActive && yActive)) { - if (xActive) { - yStart = xStart ? 0 : dx * ph / pw; - ySize = xSize * ph / pw; - } else { - xStart = yStart ? 0 : dy * pw / ph; - xSize = ySize * pw / ph; - } - } - updateSubplots([xStart, yStart, xSize, ySize]); - ticksAndAnnotations(); - gd.emit("plotly_relayouting", updates); - } - function updateMatchedAxRange(axLetter, out) { - var matchedAxes = matches.isSubplotConstrained ? { x: yaxes, y: xaxes }[axLetter] : matches[axLetter + "axes"]; - var constrainedAxes = matches.isSubplotConstrained ? { x: xaxes, y: yaxes }[axLetter] : []; - for (var i = 0; i < matchedAxes.length; i++) { - var ax = matchedAxes[i]; - var axId = ax._id; - var axId2 = matches.xLinks[axId] || matches.yLinks[axId]; - var ax2 = constrainedAxes[0] || xaHash[axId2] || yaHash[axId2]; - if (ax2) { - if (out) { - out[ax._name + ".range[0]"] = out[ax2._name + ".range[0]"]; - out[ax._name + ".range[1]"] = out[ax2._name + ".range[1]"]; - } else { - ax.range = ax2.range.slice(); - } - } - } - } - function ticksAndAnnotations() { - var activeAxIds = []; - var i; - function pushActiveAxIds(axList) { - for (i = 0; i < axList.length; i++) { - if (!axList[i].fixedrange) activeAxIds.push(axList[i]._id); - } - } - function pushActiveAxIdsSynced(axList, axisType) { - for (i = 0; i < axList.length; i++) { - var axListI = axList[i]; - var axListIType = axListI[axisType]; - if (!axListI.fixedrange && axListIType.tickmode === "sync") activeAxIds.push(axListIType._id); - } - } - if (editX) { - pushActiveAxIds(xaxes); - pushActiveAxIds(links.xaxes); - pushActiveAxIds(matches.xaxes); - pushActiveAxIdsSynced(plotinfo.overlays, "xaxis"); - } - if (editY) { - pushActiveAxIds(yaxes); - pushActiveAxIds(links.yaxes); - pushActiveAxIds(matches.yaxes); - pushActiveAxIdsSynced(plotinfo.overlays, "yaxis"); - } - updates = {}; - for (i = 0; i < activeAxIds.length; i++) { - var axId = activeAxIds[i]; - var ax = getFromId2(gd, axId); - Axes2.drawOne(gd, ax, { skipTitle: true }); - updates[ax._name + ".range[0]"] = ax.range[0]; - updates[ax._name + ".range[1]"] = ax.range[1]; - } - Axes2.redrawComponents(gd, activeAxIds); - } - function doubleClick() { - if (gd._transitioningWithDuration) return; - var doubleClickConfig = gd._context.doubleClick; - var axList = []; - if (xActive) axList = axList.concat(xaxes); - if (yActive) axList = axList.concat(yaxes); - if (matches.xaxes) axList = axList.concat(matches.xaxes); - if (matches.yaxes) axList = axList.concat(matches.yaxes); - var attrs2 = {}; - var ax, i; - if (doubleClickConfig === "reset+autosize") { - doubleClickConfig = "autosize"; - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - var r0 = ax._rangeInitial0; - var r1 = ax._rangeInitial1; - var hasRangeInitial = r0 !== void 0 || r1 !== void 0; - if (hasRangeInitial && (r0 !== void 0 && r0 !== ax.range[0] || r1 !== void 0 && r1 !== ax.range[1]) || !hasRangeInitial && ax.autorange !== true) { - doubleClickConfig = "reset"; - break; - } - } - } - if (doubleClickConfig === "autosize") { - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - if (!ax.fixedrange) attrs2[ax._name + ".autorange"] = true; - } - } else if (doubleClickConfig === "reset") { - if (xActive || links.isSubplotConstrained) axList = axList.concat(links.xaxes); - if (yActive && !links.isSubplotConstrained) axList = axList.concat(links.yaxes); - if (links.isSubplotConstrained) { - if (!xActive) axList = axList.concat(xaxes); - else if (!yActive) axList = axList.concat(yaxes); - } - for (i = 0; i < axList.length; i++) { - ax = axList[i]; - if (!ax.fixedrange) { - var axName = ax._name; - var autorangeInitial = ax._autorangeInitial; - if (ax._rangeInitial0 === void 0 && ax._rangeInitial1 === void 0) { - attrs2[axName + ".autorange"] = true; - } else if (ax._rangeInitial0 === void 0) { - attrs2[axName + ".autorange"] = autorangeInitial; - attrs2[axName + ".range"] = [null, ax._rangeInitial1]; - } else if (ax._rangeInitial1 === void 0) { - attrs2[axName + ".range"] = [ax._rangeInitial0, null]; - attrs2[axName + ".autorange"] = autorangeInitial; - } else { - attrs2[axName + ".range"] = [ax._rangeInitial0, ax._rangeInitial1]; - } - } - } - } - gd.emit("plotly_doubleclick", null); - Registry2.call("_guiRelayout", gd, attrs2); - } - function dragTail() { - updateSubplots([0, 0, pw, ph]); - Lib2.syncOrAsync([ - Plots2.previousPromises, - function() { - gd._fullLayout._replotting = false; - Registry2.call("_guiRelayout", gd, updates); - } - ], gd); - } - function updateSubplots(viewBox) { - var fullLayout = gd._fullLayout; - var plotinfos = fullLayout._plots; - var subplots = fullLayout._subplots.cartesian; - var i, sp, xa, ya; - if (hasSplom) { - Registry2.subplotsRegistry.splom.drag(gd); - } - if (hasScatterGl) { - for (i = 0; i < subplots.length; i++) { - sp = plotinfos[subplots[i]]; - xa = sp.xaxis; - ya = sp.yaxis; - if (sp._scene) { - if (xa.limitRange) xa.limitRange(); - if (ya.limitRange) ya.limitRange(); - var xrng = Lib2.simpleMap(xa.range, xa.r2l); - var yrng = Lib2.simpleMap(ya.range, ya.r2l); - sp._scene.update({ range: [xrng[0], yrng[0], xrng[1], yrng[1]] }); - } - } - } - if (hasSplom || hasScatterGl) { - clearGlCanvases3(gd); - redrawReglTraces2(gd); - } - if (hasSVG) { - var xScaleFactor = viewBox[2] / xa0._length; - var yScaleFactor = viewBox[3] / ya0._length; - for (i = 0; i < subplots.length; i++) { - sp = plotinfos[subplots[i]]; - xa = sp.xaxis; - ya = sp.yaxis; - var editX2 = (editX || matches.isSubplotConstrained) && !xa.fixedrange && xaHash[xa._id]; - var editY2 = (editY || matches.isSubplotConstrained) && !ya.fixedrange && yaHash[ya._id]; - var xScaleFactor2, yScaleFactor2; - var clipDx, clipDy; - if (editX2) { - xScaleFactor2 = xScaleFactor; - clipDx = ew || matches.isSubplotConstrained ? viewBox[0] : getShift(xa, xScaleFactor2); - } else if (matches.xaHash[xa._id]) { - xScaleFactor2 = xScaleFactor; - clipDx = viewBox[0] * xa._length / xa0._length; - } else if (matches.yaHash[xa._id]) { - xScaleFactor2 = yScaleFactor; - clipDx = yActive === "ns" ? -viewBox[1] * xa._length / ya0._length : getShift(xa, xScaleFactor2, { n: "top", s: "bottom" }[yActive]); - } else { - xScaleFactor2 = getLinkedScaleFactor(xa, xScaleFactor, yScaleFactor); - clipDx = scaleAndGetShift(xa, xScaleFactor2); - } - if (xScaleFactor2 > 1 && (xa.maxallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "e" : "w") || xa.minallowed !== void 0 && editX === (xa.range[0] < xa.range[1] ? "w" : "e"))) { - xScaleFactor2 = 1; - clipDx = 0; - } - if (editY2) { - yScaleFactor2 = yScaleFactor; - clipDy = ns || matches.isSubplotConstrained ? viewBox[1] : getShift(ya, yScaleFactor2); - } else if (matches.yaHash[ya._id]) { - yScaleFactor2 = yScaleFactor; - clipDy = viewBox[1] * ya._length / ya0._length; - } else if (matches.xaHash[ya._id]) { - yScaleFactor2 = xScaleFactor; - clipDy = xActive === "ew" ? -viewBox[0] * ya._length / xa0._length : getShift(ya, yScaleFactor2, { e: "right", w: "left" }[xActive]); - } else { - yScaleFactor2 = getLinkedScaleFactor(ya, xScaleFactor, yScaleFactor); - clipDy = scaleAndGetShift(ya, yScaleFactor2); - } - if (yScaleFactor2 > 1 && (ya.maxallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "n" : "s") || ya.minallowed !== void 0 && editY === (ya.range[0] < ya.range[1] ? "s" : "n"))) { - yScaleFactor2 = 1; - clipDy = 0; - } - if (!xScaleFactor2 && !yScaleFactor2) { - continue; - } - if (!xScaleFactor2) xScaleFactor2 = 1; - if (!yScaleFactor2) yScaleFactor2 = 1; - var plotDx = xa._offset - clipDx / xScaleFactor2; - var plotDy = ya._offset - clipDy / yScaleFactor2; - sp.clipRect.call(Drawing2.setTranslate, clipDx, clipDy).call(Drawing2.setScale, xScaleFactor2, yScaleFactor2); - sp.plot.call(Drawing2.setTranslate, plotDx, plotDy).call(Drawing2.setScale, 1 / xScaleFactor2, 1 / yScaleFactor2); - if (xScaleFactor2 !== sp.xScaleFactor || yScaleFactor2 !== sp.yScaleFactor) { - Drawing2.setPointGroupScale(sp.zoomScalePts, xScaleFactor2, yScaleFactor2); - Drawing2.setTextPointsScale(sp.zoomScaleTxt, xScaleFactor2, yScaleFactor2); - } - Drawing2.hideOutsideRangePoints(sp.clipOnAxisFalseTraces, sp); - sp.xScaleFactor = xScaleFactor2; - sp.yScaleFactor = yScaleFactor2; - } - } - } - function getLinkedScaleFactor(ax, xScaleFactor, yScaleFactor) { - if (ax.fixedrange) return 0; - if (editX && links.xaHash[ax._id]) { - return xScaleFactor; - } - if (editY && (links.isSubplotConstrained ? links.xaHash : links.yaHash)[ax._id]) { - return yScaleFactor; - } - return 0; - } - function scaleAndGetShift(ax, scaleFactor) { - if (scaleFactor) { - ax.range = ax._r.slice(); - scaleZoom3(ax, scaleFactor); - return getShift(ax, scaleFactor); - } - return 0; - } - function getShift(ax, scaleFactor, from) { - return ax._length * (1 - scaleFactor) * FROM_TL2[from || ax.constraintoward || "middle"]; - } - return dragger; - } - function makeDragger(plotinfo, nodeName, dragClass, cursor2) { - var dragger3 = Lib2.ensureSingle(plotinfo.draglayer, nodeName, dragClass, function(s) { - s.classed("drag", true).style({ fill: "transparent", "stroke-width": 0 }).attr("data-subplot", plotinfo.id); - }); - dragger3.call(setCursor3, cursor2); - return dragger3.node(); - } - function makeRectDragger(plotinfo, dragClass, cursor2, x, y, w, h) { - var dragger = makeDragger(plotinfo, "rect", dragClass, cursor2); - d32.select(dragger).call(Drawing2.setRect, x, y, w, h); - return dragger; - } - function isDirectionActive(axList, activeVal) { - for (var i = 0; i < axList.length; i++) { - if (!axList[i].fixedrange) return activeVal; - } - return ""; - } - function getEndText(ax, end) { - var initialVal = ax.range[end]; - var diff = Math.abs(initialVal - ax.range[1 - end]); - var dig; - if (ax.type === "date") { - return initialVal; - } else if (ax.type === "log") { - dig = Math.ceil(Math.max(0, -Math.log(diff) / Math.LN10)) + 3; - return numberFormat2("." + dig + "g")(Math.pow(10, initialVal)); - } else { - dig = Math.floor(Math.log(Math.abs(initialVal)) / Math.LN10) - Math.floor(Math.log(diff) / Math.LN10) + 4; - return numberFormat2("." + String(dig) + "g")(initialVal); - } - } - function zoomAxRanges(axList, r0Fraction, r1Fraction, updates, linkedAxes) { - for (var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if (axi.fixedrange) continue; - if (axi.rangebreaks) { - var isY = axi._id.charAt(0) === "y"; - var r0F = isY ? 1 - r0Fraction : r0Fraction; - var r1F = isY ? 1 - r1Fraction : r1Fraction; - updates[axi._name + ".range[0]"] = axi.l2r(axi.p2l(r0F * axi._length)); - updates[axi._name + ".range[1]"] = axi.l2r(axi.p2l(r1F * axi._length)); - } else { - var axRangeLinear0 = axi._rl[0]; - var axRangeLinearSpan = axi._rl[1] - axRangeLinear0; - updates[axi._name + ".range[0]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r0Fraction); - updates[axi._name + ".range[1]"] = axi.l2r(axRangeLinear0 + axRangeLinearSpan * r1Fraction); - } - } - if (linkedAxes && linkedAxes.length) { - var linkedR0Fraction = (r0Fraction + (1 - r1Fraction)) / 2; - zoomAxRanges(linkedAxes, linkedR0Fraction, 1 - linkedR0Fraction, updates, []); - } - } - function dragAxList(axList, pix) { - for (var i = 0; i < axList.length; i++) { - var axi = axList[i]; - if (!axi.fixedrange) { - if (axi.rangebreaks) { - var p0 = 0; - var p1 = axi._length; - var d0 = axi.p2l(p0 + pix) - axi.p2l(p0); - var d1 = axi.p2l(p1 + pix) - axi.p2l(p1); - var delta2 = (d0 + d1) / 2; - axi.range = [ - axi.l2r(axi._rl[0] - delta2), - axi.l2r(axi._rl[1] - delta2) - ]; - } else { - axi.range = [ - axi.l2r(axi._rl[0] - pix / axi._m), - axi.l2r(axi._rl[1] - pix / axi._m) - ]; - } - if (axi.limitRange) axi.limitRange(); - } - } - } - function dZoom(d) { - return 1 - (d >= 0 ? Math.min(d, 0.9) : 1 / (1 / Math.max(d, -0.3) + 3.222)); - } - function getDragCursor(nsew, dragmode, isMainDrag) { - if (!nsew) return "pointer"; - if (nsew === "nsew") { - if (isMainDrag) return ""; - if (dragmode === "pan") return "move"; - return "crosshair"; - } - return nsew.toLowerCase() + "-resize"; - } - function makeZoombox(zoomlayer, lum, xs, ys, path0) { - return zoomlayer.append("path").attr("class", "zoombox").style({ - fill: lum > 0.2 ? "rgba(0,0,0,0)" : "rgba(255,255,255,0)", - "stroke-width": 0 - }).attr("transform", strTranslate2(xs, ys)).attr("d", path0 + "Z"); - } - function makeCorners(zoomlayer, xs, ys) { - return zoomlayer.append("path").attr("class", "zoombox-corners").style({ - fill: Color2.background, - stroke: Color2.defaultLine, - "stroke-width": 1, - opacity: 0 - }).attr("transform", strTranslate2(xs, ys)).attr("d", "M0,0Z"); - } - function updateZoombox(zb, corners, box, path0, dimmed, lum) { - zb.attr( - "d", - path0 + "M" + box.l + "," + box.t + "v" + box.h + "h" + box.w + "v-" + box.h + "h-" + box.w + "Z" - ); - transitionZoombox(zb, corners, dimmed, lum); - } - function transitionZoombox(zb, corners, dimmed, lum) { - if (!dimmed) { - zb.transition().style("fill", lum > 0.2 ? "rgba(0,0,0,0.4)" : "rgba(255,255,255,0.3)").duration(200); - corners.transition().style("opacity", 1).duration(200); - } - } - function removeZoombox(gd) { - d32.select(gd).selectAll(".zoombox,.js-zoombox-backdrop,.js-zoombox-menu,.zoombox-corners").remove(); - } - function showDoubleClickNotifier(gd) { - if (SHOWZOOMOUTTIP && gd.data && gd._context.showTips) { - Lib2.notifier(Lib2._(gd, "Double-click to zoom back out"), "long"); - SHOWZOOMOUTTIP = false; - } - } - function xCorners(box, y0) { - return "M" + (box.l - 0.5) + "," + (y0 - MINZOOM - 0.5) + "h-3v" + (2 * MINZOOM + 1) + "h3ZM" + (box.r + 0.5) + "," + (y0 - MINZOOM - 0.5) + "h3v" + (2 * MINZOOM + 1) + "h-3Z"; - } - function yCorners(box, x0) { - return "M" + (x0 - MINZOOM - 0.5) + "," + (box.t - 0.5) + "v-3h" + (2 * MINZOOM + 1) + "v3ZM" + (x0 - MINZOOM - 0.5) + "," + (box.b + 0.5) + "v3h" + (2 * MINZOOM + 1) + "v-3Z"; - } - function xyCorners(box) { - var clen = Math.floor(Math.min(box.b - box.t, box.r - box.l, MINZOOM) / 2); - return "M" + (box.l - 3.5) + "," + (box.t - 0.5 + clen) + "h3v" + -clen + "h" + clen + "v-3h-" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.t - 0.5 + clen) + "h-3v" + -clen + "h" + -clen + "v-3h" + (clen + 3) + "ZM" + (box.r + 3.5) + "," + (box.b + 0.5 - clen) + "h-3v" + clen + "h" + -clen + "v3h" + (clen + 3) + "ZM" + (box.l - 3.5) + "," + (box.b + 0.5 - clen) + "h3v" + clen + "h" + clen + "v3h-" + (clen + 3) + "Z"; - } - function calcLinks(gd, groups, xaHash, yaHash, exclude) { - var isSubplotConstrained = false; - var xLinks = {}; - var yLinks = {}; - var xID, yID, xLinkID, yLinkID; - var xExclude = (exclude || {}).xaHash; - var yExclude = (exclude || {}).yaHash; - for (var i = 0; i < groups.length; i++) { - var group = groups[i]; - for (xID in xaHash) { - if (group[xID]) { - for (xLinkID in group) { - if (!(exclude && (xExclude[xLinkID] || yExclude[xLinkID])) && !(xLinkID.charAt(0) === "x" ? xaHash : yaHash)[xLinkID]) { - xLinks[xLinkID] = xID; - } - } - for (yID in yaHash) { - if (!(exclude && (xExclude[yID] || yExclude[yID])) && group[yID]) { - isSubplotConstrained = true; - } - } - } - } - for (yID in yaHash) { - if (group[yID]) { - for (yLinkID in group) { - if (!(exclude && (xExclude[yLinkID] || yExclude[yLinkID])) && !(yLinkID.charAt(0) === "x" ? xaHash : yaHash)[yLinkID]) { - yLinks[yLinkID] = yID; - } - } - } - } - } - if (isSubplotConstrained) { - Lib2.extendFlat(xLinks, yLinks); - yLinks = {}; - } - var xaHashLinked = {}; - var xaxesLinked = []; - for (xLinkID in xLinks) { - var xa = getFromId2(gd, xLinkID); - xaxesLinked.push(xa); - xaHashLinked[xa._id] = xa; - } - var yaHashLinked = {}; - var yaxesLinked = []; - for (yLinkID in yLinks) { - var ya = getFromId2(gd, yLinkID); - yaxesLinked.push(ya); - yaHashLinked[ya._id] = ya; - } - return { - xaHash: xaHashLinked, - yaHash: yaHashLinked, - xaxes: xaxesLinked, - yaxes: yaxesLinked, - xLinks, - yLinks, - isSubplotConstrained - }; - } - function attachWheelEventHandler(element, handler) { - if (!supportsPassive2) { - if (element.onwheel !== void 0) element.onwheel = handler; - else if (element.onmousewheel !== void 0) element.onmousewheel = handler; - else if (!element.isAddedWheelEvent) { - element.isAddedWheelEvent = true; - element.addEventListener("wheel", handler, { passive: false }); - } - } else { - var wheelEventName = element.onwheel !== void 0 ? "wheel" : "mousewheel"; - if (element._onwheel) { - element.removeEventListener(wheelEventName, element._onwheel); - } - element._onwheel = handler; - element.addEventListener(wheelEventName, handler, { passive: false }); - } - } - function hashValues(hash) { - var out = []; - for (var k in hash) out.push(hash[k]); - return out; - } - dragbox = { - makeDragBox, - makeDragger, - makeRectDragger, - makeZoombox, - makeCorners, - updateZoombox, - xyCorners, - transitionZoombox, - removeZoombox, - showDoubleClickNotifier, - attachWheelEventHandler - }; - return dragbox; -} -var hasRequiredGraph_interact; -function requireGraph_interact() { - if (hasRequiredGraph_interact) return graph_interact; - hasRequiredGraph_interact = 1; - (function(exports2) { - var d32 = d3Exports; - var Fx2 = fx$1; - var dragElement2 = dragelementExports; - var setCursor3 = setcursor; - var makeDragBox = requireDragbox().makeDragBox; - var DRAGGERSIZE = constants$U.DRAGGERSIZE; - exports2.initInteractions = function initInteractions(gd) { - var fullLayout = gd._fullLayout; - if (gd._context.staticPlot) { - d32.select(gd).selectAll(".drag").remove(); - return; - } - if (!fullLayout._has("cartesian") && !fullLayout._has("splom")) return; - var subplots = Object.keys(fullLayout._plots || {}).sort(function(a, b) { - if ((fullLayout._plots[a].mainplot && true) === (fullLayout._plots[b].mainplot && true)) { - var aParts = a.split("y"); - var bParts = b.split("y"); - return aParts[0] === bParts[0] ? Number(aParts[1] || 1) - Number(bParts[1] || 1) : Number(aParts[0] || 1) - Number(bParts[0] || 1); - } - return fullLayout._plots[a].mainplot ? 1 : -1; - }); - subplots.forEach(function(subplot) { - var plotinfo = fullLayout._plots[subplot]; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - if (!plotinfo.mainplot) { - var maindrag = makeDragBox( - gd, - plotinfo, - xa._offset, - ya._offset, - xa._length, - ya._length, - "ns", - "ew" - ); - maindrag.onmousemove = function(evt) { - gd._fullLayout._rehover = function() { - if (gd._fullLayout._hoversubplot === subplot && gd._fullLayout._plots[subplot]) { - Fx2.hover(gd, evt, subplot); - } - }; - Fx2.hover(gd, evt, subplot); - gd._fullLayout._lasthover = maindrag; - gd._fullLayout._hoversubplot = subplot; - }; - maindrag.onmouseout = function(evt) { - if (gd._dragging) return; - gd._fullLayout._hoversubplot = null; - dragElement2.unhover(gd, evt); - }; - if (gd._context.showAxisDragHandles) { - makeDragBox( - gd, - plotinfo, - xa._offset - DRAGGERSIZE, - ya._offset - DRAGGERSIZE, - DRAGGERSIZE, - DRAGGERSIZE, - "n", - "w" - ); - makeDragBox( - gd, - plotinfo, - xa._offset + xa._length, - ya._offset - DRAGGERSIZE, - DRAGGERSIZE, - DRAGGERSIZE, - "n", - "e" - ); - makeDragBox( - gd, - plotinfo, - xa._offset - DRAGGERSIZE, - ya._offset + ya._length, - DRAGGERSIZE, - DRAGGERSIZE, - "s", - "w" - ); - makeDragBox( - gd, - plotinfo, - xa._offset + xa._length, - ya._offset + ya._length, - DRAGGERSIZE, - DRAGGERSIZE, - "s", - "e" - ); - } - } - if (gd._context.showAxisDragHandles) { - if (subplot === xa._mainSubplot) { - var y0 = xa._mainLinePosition; - if (xa.side === "top") y0 -= DRAGGERSIZE; - makeDragBox( - gd, - plotinfo, - xa._offset + xa._length * 0.1, - y0, - xa._length * 0.8, - DRAGGERSIZE, - "", - "ew" - ); - makeDragBox( - gd, - plotinfo, - xa._offset, - y0, - xa._length * 0.1, - DRAGGERSIZE, - "", - "w" - ); - makeDragBox( - gd, - plotinfo, - xa._offset + xa._length * 0.9, - y0, - xa._length * 0.1, - DRAGGERSIZE, - "", - "e" - ); - } - if (subplot === ya._mainSubplot) { - var x0 = ya._mainLinePosition; - if (ya.side !== "right") x0 -= DRAGGERSIZE; - makeDragBox( - gd, - plotinfo, - x0, - ya._offset + ya._length * 0.1, - DRAGGERSIZE, - ya._length * 0.8, - "ns", - "" - ); - makeDragBox( - gd, - plotinfo, - x0, - ya._offset + ya._length * 0.9, - DRAGGERSIZE, - ya._length * 0.1, - "s", - "" - ); - makeDragBox( - gd, - plotinfo, - x0, - ya._offset, - DRAGGERSIZE, - ya._length * 0.1, - "n", - "" - ); - } - } - }); - var hoverLayer = fullLayout._hoverlayer.node(); - hoverLayer.onmousemove = function(evt) { - evt.target = gd._fullLayout._lasthover; - Fx2.hover(gd, evt, fullLayout._hoversubplot); - }; - hoverLayer.onclick = function(evt) { - evt.target = gd._fullLayout._lasthover; - Fx2.click(gd, evt); - }; - hoverLayer.onmousedown = function(evt) { - gd._fullLayout._lasthover.onmousedown(evt); - }; - exports2.updateFx(gd); - }; - exports2.updateFx = function(gd) { - var fullLayout = gd._fullLayout; - var cursor2 = fullLayout.dragmode === "pan" ? "move" : "crosshair"; - setCursor3(fullLayout._draggers, cursor2); - }; - })(graph_interact); - return graph_interact; -} -var manage_arrays = {}; -var Registry$t = registry; -var container_array_match = function containerArrayMatch(astr) { - var rootContainers = Registry$t.layoutArrayContainers; - var regexpContainers = Registry$t.layoutArrayRegexes; - var rootPart = astr.split("[")[0]; - var arrayStr; - var match; - for (var i = 0; i < regexpContainers.length; i++) { - match = astr.match(regexpContainers[i]); - if (match && match.index === 0) { - arrayStr = match[0]; - break; - } - } - if (!arrayStr) arrayStr = rootContainers[rootContainers.indexOf(rootPart)]; - if (!arrayStr) return false; - var tail = astr.substr(arrayStr.length); - if (!tail) return { array: arrayStr, index: "", property: "" }; - match = tail.match(/^\[(0|[1-9][0-9]*)\](\.(.+))?$/); - if (!match) return false; - return { array: arrayStr, index: Number(match[1]), property: match[3] || "" }; -}; -var isPlainObject$2 = is_plain_object; -var noop$1 = noop$2; -var Loggers = loggersExports; -var sorterAsc = search$1.sorterAsc; -var Registry$s = registry; -manage_arrays.containerArrayMatch = container_array_match; -var isAddVal = manage_arrays.isAddVal = function isAddVal2(val) { - return val === "add" || isPlainObject$2(val); -}; -var isRemoveVal = manage_arrays.isRemoveVal = function isRemoveVal2(val) { - return val === null || val === "remove"; -}; -manage_arrays.applyContainerArrayChanges = function applyContainerArrayChanges(gd, np, edits, flags, _nestedProperty) { - var componentType = np.astr; - var supplyComponentDefaults = Registry$s.getComponentMethod(componentType, "supplyLayoutDefaults"); - var draw8 = Registry$s.getComponentMethod(componentType, "draw"); - var drawOne2 = Registry$s.getComponentMethod(componentType, "drawOne"); - var replotLater = flags.replot || flags.recalc || supplyComponentDefaults === noop$1 || draw8 === noop$1; - var layout = gd.layout; - var fullLayout = gd._fullLayout; - if (edits[""]) { - if (Object.keys(edits).length > 1) { - Loggers.warn( - "Full array edits are incompatible with other edits", - componentType - ); - } - var fullVal = edits[""][""]; - if (isRemoveVal(fullVal)) np.set(null); - else if (Array.isArray(fullVal)) np.set(fullVal); - else { - Loggers.warn("Unrecognized full array edit value", componentType, fullVal); - return true; - } - if (replotLater) return false; - supplyComponentDefaults(layout, fullLayout); - draw8(gd); - return true; - } - var componentNums = Object.keys(edits).map(Number).sort(sorterAsc); - var componentArrayIn = np.get(); - var componentArray = componentArrayIn || []; - var componentArrayFull = _nestedProperty(fullLayout, componentType).get(); - var deletes = []; - var firstIndexChange = -1; - var maxIndex = componentArray.length; - var i; - var j; - var componentNum; - var objEdits; - var objKeys; - var objVal; - var adding, prefix; - for (i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - objEdits = edits[componentNum]; - objKeys = Object.keys(objEdits); - objVal = objEdits[""], adding = isAddVal(objVal); - if (componentNum < 0 || componentNum > componentArray.length - (adding ? 0 : 1)) { - Loggers.warn("index out of range", componentType, componentNum); - continue; - } - if (objVal !== void 0) { - if (objKeys.length > 1) { - Loggers.warn( - "Insertion & removal are incompatible with edits to the same index.", - componentType, - componentNum - ); - } - if (isRemoveVal(objVal)) { - deletes.push(componentNum); - } else if (adding) { - if (objVal === "add") objVal = {}; - componentArray.splice(componentNum, 0, objVal); - if (componentArrayFull) componentArrayFull.splice(componentNum, 0, {}); - } else { - Loggers.warn( - "Unrecognized full object edit value", - componentType, - componentNum, - objVal - ); - } - if (firstIndexChange === -1) firstIndexChange = componentNum; - } else { - for (j = 0; j < objKeys.length; j++) { - prefix = componentType + "[" + componentNum + "]."; - _nestedProperty(componentArray[componentNum], objKeys[j], prefix).set(objEdits[objKeys[j]]); - } - } - } - for (i = deletes.length - 1; i >= 0; i--) { - componentArray.splice(deletes[i], 1); - if (componentArrayFull) componentArrayFull.splice(deletes[i], 1); - } - if (!componentArray.length) np.set(null); - else if (!componentArrayIn) np.set(componentArray); - if (replotLater) return false; - supplyComponentDefaults(layout, fullLayout); - if (drawOne2 !== noop$1) { - var indicesToDraw; - if (firstIndexChange === -1) { - indicesToDraw = componentNums; - } else { - maxIndex = Math.max(componentArray.length, maxIndex); - indicesToDraw = []; - for (i = 0; i < componentNums.length; i++) { - componentNum = componentNums[i]; - if (componentNum >= firstIndexChange) break; - indicesToDraw.push(componentNum); - } - for (i = firstIndexChange; i < maxIndex; i++) { - indicesToDraw.push(i); - } - } - for (i = 0; i < indicesToDraw.length; i++) { - drawOne2(gd, indicesToDraw[i]); - } - } else draw8(gd); - return true; -}; -var helpers$p = {}; -(function(exports2) { - var isNumeric2 = fastIsnumeric; - var m4FromQuat = fromQuat_1; - var Registry2 = registry; - var Lib2 = libExports; - var Plots2 = plotsExports; - var AxisIds = axis_ids; - var Color2 = colorExports; - var cleanId = AxisIds.cleanId; - var getFromTrace = AxisIds.getFromTrace; - var traceIs2 = Registry2.traceIs; - exports2.clearPromiseQueue = function(gd) { - if (Array.isArray(gd._promises) && gd._promises.length > 0) { - Lib2.log("Clearing previous rejected promises from queue."); - } - gd._promises = []; - }; - exports2.cleanLayout = function(layout) { - var i, j; - if (!layout) layout = {}; - if (layout.xaxis1) { - if (!layout.xaxis) layout.xaxis = layout.xaxis1; - delete layout.xaxis1; - } - if (layout.yaxis1) { - if (!layout.yaxis) layout.yaxis = layout.yaxis1; - delete layout.yaxis1; - } - if (layout.scene1) { - if (!layout.scene) layout.scene = layout.scene1; - delete layout.scene1; - } - var axisAttrRegex = (Plots2.subplotsRegistry.cartesian || {}).attrRegex; - var polarAttrRegex = (Plots2.subplotsRegistry.polar || {}).attrRegex; - var ternaryAttrRegex = (Plots2.subplotsRegistry.ternary || {}).attrRegex; - var sceneAttrRegex = (Plots2.subplotsRegistry.gl3d || {}).attrRegex; - var keys = Object.keys(layout); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - if (axisAttrRegex && axisAttrRegex.test(key)) { - var ax = layout[key]; - if (ax.anchor && ax.anchor !== "free") { - ax.anchor = cleanId(ax.anchor); - } - if (ax.overlaying) ax.overlaying = cleanId(ax.overlaying); - if (!ax.type) { - if (ax.isdate) ax.type = "date"; - else if (ax.islog) ax.type = "log"; - else if (ax.isdate === false && ax.islog === false) ax.type = "linear"; - } - if (ax.autorange === "withzero" || ax.autorange === "tozero") { - ax.autorange = true; - ax.rangemode = "tozero"; - } - if (ax.insiderange) delete ax.range; - delete ax.islog; - delete ax.isdate; - delete ax.categories; - if (emptyContainer(ax, "domain")) delete ax.domain; - if (ax.autotick !== void 0) { - if (ax.tickmode === void 0) { - ax.tickmode = ax.autotick ? "auto" : "linear"; - } - delete ax.autotick; - } - cleanTitle(ax); - } else if (polarAttrRegex && polarAttrRegex.test(key)) { - var polar = layout[key]; - cleanTitle(polar.radialaxis); - } else if (ternaryAttrRegex && ternaryAttrRegex.test(key)) { - var ternary = layout[key]; - cleanTitle(ternary.aaxis); - cleanTitle(ternary.baxis); - cleanTitle(ternary.caxis); - } else if (sceneAttrRegex && sceneAttrRegex.test(key)) { - var scene = layout[key]; - var cameraposition = scene.cameraposition; - if (Array.isArray(cameraposition) && cameraposition[0].length === 4) { - var rotation = cameraposition[0]; - var center = cameraposition[1]; - var radius = cameraposition[2]; - var mat = m4FromQuat([], rotation); - var eye = []; - for (j = 0; j < 3; ++j) { - eye[j] = center[j] + radius * mat[2 + 4 * j]; - } - scene.camera = { - eye: { x: eye[0], y: eye[1], z: eye[2] }, - center: { x: center[0], y: center[1], z: center[2] }, - up: { x: 0, y: 0, z: 1 } - // we just ignore calculating camera z up in this case - }; - delete scene.cameraposition; - } - cleanTitle(scene.xaxis); - cleanTitle(scene.yaxis); - cleanTitle(scene.zaxis); - } - } - var annotationsLen = Array.isArray(layout.annotations) ? layout.annotations.length : 0; - for (i = 0; i < annotationsLen; i++) { - var ann = layout.annotations[i]; - if (!Lib2.isPlainObject(ann)) continue; - if (ann.ref) { - if (ann.ref === "paper") { - ann.xref = "paper"; - ann.yref = "paper"; - } else if (ann.ref === "data") { - ann.xref = "x"; - ann.yref = "y"; - } - delete ann.ref; - } - cleanAxRef(ann, "xref"); - cleanAxRef(ann, "yref"); - } - var shapesLen = Array.isArray(layout.shapes) ? layout.shapes.length : 0; - for (i = 0; i < shapesLen; i++) { - var shape = layout.shapes[i]; - if (!Lib2.isPlainObject(shape)) continue; - cleanAxRef(shape, "xref"); - cleanAxRef(shape, "yref"); - } - var imagesLen = Array.isArray(layout.images) ? layout.images.length : 0; - for (i = 0; i < imagesLen; i++) { - var image = layout.images[i]; - if (!Lib2.isPlainObject(image)) continue; - cleanAxRef(image, "xref"); - cleanAxRef(image, "yref"); - } - var legend2 = layout.legend; - if (legend2) { - if (legend2.x > 3) { - legend2.x = 1.02; - legend2.xanchor = "left"; - } else if (legend2.x < -2) { - legend2.x = -0.02; - legend2.xanchor = "right"; - } - if (legend2.y > 3) { - legend2.y = 1.02; - legend2.yanchor = "bottom"; - } else if (legend2.y < -2) { - legend2.y = -0.02; - legend2.yanchor = "top"; - } - } - cleanTitle(layout); - if (layout.dragmode === "rotate") layout.dragmode = "orbit"; - Color2.clean(layout); - if (layout.template && layout.template.layout) { - exports2.cleanLayout(layout.template.layout); - } - return layout; - }; - function cleanAxRef(container, attr) { - var valIn = container[attr]; - var axLetter = attr.charAt(0); - if (valIn && valIn !== "paper") { - container[attr] = cleanId(valIn, axLetter, true); - } - } - function cleanTitle(titleContainer) { - if (titleContainer) { - if (typeof titleContainer.title === "string" || typeof titleContainer.title === "number") { - titleContainer.title = { - text: titleContainer.title - }; - } - rewireAttr("titlefont", "font"); - rewireAttr("titleposition", "position"); - rewireAttr("titleside", "side"); - rewireAttr("titleoffset", "offset"); - } - function rewireAttr(oldAttrName, newAttrName) { - var oldAttrSet = titleContainer[oldAttrName]; - var newAttrSet = titleContainer.title && titleContainer.title[newAttrName]; - if (oldAttrSet && !newAttrSet) { - if (!titleContainer.title) { - titleContainer.title = {}; - } - titleContainer.title[newAttrName] = titleContainer[oldAttrName]; - delete titleContainer[oldAttrName]; - } - } - } - exports2.cleanData = function(data) { - for (var tracei = 0; tracei < data.length; tracei++) { - var trace = data[tracei]; - var i; - if (trace.type === "histogramy" && "xbins" in trace && !("ybins" in trace)) { - trace.ybins = trace.xbins; - delete trace.xbins; - } - if (trace.error_y && "opacity" in trace.error_y) { - var dc = Color2.defaults; - var yeColor = trace.error_y.color || (traceIs2(trace, "bar") ? Color2.defaultLine : dc[tracei % dc.length]); - trace.error_y.color = Color2.addOpacity( - Color2.rgb(yeColor), - Color2.opacity(yeColor) * trace.error_y.opacity - ); - delete trace.error_y.opacity; - } - if ("bardir" in trace) { - if (trace.bardir === "h" && (traceIs2(trace, "bar") || trace.type.substr(0, 9) === "histogram")) { - trace.orientation = "h"; - exports2.swapXYData(trace); - } - delete trace.bardir; - } - if (trace.type === "histogramy") exports2.swapXYData(trace); - if (trace.type === "histogramx" || trace.type === "histogramy") { - trace.type = "histogram"; - } - if ("scl" in trace && !("colorscale" in trace)) { - trace.colorscale = trace.scl; - delete trace.scl; - } - if ("reversescl" in trace && !("reversescale" in trace)) { - trace.reversescale = trace.reversescl; - delete trace.reversescl; - } - if (trace.xaxis) trace.xaxis = cleanId(trace.xaxis, "x"); - if (trace.yaxis) trace.yaxis = cleanId(trace.yaxis, "y"); - if (traceIs2(trace, "gl3d") && trace.scene) { - trace.scene = Plots2.subplotsRegistry.gl3d.cleanId(trace.scene); - } - if (!traceIs2(trace, "pie-like") && !traceIs2(trace, "bar-like")) { - if (Array.isArray(trace.textposition)) { - for (i = 0; i < trace.textposition.length; i++) { - trace.textposition[i] = cleanTextPosition(trace.textposition[i]); - } - } else if (trace.textposition) { - trace.textposition = cleanTextPosition(trace.textposition); - } - } - var _module = Registry2.getModule(trace); - if (_module && _module.colorbar) { - var containerName = _module.colorbar.container; - var container = containerName ? trace[containerName] : trace; - if (container && container.colorscale) { - if (container.colorscale === "YIGnBu") container.colorscale = "YlGnBu"; - if (container.colorscale === "YIOrRd") container.colorscale = "YlOrRd"; - } - } - if (trace.type === "surface" && Lib2.isPlainObject(trace.contours)) { - var dims = ["x", "y", "z"]; - for (i = 0; i < dims.length; i++) { - var opts = trace.contours[dims[i]]; - if (!Lib2.isPlainObject(opts)) continue; - if (opts.highlightColor) { - opts.highlightcolor = opts.highlightColor; - delete opts.highlightColor; - } - if (opts.highlightWidth) { - opts.highlightwidth = opts.highlightWidth; - delete opts.highlightWidth; - } - } - } - if (trace.type === "candlestick" || trace.type === "ohlc") { - var increasingShowlegend = (trace.increasing || {}).showlegend !== false; - var decreasingShowlegend = (trace.decreasing || {}).showlegend !== false; - var increasingName = cleanFinanceDir(trace.increasing); - var decreasingName = cleanFinanceDir(trace.decreasing); - if (increasingName !== false && decreasingName !== false) { - var newName = commonPrefix( - increasingName, - decreasingName, - increasingShowlegend, - decreasingShowlegend - ); - if (newName) trace.name = newName; - } else if ((increasingName || decreasingName) && !trace.name) { - trace.name = increasingName || decreasingName; - } - } - if (Array.isArray(trace.transforms)) { - var transforms = trace.transforms; - for (i = 0; i < transforms.length; i++) { - var transform = transforms[i]; - if (!Lib2.isPlainObject(transform)) continue; - switch (transform.type) { - case "filter": - if (transform.filtersrc) { - transform.target = transform.filtersrc; - delete transform.filtersrc; - } - if (transform.calendar) { - if (!transform.valuecalendar) { - transform.valuecalendar = transform.calendar; - } - delete transform.calendar; - } - break; - case "groupby": - transform.styles = transform.styles || transform.style; - if (transform.styles && !Array.isArray(transform.styles)) { - var prevStyles = transform.styles; - var styleKeys = Object.keys(prevStyles); - transform.styles = []; - for (var j = 0; j < styleKeys.length; j++) { - transform.styles.push({ - target: styleKeys[j], - value: prevStyles[styleKeys[j]] - }); - } - } - break; - } - } - } - if (emptyContainer(trace, "line")) delete trace.line; - if ("marker" in trace) { - if (emptyContainer(trace.marker, "line")) delete trace.marker.line; - if (emptyContainer(trace, "marker")) delete trace.marker; - } - Color2.clean(trace); - if (trace.autobinx) { - delete trace.autobinx; - delete trace.xbins; - } - if (trace.autobiny) { - delete trace.autobiny; - delete trace.ybins; - } - cleanTitle(trace); - if (trace.colorbar) cleanTitle(trace.colorbar); - if (trace.marker && trace.marker.colorbar) cleanTitle(trace.marker.colorbar); - if (trace.line && trace.line.colorbar) cleanTitle(trace.line.colorbar); - if (trace.aaxis) cleanTitle(trace.aaxis); - if (trace.baxis) cleanTitle(trace.baxis); - } - }; - function cleanFinanceDir(dirContainer) { - if (!Lib2.isPlainObject(dirContainer)) return false; - var dirName = dirContainer.name; - delete dirContainer.name; - delete dirContainer.showlegend; - return (typeof dirName === "string" || typeof dirName === "number") && String(dirName); - } - function commonPrefix(name1, name2, show1, show2) { - if (show1 && !show2) return name1; - if (show2 && !show1) return name2; - if (!name1.trim()) return name2; - if (!name2.trim()) return name1; - var minLen = Math.min(name1.length, name2.length); - var i; - for (i = 0; i < minLen; i++) { - if (name1.charAt(i) !== name2.charAt(i)) break; - } - var out = name1.substr(0, i); - return out.trim(); - } - function cleanTextPosition(textposition) { - var posY = "middle"; - var posX = "center"; - if (typeof textposition === "string") { - if (textposition.indexOf("top") !== -1) posY = "top"; - else if (textposition.indexOf("bottom") !== -1) posY = "bottom"; - if (textposition.indexOf("left") !== -1) posX = "left"; - else if (textposition.indexOf("right") !== -1) posX = "right"; - } - return posY + " " + posX; - } - function emptyContainer(outer, innerStr) { - return innerStr in outer && typeof outer[innerStr] === "object" && Object.keys(outer[innerStr]).length === 0; - } - exports2.swapXYData = function(trace) { - var i; - Lib2.swapAttrs(trace, ["?", "?0", "d?", "?bins", "nbins?", "autobin?", "?src", "error_?"]); - if (Array.isArray(trace.z) && Array.isArray(trace.z[0])) { - if (trace.transpose) delete trace.transpose; - else trace.transpose = true; - } - if (trace.error_x && trace.error_y) { - var errorY = trace.error_y; - var copyYstyle = "copy_ystyle" in errorY ? errorY.copy_ystyle : !(errorY.color || errorY.thickness || errorY.width); - Lib2.swapAttrs(trace, ["error_?.copy_ystyle"]); - if (copyYstyle) { - Lib2.swapAttrs(trace, ["error_?.color", "error_?.thickness", "error_?.width"]); - } - } - if (typeof trace.hoverinfo === "string") { - var hoverInfoParts = trace.hoverinfo.split("+"); - for (i = 0; i < hoverInfoParts.length; i++) { - if (hoverInfoParts[i] === "x") hoverInfoParts[i] = "y"; - else if (hoverInfoParts[i] === "y") hoverInfoParts[i] = "x"; - } - trace.hoverinfo = hoverInfoParts.join("+"); - } - }; - exports2.coerceTraceIndices = function(gd, traceIndices) { - if (isNumeric2(traceIndices)) { - return [traceIndices]; - } else if (!Array.isArray(traceIndices) || !traceIndices.length) { - return gd.data.map(function(_2, i2) { - return i2; - }); - } else if (Array.isArray(traceIndices)) { - var traceIndicesOut = []; - for (var i = 0; i < traceIndices.length; i++) { - if (Lib2.isIndex(traceIndices[i], gd.data.length)) { - traceIndicesOut.push(traceIndices[i]); - } else { - Lib2.warn("trace index (", traceIndices[i], ") is not a number or is out of bounds"); - } - } - return traceIndicesOut; - } - return traceIndices; - }; - exports2.manageArrayContainers = function(np, newVal, undoit) { - var obj = np.obj; - var parts = np.parts; - var pLength = parts.length; - var pLast = parts[pLength - 1]; - var pLastIsNumber = isNumeric2(pLast); - if (pLastIsNumber && newVal === null) { - var contPath = parts.slice(0, pLength - 1).join("."); - var cont = Lib2.nestedProperty(obj, contPath).get(); - cont.splice(pLast, 1); - } else if (pLastIsNumber && np.get() === void 0) { - if (np.get() === void 0) undoit[np.astr] = null; - np.set(newVal); - } else { - np.set(newVal); - } - }; - var ATTR_TAIL_RE = /(\.[^\[\]\.]+|\[[^\[\]\.]+\])$/; - function getParent(attr) { - var tail = attr.search(ATTR_TAIL_RE); - if (tail > 0) return attr.substr(0, tail); - } - exports2.hasParent = function(aobj, attr) { - var attrParent = getParent(attr); - while (attrParent) { - if (attrParent in aobj) return true; - attrParent = getParent(attrParent); - } - return false; - }; - var axLetters2 = ["x", "y", "z"]; - exports2.clearAxisTypes = function(gd, traces, layoutUpdate) { - for (var i = 0; i < traces.length; i++) { - var trace = gd._fullData[i]; - for (var j = 0; j < 3; j++) { - var ax = getFromTrace(gd, trace, axLetters2[j]); - if (ax && ax.type !== "log") { - var axAttr = ax._name; - var sceneName = ax._id.substr(1); - if (sceneName.substr(0, 5) === "scene") { - if (layoutUpdate[sceneName] !== void 0) continue; - axAttr = sceneName + "." + axAttr; - } - var typeAttr = axAttr + ".type"; - if (layoutUpdate[axAttr] === void 0 && layoutUpdate[typeAttr] === void 0) { - Lib2.nestedProperty(gd.layout, typeAttr).set(null); - } - } - } - } - }; -})(helpers$p); -(function(exports2) { - var d32 = d3Exports; - var isNumeric2 = fastIsnumeric; - var hasHover2 = hasHover_1; - var Lib2 = libExports; - var nestedProperty3 = Lib2.nestedProperty; - var Events2 = events; - var Queue = queue_1; - var Registry2 = registry; - var PlotSchema2 = plot_schema; - var Plots2 = plotsExports; - var Axes2 = axesExports; - var handleRangeDefaults3 = range_defaults; - var cartesianLayoutAttributes = layout_attributes$4; - var Drawing2 = drawingExports; - var Color2 = colorExports; - var initInteractions = requireGraph_interact().initInteractions; - var xmlnsNamespaces2 = xmlns_namespaces; - var clearOutline2 = selections.clearOutline; - var dfltConfig2 = plot_config.dfltConfig; - var manageArrays = manage_arrays; - var helpers2 = helpers$p; - var subroutines$1 = subroutines; - var editTypes = edit_types; - var AX_NAME_PATTERN = constants$U.AX_NAME_PATTERN; - var numericNameWarningCount = 0; - var numericNameWarningCountLimit = 5; - function _doPlot(gd, data, layout, config) { - var frames; - gd = Lib2.getGraphDiv(gd); - Events2.init(gd); - if (Lib2.isPlainObject(data)) { - var obj = data; - data = obj.data; - layout = obj.layout; - config = obj.config; - frames = obj.frames; - } - var okToPlot = Events2.triggerHandler(gd, "plotly_beforeplot", [data, layout, config]); - if (okToPlot === false) return Promise.reject(); - if (!data && !layout && !Lib2.isPlotDiv(gd)) { - Lib2.warn("Calling _doPlot as if redrawing but this container doesn't yet have a plot.", gd); - } - function addFrames2() { - if (frames) { - return exports2.addFrames(gd, frames); - } - } - setPlotContext(gd, config); - if (!layout) layout = {}; - d32.select(gd).classed("js-plotly-plot", true); - Drawing2.makeTester(); - if (!Array.isArray(gd._promises)) gd._promises = []; - var graphWasEmpty = (gd.data || []).length === 0 && Array.isArray(data); - if (Array.isArray(data)) { - helpers2.cleanData(data); - if (graphWasEmpty) gd.data = data; - else gd.data.push.apply(gd.data, data); - gd.empty = false; - } - if (!gd.layout || graphWasEmpty) { - gd.layout = helpers2.cleanLayout(layout); - } - Plots2.supplyDefaults(gd); - var fullLayout = gd._fullLayout; - var hasCartesian = fullLayout._has("cartesian"); - fullLayout._replotting = true; - if (graphWasEmpty || fullLayout._shouldCreateBgLayer) { - makePlotFramework(gd); - if (fullLayout._shouldCreateBgLayer) { - delete fullLayout._shouldCreateBgLayer; - } - } - Drawing2.initGradients(gd); - Drawing2.initPatterns(gd); - if (graphWasEmpty) Axes2.saveShowSpikeInitial(gd); - var recalc = !gd.calcdata || gd.calcdata.length !== (gd._fullData || []).length; - if (recalc) Plots2.doCalcdata(gd); - for (var i = 0; i < gd.calcdata.length; i++) { - gd.calcdata[i][0].trace = gd._fullData[i]; - } - if (gd._context.responsive) { - if (!gd._responsiveChartHandler) { - gd._responsiveChartHandler = function() { - if (!Lib2.isHidden(gd)) Plots2.resize(gd); - }; - window.addEventListener("resize", gd._responsiveChartHandler); - } - } else { - Lib2.clearResponsive(gd); - } - var oldMargins = Lib2.extendFlat({}, fullLayout._size); - var drawFrameworkCalls = 0; - function drawFramework() { - var basePlotModules = fullLayout._basePlotModules; - for (var i2 = 0; i2 < basePlotModules.length; i2++) { - if (basePlotModules[i2].drawFramework) { - basePlotModules[i2].drawFramework(gd); - } - } - if (!fullLayout._glcanvas && fullLayout._has("gl")) { - fullLayout._glcanvas = fullLayout._glcontainer.selectAll(".gl-canvas").data([{ - key: "contextLayer", - context: true, - pick: false - }, { - key: "focusLayer", - context: false, - pick: false - }, { - key: "pickLayer", - context: false, - pick: true - }], function(d) { - return d.key; - }); - fullLayout._glcanvas.enter().append("canvas").attr("class", function(d) { - return "gl-canvas gl-canvas-" + d.key.replace("Layer", ""); - }).style({ - position: "absolute", - top: 0, - left: 0, - overflow: "visible", - "pointer-events": "none" - }); - } - var plotGlPixelRatio = gd._context.plotGlPixelRatio; - if (fullLayout._glcanvas) { - fullLayout._glcanvas.attr("width", fullLayout.width * plotGlPixelRatio).attr("height", fullLayout.height * plotGlPixelRatio).style("width", fullLayout.width + "px").style("height", fullLayout.height + "px"); - var regl = fullLayout._glcanvas.data()[0].regl; - if (regl) { - if (Math.floor(fullLayout.width * plotGlPixelRatio) !== regl._gl.drawingBufferWidth || Math.floor(fullLayout.height * plotGlPixelRatio) !== regl._gl.drawingBufferHeight) { - var msg2 = "WebGL context buffer and canvas dimensions do not match due to browser/WebGL bug."; - if (drawFrameworkCalls) { - Lib2.error(msg2); - } else { - Lib2.log(msg2 + " Clearing graph and plotting again."); - Plots2.cleanPlot([], {}, gd._fullData, fullLayout); - Plots2.supplyDefaults(gd); - fullLayout = gd._fullLayout; - Plots2.doCalcdata(gd); - drawFrameworkCalls++; - return drawFramework(); - } - } - } - } - if (fullLayout.modebar.orientation === "h") { - fullLayout._modebardiv.style("height", null).style("width", "100%"); - } else { - fullLayout._modebardiv.style("width", null).style("height", fullLayout.height + "px"); - } - return Plots2.previousPromises(gd); - } - function marginPushers() { - Plots2.clearAutoMarginIds(gd); - subroutines$1.drawMarginPushers(gd); - Axes2.allowAutoMargin(gd); - if (gd._fullLayout.title.text && gd._fullLayout.title.automargin) Plots2.allowAutoMargin(gd, "title.automargin"); - if (fullLayout._has("pie")) { - var fullData = gd._fullData; - for (var i2 = 0; i2 < fullData.length; i2++) { - var trace = fullData[i2]; - if (trace.type === "pie" && trace.automargin) { - Plots2.allowAutoMargin(gd, "pie." + trace.uid + ".automargin"); - } - } - } - Plots2.doAutoMargin(gd); - return Plots2.previousPromises(gd); - } - function marginPushersAgain() { - if (!Plots2.didMarginChange(oldMargins, fullLayout._size)) return; - return Lib2.syncOrAsync([ - marginPushers, - subroutines$1.layoutStyles - ], gd); - } - function positionAndAutorange() { - if (!recalc) { - doAutoRangeAndConstraints(); - return; - } - return Lib2.syncOrAsync([ - Registry2.getComponentMethod("shapes", "calcAutorange"), - Registry2.getComponentMethod("annotations", "calcAutorange"), - doAutoRangeAndConstraints - ], gd); - } - function doAutoRangeAndConstraints() { - if (gd._transitioning) return; - subroutines$1.doAutoRangeAndConstraints(gd); - if (graphWasEmpty) Axes2.saveRangeInitial(gd); - Registry2.getComponentMethod("rangeslider", "calcAutorange")(gd); - } - function drawAxes() { - return Axes2.draw(gd, graphWasEmpty ? "" : "redraw"); - } - var seq = [ - Plots2.previousPromises, - addFrames2, - drawFramework, - marginPushers, - marginPushersAgain - ]; - if (hasCartesian) seq.push(positionAndAutorange); - seq.push(subroutines$1.layoutStyles); - if (hasCartesian) { - seq.push( - drawAxes, - function insideTickLabelsAutorange(gd2) { - var insideTickLabelsUpdaterange = gd2._fullLayout._insideTickLabelsUpdaterange; - if (insideTickLabelsUpdaterange) { - gd2._fullLayout._insideTickLabelsUpdaterange = void 0; - return relayout(gd2, insideTickLabelsUpdaterange).then(function() { - Axes2.saveRangeInitial(gd2, true); - }); - } - } - ); - } - seq.push( - subroutines$1.drawData, - subroutines$1.finalDraw, - initInteractions, - Plots2.addLinks, - Plots2.rehover, - Plots2.redrag, - Plots2.reselect, - // TODO: doAutoMargin is only needed here for axis automargin, which - // happens outside of marginPushers where all the other automargins are - // calculated. Would be much better to separate margin calculations from - // component drawing - see https://github.com/plotly/plotly.js/issues/2704 - Plots2.doAutoMargin, - Plots2.previousPromises - ); - var plotDone = Lib2.syncOrAsync(seq, gd); - if (!plotDone || !plotDone.then) plotDone = Promise.resolve(); - return plotDone.then(function() { - emitAfterPlot(gd); - return gd; - }); - } - function emitAfterPlot(gd) { - var fullLayout = gd._fullLayout; - if (fullLayout._redrawFromAutoMarginCount) { - fullLayout._redrawFromAutoMarginCount--; - } else { - gd.emit("plotly_afterplot"); - } - } - function setPlotConfig(obj) { - return Lib2.extendFlat(dfltConfig2, obj); - } - function setBackground(gd, bgColor) { - try { - gd._fullLayout._paper.style("background", bgColor); - } catch (e) { - Lib2.error(e); - } - } - function opaqueSetBackground(gd, bgColor) { - var blend = Color2.combine(bgColor, "white"); - setBackground(gd, blend); - } - function setPlotContext(gd, config) { - if (!gd._context) { - gd._context = Lib2.extendDeep({}, dfltConfig2); - var base = d32.select("base"); - gd._context._baseUrl = base.size() && base.attr("href") ? window.location.href.split("#")[0] : ""; - } - var context2 = gd._context; - var i, keys, key; - if (config) { - keys = Object.keys(config); - for (i = 0; i < keys.length; i++) { - key = keys[i]; - if (key === "editable" || key === "edits") continue; - if (key in context2) { - if (key === "setBackground" && config[key] === "opaque") { - context2[key] = opaqueSetBackground; - } else { - context2[key] = config[key]; - } - } - } - if (config.plot3dPixelRatio && !context2.plotGlPixelRatio) { - context2.plotGlPixelRatio = context2.plot3dPixelRatio; - } - var editable = config.editable; - if (editable !== void 0) { - context2.editable = editable; - keys = Object.keys(context2.edits); - for (i = 0; i < keys.length; i++) { - context2.edits[keys[i]] = editable; - } - } - if (config.edits) { - keys = Object.keys(config.edits); - for (i = 0; i < keys.length; i++) { - key = keys[i]; - if (key in context2.edits) { - context2.edits[key] = config.edits[key]; - } - } - } - context2._exportedPlot = config._exportedPlot; - } - if (context2.staticPlot) { - context2.editable = false; - context2.edits = {}; - context2.autosizable = false; - context2.scrollZoom = false; - context2.doubleClick = false; - context2.showTips = false; - context2.showLink = false; - context2.displayModeBar = false; - } - if (context2.displayModeBar === "hover" && !hasHover2) { - context2.displayModeBar = true; - } - if (context2.setBackground === "transparent" || typeof context2.setBackground !== "function") { - context2.setBackground = setBackground; - } - context2._hasZeroHeight = context2._hasZeroHeight || gd.clientHeight === 0; - context2._hasZeroWidth = context2._hasZeroWidth || gd.clientWidth === 0; - var szIn = context2.scrollZoom; - var szOut = context2._scrollZoom = {}; - if (szIn === true) { - szOut.cartesian = 1; - szOut.gl3d = 1; - szOut.geo = 1; - szOut.mapbox = 1; - szOut.map = 1; - } else if (typeof szIn === "string") { - var parts = szIn.split("+"); - for (i = 0; i < parts.length; i++) { - szOut[parts[i]] = 1; - } - } else if (szIn !== false) { - szOut.gl3d = 1; - szOut.geo = 1; - szOut.mapbox = 1; - szOut.map = 1; - } - } - function redraw(gd) { - gd = Lib2.getGraphDiv(gd); - if (!Lib2.isPlotDiv(gd)) { - throw new Error("This element is not a Plotly plot: " + gd); - } - helpers2.cleanData(gd.data); - helpers2.cleanLayout(gd.layout); - gd.calcdata = void 0; - return exports2._doPlot(gd).then(function() { - gd.emit("plotly_redraw"); - return gd; - }); - } - function newPlot(gd, data, layout, config) { - gd = Lib2.getGraphDiv(gd); - Plots2.cleanPlot([], {}, gd._fullData || [], gd._fullLayout || {}); - Plots2.purge(gd); - return exports2._doPlot(gd, data, layout, config); - } - function positivifyIndices(indices, maxIndex) { - var parentLength = maxIndex + 1; - var positiveIndices = []; - var i; - var index2; - for (i = 0; i < indices.length; i++) { - index2 = indices[i]; - if (index2 < 0) { - positiveIndices.push(parentLength + index2); - } else { - positiveIndices.push(index2); - } - } - return positiveIndices; - } - function assertIndexArray(gd, indices, arrayName) { - var i, index2; - for (i = 0; i < indices.length; i++) { - index2 = indices[i]; - if (index2 !== parseInt(index2, 10)) { - throw new Error("all values in " + arrayName + " must be integers"); - } - if (index2 >= gd.data.length || index2 < -gd.data.length) { - throw new Error(arrayName + " must be valid indices for gd.data."); - } - if (indices.indexOf(index2, i + 1) > -1 || index2 >= 0 && indices.indexOf(-gd.data.length + index2) > -1 || index2 < 0 && indices.indexOf(gd.data.length + index2) > -1) { - throw new Error("each index in " + arrayName + " must be unique."); - } - } - } - function checkMoveTracesArgs(gd, currentIndices, newIndices) { - if (!Array.isArray(gd.data)) { - throw new Error("gd.data must be an array."); - } - if (typeof currentIndices === "undefined") { - throw new Error("currentIndices is a required argument."); - } else if (!Array.isArray(currentIndices)) { - currentIndices = [currentIndices]; - } - assertIndexArray(gd, currentIndices, "currentIndices"); - if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) { - newIndices = [newIndices]; - } - if (typeof newIndices !== "undefined") { - assertIndexArray(gd, newIndices, "newIndices"); - } - if (typeof newIndices !== "undefined" && currentIndices.length !== newIndices.length) { - throw new Error("current and new indices must be of equal length."); - } - } - function checkAddTracesArgs(gd, traces, newIndices) { - var i, value2; - if (!Array.isArray(gd.data)) { - throw new Error("gd.data must be an array."); - } - if (typeof traces === "undefined") { - throw new Error("traces must be defined."); - } - if (!Array.isArray(traces)) { - traces = [traces]; - } - for (i = 0; i < traces.length; i++) { - value2 = traces[i]; - if (typeof value2 !== "object" || (Array.isArray(value2) || value2 === null)) { - throw new Error("all values in traces array must be non-array objects"); - } - } - if (typeof newIndices !== "undefined" && !Array.isArray(newIndices)) { - newIndices = [newIndices]; - } - if (typeof newIndices !== "undefined" && newIndices.length !== traces.length) { - throw new Error( - "if indices is specified, traces.length must equal indices.length" - ); - } - } - function assertExtendTracesArgs(gd, update3, indices, maxPoints) { - var maxPointsIsObject = Lib2.isPlainObject(maxPoints); - if (!Array.isArray(gd.data)) { - throw new Error("gd.data must be an array"); - } - if (!Lib2.isPlainObject(update3)) { - throw new Error("update must be a key:value object"); - } - if (typeof indices === "undefined") { - throw new Error("indices must be an integer or array of integers"); - } - assertIndexArray(gd, indices, "indices"); - for (var key in update3) { - if (!Array.isArray(update3[key]) || update3[key].length !== indices.length) { - throw new Error("attribute " + key + " must be an array of length equal to indices array length"); - } - if (maxPointsIsObject && (!(key in maxPoints) || !Array.isArray(maxPoints[key]) || maxPoints[key].length !== update3[key].length)) { - throw new Error("when maxPoints is set as a key:value object it must contain a 1:1 corrispondence with the keys and number of traces in the update object"); - } - } - } - function getExtendProperties(gd, update3, indices, maxPoints) { - var maxPointsIsObject = Lib2.isPlainObject(maxPoints); - var updateProps = []; - var trace, target, prop, insert, maxp; - if (!Array.isArray(indices)) indices = [indices]; - indices = positivifyIndices(indices, gd.data.length - 1); - for (var key in update3) { - for (var j = 0; j < indices.length; j++) { - trace = gd.data[indices[j]]; - prop = nestedProperty3(trace, key); - target = prop.get(); - insert = update3[key][j]; - if (!Lib2.isArrayOrTypedArray(insert)) { - throw new Error("attribute: " + key + " index: " + j + " must be an array"); - } - if (!Lib2.isArrayOrTypedArray(target)) { - throw new Error("cannot extend missing or non-array attribute: " + key); - } - if (target.constructor !== insert.constructor) { - throw new Error("cannot extend array with an array of a different type: " + key); - } - maxp = maxPointsIsObject ? maxPoints[key][j] : maxPoints; - if (!isNumeric2(maxp)) maxp = -1; - updateProps.push({ - prop, - target, - insert, - maxp: Math.floor(maxp) - }); - } - } - return updateProps; - } - function spliceTraces(gd, update3, indices, maxPoints, updateArray) { - assertExtendTracesArgs(gd, update3, indices, maxPoints); - var updateProps = getExtendProperties(gd, update3, indices, maxPoints); - var undoUpdate = {}; - var undoPoints = {}; - for (var i = 0; i < updateProps.length; i++) { - var prop = updateProps[i].prop; - var maxp = updateProps[i].maxp; - var out = updateArray(updateProps[i].target, updateProps[i].insert, maxp); - prop.set(out[0]); - if (!Array.isArray(undoUpdate[prop.astr])) undoUpdate[prop.astr] = []; - undoUpdate[prop.astr].push(out[1]); - if (!Array.isArray(undoPoints[prop.astr])) undoPoints[prop.astr] = []; - undoPoints[prop.astr].push(updateProps[i].target.length); - } - return { update: undoUpdate, maxPoints: undoPoints }; - } - function concatTypedArray(arr0, arr1) { - var arr2 = new arr0.constructor(arr0.length + arr1.length); - arr2.set(arr0); - arr2.set(arr1, arr0.length); - return arr2; - } - function extendTraces(gd, update3, indices, maxPoints) { - gd = Lib2.getGraphDiv(gd); - function updateArray(target, insert, maxp) { - var newArray, remainder; - if (Lib2.isTypedArray(target)) { - if (maxp < 0) { - var none = new target.constructor(0); - var both = concatTypedArray(target, insert); - if (maxp < 0) { - newArray = both; - remainder = none; - } else { - newArray = none; - remainder = both; - } - } else { - newArray = new target.constructor(maxp); - remainder = new target.constructor(target.length + insert.length - maxp); - if (maxp === insert.length) { - newArray.set(insert); - remainder.set(target); - } else if (maxp < insert.length) { - var numberOfItemsFromInsert = insert.length - maxp; - newArray.set(insert.subarray(numberOfItemsFromInsert)); - remainder.set(target); - remainder.set(insert.subarray(0, numberOfItemsFromInsert), target.length); - } else { - var numberOfItemsFromTarget = maxp - insert.length; - var targetBegin = target.length - numberOfItemsFromTarget; - newArray.set(target.subarray(targetBegin)); - newArray.set(insert, numberOfItemsFromTarget); - remainder.set(target.subarray(0, targetBegin)); - } - } - } else { - newArray = target.concat(insert); - remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(0, newArray.length - maxp) : []; - } - return [newArray, remainder]; - } - var undo2 = spliceTraces(gd, update3, indices, maxPoints, updateArray); - var promise = exports2.redraw(gd); - var undoArgs = [gd, undo2.update, indices, undo2.maxPoints]; - Queue.add(gd, exports2.prependTraces, undoArgs, extendTraces, arguments); - return promise; - } - function prependTraces(gd, update3, indices, maxPoints) { - gd = Lib2.getGraphDiv(gd); - function updateArray(target, insert, maxp) { - var newArray, remainder; - if (Lib2.isTypedArray(target)) { - if (maxp <= 0) { - var none = new target.constructor(0); - var both = concatTypedArray(insert, target); - if (maxp < 0) { - newArray = both; - remainder = none; - } else { - newArray = none; - remainder = both; - } - } else { - newArray = new target.constructor(maxp); - remainder = new target.constructor(target.length + insert.length - maxp); - if (maxp === insert.length) { - newArray.set(insert); - remainder.set(target); - } else if (maxp < insert.length) { - var numberOfItemsFromInsert = insert.length - maxp; - newArray.set(insert.subarray(0, numberOfItemsFromInsert)); - remainder.set(insert.subarray(numberOfItemsFromInsert)); - remainder.set(target, numberOfItemsFromInsert); - } else { - var numberOfItemsFromTarget = maxp - insert.length; - newArray.set(insert); - newArray.set(target.subarray(0, numberOfItemsFromTarget), insert.length); - remainder.set(target.subarray(numberOfItemsFromTarget)); - } - } - } else { - newArray = insert.concat(target); - remainder = maxp >= 0 && maxp < newArray.length ? newArray.splice(maxp, newArray.length) : []; - } - return [newArray, remainder]; - } - var undo2 = spliceTraces(gd, update3, indices, maxPoints, updateArray); - var promise = exports2.redraw(gd); - var undoArgs = [gd, undo2.update, indices, undo2.maxPoints]; - Queue.add(gd, exports2.extendTraces, undoArgs, prependTraces, arguments); - return promise; - } - function addTraces(gd, traces, newIndices) { - gd = Lib2.getGraphDiv(gd); - var currentIndices = []; - var undoFunc = exports2.deleteTraces; - var redoFunc = addTraces; - var undoArgs = [gd, currentIndices]; - var redoArgs = [gd, traces]; - var i; - var promise; - checkAddTracesArgs(gd, traces, newIndices); - if (!Array.isArray(traces)) { - traces = [traces]; - } - traces = traces.map(function(trace) { - return Lib2.extendFlat({}, trace); - }); - helpers2.cleanData(traces); - for (i = 0; i < traces.length; i++) { - gd.data.push(traces[i]); - } - for (i = 0; i < traces.length; i++) { - currentIndices.push(-traces.length + i); - } - if (typeof newIndices === "undefined") { - promise = exports2.redraw(gd); - Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return promise; - } - if (!Array.isArray(newIndices)) { - newIndices = [newIndices]; - } - try { - checkMoveTracesArgs(gd, currentIndices, newIndices); - } catch (error) { - gd.data.splice(gd.data.length - traces.length, traces.length); - throw error; - } - Queue.startSequence(gd); - Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - promise = exports2.moveTraces(gd, currentIndices, newIndices); - Queue.stopSequence(gd); - return promise; - } - function deleteTraces(gd, indices) { - gd = Lib2.getGraphDiv(gd); - var traces = []; - var undoFunc = exports2.addTraces; - var redoFunc = deleteTraces; - var undoArgs = [gd, traces, indices]; - var redoArgs = [gd, indices]; - var i; - var deletedTrace; - if (typeof indices === "undefined") { - throw new Error("indices must be an integer or array of integers."); - } else if (!Array.isArray(indices)) { - indices = [indices]; - } - assertIndexArray(gd, indices, "indices"); - indices = positivifyIndices(indices, gd.data.length - 1); - indices.sort(Lib2.sorterDes); - for (i = 0; i < indices.length; i += 1) { - deletedTrace = gd.data.splice(indices[i], 1)[0]; - traces.push(deletedTrace); - } - var promise = exports2.redraw(gd); - Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return promise; - } - function moveTraces(gd, currentIndices, newIndices) { - gd = Lib2.getGraphDiv(gd); - var newData = []; - var movingTraceMap = []; - var undoFunc = moveTraces; - var redoFunc = moveTraces; - var undoArgs = [gd, newIndices, currentIndices]; - var redoArgs = [gd, currentIndices, newIndices]; - var i; - checkMoveTracesArgs(gd, currentIndices, newIndices); - currentIndices = Array.isArray(currentIndices) ? currentIndices : [currentIndices]; - if (typeof newIndices === "undefined") { - newIndices = []; - for (i = 0; i < currentIndices.length; i++) { - newIndices.push(-currentIndices.length + i); - } - } - newIndices = Array.isArray(newIndices) ? newIndices : [newIndices]; - currentIndices = positivifyIndices(currentIndices, gd.data.length - 1); - newIndices = positivifyIndices(newIndices, gd.data.length - 1); - for (i = 0; i < gd.data.length; i++) { - if (currentIndices.indexOf(i) === -1) { - newData.push(gd.data[i]); - } - } - for (i = 0; i < currentIndices.length; i++) { - movingTraceMap.push({ newIndex: newIndices[i], trace: gd.data[currentIndices[i]] }); - } - movingTraceMap.sort(function(a, b) { - return a.newIndex - b.newIndex; - }); - for (i = 0; i < movingTraceMap.length; i += 1) { - newData.splice(movingTraceMap[i].newIndex, 0, movingTraceMap[i].trace); - } - gd.data = newData; - var promise = exports2.redraw(gd); - Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return promise; - } - function restyle(gd, astr, val, _traces) { - gd = Lib2.getGraphDiv(gd); - helpers2.clearPromiseQueue(gd); - var aobj = {}; - if (typeof astr === "string") aobj[astr] = val; - else if (Lib2.isPlainObject(astr)) { - aobj = Lib2.extendFlat({}, astr); - if (_traces === void 0) _traces = val; - } else { - Lib2.warn("Restyle fail.", astr, val, _traces); - return Promise.reject(); - } - if (Object.keys(aobj).length) gd.changed = true; - var traces = helpers2.coerceTraceIndices(gd, _traces); - var specs = _restyle(gd, aobj, traces); - var flags = specs.flags; - if (flags.calc) gd.calcdata = void 0; - if (flags.clearAxisTypes) helpers2.clearAxisTypes(gd, traces, {}); - var seq = []; - if (flags.fullReplot) { - seq.push(exports2._doPlot); - } else { - seq.push(Plots2.previousPromises); - Plots2.supplyDefaults(gd); - if (flags.markerSize) { - Plots2.doCalcdata(gd); - addAxRangeSequence(seq); - } - if (flags.style) seq.push(subroutines$1.doTraceStyle); - if (flags.colorbars) seq.push(subroutines$1.doColorBars); - seq.push(emitAfterPlot); - } - seq.push( - Plots2.rehover, - Plots2.redrag, - Plots2.reselect - ); - Queue.add( - gd, - restyle, - [gd, specs.undoit, specs.traces], - restyle, - [gd, specs.redoit, specs.traces] - ); - var plotDone = Lib2.syncOrAsync(seq, gd); - if (!plotDone || !plotDone.then) plotDone = Promise.resolve(); - return plotDone.then(function() { - gd.emit("plotly_restyle", specs.eventData); - return gd; - }); - } - function undefinedToNull(val) { - if (val === void 0) return null; - return val; - } - function makeNP(preGUI, guiEditFlag) { - if (!guiEditFlag) return nestedProperty3; - return function(container, attr, prefix) { - var np = nestedProperty3(container, attr); - var npSet2 = np.set; - np.set = function(val) { - var fullAttr = (prefix || "") + attr; - storeCurrent(fullAttr, np.get(), val, preGUI); - npSet2(val); - }; - return np; - }; - } - function storeCurrent(attr, val, newVal, preGUI) { - if (Array.isArray(val) || Array.isArray(newVal)) { - var arrayVal = Array.isArray(val) ? val : []; - var arrayNew = Array.isArray(newVal) ? newVal : []; - var maxLen = Math.max(arrayVal.length, arrayNew.length); - for (var i = 0; i < maxLen; i++) { - storeCurrent(attr + "[" + i + "]", arrayVal[i], arrayNew[i], preGUI); - } - } else if (Lib2.isPlainObject(val) || Lib2.isPlainObject(newVal)) { - var objVal = Lib2.isPlainObject(val) ? val : {}; - var objNew = Lib2.isPlainObject(newVal) ? newVal : {}; - var objBoth = Lib2.extendFlat({}, objVal, objNew); - for (var key in objBoth) { - storeCurrent(attr + "." + key, objVal[key], objNew[key], preGUI); - } - } else if (preGUI[attr] === void 0) { - preGUI[attr] = undefinedToNull(val); - } - } - function _storeDirectGUIEdit(container, preGUI, edits) { - for (var attr in edits) { - var np = nestedProperty3(container, attr); - storeCurrent(attr, np.get(), edits[attr], preGUI); - } - } - function _restyle(gd, aobj, traces) { - var fullLayout = gd._fullLayout; - var fullData = gd._fullData; - var data = gd.data; - var guiEditFlag = fullLayout._guiEditing; - var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); - var eventData5 = Lib2.extendDeepAll({}, aobj); - var i; - cleanDeprecatedAttributeKeys(aobj); - var flags = editTypes.traceFlags(); - var redoit = {}; - var undoit = {}; - var axlist; - function a0() { - return traces.map(function() { - return void 0; - }); - } - function addToAxlist(axid) { - var axName = Axes2.id2name(axid); - if (axlist.indexOf(axName) === -1) axlist.push(axName); - } - function autorangeAttr(axName) { - return "LAYOUT" + axName + ".autorange"; - } - function rangeAttr(axName) { - return "LAYOUT" + axName + ".range"; - } - function getFullTrace(traceIndex) { - for (var j = traceIndex; j < fullData.length; j++) { - if (fullData[j]._input === data[traceIndex]) return fullData[j]; - } - } - function doextra(attr, val, i2) { - if (Array.isArray(attr)) { - attr.forEach(function(a) { - doextra(a, val, i2); - }); - return; - } - if (attr in aobj || helpers2.hasParent(aobj, attr)) return; - var extraparam; - if (attr.substr(0, 6) === "LAYOUT") { - extraparam = layoutNP(gd.layout, attr.replace("LAYOUT", "")); - } else { - var tracei = traces[i2]; - var preGUI2 = fullLayout._tracePreGUI[getFullTrace(tracei)._fullInput.uid]; - extraparam = makeNP(preGUI2, guiEditFlag)(data[tracei], attr); - } - if (!(attr in undoit)) { - undoit[attr] = a0(); - } - if (undoit[attr][i2] === void 0) { - undoit[attr][i2] = undefinedToNull(extraparam.get()); - } - if (val !== void 0) { - extraparam.set(val); - } - } - function allBins(binAttr) { - return function(j) { - return fullData[j][binAttr]; - }; - } - function arrayBins(binAttr) { - return function(vij, j) { - return vij === false ? fullData[traces[j]][binAttr] : null; - }; - } - for (var ai in aobj) { - if (helpers2.hasParent(aobj, ai)) { - throw new Error("cannot set " + ai + " and a parent attribute simultaneously"); - } - var vi = aobj[ai]; - var cont; - var contFull; - var param; - var oldVal; - var newVal; - var valObject; - if (ai === "autobinx" || ai === "autobiny") { - ai = ai.charAt(ai.length - 1) + "bins"; - if (Array.isArray(vi)) vi = vi.map(arrayBins(ai)); - else if (vi === false) vi = traces.map(allBins(ai)); - else vi = null; - } - redoit[ai] = vi; - if (ai.substr(0, 6) === "LAYOUT") { - param = layoutNP(gd.layout, ai.replace("LAYOUT", "")); - undoit[ai] = [undefinedToNull(param.get())]; - param.set(Array.isArray(vi) ? vi[0] : vi); - flags.calc = true; - continue; - } - undoit[ai] = a0(); - for (i = 0; i < traces.length; i++) { - cont = data[traces[i]]; - contFull = getFullTrace(traces[i]); - var preGUI = fullLayout._tracePreGUI[contFull._fullInput.uid]; - param = makeNP(preGUI, guiEditFlag)(cont, ai); - oldVal = param.get(); - newVal = Array.isArray(vi) ? vi[i % vi.length] : vi; - if (newVal === void 0) continue; - var finalPart = param.parts[param.parts.length - 1]; - var prefix = ai.substr(0, ai.length - finalPart.length - 1); - var prefixDot = prefix ? prefix + "." : ""; - var innerContFull = prefix ? nestedProperty3(contFull, prefix).get() : contFull; - valObject = PlotSchema2.getTraceValObject(contFull, param.parts); - if (valObject && valObject.impliedEdits && newVal !== null) { - for (var impliedKey in valObject.impliedEdits) { - doextra(Lib2.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey], i); - } - } else if ((finalPart === "thicknessmode" || finalPart === "lenmode") && oldVal !== newVal && (newVal === "fraction" || newVal === "pixels") && innerContFull) { - var gs = fullLayout._size; - var orient = innerContFull.orient; - var topOrBottom = orient === "top" || orient === "bottom"; - if (finalPart === "thicknessmode") { - var thicknorm = topOrBottom ? gs.h : gs.w; - doextra(prefixDot + "thickness", innerContFull.thickness * (newVal === "fraction" ? 1 / thicknorm : thicknorm), i); - } else { - var lennorm = topOrBottom ? gs.w : gs.h; - doextra(prefixDot + "len", innerContFull.len * (newVal === "fraction" ? 1 / lennorm : lennorm), i); - } - } else if (ai === "type" && (newVal === "pie" !== (oldVal === "pie") || newVal === "funnelarea" !== (oldVal === "funnelarea"))) { - var labelsTo = "x"; - var valuesTo = "y"; - if ((newVal === "bar" || oldVal === "bar") && cont.orientation === "h") { - labelsTo = "y"; - valuesTo = "x"; - } - Lib2.swapAttrs(cont, ["?", "?src"], "labels", labelsTo); - Lib2.swapAttrs(cont, ["d?", "?0"], "label", labelsTo); - Lib2.swapAttrs(cont, ["?", "?src"], "values", valuesTo); - if (oldVal === "pie" || oldVal === "funnelarea") { - nestedProperty3(cont, "marker.color").set(nestedProperty3(cont, "marker.colors").get()); - fullLayout._pielayer.selectAll("g.trace").remove(); - } else if (Registry2.traceIs(cont, "cartesian")) { - nestedProperty3(cont, "marker.colors").set(nestedProperty3(cont, "marker.color").get()); - } - } - undoit[ai][i] = undefinedToNull(oldVal); - var swapAttrs = [ - "swapxy", - "swapxyaxes", - "orientation", - "orientationaxes" - ]; - if (swapAttrs.indexOf(ai) !== -1) { - if (ai === "orientation") { - param.set(newVal); - var defaultOrientation = cont.x && !cont.y ? "h" : "v"; - if ((param.get() || defaultOrientation) === contFull.orientation) { - continue; - } - } else if (ai === "orientationaxes") { - cont.orientation = { v: "h", h: "v" }[contFull.orientation]; - } - helpers2.swapXYData(cont); - flags.calc = flags.clearAxisTypes = true; - } else if (Plots2.dataArrayContainers.indexOf(param.parts[0]) !== -1) { - helpers2.manageArrayContainers(param, newVal, undoit); - flags.calc = true; - } else { - if (valObject) { - if (valObject.arrayOk && !Registry2.traceIs(contFull, "regl") && (Lib2.isArrayOrTypedArray(newVal) || Lib2.isArrayOrTypedArray(oldVal))) { - flags.calc = true; - } else editTypes.update(flags, valObject); - } else { - flags.calc = true; - } - param.set(newVal); - } - } - if (["swapxyaxes", "orientationaxes"].indexOf(ai) !== -1) { - Axes2.swap(gd, traces); - } - if (ai === "orientationaxes") { - var hovermode = nestedProperty3(gd.layout, "hovermode"); - var h = hovermode.get(); - if (h === "x") { - hovermode.set("y"); - } else if (h === "y") { - hovermode.set("x"); - } else if (h === "x unified") { - hovermode.set("y unified"); - } else if (h === "y unified") { - hovermode.set("x unified"); - } - } - if (["orientation", "type"].indexOf(ai) !== -1) { - axlist = []; - for (i = 0; i < traces.length; i++) { - var trace = data[traces[i]]; - if (Registry2.traceIs(trace, "cartesian")) { - addToAxlist(trace.xaxis || "x"); - addToAxlist(trace.yaxis || "y"); - } - } - doextra(axlist.map(autorangeAttr), true, 0); - doextra(axlist.map(rangeAttr), [0, 1], 0); - } - } - if (flags.calc || flags.plot) { - flags.fullReplot = true; - } - return { - flags, - undoit, - redoit, - traces, - eventData: Lib2.extendDeepNoArrays([], [eventData5, traces]) - }; - } - function cleanDeprecatedAttributeKeys(aobj) { - var oldAxisTitleRegex = Lib2.counterRegex("axis", ".title", false, false); - var colorbarRegex = /colorbar\.title$/; - var keys = Object.keys(aobj); - var i, key, value2; - for (i = 0; i < keys.length; i++) { - key = keys[i]; - value2 = aobj[key]; - if ((key === "title" || oldAxisTitleRegex.test(key) || colorbarRegex.test(key)) && (typeof value2 === "string" || typeof value2 === "number")) { - replace(key, key.replace("title", "title.text")); - } else if (key.indexOf("titlefont") > -1 && key.indexOf("grouptitlefont") === -1) { - replace(key, key.replace("titlefont", "title.font")); - } else if (key.indexOf("titleposition") > -1) { - replace(key, key.replace("titleposition", "title.position")); - } else if (key.indexOf("titleside") > -1) { - replace(key, key.replace("titleside", "title.side")); - } else if (key.indexOf("titleoffset") > -1) { - replace(key, key.replace("titleoffset", "title.offset")); - } - } - function replace(oldAttrStr, newAttrStr) { - aobj[newAttrStr] = aobj[oldAttrStr]; - delete aobj[oldAttrStr]; - } - } - function relayout(gd, astr, val) { - gd = Lib2.getGraphDiv(gd); - helpers2.clearPromiseQueue(gd); - var aobj = {}; - if (typeof astr === "string") { - aobj[astr] = val; - } else if (Lib2.isPlainObject(astr)) { - aobj = Lib2.extendFlat({}, astr); - } else { - Lib2.warn("Relayout fail.", astr, val); - return Promise.reject(); - } - if (Object.keys(aobj).length) gd.changed = true; - var specs = _relayout(gd, aobj); - var flags = specs.flags; - if (flags.calc) gd.calcdata = void 0; - var seq = [Plots2.previousPromises]; - if (flags.layoutReplot) { - seq.push(subroutines$1.layoutReplot); - } else if (Object.keys(aobj).length) { - axRangeSupplyDefaultsByPass(gd, flags, specs) || Plots2.supplyDefaults(gd); - if (flags.legend) seq.push(subroutines$1.doLegend); - if (flags.layoutstyle) seq.push(subroutines$1.layoutStyles); - if (flags.axrange) addAxRangeSequence(seq, specs.rangesAltered); - if (flags.ticks) seq.push(subroutines$1.doTicksRelayout); - if (flags.modebar) seq.push(subroutines$1.doModeBar); - if (flags.camera) seq.push(subroutines$1.doCamera); - if (flags.colorbars) seq.push(subroutines$1.doColorBars); - seq.push(emitAfterPlot); - } - seq.push( - Plots2.rehover, - Plots2.redrag, - Plots2.reselect - ); - Queue.add( - gd, - relayout, - [gd, specs.undoit], - relayout, - [gd, specs.redoit] - ); - var plotDone = Lib2.syncOrAsync(seq, gd); - if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); - return plotDone.then(function() { - gd.emit("plotly_relayout", specs.eventData); - return gd; - }); - } - function axRangeSupplyDefaultsByPass(gd, flags, specs) { - var fullLayout = gd._fullLayout; - if (!flags.axrange) return false; - for (var k in flags) { - if (k !== "axrange" && flags[k]) return false; - } - var axIn, axOut; - var coerce2 = function(attr, dflt) { - return Lib2.coerce(axIn, axOut, cartesianLayoutAttributes, attr, dflt); - }; - var options = {}; - for (var axId in specs.rangesAltered) { - var axName = Axes2.id2name(axId); - axIn = gd.layout[axName]; - axOut = fullLayout[axName]; - handleRangeDefaults3(axIn, axOut, coerce2, options); - if (axOut._matchGroup) { - for (var axId2 in axOut._matchGroup) { - if (axId2 !== axId) { - var ax2 = fullLayout[Axes2.id2name(axId2)]; - ax2.autorange = axOut.autorange; - ax2.range = axOut.range.slice(); - ax2._input.range = axOut.range.slice(); - } - } - } - } - return true; - } - function addAxRangeSequence(seq, rangesAltered) { - var drawAxes = rangesAltered ? function(gd) { - var axIds2 = []; - var skipTitle = true; - for (var id in rangesAltered) { - var ax = Axes2.getFromId(gd, id); - axIds2.push(id); - if ((ax.ticklabelposition || "").indexOf("inside") !== -1) { - if (ax._anchorAxis) { - axIds2.push(ax._anchorAxis._id); - } - } - if (ax._matchGroup) { - for (var id2 in ax._matchGroup) { - if (!rangesAltered[id2]) { - axIds2.push(id2); - } - } - } - } - return Axes2.draw(gd, axIds2, { skipTitle }); - } : function(gd) { - return Axes2.draw(gd, "redraw"); - }; - seq.push( - clearOutline2, - subroutines$1.doAutoRangeAndConstraints, - drawAxes, - subroutines$1.drawData, - subroutines$1.finalDraw - ); - } - var AX_RANGE_RE = /^[xyz]axis[0-9]*\.range(\[[0|1]\])?$/; - var AX_AUTORANGE_RE = /^[xyz]axis[0-9]*\.autorange$/; - var AX_DOMAIN_RE = /^[xyz]axis[0-9]*\.domain(\[[0|1]\])?$/; - function _relayout(gd, aobj) { - var layout = gd.layout; - var fullLayout = gd._fullLayout; - var guiEditFlag = fullLayout._guiEditing; - var layoutNP = makeNP(fullLayout._preGUI, guiEditFlag); - var keys = Object.keys(aobj); - var axes2 = Axes2.list(gd); - var eventData5 = Lib2.extendDeepAll({}, aobj); - var arrayEdits = {}; - var arrayStr, i, j; - cleanDeprecatedAttributeKeys(aobj); - keys = Object.keys(aobj); - for (i = 0; i < keys.length; i++) { - if (keys[i].indexOf("allaxes") === 0) { - for (j = 0; j < axes2.length; j++) { - var scene = axes2[j]._id.substr(1); - var axisAttr = scene.indexOf("scene") !== -1 ? scene + "." : ""; - var newkey = keys[i].replace("allaxes", axisAttr + axes2[j]._name); - if (!aobj[newkey]) aobj[newkey] = aobj[keys[i]]; - } - delete aobj[keys[i]]; - } - } - var flags = editTypes.layoutFlags(); - var redoit = {}; - var undoit = {}; - function doextra(attr, val) { - if (Array.isArray(attr)) { - attr.forEach(function(a) { - doextra(a, val); - }); - return; - } - if (attr in aobj || helpers2.hasParent(aobj, attr)) return; - var p2 = layoutNP(layout, attr); - if (!(attr in undoit)) { - undoit[attr] = undefinedToNull(p2.get()); - } - if (val !== void 0) p2.set(val); - } - var rangesAltered = {}; - var ax; - function recordAlteredAxis(pleafPlus2) { - var axId2 = Axes2.name2id(pleafPlus2.split(".")[0]); - rangesAltered[axId2] = 1; - return axId2; - } - for (var ai in aobj) { - if (helpers2.hasParent(aobj, ai)) { - throw new Error("cannot set " + ai + " and a parent attribute simultaneously"); - } - var p = layoutNP(layout, ai); - var vi = aobj[ai]; - var plen = p.parts.length; - var pend = plen - 1; - while (pend > 0 && typeof p.parts[pend] !== "string") pend--; - var pleaf = p.parts[pend]; - var pleafPlus = p.parts[pend - 1] + "." + pleaf; - var ptrunk = p.parts.slice(0, pend).join("."); - var parentIn = nestedProperty3(gd.layout, ptrunk).get(); - var parentFull = nestedProperty3(fullLayout, ptrunk).get(); - var vOld = p.get(); - if (vi === void 0) continue; - redoit[ai] = vi; - undoit[ai] = pleaf === "reverse" ? vi : undefinedToNull(vOld); - var valObject = PlotSchema2.getLayoutValObject(fullLayout, p.parts); - if (valObject && valObject.impliedEdits && vi !== null) { - for (var impliedKey in valObject.impliedEdits) { - doextra(Lib2.relativeAttr(ai, impliedKey), valObject.impliedEdits[impliedKey]); - } - } - if (["width", "height"].indexOf(ai) !== -1) { - if (vi) { - doextra("autosize", null); - var oppositeAttr = ai === "height" ? "width" : "height"; - doextra(oppositeAttr, fullLayout[oppositeAttr]); - } else { - fullLayout[ai] = gd._initialAutoSize[ai]; - } - } else if (ai === "autosize") { - doextra("width", vi ? null : fullLayout.width); - doextra("height", vi ? null : fullLayout.height); - } else if (pleafPlus.match(AX_RANGE_RE)) { - recordAlteredAxis(pleafPlus); - nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); - } else if (pleafPlus.match(AX_AUTORANGE_RE)) { - recordAlteredAxis(pleafPlus); - nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); - var axFull = nestedProperty3(fullLayout, ptrunk).get(); - if (axFull._inputDomain) { - axFull._input.domain = axFull._inputDomain.slice(); - } - } else if (pleafPlus.match(AX_DOMAIN_RE)) { - nestedProperty3(fullLayout, ptrunk + "._inputDomain").set(null); - } - if (pleaf === "type") { - ax = parentIn; - var toLog = parentFull.type === "linear" && vi === "log"; - var fromLog2 = parentFull.type === "log" && vi === "linear"; - if (toLog || fromLog2) { - if (!ax || !ax.range) { - doextra(ptrunk + ".autorange", true); - } else if (!parentFull.autorange) { - var r0 = ax.range[0]; - var r1 = ax.range[1]; - if (toLog) { - if (r0 <= 0 && r1 <= 0) { - doextra(ptrunk + ".autorange", true); - } - if (r0 <= 0) r0 = r1 / 1e6; - else if (r1 <= 0) r1 = r0 / 1e6; - doextra(ptrunk + ".range[0]", Math.log(r0) / Math.LN10); - doextra(ptrunk + ".range[1]", Math.log(r1) / Math.LN10); - } else { - doextra(ptrunk + ".range[0]", Math.pow(10, r0)); - doextra(ptrunk + ".range[1]", Math.pow(10, r1)); - } - } else if (toLog) { - ax.range = ax.range[1] > ax.range[0] ? [1, 2] : [2, 1]; - } - if (Array.isArray(fullLayout._subplots.polar) && fullLayout._subplots.polar.length && fullLayout[p.parts[0]] && p.parts[1] === "radialaxis") { - delete fullLayout[p.parts[0]]._subplot.viewInitial["radialaxis.range"]; - } - Registry2.getComponentMethod("annotations", "convertCoords")(gd, parentFull, vi, doextra); - Registry2.getComponentMethod("images", "convertCoords")(gd, parentFull, vi, doextra); - } else { - doextra(ptrunk + ".autorange", true); - doextra(ptrunk + ".range", null); - } - nestedProperty3(fullLayout, ptrunk + "._inputRange").set(null); - } else if (pleaf.match(AX_NAME_PATTERN)) { - var fullProp = nestedProperty3(fullLayout, ai).get(); - var newType = (vi || {}).type; - if (!newType || newType === "-") newType = "linear"; - Registry2.getComponentMethod("annotations", "convertCoords")(gd, fullProp, newType, doextra); - Registry2.getComponentMethod("images", "convertCoords")(gd, fullProp, newType, doextra); - } - var containerArrayMatch2 = manageArrays.containerArrayMatch(ai); - if (containerArrayMatch2) { - arrayStr = containerArrayMatch2.array; - i = containerArrayMatch2.index; - var propStr = containerArrayMatch2.property; - var updateValObject = valObject || { editType: "calc" }; - if (i !== "" && propStr === "") { - if (manageArrays.isAddVal(vi)) { - undoit[ai] = null; - } else if (manageArrays.isRemoveVal(vi)) { - undoit[ai] = (nestedProperty3(layout, arrayStr).get() || [])[i]; - } else { - Lib2.warn("unrecognized full object value", aobj); - } - } - editTypes.update(flags, updateValObject); - if (!arrayEdits[arrayStr]) arrayEdits[arrayStr] = {}; - var objEdits = arrayEdits[arrayStr][i]; - if (!objEdits) objEdits = arrayEdits[arrayStr][i] = {}; - objEdits[propStr] = vi; - delete aobj[ai]; - } else if (pleaf === "reverse") { - if (parentIn.range) parentIn.range.reverse(); - else { - doextra(ptrunk + ".autorange", true); - parentIn.range = [1, 0]; - } - if (parentFull.autorange) flags.calc = true; - else flags.plot = true; - } else { - if (ai === "dragmode" && (vi === false && vOld !== false || vi !== false && vOld === false)) { - flags.plot = true; - } else if (fullLayout._has("scatter-like") && fullLayout._has("regl") && (ai === "dragmode" && (vi === "lasso" || vi === "select") && !(vOld === "lasso" || vOld === "select"))) { - flags.plot = true; - } else if (fullLayout._has("gl2d")) { - flags.plot = true; - } else if (valObject) editTypes.update(flags, valObject); - else flags.calc = true; - p.set(vi); - } - } - for (arrayStr in arrayEdits) { - var finished = manageArrays.applyContainerArrayChanges( - gd, - layoutNP(layout, arrayStr), - arrayEdits[arrayStr], - flags, - layoutNP - ); - if (!finished) flags.plot = true; - } - for (var axId in rangesAltered) { - ax = Axes2.getFromId(gd, axId); - var group = ax && ax._constraintGroup; - if (group) { - flags.calc = true; - for (var groupAxId in group) { - if (!rangesAltered[groupAxId]) { - Axes2.getFromId(gd, groupAxId)._constraintShrinkable = true; - } - } - } - } - if (updateAutosize(gd) || aobj.height || aobj.width) flags.plot = true; - var shapes2 = fullLayout.shapes; - for (i = 0; i < shapes2.length; i++) { - if (shapes2[i].showlegend) { - flags.calc = true; - break; - } - } - if (flags.plot || flags.calc) { - flags.layoutReplot = true; - } - return { - flags, - rangesAltered, - undoit, - redoit, - eventData: eventData5 - }; - } - function updateAutosize(gd) { - var fullLayout = gd._fullLayout; - var oldWidth = fullLayout.width; - var oldHeight = fullLayout.height; - if (gd.layout.autosize) Plots2.plotAutoSize(gd, gd.layout, fullLayout); - return fullLayout.width !== oldWidth || fullLayout.height !== oldHeight; - } - function update2(gd, traceUpdate, layoutUpdate, _traces) { - gd = Lib2.getGraphDiv(gd); - helpers2.clearPromiseQueue(gd); - if (!Lib2.isPlainObject(traceUpdate)) traceUpdate = {}; - if (!Lib2.isPlainObject(layoutUpdate)) layoutUpdate = {}; - if (Object.keys(traceUpdate).length) gd.changed = true; - if (Object.keys(layoutUpdate).length) gd.changed = true; - var traces = helpers2.coerceTraceIndices(gd, _traces); - var restyleSpecs = _restyle(gd, Lib2.extendFlat({}, traceUpdate), traces); - var restyleFlags = restyleSpecs.flags; - var relayoutSpecs = _relayout(gd, Lib2.extendFlat({}, layoutUpdate)); - var relayoutFlags = relayoutSpecs.flags; - if (restyleFlags.calc || relayoutFlags.calc) gd.calcdata = void 0; - if (restyleFlags.clearAxisTypes) helpers2.clearAxisTypes(gd, traces, layoutUpdate); - var seq = []; - if (relayoutFlags.layoutReplot) { - seq.push(subroutines$1.layoutReplot); - } else if (restyleFlags.fullReplot) { - seq.push(exports2._doPlot); - } else { - seq.push(Plots2.previousPromises); - axRangeSupplyDefaultsByPass(gd, relayoutFlags, relayoutSpecs) || Plots2.supplyDefaults(gd); - if (restyleFlags.style) seq.push(subroutines$1.doTraceStyle); - if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines$1.doColorBars); - if (relayoutFlags.legend) seq.push(subroutines$1.doLegend); - if (relayoutFlags.layoutstyle) seq.push(subroutines$1.layoutStyles); - if (relayoutFlags.axrange) addAxRangeSequence(seq, relayoutSpecs.rangesAltered); - if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); - if (relayoutFlags.modebar) seq.push(subroutines$1.doModeBar); - if (relayoutFlags.camera) seq.push(subroutines$1.doCamera); - seq.push(emitAfterPlot); - } - seq.push( - Plots2.rehover, - Plots2.redrag, - Plots2.reselect - ); - Queue.add( - gd, - update2, - [gd, restyleSpecs.undoit, relayoutSpecs.undoit, restyleSpecs.traces], - update2, - [gd, restyleSpecs.redoit, relayoutSpecs.redoit, restyleSpecs.traces] - ); - var plotDone = Lib2.syncOrAsync(seq, gd); - if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); - return plotDone.then(function() { - gd.emit("plotly_update", { - data: restyleSpecs.eventData, - layout: relayoutSpecs.eventData - }); - return gd; - }); - } - function guiEdit(func) { - return function wrappedEdit(gd) { - gd._fullLayout._guiEditing = true; - var p = func.apply(null, arguments); - gd._fullLayout._guiEditing = false; - return p; - }; - } - var layoutUIControlPatterns = [ - { pattern: /^hiddenlabels/, attr: "legend.uirevision" }, - { pattern: /^((x|y)axis\d*)\.((auto)?range|title\.text)/ }, - // showspikes and modes include those nested inside scenes - { pattern: /axis\d*\.showspikes$/, attr: "modebar.uirevision" }, - { pattern: /(hover|drag)mode$/, attr: "modebar.uirevision" }, - { pattern: /^(scene\d*)\.camera/ }, - { pattern: /^(geo\d*)\.(projection|center|fitbounds)/ }, - { pattern: /^(ternary\d*\.[abc]axis)\.(min|title\.text)$/ }, - { pattern: /^(polar\d*\.radialaxis)\.((auto)?range|angle|title\.text)/ }, - { pattern: /^(polar\d*\.angularaxis)\.rotation/ }, - { pattern: /^(mapbox\d*)\.(center|zoom|bearing|pitch)/ }, - { pattern: /^(map\d*)\.(center|zoom|bearing|pitch)/ }, - { pattern: /^legend\.(x|y)$/, attr: "editrevision" }, - { pattern: /^(shapes|annotations)/, attr: "editrevision" }, - { pattern: /^title\.text$/, attr: "editrevision" } - ]; - var traceUIControlPatterns = [ - { pattern: /^selectedpoints$/, attr: "selectionrevision" }, - // "visible" includes trace.transforms[i].styles[j].value.visible - { pattern: /(^|value\.)visible$/, attr: "legend.uirevision" }, - { pattern: /^dimensions\[\d+\]\.constraintrange/ }, - { pattern: /^node\.(x|y|groups)/ }, - // for Sankey nodes - { pattern: /^level$/ }, - // for Sunburst, Treemap and Icicle traces - // below this you must be in editable: true mode - // TODO: I still put name and title with `trace.uirevision` - // reasonable or should these be `editrevision`? - // Also applies to axis titles up in the layout section - // "name" also includes transform.styles - { pattern: /(^|value\.)name$/ }, - // including nested colorbar attributes (ie marker.colorbar) - { pattern: /colorbar\.title\.text$/ }, - { pattern: /colorbar\.(x|y)$/, attr: "editrevision" } - ]; - function findUIPattern(key, patternSpecs) { - for (var i = 0; i < patternSpecs.length; i++) { - var spec = patternSpecs[i]; - var match = key.match(spec.pattern); - if (match) { - var head = match[1] || ""; - return { head, tail: key.substr(head.length + 1), attr: spec.attr }; - } - } - } - function getNewRev(revAttr, container) { - var newRev = nestedProperty3(container, revAttr).get(); - if (newRev !== void 0) return newRev; - var parts = revAttr.split("."); - parts.pop(); - while (parts.length > 1) { - parts.pop(); - newRev = nestedProperty3(container, parts.join(".") + ".uirevision").get(); - if (newRev !== void 0) return newRev; - } - return container.uirevision; - } - function getFullTraceIndexFromUid(uid, fullData) { - for (var i = 0; i < fullData.length; i++) { - if (fullData[i]._fullInput.uid === uid) return i; - } - return -1; - } - function getTraceIndexFromUid(uid, data, tracei) { - for (var i = 0; i < data.length; i++) { - if (data[i].uid === uid) return i; - } - return !data[tracei] || data[tracei].uid ? -1 : tracei; - } - function valsMatch(v1, v2) { - var v1IsObj = Lib2.isPlainObject(v1); - var v1IsArray = Array.isArray(v1); - if (v1IsObj || v1IsArray) { - return (v1IsObj && Lib2.isPlainObject(v2) || v1IsArray && Array.isArray(v2)) && JSON.stringify(v1) === JSON.stringify(v2); - } - return v1 === v2; - } - function applyUIRevisions(data, layout, oldFullData, oldFullLayout) { - var layoutPreGUI = oldFullLayout._preGUI; - var key, revAttr, oldRev, newRev, match, preGUIVal, newNP, newVal, head, tail; - var bothInheritAutorange = []; - var newAutorangeIn = {}; - var newRangeAccepted = {}; - for (key in layoutPreGUI) { - match = findUIPattern(key, layoutUIControlPatterns); - if (match) { - head = match.head; - tail = match.tail; - revAttr = match.attr || head + ".uirevision"; - oldRev = nestedProperty3(oldFullLayout, revAttr).get(); - newRev = oldRev && getNewRev(revAttr, layout); - if (newRev && newRev === oldRev) { - preGUIVal = layoutPreGUI[key]; - if (preGUIVal === null) preGUIVal = void 0; - newNP = nestedProperty3(layout, key); - newVal = newNP.get(); - if (valsMatch(newVal, preGUIVal)) { - if (newVal === void 0 && tail === "autorange") { - bothInheritAutorange.push(head); - } - newNP.set(undefinedToNull(nestedProperty3(oldFullLayout, key).get())); - continue; - } else if (tail === "autorange" || tail.substr(0, 6) === "range[") { - var pre0 = layoutPreGUI[head + ".range[0]"]; - var pre1 = layoutPreGUI[head + ".range[1]"]; - var preAuto = layoutPreGUI[head + ".autorange"]; - if (preAuto || preAuto === null && pre0 === null && pre1 === null) { - if (!(head in newAutorangeIn)) { - var newContainer = nestedProperty3(layout, head).get(); - newAutorangeIn[head] = newContainer && (newContainer.autorange || newContainer.autorange !== false && (!newContainer.range || newContainer.range.length !== 2)); - } - if (newAutorangeIn[head]) { - newNP.set(undefinedToNull(nestedProperty3(oldFullLayout, key).get())); - continue; - } - } - } - } - } else { - Lib2.warn("unrecognized GUI edit: " + key); - } - delete layoutPreGUI[key]; - if (match && match.tail.substr(0, 6) === "range[") { - newRangeAccepted[match.head] = 1; - } - } - for (var i = 0; i < bothInheritAutorange.length; i++) { - var axAttr = bothInheritAutorange[i]; - if (newRangeAccepted[axAttr]) { - var newAx = nestedProperty3(layout, axAttr).get(); - if (newAx) delete newAx.autorange; - } - } - var allTracePreGUI = oldFullLayout._tracePreGUI; - for (var uid in allTracePreGUI) { - var tracePreGUI = allTracePreGUI[uid]; - var newTrace = null; - var fullInput; - for (key in tracePreGUI) { - if (!newTrace) { - var fulli = getFullTraceIndexFromUid(uid, oldFullData); - if (fulli < 0) { - delete allTracePreGUI[uid]; - break; - } - var fullTrace = oldFullData[fulli]; - fullInput = fullTrace._fullInput; - var newTracei = getTraceIndexFromUid(uid, data, fullInput.index); - if (newTracei < 0) { - delete allTracePreGUI[uid]; - break; - } - newTrace = data[newTracei]; - } - match = findUIPattern(key, traceUIControlPatterns); - if (match) { - if (match.attr) { - oldRev = nestedProperty3(oldFullLayout, match.attr).get(); - newRev = oldRev && getNewRev(match.attr, layout); - } else { - oldRev = fullInput.uirevision; - newRev = newTrace.uirevision; - if (newRev === void 0) newRev = layout.uirevision; - } - if (newRev && newRev === oldRev) { - preGUIVal = tracePreGUI[key]; - if (preGUIVal === null) preGUIVal = void 0; - newNP = nestedProperty3(newTrace, key); - newVal = newNP.get(); - if (valsMatch(newVal, preGUIVal)) { - newNP.set(undefinedToNull(nestedProperty3(fullInput, key).get())); - continue; - } - } - } else { - Lib2.warn("unrecognized GUI edit: " + key + " in trace uid " + uid); - } - delete tracePreGUI[key]; - } - } - } - function react(gd, data, layout, config) { - var frames, plotDone; - function addFrames2() { - return exports2.addFrames(gd, frames); - } - gd = Lib2.getGraphDiv(gd); - helpers2.clearPromiseQueue(gd); - var oldFullData = gd._fullData; - var oldFullLayout = gd._fullLayout; - if (!Lib2.isPlotDiv(gd) || !oldFullData || !oldFullLayout) { - plotDone = exports2.newPlot(gd, data, layout, config); - } else { - if (Lib2.isPlainObject(data)) { - var obj = data; - data = obj.data; - layout = obj.layout; - config = obj.config; - frames = obj.frames; - } - var configChanged = false; - if (config) { - var oldConfig = Lib2.extendDeep({}, gd._context); - gd._context = void 0; - setPlotContext(gd, config); - configChanged = diffConfig(oldConfig, gd._context); - } - gd.data = data || []; - helpers2.cleanData(gd.data); - gd.layout = layout || {}; - helpers2.cleanLayout(gd.layout); - applyUIRevisions(gd.data, gd.layout, oldFullData, oldFullLayout); - Plots2.supplyDefaults(gd, { skipUpdateCalc: true }); - var newFullData = gd._fullData; - var newFullLayout = gd._fullLayout; - var immutable = newFullLayout.datarevision === void 0; - var transition2 = newFullLayout.transition; - var relayoutFlags = diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition2); - var newDataRevision = relayoutFlags.newDataRevision; - var restyleFlags = diffData(gd, oldFullData, newFullData, immutable, transition2, newDataRevision); - if (updateAutosize(gd)) relayoutFlags.layoutReplot = true; - if (restyleFlags.calc || relayoutFlags.calc) { - gd.calcdata = void 0; - var allNames = Object.getOwnPropertyNames(newFullLayout); - for (var q = 0; q < allNames.length; q++) { - var name2 = allNames[q]; - var start = name2.substring(0, 5); - if (start === "xaxis" || start === "yaxis") { - var emptyCategories = newFullLayout[name2]._emptyCategories; - if (emptyCategories) emptyCategories(); - } - } - } else { - Plots2.supplyDefaultsUpdateCalc(gd.calcdata, newFullData); - } - var seq = []; - if (frames) { - gd._transitionData = {}; - Plots2.createTransitionData(gd); - seq.push(addFrames2); - } - if (newFullLayout.transition && !configChanged && (restyleFlags.anim || relayoutFlags.anim)) { - if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); - Plots2.doCalcdata(gd); - subroutines$1.doAutoRangeAndConstraints(gd); - seq.push(function() { - return Plots2.transitionFromReact(gd, restyleFlags, relayoutFlags, oldFullLayout); - }); - } else if (restyleFlags.fullReplot || relayoutFlags.layoutReplot || configChanged) { - gd._fullLayout._skipDefaults = true; - seq.push(exports2._doPlot); - } else { - for (var componentType in relayoutFlags.arrays) { - var indices = relayoutFlags.arrays[componentType]; - if (indices.length) { - var drawOne2 = Registry2.getComponentMethod(componentType, "drawOne"); - if (drawOne2 !== Lib2.noop) { - for (var i = 0; i < indices.length; i++) { - drawOne2(gd, indices[i]); - } - } else { - var draw8 = Registry2.getComponentMethod(componentType, "draw"); - if (draw8 === Lib2.noop) { - throw new Error("cannot draw components: " + componentType); - } - draw8(gd); - } - } - } - seq.push(Plots2.previousPromises); - if (restyleFlags.style) seq.push(subroutines$1.doTraceStyle); - if (restyleFlags.colorbars || relayoutFlags.colorbars) seq.push(subroutines$1.doColorBars); - if (relayoutFlags.legend) seq.push(subroutines$1.doLegend); - if (relayoutFlags.layoutstyle) seq.push(subroutines$1.layoutStyles); - if (relayoutFlags.axrange) addAxRangeSequence(seq); - if (relayoutFlags.ticks) seq.push(subroutines$1.doTicksRelayout); - if (relayoutFlags.modebar) seq.push(subroutines$1.doModeBar); - if (relayoutFlags.camera) seq.push(subroutines$1.doCamera); - seq.push(emitAfterPlot); - } - seq.push( - Plots2.rehover, - Plots2.redrag, - Plots2.reselect - ); - plotDone = Lib2.syncOrAsync(seq, gd); - if (!plotDone || !plotDone.then) plotDone = Promise.resolve(gd); - } - return plotDone.then(function() { - gd.emit("plotly_react", { - data, - layout - }); - return gd; - }); - } - function diffData(gd, oldFullData, newFullData, immutable, transition2, newDataRevision) { - var sameTraceLength = oldFullData.length === newFullData.length; - if (!transition2 && !sameTraceLength) { - return { - fullReplot: true, - calc: true - }; - } - var flags = editTypes.traceFlags(); - flags.arrays = {}; - flags.nChanges = 0; - flags.nChangesAnim = 0; - var i, trace; - function getTraceValObject(parts) { - var out = PlotSchema2.getTraceValObject(trace, parts); - if (!trace._module.animatable && out.anim) { - out.anim = false; - } - return out; - } - var diffOpts = { - getValObject: getTraceValObject, - flags, - immutable, - transition: transition2, - newDataRevision, - gd - }; - var seenUIDs = {}; - for (i = 0; i < oldFullData.length; i++) { - if (newFullData[i]) { - trace = newFullData[i]._fullInput; - if (Plots2.hasMakesDataTransform(trace)) trace = newFullData[i]; - if (seenUIDs[trace.uid]) continue; - seenUIDs[trace.uid] = 1; - getDiffFlags(oldFullData[i]._fullInput, trace, [], diffOpts); - } - } - if (flags.calc || flags.plot) { - flags.fullReplot = true; - } - if (transition2 && flags.nChanges && flags.nChangesAnim) { - flags.anim = flags.nChanges === flags.nChangesAnim && sameTraceLength ? "all" : "some"; - } - return flags; - } - function diffLayout(gd, oldFullLayout, newFullLayout, immutable, transition2) { - var flags = editTypes.layoutFlags(); - flags.arrays = {}; - flags.rangesAltered = {}; - flags.nChanges = 0; - flags.nChangesAnim = 0; - function getLayoutValObject(parts) { - return PlotSchema2.getLayoutValObject(newFullLayout, parts); - } - var diffOpts = { - getValObject: getLayoutValObject, - flags, - immutable, - transition: transition2, - gd - }; - getDiffFlags(oldFullLayout, newFullLayout, [], diffOpts); - if (flags.plot || flags.calc) { - flags.layoutReplot = true; - } - if (transition2 && flags.nChanges && flags.nChangesAnim) { - flags.anim = flags.nChanges === flags.nChangesAnim ? "all" : "some"; - } - return flags; - } - function getDiffFlags(oldContainer, newContainer, outerparts, opts) { - var valObject, key, astr; - var getValObject = opts.getValObject; - var flags = opts.flags; - var immutable = opts.immutable; - var inArray = opts.inArray; - var arrayIndex = opts.arrayIndex; - function changed() { - var editType = valObject.editType; - if (inArray && editType.indexOf("arraydraw") !== -1) { - Lib2.pushUnique(flags.arrays[inArray], arrayIndex); - return; - } - editTypes.update(flags, valObject); - if (editType !== "none") { - flags.nChanges++; - } - if (opts.transition && valObject.anim) { - flags.nChangesAnim++; - } - if (AX_RANGE_RE.test(astr) || AX_AUTORANGE_RE.test(astr)) { - flags.rangesAltered[outerparts[0]] = 1; - } - if (AX_DOMAIN_RE.test(astr)) { - nestedProperty3(newContainer, "_inputDomain").set(null); - } - if (key === "datarevision") { - flags.newDataRevision = 1; - } - } - function valObjectCanBeDataArray(valObject2) { - return valObject2.valType === "data_array" || valObject2.arrayOk; - } - for (key in oldContainer) { - if (flags.calc && !opts.transition) return; - var oldVal = oldContainer[key]; - var newVal = newContainer[key]; - var parts = outerparts.concat(key); - astr = parts.join("."); - if (key.charAt(0) === "_" || typeof oldVal === "function" || oldVal === newVal) continue; - if ((key === "tick0" || key === "dtick") && outerparts[0] !== "geo") { - var tickMode = newContainer.tickmode; - if (tickMode === "auto" || tickMode === "array" || !tickMode) continue; - } - if (key === "range" && newContainer.autorange) continue; - if ((key === "zmin" || key === "zmax") && newContainer.type === "contourcarpet") continue; - valObject = getValObject(parts); - if (!valObject) continue; - if (valObject._compareAsJSON && JSON.stringify(oldVal) === JSON.stringify(newVal)) continue; - var valType = valObject.valType; - var i; - var canBeDataArray = valObjectCanBeDataArray(valObject); - var wasArray = Array.isArray(oldVal); - var nowArray = Array.isArray(newVal); - if (wasArray && nowArray) { - var inputKey = "_input_" + key; - var oldValIn = oldContainer[inputKey]; - var newValIn = newContainer[inputKey]; - if (Array.isArray(oldValIn) && oldValIn === newValIn) continue; - } - if (newVal === void 0) { - if (canBeDataArray && wasArray) flags.calc = true; - else changed(); - } else if (valObject._isLinkedToArray) { - var arrayEditIndices = []; - var extraIndices = false; - if (!inArray) flags.arrays[key] = arrayEditIndices; - var minLen = Math.min(oldVal.length, newVal.length); - var maxLen = Math.max(oldVal.length, newVal.length); - if (minLen !== maxLen) { - if (valObject.editType === "arraydraw") { - extraIndices = true; - } else { - changed(); - continue; - } - } - for (i = 0; i < minLen; i++) { - getDiffFlags( - oldVal[i], - newVal[i], - parts.concat(i), - // add array indices, but not if we're already in an array - Lib2.extendFlat({ inArray: key, arrayIndex: i }, opts) - ); - } - if (extraIndices) { - for (i = minLen; i < maxLen; i++) { - arrayEditIndices.push(i); - } - } - } else if (!valType && Lib2.isPlainObject(oldVal)) { - getDiffFlags(oldVal, newVal, parts, opts); - } else if (canBeDataArray) { - if (wasArray && nowArray) { - if (immutable) { - flags.calc = true; - } - if (immutable || opts.newDataRevision) { - changed(); - } - } else if (wasArray !== nowArray) { - flags.calc = true; - } else changed(); - } else if (wasArray && nowArray) { - if (oldVal.length !== newVal.length || String(oldVal) !== String(newVal)) { - changed(); - } - } else { - changed(); - } - } - for (key in newContainer) { - if (!(key in oldContainer || key.charAt(0) === "_" || typeof newContainer[key] === "function")) { - valObject = getValObject(outerparts.concat(key)); - if (valObjectCanBeDataArray(valObject) && Array.isArray(newContainer[key])) { - flags.calc = true; - return; - } else changed(); - } - } - } - function diffConfig(oldConfig, newConfig) { - var key; - for (key in oldConfig) { - if (key.charAt(0) === "_") continue; - var oldVal = oldConfig[key]; - var newVal = newConfig[key]; - if (oldVal !== newVal) { - if (Lib2.isPlainObject(oldVal) && Lib2.isPlainObject(newVal)) { - if (diffConfig(oldVal, newVal)) { - return true; - } - } else if (Array.isArray(oldVal) && Array.isArray(newVal)) { - if (oldVal.length !== newVal.length) { - return true; - } - for (var i = 0; i < oldVal.length; i++) { - if (oldVal[i] !== newVal[i]) { - if (Lib2.isPlainObject(oldVal[i]) && Lib2.isPlainObject(newVal[i])) { - if (diffConfig(oldVal[i], newVal[i])) { - return true; - } - } else { - return true; - } - } - } - } else { - return true; - } - } - } - } - function animate(gd, frameOrGroupNameOrFrameList, animationOpts) { - gd = Lib2.getGraphDiv(gd); - if (!Lib2.isPlotDiv(gd)) { - throw new Error( - "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before animating it. For more details, see https://plotly.com/javascript/animations/" - ); - } - var trans = gd._transitionData; - if (!trans._frameQueue) { - trans._frameQueue = []; - } - animationOpts = Plots2.supplyAnimationDefaults(animationOpts); - var transitionOpts = animationOpts.transition; - var frameOpts = animationOpts.frame; - if (trans._frameWaitingCnt === void 0) { - trans._frameWaitingCnt = 0; - } - function getTransitionOpts(i) { - if (Array.isArray(transitionOpts)) { - if (i >= transitionOpts.length) { - return transitionOpts[0]; - } else { - return transitionOpts[i]; - } - } else { - return transitionOpts; - } - } - function getFrameOpts(i) { - if (Array.isArray(frameOpts)) { - if (i >= frameOpts.length) { - return frameOpts[0]; - } else { - return frameOpts[i]; - } - } else { - return frameOpts; - } - } - function callbackOnNthTime(cb, n) { - var cnt = 0; - return function() { - if (cb && ++cnt === n) { - return cb(); - } - }; - } - return new Promise(function(resolve, reject) { - function discardExistingFrames() { - if (trans._frameQueue.length === 0) { - return; - } - while (trans._frameQueue.length) { - var next = trans._frameQueue.pop(); - if (next.onInterrupt) { - next.onInterrupt(); - } - } - gd.emit("plotly_animationinterrupted", []); - } - function queueFrames(frameList2) { - if (frameList2.length === 0) return; - for (var i2 = 0; i2 < frameList2.length; i2++) { - var computedFrame; - if (frameList2[i2].type === "byname") { - computedFrame = Plots2.computeFrame(gd, frameList2[i2].name); - } else { - computedFrame = frameList2[i2].data; - } - var frameOpts2 = getFrameOpts(i2); - var transitionOpts2 = getTransitionOpts(i2); - transitionOpts2.duration = Math.min(transitionOpts2.duration, frameOpts2.duration); - var nextFrame2 = { - frame: computedFrame, - name: frameList2[i2].name, - frameOpts: frameOpts2, - transitionOpts: transitionOpts2 - }; - if (i2 === frameList2.length - 1) { - nextFrame2.onComplete = callbackOnNthTime(resolve, 2); - nextFrame2.onInterrupt = reject; - } - trans._frameQueue.push(nextFrame2); - } - if (animationOpts.mode === "immediate") { - trans._lastFrameAt = -Infinity; - } - if (!trans._animationRaf) { - beginAnimationLoop(); - } - } - function stopAnimationLoop() { - gd.emit("plotly_animated"); - window.cancelAnimationFrame(trans._animationRaf); - trans._animationRaf = null; - } - function nextFrame() { - if (trans._currentFrame && trans._currentFrame.onComplete) { - trans._currentFrame.onComplete(); - } - var newFrame = trans._currentFrame = trans._frameQueue.shift(); - if (newFrame) { - var stringName = newFrame.name ? newFrame.name.toString() : null; - gd._fullLayout._currentFrame = stringName; - trans._lastFrameAt = Date.now(); - trans._timeToNext = newFrame.frameOpts.duration; - Plots2.transition( - gd, - newFrame.frame.data, - newFrame.frame.layout, - helpers2.coerceTraceIndices(gd, newFrame.frame.traces), - newFrame.frameOpts, - newFrame.transitionOpts - ).then(function() { - if (newFrame.onComplete) { - newFrame.onComplete(); - } - }); - gd.emit("plotly_animatingframe", { - name: stringName, - frame: newFrame.frame, - animation: { - frame: newFrame.frameOpts, - transition: newFrame.transitionOpts - } - }); - } else { - stopAnimationLoop(); - } - } - function beginAnimationLoop() { - gd.emit("plotly_animating"); - trans._lastFrameAt = -Infinity; - trans._timeToNext = 0; - trans._runningTransitions = 0; - trans._currentFrame = null; - var doFrame = function() { - trans._animationRaf = window.requestAnimationFrame(doFrame); - if (Date.now() - trans._lastFrameAt > trans._timeToNext) { - nextFrame(); - } - }; - doFrame(); - } - var configCounter = 0; - function setTransitionConfig(frame2) { - if (Array.isArray(transitionOpts)) { - if (configCounter >= transitionOpts.length) { - frame2.transitionOpts = transitionOpts[configCounter]; - } else { - frame2.transitionOpts = transitionOpts[0]; - } - } else { - frame2.transitionOpts = transitionOpts; - } - configCounter++; - return frame2; - } - var i, frame; - var frameList = []; - var allFrames = frameOrGroupNameOrFrameList === void 0 || frameOrGroupNameOrFrameList === null; - var isFrameArray = Array.isArray(frameOrGroupNameOrFrameList); - var isSingleFrame = !allFrames && !isFrameArray && Lib2.isPlainObject(frameOrGroupNameOrFrameList); - if (isSingleFrame) { - frameList.push({ - type: "object", - data: setTransitionConfig(Lib2.extendFlat({}, frameOrGroupNameOrFrameList)) - }); - } else if (allFrames || ["string", "number"].indexOf(typeof frameOrGroupNameOrFrameList) !== -1) { - for (i = 0; i < trans._frames.length; i++) { - frame = trans._frames[i]; - if (!frame) continue; - if (allFrames || String(frame.group) === String(frameOrGroupNameOrFrameList)) { - frameList.push({ - type: "byname", - name: String(frame.name), - data: setTransitionConfig({ name: frame.name }) - }); - } - } - } else if (isFrameArray) { - for (i = 0; i < frameOrGroupNameOrFrameList.length; i++) { - var frameOrName = frameOrGroupNameOrFrameList[i]; - if (["number", "string"].indexOf(typeof frameOrName) !== -1) { - frameOrName = String(frameOrName); - frameList.push({ - type: "byname", - name: frameOrName, - data: setTransitionConfig({ name: frameOrName }) - }); - } else if (Lib2.isPlainObject(frameOrName)) { - frameList.push({ - type: "object", - data: setTransitionConfig(Lib2.extendFlat({}, frameOrName)) - }); - } - } - } - for (i = 0; i < frameList.length; i++) { - frame = frameList[i]; - if (frame.type === "byname" && !trans._frameHash[frame.data.name]) { - Lib2.warn('animate failure: frame not found: "' + frame.data.name + '"'); - reject(); - return; - } - } - if (["next", "immediate"].indexOf(animationOpts.mode) !== -1) { - discardExistingFrames(); - } - if (animationOpts.direction === "reverse") { - frameList.reverse(); - } - var currentFrame = gd._fullLayout._currentFrame; - if (currentFrame && animationOpts.fromcurrent) { - var idx = -1; - for (i = 0; i < frameList.length; i++) { - frame = frameList[i]; - if (frame.type === "byname" && frame.name === currentFrame) { - idx = i; - break; - } - } - if (idx > 0 && idx < frameList.length - 1) { - var filteredFrameList = []; - for (i = 0; i < frameList.length; i++) { - frame = frameList[i]; - if (frameList[i].type !== "byname" || i > idx) { - filteredFrameList.push(frame); - } - } - frameList = filteredFrameList; - } - } - if (frameList.length > 0) { - queueFrames(frameList); - } else { - gd.emit("plotly_animated"); - resolve(); - } - }); - } - function addFrames(gd, frameList, indices) { - gd = Lib2.getGraphDiv(gd); - if (frameList === null || frameList === void 0) { - return Promise.resolve(); - } - if (!Lib2.isPlotDiv(gd)) { - throw new Error( - "This element is not a Plotly plot: " + gd + ". It's likely that you've failed to create a plot before adding frames. For more details, see https://plotly.com/javascript/animations/" - ); - } - var i, frame, j, idx; - var _frames = gd._transitionData._frames; - var _frameHash = gd._transitionData._frameHash; - if (!Array.isArray(frameList)) { - throw new Error("addFrames failure: frameList must be an Array of frame definitions" + frameList); - } - var bigIndex = _frames.length + frameList.length * 2; - var insertions = []; - var _frameHashLocal = {}; - for (i = frameList.length - 1; i >= 0; i--) { - if (!Lib2.isPlainObject(frameList[i])) continue; - var lookupName = frameList[i].name; - var name2 = (_frameHash[lookupName] || _frameHashLocal[lookupName] || {}).name; - var newName = frameList[i].name; - var collisionPresent = _frameHash[name2] || _frameHashLocal[name2]; - if (name2 && newName && typeof newName === "number" && collisionPresent && numericNameWarningCount < numericNameWarningCountLimit) { - numericNameWarningCount++; - Lib2.warn('addFrames: overwriting frame "' + (_frameHash[name2] || _frameHashLocal[name2]).name + '" with a frame whose name of type "number" also equates to "' + name2 + '". This is valid but may potentially lead to unexpected behavior since all plotly.js frame names are stored internally as strings.'); - if (numericNameWarningCount === numericNameWarningCountLimit) { - Lib2.warn("addFrames: This API call has yielded too many of these warnings. For the rest of this call, further warnings about numeric frame names will be suppressed."); - } - } - _frameHashLocal[lookupName] = { name: lookupName }; - insertions.push({ - frame: Plots2.supplyFrameDefaults(frameList[i]), - index: indices && indices[i] !== void 0 && indices[i] !== null ? indices[i] : bigIndex + i - }); - } - insertions.sort(function(a, b) { - if (a.index > b.index) return -1; - if (a.index < b.index) return 1; - return 0; - }); - var ops = []; - var revops = []; - var frameCount = _frames.length; - for (i = insertions.length - 1; i >= 0; i--) { - frame = insertions[i].frame; - if (typeof frame.name === "number") { - Lib2.warn("Warning: addFrames accepts frames with numeric names, but the numbers areimplicitly cast to strings"); - } - if (!frame.name) { - while (_frameHash[frame.name = "frame " + gd._transitionData._counter++]) ; - } - if (_frameHash[frame.name]) { - for (j = 0; j < _frames.length; j++) { - if ((_frames[j] || {}).name === frame.name) break; - } - ops.push({ type: "replace", index: j, value: frame }); - revops.unshift({ type: "replace", index: j, value: _frames[j] }); - } else { - idx = Math.max(0, Math.min(insertions[i].index, frameCount)); - ops.push({ type: "insert", index: idx, value: frame }); - revops.unshift({ type: "delete", index: idx }); - frameCount++; - } - } - var undoFunc = Plots2.modifyFrames; - var redoFunc = Plots2.modifyFrames; - var undoArgs = [gd, revops]; - var redoArgs = [gd, ops]; - if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return Plots2.modifyFrames(gd, ops); - } - function deleteFrames(gd, frameList) { - gd = Lib2.getGraphDiv(gd); - if (!Lib2.isPlotDiv(gd)) { - throw new Error("This element is not a Plotly plot: " + gd); - } - var i, idx; - var _frames = gd._transitionData._frames; - var ops = []; - var revops = []; - if (!frameList) { - frameList = []; - for (i = 0; i < _frames.length; i++) { - frameList.push(i); - } - } - frameList = frameList.slice(); - frameList.sort(); - for (i = frameList.length - 1; i >= 0; i--) { - idx = frameList[i]; - ops.push({ type: "delete", index: idx }); - revops.unshift({ type: "insert", index: idx, value: _frames[idx] }); - } - var undoFunc = Plots2.modifyFrames; - var redoFunc = Plots2.modifyFrames; - var undoArgs = [gd, revops]; - var redoArgs = [gd, ops]; - if (Queue) Queue.add(gd, undoFunc, undoArgs, redoFunc, redoArgs); - return Plots2.modifyFrames(gd, ops); - } - function purge(gd) { - gd = Lib2.getGraphDiv(gd); - var fullLayout = gd._fullLayout || {}; - var fullData = gd._fullData || []; - Plots2.cleanPlot([], {}, fullData, fullLayout); - Plots2.purge(gd); - Events2.purge(gd); - if (fullLayout._container) fullLayout._container.remove(); - delete gd._context; - return gd; - } - function calcInverseTransform(gd) { - var fullLayout = gd._fullLayout; - var newBBox = gd.getBoundingClientRect(); - if (Lib2.equalDomRects(newBBox, fullLayout._lastBBox)) return; - var m = fullLayout._invTransform = Lib2.inverseTransformMatrix(Lib2.getFullTransformMatrix(gd)); - fullLayout._invScaleX = Math.sqrt(m[0][0] * m[0][0] + m[0][1] * m[0][1] + m[0][2] * m[0][2]); - fullLayout._invScaleY = Math.sqrt(m[1][0] * m[1][0] + m[1][1] * m[1][1] + m[1][2] * m[1][2]); - fullLayout._lastBBox = newBBox; - } - function makePlotFramework(gd) { - var gd3 = d32.select(gd); - var fullLayout = gd._fullLayout; - fullLayout._calcInverseTransform = calcInverseTransform; - fullLayout._calcInverseTransform(gd); - fullLayout._container = gd3.selectAll(".plot-container").data([0]); - fullLayout._container.enter().insert("div", ":first-child").classed("plot-container", true).classed("plotly", true).style({ - width: "100%", - height: "100%" - }); - fullLayout._paperdiv = fullLayout._container.selectAll(".svg-container").data([0]); - fullLayout._paperdiv.enter().append("div").classed("user-select-none", true).classed("svg-container", true).style("position", "relative"); - fullLayout._glcontainer = fullLayout._paperdiv.selectAll(".gl-container").data([{}]); - fullLayout._glcontainer.enter().append("div").classed("gl-container", true); - fullLayout._paperdiv.selectAll(".main-svg").remove(); - fullLayout._paperdiv.select(".modebar-container").remove(); - fullLayout._paper = fullLayout._paperdiv.insert("svg", ":first-child").classed("main-svg", true); - fullLayout._toppaper = fullLayout._paperdiv.append("svg").classed("main-svg", true); - fullLayout._modebardiv = fullLayout._paperdiv.append("div"); - delete fullLayout._modeBar; - fullLayout._hoverpaper = fullLayout._paperdiv.append("svg").classed("main-svg", true); - if (!fullLayout._uid) { - var otherUids = {}; - d32.selectAll("defs").each(function() { - if (this.id) otherUids[this.id.split("-")[1]] = 1; - }); - fullLayout._uid = Lib2.randstr(otherUids); - } - fullLayout._paperdiv.selectAll(".main-svg").attr(xmlnsNamespaces2.svgAttrs); - fullLayout._defs = fullLayout._paper.append("defs").attr("id", "defs-" + fullLayout._uid); - fullLayout._clips = fullLayout._defs.append("g").classed("clips", true); - fullLayout._topdefs = fullLayout._toppaper.append("defs").attr("id", "topdefs-" + fullLayout._uid); - fullLayout._topclips = fullLayout._topdefs.append("g").classed("clips", true); - fullLayout._bgLayer = fullLayout._paper.append("g").classed("bglayer", true); - fullLayout._draggers = fullLayout._paper.append("g").classed("draglayer", true); - var layerBelow = fullLayout._paper.append("g").classed("layer-below", true); - fullLayout._imageLowerLayer = layerBelow.append("g").classed("imagelayer", true); - fullLayout._shapeLowerLayer = layerBelow.append("g").classed("shapelayer", true); - fullLayout._cartesianlayer = fullLayout._paper.append("g").classed("cartesianlayer", true); - fullLayout._polarlayer = fullLayout._paper.append("g").classed("polarlayer", true); - fullLayout._smithlayer = fullLayout._paper.append("g").classed("smithlayer", true); - fullLayout._ternarylayer = fullLayout._paper.append("g").classed("ternarylayer", true); - fullLayout._geolayer = fullLayout._paper.append("g").classed("geolayer", true); - fullLayout._funnelarealayer = fullLayout._paper.append("g").classed("funnelarealayer", true); - fullLayout._pielayer = fullLayout._paper.append("g").classed("pielayer", true); - fullLayout._iciclelayer = fullLayout._paper.append("g").classed("iciclelayer", true); - fullLayout._treemaplayer = fullLayout._paper.append("g").classed("treemaplayer", true); - fullLayout._sunburstlayer = fullLayout._paper.append("g").classed("sunburstlayer", true); - fullLayout._indicatorlayer = fullLayout._toppaper.append("g").classed("indicatorlayer", true); - fullLayout._glimages = fullLayout._paper.append("g").classed("glimages", true); - var layerAbove = fullLayout._toppaper.append("g").classed("layer-above", true); - fullLayout._imageUpperLayer = layerAbove.append("g").classed("imagelayer", true); - fullLayout._shapeUpperLayer = layerAbove.append("g").classed("shapelayer", true); - fullLayout._selectionLayer = fullLayout._toppaper.append("g").classed("selectionlayer", true); - fullLayout._infolayer = fullLayout._toppaper.append("g").classed("infolayer", true); - fullLayout._menulayer = fullLayout._toppaper.append("g").classed("menulayer", true); - fullLayout._zoomlayer = fullLayout._toppaper.append("g").classed("zoomlayer", true); - fullLayout._hoverlayer = fullLayout._hoverpaper.append("g").classed("hoverlayer", true); - fullLayout._modebardiv.classed("modebar-container", true).style("position", "absolute").style("top", "0px").style("right", "0px"); - gd.emit("plotly_framework"); - } - exports2.animate = animate; - exports2.addFrames = addFrames; - exports2.deleteFrames = deleteFrames; - exports2.addTraces = addTraces; - exports2.deleteTraces = deleteTraces; - exports2.extendTraces = extendTraces; - exports2.moveTraces = moveTraces; - exports2.prependTraces = prependTraces; - exports2.newPlot = newPlot; - exports2._doPlot = _doPlot; - exports2.purge = purge; - exports2.react = react; - exports2.redraw = redraw; - exports2.relayout = relayout; - exports2.restyle = restyle; - exports2.setPlotConfig = setPlotConfig; - exports2.update = update2; - exports2._guiRelayout = guiEdit(relayout); - exports2._guiRestyle = guiEdit(restyle); - exports2._guiUpdate = guiEdit(update2); - exports2._storeDirectGUIEdit = _storeDirectGUIEdit; -})(plot_api); -var helpers$o = {}; -var Registry$r = registry; -helpers$o.getDelay = function(fullLayout) { - if (!fullLayout._has) return 0; - return fullLayout._has("gl3d") || fullLayout._has("gl2d") || fullLayout._has("mapbox") || fullLayout._has("map") ? 500 : 0; -}; -helpers$o.getRedrawFunc = function(gd) { - return function() { - Registry$r.getComponentMethod("colorbar", "draw")(gd); - }; -}; -helpers$o.encodeSVG = function(svg) { - return "data:image/svg+xml," + encodeURIComponent(svg); -}; -helpers$o.encodeJSON = function(json) { - return "data:application/json," + encodeURIComponent(json); -}; -var DOM_URL = window.URL || window.webkitURL; -helpers$o.createObjectURL = function(blob) { - return DOM_URL.createObjectURL(blob); -}; -helpers$o.revokeObjectURL = function(url) { - return DOM_URL.revokeObjectURL(url); -}; -helpers$o.createBlob = function(url, format2) { - if (format2 === "svg") { - return new window.Blob([url], { type: "image/svg+xml;charset=utf-8" }); - } else if (format2 === "full-json") { - return new window.Blob([url], { type: "application/json;charset=utf-8" }); - } else { - var binary2 = fixBinary(window.atob(url)); - return new window.Blob([binary2], { type: "image/" + format2 }); - } -}; -helpers$o.octetStream = function(s) { - document.location.href = "data:application/octet-stream" + s; -}; -function fixBinary(b) { - var len = b.length; - var buf = new ArrayBuffer(len); - var arr = new Uint8Array(buf); - for (var i = 0; i < len; i++) { - arr[i] = b.charCodeAt(i); - } - return buf; -} -helpers$o.IMAGE_URL_PREFIX = /^data:image\/\w+;base64,/; -helpers$o.MSG_IE_BAD_FORMAT = "Sorry IE does not support downloading from canvas. Try {format:'svg'} instead."; -var d3$o = d3Exports; -var Lib$1g = libExports; -var Drawing$j = drawingExports; -var Color$v = colorExports; -var xmlnsNamespaces$2 = xmlns_namespaces; -var DOUBLEQUOTE_REGEX = /"/g; -var DUMMY_SUB = "TOBESTRIPPED"; -var DUMMY_REGEX = new RegExp('("' + DUMMY_SUB + ")|(" + DUMMY_SUB + '")', "g"); -function htmlEntityDecode(s) { - var hiddenDiv = d3$o.select("body").append("div").style({ display: "none" }).html(""); - var replaced = s.replace(/(&[^;]*;)/gi, function(d) { - if (d === "<") { - return "<"; - } - if (d === "&rt;") { - return ">"; - } - if (d.indexOf("<") !== -1 || d.indexOf(">") !== -1) { - return ""; - } - return hiddenDiv.html(d).text(); - }); - hiddenDiv.remove(); - return replaced; -} -function xmlEntityEncode(str2) { - return str2.replace(/&(?!\w+;|\#[0-9]+;| \#x[0-9A-F]+;)/g, "&"); -} -var tosvg = function toSVG(gd, format2, scale2) { - var fullLayout = gd._fullLayout; - var svg = fullLayout._paper; - var toppaper = fullLayout._toppaper; - var width = fullLayout.width; - var height = fullLayout.height; - var i; - svg.insert("rect", ":first-child").call(Drawing$j.setRect, 0, 0, width, height).call(Color$v.fill, fullLayout.paper_bgcolor); - var basePlotModules = fullLayout._basePlotModules || []; - for (i = 0; i < basePlotModules.length; i++) { - var _module = basePlotModules[i]; - if (_module.toSVG) _module.toSVG(gd); - } - if (toppaper) { - var nodes = toppaper.node().childNodes; - var topGroups = Array.prototype.slice.call(nodes); - for (i = 0; i < topGroups.length; i++) { - var topGroup = topGroups[i]; - if (topGroup.childNodes.length) svg.node().appendChild(topGroup); - } - } - if (fullLayout._draggers) { - fullLayout._draggers.remove(); - } - svg.node().style.background = ""; - svg.selectAll("text").attr({ "data-unformatted": null, "data-math": null }).each(function() { - var txt = d3$o.select(this); - if (this.style.visibility === "hidden" || this.style.display === "none") { - txt.remove(); - return; - } else { - txt.style({ visibility: null, display: null }); - } - var ff = this.style.fontFamily; - if (ff && ff.indexOf('"') !== -1) { - txt.style("font-family", ff.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); - } - var fw = this.style.fontWeight; - if (fw && (fw === "normal" || fw === "400")) { - txt.style("font-weight", void 0); - } - var fs = this.style.fontStyle; - if (fs && fs === "normal") { - txt.style("font-style", void 0); - } - var fv = this.style.fontVariant; - if (fv && fv === "normal") { - txt.style("font-variant", void 0); - } - }); - svg.selectAll(".gradient_filled,.pattern_filled").each(function() { - var pt = d3$o.select(this); - var fill = this.style.fill; - if (fill && fill.indexOf("url(") !== -1) { - pt.style("fill", fill.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); - } - var stroke = this.style.stroke; - if (stroke && stroke.indexOf("url(") !== -1) { - pt.style("stroke", stroke.replace(DOUBLEQUOTE_REGEX, DUMMY_SUB)); - } - }); - if (format2 === "pdf" || format2 === "eps") { - svg.selectAll("#MathJax_SVG_glyphs path").attr("stroke-width", 0); - } - svg.node().setAttributeNS(xmlnsNamespaces$2.xmlns, "xmlns", xmlnsNamespaces$2.svg); - svg.node().setAttributeNS(xmlnsNamespaces$2.xmlns, "xmlns:xlink", xmlnsNamespaces$2.xlink); - if (format2 === "svg" && scale2) { - svg.attr("width", scale2 * width); - svg.attr("height", scale2 * height); - svg.attr("viewBox", "0 0 " + width + " " + height); - } - var s = new window.XMLSerializer().serializeToString(svg.node()); - s = htmlEntityDecode(s); - s = xmlEntityEncode(s); - s = s.replace(DUMMY_REGEX, "'"); - if (Lib$1g.isIE()) { - s = s.replace(/"/gi, "'"); - s = s.replace(/(\('#)([^']*)('\))/gi, '("#$2")'); - s = s.replace(/(\\')/gi, '"'); - } - return s; -}; -var Lib$1f = libExports; -var EventEmitter$1 = eventsExports.EventEmitter; -var helpers$n = helpers$o; -function svgToImg$2(opts) { - var ev = opts.emitter || new EventEmitter$1(); - var promise = new Promise(function(resolve, reject) { - var Image2 = window.Image; - var svg = opts.svg; - var format2 = opts.format || "png"; - if (Lib$1f.isIE() && format2 !== "svg") { - var ieSvgError = new Error(helpers$n.MSG_IE_BAD_FORMAT); - reject(ieSvgError); - if (!opts.promise) { - return ev.emit("error", ieSvgError); - } else { - return promise; - } - } - var canvas2 = opts.canvas; - var scale2 = opts.scale || 1; - var w0 = opts.width || 300; - var h0 = opts.height || 150; - var w1 = scale2 * w0; - var h1 = scale2 * h0; - var ctx2 = canvas2.getContext("2d", { willReadFrequently: true }); - var img = new Image2(); - var svgBlob, url; - if (format2 === "svg" || Lib$1f.isSafari()) { - url = helpers$n.encodeSVG(svg); - } else { - svgBlob = helpers$n.createBlob(svg, "svg"); - url = helpers$n.createObjectURL(svgBlob); - } - canvas2.width = w1; - canvas2.height = h1; - img.onload = function() { - var imgData; - svgBlob = null; - helpers$n.revokeObjectURL(url); - if (format2 !== "svg") { - ctx2.drawImage(img, 0, 0, w1, h1); - } - switch (format2) { - case "jpeg": - imgData = canvas2.toDataURL("image/jpeg"); - break; - case "png": - imgData = canvas2.toDataURL("image/png"); - break; - case "webp": - imgData = canvas2.toDataURL("image/webp"); - break; - case "svg": - imgData = url; - break; - default: - var errorMsg = "Image format is not jpeg, png, svg or webp."; - reject(new Error(errorMsg)); - if (!opts.promise) { - return ev.emit("error", errorMsg); - } - } - resolve(imgData); - if (!opts.promise) { - ev.emit("success", imgData); - } - }; - img.onerror = function(err) { - svgBlob = null; - helpers$n.revokeObjectURL(url); - reject(err); - if (!opts.promise) { - return ev.emit("error", err); - } - }; - img.src = url; - }); - if (opts.promise) { - return promise; - } - return ev; -} -var svgtoimg = svgToImg$2; -var isNumeric$g = fastIsnumeric; -var plotApi = plot_api; -var plots = plotsExports; -var Lib$1e = libExports; -var helpers$m = helpers$o; -var toSVG$1 = tosvg; -var svgToImg$1 = svgtoimg; -var version = version$2.version; -var attrs$2 = { - format: { - valType: "enumerated", - values: ["png", "jpeg", "webp", "svg", "full-json"], - dflt: "png", - description: "Sets the format of exported image." - }, - width: { - valType: "number", - min: 1, - description: [ - "Sets the exported image width.", - "Defaults to the value found in `layout.width`", - "If set to *null*, the exported image width will match the current graph width." - ].join(" ") - }, - height: { - valType: "number", - min: 1, - description: [ - "Sets the exported image height.", - "Defaults to the value found in `layout.height`", - "If set to *null*, the exported image height will match the current graph height." - ].join(" ") - }, - scale: { - valType: "number", - min: 0, - dflt: 1, - description: [ - "Sets a scaling for the generated image.", - "If set, all features of a graphs (e.g. text, line width)", - "are scaled, unlike simply setting", - "a bigger *width* and *height*." - ].join(" ") - }, - setBackground: { - valType: "any", - dflt: false, - description: [ - "Sets the image background mode.", - "By default, the image background is determined by `layout.paper_bgcolor`,", - "the *transparent* mode.", - "One might consider setting `setBackground` to *opaque*", - "when exporting a *jpeg* image as JPEGs do not support opacity." - ].join(" ") - }, - imageDataOnly: { - valType: "boolean", - dflt: false, - description: [ - "Determines whether or not the return value is prefixed by", - "the image format's corresponding 'data:image;' spec." - ].join(" ") - } -}; -function toImage$2(gd, opts) { - opts = opts || {}; - var data; - var layout; - var config; - var fullLayout; - if (Lib$1e.isPlainObject(gd)) { - data = gd.data || []; - layout = gd.layout || {}; - config = gd.config || {}; - fullLayout = {}; - } else { - gd = Lib$1e.getGraphDiv(gd); - data = Lib$1e.extendDeep([], gd.data); - layout = Lib$1e.extendDeep({}, gd.layout); - config = gd._context; - fullLayout = gd._fullLayout || {}; - } - function isImpliedOrValid(attr) { - return !(attr in opts) || Lib$1e.validate(opts[attr], attrs$2[attr]); - } - if (!isImpliedOrValid("width") && opts.width !== null || !isImpliedOrValid("height") && opts.height !== null) { - throw new Error("Height and width should be pixel values."); - } - if (!isImpliedOrValid("format")) { - throw new Error("Export format is not " + Lib$1e.join2(attrs$2.format.values, ", ", " or ") + "."); - } - var fullOpts = {}; - function coerce2(attr, dflt) { - return Lib$1e.coerce(opts, fullOpts, attrs$2, attr, dflt); - } - var format2 = coerce2("format"); - var width = coerce2("width"); - var height = coerce2("height"); - var scale2 = coerce2("scale"); - var setBackground = coerce2("setBackground"); - var imageDataOnly = coerce2("imageDataOnly"); - var clonedGd = document.createElement("div"); - clonedGd.style.position = "absolute"; - clonedGd.style.left = "-5000px"; - document.body.appendChild(clonedGd); - var layoutImage = Lib$1e.extendFlat({}, layout); - if (width) { - layoutImage.width = width; - } else if (opts.width === null && isNumeric$g(fullLayout.width)) { - layoutImage.width = fullLayout.width; - } - if (height) { - layoutImage.height = height; - } else if (opts.height === null && isNumeric$g(fullLayout.height)) { - layoutImage.height = fullLayout.height; - } - var configImage = Lib$1e.extendFlat({}, config, { - _exportedPlot: true, - staticPlot: true, - setBackground - }); - var redrawFunc = helpers$m.getRedrawFunc(clonedGd); - function wait() { - return new Promise(function(resolve) { - setTimeout(resolve, helpers$m.getDelay(clonedGd._fullLayout)); - }); - } - function convert3() { - return new Promise(function(resolve, reject) { - var svg = toSVG$1(clonedGd, format2, scale2); - var width2 = clonedGd._fullLayout.width; - var height2 = clonedGd._fullLayout.height; - function cleanup() { - plotApi.purge(clonedGd); - document.body.removeChild(clonedGd); - } - if (format2 === "full-json") { - var json = plots.graphJson(clonedGd, false, "keepdata", "object", true, true); - json.version = version; - json = JSON.stringify(json); - cleanup(); - if (imageDataOnly) { - return resolve(json); - } else { - return resolve(helpers$m.encodeJSON(json)); - } - } - cleanup(); - if (format2 === "svg") { - if (imageDataOnly) { - return resolve(svg); - } else { - return resolve(helpers$m.encodeSVG(svg)); - } - } - var canvas2 = document.createElement("canvas"); - canvas2.id = Lib$1e.randstr(); - svgToImg$1({ - format: format2, - width: width2, - height: height2, - scale: scale2, - canvas: canvas2, - svg, - // ask svgToImg to return a Promise - // rather than EventEmitter - // leave EventEmitter for backward - // compatibility - promise: true - }).then(resolve).catch(reject); - }); - } - function urlToImageData(url) { - if (imageDataOnly) { - return url.replace(helpers$m.IMAGE_URL_PREFIX, ""); - } else { - return url; - } - } - return new Promise(function(resolve, reject) { - plotApi.newPlot(clonedGd, data, layoutImage, configImage).then(redrawFunc).then(wait).then(convert3).then(function(url) { - resolve(urlToImageData(url)); - }).catch(function(err) { - reject(err); - }); - }); -} -var to_image = toImage$2; -var Lib$1d = libExports; -var Plots$8 = plotsExports; -var PlotSchema$1 = plot_schema; -var dfltConfig$1 = plot_config.dfltConfig; -var isPlainObject$1 = Lib$1d.isPlainObject; -var isArray = Array.isArray; -var isArrayOrTypedArray$6 = Lib$1d.isArrayOrTypedArray; -var validate = function validate2(data, layout) { - if (data === void 0) data = []; - if (layout === void 0) layout = {}; - var schema = PlotSchema$1.get(); - var errorList = []; - var gd = { _context: Lib$1d.extendFlat({}, dfltConfig$1) }; - var dataIn, layoutIn; - if (isArray(data)) { - gd.data = Lib$1d.extendDeep([], data); - dataIn = data; - } else { - gd.data = []; - dataIn = []; - errorList.push(format$1("array", "data")); - } - if (isPlainObject$1(layout)) { - gd.layout = Lib$1d.extendDeep({}, layout); - layoutIn = layout; - } else { - gd.layout = {}; - layoutIn = {}; - if (arguments.length > 1) { - errorList.push(format$1("object", "layout")); - } - } - Plots$8.supplyDefaults(gd); - var dataOut = gd._fullData; - var len = dataIn.length; - for (var i = 0; i < len; i++) { - var traceIn = dataIn[i]; - var base = ["data", i]; - if (!isPlainObject$1(traceIn)) { - errorList.push(format$1("object", base)); - continue; - } - var traceOut = dataOut[i]; - var traceType = traceOut.type; - var traceSchema = schema.traces[traceType].attributes; - traceSchema.type = { - valType: "enumerated", - values: [traceType] - }; - if (traceOut.visible === false && traceIn.visible !== false) { - errorList.push(format$1("invisible", base)); - } - crawl(traceIn, traceOut, traceSchema, errorList, base); - var transformsIn = traceIn.transforms; - var transformsOut = traceOut.transforms; - if (transformsIn) { - if (!isArray(transformsIn)) { - errorList.push(format$1("array", base, ["transforms"])); - } - base.push("transforms"); - for (var j = 0; j < transformsIn.length; j++) { - var path = ["transforms", j]; - var transformType = transformsIn[j].type; - if (!isPlainObject$1(transformsIn[j])) { - errorList.push(format$1("object", base, path)); - continue; - } - var transformSchema = schema.transforms[transformType] ? schema.transforms[transformType].attributes : {}; - transformSchema.type = { - valType: "enumerated", - values: Object.keys(schema.transforms) - }; - crawl(transformsIn[j], transformsOut[j], transformSchema, errorList, base, path); - } - } - } - var layoutOut = gd._fullLayout; - var layoutSchema = fillLayoutSchema(schema, dataOut); - crawl(layoutIn, layoutOut, layoutSchema, errorList, "layout"); - return errorList.length === 0 ? void 0 : errorList; -}; -function crawl(objIn, objOut, schema, list, base, path) { - path = path || []; - var keys = Object.keys(objIn); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - if (k === "transforms") continue; - var p = path.slice(); - p.push(k); - var valIn = objIn[k]; - var valOut = objOut[k]; - var nestedSchema = getNestedSchema(schema, k); - var nestedValType = (nestedSchema || {}).valType; - var isInfoArray = nestedValType === "info_array"; - var isColorscale = nestedValType === "colorscale"; - var items = (nestedSchema || {}).items; - if (!isInSchema(schema, k)) { - list.push(format$1("schema", base, p)); - } else if (isPlainObject$1(valIn) && isPlainObject$1(valOut) && nestedValType !== "any") { - crawl(valIn, valOut, nestedSchema, list, base, p); - } else if (isInfoArray && isArray(valIn)) { - if (valIn.length > valOut.length) { - list.push(format$1("unused", base, p.concat(valOut.length))); - } - var len = valOut.length; - var arrayItems = Array.isArray(items); - if (arrayItems) len = Math.min(len, items.length); - var m, n, item, valInPart, valOutPart; - if (nestedSchema.dimensions === 2) { - for (n = 0; n < len; n++) { - if (isArray(valIn[n])) { - if (valIn[n].length > valOut[n].length) { - list.push(format$1("unused", base, p.concat(n, valOut[n].length))); - } - var len2 = valOut[n].length; - for (m = 0; m < (arrayItems ? Math.min(len2, items[n].length) : len2); m++) { - item = arrayItems ? items[n][m] : items; - valInPart = valIn[n][m]; - valOutPart = valOut[n][m]; - if (!Lib$1d.validate(valInPart, item)) { - list.push(format$1("value", base, p.concat(n, m), valInPart)); - } else if (valOutPart !== valInPart && valOutPart !== +valInPart) { - list.push(format$1("dynamic", base, p.concat(n, m), valInPart, valOutPart)); - } - } - } else { - list.push(format$1("array", base, p.concat(n), valIn[n])); - } - } - } else { - for (n = 0; n < len; n++) { - item = arrayItems ? items[n] : items; - valInPart = valIn[n]; - valOutPart = valOut[n]; - if (!Lib$1d.validate(valInPart, item)) { - list.push(format$1("value", base, p.concat(n), valInPart)); - } else if (valOutPart !== valInPart && valOutPart !== +valInPart) { - list.push(format$1("dynamic", base, p.concat(n), valInPart, valOutPart)); - } - } - } - } else if (nestedSchema.items && !isInfoArray && isArray(valIn)) { - var _nestedSchema = items[Object.keys(items)[0]]; - var indexList = []; - var j, _p; - for (j = 0; j < valOut.length; j++) { - var _index = valOut[j]._index || j; - _p = p.slice(); - _p.push(_index); - if (isPlainObject$1(valIn[_index]) && isPlainObject$1(valOut[j])) { - indexList.push(_index); - var valInj = valIn[_index]; - var valOutj = valOut[j]; - if (isPlainObject$1(valInj) && valInj.visible !== false && valOutj.visible === false) { - list.push(format$1("invisible", base, _p)); - } else crawl(valInj, valOutj, _nestedSchema, list, base, _p); - } - } - for (j = 0; j < valIn.length; j++) { - _p = p.slice(); - _p.push(j); - if (!isPlainObject$1(valIn[j])) { - list.push(format$1("object", base, _p, valIn[j])); - } else if (indexList.indexOf(j) === -1) { - list.push(format$1("unused", base, _p)); - } - } - } else if (!isPlainObject$1(valIn) && isPlainObject$1(valOut)) { - list.push(format$1("object", base, p, valIn)); - } else if (!isArrayOrTypedArray$6(valIn) && isArrayOrTypedArray$6(valOut) && !isInfoArray && !isColorscale) { - list.push(format$1("array", base, p, valIn)); - } else if (!(k in objOut)) { - list.push(format$1("unused", base, p, valIn)); - } else if (!Lib$1d.validate(valIn, nestedSchema)) { - list.push(format$1("value", base, p, valIn)); - } else if (nestedSchema.valType === "enumerated" && (nestedSchema.coerceNumber && valIn !== +valOut || valIn !== valOut)) { - list.push(format$1("dynamic", base, p, valIn, valOut)); - } - } - return list; -} -function fillLayoutSchema(schema, dataOut) { - var layoutSchema = schema.layout.layoutAttributes; - for (var i = 0; i < dataOut.length; i++) { - var traceOut = dataOut[i]; - var traceSchema = schema.traces[traceOut.type]; - var traceLayoutAttr = traceSchema.layoutAttributes; - if (traceLayoutAttr) { - if (traceOut.subplot) { - Lib$1d.extendFlat(layoutSchema[traceSchema.attributes.subplot.dflt], traceLayoutAttr); - } else { - Lib$1d.extendFlat(layoutSchema, traceLayoutAttr); - } - } - } - return layoutSchema; -} -var code2msgFunc = { - object: function(base, astr) { - var prefix; - if (base === "layout" && astr === "") prefix = "The layout argument"; - else if (base[0] === "data" && astr === "") { - prefix = "Trace " + base[1] + " in the data argument"; - } else prefix = inBase(base) + "key " + astr; - return prefix + " must be linked to an object container"; - }, - array: function(base, astr) { - var prefix; - if (base === "data") prefix = "The data argument"; - else prefix = inBase(base) + "key " + astr; - return prefix + " must be linked to an array container"; - }, - schema: function(base, astr) { - return inBase(base) + "key " + astr + " is not part of the schema"; - }, - unused: function(base, astr, valIn) { - var target = isPlainObject$1(valIn) ? "container" : "key"; - return inBase(base) + target + " " + astr + " did not get coerced"; - }, - dynamic: function(base, astr, valIn, valOut) { - return [ - inBase(base) + "key", - astr, - "(set to '" + valIn + "')", - "got reset to", - "'" + valOut + "'", - "during defaults." - ].join(" "); - }, - invisible: function(base, astr) { - return (astr ? inBase(base) + "item " + astr : "Trace " + base[1]) + " got defaulted to be not visible"; - }, - value: function(base, astr, valIn) { - return [ - inBase(base) + "key " + astr, - "is set to an invalid value (" + valIn + ")" - ].join(" "); - } -}; -function inBase(base) { - if (isArray(base)) return "In data trace " + base[1] + ", "; - return "In " + base + ", "; -} -function format$1(code2, base, path, valIn, valOut) { - path = path || ""; - var container, trace; - if (isArray(base)) { - container = base[0]; - trace = base[1]; - } else { - container = base; - trace = null; - } - var astr = convertPathToAttributeString(path); - var msg2 = code2msgFunc[code2](base, astr, valIn, valOut); - Lib$1d.log(msg2); - return { - code: code2, - container, - trace, - path, - astr, - msg: msg2 - }; -} -function isInSchema(schema, key) { - var parts = splitKey(key); - var keyMinusId = parts.keyMinusId; - var id = parts.id; - if (keyMinusId in schema && schema[keyMinusId]._isSubplotObj && id) { - return true; - } - return key in schema; -} -function getNestedSchema(schema, key) { - if (key in schema) return schema[key]; - var parts = splitKey(key); - return schema[parts.keyMinusId]; -} -var idRegex = Lib$1d.counterRegex("([a-z]+)"); -function splitKey(key) { - var idMatch = key.match(idRegex); - return { - keyMinusId: idMatch && idMatch[1], - id: idMatch && idMatch[2] - }; -} -function convertPathToAttributeString(path) { - if (!isArray(path)) return String(path); - var astr = ""; - for (var i = 0; i < path.length; i++) { - var p = path[i]; - if (typeof p === "number") { - astr = astr.substr(0, astr.length - 1) + "[" + p + "]"; - } else { - astr += p; - } - if (i < path.length - 1) astr += "."; - } - return astr; -} -var Lib$1c = libExports; -var helpers$l = helpers$o; -function fileSaver$1(url, name2, format2) { - var saveLink = document.createElement("a"); - var canUseSaveLink = "download" in saveLink; - var promise = new Promise(function(resolve, reject) { - var blob; - var objectUrl; - if (Lib$1c.isIE()) { - blob = helpers$l.createBlob(url, "svg"); - window.navigator.msSaveBlob(blob, name2); - blob = null; - return resolve(name2); - } - if (canUseSaveLink) { - blob = helpers$l.createBlob(url, format2); - objectUrl = helpers$l.createObjectURL(blob); - saveLink.href = objectUrl; - saveLink.download = name2; - document.body.appendChild(saveLink); - saveLink.click(); - document.body.removeChild(saveLink); - helpers$l.revokeObjectURL(objectUrl); - blob = null; - return resolve(name2); - } - if (Lib$1c.isSafari()) { - var prefix = format2 === "svg" ? "," : ";base64,"; - helpers$l.octetStream(prefix + encodeURIComponent(url)); - return resolve(name2); - } - reject(new Error("download error")); - }); - return promise; -} -var filesaver = fileSaver$1; -var Lib$1b = libExports; -var toImage$1 = to_image; -var fileSaver = filesaver; -var helpers$k = helpers$o; -function downloadImage(gd, opts) { - var _gd; - if (!Lib$1b.isPlainObject(gd)) _gd = Lib$1b.getGraphDiv(gd); - opts = opts || {}; - opts.format = opts.format || "png"; - opts.width = opts.width || null; - opts.height = opts.height || null; - opts.imageDataOnly = true; - return new Promise(function(resolve, reject) { - if (_gd && _gd._snapshotInProgress) { - reject(new Error("Snapshotting already in progress.")); - } - if (Lib$1b.isIE() && opts.format !== "svg") { - reject(new Error(helpers$k.MSG_IE_BAD_FORMAT)); - } - if (_gd) _gd._snapshotInProgress = true; - var promise = toImage$1(gd, opts); - var filename = opts.filename || gd.fn || "newplot"; - filename += "." + opts.format.replace("-", "."); - promise.then(function(result) { - if (_gd) _gd._snapshotInProgress = false; - return fileSaver(result, filename, opts.format); - }).then(function(name2) { - resolve(name2); - }).catch(function(err) { - if (_gd) _gd._snapshotInProgress = false; - reject(err); - }); - }); -} -var download = downloadImage; -var template_api = {}; -var Lib$1a = libExports; -var isPlainObject2 = Lib$1a.isPlainObject; -var PlotSchema = plot_schema; -var Plots$7 = plotsExports; -var plotAttributes = attributes$O; -var Template$3 = plot_template; -var dfltConfig = plot_config.dfltConfig; -template_api.makeTemplate = function(figure) { - figure = Lib$1a.isPlainObject(figure) ? figure : Lib$1a.getGraphDiv(figure); - figure = Lib$1a.extendDeep({ _context: dfltConfig }, { data: figure.data, layout: figure.layout }); - Plots$7.supplyDefaults(figure); - var data = figure.data || []; - var layout = figure.layout || {}; - layout._basePlotModules = figure._fullLayout._basePlotModules; - layout._modules = figure._fullLayout._modules; - var template = { - data: {}, - layout: {} - }; - data.forEach(function(trace) { - var traceTemplate = {}; - walkStyleKeys(trace, traceTemplate, getTraceInfo.bind(null, trace)); - var traceType2 = Lib$1a.coerce(trace, {}, plotAttributes, "type"); - var typeTemplates2 = template.data[traceType2]; - if (!typeTemplates2) typeTemplates2 = template.data[traceType2] = []; - typeTemplates2.push(traceTemplate); - }); - walkStyleKeys(layout, template.layout, getLayoutInfo.bind(null, layout)); - delete template.layout.template; - var oldTemplate = layout.template; - if (isPlainObject2(oldTemplate)) { - var oldLayoutTemplate = oldTemplate.layout; - var i, traceType, oldTypeTemplates, oldTypeLen, typeTemplates, typeLen; - if (isPlainObject2(oldLayoutTemplate)) { - mergeTemplates(oldLayoutTemplate, template.layout); - } - var oldDataTemplate = oldTemplate.data; - if (isPlainObject2(oldDataTemplate)) { - for (traceType in template.data) { - oldTypeTemplates = oldDataTemplate[traceType]; - if (Array.isArray(oldTypeTemplates)) { - typeTemplates = template.data[traceType]; - typeLen = typeTemplates.length; - oldTypeLen = oldTypeTemplates.length; - for (i = 0; i < typeLen; i++) { - mergeTemplates(oldTypeTemplates[i % oldTypeLen], typeTemplates[i]); - } - for (i = typeLen; i < oldTypeLen; i++) { - typeTemplates.push(Lib$1a.extendDeep({}, oldTypeTemplates[i])); - } - } - } - for (traceType in oldDataTemplate) { - if (!(traceType in template.data)) { - template.data[traceType] = Lib$1a.extendDeep([], oldDataTemplate[traceType]); - } - } - } - } - return template; -}; -function mergeTemplates(oldTemplate, newTemplate) { - oldTemplate = Lib$1a.extendDeep({}, oldTemplate); - var oldKeys = Object.keys(oldTemplate).sort(); - var i, j; - function mergeOne(oldVal2, newVal, key3) { - if (isPlainObject2(newVal) && isPlainObject2(oldVal2)) { - mergeTemplates(oldVal2, newVal); - } else if (Array.isArray(newVal) && Array.isArray(oldVal2)) { - var templater = Template$3.arrayTemplater({ _template: oldTemplate }, key3); - for (j = 0; j < newVal.length; j++) { - var item = newVal[j]; - var oldItem = templater.newItem(item)._template; - if (oldItem) mergeTemplates(oldItem, item); - } - var defaultItems = templater.defaultItems(); - for (j = 0; j < defaultItems.length; j++) newVal.push(defaultItems[j]._template); - for (j = 0; j < newVal.length; j++) delete newVal[j].templateitemname; - } - } - for (i = 0; i < oldKeys.length; i++) { - var key = oldKeys[i]; - var oldVal = oldTemplate[key]; - if (key in newTemplate) { - mergeOne(oldVal, newTemplate[key], key); - } else newTemplate[key] = oldVal; - if (getBaseKey(key) === key) { - for (var key2 in newTemplate) { - var baseKey2 = getBaseKey(key2); - if (key2 !== baseKey2 && baseKey2 === key && !(key2 in oldTemplate)) { - mergeOne(oldVal, newTemplate[key2], key); - } - } - } - } -} -function getBaseKey(key) { - return key.replace(/[0-9]+$/, ""); -} -function walkStyleKeys(parent, templateOut, getAttributeInfo, path, basePath) { - var pathAttr = basePath && getAttributeInfo(basePath); - for (var key in parent) { - var child = parent[key]; - var nextPath = getNextPath(parent, key, path); - var nextBasePath = getNextPath(parent, key, basePath); - var attr = getAttributeInfo(nextBasePath); - if (!attr) { - var baseKey = getBaseKey(key); - if (baseKey !== key) { - nextBasePath = getNextPath(parent, baseKey, basePath); - attr = getAttributeInfo(nextBasePath); - } - } - if (pathAttr && pathAttr === attr) continue; - if (!attr || attr._noTemplating || attr.valType === "data_array" || attr.arrayOk && Array.isArray(child)) { - continue; - } - if (!attr.valType && isPlainObject2(child)) { - walkStyleKeys(child, templateOut, getAttributeInfo, nextPath, nextBasePath); - } else if (attr._isLinkedToArray && Array.isArray(child)) { - var dfltDone = false; - var namedIndex = 0; - var usedNames = {}; - for (var i = 0; i < child.length; i++) { - var item = child[i]; - if (isPlainObject2(item)) { - var name2 = item.name; - if (name2) { - if (!usedNames[name2]) { - walkStyleKeys( - item, - templateOut, - getAttributeInfo, - getNextPath(child, namedIndex, nextPath), - getNextPath(child, namedIndex, nextBasePath) - ); - namedIndex++; - usedNames[name2] = 1; - } - } else if (!dfltDone) { - var dfltKey = Template$3.arrayDefaultKey(key); - var dfltPath = getNextPath(parent, dfltKey, path); - var pathInArray = getNextPath(child, namedIndex, nextPath); - walkStyleKeys( - item, - templateOut, - getAttributeInfo, - pathInArray, - getNextPath(child, namedIndex, nextBasePath) - ); - var itemPropInArray = Lib$1a.nestedProperty(templateOut, pathInArray); - var dfltProp = Lib$1a.nestedProperty(templateOut, dfltPath); - dfltProp.set(itemPropInArray.get()); - itemPropInArray.set(null); - dfltDone = true; - } - } - } - } else { - var templateProp = Lib$1a.nestedProperty(templateOut, nextPath); - templateProp.set(child); - } - } -} -function getLayoutInfo(layout, path) { - return PlotSchema.getLayoutValObject( - layout, - Lib$1a.nestedProperty({}, path).parts - ); -} -function getTraceInfo(trace, path) { - return PlotSchema.getTraceValObject( - trace, - Lib$1a.nestedProperty({}, path).parts - ); -} -function getNextPath(parent, key, path) { - var nextPath; - if (!path) nextPath = key; - else if (Array.isArray(parent)) nextPath = path + "[" + key + "]"; - else nextPath = path + "." + key; - return nextPath; -} -template_api.validateTemplate = function(figureIn, template) { - var figure = Lib$1a.extendDeep({}, { - _context: dfltConfig, - data: figureIn.data, - layout: figureIn.layout - }); - var layout = figure.layout || {}; - if (!isPlainObject2(template)) template = layout.template || {}; - var layoutTemplate = template.layout; - var dataTemplate = template.data; - var errorList = []; - figure.layout = layout; - figure.layout.template = template; - Plots$7.supplyDefaults(figure); - var fullLayout = figure._fullLayout; - var fullData = figure._fullData; - var layoutPaths = {}; - function crawlLayoutForContainers(obj, paths) { - for (var key in obj) { - if (key.charAt(0) !== "_" && isPlainObject2(obj[key])) { - var baseKey = getBaseKey(key); - var nextPaths = []; - var i2; - for (i2 = 0; i2 < paths.length; i2++) { - nextPaths.push(getNextPath(obj, key, paths[i2])); - if (baseKey !== key) nextPaths.push(getNextPath(obj, baseKey, paths[i2])); - } - for (i2 = 0; i2 < nextPaths.length; i2++) { - layoutPaths[nextPaths[i2]] = 1; - } - crawlLayoutForContainers(obj[key], nextPaths); - } - } - } - function crawlLayoutTemplateForContainers(obj, path) { - for (var key in obj) { - if (key.indexOf("defaults") === -1 && isPlainObject2(obj[key])) { - var nextPath = getNextPath(obj, key, path); - if (layoutPaths[nextPath]) { - crawlLayoutTemplateForContainers(obj[key], nextPath); - } else { - errorList.push({ code: "unused", path: nextPath }); - } - } - } - } - if (!isPlainObject2(layoutTemplate)) { - errorList.push({ code: "layout" }); - } else { - crawlLayoutForContainers(fullLayout, ["layout"]); - crawlLayoutTemplateForContainers(layoutTemplate, "layout"); - } - if (!isPlainObject2(dataTemplate)) { - errorList.push({ code: "data" }); - } else { - var typeCount = {}; - var traceType; - for (var i = 0; i < fullData.length; i++) { - var fullTrace = fullData[i]; - traceType = fullTrace.type; - typeCount[traceType] = (typeCount[traceType] || 0) + 1; - if (!fullTrace._fullInput._template) { - errorList.push({ - code: "missing", - index: fullTrace._fullInput.index, - traceType - }); - } - } - for (traceType in dataTemplate) { - var templateCount = dataTemplate[traceType].length; - var dataCount = typeCount[traceType] || 0; - if (templateCount > dataCount) { - errorList.push({ - code: "unused", - traceType, - templateCount, - dataCount - }); - } else if (dataCount > templateCount) { - errorList.push({ - code: "reused", - traceType, - templateCount, - dataCount - }); - } - } - } - function crawlForMissingTemplates(obj, path) { - for (var key in obj) { - if (key.charAt(0) === "_") continue; - var val = obj[key]; - var nextPath = getNextPath(obj, key, path); - if (isPlainObject2(val)) { - if (Array.isArray(obj) && val._template === false && val.templateitemname) { - errorList.push({ - code: "missing", - path: nextPath, - templateitemname: val.templateitemname - }); - } - crawlForMissingTemplates(val, nextPath); - } else if (Array.isArray(val) && hasPlainObject(val)) { - crawlForMissingTemplates(val, nextPath); - } - } - } - crawlForMissingTemplates({ data: fullData, layout: fullLayout }, ""); - if (errorList.length) return errorList.map(format); -}; -function hasPlainObject(arr) { - for (var i = 0; i < arr.length; i++) { - if (isPlainObject2(arr[i])) return true; - } -} -function format(opts) { - var msg2; - switch (opts.code) { - case "data": - msg2 = "The template has no key data."; - break; - case "layout": - msg2 = "The template has no key layout."; - break; - case "missing": - if (opts.path) { - msg2 = "There are no templates for item " + opts.path + " with name " + opts.templateitemname; - } else { - msg2 = "There are no templates for trace " + opts.index + ", of type " + opts.traceType + "."; - } - break; - case "unused": - if (opts.path) { - msg2 = "The template item at " + opts.path + " was not used in constructing the plot."; - } else if (opts.dataCount) { - msg2 = "Some of the templates of type " + opts.traceType + " were not used. The template has " + opts.templateCount + " traces, the data only has " + opts.dataCount + " of this type."; - } else { - msg2 = "The template has " + opts.templateCount + " traces of type " + opts.traceType + " but there are none in the data."; - } - break; - case "reused": - msg2 = "Some of the templates of type " + opts.traceType + " were used more than once. The template has " + opts.templateCount + " traces, the data has " + opts.dataCount + " of this type."; - break; - } - opts.msg = msg2; - return opts; -} -var main = plot_api; -plot_api$1._doPlot = main._doPlot; -plot_api$1.newPlot = main.newPlot; -plot_api$1.restyle = main.restyle; -plot_api$1.relayout = main.relayout; -plot_api$1.redraw = main.redraw; -plot_api$1.update = main.update; -plot_api$1._guiRestyle = main._guiRestyle; -plot_api$1._guiRelayout = main._guiRelayout; -plot_api$1._guiUpdate = main._guiUpdate; -plot_api$1._storeDirectGUIEdit = main._storeDirectGUIEdit; -plot_api$1.react = main.react; -plot_api$1.extendTraces = main.extendTraces; -plot_api$1.prependTraces = main.prependTraces; -plot_api$1.addTraces = main.addTraces; -plot_api$1.deleteTraces = main.deleteTraces; -plot_api$1.moveTraces = main.moveTraces; -plot_api$1.purge = main.purge; -plot_api$1.addFrames = main.addFrames; -plot_api$1.deleteFrames = main.deleteFrames; -plot_api$1.animate = main.animate; -plot_api$1.setPlotConfig = main.setPlotConfig; -var getGraphDiv = dom.getGraphDiv; -var eraseActiveShape = draw_1$3.eraseActiveShape; -plot_api$1.deleteActiveShape = function(gd) { - return eraseActiveShape(getGraphDiv(gd)); -}; -plot_api$1.toImage = to_image; -plot_api$1.validate = validate; -plot_api$1.downloadImage = download; -var templateApi = template_api; -plot_api$1.makeTemplate = templateApi.makeTemplate; -plot_api$1.validateTemplate = templateApi.validateTemplate; -var Lib$19 = libExports; -var Registry$q = registry; -var xy_defaults = function handleXYDefaults(traceIn, traceOut, layout, coerce2) { - var x = coerce2("x"); - var y = coerce2("y"); - var len; - var handleCalendarDefaults = Registry$q.getComponentMethod("calendars", "handleTraceDefaults"); - handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout); - if (x) { - var xlen = Lib$19.minRowLength(x); - if (y) { - len = Math.min(xlen, Lib$19.minRowLength(y)); - } else { - len = xlen; - coerce2("y0"); - coerce2("dy"); - } - } else { - if (!y) return 0; - len = Lib$19.minRowLength(y); - coerce2("x0"); - coerce2("dx"); - } - traceOut._length = len; - return len; -}; -var dateTick0 = libExports.dateTick0; -var numConstants$2 = numerical; -var ONEWEEK = numConstants$2.ONEWEEK; -function getPeriod0Dflt(period, calendar) { - if (period % ONEWEEK === 0) { - return dateTick0(calendar, 1); - } - return dateTick0(calendar, 0); -} -var period_defaults = function handlePeriodDefaults(traceIn, traceOut, layout, coerce2, opts) { - if (!opts) { - opts = { - x: true, - y: true - }; - } - if (opts.x) { - var xperiod = coerce2("xperiod"); - if (xperiod) { - coerce2("xperiod0", getPeriod0Dflt(xperiod, traceOut.xcalendar)); - coerce2("xperiodalignment"); - } - } - if (opts.y) { - var yperiod = coerce2("yperiod"); - if (yperiod) { - coerce2("yperiod0", getPeriod0Dflt(yperiod, traceOut.ycalendar)); - coerce2("yperiodalignment"); - } - } -}; -var perStackAttrs = ["orientation", "groupnorm", "stackgaps"]; -var stack_defaults = function handleStackDefaults(traceIn, traceOut, layout, coerce2) { - var stackOpts = layout._scatterStackOpts; - var stackGroup = coerce2("stackgroup"); - if (stackGroup) { - var subplot = traceOut.xaxis + traceOut.yaxis; - var subplotStackOpts = stackOpts[subplot]; - if (!subplotStackOpts) subplotStackOpts = stackOpts[subplot] = {}; - var groupOpts = subplotStackOpts[stackGroup]; - var firstTrace = false; - if (groupOpts) { - groupOpts.traces.push(traceOut); - } else { - groupOpts = subplotStackOpts[stackGroup] = { - // keep track of trace indices for use during stacking calculations - // this will be filled in during `calc` and used during `crossTraceCalc` - // so it's OK if we don't recreate it during a non-calc edit - traceIndices: [], - // Hold on to the whole set of prior traces - // First one is most important, so we can clear defaults - // there if we find explicit values only in later traces. - // We're only going to *use* the values stored in groupOpts, - // but for the editor and validate we want things self-consistent - // The full set of traces is used only to fix `fill` default if - // we find `orientation: 'h'` beyond the first trace - traces: [traceOut] - }; - firstTrace = true; - } - var dflts = { - orientation: traceOut.x && !traceOut.y ? "h" : "v" - }; - for (var i = 0; i < perStackAttrs.length; i++) { - var attr = perStackAttrs[i]; - var attrFound = attr + "Found"; - if (!groupOpts[attrFound]) { - var traceHasAttr = traceIn[attr] !== void 0; - var isOrientation = attr === "orientation"; - if (traceHasAttr || firstTrace) { - groupOpts[attr] = coerce2(attr, dflts[attr]); - if (isOrientation) { - groupOpts.fillDflt = groupOpts[attr] === "h" ? "tonextx" : "tonexty"; - } - if (traceHasAttr) { - groupOpts[attrFound] = true; - if (!firstTrace) { - delete groupOpts.traces[0][attr]; - if (isOrientation) { - for (var j = 0; j < groupOpts.traces.length - 1; j++) { - var trace2 = groupOpts.traces[j]; - if (trace2._input.fill !== trace2.fill) { - trace2.fill = groupOpts.fillDflt; - } - } - } - } - } - } - } - } - return groupOpts; - } -}; -var Color$u = colorExports; -var hasColorscale$5 = helpers$L.hasColorscale; -var colorscaleDefaults$3 = defaults$n; -var subTypes$8 = subtypes$3; -var marker_defaults = function markerDefaults(traceIn, traceOut, defaultColor, layout, coerce2, opts) { - var isBubble = subTypes$8.isBubble(traceIn); - var lineColor = (traceIn.line || {}).color; - var defaultMLC; - opts = opts || {}; - if (lineColor) defaultColor = lineColor; - coerce2("marker.symbol"); - coerce2("marker.opacity", isBubble ? 0.7 : 1); - coerce2("marker.size"); - if (!opts.noAngle) { - coerce2("marker.angle"); - if (!opts.noAngleRef) { - coerce2("marker.angleref"); - } - if (!opts.noStandOff) { - coerce2("marker.standoff"); - } - } - coerce2("marker.color", defaultColor); - if (hasColorscale$5(traceIn, "marker")) { - colorscaleDefaults$3(traceIn, traceOut, layout, coerce2, { prefix: "marker.", cLetter: "c" }); - } - if (!opts.noSelect) { - coerce2("selected.marker.color"); - coerce2("unselected.marker.color"); - coerce2("selected.marker.size"); - coerce2("unselected.marker.size"); - } - if (!opts.noLine) { - if (lineColor && !Array.isArray(lineColor) && traceOut.marker.color !== lineColor) { - defaultMLC = lineColor; - } else if (isBubble) defaultMLC = Color$u.background; - else defaultMLC = Color$u.defaultLine; - coerce2("marker.line.color", defaultMLC); - if (hasColorscale$5(traceIn, "marker.line")) { - colorscaleDefaults$3(traceIn, traceOut, layout, coerce2, { prefix: "marker.line.", cLetter: "c" }); - } - coerce2("marker.line.width", isBubble ? 1 : 0); - } - if (isBubble) { - coerce2("marker.sizeref"); - coerce2("marker.sizemin"); - coerce2("marker.sizemode"); - } - if (opts.gradient) { - var gradientType = coerce2("marker.gradient.type"); - if (gradientType !== "none") { - coerce2("marker.gradient.color"); - } - } -}; -var isArrayOrTypedArray$5 = libExports.isArrayOrTypedArray; -var hasColorscale$4 = helpers$L.hasColorscale; -var colorscaleDefaults$2 = defaults$n; -var line_defaults = function lineDefaults(traceIn, traceOut, defaultColor, layout, coerce2, opts) { - if (!opts) opts = {}; - var markerColor = (traceIn.marker || {}).color; - if (markerColor && markerColor._inputArray) markerColor = markerColor._inputArray; - coerce2("line.color", defaultColor); - if (hasColorscale$4(traceIn, "line")) { - colorscaleDefaults$2(traceIn, traceOut, layout, coerce2, { prefix: "line.", cLetter: "c" }); - } else { - var lineColorDflt = (isArrayOrTypedArray$5(markerColor) ? false : markerColor) || defaultColor; - coerce2("line.color", lineColorDflt); - } - coerce2("line.width"); - if (!opts.noDash) coerce2("line.dash"); - if (opts.backoff) coerce2("line.backoff"); -}; -var line_shape_defaults = function handleLineShapeDefaults(traceIn, traceOut, coerce2) { - var shape = coerce2("line.shape"); - if (shape === "spline") coerce2("line.smoothing"); -}; -var Lib$18 = libExports; -var text_defaults = function(traceIn, traceOut, layout, coerce2, opts) { - opts = opts || {}; - coerce2("textposition"); - Lib$18.coerceFont(coerce2, "textfont", opts.font || layout.font, opts); - if (!opts.noSelect) { - coerce2("selected.textfont.color"); - coerce2("unselected.textfont.color"); - } -}; -var Color$t = colorExports; -var isArrayOrTypedArray$4 = libExports.isArrayOrTypedArray; -function averageColors(colorscale2) { - var color2 = Color$t.interpolate(colorscale2[0][1], colorscale2[1][1], 0.5); - for (var i = 2; i < colorscale2.length; i++) { - var averageColorI = Color$t.interpolate(colorscale2[i - 1][1], colorscale2[i][1], 0.5); - color2 = Color$t.interpolate(color2, averageColorI, colorscale2[i - 1][0] / colorscale2[i][0]); - } - return color2; -} -var fillcolor_defaults = function fillColorDefaults(traceIn, traceOut, defaultColor, coerce2, opts) { - if (!opts) opts = {}; - var inheritColorFromMarker = false; - if (traceOut.marker) { - var markerColor = traceOut.marker.color; - var markerLineColor = (traceOut.marker.line || {}).color; - if (markerColor && !isArrayOrTypedArray$4(markerColor)) { - inheritColorFromMarker = markerColor; - } else if (markerLineColor && !isArrayOrTypedArray$4(markerLineColor)) { - inheritColorFromMarker = markerLineColor; - } - } - var averageGradientColor; - if (opts.moduleHasFillgradient) { - var gradientOrientation = coerce2("fillgradient.type"); - if (gradientOrientation !== "none") { - coerce2("fillgradient.start"); - coerce2("fillgradient.stop"); - var gradientColorscale = coerce2("fillgradient.colorscale"); - if (gradientColorscale) { - averageGradientColor = averageColors(gradientColorscale); - } - } - } - coerce2("fillcolor", Color$t.addOpacity( - (traceOut.line || {}).color || inheritColorFromMarker || averageGradientColor || defaultColor, - 0.5 - )); -}; -var Lib$17 = libExports; -var Registry$p = registry; -var attributes$x = attributes$A; -var constants$z = constants$B; -var subTypes$7 = subtypes$3; -var handleXYDefaults$2 = xy_defaults; -var handlePeriodDefaults$3 = period_defaults; -var handleStackDefaults2 = stack_defaults; -var handleMarkerDefaults$3 = marker_defaults; -var handleLineDefaults$1 = line_defaults; -var handleLineShapeDefaults2 = line_shape_defaults; -var handleTextDefaults$1 = text_defaults; -var handleFillColorDefaults$1 = fillcolor_defaults; -var coercePattern$2 = libExports.coercePattern; -var defaults$h = function supplyDefaults2(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$17.coerce(traceIn, traceOut, attributes$x, attr, dflt); - } - var len = handleXYDefaults$2(traceIn, traceOut, layout, coerce2); - if (!len) traceOut.visible = false; - if (!traceOut.visible) return; - handlePeriodDefaults$3(traceIn, traceOut, layout, coerce2); - coerce2("xhoverformat"); - coerce2("yhoverformat"); - coerce2("zorder"); - var stackGroupOpts = handleStackDefaults2(traceIn, traceOut, layout, coerce2); - if (layout.scattermode === "group" && traceOut.orientation === void 0) { - coerce2("orientation", "v"); - } - var defaultMode = !stackGroupOpts && len < constants$z.PTS_LINESONLY ? "lines+markers" : "lines"; - coerce2("text"); - coerce2("hovertext"); - coerce2("mode", defaultMode); - if (subTypes$7.hasMarkers(traceOut)) { - handleMarkerDefaults$3(traceIn, traceOut, defaultColor, layout, coerce2, { gradient: true }); - } - if (subTypes$7.hasLines(traceOut)) { - handleLineDefaults$1(traceIn, traceOut, defaultColor, layout, coerce2, { backoff: true }); - handleLineShapeDefaults2(traceIn, traceOut, coerce2); - coerce2("connectgaps"); - coerce2("line.simplify"); - } - if (subTypes$7.hasText(traceOut)) { - coerce2("texttemplate"); - handleTextDefaults$1(traceIn, traceOut, layout, coerce2); - } - var dfltHoverOn = []; - if (subTypes$7.hasMarkers(traceOut) || subTypes$7.hasText(traceOut)) { - coerce2("cliponaxis"); - coerce2("marker.maxdisplayed"); - dfltHoverOn.push("points"); - } - coerce2("fill", stackGroupOpts ? stackGroupOpts.fillDflt : "none"); - if (traceOut.fill !== "none") { - handleFillColorDefaults$1(traceIn, traceOut, defaultColor, coerce2, { - moduleHasFillgradient: true - }); - if (!subTypes$7.hasLines(traceOut)) handleLineShapeDefaults2(traceIn, traceOut, coerce2); - coercePattern$2(coerce2, "fillpattern", traceOut.fillcolor, false); - } - var lineColor = (traceOut.line || {}).color; - var markerColor = (traceOut.marker || {}).color; - if (traceOut.fill === "tonext" || traceOut.fill === "toself") { - dfltHoverOn.push("fills"); - } - coerce2("hoveron", dfltHoverOn.join("+") || "points"); - if (traceOut.hoveron !== "fills") coerce2("hovertemplate"); - var errorBarsSupplyDefaults = Registry$p.getComponentMethod("errorbars", "supplyDefaults"); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" }); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" }); - Lib$17.coerceSelectionMarkerOpacity(traceOut, coerce2); -}; -var getAxisGroup$2 = constraints.getAxisGroup; -var grouping_defaults = function handleGroupingDefaults(traceIn, traceOut, fullLayout, coerce2) { - var orientation = traceOut.orientation; - var posAxId = traceOut[{ v: "x", h: "y" }[orientation] + "axis"]; - var groupId = getAxisGroup$2(fullLayout, posAxId) + orientation; - var alignmentOpts = fullLayout._alignmentOpts || {}; - var alignmentgroup = coerce2("alignmentgroup"); - var alignmentGroups = alignmentOpts[groupId]; - if (!alignmentGroups) alignmentGroups = alignmentOpts[groupId] = {}; - var alignmentGroupOpts = alignmentGroups[alignmentgroup]; - if (alignmentGroupOpts) { - alignmentGroupOpts.traces.push(traceOut); - } else { - alignmentGroupOpts = alignmentGroups[alignmentgroup] = { - traces: [traceOut], - alignmentIndex: Object.keys(alignmentGroups).length, - offsetGroups: {} - }; - } - var offsetgroup = coerce2("offsetgroup"); - var offsetGroups = alignmentGroupOpts.offsetGroups; - var offsetGroupOpts = offsetGroups[offsetgroup]; - if (offsetgroup) { - if (!offsetGroupOpts) { - offsetGroupOpts = offsetGroups[offsetgroup] = { - offsetIndex: Object.keys(offsetGroups).length - }; - } - traceOut._offsetIndex = offsetGroupOpts.offsetIndex; - } -}; -var Lib$16 = libExports; -var handleGroupingDefaults$2 = grouping_defaults; -var attributes$w = attributes$A; -var cross_trace_defaults$1 = function crossTraceDefaults2(fullData, fullLayout) { - var traceIn, traceOut, i; - function coerce2(attr) { - return Lib$16.coerce(traceOut._input, traceOut, attributes$w, attr); - } - if (fullLayout.scattermode === "group") { - for (i = 0; i < fullData.length; i++) { - traceOut = fullData[i]; - if (traceOut.type === "scatter") { - traceIn = traceOut._input; - handleGroupingDefaults$2(traceIn, traceOut, fullLayout, coerce2); - } - } - } - for (i = 0; i < fullData.length; i++) { - var tracei = fullData[i]; - if (tracei.type !== "scatter") continue; - var filli = tracei.fill; - if (filli === "none" || filli === "toself") continue; - tracei.opacity = void 0; - if (filli === "tonexty" || filli === "tonextx") { - for (var j = i - 1; j >= 0; j--) { - var tracej = fullData[j]; - if (tracej.type === "scatter" && tracej.xaxis === tracei.xaxis && tracej.yaxis === tracei.yaxis) { - tracej.opacity = void 0; - break; - } - } - } - } -}; -var Lib$15 = libExports; -var layoutAttributes$4 = layout_attributes$5; -var layout_defaults$4 = function(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$15.coerce(layoutIn, layoutOut, layoutAttributes$4, attr, dflt); - } - var groupBarmode = layoutOut.barmode === "group"; - if (layoutOut.scattermode === "group") { - coerce2("scattergap", groupBarmode ? layoutOut.bargap : 0.2); - } -}; -var isNumeric$f = fastIsnumeric; -var Lib$14 = libExports; -var dateTime2ms = Lib$14.dateTime2ms; -var incrementMonth = Lib$14.incrementMonth; -var constants$y = numerical; -var ONEAVGMONTH = constants$y.ONEAVGMONTH; -var align_period = function alignPeriod(trace, ax, axLetter, vals) { - if (ax.type !== "date") return { vals }; - var alignment2 = trace[axLetter + "periodalignment"]; - if (!alignment2) return { vals }; - var period = trace[axLetter + "period"]; - var mPeriod; - if (isNumeric$f(period)) { - period = +period; - if (period <= 0) return { vals }; - } else if (typeof period === "string" && period.charAt(0) === "M") { - var n = +period.substring(1); - if (n > 0 && Math.round(n) === n) { - mPeriod = n; - } else return { vals }; - } - var calendar = ax.calendar; - var isStart = "start" === alignment2; - var isEnd = "end" === alignment2; - var period0 = trace[axLetter + "period0"]; - var base = dateTime2ms(period0, calendar) || 0; - var newVals = []; - var starts = []; - var ends = []; - var len = vals.length; - for (var i = 0; i < len; i++) { - var v = vals[i]; - var nEstimated, startTime, endTime; - if (mPeriod) { - nEstimated = Math.round((v - base) / (mPeriod * ONEAVGMONTH)); - endTime = incrementMonth(base, mPeriod * nEstimated, calendar); - while (endTime > v) { - endTime = incrementMonth(endTime, -mPeriod, calendar); - } - while (endTime <= v) { - endTime = incrementMonth(endTime, mPeriod, calendar); - } - startTime = incrementMonth(endTime, -mPeriod, calendar); - } else { - nEstimated = Math.round((v - base) / period); - endTime = base + nEstimated * period; - while (endTime > v) { - endTime -= period; - } - while (endTime <= v) { - endTime += period; - } - startTime = endTime - period; - } - newVals[i] = isStart ? startTime : isEnd ? endTime : (startTime + endTime) / 2; - starts[i] = startTime; - ends[i] = endTime; - } - return { - vals: newVals, - starts, - ends - }; -}; -var hasColorscale$3 = helpers$L.hasColorscale; -var calcColorscale$2 = calc$c; -var subTypes$6 = subtypes$3; -var colorscale_calc = function calcMarkerColorscale(gd, trace) { - if (subTypes$6.hasLines(trace) && hasColorscale$3(trace, "line")) { - calcColorscale$2(gd, trace, { - vals: trace.line.color, - containerStr: "line" - }); - } - if (subTypes$6.hasMarkers(trace)) { - if (hasColorscale$3(trace, "marker")) { - calcColorscale$2(gd, trace, { - vals: trace.marker.color, - containerStr: "marker" - }); - } - if (hasColorscale$3(trace, "marker.line")) { - calcColorscale$2(gd, trace, { - vals: trace.marker.line.color, - containerStr: "marker.line" - }); - } - } -}; -var Lib$13 = libExports; -var arrays_to_calcdata$1 = function arraysToCalcdata(cd, trace) { - for (var i = 0; i < cd.length; i++) cd[i].i = i; - Lib$13.mergeArray(trace.text, cd, "tx"); - Lib$13.mergeArray(trace.texttemplate, cd, "txt"); - Lib$13.mergeArray(trace.hovertext, cd, "htx"); - Lib$13.mergeArray(trace.customdata, cd, "data"); - Lib$13.mergeArray(trace.textposition, cd, "tp"); - if (trace.textfont) { - Lib$13.mergeArrayCastPositive(trace.textfont.size, cd, "ts"); - Lib$13.mergeArray(trace.textfont.color, cd, "tc"); - Lib$13.mergeArray(trace.textfont.family, cd, "tf"); - Lib$13.mergeArray(trace.textfont.weight, cd, "tw"); - Lib$13.mergeArray(trace.textfont.style, cd, "ty"); - Lib$13.mergeArray(trace.textfont.variant, cd, "tv"); - Lib$13.mergeArray(trace.textfont.textcase, cd, "tC"); - Lib$13.mergeArray(trace.textfont.lineposition, cd, "tE"); - Lib$13.mergeArray(trace.textfont.shadow, cd, "tS"); - } - var marker2 = trace.marker; - if (marker2) { - Lib$13.mergeArrayCastPositive(marker2.size, cd, "ms"); - Lib$13.mergeArrayCastPositive(marker2.opacity, cd, "mo"); - Lib$13.mergeArray(marker2.symbol, cd, "mx"); - Lib$13.mergeArray(marker2.angle, cd, "ma"); - Lib$13.mergeArray(marker2.standoff, cd, "mf"); - Lib$13.mergeArray(marker2.color, cd, "mc"); - var markerLine2 = marker2.line; - if (marker2.line) { - Lib$13.mergeArray(markerLine2.color, cd, "mlc"); - Lib$13.mergeArrayCastPositive(markerLine2.width, cd, "mlw"); - } - var markerGradient = marker2.gradient; - if (markerGradient && markerGradient.type !== "none") { - Lib$13.mergeArray(markerGradient.type, cd, "mgt"); - Lib$13.mergeArray(markerGradient.color, cd, "mgc"); - } - } -}; -var Lib$12 = libExports; -var calc_selection = function calcSelection(cd, trace) { - if (Lib$12.isArrayOrTypedArray(trace.selectedpoints)) { - Lib$12.tagSelected(cd, trace); - } -}; -var isNumeric$e = fastIsnumeric; -var Lib$11 = libExports; -var Axes$h = axesExports; -var alignPeriod$3 = align_period; -var BADNUM$5 = numerical.BADNUM; -var subTypes$5 = subtypes$3; -var calcColorscale$1 = colorscale_calc; -var arraysToCalcdata$2 = arrays_to_calcdata$1; -var calcSelection$1 = calc_selection; -function calc$a(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = trace._xA = Axes$h.getFromId(gd, trace.xaxis || "x", "x"); - var ya = trace._yA = Axes$h.getFromId(gd, trace.yaxis || "y", "y"); - var origX = xa.makeCalcdata(trace, "x"); - var origY = ya.makeCalcdata(trace, "y"); - var xObj = alignPeriod$3(trace, xa, "x", origX); - var yObj = alignPeriod$3(trace, ya, "y", origY); - var x = xObj.vals; - var y = yObj.vals; - var serieslen = trace._length; - var cd = new Array(serieslen); - var ids = trace.ids; - var stackGroupOpts = getStackOpts(trace, fullLayout, xa, ya); - var interpolateGaps = false; - var isV, i, j, k, interpolate2, vali; - setFirstScatter$1(fullLayout, trace); - var xAttr = "x"; - var yAttr = "y"; - var posAttr; - if (stackGroupOpts) { - Lib$11.pushUnique(stackGroupOpts.traceIndices, trace._expandedIndex); - isV = stackGroupOpts.orientation === "v"; - if (isV) { - yAttr = "s"; - posAttr = "x"; - } else { - xAttr = "s"; - posAttr = "y"; - } - interpolate2 = stackGroupOpts.stackgaps === "interpolate"; - } else { - var ppad = calcMarkerSize$1(trace, serieslen); - calcAxisExpansion$2(gd, trace, xa, ya, x, y, ppad); - } - var hasPeriodX = !!trace.xperiodalignment; - var hasPeriodY = !!trace.yperiodalignment; - for (i = 0; i < serieslen; i++) { - var cdi = cd[i] = {}; - var xValid = isNumeric$e(x[i]); - var yValid = isNumeric$e(y[i]); - if (xValid && yValid) { - cdi[xAttr] = x[i]; - cdi[yAttr] = y[i]; - if (hasPeriodX) { - cdi.orig_x = origX[i]; - cdi.xEnd = xObj.ends[i]; - cdi.xStart = xObj.starts[i]; - } - if (hasPeriodY) { - cdi.orig_y = origY[i]; - cdi.yEnd = yObj.ends[i]; - cdi.yStart = yObj.starts[i]; - } - } else if (stackGroupOpts && (isV ? xValid : yValid)) { - cdi[posAttr] = isV ? x[i] : y[i]; - cdi.gap = true; - if (interpolate2) { - cdi.s = BADNUM$5; - interpolateGaps = true; - } else { - cdi.s = 0; - } - } else { - cdi[xAttr] = cdi[yAttr] = BADNUM$5; - } - if (ids) { - cdi.id = String(ids[i]); - } - } - arraysToCalcdata$2(cd, trace); - calcColorscale$1(gd, trace); - calcSelection$1(cd, trace); - if (stackGroupOpts) { - i = 0; - while (i < cd.length) { - if (cd[i][posAttr] === BADNUM$5) { - cd.splice(i, 1); - } else i++; - } - Lib$11.sort(cd, function(a, b) { - return a[posAttr] - b[posAttr] || a.i - b.i; - }); - if (interpolateGaps) { - i = 0; - while (i < cd.length - 1 && cd[i].gap) { - i++; - } - vali = cd[i].s; - if (!vali) vali = cd[i].s = 0; - for (j = 0; j < i; j++) { - cd[j].s = vali; - } - k = cd.length - 1; - while (k > i && cd[k].gap) { - k--; - } - vali = cd[k].s; - for (j = cd.length - 1; j > k; j--) { - cd[j].s = vali; - } - while (i < k) { - i++; - if (cd[i].gap) { - j = i + 1; - while (cd[j].gap) { - j++; - } - var pos0 = cd[i - 1][posAttr]; - var size0 = cd[i - 1].s; - var m = (cd[j].s - size0) / (cd[j][posAttr] - pos0); - while (i < j) { - cd[i].s = size0 + (cd[i][posAttr] - pos0) * m; - i++; - } - } - } - } - } - return cd; -} -function calcAxisExpansion$2(gd, trace, xa, ya, x, y, ppad) { - var serieslen = trace._length; - var fullLayout = gd._fullLayout; - var xId = xa._id; - var yId = ya._id; - var firstScatter = fullLayout._firstScatter[firstScatterGroup(trace)] === trace.uid; - var stackOrientation = (getStackOpts(trace, fullLayout, xa, ya) || {}).orientation; - var fill = trace.fill; - xa._minDtick = 0; - ya._minDtick = 0; - var xOptions = { padded: true }; - var yOptions = { padded: true }; - if (ppad) { - xOptions.ppad = yOptions.ppad = ppad; - } - var openEnded = serieslen < 2 || x[0] !== x[serieslen - 1] || y[0] !== y[serieslen - 1]; - if (openEnded && (fill === "tozerox" || fill === "tonextx" && (firstScatter || stackOrientation === "h"))) { - xOptions.tozero = true; - } else if (!(trace.error_y || {}).visible && // if no error bars, markers or text, or fill to y=0 remove x padding - (fill === "tonexty" || fill === "tozeroy" || !subTypes$5.hasMarkers(trace) && !subTypes$5.hasText(trace))) { - xOptions.padded = false; - xOptions.ppad = 0; - } - if (openEnded && (fill === "tozeroy" || fill === "tonexty" && (firstScatter || stackOrientation === "v"))) { - yOptions.tozero = true; - } else if (fill === "tonextx" || fill === "tozerox") { - yOptions.padded = false; - } - if (xId) trace._extremes[xId] = Axes$h.findExtremes(xa, x, xOptions); - if (yId) trace._extremes[yId] = Axes$h.findExtremes(ya, y, yOptions); -} -function calcMarkerSize$1(trace, serieslen) { - if (!subTypes$5.hasMarkers(trace)) return; - var marker2 = trace.marker; - var sizeref = 1.6 * (trace.marker.sizeref || 1); - var markerTrans; - if (trace.marker.sizemode === "area") { - markerTrans = function(v) { - return Math.max(Math.sqrt((v || 0) / sizeref), 3); - }; - } else { - markerTrans = function(v) { - return Math.max((v || 0) / sizeref, 3); - }; - } - if (Lib$11.isArrayOrTypedArray(marker2.size)) { - var ax = { type: "linear" }; - Axes$h.setConvert(ax); - var s = ax.makeCalcdata(trace.marker, "size"); - var sizeOut = new Array(serieslen); - for (var i = 0; i < serieslen; i++) { - sizeOut[i] = markerTrans(s[i]); - } - return sizeOut; - } else { - return markerTrans(marker2.size); - } -} -function setFirstScatter$1(fullLayout, trace) { - var group = firstScatterGroup(trace); - var firstScatter = fullLayout._firstScatter; - if (!firstScatter[group]) firstScatter[group] = trace.uid; -} -function firstScatterGroup(trace) { - var stackGroup = trace.stackgroup; - return trace.xaxis + trace.yaxis + trace.type + (stackGroup ? "-" + stackGroup : ""); -} -function getStackOpts(trace, fullLayout, xa, ya) { - var stackGroup = trace.stackgroup; - if (!stackGroup) return; - var stackOpts = fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup]; - var stackAx = stackOpts.orientation === "v" ? ya : xa; - if (stackAx.type === "linear" || stackAx.type === "log") return stackOpts; -} -var calc_1$3 = { - calc: calc$a, - calcMarkerSize: calcMarkerSize$1, - calcAxisExpansion: calcAxisExpansion$2, - setFirstScatter: setFirstScatter$1, - getStackOpts -}; -var sieve = Sieve$1; -var distinctVals = libExports.distinctVals; -function Sieve$1(traces, opts) { - this.traces = traces; - this.sepNegVal = opts.sepNegVal; - this.overlapNoMerge = opts.overlapNoMerge; - var width1 = Infinity; - var axLetter = opts.posAxis._id.charAt(0); - var positions = []; - for (var i = 0; i < traces.length; i++) { - var trace = traces[i]; - for (var j = 0; j < trace.length; j++) { - var bar2 = trace[j]; - var pos = bar2.p; - if (pos === void 0) { - pos = bar2[axLetter]; - } - if (pos !== void 0) positions.push(pos); - } - if (trace[0] && trace[0].width1) { - width1 = Math.min(trace[0].width1, width1); - } - } - this.positions = positions; - var dv2 = distinctVals(positions); - this.distinctPositions = dv2.vals; - if (dv2.vals.length === 1 && width1 !== Infinity) this.minDiff = width1; - else this.minDiff = Math.min(dv2.minDiff, width1); - var type = (opts.posAxis || {}).type; - if (type === "category" || type === "multicategory") { - this.minDiff = 1; - } - this.binWidth = this.minDiff; - this.bins = {}; -} -Sieve$1.prototype.put = function put(position, value2) { - var label = this.getLabel(position, value2); - var oldValue = this.bins[label] || 0; - this.bins[label] = oldValue + value2; - return oldValue; -}; -Sieve$1.prototype.get = function get(position, value2) { - var label = this.getLabel(position, value2); - return this.bins[label] || 0; -}; -Sieve$1.prototype.getLabel = function getLabel(position, value2) { - var prefix = value2 < 0 && this.sepNegVal ? "v" : "^"; - var label = this.overlapNoMerge ? position : Math.round(position / this.binWidth); - return prefix + label; -}; -var isNumeric$d = fastIsnumeric; -var isArrayOrTypedArray$3 = libExports.isArrayOrTypedArray; -var BADNUM$4 = numerical.BADNUM; -var Registry$o = registry; -var Axes$g = axesExports; -var getAxisGroup$1 = constraints.getAxisGroup; -var Sieve = sieve; -function crossTraceCalc$1(gd, plotinfo) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var fullLayout = gd._fullLayout; - var fullTraces = gd._fullData; - var calcTraces = gd.calcdata; - var calcTracesHorz = []; - var calcTracesVert = []; - for (var i = 0; i < fullTraces.length; i++) { - var fullTrace = fullTraces[i]; - if (fullTrace.visible === true && Registry$o.traceIs(fullTrace, "bar") && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) { - if (fullTrace.orientation === "h") { - calcTracesHorz.push(calcTraces[i]); - } else { - calcTracesVert.push(calcTraces[i]); - } - if (fullTrace._computePh) { - var cd = gd.calcdata[i]; - for (var j = 0; j < cd.length; j++) { - if (typeof cd[j].ph0 === "function") cd[j].ph0 = cd[j].ph0(); - if (typeof cd[j].ph1 === "function") cd[j].ph1 = cd[j].ph1(); - } - } - } - } - var opts = { - xCat: xa.type === "category" || xa.type === "multicategory", - yCat: ya.type === "category" || ya.type === "multicategory", - mode: fullLayout.barmode, - norm: fullLayout.barnorm, - gap: fullLayout.bargap, - groupgap: fullLayout.bargroupgap - }; - setGroupPositions$1(gd, xa, ya, calcTracesVert, opts); - setGroupPositions$1(gd, ya, xa, calcTracesHorz, opts); -} -function setGroupPositions$1(gd, pa, sa, calcTraces, opts) { - if (!calcTraces.length) return; - var excluded; - var included; - var i, calcTrace, fullTrace; - initBase(sa, calcTraces); - switch (opts.mode) { - case "overlay": - setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts); - break; - case "group": - excluded = []; - included = []; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - if (fullTrace.offset === void 0) included.push(calcTrace); - else excluded.push(calcTrace); - } - if (included.length) { - setGroupPositionsInGroupMode(gd, pa, sa, included, opts); - } - if (excluded.length) { - setGroupPositionsInOverlayMode(pa, sa, excluded, opts); - } - break; - case "stack": - case "relative": - excluded = []; - included = []; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - if (fullTrace.base === void 0) included.push(calcTrace); - else excluded.push(calcTrace); - } - standardizeCornerradius(included); - if (included.length) { - setGroupPositionsInStackOrRelativeMode(gd, pa, sa, included, opts); - } - if (excluded.length) { - setGroupPositionsInOverlayMode(pa, sa, excluded, opts); - } - break; - } - setCornerradius(calcTraces); - collectExtents(calcTraces, pa); -} -function setCornerradius(calcTraces) { - var i, calcTrace, fullTrace, t, cr, crValue, crForm; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - t = calcTrace[0].t; - if (t.cornerradiusvalue === void 0) { - cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0; - if (cr !== void 0) { - crValue = isNumeric$d(cr) ? +cr : +cr.slice(0, -1); - crForm = isNumeric$d(cr) ? "px" : "%"; - t.cornerradiusvalue = crValue; - t.cornerradiusform = crForm; - } - } - } -} -function standardizeCornerradius(calcTraces) { - if (calcTraces.length < 2) return; - var i, calcTrace, fullTrace, t; - var cr, crValue, crForm; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - cr = fullTrace.marker ? fullTrace.marker.cornerradius : void 0; - if (cr !== void 0) break; - } - if (cr !== void 0) { - crValue = isNumeric$d(cr) ? +cr : +cr.slice(0, -1); - crForm = isNumeric$d(cr) ? "px" : "%"; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - t = calcTrace[0].t; - t.cornerradiusvalue = crValue; - t.cornerradiusform = crForm; - } - } -} -function initBase(sa, calcTraces) { - var i, j; - for (i = 0; i < calcTraces.length; i++) { - var cd = calcTraces[i]; - var trace = cd[0].trace; - var base = trace.type === "funnel" ? trace._base : trace.base; - var b; - var scalendar = trace.orientation === "h" ? trace.xcalendar : trace.ycalendar; - var d2c = sa.type === "category" || sa.type === "multicategory" ? function() { - return null; - } : sa.d2c; - if (isArrayOrTypedArray$3(base)) { - for (j = 0; j < Math.min(base.length, cd.length); j++) { - b = d2c(base[j], 0, scalendar); - if (isNumeric$d(b)) { - cd[j].b = +b; - cd[j].hasB = 1; - } else cd[j].b = 0; - } - for (; j < cd.length; j++) { - cd[j].b = 0; - } - } else { - b = d2c(base, 0, scalendar); - var hasBase = isNumeric$d(b); - b = hasBase ? b : 0; - for (j = 0; j < cd.length; j++) { - cd[j].b = b; - if (hasBase) cd[j].hasB = 1; - } - } - } -} -function setGroupPositionsInOverlayMode(pa, sa, calcTraces, opts) { - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var sieve2 = new Sieve([calcTrace], { - posAxis: pa, - sepNegVal: false, - overlapNoMerge: !opts.norm - }); - setOffsetAndWidth(pa, sieve2, opts); - if (opts.norm) { - sieveBars(sieve2); - normalizeBars(sa, sieve2, opts); - } else { - setBaseAndTop(sa, sieve2); - } - } -} -function setGroupPositionsInGroupMode(gd, pa, sa, calcTraces, opts) { - var sieve2 = new Sieve(calcTraces, { - posAxis: pa, - sepNegVal: false, - overlapNoMerge: !opts.norm - }); - setOffsetAndWidthInGroupMode(gd, pa, sieve2, opts); - unhideBarsWithinTrace(sieve2, pa); - if (opts.norm) { - sieveBars(sieve2); - normalizeBars(sa, sieve2, opts); - } else { - setBaseAndTop(sa, sieve2); - } -} -function setGroupPositionsInStackOrRelativeMode(gd, pa, sa, calcTraces, opts) { - var sieve2 = new Sieve(calcTraces, { - posAxis: pa, - sepNegVal: opts.mode === "relative", - overlapNoMerge: !(opts.norm || opts.mode === "stack" || opts.mode === "relative") - }); - setOffsetAndWidth(pa, sieve2, opts); - stackBars(sa, sieve2, opts); - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - if (bar2.s !== BADNUM$4) { - var isOutmostBar = bar2.b + bar2.s === sieve2.get(bar2.p, bar2.s); - if (isOutmostBar) bar2._outmost = true; - } - } - } - if (opts.norm) normalizeBars(sa, sieve2, opts); -} -function setOffsetAndWidth(pa, sieve2, opts) { - var minDiff = sieve2.minDiff; - var calcTraces = sieve2.traces; - var barGroupWidth = minDiff * (1 - opts.gap); - var barWidthPlusGap = barGroupWidth; - var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0)); - var offsetFromCenter = -barWidth / 2; - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var t = calcTrace[0].t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; - } - sieve2.binWidth = calcTraces[0][0].t.barwidth / 100; - applyAttributes(sieve2); - setBarCenterAndWidth(pa, sieve2); - updatePositionAxis(pa, sieve2); -} -function setOffsetAndWidthInGroupMode(gd, pa, sieve2, opts) { - var fullLayout = gd._fullLayout; - var positions = sieve2.positions; - var distinctPositions = sieve2.distinctPositions; - var minDiff = sieve2.minDiff; - var calcTraces = sieve2.traces; - var nTraces = calcTraces.length; - var overlap = positions.length !== distinctPositions.length; - var barGroupWidth = minDiff * (1 - opts.gap); - var groupId = getAxisGroup$1(fullLayout, pa._id) + calcTraces[0][0].trace.orientation; - var alignmentGroups = fullLayout._alignmentOpts[groupId] || {}; - for (var i = 0; i < nTraces; i++) { - var calcTrace = calcTraces[i]; - var trace = calcTrace[0].trace; - var alignmentGroupOpts = alignmentGroups[trace.alignmentgroup] || {}; - var nOffsetGroups = Object.keys(alignmentGroupOpts.offsetGroups || {}).length; - var barWidthPlusGap; - if (nOffsetGroups) { - barWidthPlusGap = barGroupWidth / nOffsetGroups; - } else { - barWidthPlusGap = overlap ? barGroupWidth / nTraces : barGroupWidth; - } - var barWidth = barWidthPlusGap * (1 - (opts.groupgap || 0)); - var offsetFromCenter; - if (nOffsetGroups) { - offsetFromCenter = ((2 * trace._offsetIndex + 1 - nOffsetGroups) * barWidthPlusGap - barWidth) / 2; - } else { - offsetFromCenter = overlap ? ((2 * i + 1 - nTraces) * barWidthPlusGap - barWidth) / 2 : -barWidth / 2; - } - var t = calcTrace[0].t; - t.barwidth = barWidth; - t.poffset = offsetFromCenter; - t.bargroupwidth = barGroupWidth; - t.bardelta = minDiff; - } - sieve2.binWidth = calcTraces[0][0].t.barwidth / 100; - applyAttributes(sieve2); - setBarCenterAndWidth(pa, sieve2); - updatePositionAxis(pa, sieve2, overlap); -} -function applyAttributes(sieve2) { - var calcTraces = sieve2.traces; - var i, j; - for (i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var calcTrace0 = calcTrace[0]; - var fullTrace = calcTrace0.trace; - var t = calcTrace0.t; - var offset = fullTrace._offset || fullTrace.offset; - var initialPoffset = t.poffset; - var newPoffset; - if (isArrayOrTypedArray$3(offset)) { - newPoffset = Array.prototype.slice.call(offset, 0, calcTrace.length); - for (j = 0; j < newPoffset.length; j++) { - if (!isNumeric$d(newPoffset[j])) { - newPoffset[j] = initialPoffset; - } - } - for (j = newPoffset.length; j < calcTrace.length; j++) { - newPoffset.push(initialPoffset); - } - t.poffset = newPoffset; - } else if (offset !== void 0) { - t.poffset = offset; - } - var width = fullTrace._width || fullTrace.width; - var initialBarwidth = t.barwidth; - if (isArrayOrTypedArray$3(width)) { - var newBarwidth = Array.prototype.slice.call(width, 0, calcTrace.length); - for (j = 0; j < newBarwidth.length; j++) { - if (!isNumeric$d(newBarwidth[j])) newBarwidth[j] = initialBarwidth; - } - for (j = newBarwidth.length; j < calcTrace.length; j++) { - newBarwidth.push(initialBarwidth); - } - t.barwidth = newBarwidth; - if (offset === void 0) { - newPoffset = []; - for (j = 0; j < calcTrace.length; j++) { - newPoffset.push( - initialPoffset + (initialBarwidth - newBarwidth[j]) / 2 - ); - } - t.poffset = newPoffset; - } - } else if (width !== void 0) { - t.barwidth = width; - if (offset === void 0) { - t.poffset = initialPoffset + (initialBarwidth - width) / 2; - } - } - } -} -function setBarCenterAndWidth(pa, sieve2) { - var calcTraces = sieve2.traces; - var pLetter = getAxisLetter(pa); - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var t = calcTrace[0].t; - var poffset = t.poffset; - var poffsetIsArray = isArrayOrTypedArray$3(poffset); - var barwidth = t.barwidth; - var barwidthIsArray = isArrayOrTypedArray$3(barwidth); - for (var j = 0; j < calcTrace.length; j++) { - var calcBar = calcTrace[j]; - var width = calcBar.w = barwidthIsArray ? barwidth[j] : barwidth; - if (calcBar.p === void 0) { - calcBar.p = calcBar[pLetter]; - calcBar["orig_" + pLetter] = calcBar[pLetter]; - } - var delta2 = (poffsetIsArray ? poffset[j] : poffset) + width / 2; - calcBar[pLetter] = calcBar.p + delta2; - } - } -} -function updatePositionAxis(pa, sieve2, allowMinDtick) { - var calcTraces = sieve2.traces; - var minDiff = sieve2.minDiff; - var vpad = minDiff / 2; - Axes$g.minDtick(pa, sieve2.minDiff, sieve2.distinctPositions[0], allowMinDtick); - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var calcTrace0 = calcTrace[0]; - var fullTrace = calcTrace0.trace; - var pts = []; - var bar2, l, r, j; - for (j = 0; j < calcTrace.length; j++) { - bar2 = calcTrace[j]; - l = bar2.p - vpad; - r = bar2.p + vpad; - pts.push(l, r); - } - if (fullTrace.width || fullTrace.offset) { - var t = calcTrace0.t; - var poffset = t.poffset; - var barwidth = t.barwidth; - var poffsetIsArray = isArrayOrTypedArray$3(poffset); - var barwidthIsArray = isArrayOrTypedArray$3(barwidth); - for (j = 0; j < calcTrace.length; j++) { - bar2 = calcTrace[j]; - var calcBarOffset = poffsetIsArray ? poffset[j] : poffset; - var calcBarWidth = barwidthIsArray ? barwidth[j] : barwidth; - l = bar2.p + calcBarOffset; - r = l + calcBarWidth; - pts.push(l, r); - } - } - fullTrace._extremes[pa._id] = Axes$g.findExtremes(pa, pts, { padded: false }); - } -} -function setBaseAndTop(sa, sieve2) { - var calcTraces = sieve2.traces; - var sLetter = getAxisLetter(sa); - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var fullTrace = calcTrace[0].trace; - var isScatter = fullTrace.type === "scatter"; - var isVertical2 = fullTrace.orientation === "v"; - var pts = []; - var tozero = false; - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - var base = isScatter ? 0 : bar2.b; - var top = isScatter ? isVertical2 ? bar2.y : bar2.x : base + bar2.s; - bar2[sLetter] = top; - pts.push(top); - if (bar2.hasB) pts.push(base); - if (!bar2.hasB || !bar2.b) { - tozero = true; - } - } - fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { - tozero, - padded: true - }); - } -} -function stackBars(sa, sieve2, opts) { - var sLetter = getAxisLetter(sa); - var calcTraces = sieve2.traces; - var calcTrace; - var fullTrace; - var isFunnel; - var i, j; - var bar2; - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - if (fullTrace.type === "funnel") { - for (j = 0; j < calcTrace.length; j++) { - bar2 = calcTrace[j]; - if (bar2.s !== BADNUM$4) { - sieve2.put(bar2.p, -0.5 * bar2.s); - } - } - } - } - for (i = 0; i < calcTraces.length; i++) { - calcTrace = calcTraces[i]; - fullTrace = calcTrace[0].trace; - isFunnel = fullTrace.type === "funnel"; - var pts = []; - for (j = 0; j < calcTrace.length; j++) { - bar2 = calcTrace[j]; - if (bar2.s !== BADNUM$4) { - var value2; - if (isFunnel) { - value2 = bar2.s; - } else { - value2 = bar2.s + bar2.b; - } - var base = sieve2.put(bar2.p, value2); - var top = base + value2; - bar2.b = base; - bar2[sLetter] = top; - if (!opts.norm) { - pts.push(top); - if (bar2.hasB) { - pts.push(base); - } - } - } - } - if (!opts.norm) { - fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { - // N.B. we don't stack base with 'base', - // so set tozero:true always! - tozero: true, - padded: true - }); - } - } -} -function sieveBars(sieve2) { - var calcTraces = sieve2.traces; - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - if (bar2.s !== BADNUM$4) { - sieve2.put(bar2.p, bar2.b + bar2.s); - } - } - } -} -function unhideBarsWithinTrace(sieve2, pa) { - var calcTraces = sieve2.traces; - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var fullTrace = calcTrace[0].trace; - if (fullTrace.base === void 0) { - var inTraceSieve = new Sieve([calcTrace], { - posAxis: pa, - sepNegVal: true, - overlapNoMerge: true - }); - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - if (bar2.p !== BADNUM$4) { - var base = inTraceSieve.put(bar2.p, bar2.b + bar2.s); - if (base) bar2.b = base; - } - } - } - } -} -function normalizeBars(sa, sieve2, opts) { - var calcTraces = sieve2.traces; - var sLetter = getAxisLetter(sa); - var sTop = opts.norm === "fraction" ? 1 : 100; - var sTiny = sTop / 1e9; - var sMin = sa.l2c(sa.c2l(0)); - var sMax = opts.mode === "stack" ? sTop : sMin; - function needsPadding(v) { - return isNumeric$d(sa.c2l(v)) && (v < sMin - sTiny || v > sMax + sTiny || !isNumeric$d(sMin)); - } - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - var fullTrace = calcTrace[0].trace; - var pts = []; - var tozero = false; - var padded = false; - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - if (bar2.s !== BADNUM$4) { - var scale2 = Math.abs(sTop / sieve2.get(bar2.p, bar2.s)); - bar2.b *= scale2; - bar2.s *= scale2; - var base = bar2.b; - var top = base + bar2.s; - bar2[sLetter] = top; - pts.push(top); - padded = padded || needsPadding(top); - if (bar2.hasB) { - pts.push(base); - padded = padded || needsPadding(base); - } - if (!bar2.hasB || !bar2.b) { - tozero = true; - } - } - } - fullTrace._extremes[sa._id] = Axes$g.findExtremes(sa, pts, { - tozero, - padded - }); - } -} -function setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa) { - var pLetter = getAxisLetter(pa); - for (var i = 0; i < calcTraces.length; i++) { - var calcTrace = calcTraces[i]; - for (var j = 0; j < calcTrace.length; j++) { - var bar2 = calcTrace[j]; - var pos = bar2[pLetter]; - bar2._sMin = sMinByPos[pos]; - bar2._sMax = sMaxByPos[pos]; - } - } -} -function collectExtents(calcTraces, pa) { - var pLetter = getAxisLetter(pa); - var extents = {}; - var i, j, cd; - var pMin = Infinity; - var pMax = -Infinity; - for (i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - for (j = 0; j < cd.length; j++) { - var p = cd[j].p; - if (isNumeric$d(p)) { - pMin = Math.min(pMin, p); - pMax = Math.max(pMax, p); - } - } - } - var roundFactor = 1e4 / (pMax - pMin); - var round2 = extents.round = function(p2) { - return String(Math.round(roundFactor * (p2 - pMin))); - }; - var sMinByPos = {}; - var sMaxByPos = {}; - var anyTraceHasCornerradius = calcTraces.some(function(x) { - var trace = x[0].trace; - return "marker" in trace && trace.marker.cornerradius; - }); - for (i = 0; i < calcTraces.length; i++) { - cd = calcTraces[i]; - cd[0].t.extents = extents; - var poffset = cd[0].t.poffset; - var poffsetIsArray = isArrayOrTypedArray$3(poffset); - for (j = 0; j < cd.length; j++) { - var di = cd[j]; - var p0 = di[pLetter] - di.w / 2; - if (isNumeric$d(p0)) { - var p1 = di[pLetter] + di.w / 2; - var pVal = round2(di.p); - if (extents[pVal]) { - extents[pVal] = [Math.min(p0, extents[pVal][0]), Math.max(p1, extents[pVal][1])]; - } else { - extents[pVal] = [p0, p1]; - } - } - di.p0 = di.p + (poffsetIsArray ? poffset[j] : poffset); - di.p1 = di.p0 + di.w; - di.s0 = di.b; - di.s1 = di.s0 + di.s; - if (anyTraceHasCornerradius) { - var sMin = Math.min(di.s0, di.s1) || 0; - var sMax = Math.max(di.s0, di.s1) || 0; - var pos = di[pLetter]; - sMinByPos[pos] = pos in sMinByPos ? Math.min(sMinByPos[pos], sMin) : sMin; - sMaxByPos[pos] = pos in sMaxByPos ? Math.max(sMaxByPos[pos], sMax) : sMax; - } - } - } - if (anyTraceHasCornerradius) { - setHelperValuesForRoundedCorners(calcTraces, sMinByPos, sMaxByPos, pa); - } -} -function getAxisLetter(ax) { - return ax._id.charAt(0); -} -var cross_trace_calc$1 = { - crossTraceCalc: crossTraceCalc$1, - setGroupPositions: setGroupPositions$1 -}; -var calc$9 = calc_1$3; -var setGroupPositions = cross_trace_calc$1.setGroupPositions; -function groupCrossTraceCalc(gd, plotinfo) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var fullLayout = gd._fullLayout; - var fullTraces = gd._fullData; - var calcTraces = gd.calcdata; - var calcTracesHorz = []; - var calcTracesVert = []; - for (var i = 0; i < fullTraces.length; i++) { - var fullTrace = fullTraces[i]; - if (fullTrace.visible === true && fullTrace.type === "scatter" && fullTrace.xaxis === xa._id && fullTrace.yaxis === ya._id) { - if (fullTrace.orientation === "h") { - calcTracesHorz.push(calcTraces[i]); - } else if (fullTrace.orientation === "v") { - calcTracesVert.push(calcTraces[i]); - } - } - } - var opts = { - mode: fullLayout.scattermode, - gap: fullLayout.scattergap - }; - setGroupPositions(gd, xa, ya, calcTracesVert, opts); - setGroupPositions(gd, ya, xa, calcTracesHorz, opts); -} -var cross_trace_calc = function crossTraceCalc(gd, plotinfo) { - if (gd._fullLayout.scattermode === "group") { - groupCrossTraceCalc(gd, plotinfo); - } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var subplot = xa._id + ya._id; - var subplotStackOpts = gd._fullLayout._scatterStackOpts[subplot]; - if (!subplotStackOpts) return; - var calcTraces = gd.calcdata; - var i, j, k, i2, cd, cd0, posj, sumj, norm2; - var groupOpts, interpolate2, groupnorm, posAttr, valAttr; - var hasAnyBlanks; - for (var stackGroup in subplotStackOpts) { - groupOpts = subplotStackOpts[stackGroup]; - var indices = groupOpts.traceIndices; - if (!indices.length) continue; - interpolate2 = groupOpts.stackgaps === "interpolate"; - groupnorm = groupOpts.groupnorm; - if (groupOpts.orientation === "v") { - posAttr = "x"; - valAttr = "y"; - } else { - posAttr = "y"; - valAttr = "x"; - } - hasAnyBlanks = new Array(indices.length); - for (i = 0; i < hasAnyBlanks.length; i++) { - hasAnyBlanks[i] = false; - } - cd0 = calcTraces[indices[0]]; - var allPositions = new Array(cd0.length); - for (i = 0; i < cd0.length; i++) { - allPositions[i] = cd0[i][posAttr]; - } - for (i = 1; i < indices.length; i++) { - cd = calcTraces[indices[i]]; - for (j = k = 0; j < cd.length; j++) { - posj = cd[j][posAttr]; - for (; posj > allPositions[k] && k < allPositions.length; k++) { - insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate2, posAttr); - j++; - } - if (posj !== allPositions[k]) { - for (i2 = 0; i2 < i; i2++) { - insertBlank(calcTraces[indices[i2]], k, posj, i2, hasAnyBlanks, interpolate2, posAttr); - } - allPositions.splice(k, 0, posj); - } - k++; - } - for (; k < allPositions.length; k++) { - insertBlank(cd, j, allPositions[k], i, hasAnyBlanks, interpolate2, posAttr); - j++; - } - } - var serieslen = allPositions.length; - for (j = 0; j < cd0.length; j++) { - sumj = cd0[j][valAttr] = cd0[j].s; - for (i = 1; i < indices.length; i++) { - cd = calcTraces[indices[i]]; - cd[0].trace._rawLength = cd[0].trace._length; - cd[0].trace._length = serieslen; - sumj += cd[j].s; - cd[j][valAttr] = sumj; - } - if (groupnorm) { - norm2 = (groupnorm === "fraction" ? sumj : sumj / 100) || 1; - for (i = 0; i < indices.length; i++) { - var cdj = calcTraces[indices[i]][j]; - cdj[valAttr] /= norm2; - cdj.sNorm = cdj.s / norm2; - } - } - } - for (i = 0; i < indices.length; i++) { - cd = calcTraces[indices[i]]; - var trace = cd[0].trace; - var ppad = calc$9.calcMarkerSize(trace, trace._rawLength); - var arrayPad = Array.isArray(ppad); - if (ppad && hasAnyBlanks[i] || arrayPad) { - var ppadRaw = ppad; - ppad = new Array(serieslen); - for (j = 0; j < serieslen; j++) { - ppad[j] = cd[j].gap ? 0 : arrayPad ? ppadRaw[cd[j].i] : ppadRaw; - } - } - var x = new Array(serieslen); - var y = new Array(serieslen); - for (j = 0; j < serieslen; j++) { - x[j] = cd[j].x; - y[j] = cd[j].y; - } - calc$9.calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); - cd[0].t.orientation = groupOpts.orientation; - } - } -}; -function insertBlank(calcTrace, index2, position, traceIndex, hasAnyBlanks, interpolate2, posAttr) { - hasAnyBlanks[traceIndex] = true; - var newEntry = { - i: null, - gap: true, - s: 0 - }; - newEntry[posAttr] = position; - calcTrace.splice(index2, 0, newEntry); - if (index2 && position === calcTrace[index2 - 1][posAttr]) { - var prevEntry = calcTrace[index2 - 1]; - newEntry.s = prevEntry.s; - newEntry.i = prevEntry.i; - newEntry.gap = prevEntry.gap; - } else if (interpolate2) { - newEntry.s = getInterp(calcTrace, index2, position, posAttr); - } - if (!index2) { - calcTrace[0].t = calcTrace[1].t; - calcTrace[0].trace = calcTrace[1].trace; - delete calcTrace[1].t; - delete calcTrace[1].trace; - } -} -function getInterp(calcTrace, index2, position, posAttr) { - var pt0 = calcTrace[index2 - 1]; - var pt1 = calcTrace[index2 + 1]; - if (!pt1) return pt0.s; - if (!pt0) return pt1.s; - return pt0.s + (pt1.s - pt0.s) * (position - pt0[posAttr]) / (pt1[posAttr] - pt0[posAttr]); -} -var Drawing$i = drawingExports; -var numConstants$1 = numerical; -var BADNUM$3 = numConstants$1.BADNUM; -var LOG_CLIP = numConstants$1.LOG_CLIP; -var LOG_CLIP_PLUS = LOG_CLIP + 0.5; -var LOG_CLIP_MINUS = LOG_CLIP - 0.5; -var Lib$10 = libExports; -var segmentsIntersect = Lib$10.segmentsIntersect; -var constrain = Lib$10.constrain; -var constants$x = constants$B; -var line_points = function linePoints(d, opts) { - var trace = opts.trace || {}; - var xa = opts.xaxis; - var ya = opts.yaxis; - var xLog = xa.type === "log"; - var yLog = ya.type === "log"; - var xLen = xa._length; - var yLen = ya._length; - var backoff = opts.backoff; - var marker2 = trace.marker; - var connectGaps = opts.connectGaps; - var baseTolerance = opts.baseTolerance; - var shape = opts.shape; - var linear2 = shape === "linear"; - var fill = trace.fill && trace.fill !== "none"; - var segments = []; - var minTolerance = constants$x.minTolerance; - var len = d.length; - var pts = new Array(len); - var pti = 0; - var i; - var clusterStartPt, clusterEndPt, clusterHighPt, clusterLowPt; - var thisPt; - var clusterHighFirst; - var clusterUnitVector; - var thisVector; - var clusterRefDist, clusterHighVal, clusterLowVal, thisVal; - var clusterMinDeviation, clusterMaxDeviation, thisDeviation; - function getPt(index2) { - var di = d[index2]; - if (!di) return false; - var x = opts.linearized ? xa.l2p(di.x) : xa.c2p(di.x); - var y = opts.linearized ? ya.l2p(di.y) : ya.c2p(di.y); - if (x === BADNUM$3) { - if (xLog) x = xa.c2p(di.x, true); - if (x === BADNUM$3) return false; - if (yLog && y === BADNUM$3) { - x *= Math.abs(xa._m * yLen * (xa._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS) / (ya._m * xLen * (ya._m > 0 ? LOG_CLIP_PLUS : LOG_CLIP_MINUS))); - } - x *= 1e3; - } - if (y === BADNUM$3) { - if (yLog) y = ya.c2p(di.y, true); - if (y === BADNUM$3) return false; - y *= 1e3; - } - return [x, y]; - } - function crossesViewport(xFrac0, yFrac0, xFrac1, yFrac1) { - var dx = xFrac1 - xFrac0; - var dy = yFrac1 - yFrac0; - var dx0 = 0.5 - xFrac0; - var dy0 = 0.5 - yFrac0; - var norm2 = dx * dx + dy * dy; - var dot2 = dx * dx0 + dy * dy0; - if (dot2 > 0 && dot2 < norm2) { - var cross = dx0 * dy - dy0 * dx; - if (cross * cross < norm2) return true; - } - } - var latestXFrac, latestYFrac; - function getTolerance(pt, nextPt2) { - var xFrac = pt[0] / xLen; - var yFrac = pt[1] / yLen; - var offScreenFraction = Math.max(0, -xFrac, xFrac - 1, -yFrac, yFrac - 1); - if (offScreenFraction && latestXFrac !== void 0 && crossesViewport(xFrac, yFrac, latestXFrac, latestYFrac)) { - offScreenFraction = 0; - } - if (offScreenFraction && nextPt2 && crossesViewport(xFrac, yFrac, nextPt2[0] / xLen, nextPt2[1] / yLen)) { - offScreenFraction = 0; - } - return (1 + constants$x.toleranceGrowth * offScreenFraction) * baseTolerance; - } - function ptDist(pt1, pt2) { - var dx = pt1[0] - pt2[0]; - var dy = pt1[1] - pt2[1]; - return Math.sqrt(dx * dx + dy * dy); - } - var maxScreensAway = constants$x.maxScreensAway; - var xEdge0 = -xLen * maxScreensAway; - var xEdge1 = xLen * (1 + maxScreensAway); - var yEdge0 = -yLen * maxScreensAway; - var yEdge1 = yLen * (1 + maxScreensAway); - var edges = [ - [xEdge0, yEdge0, xEdge1, yEdge0], - [xEdge1, yEdge0, xEdge1, yEdge1], - [xEdge1, yEdge1, xEdge0, yEdge1], - [xEdge0, yEdge1, xEdge0, yEdge0] - ]; - var xEdge, yEdge, lastXEdge, lastYEdge, lastFarPt, edgePt; - function getLinearEdgeIntersections(pt1, pt2) { - var out = []; - var ptCount = 0; - for (var i2 = 0; i2 < 4; i2++) { - var edge = edges[i2]; - var ptInt = segmentsIntersect( - pt1[0], - pt1[1], - pt2[0], - pt2[1], - edge[0], - edge[1], - edge[2], - edge[3] - ); - if (ptInt && (!ptCount || Math.abs(ptInt.x - out[0][0]) > 1 || Math.abs(ptInt.y - out[0][1]) > 1)) { - ptInt = [ptInt.x, ptInt.y]; - if (ptCount && ptDist(ptInt, pt1) < ptDist(out[0], pt1)) out.unshift(ptInt); - else out.push(ptInt); - ptCount++; - } - } - return out; - } - function onlyConstrainedPoint(pt) { - if (pt[0] < xEdge0 || pt[0] > xEdge1 || pt[1] < yEdge0 || pt[1] > yEdge1) { - return [constrain(pt[0], xEdge0, xEdge1), constrain(pt[1], yEdge0, yEdge1)]; - } - } - function sameEdge(pt1, pt2) { - if (pt1[0] === pt2[0] && (pt1[0] === xEdge0 || pt1[0] === xEdge1)) return true; - if (pt1[1] === pt2[1] && (pt1[1] === yEdge0 || pt1[1] === yEdge1)) return true; - } - function getHVEdgeIntersections(pt1, pt2) { - var out = []; - var ptInt1 = onlyConstrainedPoint(pt1); - var ptInt2 = onlyConstrainedPoint(pt2); - if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out; - if (ptInt1) out.push(ptInt1); - if (ptInt2) out.push(ptInt2); - return out; - } - function getABAEdgeIntersections(dim, limit0, limit1) { - return function(pt1, pt2) { - var ptInt1 = onlyConstrainedPoint(pt1); - var ptInt2 = onlyConstrainedPoint(pt2); - var out = []; - if (ptInt1 && ptInt2 && sameEdge(ptInt1, ptInt2)) return out; - if (ptInt1) out.push(ptInt1); - if (ptInt2) out.push(ptInt2); - var midShift = 2 * Lib$10.constrain((pt1[dim] + pt2[dim]) / 2, limit0, limit1) - ((ptInt1 || pt1)[dim] + (ptInt2 || pt2)[dim]); - if (midShift) { - var ptToAlter; - if (ptInt1 && ptInt2) { - ptToAlter = midShift > 0 === ptInt1[dim] > ptInt2[dim] ? ptInt1 : ptInt2; - } else ptToAlter = ptInt1 || ptInt2; - ptToAlter[dim] += midShift; - } - return out; - }; - } - var getEdgeIntersections; - if (shape === "linear" || shape === "spline") { - getEdgeIntersections = getLinearEdgeIntersections; - } else if (shape === "hv" || shape === "vh") { - getEdgeIntersections = getHVEdgeIntersections; - } else if (shape === "hvh") getEdgeIntersections = getABAEdgeIntersections(0, xEdge0, xEdge1); - else if (shape === "vhv") getEdgeIntersections = getABAEdgeIntersections(1, yEdge0, yEdge1); - function getClosestCorner(pt1, pt2) { - var dx = pt2[0] - pt1[0]; - var m = (pt2[1] - pt1[1]) / dx; - var b = (pt1[1] * pt2[0] - pt2[1] * pt1[0]) / dx; - if (b > 0) return [m > 0 ? xEdge0 : xEdge1, yEdge1]; - else return [m > 0 ? xEdge1 : xEdge0, yEdge0]; - } - function updateEdge(pt) { - var x = pt[0]; - var y = pt[1]; - var xSame = x === pts[pti - 1][0]; - var ySame = y === pts[pti - 1][1]; - if (xSame && ySame) return; - if (pti > 1) { - var xSame2 = x === pts[pti - 2][0]; - var ySame2 = y === pts[pti - 2][1]; - if (xSame && (x === xEdge0 || x === xEdge1) && xSame2) { - if (ySame2) pti--; - else pts[pti - 1] = pt; - } else if (ySame && (y === yEdge0 || y === yEdge1) && ySame2) { - if (xSame2) pti--; - else pts[pti - 1] = pt; - } else pts[pti++] = pt; - } else pts[pti++] = pt; - } - function updateEdgesForReentry(pt) { - if (pts[pti - 1][0] !== pt[0] && pts[pti - 1][1] !== pt[1]) { - updateEdge([lastXEdge, lastYEdge]); - } - updateEdge(pt); - lastFarPt = null; - lastXEdge = lastYEdge = 0; - } - var arrayMarker = Lib$10.isArrayOrTypedArray(marker2); - function addPt(pt) { - if (pt && backoff) { - pt.i = i; - pt.d = d; - pt.trace = trace; - pt.marker = arrayMarker ? marker2[pt.i] : marker2; - pt.backoff = backoff; - } - latestXFrac = pt[0] / xLen; - latestYFrac = pt[1] / yLen; - xEdge = pt[0] < xEdge0 ? xEdge0 : pt[0] > xEdge1 ? xEdge1 : 0; - yEdge = pt[1] < yEdge0 ? yEdge0 : pt[1] > yEdge1 ? yEdge1 : 0; - if (xEdge || yEdge) { - if (!pti) { - pts[pti++] = [xEdge || pt[0], yEdge || pt[1]]; - } else if (lastFarPt) { - var intersections = getEdgeIntersections(lastFarPt, pt); - if (intersections.length > 1) { - updateEdgesForReentry(intersections[0]); - pts[pti++] = intersections[1]; - } - } else { - edgePt = getEdgeIntersections(pts[pti - 1], pt)[0]; - pts[pti++] = edgePt; - } - var lastPt = pts[pti - 1]; - if (xEdge && yEdge && (lastPt[0] !== xEdge || lastPt[1] !== yEdge)) { - if (lastFarPt) { - if (lastXEdge !== xEdge && lastYEdge !== yEdge) { - if (lastXEdge && lastYEdge) { - updateEdge(getClosestCorner(lastFarPt, pt)); - } else { - updateEdge([lastXEdge || xEdge, lastYEdge || yEdge]); - } - } else if (lastXEdge && lastYEdge) { - updateEdge([lastXEdge, lastYEdge]); - } - } - updateEdge([xEdge, yEdge]); - } else if (lastXEdge - xEdge && lastYEdge - yEdge) { - updateEdge([xEdge || lastXEdge, yEdge || lastYEdge]); - } - lastFarPt = pt; - lastXEdge = xEdge; - lastYEdge = yEdge; - } else { - if (lastFarPt) { - updateEdgesForReentry(getEdgeIntersections(lastFarPt, pt)[0]); - } - pts[pti++] = pt; - } - } - for (i = 0; i < len; i++) { - clusterStartPt = getPt(i); - if (!clusterStartPt) continue; - pti = 0; - lastFarPt = null; - addPt(clusterStartPt); - for (i++; i < len; i++) { - clusterHighPt = getPt(i); - if (!clusterHighPt) { - if (connectGaps) continue; - else break; - } - if (!linear2 || !opts.simplify) { - addPt(clusterHighPt); - continue; - } - var nextPt = getPt(i + 1); - clusterRefDist = ptDist(clusterHighPt, clusterStartPt); - if (!(fill && (pti === 0 || pti === len - 1)) && clusterRefDist < getTolerance(clusterHighPt, nextPt) * minTolerance) continue; - clusterUnitVector = [ - (clusterHighPt[0] - clusterStartPt[0]) / clusterRefDist, - (clusterHighPt[1] - clusterStartPt[1]) / clusterRefDist - ]; - clusterLowPt = clusterStartPt; - clusterHighVal = clusterRefDist; - clusterLowVal = clusterMinDeviation = clusterMaxDeviation = 0; - clusterHighFirst = false; - clusterEndPt = clusterHighPt; - for (i++; i < d.length; i++) { - thisPt = nextPt; - nextPt = getPt(i + 1); - if (!thisPt) { - if (connectGaps) continue; - else break; - } - thisVector = [ - thisPt[0] - clusterStartPt[0], - thisPt[1] - clusterStartPt[1] - ]; - thisDeviation = thisVector[0] * clusterUnitVector[1] - thisVector[1] * clusterUnitVector[0]; - clusterMinDeviation = Math.min(clusterMinDeviation, thisDeviation); - clusterMaxDeviation = Math.max(clusterMaxDeviation, thisDeviation); - if (clusterMaxDeviation - clusterMinDeviation > getTolerance(thisPt, nextPt)) break; - clusterEndPt = thisPt; - thisVal = thisVector[0] * clusterUnitVector[0] + thisVector[1] * clusterUnitVector[1]; - if (thisVal > clusterHighVal) { - clusterHighVal = thisVal; - clusterHighPt = thisPt; - clusterHighFirst = false; - } else if (thisVal < clusterLowVal) { - clusterLowVal = thisVal; - clusterLowPt = thisPt; - clusterHighFirst = true; - } - } - if (clusterHighFirst) { - addPt(clusterHighPt); - if (clusterEndPt !== clusterLowPt) addPt(clusterLowPt); - } else { - if (clusterLowPt !== clusterStartPt) addPt(clusterLowPt); - if (clusterEndPt !== clusterHighPt) addPt(clusterHighPt); - } - addPt(clusterEndPt); - if (i >= d.length || !thisPt) break; - addPt(thisPt); - clusterStartPt = thisPt; - } - if (lastFarPt) updateEdge([lastXEdge || lastFarPt[0], lastYEdge || lastFarPt[1]]); - segments.push(pts.slice(0, pti)); - } - var lastShapeChar = shape.slice(shape.length - 1); - if (backoff && lastShapeChar !== "h" && lastShapeChar !== "v") { - var trimmed = false; - var n = -1; - var newSegments = []; - for (var j = 0; j < segments.length; j++) { - for (var k = 0; k < segments[j].length - 1; k++) { - var start = segments[j][k]; - var end = segments[j][k + 1]; - var xy = Drawing$i.applyBackoff(end, start); - if (xy[0] !== end[0] || xy[1] !== end[1]) { - trimmed = true; - } - if (!newSegments[n + 1]) { - n++; - newSegments[n] = [ - start, - [xy[0], xy[1]] - ]; - } - } - } - return trimmed ? newSegments : segments; - } - return segments; -}; -var LINKEDFILLS = { tonextx: 1, tonexty: 1, tonext: 1 }; -var link_traces = function linkTraces(gd, plotinfo, cdscatter) { - var trace, i, group, prevtrace, groupIndex; - var groupIndices = {}; - var needsSort = false; - var prevGroupIndex = -1; - var nextGroupIndex = 0; - var prevUnstackedGroupIndex = -1; - for (i = 0; i < cdscatter.length; i++) { - trace = cdscatter[i][0].trace; - group = trace.stackgroup || ""; - if (group) { - if (group in groupIndices) { - groupIndex = groupIndices[group]; - } else { - groupIndex = groupIndices[group] = nextGroupIndex; - nextGroupIndex++; - } - } else if (trace.fill in LINKEDFILLS && prevUnstackedGroupIndex >= 0) { - groupIndex = prevUnstackedGroupIndex; - } else { - groupIndex = prevUnstackedGroupIndex = nextGroupIndex; - nextGroupIndex++; - } - if (groupIndex < prevGroupIndex) needsSort = true; - trace._groupIndex = prevGroupIndex = groupIndex; - } - var cdscatterSorted = cdscatter.slice(); - if (needsSort) { - cdscatterSorted.sort(function(a, b) { - var traceA = a[0].trace; - var traceB = b[0].trace; - return traceA._groupIndex - traceB._groupIndex || traceA.index - traceB.index; - }); - } - var prevtraces = {}; - for (i = 0; i < cdscatterSorted.length; i++) { - trace = cdscatterSorted[i][0].trace; - group = trace.stackgroup || ""; - if (trace.visible === true) { - trace._nexttrace = null; - if (trace.fill in LINKEDFILLS) { - prevtrace = prevtraces[group]; - trace._prevtrace = prevtrace || null; - if (prevtrace) { - prevtrace._nexttrace = trace; - } - } - trace._ownfill = trace.fill && (trace.fill.substr(0, 6) === "tozero" || trace.fill === "toself" || trace.fill.substr(0, 2) === "to" && !trace._prevtrace); - prevtraces[group] = trace; - } else { - trace._prevtrace = trace._nexttrace = trace._ownfill = null; - } - } - return cdscatterSorted; -}; -var d3$n = d3Exports; -var Registry$n = registry; -var Lib$$ = libExports; -var ensureSingle$1 = Lib$$.ensureSingle; -var identity$1 = Lib$$.identity; -var Drawing$h = drawingExports; -var subTypes$4 = subtypes$3; -var linePoints2 = line_points; -var linkTraces$1 = link_traces; -var polygonTester = polygonExports.tester; -var plot$7 = function plot(gd, plotinfo, cdscatter, scatterLayer, transitionOpts, makeOnCompleteCallback) { - var join, onComplete; - var isFullReplot = !transitionOpts; - var hasTransition2 = !!transitionOpts && transitionOpts.duration > 0; - var cdscatterSorted = linkTraces$1(gd, plotinfo, cdscatter); - join = scatterLayer.selectAll("g.trace").data(cdscatterSorted, function(d) { - return d[0].trace.uid; - }); - join.enter().append("g").attr("class", function(d) { - return "trace scatter trace" + d[0].trace.uid; - }).style("stroke-miterlimit", 2); - join.order(); - createFills(gd, join, plotinfo); - if (hasTransition2) { - if (makeOnCompleteCallback) { - onComplete = makeOnCompleteCallback(); - } - var transition2 = d3$n.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { - onComplete && onComplete(); - }).each("interrupt", function() { - onComplete && onComplete(); - }); - transition2.each(function() { - scatterLayer.selectAll("g.trace").each(function(d, i) { - plotOne$2(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts); - }); - }); - } else { - join.each(function(d, i) { - plotOne$2(gd, i, plotinfo, d, cdscatterSorted, this, transitionOpts); - }); - } - if (isFullReplot) { - join.exit().remove(); - } - scatterLayer.selectAll("path:not([d])").remove(); -}; -function createFills(gd, traceJoin, plotinfo) { - traceJoin.each(function(d) { - var fills = ensureSingle$1(d3$n.select(this), "g", "fills"); - Drawing$h.setClipUrl(fills, plotinfo.layerClipId, gd); - var trace = d[0].trace; - var fillData = []; - if (trace._ownfill) fillData.push("_ownFill"); - if (trace._nexttrace) fillData.push("_nextFill"); - var fillJoin = fills.selectAll("g").data(fillData, identity$1); - fillJoin.enter().append("g"); - fillJoin.exit().each(function(d2) { - trace[d2] = null; - }).remove(); - fillJoin.order().each(function(d2) { - trace[d2] = ensureSingle$1(d3$n.select(this), "path", "js-fill"); - }); - }); -} -function plotOne$2(gd, idx, plotinfo, cdscatter, cdscatterAll, element, transitionOpts) { - var isStatic = gd._context.staticPlot; - var i; - selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll); - var hasTransition2 = !!transitionOpts && transitionOpts.duration > 0; - function transition2(selection) { - return hasTransition2 ? selection.transition() : selection; - } - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var trace = cdscatter[0].trace; - var line2 = trace.line; - var tr = d3$n.select(element); - var errorBarGroup = ensureSingle$1(tr, "g", "errorbars"); - var lines = ensureSingle$1(tr, "g", "lines"); - var points = ensureSingle$1(tr, "g", "points"); - var text = ensureSingle$1(tr, "g", "text"); - Registry$n.getComponentMethod("errorbars", "plot")(gd, errorBarGroup, plotinfo, transitionOpts); - if (trace.visible !== true) return; - transition2(tr).style("opacity", trace.opacity); - var ownFillEl3, tonext; - var ownFillDir = trace.fill.charAt(trace.fill.length - 1); - if (ownFillDir !== "x" && ownFillDir !== "y") ownFillDir = ""; - var fillAxisIndex, fillAxisZero; - if (ownFillDir === "y") { - fillAxisIndex = 1; - fillAxisZero = ya.c2p(0, true); - } else if (ownFillDir === "x") { - fillAxisIndex = 0; - fillAxisZero = xa.c2p(0, true); - } - cdscatter[0][plotinfo.isRangePlot ? "nodeRangePlot3" : "node3"] = tr; - var prevRevpath = ""; - var prevPolygons = []; - var prevtrace = trace._prevtrace; - var prevFillsegments = null; - var prevFillElement = null; - if (prevtrace) { - prevRevpath = prevtrace._prevRevpath || ""; - tonext = prevtrace._nextFill; - prevPolygons = prevtrace._ownPolygons; - prevFillsegments = prevtrace._fillsegments; - prevFillElement = prevtrace._fillElement; - } - var thispath; - var thisrevpath; - var fullpath = ""; - var revpath = ""; - var pathfn, revpathbase, revpathfn; - var pt0, lastSegment, pt1; - var thisPolygons = []; - trace._polygons = []; - var fillsegments = []; - var segments = []; - var makeUpdate = Lib$$.noop; - ownFillEl3 = trace._ownFill; - if (subTypes$4.hasLines(trace) || trace.fill !== "none") { - if (tonext) { - tonext.datum(cdscatter); - } - if (["hv", "vh", "hvh", "vhv"].indexOf(line2.shape) !== -1) { - pathfn = Drawing$h.steps(line2.shape); - revpathbase = Drawing$h.steps( - line2.shape.split("").reverse().join("") - ); - } else if (line2.shape === "spline") { - pathfn = revpathbase = function(pts2) { - var pLast = pts2[pts2.length - 1]; - if (pts2.length > 1 && pts2[0][0] === pLast[0] && pts2[0][1] === pLast[1]) { - return Drawing$h.smoothclosed(pts2.slice(1), line2.smoothing); - } else { - return Drawing$h.smoothopen(pts2, line2.smoothing); - } - }; - } else { - pathfn = revpathbase = function(pts2) { - return "M" + pts2.join("L"); - }; - } - revpathfn = function(pts2) { - return revpathbase(pts2.reverse()); - }; - segments = linePoints2(cdscatter, { - xaxis: xa, - yaxis: ya, - trace, - connectGaps: trace.connectgaps, - baseTolerance: Math.max(line2.width || 1, 3) / 4, - shape: line2.shape, - backoff: line2.backoff, - simplify: line2.simplify, - fill: trace.fill - }); - fillsegments = new Array(segments.length); - var fillsegmentCount = 0; - for (i = 0; i < segments.length; i++) { - var curpoints; - var pts = segments[i]; - if (!curpoints || !ownFillDir) { - curpoints = pts.slice(); - fillsegments[fillsegmentCount] = curpoints; - fillsegmentCount++; - } else { - curpoints.push.apply(curpoints, pts); - } - } - trace._fillElement = null; - trace._fillExclusionElement = prevFillElement; - trace._fillsegments = fillsegments.slice(0, fillsegmentCount); - fillsegments = trace._fillsegments; - if (segments.length) { - pt0 = segments[0][0].slice(); - lastSegment = segments[segments.length - 1]; - pt1 = lastSegment[lastSegment.length - 1].slice(); - } - makeUpdate = function(isEnter) { - return function(pts2) { - thispath = pathfn(pts2); - thisrevpath = revpathfn(pts2); - if (!fullpath) { - fullpath = thispath; - revpath = thisrevpath; - } else if (ownFillDir) { - fullpath += "L" + thispath.substr(1); - revpath = thisrevpath + ("L" + revpath.substr(1)); - } else { - fullpath += "Z" + thispath; - revpath = thisrevpath + "Z" + revpath; - } - if (subTypes$4.hasLines(trace)) { - var el = d3$n.select(this); - el.datum(cdscatter); - if (isEnter) { - transition2(el.style("opacity", 0).attr("d", thispath).call(Drawing$h.lineGroupStyle)).style("opacity", 1); - } else { - var sel = transition2(el); - sel.attr("d", thispath); - Drawing$h.singleLineStyle(cdscatter, sel); - } - } - }; - }; - } - var lineJoin = lines.selectAll(".js-line").data(segments); - transition2(lineJoin.exit()).style("opacity", 0).remove(); - lineJoin.each(makeUpdate(false)); - lineJoin.enter().append("path").classed("js-line", true).style("vector-effect", isStatic ? "none" : "non-scaling-stroke").call(Drawing$h.lineGroupStyle).each(makeUpdate(true)); - Drawing$h.setClipUrl(lineJoin, plotinfo.layerClipId, gd); - function clearFill(selection) { - transition2(selection).attr("d", "M0,0Z"); - } - var makeSelfPolygons = function() { - var polygons = new Array(fillsegments.length); - for (i = 0; i < fillsegments.length; i++) { - polygons[i] = polygonTester(fillsegments[i]); - } - return polygons; - }; - var makePolygonsToPrevious = function(prevFillsegments2) { - var polygons, i2; - if (!prevFillsegments2 || prevFillsegments2.length === 0) { - polygons = new Array(fillsegments.length); - for (i2 = 0; i2 < fillsegments.length; i2++) { - var pt02 = fillsegments[i2][0].slice(); - var pt12 = fillsegments[i2][fillsegments[i2].length - 1].slice(); - pt02[fillAxisIndex] = pt12[fillAxisIndex] = fillAxisZero; - var zeropoints = [pt12, pt02]; - var polypoints = zeropoints.concat(fillsegments[i2]); - polygons[i2] = polygonTester(polypoints); - } - } else { - polygons = new Array(prevFillsegments2.length - 1 + fillsegments.length); - for (i2 = 0; i2 < prevFillsegments2.length - 1; i2++) { - polygons[i2] = polygonTester(prevFillsegments2[i2]); - } - var reversedPrevFillsegment = prevFillsegments2[prevFillsegments2.length - 1].slice(); - reversedPrevFillsegment.reverse(); - for (i2 = 0; i2 < fillsegments.length; i2++) { - polygons[prevFillsegments2.length - 1 + i2] = polygonTester(fillsegments[i2].concat(reversedPrevFillsegment)); - } - } - return polygons; - }; - if (segments.length) { - if (ownFillEl3) { - ownFillEl3.datum(cdscatter); - if (pt0 && pt1) { - if (ownFillDir) { - pt0[fillAxisIndex] = pt1[fillAxisIndex] = fillAxisZero; - transition2(ownFillEl3).attr("d", "M" + pt1 + "L" + pt0 + "L" + fullpath.substr(1)).call(Drawing$h.singleFillStyle, gd); - thisPolygons = makePolygonsToPrevious(null); - } else { - transition2(ownFillEl3).attr("d", fullpath + "Z").call(Drawing$h.singleFillStyle, gd); - thisPolygons = makeSelfPolygons(); - } - } - trace._polygons = thisPolygons; - trace._fillElement = ownFillEl3; - } else if (tonext) { - if (trace.fill.substr(0, 6) === "tonext" && fullpath && prevRevpath) { - if (trace.fill === "tonext") { - transition2(tonext).attr("d", fullpath + "Z" + prevRevpath + "Z").call(Drawing$h.singleFillStyle, gd); - thisPolygons = makeSelfPolygons(); - trace._polygons = thisPolygons.concat(prevPolygons); - } else { - transition2(tonext).attr("d", fullpath + "L" + prevRevpath.substr(1) + "Z").call(Drawing$h.singleFillStyle, gd); - thisPolygons = makePolygonsToPrevious(prevFillsegments); - trace._polygons = thisPolygons; - } - trace._fillElement = tonext; - } else { - clearFill(tonext); - } - } - trace._prevRevpath = revpath; - } else { - if (ownFillEl3) clearFill(ownFillEl3); - else if (tonext) clearFill(tonext); - trace._prevRevpath = null; - } - trace._ownPolygons = thisPolygons; - function visFilter(d) { - return d.filter(function(v) { - return !v.gap && v.vis; - }); - } - function visFilterWithGaps(d) { - return d.filter(function(v) { - return v.vis; - }); - } - function gapFilter(d) { - return d.filter(function(v) { - return !v.gap; - }); - } - function keyFunc2(d) { - return d.id; - } - function getKeyFunc2(trace2) { - if (trace2.ids) { - return keyFunc2; - } - } - function hideFilter() { - return false; - } - function makePoints(points2, text2, cdscatter2) { - var join, selection, hasNode; - var trace2 = cdscatter2[0].trace; - var showMarkers = subTypes$4.hasMarkers(trace2); - var showText = subTypes$4.hasText(trace2); - var keyFunc3 = getKeyFunc2(trace2); - var markerFilter = hideFilter; - var textFilter = hideFilter; - if (showMarkers || showText) { - var showFilter = identity$1; - var stackGroup = trace2.stackgroup; - var isInferZero = stackGroup && gd._fullLayout._scatterStackOpts[xa._id + ya._id][stackGroup].stackgaps === "infer zero"; - if (trace2.marker.maxdisplayed || trace2._needsCull) { - showFilter = isInferZero ? visFilterWithGaps : visFilter; - } else if (stackGroup && !isInferZero) { - showFilter = gapFilter; - } - if (showMarkers) markerFilter = showFilter; - if (showText) textFilter = showFilter; - } - selection = points2.selectAll("path.point"); - join = selection.data(markerFilter, keyFunc3); - var enter = join.enter().append("path").classed("point", true); - if (hasTransition2) { - enter.call(Drawing$h.pointStyle, trace2, gd).call(Drawing$h.translatePoints, xa, ya).style("opacity", 0).transition().style("opacity", 1); - } - join.order(); - var styleFns; - if (showMarkers) { - styleFns = Drawing$h.makePointStyleFns(trace2); - } - join.each(function(d) { - var el = d3$n.select(this); - var sel = transition2(el); - hasNode = Drawing$h.translatePoint(d, sel, xa, ya); - if (hasNode) { - Drawing$h.singlePointStyle(d, sel, trace2, styleFns, gd); - if (plotinfo.layerClipId) { - Drawing$h.hideOutsideRangePoint(d, sel, xa, ya, trace2.xcalendar, trace2.ycalendar); - } - if (trace2.customdata) { - el.classed("plotly-customdata", d.data !== null && d.data !== void 0); - } - } else { - sel.remove(); - } - }); - if (hasTransition2) { - join.exit().transition().style("opacity", 0).remove(); - } else { - join.exit().remove(); - } - selection = text2.selectAll("g"); - join = selection.data(textFilter, keyFunc3); - join.enter().append("g").classed("textpoint", true).append("text"); - join.order(); - join.each(function(d) { - var g = d3$n.select(this); - var sel = transition2(g.select("text")); - hasNode = Drawing$h.translatePoint(d, sel, xa, ya); - if (hasNode) { - if (plotinfo.layerClipId) { - Drawing$h.hideOutsideRangePoint(d, g, xa, ya, trace2.xcalendar, trace2.ycalendar); - } - } else { - g.remove(); - } - }); - join.selectAll("text").call(Drawing$h.textPointStyle, trace2, gd).each(function(d) { - var x = xa.c2p(d.x); - var y = ya.c2p(d.y); - d3$n.select(this).selectAll("tspan.line").each(function() { - transition2(d3$n.select(this)).attr({ x, y }); - }); - }); - join.exit().remove(); - } - points.datum(cdscatter); - text.datum(cdscatter); - makePoints(points, text, cdscatter); - var hasClipOnAxisFalse = trace.cliponaxis === false; - var clipUrl = hasClipOnAxisFalse ? null : plotinfo.layerClipId; - Drawing$h.setClipUrl(points, clipUrl, gd); - Drawing$h.setClipUrl(text, clipUrl, gd); -} -function selectMarkers(gd, idx, plotinfo, cdscatter, cdscatterAll) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xr = d3$n.extent(Lib$$.simpleMap(xa.range, xa.r2c)); - var yr = d3$n.extent(Lib$$.simpleMap(ya.range, ya.r2c)); - var trace = cdscatter[0].trace; - if (!subTypes$4.hasMarkers(trace)) return; - var mnum = trace.marker.maxdisplayed; - if (mnum === 0) return; - var cd = cdscatter.filter(function(v) { - return v.x >= xr[0] && v.x <= xr[1] && v.y >= yr[0] && v.y <= yr[1]; - }); - var inc = Math.ceil(cd.length / mnum); - var tnum = 0; - cdscatterAll.forEach(function(cdj, j) { - var tracei = cdj[0].trace; - if (subTypes$4.hasMarkers(tracei) && tracei.marker.maxdisplayed > 0 && j < idx) { - tnum++; - } - }); - var i0 = Math.round(tnum * inc / 3 + Math.floor(tnum / 3) * inc / 7.1); - cdscatter.forEach(function(v) { - delete v.vis; - }); - cd.forEach(function(v, i) { - if (Math.round((i + i0) % inc) === 0) v.vis = true; - }); -} -var marker_colorbar = { - container: "marker", - min: "cmin", - max: "cmax" -}; -var Axes$f = axesExports; -var format_labels$1 = function formatLabels(cdi, trace, fullLayout) { - var labels = {}; - var mockGd = { _fullLayout: fullLayout }; - var xa = Axes$f.getFromTrace(mockGd, trace, "x"); - var ya = Axes$f.getFromTrace(mockGd, trace, "y"); - var x = cdi.orig_x; - if (x === void 0) x = cdi.x; - var y = cdi.orig_y; - if (y === void 0) y = cdi.y; - labels.xLabel = Axes$f.tickText(xa, xa.c2l(x), true).text; - labels.yLabel = Axes$f.tickText(ya, ya.c2l(y), true).text; - return labels; -}; -var d3$m = d3Exports; -var Drawing$g = drawingExports; -var Registry$m = registry; -function style$6(gd) { - var s = d3$m.select(gd).selectAll("g.trace.scatter"); - s.style("opacity", function(d) { - return d[0].trace.opacity; - }); - s.selectAll("g.points").each(function(d) { - var sel = d3$m.select(this); - var trace = d.trace || d[0].trace; - stylePoints$1(sel, trace, gd); - }); - s.selectAll("g.text").each(function(d) { - var sel = d3$m.select(this); - var trace = d.trace || d[0].trace; - styleText(sel, trace, gd); - }); - s.selectAll("g.trace path.js-line").call(Drawing$g.lineGroupStyle); - s.selectAll("g.trace path.js-fill").call(Drawing$g.fillGroupStyle, gd, false); - Registry$m.getComponentMethod("errorbars", "style")(s); -} -function stylePoints$1(sel, trace, gd) { - Drawing$g.pointStyle(sel.selectAll("path.point"), trace, gd); -} -function styleText(sel, trace, gd) { - Drawing$g.textPointStyle(sel.selectAll("text"), trace, gd); -} -function styleOnSelect$1(gd, cd, sel) { - var trace = cd[0].trace; - if (trace.selectedpoints) { - Drawing$g.selectedPointStyle(sel.selectAll("path.point"), trace); - Drawing$g.selectedTextStyle(sel.selectAll("text"), trace); - } else { - stylePoints$1(sel, trace, gd); - styleText(sel, trace, gd); - } -} -var style_1$3 = { - style: style$6, - styleOnSelect: styleOnSelect$1 -}; -var Color$s = colorExports; -var subtypes$2 = subtypes$3; -var get_trace_color = function getTraceColor(trace, di) { - var lc, tc; - if (trace.mode === "lines") { - lc = trace.line.color; - return lc && Color$s.opacity(lc) ? lc : trace.fillcolor; - } else if (trace.mode === "none") { - return trace.fill ? trace.fillcolor : ""; - } else { - var mc = di.mcc || (trace.marker || {}).color; - var mlc = di.mlcc || ((trace.marker || {}).line || {}).color; - tc = mc && Color$s.opacity(mc) ? mc : mlc && Color$s.opacity(mlc) && (di.mlw || ((trace.marker || {}).line || {}).width) ? mlc : ""; - if (tc) { - if (Color$s.opacity(tc) < 0.3) { - return Color$s.addOpacity(tc, 0.3); - } else return tc; - } else { - lc = (trace.line || {}).color; - return lc && Color$s.opacity(lc) && subtypes$2.hasLines(trace) && trace.line.width ? lc : trace.fillcolor; - } - } -}; -var Lib$_ = libExports; -var Fx$5 = fx$1; -var Registry$l = registry; -var getTraceColor$2 = get_trace_color; -var Color$r = colorExports; -var fillText$2 = Lib$_.fillText; -var hover$5 = function hoverPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - var xa = pointData.xa; - var ya = pointData.ya; - var xpx = xa.c2p(xval); - var ypx = ya.c2p(yval); - var pt = [xpx, ypx]; - var hoveron = trace.hoveron || ""; - var minRad = trace.mode.indexOf("markers") !== -1 ? 3 : 0.5; - var xPeriod = !!trace.xperiodalignment; - var yPeriod = !!trace.yperiodalignment; - if (hoveron.indexOf("points") !== -1) { - var dx = function(di2) { - if (xPeriod) { - var x0 = xa.c2p(di2.xStart); - var x1 = xa.c2p(di2.xEnd); - return xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity; - } - var rad2 = Math.max(3, di2.mrc || 0); - var kink = 1 - 1 / rad2; - var dxRaw = Math.abs(xa.c2p(di2.x) - xpx); - return dxRaw < rad2 ? kink * dxRaw / rad2 : dxRaw - rad2 + kink; - }; - var dy = function(di2) { - if (yPeriod) { - var y0 = ya.c2p(di2.yStart); - var y1 = ya.c2p(di2.yEnd); - return ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity; - } - var rad2 = Math.max(3, di2.mrc || 0); - var kink = 1 - 1 / rad2; - var dyRaw = Math.abs(ya.c2p(di2.y) - ypx); - return dyRaw < rad2 ? kink * dyRaw / rad2 : dyRaw - rad2 + kink; - }; - var dxy = function(di2) { - var rad2 = Math.max(minRad, di2.mrc || 0); - var dx2 = xa.c2p(di2.x) - xpx; - var dy2 = ya.c2p(di2.y) - ypx; - return Math.max(Math.sqrt(dx2 * dx2 + dy2 * dy2) - rad2, 1 - minRad / rad2); - }; - var distfn = Fx$5.getDistanceFunction(hovermode, dx, dy, dxy); - Fx$5.getClosest(cd, distfn, pointData); - if (pointData.index !== false) { - var di = cd[pointData.index]; - var xc = xa.c2p(di.x, true); - var yc = ya.c2p(di.y, true); - var rad = di.mrc || 1; - pointData.index = di.i; - var orientation = cd[0].t.orientation; - var sizeVal = orientation && (di.sNorm || di.s); - var xLabelVal = orientation === "h" ? sizeVal : di.orig_x !== void 0 ? di.orig_x : di.x; - var yLabelVal = orientation === "v" ? sizeVal : di.orig_y !== void 0 ? di.orig_y : di.y; - Lib$_.extendFlat(pointData, { - color: getTraceColor$2(trace, di), - x0: xc - rad, - x1: xc + rad, - xLabelVal, - y0: yc - rad, - y1: yc + rad, - yLabelVal, - spikeDistance: dxy(di), - hovertemplate: trace.hovertemplate - }); - fillText$2(di, trace, pointData); - Registry$l.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData); - return [pointData]; - } - } - function isHoverPointInFillElement(el) { - if (!el) { - return false; - } - var svgElement = el.node(); - try { - var domPoint = new DOMPoint(pt[0], pt[1]); - return svgElement.isPointInFill(domPoint); - } catch (TypeError2) { - var svgPoint = svgElement.ownerSVGElement.createSVGPoint(); - svgPoint.x = pt[0]; - svgPoint.y = pt[1]; - return svgElement.isPointInFill(svgPoint); - } - } - function getHoverLabelPosition(polygons) { - var i; - var polygonsIn = []; - var xmin = Infinity; - var xmax = -Infinity; - var ymin = Infinity; - var ymax = -Infinity; - var yPos; - for (i = 0; i < polygons.length; i++) { - var polygon2 = polygons[i]; - if (polygon2.contains(pt)) { - polygonsIn.push(polygon2); - ymin = Math.min(ymin, polygon2.ymin); - ymax = Math.max(ymax, polygon2.ymax); - } - } - if (polygonsIn.length === 0) { - return null; - } - ymin = Math.max(ymin, 0); - ymax = Math.min(ymax, ya._length); - yPos = (ymin + ymax) / 2; - var j, pts, xAtYPos, x0, x1, y0, y1; - for (i = 0; i < polygonsIn.length; i++) { - pts = polygonsIn[i].pts; - for (j = 1; j < pts.length; j++) { - y0 = pts[j - 1][1]; - y1 = pts[j][1]; - if (y0 > yPos !== y1 >= yPos) { - x0 = pts[j - 1][0]; - x1 = pts[j][0]; - if (y1 - y0) { - xAtYPos = x0 + (x1 - x0) * (yPos - y0) / (y1 - y0); - xmin = Math.min(xmin, xAtYPos); - xmax = Math.max(xmax, xAtYPos); - } - } - } - } - xmin = Math.max(xmin, 0); - xmax = Math.min(xmax, xa._length); - return { - x0: xmin, - x1: xmax, - y0: yPos, - y1: yPos - }; - } - if (hoveron.indexOf("fills") !== -1 && trace._fillElement) { - var inside = isHoverPointInFillElement(trace._fillElement) && !isHoverPointInFillElement(trace._fillExclusionElement); - if (inside) { - var hoverLabelCoords = getHoverLabelPosition(trace._polygons); - if (hoverLabelCoords === null) { - hoverLabelCoords = { - x0: pt[0], - x1: pt[0], - y0: pt[1], - y1: pt[1] - }; - } - var color2 = Color$r.defaultLine; - if (Color$r.opacity(trace.fillcolor)) color2 = trace.fillcolor; - else if (Color$r.opacity((trace.line || {}).color)) { - color2 = trace.line.color; - } - Lib$_.extendFlat(pointData, { - // never let a 2D override 1D type as closest point - // also: no spikeDistance, it's not allowed for fills - distance: pointData.maxHoverDistance, - x0: hoverLabelCoords.x0, - x1: hoverLabelCoords.x1, - y0: hoverLabelCoords.y0, - y1: hoverLabelCoords.y1, - color: color2, - hovertemplate: false - }); - delete pointData.index; - if (trace.text && !Lib$_.isArrayOrTypedArray(trace.text)) { - pointData.text = String(trace.text); - } else pointData.text = trace.name; - return [pointData]; - } - } -}; -var subtypes$1 = subtypes$3; -var select$3 = function selectPoints(searchInfo, selectionTester) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var trace = cd[0].trace; - var i; - var di; - var x; - var y; - var hasOnlyLines = !subtypes$1.hasMarkers(trace) && !subtypes$1.hasText(trace); - if (hasOnlyLines) return []; - if (selectionTester === false) { - for (i = 0; i < cd.length; i++) { - cd[i].selected = 0; - } - } else { - for (i = 0; i < cd.length; i++) { - di = cd[i]; - x = xa.c2p(di.x); - y = ya.c2p(di.y); - if (di.i !== null && selectionTester.contains([x, y], false, i, searchInfo)) { - selection.push({ - pointNumber: di.i, - x: xa.c2d(di.x), - y: ya.c2d(di.y) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } - } - return selection; -}; -var cartesian = {}; -var attributes$v; -var hasRequiredAttributes; -function requireAttributes() { - if (hasRequiredAttributes) return attributes$v; - hasRequiredAttributes = 1; - attributes$v = { - xaxis: { - valType: "subplotid", - dflt: "x", - editType: "calc+clearAxisTypes", - description: [ - "Sets a reference between this trace's x coordinates and", - "a 2D cartesian x axis.", - "If *x* (the default value), the x coordinates refer to", - "`layout.xaxis`.", - "If *x2*, the x coordinates refer to `layout.xaxis2`, and so on." - ].join(" ") - }, - yaxis: { - valType: "subplotid", - dflt: "y", - editType: "calc+clearAxisTypes", - description: [ - "Sets a reference between this trace's y coordinates and", - "a 2D cartesian y axis.", - "If *y* (the default value), the y coordinates refer to", - "`layout.yaxis`.", - "If *y2*, the y coordinates refer to `layout.yaxis2`, and so on." - ].join(" ") - } - }; - return attributes$v; -} -var type_defaults; -var hasRequiredType_defaults; -function requireType_defaults() { - if (hasRequiredType_defaults) return type_defaults; - hasRequiredType_defaults = 1; - var traceIs2 = registry.traceIs; - var autoType3 = axis_autotype; - type_defaults = function handleTypeDefaults(containerIn, containerOut, coerce2, options) { - coerce2("autotypenumbers", options.autotypenumbersDflt); - var axType = coerce2("type", (options.splomStash || {}).type); - if (axType === "-") { - setAutoType(containerOut, options.data); - if (containerOut.type === "-") { - containerOut.type = "linear"; - } else { - containerIn.type = containerOut.type; - } - } - }; - function setAutoType(ax, data) { - if (ax.type !== "-") return; - var id = ax._id; - var axLetter = id.charAt(0); - var i; - if (id.indexOf("scene") !== -1) id = axLetter; - var d0 = getFirstNonEmptyTrace(data, id, axLetter); - if (!d0) return; - if (d0.type === "histogram" && axLetter === { v: "y", h: "x" }[d0.orientation || "v"]) { - ax.type = "linear"; - return; - } - var calAttr = axLetter + "calendar"; - var calendar = d0[calAttr]; - var opts = { noMultiCategory: !traceIs2(d0, "cartesian") || traceIs2(d0, "noMultiCategory") }; - if (d0.type === "box" && d0._hasPreCompStats && axLetter === { h: "x", v: "y" }[d0.orientation || "v"]) { - opts.noMultiCategory = true; - } - opts.autotypenumbers = ax.autotypenumbers; - if (isBoxWithoutPositionCoords(d0, axLetter)) { - var posLetter = getBoxPosLetter(d0); - var boxPositions = []; - for (i = 0; i < data.length; i++) { - var trace = data[i]; - if (!traceIs2(trace, "box-violin") || (trace[axLetter + "axis"] || axLetter) !== id) continue; - if (trace[posLetter] !== void 0) boxPositions.push(trace[posLetter][0]); - else if (trace.name !== void 0) boxPositions.push(trace.name); - else boxPositions.push("text"); - if (trace[calAttr] !== calendar) calendar = void 0; - } - ax.type = autoType3(boxPositions, calendar, opts); - } else if (d0.type === "splom") { - var dimensions = d0.dimensions; - var dim = dimensions[d0._axesDim[id]]; - if (dim.visible) ax.type = autoType3(dim.values, calendar, opts); - } else { - ax.type = autoType3(d0[axLetter] || [d0[axLetter + "0"]], calendar, opts); - } - } - function getFirstNonEmptyTrace(data, id, axLetter) { - for (var i = 0; i < data.length; i++) { - var trace = data[i]; - if (trace.type === "splom" && trace._length > 0 && (trace["_" + axLetter + "axes"] || {})[id]) { - return trace; - } - if ((trace[axLetter + "axis"] || axLetter) === id) { - if (isBoxWithoutPositionCoords(trace, axLetter)) { - return trace; - } else if ((trace[axLetter] || []).length || trace[axLetter + "0"]) { - return trace; - } - } - } - } - function getBoxPosLetter(trace) { - return { v: "x", h: "y" }[trace.orientation || "v"]; - } - function isBoxWithoutPositionCoords(trace, axLetter) { - var posLetter = getBoxPosLetter(trace); - var isBox = traceIs2(trace, "box-violin"); - var isCandlestick = traceIs2(trace._fullInput || {}, "candlestick"); - return isBox && !isCandlestick && axLetter === posLetter && trace[posLetter] === void 0 && trace[posLetter + "0"] === void 0; - } - return type_defaults; -} -var isTypedArraySpec = array$2.isTypedArraySpec; -function findCategories(ax, opts) { - var dataAttr = opts.dataAttr || ax._id.charAt(0); - var lookup2 = {}; - var axData; - var i, j; - if (opts.axData) { - axData = opts.axData; - } else { - axData = []; - for (i = 0; i < opts.data.length; i++) { - var trace = opts.data[i]; - if (trace[dataAttr + "axis"] === ax._id) { - axData.push(trace); - } - } - } - for (i = 0; i < axData.length; i++) { - var vals = axData[i][dataAttr]; - for (j = 0; j < vals.length; j++) { - var v = vals[j]; - if (v !== null && v !== void 0) { - lookup2[v] = 1; - } - } - } - return Object.keys(lookup2); -} -var category_order_defaults = function handleCategoryOrderDefaults(containerIn, containerOut, coerce2, opts) { - if (containerOut.type !== "category") return; - var arrayIn = containerIn.categoryarray; - var isValidArray = Array.isArray(arrayIn) && arrayIn.length > 0 || isTypedArraySpec(arrayIn); - var orderDefault; - if (isValidArray) orderDefault = "array"; - var order = coerce2("categoryorder", orderDefault); - var array2; - if (order === "array") { - array2 = coerce2("categoryarray"); - } - if (!isValidArray && order === "array") { - order = containerOut.categoryorder = "trace"; - } - if (order === "trace") { - containerOut._initialCategories = []; - } else if (order === "array") { - containerOut._initialCategories = array2.slice(); - } else { - array2 = findCategories(containerOut, opts).sort(); - if (order === "category ascending") { - containerOut._initialCategories = array2; - } else if (order === "category descending") { - containerOut._initialCategories = array2.reverse(); - } - } -}; -var colorMix = tinycolorExports.mix; -var colorAttrs$3 = attributes$N; -var Lib$Z = libExports; -var line_grid_defaults = function handleLineGridDefaults(containerIn, containerOut, coerce2, opts) { - opts = opts || {}; - var dfltColor = opts.dfltColor; - function coerce22(attr, dflt) { - return Lib$Z.coerce2(containerIn, containerOut, opts.attributes, attr, dflt); - } - var lineColor = coerce22("linecolor", dfltColor); - var lineWidth = coerce22("linewidth"); - var showLine = coerce2("showline", opts.showLine || !!lineColor || !!lineWidth); - if (!showLine) { - delete containerOut.linecolor; - delete containerOut.linewidth; - } - var gridColorDflt = colorMix(dfltColor, opts.bgColor, opts.blend || colorAttrs$3.lightFraction).toRgbString(); - var gridColor = coerce22("gridcolor", gridColorDflt); - var gridWidth = coerce22("gridwidth"); - var gridDash = coerce22("griddash"); - var showGridLines = coerce2( - "showgrid", - opts.showGrid || !!gridColor || !!gridWidth || !!gridDash - ); - if (!showGridLines) { - delete containerOut.gridcolor; - delete containerOut.gridwidth; - delete containerOut.griddash; - } - if (opts.hasMinor) { - var minorGridColorDflt = colorMix(containerOut.gridcolor, opts.bgColor, 67).toRgbString(); - var minorGridColor = coerce22("minor.gridcolor", minorGridColorDflt); - var minorGridWidth = coerce22("minor.gridwidth", containerOut.gridwidth || 1); - var minorGridDash = coerce22("minor.griddash", containerOut.griddash || "solid"); - var minorShowGridLines = coerce2( - "minor.showgrid", - !!minorGridColor || !!minorGridWidth || !!minorGridDash - ); - if (!minorShowGridLines) { - delete containerOut.minor.gridcolor; - delete containerOut.minor.gridwidth; - delete containerOut.minor.griddash; - } - } - if (!opts.noZeroLine) { - var zeroLineColor = coerce22("zerolinecolor", dfltColor); - var zeroLineWidth = coerce22("zerolinewidth"); - var showZeroLine = coerce2("zeroline", opts.showGrid || !!zeroLineColor || !!zeroLineWidth); - if (!showZeroLine) { - delete containerOut.zerolinecolor; - delete containerOut.zerolinewidth; - } - } -}; -var isNumeric$c = fastIsnumeric; -var Registry$k = registry; -var Lib$Y = libExports; -var Template$2 = plot_template; -var handleArrayContainerDefaults$7 = array_container_defaults; -var layoutAttributes$3 = layout_attributes$4; -var handleTickValueDefaults2 = tick_value_defaults; -var handleTickMarkDefaults2 = tick_mark_defaults; -var handleTickLabelDefaults2 = tick_label_defaults; -var handlePrefixSuffixDefaults2 = prefix_suffix_defaults; -var handleCategoryOrderDefaults2 = category_order_defaults; -var handleLineGridDefaults2 = line_grid_defaults; -var handleRangeDefaults2 = range_defaults; -var setConvert2 = set_convert; -var DAY_OF_WEEK = constants$U.WEEKDAY_PATTERN; -var HOUR = constants$U.HOUR_PATTERN; -var axis_defaults = function handleAxisDefaults(containerIn, containerOut, coerce2, options, layoutOut) { - var letter = options.letter; - var font2 = options.font || {}; - var splomStash = options.splomStash || {}; - var visible = coerce2("visible", !options.visibleDflt); - var axTemplate = containerOut._template || {}; - var axType = containerOut.type || axTemplate.type || "-"; - var ticklabelmode; - if (axType === "date") { - var handleCalendarDefaults = Registry$k.getComponentMethod("calendars", "handleDefaults"); - handleCalendarDefaults(containerIn, containerOut, "calendar", options.calendar); - if (!options.noTicklabelmode) { - ticklabelmode = coerce2("ticklabelmode"); - } - } - if (!options.noTicklabelindex && (axType === "date" || axType === "linear")) { - coerce2("ticklabelindex"); - } - var ticklabelposition = ""; - if (!options.noTicklabelposition || axType === "multicategory") { - ticklabelposition = Lib$Y.coerce(containerIn, containerOut, { - ticklabelposition: { - valType: "enumerated", - dflt: "outside", - values: ticklabelmode === "period" ? ["outside", "inside"] : letter === "x" ? [ - "outside", - "inside", - "outside left", - "inside left", - "outside right", - "inside right" - ] : [ - "outside", - "inside", - "outside top", - "inside top", - "outside bottom", - "inside bottom" - ] - } - }, "ticklabelposition"); - } - if (!options.noTicklabeloverflow) { - coerce2( - "ticklabeloverflow", - ticklabelposition.indexOf("inside") !== -1 ? "hide past domain" : axType === "category" || axType === "multicategory" ? "allow" : "hide past div" - ); - } - setConvert2(containerOut, layoutOut); - handleRangeDefaults2(containerIn, containerOut, coerce2, options); - handleCategoryOrderDefaults2(containerIn, containerOut, coerce2, options); - if (axType !== "category" && !options.noHover) coerce2("hoverformat"); - var dfltColor = coerce2("color"); - var dfltFontColor = dfltColor !== layoutAttributes$3.color.dflt ? dfltColor : font2.color; - var dfltTitle = splomStash.label || layoutOut._dfltTitle[letter]; - handlePrefixSuffixDefaults2(containerIn, containerOut, coerce2, axType, options); - if (!visible) return containerOut; - coerce2("title.text", dfltTitle); - Lib$Y.coerceFont(coerce2, "title.font", font2, { overrideDflt: { - size: Lib$Y.bigFont(font2.size), - color: dfltFontColor - } }); - handleTickValueDefaults2(containerIn, containerOut, coerce2, axType); - var hasMinor = options.hasMinor; - if (hasMinor) { - Template$2.newContainer(containerOut, "minor"); - handleTickValueDefaults2(containerIn, containerOut, coerce2, axType, { isMinor: true }); - } - handleTickLabelDefaults2(containerIn, containerOut, coerce2, axType, options); - handleTickMarkDefaults2(containerIn, containerOut, coerce2, options); - if (hasMinor) { - var keepIsMinor = options.isMinor; - options.isMinor = true; - handleTickMarkDefaults2(containerIn, containerOut, coerce2, options); - options.isMinor = keepIsMinor; - } - handleLineGridDefaults2(containerIn, containerOut, coerce2, { - dfltColor, - bgColor: options.bgColor, - showGrid: options.showGrid, - hasMinor, - attributes: layoutAttributes$3 - }); - if (hasMinor && !containerOut.minor.ticks && !containerOut.minor.showgrid) { - delete containerOut.minor; - } - if (containerOut.showline || containerOut.ticks) coerce2("mirror"); - var isMultiCategory = axType === "multicategory"; - if (!options.noTickson && (axType === "category" || isMultiCategory) && (containerOut.ticks || containerOut.showgrid)) { - var ticksonDflt; - if (isMultiCategory) ticksonDflt = "boundaries"; - var tickson = coerce2("tickson", ticksonDflt); - if (tickson === "boundaries") { - delete containerOut.ticklabelposition; - } - } - if (isMultiCategory) { - var showDividers = coerce2("showdividers"); - if (showDividers) { - coerce2("dividercolor"); - coerce2("dividerwidth"); - } - } - if (axType === "date") { - handleArrayContainerDefaults$7(containerIn, containerOut, { - name: "rangebreaks", - inclusionAttr: "enabled", - handleItemDefaults: rangebreaksDefaults - }); - if (!containerOut.rangebreaks.length) { - delete containerOut.rangebreaks; - } else { - for (var k = 0; k < containerOut.rangebreaks.length; k++) { - if (containerOut.rangebreaks[k].pattern === DAY_OF_WEEK) { - containerOut._hasDayOfWeekBreaks = true; - break; - } - } - setConvert2(containerOut, layoutOut); - if (layoutOut._has("scattergl") || layoutOut._has("splom")) { - for (var i = 0; i < options.data.length; i++) { - var trace = options.data[i]; - if (trace.type === "scattergl" || trace.type === "splom") { - trace.visible = false; - Lib$Y.warn(trace.type + " traces do not work on axes with rangebreaks. Setting trace " + trace.index + " to `visible: false`."); - } - } - } - } - } - return containerOut; -}; -function rangebreaksDefaults(itemIn, itemOut, containerOut) { - function coerce2(attr, dflt) { - return Lib$Y.coerce(itemIn, itemOut, layoutAttributes$3.rangebreaks, attr, dflt); - } - var enabled = coerce2("enabled"); - if (enabled) { - var bnds = coerce2("bounds"); - if (bnds && bnds.length >= 2) { - var dfltPattern = ""; - var i, q; - if (bnds.length === 2) { - for (i = 0; i < 2; i++) { - q = indexOfDay(bnds[i]); - if (q) { - dfltPattern = DAY_OF_WEEK; - break; - } - } - } - var pattern2 = coerce2("pattern", dfltPattern); - if (pattern2 === DAY_OF_WEEK) { - for (i = 0; i < 2; i++) { - q = indexOfDay(bnds[i]); - if (q) { - itemOut.bounds[i] = bnds[i] = q - 1; - } - } - } - if (pattern2) { - for (i = 0; i < 2; i++) { - q = bnds[i]; - switch (pattern2) { - case DAY_OF_WEEK: - if (!isNumeric$c(q)) { - itemOut.enabled = false; - return; - } - q = +q; - if (q !== Math.floor(q) || // don't accept fractional days for mow - q < 0 || q >= 7) { - itemOut.enabled = false; - return; - } - itemOut.bounds[i] = bnds[i] = q; - break; - case HOUR: - if (!isNumeric$c(q)) { - itemOut.enabled = false; - return; - } - q = +q; - if (q < 0 || q > 24) { - itemOut.enabled = false; - return; - } - itemOut.bounds[i] = bnds[i] = q; - break; - } - } - } - if (containerOut.autorange === false) { - var rng = containerOut.range; - if (rng[0] < rng[1]) { - if (bnds[0] < rng[0] && bnds[1] > rng[1]) { - itemOut.enabled = false; - return; - } - } else if (bnds[0] > rng[0] && bnds[1] < rng[1]) { - itemOut.enabled = false; - return; - } - } - } else { - var values = coerce2("values"); - if (values && values.length) { - coerce2("dvalue"); - } else { - itemOut.enabled = false; - return; - } - } - } -} -var dayStrToNum = { - sun: 1, - mon: 2, - tue: 3, - wed: 4, - thu: 5, - fri: 6, - sat: 7 -}; -function indexOfDay(v) { - if (typeof v !== "string") return; - return dayStrToNum[v.substr(0, 3).toLowerCase()]; -} -var isNumeric$b = fastIsnumeric; -var Lib$X = libExports; -var position_defaults = function handlePositionDefaults(containerIn, containerOut, coerce2, options) { - var counterAxes = options.counterAxes || []; - var overlayableAxes = options.overlayableAxes || []; - var letter = options.letter; - var grid2 = options.grid; - var overlayingDomain = options.overlayingDomain; - var dfltAnchor, dfltDomain, dfltSide, dfltPosition, dfltShift, dfltAutomargin; - if (grid2) { - dfltDomain = grid2._domains[letter][grid2._axisMap[containerOut._id]]; - dfltAnchor = grid2._anchors[containerOut._id]; - if (dfltDomain) { - dfltSide = grid2[letter + "side"].split(" ")[0]; - dfltPosition = grid2.domain[letter][dfltSide === "right" || dfltSide === "top" ? 1 : 0]; - } - } - dfltDomain = dfltDomain || [0, 1]; - dfltAnchor = dfltAnchor || (isNumeric$b(containerIn.position) ? "free" : counterAxes[0] || "free"); - dfltSide = dfltSide || (letter === "x" ? "bottom" : "left"); - dfltPosition = dfltPosition || 0; - dfltShift = 0; - dfltAutomargin = false; - var anchor = Lib$X.coerce(containerIn, containerOut, { - anchor: { - valType: "enumerated", - values: ["free"].concat(counterAxes), - dflt: dfltAnchor - } - }, "anchor"); - var side = Lib$X.coerce(containerIn, containerOut, { - side: { - valType: "enumerated", - values: letter === "x" ? ["bottom", "top"] : ["left", "right"], - dflt: dfltSide - } - }, "side"); - if (anchor === "free") { - if (letter === "y") { - var autoshift = coerce2("autoshift"); - if (autoshift) { - dfltPosition = side === "left" ? overlayingDomain[0] : overlayingDomain[1]; - dfltAutomargin = containerOut.automargin ? containerOut.automargin : true; - dfltShift = side === "left" ? -3 : 3; - } - coerce2("shift", dfltShift); - } - coerce2("position", dfltPosition); - } - coerce2("automargin", dfltAutomargin); - var overlaying = false; - if (overlayableAxes.length) { - overlaying = Lib$X.coerce(containerIn, containerOut, { - overlaying: { - valType: "enumerated", - values: [false].concat(overlayableAxes), - dflt: false - } - }, "overlaying"); - } - if (!overlaying) { - var domain2 = coerce2("domain", dfltDomain); - if (domain2[0] > domain2[1] - 1 / 4096) containerOut.domain = dfltDomain; - Lib$X.noneOrAll(containerIn.domain, containerOut.domain, dfltDomain); - if (containerOut.tickmode === "sync") { - containerOut.tickmode = "auto"; - } - } - coerce2("layer"); - return containerOut; -}; -var layout_defaults$3; -var hasRequiredLayout_defaults; -function requireLayout_defaults() { - if (hasRequiredLayout_defaults) return layout_defaults$3; - hasRequiredLayout_defaults = 1; - var Lib2 = libExports; - var Color2 = colorExports; - var isUnifiedHover2 = helpers$J.isUnifiedHover; - var handleHoverModeDefaults3 = hovermode_defaults; - var Template2 = plot_template; - var basePlotLayoutAttributes2 = layout_attributes$6; - var layoutAttributes2 = layout_attributes$4; - var handleTypeDefaults = requireType_defaults(); - var handleAxisDefaults3 = axis_defaults; - var constraints$1 = constraints; - var handlePositionDefaults2 = position_defaults; - var axisIds2 = axis_ids; - var id2name2 = axisIds2.id2name; - var name2id = axisIds2.name2id; - var AX_ID_PATTERN = constants$U.AX_ID_PATTERN; - var Registry2 = registry; - var traceIs2 = Registry2.traceIs; - var getComponentMethod = Registry2.getComponentMethod; - function appendList(cont, k, item) { - if (Array.isArray(cont[k])) cont[k].push(item); - else cont[k] = [item]; - } - layout_defaults$3 = function supplyLayoutDefaults10(layoutIn, layoutOut, fullData) { - var autotypenumbersDflt = layoutOut.autotypenumbers; - var ax2traces = {}; - var xaMayHide = {}; - var yaMayHide = {}; - var xaMustDisplay = {}; - var yaMustDisplay = {}; - var yaMustNotReverse = {}; - var yaMayReverse = {}; - var axHasImage = {}; - var outerTicks = {}; - var noGrids = {}; - var i, j; - for (i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if (!traceIs2(trace, "cartesian") && !traceIs2(trace, "gl2d")) continue; - var xaName; - if (trace.xaxis) { - xaName = id2name2(trace.xaxis); - appendList(ax2traces, xaName, trace); - } else if (trace.xaxes) { - for (j = 0; j < trace.xaxes.length; j++) { - appendList(ax2traces, id2name2(trace.xaxes[j]), trace); - } - } - var yaName; - if (trace.yaxis) { - yaName = id2name2(trace.yaxis); - appendList(ax2traces, yaName, trace); - } else if (trace.yaxes) { - for (j = 0; j < trace.yaxes.length; j++) { - appendList(ax2traces, id2name2(trace.yaxes[j]), trace); - } - } - if (trace.type === "funnel") { - if (trace.orientation === "h") { - if (xaName) xaMayHide[xaName] = true; - if (yaName) yaMayReverse[yaName] = true; - } else { - if (yaName) yaMayHide[yaName] = true; - } - } else if (trace.type === "image") { - if (yaName) axHasImage[yaName] = true; - if (xaName) axHasImage[xaName] = true; - } else { - if (yaName) { - yaMustDisplay[yaName] = true; - yaMustNotReverse[yaName] = true; - } - if (!traceIs2(trace, "carpet") || trace.type === "carpet" && !trace._cheater) { - if (xaName) xaMustDisplay[xaName] = true; - } - } - if (trace.type === "carpet" && trace._cheater) { - if (xaName) xaMayHide[xaName] = true; - } - if (traceIs2(trace, "2dMap")) { - outerTicks[xaName] = true; - outerTicks[yaName] = true; - } - if (traceIs2(trace, "oriented")) { - var positionAxis = trace.orientation === "h" ? yaName : xaName; - noGrids[positionAxis] = true; - } - } - var subplots = layoutOut._subplots; - var xIds = subplots.xaxis; - var yIds = subplots.yaxis; - var xNames = Lib2.simpleMap(xIds, id2name2); - var yNames = Lib2.simpleMap(yIds, id2name2); - var axNames = xNames.concat(yNames); - var plotBgColor = Color2.background; - if (xIds.length && yIds.length) { - plotBgColor = Lib2.coerce(layoutIn, layoutOut, basePlotLayoutAttributes2, "plot_bgcolor"); - } - var bgColor = Color2.combine(plotBgColor, layoutOut.paper_bgcolor); - var axName; - var axId; - var axLetter; - var axLayoutIn; - var axLayoutOut; - function newAxLayoutOut() { - var traces = ax2traces[axName] || []; - axLayoutOut._traceIndices = traces.map(function(t) { - return t._expandedIndex; - }); - axLayoutOut._annIndices = []; - axLayoutOut._shapeIndices = []; - axLayoutOut._selectionIndices = []; - axLayoutOut._imgIndices = []; - axLayoutOut._subplotsWith = []; - axLayoutOut._counterAxes = []; - axLayoutOut._name = axLayoutOut._attr = axName; - axLayoutOut._id = axId; - } - function coerce2(attr, dflt) { - return Lib2.coerce(axLayoutIn, axLayoutOut, layoutAttributes2, attr, dflt); - } - function coerce22(attr, dflt) { - return Lib2.coerce2(axLayoutIn, axLayoutOut, layoutAttributes2, attr, dflt); - } - function getCounterAxes(axLetter2) { - return axLetter2 === "x" ? yIds : xIds; - } - function getOverlayableAxes(axLetter2, axName2) { - var list = axLetter2 === "x" ? xNames : yNames; - var out = []; - for (var j2 = 0; j2 < list.length; j2++) { - var axName22 = list[j2]; - if (axName22 !== axName2 && !(layoutIn[axName22] || {}).overlaying) { - out.push(name2id(axName22)); - } - } - return out; - } - var counterAxes = { x: getCounterAxes("x"), y: getCounterAxes("y") }; - var allAxisIds = counterAxes.x.concat(counterAxes.y); - var missingMatchedAxisIdsLookup = {}; - var missingMatchedAxisIds = []; - function addMissingMatchedAxis() { - var matchesIn = axLayoutIn.matches; - if (AX_ID_PATTERN.test(matchesIn) && allAxisIds.indexOf(matchesIn) === -1) { - missingMatchedAxisIdsLookup[matchesIn] = axLayoutIn.type; - missingMatchedAxisIds = Object.keys(missingMatchedAxisIdsLookup); - } - } - var hovermode = handleHoverModeDefaults3(layoutIn, layoutOut); - var unifiedHover = isUnifiedHover2(hovermode); - for (i = 0; i < axNames.length; i++) { - axName = axNames[i]; - axId = name2id(axName); - axLetter = axName.charAt(0); - if (!Lib2.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - axLayoutIn = layoutIn[axName]; - axLayoutOut = Template2.newContainer(layoutOut, axName, axLetter + "axis"); - newAxLayoutOut(); - var visibleDflt = axLetter === "x" && !xaMustDisplay[axName] && xaMayHide[axName] || axLetter === "y" && !yaMustDisplay[axName] && yaMayHide[axName]; - var reverseDflt = axLetter === "y" && (!yaMustNotReverse[axName] && yaMayReverse[axName] || axHasImage[axName]); - var defaultOptions = { - hasMinor: true, - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: ax2traces[axName] || [], - bgColor, - calendar: layoutOut.calendar, - automargin: true, - visibleDflt, - reverseDflt, - autotypenumbersDflt, - splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId], - noAutotickangles: axLetter === "y" - }; - coerce2("uirevision", layoutOut.uirevision); - handleTypeDefaults(axLayoutIn, axLayoutOut, coerce2, defaultOptions); - handleAxisDefaults3(axLayoutIn, axLayoutOut, coerce2, defaultOptions, layoutOut); - var unifiedSpike = unifiedHover && axLetter === hovermode.charAt(0); - var spikecolor = coerce22("spikecolor", unifiedHover ? axLayoutOut.color : void 0); - var spikethickness = coerce22("spikethickness", unifiedHover ? 1.5 : void 0); - var spikedash = coerce22("spikedash", unifiedHover ? "dot" : void 0); - var spikemode = coerce22("spikemode", unifiedHover ? "across" : void 0); - var spikesnap = coerce22("spikesnap"); - var showSpikes = coerce2("showspikes", !!unifiedSpike || !!spikecolor || !!spikethickness || !!spikedash || !!spikemode || !!spikesnap); - if (!showSpikes) { - delete axLayoutOut.spikecolor; - delete axLayoutOut.spikethickness; - delete axLayoutOut.spikedash; - delete axLayoutOut.spikemode; - delete axLayoutOut.spikesnap; - } - var overlayingAxis = id2name2(axLayoutIn.overlaying); - var overlayingAnchorDomain = [0, 1]; - if (layoutOut[overlayingAxis] !== void 0) { - var overlayingAnchor = id2name2(layoutOut[overlayingAxis].anchor); - if (layoutOut[overlayingAnchor] !== void 0) { - overlayingAnchorDomain = layoutOut[overlayingAnchor].domain; - } - } - handlePositionDefaults2(axLayoutIn, axLayoutOut, coerce2, { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: getOverlayableAxes(axLetter, axName), - grid: layoutOut.grid, - overlayingDomain: overlayingAnchorDomain - }); - coerce2("title.standoff"); - addMissingMatchedAxis(); - axLayoutOut._input = axLayoutIn; - } - i = 0; - while (i < missingMatchedAxisIds.length) { - axId = missingMatchedAxisIds[i++]; - axName = id2name2(axId); - axLetter = axName.charAt(0); - if (!Lib2.isPlainObject(layoutIn[axName])) { - layoutIn[axName] = {}; - } - axLayoutIn = layoutIn[axName]; - axLayoutOut = Template2.newContainer(layoutOut, axName, axLetter + "axis"); - newAxLayoutOut(); - var defaultOptions2 = { - letter: axLetter, - font: layoutOut.font, - outerTicks: outerTicks[axName], - showGrid: !noGrids[axName], - data: [], - bgColor, - calendar: layoutOut.calendar, - automargin: true, - visibleDflt: false, - reverseDflt: false, - autotypenumbersDflt, - splomStash: ((layoutOut._splomAxes || {})[axLetter] || {})[axId] - }; - coerce2("uirevision", layoutOut.uirevision); - axLayoutOut.type = missingMatchedAxisIdsLookup[axId] || "linear"; - handleAxisDefaults3(axLayoutIn, axLayoutOut, coerce2, defaultOptions2, layoutOut); - handlePositionDefaults2(axLayoutIn, axLayoutOut, coerce2, { - letter: axLetter, - counterAxes: counterAxes[axLetter], - overlayableAxes: getOverlayableAxes(axLetter, axName), - grid: layoutOut.grid - }); - coerce2("fixedrange"); - addMissingMatchedAxis(); - axLayoutOut._input = axLayoutIn; - } - var rangeSliderDefaults = getComponentMethod("rangeslider", "handleDefaults"); - var rangeSelectorDefaults = getComponentMethod("rangeselector", "handleDefaults"); - for (i = 0; i < xNames.length; i++) { - axName = xNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - rangeSliderDefaults(layoutIn, layoutOut, axName); - if (axLayoutOut.type === "date") { - rangeSelectorDefaults( - axLayoutIn, - axLayoutOut, - layoutOut, - yNames, - axLayoutOut.calendar - ); - } - coerce2("fixedrange"); - } - for (i = 0; i < yNames.length; i++) { - axName = yNames[i]; - axLayoutIn = layoutIn[axName]; - axLayoutOut = layoutOut[axName]; - var anchoredAxis = layoutOut[id2name2(axLayoutOut.anchor)]; - var fixedRangeDflt = getComponentMethod("rangeslider", "isVisible")(anchoredAxis); - coerce2("fixedrange", fixedRangeDflt); - } - constraints$1.handleDefaults(layoutIn, layoutOut, { - axIds: allAxisIds.concat(missingMatchedAxisIds).sort(axisIds2.idSort), - axHasImage - }); - }; - return layout_defaults$3; -} -var transition_axes; -var hasRequiredTransition_axes; -function requireTransition_axes() { - if (hasRequiredTransition_axes) return transition_axes; - hasRequiredTransition_axes = 1; - var d32 = d3Exports; - var Registry2 = registry; - var Lib2 = libExports; - var Drawing2 = drawingExports; - var Axes2 = axesExports; - transition_axes = function transitionAxes(gd, edits, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - if (edits.length === 0) { - Axes2.redrawComponents(gd); - return; - } - function unsetSubplotTransform(subplot) { - var xa = subplot.xaxis; - var ya = subplot.yaxis; - fullLayout._defs.select("#" + subplot.clipId + "> rect").call(Drawing2.setTranslate, 0, 0).call(Drawing2.setScale, 1, 1); - subplot.plot.call(Drawing2.setTranslate, xa._offset, ya._offset).call(Drawing2.setScale, 1, 1); - var traceGroups = subplot.plot.selectAll(".scatterlayer .trace"); - traceGroups.selectAll(".point").call(Drawing2.setPointGroupScale, 1, 1); - traceGroups.selectAll(".textpoint").call(Drawing2.setTextPointsScale, 1, 1); - traceGroups.call(Drawing2.hideOutsideRangePoints, subplot); - } - function updateSubplot(edit, progress) { - var plotinfo = edit.plotinfo; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var xlen = xa._length; - var ylen = ya._length; - var editX = !!edit.xr1; - var editY = !!edit.yr1; - var viewBox = []; - if (editX) { - var xr0 = Lib2.simpleMap(edit.xr0, xa.r2l); - var xr1 = Lib2.simpleMap(edit.xr1, xa.r2l); - var dx0 = xr0[1] - xr0[0]; - var dx1 = xr1[1] - xr1[0]; - viewBox[0] = (xr0[0] * (1 - progress) + progress * xr1[0] - xr0[0]) / (xr0[1] - xr0[0]) * xlen; - viewBox[2] = xlen * (1 - progress + progress * dx1 / dx0); - xa.range[0] = xa.l2r(xr0[0] * (1 - progress) + progress * xr1[0]); - xa.range[1] = xa.l2r(xr0[1] * (1 - progress) + progress * xr1[1]); - } else { - viewBox[0] = 0; - viewBox[2] = xlen; - } - if (editY) { - var yr0 = Lib2.simpleMap(edit.yr0, ya.r2l); - var yr1 = Lib2.simpleMap(edit.yr1, ya.r2l); - var dy0 = yr0[1] - yr0[0]; - var dy1 = yr1[1] - yr1[0]; - viewBox[1] = (yr0[1] * (1 - progress) + progress * yr1[1] - yr0[1]) / (yr0[0] - yr0[1]) * ylen; - viewBox[3] = ylen * (1 - progress + progress * dy1 / dy0); - ya.range[0] = xa.l2r(yr0[0] * (1 - progress) + progress * yr1[0]); - ya.range[1] = ya.l2r(yr0[1] * (1 - progress) + progress * yr1[1]); - } else { - viewBox[1] = 0; - viewBox[3] = ylen; - } - Axes2.drawOne(gd, xa, { skipTitle: true }); - Axes2.drawOne(gd, ya, { skipTitle: true }); - Axes2.redrawComponents(gd, [xa._id, ya._id]); - var xScaleFactor = editX ? xlen / viewBox[2] : 1; - var yScaleFactor = editY ? ylen / viewBox[3] : 1; - var clipDx = editX ? viewBox[0] : 0; - var clipDy = editY ? viewBox[1] : 0; - var fracDx = editX ? viewBox[0] / viewBox[2] * xlen : 0; - var fracDy = editY ? viewBox[1] / viewBox[3] * ylen : 0; - var plotDx = xa._offset - fracDx; - var plotDy = ya._offset - fracDy; - plotinfo.clipRect.call(Drawing2.setTranslate, clipDx, clipDy).call(Drawing2.setScale, 1 / xScaleFactor, 1 / yScaleFactor); - plotinfo.plot.call(Drawing2.setTranslate, plotDx, plotDy).call(Drawing2.setScale, xScaleFactor, yScaleFactor); - Drawing2.setPointGroupScale(plotinfo.zoomScalePts, 1 / xScaleFactor, 1 / yScaleFactor); - Drawing2.setTextPointsScale(plotinfo.zoomScaleTxt, 1 / xScaleFactor, 1 / yScaleFactor); - } - var onComplete; - if (makeOnCompleteCallback) { - onComplete = makeOnCompleteCallback(); - } - function transitionComplete() { - var aobj = {}; - for (var i = 0; i < edits.length; i++) { - var edit = edits[i]; - var xa = edit.plotinfo.xaxis; - var ya = edit.plotinfo.yaxis; - if (edit.xr1) aobj[xa._name + ".range"] = edit.xr1.slice(); - if (edit.yr1) aobj[ya._name + ".range"] = edit.yr1.slice(); - } - onComplete && onComplete(); - return Registry2.call("relayout", gd, aobj).then(function() { - for (var i2 = 0; i2 < edits.length; i2++) { - unsetSubplotTransform(edits[i2].plotinfo); - } - }); - } - function transitionInterrupt() { - var aobj = {}; - for (var i = 0; i < edits.length; i++) { - var edit = edits[i]; - var xa = edit.plotinfo.xaxis; - var ya = edit.plotinfo.yaxis; - if (edit.xr0) aobj[xa._name + ".range"] = edit.xr0.slice(); - if (edit.yr0) aobj[ya._name + ".range"] = edit.yr0.slice(); - } - return Registry2.call("relayout", gd, aobj).then(function() { - for (var i2 = 0; i2 < edits.length; i2++) { - unsetSubplotTransform(edits[i2].plotinfo); - } - }); - } - var t12, t22, raf; - var easeFn = d32.ease(transitionOpts.easing); - gd._transitionData._interruptCallbacks.push(function() { - window.cancelAnimationFrame(raf); - raf = null; - return transitionInterrupt(); - }); - function doFrame() { - t22 = Date.now(); - var tInterp = Math.min(1, (t22 - t12) / transitionOpts.duration); - var progress = easeFn(tInterp); - for (var i = 0; i < edits.length; i++) { - updateSubplot(edits[i], progress); - } - if (t22 - t12 > transitionOpts.duration) { - transitionComplete(); - raf = window.cancelAnimationFrame(doFrame); - } else { - raf = window.requestAnimationFrame(doFrame); - } - } - t12 = Date.now(); - raf = window.requestAnimationFrame(doFrame); - return Promise.resolve(); - }; - return transition_axes; -} -var d3$l = d3Exports; -var Registry$j = registry; -var Lib$W = libExports; -var Plots$6 = plotsExports; -var Drawing$f = drawingExports; -var getModuleCalcData = get_data.getModuleCalcData; -var axisIds$3 = axis_ids; -var constants$w = constants$U; -var xmlnsNamespaces$1 = xmlns_namespaces; -var ensureSingle = Lib$W.ensureSingle; -function ensureSingleAndAddDatum(parent, nodeType, className) { - return Lib$W.ensureSingle(parent, nodeType, className, function(s) { - s.datum(className); - }); -} -var zindexSeparator = constants$w.zindexSeparator; -cartesian.name = "cartesian"; -cartesian.attr = ["xaxis", "yaxis"]; -cartesian.idRoot = ["x", "y"]; -cartesian.idRegex = constants$w.idRegex; -cartesian.attrRegex = constants$w.attrRegex; -cartesian.attributes = requireAttributes(); -cartesian.layoutAttributes = layout_attributes$4; -cartesian.supplyLayoutDefaults = requireLayout_defaults(); -cartesian.transitionAxes = requireTransition_axes(); -cartesian.finalizeSubplots = function(layoutIn, layoutOut) { - var subplots = layoutOut._subplots; - var xList = subplots.xaxis; - var yList = subplots.yaxis; - var spSVG = subplots.cartesian; - var spAll = spSVG.concat(subplots.gl2d || []); - var allX = {}; - var allY = {}; - var i, xi, yi; - for (i = 0; i < spAll.length; i++) { - var parts = spAll[i].split("y"); - allX[parts[0]] = 1; - allY["y" + parts[1]] = 1; - } - for (i = 0; i < xList.length; i++) { - xi = xList[i]; - if (!allX[xi]) { - yi = (layoutIn[axisIds$3.id2name(xi)] || {}).anchor; - if (!constants$w.idRegex.y.test(yi)) yi = "y"; - spSVG.push(xi + yi); - spAll.push(xi + yi); - if (!allY[yi]) { - allY[yi] = 1; - Lib$W.pushUnique(yList, yi); - } - } - } - for (i = 0; i < yList.length; i++) { - yi = yList[i]; - if (!allY[yi]) { - xi = (layoutIn[axisIds$3.id2name(yi)] || {}).anchor; - if (!constants$w.idRegex.x.test(xi)) xi = "x"; - spSVG.push(xi + yi); - spAll.push(xi + yi); - if (!allX[xi]) { - allX[xi] = 1; - Lib$W.pushUnique(xList, xi); - } - } - } - if (!spAll.length) { - xi = ""; - yi = ""; - for (var ki in layoutIn) { - if (constants$w.attrRegex.test(ki)) { - var axLetter = ki.charAt(0); - if (axLetter === "x") { - if (!xi || +ki.substr(5) < +xi.substr(5)) { - xi = ki; - } - } else if (!yi || +ki.substr(5) < +yi.substr(5)) { - yi = ki; - } - } - } - xi = xi ? axisIds$3.name2id(xi) : "x"; - yi = yi ? axisIds$3.name2id(yi) : "y"; - xList.push(xi); - yList.push(yi); - spSVG.push(xi + yi); - } -}; -cartesian.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var subplots = fullLayout._subplots.cartesian; - var calcdata = gd.calcdata; - var i; - if (!Array.isArray(traces)) { - traces = []; - for (i = 0; i < calcdata.length; i++) traces.push(i); - } - var zindices = fullLayout._zindices; - for (var z = 0; z < zindices.length; z++) { - var zorder = zindices[z]; - for (i = 0; i < subplots.length; i++) { - var subplot = subplots[i]; - var subplotInfo = fullLayout._plots[subplot]; - if (z > 0) { - var idWithZ = subplotInfo.id; - if (idWithZ.indexOf(zindexSeparator) !== -1) continue; - idWithZ += zindexSeparator + (z + 1); - subplotInfo = Lib$W.extendFlat({}, subplotInfo, { - id: idWithZ, - plot: fullLayout._cartesianlayer.selectAll(".subplot").select("." + idWithZ) - }); - } - var cdSubplot = []; - var pcd; - for (var j = 0; j < calcdata.length; j++) { - var cd = calcdata[j]; - var trace = cd[0].trace; - if (zorder !== (trace.zorder || 0)) continue; - if (trace.xaxis + trace.yaxis === subplot) { - if (traces.indexOf(trace.index) !== -1 || trace.carpet) { - if (pcd && pcd[0].trace.xaxis + pcd[0].trace.yaxis === subplot && ["tonextx", "tonexty", "tonext"].indexOf(trace.fill) !== -1 && cdSubplot.indexOf(pcd) === -1) { - cdSubplot.push(pcd); - } - cdSubplot.push(cd); - } - pcd = cd; - } - } - plotOne$1(gd, subplotInfo, cdSubplot, transitionOpts, makeOnCompleteCallback); - } - } -}; -function plotOne$1(gd, plotinfo, cdSubplot, transitionOpts, makeOnCompleteCallback) { - var traceLayerClasses = constants$w.traceLayerClasses; - var fullLayout = gd._fullLayout; - var zindices = fullLayout._zindices; - var modules2 = fullLayout._modules; - var _module, cdModuleAndOthers, cdModule; - var layerData = []; - var zoomScaleQueryParts = []; - for (var z = 0; z < zindices.length; z++) { - var zorder = zindices[z]; - for (var i = 0; i < modules2.length; i++) { - _module = modules2[i]; - var name2 = _module.name; - var categories = Registry$j.modules[name2].categories; - if (categories.svg) { - var classBaseName = _module.layerName || name2 + "layer"; - var className = classBaseName + (z ? Number(z) + 1 : ""); - var plotMethod = _module.plot; - cdModuleAndOthers = getModuleCalcData(cdSubplot, plotMethod, zorder); - cdModule = cdModuleAndOthers[0]; - cdSubplot = cdModuleAndOthers[1]; - if (cdModule.length) { - layerData.push({ - i: traceLayerClasses.indexOf(classBaseName), - zindex: z, - className, - plotMethod, - cdModule - }); - } - if (categories.zoomScale) { - zoomScaleQueryParts.push("." + className); - } - } - } - } - layerData.sort(function(a, b) { - return (a.zindex || 0) - (b.zindex || 0) || a.i - b.i; - }); - var layers = plotinfo.plot.selectAll("g.mlayer").data(layerData, function(d) { - return d.className; - }); - layers.enter().append("g").attr("class", function(d) { - return d.className; - }).classed("mlayer", true).classed("rangeplot", plotinfo.isRangePlot); - layers.exit().remove(); - layers.order(); - layers.each(function(d) { - var sel = d3$l.select(this); - var className2 = d.className; - d.plotMethod( - gd, - plotinfo, - d.cdModule, - sel, - transitionOpts, - makeOnCompleteCallback - ); - if (constants$w.clipOnAxisFalseQuery.indexOf("." + className2) === -1) { - Drawing$f.setClipUrl(sel, plotinfo.layerClipId, gd); - } - }); - if (fullLayout._has("scattergl")) { - _module = Registry$j.getModule("scattergl"); - cdModule = getModuleCalcData(cdSubplot, _module)[0]; - _module.plot(gd, plotinfo, cdModule); - } - if (!gd._context.staticPlot) { - if (plotinfo._hasClipOnAxisFalse) { - plotinfo.clipOnAxisFalseTraces = plotinfo.plot.selectAll(constants$w.clipOnAxisFalseQuery.join(",")).selectAll(".trace"); - } - if (zoomScaleQueryParts.length) { - var traces = plotinfo.plot.selectAll(zoomScaleQueryParts.join(",")).selectAll(".trace"); - plotinfo.zoomScalePts = traces.selectAll("path.point"); - plotinfo.zoomScaleTxt = traces.selectAll(".textpoint"); - } - } -} -cartesian.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - var oldPlots = oldFullLayout._plots || {}; - var newPlots = newFullLayout._plots || {}; - var oldSubplotList = oldFullLayout._subplots || {}; - var plotinfo; - var i, k; - if (oldFullLayout._hasOnlyLargeSploms && !newFullLayout._hasOnlyLargeSploms) { - for (k in oldPlots) { - plotinfo = oldPlots[k]; - if (plotinfo.plotgroup) plotinfo.plotgroup.remove(); - } - } - var hadGl = oldFullLayout._has && oldFullLayout._has("gl"); - var hasGl = newFullLayout._has && newFullLayout._has("gl"); - if (hadGl && !hasGl) { - for (k in oldPlots) { - plotinfo = oldPlots[k]; - if (plotinfo._scene) plotinfo._scene.destroy(); - } - } - if (oldSubplotList.xaxis && oldSubplotList.yaxis) { - var oldAxIDs = axisIds$3.listIds({ _fullLayout: oldFullLayout }); - for (i = 0; i < oldAxIDs.length; i++) { - var oldAxId = oldAxIDs[i]; - if (!newFullLayout[axisIds$3.id2name(oldAxId)]) { - oldFullLayout._infolayer.selectAll(".g-" + oldAxId + "title").remove(); - } - } - } - var hadCartesian = oldFullLayout._has && oldFullLayout._has("cartesian"); - var hasCartesian = newFullLayout._has && newFullLayout._has("cartesian"); - if (hadCartesian && !hasCartesian) { - purgeSubplotLayers(oldFullLayout._cartesianlayer.selectAll(".subplot"), oldFullLayout); - oldFullLayout._defs.selectAll(".axesclip").remove(); - delete oldFullLayout._axisConstraintGroups; - delete oldFullLayout._axisMatchGroups; - } else if (oldSubplotList.cartesian) { - for (i = 0; i < oldSubplotList.cartesian.length; i++) { - var oldSubplotId = oldSubplotList.cartesian[i]; - if (oldSubplotId.indexOf(zindexSeparator) !== -1) continue; - if (!newPlots[oldSubplotId]) { - var selector = "." + oldSubplotId + ",." + oldSubplotId + "-x,." + oldSubplotId + "-y"; - oldFullLayout._cartesianlayer.selectAll(selector).remove(); - removeSubplotExtras(oldSubplotId, oldFullLayout); - } - } - } -}; -cartesian.drawFramework = function(gd) { - var fullLayout = gd._fullLayout; - var calcdata = gd.calcdata; - var i; - var traceZorderGroups = {}; - for (i = 0; i < calcdata.length; i++) { - var cdi = calcdata[i][0]; - var trace = cdi.trace; - var zi = trace.zorder || 0; - if (!traceZorderGroups[zi]) traceZorderGroups[zi] = []; - traceZorderGroups[zi].push(cdi); - } - var zindices = Object.keys(traceZorderGroups).map(Number).sort(Lib$W.sorterAsc); - if (!zindices.length) zindices = [0]; - fullLayout._zindices = zindices; - var initialSubplotData = makeSubplotData(gd); - var len = initialSubplotData.length; - var subplotData = []; - for (i = 0; i < len; i++) { - subplotData[i] = initialSubplotData[i].slice(); - } - for (var z = 1; z < zindices.length; z++) { - var newSubplotData = []; - for (i = 0; i < len; i++) { - newSubplotData[i] = initialSubplotData[i].slice(); - newSubplotData[i][0] += zindexSeparator + (z + 1); - } - subplotData = subplotData.concat(newSubplotData); - } - var subplotLayers = fullLayout._cartesianlayer.selectAll(".subplot").data(subplotData, String); - subplotLayers.enter().append("g").attr("class", function(d) { - return "subplot " + d[0]; - }); - subplotLayers.order(); - subplotLayers.exit().call(purgeSubplotLayers, fullLayout); - subplotLayers.each(function(d) { - var id = d[0]; - var posZ = id.indexOf(zindexSeparator); - var hasZ = posZ !== -1; - var idWithoutZ = hasZ ? id.slice(0, posZ) : id; - var plotinfo = fullLayout._plots[id]; - if (!plotinfo) { - plotinfo = Lib$W.extendFlat({}, fullLayout._plots[idWithoutZ]); - if (plotinfo) { - plotinfo.id = id; - fullLayout._plots[id] = plotinfo; - fullLayout._subplots.cartesian.push(id); - } - } - if (plotinfo) { - plotinfo.plotgroup = d3$l.select(this); - makeSubplotLayer(gd, plotinfo); - if (!hasZ) { - plotinfo.draglayer = ensureSingle(fullLayout._draggers, "g", id); - } - } - }); -}; -cartesian.rangePlot = function(gd, plotinfo, cdSubplot) { - makeSubplotLayer(gd, plotinfo); - plotOne$1(gd, plotinfo, cdSubplot); - Plots$6.style(gd); -}; -function makeSubplotData(gd) { - var fullLayout = gd._fullLayout; - var numZ = fullLayout._zindices.length; - var ids = fullLayout._subplots.cartesian; - var len = ids.length; - var i, j, id, plotinfo, xa, ya; - var regulars = []; - var overlays = []; - for (i = 0; i < len; i++) { - id = ids[i]; - plotinfo = fullLayout._plots[id]; - xa = plotinfo.xaxis; - ya = plotinfo.yaxis; - var xa2 = xa._mainAxis; - var ya2 = ya._mainAxis; - var mainplot = xa2._id + ya2._id; - var mainplotinfo = fullLayout._plots[mainplot]; - plotinfo.overlays = []; - if (mainplot !== id && mainplotinfo) { - plotinfo.mainplot = mainplot; - plotinfo.mainplotinfo = mainplotinfo; - overlays.push(id); - } else { - plotinfo.mainplot = void 0; - plotinfo.mainplotinfo = void 0; - regulars.push(id); - } - } - for (i = 0; i < overlays.length; i++) { - id = overlays[i]; - plotinfo = fullLayout._plots[id]; - plotinfo.mainplotinfo.overlays.push(plotinfo); - } - var subplotIds = regulars.concat(overlays); - var subplotData = []; - for (i = 0; i < len; i++) { - id = subplotIds[i]; - plotinfo = fullLayout._plots[id]; - xa = plotinfo.xaxis; - ya = plotinfo.yaxis; - var d = []; - for (var z = 1; z <= numZ; z++) { - var zStr = ""; - if (z > 1) zStr += zindexSeparator + z; - d.push(id + zStr); - for (j = 0; j < plotinfo.overlays.length; j++) { - d.push(plotinfo.overlays[j].id + zStr); - } - } - d = d.concat([ - xa.layer, - ya.layer, - xa.overlaying || "", - ya.overlaying || "" - ]); - subplotData.push(d); - } - return subplotData; -} -function makeSubplotLayer(gd, plotinfo) { - var fullLayout = gd._fullLayout; - var plotgroup = plotinfo.plotgroup; - var id = plotinfo.id; - var posZ = id.indexOf(zindexSeparator); - var hasZ = posZ !== -1; - var xLayer = constants$w.layerValue2layerClass[plotinfo.xaxis.layer]; - var yLayer = constants$w.layerValue2layerClass[plotinfo.yaxis.layer]; - var hasOnlyLargeSploms = fullLayout._hasOnlyLargeSploms; - if (!plotinfo.mainplot || fullLayout._zindices.length > 1) { - if (hasOnlyLargeSploms) { - plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above"); - plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above"); - plotinfo.xaxislayer = ensureSingle(plotgroup, "g", "xaxislayer-above"); - plotinfo.yaxislayer = ensureSingle(plotgroup, "g", "yaxislayer-above"); - } else { - if (!hasZ) { - var backLayer = ensureSingle(plotgroup, "g", "layer-subplot"); - plotinfo.shapelayer = ensureSingle(backLayer, "g", "shapelayer"); - plotinfo.imagelayer = ensureSingle(backLayer, "g", "imagelayer"); - plotinfo.minorGridlayer = ensureSingle(plotgroup, "g", "minor-gridlayer"); - plotinfo.gridlayer = ensureSingle(plotgroup, "g", "gridlayer"); - plotinfo.zerolinelayer = ensureSingle(plotgroup, "g", "zerolinelayer"); - var betweenLayer = ensureSingle(plotgroup, "g", "layer-between"); - plotinfo.shapelayerBetween = ensureSingle(betweenLayer, "g", "shapelayer"); - plotinfo.imagelayerBetween = ensureSingle(betweenLayer, "g", "imagelayer"); - ensureSingle(plotgroup, "path", "xlines-below"); - ensureSingle(plotgroup, "path", "ylines-below"); - plotinfo.overlinesBelow = ensureSingle(plotgroup, "g", "overlines-below"); - ensureSingle(plotgroup, "g", "xaxislayer-below"); - ensureSingle(plotgroup, "g", "yaxislayer-below"); - plotinfo.overaxesBelow = ensureSingle(plotgroup, "g", "overaxes-below"); - } - plotinfo.overplot = ensureSingle(plotgroup, "g", "overplot"); - plotinfo.plot = ensureSingle(plotinfo.overplot, "g", id); - if (!hasZ) { - plotinfo.xlines = ensureSingle(plotgroup, "path", "xlines-above"); - plotinfo.ylines = ensureSingle(plotgroup, "path", "ylines-above"); - plotinfo.overlinesAbove = ensureSingle(plotgroup, "g", "overlines-above"); - ensureSingle(plotgroup, "g", "xaxislayer-above"); - ensureSingle(plotgroup, "g", "yaxislayer-above"); - plotinfo.overaxesAbove = ensureSingle(plotgroup, "g", "overaxes-above"); - plotinfo.xlines = plotgroup.select(".xlines-" + xLayer); - plotinfo.ylines = plotgroup.select(".ylines-" + yLayer); - plotinfo.xaxislayer = plotgroup.select(".xaxislayer-" + xLayer); - plotinfo.yaxislayer = plotgroup.select(".yaxislayer-" + yLayer); - } - } - } else { - var mainplotinfo = plotinfo.mainplotinfo; - var mainplotgroup = mainplotinfo.plotgroup; - var xId = id + "-x"; - var yId = id + "-y"; - plotinfo.minorGridlayer = mainplotinfo.minorGridlayer; - plotinfo.gridlayer = mainplotinfo.gridlayer; - plotinfo.zerolinelayer = mainplotinfo.zerolinelayer; - ensureSingle(mainplotinfo.overlinesBelow, "path", xId); - ensureSingle(mainplotinfo.overlinesBelow, "path", yId); - ensureSingle(mainplotinfo.overaxesBelow, "g", xId); - ensureSingle(mainplotinfo.overaxesBelow, "g", yId); - plotinfo.plot = ensureSingle(mainplotinfo.overplot, "g", id); - ensureSingle(mainplotinfo.overlinesAbove, "path", xId); - ensureSingle(mainplotinfo.overlinesAbove, "path", yId); - ensureSingle(mainplotinfo.overaxesAbove, "g", xId); - ensureSingle(mainplotinfo.overaxesAbove, "g", yId); - plotinfo.xlines = mainplotgroup.select(".overlines-" + xLayer).select("." + xId); - plotinfo.ylines = mainplotgroup.select(".overlines-" + yLayer).select("." + yId); - plotinfo.xaxislayer = mainplotgroup.select(".overaxes-" + xLayer).select("." + xId); - plotinfo.yaxislayer = mainplotgroup.select(".overaxes-" + yLayer).select("." + yId); - } - if (!hasZ) { - if (!hasOnlyLargeSploms) { - ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.xaxis._id); - ensureSingleAndAddDatum(plotinfo.minorGridlayer, "g", plotinfo.yaxis._id); - plotinfo.minorGridlayer.selectAll("g").map(function(d) { - return d[0]; - }).sort(axisIds$3.idSort); - ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.xaxis._id); - ensureSingleAndAddDatum(plotinfo.gridlayer, "g", plotinfo.yaxis._id); - plotinfo.gridlayer.selectAll("g").map(function(d) { - return d[0]; - }).sort(axisIds$3.idSort); - } - plotinfo.xlines.style("fill", "none").classed("crisp", true); - plotinfo.ylines.style("fill", "none").classed("crisp", true); - } -} -function purgeSubplotLayers(layers, fullLayout) { - if (!layers) return; - var overlayIdsToRemove = {}; - layers.each(function(d) { - var id = d[0]; - var plotgroup = d3$l.select(this); - plotgroup.remove(); - removeSubplotExtras(id, fullLayout); - overlayIdsToRemove[id] = true; - }); - for (var k in fullLayout._plots) { - var subplotInfo = fullLayout._plots[k]; - var overlays = subplotInfo.overlays || []; - for (var j = 0; j < overlays.length; j++) { - var overlayInfo = overlays[j]; - if (overlayIdsToRemove[overlayInfo.id]) { - overlayInfo.plot.selectAll(".trace").remove(); - } - } - } -} -function removeSubplotExtras(subplotId, fullLayout) { - fullLayout._draggers.selectAll("g." + subplotId).remove(); - fullLayout._defs.select("#clip" + fullLayout._uid + subplotId + "plot").remove(); -} -cartesian.toSVG = function(gd) { - var imageRoot = gd._fullLayout._glimages; - var root = d3$l.select(gd).selectAll(".svg-container"); - var canvases = root.filter(function(d, i) { - return i === root.size() - 1; - }).selectAll(".gl-canvas-context, .gl-canvas-focus"); - function canvasToImage() { - var canvas2 = this; - var imageData = canvas2.toDataURL("image/png"); - var image = imageRoot.append("svg:image"); - image.attr({ - xmlns: xmlnsNamespaces$1.svg, - "xlink:href": imageData, - preserveAspectRatio: "none", - x: 0, - y: 0, - width: canvas2.style.width, - height: canvas2.style.height - }); - } - canvases.each(canvasToImage); -}; -cartesian.updateFx = requireGraph_interact().updateFx; -var subtypes = subtypes$3; -var scatter$1 = { - hasLines: subtypes.hasLines, - hasMarkers: subtypes.hasMarkers, - hasText: subtypes.hasText, - isBubble: subtypes.isBubble, - attributes: attributes$A, - layoutAttributes: layout_attributes$5, - supplyDefaults: defaults$h, - crossTraceDefaults: cross_trace_defaults$1, - supplyLayoutDefaults: layout_defaults$4, - calc: calc_1$3.calc, - crossTraceCalc: cross_trace_calc, - arraysToCalcdata: arrays_to_calcdata$1, - plot: plot$7, - colorbar: marker_colorbar, - formatLabels: format_labels$1, - style: style_1$3.style, - styleOnSelect: style_1$3.styleOnSelect, - hoverPoints: hover$5, - selectPoints: select$3, - animatable: true, - moduleType: "trace", - name: "scatter", - basePlotModule: cartesian, - categories: [ - "cartesian", - "svg", - "symbols", - "errorBarsOK", - "showLegend", - "scatter-like", - "zoomScale" - ], - meta: { - description: [ - "The scatter trace type encompasses line charts, scatter charts, text charts, and bubble charts.", - "The data visualized as scatter point or lines is set in `x` and `y`.", - "Text (appearing either on the chart or on hover only) is via `text`.", - "Bubble charts are achieved by setting `marker.size` and/or `marker.color`", - "to numerical arrays." - ].join(" ") - } -}; -var d3$k = d3Exports; -var Color$q = colorExports; -var ARROWPATHS = arrow_paths; -var Lib$V = libExports; -var strScale$1 = Lib$V.strScale; -var strRotate = Lib$V.strRotate; -var strTranslate$5 = Lib$V.strTranslate; -var draw_arrow_head = function drawArrowHead(el3, ends, options) { - var el = el3.node(); - var headStyle = ARROWPATHS[options.arrowhead || 0]; - var startHeadStyle = ARROWPATHS[options.startarrowhead || 0]; - var scale2 = (options.arrowwidth || 1) * (options.arrowsize || 1); - var startScale = (options.arrowwidth || 1) * (options.startarrowsize || 1); - var doStart = ends.indexOf("start") >= 0; - var doEnd = ends.indexOf("end") >= 0; - var backOff = headStyle.backoff * scale2 + options.standoff; - var startBackOff = startHeadStyle.backoff * startScale + options.startstandoff; - var start, end, startRot, endRot; - if (el.nodeName === "line") { - start = { x: +el3.attr("x1"), y: +el3.attr("y1") }; - end = { x: +el3.attr("x2"), y: +el3.attr("y2") }; - var dx = start.x - end.x; - var dy = start.y - end.y; - startRot = Math.atan2(dy, dx); - endRot = startRot + Math.PI; - if (backOff && startBackOff) { - if (backOff + startBackOff > Math.sqrt(dx * dx + dy * dy)) { - hideLine(); - return; - } - } - if (backOff) { - if (backOff * backOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var backOffX = backOff * Math.cos(startRot); - var backOffY = backOff * Math.sin(startRot); - end.x += backOffX; - end.y += backOffY; - el3.attr({ x2: end.x, y2: end.y }); - } - if (startBackOff) { - if (startBackOff * startBackOff > dx * dx + dy * dy) { - hideLine(); - return; - } - var startBackOffX = startBackOff * Math.cos(startRot); - var startbackOffY = startBackOff * Math.sin(startRot); - start.x -= startBackOffX; - start.y -= startbackOffY; - el3.attr({ x1: start.x, y1: start.y }); - } - } else if (el.nodeName === "path") { - var pathlen = el.getTotalLength(); - var dashArray = ""; - if (pathlen < backOff + startBackOff) { - hideLine(); - return; - } - var start0 = el.getPointAtLength(0); - var dstart = el.getPointAtLength(0.1); - startRot = Math.atan2(start0.y - dstart.y, start0.x - dstart.x); - start = el.getPointAtLength(Math.min(startBackOff, pathlen)); - dashArray = "0px," + startBackOff + "px,"; - var end0 = el.getPointAtLength(pathlen); - var dend = el.getPointAtLength(pathlen - 0.1); - endRot = Math.atan2(end0.y - dend.y, end0.x - dend.x); - end = el.getPointAtLength(Math.max(0, pathlen - backOff)); - var shortening = dashArray ? startBackOff + backOff : backOff; - dashArray += pathlen - shortening + "px," + pathlen + "px"; - el3.style("stroke-dasharray", dashArray); - } - function hideLine() { - el3.style("stroke-dasharray", "0px,100px"); - } - function drawhead(arrowHeadStyle, p, rot, arrowScale) { - if (!arrowHeadStyle.path) return; - if (arrowHeadStyle.noRotate) rot = 0; - d3$k.select(el.parentNode).append("path").attr({ - class: el3.attr("class"), - d: arrowHeadStyle.path, - transform: strTranslate$5(p.x, p.y) + strRotate(rot * 180 / Math.PI) + strScale$1(arrowScale) - }).style({ - fill: Color$q.rgb(options.arrowcolor), - "stroke-width": 0 - }); - } - if (doStart) drawhead(startHeadStyle, start, startRot, startScale); - if (doEnd) drawhead(headStyle, end, endRot, scale2); -}; -var d3$j = d3Exports; -var Registry$i = registry; -var Plots$5 = plotsExports; -var Lib$U = libExports; -var strTranslate$4 = Lib$U.strTranslate; -var Axes$e = axesExports; -var Color$p = colorExports; -var Drawing$e = drawingExports; -var Fx$4 = fx$1; -var svgTextUtils$9 = svg_text_utils; -var setCursor$1 = setcursor; -var dragElement$1 = dragelementExports; -var arrayEditor$3 = plot_template.arrayEditor; -var drawArrowHead2 = draw_arrow_head; -var draw_1$1 = { - draw: draw$a, - drawOne, - drawRaw: drawRaw$1 -}; -function draw$a(gd) { - var fullLayout = gd._fullLayout; - fullLayout._infolayer.selectAll(".annotation").remove(); - for (var i = 0; i < fullLayout.annotations.length; i++) { - if (fullLayout.annotations[i].visible) { - drawOne(gd, i); - } - } - return Plots$5.previousPromises(gd); -} -function drawOne(gd, index2) { - var fullLayout = gd._fullLayout; - var options = fullLayout.annotations[index2] || {}; - var xa = Axes$e.getFromId(gd, options.xref); - var ya = Axes$e.getFromId(gd, options.yref); - if (xa) xa.setScale(); - if (ya) ya.setScale(); - drawRaw$1(gd, options, index2, false, xa, ya); -} -function shiftPosition(axa, dAx, axLetter, gs, options) { - var optAx = options[axLetter]; - var axRef = options[axLetter + "ref"]; - var vertical = axLetter.indexOf("y") !== -1; - var axDomainRef = Axes$e.getRefType(axRef) === "domain"; - var gsDim = vertical ? gs.h : gs.w; - if (axa) { - if (axDomainRef) { - return optAx + (vertical ? -dAx : dAx) / axa._length; - } else { - return axa.p2r(axa.r2p(optAx) + dAx); - } - } else { - return optAx + (vertical ? -dAx : dAx) / gsDim; - } -} -function drawRaw$1(gd, options, index2, subplotId, xa, ya) { - var fullLayout = gd._fullLayout; - var gs = gd._fullLayout._size; - var edits = gd._context.edits; - var className, containerStr; - if (subplotId) { - className = "annotation-" + subplotId; - containerStr = subplotId + ".annotations"; - } else { - className = "annotation"; - containerStr = "annotations"; - } - var editHelpers = arrayEditor$3(gd.layout, containerStr, options); - var modifyBase = editHelpers.modifyBase; - var modifyItem = editHelpers.modifyItem; - var getUpdateObj = editHelpers.getUpdateObj; - fullLayout._infolayer.selectAll("." + className + '[data-index="' + index2 + '"]').remove(); - var annClipID = "clip" + fullLayout._uid + "_ann" + index2; - if (!options._input || options.visible === false) { - d3$j.selectAll("#" + annClipID).remove(); - return; - } - var annPosPx = { x: {}, y: {} }; - var textangle = +options.textangle || 0; - var annGroup = fullLayout._infolayer.append("g").classed(className, true).attr("data-index", String(index2)).style("opacity", options.opacity); - var annTextGroup = annGroup.append("g").classed("annotation-text-g", true); - var editTextPosition = edits[options.showarrow ? "annotationTail" : "annotationPosition"]; - var textEvents = options.captureevents || edits.annotationText || editTextPosition; - function makeEventData2(initialEvent) { - var eventData5 = { - index: index2, - annotation: options._input, - fullAnnotation: options, - event: initialEvent - }; - if (subplotId) { - eventData5.subplotId = subplotId; - } - return eventData5; - } - var annTextGroupInner = annTextGroup.append("g").style("pointer-events", textEvents ? "all" : null).call(setCursor$1, "pointer").on("click", function() { - gd._dragging = false; - gd.emit("plotly_clickannotation", makeEventData2(d3$j.event)); - }); - if (options.hovertext) { - annTextGroupInner.on("mouseover", function() { - var hoverOptions = options.hoverlabel; - var hoverFont = hoverOptions.font; - var bBox = this.getBoundingClientRect(); - var bBoxRef = gd.getBoundingClientRect(); - Fx$4.loneHover({ - x0: bBox.left - bBoxRef.left, - x1: bBox.right - bBoxRef.left, - y: (bBox.top + bBox.bottom) / 2 - bBoxRef.top, - text: options.hovertext, - color: hoverOptions.bgcolor, - borderColor: hoverOptions.bordercolor, - fontFamily: hoverFont.family, - fontSize: hoverFont.size, - fontColor: hoverFont.color, - fontWeight: hoverFont.weight, - fontStyle: hoverFont.style, - fontVariant: hoverFont.variant, - fontShadow: hoverFont.fontShadow, - fontLineposition: hoverFont.fontLineposition, - fontTextcase: hoverFont.fontTextcase - }, { - container: fullLayout._hoverlayer.node(), - outerContainer: fullLayout._paper.node(), - gd - }); - }).on("mouseout", function() { - Fx$4.loneUnhover(fullLayout._hoverlayer.node()); - }); - } - var borderwidth = options.borderwidth; - var borderpad = options.borderpad; - var borderfull = borderwidth + borderpad; - var annTextBG = annTextGroupInner.append("rect").attr("class", "bg").style("stroke-width", borderwidth + "px").call(Color$p.stroke, options.bordercolor).call(Color$p.fill, options.bgcolor); - var isSizeConstrained = options.width || options.height; - var annTextClip = fullLayout._topclips.selectAll("#" + annClipID).data(isSizeConstrained ? [0] : []); - annTextClip.enter().append("clipPath").classed("annclip", true).attr("id", annClipID).append("rect"); - annTextClip.exit().remove(); - var font2 = options.font; - var text = fullLayout._meta ? Lib$U.templateString(options.text, fullLayout._meta) : options.text; - var annText = annTextGroupInner.append("text").classed("annotation-text", true).text(text); - function textLayout2(s) { - s.call(Drawing$e.font, font2).attr({ - "text-anchor": { - left: "start", - right: "end" - }[options.align] || "middle" - }); - svgTextUtils$9.convertToTspans(s, gd, drawGraphicalElements); - return s; - } - function drawGraphicalElements() { - var anchor3 = annText.selectAll("a"); - if (anchor3.size() === 1 && anchor3.text() === annText.text()) { - var wholeLink = annTextGroupInner.insert("a", ":first-child").attr({ - "xlink:xlink:href": anchor3.attr("xlink:href"), - "xlink:xlink:show": anchor3.attr("xlink:show") - }).style({ cursor: "pointer" }); - wholeLink.node().appendChild(annTextBG.node()); - } - var mathjaxGroup = annTextGroupInner.select(".annotation-text-math-group"); - var hasMathjax = !mathjaxGroup.empty(); - var anntextBB = Drawing$e.bBox( - (hasMathjax ? mathjaxGroup : annText).node() - ); - var textWidth = anntextBB.width; - var textHeight = anntextBB.height; - var annWidth = options.width || textWidth; - var annHeight = options.height || textHeight; - var outerWidth = Math.round(annWidth + 2 * borderfull); - var outerHeight = Math.round(annHeight + 2 * borderfull); - function shiftFraction(v, anchor2) { - if (anchor2 === "auto") { - if (v < 1 / 3) anchor2 = "left"; - else if (v > 2 / 3) anchor2 = "right"; - else anchor2 = "center"; - } - return { - center: 0, - middle: 0, - left: 0.5, - bottom: -0.5, - right: -0.5, - top: 0.5 - }[anchor2]; - } - var annotationIsOffscreen = false; - var letters = ["x", "y"]; - for (var i = 0; i < letters.length; i++) { - var axLetter = letters[i]; - var axRef = options[axLetter + "ref"] || axLetter; - var tailRef = options["a" + axLetter + "ref"]; - var ax = { x: xa, y: ya }[axLetter]; - var dimAngle = (textangle + (axLetter === "x" ? 0 : -90)) * Math.PI / 180; - var annSizeFromWidth = outerWidth * Math.cos(dimAngle); - var annSizeFromHeight = outerHeight * Math.sin(dimAngle); - var annSize = Math.abs(annSizeFromWidth) + Math.abs(annSizeFromHeight); - var anchor = options[axLetter + "anchor"]; - var overallShift = options[axLetter + "shift"] * (axLetter === "x" ? 1 : -1); - var posPx = annPosPx[axLetter]; - var basePx; - var textPadShift; - var alignPosition; - var autoAlignFraction; - var textShift; - var axRefType = Axes$e.getRefType(axRef); - if (ax && axRefType !== "domain") { - var posFraction = ax.r2fraction(options[axLetter]); - if (posFraction < 0 || posFraction > 1) { - if (tailRef === axRef) { - posFraction = ax.r2fraction(options["a" + axLetter]); - if (posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - } - } else { - annotationIsOffscreen = true; - } - } - basePx = ax._offset + ax.r2p(options[axLetter]); - autoAlignFraction = 0.5; - } else { - var axRefTypeEqDomain = axRefType === "domain"; - if (axLetter === "x") { - alignPosition = options[axLetter]; - basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.l + gs.w * alignPosition; - } else { - alignPosition = 1 - options[axLetter]; - basePx = axRefTypeEqDomain ? ax._offset + ax._length * alignPosition : basePx = gs.t + gs.h * alignPosition; - } - autoAlignFraction = options.showarrow ? 0.5 : alignPosition; - } - if (options.showarrow) { - posPx.head = basePx; - var arrowLength = options["a" + axLetter]; - textShift = annSizeFromWidth * shiftFraction(0.5, options.xanchor) - annSizeFromHeight * shiftFraction(0.5, options.yanchor); - if (tailRef === axRef) { - var tailRefType = Axes$e.getRefType(tailRef); - if (tailRefType === "domain") { - if (axLetter === "y") { - arrowLength = 1 - arrowLength; - } - posPx.tail = ax._offset + ax._length * arrowLength; - } else if (tailRefType === "paper") { - if (axLetter === "y") { - arrowLength = 1 - arrowLength; - posPx.tail = gs.t + gs.h * arrowLength; - } else { - posPx.tail = gs.l + gs.w * arrowLength; - } - } else { - posPx.tail = ax._offset + ax.r2p(arrowLength); - } - textPadShift = textShift; - } else { - posPx.tail = basePx + arrowLength; - textPadShift = textShift + arrowLength; - } - posPx.text = posPx.tail + textShift; - var maxPx = fullLayout[axLetter === "x" ? "width" : "height"]; - if (axRef === "paper") { - posPx.head = Lib$U.constrain(posPx.head, 1, maxPx - 1); - } - if (tailRef === "pixel") { - var shiftPlus = -Math.max(posPx.tail - 3, posPx.text); - var shiftMinus = Math.min(posPx.tail + 3, posPx.text) - maxPx; - if (shiftPlus > 0) { - posPx.tail += shiftPlus; - posPx.text += shiftPlus; - } else if (shiftMinus > 0) { - posPx.tail -= shiftMinus; - posPx.text -= shiftMinus; - } - } - posPx.tail += overallShift; - posPx.head += overallShift; - } else { - textShift = annSize * shiftFraction(autoAlignFraction, anchor); - textPadShift = textShift; - posPx.text = basePx + textShift; - } - posPx.text += overallShift; - textShift += overallShift; - textPadShift += overallShift; - options["_" + axLetter + "padplus"] = annSize / 2 + textPadShift; - options["_" + axLetter + "padminus"] = annSize / 2 - textPadShift; - options["_" + axLetter + "size"] = annSize; - options["_" + axLetter + "shift"] = textShift; - } - if (annotationIsOffscreen) { - annTextGroupInner.remove(); - return; - } - var xShift = 0; - var yShift = 0; - if (options.align !== "left") { - xShift = (annWidth - textWidth) * (options.align === "center" ? 0.5 : 1); - } - if (options.valign !== "top") { - yShift = (annHeight - textHeight) * (options.valign === "middle" ? 0.5 : 1); - } - if (hasMathjax) { - mathjaxGroup.select("svg").attr({ - x: borderfull + xShift - 1, - y: borderfull + yShift - }).call(Drawing$e.setClipUrl, isSizeConstrained ? annClipID : null, gd); - } else { - var texty = borderfull + yShift - anntextBB.top; - var textx = borderfull + xShift - anntextBB.left; - annText.call(svgTextUtils$9.positionText, textx, texty).call(Drawing$e.setClipUrl, isSizeConstrained ? annClipID : null, gd); - } - annTextClip.select("rect").call( - Drawing$e.setRect, - borderfull, - borderfull, - annWidth, - annHeight - ); - annTextBG.call( - Drawing$e.setRect, - borderwidth / 2, - borderwidth / 2, - outerWidth - borderwidth, - outerHeight - borderwidth - ); - annTextGroupInner.call( - Drawing$e.setTranslate, - Math.round(annPosPx.x.text - outerWidth / 2), - Math.round(annPosPx.y.text - outerHeight / 2) - ); - annTextGroup.attr({ transform: "rotate(" + textangle + "," + annPosPx.x.text + "," + annPosPx.y.text + ")" }); - var drawArrow = function(dx, dy) { - annGroup.selectAll(".annotation-arrow-g").remove(); - var headX = annPosPx.x.head; - var headY = annPosPx.y.head; - var tailX = annPosPx.x.tail + dx; - var tailY = annPosPx.y.tail + dy; - var textX = annPosPx.x.text + dx; - var textY = annPosPx.y.text + dy; - var transform = Lib$U.rotationXYMatrix(textangle, textX, textY); - var applyTransform = Lib$U.apply2DTransform(transform); - var applyTransform2 = Lib$U.apply2DTransform2(transform); - var width = +annTextBG.attr("width"); - var height = +annTextBG.attr("height"); - var xLeft = textX - 0.5 * width; - var xRight = xLeft + width; - var yTop = textY - 0.5 * height; - var yBottom = yTop + height; - var edges = [ - [xLeft, yTop, xLeft, yBottom], - [xLeft, yBottom, xRight, yBottom], - [xRight, yBottom, xRight, yTop], - [xRight, yTop, xLeft, yTop] - ].map(applyTransform2); - if (edges.reduce(function(a, x) { - return a ^ !!Lib$U.segmentsIntersect( - headX, - headY, - headX + 1e6, - headY + 1e6, - x[0], - x[1], - x[2], - x[3] - ); - }, false)) { - return; - } - edges.forEach(function(x) { - var p = Lib$U.segmentsIntersect( - tailX, - tailY, - headX, - headY, - x[0], - x[1], - x[2], - x[3] - ); - if (p) { - tailX = p.x; - tailY = p.y; - } - }); - var strokewidth = options.arrowwidth; - var arrowColor = options.arrowcolor; - var arrowSide = options.arrowside; - var arrowGroup = annGroup.append("g").style({ opacity: Color$p.opacity(arrowColor) }).classed("annotation-arrow-g", true); - var arrow = arrowGroup.append("path").attr("d", "M" + tailX + "," + tailY + "L" + headX + "," + headY).style("stroke-width", strokewidth + "px").call(Color$p.stroke, Color$p.rgb(arrowColor)); - drawArrowHead2(arrow, arrowSide, options); - if (edits.annotationPosition && arrow.node().parentNode && !subplotId) { - var arrowDragHeadX = headX; - var arrowDragHeadY = headY; - if (options.standoff) { - var arrowLength2 = Math.sqrt(Math.pow(headX - tailX, 2) + Math.pow(headY - tailY, 2)); - arrowDragHeadX += options.standoff * (tailX - headX) / arrowLength2; - arrowDragHeadY += options.standoff * (tailY - headY) / arrowLength2; - } - var arrowDrag = arrowGroup.append("path").classed("annotation-arrow", true).classed("anndrag", true).classed("cursor-move", true).attr({ - d: "M3,3H-3V-3H3ZM0,0L" + (tailX - arrowDragHeadX) + "," + (tailY - arrowDragHeadY), - transform: strTranslate$4(arrowDragHeadX, arrowDragHeadY) - }).style("stroke-width", strokewidth + 6 + "px").call(Color$p.stroke, "rgba(0,0,0,0)").call(Color$p.fill, "rgba(0,0,0,0)"); - var annx0, anny0; - dragElement$1.init({ - element: arrowDrag.node(), - gd, - prepFn: function() { - var pos = Drawing$e.getTranslate(annTextGroupInner); - annx0 = pos.x; - anny0 = pos.y; - if (xa && xa.autorange) { - modifyBase(xa._name + ".autorange", true); - } - if (ya && ya.autorange) { - modifyBase(ya._name + ".autorange", true); - } - }, - moveFn: function(dx2, dy2) { - var annxy0 = applyTransform(annx0, anny0); - var xcenter = annxy0[0] + dx2; - var ycenter = annxy0[1] + dy2; - annTextGroupInner.call(Drawing$e.setTranslate, xcenter, ycenter); - modifyItem( - "x", - shiftPosition(xa, dx2, "x", gs, options) - ); - modifyItem( - "y", - shiftPosition(ya, dy2, "y", gs, options) - ); - if (options.axref === options.xref) { - modifyItem("ax", shiftPosition(xa, dx2, "ax", gs, options)); - } - if (options.ayref === options.yref) { - modifyItem("ay", shiftPosition(ya, dy2, "ay", gs, options)); - } - arrowGroup.attr("transform", strTranslate$4(dx2, dy2)); - annTextGroup.attr({ - transform: "rotate(" + textangle + "," + xcenter + "," + ycenter + ")" - }); - }, - doneFn: function() { - Registry$i.call("_guiRelayout", gd, getUpdateObj()); - var notesBox = document.querySelector(".js-notes-box-panel"); - if (notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } - }; - if (options.showarrow) drawArrow(0, 0); - if (editTextPosition) { - var baseTextTransform; - dragElement$1.init({ - element: annTextGroupInner.node(), - gd, - prepFn: function() { - baseTextTransform = annTextGroup.attr("transform"); - }, - moveFn: function(dx, dy) { - var csr = "pointer"; - if (options.showarrow) { - if (options.axref === options.xref) { - modifyItem("ax", shiftPosition(xa, dx, "ax", gs, options)); - } else { - modifyItem("ax", options.ax + dx); - } - if (options.ayref === options.yref) { - modifyItem("ay", shiftPosition(ya, dy, "ay", gs.w, options)); - } else { - modifyItem("ay", options.ay + dy); - } - drawArrow(dx, dy); - } else if (!subplotId) { - var xUpdate, yUpdate; - if (xa) { - xUpdate = shiftPosition(xa, dx, "x", gs, options); - } else { - var widthFraction = options._xsize / gs.w; - var xLeft = options.x + (options._xshift - options.xshift) / gs.w - widthFraction / 2; - xUpdate = dragElement$1.align( - xLeft + dx / gs.w, - widthFraction, - 0, - 1, - options.xanchor - ); - } - if (ya) { - yUpdate = shiftPosition(ya, dy, "y", gs, options); - } else { - var heightFraction = options._ysize / gs.h; - var yBottom = options.y - (options._yshift + options.yshift) / gs.h - heightFraction / 2; - yUpdate = dragElement$1.align( - yBottom - dy / gs.h, - heightFraction, - 0, - 1, - options.yanchor - ); - } - modifyItem("x", xUpdate); - modifyItem("y", yUpdate); - if (!xa || !ya) { - csr = dragElement$1.getCursor( - xa ? 0.5 : xUpdate, - ya ? 0.5 : yUpdate, - options.xanchor, - options.yanchor - ); - } - } else return; - annTextGroup.attr({ - transform: strTranslate$4(dx, dy) + baseTextTransform - }); - setCursor$1(annTextGroupInner, csr); - }, - clickFn: function(_2, initialEvent) { - if (options.captureevents) { - gd.emit("plotly_clickannotation", makeEventData2(initialEvent)); - } - }, - doneFn: function() { - setCursor$1(annTextGroupInner); - Registry$i.call("_guiRelayout", gd, getUpdateObj()); - var notesBox = document.querySelector(".js-notes-box-panel"); - if (notesBox) notesBox.redraw(notesBox.selectedObj); - } - }); - } - } - if (edits.annotationText) { - annText.call(svgTextUtils$9.makeEditable, { delegate: annTextGroupInner, gd }).call(textLayout2).on("edit", function(_text) { - options.text = _text; - this.call(textLayout2); - modifyItem("text", _text); - if (xa && xa.autorange) { - modifyBase(xa._name + ".autorange", true); - } - if (ya && ya.autorange) { - modifyBase(ya._name + ".autorange", true); - } - Registry$i.call("_guiRelayout", gd, getUpdateObj()); - }); - } else annText.call(textLayout2); -} -var Lib$T = libExports; -var Registry$h = registry; -var arrayEditor$2 = plot_template.arrayEditor; -var click2 = { - hasClickToShow, - onClick -}; -function hasClickToShow(gd, hoverData) { - var sets = getToggleSets(gd, hoverData); - return sets.on.length > 0 || sets.explicitOff.length > 0; -} -function onClick(gd, hoverData) { - var toggleSets = getToggleSets(gd, hoverData); - var onSet = toggleSets.on; - var offSet = toggleSets.off.concat(toggleSets.explicitOff); - var update2 = {}; - var annotationsOut = gd._fullLayout.annotations; - var i, editHelpers; - if (!(onSet.length || offSet.length)) return; - for (i = 0; i < onSet.length; i++) { - editHelpers = arrayEditor$2(gd.layout, "annotations", annotationsOut[onSet[i]]); - editHelpers.modifyItem("visible", true); - Lib$T.extendFlat(update2, editHelpers.getUpdateObj()); - } - for (i = 0; i < offSet.length; i++) { - editHelpers = arrayEditor$2(gd.layout, "annotations", annotationsOut[offSet[i]]); - editHelpers.modifyItem("visible", false); - Lib$T.extendFlat(update2, editHelpers.getUpdateObj()); - } - return Registry$h.call("update", gd, {}, update2); -} -function getToggleSets(gd, hoverData) { - var annotations2 = gd._fullLayout.annotations; - var onSet = []; - var offSet = []; - var explicitOffSet = []; - var hoverLen = (hoverData || []).length; - var i, j, anni, showMode, pointj, xa, ya, toggleType; - for (i = 0; i < annotations2.length; i++) { - anni = annotations2[i]; - showMode = anni.clicktoshow; - if (showMode) { - for (j = 0; j < hoverLen; j++) { - pointj = hoverData[j]; - xa = pointj.xaxis; - ya = pointj.yaxis; - if (xa._id === anni.xref && ya._id === anni.yref && xa.d2r(pointj.x) === clickData2r(anni._xclick, xa) && ya.d2r(pointj.y) === clickData2r(anni._yclick, ya)) { - if (anni.visible) { - if (showMode === "onout") toggleType = offSet; - else toggleType = explicitOffSet; - } else { - toggleType = onSet; - } - toggleType.push(i); - break; - } - } - if (j === hoverLen) { - if (anni.visible && showMode === "onout") offSet.push(i); - } - } - } - return { on: onSet, off: offSet, explicitOff: explicitOffSet }; -} -function clickData2r(d, ax) { - return ax.type === "log" ? ax.l2r(d) : ax.d2r(d); -} -var Lib$S = libExports; -var Color$o = colorExports; -var common_defaults = function handleAnnotationCommonDefaults(annIn, annOut, fullLayout, coerce2) { - coerce2("opacity"); - var bgColor = coerce2("bgcolor"); - var borderColor = coerce2("bordercolor"); - var borderOpacity = Color$o.opacity(borderColor); - coerce2("borderpad"); - var borderWidth = coerce2("borderwidth"); - var showArrow = coerce2("showarrow"); - coerce2("text", showArrow ? " " : fullLayout._dfltTitle.annotation); - coerce2("textangle"); - Lib$S.coerceFont(coerce2, "font", fullLayout.font); - coerce2("width"); - coerce2("align"); - var h = coerce2("height"); - if (h) coerce2("valign"); - if (showArrow) { - var arrowside = coerce2("arrowside"); - var arrowhead; - var arrowsize; - if (arrowside.indexOf("end") !== -1) { - arrowhead = coerce2("arrowhead"); - arrowsize = coerce2("arrowsize"); - } - if (arrowside.indexOf("start") !== -1) { - coerce2("startarrowhead", arrowhead); - coerce2("startarrowsize", arrowsize); - } - coerce2("arrowcolor", borderOpacity ? annOut.bordercolor : Color$o.defaultLine); - coerce2("arrowwidth", (borderOpacity && borderWidth || 1) * 2); - coerce2("standoff"); - coerce2("startstandoff"); - } - var hoverText = coerce2("hovertext"); - var globalHoverLabel = fullLayout.hoverlabel || {}; - if (hoverText) { - var hoverBG = coerce2( - "hoverlabel.bgcolor", - globalHoverLabel.bgcolor || (Color$o.opacity(bgColor) ? Color$o.rgb(bgColor) : Color$o.defaultLine) - ); - var hoverBorder = coerce2( - "hoverlabel.bordercolor", - globalHoverLabel.bordercolor || Color$o.contrast(hoverBG) - ); - var fontDflt = Lib$S.extendFlat({}, globalHoverLabel.font); - if (!fontDflt.color) { - fontDflt.color = hoverBorder; - } - Lib$S.coerceFont(coerce2, "hoverlabel.font", fontDflt); - } - coerce2("captureevents", !!hoverText); -}; -var Lib$R = libExports; -var Axes$d = axesExports; -var handleArrayContainerDefaults$6 = array_container_defaults; -var handleAnnotationCommonDefaults$1 = common_defaults; -var attributes$u = attributes$B; -var defaults$g = function supplyLayoutDefaults5(layoutIn, layoutOut) { - handleArrayContainerDefaults$6(layoutIn, layoutOut, { - name: "annotations", - handleItemDefaults: handleAnnotationDefaults$1 - }); -}; -function handleAnnotationDefaults$1(annIn, annOut, fullLayout) { - function coerce2(attr, dflt) { - return Lib$R.coerce(annIn, annOut, attributes$u, attr, dflt); - } - var visible = coerce2("visible"); - var clickToShow = coerce2("clicktoshow"); - if (!(visible || clickToShow)) return; - handleAnnotationCommonDefaults$1(annIn, annOut, fullLayout, coerce2); - var showArrow = annOut.showarrow; - var axLetters2 = ["x", "y"]; - var arrowPosDflt = [-10, -30]; - var gdMock = { _fullLayout: fullLayout }; - for (var i = 0; i < 2; i++) { - var axLetter = axLetters2[i]; - var axRef = Axes$d.coerceRef(annIn, annOut, gdMock, axLetter, "", "paper"); - if (axRef !== "paper") { - var ax = Axes$d.getFromId(gdMock, axRef); - ax._annIndices.push(annOut._index); - } - Axes$d.coercePosition(annOut, gdMock, coerce2, axRef, axLetter, 0.5); - if (showArrow) { - var arrowPosAttr = "a" + axLetter; - var aaxRef = Axes$d.coerceRef( - annIn, - annOut, - gdMock, - arrowPosAttr, - "pixel", - ["pixel", "paper"] - ); - if (aaxRef !== "pixel" && aaxRef !== axRef) { - aaxRef = annOut[arrowPosAttr] = "pixel"; - } - var aDflt = aaxRef === "pixel" ? arrowPosDflt[i] : 0.4; - Axes$d.coercePosition(annOut, gdMock, coerce2, aaxRef, arrowPosAttr, aDflt); - } - coerce2(axLetter + "anchor"); - coerce2(axLetter + "shift"); - } - Lib$R.noneOrAll(annIn, annOut, ["x", "y"]); - if (showArrow) { - Lib$R.noneOrAll(annIn, annOut, ["ax", "ay"]); - } - if (clickToShow) { - var xClick = coerce2("xclick"); - var yClick = coerce2("yclick"); - annOut._xclick = xClick === void 0 ? annOut.x : Axes$d.cleanPosition(xClick, gdMock, annOut.xref); - annOut._yclick = yClick === void 0 ? annOut.y : Axes$d.cleanPosition(yClick, gdMock, annOut.yref); - } -} -var Lib$Q = libExports; -var Axes$c = axesExports; -var draw$9 = draw_1$1.draw; -var calc_autorange$2 = function calcAutorange(gd) { - var fullLayout = gd._fullLayout; - var annotationList = Lib$Q.filterVisible(fullLayout.annotations); - if (annotationList.length && gd._fullData.length) { - return Lib$Q.syncOrAsync([draw$9, annAutorange], gd); - } -}; -function annAutorange(gd) { - var fullLayout = gd._fullLayout; - Lib$Q.filterVisible(fullLayout.annotations).forEach(function(ann) { - var xa = Axes$c.getFromId(gd, ann.xref); - var ya = Axes$c.getFromId(gd, ann.yref); - var xRefType = Axes$c.getRefType(ann.xref); - var yRefType = Axes$c.getRefType(ann.yref); - ann._extremes = {}; - if (xRefType === "range") calcAxisExpansion$1(ann, xa); - if (yRefType === "range") calcAxisExpansion$1(ann, ya); - }); -} -function calcAxisExpansion$1(ann, ax) { - var axId = ax._id; - var letter = axId.charAt(0); - var pos = ann[letter]; - var apos = ann["a" + letter]; - var ref2 = ann[letter + "ref"]; - var aref = ann["a" + letter + "ref"]; - var padplus = ann["_" + letter + "padplus"]; - var padminus = ann["_" + letter + "padminus"]; - var shift = { x: 1, y: -1 }[letter] * ann[letter + "shift"]; - var headSize = 3 * ann.arrowsize * ann.arrowwidth || 0; - var headPlus = headSize + shift; - var headMinus = headSize - shift; - var startHeadSize = 3 * ann.startarrowsize * ann.arrowwidth || 0; - var startHeadPlus = startHeadSize + shift; - var startHeadMinus = startHeadSize - shift; - var extremes; - if (aref === ref2) { - var extremeArrowHead = Axes$c.findExtremes(ax, [ax.r2c(pos)], { - ppadplus: headPlus, - ppadminus: headMinus - }); - var extremeText = Axes$c.findExtremes(ax, [ax.r2c(apos)], { - ppadplus: Math.max(padplus, startHeadPlus), - ppadminus: Math.max(padminus, startHeadMinus) - }); - extremes = { - min: [extremeArrowHead.min[0], extremeText.min[0]], - max: [extremeArrowHead.max[0], extremeText.max[0]] - }; - } else { - startHeadPlus = apos ? startHeadPlus + apos : startHeadPlus; - startHeadMinus = apos ? startHeadMinus - apos : startHeadMinus; - extremes = Axes$c.findExtremes(ax, [ax.r2c(pos)], { - ppadplus: Math.max(padplus, headPlus, startHeadPlus), - ppadminus: Math.max(padminus, headMinus, startHeadMinus) - }); - } - ann._extremes[axId] = extremes; -} -var isNumeric$a = fastIsnumeric; -var toLogRange$1 = to_log_range; -var convert_coords$1 = function convertCoords(gd, ax, newType, doExtra) { - ax = ax || {}; - var toLog = newType === "log" && ax.type === "linear"; - var fromLog2 = newType === "linear" && ax.type === "log"; - if (!(toLog || fromLog2)) return; - var annotations2 = gd._fullLayout.annotations; - var axLetter = ax._id.charAt(0); - var ann; - var attrPrefix; - function convert3(attr) { - var currentVal = ann[attr]; - var newVal = null; - if (toLog) newVal = toLogRange$1(currentVal, ax.range); - else newVal = Math.pow(10, currentVal); - if (!isNumeric$a(newVal)) newVal = null; - doExtra(attrPrefix + attr, newVal); - } - for (var i = 0; i < annotations2.length; i++) { - ann = annotations2[i]; - attrPrefix = "annotations[" + i + "]."; - if (ann[axLetter + "ref"] === ax._id) convert3(axLetter); - if (ann["a" + axLetter + "ref"] === ax._id) convert3("a" + axLetter); - } -}; -var drawModule$1 = draw_1$1; -var clickModule = click2; -var annotations = { - moduleType: "component", - name: "annotations", - layoutAttributes: attributes$B, - supplyLayoutDefaults: defaults$g, - includeBasePlot: include_components("annotations"), - calcAutorange: calc_autorange$2, - draw: drawModule$1.draw, - drawOne: drawModule$1.drawOne, - drawRaw: drawModule$1.drawRaw, - hasClickToShow: clickModule.hasClickToShow, - onClick: clickModule.onClick, - convertCoords: convert_coords$1 -}; -var annAttrs$1 = attributes$B; -var overrideAll$4 = edit_types.overrideAll; -var templatedArray$5 = plot_template.templatedArray; -var attributes$t = overrideAll$4(templatedArray$5("annotation", { - visible: annAttrs$1.visible, - x: { - valType: "any", - description: [ - "Sets the annotation's x position." - ].join(" ") - }, - y: { - valType: "any", - description: [ - "Sets the annotation's y position." - ].join(" ") - }, - z: { - valType: "any", - description: [ - "Sets the annotation's z position." - ].join(" ") - }, - ax: { - valType: "number", - description: [ - "Sets the x component of the arrow tail about the arrow head (in pixels)." - ].join(" ") - }, - ay: { - valType: "number", - description: [ - "Sets the y component of the arrow tail about the arrow head (in pixels)." - ].join(" ") - }, - xanchor: annAttrs$1.xanchor, - xshift: annAttrs$1.xshift, - yanchor: annAttrs$1.yanchor, - yshift: annAttrs$1.yshift, - text: annAttrs$1.text, - textangle: annAttrs$1.textangle, - font: annAttrs$1.font, - width: annAttrs$1.width, - height: annAttrs$1.height, - opacity: annAttrs$1.opacity, - align: annAttrs$1.align, - valign: annAttrs$1.valign, - bgcolor: annAttrs$1.bgcolor, - bordercolor: annAttrs$1.bordercolor, - borderpad: annAttrs$1.borderpad, - borderwidth: annAttrs$1.borderwidth, - showarrow: annAttrs$1.showarrow, - arrowcolor: annAttrs$1.arrowcolor, - arrowhead: annAttrs$1.arrowhead, - startarrowhead: annAttrs$1.startarrowhead, - arrowside: annAttrs$1.arrowside, - arrowsize: annAttrs$1.arrowsize, - startarrowsize: annAttrs$1.startarrowsize, - arrowwidth: annAttrs$1.arrowwidth, - standoff: annAttrs$1.standoff, - startstandoff: annAttrs$1.startstandoff, - hovertext: annAttrs$1.hovertext, - hoverlabel: annAttrs$1.hoverlabel, - captureevents: annAttrs$1.captureevents - // maybes later? - // clicktoshow: annAttrs.clicktoshow, - // xclick: annAttrs.xclick, - // yclick: annAttrs.yclick, - // not needed! - // axref: 'pixel' - // ayref: 'pixel' - // xref: 'x' - // yref: 'y - // zref: 'z' -}), "calc", "from-root"); -var Lib$P = libExports; -var Axes$b = axesExports; -var handleArrayContainerDefaults$5 = array_container_defaults; -var handleAnnotationCommonDefaults2 = common_defaults; -var attributes$s = attributes$t; -var defaults$f = function handleDefaults(sceneLayoutIn, sceneLayoutOut, opts) { - handleArrayContainerDefaults$5(sceneLayoutIn, sceneLayoutOut, { - name: "annotations", - handleItemDefaults: handleAnnotationDefaults, - fullLayout: opts.fullLayout - }); -}; -function handleAnnotationDefaults(annIn, annOut, sceneLayout, opts) { - function coerce2(attr, dflt) { - return Lib$P.coerce(annIn, annOut, attributes$s, attr, dflt); - } - function coercePosition(axLetter) { - var axName = axLetter + "axis"; - var gdMock = { _fullLayout: {} }; - gdMock._fullLayout[axName] = sceneLayout[axName]; - return Axes$b.coercePosition(annOut, gdMock, coerce2, axLetter, axLetter, 0.5); - } - var visible = coerce2("visible"); - if (!visible) return; - handleAnnotationCommonDefaults2(annIn, annOut, opts.fullLayout, coerce2); - coercePosition("x"); - coercePosition("y"); - coercePosition("z"); - Lib$P.noneOrAll(annIn, annOut, ["x", "y", "z"]); - annOut.xref = "x"; - annOut.yref = "y"; - annOut.zref = "z"; - coerce2("xanchor"); - coerce2("yanchor"); - coerce2("xshift"); - coerce2("yshift"); - if (annOut.showarrow) { - annOut.axref = "pixel"; - annOut.ayref = "pixel"; - coerce2("ax", -10); - coerce2("ay", -30); - Lib$P.noneOrAll(annIn, annOut, ["ax", "ay"]); - } -} -var Lib$O = libExports; -var Axes$a = axesExports; -var convert$2 = function convert(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var anns = fullSceneLayout.annotations; - for (var i = 0; i < anns.length; i++) { - mockAnnAxes(anns[i], scene); - } - scene.fullLayout._infolayer.selectAll(".annotation-" + scene.id).remove(); -}; -function mockAnnAxes(ann, scene) { - var fullSceneLayout = scene.fullSceneLayout; - var domain2 = fullSceneLayout.domain; - var size = scene.fullLayout._size; - var base = { - // this gets fill in on render - pdata: null, - // to get setConvert to not execute cleanly - type: "linear", - // don't try to update them on `editable: true` - autorange: false, - // set infinite range so that annotation draw routine - // does not try to remove 'outside-range' annotations, - // this case is handled in the render loop - range: [-Infinity, Infinity] - }; - ann._xa = {}; - Lib$O.extendFlat(ann._xa, base); - Axes$a.setConvert(ann._xa); - ann._xa._offset = size.l + domain2.x[0] * size.w; - ann._xa.l2p = function() { - return 0.5 * (1 + ann._pdata[0] / ann._pdata[3]) * size.w * (domain2.x[1] - domain2.x[0]); - }; - ann._ya = {}; - Lib$O.extendFlat(ann._ya, base); - Axes$a.setConvert(ann._ya); - ann._ya._offset = size.t + (1 - domain2.y[1]) * size.h; - ann._ya.l2p = function() { - return 0.5 * (1 - ann._pdata[1] / ann._pdata[3]) * size.h * (domain2.y[1] - domain2.y[0]); - }; -} -function xformMatrix(m, v) { - var out = [0, 0, 0, 0]; - var i, j; - for (i = 0; i < 4; ++i) { - for (j = 0; j < 4; ++j) { - out[j] += m[4 * i + j] * v[i]; - } - } - return out; -} -function project$1(camera, v) { - var p = xformMatrix( - camera.projection, - xformMatrix( - camera.view, - xformMatrix(camera.model, [v[0], v[1], v[2], 1]) - ) - ); - return p; -} -var project_1 = project$1; -var drawRaw = draw_1$1.drawRaw; -var project = project_1; -var axLetters = ["x", "y", "z"]; -var draw$8 = function draw2(scene) { - var fullSceneLayout = scene.fullSceneLayout; - var dataScale = scene.dataScale; - var anns = fullSceneLayout.annotations; - for (var i = 0; i < anns.length; i++) { - var ann = anns[i]; - var annotationIsOffscreen = false; - for (var j = 0; j < 3; j++) { - var axLetter = axLetters[j]; - var pos = ann[axLetter]; - var ax = fullSceneLayout[axLetter + "axis"]; - var posFraction = ax.r2fraction(pos); - if (posFraction < 0 || posFraction > 1) { - annotationIsOffscreen = true; - break; - } - } - if (annotationIsOffscreen) { - scene.fullLayout._infolayer.select(".annotation-" + scene.id + '[data-index="' + i + '"]').remove(); - } else { - ann._pdata = project(scene.glplot.cameraParams, [ - fullSceneLayout.xaxis.r2l(ann.x) * dataScale[0], - fullSceneLayout.yaxis.r2l(ann.y) * dataScale[1], - fullSceneLayout.zaxis.r2l(ann.z) * dataScale[2] - ]); - drawRaw(scene.graphDiv, ann, i, scene.id, ann._xa, ann._ya); - } - } -}; -var Registry$g = registry; -var Lib$N = libExports; -var annotations3d = { - moduleType: "component", - name: "annotations3d", - schema: { - subplots: { - scene: { annotations: attributes$t } - } - }, - layoutAttributes: attributes$t, - handleDefaults: defaults$f, - includeBasePlot: includeGL3D, - convert: convert$2, - draw: draw$8 -}; -function includeGL3D(layoutIn, layoutOut) { - var GL3D = Registry$g.subplotsRegistry.gl3d; - if (!GL3D) return; - var attrRegex = GL3D.attrRegex; - var keys = Object.keys(layoutIn); - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - if (attrRegex.test(k) && (layoutIn[k].annotations || []).length) { - Lib$N.pushUnique(layoutOut._basePlotModules, GL3D); - Lib$N.pushUnique(layoutOut._subplots.gl3d, k); - } - } -} -var annAttrs = attributes$B; -var fontAttrs$7 = font_attributes; -var scatterLineAttrs$1 = attributes$A.line; -var dash$1 = attributes$M.dash; -var extendFlat$b = extend$5.extendFlat; -var templatedArray$4 = plot_template.templatedArray; -var axisPlaceableObjs$1 = axis_placeable_objects; -var basePlotAttributes = attributes$O; -var shapeTexttemplateAttrs = template_attributes.shapeTexttemplateAttrs; -var shapeLabelTexttemplateVars = label_texttemplate; -var attributes$r = templatedArray$4("shape", { - visible: extendFlat$b({}, basePlotAttributes.visible, { - editType: "calc+arraydraw", - description: [ - "Determines whether or not this shape is visible.", - "If *legendonly*, the shape is not drawn,", - "but can appear as a legend item", - "(provided that the legend itself is visible)." - ].join(" ") - }), - showlegend: { - valType: "boolean", - dflt: false, - editType: "calc+arraydraw", - description: [ - "Determines whether or not this", - "shape is shown in the legend." - ].join(" ") - }, - legend: extendFlat$b({}, basePlotAttributes.legend, { - editType: "calc+arraydraw", - description: [ - "Sets the reference to a legend to show this shape in.", - "References to these legends are *legend*, *legend2*, *legend3*, etc.", - "Settings for these legends are set in the layout, under", - "`layout.legend`, `layout.legend2`, etc." - ].join(" ") - }), - legendgroup: extendFlat$b({}, basePlotAttributes.legendgroup, { - editType: "calc+arraydraw", - description: [ - "Sets the legend group for this shape.", - "Traces and shapes part of the same legend group hide/show at the same time", - "when toggling legend items." - ].join(" ") - }), - legendgrouptitle: { - text: extendFlat$b({}, basePlotAttributes.legendgrouptitle.text, { - editType: "calc+arraydraw" - }), - font: fontAttrs$7({ - editType: "calc+arraydraw", - description: [ - "Sets this legend group's title font." - ].join(" ") - }), - editType: "calc+arraydraw" - }, - legendrank: extendFlat$b({}, basePlotAttributes.legendrank, { - editType: "calc+arraydraw", - description: [ - "Sets the legend rank for this shape.", - "Items and groups with smaller ranks are presented on top/left side while", - "with *reversed* `legend.traceorder` they are on bottom/right side.", - "The default legendrank is 1000,", - "so that you can use ranks less than 1000 to place certain items before all unranked items,", - "and ranks greater than 1000 to go after all unranked items.", - "When having unranked or equal rank items shapes would be displayed after traces", - "i.e. according to their order in data and layout." - ].join(" ") - }), - legendwidth: extendFlat$b({}, basePlotAttributes.legendwidth, { - editType: "calc+arraydraw", - description: "Sets the width (in px or fraction) of the legend for this shape." - }), - type: { - valType: "enumerated", - values: ["circle", "rect", "path", "line"], - editType: "calc+arraydraw", - description: [ - "Specifies the shape type to be drawn.", - "If *line*, a line is drawn from (`x0`,`y0`) to (`x1`,`y1`)", - "with respect to the axes' sizing mode.", - "If *circle*, a circle is drawn from", - "((`x0`+`x1`)/2, (`y0`+`y1`)/2))", - "with radius", - "(|(`x0`+`x1`)/2 - `x0`|, |(`y0`+`y1`)/2 -`y0`)|)", - "with respect to the axes' sizing mode.", - "If *rect*, a rectangle is drawn linking", - "(`x0`,`y0`), (`x1`,`y0`), (`x1`,`y1`), (`x0`,`y1`), (`x0`,`y0`)", - "with respect to the axes' sizing mode.", - "If *path*, draw a custom SVG path using `path`.", - "with respect to the axes' sizing mode." - ].join(" ") - }, - layer: { - valType: "enumerated", - values: ["below", "above", "between"], - dflt: "above", - editType: "arraydraw", - description: [ - "Specifies whether shapes are drawn below gridlines (*below*),", - "between gridlines and traces (*between*) or above traces (*above*)." - ].join(" ") - }, - xref: extendFlat$b({}, annAttrs.xref, { - description: [ - "Sets the shape's x coordinate axis.", - axisPlaceableObjs$1.axisRefDescription("x", "left", "right") - ].join(" ") - }), - xsizemode: { - valType: "enumerated", - values: ["scaled", "pixel"], - dflt: "scaled", - editType: "calc+arraydraw", - description: [ - "Sets the shapes's sizing mode along the x axis.", - "If set to *scaled*, `x0`, `x1` and x coordinates within `path` refer to", - "data values on the x axis or a fraction of the plot area's width", - "(`xref` set to *paper*).", - "If set to *pixel*, `xanchor` specifies the x position in terms", - "of data or plot fraction but `x0`, `x1` and x coordinates within `path`", - "are pixels relative to `xanchor`. This way, the shape can have", - "a fixed width while maintaining a position relative to data or", - "plot fraction." - ].join(" ") - }, - xanchor: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Only relevant in conjunction with `xsizemode` set to *pixel*.", - "Specifies the anchor point on the x axis to which `x0`, `x1`", - "and x coordinates within `path` are relative to.", - "E.g. useful to attach a pixel sized shape to a certain data value.", - "No effect when `xsizemode` not set to *pixel*." - ].join(" ") - }, - x0: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the shape's starting x position.", - "See `type` and `xsizemode` for more info." - ].join(" ") - }, - x1: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the shape's end x position.", - "See `type` and `xsizemode` for more info." - ].join(" ") - }, - x0shift: { - valType: "number", - dflt: 0, - min: -1, - max: 1, - editType: "calc", - description: [ - "Shifts `x0` away from the center of the category when `xref` is a *category* or", - "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", - "corresponds to the end of the category." - ].join(" ") - }, - x1shift: { - valType: "number", - dflt: 0, - min: -1, - max: 1, - editType: "calc", - description: [ - "Shifts `x1` away from the center of the category when `xref` is a *category* or", - "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", - "corresponds to the end of the category." - ].join(" ") - }, - yref: extendFlat$b({}, annAttrs.yref, { - description: [ - "Sets the shape's y coordinate axis.", - axisPlaceableObjs$1.axisRefDescription("y", "bottom", "top") - ].join(" ") - }), - ysizemode: { - valType: "enumerated", - values: ["scaled", "pixel"], - dflt: "scaled", - editType: "calc+arraydraw", - description: [ - "Sets the shapes's sizing mode along the y axis.", - "If set to *scaled*, `y0`, `y1` and y coordinates within `path` refer to", - "data values on the y axis or a fraction of the plot area's height", - "(`yref` set to *paper*).", - "If set to *pixel*, `yanchor` specifies the y position in terms", - "of data or plot fraction but `y0`, `y1` and y coordinates within `path`", - "are pixels relative to `yanchor`. This way, the shape can have", - "a fixed height while maintaining a position relative to data or", - "plot fraction." - ].join(" ") - }, - yanchor: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Only relevant in conjunction with `ysizemode` set to *pixel*.", - "Specifies the anchor point on the y axis to which `y0`, `y1`", - "and y coordinates within `path` are relative to.", - "E.g. useful to attach a pixel sized shape to a certain data value.", - "No effect when `ysizemode` not set to *pixel*." - ].join(" ") - }, - y0: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the shape's starting y position.", - "See `type` and `ysizemode` for more info." - ].join(" ") - }, - y1: { - valType: "any", - editType: "calc+arraydraw", - description: [ - "Sets the shape's end y position.", - "See `type` and `ysizemode` for more info." - ].join(" ") - }, - y0shift: { - valType: "number", - dflt: 0, - min: -1, - max: 1, - editType: "calc", - description: [ - "Shifts `y0` away from the center of the category when `yref` is a *category* or", - "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", - "corresponds to the end of the category." - ].join(" ") - }, - y1shift: { - valType: "number", - dflt: 0, - min: -1, - max: 1, - editType: "calc", - description: [ - "Shifts `y1` away from the center of the category when `yref` is a *category* or", - "*multicategory* axis. -0.5 corresponds to the start of the category and 0.5", - "corresponds to the end of the category." - ].join(" ") - }, - path: { - valType: "string", - editType: "calc+arraydraw", - description: [ - "For `type` *path* - a valid SVG path with the pixel values", - "replaced by data values in `xsizemode`/`ysizemode` being *scaled*", - "and taken unmodified as pixels relative to `xanchor` and `yanchor`", - "in case of *pixel* size mode.", - "There are a few restrictions / quirks", - "only absolute instructions, not relative. So the allowed segments", - "are: M, L, H, V, Q, C, T, S, and Z", - "arcs (A) are not allowed because radius rx and ry are relative.", - "In the future we could consider supporting relative commands,", - "but we would have to decide on how to handle date and log axes.", - "Note that even as is, Q and C Bezier paths that are smooth on", - "linear axes may not be smooth on log, and vice versa.", - 'no chained "polybezier" commands - specify the segment type for', - "each one.", - "On category axes, values are numbers scaled to the serial numbers", - "of categories because using the categories themselves there would", - "be no way to describe fractional positions", - "On data axes: because space and T are both normal components of path", - "strings, we can't use either to separate date from time parts.", - "Therefore we'll use underscore for this purpose:", - "2015-02-21_13:45:56.789" - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 1, - editType: "arraydraw", - description: "Sets the opacity of the shape." - }, - line: { - color: extendFlat$b({}, scatterLineAttrs$1.color, { editType: "arraydraw" }), - width: extendFlat$b({}, scatterLineAttrs$1.width, { editType: "calc+arraydraw" }), - dash: extendFlat$b({}, dash$1, { editType: "arraydraw" }), - editType: "calc+arraydraw" - }, - fillcolor: { - valType: "color", - dflt: "rgba(0,0,0,0)", - editType: "arraydraw", - description: [ - "Sets the color filling the shape's interior. Only applies to closed shapes." - ].join(" ") - }, - fillrule: { - valType: "enumerated", - values: ["evenodd", "nonzero"], - dflt: "evenodd", - editType: "arraydraw", - description: [ - "Determines which regions of complex paths constitute the interior.", - "For more info please visit https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule" - ].join(" ") - }, - editable: { - valType: "boolean", - dflt: false, - editType: "calc+arraydraw", - description: [ - "Determines whether the shape could be activated for edit or not.", - "Has no effect when the older editable shapes mode is enabled via", - "`config.editable` or `config.edits.shapePosition`." - ].join(" ") - }, - label: { - text: { - valType: "string", - dflt: "", - editType: "arraydraw", - description: [ - "Sets the text to display with shape.", - "It is also used for legend item if `name` is not provided." - ].join(" ") - }, - texttemplate: shapeTexttemplateAttrs({}, { keys: Object.keys(shapeLabelTexttemplateVars) }), - font: fontAttrs$7({ - editType: "calc+arraydraw", - colorEditType: "arraydraw", - description: "Sets the shape label text font." - }), - textposition: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right", - "start", - "middle", - "end" - ], - editType: "arraydraw", - description: [ - "Sets the position of the label text relative to the shape.", - "Supported values for rectangles, circles and paths are", - "*top left*, *top center*, *top right*, *middle left*,", - "*middle center*, *middle right*, *bottom left*, *bottom center*,", - "and *bottom right*.", - "Supported values for lines are *start*, *middle*, and *end*.", - "Default: *middle center* for rectangles, circles, and paths; *middle* for lines." - ].join(" ") - }, - textangle: { - valType: "angle", - dflt: "auto", - editType: "calc+arraydraw", - description: [ - "Sets the angle at which the label text is drawn", - "with respect to the horizontal. For lines, angle *auto*", - "is the same angle as the line. For all other shapes,", - "angle *auto* is horizontal." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "auto", - editType: "calc+arraydraw", - description: [ - "Sets the label's horizontal position anchor", - "This anchor binds the specified `textposition` to the *left*, *center*", - "or *right* of the label text.", - "For example, if `textposition` is set to *top right* and", - "`xanchor` to *right* then the right-most portion of the", - "label text lines up with the right-most edge of the", - "shape." - ].join(" ") - }, - yanchor: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - editType: "calc+arraydraw", - description: [ - "Sets the label's vertical position anchor", - "This anchor binds the specified `textposition` to the *top*, *middle*", - "or *bottom* of the label text.", - "For example, if `textposition` is set to *top right* and", - "`yanchor` to *top* then the top-most portion of the", - "label text lines up with the top-most edge of the", - "shape." - ].join(" ") - }, - padding: { - valType: "number", - dflt: 3, - min: 0, - editType: "arraydraw", - description: "Sets padding (in px) between edge of label and edge of shape." - }, - editType: "arraydraw" - }, - editType: "arraydraw" -}); -var Lib$M = libExports; -var Axes$9 = axesExports; -var handleArrayContainerDefaults$4 = array_container_defaults; -var attributes$q = attributes$r; -var helpers$j = helpers$w; -var defaults$e = function supplyLayoutDefaults6(layoutIn, layoutOut) { - handleArrayContainerDefaults$4(layoutIn, layoutOut, { - name: "shapes", - handleItemDefaults: handleShapeDefaults - }); -}; -function dfltLabelYanchor$1(isLine, labelTextPosition) { - return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; -} -function handleShapeDefaults(shapeIn, shapeOut, fullLayout) { - function coerce2(attr, dflt) { - return Lib$M.coerce(shapeIn, shapeOut, attributes$q, attr, dflt); - } - shapeOut._isShape = true; - var visible = coerce2("visible"); - if (!visible) return; - var showlegend = coerce2("showlegend"); - if (showlegend) { - coerce2("legend"); - coerce2("legendwidth"); - coerce2("legendgroup"); - coerce2("legendgrouptitle.text"); - Lib$M.coerceFont(coerce2, "legendgrouptitle.font"); - coerce2("legendrank"); - } - var path = coerce2("path"); - var dfltType = path ? "path" : "rect"; - var shapeType = coerce2("type", dfltType); - var noPath = shapeType !== "path"; - if (noPath) delete shapeOut.path; - coerce2("editable"); - coerce2("layer"); - coerce2("opacity"); - coerce2("fillcolor"); - coerce2("fillrule"); - var lineWidth = coerce2("line.width"); - if (lineWidth) { - coerce2("line.color"); - coerce2("line.dash"); - } - var xSizeMode = coerce2("xsizemode"); - var ySizeMode = coerce2("ysizemode"); - var axLetters2 = ["x", "y"]; - for (var i = 0; i < 2; i++) { - var axLetter = axLetters2[i]; - var attrAnchor = axLetter + "anchor"; - var sizeMode = axLetter === "x" ? xSizeMode : ySizeMode; - var gdMock = { _fullLayout: fullLayout }; - var ax; - var pos2r; - var r2pos; - var axRef = Axes$9.coerceRef( - shapeIn, - shapeOut, - gdMock, - axLetter, - void 0, - "paper" - ); - var axRefType = Axes$9.getRefType(axRef); - if (axRefType === "range") { - ax = Axes$9.getFromId(gdMock, axRef); - ax._shapeIndices.push(shapeOut._index); - r2pos = helpers$j.rangeToShapePosition(ax); - pos2r = helpers$j.shapePositionToRange(ax); - if (ax.type === "category" || ax.type === "multicategory") { - coerce2(axLetter + "0shift"); - coerce2(axLetter + "1shift"); - } - } else { - pos2r = r2pos = Lib$M.identity; - } - if (noPath) { - var dflt0 = 0.25; - var dflt1 = 0.75; - var attr0 = axLetter + "0"; - var attr1 = axLetter + "1"; - var in0 = shapeIn[attr0]; - var in1 = shapeIn[attr1]; - shapeIn[attr0] = pos2r(shapeIn[attr0], true); - shapeIn[attr1] = pos2r(shapeIn[attr1], true); - if (sizeMode === "pixel") { - coerce2(attr0, 0); - coerce2(attr1, 10); - } else { - Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attr0, dflt0); - Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attr1, dflt1); - } - shapeOut[attr0] = r2pos(shapeOut[attr0]); - shapeOut[attr1] = r2pos(shapeOut[attr1]); - shapeIn[attr0] = in0; - shapeIn[attr1] = in1; - } - if (sizeMode === "pixel") { - var inAnchor = shapeIn[attrAnchor]; - shapeIn[attrAnchor] = pos2r(shapeIn[attrAnchor], true); - Axes$9.coercePosition(shapeOut, gdMock, coerce2, axRef, attrAnchor, 0.25); - shapeOut[attrAnchor] = r2pos(shapeOut[attrAnchor]); - shapeIn[attrAnchor] = inAnchor; - } - } - if (noPath) { - Lib$M.noneOrAll(shapeIn, shapeOut, ["x0", "x1", "y0", "y1"]); - } - var isLine = shapeType === "line"; - var labelTextTemplate, labelText; - if (noPath) { - labelTextTemplate = coerce2("label.texttemplate"); - } - if (!labelTextTemplate) { - labelText = coerce2("label.text"); - } - if (labelText || labelTextTemplate) { - coerce2("label.textangle"); - var labelTextPosition = coerce2("label.textposition", isLine ? "middle" : "middle center"); - coerce2("label.xanchor"); - coerce2("label.yanchor", dfltLabelYanchor$1(isLine, labelTextPosition)); - coerce2("label.padding"); - Lib$M.coerceFont(coerce2, "label.font", fullLayout.font); - } -} -var Color$n = colorExports; -var Lib$L = libExports; -function dfltLabelYanchor(isLine, labelTextPosition) { - return isLine ? "bottom" : labelTextPosition.indexOf("top") !== -1 ? "top" : labelTextPosition.indexOf("bottom") !== -1 ? "bottom" : "middle"; -} -var defaults$d = function supplyDrawNewShapeDefaults(layoutIn, layoutOut, coerce2) { - coerce2("newshape.visible"); - coerce2("newshape.name"); - coerce2("newshape.showlegend"); - coerce2("newshape.legend"); - coerce2("newshape.legendwidth"); - coerce2("newshape.legendgroup"); - coerce2("newshape.legendgrouptitle.text"); - Lib$L.coerceFont(coerce2, "newshape.legendgrouptitle.font"); - coerce2("newshape.legendrank"); - coerce2("newshape.drawdirection"); - coerce2("newshape.layer"); - coerce2("newshape.fillcolor"); - coerce2("newshape.fillrule"); - coerce2("newshape.opacity"); - var newshapeLineWidth = coerce2("newshape.line.width"); - if (newshapeLineWidth) { - var bgcolor = (layoutIn || {}).plot_bgcolor || "#FFF"; - coerce2("newshape.line.color", Color$n.contrast(bgcolor)); - coerce2("newshape.line.dash"); - } - var isLine = layoutIn.dragmode === "drawline"; - var labelText = coerce2("newshape.label.text"); - var labelTextTemplate = coerce2("newshape.label.texttemplate"); - if (labelText || labelTextTemplate) { - coerce2("newshape.label.textangle"); - var labelTextPosition = coerce2("newshape.label.textposition", isLine ? "middle" : "middle center"); - coerce2("newshape.label.xanchor"); - coerce2("newshape.label.yanchor", dfltLabelYanchor(isLine, labelTextPosition)); - coerce2("newshape.label.padding"); - Lib$L.coerceFont(coerce2, "newshape.label.font", layoutOut.font); - } - coerce2("activeshape.fillcolor"); - coerce2("activeshape.opacity"); -}; -var Lib$K = libExports; -var Axes$8 = axesExports; -var constants$v = constants$I; -var helpers$i = helpers$w; -var calc_autorange$1 = function calcAutorange2(gd) { - var fullLayout = gd._fullLayout; - var shapeList = Lib$K.filterVisible(fullLayout.shapes); - if (!shapeList.length || !gd._fullData.length) return; - for (var i = 0; i < shapeList.length; i++) { - var shape = shapeList[i]; - shape._extremes = {}; - var ax; - var bounds; - var xRefType = Axes$8.getRefType(shape.xref); - var yRefType = Axes$8.getRefType(shape.yref); - if (shape.xref !== "paper" && xRefType !== "domain") { - ax = Axes$8.getFromId(gd, shape.xref); - bounds = shapeBounds(ax, shape, constants$v.paramIsX); - if (bounds) { - shape._extremes[ax._id] = Axes$8.findExtremes(ax, bounds, calcXPaddingOptions(shape)); - } - } - if (shape.yref !== "paper" && yRefType !== "domain") { - ax = Axes$8.getFromId(gd, shape.yref); - bounds = shapeBounds(ax, shape, constants$v.paramIsY); - if (bounds) { - shape._extremes[ax._id] = Axes$8.findExtremes(ax, bounds, calcYPaddingOptions(shape)); - } - } - } -}; -function calcXPaddingOptions(shape) { - return calcPaddingOptions(shape.line.width, shape.xsizemode, shape.x0, shape.x1, shape.path, false); -} -function calcYPaddingOptions(shape) { - return calcPaddingOptions(shape.line.width, shape.ysizemode, shape.y0, shape.y1, shape.path, true); -} -function calcPaddingOptions(lineWidth, sizeMode, v0, v1, path, isYAxis) { - var ppad = lineWidth / 2; - var axisDirectionReverted = isYAxis; - if (sizeMode === "pixel") { - var coords = path ? helpers$i.extractPathCoords(path, isYAxis ? constants$v.paramIsY : constants$v.paramIsX) : [v0, v1]; - var maxValue = Lib$K.aggNums(Math.max, null, coords); - var minValue = Lib$K.aggNums(Math.min, null, coords); - var beforePad = minValue < 0 ? Math.abs(minValue) + ppad : ppad; - var afterPad = maxValue > 0 ? maxValue + ppad : ppad; - return { - ppad, - ppadplus: axisDirectionReverted ? beforePad : afterPad, - ppadminus: axisDirectionReverted ? afterPad : beforePad - }; - } else { - return { ppad }; - } -} -function shapeBounds(ax, shape, paramsToUse) { - var dim = ax._id.charAt(0) === "x" ? "x" : "y"; - var isCategory = ax.type === "category" || ax.type === "multicategory"; - var v0; - var v1; - var shiftStart = 0; - var shiftEnd = 0; - var convertVal = isCategory ? ax.r2c : ax.d2c; - var isSizeModeScale = shape[dim + "sizemode"] === "scaled"; - if (isSizeModeScale) { - v0 = shape[dim + "0"]; - v1 = shape[dim + "1"]; - if (isCategory) { - shiftStart = shape[dim + "0shift"]; - shiftEnd = shape[dim + "1shift"]; - } - } else { - v0 = shape[dim + "anchor"]; - v1 = shape[dim + "anchor"]; - } - if (v0 !== void 0) return [convertVal(v0) + shiftStart, convertVal(v1) + shiftEnd]; - if (!shape.path) return; - var min = Infinity; - var max = -Infinity; - var segments = shape.path.match(constants$v.segmentRE); - var i; - var segment2; - var drawnParam; - var params; - var val; - if (ax.type === "date") convertVal = helpers$i.decodeDate(convertVal); - for (i = 0; i < segments.length; i++) { - segment2 = segments[i]; - drawnParam = paramsToUse[segment2.charAt(0)].drawn; - if (drawnParam === void 0) continue; - params = segments[i].substr(1).match(constants$v.paramRE); - if (!params || params.length < drawnParam) continue; - val = convertVal(params[drawnParam]); - if (val < min) min = val; - if (val > max) max = val; - } - if (max >= min) return [min, max]; -} -var drawModule = draw_1$3; -var shapes = { - moduleType: "component", - name: "shapes", - layoutAttributes: attributes$r, - supplyLayoutDefaults: defaults$e, - supplyDrawNewShapeDefaults: defaults$d, - includeBasePlot: include_components("shapes"), - calcAutorange: calc_autorange$1, - draw: drawModule.draw, - drawOne: drawModule.drawOne -}; -var cartesianConstants = constants$U; -var templatedArray$3 = plot_template.templatedArray; -var axisPlaceableObjs = axis_placeable_objects; -var attributes$p = templatedArray$3("image", { - visible: { - valType: "boolean", - dflt: true, - editType: "arraydraw", - description: [ - "Determines whether or not this image is visible." - ].join(" ") - }, - source: { - valType: "string", - editType: "arraydraw", - description: [ - "Specifies the URL of the image to be used.", - "The URL must be accessible from the domain where the", - "plot code is run, and can be either relative or absolute." - ].join(" ") - }, - layer: { - valType: "enumerated", - values: ["below", "above"], - dflt: "above", - editType: "arraydraw", - description: [ - "Specifies whether images are drawn below or above traces.", - "When `xref` and `yref` are both set to `paper`,", - "image is drawn below the entire plot area." - ].join(" ") - }, - sizex: { - valType: "number", - dflt: 0, - editType: "arraydraw", - description: [ - "Sets the image container size horizontally.", - "The image will be sized based on the `position` value.", - "When `xref` is set to `paper`, units are sized relative", - "to the plot width.", - "When `xref` ends with ` domain`, units are sized relative", - "to the axis width." - ].join(" ") - }, - sizey: { - valType: "number", - dflt: 0, - editType: "arraydraw", - description: [ - "Sets the image container size vertically.", - "The image will be sized based on the `position` value.", - "When `yref` is set to `paper`, units are sized relative", - "to the plot height.", - "When `yref` ends with ` domain`, units are sized relative", - "to the axis height." - ].join(" ") - }, - sizing: { - valType: "enumerated", - values: ["fill", "contain", "stretch"], - dflt: "contain", - editType: "arraydraw", - description: [ - "Specifies which dimension of the image to constrain." - ].join(" ") - }, - opacity: { - valType: "number", - min: 0, - max: 1, - dflt: 1, - editType: "arraydraw", - description: "Sets the opacity of the image." - }, - x: { - valType: "any", - dflt: 0, - editType: "arraydraw", - description: [ - "Sets the image's x position.", - "When `xref` is set to `paper`, units are sized relative", - "to the plot height.", - "See `xref` for more info" - ].join(" ") - }, - y: { - valType: "any", - dflt: 0, - editType: "arraydraw", - description: [ - "Sets the image's y position.", - "When `yref` is set to `paper`, units are sized relative", - "to the plot height.", - "See `yref` for more info" - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["left", "center", "right"], - dflt: "left", - editType: "arraydraw", - description: "Sets the anchor for the x position" - }, - yanchor: { - valType: "enumerated", - values: ["top", "middle", "bottom"], - dflt: "top", - editType: "arraydraw", - description: "Sets the anchor for the y position." - }, - xref: { - valType: "enumerated", - values: [ - "paper", - cartesianConstants.idRegex.x.toString() - ], - dflt: "paper", - editType: "arraydraw", - description: [ - "Sets the images's x coordinate axis.", - axisPlaceableObjs.axisRefDescription("x", "left", "right") - ].join(" ") - }, - yref: { - valType: "enumerated", - values: [ - "paper", - cartesianConstants.idRegex.y.toString() - ], - dflt: "paper", - editType: "arraydraw", - description: [ - "Sets the images's y coordinate axis.", - axisPlaceableObjs.axisRefDescription("y", "bottom", "top") - ].join(" ") - }, - editType: "arraydraw" -}); -var Lib$J = libExports; -var Axes$7 = axesExports; -var handleArrayContainerDefaults$3 = array_container_defaults; -var attributes$o = attributes$p; -var name$3 = "images"; -var defaults$c = function supplyLayoutDefaults7(layoutIn, layoutOut) { - var opts = { - name: name$3, - handleItemDefaults: imageDefaults - }; - handleArrayContainerDefaults$3(layoutIn, layoutOut, opts); -}; -function imageDefaults(imageIn, imageOut, fullLayout) { - function coerce2(attr, dflt) { - return Lib$J.coerce(imageIn, imageOut, attributes$o, attr, dflt); - } - var source = coerce2("source"); - var visible = coerce2("visible", !!source); - if (!visible) return imageOut; - coerce2("layer"); - coerce2("xanchor"); - coerce2("yanchor"); - coerce2("sizex"); - coerce2("sizey"); - coerce2("sizing"); - coerce2("opacity"); - var gdMock = { _fullLayout: fullLayout }; - var axLetters2 = ["x", "y"]; - for (var i = 0; i < 2; i++) { - var axLetter = axLetters2[i]; - var axRef = Axes$7.coerceRef(imageIn, imageOut, gdMock, axLetter, "paper", void 0); - if (axRef !== "paper") { - var ax = Axes$7.getFromId(gdMock, axRef); - ax._imgIndices.push(imageOut._index); - } - Axes$7.coercePosition(imageOut, gdMock, coerce2, axRef, axLetter, 0); - } - return imageOut; -} -var d3$i = d3Exports; -var Drawing$d = drawingExports; -var Axes$6 = axesExports; -var axisIds$2 = axis_ids; -var xmlnsNamespaces = xmlns_namespaces; -var draw$7 = function draw3(gd) { - var fullLayout = gd._fullLayout; - var imageDataAbove = []; - var imageDataSubplot = {}; - var imageDataBelow = []; - var subplot; - var i; - for (i = 0; i < fullLayout.images.length; i++) { - var img = fullLayout.images[i]; - if (img.visible) { - if (img.layer === "below" && img.xref !== "paper" && img.yref !== "paper") { - subplot = axisIds$2.ref2id(img.xref) + axisIds$2.ref2id(img.yref); - var plotinfo = fullLayout._plots[subplot]; - if (!plotinfo) { - imageDataBelow.push(img); - continue; - } - if (plotinfo.mainplot) { - subplot = plotinfo.mainplot.id; - } - if (!imageDataSubplot[subplot]) { - imageDataSubplot[subplot] = []; - } - imageDataSubplot[subplot].push(img); - } else if (img.layer === "above") { - imageDataAbove.push(img); - } else { - imageDataBelow.push(img); - } - } - } - var anchors = { - x: { - left: { sizing: "xMin", offset: 0 }, - center: { sizing: "xMid", offset: -1 / 2 }, - right: { sizing: "xMax", offset: -1 } - }, - y: { - top: { sizing: "YMin", offset: 0 }, - middle: { sizing: "YMid", offset: -1 / 2 }, - bottom: { sizing: "YMax", offset: -1 } - } - }; - function setImage(d) { - var thisImage = d3$i.select(this); - if (this._imgSrc === d.source) { - return; - } - thisImage.attr("xmlns", xmlnsNamespaces.svg); - if (d.source && d.source.slice(0, 5) === "data:") { - thisImage.attr("xlink:href", d.source); - this._imgSrc = d.source; - } else { - var imagePromise = new Promise((function(resolve) { - var img2 = new Image(); - this.img = img2; - img2.setAttribute("crossOrigin", "anonymous"); - img2.onerror = errorHandler; - img2.onload = function() { - var canvas2 = document.createElement("canvas"); - canvas2.width = this.width; - canvas2.height = this.height; - var ctx2 = canvas2.getContext("2d", { willReadFrequently: true }); - ctx2.drawImage(this, 0, 0); - var dataURL = canvas2.toDataURL("image/png"); - thisImage.attr("xlink:href", dataURL); - resolve(); - }; - thisImage.on("error", errorHandler); - img2.src = d.source; - this._imgSrc = d.source; - function errorHandler() { - thisImage.remove(); - resolve(); - } - }).bind(this)); - gd._promises.push(imagePromise); - } - } - function applyAttributes2(d) { - var thisImage = d3$i.select(this); - var xa = Axes$6.getFromId(gd, d.xref); - var ya = Axes$6.getFromId(gd, d.yref); - var xIsDomain = Axes$6.getRefType(d.xref) === "domain"; - var yIsDomain = Axes$6.getRefType(d.yref) === "domain"; - var size = fullLayout._size; - var width, height; - if (xa !== void 0) { - width = typeof d.xref === "string" && xIsDomain ? xa._length * d.sizex : Math.abs(xa.l2p(d.sizex) - xa.l2p(0)); - } else { - width = d.sizex * size.w; - } - if (ya !== void 0) { - height = typeof d.yref === "string" && yIsDomain ? ya._length * d.sizey : Math.abs(ya.l2p(d.sizey) - ya.l2p(0)); - } else { - height = d.sizey * size.h; - } - var xOffset = width * anchors.x[d.xanchor].offset; - var yOffset = height * anchors.y[d.yanchor].offset; - var sizing = anchors.x[d.xanchor].sizing + anchors.y[d.yanchor].sizing; - var xPos, yPos; - if (xa !== void 0) { - xPos = typeof d.xref === "string" && xIsDomain ? xa._length * d.x + xa._offset : xa.r2p(d.x) + xa._offset; - } else { - xPos = d.x * size.w + size.l; - } - xPos += xOffset; - if (ya !== void 0) { - yPos = typeof d.yref === "string" && yIsDomain ? ( - // consistent with "paper" yref value, where positive values - // move up the page - ya._length * (1 - d.y) + ya._offset - ) : ya.r2p(d.y) + ya._offset; - } else { - yPos = size.h - d.y * size.h + size.t; - } - yPos += yOffset; - switch (d.sizing) { - case "fill": - sizing += " slice"; - break; - case "stretch": - sizing = "none"; - break; - } - thisImage.attr({ - x: xPos, - y: yPos, - width, - height, - preserveAspectRatio: sizing, - opacity: d.opacity - }); - var xId = xa && Axes$6.getRefType(d.xref) !== "domain" ? xa._id : ""; - var yId = ya && Axes$6.getRefType(d.yref) !== "domain" ? ya._id : ""; - var clipAxes = xId + yId; - Drawing$d.setClipUrl( - thisImage, - clipAxes ? "clip" + fullLayout._uid + clipAxes : null, - gd - ); - } - var imagesBelow = fullLayout._imageLowerLayer.selectAll("image").data(imageDataBelow); - var imagesAbove = fullLayout._imageUpperLayer.selectAll("image").data(imageDataAbove); - imagesBelow.enter().append("image"); - imagesAbove.enter().append("image"); - imagesBelow.exit().remove(); - imagesAbove.exit().remove(); - imagesBelow.each(function(d) { - setImage.bind(this)(d); - applyAttributes2.bind(this)(d); - }); - imagesAbove.each(function(d) { - setImage.bind(this)(d); - applyAttributes2.bind(this)(d); - }); - var allSubplots = Object.keys(fullLayout._plots); - for (i = 0; i < allSubplots.length; i++) { - subplot = allSubplots[i]; - var subplotObj = fullLayout._plots[subplot]; - if (!subplotObj.imagelayer) continue; - var imagesOnSubplot = subplotObj.imagelayer.selectAll("image").data(imageDataSubplot[subplot] || []); - imagesOnSubplot.enter().append("image"); - imagesOnSubplot.exit().remove(); - imagesOnSubplot.each(function(d) { - setImage.bind(this)(d); - applyAttributes2.bind(this)(d); - }); - } -}; -var isNumeric$9 = fastIsnumeric; -var toLogRange2 = to_log_range; -var convert_coords = function convertCoords2(gd, ax, newType, doExtra) { - ax = ax || {}; - var toLog = newType === "log" && ax.type === "linear"; - var fromLog2 = newType === "linear" && ax.type === "log"; - if (!(toLog || fromLog2)) return; - var images2 = gd._fullLayout.images; - var axLetter = ax._id.charAt(0); - var image; - var attrPrefix; - for (var i = 0; i < images2.length; i++) { - image = images2[i]; - attrPrefix = "images[" + i + "]."; - if (image[axLetter + "ref"] === ax._id) { - var currentPos = image[axLetter]; - var currentSize = image["size" + axLetter]; - var newPos = null; - var newSize = null; - if (toLog) { - newPos = toLogRange2(currentPos, ax.range); - var dx = currentSize / Math.pow(10, newPos) / 2; - newSize = 2 * Math.log(dx + Math.sqrt(1 + dx * dx)) / Math.LN10; - } else { - newPos = Math.pow(10, currentPos); - newSize = newPos * (Math.pow(10, currentSize / 2) - Math.pow(10, -currentSize / 2)); - } - if (!isNumeric$9(newPos)) { - newPos = null; - newSize = null; - } else if (!isNumeric$9(newSize)) newSize = null; - doExtra(attrPrefix + axLetter, newPos); - doExtra(attrPrefix + "size" + axLetter, newSize); - } - } -}; -var images = { - moduleType: "component", - name: "images", - layoutAttributes: attributes$p, - supplyLayoutDefaults: defaults$c, - includeBasePlot: include_components("images"), - draw: draw$7, - convertCoords: convert_coords -}; -var constants$u = { - // layout attribute name - name: "updatemenus", - // class names - containerClassName: "updatemenu-container", - headerGroupClassName: "updatemenu-header-group", - headerClassName: "updatemenu-header", - headerArrowClassName: "updatemenu-header-arrow", - dropdownButtonGroupClassName: "updatemenu-dropdown-button-group", - dropdownButtonClassName: "updatemenu-dropdown-button", - buttonClassName: "updatemenu-button", - itemRectClassName: "updatemenu-item-rect", - itemTextClassName: "updatemenu-item-text", - // DOM attribute name in button group keeping track - // of active update menu - menuIndexAttrName: "updatemenu-active-index", - // id root pass to Plots.autoMargin - autoMarginIdRoot: "updatemenu-", - // options when 'active: -1' - blankHeaderOpts: { label: " " }, - // min item width / height - minWidth: 30, - minHeight: 30, - // padding around item text - textPadX: 24, - arrowPadX: 16, - // item rect radii - rx: 2, - ry: 2, - // item text x offset off left edge - textOffsetX: 12, - // item text y offset (w.r.t. middle) - textOffsetY: 3, - // arrow offset off right edge - arrowOffsetX: 4, - // gap between header and buttons - gapButtonHeader: 5, - // gap between between buttons - gapButton: 2, - // color given to active buttons - activeColor: "#F4FAFF", - // color given to hovered buttons - hoverColor: "#F4FAFF", - // symbol for menu open arrow - arrowSymbol: { - left: "◄", - right: "►", - up: "▲", - down: "▼" - } -}; -var fontAttrs$6 = font_attributes; -var colorAttrs$2 = attributes$N; -var extendFlat$a = extend$5.extendFlat; -var overrideAll$3 = edit_types.overrideAll; -var padAttrs$1 = pad_attributes; -var templatedArray$2 = plot_template.templatedArray; -var buttonsAttrs = templatedArray$2("button", { - visible: { - valType: "boolean", - description: "Determines whether or not this button is visible." - }, - method: { - valType: "enumerated", - values: ["restyle", "relayout", "animate", "update", "skip"], - dflt: "restyle", - description: [ - "Sets the Plotly method to be called on click.", - "If the `skip` method is used, the API updatemenu will function as normal", - "but will perform no API calls and will not bind automatically to state", - "updates. This may be used to create a component interface and attach to", - "updatemenu events manually via JavaScript." - ].join(" ") - }, - args: { - valType: "info_array", - freeLength: true, - items: [ - { valType: "any" }, - { valType: "any" }, - { valType: "any" } - ], - description: [ - "Sets the arguments values to be passed to the Plotly", - "method set in `method` on click." - ].join(" ") - }, - args2: { - valType: "info_array", - freeLength: true, - items: [ - { valType: "any" }, - { valType: "any" }, - { valType: "any" } - ], - description: [ - "Sets a 2nd set of `args`,", - "these arguments values are passed to the Plotly", - "method set in `method` when clicking this button while in the active state.", - "Use this to create toggle buttons." - ].join(" ") - }, - label: { - valType: "string", - dflt: "", - description: "Sets the text label to appear on the button." - }, - execute: { - valType: "boolean", - dflt: true, - description: [ - "When true, the API method is executed. When false, all other behaviors are the same", - "and command execution is skipped. This may be useful when hooking into, for example,", - "the `plotly_buttonclicked` method and executing the API command manually without losing", - "the benefit of the updatemenu automatically binding to the state of the plot through the", - "specification of `method` and `args`." - ].join(" ") - } -}); -var attributes$n = overrideAll$3(templatedArray$2("updatemenu", { - _arrayAttrRegexps: [/^updatemenus\[(0|[1-9][0-9]+)\]\.buttons/], - visible: { - valType: "boolean", - description: [ - "Determines whether or not the update menu is visible." - ].join(" ") - }, - type: { - valType: "enumerated", - values: ["dropdown", "buttons"], - dflt: "dropdown", - description: [ - "Determines whether the buttons are accessible via a dropdown menu", - "or whether the buttons are stacked horizontally or vertically" - ].join(" ") - }, - direction: { - valType: "enumerated", - values: ["left", "right", "up", "down"], - dflt: "down", - description: [ - "Determines the direction in which the buttons are laid out, whether", - "in a dropdown menu or a row/column of buttons. For `left` and `up`,", - "the buttons will still appear in left-to-right or top-to-bottom order", - "respectively." - ].join(" ") - }, - active: { - valType: "integer", - min: -1, - dflt: 0, - description: [ - "Determines which button (by index starting from 0) is", - "considered active." - ].join(" ") - }, - showactive: { - valType: "boolean", - dflt: true, - description: "Highlights active dropdown item or active button if true." - }, - buttons: buttonsAttrs, - x: { - valType: "number", - min: -2, - max: 3, - dflt: -0.05, - description: "Sets the x position (in normalized coordinates) of the update menu." - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "right", - description: [ - "Sets the update menu's horizontal position anchor.", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the range selector." - ].join(" ") - }, - y: { - valType: "number", - min: -2, - max: 3, - dflt: 1, - description: "Sets the y position (in normalized coordinates) of the update menu." - }, - yanchor: { - valType: "enumerated", - values: ["auto", "top", "middle", "bottom"], - dflt: "top", - description: [ - "Sets the update menu's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the range selector." - ].join(" ") - }, - pad: extendFlat$a(padAttrs$1({ editType: "arraydraw" }), { - description: "Sets the padding around the buttons or dropdown menu." - }), - font: fontAttrs$6({ - description: "Sets the font of the update menu button text." - }), - bgcolor: { - valType: "color", - description: "Sets the background color of the update menu buttons." - }, - bordercolor: { - valType: "color", - dflt: colorAttrs$2.borderLine, - description: "Sets the color of the border enclosing the update menu." - }, - borderwidth: { - valType: "number", - min: 0, - dflt: 1, - editType: "arraydraw", - description: "Sets the width (in px) of the border enclosing the update menu." - } -}), "arraydraw", "from-root"); -var Lib$I = libExports; -var handleArrayContainerDefaults$2 = array_container_defaults; -var attributes$m = attributes$n; -var constants$t = constants$u; -var name$2 = constants$t.name; -var buttonAttrs$1 = attributes$m.buttons; -var defaults$b = function updateMenusDefaults(layoutIn, layoutOut) { - var opts = { - name: name$2, - handleItemDefaults: menuDefaults - }; - handleArrayContainerDefaults$2(layoutIn, layoutOut, opts); -}; -function menuDefaults(menuIn, menuOut, layoutOut) { - function coerce2(attr, dflt) { - return Lib$I.coerce(menuIn, menuOut, attributes$m, attr, dflt); - } - var buttons2 = handleArrayContainerDefaults$2(menuIn, menuOut, { - name: "buttons", - handleItemDefaults: buttonDefaults$1 - }); - var visible = coerce2("visible", buttons2.length > 0); - if (!visible) return; - coerce2("active"); - coerce2("direction"); - coerce2("type"); - coerce2("showactive"); - coerce2("x"); - coerce2("y"); - Lib$I.noneOrAll(menuIn, menuOut, ["x", "y"]); - coerce2("xanchor"); - coerce2("yanchor"); - coerce2("pad.t"); - coerce2("pad.r"); - coerce2("pad.b"); - coerce2("pad.l"); - Lib$I.coerceFont(coerce2, "font", layoutOut.font); - coerce2("bgcolor", layoutOut.paper_bgcolor); - coerce2("bordercolor"); - coerce2("borderwidth"); -} -function buttonDefaults$1(buttonIn, buttonOut) { - function coerce2(attr, dflt) { - return Lib$I.coerce(buttonIn, buttonOut, buttonAttrs$1, attr, dflt); - } - var visible = coerce2( - "visible", - buttonIn.method === "skip" || Array.isArray(buttonIn.args) - ); - if (visible) { - coerce2("method"); - coerce2("args"); - coerce2("args2"); - coerce2("label"); - coerce2("execute"); - } -} -var scrollbox = ScrollBox$1; -var d3$h = d3Exports; -var Color$m = colorExports; -var Drawing$c = drawingExports; -var Lib$H = libExports; -function ScrollBox$1(gd, container, id) { - this.gd = gd; - this.container = container; - this.id = id; - this.position = null; - this.translateX = null; - this.translateY = null; - this.hbar = null; - this.vbar = null; - this.bg = this.container.selectAll("rect.scrollbox-bg").data([0]); - this.bg.exit().on(".drag", null).on("wheel", null).remove(); - this.bg.enter().append("rect").classed("scrollbox-bg", true).style("pointer-events", "all").attr({ - opacity: 0, - x: 0, - y: 0, - width: 0, - height: 0 - }); -} -ScrollBox$1.barWidth = 2; -ScrollBox$1.barLength = 20; -ScrollBox$1.barRadius = 2; -ScrollBox$1.barPad = 1; -ScrollBox$1.barColor = "#808BA4"; -ScrollBox$1.prototype.enable = function enable(position, translateX, translateY) { - var fullLayout = this.gd._fullLayout; - var fullWidth = fullLayout.width; - var fullHeight = fullLayout.height; - this.position = position; - var l = this.position.l; - var w = this.position.w; - var t = this.position.t; - var h = this.position.h; - var direction = this.position.direction; - var isDown = direction === "down"; - var isLeft = direction === "left"; - var isRight = direction === "right"; - var isUp = direction === "up"; - var boxW = w; - var boxH = h; - var boxL, boxR; - var boxT, boxB; - if (!isDown && !isLeft && !isRight && !isUp) { - this.position.direction = "down"; - isDown = true; - } - var isVertical2 = isDown || isUp; - if (isVertical2) { - boxL = l; - boxR = boxL + boxW; - if (isDown) { - boxT = t; - boxB = Math.min(boxT + boxH, fullHeight); - boxH = boxB - boxT; - } else { - boxB = t + boxH; - boxT = Math.max(boxB - boxH, 0); - boxH = boxB - boxT; - } - } else { - boxT = t; - boxB = boxT + boxH; - if (isLeft) { - boxR = l + boxW; - boxL = Math.max(boxR - boxW, 0); - boxW = boxR - boxL; - } else { - boxL = l; - boxR = Math.min(boxL + boxW, fullWidth); - boxW = boxR - boxL; - } - } - this._box = { - l: boxL, - t: boxT, - w: boxW, - h: boxH - }; - var needsHorizontalScrollBar = w > boxW; - var hbarW = ScrollBox$1.barLength + 2 * ScrollBox$1.barPad; - var hbarH = ScrollBox$1.barWidth + 2 * ScrollBox$1.barPad; - var hbarL = l; - var hbarT = t + h; - if (hbarT + hbarH > fullHeight) hbarT = fullHeight - hbarH; - var hbar = this.container.selectAll("rect.scrollbar-horizontal").data( - needsHorizontalScrollBar ? [0] : [] - ); - hbar.exit().on(".drag", null).remove(); - hbar.enter().append("rect").classed("scrollbar-horizontal", true).call(Color$m.fill, ScrollBox$1.barColor); - if (needsHorizontalScrollBar) { - this.hbar = hbar.attr({ - rx: ScrollBox$1.barRadius, - ry: ScrollBox$1.barRadius, - x: hbarL, - y: hbarT, - width: hbarW, - height: hbarH - }); - this._hbarXMin = hbarL + hbarW / 2; - this._hbarTranslateMax = boxW - hbarW; - } else { - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } - var needsVerticalScrollBar = h > boxH; - var vbarW = ScrollBox$1.barWidth + 2 * ScrollBox$1.barPad; - var vbarH = ScrollBox$1.barLength + 2 * ScrollBox$1.barPad; - var vbarL = l + w; - var vbarT = t; - if (vbarL + vbarW > fullWidth) vbarL = fullWidth - vbarW; - var vbar = this.container.selectAll("rect.scrollbar-vertical").data( - needsVerticalScrollBar ? [0] : [] - ); - vbar.exit().on(".drag", null).remove(); - vbar.enter().append("rect").classed("scrollbar-vertical", true).call(Color$m.fill, ScrollBox$1.barColor); - if (needsVerticalScrollBar) { - this.vbar = vbar.attr({ - rx: ScrollBox$1.barRadius, - ry: ScrollBox$1.barRadius, - x: vbarL, - y: vbarT, - width: vbarW, - height: vbarH - }); - this._vbarYMin = vbarT + vbarH / 2; - this._vbarTranslateMax = boxH - vbarH; - } else { - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } - var clipId = this.id; - var clipL = boxL - 0.5; - var clipR = needsVerticalScrollBar ? boxR + vbarW + 0.5 : boxR + 0.5; - var clipT = boxT - 0.5; - var clipB = needsHorizontalScrollBar ? boxB + hbarH + 0.5 : boxB + 0.5; - var clipPath = fullLayout._topdefs.selectAll("#" + clipId).data(needsHorizontalScrollBar || needsVerticalScrollBar ? [0] : []); - clipPath.exit().remove(); - clipPath.enter().append("clipPath").attr("id", clipId).append("rect"); - if (needsHorizontalScrollBar || needsVerticalScrollBar) { - this._clipRect = clipPath.select("rect").attr({ - x: Math.floor(clipL), - y: Math.floor(clipT), - width: Math.ceil(clipR) - Math.floor(clipL), - height: Math.ceil(clipB) - Math.floor(clipT) - }); - this.container.call(Drawing$c.setClipUrl, clipId, this.gd); - this.bg.attr({ - x: l, - y: t, - width: w, - height: h - }); - } else { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container.on("wheel", null).on(".drag", null).call(Drawing$c.setClipUrl, null); - delete this._clipRect; - } - if (needsHorizontalScrollBar || needsVerticalScrollBar) { - var onBoxDrag = d3$h.behavior.drag().on("dragstart", function() { - d3$h.event.sourceEvent.preventDefault(); - }).on("drag", this._onBoxDrag.bind(this)); - this.container.on("wheel", null).on("wheel", this._onBoxWheel.bind(this)).on(".drag", null).call(onBoxDrag); - var onBarDrag = d3$h.behavior.drag().on("dragstart", function() { - d3$h.event.sourceEvent.preventDefault(); - d3$h.event.sourceEvent.stopPropagation(); - }).on("drag", this._onBarDrag.bind(this)); - if (needsHorizontalScrollBar) { - this.hbar.on(".drag", null).call(onBarDrag); - } - if (needsVerticalScrollBar) { - this.vbar.on(".drag", null).call(onBarDrag); - } - } - this.setTranslate(translateX, translateY); -}; -ScrollBox$1.prototype.disable = function disable() { - if (this.hbar || this.vbar) { - this.bg.attr({ - width: 0, - height: 0 - }); - this.container.on("wheel", null).on(".drag", null).call(Drawing$c.setClipUrl, null); - delete this._clipRect; - } - if (this.hbar) { - this.hbar.on(".drag", null); - this.hbar.remove(); - delete this.hbar; - delete this._hbarXMin; - delete this._hbarTranslateMax; - } - if (this.vbar) { - this.vbar.on(".drag", null); - this.vbar.remove(); - delete this.vbar; - delete this._vbarYMin; - delete this._vbarTranslateMax; - } -}; -ScrollBox$1.prototype._onBoxDrag = function _onBoxDrag() { - var translateX = this.translateX; - var translateY = this.translateY; - if (this.hbar) { - translateX -= d3$h.event.dx; - } - if (this.vbar) { - translateY -= d3$h.event.dy; - } - this.setTranslate(translateX, translateY); -}; -ScrollBox$1.prototype._onBoxWheel = function _onBoxWheel() { - var translateX = this.translateX; - var translateY = this.translateY; - if (this.hbar) { - translateX += d3$h.event.deltaY; - } - if (this.vbar) { - translateY += d3$h.event.deltaY; - } - this.setTranslate(translateX, translateY); -}; -ScrollBox$1.prototype._onBarDrag = function _onBarDrag() { - var translateX = this.translateX; - var translateY = this.translateY; - if (this.hbar) { - var xMin = translateX + this._hbarXMin; - var xMax = xMin + this._hbarTranslateMax; - var x = Lib$H.constrain(d3$h.event.x, xMin, xMax); - var xf = (x - xMin) / (xMax - xMin); - var translateXMax = this.position.w - this._box.w; - translateX = xf * translateXMax; - } - if (this.vbar) { - var yMin = translateY + this._vbarYMin; - var yMax = yMin + this._vbarTranslateMax; - var y = Lib$H.constrain(d3$h.event.y, yMin, yMax); - var yf = (y - yMin) / (yMax - yMin); - var translateYMax = this.position.h - this._box.h; - translateY = yf * translateYMax; - } - this.setTranslate(translateX, translateY); -}; -ScrollBox$1.prototype.setTranslate = function setTranslate(translateX, translateY) { - var translateXMax = this.position.w - this._box.w; - var translateYMax = this.position.h - this._box.h; - translateX = Lib$H.constrain(translateX || 0, 0, translateXMax); - translateY = Lib$H.constrain(translateY || 0, 0, translateYMax); - this.translateX = translateX; - this.translateY = translateY; - this.container.call( - Drawing$c.setTranslate, - this._box.l - this.position.l - translateX, - this._box.t - this.position.t - translateY - ); - if (this._clipRect) { - this._clipRect.attr({ - x: Math.floor(this.position.l + translateX - 0.5), - y: Math.floor(this.position.t + translateY - 0.5) - }); - } - if (this.hbar) { - var xf = translateX / translateXMax; - this.hbar.call( - Drawing$c.setTranslate, - translateX + xf * this._hbarTranslateMax, - translateY - ); - } - if (this.vbar) { - var yf = translateY / translateYMax; - this.vbar.call( - Drawing$c.setTranslate, - translateX, - translateY + yf * this._vbarTranslateMax - ); - } -}; -var d3$g = d3Exports; -var Plots$4 = plotsExports; -var Color$l = colorExports; -var Drawing$b = drawingExports; -var Lib$G = libExports; -var svgTextUtils$8 = svg_text_utils; -var arrayEditor$1 = plot_template.arrayEditor; -var LINE_SPACING$4 = alignment$1.LINE_SPACING; -var constants$s = constants$u; -var ScrollBox = scrollbox; -var draw$6 = function draw4(gd) { - var fullLayout = gd._fullLayout; - var menuData = Lib$G.filterVisible(fullLayout[constants$s.name]); - function clearAutoMargin(menuOpts2) { - Plots$4.autoMargin(gd, autoMarginId$1(menuOpts2)); - } - var menus = fullLayout._menulayer.selectAll("g." + constants$s.containerClassName).data(menuData.length > 0 ? [0] : []); - menus.enter().append("g").classed(constants$s.containerClassName, true).style("cursor", "pointer"); - menus.exit().each(function() { - d3$g.select(this).selectAll("g." + constants$s.headerGroupClassName).each(clearAutoMargin); - }).remove(); - if (menuData.length === 0) return; - var headerGroups = menus.selectAll("g." + constants$s.headerGroupClassName).data(menuData, keyFunction$1); - headerGroups.enter().append("g").classed(constants$s.headerGroupClassName, true); - var gButton = Lib$G.ensureSingle(menus, "g", constants$s.dropdownButtonGroupClassName, function(s) { - s.style("pointer-events", "all"); - }); - for (var i = 0; i < menuData.length; i++) { - var menuOpts = menuData[i]; - findDimensions$1(gd, menuOpts); - } - var scrollBoxId = "updatemenus" + fullLayout._uid; - var scrollBox = new ScrollBox(gd, gButton, scrollBoxId); - if (headerGroups.enter().size()) { - gButton.node().parentNode.appendChild(gButton.node()); - gButton.call(removeAllButtons); - } - headerGroups.exit().each(function(menuOpts2) { - gButton.call(removeAllButtons); - clearAutoMargin(menuOpts2); - }).remove(); - headerGroups.each(function(menuOpts2) { - var gHeader = d3$g.select(this); - var _gButton = menuOpts2.type === "dropdown" ? gButton : null; - Plots$4.manageCommandObserver(gd, menuOpts2, menuOpts2.buttons, function(data) { - setActive$1(gd, menuOpts2, menuOpts2.buttons[data.index], gHeader, _gButton, scrollBox, data.index, true); - }); - if (menuOpts2.type === "dropdown") { - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts2); - if (isActive$1(gButton, menuOpts2)) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts2); - } - } else { - drawButtons(gd, gHeader, null, null, menuOpts2); - } - }); -}; -function keyFunction$1(menuOpts) { - return menuOpts._index; -} -function isFolded(gButton) { - return +gButton.attr(constants$s.menuIndexAttrName) === -1; -} -function isActive$1(gButton, menuOpts) { - return +gButton.attr(constants$s.menuIndexAttrName) === menuOpts._index; -} -function setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex, isSilentUpdate) { - menuOpts.active = buttonIndex; - arrayEditor$1(gd.layout, constants$s.name, menuOpts).applyUpdate("active", buttonIndex); - if (menuOpts.type === "buttons") { - drawButtons(gd, gHeader, null, null, menuOpts); - } else if (menuOpts.type === "dropdown") { - gButton.attr(constants$s.menuIndexAttrName, "-1"); - drawHeader(gd, gHeader, gButton, scrollBox, menuOpts); - if (!isSilentUpdate) { - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - } - } -} -function drawHeader(gd, gHeader, gButton, scrollBox, menuOpts) { - var header = Lib$G.ensureSingle(gHeader, "g", constants$s.headerClassName, function(s) { - s.style("pointer-events", "all"); - }); - var dims = menuOpts._dims; - var active = menuOpts.active; - var headerOpts = menuOpts.buttons[active] || constants$s.blankHeaderOpts; - var posOpts = { y: menuOpts.pad.t, yPad: 0, x: menuOpts.pad.l, xPad: 0, index: 0 }; - var positionOverrides = { - width: dims.headerWidth, - height: dims.headerHeight - }; - header.call(drawItem, menuOpts, headerOpts, gd).call(setItemPosition, menuOpts, posOpts, positionOverrides); - var arrow = Lib$G.ensureSingle(gHeader, "text", constants$s.headerArrowClassName, function(s) { - s.attr("text-anchor", "end").call(Drawing$b.font, menuOpts.font).text(constants$s.arrowSymbol[menuOpts.direction]); - }); - arrow.attr({ - x: dims.headerWidth - constants$s.arrowOffsetX + menuOpts.pad.l, - y: dims.headerHeight / 2 + constants$s.textOffsetY + menuOpts.pad.t - }); - header.on("click", function() { - gButton.call( - removeAllButtons, - String(isActive$1(gButton, menuOpts) ? -1 : menuOpts._index) - ); - drawButtons(gd, gHeader, gButton, scrollBox, menuOpts); - }); - header.on("mouseover", function() { - header.call(styleOnMouseOver); - }); - header.on("mouseout", function() { - header.call(styleOnMouseOut, menuOpts); - }); - Drawing$b.setTranslate(gHeader, dims.lx, dims.ly); -} -function drawButtons(gd, gHeader, gButton, scrollBox, menuOpts) { - if (!gButton) { - gButton = gHeader; - gButton.attr("pointer-events", "all"); - } - var buttonData = !isFolded(gButton) || menuOpts.type === "buttons" ? menuOpts.buttons : []; - var klass = menuOpts.type === "dropdown" ? constants$s.dropdownButtonClassName : constants$s.buttonClassName; - var buttons2 = gButton.selectAll("g." + klass).data(Lib$G.filterVisible(buttonData)); - var enter = buttons2.enter().append("g").classed(klass, true); - var exit = buttons2.exit(); - if (menuOpts.type === "dropdown") { - enter.attr("opacity", "0").transition().attr("opacity", "1"); - exit.transition().attr("opacity", "0").remove(); - } else { - exit.remove(); - } - var x0 = 0; - var y0 = 0; - var dims = menuOpts._dims; - var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; - if (menuOpts.type === "dropdown") { - if (isVertical2) { - y0 = dims.headerHeight + constants$s.gapButtonHeader; - } else { - x0 = dims.headerWidth + constants$s.gapButtonHeader; - } - } - if (menuOpts.type === "dropdown" && menuOpts.direction === "up") { - y0 = -constants$s.gapButtonHeader + constants$s.gapButton - dims.openHeight; - } - if (menuOpts.type === "dropdown" && menuOpts.direction === "left") { - x0 = -constants$s.gapButtonHeader + constants$s.gapButton - dims.openWidth; - } - var posOpts = { - x: dims.lx + x0 + menuOpts.pad.l, - y: dims.ly + y0 + menuOpts.pad.t, - yPad: constants$s.gapButton, - xPad: constants$s.gapButton, - index: 0 - }; - var scrollBoxPosition = { - l: posOpts.x + menuOpts.borderwidth, - t: posOpts.y + menuOpts.borderwidth - }; - buttons2.each(function(buttonOpts, buttonIndex) { - var button = d3$g.select(this); - button.call(drawItem, menuOpts, buttonOpts, gd).call(setItemPosition, menuOpts, posOpts); - button.on("click", function() { - if (d3$g.event.defaultPrevented) return; - if (buttonOpts.execute) { - if (buttonOpts.args2 && menuOpts.active === buttonIndex) { - setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, -1); - Plots$4.executeAPICommand(gd, buttonOpts.method, buttonOpts.args2); - } else { - setActive$1(gd, menuOpts, buttonOpts, gHeader, gButton, scrollBox, buttonIndex); - Plots$4.executeAPICommand(gd, buttonOpts.method, buttonOpts.args); - } - } - gd.emit("plotly_buttonclicked", { menu: menuOpts, button: buttonOpts, active: menuOpts.active }); - }); - button.on("mouseover", function() { - button.call(styleOnMouseOver); - }); - button.on("mouseout", function() { - button.call(styleOnMouseOut, menuOpts); - buttons2.call(styleButtons, menuOpts); - }); - }); - buttons2.call(styleButtons, menuOpts); - if (isVertical2) { - scrollBoxPosition.w = Math.max(dims.openWidth, dims.headerWidth); - scrollBoxPosition.h = posOpts.y - scrollBoxPosition.t; - } else { - scrollBoxPosition.w = posOpts.x - scrollBoxPosition.l; - scrollBoxPosition.h = Math.max(dims.openHeight, dims.headerHeight); - } - scrollBoxPosition.direction = menuOpts.direction; - if (scrollBox) { - if (buttons2.size()) { - drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, scrollBoxPosition); - } else { - hideScrollBox(scrollBox); - } - } -} -function drawScrollBox(gd, gHeader, gButton, scrollBox, menuOpts, position) { - var direction = menuOpts.direction; - var isVertical2 = direction === "up" || direction === "down"; - var dims = menuOpts._dims; - var active = menuOpts.active; - var translateX, translateY; - var i; - if (isVertical2) { - translateY = 0; - for (i = 0; i < active; i++) { - translateY += dims.heights[i] + constants$s.gapButton; - } - } else { - translateX = 0; - for (i = 0; i < active; i++) { - translateX += dims.widths[i] + constants$s.gapButton; - } - } - scrollBox.enable(position, translateX, translateY); - if (scrollBox.hbar) { - scrollBox.hbar.attr("opacity", "0").transition().attr("opacity", "1"); - } - if (scrollBox.vbar) { - scrollBox.vbar.attr("opacity", "0").transition().attr("opacity", "1"); - } -} -function hideScrollBox(scrollBox) { - var hasHBar = !!scrollBox.hbar; - var hasVBar = !!scrollBox.vbar; - if (hasHBar) { - scrollBox.hbar.transition().attr("opacity", "0").each("end", function() { - hasHBar = false; - if (!hasVBar) scrollBox.disable(); - }); - } - if (hasVBar) { - scrollBox.vbar.transition().attr("opacity", "0").each("end", function() { - hasVBar = false; - if (!hasHBar) scrollBox.disable(); - }); - } -} -function drawItem(item, menuOpts, itemOpts, gd) { - item.call(drawItemRect, menuOpts).call(drawItemText, menuOpts, itemOpts, gd); -} -function drawItemRect(item, menuOpts) { - var rect2 = Lib$G.ensureSingle(item, "rect", constants$s.itemRectClassName, function(s) { - s.attr({ - rx: constants$s.rx, - ry: constants$s.ry, - "shape-rendering": "crispEdges" - }); - }); - rect2.call(Color$l.stroke, menuOpts.bordercolor).call(Color$l.fill, menuOpts.bgcolor).style("stroke-width", menuOpts.borderwidth + "px"); -} -function drawItemText(item, menuOpts, itemOpts, gd) { - var text = Lib$G.ensureSingle(item, "text", constants$s.itemTextClassName, function(s) { - s.attr({ - "text-anchor": "start", - "data-notex": 1 - }); - }); - var tx = itemOpts.label; - var _meta = gd._fullLayout._meta; - if (_meta) tx = Lib$G.templateString(tx, _meta); - text.call(Drawing$b.font, menuOpts.font).text(tx).call(svgTextUtils$8.convertToTspans, gd); -} -function styleButtons(buttons2, menuOpts) { - var active = menuOpts.active; - buttons2.each(function(buttonOpts, i) { - var button = d3$g.select(this); - if (i === active && menuOpts.showactive) { - button.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, constants$s.activeColor); - } - }); -} -function styleOnMouseOver(item) { - item.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, constants$s.hoverColor); -} -function styleOnMouseOut(item, menuOpts) { - item.select("rect." + constants$s.itemRectClassName).call(Color$l.fill, menuOpts.bgcolor); -} -function findDimensions$1(gd, menuOpts) { - var dims = menuOpts._dims = { - width1: 0, - height1: 0, - heights: [], - widths: [], - totalWidth: 0, - totalHeight: 0, - openWidth: 0, - openHeight: 0, - lx: 0, - ly: 0 - }; - var fakeButtons = Drawing$b.tester.selectAll("g." + constants$s.dropdownButtonClassName).data(Lib$G.filterVisible(menuOpts.buttons)); - fakeButtons.enter().append("g").classed(constants$s.dropdownButtonClassName, true); - var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; - fakeButtons.each(function(buttonOpts, i) { - var button = d3$g.select(this); - button.call(drawItem, menuOpts, buttonOpts, gd); - var text = button.select("." + constants$s.itemTextClassName); - var tWidth = text.node() && Drawing$b.bBox(text.node()).width; - var wEff = Math.max(tWidth + constants$s.textPadX, constants$s.minWidth); - var tHeight = menuOpts.font.size * LINE_SPACING$4; - var tLines = svgTextUtils$8.lineCount(text); - var hEff = Math.max(tHeight * tLines, constants$s.minHeight) + constants$s.textOffsetY; - hEff = Math.ceil(hEff); - wEff = Math.ceil(wEff); - dims.widths[i] = wEff; - dims.heights[i] = hEff; - dims.height1 = Math.max(dims.height1, hEff); - dims.width1 = Math.max(dims.width1, wEff); - if (isVertical2) { - dims.totalWidth = Math.max(dims.totalWidth, wEff); - dims.openWidth = dims.totalWidth; - dims.totalHeight += hEff + constants$s.gapButton; - dims.openHeight += hEff + constants$s.gapButton; - } else { - dims.totalWidth += wEff + constants$s.gapButton; - dims.openWidth += wEff + constants$s.gapButton; - dims.totalHeight = Math.max(dims.totalHeight, hEff); - dims.openHeight = dims.totalHeight; - } - }); - if (isVertical2) { - dims.totalHeight -= constants$s.gapButton; - } else { - dims.totalWidth -= constants$s.gapButton; - } - dims.headerWidth = dims.width1 + constants$s.arrowPadX; - dims.headerHeight = dims.height1; - if (menuOpts.type === "dropdown") { - if (isVertical2) { - dims.width1 += constants$s.arrowPadX; - dims.totalHeight = dims.height1; - } else { - dims.totalWidth = dims.width1; - } - dims.totalWidth += constants$s.arrowPadX; - } - fakeButtons.remove(); - var paddedWidth = dims.totalWidth + menuOpts.pad.l + menuOpts.pad.r; - var paddedHeight = dims.totalHeight + menuOpts.pad.t + menuOpts.pad.b; - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * menuOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - menuOpts.y); - var xanchor = "left"; - if (Lib$G.isRightAnchor(menuOpts)) { - dims.lx -= paddedWidth; - xanchor = "right"; - } - if (Lib$G.isCenterAnchor(menuOpts)) { - dims.lx -= paddedWidth / 2; - xanchor = "center"; - } - var yanchor = "top"; - if (Lib$G.isBottomAnchor(menuOpts)) { - dims.ly -= paddedHeight; - yanchor = "bottom"; - } - if (Lib$G.isMiddleAnchor(menuOpts)) { - dims.ly -= paddedHeight / 2; - yanchor = "middle"; - } - dims.totalWidth = Math.ceil(dims.totalWidth); - dims.totalHeight = Math.ceil(dims.totalHeight); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); - Plots$4.autoMargin(gd, autoMarginId$1(menuOpts), { - x: menuOpts.x, - y: menuOpts.y, - l: paddedWidth * ({ right: 1, center: 0.5 }[xanchor] || 0), - r: paddedWidth * ({ left: 1, center: 0.5 }[xanchor] || 0), - b: paddedHeight * ({ top: 1, middle: 0.5 }[yanchor] || 0), - t: paddedHeight * ({ bottom: 1, middle: 0.5 }[yanchor] || 0) - }); -} -function autoMarginId$1(menuOpts) { - return constants$s.autoMarginIdRoot + menuOpts._index; -} -function setItemPosition(item, menuOpts, posOpts, overrideOpts) { - overrideOpts = overrideOpts || {}; - var rect2 = item.select("." + constants$s.itemRectClassName); - var text = item.select("." + constants$s.itemTextClassName); - var borderWidth = menuOpts.borderwidth; - var index2 = posOpts.index; - var dims = menuOpts._dims; - Drawing$b.setTranslate(item, borderWidth + posOpts.x, borderWidth + posOpts.y); - var isVertical2 = ["up", "down"].indexOf(menuOpts.direction) !== -1; - var finalHeight = overrideOpts.height || (isVertical2 ? dims.heights[index2] : dims.height1); - rect2.attr({ - x: 0, - y: 0, - width: overrideOpts.width || (isVertical2 ? dims.width1 : dims.widths[index2]), - height: finalHeight - }); - var tHeight = menuOpts.font.size * LINE_SPACING$4; - var tLines = svgTextUtils$8.lineCount(text); - var spanOffset = (tLines - 1) * tHeight / 2; - svgTextUtils$8.positionText( - text, - constants$s.textOffsetX, - finalHeight / 2 - spanOffset + constants$s.textOffsetY - ); - if (isVertical2) { - posOpts.y += dims.heights[index2] + posOpts.yPad; - } else { - posOpts.x += dims.widths[index2] + posOpts.xPad; - } - posOpts.index++; -} -function removeAllButtons(gButton, newMenuIndexAttr) { - gButton.attr(constants$s.menuIndexAttrName, newMenuIndexAttr || "-1").selectAll("g." + constants$s.dropdownButtonClassName).remove(); -} -var constants$r = constants$u; -var updatemenus = { - moduleType: "component", - name: constants$r.name, - layoutAttributes: attributes$n, - supplyLayoutDefaults: defaults$b, - draw: draw$6 -}; -var constants$q = { - // layout attribute name - name: "sliders", - // class names - containerClassName: "slider-container", - groupClassName: "slider-group", - railRectClass: "slider-rail-rect", - railTouchRectClass: "slider-rail-touch-rect", - gripRectClass: "slider-grip-rect", - tickRectClass: "slider-tick-rect", - labelsClass: "slider-labels", - labelGroupClass: "slider-label-group", - labelClass: "slider-label", - // id root pass to Plots.autoMargin - autoMarginIdRoot: "slider-", - railRadius: 2, - railWidth: 5, - railBorderWidth: 1, - railBorderColor: "#bec8d9", - railBgColor: "#f8fafc", - // The distance of the rail from the edge of the touchable area - // Slightly less than the step inset because of the curved edges - // of the rail - railInset: 8, - // The distance from the extremal tick marks to the edge of the - // touchable area. This is basically the same as the grip radius, - // but for other styles it wouldn't really need to be. - stepInset: 10, - gripRadius: 10, - gripWidth: 20, - gripHeight: 20, - gripBgActiveColor: "#dbdde0", - labelPadding: 8, - labelOffset: 0, - tickColor: "#333", - tickOffset: 25, - tickLength: 7, - minorTickOffset: 25, - minorTickLength: 4, - currentValueInset: 0 -}; -var fontAttrs$5 = font_attributes; -var padAttrs = pad_attributes; -var extendDeepAll = extend$5.extendDeepAll; -var overrideAll$2 = edit_types.overrideAll; -var animationAttrs = animation_attributes; -var templatedArray$1 = plot_template.templatedArray; -var constants$p = constants$q; -var stepsAttrs = templatedArray$1("step", { - visible: { - valType: "boolean", - dflt: true, - description: [ - "Determines whether or not this step is included in the slider." - ].join(" ") - }, - method: { - valType: "enumerated", - values: ["restyle", "relayout", "animate", "update", "skip"], - dflt: "restyle", - description: [ - "Sets the Plotly method to be called when the slider value is changed.", - "If the `skip` method is used, the API slider will function as normal", - "but will perform no API calls and will not bind automatically to state", - "updates. This may be used to create a component interface and attach to", - "slider events manually via JavaScript." - ].join(" ") - }, - args: { - valType: "info_array", - freeLength: true, - items: [ - { valType: "any" }, - { valType: "any" }, - { valType: "any" } - ], - description: [ - "Sets the arguments values to be passed to the Plotly", - "method set in `method` on slide." - ].join(" ") - }, - label: { - valType: "string", - description: "Sets the text label to appear on the slider" - }, - value: { - valType: "string", - description: [ - "Sets the value of the slider step, used to refer to the step programatically.", - "Defaults to the slider label if not provided." - ].join(" ") - }, - execute: { - valType: "boolean", - dflt: true, - description: [ - "When true, the API method is executed. When false, all other behaviors are the same", - "and command execution is skipped. This may be useful when hooking into, for example,", - "the `plotly_sliderchange` method and executing the API command manually without losing", - "the benefit of the slider automatically binding to the state of the plot through the", - "specification of `method` and `args`." - ].join(" ") - } -}); -var attributes$l = overrideAll$2(templatedArray$1("slider", { - visible: { - valType: "boolean", - dflt: true, - description: [ - "Determines whether or not the slider is visible." - ].join(" ") - }, - active: { - valType: "number", - min: 0, - dflt: 0, - description: [ - "Determines which button (by index starting from 0) is", - "considered active." - ].join(" ") - }, - steps: stepsAttrs, - lenmode: { - valType: "enumerated", - values: ["fraction", "pixels"], - dflt: "fraction", - description: [ - "Determines whether this slider length", - "is set in units of plot *fraction* or in *pixels.", - "Use `len` to set the value." - ].join(" ") - }, - len: { - valType: "number", - min: 0, - dflt: 1, - description: [ - "Sets the length of the slider", - "This measure excludes the padding of both ends.", - "That is, the slider's length is this length minus the", - "padding on both ends." - ].join(" ") - }, - x: { - valType: "number", - min: -2, - max: 3, - dflt: 0, - description: "Sets the x position (in normalized coordinates) of the slider." - }, - pad: extendDeepAll(padAttrs({ editType: "arraydraw" }), { - description: "Set the padding of the slider component along each side." - }, { t: { dflt: 20 } }), - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "left", - description: [ - "Sets the slider's horizontal position anchor.", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the range selector." - ].join(" ") - }, - y: { - valType: "number", - min: -2, - max: 3, - dflt: 0, - description: "Sets the y position (in normalized coordinates) of the slider." - }, - yanchor: { - valType: "enumerated", - values: ["auto", "top", "middle", "bottom"], - dflt: "top", - description: [ - "Sets the slider's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the range selector." - ].join(" ") - }, - transition: { - duration: { - valType: "number", - min: 0, - dflt: 150, - description: "Sets the duration of the slider transition" - }, - easing: { - valType: "enumerated", - values: animationAttrs.transition.easing.values, - dflt: "cubic-in-out", - description: "Sets the easing function of the slider transition" - } - }, - currentvalue: { - visible: { - valType: "boolean", - dflt: true, - description: [ - "Shows the currently-selected value above the slider." - ].join(" ") - }, - xanchor: { - valType: "enumerated", - values: ["left", "center", "right"], - dflt: "left", - description: [ - "The alignment of the value readout relative to the length of the slider." - ].join(" ") - }, - offset: { - valType: "number", - dflt: 10, - description: [ - "The amount of space, in pixels, between the current value label", - "and the slider." - ].join(" ") - }, - prefix: { - valType: "string", - description: "When currentvalue.visible is true, this sets the prefix of the label." - }, - suffix: { - valType: "string", - description: "When currentvalue.visible is true, this sets the suffix of the label." - }, - font: fontAttrs$5({ - description: "Sets the font of the current value label text." - }) - }, - font: fontAttrs$5({ - description: "Sets the font of the slider step labels." - }), - activebgcolor: { - valType: "color", - dflt: constants$p.gripBgActiveColor, - description: [ - "Sets the background color of the slider grip", - "while dragging." - ].join(" ") - }, - bgcolor: { - valType: "color", - dflt: constants$p.railBgColor, - description: "Sets the background color of the slider." - }, - bordercolor: { - valType: "color", - dflt: constants$p.railBorderColor, - description: "Sets the color of the border enclosing the slider." - }, - borderwidth: { - valType: "number", - min: 0, - dflt: constants$p.railBorderWidth, - description: "Sets the width (in px) of the border enclosing the slider." - }, - ticklen: { - valType: "number", - min: 0, - dflt: constants$p.tickLength, - description: "Sets the length in pixels of step tick marks" - }, - tickcolor: { - valType: "color", - dflt: constants$p.tickColor, - description: "Sets the color of the border enclosing the slider." - }, - tickwidth: { - valType: "number", - min: 0, - dflt: 1, - description: "Sets the tick width (in px)." - }, - minorticklen: { - valType: "number", - min: 0, - dflt: constants$p.minorTickLength, - description: "Sets the length in pixels of minor step tick marks" - } -}), "arraydraw", "from-root"); -var Lib$F = libExports; -var handleArrayContainerDefaults$1 = array_container_defaults; -var attributes$k = attributes$l; -var constants$o = constants$q; -var name$1 = constants$o.name; -var stepAttrs = attributes$k.steps; -var defaults$a = function slidersDefaults(layoutIn, layoutOut) { - handleArrayContainerDefaults$1(layoutIn, layoutOut, { - name: name$1, - handleItemDefaults: sliderDefaults - }); -}; -function sliderDefaults(sliderIn, sliderOut, layoutOut) { - function coerce2(attr, dflt) { - return Lib$F.coerce(sliderIn, sliderOut, attributes$k, attr, dflt); - } - var steps = handleArrayContainerDefaults$1(sliderIn, sliderOut, { - name: "steps", - handleItemDefaults: stepDefaults - }); - var stepCount = 0; - for (var i = 0; i < steps.length; i++) { - if (steps[i].visible) stepCount++; - } - var visible; - if (stepCount < 2) visible = sliderOut.visible = false; - else visible = coerce2("visible"); - if (!visible) return; - sliderOut._stepCount = stepCount; - var visSteps = sliderOut._visibleSteps = Lib$F.filterVisible(steps); - var active = coerce2("active"); - if (!(steps[active] || {}).visible) sliderOut.active = visSteps[0]._index; - coerce2("x"); - coerce2("y"); - Lib$F.noneOrAll(sliderIn, sliderOut, ["x", "y"]); - coerce2("xanchor"); - coerce2("yanchor"); - coerce2("len"); - coerce2("lenmode"); - coerce2("pad.t"); - coerce2("pad.r"); - coerce2("pad.b"); - coerce2("pad.l"); - Lib$F.coerceFont(coerce2, "font", layoutOut.font); - var currentValueIsVisible = coerce2("currentvalue.visible"); - if (currentValueIsVisible) { - coerce2("currentvalue.xanchor"); - coerce2("currentvalue.prefix"); - coerce2("currentvalue.suffix"); - coerce2("currentvalue.offset"); - Lib$F.coerceFont(coerce2, "currentvalue.font", sliderOut.font); - } - coerce2("transition.duration"); - coerce2("transition.easing"); - coerce2("bgcolor"); - coerce2("activebgcolor"); - coerce2("bordercolor"); - coerce2("borderwidth"); - coerce2("ticklen"); - coerce2("tickwidth"); - coerce2("tickcolor"); - coerce2("minorticklen"); -} -function stepDefaults(valueIn, valueOut) { - function coerce2(attr, dflt) { - return Lib$F.coerce(valueIn, valueOut, stepAttrs, attr, dflt); - } - var visible; - if (valueIn.method !== "skip" && !Array.isArray(valueIn.args)) { - visible = valueOut.visible = false; - } else visible = coerce2("visible"); - if (visible) { - coerce2("method"); - coerce2("args"); - var label = coerce2("label", "step-" + valueOut._index); - coerce2("value", label); - coerce2("execute"); - } -} -var d3$f = d3Exports; -var Plots$3 = plotsExports; -var Color$k = colorExports; -var Drawing$a = drawingExports; -var Lib$E = libExports; -var strTranslate$3 = Lib$E.strTranslate; -var svgTextUtils$7 = svg_text_utils; -var arrayEditor = plot_template.arrayEditor; -var constants$n = constants$q; -var alignmentConstants$2 = alignment$1; -var LINE_SPACING$3 = alignmentConstants$2.LINE_SPACING; -var FROM_TL$2 = alignmentConstants$2.FROM_TL; -var FROM_BR$2 = alignmentConstants$2.FROM_BR; -var draw$5 = function draw5(gd) { - var staticPlot = gd._context.staticPlot; - var fullLayout = gd._fullLayout; - var sliderData = makeSliderData(fullLayout, gd); - var sliders2 = fullLayout._infolayer.selectAll("g." + constants$n.containerClassName).data(sliderData.length > 0 ? [0] : []); - sliders2.enter().append("g").classed(constants$n.containerClassName, true).style("cursor", staticPlot ? null : "ew-resize"); - function clearSlider(sliderOpts2) { - if (sliderOpts2._commandObserver) { - sliderOpts2._commandObserver.remove(); - delete sliderOpts2._commandObserver; - } - Plots$3.autoMargin(gd, autoMarginId(sliderOpts2)); - } - sliders2.exit().each(function() { - d3$f.select(this).selectAll("g." + constants$n.groupClassName).each(clearSlider); - }).remove(); - if (sliderData.length === 0) return; - var sliderGroups = sliders2.selectAll("g." + constants$n.groupClassName).data(sliderData, keyFunction); - sliderGroups.enter().append("g").classed(constants$n.groupClassName, true); - sliderGroups.exit().each(clearSlider).remove(); - for (var i = 0; i < sliderData.length; i++) { - var sliderOpts = sliderData[i]; - findDimensions(gd, sliderOpts); - } - sliderGroups.each(function(sliderOpts2) { - var gSlider = d3$f.select(this); - computeLabelSteps(sliderOpts2); - Plots$3.manageCommandObserver(gd, sliderOpts2, sliderOpts2._visibleSteps, function(data) { - var opts = gSlider.data()[0]; - if (opts.active === data.index) return; - if (opts._dragging) return; - setActive(gd, gSlider, opts, data.index, false, true); - }); - drawSlider(gd, d3$f.select(this), sliderOpts2); - }); -}; -function autoMarginId(sliderOpts) { - return constants$n.autoMarginIdRoot + sliderOpts._index; -} -function makeSliderData(fullLayout, gd) { - var contOpts = fullLayout[constants$n.name]; - var sliderData = []; - for (var i = 0; i < contOpts.length; i++) { - var item = contOpts[i]; - if (!item.visible) continue; - item._gd = gd; - sliderData.push(item); - } - return sliderData; -} -function keyFunction(opts) { - return opts._index; -} -function findDimensions(gd, sliderOpts) { - var sliderLabels = Drawing$a.tester.selectAll("g." + constants$n.labelGroupClass).data(sliderOpts._visibleSteps); - sliderLabels.enter().append("g").classed(constants$n.labelGroupClass, true); - var maxLabelWidth = 0; - var labelHeight = 0; - sliderLabels.each(function(stepOpts) { - var labelGroup = d3$f.select(this); - var text = drawLabel2(labelGroup, { step: stepOpts }, sliderOpts); - var textNode = text.node(); - if (textNode) { - var bBox = Drawing$a.bBox(textNode); - labelHeight = Math.max(labelHeight, bBox.height); - maxLabelWidth = Math.max(maxLabelWidth, bBox.width); - } - }); - sliderLabels.remove(); - var dims = sliderOpts._dims = {}; - dims.inputAreaWidth = Math.max( - constants$n.railWidth, - constants$n.gripHeight - ); - var graphSize = gd._fullLayout._size; - dims.lx = graphSize.l + graphSize.w * sliderOpts.x; - dims.ly = graphSize.t + graphSize.h * (1 - sliderOpts.y); - if (sliderOpts.lenmode === "fraction") { - dims.outerLength = Math.round(graphSize.w * sliderOpts.len); - } else { - dims.outerLength = sliderOpts.len; - } - dims.inputAreaStart = 0; - dims.inputAreaLength = Math.round(dims.outerLength - sliderOpts.pad.l - sliderOpts.pad.r); - var textableInputLength = dims.inputAreaLength - 2 * constants$n.stepInset; - var availableSpacePerLabel = textableInputLength / (sliderOpts._stepCount - 1); - var computedSpacePerLabel = maxLabelWidth + constants$n.labelPadding; - dims.labelStride = Math.max(1, Math.ceil(computedSpacePerLabel / availableSpacePerLabel)); - dims.labelHeight = labelHeight; - dims.currentValueMaxWidth = 0; - dims.currentValueHeight = 0; - dims.currentValueTotalHeight = 0; - dims.currentValueMaxLines = 1; - if (sliderOpts.currentvalue.visible) { - var dummyGroup = Drawing$a.tester.append("g"); - sliderLabels.each(function(stepOpts) { - var curValPrefix = drawCurrentValue(dummyGroup, sliderOpts, stepOpts.label); - var curValSize = curValPrefix.node() && Drawing$a.bBox(curValPrefix.node()) || { width: 0, height: 0 }; - var lines = svgTextUtils$7.lineCount(curValPrefix); - dims.currentValueMaxWidth = Math.max(dims.currentValueMaxWidth, Math.ceil(curValSize.width)); - dims.currentValueHeight = Math.max(dims.currentValueHeight, Math.ceil(curValSize.height)); - dims.currentValueMaxLines = Math.max(dims.currentValueMaxLines, lines); - }); - dims.currentValueTotalHeight = dims.currentValueHeight + sliderOpts.currentvalue.offset; - dummyGroup.remove(); - } - dims.height = dims.currentValueTotalHeight + constants$n.tickOffset + sliderOpts.ticklen + constants$n.labelOffset + dims.labelHeight + sliderOpts.pad.t + sliderOpts.pad.b; - var xanchor = "left"; - if (Lib$E.isRightAnchor(sliderOpts)) { - dims.lx -= dims.outerLength; - xanchor = "right"; - } - if (Lib$E.isCenterAnchor(sliderOpts)) { - dims.lx -= dims.outerLength / 2; - xanchor = "center"; - } - var yanchor = "top"; - if (Lib$E.isBottomAnchor(sliderOpts)) { - dims.ly -= dims.height; - yanchor = "bottom"; - } - if (Lib$E.isMiddleAnchor(sliderOpts)) { - dims.ly -= dims.height / 2; - yanchor = "middle"; - } - dims.outerLength = Math.ceil(dims.outerLength); - dims.height = Math.ceil(dims.height); - dims.lx = Math.round(dims.lx); - dims.ly = Math.round(dims.ly); - var marginOpts = { - y: sliderOpts.y, - b: dims.height * FROM_BR$2[yanchor], - t: dims.height * FROM_TL$2[yanchor] - }; - if (sliderOpts.lenmode === "fraction") { - marginOpts.l = 0; - marginOpts.xl = sliderOpts.x - sliderOpts.len * FROM_TL$2[xanchor]; - marginOpts.r = 0; - marginOpts.xr = sliderOpts.x + sliderOpts.len * FROM_BR$2[xanchor]; - } else { - marginOpts.x = sliderOpts.x; - marginOpts.l = dims.outerLength * FROM_TL$2[xanchor]; - marginOpts.r = dims.outerLength * FROM_BR$2[xanchor]; - } - Plots$3.autoMargin(gd, autoMarginId(sliderOpts), marginOpts); -} -function drawSlider(gd, sliderGroup, sliderOpts) { - if (!(sliderOpts.steps[sliderOpts.active] || {}).visible) { - sliderOpts.active = sliderOpts._visibleSteps[0]._index; - } - sliderGroup.call(drawCurrentValue, sliderOpts).call(drawRail, sliderOpts).call(drawLabelGroup, sliderOpts).call(drawTicks, sliderOpts).call(drawTouchRect, gd, sliderOpts).call(drawGrip, gd, sliderOpts); - var dims = sliderOpts._dims; - Drawing$a.setTranslate(sliderGroup, dims.lx + sliderOpts.pad.l, dims.ly + sliderOpts.pad.t); - sliderGroup.call(setGripPosition, sliderOpts, false); - sliderGroup.call(drawCurrentValue, sliderOpts); -} -function drawCurrentValue(sliderGroup, sliderOpts, valueOverride) { - if (!sliderOpts.currentvalue.visible) return; - var dims = sliderOpts._dims; - var x0, textAnchor; - switch (sliderOpts.currentvalue.xanchor) { - case "right": - x0 = dims.inputAreaLength - constants$n.currentValueInset - dims.currentValueMaxWidth; - textAnchor = "left"; - break; - case "center": - x0 = dims.inputAreaLength * 0.5; - textAnchor = "middle"; - break; - default: - x0 = constants$n.currentValueInset; - textAnchor = "left"; - } - var text = Lib$E.ensureSingle(sliderGroup, "text", constants$n.labelClass, function(s) { - s.attr({ - "text-anchor": textAnchor, - "data-notex": 1 - }); - }); - var str2 = sliderOpts.currentvalue.prefix ? sliderOpts.currentvalue.prefix : ""; - if (typeof valueOverride === "string") { - str2 += valueOverride; - } else { - var curVal = sliderOpts.steps[sliderOpts.active].label; - var _meta = sliderOpts._gd._fullLayout._meta; - if (_meta) curVal = Lib$E.templateString(curVal, _meta); - str2 += curVal; - } - if (sliderOpts.currentvalue.suffix) { - str2 += sliderOpts.currentvalue.suffix; - } - text.call(Drawing$a.font, sliderOpts.currentvalue.font).text(str2).call(svgTextUtils$7.convertToTspans, sliderOpts._gd); - var lines = svgTextUtils$7.lineCount(text); - var y0 = (dims.currentValueMaxLines + 1 - lines) * sliderOpts.currentvalue.font.size * LINE_SPACING$3; - svgTextUtils$7.positionText(text, x0, y0); - return text; -} -function drawGrip(sliderGroup, gd, sliderOpts) { - var grip = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.gripRectClass, function(s) { - s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all"); - }); - grip.attr({ - width: constants$n.gripWidth, - height: constants$n.gripHeight, - rx: constants$n.gripRadius, - ry: constants$n.gripRadius - }).call(Color$k.stroke, sliderOpts.bordercolor).call(Color$k.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px"); -} -function drawLabel2(item, data, sliderOpts) { - var text = Lib$E.ensureSingle(item, "text", constants$n.labelClass, function(s) { - s.attr({ - "text-anchor": "middle", - "data-notex": 1 - }); - }); - var tx = data.step.label; - var _meta = sliderOpts._gd._fullLayout._meta; - if (_meta) tx = Lib$E.templateString(tx, _meta); - text.call(Drawing$a.font, sliderOpts.font).text(tx).call(svgTextUtils$7.convertToTspans, sliderOpts._gd); - return text; -} -function drawLabelGroup(sliderGroup, sliderOpts) { - var labels = Lib$E.ensureSingle(sliderGroup, "g", constants$n.labelsClass); - var dims = sliderOpts._dims; - var labelItems = labels.selectAll("g." + constants$n.labelGroupClass).data(dims.labelSteps); - labelItems.enter().append("g").classed(constants$n.labelGroupClass, true); - labelItems.exit().remove(); - labelItems.each(function(d) { - var item = d3$f.select(this); - item.call(drawLabel2, d, sliderOpts); - Drawing$a.setTranslate( - item, - normalizedValueToPosition(sliderOpts, d.fraction), - constants$n.tickOffset + sliderOpts.ticklen + // position is the baseline of the top line of text only, even - // if the label spans multiple lines - sliderOpts.font.size * LINE_SPACING$3 + constants$n.labelOffset + dims.currentValueTotalHeight - ); - }); -} -function handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, doTransition) { - var quantizedPosition = Math.round(normalizedPosition * (sliderOpts._stepCount - 1)); - var quantizedIndex = sliderOpts._visibleSteps[quantizedPosition]._index; - if (quantizedIndex !== sliderOpts.active) { - setActive(gd, sliderGroup, sliderOpts, quantizedIndex, true, doTransition); - } -} -function setActive(gd, sliderGroup, sliderOpts, index2, doCallback, doTransition) { - var previousActive = sliderOpts.active; - sliderOpts.active = index2; - arrayEditor(gd.layout, constants$n.name, sliderOpts).applyUpdate("active", index2); - var step = sliderOpts.steps[sliderOpts.active]; - sliderGroup.call(setGripPosition, sliderOpts, doTransition); - sliderGroup.call(drawCurrentValue, sliderOpts); - gd.emit("plotly_sliderchange", { - slider: sliderOpts, - step: sliderOpts.steps[sliderOpts.active], - interaction: doCallback, - previousActive - }); - if (step && step.method && doCallback) { - if (sliderGroup._nextMethod) { - sliderGroup._nextMethod.step = step; - sliderGroup._nextMethod.doCallback = doCallback; - sliderGroup._nextMethod.doTransition = doTransition; - } else { - sliderGroup._nextMethod = { step, doCallback, doTransition }; - sliderGroup._nextMethodRaf = window.requestAnimationFrame(function() { - var _step = sliderGroup._nextMethod.step; - if (!_step.method) return; - if (_step.execute) { - Plots$3.executeAPICommand(gd, _step.method, _step.args); - } - sliderGroup._nextMethod = null; - sliderGroup._nextMethodRaf = null; - }); - } - } -} -function attachGripEvents(item, gd, sliderGroup) { - if (gd._context.staticPlot) return; - var node = sliderGroup.node(); - var $gd = d3$f.select(gd); - function getSliderOpts() { - return sliderGroup.data()[0]; - } - function mouseDownHandler() { - var sliderOpts = getSliderOpts(); - gd.emit("plotly_sliderstart", { slider: sliderOpts }); - var grip = sliderGroup.select("." + constants$n.gripRectClass); - d3$f.event.stopPropagation(); - d3$f.event.preventDefault(); - grip.call(Color$k.fill, sliderOpts.activebgcolor); - var normalizedPosition = positionToNormalizedValue(sliderOpts, d3$f.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts, normalizedPosition, true); - sliderOpts._dragging = true; - function mouseMoveHandler() { - var sliderOpts2 = getSliderOpts(); - var normalizedPosition2 = positionToNormalizedValue(sliderOpts2, d3$f.mouse(node)[0]); - handleInput(gd, sliderGroup, sliderOpts2, normalizedPosition2, false); - } - $gd.on("mousemove", mouseMoveHandler); - $gd.on("touchmove", mouseMoveHandler); - function mouseUpHandler() { - var sliderOpts2 = getSliderOpts(); - sliderOpts2._dragging = false; - grip.call(Color$k.fill, sliderOpts2.bgcolor); - $gd.on("mouseup", null); - $gd.on("mousemove", null); - $gd.on("touchend", null); - $gd.on("touchmove", null); - gd.emit("plotly_sliderend", { - slider: sliderOpts2, - step: sliderOpts2.steps[sliderOpts2.active] - }); - } - $gd.on("mouseup", mouseUpHandler); - $gd.on("touchend", mouseUpHandler); - } - item.on("mousedown", mouseDownHandler); - item.on("touchstart", mouseDownHandler); -} -function drawTicks(sliderGroup, sliderOpts) { - var tick = sliderGroup.selectAll("rect." + constants$n.tickRectClass).data(sliderOpts._visibleSteps); - var dims = sliderOpts._dims; - tick.enter().append("rect").classed(constants$n.tickRectClass, true); - tick.exit().remove(); - tick.attr({ - width: sliderOpts.tickwidth + "px", - "shape-rendering": "crispEdges" - }); - tick.each(function(d, i) { - var isMajor = i % dims.labelStride === 0; - var item = d3$f.select(this); - item.attr({ height: isMajor ? sliderOpts.ticklen : sliderOpts.minorticklen }).call(Color$k.fill, isMajor ? sliderOpts.tickcolor : sliderOpts.tickcolor); - Drawing$a.setTranslate( - item, - normalizedValueToPosition(sliderOpts, i / (sliderOpts._stepCount - 1)) - 0.5 * sliderOpts.tickwidth, - (isMajor ? constants$n.tickOffset : constants$n.minorTickOffset) + dims.currentValueTotalHeight - ); - }); -} -function computeLabelSteps(sliderOpts) { - var dims = sliderOpts._dims; - dims.labelSteps = []; - var nsteps = sliderOpts._stepCount; - for (var i = 0; i < nsteps; i += dims.labelStride) { - dims.labelSteps.push({ - fraction: i / (nsteps - 1), - step: sliderOpts._visibleSteps[i] - }); - } -} -function setGripPosition(sliderGroup, sliderOpts, doTransition) { - var grip = sliderGroup.select("rect." + constants$n.gripRectClass); - var quantizedIndex = 0; - for (var i = 0; i < sliderOpts._stepCount; i++) { - if (sliderOpts._visibleSteps[i]._index === sliderOpts.active) { - quantizedIndex = i; - break; - } - } - var x = normalizedValueToPosition(sliderOpts, quantizedIndex / (sliderOpts._stepCount - 1)); - if (sliderOpts._invokingCommand) return; - var el = grip; - if (doTransition && sliderOpts.transition.duration > 0) { - el = el.transition().duration(sliderOpts.transition.duration).ease(sliderOpts.transition.easing); - } - el.attr("transform", strTranslate$3(x - constants$n.gripWidth * 0.5, sliderOpts._dims.currentValueTotalHeight)); -} -function normalizedValueToPosition(sliderOpts, normalizedPosition) { - var dims = sliderOpts._dims; - return dims.inputAreaStart + constants$n.stepInset + (dims.inputAreaLength - 2 * constants$n.stepInset) * Math.min(1, Math.max(0, normalizedPosition)); -} -function positionToNormalizedValue(sliderOpts, position) { - var dims = sliderOpts._dims; - return Math.min(1, Math.max(0, (position - constants$n.stepInset - dims.inputAreaStart) / (dims.inputAreaLength - 2 * constants$n.stepInset - 2 * dims.inputAreaStart))); -} -function drawTouchRect(sliderGroup, gd, sliderOpts) { - var dims = sliderOpts._dims; - var rect2 = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.railTouchRectClass, function(s) { - s.call(attachGripEvents, gd, sliderGroup, sliderOpts).style("pointer-events", "all"); - }); - rect2.attr({ - width: dims.inputAreaLength, - height: Math.max(dims.inputAreaWidth, constants$n.tickOffset + sliderOpts.ticklen + dims.labelHeight) - }).call(Color$k.fill, sliderOpts.bgcolor).attr("opacity", 0); - Drawing$a.setTranslate(rect2, 0, dims.currentValueTotalHeight); -} -function drawRail(sliderGroup, sliderOpts) { - var dims = sliderOpts._dims; - var computedLength = dims.inputAreaLength - constants$n.railInset * 2; - var rect2 = Lib$E.ensureSingle(sliderGroup, "rect", constants$n.railRectClass); - rect2.attr({ - width: computedLength, - height: constants$n.railWidth, - rx: constants$n.railRadius, - ry: constants$n.railRadius, - "shape-rendering": "crispEdges" - }).call(Color$k.stroke, sliderOpts.bordercolor).call(Color$k.fill, sliderOpts.bgcolor).style("stroke-width", sliderOpts.borderwidth + "px"); - Drawing$a.setTranslate( - rect2, - constants$n.railInset, - (dims.inputAreaWidth - constants$n.railWidth) * 0.5 + dims.currentValueTotalHeight - ); -} -var constants$m = constants$q; -var sliders = { - moduleType: "component", - name: constants$m.name, - layoutAttributes: attributes$l, - supplyLayoutDefaults: defaults$a, - draw: draw$5 -}; -var colorAttributes = attributes$N; -var attributes$j = { - bgcolor: { - valType: "color", - dflt: colorAttributes.background, - editType: "plot", - description: "Sets the background color of the range slider." - }, - bordercolor: { - valType: "color", - dflt: colorAttributes.defaultLine, - editType: "plot", - description: "Sets the border color of the range slider." - }, - borderwidth: { - valType: "integer", - dflt: 0, - min: 0, - editType: "plot", - description: "Sets the border width of the range slider." - }, - autorange: { - valType: "boolean", - dflt: true, - editType: "calc", - impliedEdits: { "range[0]": void 0, "range[1]": void 0 }, - description: [ - "Determines whether or not the range slider range is", - "computed in relation to the input data.", - "If `range` is provided, then `autorange` is set to *false*." - ].join(" ") - }, - range: { - valType: "info_array", - items: [ - { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } }, - { valType: "any", editType: "calc", impliedEdits: { "^autorange": false } } - ], - editType: "calc", - impliedEdits: { autorange: false }, - description: [ - "Sets the range of the range slider.", - "If not set, defaults to the full xaxis range.", - "If the axis `type` is *log*, then you must take the", - "log of your desired range.", - "If the axis `type` is *date*, it should be date strings,", - "like date data, though Date objects and unix milliseconds", - "will be accepted and converted to strings.", - "If the axis `type` is *category*, it should be numbers,", - "using the scale where each category is assigned a serial", - "number from zero in the order it appears." - ].join(" ") - }, - thickness: { - valType: "number", - dflt: 0.15, - min: 0, - max: 1, - editType: "plot", - description: [ - "The height of the range slider as a fraction of the", - "total plot area height." - ].join(" ") - }, - visible: { - valType: "boolean", - dflt: true, - editType: "calc", - description: [ - "Determines whether or not the range slider will be visible.", - "If visible, perpendicular axes will be set to `fixedrange`" - ].join(" ") - }, - editType: "calc" -}; -var oppaxis_attributes = { - // not really a 'subplot' attribute container, - // but this is the flag we use to denote attributes that - // support yaxis, yaxis2, yaxis3, ... counters - _isSubplotObj: true, - rangemode: { - valType: "enumerated", - values: ["auto", "fixed", "match"], - dflt: "match", - editType: "calc", - description: [ - "Determines whether or not the range of this axis in", - "the rangeslider use the same value than in the main plot", - "when zooming in/out.", - "If *auto*, the autorange will be used.", - "If *fixed*, the `range` is used.", - "If *match*, the current range of the corresponding y-axis on the main subplot is used." - ].join(" ") - }, - range: { - valType: "info_array", - items: [ - { valType: "any", editType: "plot" }, - { valType: "any", editType: "plot" } - ], - editType: "plot", - description: [ - "Sets the range of this axis for the rangeslider." - ].join(" ") - }, - editType: "calc" -}; -var helpers$h = {}; -var constants$l = { - // attribute container name - name: "rangeslider", - // class names - containerClassName: "rangeslider-container", - bgClassName: "rangeslider-bg", - rangePlotClassName: "rangeslider-rangeplot", - maskMinClassName: "rangeslider-mask-min", - maskMaxClassName: "rangeslider-mask-max", - slideBoxClassName: "rangeslider-slidebox", - grabberMinClassName: "rangeslider-grabber-min", - grabAreaMinClassName: "rangeslider-grabarea-min", - handleMinClassName: "rangeslider-handle-min", - grabberMaxClassName: "rangeslider-grabber-max", - grabAreaMaxClassName: "rangeslider-grabarea-max", - handleMaxClassName: "rangeslider-handle-max", - maskMinOppAxisClassName: "rangeslider-mask-min-opp-axis", - maskMaxOppAxisClassName: "rangeslider-mask-max-opp-axis", - // style constants - maskColor: "rgba(0,0,0,0.4)", - maskOppAxisColor: "rgba(0,0,0,0.2)", - slideBoxFill: "transparent", - slideBoxCursor: "ew-resize", - grabAreaFill: "transparent", - grabAreaCursor: "col-resize", - grabAreaWidth: 10, - handleWidth: 4, - handleRadius: 1, - handleStrokeWidth: 1, - extraPad: 15 -}; -var axisIDs = axis_ids; -var svgTextUtils$6 = svg_text_utils; -var constants$k = constants$l; -var LINE_SPACING$2 = alignment$1.LINE_SPACING; -var name = constants$k.name; -function isVisible(ax) { - var rangeSlider = ax && ax[name]; - return rangeSlider && rangeSlider.visible; -} -helpers$h.isVisible = isVisible; -helpers$h.makeData = function(fullLayout) { - var axes2 = axisIDs.list({ _fullLayout: fullLayout }, "x", true); - var margin = fullLayout.margin; - var rangeSliderData = []; - if (!fullLayout._has("gl2d")) { - for (var i = 0; i < axes2.length; i++) { - var ax = axes2[i]; - if (isVisible(ax)) { - rangeSliderData.push(ax); - var opts = ax[name]; - opts._id = name + ax._id; - opts._height = (fullLayout.height - margin.b - margin.t) * opts.thickness; - opts._offsetShift = Math.floor(opts.borderwidth / 2); - } - } - } - fullLayout._rangeSliderData = rangeSliderData; -}; -helpers$h.autoMarginOpts = function(gd, ax) { - var fullLayout = gd._fullLayout; - var opts = ax[name]; - var axLetter = ax._id.charAt(0); - var bottomDepth = 0; - var titleHeight = 0; - if (ax.side === "bottom") { - bottomDepth = ax._depth; - if (ax.title.text !== fullLayout._dfltTitle[axLetter]) { - titleHeight = 1.5 * ax.title.font.size + 10 + opts._offsetShift; - var extraLines = (ax.title.text.match(svgTextUtils$6.BR_TAG_ALL) || []).length; - titleHeight += extraLines * ax.title.font.size * LINE_SPACING$2; - } - } - return { - x: 0, - y: ax._counterDomainMin, - l: 0, - r: 0, - t: 0, - b: opts._height + bottomDepth + Math.max(fullLayout.margin.b, titleHeight), - pad: constants$k.extraPad + opts._offsetShift * 2 - }; -}; -var defaults$9; -var hasRequiredDefaults$1; -function requireDefaults$1() { - if (hasRequiredDefaults$1) return defaults$9; - hasRequiredDefaults$1 = 1; - var Lib2 = libExports; - var Template2 = plot_template; - var axisIds2 = axis_ids; - var attributes2 = attributes$j; - var oppAxisAttrs2 = oppaxis_attributes; - defaults$9 = function handleDefaults3(layoutIn, layoutOut, axName) { - var axIn = layoutIn[axName]; - var axOut = layoutOut[axName]; - if (!(axIn.rangeslider || layoutOut._requestRangeslider[axOut._id])) return; - if (!Lib2.isPlainObject(axIn.rangeslider)) { - axIn.rangeslider = {}; - } - var containerIn = axIn.rangeslider; - var containerOut = Template2.newContainer(axOut, "rangeslider"); - function coerce2(attr, dflt) { - return Lib2.coerce(containerIn, containerOut, attributes2, attr, dflt); - } - var rangeContainerIn, rangeContainerOut; - function coerceRange(attr, dflt) { - return Lib2.coerce(rangeContainerIn, rangeContainerOut, oppAxisAttrs2, attr, dflt); - } - var visible = coerce2("visible"); - if (!visible) return; - coerce2("bgcolor", layoutOut.plot_bgcolor); - coerce2("bordercolor"); - coerce2("borderwidth"); - coerce2("thickness"); - coerce2("autorange", !axOut.isValidRange(containerIn.range)); - coerce2("range"); - var subplots = layoutOut._subplots; - if (subplots) { - var yIds = subplots.cartesian.filter(function(subplotId) { - return subplotId.substr(0, subplotId.indexOf("y")) === axisIds2.name2id(axName); - }).map(function(subplotId) { - return subplotId.substr(subplotId.indexOf("y"), subplotId.length); - }); - var yNames = Lib2.simpleMap(yIds, axisIds2.id2name); - for (var i = 0; i < yNames.length; i++) { - var yName = yNames[i]; - rangeContainerIn = containerIn[yName] || {}; - rangeContainerOut = Template2.newContainer(containerOut, yName, "yaxis"); - var yAxOut = layoutOut[yName]; - var rangemodeDflt; - if (rangeContainerIn.range && yAxOut.isValidRange(rangeContainerIn.range)) { - rangemodeDflt = "fixed"; - } - var rangeMode = coerceRange("rangemode", rangemodeDflt); - if (rangeMode !== "match") { - coerceRange("range", yAxOut.range.slice()); - } - } - } - containerOut._input = containerIn; - }; - return defaults$9; -} -var calc_autorange; -var hasRequiredCalc_autorange; -function requireCalc_autorange() { - if (hasRequiredCalc_autorange) return calc_autorange; - hasRequiredCalc_autorange = 1; - var listAxes = axis_ids.list; - var getAutoRange2 = autorange$2.getAutoRange; - var constants2 = constants$l; - calc_autorange = function calcAutorange3(gd) { - var axes2 = listAxes(gd, "x", true); - for (var i = 0; i < axes2.length; i++) { - var ax = axes2[i]; - var opts = ax[constants2.name]; - if (opts && opts.visible && opts.autorange) { - opts._input.autorange = true; - opts._input.range = opts.range = getAutoRange2(gd, ax); - } - } - }; - return calc_autorange; -} -var draw$4; -var hasRequiredDraw; -function requireDraw() { - if (hasRequiredDraw) return draw$4; - hasRequiredDraw = 1; - var d32 = d3Exports; - var Registry2 = registry; - var Plots2 = plotsExports; - var Lib2 = libExports; - var strTranslate2 = Lib2.strTranslate; - var Drawing2 = drawingExports; - var Color2 = colorExports; - var Titles2 = titles; - var Cartesian = cartesian; - var axisIDs2 = axis_ids; - var dragElement2 = dragelementExports; - var setCursor3 = setcursor; - var constants2 = constants$l; - draw$4 = function(gd) { - var fullLayout = gd._fullLayout; - var rangeSliderData = fullLayout._rangeSliderData; - for (var i = 0; i < rangeSliderData.length; i++) { - var opts = rangeSliderData[i][constants2.name]; - opts._clipId = opts._id + "-" + fullLayout._uid; - } - function keyFunction2(axisOpts) { - return axisOpts._name; - } - var rangeSliders = fullLayout._infolayer.selectAll("g." + constants2.containerClassName).data(rangeSliderData, keyFunction2); - rangeSliders.exit().each(function(axisOpts) { - var opts2 = axisOpts[constants2.name]; - fullLayout._topdefs.select("#" + opts2._clipId).remove(); - }).remove(); - if (rangeSliderData.length === 0) return; - rangeSliders.enter().append("g").classed(constants2.containerClassName, true).attr("pointer-events", "all"); - rangeSliders.each(function(axisOpts) { - var rangeSlider = d32.select(this); - var opts2 = axisOpts[constants2.name]; - var oppAxisOpts = fullLayout[axisIDs2.id2name(axisOpts.anchor)]; - var oppAxisRangeOpts = opts2[axisIDs2.id2name(axisOpts.anchor)]; - if (opts2.range) { - var rng = Lib2.simpleMap(opts2.range, axisOpts.r2l); - var axRng = Lib2.simpleMap(axisOpts.range, axisOpts.r2l); - var newRng; - if (axRng[0] < axRng[1]) { - newRng = [ - Math.min(rng[0], axRng[0]), - Math.max(rng[1], axRng[1]) - ]; - } else { - newRng = [ - Math.max(rng[0], axRng[0]), - Math.min(rng[1], axRng[1]) - ]; - } - opts2.range = opts2._input.range = Lib2.simpleMap(newRng, axisOpts.l2r); - } - axisOpts.cleanRange("rangeslider.range"); - var gs = fullLayout._size; - var domain2 = axisOpts.domain; - opts2._width = gs.w * (domain2[1] - domain2[0]); - var x = Math.round(gs.l + gs.w * domain2[0]); - var y = Math.round( - gs.t + gs.h * (1 - axisOpts._counterDomainMin) + (axisOpts.side === "bottom" ? axisOpts._depth : 0) + opts2._offsetShift + constants2.extraPad - ); - rangeSlider.attr("transform", strTranslate2(x, y)); - opts2._rl = Lib2.simpleMap(opts2.range, axisOpts.r2l); - var rl0 = opts2._rl[0]; - var rl1 = opts2._rl[1]; - var drl = rl1 - rl0; - opts2.p2d = function(v) { - return v / opts2._width * drl + rl0; - }; - opts2.d2p = function(v) { - return (v - rl0) / drl * opts2._width; - }; - if (axisOpts.rangebreaks) { - var rsBreaks = axisOpts.locateBreaks(rl0, rl1); - if (rsBreaks.length) { - var j, brk; - var lBreaks = 0; - for (j = 0; j < rsBreaks.length; j++) { - brk = rsBreaks[j]; - lBreaks += brk.max - brk.min; - } - var m2 = opts2._width / (rl1 - rl0 - lBreaks); - var _B = [-m2 * rl0]; - for (j = 0; j < rsBreaks.length; j++) { - brk = rsBreaks[j]; - _B.push(_B[_B.length - 1] - m2 * (brk.max - brk.min)); - } - opts2.d2p = function(v) { - var b = _B[0]; - for (var j2 = 0; j2 < rsBreaks.length; j2++) { - var brk2 = rsBreaks[j2]; - if (v >= brk2.max) b = _B[j2 + 1]; - else if (v < brk2.min) break; - } - return b + m2 * v; - }; - for (j = 0; j < rsBreaks.length; j++) { - brk = rsBreaks[j]; - brk.pmin = opts2.d2p(brk.min); - brk.pmax = opts2.d2p(brk.max); - } - opts2.p2d = function(v) { - var b = _B[0]; - for (var j2 = 0; j2 < rsBreaks.length; j2++) { - var brk2 = rsBreaks[j2]; - if (v >= brk2.pmax) b = _B[j2 + 1]; - else if (v < brk2.pmin) break; - } - return (v - b) / m2; - }; - } - } - if (oppAxisRangeOpts.rangemode !== "match") { - var range0OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[0]); - var range1OppAxis = oppAxisOpts.r2l(oppAxisRangeOpts.range[1]); - var distOppAxis = range1OppAxis - range0OppAxis; - opts2.d2pOppAxis = function(v) { - return (v - range0OppAxis) / distOppAxis * opts2._height; - }; - } - rangeSlider.call(drawBg, gd, axisOpts, opts2).call(addClipPath, gd, axisOpts, opts2).call(drawRangePlot, gd, axisOpts, opts2).call(drawMasks, gd, axisOpts, opts2, oppAxisRangeOpts).call(drawSlideBox, gd, axisOpts, opts2).call(drawGrabbers, gd, axisOpts, opts2); - setupDragElement2(rangeSlider, gd, axisOpts, opts2); - setPixelRange(rangeSlider, gd, axisOpts, opts2, oppAxisOpts, oppAxisRangeOpts); - if (axisOpts.side === "bottom") { - Titles2.draw(gd, axisOpts._id + "title", { - propContainer: axisOpts, - propName: axisOpts._name + ".title", - placeholder: fullLayout._dfltTitle.x, - attributes: { - x: axisOpts._offset + axisOpts._length / 2, - y: y + opts2._height + opts2._offsetShift + 10 + 1.5 * axisOpts.title.font.size, - "text-anchor": "middle" - } - }); - } - }); - }; - function eventX(event) { - if (typeof event.clientX === "number") { - return event.clientX; - } - if (event.touches && event.touches.length > 0) { - return event.touches[0].clientX; - } - return 0; - } - function setupDragElement2(rangeSlider, gd, axisOpts, opts) { - if (gd._context.staticPlot) return; - var slideBox = rangeSlider.select("rect." + constants2.slideBoxClassName).node(); - var grabAreaMin = rangeSlider.select("rect." + constants2.grabAreaMinClassName).node(); - var grabAreaMax = rangeSlider.select("rect." + constants2.grabAreaMaxClassName).node(); - function mouseDownHandler() { - var event = d32.event; - var target = event.target; - var startX = eventX(event); - var offsetX = startX - rangeSlider.node().getBoundingClientRect().left; - var minVal = opts.d2p(axisOpts._rl[0]); - var maxVal = opts.d2p(axisOpts._rl[1]); - var dragCover = dragElement2.coverSlip(); - this.addEventListener("touchmove", mouseMove); - this.addEventListener("touchend", mouseUp); - dragCover.addEventListener("mousemove", mouseMove); - dragCover.addEventListener("mouseup", mouseUp); - function mouseMove(e) { - var clientX = eventX(e); - var delta2 = +clientX - startX; - var pixelMin, pixelMax, cursor2; - switch (target) { - case slideBox: - cursor2 = "ew-resize"; - if (minVal + delta2 > axisOpts._length || maxVal + delta2 < 0) { - return; - } - pixelMin = minVal + delta2; - pixelMax = maxVal + delta2; - break; - case grabAreaMin: - cursor2 = "col-resize"; - if (minVal + delta2 > axisOpts._length) { - return; - } - pixelMin = minVal + delta2; - pixelMax = maxVal; - break; - case grabAreaMax: - cursor2 = "col-resize"; - if (maxVal + delta2 < 0) { - return; - } - pixelMin = minVal; - pixelMax = maxVal + delta2; - break; - default: - cursor2 = "ew-resize"; - pixelMin = offsetX; - pixelMax = offsetX + delta2; - break; - } - if (pixelMax < pixelMin) { - var tmp = pixelMax; - pixelMax = pixelMin; - pixelMin = tmp; - } - opts._pixelMin = pixelMin; - opts._pixelMax = pixelMax; - setCursor3(d32.select(dragCover), cursor2); - setDataRange(rangeSlider, gd, axisOpts, opts); - } - function mouseUp() { - dragCover.removeEventListener("mousemove", mouseMove); - dragCover.removeEventListener("mouseup", mouseUp); - this.removeEventListener("touchmove", mouseMove); - this.removeEventListener("touchend", mouseUp); - Lib2.removeElement(dragCover); - } - } - rangeSlider.on("mousedown", mouseDownHandler); - rangeSlider.on("touchstart", mouseDownHandler); - } - function setDataRange(rangeSlider, gd, axisOpts, opts) { - function clamp2(v) { - return axisOpts.l2r(Lib2.constrain(v, opts._rl[0], opts._rl[1])); - } - var dataMin = clamp2(opts.p2d(opts._pixelMin)); - var dataMax = clamp2(opts.p2d(opts._pixelMax)); - window.requestAnimationFrame(function() { - Registry2.call("_guiRelayout", gd, axisOpts._name + ".range", [dataMin, dataMax]); - }); - } - function setPixelRange(rangeSlider, gd, axisOpts, opts, oppAxisOpts, oppAxisRangeOpts) { - var hw2 = constants2.handleWidth / 2; - function clamp2(v) { - return Lib2.constrain(v, 0, opts._width); - } - function clampOppAxis(v) { - return Lib2.constrain(v, 0, opts._height); - } - function clampHandle(v) { - return Lib2.constrain(v, -hw2, opts._width + hw2); - } - var pixelMin = clamp2(opts.d2p(axisOpts._rl[0])); - var pixelMax = clamp2(opts.d2p(axisOpts._rl[1])); - rangeSlider.select("rect." + constants2.slideBoxClassName).attr("x", pixelMin).attr("width", pixelMax - pixelMin); - rangeSlider.select("rect." + constants2.maskMinClassName).attr("width", pixelMin); - rangeSlider.select("rect." + constants2.maskMaxClassName).attr("x", pixelMax).attr("width", opts._width - pixelMax); - if (oppAxisRangeOpts.rangemode !== "match") { - var pixelMinOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[1])); - var pixelMaxOppAxis = opts._height - clampOppAxis(opts.d2pOppAxis(oppAxisOpts._rl[0])); - rangeSlider.select("rect." + constants2.maskMinOppAxisClassName).attr("x", pixelMin).attr("height", pixelMinOppAxis).attr("width", pixelMax - pixelMin); - rangeSlider.select("rect." + constants2.maskMaxOppAxisClassName).attr("x", pixelMin).attr("y", pixelMaxOppAxis).attr("height", opts._height - pixelMaxOppAxis).attr("width", pixelMax - pixelMin); - rangeSlider.select("rect." + constants2.slideBoxClassName).attr("y", pixelMinOppAxis).attr("height", pixelMaxOppAxis - pixelMinOppAxis); - } - var offset = 0.5; - var xMin = Math.round(clampHandle(pixelMin - hw2)) - offset; - var xMax = Math.round(clampHandle(pixelMax - hw2)) + offset; - rangeSlider.select("g." + constants2.grabberMinClassName).attr("transform", strTranslate2(xMin, offset)); - rangeSlider.select("g." + constants2.grabberMaxClassName).attr("transform", strTranslate2(xMax, offset)); - } - function drawBg(rangeSlider, gd, axisOpts, opts) { - var bg = Lib2.ensureSingle(rangeSlider, "rect", constants2.bgClassName, function(s) { - s.attr({ - x: 0, - y: 0, - "shape-rendering": "crispEdges" - }); - }); - var borderCorrect = opts.borderwidth % 2 === 0 ? opts.borderwidth : opts.borderwidth - 1; - var offsetShift = -opts._offsetShift; - var lw = Drawing2.crispRound(gd, opts.borderwidth); - bg.attr({ - width: opts._width + borderCorrect, - height: opts._height + borderCorrect, - transform: strTranslate2(offsetShift, offsetShift), - "stroke-width": lw - }).call(Color2.stroke, opts.bordercolor).call(Color2.fill, opts.bgcolor); - } - function addClipPath(rangeSlider, gd, axisOpts, opts) { - var fullLayout = gd._fullLayout; - var clipPath = Lib2.ensureSingleById(fullLayout._topdefs, "clipPath", opts._clipId, function(s) { - s.append("rect").attr({ x: 0, y: 0 }); - }); - clipPath.select("rect").attr({ - width: opts._width, - height: opts._height - }); - } - function drawRangePlot(rangeSlider, gd, axisOpts, opts) { - var calcData = gd.calcdata; - var rangePlots = rangeSlider.selectAll("g." + constants2.rangePlotClassName).data(axisOpts._subplotsWith, Lib2.identity); - rangePlots.enter().append("g").attr("class", function(id) { - return constants2.rangePlotClassName + " " + id; - }).call(Drawing2.setClipUrl, opts._clipId, gd); - rangePlots.order(); - rangePlots.exit().remove(); - var mainplotinfo; - rangePlots.each(function(id, i) { - var plotgroup = d32.select(this); - var isMainPlot = i === 0; - var oppAxisOpts = axisIDs2.getFromId(gd, id, "y"); - var oppAxisName = oppAxisOpts._name; - var oppAxisRangeOpts = opts[oppAxisName]; - var mockFigure = { - data: [], - layout: { - xaxis: { - type: axisOpts.type, - domain: [0, 1], - range: opts.range.slice(), - calendar: axisOpts.calendar - }, - width: opts._width, - height: opts._height, - margin: { t: 0, b: 0, l: 0, r: 0 } - }, - _context: gd._context - }; - if (axisOpts.rangebreaks) { - mockFigure.layout.xaxis.rangebreaks = axisOpts.rangebreaks; - } - mockFigure.layout[oppAxisName] = { - type: oppAxisOpts.type, - domain: [0, 1], - range: oppAxisRangeOpts.rangemode !== "match" ? oppAxisRangeOpts.range.slice() : oppAxisOpts.range.slice(), - calendar: oppAxisOpts.calendar - }; - if (oppAxisOpts.rangebreaks) { - mockFigure.layout[oppAxisName].rangebreaks = oppAxisOpts.rangebreaks; - } - Plots2.supplyDefaults(mockFigure); - var xa = mockFigure._fullLayout.xaxis; - var ya = mockFigure._fullLayout[oppAxisName]; - xa.clearCalc(); - xa.setScale(); - ya.clearCalc(); - ya.setScale(); - var plotinfo = { - id, - plotgroup, - xaxis: xa, - yaxis: ya, - isRangePlot: true - }; - if (isMainPlot) mainplotinfo = plotinfo; - else { - plotinfo.mainplot = "xy"; - plotinfo.mainplotinfo = mainplotinfo; - } - Cartesian.rangePlot(gd, plotinfo, filterRangePlotCalcData(calcData, id)); - }); - } - function filterRangePlotCalcData(calcData, subplotId) { - var out = []; - for (var i = 0; i < calcData.length; i++) { - var calcTrace = calcData[i]; - var trace = calcTrace[0].trace; - if (trace.xaxis + trace.yaxis === subplotId) { - out.push(calcTrace); - } - } - return out; - } - function drawMasks(rangeSlider, gd, axisOpts, opts, oppAxisRangeOpts) { - var maskMin = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMinClassName, function(s) { - s.attr({ - x: 0, - y: 0, - "shape-rendering": "crispEdges" - }); - }); - maskMin.attr("height", opts._height).call(Color2.fill, constants2.maskColor); - var maskMax = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMaxClassName, function(s) { - s.attr({ - y: 0, - "shape-rendering": "crispEdges" - }); - }); - maskMax.attr("height", opts._height).call(Color2.fill, constants2.maskColor); - if (oppAxisRangeOpts.rangemode !== "match") { - var maskMinOppAxis = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMinOppAxisClassName, function(s) { - s.attr({ - y: 0, - "shape-rendering": "crispEdges" - }); - }); - maskMinOppAxis.attr("width", opts._width).call(Color2.fill, constants2.maskOppAxisColor); - var maskMaxOppAxis = Lib2.ensureSingle(rangeSlider, "rect", constants2.maskMaxOppAxisClassName, function(s) { - s.attr({ - y: 0, - "shape-rendering": "crispEdges" - }); - }); - maskMaxOppAxis.attr("width", opts._width).style("border-top", constants2.maskOppBorder).call(Color2.fill, constants2.maskOppAxisColor); - } - } - function drawSlideBox(rangeSlider, gd, axisOpts, opts) { - if (gd._context.staticPlot) return; - var slideBox = Lib2.ensureSingle(rangeSlider, "rect", constants2.slideBoxClassName, function(s) { - s.attr({ - y: 0, - cursor: constants2.slideBoxCursor, - "shape-rendering": "crispEdges" - }); - }); - slideBox.attr({ - height: opts._height, - fill: constants2.slideBoxFill - }); - } - function drawGrabbers(rangeSlider, gd, axisOpts, opts) { - var grabberMin = Lib2.ensureSingle(rangeSlider, "g", constants2.grabberMinClassName); - var grabberMax = Lib2.ensureSingle(rangeSlider, "g", constants2.grabberMaxClassName); - var handleFixAttrs = { - x: 0, - width: constants2.handleWidth, - rx: constants2.handleRadius, - fill: Color2.background, - stroke: Color2.defaultLine, - "stroke-width": constants2.handleStrokeWidth, - "shape-rendering": "crispEdges" - }; - var handleDynamicAttrs = { - y: Math.round(opts._height / 4), - height: Math.round(opts._height / 2) - }; - var handleMin = Lib2.ensureSingle(grabberMin, "rect", constants2.handleMinClassName, function(s) { - s.attr(handleFixAttrs); - }); - handleMin.attr(handleDynamicAttrs); - var handleMax = Lib2.ensureSingle(grabberMax, "rect", constants2.handleMaxClassName, function(s) { - s.attr(handleFixAttrs); - }); - handleMax.attr(handleDynamicAttrs); - var grabAreaFixAttrs = { - width: constants2.grabAreaWidth, - x: 0, - y: 0, - fill: constants2.grabAreaFill, - cursor: !gd._context.staticPlot ? constants2.grabAreaCursor : void 0 - }; - var grabAreaMin = Lib2.ensureSingle(grabberMin, "rect", constants2.grabAreaMinClassName, function(s) { - s.attr(grabAreaFixAttrs); - }); - grabAreaMin.attr("height", opts._height); - var grabAreaMax = Lib2.ensureSingle(grabberMax, "rect", constants2.grabAreaMaxClassName, function(s) { - s.attr(grabAreaFixAttrs); - }); - grabAreaMax.attr("height", opts._height); - } - return draw$4; -} -var Lib$D = libExports; -var attrs$1 = attributes$j; -var oppAxisAttrs = oppaxis_attributes; -var helpers$g = helpers$h; -var rangeslider = { - moduleType: "component", - name: "rangeslider", - schema: { - subplots: { - xaxis: { - rangeslider: Lib$D.extendFlat({}, attrs$1, { - yaxis: oppAxisAttrs - }) - } - } - }, - layoutAttributes: attributes$j, - handleDefaults: requireDefaults$1(), - calcAutorange: requireCalc_autorange(), - draw: requireDraw(), - isVisible: helpers$g.isVisible, - makeData: helpers$g.makeData, - autoMarginOpts: helpers$g.autoMarginOpts -}; -var fontAttrs$4 = font_attributes; -var colorAttrs$1 = attributes$N; -var templatedArray = plot_template.templatedArray; -var buttonAttrs = templatedArray("button", { - visible: { - valType: "boolean", - dflt: true, - editType: "plot", - description: "Determines whether or not this button is visible." - }, - step: { - valType: "enumerated", - values: ["month", "year", "day", "hour", "minute", "second", "all"], - dflt: "month", - editType: "plot", - description: [ - "The unit of measurement that the `count` value will set the range by." - ].join(" ") - }, - stepmode: { - valType: "enumerated", - values: ["backward", "todate"], - dflt: "backward", - editType: "plot", - description: [ - "Sets the range update mode.", - "If *backward*, the range update shifts the start of range", - "back *count* times *step* milliseconds.", - "If *todate*, the range update shifts the start of range", - "back to the first timestamp from *count* times", - "*step* milliseconds back.", - "For example, with `step` set to *year* and `count` set to *1*", - "the range update shifts the start of the range back to", - "January 01 of the current year.", - "Month and year *todate* are currently available only", - "for the built-in (Gregorian) calendar." - ].join(" ") - }, - count: { - valType: "number", - min: 0, - dflt: 1, - editType: "plot", - description: [ - "Sets the number of steps to take to update the range.", - "Use with `step` to specify the update interval." - ].join(" ") - }, - label: { - valType: "string", - editType: "plot", - description: "Sets the text label to appear on the button." - }, - editType: "plot", - description: [ - "Sets the specifications for each buttons.", - "By default, a range selector comes with no buttons." - ].join(" ") -}); -var attributes$i = { - visible: { - valType: "boolean", - editType: "plot", - description: [ - "Determines whether or not this range selector is visible.", - "Note that range selectors are only available for x axes of", - "`type` set to or auto-typed to *date*." - ].join(" ") - }, - buttons: buttonAttrs, - x: { - valType: "number", - min: -2, - max: 3, - editType: "plot", - description: "Sets the x position (in normalized coordinates) of the range selector." - }, - xanchor: { - valType: "enumerated", - values: ["auto", "left", "center", "right"], - dflt: "left", - editType: "plot", - description: [ - "Sets the range selector's horizontal position anchor.", - "This anchor binds the `x` position to the *left*, *center*", - "or *right* of the range selector." - ].join(" ") - }, - y: { - valType: "number", - min: -2, - max: 3, - editType: "plot", - description: "Sets the y position (in normalized coordinates) of the range selector." - }, - yanchor: { - valType: "enumerated", - values: ["auto", "top", "middle", "bottom"], - dflt: "bottom", - editType: "plot", - description: [ - "Sets the range selector's vertical position anchor", - "This anchor binds the `y` position to the *top*, *middle*", - "or *bottom* of the range selector." - ].join(" ") - }, - font: fontAttrs$4({ - editType: "plot", - description: "Sets the font of the range selector button text." - }), - bgcolor: { - valType: "color", - dflt: colorAttrs$1.lightLine, - editType: "plot", - description: "Sets the background color of the range selector buttons." - }, - activecolor: { - valType: "color", - editType: "plot", - description: "Sets the background color of the active range selector button." - }, - bordercolor: { - valType: "color", - dflt: colorAttrs$1.defaultLine, - editType: "plot", - description: "Sets the color of the border enclosing the range selector." - }, - borderwidth: { - valType: "number", - min: 0, - dflt: 0, - editType: "plot", - description: "Sets the width (in px) of the border enclosing the range selector." - }, - editType: "plot" -}; -var constants$j = { - // 'y' position pad above counter axis domain - yPad: 0.02, - // minimum button width (regardless of text size) - minButtonWidth: 30, - // buttons rect radii - rx: 3, - ry: 3, - // light fraction used to compute the 'activecolor' default - lightAmount: 25, - darkAmount: 10 -}; -var Lib$C = libExports; -var Color$j = colorExports; -var Template$1 = plot_template; -var handleArrayContainerDefaults2 = array_container_defaults; -var attributes$h = attributes$i; -var constants$i = constants$j; -var defaults$8 = function handleDefaults2(containerIn, containerOut, layout, counterAxes, calendar) { - var selectorIn = containerIn.rangeselector || {}; - var selectorOut = Template$1.newContainer(containerOut, "rangeselector"); - function coerce2(attr, dflt) { - return Lib$C.coerce(selectorIn, selectorOut, attributes$h, attr, dflt); - } - var buttons2 = handleArrayContainerDefaults2(selectorIn, selectorOut, { - name: "buttons", - handleItemDefaults: buttonDefaults, - calendar - }); - var visible = coerce2("visible", buttons2.length > 0); - if (visible) { - var posDflt = getPosDflt(containerOut, layout, counterAxes); - coerce2("x", posDflt[0]); - coerce2("y", posDflt[1]); - Lib$C.noneOrAll(containerIn, containerOut, ["x", "y"]); - coerce2("xanchor"); - coerce2("yanchor"); - Lib$C.coerceFont(coerce2, "font", layout.font); - var bgColor = coerce2("bgcolor"); - coerce2("activecolor", Color$j.contrast(bgColor, constants$i.lightAmount, constants$i.darkAmount)); - coerce2("bordercolor"); - coerce2("borderwidth"); - } -}; -function buttonDefaults(buttonIn, buttonOut, selectorOut, opts) { - var calendar = opts.calendar; - function coerce2(attr, dflt) { - return Lib$C.coerce(buttonIn, buttonOut, attributes$h.buttons, attr, dflt); - } - var visible = coerce2("visible"); - if (visible) { - var step = coerce2("step"); - if (step !== "all") { - if (calendar && calendar !== "gregorian" && (step === "month" || step === "year")) { - buttonOut.stepmode = "backward"; - } else { - coerce2("stepmode"); - } - coerce2("count"); - } - coerce2("label"); - } -} -function getPosDflt(containerOut, layout, counterAxes) { - var anchoredList = counterAxes.filter(function(ax) { - return layout[ax].anchor === containerOut._id; - }); - var posY = 0; - for (var i = 0; i < anchoredList.length; i++) { - var domain2 = layout[anchoredList[i]].domain; - if (domain2) posY = Math.max(domain2[1], posY); - } - return [containerOut.domain[0], posY + constants$i.yPad]; -} -const require$$0$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$4); -var d3Time = require$$0$2; -var titleCase = libExports.titleCase; -var get_update_object = function getUpdateObject(axisLayout, buttonLayout) { - var axName = axisLayout._name; - var update2 = {}; - if (buttonLayout.step === "all") { - update2[axName + ".autorange"] = true; - } else { - var xrange = getXRange(axisLayout, buttonLayout); - update2[axName + ".range[0]"] = xrange[0]; - update2[axName + ".range[1]"] = xrange[1]; - } - return update2; -}; -function getXRange(axisLayout, buttonLayout) { - var currentRange = axisLayout.range; - var base = new Date(axisLayout.r2l(currentRange[1])); - var step = buttonLayout.step; - var utcStep = d3Time["utc" + titleCase(step)]; - var count2 = buttonLayout.count; - var range0; - switch (buttonLayout.stepmode) { - case "backward": - range0 = axisLayout.l2r(+utcStep.offset(base, -count2)); - break; - case "todate": - var base2 = utcStep.offset(base, -count2); - range0 = axisLayout.l2r(+utcStep.ceil(base2)); - break; - } - var range1 = currentRange[1]; - return [range0, range1]; -} -var d3$e = d3Exports; -var Registry$f = registry; -var Plots$2 = plotsExports; -var Color$i = colorExports; -var Drawing$9 = drawingExports; -var Lib$B = libExports; -var strTranslate$2 = Lib$B.strTranslate; -var svgTextUtils$5 = svg_text_utils; -var axisIds$1 = axis_ids; -var alignmentConstants$1 = alignment$1; -var LINE_SPACING$1 = alignmentConstants$1.LINE_SPACING; -var FROM_TL$1 = alignmentConstants$1.FROM_TL; -var FROM_BR$1 = alignmentConstants$1.FROM_BR; -var constants$h = constants$j; -var getUpdateObject2 = get_update_object; -var draw$3 = function draw6(gd) { - var fullLayout = gd._fullLayout; - var selectors = fullLayout._infolayer.selectAll(".rangeselector").data(makeSelectorData(gd), selectorKeyFunc); - selectors.enter().append("g").classed("rangeselector", true); - selectors.exit().remove(); - selectors.style({ - cursor: "pointer", - "pointer-events": "all" - }); - selectors.each(function(d) { - var selector = d3$e.select(this); - var axisLayout = d; - var selectorLayout = axisLayout.rangeselector; - var buttons2 = selector.selectAll("g.button").data(Lib$B.filterVisible(selectorLayout.buttons)); - buttons2.enter().append("g").classed("button", true); - buttons2.exit().remove(); - buttons2.each(function(d2) { - var button = d3$e.select(this); - var update2 = getUpdateObject2(axisLayout, d2); - d2._isActive = isActive(axisLayout, d2, update2); - button.call(drawButtonRect, selectorLayout, d2); - button.call(drawButtonText, selectorLayout, d2, gd); - button.on("click", function() { - if (gd._dragged) return; - Registry$f.call("_guiRelayout", gd, update2); - }); - button.on("mouseover", function() { - d2._isHovered = true; - button.call(drawButtonRect, selectorLayout, d2); - }); - button.on("mouseout", function() { - d2._isHovered = false; - button.call(drawButtonRect, selectorLayout, d2); - }); - }); - reposition(gd, buttons2, selectorLayout, axisLayout._name, selector); - }); -}; -function makeSelectorData(gd) { - var axes2 = axisIds$1.list(gd, "x", true); - var data = []; - for (var i = 0; i < axes2.length; i++) { - var axis = axes2[i]; - if (axis.rangeselector && axis.rangeselector.visible) { - data.push(axis); - } - } - return data; -} -function selectorKeyFunc(d) { - return d._id; -} -function isActive(axisLayout, opts, update2) { - if (opts.step === "all") { - return axisLayout.autorange === true; - } else { - var keys = Object.keys(update2); - return axisLayout.range[0] === update2[keys[0]] && axisLayout.range[1] === update2[keys[1]]; - } -} -function drawButtonRect(button, selectorLayout, d) { - var rect2 = Lib$B.ensureSingle(button, "rect", "selector-rect", function(s) { - s.attr("shape-rendering", "crispEdges"); - }); - rect2.attr({ - rx: constants$h.rx, - ry: constants$h.ry - }); - rect2.call(Color$i.stroke, selectorLayout.bordercolor).call(Color$i.fill, getFillColor(selectorLayout, d)).style("stroke-width", selectorLayout.borderwidth + "px"); -} -function getFillColor(selectorLayout, d) { - return d._isActive || d._isHovered ? selectorLayout.activecolor : selectorLayout.bgcolor; -} -function drawButtonText(button, selectorLayout, d, gd) { - function textLayout2(s) { - svgTextUtils$5.convertToTspans(s, gd); - } - var text = Lib$B.ensureSingle(button, "text", "selector-text", function(s) { - s.attr("text-anchor", "middle"); - }); - text.call(Drawing$9.font, selectorLayout.font).text(getLabel2(d, gd._fullLayout._meta)).call(textLayout2); -} -function getLabel2(opts, _meta) { - if (opts.label) { - return _meta ? Lib$B.templateString(opts.label, _meta) : opts.label; - } - if (opts.step === "all") return "all"; - return opts.count + opts.step.charAt(0); -} -function reposition(gd, buttons2, opts, axName, selector) { - var width = 0; - var height = 0; - var borderWidth = opts.borderwidth; - buttons2.each(function() { - var button = d3$e.select(this); - var text = button.select(".selector-text"); - var tHeight = opts.font.size * LINE_SPACING$1; - var hEff = Math.max(tHeight * svgTextUtils$5.lineCount(text), 16) + 3; - height = Math.max(height, hEff); - }); - buttons2.each(function() { - var button = d3$e.select(this); - var rect2 = button.select(".selector-rect"); - var text = button.select(".selector-text"); - var tWidth = text.node() && Drawing$9.bBox(text.node()).width; - var tHeight = opts.font.size * LINE_SPACING$1; - var tLines = svgTextUtils$5.lineCount(text); - var wEff = Math.max(tWidth + 10, constants$h.minButtonWidth); - button.attr("transform", strTranslate$2(borderWidth + width, borderWidth)); - rect2.attr({ - x: 0, - y: 0, - width: wEff, - height - }); - svgTextUtils$5.positionText( - text, - wEff / 2, - height / 2 - (tLines - 1) * tHeight / 2 + 3 - ); - width += wEff + 5; - }); - var graphSize = gd._fullLayout._size; - var lx = graphSize.l + graphSize.w * opts.x; - var ly = graphSize.t + graphSize.h * (1 - opts.y); - var xanchor = "left"; - if (Lib$B.isRightAnchor(opts)) { - lx -= width; - xanchor = "right"; - } - if (Lib$B.isCenterAnchor(opts)) { - lx -= width / 2; - xanchor = "center"; - } - var yanchor = "top"; - if (Lib$B.isBottomAnchor(opts)) { - ly -= height; - yanchor = "bottom"; - } - if (Lib$B.isMiddleAnchor(opts)) { - ly -= height / 2; - yanchor = "middle"; - } - width = Math.ceil(width); - height = Math.ceil(height); - lx = Math.round(lx); - ly = Math.round(ly); - Plots$2.autoMargin(gd, axName + "-range-selector", { - x: opts.x, - y: opts.y, - l: width * FROM_TL$1[xanchor], - r: width * FROM_BR$1[xanchor], - b: height * FROM_BR$1[yanchor], - t: height * FROM_TL$1[yanchor] - }); - selector.attr("transform", strTranslate$2(lx, ly)); -} -var rangeselector = { - moduleType: "component", - name: "rangeselector", - schema: { - subplots: { - xaxis: { rangeselector: attributes$i } - } - }, - layoutAttributes: attributes$i, - handleDefaults: defaults$8, - draw: draw$3 -}; -var domain = {}; -var extendFlat$9 = extend$5.extendFlat; -domain.attributes = function(opts, extra) { - opts = opts || {}; - extra = extra || {}; - var base = { - valType: "info_array", - editType: opts.editType, - items: [ - { valType: "number", min: 0, max: 1, editType: opts.editType }, - { valType: "number", min: 0, max: 1, editType: opts.editType } - ], - dflt: [0, 1] - }; - var namePart = opts.name ? opts.name + " " : ""; - var contPart = opts.trace ? "trace " : "subplot "; - var descPart = extra.description ? " " + extra.description : ""; - var out = { - x: extendFlat$9({}, base, { - description: [ - "Sets the horizontal domain of this ", - namePart, - contPart, - "(in plot fraction).", - descPart - ].join("") - }), - y: extendFlat$9({}, base, { - description: [ - "Sets the vertical domain of this ", - namePart, - contPart, - "(in plot fraction).", - descPart - ].join("") - }), - editType: opts.editType - }; - if (!opts.noGridCell) { - out.row = { - valType: "integer", - min: 0, - dflt: 0, - editType: opts.editType, - description: [ - "If there is a layout grid, use the domain ", - "for this row in the grid for this ", - namePart, - contPart, - ".", - descPart - ].join("") - }; - out.column = { - valType: "integer", - min: 0, - dflt: 0, - editType: opts.editType, - description: [ - "If there is a layout grid, use the domain ", - "for this column in the grid for this ", - namePart, - contPart, - ".", - descPart - ].join("") - }; - } - return out; -}; -domain.defaults = function(containerOut, layout, coerce2, dfltDomains) { - var dfltX = dfltDomains && dfltDomains.x || [0, 1]; - var dfltY = dfltDomains && dfltDomains.y || [0, 1]; - var grid2 = layout.grid; - if (grid2) { - var column = coerce2("domain.column"); - if (column !== void 0) { - if (column < grid2.columns) dfltX = grid2._domains.x[column]; - else delete containerOut.domain.column; - } - var row = coerce2("domain.row"); - if (row !== void 0) { - if (row < grid2.rows) dfltY = grid2._domains.y[row]; - else delete containerOut.domain.row; - } - } - var x = coerce2("domain.x", dfltX); - var y = coerce2("domain.y", dfltY); - if (!(x[0] < x[1])) containerOut.domain.x = dfltX.slice(); - if (!(y[0] < y[1])) containerOut.domain.y = dfltY.slice(); -}; -var Lib$A = libExports; -var counterRegex = regex.counter; -var domainAttrs$3 = domain.attributes; -var cartesianIdRegex = constants$U.idRegex; -var Template = plot_template; -var gridAttrs = { - rows: { - valType: "integer", - min: 1, - editType: "plot", - description: [ - "The number of rows in the grid. If you provide a 2D `subplots`", - "array or a `yaxes` array, its length is used as the default.", - "But it's also possible to have a different length, if you", - "want to leave a row at the end for non-cartesian subplots." - ].join(" ") - }, - roworder: { - valType: "enumerated", - values: ["top to bottom", "bottom to top"], - dflt: "top to bottom", - editType: "plot", - description: [ - "Is the first row the top or the bottom? Note that columns", - "are always enumerated from left to right." - ].join(" ") - }, - columns: { - valType: "integer", - min: 1, - editType: "plot", - description: [ - "The number of columns in the grid. If you provide a 2D `subplots`", - "array, the length of its longest row is used as the default.", - "If you give an `xaxes` array, its length is used as the default.", - "But it's also possible to have a different length, if you", - "want to leave a row at the end for non-cartesian subplots." - ].join(" ") - }, - subplots: { - valType: "info_array", - freeLength: true, - dimensions: 2, - items: { valType: "enumerated", values: [counterRegex("xy").toString(), ""], editType: "plot" }, - editType: "plot", - description: [ - "Used for freeform grids, where some axes may be shared across subplots", - "but others are not. Each entry should be a cartesian subplot id, like", - "*xy* or *x3y2*, or ** to leave that cell empty. You may reuse x axes", - "within the same column, and y axes within the same row.", - "Non-cartesian subplots and traces that support `domain` can place themselves", - "in this grid separately using the `gridcell` attribute." - ].join(" ") - }, - xaxes: { - valType: "info_array", - freeLength: true, - items: { valType: "enumerated", values: [cartesianIdRegex.x.toString(), ""], editType: "plot" }, - editType: "plot", - description: [ - "Used with `yaxes` when the x and y axes are shared across columns and rows.", - "Each entry should be an x axis id like *x*, *x2*, etc., or ** to", - "not put an x axis in that column. Entries other than ** must be unique.", - "Ignored if `subplots` is present. If missing but `yaxes` is present,", - "will generate consecutive IDs." - ].join(" ") - }, - yaxes: { - valType: "info_array", - freeLength: true, - items: { valType: "enumerated", values: [cartesianIdRegex.y.toString(), ""], editType: "plot" }, - editType: "plot", - description: [ - "Used with `yaxes` when the x and y axes are shared across columns and rows.", - "Each entry should be an y axis id like *y*, *y2*, etc., or ** to", - "not put a y axis in that row. Entries other than ** must be unique.", - "Ignored if `subplots` is present. If missing but `xaxes` is present,", - "will generate consecutive IDs." - ].join(" ") - }, - pattern: { - valType: "enumerated", - values: ["independent", "coupled"], - dflt: "coupled", - editType: "plot", - description: [ - "If no `subplots`, `xaxes`, or `yaxes` are given but we do have `rows` and `columns`,", - "we can generate defaults using consecutive axis IDs, in two ways:", - "*coupled* gives one x axis per column and one y axis per row.", - "*independent* uses a new xy pair for each cell, left-to-right across each row", - "then iterating rows according to `roworder`." - ].join(" ") - }, - xgap: { - valType: "number", - min: 0, - max: 1, - editType: "plot", - description: [ - "Horizontal space between grid cells, expressed as a fraction", - "of the total width available to one cell. Defaults to 0.1", - "for coupled-axes grids and 0.2 for independent grids." - ].join(" ") - }, - ygap: { - valType: "number", - min: 0, - max: 1, - editType: "plot", - description: [ - "Vertical space between grid cells, expressed as a fraction", - "of the total height available to one cell. Defaults to 0.1", - "for coupled-axes grids and 0.3 for independent grids." - ].join(" ") - }, - domain: domainAttrs$3({ name: "grid", editType: "plot", noGridCell: true }, { - description: [ - "The first and last cells end exactly at the domain", - "edges, with no grout around the edges." - ].join(" ") - }), - xside: { - valType: "enumerated", - values: ["bottom", "bottom plot", "top plot", "top"], - dflt: "bottom plot", - editType: "plot", - description: [ - "Sets where the x axis labels and titles go. *bottom* means", - "the very bottom of the grid. *bottom plot* is the lowest plot", - "that each x axis is used in. *top* and *top plot* are similar." - ].join(" ") - }, - yside: { - valType: "enumerated", - values: ["left", "left plot", "right plot", "right"], - dflt: "left plot", - editType: "plot", - description: [ - "Sets where the y axis labels and titles go. *left* means", - "the very left edge of the grid. *left plot* is the leftmost plot", - "that each y axis is used in. *right* and *right plot* are similar." - ].join(" ") - }, - editType: "plot" -}; -function getAxes(layout, grid2, axLetter) { - var gridVal = grid2[axLetter + "axes"]; - var splomVal = Object.keys((layout._splomAxes || {})[axLetter] || {}); - if (Array.isArray(gridVal)) return gridVal; - if (splomVal.length) return splomVal; -} -function sizeDefaults(layoutIn, layoutOut) { - var gridIn = layoutIn.grid || {}; - var xAxes = getAxes(layoutOut, gridIn, "x"); - var yAxes = getAxes(layoutOut, gridIn, "y"); - if (!layoutIn.grid && !xAxes && !yAxes) return; - var hasSubplotGrid = Array.isArray(gridIn.subplots) && Array.isArray(gridIn.subplots[0]); - var hasXaxes = Array.isArray(xAxes); - var hasYaxes = Array.isArray(yAxes); - var isSplomGenerated = hasXaxes && xAxes !== gridIn.xaxes && hasYaxes && yAxes !== gridIn.yaxes; - var dfltRows, dfltColumns; - if (hasSubplotGrid) { - dfltRows = gridIn.subplots.length; - dfltColumns = gridIn.subplots[0].length; - } else { - if (hasYaxes) dfltRows = yAxes.length; - if (hasXaxes) dfltColumns = xAxes.length; - } - var gridOut = Template.newContainer(layoutOut, "grid"); - function coerce2(attr, dflt) { - return Lib$A.coerce(gridIn, gridOut, gridAttrs, attr, dflt); - } - var rows = coerce2("rows", dfltRows); - var columns = coerce2("columns", dfltColumns); - if (!(rows * columns > 1)) { - delete layoutOut.grid; - return; - } - if (!hasSubplotGrid && !hasXaxes && !hasYaxes) { - var useDefaultSubplots = coerce2("pattern") === "independent"; - if (useDefaultSubplots) hasSubplotGrid = true; - } - gridOut._hasSubplotGrid = hasSubplotGrid; - var rowOrder = coerce2("roworder"); - var reversed = rowOrder === "top to bottom"; - var dfltGapX = hasSubplotGrid ? 0.2 : 0.1; - var dfltGapY = hasSubplotGrid ? 0.3 : 0.1; - var dfltSideX, dfltSideY; - if (isSplomGenerated && layoutOut._splomGridDflt) { - dfltSideX = layoutOut._splomGridDflt.xside; - dfltSideY = layoutOut._splomGridDflt.yside; - } - gridOut._domains = { - x: fillGridPositions("x", coerce2, dfltGapX, dfltSideX, columns), - y: fillGridPositions("y", coerce2, dfltGapY, dfltSideY, rows, reversed) - }; -} -function fillGridPositions(axLetter, coerce2, dfltGap, dfltSide, len, reversed) { - var dirGap = coerce2(axLetter + "gap", dfltGap); - var domain2 = coerce2("domain." + axLetter); - coerce2(axLetter + "side", dfltSide); - var out = new Array(len); - var start = domain2[0]; - var step = (domain2[1] - start) / (len - dirGap); - var cellDomain = step * (1 - dirGap); - for (var i = 0; i < len; i++) { - var cellStart = start + step * i; - out[reversed ? len - 1 - i : i] = [cellStart, cellStart + cellDomain]; - } - return out; -} -function contentDefaults(layoutIn, layoutOut) { - var gridOut = layoutOut.grid; - if (!gridOut || !gridOut._domains) return; - var gridIn = layoutIn.grid || {}; - var subplots = layoutOut._subplots; - var hasSubplotGrid = gridOut._hasSubplotGrid; - var rows = gridOut.rows; - var columns = gridOut.columns; - var useDefaultSubplots = gridOut.pattern === "independent"; - var i, j, xId, yId, subplotId, subplotsOut, yPos; - var axisMap = gridOut._axisMap = {}; - if (hasSubplotGrid) { - var subplotsIn = gridIn.subplots || []; - subplotsOut = gridOut.subplots = new Array(rows); - var index2 = 1; - for (i = 0; i < rows; i++) { - var rowOut = subplotsOut[i] = new Array(columns); - var rowIn = subplotsIn[i] || []; - for (j = 0; j < columns; j++) { - if (useDefaultSubplots) { - subplotId = index2 === 1 ? "xy" : "x" + index2 + "y" + index2; - index2++; - } else subplotId = rowIn[j]; - rowOut[j] = ""; - if (subplots.cartesian.indexOf(subplotId) !== -1) { - yPos = subplotId.indexOf("y"); - xId = subplotId.slice(0, yPos); - yId = subplotId.slice(yPos); - if (axisMap[xId] !== void 0 && axisMap[xId] !== j || axisMap[yId] !== void 0 && axisMap[yId] !== i) { - continue; - } - rowOut[j] = subplotId; - axisMap[xId] = j; - axisMap[yId] = i; - } - } - } - } else { - var xAxes = getAxes(layoutOut, gridIn, "x"); - var yAxes = getAxes(layoutOut, gridIn, "y"); - gridOut.xaxes = fillGridAxes(xAxes, subplots.xaxis, columns, axisMap, "x"); - gridOut.yaxes = fillGridAxes(yAxes, subplots.yaxis, rows, axisMap, "y"); - } - var anchors = gridOut._anchors = {}; - var reversed = gridOut.roworder === "top to bottom"; - for (var axisId in axisMap) { - var axLetter = axisId.charAt(0); - var side = gridOut[axLetter + "side"]; - var i0, inc, iFinal; - if (side.length < 8) { - anchors[axisId] = "free"; - } else if (axLetter === "x") { - if (side.charAt(0) === "t" === reversed) { - i0 = 0; - inc = 1; - iFinal = rows; - } else { - i0 = rows - 1; - inc = -1; - iFinal = -1; - } - if (hasSubplotGrid) { - var column = axisMap[axisId]; - for (i = i0; i !== iFinal; i += inc) { - subplotId = subplotsOut[i][column]; - if (!subplotId) continue; - yPos = subplotId.indexOf("y"); - if (subplotId.slice(0, yPos) === axisId) { - anchors[axisId] = subplotId.slice(yPos); - break; - } - } - } else { - for (i = i0; i !== iFinal; i += inc) { - yId = gridOut.yaxes[i]; - if (subplots.cartesian.indexOf(axisId + yId) !== -1) { - anchors[axisId] = yId; - break; - } - } - } - } else { - if (side.charAt(0) === "l") { - i0 = 0; - inc = 1; - iFinal = columns; - } else { - i0 = columns - 1; - inc = -1; - iFinal = -1; - } - if (hasSubplotGrid) { - var row = axisMap[axisId]; - for (i = i0; i !== iFinal; i += inc) { - subplotId = subplotsOut[row][i]; - if (!subplotId) continue; - yPos = subplotId.indexOf("y"); - if (subplotId.slice(yPos) === axisId) { - anchors[axisId] = subplotId.slice(0, yPos); - break; - } - } - } else { - for (i = i0; i !== iFinal; i += inc) { - xId = gridOut.xaxes[i]; - if (subplots.cartesian.indexOf(xId + axisId) !== -1) { - anchors[axisId] = xId; - break; - } - } - } - } - } -} -function fillGridAxes(axesIn, axesAllowed, len, axisMap, axLetter) { - var out = new Array(len); - var i; - function fillOneAxis(i2, axisId) { - if (axesAllowed.indexOf(axisId) !== -1 && axisMap[axisId] === void 0) { - out[i2] = axisId; - axisMap[axisId] = i2; - } else out[i2] = ""; - } - if (Array.isArray(axesIn)) { - for (i = 0; i < len; i++) { - fillOneAxis(i, axesIn[i]); - } - } else { - fillOneAxis(0, axLetter); - for (i = 1; i < len; i++) { - fillOneAxis(i, axLetter + (i + 1)); - } - } - return out; -} -var grid = { - moduleType: "component", - name: "grid", - schema: { - layout: { grid: gridAttrs } - }, - layoutAttributes: gridAttrs, - sizeDefaults, - contentDefaults -}; -var attributes$g = { - visible: { - valType: "boolean", - editType: "calc", - description: [ - "Determines whether or not this set of error bars is visible." - ].join(" ") - }, - type: { - valType: "enumerated", - values: ["percent", "constant", "sqrt", "data"], - editType: "calc", - description: [ - "Determines the rule used to generate the error bars.", - "If *constant`, the bar lengths are of a constant value.", - "Set this constant in `value`.", - "If *percent*, the bar lengths correspond to a percentage of", - "underlying data. Set this percentage in `value`.", - "If *sqrt*, the bar lengths correspond to the square of the", - "underlying data.", - "If *data*, the bar lengths are set with data set `array`." - ].join(" ") - }, - symmetric: { - valType: "boolean", - editType: "calc", - description: [ - "Determines whether or not the error bars have the same length", - "in both direction", - "(top/bottom for vertical bars, left/right for horizontal bars." - ].join(" ") - }, - array: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the data corresponding the length of each error bar.", - "Values are plotted relative to the underlying data." - ].join(" ") - }, - arrayminus: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the data corresponding the length of each error bar in the", - "bottom (left) direction for vertical (horizontal) bars", - "Values are plotted relative to the underlying data." - ].join(" ") - }, - value: { - valType: "number", - min: 0, - dflt: 10, - editType: "calc", - description: [ - "Sets the value of either the percentage", - "(if `type` is set to *percent*) or the constant", - "(if `type` is set to *constant*) corresponding to the lengths of", - "the error bars." - ].join(" ") - }, - valueminus: { - valType: "number", - min: 0, - dflt: 10, - editType: "calc", - description: [ - "Sets the value of either the percentage", - "(if `type` is set to *percent*) or the constant", - "(if `type` is set to *constant*) corresponding to the lengths of", - "the error bars in the", - "bottom (left) direction for vertical (horizontal) bars" - ].join(" ") - }, - traceref: { - valType: "integer", - min: 0, - dflt: 0, - editType: "style" - }, - tracerefminus: { - valType: "integer", - min: 0, - dflt: 0, - editType: "style" - }, - copy_ystyle: { - valType: "boolean", - editType: "plot" - }, - copy_zstyle: { - valType: "boolean", - editType: "style" - }, - color: { - valType: "color", - editType: "style", - description: "Sets the stoke color of the error bars." - }, - thickness: { - valType: "number", - min: 0, - dflt: 2, - editType: "style", - description: "Sets the thickness (in px) of the error bars." - }, - width: { - valType: "number", - min: 0, - editType: "plot", - description: [ - "Sets the width (in px) of the cross-bar at both ends", - "of the error bars." - ].join(" ") - }, - editType: "calc", - _deprecated: { - opacity: { - valType: "number", - editType: "style", - description: [ - "Obsolete.", - "Use the alpha channel in error bar `color` to set the opacity." - ].join(" ") - } - } -}; -var defaults$7; -var hasRequiredDefaults; -function requireDefaults() { - if (hasRequiredDefaults) return defaults$7; - hasRequiredDefaults = 1; - var isNumeric2 = fastIsnumeric; - var Registry2 = registry; - var Lib2 = libExports; - var Template2 = plot_template; - var attributes2 = attributes$g; - defaults$7 = function(traceIn, traceOut, defaultColor, opts) { - var objName = "error_" + opts.axis; - var containerOut = Template2.newContainer(traceOut, objName); - var containerIn = traceIn[objName] || {}; - function coerce2(attr, dflt) { - return Lib2.coerce(containerIn, containerOut, attributes2, attr, dflt); - } - var hasErrorBars = containerIn.array !== void 0 || containerIn.value !== void 0 || containerIn.type === "sqrt"; - var visible = coerce2("visible", hasErrorBars); - if (visible === false) return; - var type = coerce2("type", "array" in containerIn ? "data" : "percent"); - var symmetric = true; - if (type !== "sqrt") { - symmetric = coerce2( - "symmetric", - !((type === "data" ? "arrayminus" : "valueminus") in containerIn) - ); - } - if (type === "data") { - coerce2("array"); - coerce2("traceref"); - if (!symmetric) { - coerce2("arrayminus"); - coerce2("tracerefminus"); - } - } else if (type === "percent" || type === "constant") { - coerce2("value"); - if (!symmetric) coerce2("valueminus"); - } - var copyAttr = "copy_" + opts.inherit + "style"; - if (opts.inherit) { - var inheritObj = traceOut["error_" + opts.inherit]; - if ((inheritObj || {}).visible) { - coerce2(copyAttr, !(containerIn.color || isNumeric2(containerIn.thickness) || isNumeric2(containerIn.width))); - } - } - if (!opts.inherit || !containerOut[copyAttr]) { - coerce2("color", defaultColor); - coerce2("thickness"); - coerce2("width", Registry2.traceIs(traceOut, "gl3d") ? 0 : 4); - } - }; - return defaults$7; -} -var compute_error; -var hasRequiredCompute_error; -function requireCompute_error() { - if (hasRequiredCompute_error) return compute_error; - hasRequiredCompute_error = 1; - compute_error = function makeComputeError(opts) { - var type = opts.type; - var symmetric = opts.symmetric; - if (type === "data") { - var array2 = opts.array || []; - if (symmetric) { - return function computeError(dataPt, index2) { - var val = +array2[index2]; - return [val, val]; - }; - } else { - var arrayminus = opts.arrayminus || []; - return function computeError(dataPt, index2) { - var val = +array2[index2]; - var valMinus = +arrayminus[index2]; - if (!isNaN(val) || !isNaN(valMinus)) { - return [valMinus || 0, val || 0]; - } - return [NaN, NaN]; - }; - } - } else { - var computeErrorValue = makeComputeErrorValue(type, opts.value); - var computeErrorValueMinus = makeComputeErrorValue(type, opts.valueminus); - if (symmetric || opts.valueminus === void 0) { - return function computeError(dataPt) { - var val = computeErrorValue(dataPt); - return [val, val]; - }; - } else { - return function computeError(dataPt) { - return [ - computeErrorValueMinus(dataPt), - computeErrorValue(dataPt) - ]; - }; - } - } - }; - function makeComputeErrorValue(type, value2) { - if (type === "percent") { - return function(dataPt) { - return Math.abs(dataPt * value2 / 100); - }; - } - if (type === "constant") { - return function() { - return Math.abs(value2); - }; - } - if (type === "sqrt") { - return function(dataPt) { - return Math.sqrt(Math.abs(dataPt)); - }; - } - } - return compute_error; -} -var calc$8; -var hasRequiredCalc; -function requireCalc() { - if (hasRequiredCalc) return calc$8; - hasRequiredCalc = 1; - var isNumeric2 = fastIsnumeric; - var Registry2 = registry; - var Axes2 = axesExports; - var Lib2 = libExports; - var makeComputeError = requireCompute_error(); - calc$8 = function calc6(gd) { - var calcdata = gd.calcdata; - for (var i = 0; i < calcdata.length; i++) { - var calcTrace = calcdata[i]; - var trace = calcTrace[0].trace; - if (trace.visible === true && Registry2.traceIs(trace, "errorBarsOK")) { - var xa = Axes2.getFromId(gd, trace.xaxis); - var ya = Axes2.getFromId(gd, trace.yaxis); - calcOneAxis(calcTrace, trace, xa, "x"); - calcOneAxis(calcTrace, trace, ya, "y"); - } - } - }; - function calcOneAxis(calcTrace, trace, axis, coord) { - var opts = trace["error_" + coord] || {}; - var isVisible2 = opts.visible && ["linear", "log"].indexOf(axis.type) !== -1; - var vals = []; - if (!isVisible2) return; - var computeError = makeComputeError(opts); - for (var i = 0; i < calcTrace.length; i++) { - var calcPt = calcTrace[i]; - var iIn = calcPt.i; - if (iIn === void 0) iIn = i; - else if (iIn === null) continue; - var calcCoord = calcPt[coord]; - if (!isNumeric2(axis.c2l(calcCoord))) continue; - var errors = computeError(calcCoord, iIn); - if (isNumeric2(errors[0]) && isNumeric2(errors[1])) { - var shoe = calcPt[coord + "s"] = calcCoord - errors[0]; - var hat = calcPt[coord + "h"] = calcCoord + errors[1]; - vals.push(shoe, hat); - } - } - var axId = axis._id; - var baseExtremes = trace._extremes[axId]; - var extremes = Axes2.findExtremes( - axis, - vals, - Lib2.extendFlat({ tozero: baseExtremes.opts.tozero }, { padded: true }) - ); - baseExtremes.min = baseExtremes.min.concat(extremes.min); - baseExtremes.max = baseExtremes.max.concat(extremes.max); - } - return calc$8; -} -var plot$6; -var hasRequiredPlot; -function requirePlot() { - if (hasRequiredPlot) return plot$6; - hasRequiredPlot = 1; - var d32 = d3Exports; - var isNumeric2 = fastIsnumeric; - var Drawing2 = drawingExports; - var subTypes2 = subtypes$3; - plot$6 = function plot5(gd, traces, plotinfo, transitionOpts) { - var isNew; - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var hasAnimation = transitionOpts && transitionOpts.duration > 0; - var isStatic = gd._context.staticPlot; - traces.each(function(d) { - var trace = d[0].trace; - var xObj = trace.error_x || {}; - var yObj = trace.error_y || {}; - var keyFunc2; - if (trace.ids) { - keyFunc2 = function(d2) { - return d2.id; - }; - } - var sparse = subTypes2.hasMarkers(trace) && trace.marker.maxdisplayed > 0; - if (!yObj.visible && !xObj.visible) d = []; - var errorbars2 = d32.select(this).selectAll("g.errorbar").data(d, keyFunc2); - errorbars2.exit().remove(); - if (!d.length) return; - if (!xObj.visible) errorbars2.selectAll("path.xerror").remove(); - if (!yObj.visible) errorbars2.selectAll("path.yerror").remove(); - errorbars2.style("opacity", 1); - var enter = errorbars2.enter().append("g").classed("errorbar", true); - if (hasAnimation) { - enter.style("opacity", 0).transition().duration(transitionOpts.duration).style("opacity", 1); - } - Drawing2.setClipUrl(errorbars2, plotinfo.layerClipId, gd); - errorbars2.each(function(d2) { - var errorbar = d32.select(this); - var coords = errorCoords(d2, xa, ya); - if (sparse && !d2.vis) return; - var path; - var yerror = errorbar.select("path.yerror"); - if (yObj.visible && isNumeric2(coords.x) && isNumeric2(coords.yh) && isNumeric2(coords.ys)) { - var yw = yObj.width; - path = "M" + (coords.x - yw) + "," + coords.yh + "h" + 2 * yw + // hat - "m-" + yw + ",0V" + coords.ys; - if (!coords.noYS) path += "m-" + yw + ",0h" + 2 * yw; - isNew = !yerror.size(); - if (isNew) { - yerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("yerror", true); - } else if (hasAnimation) { - yerror = yerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing); - } - yerror.attr("d", path); - } else yerror.remove(); - var xerror = errorbar.select("path.xerror"); - if (xObj.visible && isNumeric2(coords.y) && isNumeric2(coords.xh) && isNumeric2(coords.xs)) { - var xw = (xObj.copy_ystyle ? yObj : xObj).width; - path = "M" + coords.xh + "," + (coords.y - xw) + "v" + 2 * xw + // hat - "m0,-" + xw + "H" + coords.xs; - if (!coords.noXS) path += "m0,-" + xw + "v" + 2 * xw; - isNew = !xerror.size(); - if (isNew) { - xerror = errorbar.append("path").style("vector-effect", isStatic ? "none" : "non-scaling-stroke").classed("xerror", true); - } else if (hasAnimation) { - xerror = xerror.transition().duration(transitionOpts.duration).ease(transitionOpts.easing); - } - xerror.attr("d", path); - } else xerror.remove(); - }); - }); - }; - function errorCoords(d, xa, ya) { - var out = { - x: xa.c2p(d.x), - y: ya.c2p(d.y) - }; - if (d.yh !== void 0) { - out.yh = ya.c2p(d.yh); - out.ys = ya.c2p(d.ys); - if (!isNumeric2(out.ys)) { - out.noYS = true; - out.ys = ya.c2p(d.ys, true); - } - } - if (d.xh !== void 0) { - out.xh = xa.c2p(d.xh); - out.xs = xa.c2p(d.xs); - if (!isNumeric2(out.xs)) { - out.noXS = true; - out.xs = xa.c2p(d.xs, true); - } - } - return out; - } - return plot$6; -} -var style$5; -var hasRequiredStyle; -function requireStyle() { - if (hasRequiredStyle) return style$5; - hasRequiredStyle = 1; - var d32 = d3Exports; - var Color2 = colorExports; - style$5 = function style5(traces) { - traces.each(function(d) { - var trace = d[0].trace; - var yObj = trace.error_y || {}; - var xObj = trace.error_x || {}; - var s = d32.select(this); - s.selectAll("path.yerror").style("stroke-width", yObj.thickness + "px").call(Color2.stroke, yObj.color); - if (xObj.copy_ystyle) xObj = yObj; - s.selectAll("path.xerror").style("stroke-width", xObj.thickness + "px").call(Color2.stroke, xObj.color); - }); - }; - return style$5; -} -var Lib$z = libExports; -var overrideAll$1 = edit_types.overrideAll; -var attributes$f = attributes$g; -var xyAttrs = { - error_x: Lib$z.extendFlat({}, attributes$f), - error_y: Lib$z.extendFlat({}, attributes$f) -}; -delete xyAttrs.error_x.copy_zstyle; -delete xyAttrs.error_y.copy_zstyle; -delete xyAttrs.error_y.copy_ystyle; -var xyzAttrs = { - error_x: Lib$z.extendFlat({}, attributes$f), - error_y: Lib$z.extendFlat({}, attributes$f), - error_z: Lib$z.extendFlat({}, attributes$f) -}; -delete xyzAttrs.error_x.copy_ystyle; -delete xyzAttrs.error_y.copy_ystyle; -delete xyzAttrs.error_z.copy_ystyle; -delete xyzAttrs.error_z.copy_zstyle; -var errorbars = { - moduleType: "component", - name: "errorbars", - schema: { - traces: { - scatter: xyAttrs, - bar: xyAttrs, - histogram: xyAttrs, - scatter3d: overrideAll$1(xyzAttrs, "calc", "nested"), - scattergl: overrideAll$1(xyAttrs, "calc", "nested") - } - }, - supplyDefaults: requireDefaults(), - calc: requireCalc(), - makeComputeError: requireCompute_error(), - plot: requirePlot(), - style: requireStyle(), - hoverInfo -}; -function hoverInfo(calcPoint, trace, hoverPoint) { - if ((trace.error_y || {}).visible) { - hoverPoint.yerr = calcPoint.yh - calcPoint.y; - if (!trace.error_y.symmetric) hoverPoint.yerrneg = calcPoint.y - calcPoint.ys; - } - if ((trace.error_x || {}).visible) { - hoverPoint.xerr = calcPoint.xh - calcPoint.x; - if (!trace.error_x.symmetric) hoverPoint.xerrneg = calcPoint.x - calcPoint.xs; - } -} -var constants$g = { - cn: { - colorbar: "colorbar", - cbbg: "cbbg", - cbfill: "cbfill", - cbfills: "cbfills", - cbline: "cbline", - cblines: "cblines", - cbaxis: "cbaxis", - cbtitleunshift: "cbtitleunshift", - cbtitle: "cbtitle", - cboutline: "cboutline", - crisp: "crisp", - jsPlaceholder: "js-placeholder" - } -}; -var d3$d = d3Exports; -var tinycolor$2 = tinycolorExports; -var Plots$1 = plotsExports; -var Registry$e = registry; -var Axes$5 = axesExports; -var dragElement = dragelementExports; -var Lib$y = libExports; -var strTranslate$1 = Lib$y.strTranslate; -var extendFlat$8 = extend$5.extendFlat; -var setCursor2 = setcursor; -var Drawing$8 = drawingExports; -var Color$h = colorExports; -var Titles = titles; -var svgTextUtils$4 = svg_text_utils; -var flipScale = helpers$L.flipScale; -var handleAxisDefaults2 = axis_defaults; -var handleAxisPositionDefaults = position_defaults; -var axisLayoutAttrs = layout_attributes$4; -var alignmentConstants = alignment$1; -var LINE_SPACING = alignmentConstants.LINE_SPACING; -var FROM_TL = alignmentConstants.FROM_TL; -var FROM_BR = alignmentConstants.FROM_BR; -var cn = constants$g.cn; -function draw$2(gd) { - var fullLayout = gd._fullLayout; - var colorBars = fullLayout._infolayer.selectAll("g." + cn.colorbar).data(makeColorBarData(gd), function(opts) { - return opts._id; - }); - colorBars.enter().append("g").attr("class", function(opts) { - return opts._id; - }).classed(cn.colorbar, true); - colorBars.each(function(opts) { - var g = d3$d.select(this); - Lib$y.ensureSingle(g, "rect", cn.cbbg); - Lib$y.ensureSingle(g, "g", cn.cbfills); - Lib$y.ensureSingle(g, "g", cn.cblines); - Lib$y.ensureSingle(g, "g", cn.cbaxis, function(s) { - s.classed(cn.crisp, true); - }); - Lib$y.ensureSingle(g, "g", cn.cbtitleunshift, function(s) { - s.append("g").classed(cn.cbtitle, true); - }); - Lib$y.ensureSingle(g, "rect", cn.cboutline); - var done = drawColorBar(g, opts, gd); - if (done && done.then) (gd._promises || []).push(done); - if (gd._context.edits.colorbarPosition) { - makeEditable(g, opts, gd); - } - }); - colorBars.exit().each(function(opts) { - Plots$1.autoMargin(gd, opts._id); - }).remove(); - colorBars.order(); -} -function makeColorBarData(gd) { - var fullLayout = gd._fullLayout; - var calcdata = gd.calcdata; - var out = []; - var opts; - var cont; - var trace; - var cbOpt; - function initOpts(opts2) { - return extendFlat$8(opts2, { - // fillcolor can be a d3 scale, domain is z values, range is colors - // or leave it out for no fill, - // or set to a string constant for single-color fill - _fillcolor: null, - // line.color has the same options as fillcolor - _line: { color: null, width: null, dash: null }, - // levels of lines to draw. - // note that this DOES NOT determine the extent of the bar - // that's given by the domain of fillcolor - // (or line.color if no fillcolor domain) - _levels: { start: null, end: null, size: null }, - // separate fill levels (for example, heatmap coloring of a - // contour map) if this is omitted, fillcolors will be - // evaluated halfway between levels - _filllevels: null, - // for continuous colorscales: fill with a gradient instead of explicit levels - // value should be the colorscale [[0, c0], [v1, c1], ..., [1, cEnd]] - _fillgradient: null, - // when using a gradient, we need the data range specified separately - _zrange: null - }); - } - function calcOpts() { - if (typeof cbOpt.calc === "function") { - cbOpt.calc(gd, trace, opts); - } else { - opts._fillgradient = cont.reversescale ? flipScale(cont.colorscale) : cont.colorscale; - opts._zrange = [cont[cbOpt.min], cont[cbOpt.max]]; - } - } - for (var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - trace = cd[0].trace; - if (!trace._module) continue; - var moduleOpts = trace._module.colorbar; - if (trace.visible === true && moduleOpts) { - var allowsMultiplotCbs = Array.isArray(moduleOpts); - var cbOpts = allowsMultiplotCbs ? moduleOpts : [moduleOpts]; - for (var j = 0; j < cbOpts.length; j++) { - cbOpt = cbOpts[j]; - var contName = cbOpt.container; - cont = contName ? trace[contName] : trace; - if (cont && cont.showscale) { - opts = initOpts(cont.colorbar); - opts._id = "cb" + trace.uid + (allowsMultiplotCbs && contName ? "-" + contName : ""); - opts._traceIndex = trace.index; - opts._propPrefix = (contName ? contName + "." : "") + "colorbar."; - opts._meta = trace._meta; - calcOpts(); - out.push(opts); - } - } - } - } - for (var k in fullLayout._colorAxes) { - cont = fullLayout[k]; - if (cont.showscale) { - var colorAxOpts = fullLayout._colorAxes[k]; - opts = initOpts(cont.colorbar); - opts._id = "cb" + k; - opts._propPrefix = k + ".colorbar."; - opts._meta = fullLayout._meta; - cbOpt = { min: "cmin", max: "cmax" }; - if (colorAxOpts[0] !== "heatmap") { - trace = colorAxOpts[1]; - cbOpt.calc = trace._module.colorbar.calc; - } - calcOpts(); - out.push(opts); - } - } - return out; -} -function drawColorBar(g, opts, gd) { - var isVertical2 = opts.orientation === "v"; - var len = opts.len; - var lenmode = opts.lenmode; - var thickness = opts.thickness; - var thicknessmode = opts.thicknessmode; - var outlinewidth = opts.outlinewidth; - var borderwidth = opts.borderwidth; - var bgcolor = opts.bgcolor; - var xanchor = opts.xanchor; - var yanchor = opts.yanchor; - var xpad = opts.xpad; - var ypad = opts.ypad; - var optsX = opts.x; - var optsY = isVertical2 ? opts.y : 1 - opts.y; - var isPaperY = opts.yref === "paper"; - var isPaperX = opts.xref === "paper"; - var fullLayout = gd._fullLayout; - var gs = fullLayout._size; - var fillColor = opts._fillcolor; - var line2 = opts._line; - var title = opts.title; - var titleSide = title.side; - var zrange = opts._zrange || d3$d.extent((typeof fillColor === "function" ? fillColor : line2.color).domain()); - var lineColormap = typeof line2.color === "function" ? line2.color : function() { - return line2.color; - }; - var fillColormap = typeof fillColor === "function" ? fillColor : function() { - return fillColor; - }; - var levelsIn = opts._levels; - var levelsOut = calcLevels(gd, opts, zrange); - var fillLevels = levelsOut.fill; - var lineLevels = levelsOut.line; - var thickPx = Math.round(thickness * (thicknessmode === "fraction" ? isVertical2 ? gs.w : gs.h : 1)); - var thickFrac = thickPx / (isVertical2 ? gs.w : gs.h); - var lenPx = Math.round(len * (lenmode === "fraction" ? isVertical2 ? gs.h : gs.w : 1)); - var lenFrac = lenPx / (isVertical2 ? gs.h : gs.w); - var posW = isPaperX ? gs.w : gd._fullLayout.width; - var posH = isPaperY ? gs.h : gd._fullLayout.height; - var uPx = Math.round( - isVertical2 ? optsX * posW + xpad : optsY * posH + ypad - ); - var xRatio = { center: 0.5, right: 1 }[xanchor] || 0; - var yRatio = { top: 1, middle: 0.5 }[yanchor] || 0; - var uFrac = isVertical2 ? optsX - xRatio * thickFrac : optsY - yRatio * thickFrac; - var vFrac = isVertical2 ? optsY - yRatio * lenFrac : optsX - xRatio * lenFrac; - var vPx = Math.round( - isVertical2 ? posH * (1 - vFrac) : posW * vFrac - ); - opts._lenFrac = lenFrac; - opts._thickFrac = thickFrac; - opts._uFrac = uFrac; - opts._vFrac = vFrac; - var ax = opts._axis = mockColorBarAxis(gd, opts, zrange); - ax.position = thickFrac + (isVertical2 ? optsX + xpad / gs.w : optsY + ypad / gs.h); - var topOrBottom = ["top", "bottom"].indexOf(titleSide) !== -1; - if (isVertical2 && topOrBottom) { - ax.title.side = titleSide; - ax.titlex = optsX + xpad / gs.w; - ax.titley = vFrac + (title.side === "top" ? lenFrac - ypad / gs.h : ypad / gs.h); - } - if (!isVertical2 && !topOrBottom) { - ax.title.side = titleSide; - ax.titley = optsY + ypad / gs.h; - ax.titlex = vFrac + xpad / gs.w; - } - if (line2.color && opts.tickmode === "auto") { - ax.tickmode = "linear"; - ax.tick0 = levelsIn.start; - var dtick2 = levelsIn.size; - var autoNtick = Lib$y.constrain(lenPx / 50, 4, 15) + 1; - var dtFactor = (zrange[1] - zrange[0]) / ((opts.nticks || autoNtick) * dtick2); - if (dtFactor > 1) { - var dtexp = Math.pow(10, Math.floor(Math.log(dtFactor) / Math.LN10)); - dtick2 *= dtexp * Lib$y.roundUp(dtFactor / dtexp, [2, 5, 10]); - if ((Math.abs(levelsIn.start) / levelsIn.size + 1e-6) % 1 < 2e-6) { - ax.tick0 = 0; - } - } - ax.dtick = dtick2; - } - ax.domain = isVertical2 ? [ - vFrac + ypad / gs.h, - vFrac + lenFrac - ypad / gs.h - ] : [ - vFrac + xpad / gs.w, - vFrac + lenFrac - xpad / gs.w - ]; - ax.setScale(); - g.attr("transform", strTranslate$1(Math.round(gs.l), Math.round(gs.t))); - var titleCont = g.select("." + cn.cbtitleunshift).attr("transform", strTranslate$1(-Math.round(gs.l), -Math.round(gs.t))); - var ticklabelposition = ax.ticklabelposition; - var titleFontSize = ax.title.font.size; - var axLayer = g.select("." + cn.cbaxis); - var titleEl; - var titleHeight = 0; - var titleWidth = 0; - function drawTitle2(titleClass, titleOpts) { - var dfltTitleOpts = { - propContainer: ax, - propName: opts._propPrefix + "title", - traceIndex: opts._traceIndex, - _meta: opts._meta, - placeholder: fullLayout._dfltTitle.colorbar, - containerGroup: g.select("." + cn.cbtitle) - }; - var otherClass = titleClass.charAt(0) === "h" ? titleClass.substr(1) : "h" + titleClass; - g.selectAll("." + otherClass + ",." + otherClass + "-math-group").remove(); - Titles.draw(gd, titleClass, extendFlat$8(dfltTitleOpts, titleOpts || {})); - } - function drawDummyTitle() { - if (isVertical2 && topOrBottom || !isVertical2 && !topOrBottom) { - var x, y; - if (titleSide === "top") { - x = xpad + gs.l + posW * optsX; - y = ypad + gs.t + posH * (1 - vFrac - lenFrac) + 3 + titleFontSize * 0.75; - } - if (titleSide === "bottom") { - x = xpad + gs.l + posW * optsX; - y = ypad + gs.t + posH * (1 - vFrac) - 3 - titleFontSize * 0.25; - } - if (titleSide === "right") { - y = ypad + gs.t + posH * optsY + 3 + titleFontSize * 0.75; - x = xpad + gs.l + posW * vFrac; - } - drawTitle2(ax._id + "title", { - attributes: { x, y, "text-anchor": isVertical2 ? "start" : "middle" } - }); - } - } - function drawCbTitle() { - if (isVertical2 && !topOrBottom || !isVertical2 && topOrBottom) { - var pos = ax.position || 0; - var mid = ax._offset + ax._length / 2; - var x, y; - if (titleSide === "right") { - y = mid; - x = gs.l + posW * pos + 10 + titleFontSize * (ax.showticklabels ? 1 : 0.5); - } else { - x = mid; - if (titleSide === "bottom") { - y = gs.t + posH * pos + 10 + (ticklabelposition.indexOf("inside") === -1 ? ax.tickfont.size : 0) + (ax.ticks !== "intside" ? opts.ticklen || 0 : 0); - } - if (titleSide === "top") { - var nlines = title.text.split("
").length; - y = gs.t + posH * pos + 10 - thickPx - LINE_SPACING * titleFontSize * nlines; - } - } - drawTitle2((isVertical2 ? ( - // the 'h' + is a hack to get around the fact that - // convertToTspans rotates any 'y...' class by 90 degrees. - // TODO: find a better way to control this. - "h" - ) : "v") + ax._id + "title", { - avoid: { - selection: d3$d.select(gd).selectAll("g." + ax._id + "tick"), - side: titleSide, - offsetTop: isVertical2 ? 0 : gs.t, - offsetLeft: isVertical2 ? gs.l : 0, - maxShift: isVertical2 ? fullLayout.width : fullLayout.height - }, - attributes: { x, y, "text-anchor": "middle" }, - transform: { rotate: isVertical2 ? -90 : 0, offset: 0 } - }); - } - } - function drawAxis() { - if (!isVertical2 && !topOrBottom || isVertical2 && topOrBottom) { - var titleGroup = g.select("." + cn.cbtitle); - var titleText = titleGroup.select("text"); - var titleTrans = [-outlinewidth / 2, outlinewidth / 2]; - var mathJaxNode = titleGroup.select(".h" + ax._id + "title-math-group").node(); - var lineSize = 15.6; - if (titleText.node()) { - lineSize = parseInt(titleText.node().style.fontSize, 10) * LINE_SPACING; - } - var bb; - if (mathJaxNode) { - bb = Drawing$8.bBox(mathJaxNode); - titleWidth = bb.width; - titleHeight = bb.height; - if (titleHeight > lineSize) { - titleTrans[1] -= (titleHeight - lineSize) / 2; - } - } else if (titleText.node() && !titleText.classed(cn.jsPlaceholder)) { - bb = Drawing$8.bBox(titleText.node()); - titleWidth = bb.width; - titleHeight = bb.height; - } - if (isVertical2) { - if (titleHeight) { - titleHeight += 5; - if (titleSide === "top") { - ax.domain[1] -= titleHeight / gs.h; - titleTrans[1] *= -1; - } else { - ax.domain[0] += titleHeight / gs.h; - var nlines = svgTextUtils$4.lineCount(titleText); - titleTrans[1] += (1 - nlines) * lineSize; - } - titleGroup.attr("transform", strTranslate$1(titleTrans[0], titleTrans[1])); - ax.setScale(); - } - } else { - if (titleWidth) { - if (titleSide === "right") { - ax.domain[0] += (titleWidth + titleFontSize / 2) / gs.w; - } - titleGroup.attr("transform", strTranslate$1(titleTrans[0], titleTrans[1])); - ax.setScale(); - } - } - } - g.selectAll("." + cn.cbfills + ",." + cn.cblines).attr( - "transform", - isVertical2 ? strTranslate$1(0, Math.round(gs.h * (1 - ax.domain[1]))) : strTranslate$1(Math.round(gs.w * ax.domain[0]), 0) - ); - axLayer.attr( - "transform", - isVertical2 ? strTranslate$1(0, Math.round(-gs.t)) : strTranslate$1(Math.round(-gs.l), 0) - ); - var fills = g.select("." + cn.cbfills).selectAll("rect." + cn.cbfill).attr("style", "").data(fillLevels); - fills.enter().append("rect").classed(cn.cbfill, true).attr("style", ""); - fills.exit().remove(); - var zBounds = zrange.map(ax.c2p).map(Math.round).sort(function(a, b) { - return a - b; - }); - fills.each(function(d, i) { - var z = [ - i === 0 ? zrange[0] : (fillLevels[i] + fillLevels[i - 1]) / 2, - i === fillLevels.length - 1 ? zrange[1] : (fillLevels[i] + fillLevels[i + 1]) / 2 - ].map(ax.c2p).map(Math.round); - if (isVertical2) { - z[1] = Lib$y.constrain(z[1] + (z[1] > z[0]) ? 1 : -1, zBounds[0], zBounds[1]); - } - var fillEl = d3$d.select(this).attr(isVertical2 ? "x" : "y", uPx).attr(isVertical2 ? "y" : "x", d3$d.min(z)).attr(isVertical2 ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical2 ? "height" : "width", Math.max(d3$d.max(z) - d3$d.min(z), 2)); - if (opts._fillgradient) { - Drawing$8.gradient(fillEl, gd, opts._id, isVertical2 ? "vertical" : "horizontalreversed", opts._fillgradient, "fill"); - } else { - var colorString = fillColormap(d).replace("e-", ""); - fillEl.attr("fill", tinycolor$2(colorString).toHexString()); - } - }); - var lines = g.select("." + cn.cblines).selectAll("path." + cn.cbline).data(line2.color && line2.width ? lineLevels : []); - lines.enter().append("path").classed(cn.cbline, true); - lines.exit().remove(); - lines.each(function(d) { - var a = uPx; - var b = Math.round(ax.c2p(d)) + line2.width / 2 % 1; - d3$d.select(this).attr( - "d", - "M" + (isVertical2 ? a + "," + b : b + "," + a) + (isVertical2 ? "h" : "v") + thickPx - ).call(Drawing$8.lineGroupStyle, line2.width, lineColormap(d), line2.dash); - }); - axLayer.selectAll("g." + ax._id + "tick,path").remove(); - var shift = uPx + thickPx + (outlinewidth || 0) / 2 - (opts.ticks === "outside" ? 1 : 0); - var vals = Axes$5.calcTicks(ax); - var tickSign = Axes$5.getTickSigns(ax)[2]; - Axes$5.drawTicks(gd, ax, { - vals: ax.ticks === "inside" ? Axes$5.clipEnds(ax, vals) : vals, - layer: axLayer, - path: Axes$5.makeTickPath(ax, shift, tickSign), - transFn: Axes$5.makeTransTickFn(ax) - }); - return Axes$5.drawLabels(gd, ax, { - vals, - layer: axLayer, - transFn: Axes$5.makeTransTickLabelFn(ax), - labelFns: Axes$5.makeLabelFns(ax, shift) - }); - } - function positionCB() { - var bb; - var innerThickness = thickPx + outlinewidth / 2; - if (ticklabelposition.indexOf("inside") === -1) { - bb = Drawing$8.bBox(axLayer.node()); - innerThickness += isVertical2 ? bb.width : bb.height; - } - titleEl = titleCont.select("text"); - var titleWidth2 = 0; - var topSideVertical = isVertical2 && titleSide === "top"; - var rightSideHorizontal = !isVertical2 && titleSide === "right"; - var moveY = 0; - if (titleEl.node() && !titleEl.classed(cn.jsPlaceholder)) { - var _titleHeight; - var mathJaxNode = titleCont.select(".h" + ax._id + "title-math-group").node(); - if (mathJaxNode && (isVertical2 && topOrBottom || !isVertical2 && !topOrBottom)) { - bb = Drawing$8.bBox(mathJaxNode); - titleWidth2 = bb.width; - _titleHeight = bb.height; - } else { - bb = Drawing$8.bBox(titleCont.node()); - titleWidth2 = bb.right - gs.l - (isVertical2 ? uPx : vPx); - _titleHeight = bb.bottom - gs.t - (isVertical2 ? vPx : uPx); - if (!isVertical2 && titleSide === "top") { - innerThickness += bb.height; - moveY = bb.height; - } - } - if (rightSideHorizontal) { - titleEl.attr("transform", strTranslate$1(titleWidth2 / 2 + titleFontSize / 2, 0)); - titleWidth2 *= 2; - } - innerThickness = Math.max( - innerThickness, - isVertical2 ? titleWidth2 : _titleHeight - ); - } - var outerThickness = (isVertical2 ? xpad : ypad) * 2 + innerThickness + borderwidth + outlinewidth / 2; - var hColorbarMoveTitle = 0; - if (!isVertical2 && title.text && yanchor === "bottom" && optsY <= 0) { - hColorbarMoveTitle = outerThickness / 2; - outerThickness += hColorbarMoveTitle; - moveY += hColorbarMoveTitle; - } - fullLayout._hColorbarMoveTitle = hColorbarMoveTitle; - fullLayout._hColorbarMoveCBTitle = moveY; - var extraW = borderwidth + outlinewidth; - var lx = (isVertical2 ? uPx : vPx) - extraW / 2 - (isVertical2 ? xpad : 0); - var ly = (isVertical2 ? vPx : uPx) - (isVertical2 ? lenPx : ypad + moveY - hColorbarMoveTitle); - g.select("." + cn.cbbg).attr("x", lx).attr("y", ly).attr(isVertical2 ? "width" : "height", Math.max(outerThickness - hColorbarMoveTitle, 2)).attr(isVertical2 ? "height" : "width", Math.max(lenPx + extraW, 2)).call(Color$h.fill, bgcolor).call(Color$h.stroke, opts.bordercolor).style("stroke-width", borderwidth); - var moveX = rightSideHorizontal ? Math.max(titleWidth2 - 10, 0) : 0; - g.selectAll("." + cn.cboutline).attr("x", (isVertical2 ? uPx : vPx + xpad) + moveX).attr("y", (isVertical2 ? vPx + ypad - lenPx : uPx) + (topSideVertical ? titleHeight : 0)).attr(isVertical2 ? "width" : "height", Math.max(thickPx, 2)).attr(isVertical2 ? "height" : "width", Math.max(lenPx - (isVertical2 ? 2 * ypad + titleHeight : 2 * xpad + moveX), 2)).call(Color$h.stroke, opts.outlinecolor).style({ - fill: "none", - "stroke-width": outlinewidth - }); - var xShift = isVertical2 ? xRatio * outerThickness : 0; - var yShift = isVertical2 ? 0 : (1 - yRatio) * outerThickness - moveY; - xShift = isPaperX ? gs.l - xShift : -xShift; - yShift = isPaperY ? gs.t - yShift : -yShift; - g.attr("transform", strTranslate$1( - xShift, - yShift - )); - if (!isVertical2 && (borderwidth || tinycolor$2(bgcolor).getAlpha() && !tinycolor$2.equals(fullLayout.paper_bgcolor, bgcolor))) { - var tickLabels = axLayer.selectAll("text"); - var numTicks = tickLabels[0].length; - var border = g.select("." + cn.cbbg).node(); - var oBb = Drawing$8.bBox(border); - var oTr = Drawing$8.getTranslate(g); - var TEXTPAD2 = 2; - tickLabels.each(function(d, i) { - var first = 0; - var last = numTicks - 1; - if (i === first || i === last) { - var iBb = Drawing$8.bBox(this); - var iTr = Drawing$8.getTranslate(this); - var deltaX; - if (i === last) { - var iRight = iBb.right + iTr.x; - var oRight = oBb.right + oTr.x + vPx - borderwidth - TEXTPAD2 + optsX; - deltaX = oRight - iRight; - if (deltaX > 0) deltaX = 0; - } else if (i === first) { - var iLeft = iBb.left + iTr.x; - var oLeft = oBb.left + oTr.x + vPx + borderwidth + TEXTPAD2; - deltaX = oLeft - iLeft; - if (deltaX < 0) deltaX = 0; - } - if (deltaX) { - if (numTicks < 3) { - this.setAttribute( - "transform", - "translate(" + deltaX + ",0) " + this.getAttribute("transform") - ); - } else { - this.setAttribute("visibility", "hidden"); - } - } - } - }); - } - var marginOpts = {}; - var lFrac = FROM_TL[xanchor]; - var rFrac = FROM_BR[xanchor]; - var tFrac = FROM_TL[yanchor]; - var bFrac = FROM_BR[yanchor]; - var extraThickness = outerThickness - thickPx; - if (isVertical2) { - if (lenmode === "pixels") { - marginOpts.y = optsY; - marginOpts.t = lenPx * tFrac; - marginOpts.b = lenPx * bFrac; - } else { - marginOpts.t = marginOpts.b = 0; - marginOpts.yt = optsY + len * tFrac; - marginOpts.yb = optsY - len * bFrac; - } - if (thicknessmode === "pixels") { - marginOpts.x = optsX; - marginOpts.l = outerThickness * lFrac; - marginOpts.r = outerThickness * rFrac; - } else { - marginOpts.l = extraThickness * lFrac; - marginOpts.r = extraThickness * rFrac; - marginOpts.xl = optsX - thickness * lFrac; - marginOpts.xr = optsX + thickness * rFrac; - } - } else { - if (lenmode === "pixels") { - marginOpts.x = optsX; - marginOpts.l = lenPx * lFrac; - marginOpts.r = lenPx * rFrac; - } else { - marginOpts.l = marginOpts.r = 0; - marginOpts.xl = optsX + len * lFrac; - marginOpts.xr = optsX - len * rFrac; - } - if (thicknessmode === "pixels") { - marginOpts.y = 1 - optsY; - marginOpts.t = outerThickness * tFrac; - marginOpts.b = outerThickness * bFrac; - } else { - marginOpts.t = extraThickness * tFrac; - marginOpts.b = extraThickness * bFrac; - marginOpts.yt = optsY - thickness * tFrac; - marginOpts.yb = optsY + thickness * bFrac; - } - } - var sideY = opts.y < 0.5 ? "b" : "t"; - var sideX = opts.x < 0.5 ? "l" : "r"; - gd._fullLayout._reservedMargin[opts._id] = {}; - var possibleReservedMargins = { - r: fullLayout.width - lx - xShift, - l: lx + marginOpts.r, - b: fullLayout.height - ly - yShift, - t: ly + marginOpts.b - }; - if (isPaperX && isPaperY) { - Plots$1.autoMargin(gd, opts._id, marginOpts); - } else if (isPaperX) { - gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY]; - } else if (isPaperY) { - gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX]; - } else { - if (isVertical2) { - gd._fullLayout._reservedMargin[opts._id][sideX] = possibleReservedMargins[sideX]; - } else { - gd._fullLayout._reservedMargin[opts._id][sideY] = possibleReservedMargins[sideY]; - } - } - } - return Lib$y.syncOrAsync([ - Plots$1.previousPromises, - drawDummyTitle, - drawAxis, - drawCbTitle, - Plots$1.previousPromises, - positionCB - ], gd); -} -function makeEditable(g, opts, gd) { - var isVertical2 = opts.orientation === "v"; - var fullLayout = gd._fullLayout; - var gs = fullLayout._size; - var t02, xf, yf; - dragElement.init({ - element: g.node(), - gd, - prepFn: function() { - t02 = g.attr("transform"); - setCursor2(g); - }, - moveFn: function(dx, dy) { - g.attr("transform", t02 + strTranslate$1(dx, dy)); - xf = dragElement.align( - (isVertical2 ? opts._uFrac : opts._vFrac) + dx / gs.w, - isVertical2 ? opts._thickFrac : opts._lenFrac, - 0, - 1, - opts.xanchor - ); - yf = dragElement.align( - (isVertical2 ? opts._vFrac : 1 - opts._uFrac) - dy / gs.h, - isVertical2 ? opts._lenFrac : opts._thickFrac, - 0, - 1, - opts.yanchor - ); - var csr = dragElement.getCursor(xf, yf, opts.xanchor, opts.yanchor); - setCursor2(g, csr); - }, - doneFn: function() { - setCursor2(g); - if (xf !== void 0 && yf !== void 0) { - var update2 = {}; - update2[opts._propPrefix + "x"] = xf; - update2[opts._propPrefix + "y"] = yf; - if (opts._traceIndex !== void 0) { - Registry$e.call("_guiRestyle", gd, update2, opts._traceIndex); - } else { - Registry$e.call("_guiRelayout", gd, update2); - } - } - } - }); -} -function calcLevels(gd, opts, zrange) { - var levelsIn = opts._levels; - var lineLevels = []; - var fillLevels = []; - var l; - var i; - var l0 = levelsIn.end + levelsIn.size / 100; - var ls = levelsIn.size; - var zr0 = 1.001 * zrange[0] - 1e-3 * zrange[1]; - var zr1 = 1.001 * zrange[1] - 1e-3 * zrange[0]; - for (i = 0; i < 1e5; i++) { - l = levelsIn.start + i * ls; - if (ls > 0 ? l >= l0 : l <= l0) break; - if (l > zr0 && l < zr1) lineLevels.push(l); - } - if (opts._fillgradient) { - fillLevels = [0]; - } else if (typeof opts._fillcolor === "function") { - var fillLevelsIn = opts._filllevels; - if (fillLevelsIn) { - l0 = fillLevelsIn.end + fillLevelsIn.size / 100; - ls = fillLevelsIn.size; - for (i = 0; i < 1e5; i++) { - l = fillLevelsIn.start + i * ls; - if (ls > 0 ? l >= l0 : l <= l0) break; - if (l > zrange[0] && l < zrange[1]) fillLevels.push(l); - } - } else { - fillLevels = lineLevels.map(function(v) { - return v - levelsIn.size / 2; - }); - fillLevels.push(fillLevels[fillLevels.length - 1] + levelsIn.size); - } - } else if (opts._fillcolor && typeof opts._fillcolor === "string") { - fillLevels = [0]; - } - if (levelsIn.size < 0) { - lineLevels.reverse(); - fillLevels.reverse(); - } - return { line: lineLevels, fill: fillLevels }; -} -function mockColorBarAxis(gd, opts, zrange) { - var fullLayout = gd._fullLayout; - var isVertical2 = opts.orientation === "v"; - var cbAxisIn = { - type: "linear", - range: zrange, - tickmode: opts.tickmode, - nticks: opts.nticks, - tick0: opts.tick0, - dtick: opts.dtick, - tickvals: opts.tickvals, - ticktext: opts.ticktext, - ticks: opts.ticks, - ticklen: opts.ticklen, - tickwidth: opts.tickwidth, - tickcolor: opts.tickcolor, - showticklabels: opts.showticklabels, - labelalias: opts.labelalias, - ticklabelposition: opts.ticklabelposition, - ticklabeloverflow: opts.ticklabeloverflow, - ticklabelstep: opts.ticklabelstep, - tickfont: opts.tickfont, - tickangle: opts.tickangle, - tickformat: opts.tickformat, - exponentformat: opts.exponentformat, - minexponent: opts.minexponent, - separatethousands: opts.separatethousands, - showexponent: opts.showexponent, - showtickprefix: opts.showtickprefix, - tickprefix: opts.tickprefix, - showticksuffix: opts.showticksuffix, - ticksuffix: opts.ticksuffix, - title: opts.title, - showline: true, - anchor: "free", - side: isVertical2 ? "right" : "bottom", - position: 1 - }; - var letter = isVertical2 ? "y" : "x"; - var cbAxisOut = { - type: "linear", - _id: letter + opts._id - }; - var axisOptions = { - letter, - font: fullLayout.font, - noAutotickangles: letter === "y", - noHover: true, - noTickson: true, - noTicklabelmode: true, - noInsideRange: true, - calendar: fullLayout.calendar - // not really necessary (yet?) - }; - function coerce2(attr, dflt) { - return Lib$y.coerce(cbAxisIn, cbAxisOut, axisLayoutAttrs, attr, dflt); - } - handleAxisDefaults2(cbAxisIn, cbAxisOut, coerce2, axisOptions, fullLayout); - handleAxisPositionDefaults(cbAxisIn, cbAxisOut, coerce2, axisOptions); - return cbAxisOut; -} -var draw_1 = { - draw: draw$2 -}; -var colorbar = { - moduleType: "component", - name: "colorbar", - attributes: attributes$J, - supplyDefaults: defaults$o, - draw: draw_1.draw, - hasColorbar: has_colorbar -}; -var legend = { - moduleType: "component", - name: "legend", - layoutAttributes: attributes$G, - supplyLayoutDefaults: defaults$m, - draw: draw$d, - style: style$8 -}; -var localeEn = { - moduleType: "locale", - name: "en", - dictionary: { - "Click to enter Colorscale title": "Click to enter Colourscale title" - }, - format: { - days: ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"], - shortDays: ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"], - months: [ - "January", - "February", - "March", - "April", - "May", - "June", - "July", - "August", - "September", - "October", - "November", - "December" - ], - shortMonths: [ - "Jan", - "Feb", - "Mar", - "Apr", - "May", - "Jun", - "Jul", - "Aug", - "Sep", - "Oct", - "Nov", - "Dec" - ], - periods: ["AM", "PM"], - dateTime: "%a %b %e %X %Y", - date: "%d/%m/%Y", - time: "%H:%M:%S", - decimal: ".", - thousands: ",", - grouping: [3], - currency: ["$", ""], - year: "%Y", - month: "%b %Y", - dayMonth: "%b %-d", - dayMonthYear: "%b %-d, %Y" - } -}; -var localeEnUs = { - moduleType: "locale", - name: "en-US", - dictionary: { - "Click to enter Colorscale title": "Click to enter Colorscale title" - }, - format: { - date: "%m/%d/%Y" - } -}; -var Registry$d = registry; -var Lib$x = libExports; -var extendFlat$7 = Lib$x.extendFlat; -var extendDeep = Lib$x.extendDeep; -function cloneLayoutOverride(tileClass) { - var override; - switch (tileClass) { - case "themes__thumb": - override = { - autosize: true, - width: 150, - height: 150, - title: { text: "" }, - showlegend: false, - margin: { l: 5, r: 5, t: 5, b: 5, pad: 0 }, - annotations: [] - }; - break; - case "thumbnail": - override = { - title: { text: "" }, - hidesources: true, - showlegend: false, - borderwidth: 0, - bordercolor: "", - margin: { l: 1, r: 1, t: 1, b: 1, pad: 0 }, - annotations: [] - }; - break; - default: - override = {}; - } - return override; -} -function keyIsAxis(keyName) { - var types = ["xaxis", "yaxis", "zaxis"]; - return types.indexOf(keyName.slice(0, 5)) > -1; -} -var cloneplot = function clonePlot(graphObj, options) { - var i; - var oldData = graphObj.data; - var oldLayout = graphObj.layout; - var newData = extendDeep([], oldData); - var newLayout = extendDeep({}, oldLayout, cloneLayoutOverride(options.tileClass)); - var context2 = graphObj._context || {}; - if (options.width) newLayout.width = options.width; - if (options.height) newLayout.height = options.height; - if (options.tileClass === "thumbnail" || options.tileClass === "themes__thumb") { - newLayout.annotations = []; - var keys = Object.keys(newLayout); - for (i = 0; i < keys.length; i++) { - if (keyIsAxis(keys[i])) { - newLayout[keys[i]].title = { text: "" }; - } - } - for (i = 0; i < newData.length; i++) { - var trace = newData[i]; - trace.showscale = false; - if (trace.marker) trace.marker.showscale = false; - if (Registry$d.traceIs(trace, "pie-like")) trace.textposition = "none"; - } - } - if (Array.isArray(options.annotations)) { - for (i = 0; i < options.annotations.length; i++) { - newLayout.annotations.push(options.annotations[i]); - } - } - var sceneIds = Object.keys(newLayout).filter(function(key) { - return key.match(/^scene\d*$/); - }); - if (sceneIds.length) { - var axesImageOverride = {}; - if (options.tileClass === "thumbnail") { - axesImageOverride = { - title: { text: "" }, - showaxeslabels: false, - showticklabels: false, - linetickenable: false - }; - } - for (i = 0; i < sceneIds.length; i++) { - var scene = newLayout[sceneIds[i]]; - if (!scene.xaxis) { - scene.xaxis = {}; - } - if (!scene.yaxis) { - scene.yaxis = {}; - } - if (!scene.zaxis) { - scene.zaxis = {}; - } - extendFlat$7(scene.xaxis, axesImageOverride); - extendFlat$7(scene.yaxis, axesImageOverride); - extendFlat$7(scene.zaxis, axesImageOverride); - scene._scene = null; - } - } - var gd = document.createElement("div"); - if (options.tileClass) gd.className = options.tileClass; - var plotTile = { - gd, - td: gd, - // for external (image server) compatibility - layout: newLayout, - data: newData, - config: { - staticPlot: options.staticPlot === void 0 ? true : options.staticPlot, - plotGlPixelRatio: options.plotGlPixelRatio === void 0 ? 2 : options.plotGlPixelRatio, - displaylogo: options.displaylogo || false, - showLink: options.showLink || false, - showTips: options.showTips || false, - mapboxAccessToken: context2.mapboxAccessToken - } - }; - if (options.setBackground !== "transparent") { - plotTile.config.setBackground = options.setBackground || "opaque"; - } - plotTile.gd.defaultLayout = cloneLayoutOverride(options.tileClass); - return plotTile; -}; -var EventEmitter = eventsExports.EventEmitter; -var Registry$c = registry; -var Lib$w = libExports; -var helpers$f = helpers$o; -var clonePlot2 = cloneplot; -var toSVG2 = tosvg; -var svgToImg = svgtoimg; -function toImage(gd, opts) { - var ev = new EventEmitter(); - var clone2 = clonePlot2(gd, {}); - var clonedGd = clone2.gd; - clonedGd.style.position = "absolute"; - clonedGd.style.left = "-5000px"; - document.body.appendChild(clonedGd); - function wait() { - var delay = helpers$f.getDelay(clonedGd._fullLayout); - setTimeout(function() { - var svg = toSVG2(clonedGd); - var canvas2 = document.createElement("canvas"); - canvas2.id = Lib$w.randstr(); - ev = svgToImg({ - format: opts.format, - width: clonedGd._fullLayout.width, - height: clonedGd._fullLayout.height, - canvas: canvas2, - emitter: ev, - svg - }); - ev.clean = function() { - if (clonedGd) document.body.removeChild(clonedGd); - }; - }, delay); - } - var redrawFunc = helpers$f.getRedrawFunc(clonedGd); - Registry$c.call("_doPlot", clonedGd, clone2.data, clone2.layout, clone2.config).then(redrawFunc).then(wait).catch(function(err) { - ev.emit("error", err); - }); - return ev; -} -var toimage = toImage; -var helpers$e = helpers$o; -var Snapshot = { - getDelay: helpers$e.getDelay, - getRedrawFunc: helpers$e.getRedrawFunc, - clone: cloneplot, - toSVG: tosvg, - svgToImg: svgtoimg, - toImage: toimage, - downloadImage: download -}; -var snapshot = Snapshot; -(function(exports2) { - exports2.version = version$2.version; - var Registry2 = registry; - var register = exports2.register = Registry2.register; - var plotApi2 = plot_api$1; - var methodNames = Object.keys(plotApi2); - for (var i = 0; i < methodNames.length; i++) { - var name2 = methodNames[i]; - if (name2.charAt(0) !== "_") exports2[name2] = plotApi2[name2]; - register({ - moduleType: "apiMethod", - name: name2, - fn: plotApi2[name2] - }); - } - register(scatter$1); - register([ - annotations, - annotations3d, - selections, - shapes, - images, - updatemenus, - sliders, - rangeslider, - rangeselector, - grid, - errorbars, - colorscale, - colorbar, - legend, - // legend needs to come after shape | legend defaults depends on shapes - fx$1, - // fx needs to come after legend | unified hover defaults depends on legends - modebar - ]); - register([ - localeEn, - localeEnUs - ]); - if (window.PlotlyLocales && Array.isArray(window.PlotlyLocales)) { - register(window.PlotlyLocales); - delete window.PlotlyLocales; - } - exports2.Icons = ploticon; - var Fx2 = fx$1; - var Plots2 = plotsExports; - exports2.Plots = { - resize: Plots2.resize, - graphJson: Plots2.graphJson, - sendDataToCloud: Plots2.sendDataToCloud - }; - exports2.Fx = { - hover: Fx2.hover, - unhover: Fx2.unhover, - loneHover: Fx2.loneHover, - loneUnhover: Fx2.loneUnhover - }; - exports2.Snapshot = snapshot; - exports2.PlotSchema = plot_schema; -})(core$1); -var core = core$1; -const Plotly = /* @__PURE__ */ index$3.getDefaultExportFromCjs(core); -var constants$f = { - // padding in pixels around text - TEXTPAD: 3, - // 'value' and 'label' are not really necessary for bar traces, - // but they were made available to `texttemplate` (maybe by accident) - // via tokens `%{value}` and `%{label}` starting in 1.50.0, - // so let's include them in the event data also. - eventDataKeys: ["value", "label"] -}; -var scatterAttrs$2 = attributes$A; -var axisHoverFormat$3 = axis_format_attributes.axisHoverFormat; -var hovertemplateAttrs$4 = template_attributes.hovertemplateAttrs; -var texttemplateAttrs$4 = template_attributes.texttemplateAttrs; -var colorScaleAttrs$3 = attributes$I; -var fontAttrs$3 = font_attributes; -var constants$e = constants$f; -var pattern$3 = attributes$M.pattern; -var extendFlat$6 = extend$5.extendFlat; -var textFontAttrs$1 = fontAttrs$3({ - editType: "calc", - arrayOk: true, - colorEditType: "style", - description: "" -}); -var scatterMarkerAttrs$1 = scatterAttrs$2.marker; -var scatterMarkerLineAttrs$1 = scatterMarkerAttrs$1.line; -var markerLineWidth = extendFlat$6( - {}, - scatterMarkerLineAttrs$1.width, - { dflt: 0 } -); -var markerLine = extendFlat$6({ - width: markerLineWidth, - editType: "calc" -}, colorScaleAttrs$3("marker.line")); -var marker = extendFlat$6({ - line: markerLine, - editType: "calc" -}, colorScaleAttrs$3("marker"), { - opacity: { - valType: "number", - arrayOk: true, - dflt: 1, - min: 0, - max: 1, - editType: "style", - description: "Sets the opacity of the bars." - }, - pattern: pattern$3, - cornerradius: { - valType: "any", - editType: "calc", - description: [ - "Sets the rounding of corners. May be an integer number of pixels,", - "or a percentage of bar width (as a string ending in %). Defaults to `layout.barcornerradius`.", - "In stack or relative barmode, the first trace to set cornerradius is used for the whole stack." - ].join(" ") - } -}); -var attributes$e = { - x: scatterAttrs$2.x, - x0: scatterAttrs$2.x0, - dx: scatterAttrs$2.dx, - y: scatterAttrs$2.y, - y0: scatterAttrs$2.y0, - dy: scatterAttrs$2.dy, - xperiod: scatterAttrs$2.xperiod, - yperiod: scatterAttrs$2.yperiod, - xperiod0: scatterAttrs$2.xperiod0, - yperiod0: scatterAttrs$2.yperiod0, - xperiodalignment: scatterAttrs$2.xperiodalignment, - yperiodalignment: scatterAttrs$2.yperiodalignment, - xhoverformat: axisHoverFormat$3("x"), - yhoverformat: axisHoverFormat$3("y"), - text: scatterAttrs$2.text, - texttemplate: texttemplateAttrs$4({ editType: "plot" }, { - keys: constants$e.eventDataKeys - }), - hovertext: scatterAttrs$2.hovertext, - hovertemplate: hovertemplateAttrs$4({}, { - keys: constants$e.eventDataKeys - }), - textposition: { - valType: "enumerated", - values: ["inside", "outside", "auto", "none"], - dflt: "auto", - arrayOk: true, - editType: "calc", - description: [ - "Specifies the location of the `text`.", - "*inside* positions `text` inside, next to the bar end", - "(rotated and scaled if needed).", - "*outside* positions `text` outside, next to the bar end", - "(scaled if needed), unless there is another bar stacked on", - "this one, then the text gets pushed inside.", - "*auto* tries to position `text` inside the bar, but if", - "the bar is too small and no bar is stacked on this one", - "the text is moved outside.", - "If *none*, no text appears." - ].join(" ") - }, - insidetextanchor: { - valType: "enumerated", - values: ["end", "middle", "start"], - dflt: "end", - editType: "plot", - description: [ - "Determines if texts are kept at center or start/end points in `textposition` *inside* mode." - ].join(" ") - }, - textangle: { - valType: "angle", - dflt: "auto", - editType: "plot", - description: [ - "Sets the angle of the tick labels with respect to the bar.", - "For example, a `tickangle` of -90 draws the tick labels", - "vertically. With *auto* the texts may automatically be", - "rotated to fit with the maximum size in bars." - ].join(" ") - }, - textfont: extendFlat$6({}, textFontAttrs$1, { - description: "Sets the font used for `text`." - }), - insidetextfont: extendFlat$6({}, textFontAttrs$1, { - description: "Sets the font used for `text` lying inside the bar." - }), - outsidetextfont: extendFlat$6({}, textFontAttrs$1, { - description: "Sets the font used for `text` lying outside the bar." - }), - constraintext: { - valType: "enumerated", - values: ["inside", "outside", "both", "none"], - dflt: "both", - editType: "calc", - description: [ - "Constrain the size of text inside or outside a bar to be no", - "larger than the bar itself." - ].join(" ") - }, - cliponaxis: extendFlat$6({}, scatterAttrs$2.cliponaxis, { - description: [ - "Determines whether the text nodes", - "are clipped about the subplot axes.", - "To show the text nodes above axis lines and tick labels,", - "make sure to set `xaxis.layer` and `yaxis.layer` to *below traces*." - ].join(" ") - }), - orientation: { - valType: "enumerated", - values: ["v", "h"], - editType: "calc+clearAxisTypes", - description: [ - "Sets the orientation of the bars.", - "With *v* (*h*), the value of the each bar spans", - "along the vertical (horizontal)." - ].join(" ") - }, - base: { - valType: "any", - dflt: null, - arrayOk: true, - editType: "calc", - description: [ - "Sets where the bar base is drawn (in position axis units).", - "In *stack* or *relative* barmode,", - "traces that set *base* will be excluded", - "and drawn in *overlay* mode instead." - ].join(" ") - }, - offset: { - valType: "number", - dflt: null, - arrayOk: true, - editType: "calc", - description: [ - "Shifts the position where the bar is drawn", - "(in position axis units).", - "In *group* barmode,", - "traces that set *offset* will be excluded", - "and drawn in *overlay* mode instead." - ].join(" ") - }, - width: { - valType: "number", - dflt: null, - min: 0, - arrayOk: true, - editType: "calc", - description: [ - "Sets the bar width (in position axis units)." - ].join(" ") - }, - marker, - offsetgroup: scatterAttrs$2.offsetgroup, - alignmentgroup: scatterAttrs$2.alignmentgroup, - selected: { - marker: { - opacity: scatterAttrs$2.selected.marker.opacity, - color: scatterAttrs$2.selected.marker.color, - editType: "style" - }, - textfont: scatterAttrs$2.selected.textfont, - editType: "style" - }, - unselected: { - marker: { - opacity: scatterAttrs$2.unselected.marker.opacity, - color: scatterAttrs$2.unselected.marker.color, - editType: "style" - }, - textfont: scatterAttrs$2.unselected.textfont, - editType: "style" - }, - zorder: scatterAttrs$2.zorder, - _deprecated: { - bardir: { - valType: "enumerated", - editType: "calc", - values: ["v", "h"], - description: "Renamed to `orientation`." - } - } -}; -var layout_attributes$2 = { - barmode: { - valType: "enumerated", - values: ["stack", "group", "overlay", "relative"], - dflt: "group", - editType: "calc", - description: [ - "Determines how bars at the same location coordinate", - "are displayed on the graph.", - "With *stack*, the bars are stacked on top of one another", - "With *relative*, the bars are stacked on top of one another,", - "with negative values below the axis, positive values above", - "With *group*, the bars are plotted next to one another", - "centered around the shared location.", - "With *overlay*, the bars are plotted over one another,", - "you might need to reduce *opacity* to see multiple bars." - ].join(" ") - }, - barnorm: { - valType: "enumerated", - values: ["", "fraction", "percent"], - dflt: "", - editType: "calc", - description: [ - "Sets the normalization for bar traces on the graph.", - "With *fraction*, the value of each bar is divided by the sum of all", - "values at that location coordinate.", - "*percent* is the same but multiplied by 100 to show percentages." - ].join(" ") - }, - bargap: { - valType: "number", - min: 0, - max: 1, - editType: "calc", - description: [ - "Sets the gap (in plot fraction) between bars of", - "adjacent location coordinates." - ].join(" ") - }, - bargroupgap: { - valType: "number", - min: 0, - max: 1, - dflt: 0, - editType: "calc", - description: [ - "Sets the gap (in plot fraction) between bars of", - "the same location coordinate." - ].join(" ") - }, - barcornerradius: { - valType: "any", - editType: "calc", - description: [ - "Sets the rounding of bar corners. May be an integer number of pixels,", - "or a percentage of bar width (as a string ending in %)." - ].join(" ") - } -}; -var Color$g = colorExports; -var hasColorscale$2 = helpers$L.hasColorscale; -var colorscaleDefaults$1 = defaults$n; -var coercePattern$1 = libExports.coercePattern; -var style_defaults = function handleStyleDefaults(traceIn, traceOut, coerce2, defaultColor, layout) { - var markerColor = coerce2("marker.color", defaultColor); - var hasMarkerColorscale = hasColorscale$2(traceIn, "marker"); - if (hasMarkerColorscale) { - colorscaleDefaults$1( - traceIn, - traceOut, - layout, - coerce2, - { prefix: "marker.", cLetter: "c" } - ); - } - coerce2("marker.line.color", Color$g.defaultLine); - if (hasColorscale$2(traceIn, "marker.line")) { - colorscaleDefaults$1( - traceIn, - traceOut, - layout, - coerce2, - { prefix: "marker.line.", cLetter: "c" } - ); - } - coerce2("marker.line.width"); - coerce2("marker.opacity"); - coercePattern$1(coerce2, "marker.pattern", markerColor, hasMarkerColorscale); - coerce2("selected.marker.color"); - coerce2("unselected.marker.color"); -}; -var isNumeric$8 = fastIsnumeric; -var Lib$v = libExports; -var Color$f = colorExports; -var Registry$b = registry; -var handleXYDefaults$1 = xy_defaults; -var handlePeriodDefaults$2 = period_defaults; -var handleStyleDefaults$1 = style_defaults; -var handleGroupingDefaults$1 = grouping_defaults; -var attributes$d = attributes$e; -var coerceFont = Lib$v.coerceFont; -function supplyDefaults$1(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$v.coerce(traceIn, traceOut, attributes$d, attr, dflt); - } - var len = handleXYDefaults$1(traceIn, traceOut, layout, coerce2); - if (!len) { - traceOut.visible = false; - return; - } - handlePeriodDefaults$2(traceIn, traceOut, layout, coerce2); - coerce2("xhoverformat"); - coerce2("yhoverformat"); - coerce2("zorder"); - coerce2("orientation", traceOut.x && !traceOut.y ? "h" : "v"); - coerce2("base"); - coerce2("offset"); - coerce2("width"); - coerce2("text"); - coerce2("hovertext"); - coerce2("hovertemplate"); - var textposition = coerce2("textposition"); - handleText$3(traceIn, traceOut, layout, coerce2, textposition, { - moduleHasSelected: true, - moduleHasUnselected: true, - moduleHasConstrain: true, - moduleHasCliponaxis: true, - moduleHasTextangle: true, - moduleHasInsideanchor: true - }); - handleStyleDefaults$1(traceIn, traceOut, coerce2, defaultColor, layout); - var lineColor = (traceOut.marker.line || {}).color; - var errorBarsSupplyDefaults = Registry$b.getComponentMethod("errorbars", "supplyDefaults"); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$f.defaultLine, { axis: "y" }); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$f.defaultLine, { axis: "x", inherit: "y" }); - Lib$v.coerceSelectionMarkerOpacity(traceOut, coerce2); -} -function crossTraceDefaults3(fullData, fullLayout) { - var traceIn, traceOut; - function coerce2(attr, dflt) { - return Lib$v.coerce(traceOut._input, traceOut, attributes$d, attr, dflt); - } - for (var i = 0; i < fullData.length; i++) { - traceOut = fullData[i]; - if (traceOut.type === "bar") { - traceIn = traceOut._input; - var r = coerce2("marker.cornerradius", fullLayout.barcornerradius); - if (traceOut.marker) { - traceOut.marker.cornerradius = validateCornerradius$2(r); - } - if (fullLayout.barmode === "group") { - handleGroupingDefaults$1(traceIn, traceOut, fullLayout, coerce2); - } - } - } -} -function validateCornerradius$2(r) { - if (isNumeric$8(r)) { - r = +r; - if (r >= 0) return r; - } else if (typeof r === "string") { - r = r.trim(); - if (r.slice(-1) === "%" && isNumeric$8(r.slice(0, -1))) { - r = +r.slice(0, -1); - if (r >= 0) return r + "%"; - } - } - return void 0; -} -function handleText$3(traceIn, traceOut, layout, coerce2, textposition, opts) { - opts = opts || {}; - var moduleHasSelected = !(opts.moduleHasSelected === false); - var moduleHasUnselected = !(opts.moduleHasUnselected === false); - var moduleHasConstrain = !(opts.moduleHasConstrain === false); - var moduleHasCliponaxis = !(opts.moduleHasCliponaxis === false); - var moduleHasTextangle = !(opts.moduleHasTextangle === false); - var moduleHasInsideanchor = !(opts.moduleHasInsideanchor === false); - var hasPathbar = !!opts.hasPathbar; - var hasBoth = Array.isArray(textposition) || textposition === "auto"; - var hasInside = hasBoth || textposition === "inside"; - var hasOutside = hasBoth || textposition === "outside"; - if (hasInside || hasOutside) { - var dfltFont = coerceFont(coerce2, "textfont", layout.font); - var insideTextFontDefault = Lib$v.extendFlat({}, dfltFont); - var isTraceTextfontColorSet = traceIn.textfont && traceIn.textfont.color; - var isColorInheritedFromLayoutFont = !isTraceTextfontColorSet; - if (isColorInheritedFromLayoutFont) { - delete insideTextFontDefault.color; - } - coerceFont(coerce2, "insidetextfont", insideTextFontDefault); - if (hasPathbar) { - var pathbarTextFontDefault = Lib$v.extendFlat({}, dfltFont); - if (isColorInheritedFromLayoutFont) { - delete pathbarTextFontDefault.color; - } - coerceFont(coerce2, "pathbar.textfont", pathbarTextFontDefault); - } - if (hasOutside) coerceFont(coerce2, "outsidetextfont", dfltFont); - if (moduleHasSelected) coerce2("selected.textfont.color"); - if (moduleHasUnselected) coerce2("unselected.textfont.color"); - if (moduleHasConstrain) coerce2("constraintext"); - if (moduleHasCliponaxis) coerce2("cliponaxis"); - if (moduleHasTextangle) coerce2("textangle"); - coerce2("texttemplate"); - } - if (hasInside) { - if (moduleHasInsideanchor) coerce2("insidetextanchor"); - } -} -var defaults$6 = { - supplyDefaults: supplyDefaults$1, - crossTraceDefaults: crossTraceDefaults3, - handleText: handleText$3, - validateCornerradius: validateCornerradius$2 -}; -var Registry$a = registry; -var Axes$4 = axesExports; -var Lib$u = libExports; -var layoutAttributes$2 = layout_attributes$2; -var validateCornerradius$1 = defaults$6.validateCornerradius; -var layout_defaults$2 = function(layoutIn, layoutOut, fullData) { - function coerce2(attr, dflt) { - return Lib$u.coerce(layoutIn, layoutOut, layoutAttributes$2, attr, dflt); - } - var hasBars = false; - var shouldBeGapless = false; - var gappedAnyway = false; - var usedSubplots = {}; - var mode = coerce2("barmode"); - for (var i = 0; i < fullData.length; i++) { - var trace = fullData[i]; - if (Registry$a.traceIs(trace, "bar") && trace.visible) hasBars = true; - else continue; - if (mode === "group") { - var subploti = trace.xaxis + trace.yaxis; - if (usedSubplots[subploti]) gappedAnyway = true; - usedSubplots[subploti] = true; - } - if (trace.visible && trace.type === "histogram") { - var pa = Axes$4.getFromId( - { _fullLayout: layoutOut }, - trace[trace.orientation === "v" ? "xaxis" : "yaxis"] - ); - if (pa.type !== "category") shouldBeGapless = true; - } - } - if (!hasBars) { - delete layoutOut.barmode; - return; - } - if (mode !== "overlay") coerce2("barnorm"); - coerce2("bargap", shouldBeGapless && !gappedAnyway ? 0 : 0.2); - coerce2("bargroupgap"); - var r = coerce2("barcornerradius"); - layoutOut.barcornerradius = validateCornerradius$1(r); -}; -var Lib$t = libExports; -var arrays_to_calcdata = function arraysToCalcdata2(cd, trace) { - for (var i = 0; i < cd.length; i++) cd[i].i = i; - Lib$t.mergeArray(trace.text, cd, "tx"); - Lib$t.mergeArray(trace.hovertext, cd, "htx"); - var marker2 = trace.marker; - if (marker2) { - Lib$t.mergeArray(marker2.opacity, cd, "mo", true); - Lib$t.mergeArray(marker2.color, cd, "mc"); - var markerLine2 = marker2.line; - if (markerLine2) { - Lib$t.mergeArray(markerLine2.color, cd, "mlc"); - Lib$t.mergeArrayCastPositive(markerLine2.width, cd, "mlw"); - } - } -}; -var Axes$3 = axesExports; -var alignPeriod$2 = align_period; -var hasColorscale$1 = helpers$L.hasColorscale; -var colorscaleCalc = calc$c; -var arraysToCalcdata$1 = arrays_to_calcdata; -var calcSelection2 = calc_selection; -var calc$7 = function calc3(gd, trace) { - var xa = Axes$3.getFromId(gd, trace.xaxis || "x"); - var ya = Axes$3.getFromId(gd, trace.yaxis || "y"); - var size, pos, origPos, pObj, hasPeriod, pLetter; - var sizeOpts = { - msUTC: !!(trace.base || trace.base === 0) - }; - if (trace.orientation === "h") { - size = xa.makeCalcdata(trace, "x", sizeOpts); - origPos = ya.makeCalcdata(trace, "y"); - pObj = alignPeriod$2(trace, ya, "y", origPos); - hasPeriod = !!trace.yperiodalignment; - pLetter = "y"; - } else { - size = ya.makeCalcdata(trace, "y", sizeOpts); - origPos = xa.makeCalcdata(trace, "x"); - pObj = alignPeriod$2(trace, xa, "x", origPos); - hasPeriod = !!trace.xperiodalignment; - pLetter = "x"; - } - pos = pObj.vals; - var serieslen = Math.min(pos.length, size.length); - var cd = new Array(serieslen); - for (var i = 0; i < serieslen; i++) { - cd[i] = { p: pos[i], s: size[i] }; - if (hasPeriod) { - cd[i].orig_p = origPos[i]; - cd[i][pLetter + "End"] = pObj.ends[i]; - cd[i][pLetter + "Start"] = pObj.starts[i]; - } - if (trace.ids) { - cd[i].id = String(trace.ids[i]); - } - } - if (hasColorscale$1(trace, "marker")) { - colorscaleCalc(gd, trace, { - vals: trace.marker.color, - containerStr: "marker" - }); - } - if (hasColorscale$1(trace, "marker.line")) { - colorscaleCalc(gd, trace, { - vals: trace.marker.line.color, - containerStr: "marker.line" - }); - } - arraysToCalcdata$1(cd, trace); - calcSelection2(cd, trace); - return cd; -}; -var d3$c = d3Exports; -var Lib$s = libExports; -function resizeText$4(gd, gTrace, traceType) { - var fullLayout = gd._fullLayout; - var minSize = fullLayout["_" + traceType + "Text_minsize"]; - if (minSize) { - var shouldHide = fullLayout.uniformtext.mode === "hide"; - var selector; - switch (traceType) { - case "funnelarea": - case "pie": - case "sunburst": - selector = "g.slice"; - break; - case "treemap": - case "icicle": - selector = "g.slice, g.pathbar"; - break; - default: - selector = "g.points > g.point"; - } - gTrace.selectAll(selector).each(function(d) { - var transform = d.transform; - if (transform) { - transform.scale = shouldHide && transform.hide ? 0 : minSize / transform.fontSize; - var el = d3$c.select(this).select("text"); - Lib$s.setTransormAndDisplay(el, transform); - } - }); - } -} -function recordMinTextSize$3(traceType, transform, fullLayout) { - if (fullLayout.uniformtext.mode) { - var minKey = getMinKey(traceType); - var minSize = fullLayout.uniformtext.minsize; - var size = transform.scale * transform.fontSize; - transform.hide = size < minSize; - fullLayout[minKey] = fullLayout[minKey] || Infinity; - if (!transform.hide) { - fullLayout[minKey] = Math.min( - fullLayout[minKey], - Math.max(size, minSize) - ); - } - } -} -function clearMinTextSize$3(traceType, fullLayout) { - var minKey = getMinKey(traceType); - fullLayout[minKey] = void 0; -} -function getMinKey(traceType) { - return "_" + traceType + "Text_minsize"; -} -var uniform_text = { - recordMinTextSize: recordMinTextSize$3, - clearMinTextSize: clearMinTextSize$3, - resizeText: resizeText$4 -}; -var helpers$d = {}; -var isNumeric$7 = fastIsnumeric; -var tinycolor$1 = tinycolorExports; -var isArrayOrTypedArray$2 = libExports.isArrayOrTypedArray; -helpers$d.coerceString = function(attributeDefinition, value2, defaultValue) { - if (typeof value2 === "string") { - if (value2 || !attributeDefinition.noBlank) return value2; - } else if (typeof value2 === "number" || value2 === true) { - if (!attributeDefinition.strict) return String(value2); - } - return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; -}; -helpers$d.coerceNumber = function(attributeDefinition, value2, defaultValue) { - if (isNumeric$7(value2)) { - value2 = +value2; - var min = attributeDefinition.min; - var max = attributeDefinition.max; - var isOutOfBounds = min !== void 0 && value2 < min || max !== void 0 && value2 > max; - if (!isOutOfBounds) return value2; - } - return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; -}; -helpers$d.coerceColor = function(attributeDefinition, value2, defaultValue) { - if (tinycolor$1(value2).isValid()) return value2; - return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; -}; -helpers$d.coerceEnumerated = function(attributeDefinition, value2, defaultValue) { - if (attributeDefinition.coerceNumber) value2 = +value2; - if (attributeDefinition.values.indexOf(value2) !== -1) return value2; - return defaultValue !== void 0 ? defaultValue : attributeDefinition.dflt; -}; -helpers$d.getValue = function(arrayOrScalar, index2) { - var value2; - if (!isArrayOrTypedArray$2(arrayOrScalar)) value2 = arrayOrScalar; - else if (index2 < arrayOrScalar.length) value2 = arrayOrScalar[index2]; - return value2; -}; -helpers$d.getLineWidth = function(trace, di) { - var w = 0 < di.mlw ? di.mlw : !isArrayOrTypedArray$2(trace.marker.line.width) ? trace.marker.line.width : 0; - return w; -}; -var d3$b = d3Exports; -var Color$e = colorExports; -var Drawing$7 = drawingExports; -var Lib$r = libExports; -var Registry$9 = registry; -var resizeText$3 = uniform_text.resizeText; -var attributes$c = attributes$e; -var attributeTextFont = attributes$c.textfont; -var attributeInsideTextFont = attributes$c.insidetextfont; -var attributeOutsideTextFont = attributes$c.outsidetextfont; -var helpers$c = helpers$d; -function style$4(gd) { - var s = d3$b.select(gd).selectAll('g[class^="barlayer"]').selectAll("g.trace"); - resizeText$3(gd, s, "bar"); - var barcount = s.size(); - var fullLayout = gd._fullLayout; - s.style("opacity", function(d) { - return d[0].trace.opacity; - }).each(function(d) { - if (fullLayout.barmode === "stack" && barcount > 1 || fullLayout.bargap === 0 && fullLayout.bargroupgap === 0 && !d[0].trace.marker.line.width) { - d3$b.select(this).attr("shape-rendering", "crispEdges"); - } - }); - s.selectAll("g.points").each(function(d) { - var sel = d3$b.select(this); - var trace = d[0].trace; - stylePoints(sel, trace, gd); - }); - Registry$9.getComponentMethod("errorbars", "style")(s); -} -function stylePoints(sel, trace, gd) { - Drawing$7.pointStyle(sel.selectAll("path"), trace, gd); - styleTextPoints(sel, trace, gd); -} -function styleTextPoints(sel, trace, gd) { - sel.selectAll("text").each(function(d) { - var tx = d3$b.select(this); - var font2 = Lib$r.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); - Drawing$7.font(tx, font2); - }); -} -function styleOnSelect(gd, cd, sel) { - var trace = cd[0].trace; - if (trace.selectedpoints) { - stylePointsInSelectionMode(sel, trace, gd); - } else { - stylePoints(sel, trace, gd); - Registry$9.getComponentMethod("errorbars", "style")(sel); - } -} -function stylePointsInSelectionMode(s, trace, gd) { - Drawing$7.selectedPointStyle(s.selectAll("path"), trace); - styleTextInSelectionMode(s.selectAll("text"), trace, gd); -} -function styleTextInSelectionMode(txs, trace, gd) { - txs.each(function(d) { - var tx = d3$b.select(this); - var font2; - if (d.selected) { - font2 = Lib$r.ensureUniformFontSize(gd, determineFont(tx, d, trace, gd)); - var selectedFontColor = trace.selected.textfont && trace.selected.textfont.color; - if (selectedFontColor) { - font2.color = selectedFontColor; - } - Drawing$7.font(tx, font2); - } else { - Drawing$7.selectedTextStyle(tx, trace); - } - }); -} -function determineFont(tx, d, trace, gd) { - var layoutFont = gd._fullLayout.font; - var textFont = trace.textfont; - if (tx.classed("bartext-inside")) { - var barColor = getBarColor(d, trace); - textFont = getInsideTextFont(trace, d.i, layoutFont, barColor); - } else if (tx.classed("bartext-outside")) { - textFont = getOutsideTextFont(trace, d.i, layoutFont); - } - return textFont; -} -function getTextFont(trace, index2, defaultValue) { - return getFontValue( - attributeTextFont, - trace.textfont, - index2, - defaultValue - ); -} -function getInsideTextFont(trace, index2, layoutFont, barColor) { - var defaultFont = getTextFont(trace, index2, layoutFont); - var wouldFallBackToLayoutFont = trace._input.textfont === void 0 || trace._input.textfont.color === void 0 || Array.isArray(trace.textfont.color) && trace.textfont.color[index2] === void 0; - if (wouldFallBackToLayoutFont) { - defaultFont = { - color: Color$e.contrast(barColor), - family: defaultFont.family, - size: defaultFont.size, - weight: defaultFont.weight, - style: defaultFont.style, - variant: defaultFont.variant, - textcase: defaultFont.textcase, - lineposition: defaultFont.lineposition, - shadow: defaultFont.shadow - }; - } - return getFontValue( - attributeInsideTextFont, - trace.insidetextfont, - index2, - defaultFont - ); -} -function getOutsideTextFont(trace, index2, layoutFont) { - var defaultFont = getTextFont(trace, index2, layoutFont); - return getFontValue( - attributeOutsideTextFont, - trace.outsidetextfont, - index2, - defaultFont - ); -} -function getFontValue(attributeDefinition, attributeValue, index2, defaultValue) { - attributeValue = attributeValue || {}; - var familyValue = helpers$c.getValue(attributeValue.family, index2); - var sizeValue = helpers$c.getValue(attributeValue.size, index2); - var colorValue = helpers$c.getValue(attributeValue.color, index2); - var weightValue = helpers$c.getValue(attributeValue.weight, index2); - var styleValue = helpers$c.getValue(attributeValue.style, index2); - var variantValue = helpers$c.getValue(attributeValue.variant, index2); - var textcaseValue = helpers$c.getValue(attributeValue.textcase, index2); - var linepositionValue = helpers$c.getValue(attributeValue.lineposition, index2); - var shadowValue = helpers$c.getValue(attributeValue.shadow, index2); - return { - family: helpers$c.coerceString( - attributeDefinition.family, - familyValue, - defaultValue.family - ), - size: helpers$c.coerceNumber( - attributeDefinition.size, - sizeValue, - defaultValue.size - ), - color: helpers$c.coerceColor( - attributeDefinition.color, - colorValue, - defaultValue.color - ), - weight: helpers$c.coerceString( - attributeDefinition.weight, - weightValue, - defaultValue.weight - ), - style: helpers$c.coerceString( - attributeDefinition.style, - styleValue, - defaultValue.style - ), - variant: helpers$c.coerceString( - attributeDefinition.variant, - variantValue, - defaultValue.variant - ), - textcase: helpers$c.coerceString( - attributeDefinition.variant, - textcaseValue, - defaultValue.textcase - ), - lineposition: helpers$c.coerceString( - attributeDefinition.variant, - linepositionValue, - defaultValue.lineposition - ), - shadow: helpers$c.coerceString( - attributeDefinition.variant, - shadowValue, - defaultValue.shadow - ) - }; -} -function getBarColor(cd, trace) { - if (trace.type === "waterfall") { - return trace[cd.dir].marker.color; - } - return cd.mcc || cd.mc || trace.marker.color; -} -var style_1$2 = { - style: style$4, - styleTextPoints, - styleOnSelect, - getInsideTextFont, - getOutsideTextFont, - getBarColor, - resizeText: resizeText$3 -}; -var d3$a = d3Exports; -var isNumeric$6 = fastIsnumeric; -var Lib$q = libExports; -var svgTextUtils$3 = svg_text_utils; -var Color$d = colorExports; -var Drawing$6 = drawingExports; -var Registry$8 = registry; -var tickText = axesExports.tickText; -var uniformText$3 = uniform_text; -var recordMinTextSize$2 = uniformText$3.recordMinTextSize; -var clearMinTextSize$2 = uniformText$3.clearMinTextSize; -var style$3 = style_1$2; -var helpers$b = helpers$d; -var constants$d = constants$f; -var attributes$b = attributes$e; -var attributeText = attributes$b.text; -var attributeTextPosition = attributes$b.textposition; -var appendArrayPointValue$2 = helpers$J.appendArrayPointValue; -var TEXTPAD$3 = constants$d.TEXTPAD; -function keyFunc(d) { - return d.id; -} -function getKeyFunc(trace) { - if (trace.ids) { - return keyFunc; - } -} -function sign$1(v) { - return (v > 0) - (v < 0); -} -function dirSign(a, b) { - return a < b ? 1 : -1; -} -function getXY(di, xa, ya, isHorizontal) { - var s = []; - var p = []; - var sAxis = isHorizontal ? xa : ya; - var pAxis = isHorizontal ? ya : xa; - s[0] = sAxis.c2p(di.s0, true); - p[0] = pAxis.c2p(di.p0, true); - s[1] = sAxis.c2p(di.s1, true); - p[1] = pAxis.c2p(di.p1, true); - return isHorizontal ? [s, p] : [p, s]; -} -function transition(selection, fullLayout, opts, makeOnCompleteCallback) { - if (!fullLayout.uniformtext.mode && hasTransition(opts)) { - var onComplete; - if (makeOnCompleteCallback) { - onComplete = makeOnCompleteCallback(); - } - return selection.transition().duration(opts.duration).ease(opts.easing).each("end", function() { - onComplete && onComplete(); - }).each("interrupt", function() { - onComplete && onComplete(); - }); - } else { - return selection; - } -} -function hasTransition(transitionOpts) { - return transitionOpts && transitionOpts.duration > 0; -} -function plot$5(gd, plotinfo, cdModule, traceLayer, opts, makeOnCompleteCallback) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var fullLayout = gd._fullLayout; - var isStatic = gd._context.staticPlot; - if (!opts) { - opts = { - mode: fullLayout.barmode, - norm: fullLayout.barmode, - gap: fullLayout.bargap, - groupgap: fullLayout.bargroupgap - }; - clearMinTextSize$2("bar", fullLayout); - } - var bartraces = Lib$q.makeTraceGroups(traceLayer, cdModule, "trace bars").each(function(cd) { - var plotGroup = d3$a.select(this); - var trace = cd[0].trace; - var t = cd[0].t; - var isWaterfall = trace.type === "waterfall"; - var isFunnel = trace.type === "funnel"; - var isHistogram = trace.type === "histogram"; - var isBar = trace.type === "bar"; - var shouldDisplayZeros = isBar || isFunnel; - var adjustPixel = 0; - if (isWaterfall && trace.connector.visible && trace.connector.mode === "between") { - adjustPixel = trace.connector.line.width / 2; - } - var isHorizontal = trace.orientation === "h"; - var withTransition = hasTransition(opts); - var pointGroup = Lib$q.ensureSingle(plotGroup, "g", "points"); - var keyFunc2 = getKeyFunc(trace); - var bars = pointGroup.selectAll("g.point").data(Lib$q.identity, keyFunc2); - bars.enter().append("g").classed("point", true); - bars.exit().remove(); - bars.each(function(di, i) { - var bar2 = d3$a.select(this); - var xy = getXY(di, xa, ya, isHorizontal); - var x0 = xy[0][0]; - var x1 = xy[0][1]; - var y0 = xy[1][0]; - var y1 = xy[1][1]; - var isBlank = (isHorizontal ? x1 - x0 : y1 - y0) === 0; - if (isBlank && shouldDisplayZeros && helpers$b.getLineWidth(trace, di)) { - isBlank = false; - } - if (!isBlank) { - isBlank = !isNumeric$6(x0) || !isNumeric$6(x1) || !isNumeric$6(y0) || !isNumeric$6(y1); - } - di.isBlank = isBlank; - if (isBlank) { - if (isHorizontal) { - x1 = x0; - } else { - y1 = y0; - } - } - if (adjustPixel && !isBlank) { - if (isHorizontal) { - x0 -= dirSign(x0, x1) * adjustPixel; - x1 += dirSign(x0, x1) * adjustPixel; - } else { - y0 -= dirSign(y0, y1) * adjustPixel; - y1 += dirSign(y0, y1) * adjustPixel; - } - } - var lw; - var mc; - if (trace.type === "waterfall") { - if (!isBlank) { - var cont = trace[di.dir].marker; - lw = cont.line.width; - mc = cont.color; - } - } else { - lw = helpers$b.getLineWidth(trace, di); - mc = di.mc || trace.marker.color; - } - function roundWithLine(v) { - var offset = d3$a.round(lw / 2 % 1, 2); - return opts.gap === 0 && opts.groupgap === 0 ? d3$a.round(Math.round(v) - offset, 2) : v; - } - function expandToVisible(v, vc, hideZeroSpan) { - if (hideZeroSpan && v === vc) { - return v; - } - return Math.abs(v - vc) >= 2 ? roundWithLine(v) : ( - // but if it's very thin, expand it so it's - // necessarily visible, even if it might overlap - // its neighbor - v > vc ? Math.ceil(v) : Math.floor(v) - ); - } - var op = Color$d.opacity(mc); - var fixpx = op < 1 || lw > 0.01 ? roundWithLine : expandToVisible; - if (!gd._context.staticPlot) { - x0 = fixpx(x0, x1, isHorizontal); - x1 = fixpx(x1, x0, isHorizontal); - y0 = fixpx(y0, y1, !isHorizontal); - y1 = fixpx(y1, y0, !isHorizontal); - } - var c2p = isHorizontal ? xa.c2p : ya.c2p; - var outerBound; - if (di.s0 > 0) { - outerBound = di._sMax; - } else if (di.s0 < 0) { - outerBound = di._sMin; - } else { - outerBound = di.s1 > 0 ? di._sMax : di._sMin; - } - function calcCornerRadius(crValue, crForm) { - if (!crValue) return 0; - var barWidth = isHorizontal ? Math.abs(y1 - y0) : Math.abs(x1 - x0); - var barLength = isHorizontal ? Math.abs(x1 - x0) : Math.abs(y1 - y0); - var stackedBarTotalLength = fixpx(Math.abs(c2p(outerBound, true) - c2p(0, true))); - var maxRadius = di.hasB ? Math.min(barWidth / 2, barLength / 2) : Math.min(barWidth / 2, stackedBarTotalLength); - var crPx; - if (crForm === "%") { - var crPercent = Math.min(50, crValue); - crPx = barWidth * (crPercent / 100); - } else { - crPx = crValue; - } - return fixpx(Math.max(Math.min(crPx, maxRadius), 0)); - } - var r = isBar || isHistogram ? calcCornerRadius(t.cornerradiusvalue, t.cornerradiusform) : 0; - var path, h; - var rectanglePath = "M" + x0 + "," + y0 + "V" + y1 + "H" + x1 + "V" + y0 + "Z"; - var overhead = 0; - if (r && di.s) { - var refPoint = sign$1(di.s0) === 0 || sign$1(di.s) === sign$1(di.s0) ? di.s1 : di.s0; - overhead = fixpx(!di.hasB ? Math.abs(c2p(outerBound, true) - c2p(refPoint, true)) : 0); - if (overhead < r) { - var xdir = dirSign(x0, x1); - var ydir = dirSign(y0, y1); - var cornersweep = xdir === -ydir ? 1 : 0; - if (isHorizontal) { - if (di.hasB) { - path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z"; - } else { - h = Math.abs(x1 - x0) + overhead; - var dy1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0; - var dy2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0; - var xminfunc = xdir > 0 ? Math.max : Math.min; - path = "M" + x0 + "," + y0 + "V" + (y1 - dy1 * ydir) + "H" + xminfunc(x1 - (r - overhead) * xdir, x0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir - dy2) + "V" + (y0 + r * ydir + dy2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + xminfunc(x1 - (r - overhead) * xdir, x0) + "," + (y0 + dy1 * ydir) + "Z"; - } - } else { - if (di.hasB) { - path = "M" + (x0 + r * xdir) + "," + y0 + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x0 + "," + (y0 + r * ydir) + "V" + (y1 - r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir) + "," + y1 + "H" + (x1 - r * xdir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + x1 + "," + (y1 - r * ydir) + "V" + (y0 + r * ydir) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - r * xdir) + "," + y0 + "Z"; - } else { - h = Math.abs(y1 - y0) + overhead; - var dx1 = h < r ? r - Math.sqrt(h * (2 * r - h)) : 0; - var dx2 = overhead > 0 ? Math.sqrt(overhead * (2 * r - overhead)) : 0; - var yminfunc = ydir > 0 ? Math.max : Math.min; - path = "M" + (x0 + dx1 * xdir) + "," + y0 + "V" + yminfunc(y1 - (r - overhead) * ydir, y0) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x0 + r * xdir - dx2) + "," + y1 + "H" + (x1 - r * xdir + dx2) + "A " + r + "," + r + " 0 0 " + cornersweep + " " + (x1 - dx1 * xdir) + "," + yminfunc(y1 - (r - overhead) * ydir, y0) + "V" + y0 + "Z"; - } - } - } else { - path = rectanglePath; - } - } else { - path = rectanglePath; - } - var sel = transition(Lib$q.ensureSingle(bar2, "path"), fullLayout, opts, makeOnCompleteCallback); - sel.style("vector-effect", isStatic ? "none" : "non-scaling-stroke").attr("d", isNaN((x1 - x0) * (y1 - y0)) || isBlank && gd._context.staticPlot ? "M0,0Z" : path).call(Drawing$6.setClipUrl, plotinfo.layerClipId, gd); - if (!fullLayout.uniformtext.mode && withTransition) { - var styleFns = Drawing$6.makePointStyleFns(trace); - Drawing$6.singlePointStyle(di, sel, trace, styleFns, gd); - } - appendBarText(gd, plotinfo, bar2, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback); - if (plotinfo.layerClipId) { - Drawing$6.hideOutsideRangePoint(di, bar2.select("text"), xa, ya, trace.xcalendar, trace.ycalendar); - } - }); - var hasClipOnAxisFalse = trace.cliponaxis === false; - Drawing$6.setClipUrl(plotGroup, hasClipOnAxisFalse ? null : plotinfo.layerClipId, gd); - }); - Registry$8.getComponentMethod("errorbars", "plot")(gd, bartraces, plotinfo, opts); -} -function appendBarText(gd, plotinfo, bar2, cd, i, x0, x1, y0, y1, r, overhead, opts, makeOnCompleteCallback) { - var xa = plotinfo.xaxis; - var ya = plotinfo.yaxis; - var fullLayout = gd._fullLayout; - var textPosition; - function appendTextNode(bar3, text2, font3) { - var textSelection2 = Lib$q.ensureSingle(bar3, "text").text(text2).attr({ - class: "bartext bartext-" + textPosition, - "text-anchor": "middle", - // prohibit tex interpretation until we can handle - // tex and regular text together - "data-notex": 1 - }).call(Drawing$6.font, font3).call(svgTextUtils$3.convertToTspans, gd); - return textSelection2; - } - var trace = cd[0].trace; - var isHorizontal = trace.orientation === "h"; - var text = getText(fullLayout, cd, i, xa, ya); - textPosition = getTextPosition(trace, i); - var inStackOrRelativeMode = opts.mode === "stack" || opts.mode === "relative"; - var calcBar = cd[i]; - var isOutmostBar = !inStackOrRelativeMode || calcBar._outmost; - var hasB = calcBar.hasB; - var barIsRounded = r && r - overhead > TEXTPAD$3; - if (!text || textPosition === "none" || (calcBar.isBlank || x0 === x1 || y0 === y1) && (textPosition === "auto" || textPosition === "inside")) { - bar2.select("text").remove(); - return; - } - var layoutFont = fullLayout.font; - var barColor = style$3.getBarColor(cd[i], trace); - var insideTextFont = style$3.getInsideTextFont(trace, i, layoutFont, barColor); - var outsideTextFont = style$3.getOutsideTextFont(trace, i, layoutFont); - var insidetextanchor = trace.insidetextanchor || "end"; - var di = bar2.datum(); - if (isHorizontal) { - if (xa.type === "log" && di.s0 <= 0) { - if (xa.range[0] < xa.range[1]) { - x0 = 0; - } else { - x0 = xa._length; - } - } - } else { - if (ya.type === "log" && di.s0 <= 0) { - if (ya.range[0] < ya.range[1]) { - y0 = ya._length; - } else { - y0 = 0; - } - } - } - var lx = Math.abs(x1 - x0); - var ly = Math.abs(y1 - y0); - var barWidth = lx - 2 * TEXTPAD$3; - var barHeight = ly - 2 * TEXTPAD$3; - var textSelection; - var textBB; - var textWidth; - var textHeight; - var font2; - if (textPosition === "outside") { - if (!isOutmostBar && !calcBar.hasB) textPosition = "inside"; - } - if (textPosition === "auto") { - if (isOutmostBar) { - textPosition = "inside"; - font2 = Lib$q.ensureUniformFontSize(gd, insideTextFont); - textSelection = appendTextNode(bar2, text, font2); - textBB = Drawing$6.bBox(textSelection.node()); - textWidth = textBB.width; - textHeight = textBB.height; - var textHasSize = textWidth > 0 && textHeight > 0; - var fitsInside; - if (barIsRounded) { - if (hasB) { - fitsInside = textfitsInsideBar(barWidth - 2 * r, barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * r, textWidth, textHeight, isHorizontal); - } else if (isHorizontal) { - fitsInside = textfitsInsideBar(barWidth - (r - overhead), barHeight, textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth, barHeight - 2 * (r - overhead), textWidth, textHeight, isHorizontal); - } else { - fitsInside = textfitsInsideBar(barWidth, barHeight - (r - overhead), textWidth, textHeight, isHorizontal) || textfitsInsideBar(barWidth - 2 * (r - overhead), barHeight, textWidth, textHeight, isHorizontal); - } - } else { - fitsInside = textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal); - } - if (textHasSize && fitsInside) { - textPosition = "inside"; - } else { - textPosition = "outside"; - textSelection.remove(); - textSelection = null; - } - } else { - textPosition = "inside"; - } - } - if (!textSelection) { - font2 = Lib$q.ensureUniformFontSize(gd, textPosition === "outside" ? outsideTextFont : insideTextFont); - textSelection = appendTextNode(bar2, text, font2); - var currentTransform = textSelection.attr("transform"); - textSelection.attr("transform", ""); - textBB = Drawing$6.bBox(textSelection.node()), textWidth = textBB.width, textHeight = textBB.height; - textSelection.attr("transform", currentTransform); - if (textWidth <= 0 || textHeight <= 0) { - textSelection.remove(); - return; - } - } - var angle = trace.textangle; - var transform, constrained; - if (textPosition === "outside") { - constrained = trace.constraintext === "both" || trace.constraintext === "outside"; - transform = toMoveOutsideBar(x0, x1, y0, y1, textBB, { - isHorizontal, - constrained, - angle - }); - } else { - constrained = trace.constraintext === "both" || trace.constraintext === "inside"; - transform = toMoveInsideBar$1(x0, x1, y0, y1, textBB, { - isHorizontal, - constrained, - angle, - anchor: insidetextanchor, - hasB, - r, - overhead - }); - } - transform.fontSize = font2.size; - recordMinTextSize$2(trace.type === "histogram" ? "bar" : trace.type, transform, fullLayout); - calcBar.transform = transform; - var s = transition(textSelection, fullLayout, opts, makeOnCompleteCallback); - Lib$q.setTransormAndDisplay(s, transform); -} -function textfitsInsideBar(barWidth, barHeight, textWidth, textHeight, isHorizontal) { - if (barWidth < 0 || barHeight < 0) return false; - var fitsInside = textWidth <= barWidth && textHeight <= barHeight; - var fitsInsideIfRotated = textWidth <= barHeight && textHeight <= barWidth; - var fitsInsideIfShrunk = isHorizontal ? barWidth >= textWidth * (barHeight / textHeight) : barHeight >= textHeight * (barWidth / textWidth); - return fitsInside || fitsInsideIfRotated || fitsInsideIfShrunk; -} -function getRotateFromAngle(angle) { - return angle === "auto" ? 0 : angle; -} -function getRotatedTextSize(textBB, rotate2) { - var a = Math.PI / 180 * rotate2; - var absSin = Math.abs(Math.sin(a)); - var absCos = Math.abs(Math.cos(a)); - return { - x: textBB.width * absCos + textBB.height * absSin, - y: textBB.width * absSin + textBB.height * absCos - }; -} -function toMoveInsideBar$1(x0, x1, y0, y1, textBB, opts) { - var isHorizontal = !!opts.isHorizontal; - var constrained = !!opts.constrained; - var angle = opts.angle || 0; - var anchor = opts.anchor; - var isEnd = anchor === "end"; - var isStart = anchor === "start"; - var leftToRight = opts.leftToRight || 0; - var toRight = (leftToRight + 1) / 2; - var toLeft = 1 - toRight; - var hasB = opts.hasB; - var r = opts.r; - var overhead = opts.overhead; - var textWidth = textBB.width; - var textHeight = textBB.height; - var lx = Math.abs(x1 - x0); - var ly = Math.abs(y1 - y0); - var textpad = lx > 2 * TEXTPAD$3 && ly > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; - lx -= 2 * textpad; - ly -= 2 * textpad; - var rotate2 = getRotateFromAngle(angle); - if (angle === "auto" && !(textWidth <= lx && textHeight <= ly) && (textWidth > lx || textHeight > ly) && (!(textWidth > ly || textHeight > lx) || textWidth < textHeight !== lx < ly)) { - rotate2 += 90; - } - var t = getRotatedTextSize(textBB, rotate2); - var scale2, padForRounding; - if (r && r - overhead > TEXTPAD$3) { - var scaleAndPad = scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB); - scale2 = scaleAndPad.scale; - padForRounding = scaleAndPad.pad; - } else { - scale2 = 1; - if (constrained) { - scale2 = Math.min( - 1, - lx / t.x, - ly / t.y - ); - } - padForRounding = 0; - } - var textX = textBB.left * toLeft + textBB.right * toRight; - var textY = (textBB.top + textBB.bottom) / 2; - var targetX = (x0 + TEXTPAD$3) * toLeft + (x1 - TEXTPAD$3) * toRight; - var targetY = (y0 + y1) / 2; - var anchorX = 0; - var anchorY = 0; - if (isStart || isEnd) { - var extrapad = (isHorizontal ? t.x : t.y) / 2; - if (r && (isEnd || hasB)) { - textpad += padForRounding; - } - var dir = isHorizontal ? dirSign(x0, x1) : dirSign(y0, y1); - if (isHorizontal) { - if (isStart) { - targetX = x0 + dir * textpad; - anchorX = -dir * extrapad; - } else { - targetX = x1 - dir * textpad; - anchorX = dir * extrapad; - } - } else { - if (isStart) { - targetY = y0 + dir * textpad; - anchorY = -dir * extrapad; - } else { - targetY = y1 - dir * textpad; - anchorY = dir * extrapad; - } - } - } - return { - textX, - textY, - targetX, - targetY, - anchorX, - anchorY, - scale: scale2, - rotate: rotate2 - }; -} -function scaleTextForRoundedBar(x0, x1, y0, y1, t, r, overhead, isHorizontal, hasB) { - var barWidth = Math.max(0, Math.abs(x1 - x0) - 2 * TEXTPAD$3); - var barHeight = Math.max(0, Math.abs(y1 - y0) - 2 * TEXTPAD$3); - var R2 = r - TEXTPAD$3; - var clippedR = overhead ? R2 - Math.sqrt(R2 * R2 - (R2 - overhead) * (R2 - overhead)) : R2; - var rX = hasB ? R2 * 2 : isHorizontal ? R2 - overhead : 2 * clippedR; - var rY = hasB ? R2 * 2 : isHorizontal ? 2 * clippedR : R2 - overhead; - var a, b, c; - var scale2, pad2; - if (t.y / t.x >= barHeight / (barWidth - rX)) { - scale2 = barHeight / t.y; - } else if (t.y / t.x <= (barHeight - rY) / barWidth) { - scale2 = barWidth / t.x; - } else if (!hasB && isHorizontal) { - a = t.x * t.x + t.y * t.y / 4; - b = -2 * t.x * (barWidth - R2) - t.y * (barHeight / 2 - R2); - c = (barWidth - R2) * (barWidth - R2) + (barHeight / 2 - R2) * (barHeight / 2 - R2) - R2 * R2; - scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); - } else if (!hasB) { - a = t.x * t.x / 4 + t.y * t.y; - b = -t.x * (barWidth / 2 - R2) - 2 * t.y * (barHeight - R2); - c = (barWidth / 2 - R2) * (barWidth / 2 - R2) + (barHeight - R2) * (barHeight - R2) - R2 * R2; - scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); - } else { - a = (t.x * t.x + t.y * t.y) / 4; - b = -t.x * (barWidth / 2 - R2) - t.y * (barHeight / 2 - R2); - c = (barWidth / 2 - R2) * (barWidth / 2 - R2) + (barHeight / 2 - R2) * (barHeight / 2 - R2) - R2 * R2; - scale2 = (-b + Math.sqrt(b * b - 4 * a * c)) / (2 * a); - } - scale2 = Math.min(1, scale2); - if (isHorizontal) { - pad2 = Math.max(0, R2 - Math.sqrt(Math.max(0, R2 * R2 - (R2 - (barHeight - t.y * scale2) / 2) * (R2 - (barHeight - t.y * scale2) / 2))) - overhead); - } else { - pad2 = Math.max(0, R2 - Math.sqrt(Math.max(0, R2 * R2 - (R2 - (barWidth - t.x * scale2) / 2) * (R2 - (barWidth - t.x * scale2) / 2))) - overhead); - } - return { scale: scale2, pad: pad2 }; -} -function toMoveOutsideBar(x0, x1, y0, y1, textBB, opts) { - var isHorizontal = !!opts.isHorizontal; - var constrained = !!opts.constrained; - var angle = opts.angle || 0; - var textWidth = textBB.width; - var textHeight = textBB.height; - var lx = Math.abs(x1 - x0); - var ly = Math.abs(y1 - y0); - var textpad; - if (isHorizontal) { - textpad = ly > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; - } else { - textpad = lx > 2 * TEXTPAD$3 ? TEXTPAD$3 : 0; - } - var scale2 = 1; - if (constrained) { - scale2 = isHorizontal ? Math.min(1, ly / textHeight) : Math.min(1, lx / textWidth); - } - var rotate2 = getRotateFromAngle(angle); - var t = getRotatedTextSize(textBB, rotate2); - var extrapad = (isHorizontal ? t.x : t.y) / 2; - var textX = (textBB.left + textBB.right) / 2; - var textY = (textBB.top + textBB.bottom) / 2; - var targetX = (x0 + x1) / 2; - var targetY = (y0 + y1) / 2; - var anchorX = 0; - var anchorY = 0; - var dir = isHorizontal ? dirSign(x1, x0) : dirSign(y0, y1); - if (isHorizontal) { - targetX = x1 - dir * textpad; - anchorX = dir * extrapad; - } else { - targetY = y1 + dir * textpad; - anchorY = -dir * extrapad; - } - return { - textX, - textY, - targetX, - targetY, - anchorX, - anchorY, - scale: scale2, - rotate: rotate2 - }; -} -function getText(fullLayout, cd, index2, xa, ya) { - var trace = cd[0].trace; - var texttemplate = trace.texttemplate; - var value2; - if (texttemplate) { - value2 = calcTexttemplate(fullLayout, cd, index2, xa, ya); - } else if (trace.textinfo) { - value2 = calcTextinfo(cd, index2, xa, ya); - } else { - value2 = helpers$b.getValue(trace.text, index2); - } - return helpers$b.coerceString(attributeText, value2); -} -function getTextPosition(trace, index2) { - var value2 = helpers$b.getValue(trace.textposition, index2); - return helpers$b.coerceEnumerated(attributeTextPosition, value2); -} -function calcTexttemplate(fullLayout, cd, index2, xa, ya) { - var trace = cd[0].trace; - var texttemplate = Lib$q.castOption(trace, index2, "texttemplate"); - if (!texttemplate) return ""; - var isHistogram = trace.type === "histogram"; - var isWaterfall = trace.type === "waterfall"; - var isFunnel = trace.type === "funnel"; - var isHorizontal = trace.orientation === "h"; - var pLetter, pAxis; - var vLetter, vAxis; - if (isHorizontal) { - pLetter = "y"; - pAxis = ya; - vLetter = "x"; - vAxis = xa; - } else { - pLetter = "x"; - pAxis = xa; - vLetter = "y"; - vAxis = ya; - } - function formatLabel(u) { - return tickText(pAxis, pAxis.c2l(u), true).text; - } - function formatNumber(v) { - return tickText(vAxis, vAxis.c2l(v), true).text; - } - var cdi = cd[index2]; - var obj = {}; - obj.label = cdi.p; - obj.labelLabel = obj[pLetter + "Label"] = formatLabel(cdi.p); - var tx = Lib$q.castOption(trace, cdi.i, "text"); - if (tx === 0 || tx) obj.text = tx; - obj.value = cdi.s; - obj.valueLabel = obj[vLetter + "Label"] = formatNumber(cdi.s); - var pt = {}; - appendArrayPointValue$2(pt, trace, cdi.i); - if (isHistogram || pt.x === void 0) pt.x = isHorizontal ? obj.value : obj.label; - if (isHistogram || pt.y === void 0) pt.y = isHorizontal ? obj.label : obj.value; - if (isHistogram || pt.xLabel === void 0) pt.xLabel = isHorizontal ? obj.valueLabel : obj.labelLabel; - if (isHistogram || pt.yLabel === void 0) pt.yLabel = isHorizontal ? obj.labelLabel : obj.valueLabel; - if (isWaterfall) { - obj.delta = +cdi.rawS || cdi.s; - obj.deltaLabel = formatNumber(obj.delta); - obj.final = cdi.v; - obj.finalLabel = formatNumber(obj.final); - obj.initial = obj.final - obj.delta; - obj.initialLabel = formatNumber(obj.initial); - } - if (isFunnel) { - obj.value = cdi.s; - obj.valueLabel = formatNumber(obj.value); - obj.percentInitial = cdi.begR; - obj.percentInitialLabel = Lib$q.formatPercent(cdi.begR); - obj.percentPrevious = cdi.difR; - obj.percentPreviousLabel = Lib$q.formatPercent(cdi.difR); - obj.percentTotal = cdi.sumR; - obj.percenTotalLabel = Lib$q.formatPercent(cdi.sumR); - } - var customdata = Lib$q.castOption(trace, cdi.i, "customdata"); - if (customdata) obj.customdata = customdata; - return Lib$q.texttemplateString(texttemplate, obj, fullLayout._d3locale, pt, obj, trace._meta || {}); -} -function calcTextinfo(cd, index2, xa, ya) { - var trace = cd[0].trace; - var isHorizontal = trace.orientation === "h"; - var isWaterfall = trace.type === "waterfall"; - var isFunnel = trace.type === "funnel"; - function formatLabel(u) { - var pAxis = isHorizontal ? ya : xa; - return tickText(pAxis, u, true).text; - } - function formatNumber(v) { - var sAxis = isHorizontal ? xa : ya; - return tickText(sAxis, +v, true).text; - } - var textinfo = trace.textinfo; - var cdi = cd[index2]; - var parts = textinfo.split("+"); - var text = []; - var tx; - var hasFlag = function(flag) { - return parts.indexOf(flag) !== -1; - }; - if (hasFlag("label")) { - text.push(formatLabel(cd[index2].p)); - } - if (hasFlag("text")) { - tx = Lib$q.castOption(trace, cdi.i, "text"); - if (tx === 0 || tx) text.push(tx); - } - if (isWaterfall) { - var delta2 = +cdi.rawS || cdi.s; - var final = cdi.v; - var initial = final - delta2; - if (hasFlag("initial")) text.push(formatNumber(initial)); - if (hasFlag("delta")) text.push(formatNumber(delta2)); - if (hasFlag("final")) text.push(formatNumber(final)); - } - if (isFunnel) { - if (hasFlag("value")) text.push(formatNumber(cdi.s)); - var nPercent = 0; - if (hasFlag("percent initial")) nPercent++; - if (hasFlag("percent previous")) nPercent++; - if (hasFlag("percent total")) nPercent++; - var hasMultiplePercents = nPercent > 1; - if (hasFlag("percent initial")) { - tx = Lib$q.formatPercent(cdi.begR); - if (hasMultiplePercents) tx += " of initial"; - text.push(tx); - } - if (hasFlag("percent previous")) { - tx = Lib$q.formatPercent(cdi.difR); - if (hasMultiplePercents) tx += " of previous"; - text.push(tx); - } - if (hasFlag("percent total")) { - tx = Lib$q.formatPercent(cdi.sumR); - if (hasMultiplePercents) tx += " of total"; - text.push(tx); - } - } - return text.join("
"); -} -var plot_1$1 = { - plot: plot$5, - toMoveInsideBar: toMoveInsideBar$1 -}; -var Fx$3 = fx$1; -var Registry$7 = registry; -var Color$c = colorExports; -var fillText$1 = libExports.fillText; -var getLineWidth = helpers$d.getLineWidth; -var hoverLabelText$1 = axesExports.hoverLabelText; -var BADNUM$2 = numerical.BADNUM; -function hoverPoints$2(pointData, xval, yval, hovermode, opts) { - var barPointData = hoverOnBars(pointData, xval, yval, hovermode, opts); - if (barPointData) { - var cd = barPointData.cd; - var trace = cd[0].trace; - var di = cd[barPointData.index]; - barPointData.color = getTraceColor$1(trace, di); - Registry$7.getComponentMethod("errorbars", "hoverInfo")(di, trace, barPointData); - return [barPointData]; - } -} -function hoverOnBars(pointData, xval, yval, hovermode, opts) { - var cd = pointData.cd; - var trace = cd[0].trace; - var t = cd[0].t; - var isClosest = hovermode === "closest"; - var isWaterfall = trace.type === "waterfall"; - var maxHoverDistance = pointData.maxHoverDistance; - var maxSpikeDistance = pointData.maxSpikeDistance; - var posVal, sizeVal, posLetter, sizeLetter, dx, dy, pRangeCalc; - if (trace.orientation === "h") { - posVal = yval; - sizeVal = xval; - posLetter = "y"; - sizeLetter = "x"; - dx = sizeFn; - dy = positionFn; - } else { - posVal = xval; - sizeVal = yval; - posLetter = "x"; - sizeLetter = "y"; - dy = sizeFn; - dx = positionFn; - } - var period = trace[posLetter + "period"]; - var isClosestOrPeriod = isClosest || period; - function thisBarMinPos(di2) { - return thisBarExtPos(di2, -1); - } - function thisBarMaxPos(di2) { - return thisBarExtPos(di2, 1); - } - function thisBarExtPos(di2, sgn) { - var w = di2.w; - return di2[posLetter] + sgn * w / 2; - } - function periodLength(di2) { - return di2[posLetter + "End"] - di2[posLetter + "Start"]; - } - var minPos = isClosest ? thisBarMinPos : period ? function(di2) { - return di2.p - periodLength(di2) / 2; - } : function(di2) { - return Math.min(thisBarMinPos(di2), di2.p - t.bardelta / 2); - }; - var maxPos = isClosest ? thisBarMaxPos : period ? function(di2) { - return di2.p + periodLength(di2) / 2; - } : function(di2) { - return Math.max(thisBarMaxPos(di2), di2.p + t.bardelta / 2); - }; - function inbox(_minPos, _maxPos, maxDistance) { - if (opts.finiteRange) maxDistance = 0; - return Fx$3.inbox( - _minPos - posVal, - _maxPos - posVal, - maxDistance + Math.min(1, Math.abs(_maxPos - _minPos) / pRangeCalc) - 1 - ); - } - function positionFn(di2) { - return inbox(minPos(di2), maxPos(di2), maxHoverDistance); - } - function thisBarPositionFn(di2) { - return inbox(thisBarMinPos(di2), thisBarMaxPos(di2), maxSpikeDistance); - } - function getSize(di2) { - var s = di2[sizeLetter]; - if (isWaterfall) { - var rawS = Math.abs(di2.rawS) || 0; - if (sizeVal > 0) { - s += rawS; - } else if (sizeVal < 0) { - s -= rawS; - } - } - return s; - } - function sizeFn(di2) { - var v = sizeVal; - var b = di2.b; - var s = getSize(di2); - return Fx$3.inbox(b - v, s - v, maxHoverDistance + (s - v) / (s - b) - 1); - } - function thisBarSizeFn(di2) { - var v = sizeVal; - var b = di2.b; - var s = getSize(di2); - return Fx$3.inbox(b - v, s - v, maxSpikeDistance + (s - v) / (s - b) - 1); - } - var pa = pointData[posLetter + "a"]; - var sa = pointData[sizeLetter + "a"]; - pRangeCalc = Math.abs(pa.r2c(pa.range[1]) - pa.r2c(pa.range[0])); - function dxy(di2) { - return (dx(di2) + dy(di2)) / 2; - } - var distfn = Fx$3.getDistanceFunction(hovermode, dx, dy, dxy); - Fx$3.getClosest(cd, distfn, pointData); - if (pointData.index === false) return; - if (cd[pointData.index].p === BADNUM$2) return; - if (!isClosestOrPeriod) { - minPos = function(di2) { - return Math.min(thisBarMinPos(di2), di2.p - t.bargroupwidth / 2); - }; - maxPos = function(di2) { - return Math.max(thisBarMaxPos(di2), di2.p + t.bargroupwidth / 2); - }; - } - var index2 = pointData.index; - var di = cd[index2]; - var size = trace.base ? di.b + di.s : di.s; - pointData[sizeLetter + "0"] = pointData[sizeLetter + "1"] = sa.c2p(di[sizeLetter], true); - pointData[sizeLetter + "LabelVal"] = size; - var extent2 = t.extents[t.extents.round(di.p)]; - pointData[posLetter + "0"] = pa.c2p(isClosest ? minPos(di) : extent2[0], true); - pointData[posLetter + "1"] = pa.c2p(isClosest ? maxPos(di) : extent2[1], true); - var hasPeriod = di.orig_p !== void 0; - pointData[posLetter + "LabelVal"] = hasPeriod ? di.orig_p : di.p; - pointData.labelLabel = hoverLabelText$1(pa, pointData[posLetter + "LabelVal"], trace[posLetter + "hoverformat"]); - pointData.valueLabel = hoverLabelText$1(sa, pointData[sizeLetter + "LabelVal"], trace[sizeLetter + "hoverformat"]); - pointData.baseLabel = hoverLabelText$1(sa, di.b, trace[sizeLetter + "hoverformat"]); - pointData.spikeDistance = (thisBarSizeFn(di) + thisBarPositionFn(di)) / 2; - pointData[posLetter + "Spike"] = pa.c2p(di.p, true); - fillText$1(di, trace, pointData); - pointData.hovertemplate = trace.hovertemplate; - return pointData; -} -function getTraceColor$1(trace, di) { - var mc = di.mcc || trace.marker.color; - var mlc = di.mlcc || trace.marker.line.color; - var mlw = getLineWidth(trace, di); - if (Color$c.opacity(mc)) return mc; - else if (Color$c.opacity(mlc) && mlw) return mlc; -} -var hover$4 = { - hoverPoints: hoverPoints$2 -}; -var event_data$2 = function eventData(out, pt, trace) { - out.x = "xVal" in pt ? pt.xVal : pt.x; - out.y = "yVal" in pt ? pt.yVal : pt.y; - if (pt.xa) out.xaxis = pt.xa; - if (pt.ya) out.yaxis = pt.ya; - if (trace.orientation === "h") { - out.label = out.y; - out.value = out.x; - } else { - out.label = out.x; - out.value = out.y; - } - return out; -}; -var select$2 = function selectPoints2(searchInfo, selectionTester) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var trace = cd[0].trace; - var isFunnel = trace.type === "funnel"; - var isHorizontal = trace.orientation === "h"; - var selection = []; - var i; - if (selectionTester === false) { - for (i = 0; i < cd.length; i++) { - cd[i].selected = 0; - } - } else { - for (i = 0; i < cd.length; i++) { - var di = cd[i]; - var ct = "ct" in di ? di.ct : getCentroid(di, xa, ya, isHorizontal, isFunnel); - if (selectionTester.contains(ct, false, i, searchInfo)) { - selection.push({ - pointNumber: i, - x: xa.c2d(di.x), - y: ya.c2d(di.y) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } - } - return selection; -}; -function getCentroid(d, xa, ya, isHorizontal, isFunnel) { - var x0 = xa.c2p(isHorizontal ? d.s0 : d.p0, true); - var x1 = xa.c2p(isHorizontal ? d.s1 : d.p1, true); - var y0 = ya.c2p(isHorizontal ? d.p0 : d.s0, true); - var y1 = ya.c2p(isHorizontal ? d.p1 : d.s1, true); - if (isFunnel) { - return [(x0 + x1) / 2, (y0 + y1) / 2]; - } else { - if (isHorizontal) { - return [x1, (y0 + y1) / 2]; - } else { - return [(x0 + x1) / 2, y1]; - } - } -} -var bar$2 = { - attributes: attributes$e, - layoutAttributes: layout_attributes$2, - supplyDefaults: defaults$6.supplyDefaults, - crossTraceDefaults: defaults$6.crossTraceDefaults, - supplyLayoutDefaults: layout_defaults$2, - calc: calc$7, - crossTraceCalc: cross_trace_calc$1.crossTraceCalc, - colorbar: marker_colorbar, - arraysToCalcdata: arrays_to_calcdata, - plot: plot_1$1.plot, - style: style_1$2.style, - styleOnSelect: style_1$2.styleOnSelect, - hoverPoints: hover$4.hoverPoints, - eventData: event_data$2, - selectPoints: select$2, - moduleType: "trace", - name: "bar", - basePlotModule: cartesian, - categories: ["bar-like", "cartesian", "svg", "bar", "oriented", "errorBarsOK", "showLegend", "zoomScale"], - animatable: true, - meta: { - description: [ - "The data visualized by the span of the bars is set in `y`", - "if `orientation` is set to *v* (the default)", - "and the labels are set in `x`.", - "By setting `orientation` to *h*, the roles are interchanged." - ].join(" ") - } -}; -var bar = bar$2; -const bar$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(bar); -var bin_attributes = function makeBinAttrs(axLetter, match) { - return { - start: { - valType: "any", - // for date axes - editType: "calc", - description: [ - "Sets the starting value for the", - axLetter, - "axis bins. Defaults to the minimum data value,", - "shifted down if necessary to make nice round values", - "and to remove ambiguous bin edges. For example, if most of the", - "data is integers we shift the bin edges 0.5 down, so a `size`", - "of 5 would have a default `start` of -0.5, so it is clear", - "that 0-4 are in the first bin, 5-9 in the second, but", - "continuous data gets a start of 0 and bins [0,5), [5,10) etc.", - "Dates behave similarly, and `start` should be a date string.", - "For category data, `start` is based on the category serial", - "numbers, and defaults to -0.5.", - match ? "If multiple non-overlaying histograms share a subplot, the first explicit `start` is used exactly and all others are shifted down (if necessary) to differ from that one by an integer number of bins." : "" - ].join(" ") - }, - end: { - valType: "any", - // for date axes - editType: "calc", - description: [ - "Sets the end value for the", - axLetter, - "axis bins. The last bin may not end exactly at this value,", - "we increment the bin edge by `size` from `start` until we", - "reach or exceed `end`. Defaults to the maximum data value.", - "Like `start`, for dates use a date string, and for category", - "data `end` is based on the category serial numbers." - ].join(" ") - }, - size: { - valType: "any", - // for date axes - editType: "calc", - description: [ - "Sets the size of each", - axLetter, - "axis bin.", - "Default behavior: If `nbins" + axLetter + "` is 0 or omitted,", - "we choose a nice round bin size such that the number of bins", - "is about the same as the typical number of samples in each bin.", - "If `nbins" + axLetter + "` is provided, we choose a nice round", - "bin size giving no more than that many bins.", - "For date data, use milliseconds or *M* for months, as in", - "`axis.dtick`. For category data, the number of categories to", - "bin together (always defaults to 1).", - match ? "If multiple non-overlaying histograms share a subplot, the first explicit `size` is used and all others discarded. If no `size` is provided,the sample data from all traces is combined to determine `size` as described above." : "" - ].join(" ") - }, - editType: "calc" - }; -}; -var constants$c = { - eventDataKeys: ["binNumber"] -}; -var barAttrs = attributes$e; -var axisHoverFormat$2 = axis_format_attributes.axisHoverFormat; -var hovertemplateAttrs$3 = template_attributes.hovertemplateAttrs; -var texttemplateAttrs$3 = template_attributes.texttemplateAttrs; -var fontAttrs$2 = font_attributes; -var makeBinAttrs2 = bin_attributes; -var constants$b = constants$c; -var extendFlat$5 = extend$5.extendFlat; -var attributes$a = { - x: { - valType: "data_array", - editType: "calc+clearAxisTypes", - description: [ - "Sets the sample data to be binned on the x axis." - ].join(" ") - }, - y: { - valType: "data_array", - editType: "calc+clearAxisTypes", - description: [ - "Sets the sample data to be binned on the y axis." - ].join(" ") - }, - xhoverformat: axisHoverFormat$2("x"), - yhoverformat: axisHoverFormat$2("y"), - text: extendFlat$5({}, barAttrs.text, { - description: [ - "Sets hover text elements associated with each bar.", - "If a single string, the same string appears over all bars.", - "If an array of string, the items are mapped in order to the", - "this trace's coordinates." - ].join(" ") - }), - hovertext: extendFlat$5({}, barAttrs.hovertext, { - description: "Same as `text`." - }), - orientation: barAttrs.orientation, - histfunc: { - valType: "enumerated", - values: ["count", "sum", "avg", "min", "max"], - dflt: "count", - editType: "calc", - description: [ - "Specifies the binning function used for this histogram trace.", - "If *count*, the histogram values are computed by counting the", - "number of values lying inside each bin.", - "If *sum*, *avg*, *min*, *max*,", - "the histogram values are computed using", - "the sum, the average, the minimum or the maximum", - "of the values lying inside each bin respectively." - ].join(" ") - }, - histnorm: { - valType: "enumerated", - values: ["", "percent", "probability", "density", "probability density"], - dflt: "", - editType: "calc", - description: [ - "Specifies the type of normalization used for this histogram trace.", - "If **, the span of each bar corresponds to the number of", - "occurrences (i.e. the number of data points lying inside the bins).", - "If *percent* / *probability*, the span of each bar corresponds to", - "the percentage / fraction of occurrences with respect to the total", - "number of sample points", - "(here, the sum of all bin HEIGHTS equals 100% / 1).", - "If *density*, the span of each bar corresponds to the number of", - "occurrences in a bin divided by the size of the bin interval", - "(here, the sum of all bin AREAS equals the", - "total number of sample points).", - "If *probability density*, the area of each bar corresponds to the", - "probability that an event will fall into the corresponding bin", - "(here, the sum of all bin AREAS equals 1)." - ].join(" ") - }, - cumulative: { - enabled: { - valType: "boolean", - dflt: false, - editType: "calc", - description: [ - "If true, display the cumulative distribution by summing the", - "binned values. Use the `direction` and `centralbin` attributes", - "to tune the accumulation method.", - "Note: in this mode, the *density* `histnorm` settings behave", - "the same as their equivalents without *density*:", - "** and *density* both rise to the number of data points, and", - "*probability* and *probability density* both rise to the", - "number of sample points." - ].join(" ") - }, - direction: { - valType: "enumerated", - values: ["increasing", "decreasing"], - dflt: "increasing", - editType: "calc", - description: [ - "Only applies if cumulative is enabled.", - "If *increasing* (default) we sum all prior bins, so the result", - "increases from left to right. If *decreasing* we sum later bins", - "so the result decreases from left to right." - ].join(" ") - }, - currentbin: { - valType: "enumerated", - values: ["include", "exclude", "half"], - dflt: "include", - editType: "calc", - description: [ - "Only applies if cumulative is enabled.", - "Sets whether the current bin is included, excluded, or has half", - "of its value included in the current cumulative value.", - "*include* is the default for compatibility with various other", - "tools, however it introduces a half-bin bias to the results.", - "*exclude* makes the opposite half-bin bias, and *half* removes", - "it." - ].join(" ") - }, - editType: "calc" - }, - nbinsx: { - valType: "integer", - min: 0, - dflt: 0, - editType: "calc", - description: [ - "Specifies the maximum number of desired bins. This value will be used", - "in an algorithm that will decide the optimal bin size such that the", - "histogram best visualizes the distribution of the data.", - "Ignored if `xbins.size` is provided." - ].join(" ") - }, - xbins: makeBinAttrs2("x", true), - nbinsy: { - valType: "integer", - min: 0, - dflt: 0, - editType: "calc", - description: [ - "Specifies the maximum number of desired bins. This value will be used", - "in an algorithm that will decide the optimal bin size such that the", - "histogram best visualizes the distribution of the data.", - "Ignored if `ybins.size` is provided." - ].join(" ") - }, - ybins: makeBinAttrs2("y", true), - autobinx: { - valType: "boolean", - dflt: null, - editType: "calc", - description: [ - "Obsolete: since v1.42 each bin attribute is auto-determined", - "separately and `autobinx` is not needed. However, we accept", - "`autobinx: true` or `false` and will update `xbins` accordingly", - "before deleting `autobinx` from the trace." - ].join(" ") - }, - autobiny: { - valType: "boolean", - dflt: null, - editType: "calc", - description: [ - "Obsolete: since v1.42 each bin attribute is auto-determined", - "separately and `autobiny` is not needed. However, we accept", - "`autobiny: true` or `false` and will update `ybins` accordingly", - "before deleting `autobiny` from the trace." - ].join(" ") - }, - bingroup: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "Set a group of histogram traces which will have compatible bin settings.", - "Note that traces on the same subplot and with the same *orientation*", - "under `barmode` *stack*, *relative* and *group* are forced into the same bingroup,", - "Using `bingroup`, traces under `barmode` *overlay* and on different axes", - "(of the same axis type) can have compatible bin settings.", - "Note that histogram and histogram2d* trace can share the same `bingroup`" - ].join(" ") - }, - hovertemplate: hovertemplateAttrs$3({}, { - keys: constants$b.eventDataKeys - }), - texttemplate: texttemplateAttrs$3({ - arrayOk: false, - editType: "plot" - }, { - keys: ["label", "value"] - }), - textposition: extendFlat$5({}, barAttrs.textposition, { - arrayOk: false - }), - textfont: fontAttrs$2({ - arrayOk: false, - editType: "plot", - colorEditType: "style", - description: "Sets the text font." - }), - outsidetextfont: fontAttrs$2({ - arrayOk: false, - editType: "plot", - colorEditType: "style", - description: "Sets the font used for `text` lying outside the bar." - }), - insidetextfont: fontAttrs$2({ - arrayOk: false, - editType: "plot", - colorEditType: "style", - description: "Sets the font used for `text` lying inside the bar." - }), - insidetextanchor: barAttrs.insidetextanchor, - textangle: barAttrs.textangle, - cliponaxis: barAttrs.cliponaxis, - constraintext: barAttrs.constraintext, - marker: barAttrs.marker, - offsetgroup: barAttrs.offsetgroup, - alignmentgroup: barAttrs.alignmentgroup, - selected: barAttrs.selected, - unselected: barAttrs.unselected, - _deprecated: { - bardir: barAttrs._deprecated.bardir - }, - zorder: barAttrs.zorder -}; -var Registry$6 = registry; -var Lib$p = libExports; -var Color$b = colorExports; -var handleText$2 = defaults$6.handleText; -var handleStyleDefaults2 = style_defaults; -var attributes$9 = attributes$a; -var defaults$5 = function supplyDefaults3(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$p.coerce(traceIn, traceOut, attributes$9, attr, dflt); - } - var x = coerce2("x"); - var y = coerce2("y"); - var cumulative = coerce2("cumulative.enabled"); - if (cumulative) { - coerce2("cumulative.direction"); - coerce2("cumulative.currentbin"); - } - coerce2("text"); - var textposition = coerce2("textposition"); - handleText$2(traceIn, traceOut, layout, coerce2, textposition, { - moduleHasSelected: true, - moduleHasUnselected: true, - moduleHasConstrain: true, - moduleHasCliponaxis: true, - moduleHasTextangle: true, - moduleHasInsideanchor: true - }); - coerce2("hovertext"); - coerce2("hovertemplate"); - coerce2("xhoverformat"); - coerce2("yhoverformat"); - var orientation = coerce2("orientation", y && !x ? "h" : "v"); - var sampleLetter = orientation === "v" ? "x" : "y"; - var aggLetter = orientation === "v" ? "y" : "x"; - var len = x && y ? Math.min(Lib$p.minRowLength(x) && Lib$p.minRowLength(y)) : Lib$p.minRowLength(traceOut[sampleLetter] || []); - if (!len) { - traceOut.visible = false; - return; - } - traceOut._length = len; - var handleCalendarDefaults = Registry$6.getComponentMethod("calendars", "handleTraceDefaults"); - handleCalendarDefaults(traceIn, traceOut, ["x", "y"], layout); - var hasAggregationData = traceOut[aggLetter]; - if (hasAggregationData) coerce2("histfunc"); - coerce2("histnorm"); - coerce2("autobin" + sampleLetter); - handleStyleDefaults2(traceIn, traceOut, coerce2, defaultColor, layout); - Lib$p.coerceSelectionMarkerOpacity(traceOut, coerce2); - var lineColor = (traceOut.marker.line || {}).color; - var errorBarsSupplyDefaults = Registry$6.getComponentMethod("errorbars", "supplyDefaults"); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$b.defaultLine, { axis: "y" }); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || Color$b.defaultLine, { axis: "x", inherit: "y" }); - coerce2("zorder"); -}; -var Lib$o = libExports; -var axisIds = axis_ids; -var traceIs = registry.traceIs; -var handleGroupingDefaults2 = grouping_defaults; -var validateCornerradius = defaults$6.validateCornerradius; -var nestedProperty2 = Lib$o.nestedProperty; -var getAxisGroup2 = constraints.getAxisGroup; -var BINATTRS = [ - { aStr: { x: "xbins.start", y: "ybins.start" }, name: "start" }, - { aStr: { x: "xbins.end", y: "ybins.end" }, name: "end" }, - { aStr: { x: "xbins.size", y: "ybins.size" }, name: "size" }, - { aStr: { x: "nbinsx", y: "nbinsy" }, name: "nbins" } -]; -var BINDIRECTIONS = ["x", "y"]; -var cross_trace_defaults = function crossTraceDefaults4(fullData, fullLayout) { - var allBinOpts = fullLayout._histogramBinOpts = {}; - var histTraces = []; - var mustMatchTracesLookup = {}; - var otherTracesList = []; - var traceOut, traces, groupName, binDir; - var i, j, k; - function coerce2(attr2, dflt) { - return Lib$o.coerce(traceOut._input, traceOut, traceOut._module.attributes, attr2, dflt); - } - function orientation2binDir(traceOut2) { - return traceOut2.orientation === "v" ? "x" : "y"; - } - function getAxisType(traceOut2, binDir2) { - var ax = axisIds.getFromTrace({ _fullLayout: fullLayout }, traceOut2, binDir2); - return ax.type; - } - function fillBinOpts(traceOut2, groupName2, binDir2) { - var fallbackGroupName = traceOut2.uid + "__" + binDir2; - if (!groupName2) groupName2 = fallbackGroupName; - var axType = getAxisType(traceOut2, binDir2); - var calendar = traceOut2[binDir2 + "calendar"] || ""; - var binOpts2 = allBinOpts[groupName2]; - var needsNewItem = true; - if (binOpts2) { - if (axType === binOpts2.axType && calendar === binOpts2.calendar) { - needsNewItem = false; - binOpts2.traces.push(traceOut2); - binOpts2.dirs.push(binDir2); - } else { - groupName2 = fallbackGroupName; - if (axType !== binOpts2.axType) { - Lib$o.warn([ - "Attempted to group the bins of trace", - traceOut2.index, - "set on a", - "type:" + axType, - "axis", - "with bins on", - "type:" + binOpts2.axType, - "axis." - ].join(" ")); - } - if (calendar !== binOpts2.calendar) { - Lib$o.warn([ - "Attempted to group the bins of trace", - traceOut2.index, - "set with a", - calendar, - "calendar", - "with bins", - binOpts2.calendar ? "on a " + binOpts2.calendar + " calendar" : "w/o a set calendar" - ].join(" ")); - } - } - } - if (needsNewItem) { - allBinOpts[groupName2] = { - traces: [traceOut2], - dirs: [binDir2], - axType, - calendar: traceOut2[binDir2 + "calendar"] || "" - }; - } - traceOut2["_" + binDir2 + "bingroup"] = groupName2; - } - for (i = 0; i < fullData.length; i++) { - traceOut = fullData[i]; - if (traceIs(traceOut, "histogram")) { - histTraces.push(traceOut); - delete traceOut._xautoBinFinished; - delete traceOut._yautoBinFinished; - if (traceOut.type === "histogram") { - var r = coerce2("marker.cornerradius", fullLayout.barcornerradius); - if (traceOut.marker) { - traceOut.marker.cornerradius = validateCornerradius(r); - } - } - if (!traceIs(traceOut, "2dMap")) { - handleGroupingDefaults2(traceOut._input, traceOut, fullLayout, coerce2); - } - } - } - var alignmentOpts = fullLayout._alignmentOpts || {}; - for (i = 0; i < histTraces.length; i++) { - traceOut = histTraces[i]; - groupName = ""; - if (!traceIs(traceOut, "2dMap")) { - binDir = orientation2binDir(traceOut); - if (fullLayout.barmode === "group" && traceOut.alignmentgroup) { - var pa = traceOut[binDir + "axis"]; - var aGroupId = getAxisGroup2(fullLayout, pa) + traceOut.orientation; - if ((alignmentOpts[aGroupId] || {})[traceOut.alignmentgroup]) { - groupName = aGroupId; - } - } - if (!groupName && fullLayout.barmode !== "overlay") { - groupName = getAxisGroup2(fullLayout, traceOut.xaxis) + getAxisGroup2(fullLayout, traceOut.yaxis) + orientation2binDir(traceOut); - } - } - if (groupName) { - if (!mustMatchTracesLookup[groupName]) { - mustMatchTracesLookup[groupName] = []; - } - mustMatchTracesLookup[groupName].push(traceOut); - } else { - otherTracesList.push(traceOut); - } - } - for (groupName in mustMatchTracesLookup) { - traces = mustMatchTracesLookup[groupName]; - if (traces.length === 1) { - otherTracesList.push(traces[0]); - continue; - } - var binGroupFound = false; - if (traces.length) { - traceOut = traces[0]; - binGroupFound = coerce2("bingroup"); - } - groupName = binGroupFound || groupName; - for (i = 0; i < traces.length; i++) { - traceOut = traces[i]; - var bingroupIn = traceOut._input.bingroup; - if (bingroupIn && bingroupIn !== groupName) { - Lib$o.warn([ - "Trace", - traceOut.index, - "must match", - "within bingroup", - groupName + ".", - "Ignoring its bingroup:", - bingroupIn, - "setting." - ].join(" ")); - } - traceOut.bingroup = groupName; - fillBinOpts(traceOut, groupName, orientation2binDir(traceOut)); - } - } - for (i = 0; i < otherTracesList.length; i++) { - traceOut = otherTracesList[i]; - var binGroup = coerce2("bingroup"); - if (traceIs(traceOut, "2dMap")) { - for (k = 0; k < 2; k++) { - binDir = BINDIRECTIONS[k]; - var binGroupInDir = coerce2( - binDir + "bingroup", - binGroup ? binGroup + "__" + binDir : null - ); - fillBinOpts(traceOut, binGroupInDir, binDir); - } - } else { - fillBinOpts(traceOut, binGroup, orientation2binDir(traceOut)); - } - } - for (groupName in allBinOpts) { - var binOpts = allBinOpts[groupName]; - traces = binOpts.traces; - for (j = 0; j < BINATTRS.length; j++) { - var attrSpec = BINATTRS[j]; - var attr = attrSpec.name; - var aStr; - var autoVals; - if (attr === "nbins" && binOpts.sizeFound) continue; - for (i = 0; i < traces.length; i++) { - traceOut = traces[i]; - binDir = binOpts.dirs[i]; - aStr = attrSpec.aStr[binDir]; - if (nestedProperty2(traceOut._input, aStr).get() !== void 0) { - binOpts[attr] = coerce2(aStr); - binOpts[attr + "Found"] = true; - break; - } - autoVals = (traceOut._autoBin || {})[binDir] || {}; - if (autoVals[attr]) { - nestedProperty2(traceOut, aStr).set(autoVals[attr]); - } - } - if (attr === "start" || attr === "end") { - for (; i < traces.length; i++) { - traceOut = traces[i]; - if (traceOut["_" + binDir + "bingroup"]) { - autoVals = (traceOut._autoBin || {})[binDir] || {}; - coerce2(aStr, autoVals[attr]); - } - } - } - if (attr === "nbins" && !binOpts.sizeFound && !binOpts.nbinsFound) { - traceOut = traces[0]; - binOpts[attr] = coerce2(aStr); - } - } - } -}; -var isNumeric$5 = fastIsnumeric; -var bin_functions = { - count: function(n, i, size) { - size[n]++; - return 1; - }, - sum: function(n, i, size, counterData) { - var v = counterData[i]; - if (isNumeric$5(v)) { - v = Number(v); - size[n] += v; - return v; - } - return 0; - }, - avg: function(n, i, size, counterData, counts) { - var v = counterData[i]; - if (isNumeric$5(v)) { - v = Number(v); - size[n] += v; - counts[n]++; - } - return 0; - }, - min: function(n, i, size, counterData) { - var v = counterData[i]; - if (isNumeric$5(v)) { - v = Number(v); - if (!isNumeric$5(size[n])) { - size[n] = v; - return v; - } else if (size[n] > v) { - var delta2 = v - size[n]; - size[n] = v; - return delta2; - } - } - return 0; - }, - max: function(n, i, size, counterData) { - var v = counterData[i]; - if (isNumeric$5(v)) { - v = Number(v); - if (!isNumeric$5(size[n])) { - size[n] = v; - return v; - } else if (size[n] < v) { - var delta2 = v - size[n]; - size[n] = v; - return delta2; - } - } - return 0; - } -}; -var norm_functions = { - percent: function(size, total) { - var nMax = size.length; - var norm2 = 100 / total; - for (var n = 0; n < nMax; n++) size[n] *= norm2; - }, - probability: function(size, total) { - var nMax = size.length; - for (var n = 0; n < nMax; n++) size[n] /= total; - }, - density: function(size, total, inc, yinc) { - var nMax = size.length; - yinc = yinc || 1; - for (var n = 0; n < nMax; n++) size[n] *= inc[n] * yinc; - }, - "probability density": function(size, total, inc, yinc) { - var nMax = size.length; - if (yinc) total /= yinc; - for (var n = 0; n < nMax; n++) size[n] *= inc[n] / total; - } -}; -var average = function doAvg(size, counts) { - var nMax = size.length; - var total = 0; - for (var i = 0; i < nMax; i++) { - if (counts[i]) { - size[i] /= counts[i]; - total += size[i]; - } else size[i] = null; - } - return total; -}; -var numConstants = numerical; -var oneYear = numConstants.ONEAVGYEAR; -var oneMonth = numConstants.ONEAVGMONTH; -var oneDay = numConstants.ONEDAY; -var oneHour = numConstants.ONEHOUR; -var oneMin = numConstants.ONEMIN; -var oneSec = numConstants.ONESEC; -var tickIncrement = axesExports.tickIncrement; -var bin_label_vals = function getBinSpanLabelRound(leftGap, rightGap, binEdges, pa, calendar) { - var dv0 = -1.1 * rightGap; - var dv1 = -0.1 * rightGap; - var dv2 = leftGap - dv1; - var edge0 = binEdges[0]; - var edge1 = binEdges[1]; - var leftDigit = Math.min( - biggestDigitChanged(edge0 + dv1, edge0 + dv2, pa, calendar), - biggestDigitChanged(edge1 + dv1, edge1 + dv2, pa, calendar) - ); - var rightDigit = Math.min( - biggestDigitChanged(edge0 + dv0, edge0 + dv1, pa, calendar), - biggestDigitChanged(edge1 + dv0, edge1 + dv1, pa, calendar) - ); - var digit, disambiguateEdges; - if (leftDigit > rightDigit && rightDigit < Math.abs(edge1 - edge0) / 4e3) { - digit = leftDigit; - disambiguateEdges = false; - } else { - digit = Math.min(leftDigit, rightDigit); - disambiguateEdges = true; - } - if (pa.type === "date" && digit > oneDay) { - var dashExclude = digit === oneYear ? 1 : 6; - var increment2 = digit === oneYear ? "M12" : "M1"; - return function(v, isRightEdge) { - var dateStr = pa.c2d(v, oneYear, calendar); - var dashPos = dateStr.indexOf("-", dashExclude); - if (dashPos > 0) dateStr = dateStr.substr(0, dashPos); - var roundedV = pa.d2c(dateStr, 0, calendar); - if (roundedV < v) { - var nextV = tickIncrement(roundedV, increment2, false, calendar); - if ((roundedV + nextV) / 2 < v + leftGap) roundedV = nextV; - } - if (isRightEdge && disambiguateEdges) { - return tickIncrement(roundedV, increment2, true, calendar); - } - return roundedV; - }; - } - return function(v, isRightEdge) { - var roundedV = digit * Math.round(v / digit); - if (roundedV + digit / 10 < v && roundedV + digit * 0.9 < v + leftGap) { - roundedV += digit; - } - if (isRightEdge && disambiguateEdges) { - roundedV -= digit; - } - return roundedV; - }; -}; -function biggestDigitChanged(v1, v2, pa, calendar) { - if (v1 * v2 <= 0) return Infinity; - var dv2 = Math.abs(v2 - v1); - var isDate = pa.type === "date"; - var digit = biggestGuaranteedDigitChanged(dv2, isDate); - for (var i = 0; i < 10; i++) { - var nextDigit = biggestGuaranteedDigitChanged(digit * 80, isDate); - if (digit === nextDigit) break; - if (didDigitChange(nextDigit, v1, v2, isDate, pa, calendar)) digit = nextDigit; - else break; - } - return digit; -} -function biggestGuaranteedDigitChanged(dv2, isDate) { - if (isDate && dv2 > oneSec) { - if (dv2 > oneDay) { - if (dv2 > oneYear * 1.1) return oneYear; - if (dv2 > oneMonth * 1.1) return oneMonth; - return oneDay; - } - if (dv2 > oneHour) return oneHour; - if (dv2 > oneMin) return oneMin; - return oneSec; - } - return Math.pow(10, Math.floor(Math.log(dv2) / Math.LN10)); -} -function didDigitChange(digit, v1, v2, isDate, pa, calendar) { - if (isDate && digit > oneDay) { - var dateParts1 = dateParts(v1, pa, calendar); - var dateParts2 = dateParts(v2, pa, calendar); - var parti = digit === oneYear ? 0 : 1; - return dateParts1[parti] !== dateParts2[parti]; - } - return Math.floor(v2 / digit) - Math.floor(v1 / digit) > 0.1; -} -function dateParts(v, pa, calendar) { - var parts = pa.c2d(v, oneYear, calendar).split("-"); - if (parts[0] === "") { - parts.unshift(); - parts[0] = "-" + parts[0]; - } - return parts; -} -var isNumeric$4 = fastIsnumeric; -var Lib$n = libExports; -var Registry$5 = registry; -var Axes$2 = axesExports; -var arraysToCalcdata3 = arrays_to_calcdata; -var binFunctions = bin_functions; -var normFunctions = norm_functions; -var doAvg2 = average; -var getBinSpanLabelRound2 = bin_label_vals; -function calc$6(gd, trace) { - var pos = []; - var size = []; - var isHorizontal = trace.orientation === "h"; - var pa = Axes$2.getFromId(gd, isHorizontal ? trace.yaxis : trace.xaxis); - var mainData = isHorizontal ? "y" : "x"; - var counterData = { x: "y", y: "x" }[mainData]; - var calendar = trace[mainData + "calendar"]; - var cumulativeSpec = trace.cumulative; - var i; - var binsAndPos = calcAllAutoBins(gd, trace, pa, mainData); - var binSpec = binsAndPos[0]; - var pos0 = binsAndPos[1]; - var nonuniformBins = typeof binSpec.size === "string"; - var binEdges = []; - var bins = nonuniformBins ? binEdges : binSpec; - var inc = []; - var counts = []; - var inputPoints = []; - var total = 0; - var norm2 = trace.histnorm; - var func = trace.histfunc; - var densityNorm = norm2.indexOf("density") !== -1; - var i2, binEnd, n; - if (cumulativeSpec.enabled && densityNorm) { - norm2 = norm2.replace(/ ?density$/, ""); - densityNorm = false; - } - var extremeFunc = func === "max" || func === "min"; - var sizeInit = extremeFunc ? null : 0; - var binFunc = binFunctions.count; - var normFunc = normFunctions[norm2]; - var isAvg = false; - var pr2c = function(v) { - return pa.r2c(v, 0, calendar); - }; - var rawCounterData; - if (Lib$n.isArrayOrTypedArray(trace[counterData]) && func !== "count") { - rawCounterData = trace[counterData]; - isAvg = func === "avg"; - binFunc = binFunctions[func]; - } - i = pr2c(binSpec.start); - binEnd = pr2c(binSpec.end) + (i - Axes$2.tickIncrement(i, binSpec.size, false, calendar)) / 1e6; - while (i < binEnd && pos.length < 1e6) { - i2 = Axes$2.tickIncrement(i, binSpec.size, false, calendar); - pos.push((i + i2) / 2); - size.push(sizeInit); - inputPoints.push([]); - binEdges.push(i); - if (densityNorm) inc.push(1 / (i2 - i)); - if (isAvg) counts.push(0); - if (i2 <= i) break; - i = i2; - } - binEdges.push(i); - if (!nonuniformBins && pa.type === "date") { - bins = { - start: pr2c(bins.start), - end: pr2c(bins.end), - size: bins.size - }; - } - if (!gd._fullLayout._roundFnOpts) gd._fullLayout._roundFnOpts = {}; - var groupName = trace["_" + mainData + "bingroup"]; - var roundFnOpts = { leftGap: Infinity, rightGap: Infinity }; - if (groupName) { - if (!gd._fullLayout._roundFnOpts[groupName]) gd._fullLayout._roundFnOpts[groupName] = roundFnOpts; - roundFnOpts = gd._fullLayout._roundFnOpts[groupName]; - } - var nMax = size.length; - var uniqueValsPerBin = true; - var leftGap = roundFnOpts.leftGap; - var rightGap = roundFnOpts.rightGap; - var ptNumber2cdIndex = {}; - for (i = 0; i < pos0.length; i++) { - var posi = pos0[i]; - n = Lib$n.findBin(posi, bins); - if (n >= 0 && n < nMax) { - total += binFunc(n, i, size, rawCounterData, counts); - if (uniqueValsPerBin && inputPoints[n].length && posi !== pos0[inputPoints[n][0]]) { - uniqueValsPerBin = false; - } - inputPoints[n].push(i); - ptNumber2cdIndex[i] = n; - leftGap = Math.min(leftGap, posi - binEdges[n]); - rightGap = Math.min(rightGap, binEdges[n + 1] - posi); - } - } - roundFnOpts.leftGap = leftGap; - roundFnOpts.rightGap = rightGap; - var roundFn; - if (!uniqueValsPerBin) { - roundFn = function(v, isRightEdge) { - return function() { - var roundFnOpts2 = gd._fullLayout._roundFnOpts[groupName]; - return getBinSpanLabelRound2( - roundFnOpts2.leftGap, - roundFnOpts2.rightGap, - binEdges, - pa, - calendar - )(v, isRightEdge); - }; - }; - } - if (isAvg) total = doAvg2(size, counts); - if (normFunc) normFunc(size, total, inc); - if (cumulativeSpec.enabled) cdf(size, cumulativeSpec.direction, cumulativeSpec.currentbin); - var seriesLen = Math.min(pos.length, size.length); - var cd = []; - var firstNonzero = 0; - var lastNonzero = seriesLen - 1; - for (i = 0; i < seriesLen; i++) { - if (size[i]) { - firstNonzero = i; - break; - } - } - for (i = seriesLen - 1; i >= firstNonzero; i--) { - if (size[i]) { - lastNonzero = i; - break; - } - } - for (i = firstNonzero; i <= lastNonzero; i++) { - if (isNumeric$4(pos[i]) && isNumeric$4(size[i])) { - var cdi = { - p: pos[i], - s: size[i], - b: 0 - }; - if (!cumulativeSpec.enabled) { - cdi.pts = inputPoints[i]; - if (uniqueValsPerBin) { - cdi.ph0 = cdi.ph1 = inputPoints[i].length ? pos0[inputPoints[i][0]] : pos[i]; - } else { - trace._computePh = true; - cdi.ph0 = roundFn(binEdges[i]); - cdi.ph1 = roundFn(binEdges[i + 1], true); - } - } - cd.push(cdi); - } - } - if (cd.length === 1) { - cd[0].width1 = Axes$2.tickIncrement(cd[0].p, binSpec.size, false, calendar) - cd[0].p; - } - arraysToCalcdata3(cd, trace); - if (Lib$n.isArrayOrTypedArray(trace.selectedpoints)) { - Lib$n.tagSelected(cd, trace, ptNumber2cdIndex); - } - return cd; -} -function calcAllAutoBins(gd, trace, pa, mainData, _overlayEdgeCase) { - var binAttr = mainData + "bins"; - var fullLayout = gd._fullLayout; - var groupName = trace["_" + mainData + "bingroup"]; - var binOpts = fullLayout._histogramBinOpts[groupName]; - var isOverlay = fullLayout.barmode === "overlay"; - var i, traces, tracei, calendar, pos0, autoVals, cumulativeSpec; - var r2c = function(v) { - return pa.r2c(v, 0, calendar); - }; - var c2r = function(v) { - return pa.c2r(v, 0, calendar); - }; - var cleanBound = pa.type === "date" ? function(v) { - return v || v === 0 ? Lib$n.cleanDate(v, null, calendar) : null; - } : function(v) { - return isNumeric$4(v) ? Number(v) : null; - }; - function setBound(attr, bins, newBins) { - if (bins[attr + "Found"]) { - bins[attr] = cleanBound(bins[attr]); - if (bins[attr] === null) bins[attr] = newBins[attr]; - } else { - autoVals[attr] = bins[attr] = newBins[attr]; - Lib$n.nestedProperty(traces[0], binAttr + "." + attr).set(newBins[attr]); - } - } - if (trace["_" + mainData + "autoBinFinished"]) { - delete trace["_" + mainData + "autoBinFinished"]; - } else { - traces = binOpts.traces; - var allPos = []; - var isFirstVisible = true; - var has2dMap = false; - var hasHist2dContour = false; - for (i = 0; i < traces.length; i++) { - tracei = traces[i]; - if (tracei.visible) { - var mainDatai = binOpts.dirs[i]; - pos0 = tracei["_" + mainDatai + "pos0"] = pa.makeCalcdata(tracei, mainDatai); - allPos = Lib$n.concat(allPos, pos0); - delete tracei["_" + mainData + "autoBinFinished"]; - if (trace.visible === true) { - if (isFirstVisible) { - isFirstVisible = false; - } else { - delete tracei._autoBin; - tracei["_" + mainData + "autoBinFinished"] = 1; - } - if (Registry$5.traceIs(tracei, "2dMap")) { - has2dMap = true; - } - if (tracei.type === "histogram2dcontour") { - hasHist2dContour = true; - } - } - } - } - calendar = traces[0][mainData + "calendar"]; - var newBinSpec = Axes$2.autoBin(allPos, pa, binOpts.nbins, has2dMap, calendar, binOpts.sizeFound && binOpts.size); - var autoBin = traces[0]._autoBin = {}; - autoVals = autoBin[binOpts.dirs[0]] = {}; - if (hasHist2dContour) { - if (!binOpts.size) { - newBinSpec.start = c2r(Axes$2.tickIncrement( - r2c(newBinSpec.start), - newBinSpec.size, - true, - calendar - )); - } - if (binOpts.end === void 0) { - newBinSpec.end = c2r(Axes$2.tickIncrement( - r2c(newBinSpec.end), - newBinSpec.size, - false, - calendar - )); - } - } - if (isOverlay && !Registry$5.traceIs(trace, "2dMap") && newBinSpec._dataSpan === 0 && pa.type !== "category" && pa.type !== "multicategory" && trace.bingroup === "" && typeof trace.xbins === "undefined") { - if (_overlayEdgeCase) return [newBinSpec, pos0, true]; - newBinSpec = handleSingleValueOverlays(gd, trace, pa, mainData, binAttr); - } - cumulativeSpec = tracei.cumulative || {}; - if (cumulativeSpec.enabled && cumulativeSpec.currentbin !== "include") { - if (cumulativeSpec.direction === "decreasing") { - newBinSpec.start = c2r(Axes$2.tickIncrement( - r2c(newBinSpec.start), - newBinSpec.size, - true, - calendar - )); - } else { - newBinSpec.end = c2r(Axes$2.tickIncrement( - r2c(newBinSpec.end), - newBinSpec.size, - false, - calendar - )); - } - } - binOpts.size = newBinSpec.size; - if (!binOpts.sizeFound) { - autoVals.size = newBinSpec.size; - Lib$n.nestedProperty(traces[0], binAttr + ".size").set(newBinSpec.size); - } - setBound("start", binOpts, newBinSpec); - setBound("end", binOpts, newBinSpec); - } - pos0 = trace["_" + mainData + "pos0"]; - delete trace["_" + mainData + "pos0"]; - var traceInputBins = trace._input[binAttr] || {}; - var traceBinOptsCalc = Lib$n.extendFlat({}, binOpts); - var mainStart = binOpts.start; - var startIn = pa.r2l(traceInputBins.start); - var hasStart = startIn !== void 0; - if ((binOpts.startFound || hasStart) && startIn !== pa.r2l(mainStart)) { - var traceStart = hasStart ? startIn : Lib$n.aggNums(Math.min, null, pos0); - var dummyAx = { - type: pa.type === "category" || pa.type === "multicategory" ? "linear" : pa.type, - r2l: pa.r2l, - dtick: binOpts.size, - tick0: mainStart, - calendar, - range: [traceStart, Axes$2.tickIncrement(traceStart, binOpts.size, false, calendar)].map(pa.l2r) - }; - var newStart = Axes$2.tickFirst(dummyAx); - if (newStart > pa.r2l(traceStart)) { - newStart = Axes$2.tickIncrement(newStart, binOpts.size, true, calendar); - } - traceBinOptsCalc.start = pa.l2r(newStart); - if (!hasStart) Lib$n.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.start); - } - var mainEnd = binOpts.end; - var endIn = pa.r2l(traceInputBins.end); - var hasEnd = endIn !== void 0; - if ((binOpts.endFound || hasEnd) && endIn !== pa.r2l(mainEnd)) { - var traceEnd = hasEnd ? endIn : Lib$n.aggNums(Math.max, null, pos0); - traceBinOptsCalc.end = pa.l2r(traceEnd); - if (!hasEnd) Lib$n.nestedProperty(trace, binAttr + ".start").set(traceBinOptsCalc.end); - } - var autoBinAttr = "autobin" + mainData; - if (trace._input[autoBinAttr] === false) { - trace._input[binAttr] = Lib$n.extendFlat({}, trace[binAttr] || {}); - delete trace._input[autoBinAttr]; - delete trace[autoBinAttr]; - } - return [traceBinOptsCalc, pos0]; -} -function handleSingleValueOverlays(gd, trace, pa, mainData, binAttr) { - var fullLayout = gd._fullLayout; - var overlaidTraceGroup = getConnectedHistograms(gd, trace); - var pastThisTrace = false; - var minSize = Infinity; - var singleValuedTraces = [trace]; - var i, tracei, binOpts; - for (i = 0; i < overlaidTraceGroup.length; i++) { - tracei = overlaidTraceGroup[i]; - if (tracei === trace) { - pastThisTrace = true; - } else if (!pastThisTrace) { - binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]]; - minSize = Math.min(minSize, binOpts.size || tracei[binAttr].size); - } else { - var resulti = calcAllAutoBins(gd, tracei, pa, mainData, true); - var binSpeci = resulti[0]; - var isSingleValued = resulti[2]; - tracei["_" + mainData + "autoBinFinished"] = 1; - tracei["_" + mainData + "pos0"] = resulti[1]; - if (isSingleValued) { - singleValuedTraces.push(tracei); - } else { - minSize = Math.min(minSize, binSpeci.size); - } - } - } - var dataVals = new Array(singleValuedTraces.length); - for (i = 0; i < singleValuedTraces.length; i++) { - var pos0 = singleValuedTraces[i]["_" + mainData + "pos0"]; - for (var j = 0; j < pos0.length; j++) { - if (pos0[j] !== void 0) { - dataVals[i] = pos0[j]; - break; - } - } - } - if (!isFinite(minSize)) { - minSize = Lib$n.distinctVals(dataVals).minDiff; - } - for (i = 0; i < singleValuedTraces.length; i++) { - tracei = singleValuedTraces[i]; - var calendar = tracei[mainData + "calendar"]; - var newBins = { - start: pa.c2r(dataVals[i] - minSize / 2, 0, calendar), - end: pa.c2r(dataVals[i] + minSize / 2, 0, calendar), - size: minSize - }; - tracei._input[binAttr] = tracei[binAttr] = newBins; - binOpts = fullLayout._histogramBinOpts[tracei["_" + mainData + "bingroup"]]; - if (binOpts) Lib$n.extendFlat(binOpts, newBins); - } - return trace[binAttr]; -} -function getConnectedHistograms(gd, trace) { - var xid = trace.xaxis; - var yid = trace.yaxis; - var orientation = trace.orientation; - var out = []; - var fullData = gd._fullData; - for (var i = 0; i < fullData.length; i++) { - var tracei = fullData[i]; - if (tracei.type === "histogram" && tracei.visible === true && tracei.orientation === orientation && tracei.xaxis === xid && tracei.yaxis === yid) { - out.push(tracei); - } - } - return out; -} -function cdf(size, direction, currentBin) { - var i, vi, prevSum; - function firstHalfPoint(i2) { - prevSum = size[i2]; - size[i2] /= 2; - } - function nextHalfPoint(i2) { - vi = size[i2]; - size[i2] = prevSum + vi / 2; - prevSum += vi; - } - if (currentBin === "half") { - if (direction === "increasing") { - firstHalfPoint(0); - for (i = 1; i < size.length; i++) { - nextHalfPoint(i); - } - } else { - firstHalfPoint(size.length - 1); - for (i = size.length - 2; i >= 0; i--) { - nextHalfPoint(i); - } - } - } else if (direction === "increasing") { - for (i = 1; i < size.length; i++) { - size[i] += size[i - 1]; - } - if (currentBin === "exclude") { - size.unshift(0); - size.pop(); - } - } else { - for (i = size.length - 2; i >= 0; i--) { - size[i] += size[i + 1]; - } - if (currentBin === "exclude") { - size.push(0); - size.shift(); - } - } -} -var calc_1$2 = { - calc: calc$6 -}; -var barHover = hover$4.hoverPoints; -var hoverLabelText = axesExports.hoverLabelText; -var hover$3 = function hoverPoints2(pointData, xval, yval, hovermode, opts) { - var pts = barHover(pointData, xval, yval, hovermode, opts); - if (!pts) return; - pointData = pts[0]; - var di = pointData.cd[pointData.index]; - var trace = pointData.cd[0].trace; - if (!trace.cumulative.enabled) { - var posLetter = trace.orientation === "h" ? "y" : "x"; - pointData[posLetter + "Label"] = hoverLabelText(pointData[posLetter + "a"], [di.ph0, di.ph1], trace[posLetter + "hoverformat"]); - } - return pts; -}; -var event_data$1 = function eventData2(out, pt, trace, cd, pointNumber) { - out.x = "xVal" in pt ? pt.xVal : pt.x; - out.y = "yVal" in pt ? pt.yVal : pt.y; - if ("zLabelVal" in pt) out.z = pt.zLabelVal; - if (pt.xa) out.xaxis = pt.xa; - if (pt.ya) out.yaxis = pt.ya; - if (!(trace.cumulative || {}).enabled) { - var pts = Array.isArray(pointNumber) ? cd[0].pts[pointNumber[0]][pointNumber[1]] : cd[pointNumber].pts; - out.pointNumbers = pts; - out.binNumber = out.pointNumber; - delete out.pointNumber; - delete out.pointIndex; - var pointIndices; - if (trace._indexToPoints) { - pointIndices = []; - for (var i = 0; i < pts.length; i++) { - pointIndices = pointIndices.concat(trace._indexToPoints[pts[i]]); - } - } else { - pointIndices = pts; - } - out.pointIndices = pointIndices; - } - return out; -}; -var histogram$2 = { - attributes: attributes$a, - layoutAttributes: layout_attributes$2, - supplyDefaults: defaults$5, - crossTraceDefaults: cross_trace_defaults, - supplyLayoutDefaults: layout_defaults$2, - calc: calc_1$2.calc, - crossTraceCalc: cross_trace_calc$1.crossTraceCalc, - plot: plot_1$1.plot, - layerName: "barlayer", - style: style_1$2.style, - styleOnSelect: style_1$2.styleOnSelect, - colorbar: marker_colorbar, - hoverPoints: hover$3, - selectPoints: select$2, - eventData: event_data$1, - moduleType: "trace", - name: "histogram", - basePlotModule: cartesian, - categories: ["bar-like", "cartesian", "svg", "bar", "histogram", "oriented", "errorBarsOK", "showLegend"], - meta: { - description: [ - "The sample data from which statistics are computed is set in `x`", - "for vertically spanning histograms and", - "in `y` for horizontally spanning histograms.", - "Binning options are set `xbins` and `ybins` respectively", - "if no aggregation data is provided." - ].join(" ") - } -}; -var histogram = histogram$2; -const histogram$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(histogram); -var baseAttrs$2 = attributes$O; -var domainAttrs$2 = domain.attributes; -var fontAttrs$1 = font_attributes; -var colorAttrs = attributes$N; -var hovertemplateAttrs$2 = template_attributes.hovertemplateAttrs; -var texttemplateAttrs$2 = template_attributes.texttemplateAttrs; -var extendFlat$4 = extend$5.extendFlat; -var pattern$2 = attributes$M.pattern; -var textFontAttrs = fontAttrs$1({ - editType: "plot", - arrayOk: true, - colorEditType: "plot", - description: "Sets the font used for `textinfo`." -}); -var attributes$8 = { - labels: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the sector labels.", - "If `labels` entries are duplicated, we sum associated `values`", - "or simply count occurrences if `values` is not provided.", - "For other array attributes (including color) we use the first", - "non-empty entry among all occurrences of the label." - ].join(" ") - }, - // equivalent of x0 and dx, if label is missing - label0: { - valType: "number", - dflt: 0, - editType: "calc", - description: [ - "Alternate to `labels`.", - "Builds a numeric set of labels.", - "Use with `dlabel`", - "where `label0` is the starting label and `dlabel` the step." - ].join(" ") - }, - dlabel: { - valType: "number", - dflt: 1, - editType: "calc", - description: "Sets the label step. See `label0` for more info." - }, - values: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the values of the sectors.", - "If omitted, we count occurrences of each label." - ].join(" ") - }, - marker: { - colors: { - valType: "data_array", - // TODO 'color_array' ? - editType: "calc", - description: [ - "Sets the color of each sector.", - "If not specified, the default trace color set is used", - "to pick the sector colors." - ].join(" ") - }, - line: { - color: { - valType: "color", - dflt: colorAttrs.defaultLine, - arrayOk: true, - editType: "style", - description: [ - "Sets the color of the line enclosing each sector." - ].join(" ") - }, - width: { - valType: "number", - min: 0, - dflt: 0, - arrayOk: true, - editType: "style", - description: [ - "Sets the width (in px) of the line enclosing each sector." - ].join(" ") - }, - editType: "calc" - }, - pattern: pattern$2, - editType: "calc" - }, - text: { - valType: "data_array", - editType: "plot", - description: [ - "Sets text elements associated with each sector.", - "If trace `textinfo` contains a *text* flag, these elements will be seen", - "on the chart.", - "If trace `hoverinfo` contains a *text* flag and *hovertext* is not set,", - "these elements will be seen in the hover labels." - ].join(" ") - }, - hovertext: { - valType: "string", - dflt: "", - arrayOk: true, - editType: "style", - description: [ - "Sets hover text elements associated with each sector.", - "If a single string, the same string appears for", - "all data points.", - "If an array of string, the items are mapped in order of", - "this trace's sectors.", - "To be seen, trace `hoverinfo` must contain a *text* flag." - ].join(" ") - }, - // 'see eg:' - // 'https://www.e-education.psu.edu/natureofgeoinfo/sites/www.e-education.psu.edu.natureofgeoinfo/files/image/hisp_pies.gif', - // '(this example involves a map too - may someday be a whole trace type', - // 'of its own. but the point is the size of the whole pie is important.)' - scalegroup: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "If there are multiple pie charts that should be sized according to", - "their totals, link them by providing a non-empty group id here", - "shared by every trace in the same group." - ].join(" ") - }, - // labels (legend is handled by plots.attributes.showlegend and layout.hiddenlabels) - textinfo: { - valType: "flaglist", - flags: ["label", "text", "value", "percent"], - extras: ["none"], - editType: "calc", - description: [ - "Determines which trace information appear on the graph." - ].join(" ") - }, - hoverinfo: extendFlat$4({}, baseAttrs$2.hoverinfo, { - flags: ["label", "text", "value", "percent", "name"] - }), - hovertemplate: hovertemplateAttrs$2({}, { - keys: ["label", "color", "value", "percent", "text"] - }), - texttemplate: texttemplateAttrs$2({ editType: "plot" }, { - keys: ["label", "color", "value", "percent", "text"] - }), - textposition: { - valType: "enumerated", - values: ["inside", "outside", "auto", "none"], - dflt: "auto", - arrayOk: true, - editType: "plot", - description: [ - "Specifies the location of the `textinfo`." - ].join(" ") - }, - textfont: extendFlat$4({}, textFontAttrs, { - description: "Sets the font used for `textinfo`." - }), - insidetextorientation: { - valType: "enumerated", - values: ["horizontal", "radial", "tangential", "auto"], - dflt: "auto", - editType: "plot", - description: [ - "Controls the orientation of the text inside chart sectors.", - "When set to *auto*, text may be oriented in any direction in order", - "to be as big as possible in the middle of a sector.", - "The *horizontal* option orients text to be parallel with the bottom", - "of the chart, and may make text smaller in order to achieve that goal.", - "The *radial* option orients text along the radius of the sector.", - "The *tangential* option orients text perpendicular to the radius of the sector." - ].join(" ") - }, - insidetextfont: extendFlat$4({}, textFontAttrs, { - description: "Sets the font used for `textinfo` lying inside the sector." - }), - outsidetextfont: extendFlat$4({}, textFontAttrs, { - description: "Sets the font used for `textinfo` lying outside the sector." - }), - automargin: { - valType: "boolean", - dflt: false, - editType: "plot", - description: [ - "Determines whether outside text labels can push the margins." - ].join(" ") - }, - title: { - text: { - valType: "string", - dflt: "", - editType: "plot", - description: [ - "Sets the title of the chart.", - "If it is empty, no title is displayed.", - "Note that before the existence of `title.text`, the title's", - "contents used to be defined as the `title` attribute itself.", - "This behavior has been deprecated." - ].join(" ") - }, - font: extendFlat$4({}, textFontAttrs, { - description: [ - "Sets the font used for `title`.", - "Note that the title's font used to be set", - "by the now deprecated `titlefont` attribute." - ].join(" ") - }), - position: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle center", - "bottom left", - "bottom center", - "bottom right" - ], - editType: "plot", - description: [ - "Specifies the location of the `title`.", - "Note that the title's position used to be set", - "by the now deprecated `titleposition` attribute." - ].join(" ") - }, - editType: "plot" - }, - // position and shape - domain: domainAttrs$2({ name: "pie", trace: true, editType: "calc" }), - hole: { - valType: "number", - min: 0, - max: 1, - dflt: 0, - editType: "calc", - description: [ - "Sets the fraction of the radius to cut out of the pie.", - "Use this to make a donut chart." - ].join(" ") - }, - // ordering and direction - sort: { - valType: "boolean", - dflt: true, - editType: "calc", - description: [ - "Determines whether or not the sectors are reordered", - "from largest to smallest." - ].join(" ") - }, - direction: { - /** - * there are two common conventions, both of which place the first - * (largest, if sorted) slice with its left edge at 12 o'clock but - * succeeding slices follow either cw or ccw from there. - * - * see http://visage.co/data-visualization-101-pie-charts/ - */ - valType: "enumerated", - values: ["clockwise", "counterclockwise"], - dflt: "counterclockwise", - editType: "calc", - description: [ - "Specifies the direction at which succeeding sectors follow", - "one another." - ].join(" ") - }, - rotation: { - valType: "angle", - dflt: 0, - editType: "calc", - description: [ - "Instead of the first slice starting at 12 o'clock,", - "rotate to some other angle." - ].join(" ") - }, - pull: { - valType: "number", - min: 0, - max: 1, - dflt: 0, - arrayOk: true, - editType: "calc", - description: [ - "Sets the fraction of larger radius to pull the sectors", - "out from the center. This can be a constant", - "to pull all slices apart from each other equally", - "or an array to highlight one or more slices." - ].join(" ") - }, - _deprecated: { - title: { - valType: "string", - dflt: "", - editType: "calc", - description: [ - "Deprecated in favor of `title.text`.", - "Note that value of `title` is no longer a simple", - "*string* but a set of sub-attributes." - ].join(" ") - }, - titlefont: extendFlat$4({}, textFontAttrs, { - description: "Deprecated in favor of `title.font`." - }), - titleposition: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle center", - "bottom left", - "bottom center", - "bottom right" - ], - editType: "calc", - description: "Deprecated in favor of `title.position`." - } - } -}; -var isNumeric$3 = fastIsnumeric; -var Lib$m = libExports; -var attributes$7 = attributes$8; -var handleDomainDefaults$1 = domain.defaults; -var handleText$1 = defaults$6.handleText; -var coercePattern = libExports.coercePattern; -function handleLabelsAndValues(labels, values) { - var hasLabels = Lib$m.isArrayOrTypedArray(labels); - var hasValues = Lib$m.isArrayOrTypedArray(values); - var len = Math.min( - hasLabels ? labels.length : Infinity, - hasValues ? values.length : Infinity - ); - if (!isFinite(len)) len = 0; - if (len && hasValues) { - var hasPositive; - for (var i = 0; i < len; i++) { - var v = values[i]; - if (isNumeric$3(v) && v > 0) { - hasPositive = true; - break; - } - } - if (!hasPositive) len = 0; - } - return { - hasLabels, - hasValues, - len - }; -} -function handleMarkerDefaults$2(traceIn, traceOut, layout, coerce2, isPie) { - var lineWidth = coerce2("marker.line.width"); - if (lineWidth) { - coerce2( - "marker.line.color", - isPie ? void 0 : layout.paper_bgcolor - // case of funnelarea, sunburst, icicle, treemap - ); - } - var markerColors = coerce2("marker.colors"); - coercePattern(coerce2, "marker.pattern", markerColors); - if (traceIn.marker && !traceOut.marker.pattern.fgcolor) traceOut.marker.pattern.fgcolor = traceIn.marker.colors; - if (!traceOut.marker.pattern.bgcolor) traceOut.marker.pattern.bgcolor = layout.paper_bgcolor; -} -function supplyDefaults4(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$m.coerce(traceIn, traceOut, attributes$7, attr, dflt); - } - var labels = coerce2("labels"); - var values = coerce2("values"); - var res = handleLabelsAndValues(labels, values); - var len = res.len; - traceOut._hasLabels = res.hasLabels; - traceOut._hasValues = res.hasValues; - if (!traceOut._hasLabels && traceOut._hasValues) { - coerce2("label0"); - coerce2("dlabel"); - } - if (!len) { - traceOut.visible = false; - return; - } - traceOut._length = len; - handleMarkerDefaults$2(traceIn, traceOut, layout, coerce2, true); - coerce2("scalegroup"); - var textData = coerce2("text"); - var textTemplate = coerce2("texttemplate"); - var textInfo; - if (!textTemplate) textInfo = coerce2("textinfo", Lib$m.isArrayOrTypedArray(textData) ? "text+percent" : "percent"); - coerce2("hovertext"); - coerce2("hovertemplate"); - if (textTemplate || textInfo && textInfo !== "none") { - var textposition = coerce2("textposition"); - handleText$1(traceIn, traceOut, layout, coerce2, textposition, { - moduleHasSelected: false, - moduleHasUnselected: false, - moduleHasConstrain: false, - moduleHasCliponaxis: false, - moduleHasTextangle: false, - moduleHasInsideanchor: false - }); - var hasBoth = Array.isArray(textposition) || textposition === "auto"; - var hasOutside = hasBoth || textposition === "outside"; - if (hasOutside) { - coerce2("automargin"); - } - if (textposition === "inside" || textposition === "auto" || Array.isArray(textposition)) { - coerce2("insidetextorientation"); - } - } else if (textInfo === "none") { - coerce2("textposition", "none"); - } - handleDomainDefaults$1(traceOut, layout, coerce2); - var hole = coerce2("hole"); - var title = coerce2("title.text"); - if (title) { - var titlePosition = coerce2("title.position", hole ? "middle center" : "top center"); - if (!hole && titlePosition === "middle center") traceOut.title.position = "top center"; - Lib$m.coerceFont(coerce2, "title.font", layout.font); - } - coerce2("sort"); - coerce2("direction"); - coerce2("rotation"); - coerce2("pull"); -} -var defaults$4 = { - handleMarkerDefaults: handleMarkerDefaults$2, - supplyDefaults: supplyDefaults4 -}; -var layout_attributes$1 = { - hiddenlabels: { - valType: "data_array", - editType: "calc", - description: [ - "hiddenlabels is the funnelarea & pie chart analog of", - "visible:'legendonly'", - "but it can contain many labels, and can simultaneously", - "hide slices from several pies/funnelarea charts" - ].join(" ") - }, - piecolorway: { - valType: "colorlist", - editType: "calc", - description: [ - "Sets the default pie slice colors. Defaults to the main", - "`colorway` used for trace colors. If you specify a new", - "list here it can still be extended with lighter and darker", - "colors, see `extendpiecolors`." - ].join(" ") - }, - extendpiecolors: { - valType: "boolean", - dflt: true, - editType: "calc", - description: [ - "If `true`, the pie slice colors (whether given by `piecolorway` or", - "inherited from `colorway`) will be extended to three times its", - "original length by first repeating every color 20% lighter then", - "each color 20% darker. This is intended to reduce the likelihood", - "of reusing the same color when you have many slices, but you can", - "set `false` to disable.", - "Colors provided in the trace, using `marker.colors`, are never", - "extended." - ].join(" ") - } -}; -var Lib$l = libExports; -var layoutAttributes$1 = layout_attributes$1; -var layout_defaults$1 = function supplyLayoutDefaults8(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$l.coerce(layoutIn, layoutOut, layoutAttributes$1, attr, dflt); - } - coerce2("hiddenlabels"); - coerce2("piecolorway", layoutOut.colorway); - coerce2("extendpiecolors"); -}; -var isNumeric$2 = fastIsnumeric; -var tinycolor = tinycolorExports; -var Color$a = colorExports; -var extendedColorWayList = {}; -function calc$5(gd, trace) { - var cd = []; - var fullLayout = gd._fullLayout; - var hiddenLabels = fullLayout.hiddenlabels || []; - var labels = trace.labels; - var colors = trace.marker.colors || []; - var vals = trace.values; - var len = trace._length; - var hasValues = trace._hasValues && len; - var i, pt; - if (trace.dlabel) { - labels = new Array(len); - for (i = 0; i < len; i++) { - labels[i] = String(trace.label0 + i * trace.dlabel); - } - } - var allThisTraceLabels = {}; - var pullColor = makePullColorFn(fullLayout["_" + trace.type + "colormap"]); - var vTotal = 0; - var isAggregated = false; - for (i = 0; i < len; i++) { - var v, label, hidden; - if (hasValues) { - v = vals[i]; - if (!isNumeric$2(v)) continue; - v = +v; - } else v = 1; - label = labels[i]; - if (label === void 0 || label === "") label = i; - label = String(label); - var thisLabelIndex = allThisTraceLabels[label]; - if (thisLabelIndex === void 0) { - allThisTraceLabels[label] = cd.length; - hidden = hiddenLabels.indexOf(label) !== -1; - if (!hidden) vTotal += v; - cd.push({ - v, - label, - color: pullColor(colors[i], label), - i, - pts: [i], - hidden - }); - } else { - isAggregated = true; - pt = cd[thisLabelIndex]; - pt.v += v; - pt.pts.push(i); - if (!pt.hidden) vTotal += v; - if (pt.color === false && colors[i]) { - pt.color = pullColor(colors[i], label); - } - } - } - cd = cd.filter(function(elem) { - return elem.v >= 0; - }); - var shouldSort = trace.type === "funnelarea" ? isAggregated : trace.sort; - if (shouldSort) cd.sort(function(a, b) { - return b.v - a.v; - }); - if (cd[0]) cd[0].vTotal = vTotal; - return cd; -} -function makePullColorFn(colorMap) { - return function pullColor(color2, id) { - if (!color2) return false; - color2 = tinycolor(color2); - if (!color2.isValid()) return false; - color2 = Color$a.addOpacity(color2, color2.getAlpha()); - if (!colorMap[id]) colorMap[id] = color2; - return color2; - }; -} -function crossTraceCalc2(gd, plotinfo) { - var desiredType = (plotinfo || {}).type; - if (!desiredType) desiredType = "pie"; - var fullLayout = gd._fullLayout; - var calcdata = gd.calcdata; - var colorWay = fullLayout[desiredType + "colorway"]; - var colorMap = fullLayout["_" + desiredType + "colormap"]; - if (fullLayout["extend" + desiredType + "colors"]) { - colorWay = generateExtendedColors(colorWay, extendedColorWayList); - } - var dfltColorCount = 0; - for (var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var traceType = cd[0].trace.type; - if (traceType !== desiredType) continue; - for (var j = 0; j < cd.length; j++) { - var pt = cd[j]; - if (pt.color === false) { - if (colorMap[pt.label]) { - pt.color = colorMap[pt.label]; - } else { - colorMap[pt.label] = pt.color = colorWay[dfltColorCount % colorWay.length]; - dfltColorCount++; - } - } - } - } -} -function generateExtendedColors(colorList, extendedColorWays) { - var i; - var colorString = JSON.stringify(colorList); - var colors = extendedColorWays[colorString]; - if (!colors) { - colors = colorList.slice(); - for (i = 0; i < colorList.length; i++) { - colors.push(tinycolor(colorList[i]).lighten(20).toHexString()); - } - for (i = 0; i < colorList.length; i++) { - colors.push(tinycolor(colorList[i]).darken(20).toHexString()); - } - extendedColorWays[colorString] = colors; - } - return colors; -} -var calc_1$1 = { - calc: calc$5, - crossTraceCalc: crossTraceCalc2, - makePullColorFn, - generateExtendedColors -}; -var appendArrayMultiPointValues = helpers$J.appendArrayMultiPointValues; -var event_data = function eventData3(pt, trace) { - var out = { - curveNumber: trace.index, - pointNumbers: pt.pts, - data: trace._input, - fullData: trace, - label: pt.label, - color: pt.color, - value: pt.v, - percent: pt.percent, - text: pt.text, - bbox: pt.bbox, - // pt.v (and pt.i below) for backward compatibility - v: pt.v - }; - if (pt.pts.length === 1) out.pointNumber = out.i = pt.pts[0]; - appendArrayMultiPointValues(out, trace, pt.pts); - if (trace.type === "funnelarea") { - delete out.v; - delete out.i; - } - return out; -}; -var d3$9 = d3Exports; -var Plots = plotsExports; -var Fx$2 = fx$1; -var Color$9 = colorExports; -var Drawing$5 = drawingExports; -var Lib$k = libExports; -var strScale = Lib$k.strScale; -var strTranslate = Lib$k.strTranslate; -var svgTextUtils$2 = svg_text_utils; -var uniformText$2 = uniform_text; -var recordMinTextSize$1 = uniformText$2.recordMinTextSize; -var clearMinTextSize$1 = uniformText$2.clearMinTextSize; -var TEXTPAD$2 = constants$f.TEXTPAD; -var helpers$a = helpers$F; -var eventData4 = event_data; -var isValidTextValue = libExports.isValidTextValue; -function plot$4(gd, cdModule) { - var isStatic = gd._context.staticPlot; - var fullLayout = gd._fullLayout; - var gs = fullLayout._size; - clearMinTextSize$1("pie", fullLayout); - prerenderTitles(cdModule, gd); - layoutAreas(cdModule, gs); - var plotGroups = Lib$k.makeTraceGroups(fullLayout._pielayer, cdModule, "trace").each(function(cd) { - var plotGroup = d3$9.select(this); - var cd0 = cd[0]; - var trace = cd0.trace; - setCoords(cd); - plotGroup.attr("stroke-linejoin", "round"); - plotGroup.each(function() { - var slices = d3$9.select(this).selectAll("g.slice").data(cd); - slices.enter().append("g").classed("slice", true); - slices.exit().remove(); - var quadrants = [ - [[], []], - // y<0: x<0, x>=0 - [[], []] - // y>=0: x<0, x>=0 - ]; - var hasOutsideText = false; - slices.each(function(pt, i) { - if (pt.hidden) { - d3$9.select(this).selectAll("path,g").remove(); - return; - } - pt.pointNumber = pt.i; - pt.curveNumber = trace.index; - quadrants[pt.pxmid[1] < 0 ? 0 : 1][pt.pxmid[0] < 0 ? 0 : 1].push(pt); - var cx = cd0.cx; - var cy = cd0.cy; - var sliceTop = d3$9.select(this); - var slicePath = sliceTop.selectAll("path.surface").data([pt]); - slicePath.enter().append("path").classed("surface", true).style({ "pointer-events": isStatic ? "none" : "all" }); - sliceTop.call(attachFxHandlers$2, gd, cd); - if (trace.pull) { - var pull = +helpers$a.castOption(trace.pull, pt.pts) || 0; - if (pull > 0) { - cx += pull * pt.pxmid[0]; - cy += pull * pt.pxmid[1]; - } - } - pt.cxFinal = cx; - pt.cyFinal = cy; - function arc2(start, finish, cw, scale2) { - var dx = scale2 * (finish[0] - start[0]); - var dy = scale2 * (finish[1] - start[1]); - return "a" + scale2 * cd0.r + "," + scale2 * cd0.r + " 0 " + pt.largeArc + (cw ? " 1 " : " 0 ") + dx + "," + dy; - } - var hole = trace.hole; - if (pt.v === cd0.vTotal) { - var outerCircle = "M" + (cx + pt.px0[0]) + "," + (cy + pt.px0[1]) + arc2(pt.px0, pt.pxmid, true, 1) + arc2(pt.pxmid, pt.px0, true, 1) + "Z"; - if (hole) { - slicePath.attr( - "d", - "M" + (cx + hole * pt.px0[0]) + "," + (cy + hole * pt.px0[1]) + arc2(pt.px0, pt.pxmid, false, hole) + arc2(pt.pxmid, pt.px0, false, hole) + "Z" + outerCircle - ); - } else slicePath.attr("d", outerCircle); - } else { - var outerArc = arc2(pt.px0, pt.px1, true, 1); - if (hole) { - var rim = 1 - hole; - slicePath.attr( - "d", - "M" + (cx + hole * pt.px1[0]) + "," + (cy + hole * pt.px1[1]) + arc2(pt.px1, pt.px0, false, hole) + "l" + rim * pt.px0[0] + "," + rim * pt.px0[1] + outerArc + "Z" - ); - } else { - slicePath.attr( - "d", - "M" + cx + "," + cy + "l" + pt.px0[0] + "," + pt.px0[1] + outerArc + "Z" - ); - } - } - formatSliceLabel$1(gd, pt, cd0); - var textPosition = helpers$a.castOption(trace.textposition, pt.pts); - var sliceTextGroup = sliceTop.selectAll("g.slicetext").data(pt.text && textPosition !== "none" ? [0] : []); - sliceTextGroup.enter().append("g").classed("slicetext", true); - sliceTextGroup.exit().remove(); - sliceTextGroup.each(function() { - var sliceText = Lib$k.ensureSingle(d3$9.select(this), "text", "", function(s) { - s.attr("data-notex", 1); - }); - var font2 = Lib$k.ensureUniformFontSize( - gd, - textPosition === "outside" ? determineOutsideTextFont(trace, pt, fullLayout.font) : determineInsideTextFont(trace, pt, fullLayout.font) - ); - sliceText.text(pt.text).attr({ - class: "slicetext", - transform: "", - "text-anchor": "middle" - }).call(Drawing$5.font, font2).call(svgTextUtils$2.convertToTspans, gd); - var textBB = Drawing$5.bBox(sliceText.node()); - var transform; - if (textPosition === "outside") { - transform = transformOutsideText(textBB, pt); - } else { - transform = transformInsideText(textBB, pt, cd0); - if (textPosition === "auto" && transform.scale < 1) { - var newFont = Lib$k.ensureUniformFontSize(gd, trace.outsidetextfont); - sliceText.call(Drawing$5.font, newFont); - textBB = Drawing$5.bBox(sliceText.node()); - transform = transformOutsideText(textBB, pt); - } - } - var textPosAngle = transform.textPosAngle; - var textXY = textPosAngle === void 0 ? pt.pxmid : getCoords(cd0.r, textPosAngle); - transform.targetX = cx + textXY[0] * transform.rCenter + (transform.x || 0); - transform.targetY = cy + textXY[1] * transform.rCenter + (transform.y || 0); - computeTransform(transform, textBB); - if (transform.outside) { - var targetY = transform.targetY; - pt.yLabelMin = targetY - textBB.height / 2; - pt.yLabelMid = targetY; - pt.yLabelMax = targetY + textBB.height / 2; - pt.labelExtraX = 0; - pt.labelExtraY = 0; - hasOutsideText = true; - } - transform.fontSize = font2.size; - recordMinTextSize$1(trace.type, transform, fullLayout); - cd[i].transform = transform; - Lib$k.setTransormAndDisplay(sliceText, transform); - }); - }); - var titleTextGroup = d3$9.select(this).selectAll("g.titletext").data(trace.title.text ? [0] : []); - titleTextGroup.enter().append("g").classed("titletext", true); - titleTextGroup.exit().remove(); - titleTextGroup.each(function() { - var titleText = Lib$k.ensureSingle(d3$9.select(this), "text", "", function(s) { - s.attr("data-notex", 1); - }); - var txt = trace.title.text; - if (trace._meta) { - txt = Lib$k.templateString(txt, trace._meta); - } - titleText.text(txt).attr({ - class: "titletext", - transform: "", - "text-anchor": "middle" - }).call(Drawing$5.font, trace.title.font).call(svgTextUtils$2.convertToTspans, gd); - var transform; - if (trace.title.position === "middle center") { - transform = positionTitleInside(cd0); - } else { - transform = positionTitleOutside(cd0, gs); - } - titleText.attr( - "transform", - strTranslate(transform.x, transform.y) + strScale(Math.min(1, transform.scale)) + strTranslate(transform.tx, transform.ty) - ); - }); - if (hasOutsideText) scootLabels(quadrants, trace); - plotTextLines(slices, trace); - if (hasOutsideText && trace.automargin) { - var traceBbox = Drawing$5.bBox(plotGroup.node()); - var domain2 = trace.domain; - var vpw = gs.w * (domain2.x[1] - domain2.x[0]); - var vph = gs.h * (domain2.y[1] - domain2.y[0]); - var xgap = (0.5 * vpw - cd0.r) / gs.w; - var ygap = (0.5 * vph - cd0.r) / gs.h; - Plots.autoMargin(gd, "pie." + trace.uid + ".automargin", { - xl: domain2.x[0] - xgap, - xr: domain2.x[1] + xgap, - yb: domain2.y[0] - ygap, - yt: domain2.y[1] + ygap, - l: Math.max(cd0.cx - cd0.r - traceBbox.left, 0), - r: Math.max(traceBbox.right - (cd0.cx + cd0.r), 0), - b: Math.max(traceBbox.bottom - (cd0.cy + cd0.r), 0), - t: Math.max(cd0.cy - cd0.r - traceBbox.top, 0), - pad: 5 - }); - } - }); - }); - setTimeout(function() { - plotGroups.selectAll("tspan").each(function() { - var s = d3$9.select(this); - if (s.attr("dy")) s.attr("dy", s.attr("dy")); - }); - }, 0); -} -function plotTextLines(slices, trace) { - slices.each(function(pt) { - var sliceTop = d3$9.select(this); - if (!pt.labelExtraX && !pt.labelExtraY) { - sliceTop.select("path.textline").remove(); - return; - } - var sliceText = sliceTop.select("g.slicetext text"); - pt.transform.targetX += pt.labelExtraX; - pt.transform.targetY += pt.labelExtraY; - Lib$k.setTransormAndDisplay(sliceText, pt.transform); - var lineStartX = pt.cxFinal + pt.pxmid[0]; - var lineStartY = pt.cyFinal + pt.pxmid[1]; - var textLinePath = "M" + lineStartX + "," + lineStartY; - var finalX = (pt.yLabelMax - pt.yLabelMin) * (pt.pxmid[0] < 0 ? -1 : 1) / 4; - if (pt.labelExtraX) { - var yFromX = pt.labelExtraX * pt.pxmid[1] / pt.pxmid[0]; - var yNet = pt.yLabelMid + pt.labelExtraY - (pt.cyFinal + pt.pxmid[1]); - if (Math.abs(yFromX) > Math.abs(yNet)) { - textLinePath += "l" + yNet * pt.pxmid[0] / pt.pxmid[1] + "," + yNet + "H" + (lineStartX + pt.labelExtraX + finalX); - } else { - textLinePath += "l" + pt.labelExtraX + "," + yFromX + "v" + (yNet - yFromX) + "h" + finalX; - } - } else { - textLinePath += "V" + (pt.yLabelMid + pt.labelExtraY) + "h" + finalX; - } - Lib$k.ensureSingle(sliceTop, "path", "textline").call(Color$9.stroke, trace.outsidetextfont.color).attr({ - "stroke-width": Math.min(2, trace.outsidetextfont.size / 8), - d: textLinePath, - fill: "none" - }); - }); -} -function attachFxHandlers$2(sliceTop, gd, cd) { - var cd0 = cd[0]; - var cx = cd0.cx; - var cy = cd0.cy; - var trace = cd0.trace; - var isFunnelArea = trace.type === "funnelarea"; - if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false; - if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false; - sliceTop.on("mouseover", function(pt) { - var fullLayout2 = gd._fullLayout; - var trace2 = gd._fullData[trace.index]; - if (gd._dragging || fullLayout2.hovermode === false) return; - var hoverinfo = trace2.hoverinfo; - if (Array.isArray(hoverinfo)) { - hoverinfo = Fx$2.castHoverinfo({ - hoverinfo: [helpers$a.castOption(hoverinfo, pt.pts)], - _module: trace._module - }, fullLayout2, 0); - } - if (hoverinfo === "all") hoverinfo = "label+text+value+percent+name"; - if (trace2.hovertemplate || hoverinfo !== "none" && hoverinfo !== "skip" && hoverinfo) { - var rInscribed = pt.rInscribed || 0; - var hoverCenterX = cx + pt.pxmid[0] * (1 - rInscribed); - var hoverCenterY = cy + pt.pxmid[1] * (1 - rInscribed); - var separators = fullLayout2.separators; - var text = []; - if (hoverinfo && hoverinfo.indexOf("label") !== -1) text.push(pt.label); - pt.text = helpers$a.castOption(trace2.hovertext || trace2.text, pt.pts); - if (hoverinfo && hoverinfo.indexOf("text") !== -1) { - var tx = pt.text; - if (Lib$k.isValidTextValue(tx)) text.push(tx); - } - pt.value = pt.v; - pt.valueLabel = helpers$a.formatPieValue(pt.v, separators); - if (hoverinfo && hoverinfo.indexOf("value") !== -1) text.push(pt.valueLabel); - pt.percent = pt.v / cd0.vTotal; - pt.percentLabel = helpers$a.formatPiePercent(pt.percent, separators); - if (hoverinfo && hoverinfo.indexOf("percent") !== -1) text.push(pt.percentLabel); - var hoverLabel = trace2.hoverlabel; - var hoverFont = hoverLabel.font; - var bbox = []; - Fx$2.loneHover({ - trace, - x0: hoverCenterX - rInscribed * cd0.r, - x1: hoverCenterX + rInscribed * cd0.r, - y: hoverCenterY, - _x0: isFunnelArea ? cx + pt.TL[0] : hoverCenterX - rInscribed * cd0.r, - _x1: isFunnelArea ? cx + pt.TR[0] : hoverCenterX + rInscribed * cd0.r, - _y0: isFunnelArea ? cy + pt.TL[1] : hoverCenterY - rInscribed * cd0.r, - _y1: isFunnelArea ? cy + pt.BL[1] : hoverCenterY + rInscribed * cd0.r, - text: text.join("
"), - name: trace2.hovertemplate || hoverinfo.indexOf("name") !== -1 ? trace2.name : void 0, - idealAlign: pt.pxmid[0] < 0 ? "left" : "right", - color: helpers$a.castOption(hoverLabel.bgcolor, pt.pts) || pt.color, - borderColor: helpers$a.castOption(hoverLabel.bordercolor, pt.pts), - fontFamily: helpers$a.castOption(hoverFont.family, pt.pts), - fontSize: helpers$a.castOption(hoverFont.size, pt.pts), - fontColor: helpers$a.castOption(hoverFont.color, pt.pts), - nameLength: helpers$a.castOption(hoverLabel.namelength, pt.pts), - textAlign: helpers$a.castOption(hoverLabel.align, pt.pts), - hovertemplate: helpers$a.castOption(trace2.hovertemplate, pt.pts), - hovertemplateLabels: pt, - eventData: [eventData4(pt, trace2)] - }, { - container: fullLayout2._hoverlayer.node(), - outerContainer: fullLayout2._paper.node(), - gd, - inOut_bbox: bbox - }); - pt.bbox = bbox[0]; - trace._hasHoverLabel = true; - } - trace._hasHoverEvent = true; - gd.emit("plotly_hover", { - points: [eventData4(pt, trace2)], - event: d3$9.event - }); - }); - sliceTop.on("mouseout", function(evt) { - var fullLayout2 = gd._fullLayout; - var trace2 = gd._fullData[trace.index]; - var pt = d3$9.select(this).datum(); - if (trace._hasHoverEvent) { - evt.originalEvent = d3$9.event; - gd.emit("plotly_unhover", { - points: [eventData4(pt, trace2)], - event: d3$9.event - }); - trace._hasHoverEvent = false; - } - if (trace._hasHoverLabel) { - Fx$2.loneUnhover(fullLayout2._hoverlayer.node()); - trace._hasHoverLabel = false; - } - }); - sliceTop.on("click", function(pt) { - var fullLayout2 = gd._fullLayout; - var trace2 = gd._fullData[trace.index]; - if (gd._dragging || fullLayout2.hovermode === false) return; - gd._hoverdata = [eventData4(pt, trace2)]; - Fx$2.click(gd, d3$9.event); - }); -} -function determineOutsideTextFont(trace, pt, layoutFont) { - var color2 = helpers$a.castOption(trace.outsidetextfont.color, pt.pts) || helpers$a.castOption(trace.textfont.color, pt.pts) || layoutFont.color; - var family = helpers$a.castOption(trace.outsidetextfont.family, pt.pts) || helpers$a.castOption(trace.textfont.family, pt.pts) || layoutFont.family; - var size = helpers$a.castOption(trace.outsidetextfont.size, pt.pts) || helpers$a.castOption(trace.textfont.size, pt.pts) || layoutFont.size; - var weight = helpers$a.castOption(trace.outsidetextfont.weight, pt.pts) || helpers$a.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight; - var style5 = helpers$a.castOption(trace.outsidetextfont.style, pt.pts) || helpers$a.castOption(trace.textfont.style, pt.pts) || layoutFont.style; - var variant = helpers$a.castOption(trace.outsidetextfont.variant, pt.pts) || helpers$a.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant; - var textcase = helpers$a.castOption(trace.outsidetextfont.textcase, pt.pts) || helpers$a.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase; - var lineposition = helpers$a.castOption(trace.outsidetextfont.lineposition, pt.pts) || helpers$a.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition; - var shadow = helpers$a.castOption(trace.outsidetextfont.shadow, pt.pts) || helpers$a.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow; - return { - color: color2, - family, - size, - weight, - style: style5, - variant, - textcase, - lineposition, - shadow - }; -} -function determineInsideTextFont(trace, pt, layoutFont) { - var customColor = helpers$a.castOption(trace.insidetextfont.color, pt.pts); - if (!customColor && trace._input.textfont) { - customColor = helpers$a.castOption(trace._input.textfont.color, pt.pts); - } - var family = helpers$a.castOption(trace.insidetextfont.family, pt.pts) || helpers$a.castOption(trace.textfont.family, pt.pts) || layoutFont.family; - var size = helpers$a.castOption(trace.insidetextfont.size, pt.pts) || helpers$a.castOption(trace.textfont.size, pt.pts) || layoutFont.size; - var weight = helpers$a.castOption(trace.insidetextfont.weight, pt.pts) || helpers$a.castOption(trace.textfont.weight, pt.pts) || layoutFont.weight; - var style5 = helpers$a.castOption(trace.insidetextfont.style, pt.pts) || helpers$a.castOption(trace.textfont.style, pt.pts) || layoutFont.style; - var variant = helpers$a.castOption(trace.insidetextfont.variant, pt.pts) || helpers$a.castOption(trace.textfont.variant, pt.pts) || layoutFont.variant; - var textcase = helpers$a.castOption(trace.insidetextfont.textcase, pt.pts) || helpers$a.castOption(trace.textfont.textcase, pt.pts) || layoutFont.textcase; - var lineposition = helpers$a.castOption(trace.insidetextfont.lineposition, pt.pts) || helpers$a.castOption(trace.textfont.lineposition, pt.pts) || layoutFont.lineposition; - var shadow = helpers$a.castOption(trace.insidetextfont.shadow, pt.pts) || helpers$a.castOption(trace.textfont.shadow, pt.pts) || layoutFont.shadow; - return { - color: customColor || Color$9.contrast(pt.color), - family, - size, - weight, - style: style5, - variant, - textcase, - lineposition, - shadow - }; -} -function prerenderTitles(cdModule, gd) { - var cd0, trace; - for (var i = 0; i < cdModule.length; i++) { - cd0 = cdModule[i][0]; - trace = cd0.trace; - if (trace.title.text) { - var txt = trace.title.text; - if (trace._meta) { - txt = Lib$k.templateString(txt, trace._meta); - } - var dummyTitle = Drawing$5.tester.append("text").attr("data-notex", 1).text(txt).call(Drawing$5.font, trace.title.font).call(svgTextUtils$2.convertToTspans, gd); - var bBox = Drawing$5.bBox(dummyTitle.node(), true); - cd0.titleBox = { - width: bBox.width, - height: bBox.height - }; - dummyTitle.remove(); - } - } -} -function transformInsideText(textBB, pt, cd0) { - var r = cd0.r || pt.rpx1; - var rInscribed = pt.rInscribed; - var isEmpty = pt.startangle === pt.stopangle; - if (isEmpty) { - return { - rCenter: 1 - rInscribed, - scale: 0, - rotate: 0, - textPosAngle: 0 - }; - } - var ring = pt.ring; - var isCircle = ring === 1 && Math.abs(pt.startangle - pt.stopangle) === Math.PI * 2; - var halfAngle = pt.halfangle; - var midAngle = pt.midangle; - var orientation = cd0.trace.insidetextorientation; - var isHorizontal = orientation === "horizontal"; - var isTangential = orientation === "tangential"; - var isRadial = orientation === "radial"; - var isAuto = orientation === "auto"; - var allTransforms = []; - var newT; - if (!isAuto) { - var considerCrossing = function(angle, key) { - if (isCrossing(pt, angle)) { - var dStart = Math.abs(angle - pt.startangle); - var dStop = Math.abs(angle - pt.stopangle); - var closestEdge = dStart < dStop ? dStart : dStop; - if (key === "tan") { - newT = calcTanTransform(textBB, r, ring, closestEdge, 0); - } else { - newT = calcRadTransform(textBB, r, ring, closestEdge, Math.PI / 2); - } - newT.textPosAngle = angle; - allTransforms.push(newT); - } - }; - var i; - if (isHorizontal || isTangential) { - for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * i, "tan"); - for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1), "tan"); - } - if (isHorizontal || isRadial) { - for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 1.5), "rad"); - for (i = 4; i >= -4; i -= 2) considerCrossing(Math.PI * (i + 0.5), "rad"); - } - } - if (isCircle || isAuto || isHorizontal) { - var textDiameter = Math.sqrt(textBB.width * textBB.width + textBB.height * textBB.height); - newT = { - scale: rInscribed * r * 2 / textDiameter, - // and the center position and rotation in this case - rCenter: 1 - rInscribed, - rotate: 0 - }; - newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; - if (newT.scale >= 1) return newT; - allTransforms.push(newT); - } - if (isAuto || isRadial) { - newT = calcRadTransform(textBB, r, ring, halfAngle, midAngle); - newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; - allTransforms.push(newT); - } - if (isAuto || isTangential) { - newT = calcTanTransform(textBB, r, ring, halfAngle, midAngle); - newT.textPosAngle = (pt.startangle + pt.stopangle) / 2; - allTransforms.push(newT); - } - var id = 0; - var maxScale = 0; - for (var k = 0; k < allTransforms.length; k++) { - var s = allTransforms[k].scale; - if (maxScale < s) { - maxScale = s; - id = k; - } - if (!isAuto && maxScale >= 1) { - break; - } - } - return allTransforms[id]; -} -function isCrossing(pt, angle) { - var start = pt.startangle; - var stop = pt.stopangle; - return start > angle && angle > stop || start < angle && angle < stop; -} -function calcRadTransform(textBB, r, ring, halfAngle, midAngle) { - r = Math.max(0, r - 2 * TEXTPAD$2); - var a = textBB.width / textBB.height; - var s = calcMaxHalfSize(a, halfAngle, r, ring); - return { - scale: s * 2 / textBB.height, - rCenter: calcRCenter(a, s / r), - rotate: calcRotate(midAngle) - }; -} -function calcTanTransform(textBB, r, ring, halfAngle, midAngle) { - r = Math.max(0, r - 2 * TEXTPAD$2); - var a = textBB.height / textBB.width; - var s = calcMaxHalfSize(a, halfAngle, r, ring); - return { - scale: s * 2 / textBB.width, - rCenter: calcRCenter(a, s / r), - rotate: calcRotate(midAngle + Math.PI / 2) - }; -} -function calcRCenter(a, b) { - return Math.cos(b) - a * b; -} -function calcRotate(t) { - return (180 / Math.PI * t + 720) % 180 - 90; -} -function calcMaxHalfSize(a, halfAngle, r, ring) { - var q = a + 1 / (2 * Math.tan(halfAngle)); - return r * Math.min( - 1 / (Math.sqrt(q * q + 0.5) + q), - ring / (Math.sqrt(a * a + ring / 2) + a) - ); -} -function getInscribedRadiusFraction(pt, cd0) { - if (pt.v === cd0.vTotal && !cd0.trace.hole) return 1; - return Math.min(1 / (1 + 1 / Math.sin(pt.halfangle)), pt.ring / 2); -} -function transformOutsideText(textBB, pt) { - var x = pt.pxmid[0]; - var y = pt.pxmid[1]; - var dx = textBB.width / 2; - var dy = textBB.height / 2; - if (x < 0) dx *= -1; - if (y < 0) dy *= -1; - return { - scale: 1, - rCenter: 1, - rotate: 0, - x: dx + Math.abs(dy) * (dx > 0 ? 1 : -1) / 2, - y: dy / (1 + x * x / (y * y)), - outside: true - }; -} -function positionTitleInside(cd0) { - var textDiameter = Math.sqrt(cd0.titleBox.width * cd0.titleBox.width + cd0.titleBox.height * cd0.titleBox.height); - return { - x: cd0.cx, - y: cd0.cy, - scale: cd0.trace.hole * cd0.r * 2 / textDiameter, - tx: 0, - ty: -cd0.titleBox.height / 2 + cd0.trace.title.font.size - }; -} -function positionTitleOutside(cd0, plotSize) { - var scaleX = 1; - var scaleY = 1; - var maxPull; - var trace = cd0.trace; - var topMiddle = { - x: cd0.cx, - y: cd0.cy - }; - var translate2 = { - tx: 0, - ty: 0 - }; - translate2.ty += trace.title.font.size; - maxPull = getMaxPull(trace); - if (trace.title.position.indexOf("top") !== -1) { - topMiddle.y -= (1 + maxPull) * cd0.r; - translate2.ty -= cd0.titleBox.height; - } else if (trace.title.position.indexOf("bottom") !== -1) { - topMiddle.y += (1 + maxPull) * cd0.r; - } - var rx = applyAspectRatio(cd0.r, cd0.trace.aspectratio); - var maxWidth = plotSize.w * (trace.domain.x[1] - trace.domain.x[0]) / 2; - if (trace.title.position.indexOf("left") !== -1) { - maxWidth = maxWidth + rx; - topMiddle.x -= (1 + maxPull) * rx; - translate2.tx += cd0.titleBox.width / 2; - } else if (trace.title.position.indexOf("center") !== -1) { - maxWidth *= 2; - } else if (trace.title.position.indexOf("right") !== -1) { - maxWidth = maxWidth + rx; - topMiddle.x += (1 + maxPull) * rx; - translate2.tx -= cd0.titleBox.width / 2; - } - scaleX = maxWidth / cd0.titleBox.width; - scaleY = getTitleSpace(cd0, plotSize) / cd0.titleBox.height; - return { - x: topMiddle.x, - y: topMiddle.y, - scale: Math.min(scaleX, scaleY), - tx: translate2.tx, - ty: translate2.ty - }; -} -function applyAspectRatio(x, aspectratio) { - return x / (aspectratio === void 0 ? 1 : aspectratio); -} -function getTitleSpace(cd0, plotSize) { - var trace = cd0.trace; - var pieBoxHeight = plotSize.h * (trace.domain.y[1] - trace.domain.y[0]); - return Math.min(cd0.titleBox.height, pieBoxHeight / 2); -} -function getMaxPull(trace) { - var maxPull = trace.pull; - if (!maxPull) return 0; - var j; - if (Lib$k.isArrayOrTypedArray(maxPull)) { - maxPull = 0; - for (j = 0; j < trace.pull.length; j++) { - if (trace.pull[j] > maxPull) maxPull = trace.pull[j]; - } - } - return maxPull; -} -function scootLabels(quadrants, trace) { - var xHalf, yHalf, equatorFirst, farthestX, farthestY, xDiffSign, yDiffSign, thisQuad, oppositeQuad, wholeSide, i, thisQuadOutside, firstOppositeOutsidePt; - function topFirst(a, b) { - return a.pxmid[1] - b.pxmid[1]; - } - function bottomFirst(a, b) { - return b.pxmid[1] - a.pxmid[1]; - } - function scootOneLabel(thisPt, prevPt2) { - if (!prevPt2) prevPt2 = {}; - var prevOuterY = prevPt2.labelExtraY + (yHalf ? prevPt2.yLabelMax : prevPt2.yLabelMin); - var thisInnerY = yHalf ? thisPt.yLabelMin : thisPt.yLabelMax; - var thisOuterY = yHalf ? thisPt.yLabelMax : thisPt.yLabelMin; - var thisSliceOuterY = thisPt.cyFinal + farthestY(thisPt.px0[1], thisPt.px1[1]); - var newExtraY = prevOuterY - thisInnerY; - var xBuffer, i2, otherPt, otherOuterY, otherOuterX, newExtraX; - if (newExtraY * yDiffSign > 0) thisPt.labelExtraY = newExtraY; - if (!Lib$k.isArrayOrTypedArray(trace.pull)) return; - for (i2 = 0; i2 < wholeSide.length; i2++) { - otherPt = wholeSide[i2]; - if (otherPt === thisPt || (helpers$a.castOption(trace.pull, thisPt.pts) || 0) >= (helpers$a.castOption(trace.pull, otherPt.pts) || 0)) { - continue; - } - if ((thisPt.pxmid[1] - otherPt.pxmid[1]) * yDiffSign > 0) { - otherOuterY = otherPt.cyFinal + farthestY(otherPt.px0[1], otherPt.px1[1]); - newExtraY = otherOuterY - thisInnerY - thisPt.labelExtraY; - if (newExtraY * yDiffSign > 0) thisPt.labelExtraY += newExtraY; - } else if ((thisOuterY + thisPt.labelExtraY - thisSliceOuterY) * yDiffSign > 0) { - xBuffer = 3 * xDiffSign * Math.abs(i2 - wholeSide.indexOf(thisPt)); - otherOuterX = otherPt.cxFinal + farthestX(otherPt.px0[0], otherPt.px1[0]); - newExtraX = otherOuterX + xBuffer - (thisPt.cxFinal + thisPt.pxmid[0]) - thisPt.labelExtraX; - if (newExtraX * xDiffSign > 0) thisPt.labelExtraX += newExtraX; - } - } - } - for (yHalf = 0; yHalf < 2; yHalf++) { - equatorFirst = yHalf ? topFirst : bottomFirst; - farthestY = yHalf ? Math.max : Math.min; - yDiffSign = yHalf ? 1 : -1; - for (xHalf = 0; xHalf < 2; xHalf++) { - farthestX = xHalf ? Math.max : Math.min; - xDiffSign = xHalf ? 1 : -1; - thisQuad = quadrants[yHalf][xHalf]; - thisQuad.sort(equatorFirst); - oppositeQuad = quadrants[1 - yHalf][xHalf]; - wholeSide = oppositeQuad.concat(thisQuad); - thisQuadOutside = []; - for (i = 0; i < thisQuad.length; i++) { - if (thisQuad[i].yLabelMid !== void 0) thisQuadOutside.push(thisQuad[i]); - } - firstOppositeOutsidePt = false; - for (i = 0; yHalf && i < oppositeQuad.length; i++) { - if (oppositeQuad[i].yLabelMid !== void 0) { - firstOppositeOutsidePt = oppositeQuad[i]; - break; - } - } - for (i = 0; i < thisQuadOutside.length; i++) { - var prevPt = i && thisQuadOutside[i - 1]; - if (firstOppositeOutsidePt && !i) prevPt = firstOppositeOutsidePt; - scootOneLabel(thisQuadOutside[i], prevPt); - } - } - } -} -function layoutAreas(cdModule, plotSize) { - var scaleGroups = []; - for (var i = 0; i < cdModule.length; i++) { - var cd0 = cdModule[i][0]; - var trace = cd0.trace; - var domain2 = trace.domain; - var width = plotSize.w * (domain2.x[1] - domain2.x[0]); - var height = plotSize.h * (domain2.y[1] - domain2.y[0]); - if (trace.title.text && trace.title.position !== "middle center") { - height -= getTitleSpace(cd0, plotSize); - } - var rx = width / 2; - var ry = height / 2; - if (trace.type === "funnelarea" && !trace.scalegroup) { - ry /= trace.aspectratio; - } - cd0.r = Math.min(rx, ry) / (1 + getMaxPull(trace)); - cd0.cx = plotSize.l + plotSize.w * (trace.domain.x[1] + trace.domain.x[0]) / 2; - cd0.cy = plotSize.t + plotSize.h * (1 - trace.domain.y[0]) - height / 2; - if (trace.title.text && trace.title.position.indexOf("bottom") !== -1) { - cd0.cy -= getTitleSpace(cd0, plotSize); - } - if (trace.scalegroup && scaleGroups.indexOf(trace.scalegroup) === -1) { - scaleGroups.push(trace.scalegroup); - } - } - groupScale(cdModule, scaleGroups); -} -function groupScale(cdModule, scaleGroups) { - var cd0, i, trace; - for (var k = 0; k < scaleGroups.length; k++) { - var min = Infinity; - var g = scaleGroups[k]; - for (i = 0; i < cdModule.length; i++) { - cd0 = cdModule[i][0]; - trace = cd0.trace; - if (trace.scalegroup === g) { - var area2; - if (trace.type === "pie") { - area2 = cd0.r * cd0.r; - } else if (trace.type === "funnelarea") { - var rx, ry; - if (trace.aspectratio > 1) { - rx = cd0.r; - ry = rx / trace.aspectratio; - } else { - ry = cd0.r; - rx = ry * trace.aspectratio; - } - rx *= (1 + trace.baseratio) / 2; - area2 = rx * ry; - } - min = Math.min(min, area2 / cd0.vTotal); - } - } - for (i = 0; i < cdModule.length; i++) { - cd0 = cdModule[i][0]; - trace = cd0.trace; - if (trace.scalegroup === g) { - var v = min * cd0.vTotal; - if (trace.type === "funnelarea") { - v /= (1 + trace.baseratio) / 2; - v /= trace.aspectratio; - } - cd0.r = Math.sqrt(v); - } - } - } -} -function setCoords(cd) { - var cd0 = cd[0]; - var r = cd0.r; - var trace = cd0.trace; - var currentAngle = helpers$a.getRotationAngle(trace.rotation); - var angleFactor = 2 * Math.PI / cd0.vTotal; - var firstPt = "px0"; - var lastPt = "px1"; - var i, cdi, currentCoords; - if (trace.direction === "counterclockwise") { - for (i = 0; i < cd.length; i++) { - if (!cd[i].hidden) break; - } - if (i === cd.length) return; - currentAngle += angleFactor * cd[i].v; - angleFactor *= -1; - firstPt = "px1"; - lastPt = "px0"; - } - currentCoords = getCoords(r, currentAngle); - for (i = 0; i < cd.length; i++) { - cdi = cd[i]; - if (cdi.hidden) continue; - cdi[firstPt] = currentCoords; - cdi.startangle = currentAngle; - currentAngle += angleFactor * cdi.v / 2; - cdi.pxmid = getCoords(r, currentAngle); - cdi.midangle = currentAngle; - currentAngle += angleFactor * cdi.v / 2; - currentCoords = getCoords(r, currentAngle); - cdi.stopangle = currentAngle; - cdi[lastPt] = currentCoords; - cdi.largeArc = cdi.v > cd0.vTotal / 2 ? 1 : 0; - cdi.halfangle = Math.PI * Math.min(cdi.v / cd0.vTotal, 0.5); - cdi.ring = 1 - trace.hole; - cdi.rInscribed = getInscribedRadiusFraction(cdi, cd0); - } -} -function getCoords(r, angle) { - return [r * Math.sin(angle), -r * Math.cos(angle)]; -} -function formatSliceLabel$1(gd, pt, cd0) { - var fullLayout = gd._fullLayout; - var trace = cd0.trace; - var texttemplate = trace.texttemplate; - var textinfo = trace.textinfo; - if (!texttemplate && textinfo && textinfo !== "none") { - var parts = textinfo.split("+"); - var hasFlag = function(flag) { - return parts.indexOf(flag) !== -1; - }; - var hasLabel = hasFlag("label"); - var hasText = hasFlag("text"); - var hasValue = hasFlag("value"); - var hasPercent = hasFlag("percent"); - var separators = fullLayout.separators; - var text; - text = hasLabel ? [pt.label] : []; - if (hasText) { - var tx = helpers$a.getFirstFilled(trace.text, pt.pts); - if (isValidTextValue(tx)) text.push(tx); - } - if (hasValue) text.push(helpers$a.formatPieValue(pt.v, separators)); - if (hasPercent) text.push(helpers$a.formatPiePercent(pt.v / cd0.vTotal, separators)); - pt.text = text.join("
"); - } - function makeTemplateVariables(pt2) { - return { - label: pt2.label, - value: pt2.v, - valueLabel: helpers$a.formatPieValue(pt2.v, fullLayout.separators), - percent: pt2.v / cd0.vTotal, - percentLabel: helpers$a.formatPiePercent(pt2.v / cd0.vTotal, fullLayout.separators), - color: pt2.color, - text: pt2.text, - customdata: Lib$k.castOption(trace, pt2.i, "customdata") - }; - } - if (texttemplate) { - var txt = Lib$k.castOption(trace, pt.i, "texttemplate"); - if (!txt) { - pt.text = ""; - } else { - var obj = makeTemplateVariables(pt); - var ptTx = helpers$a.getFirstFilled(trace.text, pt.pts); - if (isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx; - pt.text = Lib$k.texttemplateString(txt, obj, gd._fullLayout._d3locale, obj, trace._meta || {}); - } - } -} -function computeTransform(transform, textBB) { - var a = transform.rotate * Math.PI / 180; - var cosA = Math.cos(a); - var sinA = Math.sin(a); - var midX = (textBB.left + textBB.right) / 2; - var midY = (textBB.top + textBB.bottom) / 2; - transform.textX = midX * cosA - midY * sinA; - transform.textY = midX * sinA + midY * cosA; - transform.noCenter = true; -} -var plot_1 = { - plot: plot$4, - transformInsideText, - computeTransform -}; -var d3$8 = d3Exports; -var styleOne$4 = style_one; -var resizeText$2 = uniform_text.resizeText; -var style$2 = function style2(gd) { - var s = gd._fullLayout._pielayer.selectAll(".trace"); - resizeText$2(gd, s, "pie"); - s.each(function(cd) { - var cd0 = cd[0]; - var trace = cd0.trace; - var traceSelection = d3$8.select(this); - traceSelection.style({ opacity: trace.opacity }); - traceSelection.selectAll("path.surface").each(function(pt) { - d3$8.select(this).call(styleOne$4, pt, trace, gd); - }); - }); -}; -var base_plot$1 = {}; -(function(exports2) { - var plots2 = plotsExports; - exports2.name = "pie"; - exports2.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - plots2.plotBasePlot(exports2.name, gd, traces, transitionOpts, makeOnCompleteCallback); - }; - exports2.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - plots2.cleanBasePlot(exports2.name, newFullData, newFullLayout, oldFullData, oldFullLayout); - }; -})(base_plot$1); -var pie$2 = { - attributes: attributes$8, - supplyDefaults: defaults$4.supplyDefaults, - supplyLayoutDefaults: layout_defaults$1, - layoutAttributes: layout_attributes$1, - calc: calc_1$1.calc, - crossTraceCalc: calc_1$1.crossTraceCalc, - plot: plot_1.plot, - style: style$2, - styleOne: style_one, - moduleType: "trace", - name: "pie", - basePlotModule: base_plot$1, - categories: ["pie-like", "pie", "showLegend"], - meta: { - description: [ - "A data visualized by the sectors of the pie is set in `values`.", - "The sector labels are set in `labels`.", - "The sector colors are set in `marker.colors`" - ].join(" ") - } -}; -var pie = pie$2; -const pie$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(pie); -var delta$2 = { - INCREASING: { - COLOR: "#3D9970", - SYMBOL: "▲" - }, - DECREASING: { - COLOR: "#FF4136", - SYMBOL: "▼" - } -}; -var extendFlat$3 = libExports.extendFlat; -var scatterAttrs$1 = attributes$A; -var axisHoverFormat$1 = axis_format_attributes.axisHoverFormat; -var dash = attributes$M.dash; -var fxAttrs = attributes$P; -var delta$1 = delta$2; -var INCREASING_COLOR = delta$1.INCREASING.COLOR; -var DECREASING_COLOR = delta$1.DECREASING.COLOR; -var lineAttrs = scatterAttrs$1.line; -function directionAttrs(lineColorDefault) { - return { - line: { - color: extendFlat$3({}, lineAttrs.color, { dflt: lineColorDefault }), - width: lineAttrs.width, - dash, - editType: "style" - }, - editType: "style" - }; -} -var attributes$6 = { - xperiod: scatterAttrs$1.xperiod, - xperiod0: scatterAttrs$1.xperiod0, - xperiodalignment: scatterAttrs$1.xperiodalignment, - xhoverformat: axisHoverFormat$1("x"), - yhoverformat: axisHoverFormat$1("y"), - x: { - valType: "data_array", - editType: "calc+clearAxisTypes", - description: [ - "Sets the x coordinates.", - "If absent, linear coordinate will be generated." - ].join(" ") - }, - open: { - valType: "data_array", - editType: "calc", - description: "Sets the open values." - }, - high: { - valType: "data_array", - editType: "calc", - description: "Sets the high values." - }, - low: { - valType: "data_array", - editType: "calc", - description: "Sets the low values." - }, - close: { - valType: "data_array", - editType: "calc", - description: "Sets the close values." - }, - line: { - width: extendFlat$3({}, lineAttrs.width, { - description: [ - lineAttrs.width, - "Note that this style setting can also be set per", - "direction via `increasing.line.width` and", - "`decreasing.line.width`." - ].join(" ") - }), - dash: extendFlat$3({}, dash, { - description: [ - dash.description, - "Note that this style setting can also be set per", - "direction via `increasing.line.dash` and", - "`decreasing.line.dash`." - ].join(" ") - }), - editType: "style" - }, - increasing: directionAttrs(INCREASING_COLOR), - decreasing: directionAttrs(DECREASING_COLOR), - text: { - valType: "string", - dflt: "", - arrayOk: true, - editType: "calc", - description: [ - "Sets hover text elements associated with each sample point.", - "If a single string, the same string appears over", - "all the data points.", - "If an array of string, the items are mapped in order to", - "this trace's sample points." - ].join(" ") - }, - hovertext: { - valType: "string", - dflt: "", - arrayOk: true, - editType: "calc", - description: "Same as `text`." - }, - tickwidth: { - valType: "number", - min: 0, - max: 0.5, - dflt: 0.3, - editType: "calc", - description: [ - "Sets the width of the open/close tick marks", - "relative to the *x* minimal interval." - ].join(" ") - }, - hoverlabel: extendFlat$3({}, fxAttrs.hoverlabel, { - split: { - valType: "boolean", - dflt: false, - editType: "style", - description: [ - "Show hover information (open, close, high, low) in", - "separate labels." - ].join(" ") - } - }), - zorder: scatterAttrs$1.zorder -}; -var Registry$4 = registry; -var Lib$j = libExports; -var ohlc_defaults = function handleOHLC(traceIn, traceOut, coerce2, layout) { - var x = coerce2("x"); - var open = coerce2("open"); - var high = coerce2("high"); - var low = coerce2("low"); - var close = coerce2("close"); - coerce2("hoverlabel.split"); - var handleCalendarDefaults = Registry$4.getComponentMethod("calendars", "handleTraceDefaults"); - handleCalendarDefaults(traceIn, traceOut, ["x"], layout); - if (!(open && high && low && close)) return; - var len = Math.min(open.length, high.length, low.length, close.length); - if (x) len = Math.min(len, Lib$j.minRowLength(x)); - traceOut._length = len; - return len; -}; -var Lib$i = libExports; -var handleOHLC2 = ohlc_defaults; -var handlePeriodDefaults$1 = period_defaults; -var attributes$5 = attributes$6; -var defaults$3 = function supplyDefaults5(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$i.coerce(traceIn, traceOut, attributes$5, attr, dflt); - } - var len = handleOHLC2(traceIn, traceOut, coerce2, layout); - if (!len) { - traceOut.visible = false; - return; - } - handlePeriodDefaults$1(traceIn, traceOut, layout, coerce2, { x: true }); - coerce2("xhoverformat"); - coerce2("yhoverformat"); - coerce2("line.width"); - coerce2("line.dash"); - handleDirection(traceIn, traceOut, coerce2, "increasing"); - handleDirection(traceIn, traceOut, coerce2, "decreasing"); - coerce2("text"); - coerce2("hovertext"); - coerce2("tickwidth"); - layout._requestRangeslider[traceOut.xaxis] = true; - coerce2("zorder"); -}; -function handleDirection(traceIn, traceOut, coerce2, direction) { - coerce2(direction + ".line.color"); - coerce2(direction + ".line.width", traceOut.line.width); - coerce2(direction + ".line.dash", traceOut.line.dash); -} -var Lib$h = libExports; -var _ = Lib$h._; -var Axes$1 = axesExports; -var alignPeriod$1 = align_period; -var BADNUM$1 = numerical.BADNUM; -function calc$4(gd, trace) { - var xa = Axes$1.getFromId(gd, trace.xaxis); - var ya = Axes$1.getFromId(gd, trace.yaxis); - var tickLen = convertTickWidth(gd, xa, trace); - var minDiff = trace._minDiff; - trace._minDiff = null; - var origX = trace._origX; - trace._origX = null; - var x = trace._xcalc; - trace._xcalc = null; - var cd = calcCommon(gd, trace, origX, x, ya, ptFunc); - trace._extremes[xa._id] = Axes$1.findExtremes(xa, x, { vpad: minDiff / 2 }); - if (cd.length) { - Lib$h.extendFlat(cd[0].t, { - wHover: minDiff / 2, - tickLen - }); - return cd; - } else { - return [{ t: { empty: true } }]; - } -} -function ptFunc(o, h, l, c) { - return { - o, - h, - l, - c - }; -} -function calcCommon(gd, trace, origX, x, ya, ptFunc2) { - var o = ya.makeCalcdata(trace, "open"); - var h = ya.makeCalcdata(trace, "high"); - var l = ya.makeCalcdata(trace, "low"); - var c = ya.makeCalcdata(trace, "close"); - var hasTextArray = Lib$h.isArrayOrTypedArray(trace.text); - var hasHovertextArray = Lib$h.isArrayOrTypedArray(trace.hovertext); - var increasing = true; - var cPrev = null; - var hasPeriod = !!trace.xperiodalignment; - var cd = []; - for (var i = 0; i < x.length; i++) { - var xi = x[i]; - var oi = o[i]; - var hi = h[i]; - var li = l[i]; - var ci = c[i]; - if (xi !== BADNUM$1 && oi !== BADNUM$1 && hi !== BADNUM$1 && li !== BADNUM$1 && ci !== BADNUM$1) { - if (ci === oi) { - if (cPrev !== null && ci !== cPrev) increasing = ci > cPrev; - } else increasing = ci > oi; - cPrev = ci; - var pt = ptFunc2(oi, hi, li, ci); - pt.pos = xi; - pt.yc = (oi + ci) / 2; - pt.i = i; - pt.dir = increasing ? "increasing" : "decreasing"; - pt.x = pt.pos; - pt.y = [li, hi]; - if (hasPeriod) pt.orig_p = origX[i]; - if (hasTextArray) pt.tx = trace.text[i]; - if (hasHovertextArray) pt.htx = trace.hovertext[i]; - cd.push(pt); - } else { - cd.push({ pos: xi, empty: true }); - } - } - trace._extremes[ya._id] = Axes$1.findExtremes(ya, Lib$h.concat(l, h), { padded: true }); - if (cd.length) { - cd[0].t = { - labels: { - open: _(gd, "open:") + " ", - high: _(gd, "high:") + " ", - low: _(gd, "low:") + " ", - close: _(gd, "close:") + " " - } - }; - } - return cd; -} -function convertTickWidth(gd, xa, trace) { - var minDiff = trace._minDiff; - if (!minDiff) { - var fullData = gd._fullData; - var ohlcTracesOnThisXaxis = []; - minDiff = Infinity; - var i; - for (i = 0; i < fullData.length; i++) { - var tracei = fullData[i]; - if (tracei.type === "ohlc" && tracei.visible === true && tracei.xaxis === xa._id) { - ohlcTracesOnThisXaxis.push(tracei); - var origX = xa.makeCalcdata(tracei, "x"); - tracei._origX = origX; - var xcalc = alignPeriod$1(trace, xa, "x", origX).vals; - tracei._xcalc = xcalc; - var _minDiff = Lib$h.distinctVals(xcalc).minDiff; - if (_minDiff && isFinite(_minDiff)) { - minDiff = Math.min(minDiff, _minDiff); - } - } - } - if (minDiff === Infinity) minDiff = 1; - for (i = 0; i < ohlcTracesOnThisXaxis.length; i++) { - ohlcTracesOnThisXaxis[i]._minDiff = minDiff; - } - } - return minDiff * trace.tickwidth; -} -var calc_1 = { - calc: calc$4 -}; -var d3$7 = d3Exports; -var Lib$g = libExports; -var plot$3 = function plot2(gd, plotinfo, cdOHLC, ohlcLayer) { - var ya = plotinfo.yaxis; - var xa = plotinfo.xaxis; - var posHasRangeBreaks = !!xa.rangebreaks; - Lib$g.makeTraceGroups(ohlcLayer, cdOHLC, "trace ohlc").each(function(cd) { - var plotGroup = d3$7.select(this); - var cd0 = cd[0]; - var t = cd0.t; - var trace = cd0.trace; - if (trace.visible !== true || t.empty) { - plotGroup.remove(); - return; - } - var tickLen = t.tickLen; - var paths = plotGroup.selectAll("path").data(Lib$g.identity); - paths.enter().append("path"); - paths.exit().remove(); - paths.attr("d", function(d) { - if (d.empty) return "M0,0Z"; - var xo = xa.c2p(d.pos - tickLen, true); - var xc = xa.c2p(d.pos + tickLen, true); - var x = posHasRangeBreaks ? (xo + xc) / 2 : xa.c2p(d.pos, true); - var yo = ya.c2p(d.o, true); - var yh = ya.c2p(d.h, true); - var yl = ya.c2p(d.l, true); - var yc = ya.c2p(d.c, true); - return "M" + xo + "," + yo + "H" + x + "M" + x + "," + yh + "V" + yl + "M" + xc + "," + yc + "H" + x; - }); - }); -}; -var d3$6 = d3Exports; -var Drawing$4 = drawingExports; -var Color$8 = colorExports; -var style$1 = function style3(gd, cd, sel) { - var s = sel ? sel : d3$6.select(gd).selectAll("g.ohlclayer").selectAll("g.trace"); - s.style("opacity", function(d) { - return d[0].trace.opacity; - }); - s.each(function(d) { - var trace = d[0].trace; - d3$6.select(this).selectAll("path").each(function(di) { - if (di.empty) return; - var dirLine = trace[di.dir].line; - d3$6.select(this).style("fill", "none").call(Color$8.stroke, dirLine.color).call(Drawing$4.dashLine, dirLine.dash, dirLine.width).style("opacity", trace.selectedpoints && !di.selected ? 0.3 : 1); - }); - }); -}; -var Axes = axesExports; -var Lib$f = libExports; -var Fx$1 = fx$1; -var Color$7 = colorExports; -var fillText = libExports.fillText; -var delta = delta$2; -var DIRSYMBOL = { - increasing: delta.INCREASING.SYMBOL, - decreasing: delta.DECREASING.SYMBOL -}; -function hoverPoints$1(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var trace = cd[0].trace; - if (trace.hoverlabel.split) { - return hoverSplit(pointData, xval, yval, hovermode); - } - return hoverOnPoints(pointData, xval, yval, hovermode); -} -function _getClosestPoint(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var xa = pointData.xa; - var trace = cd[0].trace; - var t = cd[0].t; - var type = trace.type; - var minAttr = type === "ohlc" ? "l" : "min"; - var maxAttr = type === "ohlc" ? "h" : "max"; - var hoverPseudoDistance, spikePseudoDistance; - var centerShift = t.bPos || 0; - var shiftPos = function(di2) { - return di2.pos + centerShift - xval; - }; - var displayHalfWidth = t.bdPos || t.tickLen; - var hoverHalfWidth = t.wHover; - var pseudoDistance = Math.min(1, displayHalfWidth / Math.abs(xa.r2c(xa.range[1]) - xa.r2c(xa.range[0]))); - hoverPseudoDistance = pointData.maxHoverDistance - pseudoDistance; - spikePseudoDistance = pointData.maxSpikeDistance - pseudoDistance; - function dx(di2) { - var pos = shiftPos(di2); - return Fx$1.inbox(pos - hoverHalfWidth, pos + hoverHalfWidth, hoverPseudoDistance); - } - function dy(di2) { - var min = di2[minAttr]; - var max = di2[maxAttr]; - return min === max || Fx$1.inbox(min - yval, max - yval, hoverPseudoDistance); - } - function dxy(di2) { - return (dx(di2) + dy(di2)) / 2; - } - var distfn = Fx$1.getDistanceFunction(hovermode, dx, dy, dxy); - Fx$1.getClosest(cd, distfn, pointData); - if (pointData.index === false) return null; - var di = cd[pointData.index]; - if (di.empty) return null; - var dir = di.dir; - var container = trace[dir]; - var lc = container.line.color; - if (Color$7.opacity(lc) && container.line.width) pointData.color = lc; - else pointData.color = container.fillcolor; - pointData.x0 = xa.c2p(di.pos + centerShift - displayHalfWidth, true); - pointData.x1 = xa.c2p(di.pos + centerShift + displayHalfWidth, true); - pointData.xLabelVal = di.orig_p !== void 0 ? di.orig_p : di.pos; - pointData.spikeDistance = dxy(di) * spikePseudoDistance / hoverPseudoDistance; - pointData.xSpike = xa.c2p(di.pos, true); - return pointData; -} -function hoverSplit(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var ya = pointData.ya; - var trace = cd[0].trace; - var t = cd[0].t; - var closeBoxData = []; - var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode); - if (!closestPoint) return []; - var cdIndex = closestPoint.index; - var di = cd[cdIndex]; - var hoverinfo = di.hi || trace.hoverinfo; - var hoverParts = hoverinfo.split("+"); - var isAll = hoverinfo === "all"; - var hasY = isAll || hoverParts.indexOf("y") !== -1; - if (!hasY) return []; - var attrs2 = ["high", "open", "close", "low"]; - var usedVals = {}; - for (var i = 0; i < attrs2.length; i++) { - var attr = attrs2[i]; - var val = trace[attr][closestPoint.index]; - var valPx = ya.c2p(val, true); - var pointData2; - if (val in usedVals) { - pointData2 = usedVals[val]; - pointData2.yLabel += "
" + t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat); - } else { - pointData2 = Lib$f.extendFlat({}, closestPoint); - pointData2.y0 = pointData2.y1 = valPx; - pointData2.yLabelVal = val; - pointData2.yLabel = t.labels[attr] + Axes.hoverLabelText(ya, val, trace.yhoverformat); - pointData2.name = ""; - closeBoxData.push(pointData2); - usedVals[val] = pointData2; - } - } - return closeBoxData; -} -function hoverOnPoints(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var ya = pointData.ya; - var trace = cd[0].trace; - var t = cd[0].t; - var closestPoint = _getClosestPoint(pointData, xval, yval, hovermode); - if (!closestPoint) return []; - var cdIndex = closestPoint.index; - var di = cd[cdIndex]; - var i = closestPoint.index = di.i; - var dir = di.dir; - function getLabelLine(attr) { - return t.labels[attr] + Axes.hoverLabelText(ya, trace[attr][i], trace.yhoverformat); - } - var hoverinfo = di.hi || trace.hoverinfo; - var hoverParts = hoverinfo.split("+"); - var isAll = hoverinfo === "all"; - var hasY = isAll || hoverParts.indexOf("y") !== -1; - var hasText = isAll || hoverParts.indexOf("text") !== -1; - var textParts = hasY ? [ - getLabelLine("open"), - getLabelLine("high"), - getLabelLine("low"), - getLabelLine("close") + " " + DIRSYMBOL[dir] - ] : []; - if (hasText) fillText(di, trace, textParts); - closestPoint.extraText = textParts.join("
"); - closestPoint.y0 = closestPoint.y1 = ya.c2p(di.yc, true); - return [closestPoint]; -} -var hover$2 = { - hoverPoints: hoverPoints$1 -}; -var select$1 = function selectPoints3(searchInfo, selectionTester) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var i; - var posOffset = cd[0].t.bPos || 0; - if (selectionTester === false) { - for (i = 0; i < cd.length; i++) { - cd[i].selected = 0; - } - } else { - for (i = 0; i < cd.length; i++) { - var di = cd[i]; - if (selectionTester.contains([xa.c2p(di.pos + posOffset), ya.c2p(di.yc)], null, di.i, searchInfo)) { - selection.push({ - pointNumber: di.i, - x: xa.c2d(di.pos), - y: ya.c2d(di.yc) - }); - di.selected = 1; - } else { - di.selected = 0; - } - } - } - return selection; -}; -var ohlc$2 = { - moduleType: "trace", - name: "ohlc", - basePlotModule: cartesian, - categories: ["cartesian", "svg", "showLegend"], - meta: { - description: [ - "The ohlc (short for Open-High-Low-Close) is a style of financial chart describing", - "open, high, low and close for a given `x` coordinate (most likely time).", - "The tip of the lines represent the `low` and `high` values and", - "the horizontal segments represent the `open` and `close` values.", - "Sample points where the close value is higher (lower) then the open", - "value are called increasing (decreasing).", - "By default, increasing items are drawn in green whereas", - "decreasing are drawn in red." - ].join(" ") - }, - attributes: attributes$6, - supplyDefaults: defaults$3, - calc: calc_1.calc, - plot: plot$3, - style: style$1, - hoverPoints: hover$2.hoverPoints, - selectPoints: select$1 -}; -var ohlc = ohlc$2; -const ohlc$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(ohlc); -var Registry$3 = registry; -var Lib$e = libExports; -var getTraceColor2 = get_trace_color; -function hoverPoints3(pointData, xval, yval, hovermode) { - var cd = pointData.cd; - var stash = cd[0].t; - var trace = cd[0].trace; - var xa = pointData.xa; - var ya = pointData.ya; - var x = stash.x; - var y = stash.y; - var xpx = xa.c2p(xval); - var ypx = ya.c2p(yval); - var maxDistance = pointData.distance; - var ids; - if (stash.tree) { - var xl = xa.p2c(xpx - maxDistance); - var xr = xa.p2c(xpx + maxDistance); - var yl = ya.p2c(ypx - maxDistance); - var yr = ya.p2c(ypx + maxDistance); - if (hovermode === "x") { - ids = stash.tree.range( - Math.min(xl, xr), - Math.min(ya._rl[0], ya._rl[1]), - Math.max(xl, xr), - Math.max(ya._rl[0], ya._rl[1]) - ); - } else { - ids = stash.tree.range( - Math.min(xl, xr), - Math.min(yl, yr), - Math.max(xl, xr), - Math.max(yl, yr) - ); - } - } else { - ids = stash.ids; - } - var k, closestId, ptx, pty, i, dx, dy, dist2, dxy; - var minDist = maxDistance; - if (hovermode === "x") { - var xPeriod = !!trace.xperiodalignment; - var yPeriod = !!trace.yperiodalignment; - for (i = 0; i < ids.length; i++) { - k = ids[i]; - ptx = x[k]; - dx = Math.abs(xa.c2p(ptx) - xpx); - if (xPeriod) { - var x0 = xa.c2p(trace._xStarts[k]); - var x1 = xa.c2p(trace._xEnds[k]); - dx = xpx >= Math.min(x0, x1) && xpx <= Math.max(x0, x1) ? 0 : Infinity; - } - if (dx < minDist) { - minDist = dx; - pty = y[k]; - dy = ya.c2p(pty) - ypx; - if (yPeriod) { - var y0 = ya.c2p(trace._yStarts[k]); - var y1 = ya.c2p(trace._yEnds[k]); - dy = ypx >= Math.min(y0, y1) && ypx <= Math.max(y0, y1) ? 0 : Infinity; - } - dxy = Math.sqrt(dx * dx + dy * dy); - closestId = ids[i]; - } - } - } else { - for (i = ids.length - 1; i > -1; i--) { - k = ids[i]; - ptx = x[k]; - pty = y[k]; - dx = xa.c2p(ptx) - xpx; - dy = ya.c2p(pty) - ypx; - dist2 = Math.sqrt(dx * dx + dy * dy); - if (dist2 < minDist) { - minDist = dxy = dist2; - closestId = k; - } - } - } - pointData.index = closestId; - pointData.distance = minDist; - pointData.dxy = dxy; - if (closestId === void 0) return [pointData]; - return [calcHover(pointData, x, y, trace)]; -} -function calcHover(pointData, x, y, trace) { - var xa = pointData.xa; - var ya = pointData.ya; - var minDist = pointData.distance; - var dxy = pointData.dxy; - var id = pointData.index; - var di = { - pointNumber: id, - x: x[id], - y: y[id] - }; - di.tx = Lib$e.isArrayOrTypedArray(trace.text) ? trace.text[id] : trace.text; - di.htx = Array.isArray(trace.hovertext) ? trace.hovertext[id] : trace.hovertext; - di.data = Array.isArray(trace.customdata) ? trace.customdata[id] : trace.customdata; - di.tp = Array.isArray(trace.textposition) ? trace.textposition[id] : trace.textposition; - var font2 = trace.textfont; - if (font2) { - di.ts = Lib$e.isArrayOrTypedArray(font2.size) ? font2.size[id] : font2.size; - di.tc = Lib$e.isArrayOrTypedArray(font2.color) ? font2.color[id] : font2.color; - di.tf = Array.isArray(font2.family) ? font2.family[id] : font2.family; - di.tw = Array.isArray(font2.weight) ? font2.weight[id] : font2.weight; - di.ty = Array.isArray(font2.style) ? font2.style[id] : font2.style; - di.tv = Array.isArray(font2.variant) ? font2.variant[id] : font2.variant; - } - var marker2 = trace.marker; - if (marker2) { - di.ms = Lib$e.isArrayOrTypedArray(marker2.size) ? marker2.size[id] : marker2.size; - di.mo = Lib$e.isArrayOrTypedArray(marker2.opacity) ? marker2.opacity[id] : marker2.opacity; - di.mx = Lib$e.isArrayOrTypedArray(marker2.symbol) ? marker2.symbol[id] : marker2.symbol; - di.ma = Lib$e.isArrayOrTypedArray(marker2.angle) ? marker2.angle[id] : marker2.angle; - di.mc = Lib$e.isArrayOrTypedArray(marker2.color) ? marker2.color[id] : marker2.color; - } - var line2 = marker2 && marker2.line; - if (line2) { - di.mlc = Array.isArray(line2.color) ? line2.color[id] : line2.color; - di.mlw = Lib$e.isArrayOrTypedArray(line2.width) ? line2.width[id] : line2.width; - } - var grad = marker2 && marker2.gradient; - if (grad && grad.type !== "none") { - di.mgt = Array.isArray(grad.type) ? grad.type[id] : grad.type; - di.mgc = Array.isArray(grad.color) ? grad.color[id] : grad.color; - } - var xp = xa.c2p(di.x, true); - var yp = ya.c2p(di.y, true); - var rad = di.mrc || 1; - var hoverlabel = trace.hoverlabel; - if (hoverlabel) { - di.hbg = Array.isArray(hoverlabel.bgcolor) ? hoverlabel.bgcolor[id] : hoverlabel.bgcolor; - di.hbc = Array.isArray(hoverlabel.bordercolor) ? hoverlabel.bordercolor[id] : hoverlabel.bordercolor; - di.hts = Lib$e.isArrayOrTypedArray(hoverlabel.font.size) ? hoverlabel.font.size[id] : hoverlabel.font.size; - di.htc = Array.isArray(hoverlabel.font.color) ? hoverlabel.font.color[id] : hoverlabel.font.color; - di.htf = Array.isArray(hoverlabel.font.family) ? hoverlabel.font.family[id] : hoverlabel.font.family; - di.hnl = Lib$e.isArrayOrTypedArray(hoverlabel.namelength) ? hoverlabel.namelength[id] : hoverlabel.namelength; - } - var hoverinfo = trace.hoverinfo; - if (hoverinfo) { - di.hi = Array.isArray(hoverinfo) ? hoverinfo[id] : hoverinfo; - } - var hovertemplate = trace.hovertemplate; - if (hovertemplate) { - di.ht = Array.isArray(hovertemplate) ? hovertemplate[id] : hovertemplate; - } - var fakeCd = {}; - fakeCd[pointData.index] = di; - var origX = trace._origX; - var origY = trace._origY; - var pointData2 = Lib$e.extendFlat({}, pointData, { - color: getTraceColor2(trace, di), - x0: xp - rad, - x1: xp + rad, - xLabelVal: origX ? origX[id] : di.x, - y0: yp - rad, - y1: yp + rad, - yLabelVal: origY ? origY[id] : di.y, - cd: fakeCd, - distance: minDist, - spikeDistance: dxy, - hovertemplate: di.ht - }); - if (di.htx) pointData2.text = di.htx; - else if (di.tx) pointData2.text = di.tx; - else if (trace.text) pointData2.text = trace.text; - Lib$e.fillText(di, trace, pointData2); - Registry$3.getComponentMethod("errorbars", "hoverInfo")(di, trace, pointData2); - return pointData2; -} -var hover$1 = { - hoverPoints: hoverPoints3 -}; -var attributes$4 = { exports: {} }; -var SYMBOL_SIZE$1 = 20; -var constants$a = { - TOO_MANY_POINTS: 1e5, - SYMBOL_SDF_SIZE: 200, - SYMBOL_SIZE: SYMBOL_SIZE$1, - SYMBOL_STROKE: SYMBOL_SIZE$1 / 20, - DOT_RE: /-dot/, - OPEN_RE: /-open/, - DASHES: { - solid: [1], - dot: [1, 1], - dash: [4, 1], - longdash: [8, 1], - dashdot: [4, 1, 1, 1], - longdashdot: [8, 1, 1, 1] - } -}; -var baseAttrs$1 = attributes$O; -var fontAttrs = font_attributes; -var makeFillcolorAttr2 = fillcolor_attribute; -var scatterAttrs = attributes$A; -var axisHoverFormat = axis_format_attributes.axisHoverFormat; -var colorScaleAttrs$2 = attributes$I; -var sortObjectKeys2 = sort_object_keys; -var extendFlat$2 = extend$5.extendFlat; -var overrideAll = edit_types.overrideAll; -var DASHES = constants$a.DASHES; -var scatterLineAttrs = scatterAttrs.line; -var scatterMarkerAttrs = scatterAttrs.marker; -var scatterMarkerLineAttrs = scatterMarkerAttrs.line; -var attrs = attributes$4.exports = overrideAll({ - x: scatterAttrs.x, - x0: scatterAttrs.x0, - dx: scatterAttrs.dx, - y: scatterAttrs.y, - y0: scatterAttrs.y0, - dy: scatterAttrs.dy, - xperiod: scatterAttrs.xperiod, - yperiod: scatterAttrs.yperiod, - xperiod0: scatterAttrs.xperiod0, - yperiod0: scatterAttrs.yperiod0, - xperiodalignment: scatterAttrs.xperiodalignment, - yperiodalignment: scatterAttrs.yperiodalignment, - xhoverformat: axisHoverFormat("x"), - yhoverformat: axisHoverFormat("y"), - text: scatterAttrs.text, - hovertext: scatterAttrs.hovertext, - textposition: scatterAttrs.textposition, - textfont: fontAttrs({ - noFontShadow: true, - noFontLineposition: true, - noFontTextcase: true, - editType: "calc", - colorEditType: "style", - arrayOk: true, - noNumericWeightValues: true, - variantValues: ["normal", "small-caps"], - description: "Sets the text font." - }), - mode: { - valType: "flaglist", - flags: ["lines", "markers", "text"], - extras: ["none"], - description: [ - "Determines the drawing mode for this scatter trace." - ].join(" ") - }, - line: { - color: scatterLineAttrs.color, - width: scatterLineAttrs.width, - shape: { - valType: "enumerated", - values: ["linear", "hv", "vh", "hvh", "vhv"], - dflt: "linear", - editType: "plot", - description: [ - "Determines the line shape.", - "The values correspond to step-wise line shapes." - ].join(" ") - }, - dash: { - valType: "enumerated", - values: sortObjectKeys2(DASHES), - dflt: "solid", - description: "Sets the style of the lines." - } - }, - marker: extendFlat$2({}, colorScaleAttrs$2("marker"), { - symbol: scatterMarkerAttrs.symbol, - angle: scatterMarkerAttrs.angle, - size: scatterMarkerAttrs.size, - sizeref: scatterMarkerAttrs.sizeref, - sizemin: scatterMarkerAttrs.sizemin, - sizemode: scatterMarkerAttrs.sizemode, - opacity: scatterMarkerAttrs.opacity, - colorbar: scatterMarkerAttrs.colorbar, - line: extendFlat$2({}, colorScaleAttrs$2("marker.line"), { - width: scatterMarkerLineAttrs.width - }) - }), - connectgaps: scatterAttrs.connectgaps, - fill: extendFlat$2({}, scatterAttrs.fill, { dflt: "none" }), - fillcolor: makeFillcolorAttr2(), - // no hoveron - selected: { - marker: scatterAttrs.selected.marker, - textfont: scatterAttrs.selected.textfont - }, - unselected: { - marker: scatterAttrs.unselected.marker, - textfont: scatterAttrs.unselected.textfont - }, - opacity: baseAttrs$1.opacity -}, "calc", "nested"); -attrs.x.editType = attrs.y.editType = attrs.x0.editType = attrs.y0.editType = "calc+clearAxisTypes"; -attrs.hovertemplate = scatterAttrs.hovertemplate; -attrs.texttemplate = scatterAttrs.texttemplate; -var attributesExports = attributes$4.exports; -var helpers$9 = {}; -var constants$9 = constants$a; -helpers$9.isOpenSymbol = function(symbol) { - return typeof symbol === "string" ? constants$9.OPEN_RE.test(symbol) : symbol % 200 > 100; -}; -helpers$9.isDotSymbol = function(symbol) { - return typeof symbol === "string" ? constants$9.DOT_RE.test(symbol) : symbol > 200; -}; -var Lib$d = libExports; -var Registry$2 = registry; -var helpers$8 = helpers$9; -var attributes$3 = attributesExports; -var constants$8 = constants$B; -var subTypes$3 = subtypes$3; -var handleXYDefaults2 = xy_defaults; -var handlePeriodDefaults2 = period_defaults; -var handleMarkerDefaults$1 = marker_defaults; -var handleLineDefaults = line_defaults; -var handleFillColorDefaults = fillcolor_defaults; -var handleTextDefaults = text_defaults; -var defaults$2 = function supplyDefaults6(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$d.coerce(traceIn, traceOut, attributes$3, attr, dflt); - } - var isOpen = traceIn.marker ? helpers$8.isOpenSymbol(traceIn.marker.symbol) : false; - var isBubble = subTypes$3.isBubble(traceIn); - var len = handleXYDefaults2(traceIn, traceOut, layout, coerce2); - if (!len) { - traceOut.visible = false; - return; - } - handlePeriodDefaults2(traceIn, traceOut, layout, coerce2); - coerce2("xhoverformat"); - coerce2("yhoverformat"); - var defaultMode = len < constants$8.PTS_LINESONLY ? "lines+markers" : "lines"; - coerce2("text"); - coerce2("hovertext"); - coerce2("hovertemplate"); - coerce2("mode", defaultMode); - if (subTypes$3.hasMarkers(traceOut)) { - handleMarkerDefaults$1(traceIn, traceOut, defaultColor, layout, coerce2, { noAngleRef: true, noStandOff: true }); - coerce2("marker.line.width", isOpen || isBubble ? 1 : 0); - } - if (subTypes$3.hasLines(traceOut)) { - coerce2("connectgaps"); - handleLineDefaults(traceIn, traceOut, defaultColor, layout, coerce2); - coerce2("line.shape"); - } - if (subTypes$3.hasText(traceOut)) { - coerce2("texttemplate"); - handleTextDefaults(traceIn, traceOut, layout, coerce2, { - noFontShadow: true, - noFontLineposition: true, - noFontTextcase: true - }); - } - var lineColor = (traceOut.line || {}).color; - var markerColor = (traceOut.marker || {}).color; - coerce2("fill"); - if (traceOut.fill !== "none") { - handleFillColorDefaults(traceIn, traceOut, defaultColor, coerce2); - } - var errorBarsSupplyDefaults = Registry$2.getComponentMethod("errorbars", "supplyDefaults"); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "y" }); - errorBarsSupplyDefaults(traceIn, traceOut, lineColor || markerColor || defaultColor, { axis: "x", inherit: "y" }); - Lib$d.coerceSelectionMarkerOpacity(traceOut, coerce2); -}; -var scatterFormatLabels = format_labels$1; -var format_labels = function formatLabels2(cdi, trace, fullLayout) { - var i = cdi.i; - if (!("x" in cdi)) cdi.x = trace._x[i]; - if (!("y" in cdi)) cdi.y = trace._y[i]; - return scatterFormatLabels(cdi, trace, fullLayout); -}; -function ge(a, y, c, l, h) { - var i = h + 1; - while (l <= h) { - var m = l + h >>> 1, x = a[m]; - var p = c !== void 0 ? c(x, y) : x - y; - if (p >= 0) { - i = m; - h = m - 1; - } else { - l = m + 1; - } - } - return i; -} -function gt(a, y, c, l, h) { - var i = h + 1; - while (l <= h) { - var m = l + h >>> 1, x = a[m]; - var p = c !== void 0 ? c(x, y) : x - y; - if (p > 0) { - i = m; - h = m - 1; - } else { - l = m + 1; - } - } - return i; -} -function lt(a, y, c, l, h) { - var i = l - 1; - while (l <= h) { - var m = l + h >>> 1, x = a[m]; - var p = c !== void 0 ? c(x, y) : x - y; - if (p < 0) { - i = m; - l = m + 1; - } else { - h = m - 1; - } - } - return i; -} -function le(a, y, c, l, h) { - var i = l - 1; - while (l <= h) { - var m = l + h >>> 1, x = a[m]; - var p = c !== void 0 ? c(x, y) : x - y; - if (p <= 0) { - i = m; - l = m + 1; - } else { - h = m - 1; - } - } - return i; -} -function eq(a, y, c, l, h) { - while (l <= h) { - var m = l + h >>> 1, x = a[m]; - var p = c !== void 0 ? c(x, y) : x - y; - if (p === 0) { - return m; - } - if (p <= 0) { - l = m + 1; - } else { - h = m - 1; - } - } - return -1; -} -function norm(a, y, c, l, h, f) { - if (typeof c === "function") { - return f(a, y, c, l === void 0 ? 0 : l | 0, h === void 0 ? a.length - 1 : h | 0); - } - return f(a, y, void 0, c === void 0 ? 0 : c | 0, l === void 0 ? a.length - 1 : l | 0); -} -var searchBounds = { - ge: function(a, y, c, l, h) { - return norm(a, y, c, l, h, ge); - }, - gt: function(a, y, c, l, h) { - return norm(a, y, c, l, h, gt); - }, - lt: function(a, y, c, l, h) { - return norm(a, y, c, l, h, lt); - }, - le: function(a, y, c, l, h) { - return norm(a, y, c, l, h, le); - }, - eq: function(a, y, c, l, h) { - return norm(a, y, c, l, h, eq); - } -}; -var clamp_1 = clamp$4; -function clamp$4(value2, min, max) { - return min < max ? value2 < min ? min : value2 > max ? max : value2 : value2 < max ? max : value2 > min ? min : value2; -} -var pickByAlias = function pick(src2, props, keepRest) { - var result = {}, prop, i; - if (typeof props === "string") props = toList(props); - if (Array.isArray(props)) { - var res = {}; - for (i = 0; i < props.length; i++) { - res[props[i]] = true; - } - props = res; - } - for (prop in props) { - props[prop] = toList(props[prop]); - } - var occupied = {}; - for (prop in props) { - var aliases = props[prop]; - if (Array.isArray(aliases)) { - for (i = 0; i < aliases.length; i++) { - var alias = aliases[i]; - if (keepRest) { - occupied[alias] = true; - } - if (alias in src2) { - result[prop] = src2[alias]; - if (keepRest) { - for (var j = i; j < aliases.length; j++) { - occupied[aliases[j]] = true; - } - } - break; - } - } - } else if (prop in src2) { - if (props[prop]) { - result[prop] = src2[prop]; - } - if (keepRest) { - occupied[prop] = true; - } - } - } - if (keepRest) { - for (prop in src2) { - if (occupied[prop]) continue; - result[prop] = src2[prop]; - } - } - return result; -}; -var CACHE = {}; -function toList(arg) { - if (CACHE[arg]) return CACHE[arg]; - if (typeof arg === "string") { - arg = CACHE[arg] = arg.split(/\s*,\s*|\s+/); - } - return arg; -} -var pick$7 = pickByAlias; -var parseRect_1 = parseRect$3; -function parseRect$3(arg) { - var rect2; - if (arguments.length > 1) { - arg = arguments; - } - if (typeof arg === "string") { - arg = arg.split(/\s/).map(parseFloat); - } else if (typeof arg === "number") { - arg = [arg]; - } - if (arg.length && typeof arg[0] === "number") { - if (arg.length === 1) { - rect2 = { - width: arg[0], - height: arg[0], - x: 0, - y: 0 - }; - } else if (arg.length === 2) { - rect2 = { - width: arg[0], - height: arg[1], - x: 0, - y: 0 - }; - } else { - rect2 = { - x: arg[0], - y: arg[1], - width: arg[2] - arg[0] || 0, - height: arg[3] - arg[1] || 0 - }; - } - } else if (arg) { - arg = pick$7(arg, { - left: "x l left Left", - top: "y t top Top", - width: "w width W Width", - height: "h height W Width", - bottom: "b bottom Bottom", - right: "r right Right" - }); - rect2 = { - x: arg.left || 0, - y: arg.top || 0 - }; - if (arg.width == null) { - if (arg.right) rect2.width = arg.right - rect2.x; - else rect2.width = 0; - } else { - rect2.width = arg.width; - } - if (arg.height == null) { - if (arg.bottom) rect2.height = arg.bottom - rect2.y; - else rect2.height = 0; - } else { - rect2.height = arg.height; - } - } - return rect2; -} -var arrayBounds = normalize$7; -function normalize$7(arr, dim) { - if (!arr || arr.length == null) throw Error("Argument should be an array"); - if (dim == null) dim = 1; - else dim = Math.floor(dim); - var bounds = Array(dim * 2); - for (var offset = 0; offset < dim; offset++) { - var max = -Infinity, min = Infinity, i = offset, l = arr.length; - for (; i < l; i += dim) { - if (arr[i] > max) max = arr[i]; - if (arr[i] < min) min = arr[i]; - } - bounds[offset] = min; - bounds[dim + offset] = max; - } - return bounds; -} -var defined$1 = function defined() { - for (var i = 0; i < arguments.length; i++) { - if (typeof arguments[i] !== "undefined") { - return arguments[i]; - } - } -}; -var dtype$3 = function(dtype2) { - switch (dtype2) { - case "int8": - return Int8Array; - case "int16": - return Int16Array; - case "int32": - return Int32Array; - case "uint8": - return Uint8Array; - case "uint16": - return Uint16Array; - case "uint32": - return Uint32Array; - case "float32": - return Float32Array; - case "float64": - return Float64Array; - case "array": - return Array; - case "uint8_clamped": - return Uint8ClampedArray; - } -}; -var dtype$2 = dtype$3; -var flattenVertexData_1 = flattenVertexData; -function flattenVertexData(data, output, offset) { - if (!data) throw new TypeError("must specify data as first parameter"); - offset = +(offset || 0) | 0; - if (Array.isArray(data) && (data[0] && typeof data[0][0] === "number")) { - var dim = data[0].length; - var length2 = data.length * dim; - var i, j, k, l; - if (!output || typeof output === "string") { - output = new (dtype$2(output || "float32"))(length2 + offset); - } - var dstLength = output.length - offset; - if (length2 !== dstLength) { - throw new Error("source length " + length2 + " (" + dim + "x" + data.length + ") does not match destination length " + dstLength); - } - for (i = 0, k = offset; i < data.length; i++) { - for (j = 0; j < dim; j++) { - output[k++] = data[i][j] === null ? NaN : data[i][j]; - } - } - } else { - if (!output || typeof output === "string") { - var Ctor = dtype$2(output || "float32"); - if (Array.isArray(data) || output === "array") { - output = new Ctor(data.length + offset); - for (i = 0, k = offset, l = output.length; k < l; k++, i++) { - output[k] = data[i] === null ? NaN : data[i]; - } - } else { - if (offset === 0) { - output = new Ctor(data); - } else { - output = new Ctor(data.length + offset); - output.set(data, offset); - } - } - } else { - output.set(data, offset); - } - } - return output; -} -var isObj$2 = function(x) { - var type = typeof x; - return x !== null && (type === "object" || type === "function"); -}; -var mathLog2 = Math.log2 || function(x) { - return Math.log(x) * Math.LOG2E; -}; -const search = searchBounds; -const clamp$3 = clamp_1; -const rect = parseRect_1; -const getBounds$4 = arrayBounds; -const pick$6 = pickByAlias; -const defined2 = defined$1; -const flatten$4 = flattenVertexData_1; -const isObj$1 = isObj$2; -const dtype$1 = dtype$3; -const log2 = mathLog2; -const MAX_GROUP_ID = 1073741824; -var quad = function cluster(srcPoints, options) { - if (!options) options = {}; - srcPoints = flatten$4(srcPoints, "float64"); - options = pick$6(options, { - bounds: "range bounds dataBox databox", - maxDepth: "depth maxDepth maxdepth level maxLevel maxlevel levels", - dtype: "type dtype format out dst output destination" - // sort: 'sortBy sortby sort', - // pick: 'pick levelPoint', - // nodeSize: 'node nodeSize minNodeSize minSize size' - }); - let maxDepth = defined2(options.maxDepth, 255); - let bounds = defined2(options.bounds, getBounds$4(srcPoints, 2)); - if (bounds[0] === bounds[2]) bounds[2]++; - if (bounds[1] === bounds[3]) bounds[3]++; - let points = normalize$6(srcPoints, bounds); - let n = srcPoints.length >>> 1; - let ids; - if (!options.dtype) options.dtype = "array"; - if (typeof options.dtype === "string") { - ids = new (dtype$1(options.dtype))(n); - } else if (options.dtype) { - ids = options.dtype; - if (Array.isArray(ids)) ids.length = n; - } - for (let i = 0; i < n; ++i) { - ids[i] = i; - } - let levels = []; - let sublevels = []; - let groups = []; - let offsets = []; - sort(0, 0, 1, ids, 0, 1); - let offset = 0; - for (let level = 0; level < levels.length; level++) { - let levelItems = levels[level]; - if (ids.set) ids.set(levelItems, offset); - else { - for (let i = 0, l = levelItems.length; i < l; i++) { - ids[i + offset] = levelItems[i]; - } - } - let nextOffset = offset + levels[level].length; - offsets[level] = [offset, nextOffset]; - offset = nextOffset; - } - ids.range = range; - return ids; - function sort(x, y, diam, ids2, level, group2) { - if (!ids2.length) return null; - let levelItems = levels[level] || (levels[level] = []); - let levelGroups = groups[level] || (groups[level] = []); - let sublevel = sublevels[level] || (sublevels[level] = []); - let offset2 = levelItems.length; - level++; - if (level > maxDepth || group2 > MAX_GROUP_ID) { - for (let i = 0; i < ids2.length; i++) { - levelItems.push(ids2[i]); - levelGroups.push(group2); - sublevel.push(null, null, null, null); - } - return offset2; - } - levelItems.push(ids2[0]); - levelGroups.push(group2); - if (ids2.length <= 1) { - sublevel.push(null, null, null, null); - return offset2; - } - let d2 = diam * 0.5; - let cx = x + d2, cy = y + d2; - let lolo = [], lohi = [], hilo = [], hihi = []; - for (let i = 1, l = ids2.length; i < l; i++) { - let idx = ids2[i], x2 = points[idx * 2], y2 = points[idx * 2 + 1]; - x2 < cx ? y2 < cy ? lolo.push(idx) : lohi.push(idx) : y2 < cy ? hilo.push(idx) : hihi.push(idx); - } - group2 <<= 2; - sublevel.push( - sort(x, y, d2, lolo, level, group2), - sort(x, cy, d2, lohi, level, group2 + 1), - sort(cx, y, d2, hilo, level, group2 + 2), - sort(cx, cy, d2, hihi, level, group2 + 3) - ); - return offset2; - } - function range(...args) { - let options2; - if (isObj$1(args[args.length - 1])) { - let arg = args.pop(); - if (!args.length && (arg.x != null || arg.l != null || arg.left != null)) { - args = [arg]; - options2 = {}; - } - options2 = pick$6(arg, { - level: "level maxLevel", - d: "d diam diameter r radius px pxSize pixel pixelSize maxD size minSize", - lod: "lod details ranges offsets" - }); - } else { - options2 = {}; - } - if (!args.length) args = bounds; - let box = rect(...args); - let [minX, minY, maxX, maxY2] = [ - Math.min(box.x, box.x + box.width), - Math.min(box.y, box.y + box.height), - Math.max(box.x, box.x + box.width), - Math.max(box.y, box.y + box.height) - ]; - let [nminX, nminY, nmaxX, nmaxY] = normalize$6([minX, minY, maxX, maxY2], bounds); - let maxLevel = defined2(options2.level, levels.length); - if (options2.d != null) { - let d; - if (typeof options2.d === "number") d = [options2.d, options2.d]; - else if (options2.d.length) d = options2.d; - maxLevel = Math.min( - Math.max( - Math.ceil(-log2(Math.abs(d[0]) / (bounds[2] - bounds[0]))), - Math.ceil(-log2(Math.abs(d[1]) / (bounds[3] - bounds[1]))) - ), - maxLevel - ); - } - maxLevel = Math.min(maxLevel, levels.length); - if (options2.lod) { - return lod(nminX, nminY, nmaxX, nmaxY, maxLevel); - } - let selection = []; - select3(0, 0, 1, 0, 0, 1); - function select3(lox, loy, d, level, from, to) { - if (from === null || to === null) return; - let hix = lox + d; - let hiy = loy + d; - if (nminX > hix || nminY > hiy || nmaxX < lox || nmaxY < loy) return; - if (level >= maxLevel) return; - if (from === to) return; - let levelItems = levels[level]; - if (to === void 0) to = levelItems.length; - for (let i = from; i < to; i++) { - let id = levelItems[i]; - let px2 = srcPoints[id * 2]; - let py = srcPoints[id * 2 + 1]; - if (px2 >= minX && px2 <= maxX && py >= minY && py <= maxY2) { - selection.push(id); - } - } - let offsets2 = sublevels[level]; - let off0 = offsets2[from * 4 + 0]; - let off1 = offsets2[from * 4 + 1]; - let off2 = offsets2[from * 4 + 2]; - let off3 = offsets2[from * 4 + 3]; - let end = nextOffset(offsets2, from + 1); - let d2 = d * 0.5; - let nextLevel = level + 1; - select3(lox, loy, d2, nextLevel, off0, off1 || off2 || off3 || end); - select3(lox, loy + d2, d2, nextLevel, off1, off2 || off3 || end); - select3(lox + d2, loy, d2, nextLevel, off2, off3 || end); - select3(lox + d2, loy + d2, d2, nextLevel, off3, end); - } - function nextOffset(offsets2, from) { - let offset2 = null, i = 0; - while (offset2 === null) { - offset2 = offsets2[from * 4 + i]; - i++; - if (i > offsets2.length) return null; - } - return offset2; - } - return selection; - } - function lod(lox, loy, hix, hiy, maxLevel) { - let ranges = []; - for (let level = 0; level < maxLevel; level++) { - let levelGroups = groups[level]; - let from = offsets[level][0]; - let levelGroupStart = group(lox, loy, level); - let levelGroupEnd = group(hix, hiy, level); - let startOffset = search.ge(levelGroups, levelGroupStart); - let endOffset = search.gt(levelGroups, levelGroupEnd, startOffset, levelGroups.length - 1); - ranges[level] = [startOffset + from, endOffset + from]; - } - return ranges; - } - function group(x, y, level) { - let group2 = 1; - let cx = 0.5, cy = 0.5; - let diam = 0.5; - for (let i = 0; i < level; i++) { - group2 <<= 2; - group2 += x < cx ? y < cy ? 0 : 1 : y < cy ? 2 : 3; - diam *= 0.5; - cx += x < cx ? -diam : diam; - cy += y < cy ? -diam : diam; - } - return group2; - } -}; -function normalize$6(pts, bounds) { - let [lox, loy, hix, hiy] = bounds; - let scaleX = 1 / (hix - lox); - let scaleY = 1 / (hiy - loy); - let result = new Array(pts.length); - for (let i = 0, n = pts.length / 2; i < n; i++) { - result[2 * i] = clamp$3((pts[2 * i] - lox) * scaleX, 0, 1); - result[2 * i + 1] = clamp$3((pts[2 * i + 1] - loy) * scaleY, 0, 1); - } - return result; -} -var pointCluster = quad; -var absSvgPath = absolutize; -function absolutize(path) { - var startX = 0; - var startY = 0; - var x = 0; - var y = 0; - return path.map(function(seg) { - seg = seg.slice(); - var type = seg[0]; - var command2 = type.toUpperCase(); - if (type != command2) { - seg[0] = command2; - switch (type) { - case "a": - seg[6] += x; - seg[7] += y; - break; - case "v": - seg[1] += y; - break; - case "h": - seg[1] += x; - break; - default: - for (var i = 1; i < seg.length; ) { - seg[i++] += x; - seg[i++] += y; - } - } - } - switch (command2) { - case "Z": - x = startX; - y = startY; - break; - case "H": - x = seg[1]; - break; - case "V": - y = seg[1]; - break; - case "M": - x = startX = seg[1]; - y = startY = seg[2]; - break; - default: - x = seg[seg.length - 2]; - y = seg[seg.length - 1]; - } - return seg; - }); -} -var _slicedToArray$1 = /* @__PURE__ */ function() { - function sliceIterator(arr, i) { - var _arr = []; - var _n = true; - var _d = false; - var _e = void 0; - try { - for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { - _arr.push(_s.value); - if (i && _arr.length === i) break; - } - } catch (err) { - _d = true; - _e = err; - } finally { - try { - if (!_n && _i["return"]) _i["return"](); - } finally { - if (_d) throw _e; - } - } - return _arr; - } - return function(arr, i) { - if (Array.isArray(arr)) { - return arr; - } else if (Symbol.iterator in Object(arr)) { - return sliceIterator(arr, i); - } else { - throw new TypeError("Invalid attempt to destructure non-iterable instance"); - } - }; -}(); -var TAU = Math.PI * 2; -var mapToEllipse = function mapToEllipse2(_ref, rx, ry, cosphi, sinphi, centerx, centery) { - var x = _ref.x, y = _ref.y; - x *= rx; - y *= ry; - var xp = cosphi * x - sinphi * y; - var yp = sinphi * x + cosphi * y; - return { - x: xp + centerx, - y: yp + centery - }; -}; -var approxUnitArc = function approxUnitArc2(ang1, ang2) { - var a = ang2 === 1.5707963267948966 ? 0.551915024494 : ang2 === -1.5707963267948966 ? -0.551915024494 : 4 / 3 * Math.tan(ang2 / 4); - var x1 = Math.cos(ang1); - var y1 = Math.sin(ang1); - var x2 = Math.cos(ang1 + ang2); - var y2 = Math.sin(ang1 + ang2); - return [{ - x: x1 - y1 * a, - y: y1 + x1 * a - }, { - x: x2 + y2 * a, - y: y2 - x2 * a - }, { - x: x2, - y: y2 - }]; -}; -var vectorAngle = function vectorAngle2(ux, uy, vx, vy) { - var sign2 = ux * vy - uy * vx < 0 ? -1 : 1; - var dot2 = ux * vx + uy * vy; - if (dot2 > 1) { - dot2 = 1; - } - if (dot2 < -1) { - dot2 = -1; - } - return sign2 * Math.acos(dot2); -}; -var getArcCenter = function getArcCenter2(px2, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp) { - var rxsq = Math.pow(rx, 2); - var rysq = Math.pow(ry, 2); - var pxpsq = Math.pow(pxp, 2); - var pypsq = Math.pow(pyp, 2); - var radicant = rxsq * rysq - rxsq * pypsq - rysq * pxpsq; - if (radicant < 0) { - radicant = 0; - } - radicant /= rxsq * pypsq + rysq * pxpsq; - radicant = Math.sqrt(radicant) * (largeArcFlag === sweepFlag ? -1 : 1); - var centerxp = radicant * rx / ry * pyp; - var centeryp = radicant * -ry / rx * pxp; - var centerx = cosphi * centerxp - sinphi * centeryp + (px2 + cx) / 2; - var centery = sinphi * centerxp + cosphi * centeryp + (py + cy) / 2; - var vx1 = (pxp - centerxp) / rx; - var vy1 = (pyp - centeryp) / ry; - var vx2 = (-pxp - centerxp) / rx; - var vy2 = (-pyp - centeryp) / ry; - var ang1 = vectorAngle(1, 0, vx1, vy1); - var ang2 = vectorAngle(vx1, vy1, vx2, vy2); - if (sweepFlag === 0 && ang2 > 0) { - ang2 -= TAU; - } - if (sweepFlag === 1 && ang2 < 0) { - ang2 += TAU; - } - return [centerx, centery, ang1, ang2]; -}; -var arcToBezier = function arcToBezier2(_ref2) { - var px2 = _ref2.px, py = _ref2.py, cx = _ref2.cx, cy = _ref2.cy, rx = _ref2.rx, ry = _ref2.ry, _ref2$xAxisRotation = _ref2.xAxisRotation, xAxisRotation = _ref2$xAxisRotation === void 0 ? 0 : _ref2$xAxisRotation, _ref2$largeArcFlag = _ref2.largeArcFlag, largeArcFlag = _ref2$largeArcFlag === void 0 ? 0 : _ref2$largeArcFlag, _ref2$sweepFlag = _ref2.sweepFlag, sweepFlag = _ref2$sweepFlag === void 0 ? 0 : _ref2$sweepFlag; - var curves = []; - if (rx === 0 || ry === 0) { - return []; - } - var sinphi = Math.sin(xAxisRotation * TAU / 360); - var cosphi = Math.cos(xAxisRotation * TAU / 360); - var pxp = cosphi * (px2 - cx) / 2 + sinphi * (py - cy) / 2; - var pyp = -sinphi * (px2 - cx) / 2 + cosphi * (py - cy) / 2; - if (pxp === 0 && pyp === 0) { - return []; - } - rx = Math.abs(rx); - ry = Math.abs(ry); - var lambda = Math.pow(pxp, 2) / Math.pow(rx, 2) + Math.pow(pyp, 2) / Math.pow(ry, 2); - if (lambda > 1) { - rx *= Math.sqrt(lambda); - ry *= Math.sqrt(lambda); - } - var _getArcCenter = getArcCenter(px2, py, cx, cy, rx, ry, largeArcFlag, sweepFlag, sinphi, cosphi, pxp, pyp), _getArcCenter2 = _slicedToArray$1(_getArcCenter, 4), centerx = _getArcCenter2[0], centery = _getArcCenter2[1], ang1 = _getArcCenter2[2], ang2 = _getArcCenter2[3]; - var ratio = Math.abs(ang2) / (TAU / 4); - if (Math.abs(1 - ratio) < 1e-7) { - ratio = 1; - } - var segments = Math.max(Math.ceil(ratio), 1); - ang2 /= segments; - for (var i = 0; i < segments; i++) { - curves.push(approxUnitArc(ang1, ang2)); - ang1 += ang2; - } - return curves.map(function(curve) { - var _mapToEllipse = mapToEllipse(curve[0], rx, ry, cosphi, sinphi, centerx, centery), x1 = _mapToEllipse.x, y1 = _mapToEllipse.y; - var _mapToEllipse2 = mapToEllipse(curve[1], rx, ry, cosphi, sinphi, centerx, centery), x2 = _mapToEllipse2.x, y2 = _mapToEllipse2.y; - var _mapToEllipse3 = mapToEllipse(curve[2], rx, ry, cosphi, sinphi, centerx, centery), x = _mapToEllipse3.x, y = _mapToEllipse3.y; - return { x1, y1, x2, y2, x, y }; - }); -}; -const modules = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - default: arcToBezier -}, Symbol.toStringTag, { value: "Module" })); -const require$$0$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(modules); -var normalizeSvgPath$1 = normalize$5; -var arcToCurve = require$$0$1; -function normalize$5(path) { - var prev; - var result = []; - var bezierX = 0; - var bezierY = 0; - var startX = 0; - var startY = 0; - var quadX = null; - var quadY = null; - var x = 0; - var y = 0; - for (var i = 0, len = path.length; i < len; i++) { - var seg = path[i]; - var command2 = seg[0]; - switch (command2) { - case "M": - startX = seg[1]; - startY = seg[2]; - break; - case "A": - var curves = arcToCurve({ - px: x, - py: y, - cx: seg[6], - cy: seg[7], - rx: seg[1], - ry: seg[2], - xAxisRotation: seg[3], - largeArcFlag: seg[4], - sweepFlag: seg[5] - }); - if (!curves.length) continue; - for (var j = 0, c; j < curves.length; j++) { - c = curves[j]; - seg = ["C", c.x1, c.y1, c.x2, c.y2, c.x, c.y]; - if (j < curves.length - 1) result.push(seg); - } - break; - case "S": - var cx = x; - var cy = y; - if (prev == "C" || prev == "S") { - cx += cx - bezierX; - cy += cy - bezierY; - } - seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]]; - break; - case "T": - if (prev == "Q" || prev == "T") { - quadX = x * 2 - quadX; - quadY = y * 2 - quadY; - } else { - quadX = x; - quadY = y; - } - seg = quadratic$1(x, y, quadX, quadY, seg[1], seg[2]); - break; - case "Q": - quadX = seg[1]; - quadY = seg[2]; - seg = quadratic$1(x, y, seg[1], seg[2], seg[3], seg[4]); - break; - case "L": - seg = line$1(x, y, seg[1], seg[2]); - break; - case "H": - seg = line$1(x, y, seg[1], y); - break; - case "V": - seg = line$1(x, y, x, seg[1]); - break; - case "Z": - seg = line$1(x, y, startX, startY); - break; - } - prev = command2; - x = seg[seg.length - 2]; - y = seg[seg.length - 1]; - if (seg.length > 4) { - bezierX = seg[seg.length - 4]; - bezierY = seg[seg.length - 3]; - } else { - bezierX = x; - bezierY = y; - } - result.push(seg); - } - return result; -} -function line$1(x1, y1, x2, y2) { - return ["C", x1, y1, x2, y2, x2, y2]; -} -function quadratic$1(x1, y1, cx, cy, x2, y2) { - return [ - "C", - x1 / 3 + 2 / 3 * cx, - y1 / 3 + 2 / 3 * cy, - x2 / 3 + 2 / 3 * cx, - y2 / 3 + 2 / 3 * cy, - x2, - y2 - ]; -} -var isSvgPath$2 = function isPath(str2) { - if (typeof str2 !== "string") return false; - str2 = str2.trim(); - if (/^[mzlhvcsqta]\s*[-+.0-9][^mlhvzcsqta]+/i.test(str2) && /[\dz]$/i.test(str2) && str2.length > 4) return true; - return false; -}; -var parse$4 = parseSvgPath; -var abs$1 = absSvgPath; -var normalize$4 = normalizeSvgPath$1; -var isSvgPath$1 = isSvgPath$2; -var svgPathBounds = pathBounds$1; -function pathBounds$1(path) { - if (Array.isArray(path) && path.length === 1 && typeof path[0] === "string") path = path[0]; - if (typeof path === "string") { - if (!isSvgPath$1(path)) throw Error("String is not an SVG path."); - path = parse$4(path); - } - if (!Array.isArray(path)) throw Error("Argument should be a string or an array of path segments."); - path = abs$1(path); - path = normalize$4(path); - if (!path.length) return [0, 0, 0, 0]; - var bounds = [Infinity, Infinity, -Infinity, -Infinity]; - for (var i = 0, l = path.length; i < l; i++) { - var points = path[i].slice(1); - for (var j = 0; j < points.length; j += 2) { - if (points[j + 0] < bounds[0]) bounds[0] = points[j + 0]; - if (points[j + 1] < bounds[1]) bounds[1] = points[j + 1]; - if (points[j + 0] > bounds[2]) bounds[2] = points[j + 0]; - if (points[j + 1] > bounds[3]) bounds[3] = points[j + 1]; - } - } - return bounds; -} -var π = Math.PI; -var _120 = radians$1(120); -var normalizeSvgPath = normalize$3; -function normalize$3(path) { - var prev; - var result = []; - var bezierX = 0; - var bezierY = 0; - var startX = 0; - var startY = 0; - var quadX = null; - var quadY = null; - var x = 0; - var y = 0; - for (var i = 0, len = path.length; i < len; i++) { - var seg = path[i]; - var command2 = seg[0]; - switch (command2) { - case "M": - startX = seg[1]; - startY = seg[2]; - break; - case "A": - seg = arc(x, y, seg[1], seg[2], radians$1(seg[3]), seg[4], seg[5], seg[6], seg[7]); - seg.unshift("C"); - if (seg.length > 7) { - result.push(seg.splice(0, 7)); - seg.unshift("C"); - } - break; - case "S": - var cx = x; - var cy = y; - if (prev == "C" || prev == "S") { - cx += cx - bezierX; - cy += cy - bezierY; - } - seg = ["C", cx, cy, seg[1], seg[2], seg[3], seg[4]]; - break; - case "T": - if (prev == "Q" || prev == "T") { - quadX = x * 2 - quadX; - quadY = y * 2 - quadY; - } else { - quadX = x; - quadY = y; - } - seg = quadratic(x, y, quadX, quadY, seg[1], seg[2]); - break; - case "Q": - quadX = seg[1]; - quadY = seg[2]; - seg = quadratic(x, y, seg[1], seg[2], seg[3], seg[4]); - break; - case "L": - seg = line(x, y, seg[1], seg[2]); - break; - case "H": - seg = line(x, y, seg[1], y); - break; - case "V": - seg = line(x, y, x, seg[1]); - break; - case "Z": - seg = line(x, y, startX, startY); - break; - } - prev = command2; - x = seg[seg.length - 2]; - y = seg[seg.length - 1]; - if (seg.length > 4) { - bezierX = seg[seg.length - 4]; - bezierY = seg[seg.length - 3]; - } else { - bezierX = x; - bezierY = y; - } - result.push(seg); - } - return result; -} -function line(x1, y1, x2, y2) { - return ["C", x1, y1, x2, y2, x2, y2]; -} -function quadratic(x1, y1, cx, cy, x2, y2) { - return [ - "C", - x1 / 3 + 2 / 3 * cx, - y1 / 3 + 2 / 3 * cy, - x2 / 3 + 2 / 3 * cx, - y2 / 3 + 2 / 3 * cy, - x2, - y2 - ]; -} -function arc(x1, y1, rx, ry, angle, large_arc_flag, sweep_flag, x2, y2, recursive) { - if (!recursive) { - var xy = rotate(x1, y1, -angle); - x1 = xy.x; - y1 = xy.y; - xy = rotate(x2, y2, -angle); - x2 = xy.x; - y2 = xy.y; - var x = (x1 - x2) / 2; - var y = (y1 - y2) / 2; - var h = x * x / (rx * rx) + y * y / (ry * ry); - if (h > 1) { - h = Math.sqrt(h); - rx = h * rx; - ry = h * ry; - } - var rx2 = rx * rx; - var ry2 = ry * ry; - var k = (large_arc_flag == sweep_flag ? -1 : 1) * Math.sqrt(Math.abs((rx2 * ry2 - rx2 * y * y - ry2 * x * x) / (rx2 * y * y + ry2 * x * x))); - if (k == Infinity) k = 1; - var cx = k * rx * y / ry + (x1 + x2) / 2; - var cy = k * -ry * x / rx + (y1 + y2) / 2; - var f1 = Math.asin(((y1 - cy) / ry).toFixed(9)); - var f2 = Math.asin(((y2 - cy) / ry).toFixed(9)); - f1 = x1 < cx ? π - f1 : f1; - f2 = x2 < cx ? π - f2 : f2; - if (f1 < 0) f1 = π * 2 + f1; - if (f2 < 0) f2 = π * 2 + f2; - if (sweep_flag && f1 > f2) f1 = f1 - π * 2; - if (!sweep_flag && f2 > f1) f2 = f2 - π * 2; - } else { - f1 = recursive[0]; - f2 = recursive[1]; - cx = recursive[2]; - cy = recursive[3]; - } - if (Math.abs(f2 - f1) > _120) { - var f2old = f2; - var x2old = x2; - var y2old = y2; - f2 = f1 + _120 * (sweep_flag && f2 > f1 ? 1 : -1); - x2 = cx + rx * Math.cos(f2); - y2 = cy + ry * Math.sin(f2); - var res = arc(x2, y2, rx, ry, angle, 0, sweep_flag, x2old, y2old, [f2, f2old, cx, cy]); - } - var t = Math.tan((f2 - f1) / 4); - var hx = 4 / 3 * rx * t; - var hy = 4 / 3 * ry * t; - var curve = [ - 2 * x1 - (x1 + hx * Math.sin(f1)), - 2 * y1 - (y1 - hy * Math.cos(f1)), - x2 + hx * Math.sin(f2), - y2 - hy * Math.cos(f2), - x2, - y2 - ]; - if (recursive) return curve; - if (res) curve = curve.concat(res); - for (var i = 0; i < curve.length; ) { - var rot = rotate(curve[i], curve[i + 1], angle); - curve[i++] = rot.x; - curve[i++] = rot.y; - } - return curve; -} -function rotate(x, y, rad) { - return { - x: x * Math.cos(rad) - y * Math.sin(rad), - y: x * Math.sin(rad) + y * Math.cos(rad) - }; -} -function radians$1(degress) { - return degress * (π / 180); -} -var abs = absSvgPath; -var normalize$2 = normalizeSvgPath; -var methods = { - "M": "moveTo", - "C": "bezierCurveTo" -}; -var drawSvgPath = function(context2, segments) { - context2.beginPath(); - normalize$2(abs(segments)).forEach( - function(segment2) { - var command2 = segment2[0]; - var args = segment2.slice(1); - context2[methods[command2]].apply(context2, args); - } - ); - context2.closePath(); -}; -var bitmapSdf$1 = calcSDF; -var INF = 1e20; -function calcSDF(src2, options) { - if (!options) options = {}; - var cutoff = options.cutoff == null ? 0.25 : options.cutoff; - var radius = options.radius == null ? 8 : options.radius; - var channel = options.channel || 0; - var w, h, size, data, intData, stride, ctx2, canvas2, imgData, i, l; - if (ArrayBuffer.isView(src2) || Array.isArray(src2)) { - if (!options.width || !options.height) throw Error("For raw data width and height should be provided by options"); - w = options.width, h = options.height; - data = src2; - if (!options.stride) stride = Math.floor(src2.length / w / h); - else stride = options.stride; - } else { - if (window.HTMLCanvasElement && src2 instanceof window.HTMLCanvasElement) { - canvas2 = src2; - ctx2 = canvas2.getContext("2d"); - w = canvas2.width, h = canvas2.height; - imgData = ctx2.getImageData(0, 0, w, h); - data = imgData.data; - stride = 4; - } else if (window.CanvasRenderingContext2D && src2 instanceof window.CanvasRenderingContext2D) { - canvas2 = src2.canvas; - ctx2 = src2; - w = canvas2.width, h = canvas2.height; - imgData = ctx2.getImageData(0, 0, w, h); - data = imgData.data; - stride = 4; - } else if (window.ImageData && src2 instanceof window.ImageData) { - imgData = src2; - w = src2.width, h = src2.height; - data = imgData.data; - stride = 4; - } - } - size = Math.max(w, h); - if (window.Uint8ClampedArray && data instanceof window.Uint8ClampedArray || window.Uint8Array && data instanceof window.Uint8Array) { - intData = data; - data = Array(w * h); - for (i = 0, l = Math.floor(intData.length / stride); i < l; i++) { - data[i] = intData[i * stride + channel] / 255; - } - } else { - if (stride !== 1) throw Error("Raw data can have only 1 value per pixel"); - } - var gridOuter = Array(w * h); - var gridInner = Array(w * h); - var f = Array(size); - var d = Array(size); - var z = Array(size + 1); - var v = Array(size); - for (i = 0, l = w * h; i < l; i++) { - var a = data[i]; - gridOuter[i] = a === 1 ? 0 : a === 0 ? INF : Math.pow(Math.max(0, 0.5 - a), 2); - gridInner[i] = a === 1 ? INF : a === 0 ? 0 : Math.pow(Math.max(0, a - 0.5), 2); - } - edt(gridOuter, w, h, f, d, v, z); - edt(gridInner, w, h, f, d, v, z); - var dist2 = window.Float32Array ? new Float32Array(w * h) : new Array(w * h); - for (i = 0, l = w * h; i < l; i++) { - dist2[i] = Math.min(Math.max(1 - ((gridOuter[i] - gridInner[i]) / radius + cutoff), 0), 1); - } - return dist2; -} -function edt(data, width, height, f, d, v, z) { - for (var x = 0; x < width; x++) { - for (var y = 0; y < height; y++) { - f[y] = data[y * width + x]; - } - edt1d(f, d, v, z, height); - for (y = 0; y < height; y++) { - data[y * width + x] = d[y]; - } - } - for (y = 0; y < height; y++) { - for (x = 0; x < width; x++) { - f[x] = data[y * width + x]; - } - edt1d(f, d, v, z, width); - for (x = 0; x < width; x++) { - data[y * width + x] = Math.sqrt(d[x]); - } - } -} -function edt1d(f, d, v, z, n) { - v[0] = 0; - z[0] = -1e20; - z[1] = 1e20; - for (var q = 1, k = 0; q < n; q++) { - var s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); - while (s <= z[k]) { - k--; - s = (f[q] + q * q - (f[v[k]] + v[k] * v[k])) / (2 * q - 2 * v[k]); - } - k++; - v[k] = q; - z[k] = s; - z[k + 1] = 1e20; - } - for (q = 0, k = 0; q < n; q++) { - while (z[k + 1] < q) k++; - d[q] = (q - v[k]) * (q - v[k]) + f[v[k]]; - } -} -var pathBounds = svgPathBounds; -var parsePath = parseSvgPath; -var drawPath = drawSvgPath; -var isSvgPath = isSvgPath$2; -var bitmapSdf = bitmapSdf$1; -var canvas$1 = document.createElement("canvas"); -var ctx$1 = canvas$1.getContext("2d"); -var svgPathSdf = pathSdf; -function pathSdf(path, options) { - if (!isSvgPath(path)) throw Error("Argument should be valid svg path string"); - if (!options) options = {}; - var w, h; - if (options.shape) { - w = options.shape[0]; - h = options.shape[1]; - } else { - w = canvas$1.width = options.w || options.width || 200; - h = canvas$1.height = options.h || options.height || 200; - } - var size = Math.min(w, h); - var stroke = options.stroke || 0; - var viewbox = options.viewbox || options.viewBox || pathBounds(path); - var scale2 = [w / (viewbox[2] - viewbox[0]), h / (viewbox[3] - viewbox[1])]; - var maxScale = Math.min(scale2[0] || 0, scale2[1] || 0) / 2; - ctx$1.fillStyle = "black"; - ctx$1.fillRect(0, 0, w, h); - ctx$1.fillStyle = "white"; - if (stroke) { - if (typeof stroke != "number") stroke = 1; - if (stroke > 0) { - ctx$1.strokeStyle = "white"; - } else { - ctx$1.strokeStyle = "black"; - } - ctx$1.lineWidth = Math.abs(stroke); - } - ctx$1.translate(w * 0.5, h * 0.5); - ctx$1.scale(maxScale, maxScale); - if (isPath2DSupported()) { - var path2d = new Path2D(path); - ctx$1.fill(path2d); - stroke && ctx$1.stroke(path2d); - } else { - var segments = parsePath(path); - drawPath(ctx$1, segments); - ctx$1.fill(); - stroke && ctx$1.stroke(); - } - ctx$1.setTransform(1, 0, 0, 1, 0, 0); - var data = bitmapSdf(ctx$1, { - cutoff: options.cutoff != null ? options.cutoff : 0.5, - radius: options.radius != null ? options.radius : size * 0.5 - }); - return data; -} -var path2DSupported; -function isPath2DSupported() { - if (path2DSupported != null) return path2DSupported; - var ctx2 = document.createElement("canvas").getContext("2d"); - ctx2.canvas.width = ctx2.canvas.height = 1; - if (!window.Path2D) return path2DSupported = false; - var path = new Path2D("M0,0h1v1h-1v-1Z"); - ctx2.fillStyle = "black"; - ctx2.fill(path); - var idata = ctx2.getImageData(0, 0, 1, 1); - return path2DSupported = idata && idata.data && idata.data[3] === 255; -} -var colorName = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; -var names = colorName; -var colorParse = parse$3; -var baseHues = { - red: 0, - orange: 60, - yellow: 120, - green: 180, - blue: 240, - purple: 300 -}; -function parse$3(cstr) { - var m, parts = [], alpha = 1, space; - if (typeof cstr === "string") { - cstr = cstr.toLowerCase(); - if (names[cstr]) { - parts = names[cstr].slice(); - space = "rgb"; - } else if (cstr === "transparent") { - alpha = 0; - space = "rgb"; - parts = [0, 0, 0]; - } else if (/^#[A-Fa-f0-9]+$/.test(cstr)) { - var base = cstr.slice(1); - var size = base.length; - var isShort = size <= 4; - alpha = 1; - if (isShort) { - parts = [ - parseInt(base[0] + base[0], 16), - parseInt(base[1] + base[1], 16), - parseInt(base[2] + base[2], 16) - ]; - if (size === 4) { - alpha = parseInt(base[3] + base[3], 16) / 255; - } - } else { - parts = [ - parseInt(base[0] + base[1], 16), - parseInt(base[2] + base[3], 16), - parseInt(base[4] + base[5], 16) - ]; - if (size === 8) { - alpha = parseInt(base[6] + base[7], 16) / 255; - } - } - if (!parts[0]) parts[0] = 0; - if (!parts[1]) parts[1] = 0; - if (!parts[2]) parts[2] = 0; - space = "rgb"; - } else if (m = /^((?:rgb|hs[lvb]|hwb|cmyk?|xy[zy]|gray|lab|lchu?v?|[ly]uv|lms)a?)\s*\(([^\)]*)\)/.exec(cstr)) { - var name2 = m[1]; - var isRGB = name2 === "rgb"; - var base = name2.replace(/a$/, ""); - space = base; - var size = base === "cmyk" ? 4 : base === "gray" ? 1 : 3; - parts = m[2].trim().split(/\s*[,\/]\s*|\s+/).map(function(x, i) { - if (/%$/.test(x)) { - if (i === size) return parseFloat(x) / 100; - if (base === "rgb") return parseFloat(x) * 255 / 100; - return parseFloat(x); - } else if (base[i] === "h") { - if (/deg$/.test(x)) { - return parseFloat(x); - } else if (baseHues[x] !== void 0) { - return baseHues[x]; - } - } - return parseFloat(x); - }); - if (name2 === base) parts.push(1); - alpha = isRGB ? 1 : parts[size] === void 0 ? 1 : parts[size]; - parts = parts.slice(0, size); - } else if (cstr.length > 10 && /[0-9](?:\s|\/)/.test(cstr)) { - parts = cstr.match(/([0-9]+)/g).map(function(value2) { - return parseFloat(value2); - }); - space = cstr.match(/([a-z])/ig).join("").toLowerCase(); - } - } else if (!isNaN(cstr)) { - space = "rgb"; - parts = [cstr >>> 16, (cstr & 65280) >>> 8, cstr & 255]; - } else if (Array.isArray(cstr) || cstr.length) { - parts = [cstr[0], cstr[1], cstr[2]]; - space = "rgb"; - alpha = cstr.length === 4 ? cstr[3] : 1; - } else if (cstr instanceof Object) { - if (cstr.r != null || cstr.red != null || cstr.R != null) { - space = "rgb"; - parts = [ - cstr.r || cstr.red || cstr.R || 0, - cstr.g || cstr.green || cstr.G || 0, - cstr.b || cstr.blue || cstr.B || 0 - ]; - } else { - space = "hsl"; - parts = [ - cstr.h || cstr.hue || cstr.H || 0, - cstr.s || cstr.saturation || cstr.S || 0, - cstr.l || cstr.lightness || cstr.L || cstr.b || cstr.brightness - ]; - } - alpha = cstr.a || cstr.alpha || cstr.opacity || 1; - if (cstr.opacity != null) alpha /= 100; - } - return { - space, - values: parts, - alpha - }; -} -var rgb$3 = {}; -var rgb$2 = rgb$3; -var hsl$4 = { - name: "hsl", - min: [0, 0, 0], - max: [360, 100, 100], - channel: ["hue", "saturation", "lightness"], - alias: ["HSL"], - rgb: function(hsl2) { - var h = hsl2[0] / 360, s = hsl2[1] / 100, l = hsl2[2] / 100, t12, t22, t32, rgb2, val; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } - if (l < 0.5) { - t22 = l * (1 + s); - } else { - t22 = l + s - l * s; - } - t12 = 2 * l - t22; - rgb2 = [0, 0, 0]; - for (var i = 0; i < 3; i++) { - t32 = h + 1 / 3 * -(i - 1); - if (t32 < 0) { - t32++; - } else if (t32 > 1) { - t32--; - } - if (6 * t32 < 1) { - val = t12 + (t22 - t12) * 6 * t32; - } else if (2 * t32 < 1) { - val = t22; - } else if (3 * t32 < 2) { - val = t12 + (t22 - t12) * (2 / 3 - t32) * 6; - } else { - val = t12; - } - rgb2[i] = val * 255; - } - return rgb2; - } -}; -rgb$2.hsl = function(rgb2) { - var r = rgb2[0] / 255, g = rgb2[1] / 255, b = rgb2[2] / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), delta2 = max - min, h, s, l; - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta2; - } else if (g === max) { - h = 2 + (b - r) / delta2; - } else if (b === max) { - h = 4 + (r - g) / delta2; - } - h = Math.min(h * 60, 360); - if (h < 0) { - h += 360; - } - l = (min + max) / 2; - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta2 / (max + min); - } else { - s = delta2 / (2 - max - min); - } - return [h, s * 100, l * 100]; -}; -var parse$2 = colorParse; -var hsl$3 = hsl$4; -var clamp$2 = clamp_1; -var colorRgba = function rgba(color2) { - var values; - var parsed = parse$2(color2); - if (!parsed.space) return []; - values = Array(3); - values[0] = clamp$2(parsed.values[0], 0, 255); - values[1] = clamp$2(parsed.values[1], 0, 255); - values[2] = clamp$2(parsed.values[2], 0, 255); - if (parsed.space[0] === "h") { - values = hsl$3.rgb(values); - } - values.push(clamp$2(parsed.alpha, 0, 1)); - return values; -}; -var rgba$7 = colorRgba; -var clamp$1 = clamp_1; -var dtype = dtype$3; -var colorNormalize = function normalize(color2, type) { - if (type === "float" || !type) type = "array"; - if (type === "uint") type = "uint8"; - if (type === "uint_clamped") type = "uint8_clamped"; - var Ctor = dtype(type); - var output = new Ctor(4); - var normalize3 = type !== "uint8" && type !== "uint8_clamped"; - if (!color2.length || typeof color2 === "string") { - color2 = rgba$7(color2); - color2[0] /= 255; - color2[1] /= 255; - color2[2] /= 255; - } - if (isInt(color2)) { - output[0] = color2[0]; - output[1] = color2[1]; - output[2] = color2[2]; - output[3] = color2[3] != null ? color2[3] : 255; - if (normalize3) { - output[0] /= 255; - output[1] /= 255; - output[2] /= 255; - output[3] /= 255; - } - return output; - } - if (!normalize3) { - output[0] = clamp$1(Math.floor(color2[0] * 255), 0, 255); - output[1] = clamp$1(Math.floor(color2[1] * 255), 0, 255); - output[2] = clamp$1(Math.floor(color2[2] * 255), 0, 255); - output[3] = color2[3] == null ? 255 : clamp$1(Math.floor(color2[3] * 255), 0, 255); - } else { - output[0] = color2[0]; - output[1] = color2[1]; - output[2] = color2[2]; - output[3] = color2[3] != null ? color2[3] : 1; - } - return output; -}; -function isInt(color2) { - if (color2 instanceof Uint8Array || color2 instanceof Uint8ClampedArray) return true; - if (Array.isArray(color2) && (color2[0] > 1 || color2[0] === 0) && (color2[1] > 1 || color2[1] === 0) && (color2[2] > 1 || color2[2] === 0) && (!color2[3] || color2[3] > 1)) return true; - return false; -} -var isNumeric$1 = fastIsnumeric; -var rgba$6 = colorNormalize; -var Colorscale$1 = colorscale; -var colorDflt = attributes$N.defaultLine; -var isArrayOrTypedArray$1 = array$2.isArrayOrTypedArray; -var colorDfltRgba = rgba$6(colorDflt); -var opacityDflt = 1; -function calculateColor(colorIn, opacityIn) { - var colorOut = colorIn; - colorOut[3] *= opacityIn; - return colorOut; -} -function validateColor(colorIn) { - if (isNumeric$1(colorIn)) return colorDfltRgba; - var colorOut = rgba$6(colorIn); - return colorOut.length ? colorOut : colorDfltRgba; -} -function validateOpacity(opacityIn) { - return isNumeric$1(opacityIn) ? opacityIn : opacityDflt; -} -function formatColor$1(containerIn, opacityIn, len) { - var colorIn = containerIn.color; - if (colorIn && colorIn._inputArray) colorIn = colorIn._inputArray; - var isArrayColorIn = isArrayOrTypedArray$1(colorIn); - var isArrayOpacityIn = isArrayOrTypedArray$1(opacityIn); - var cOpts = Colorscale$1.extractOpts(containerIn); - var colorOut = []; - var sclFunc, getColor, getOpacity, colori, opacityi; - if (cOpts.colorscale !== void 0) { - sclFunc = Colorscale$1.makeColorScaleFuncFromTrace(containerIn); - } else { - sclFunc = validateColor; - } - if (isArrayColorIn) { - getColor = function(c, i2) { - return c[i2] === void 0 ? colorDfltRgba : rgba$6(sclFunc(c[i2])); - }; - } else getColor = validateColor; - if (isArrayOpacityIn) { - getOpacity = function(o, i2) { - return o[i2] === void 0 ? opacityDflt : validateOpacity(o[i2]); - }; - } else getOpacity = validateOpacity; - if (isArrayColorIn || isArrayOpacityIn) { - for (var i = 0; i < len; i++) { - colori = getColor(colorIn, i); - opacityi = getOpacity(opacityIn, i); - colorOut[i] = calculateColor(colori, opacityi); - } - } else colorOut = calculateColor(rgba$6(colorIn), opacityIn); - return colorOut; -} -var gl_format_color = { - formatColor: formatColor$1 -}; -var isNumeric = fastIsnumeric; -var svgSdf = svgPathSdf; -var rgba$5 = colorNormalize; -var Registry$1 = registry; -var Lib$c = libExports; -var isArrayOrTypedArray = Lib$c.isArrayOrTypedArray; -var Drawing$3 = drawingExports; -var AxisIDs$1 = axis_ids; -var formatColor = gl_format_color.formatColor; -var subTypes$2 = subtypes$3; -var makeBubbleSizeFn2 = make_bubble_size_func; -var helpers$7 = helpers$9; -var constants$7 = constants$a; -var DESELECTDIM$1 = interactions.DESELECTDIM; -var TEXTOFFSETSIGN = { - start: 1, - left: 1, - end: -1, - right: -1, - middle: 0, - center: 0, - bottom: 1, - top: -1 -}; -var appendArrayPointValue$1 = helpers$J.appendArrayPointValue; -function convertStyle(gd, trace) { - var i; - var opts = { - marker: void 0, - markerSel: void 0, - markerUnsel: void 0, - line: void 0, - fill: void 0, - errorX: void 0, - errorY: void 0, - text: void 0, - textSel: void 0, - textUnsel: void 0 - }; - var plotGlPixelRatio = gd._context.plotGlPixelRatio; - if (trace.visible !== true) return opts; - if (subTypes$2.hasText(trace)) { - opts.text = convertTextStyle(gd, trace); - opts.textSel = convertTextSelection(gd, trace, trace.selected); - opts.textUnsel = convertTextSelection(gd, trace, trace.unselected); - } - if (subTypes$2.hasMarkers(trace)) { - opts.marker = convertMarkerStyle(gd, trace); - opts.markerSel = convertMarkerSelection(gd, trace, trace.selected); - opts.markerUnsel = convertMarkerSelection(gd, trace, trace.unselected); - if (!trace.unselected && isArrayOrTypedArray(trace.marker.opacity)) { - var mo = trace.marker.opacity; - opts.markerUnsel.opacity = new Array(mo.length); - for (i = 0; i < mo.length; i++) { - opts.markerUnsel.opacity[i] = DESELECTDIM$1 * mo[i]; - } - } - } - if (subTypes$2.hasLines(trace)) { - opts.line = { - overlay: true, - thickness: trace.line.width * plotGlPixelRatio, - color: trace.line.color, - opacity: trace.opacity - }; - var dashes = (constants$7.DASHES[trace.line.dash] || [1]).slice(); - for (i = 0; i < dashes.length; ++i) { - dashes[i] *= trace.line.width * plotGlPixelRatio; - } - opts.line.dashes = dashes; - } - if (trace.error_x && trace.error_x.visible) { - opts.errorX = convertErrorBarStyle(trace, trace.error_x, plotGlPixelRatio); - } - if (trace.error_y && trace.error_y.visible) { - opts.errorY = convertErrorBarStyle(trace, trace.error_y, plotGlPixelRatio); - } - if (!!trace.fill && trace.fill !== "none") { - opts.fill = { - closed: true, - fill: trace.fillcolor, - thickness: 0 - }; - } - return opts; -} -function convertTextStyle(gd, trace) { - var fullLayout = gd._fullLayout; - var count2 = trace._length; - var textfontIn = trace.textfont; - var textpositionIn = trace.textposition; - var textPos = isArrayOrTypedArray(textpositionIn) ? textpositionIn : [textpositionIn]; - var tfc = textfontIn.color; - var tfs = textfontIn.size; - var tff = textfontIn.family; - var tfw = textfontIn.weight; - var tfy = textfontIn.style; - var tfv = textfontIn.variant; - var optsOut = {}; - var i; - var plotGlPixelRatio = gd._context.plotGlPixelRatio; - var texttemplate = trace.texttemplate; - if (texttemplate) { - optsOut.text = []; - var d3locale = fullLayout._d3locale; - var isArray2 = Array.isArray(texttemplate); - var N = isArray2 ? Math.min(texttemplate.length, count2) : count2; - var txt = isArray2 ? function(i2) { - return texttemplate[i2]; - } : function() { - return texttemplate; - }; - for (i = 0; i < N; i++) { - var d = { i }; - var labels = trace._module.formatLabels(d, trace, fullLayout); - var pointValues = {}; - appendArrayPointValue$1(pointValues, trace, i); - var meta = trace._meta || {}; - optsOut.text.push(Lib$c.texttemplateString(txt(i), labels, d3locale, pointValues, d, meta)); - } - } else { - if (isArrayOrTypedArray(trace.text) && trace.text.length < count2) { - optsOut.text = trace.text.slice(); - } else { - optsOut.text = trace.text; - } - } - if (isArrayOrTypedArray(optsOut.text)) { - for (i = optsOut.text.length; i < count2; i++) { - optsOut.text[i] = ""; - } - } - optsOut.opacity = trace.opacity; - optsOut.font = {}; - optsOut.align = []; - optsOut.baseline = []; - for (i = 0; i < textPos.length; i++) { - var tp = textPos[i].split(/\s+/); - switch (tp[1]) { - case "left": - optsOut.align.push("right"); - break; - case "right": - optsOut.align.push("left"); - break; - default: - optsOut.align.push(tp[1]); - } - switch (tp[0]) { - case "top": - optsOut.baseline.push("bottom"); - break; - case "bottom": - optsOut.baseline.push("top"); - break; - default: - optsOut.baseline.push(tp[0]); - } - } - if (isArrayOrTypedArray(tfc)) { - optsOut.color = new Array(count2); - for (i = 0; i < count2; i++) { - optsOut.color[i] = tfc[i]; - } - } else { - optsOut.color = tfc; - } - if (isArrayOrTypedArray(tfs) || Array.isArray(tff) || isArrayOrTypedArray(tfw) || Array.isArray(tfy) || Array.isArray(tfv)) { - optsOut.font = new Array(count2); - for (i = 0; i < count2; i++) { - var fonti = optsOut.font[i] = {}; - fonti.size = (Lib$c.isTypedArray(tfs) ? tfs[i] : isArrayOrTypedArray(tfs) ? isNumeric(tfs[i]) ? tfs[i] : 0 : tfs) * plotGlPixelRatio; - fonti.family = Array.isArray(tff) ? tff[i] : tff; - fonti.weight = weightFallBack(isArrayOrTypedArray(tfw) ? tfw[i] : tfw); - fonti.style = Array.isArray(tfy) ? tfy[i] : tfy; - fonti.variant = Array.isArray(tfv) ? tfv[i] : tfv; - } - } else { - optsOut.font = { - size: tfs * plotGlPixelRatio, - family: tff, - weight: weightFallBack(tfw), - style: tfy, - variant: tfv - }; - } - return optsOut; -} -function weightFallBack(w) { - if (w <= 1e3) { - return w > 500 ? "bold" : "normal"; - } - return w; -} -function convertMarkerStyle(gd, trace) { - var count2 = trace._length; - var optsIn = trace.marker; - var optsOut = {}; - var i; - var multiSymbol = isArrayOrTypedArray(optsIn.symbol); - var multiAngle = isArrayOrTypedArray(optsIn.angle); - var multiColor = isArrayOrTypedArray(optsIn.color); - var multiLineColor = isArrayOrTypedArray(optsIn.line.color); - var multiOpacity = isArrayOrTypedArray(optsIn.opacity); - var multiSize = isArrayOrTypedArray(optsIn.size); - var multiLineWidth = isArrayOrTypedArray(optsIn.line.width); - var isOpen; - if (!multiSymbol) isOpen = helpers$7.isOpenSymbol(optsIn.symbol); - if (multiSymbol || multiColor || multiLineColor || multiOpacity || multiAngle) { - optsOut.symbols = new Array(count2); - optsOut.angles = new Array(count2); - optsOut.colors = new Array(count2); - optsOut.borderColors = new Array(count2); - var symbols = optsIn.symbol; - var angles2 = optsIn.angle; - var colors = formatColor(optsIn, optsIn.opacity, count2); - var borderColors = formatColor(optsIn.line, optsIn.opacity, count2); - if (!isArrayOrTypedArray(borderColors[0])) { - var borderColor = borderColors; - borderColors = Array(count2); - for (i = 0; i < count2; i++) { - borderColors[i] = borderColor; - } - } - if (!isArrayOrTypedArray(colors[0])) { - var color2 = colors; - colors = Array(count2); - for (i = 0; i < count2; i++) { - colors[i] = color2; - } - } - if (!isArrayOrTypedArray(symbols)) { - var symbol = symbols; - symbols = Array(count2); - for (i = 0; i < count2; i++) { - symbols[i] = symbol; - } - } - if (!isArrayOrTypedArray(angles2)) { - var angle = angles2; - angles2 = Array(count2); - for (i = 0; i < count2; i++) { - angles2[i] = angle; - } - } - optsOut.symbols = symbols; - optsOut.angles = angles2; - optsOut.colors = colors; - optsOut.borderColors = borderColors; - for (i = 0; i < count2; i++) { - if (multiSymbol) { - isOpen = helpers$7.isOpenSymbol(optsIn.symbol[i]); - } - if (isOpen) { - borderColors[i] = colors[i].slice(); - colors[i] = colors[i].slice(); - colors[i][3] = 0; - } - } - optsOut.opacity = trace.opacity; - optsOut.markers = new Array(count2); - for (i = 0; i < count2; i++) { - optsOut.markers[i] = getSymbolSdf({ - mx: optsOut.symbols[i], - ma: optsOut.angles[i] - }, trace); - } - } else { - if (isOpen) { - optsOut.color = rgba$5(optsIn.color, "uint8"); - optsOut.color[3] = 0; - optsOut.borderColor = rgba$5(optsIn.color, "uint8"); - } else { - optsOut.color = rgba$5(optsIn.color, "uint8"); - optsOut.borderColor = rgba$5(optsIn.line.color, "uint8"); - } - optsOut.opacity = trace.opacity * optsIn.opacity; - optsOut.marker = getSymbolSdf({ - mx: optsIn.symbol, - ma: optsIn.angle - }, trace); - } - var sizeFactor = 1; - var markerSizeFunc = makeBubbleSizeFn2(trace, sizeFactor); - var s; - if (multiSize || multiLineWidth) { - var sizes2 = optsOut.sizes = new Array(count2); - var borderSizes = optsOut.borderSizes = new Array(count2); - var sizeTotal = 0; - var sizeAvg; - if (multiSize) { - for (i = 0; i < count2; i++) { - sizes2[i] = markerSizeFunc(optsIn.size[i]); - sizeTotal += sizes2[i]; - } - sizeAvg = sizeTotal / count2; - } else { - s = markerSizeFunc(optsIn.size); - for (i = 0; i < count2; i++) { - sizes2[i] = s; - } - } - if (multiLineWidth) { - for (i = 0; i < count2; i++) { - borderSizes[i] = optsIn.line.width[i]; - } - } else { - s = optsIn.line.width; - for (i = 0; i < count2; i++) { - borderSizes[i] = s; - } - } - optsOut.sizeAvg = sizeAvg; - } else { - optsOut.size = markerSizeFunc(optsIn && optsIn.size || 10); - optsOut.borderSizes = markerSizeFunc(optsIn.line.width); - } - return optsOut; -} -function convertMarkerSelection(gd, trace, target) { - var optsIn = trace.marker; - var optsOut = {}; - if (!target) return optsOut; - if (target.marker && target.marker.symbol) { - optsOut = convertMarkerStyle(gd, Lib$c.extendFlat({}, optsIn, target.marker)); - } else if (target.marker) { - if (target.marker.size) optsOut.size = target.marker.size; - if (target.marker.color) optsOut.colors = target.marker.color; - if (target.marker.opacity !== void 0) optsOut.opacity = target.marker.opacity; - } - return optsOut; -} -function convertTextSelection(gd, trace, target) { - var optsOut = {}; - if (!target) return optsOut; - if (target.textfont) { - var optsIn = { - opacity: 1, - text: trace.text, - texttemplate: trace.texttemplate, - textposition: trace.textposition, - textfont: Lib$c.extendFlat({}, trace.textfont) - }; - if (target.textfont) { - Lib$c.extendFlat(optsIn.textfont, target.textfont); - } - optsOut = convertTextStyle(gd, optsIn); - } - return optsOut; -} -function convertErrorBarStyle(trace, target, plotGlPixelRatio) { - var optsOut = { - capSize: target.width * 2 * plotGlPixelRatio, - lineWidth: target.thickness * plotGlPixelRatio, - color: target.color - }; - if (target.copy_ystyle) { - optsOut = trace.error_y; - } - return optsOut; -} -var SYMBOL_SDF_SIZE = constants$7.SYMBOL_SDF_SIZE; -var SYMBOL_SIZE = constants$7.SYMBOL_SIZE; -var SYMBOL_STROKE = constants$7.SYMBOL_STROKE; -var SYMBOL_SDF = {}; -var SYMBOL_SVG_CIRCLE = Drawing$3.symbolFuncs[0](SYMBOL_SIZE * 0.05); -function getSymbolSdf(d, trace) { - var symbol = d.mx; - if (symbol === "circle") return null; - var symbolPath, symbolSdf; - var symbolNumber = Drawing$3.symbolNumber(symbol); - var symbolFunc = Drawing$3.symbolFuncs[symbolNumber % 100]; - var symbolNoDot = !!Drawing$3.symbolNoDot[symbolNumber % 100]; - var symbolNoFill = !!Drawing$3.symbolNoFill[symbolNumber % 100]; - var isDot = helpers$7.isDotSymbol(symbol); - if (d.ma) symbol += "_" + d.ma; - if (SYMBOL_SDF[symbol]) return SYMBOL_SDF[symbol]; - var angle = Drawing$3.getMarkerAngle(d, trace); - if (isDot && !symbolNoDot) { - symbolPath = symbolFunc(SYMBOL_SIZE * 1.1, angle) + SYMBOL_SVG_CIRCLE; - } else { - symbolPath = symbolFunc(SYMBOL_SIZE, angle); - } - symbolSdf = svgSdf(symbolPath, { - w: SYMBOL_SDF_SIZE, - h: SYMBOL_SDF_SIZE, - viewBox: [-SYMBOL_SIZE, -SYMBOL_SIZE, SYMBOL_SIZE, SYMBOL_SIZE], - stroke: symbolNoFill ? SYMBOL_STROKE : -SYMBOL_STROKE - }); - SYMBOL_SDF[symbol] = symbolSdf; - return symbolSdf || null; -} -function convertLinePositions(gd, trace, positions) { - var len = positions.length; - var count2 = len / 2; - var linePositions; - var i; - if (subTypes$2.hasLines(trace) && count2) { - if (trace.line.shape === "hv") { - linePositions = []; - for (i = 0; i < count2 - 1; i++) { - if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN, NaN, NaN, NaN); - } else { - linePositions.push(positions[i * 2], positions[i * 2 + 1]); - if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) { - linePositions.push(positions[i * 2 + 2], positions[i * 2 + 1]); - } else { - linePositions.push(NaN, NaN); - } - } - } - linePositions.push(positions[len - 2], positions[len - 1]); - } else if (trace.line.shape === "hvh") { - linePositions = []; - for (i = 0; i < count2 - 1; i++) { - if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) { - if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) { - linePositions.push(positions[i * 2], positions[i * 2 + 1]); - } else { - linePositions.push(NaN, NaN); - } - linePositions.push(NaN, NaN); - } else { - var midPtX = (positions[i * 2] + positions[i * 2 + 2]) / 2; - linePositions.push( - positions[i * 2], - positions[i * 2 + 1], - midPtX, - positions[i * 2 + 1], - midPtX, - positions[i * 2 + 3] - ); - } - } - linePositions.push(positions[len - 2], positions[len - 1]); - } else if (trace.line.shape === "vhv") { - linePositions = []; - for (i = 0; i < count2 - 1; i++) { - if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1]) || isNaN(positions[i * 2 + 2]) || isNaN(positions[i * 2 + 3])) { - if (!isNaN(positions[i * 2]) && !isNaN(positions[i * 2 + 1])) { - linePositions.push(positions[i * 2], positions[i * 2 + 1]); - } else { - linePositions.push(NaN, NaN); - } - linePositions.push(NaN, NaN); - } else { - var midPtY = (positions[i * 2 + 1] + positions[i * 2 + 3]) / 2; - linePositions.push( - positions[i * 2], - positions[i * 2 + 1], - positions[i * 2], - midPtY, - positions[i * 2 + 2], - midPtY - ); - } - } - linePositions.push(positions[len - 2], positions[len - 1]); - } else if (trace.line.shape === "vh") { - linePositions = []; - for (i = 0; i < count2 - 1; i++) { - if (isNaN(positions[i * 2]) || isNaN(positions[i * 2 + 1])) { - linePositions.push(NaN, NaN, NaN, NaN); - } else { - linePositions.push(positions[i * 2], positions[i * 2 + 1]); - if (!isNaN(positions[i * 2 + 2]) && !isNaN(positions[i * 2 + 3])) { - linePositions.push(positions[i * 2], positions[i * 2 + 3]); - } else { - linePositions.push(NaN, NaN); - } - } - } - linePositions.push(positions[len - 2], positions[len - 1]); - } else { - linePositions = positions; - } - } - var hasNaN = false; - for (i = 0; i < linePositions.length; i++) { - if (isNaN(linePositions[i])) { - hasNaN = true; - break; - } - } - var join = hasNaN || linePositions.length > constants$7.TOO_MANY_POINTS ? "rect" : subTypes$2.hasMarkers(trace) ? "rect" : "round"; - if (hasNaN && trace.connectgaps) { - var lastX = linePositions[0]; - var lastY = linePositions[1]; - for (i = 0; i < linePositions.length; i += 2) { - if (isNaN(linePositions[i]) || isNaN(linePositions[i + 1])) { - linePositions[i] = lastX; - linePositions[i + 1] = lastY; - } else { - lastX = linePositions[i]; - lastY = linePositions[i + 1]; - } - } - } - return { - join, - positions: linePositions - }; -} -function convertErrorBarPositions(gd, trace, positions, x, y) { - var makeComputeError = Registry$1.getComponentMethod("errorbars", "makeComputeError"); - var xa = AxisIDs$1.getFromId(gd, trace.xaxis, "x"); - var ya = AxisIDs$1.getFromId(gd, trace.yaxis, "y"); - var count2 = positions.length / 2; - var out = {}; - function convertOneAxis(coords, ax) { - var axLetter = ax._id.charAt(0); - var opts = trace["error_" + axLetter]; - if (opts && opts.visible && (ax.type === "linear" || ax.type === "log")) { - var computeError = makeComputeError(opts); - var pOffset = { x: 0, y: 1 }[axLetter]; - var eOffset = { x: [0, 1, 2, 3], y: [2, 3, 0, 1] }[axLetter]; - var errors = new Float64Array(4 * count2); - var minShoe = Infinity; - var maxHat = -Infinity; - for (var i = 0, j = 0; i < count2; i++, j += 4) { - var dc = coords[i]; - if (isNumeric(dc)) { - var dl = positions[i * 2 + pOffset]; - var vals = computeError(dc, i); - var lv = vals[0]; - var hv = vals[1]; - if (isNumeric(lv) && isNumeric(hv)) { - var shoe = dc - lv; - var hat = dc + hv; - errors[j + eOffset[0]] = dl - ax.c2l(shoe); - errors[j + eOffset[1]] = ax.c2l(hat) - dl; - errors[j + eOffset[2]] = 0; - errors[j + eOffset[3]] = 0; - minShoe = Math.min(minShoe, dc - lv); - maxHat = Math.max(maxHat, dc + hv); - } - } - } - out[axLetter] = { - positions, - errors, - _bnds: [minShoe, maxHat] - }; - } - } - convertOneAxis(x, xa); - convertOneAxis(y, ya); - return out; -} -function convertTextPosition(gd, trace, textOpts, markerOpts) { - var count2 = trace._length; - var out = {}; - var i; - if (subTypes$2.hasMarkers(trace)) { - var fontOpts = textOpts.font; - var align3 = textOpts.align; - var baseline = textOpts.baseline; - out.offset = new Array(count2); - for (i = 0; i < count2; i++) { - var ms = markerOpts.sizes ? markerOpts.sizes[i] : markerOpts.size; - var fs = isArrayOrTypedArray(fontOpts) ? fontOpts[i].size : fontOpts.size; - var a = isArrayOrTypedArray(align3) ? align3.length > 1 ? align3[i] : align3[0] : align3; - var b = isArrayOrTypedArray(baseline) ? baseline.length > 1 ? baseline[i] : baseline[0] : baseline; - var hSign = TEXTOFFSETSIGN[a]; - var vSign = TEXTOFFSETSIGN[b]; - var xPad = ms ? ms / 0.8 + 1 : 0; - var yPad = -vSign * xPad - vSign * 0.5; - out.offset[i] = [hSign * xPad / fs, yPad / fs]; - } - } - return out; -} -var convert$1 = { - style: convertStyle, - markerStyle: convertMarkerStyle, - markerSelection: convertMarkerSelection, - linePositions: convertLinePositions, - errorBarPositions: convertErrorBarPositions, - textPosition: convertTextPosition -}; -var Lib$b = libExports; -var scene_update = function sceneUpdate(gd, subplot) { - var scene = subplot._scene; - var resetOpts = { - // number of traces in subplot, since scene:subplot -> 1:1 - count: 0, - // whether scene requires init hook in plot call (dirty plot call) - dirty: true, - // last used options - lineOptions: [], - fillOptions: [], - markerOptions: [], - markerSelectedOptions: [], - markerUnselectedOptions: [], - errorXOptions: [], - errorYOptions: [], - textOptions: [], - textSelectedOptions: [], - textUnselectedOptions: [], - // selection batches - selectBatch: [], - unselectBatch: [] - }; - var initOpts = { - fill2d: false, - scatter2d: false, - error2d: false, - line2d: false, - glText: false, - select2d: false - }; - if (!subplot._scene) { - scene = subplot._scene = {}; - scene.init = function init2() { - Lib$b.extendFlat(scene, initOpts, resetOpts); - }; - scene.init(); - scene.update = function update2(opt) { - var opts = Lib$b.repeat(opt, scene.count); - if (scene.fill2d) scene.fill2d.update(opts); - if (scene.scatter2d) scene.scatter2d.update(opts); - if (scene.line2d) scene.line2d.update(opts); - if (scene.error2d) scene.error2d.update(opts.concat(opts)); - if (scene.select2d) scene.select2d.update(opts); - if (scene.glText) { - for (var i = 0; i < scene.count; i++) { - scene.glText[i].update(opt); - } - } - }; - scene.draw = function draw8() { - var count2 = scene.count; - var fill2d = scene.fill2d; - var error2d = scene.error2d; - var line2d = scene.line2d; - var scatter2d = scene.scatter2d; - var glText = scene.glText; - var select2d = scene.select2d; - var selectBatch = scene.selectBatch; - var unselectBatch = scene.unselectBatch; - for (var i = 0; i < count2; i++) { - if (fill2d && scene.fillOrder[i]) { - fill2d.draw(scene.fillOrder[i]); - } - if (line2d && scene.lineOptions[i]) { - line2d.draw(i); - } - if (error2d) { - if (scene.errorXOptions[i]) error2d.draw(i); - if (scene.errorYOptions[i]) error2d.draw(i + count2); - } - if (scatter2d && scene.markerOptions[i]) { - if (unselectBatch[i].length) { - var arg = Lib$b.repeat([], scene.count); - arg[i] = unselectBatch[i]; - scatter2d.draw(arg); - } else if (!selectBatch[i].length) { - scatter2d.draw(i); - } - } - if (glText[i] && scene.textOptions[i]) { - glText[i].render(); - } - } - if (select2d) { - select2d.draw(selectBatch); - } - scene.dirty = false; - }; - scene.destroy = function destroy2() { - if (scene.fill2d && scene.fill2d.destroy) scene.fill2d.destroy(); - if (scene.scatter2d && scene.scatter2d.destroy) scene.scatter2d.destroy(); - if (scene.error2d && scene.error2d.destroy) scene.error2d.destroy(); - if (scene.line2d && scene.line2d.destroy) scene.line2d.destroy(); - if (scene.select2d && scene.select2d.destroy) scene.select2d.destroy(); - if (scene.glText) { - scene.glText.forEach(function(text) { - if (text.destroy) text.destroy(); - }); - } - scene.lineOptions = null; - scene.fillOptions = null; - scene.markerOptions = null; - scene.markerSelectedOptions = null; - scene.markerUnselectedOptions = null; - scene.errorXOptions = null; - scene.errorYOptions = null; - scene.textOptions = null; - scene.textSelectedOptions = null; - scene.textUnselectedOptions = null; - scene.selectBatch = null; - scene.unselectBatch = null; - subplot._scene = null; - }; - } - if (!scene.dirty) { - Lib$b.extendFlat(scene, resetOpts); - } - return scene; -}; -var cluster$2 = pointCluster; -var Lib$a = libExports; -var AxisIDs = axis_ids; -var findExtremes = autorange$2.findExtremes; -var alignPeriod2 = align_period; -var scatterCalc = calc_1$3; -var calcMarkerSize = scatterCalc.calcMarkerSize; -var calcAxisExpansion = scatterCalc.calcAxisExpansion; -var setFirstScatter = scatterCalc.setFirstScatter; -var calcColorscale = colorscale_calc; -var convert2 = convert$1; -var sceneUpdate2 = scene_update; -var BADNUM = numerical.BADNUM; -var TOO_MANY_POINTS = constants$a.TOO_MANY_POINTS; -var calc$3 = function calc4(gd, trace) { - var fullLayout = gd._fullLayout; - var xa = trace._xA = AxisIDs.getFromId(gd, trace.xaxis, "x"); - var ya = trace._yA = AxisIDs.getFromId(gd, trace.yaxis, "y"); - var subplot = fullLayout._plots[trace.xaxis + trace.yaxis]; - var len = trace._length; - var hasTooManyPoints = len >= TOO_MANY_POINTS; - var len2 = len * 2; - var stash = {}; - var i; - var origX = xa.makeCalcdata(trace, "x"); - var origY = ya.makeCalcdata(trace, "y"); - var xObj = alignPeriod2(trace, xa, "x", origX); - var yObj = alignPeriod2(trace, ya, "y", origY); - var x = xObj.vals; - var y = yObj.vals; - trace._x = x; - trace._y = y; - if (trace.xperiodalignment) { - trace._origX = origX; - trace._xStarts = xObj.starts; - trace._xEnds = xObj.ends; - } - if (trace.yperiodalignment) { - trace._origY = origY; - trace._yStarts = yObj.starts; - trace._yEnds = yObj.ends; - } - var positions = new Array(len2); - var _ids = new Array(len); - for (i = 0; i < len; i++) { - positions[i * 2] = x[i] === BADNUM ? NaN : x[i]; - positions[i * 2 + 1] = y[i] === BADNUM ? NaN : y[i]; - _ids[i] = i; - } - if (xa.type === "log") { - for (i = 0; i < len2; i += 2) { - positions[i] = xa.c2l(positions[i]); - } - } - if (ya.type === "log") { - for (i = 1; i < len2; i += 2) { - positions[i] = ya.c2l(positions[i]); - } - } - if (hasTooManyPoints && (xa.type !== "log" && ya.type !== "log")) { - stash.tree = cluster$2(positions); - } else { - stash.ids = _ids; - } - calcColorscale(gd, trace); - var opts = sceneOptions(gd, subplot, trace, positions, x, y); - var scene = sceneUpdate2(gd, subplot); - setFirstScatter(fullLayout, trace); - var ppad; - if (!hasTooManyPoints) { - ppad = calcMarkerSize(trace, len); - } else if (opts.marker) { - ppad = opts.marker.sizeAvg || Math.max(opts.marker.size, 3); - } - calcAxisExpansion(gd, trace, xa, ya, x, y, ppad); - if (opts.errorX) expandForErrorBars(trace, xa, opts.errorX); - if (opts.errorY) expandForErrorBars(trace, ya, opts.errorY); - if (opts.fill && !scene.fill2d) scene.fill2d = true; - if (opts.marker && !scene.scatter2d) scene.scatter2d = true; - if (opts.line && !scene.line2d) scene.line2d = true; - if ((opts.errorX || opts.errorY) && !scene.error2d) scene.error2d = true; - if (opts.text && !scene.glText) scene.glText = true; - if (opts.marker) opts.marker.snap = len; - scene.lineOptions.push(opts.line); - scene.errorXOptions.push(opts.errorX); - scene.errorYOptions.push(opts.errorY); - scene.fillOptions.push(opts.fill); - scene.markerOptions.push(opts.marker); - scene.markerSelectedOptions.push(opts.markerSel); - scene.markerUnselectedOptions.push(opts.markerUnsel); - scene.textOptions.push(opts.text); - scene.textSelectedOptions.push(opts.textSel); - scene.textUnselectedOptions.push(opts.textUnsel); - scene.selectBatch.push([]); - scene.unselectBatch.push([]); - stash._scene = scene; - stash.index = scene.count; - stash.x = x; - stash.y = y; - stash.positions = positions; - scene.count++; - return [{ x: false, y: false, t: stash, trace }]; -}; -function expandForErrorBars(trace, ax, opts) { - var extremes = trace._extremes[ax._id]; - var errExt = findExtremes(ax, opts._bnds, { padded: true }); - extremes.min = extremes.min.concat(errExt.min); - extremes.max = extremes.max.concat(errExt.max); -} -function sceneOptions(gd, subplot, trace, positions, x, y) { - var opts = convert2.style(gd, trace); - if (opts.marker) { - opts.marker.positions = positions; - } - if (opts.line && positions.length > 1) { - Lib$a.extendFlat( - opts.line, - convert2.linePositions(gd, trace, positions) - ); - } - if (opts.errorX || opts.errorY) { - var errors = convert2.errorBarPositions(gd, trace, positions, x, y); - if (opts.errorX) { - Lib$a.extendFlat(opts.errorX, errors.x); - } - if (opts.errorY) { - Lib$a.extendFlat(opts.errorY, errors.y); - } - } - if (opts.text) { - Lib$a.extendFlat( - opts.text, - { positions }, - convert2.textPosition(gd, trace, opts.text, opts.marker) - ); - Lib$a.extendFlat( - opts.textSel, - { positions }, - convert2.textPosition(gd, trace, opts.text, opts.markerSel) - ); - Lib$a.extendFlat( - opts.textUnsel, - { positions }, - convert2.textPosition(gd, trace, opts.text, opts.markerUnsel) - ); - } - return opts; -} -var Lib$9 = libExports; -var Color$6 = colorExports; -var DESELECTDIM = interactions.DESELECTDIM; -function styleTextSelection$2(cd) { - var cd0 = cd[0]; - var trace = cd0.trace; - var stash = cd0.t; - var scene = stash._scene; - var index2 = stash.index; - var els = scene.selectBatch[index2]; - var unels = scene.unselectBatch[index2]; - var baseOpts = scene.textOptions[index2]; - var selOpts = scene.textSelectedOptions[index2] || {}; - var unselOpts = scene.textUnselectedOptions[index2] || {}; - var opts = Lib$9.extendFlat({}, baseOpts); - var i, j; - if (els.length || unels.length) { - var stc = selOpts.color; - var utc = unselOpts.color; - var base = baseOpts.color; - var hasArrayBase = Lib$9.isArrayOrTypedArray(base); - opts.color = new Array(trace._length); - for (i = 0; i < els.length; i++) { - j = els[i]; - opts.color[j] = stc || (hasArrayBase ? base[j] : base); - } - for (i = 0; i < unels.length; i++) { - j = unels[i]; - var basej = hasArrayBase ? base[j] : base; - opts.color[j] = utc ? utc : stc ? basej : Color$6.addOpacity(basej, DESELECTDIM); - } - } - scene.glText[index2].update(opts); -} -var edit_style = { - styleTextSelection: styleTextSelection$2 -}; -var subTypes$1 = subtypes$3; -var styleTextSelection$1 = edit_style.styleTextSelection; -var select = function select2(searchInfo, selectionTester) { - var cd = searchInfo.cd; - var xa = searchInfo.xaxis; - var ya = searchInfo.yaxis; - var selection = []; - var trace = cd[0].trace; - var stash = cd[0].t; - var len = trace._length; - var x = stash.x; - var y = stash.y; - var scene = stash._scene; - var index2 = stash.index; - if (!scene) return selection; - var hasText = subTypes$1.hasText(trace); - var hasMarkers = subTypes$1.hasMarkers(trace); - var hasOnlyLines = !hasMarkers && !hasText; - if (trace.visible !== true || hasOnlyLines) return selection; - var els = []; - var unels = []; - if (selectionTester !== false && !selectionTester.degenerate) { - for (var i = 0; i < len; i++) { - if (selectionTester.contains([stash.xpx[i], stash.ypx[i]], false, i, searchInfo)) { - els.push(i); - selection.push({ - pointNumber: i, - x: xa.c2d(x[i]), - y: ya.c2d(y[i]) - }); - } else { - unels.push(i); - } - } - } - if (hasMarkers) { - var scatter2d = scene.scatter2d; - if (!els.length && !unels.length) { - var baseOpts = new Array(scene.count); - baseOpts[index2] = scene.markerOptions[index2]; - scatter2d.update.apply(scatter2d, baseOpts); - } else if (!scene.selectBatch[index2].length && !scene.unselectBatch[index2].length) { - var unselOpts = new Array(scene.count); - unselOpts[index2] = scene.markerUnselectedOptions[index2]; - scatter2d.update.apply(scatter2d, unselOpts); - } - } - scene.selectBatch[index2] = els; - scene.unselectBatch[index2] = unels; - if (hasText) { - styleTextSelection$1(cd); - } - return selection; -}; -var hover2 = hover$1; -var base_index = { - moduleType: "trace", - name: "scattergl", - basePlotModule: cartesian, - categories: ["gl", "regl", "cartesian", "symbols", "errorBarsOK", "showLegend", "scatter-like"], - attributes: attributesExports, - supplyDefaults: defaults$2, - crossTraceDefaults: cross_trace_defaults$1, - colorbar: marker_colorbar, - formatLabels: format_labels, - calc: calc$3, - hoverPoints: hover2.hoverPoints, - selectPoints: select, - meta: { - hrName: "scatter_gl", - description: [ - "The data visualized as scatter point or lines is set in `x` and `y`", - "using the WebGL plotting engine.", - "Bubble charts are achieved by setting `marker.size` and/or `marker.color`", - "to a numerical arrays." - ].join(" ") - } -}; -var plot$2 = { exports: {} }; -var colorId$1 = { exports: {} }; -var clamp = clamp_1; -colorId$1.exports = toNumber; -colorId$1.exports.to = toNumber; -colorId$1.exports.from = fromNumber; -function toNumber(rgba3, normalized) { - if (normalized == null) normalized = true; - var r = rgba3[0], g = rgba3[1], b = rgba3[2], a = rgba3[3]; - if (a == null) a = normalized ? 1 : 255; - if (normalized) { - r *= 255; - g *= 255; - b *= 255; - a *= 255; - } - r = clamp(r, 0, 255) & 255; - g = clamp(g, 0, 255) & 255; - b = clamp(b, 0, 255) & 255; - a = clamp(a, 0, 255) & 255; - var n = r * 16777216 + (g << 16) + (b << 8) + a; - return n; -} -function fromNumber(n, normalized) { - n = +n; - var r = n >>> 24; - var g = (n & 16711680) >>> 16; - var b = (n & 65280) >>> 8; - var a = n & 255; - if (normalized === false) return [r, g, b, a]; - return [r / 255, g / 255, b / 255, a / 255]; -} -var colorIdExports = colorId$1.exports; -var browser = function(strings) { - if (typeof strings === "string") strings = [strings]; - var exprs = [].slice.call(arguments, 1); - var parts = []; - for (var i = 0; i < strings.length - 1; i++) { - parts.push(strings[i], exprs[i] || ""); - } - parts.push(strings[i]); - return parts.join(""); -}; -var updateDiff$2 = function updateDiff(obj, diff, mappers) { - if (!Array.isArray(mappers)) mappers = [].slice.call(arguments, 2); - for (var i = 0, l = mappers.length; i < l; i++) { - var dict = mappers[i]; - for (var prop in dict) { - if (diff[prop] !== void 0 && !Array.isArray(diff[prop]) && obj[prop] === diff[prop]) continue; - if (prop in diff) { - var result; - if (dict[prop] === true) result = diff[prop]; - else if (dict[prop] === false) continue; - else if (typeof dict[prop] === "function") { - result = dict[prop](diff[prop], obj, diff); - if (result === void 0) continue; - } - obj[prop] = result; - } - } - } - return obj; -}; -var isIexplorer = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion)); -var toFloat32 = { exports: {} }; -toFloat32.exports = float32$2; -toFloat32.exports.float32 = toFloat32.exports.float = float32$2; -toFloat32.exports.fract32 = toFloat32.exports.fract = fract32$2; -var narr = new Float32Array(1); -function fract32$2(arr, fract) { - if (arr.length) { - if (arr instanceof Float32Array) return new Float32Array(arr.length); - if (!(fract instanceof Float32Array)) fract = float32$2(arr); - for (var i = 0, l = fract.length; i < l; i++) { - fract[i] = arr[i] - fract[i]; - } - return fract; - } - return float32$2(arr - float32$2(arr)); -} -function float32$2(arr) { - if (arr.length) { - if (arr instanceof Float32Array) return arr; - return new Float32Array(arr); - } - narr[0] = arr; - return narr[0]; -} -var toFloat32Exports = toFloat32.exports; -function _iterableToArrayLimit(arr, i) { - var _i = null == arr ? null : "undefined" != typeof Symbol && arr[Symbol.iterator] || arr["@@iterator"]; - if (null != _i) { - var _s, _e, _x, _r, _arr = [], _n = true, _d = false; - try { - if (_x = (_i = _i.call(arr)).next, 0 === i) ; - else for (; !(_n = (_s = _x.call(_i)).done) && (_arr.push(_s.value), _arr.length !== i); _n = true) ; - } catch (err) { - _d = true, _e = err; - } finally { - try { - if (!_n && null != _i.return && (_r = _i.return(), Object(_r) !== _r)) return; - } finally { - if (_d) throw _e; - } - } - return _arr; - } -} -function _slicedToArray(arr, i) { - return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); -} -function _toConsumableArray(arr) { - return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); -} -function _arrayWithoutHoles(arr) { - if (Array.isArray(arr)) return _arrayLikeToArray(arr); -} -function _arrayWithHoles(arr) { - if (Array.isArray(arr)) return arr; -} -function _iterableToArray(iter) { - if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); -} -function _unsupportedIterableToArray(o, minLen) { - if (!o) return; - if (typeof o === "string") return _arrayLikeToArray(o, minLen); - var n = Object.prototype.toString.call(o).slice(8, -1); - if (n === "Object" && o.constructor) n = o.constructor.name; - if (n === "Map" || n === "Set") return Array.from(o); - if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); -} -function _arrayLikeToArray(arr, len) { - if (len == null || len > arr.length) len = arr.length; - for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; - return arr2; -} -function _nonIterableSpread() { - throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} -function _nonIterableRest() { - throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); -} -var rgba$4 = colorNormalize; -var getBounds$3 = arrayBounds; -var colorId = colorIdExports; -var cluster$1 = pointCluster; -var extend$4 = index$3.objectAssign; -var glslify = browser; -var pick$5 = pickByAlias; -var updateDiff$1 = updateDiff$2; -var flatten$3 = flattenVertexData_1; -var ie = isIexplorer; -var f32 = toFloat32Exports; -var parseRect$2 = parseRect_1; -var scatter = Scatter; -function Scatter(regl, options) { - var _this = this; - if (!(this instanceof Scatter)) return new Scatter(regl, options); - if (typeof regl === "function") { - if (!options) options = {}; - options.regl = regl; - } else { - options = regl; - regl = null; - } - if (options && options.length) options.positions = options; - regl = options.regl; - var gl = regl._gl, paletteTexture, palette = [], paletteIds = {}, groups = [], markerTextures = [null], markerCache = [null]; - var maxColors = 255, maxSize = 100; - this.tooManyColors = ie; - paletteTexture = regl.texture({ - data: new Uint8Array(maxColors * 4), - width: maxColors, - height: 1, - type: "uint8", - format: "rgba", - wrapS: "clamp", - wrapT: "clamp", - mag: "nearest", - min: "nearest" - }); - extend$4(this, { - regl, - gl, - groups, - markerCache, - markerTextures, - palette, - paletteIds, - paletteTexture, - maxColors, - maxSize, - canvas: gl.canvas - }); - this.update(options); - var shaderOptions = { - uniforms: { - constPointSize: !!options.constPointSize, - opacity: regl.prop("opacity"), - paletteSize: function paletteSize(ctx2, prop) { - return [_this.tooManyColors ? 0 : maxColors, paletteTexture.height]; - }, - pixelRatio: regl.context("pixelRatio"), - scale: regl.prop("scale"), - scaleFract: regl.prop("scaleFract"), - translate: regl.prop("translate"), - translateFract: regl.prop("translateFract"), - markerTexture: regl.prop("markerTexture"), - paletteTexture - }, - attributes: { - // FIXME: optimize these parts - x: function x(ctx2, prop) { - return prop.xAttr || { - buffer: prop.positionBuffer, - stride: 8, - offset: 0 - }; - }, - y: function y(ctx2, prop) { - return prop.yAttr || { - buffer: prop.positionBuffer, - stride: 8, - offset: 4 - }; - }, - xFract: function xFract(ctx2, prop) { - return prop.xAttr ? { - constant: [0, 0] - } : { - buffer: prop.positionFractBuffer, - stride: 8, - offset: 0 - }; - }, - yFract: function yFract(ctx2, prop) { - return prop.yAttr ? { - constant: [0, 0] - } : { - buffer: prop.positionFractBuffer, - stride: 8, - offset: 4 - }; - }, - size: function size(ctx2, prop) { - return prop.size.length ? { - buffer: prop.sizeBuffer, - stride: 2, - offset: 0 - } : { - constant: [Math.round(prop.size * 255 / _this.maxSize)] - }; - }, - borderSize: function borderSize(ctx2, prop) { - return prop.borderSize.length ? { - buffer: prop.sizeBuffer, - stride: 2, - offset: 1 - } : { - constant: [Math.round(prop.borderSize * 255 / _this.maxSize)] - }; - }, - colorId: function colorId2(ctx2, prop) { - return prop.color.length ? { - buffer: prop.colorBuffer, - stride: _this.tooManyColors ? 8 : 4, - offset: 0 - } : { - constant: _this.tooManyColors ? palette.slice(prop.color * 4, prop.color * 4 + 4) : [prop.color] - }; - }, - borderColorId: function borderColorId(ctx2, prop) { - return prop.borderColor.length ? { - buffer: prop.colorBuffer, - stride: _this.tooManyColors ? 8 : 4, - offset: _this.tooManyColors ? 4 : 2 - } : { - constant: _this.tooManyColors ? palette.slice(prop.borderColor * 4, prop.borderColor * 4 + 4) : [prop.borderColor] - }; - }, - isActive: function isActive2(ctx2, prop) { - return prop.activation === true ? { - constant: [1] - } : prop.activation ? prop.activation : { - constant: [0] - }; - } - }, - blend: { - enable: true, - color: [0, 0, 0, 1], - // photoshop blending - func: { - srcRGB: "src alpha", - dstRGB: "one minus src alpha", - srcAlpha: "one minus dst alpha", - dstAlpha: "one" - } - }, - scissor: { - enable: true, - box: regl.prop("viewport") - }, - viewport: regl.prop("viewport"), - stencil: { - enable: false - }, - depth: { - enable: false - }, - elements: regl.prop("elements"), - count: regl.prop("count"), - offset: regl.prop("offset"), - primitive: "points" - }; - var markerOptions = extend$4({}, shaderOptions); - markerOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nuniform float opacity;\nuniform sampler2D markerTexture;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat smoothStep(float x, float y) {\n return 1.0 / (1.0 + exp(50.0*(x - y)));\n}\n\nvoid main() {\n float dist = texture2D(markerTexture, gl_PointCoord).r, delta = fragWidth;\n\n // max-distance alpha\n if (dist < 0.003) discard;\n\n // null-border case\n if (fragBorderColorLevel == fragColorLevel || fragBorderColor.a == 0.) {\n float colorAmt = smoothstep(.5 - delta, .5 + delta, dist);\n gl_FragColor = vec4(fragColor.rgb, colorAmt * fragColor.a * opacity);\n }\n else {\n float borderColorAmt = smoothstep(fragBorderColorLevel - delta, fragBorderColorLevel + delta, dist);\n float colorAmt = smoothstep(fragColorLevel - delta, fragColorLevel + delta, dist);\n\n vec4 color = fragBorderColor;\n color.a *= borderColorAmt;\n color = mix(color, fragColor, colorAmt);\n color.a *= opacity;\n\n gl_FragColor = color;\n }\n\n}\n"]); - markerOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 scale, scaleFract, translate, translateFract, paletteSize;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\nconst float borderLevel = .5;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragPointSize, fragBorderRadius, fragWidth, fragBorderColorLevel, fragColorLevel;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n return isDirect ? id / 255. : texture2D(paletteTexture,\n vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n )\n );\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = 2. * size * pointSizeScale;\n fragPointSize = size * pixelRatio;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n fragColor = color;\n fragBorderColor = borderColor;\n fragWidth = 1. / gl_PointSize;\n\n fragBorderColorLevel = clamp(borderLevel - borderLevel * borderSize / size, 0., 1.);\n fragColorLevel = clamp(borderLevel + (1. - borderLevel) * borderSize / size, 0., 1.);\n}\n"]); - this.drawMarker = regl(markerOptions); - var circleOptions = extend$4({}, shaderOptions); - circleOptions.frag = glslify(["precision highp float;\n#define GLSLIFY 1\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nuniform float opacity;\n\nfloat smoothStep(float edge0, float edge1, float x) {\n float t;\n t = clamp((x - edge0) / (edge1 - edge0), 0.0, 1.0);\n return t * t * (3.0 - 2.0 * t);\n}\n\nvoid main() {\n float radius, alpha = 1.0, delta = fragWidth;\n\n radius = length(2.0 * gl_PointCoord.xy - 1.0);\n\n if (radius > 1.0 + delta) {\n discard;\n }\n\n alpha -= smoothstep(1.0 - delta, 1.0 + delta, radius);\n\n float borderRadius = fragBorderRadius;\n float ratio = smoothstep(borderRadius - delta, borderRadius + delta, radius);\n vec4 color = mix(fragColor, fragBorderColor, ratio);\n color.a *= alpha * opacity;\n gl_FragColor = color;\n}\n"]); - circleOptions.vert = glslify(["precision highp float;\n#define GLSLIFY 1\n\nattribute float x, y, xFract, yFract;\nattribute float size, borderSize;\nattribute vec4 colorId, borderColorId;\nattribute float isActive;\n\n// `invariant` effectively turns off optimizations for the position.\n// We need this because -fast-math on M1 Macs is re-ordering\n// floating point operations in a way that causes floating point\n// precision limits to put points in the wrong locations.\ninvariant gl_Position;\n\nuniform bool constPointSize;\nuniform float pixelRatio;\nuniform vec2 paletteSize, scale, scaleFract, translate, translateFract;\nuniform sampler2D paletteTexture;\n\nconst float maxSize = 100.;\n\nvarying vec4 fragColor, fragBorderColor;\nvarying float fragBorderRadius, fragWidth;\n\nfloat pointSizeScale = (constPointSize) ? 2. : pixelRatio;\n\nbool isDirect = (paletteSize.x < 1.);\n\nvec4 getColor(vec4 id) {\n return isDirect ? id / 255. : texture2D(paletteTexture,\n vec2(\n (id.x + .5) / paletteSize.x,\n (id.y + .5) / paletteSize.y\n )\n );\n}\n\nvoid main() {\n // ignore inactive points\n if (isActive == 0.) return;\n\n vec2 position = vec2(x, y);\n vec2 positionFract = vec2(xFract, yFract);\n\n vec4 color = getColor(colorId);\n vec4 borderColor = getColor(borderColorId);\n\n float size = size * maxSize / 255.;\n float borderSize = borderSize * maxSize / 255.;\n\n gl_PointSize = (size + borderSize) * pointSizeScale;\n\n vec2 pos = (position + translate) * scale\n + (positionFract + translateFract) * scale\n + (position + translate) * scaleFract\n + (positionFract + translateFract) * scaleFract;\n\n gl_Position = vec4(pos * 2. - 1., 0., 1.);\n\n fragBorderRadius = 1. - 2. * borderSize / (size + borderSize);\n fragColor = color;\n fragBorderColor = borderColor.a == 0. || borderSize == 0. ? vec4(color.rgb, 0.) : borderColor;\n fragWidth = 1. / gl_PointSize;\n}\n"]); - if (ie) { - circleOptions.frag = circleOptions.frag.replace("smoothstep", "smoothStep"); - markerOptions.frag = markerOptions.frag.replace("smoothstep", "smoothStep"); - } - this.drawCircle = regl(circleOptions); -} -Scatter.defaults = { - color: "black", - borderColor: "transparent", - borderSize: 0, - size: 12, - opacity: 1, - marker: void 0, - viewport: null, - range: null, - pixelSize: null, - count: 0, - offset: 0, - bounds: null, - positions: [], - snap: 1e4 -}; -Scatter.prototype.render = function() { - if (arguments.length) { - this.update.apply(this, arguments); - } - this.draw(); - return this; -}; -Scatter.prototype.draw = function() { - var _this2 = this; - for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { - args[_key] = arguments[_key]; - } - var groups = this.groups; - if (args.length === 1 && Array.isArray(args[0]) && (args[0][0] === null || Array.isArray(args[0][0]))) { - args = args[0]; - } - this.regl._refresh(); - if (args.length) { - for (var i = 0; i < args.length; i++) { - this.drawItem(i, args[i]); - } - } else { - groups.forEach(function(group, i2) { - _this2.drawItem(i2); - }); - } - return this; -}; -Scatter.prototype.drawItem = function(id, els) { - var groups = this.groups; - var group = groups[id]; - if (typeof els === "number") { - id = els; - group = groups[els]; - els = null; - } - if (!(group && group.count && group.opacity)) return; - if (group.activation[0]) { - this.drawCircle(this.getMarkerDrawOptions(0, group, els)); - } - var batch = []; - for (var i = 1; i < group.activation.length; i++) { - if (!group.activation[i] || group.activation[i] !== true && !group.activation[i].data.length) continue; - batch.push.apply(batch, _toConsumableArray(this.getMarkerDrawOptions(i, group, els))); - } - if (batch.length) { - this.drawMarker(batch); - } -}; -Scatter.prototype.getMarkerDrawOptions = function(markerId, group, elements) { - var range = group.range, tree2 = group.tree, viewport = group.viewport, activation = group.activation, selectionBuffer = group.selectionBuffer, count2 = group.count; - this.regl; - if (!tree2) { - if (elements) { - return [extend$4({}, group, { - markerTexture: this.markerTextures[markerId], - activation: activation[markerId], - count: elements.length, - elements, - offset: 0 - })]; - } - return [extend$4({}, group, { - markerTexture: this.markerTextures[markerId], - activation: activation[markerId], - offset: 0 - })]; - } - var batch = []; - var lod = tree2.range(range, { - lod: true, - px: [(range[2] - range[0]) / viewport.width, (range[3] - range[1]) / viewport.height] - }); - if (elements) { - var markerActivation = activation[markerId]; - var mask = markerActivation.data; - var data = new Uint8Array(count2); - for (var i = 0; i < elements.length; i++) { - var id = elements[i]; - data[id] = mask ? mask[id] : 1; - } - selectionBuffer.subdata(data); - } - for (var l = lod.length; l--; ) { - var _lod$l = _slicedToArray(lod[l], 2), from = _lod$l[0], to = _lod$l[1]; - batch.push(extend$4({}, group, { - markerTexture: this.markerTextures[markerId], - activation: elements ? selectionBuffer : activation[markerId], - offset: from, - count: to - from - })); - } - return batch; -}; -Scatter.prototype.update = function() { - var _this3 = this; - for (var _len2 = arguments.length, args = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { - args[_key2] = arguments[_key2]; - } - if (!args.length) return; - if (args.length === 1 && Array.isArray(args[0])) args = args[0]; - var groups = this.groups, gl = this.gl, regl = this.regl, maxSize = this.maxSize, maxColors = this.maxColors, palette = this.palette; - this.groups = groups = args.map(function(options, i) { - var group = groups[i]; - if (options === void 0) return group; - if (options === null) options = { - positions: null - }; - else if (typeof options === "function") options = { - ondraw: options - }; - else if (typeof options[0] === "number") options = { - positions: options - }; - options = pick$5(options, { - positions: "positions data points", - snap: "snap cluster lod tree", - size: "sizes size radius", - borderSize: "borderSizes borderSize border-size bordersize borderWidth borderWidths border-width borderwidth stroke-width strokeWidth strokewidth outline", - color: "colors color fill fill-color fillColor", - borderColor: "borderColors borderColor stroke stroke-color strokeColor", - marker: "markers marker shape", - range: "range dataBox databox", - viewport: "viewport viewPort viewBox viewbox", - opacity: "opacity alpha transparency", - bounds: "bound bounds boundaries limits", - tooManyColors: "tooManyColors palette paletteMode optimizePalette enablePalette" - }); - if (options.positions === null) options.positions = []; - if (options.tooManyColors != null) _this3.tooManyColors = options.tooManyColors; - if (!group) { - groups[i] = group = { - id: i, - scale: null, - translate: null, - scaleFract: null, - translateFract: null, - // buffers for active markers - activation: [], - // buffer for filtered markers - selectionBuffer: regl.buffer({ - data: new Uint8Array(0), - usage: "stream", - type: "uint8" - }), - // buffers with data: it is faster to switch them per-pass - // than provide one congregate buffer - sizeBuffer: regl.buffer({ - data: new Uint8Array(0), - usage: "dynamic", - type: "uint8" - }), - colorBuffer: regl.buffer({ - data: new Uint8Array(0), - usage: "dynamic", - type: "uint8" - }), - positionBuffer: regl.buffer({ - data: new Uint8Array(0), - usage: "dynamic", - type: "float" - }), - positionFractBuffer: regl.buffer({ - data: new Uint8Array(0), - usage: "dynamic", - type: "float" - }) - }; - options = extend$4({}, Scatter.defaults, options); - } - if (options.positions && !("marker" in options)) { - options.marker = group.marker; - delete group.marker; - } - if (options.marker && !("positions" in options)) { - options.positions = group.positions; - delete group.positions; - } - var hasSize = 0, hasColor = 0; - updateDiff$1(group, options, [{ - snap: true, - size: function size2(s, group2) { - if (s == null) s = Scatter.defaults.size; - hasSize += s && s.length ? 1 : 0; - return s; - }, - borderSize: function borderSize2(s, group2) { - if (s == null) s = Scatter.defaults.borderSize; - hasSize += s && s.length ? 1 : 0; - return s; - }, - opacity: parseFloat, - // add colors to palette, save references - color: function color3(c, group2) { - if (c == null) c = Scatter.defaults.color; - c = _this3.updateColor(c); - hasColor++; - return c; - }, - borderColor: function borderColor2(c, group2) { - if (c == null) c = Scatter.defaults.borderColor; - c = _this3.updateColor(c); - hasColor++; - return c; - }, - bounds: function bounds(_bounds, group2, options2) { - if (!("range" in options2)) options2.range = null; - return _bounds; - }, - positions: function positions(_positions, group2, options2) { - var snap = group2.snap; - var positionBuffer = group2.positionBuffer, positionFractBuffer = group2.positionFractBuffer, selectionBuffer = group2.selectionBuffer; - if (_positions.x || _positions.y) { - if (_positions.x.length) { - group2.xAttr = { - buffer: regl.buffer(_positions.x), - offset: 0, - stride: 4, - count: _positions.x.length - }; - } else { - group2.xAttr = { - buffer: _positions.x.buffer, - offset: _positions.x.offset * 4 || 0, - stride: (_positions.x.stride || 1) * 4, - count: _positions.x.count - }; - } - if (_positions.y.length) { - group2.yAttr = { - buffer: regl.buffer(_positions.y), - offset: 0, - stride: 4, - count: _positions.y.length - }; - } else { - group2.yAttr = { - buffer: _positions.y.buffer, - offset: _positions.y.offset * 4 || 0, - stride: (_positions.y.stride || 1) * 4, - count: _positions.y.count - }; - } - group2.count = Math.max(group2.xAttr.count, group2.yAttr.count); - return _positions; - } - _positions = flatten$3(_positions, "float64"); - var count3 = group2.count = Math.floor(_positions.length / 2); - var bounds = group2.bounds = count3 ? getBounds$3(_positions, 2) : null; - if (!options2.range && !group2.range) { - delete group2.range; - options2.range = bounds; - } - if (!options2.marker && !group2.marker) { - delete group2.marker; - options2.marker = null; - } - if (snap && (snap === true || count3 > snap)) { - group2.tree = cluster$1(_positions, { - bounds - }); - } else if (snap && snap.length) { - group2.tree = snap; - } - if (group2.tree) { - var opts = { - primitive: "points", - usage: "static", - data: group2.tree, - type: "uint32" - }; - if (group2.elements) group2.elements(opts); - else group2.elements = regl.elements(opts); - } - var float_data = f32.float32(_positions); - positionBuffer({ - data: float_data, - usage: "dynamic" - }); - var frac_data = f32.fract32(_positions, float_data); - positionFractBuffer({ - data: frac_data, - usage: "dynamic" - }); - selectionBuffer({ - data: new Uint8Array(count3), - type: "uint8", - usage: "stream" - }); - return _positions; - } - }, { - // create marker ids corresponding to known marker textures - marker: function marker2(markers, group2, options2) { - var activation = group2.activation; - activation.forEach(function(buffer2) { - return buffer2 && buffer2.destroy && buffer2.destroy(); - }); - activation.length = 0; - if (!markers || typeof markers[0] === "number") { - var id = _this3.addMarker(markers); - activation[id] = true; - } else { - var markerMasks = []; - for (var _i = 0, l = Math.min(markers.length, group2.count); _i < l; _i++) { - var _id = _this3.addMarker(markers[_i]); - if (!markerMasks[_id]) markerMasks[_id] = new Uint8Array(group2.count); - markerMasks[_id][_i] = 1; - } - for (var _id2 = 0; _id2 < markerMasks.length; _id2++) { - if (!markerMasks[_id2]) continue; - var opts = { - data: markerMasks[_id2], - type: "uint8", - usage: "static" - }; - if (!activation[_id2]) { - activation[_id2] = regl.buffer(opts); - } else { - activation[_id2](opts); - } - activation[_id2].data = markerMasks[_id2]; - } - } - return markers; - }, - range: function range(_range, group2, options2) { - var bounds = group2.bounds; - if (!bounds) return; - if (!_range) _range = bounds; - group2.scale = [1 / (_range[2] - _range[0]), 1 / (_range[3] - _range[1])]; - group2.translate = [-_range[0], -_range[1]]; - group2.scaleFract = f32.fract(group2.scale); - group2.translateFract = f32.fract(group2.translate); - return _range; - }, - viewport: function viewport(vp) { - var rect2 = parseRect$2(vp || [gl.drawingBufferWidth, gl.drawingBufferHeight]); - return rect2; - } - }]); - if (hasSize) { - var _group = group, count2 = _group.count, size = _group.size, borderSize = _group.borderSize, sizeBuffer = _group.sizeBuffer; - var sizes2 = new Uint8Array(count2 * 2); - if (size.length || borderSize.length) { - for (var _i2 = 0; _i2 < count2; _i2++) { - sizes2[_i2 * 2] = Math.round((size[_i2] == null ? size : size[_i2]) * 255 / maxSize); - sizes2[_i2 * 2 + 1] = Math.round((borderSize[_i2] == null ? borderSize : borderSize[_i2]) * 255 / maxSize); - } - } - sizeBuffer({ - data: sizes2, - usage: "dynamic" - }); - } - if (hasColor) { - var _group2 = group, _count = _group2.count, color2 = _group2.color, borderColor = _group2.borderColor, colorBuffer = _group2.colorBuffer; - var colors; - if (_this3.tooManyColors) { - if (color2.length || borderColor.length) { - colors = new Uint8Array(_count * 8); - for (var _i3 = 0; _i3 < _count; _i3++) { - var _colorId = color2[_i3]; - colors[_i3 * 8] = palette[_colorId * 4]; - colors[_i3 * 8 + 1] = palette[_colorId * 4 + 1]; - colors[_i3 * 8 + 2] = palette[_colorId * 4 + 2]; - colors[_i3 * 8 + 3] = palette[_colorId * 4 + 3]; - var borderColorId = borderColor[_i3]; - colors[_i3 * 8 + 4] = palette[borderColorId * 4]; - colors[_i3 * 8 + 5] = palette[borderColorId * 4 + 1]; - colors[_i3 * 8 + 6] = palette[borderColorId * 4 + 2]; - colors[_i3 * 8 + 7] = palette[borderColorId * 4 + 3]; - } - } - } else { - if (color2.length || borderColor.length) { - colors = new Uint8Array(_count * 4 + 2); - for (var _i4 = 0; _i4 < _count; _i4++) { - if (color2[_i4] != null) { - colors[_i4 * 4] = color2[_i4] % maxColors; - colors[_i4 * 4 + 1] = Math.floor(color2[_i4] / maxColors); - } - if (borderColor[_i4] != null) { - colors[_i4 * 4 + 2] = borderColor[_i4] % maxColors; - colors[_i4 * 4 + 3] = Math.floor(borderColor[_i4] / maxColors); - } - } - } - } - colorBuffer({ - data: colors || new Uint8Array(0), - type: "uint8", - usage: "dynamic" - }); - } - return group; - }); -}; -Scatter.prototype.addMarker = function(sdf) { - var markerTextures = this.markerTextures, regl = this.regl, markerCache = this.markerCache; - var pos = sdf == null ? 0 : markerCache.indexOf(sdf); - if (pos >= 0) return pos; - var distArr; - if (sdf instanceof Uint8Array || sdf instanceof Uint8ClampedArray) { - distArr = sdf; - } else { - distArr = new Uint8Array(sdf.length); - for (var i = 0, l = sdf.length; i < l; i++) { - distArr[i] = sdf[i] * 255; - } - } - var radius = Math.floor(Math.sqrt(distArr.length)); - pos = markerTextures.length; - markerCache.push(sdf); - markerTextures.push(regl.texture({ - channels: 1, - data: distArr, - radius, - mag: "linear", - min: "linear" - })); - return pos; -}; -Scatter.prototype.updateColor = function(colors) { - var paletteIds = this.paletteIds, palette = this.palette, maxColors = this.maxColors; - if (!Array.isArray(colors)) { - colors = [colors]; - } - var idx = []; - if (typeof colors[0] === "number") { - var grouped = []; - if (Array.isArray(colors)) { - for (var i = 0; i < colors.length; i += 4) { - grouped.push(colors.slice(i, i + 4)); - } - } else { - for (var _i5 = 0; _i5 < colors.length; _i5 += 4) { - grouped.push(colors.subarray(_i5, _i5 + 4)); - } - } - colors = grouped; - } - for (var _i6 = 0; _i6 < colors.length; _i6++) { - var color2 = colors[_i6]; - color2 = rgba$4(color2, "uint8"); - var id = colorId(color2, false); - if (paletteIds[id] == null) { - var pos = palette.length; - paletteIds[id] = Math.floor(pos / 4); - palette[pos] = color2[0]; - palette[pos + 1] = color2[1]; - palette[pos + 2] = color2[2]; - palette[pos + 3] = color2[3]; - } - idx[_i6] = paletteIds[id]; - } - if (!this.tooManyColors && palette.length > maxColors * 4) this.tooManyColors = true; - this.updatePalette(palette); - return idx.length === 1 ? idx[0] : idx; -}; -Scatter.prototype.updatePalette = function(palette) { - if (this.tooManyColors) return; - var maxColors = this.maxColors, paletteTexture = this.paletteTexture; - var requiredHeight = Math.ceil(palette.length * 0.25 / maxColors); - if (requiredHeight > 1) { - palette = palette.slice(); - for (var i = palette.length * 0.25 % maxColors; i < requiredHeight * maxColors; i++) { - palette.push(0, 0, 0, 0); - } - } - if (paletteTexture.height < requiredHeight) { - paletteTexture.resize(maxColors, requiredHeight); - } - paletteTexture.subimage({ - width: Math.min(palette.length * 0.25, maxColors), - height: requiredHeight, - data: palette - }, 0, 0); -}; -Scatter.prototype.destroy = function() { - this.groups.forEach(function(group) { - group.sizeBuffer.destroy(); - group.positionBuffer.destroy(); - group.positionFractBuffer.destroy(); - group.colorBuffer.destroy(); - group.activation.forEach(function(b) { - return b && b.destroy && b.destroy(); - }); - group.selectionBuffer.destroy(); - if (group.elements) group.elements.destroy(); - }); - this.groups.length = 0; - this.paletteTexture.destroy(); - this.markerTextures.forEach(function(txt) { - return txt && txt.destroy && txt.destroy(); - }); - return this; -}; -var extend$1$1 = index$3.objectAssign; -var reglScatter2d = function reglScatter2d2(regl, options) { - var scatter$12 = new scatter(regl, options); - var render = scatter$12.render.bind(scatter$12); - extend$1$1(render, { - render, - update: scatter$12.update.bind(scatter$12), - draw: scatter$12.draw.bind(scatter$12), - destroy: scatter$12.destroy.bind(scatter$12), - regl: scatter$12.regl, - gl: scatter$12.gl, - canvas: scatter$12.gl.canvas, - groups: scatter$12.groups, - markers: scatter$12.markerCache, - palette: scatter$12.palette - }); - return render; -}; -var bundle = reglScatter2d; -var earcut$1 = { exports: {} }; -earcut$1.exports = earcut; -earcut$1.exports.default = earcut; -function earcut(data, holeIndices, dim) { - dim = dim || 2; - var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = []; - if (!outerNode || outerNode.next === outerNode.prev) return triangles; - var minX, minY, maxX, maxY2, x, y, invSize; - if (hasHoles) outerNode = eliminateHoles(data, holeIndices, outerNode, dim); - if (data.length > 80 * dim) { - minX = maxX = data[0]; - minY = maxY2 = data[1]; - for (var i = dim; i < outerLen; i += dim) { - x = data[i]; - y = data[i + 1]; - if (x < minX) minX = x; - if (y < minY) minY = y; - if (x > maxX) maxX = x; - if (y > maxY2) maxY2 = y; - } - invSize = Math.max(maxX - minX, maxY2 - minY); - invSize = invSize !== 0 ? 32767 / invSize : 0; - } - earcutLinked(outerNode, triangles, dim, minX, minY, invSize, 0); - return triangles; -} -function linkedList(data, start, end, dim, clockwise) { - var i, last; - if (clockwise === signedArea(data, start, end, dim) > 0) { - for (i = start; i < end; i += dim) last = insertNode(i, data[i], data[i + 1], last); - } else { - for (i = end - dim; i >= start; i -= dim) last = insertNode(i, data[i], data[i + 1], last); - } - if (last && equals(last, last.next)) { - removeNode(last); - last = last.next; - } - return last; -} -function filterPoints(start, end) { - if (!start) return start; - if (!end) end = start; - var p = start, again; - do { - again = false; - if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) { - removeNode(p); - p = end = p.prev; - if (p === p.next) break; - again = true; - } else { - p = p.next; - } - } while (again || p !== end); - return end; -} -function earcutLinked(ear, triangles, dim, minX, minY, invSize, pass) { - if (!ear) return; - if (!pass && invSize) indexCurve(ear, minX, minY, invSize); - var stop = ear, prev, next; - while (ear.prev !== ear.next) { - prev = ear.prev; - next = ear.next; - if (invSize ? isEarHashed(ear, minX, minY, invSize) : isEar(ear)) { - triangles.push(prev.i / dim | 0); - triangles.push(ear.i / dim | 0); - triangles.push(next.i / dim | 0); - removeNode(ear); - ear = next.next; - stop = next.next; - continue; - } - ear = next; - if (ear === stop) { - if (!pass) { - earcutLinked(filterPoints(ear), triangles, dim, minX, minY, invSize, 1); - } else if (pass === 1) { - ear = cureLocalIntersections(filterPoints(ear), triangles, dim); - earcutLinked(ear, triangles, dim, minX, minY, invSize, 2); - } else if (pass === 2) { - splitEarcut(ear, triangles, dim, minX, minY, invSize); - } - break; - } - } -} -function isEar(ear) { - var a = ear.prev, b = ear, c = ear.next; - if (area(a, b, c) >= 0) return false; - var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; - var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; - var p = c.next; - while (p !== a) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.next; - } - return true; -} -function isEarHashed(ear, minX, minY, invSize) { - var a = ear.prev, b = ear, c = ear.next; - if (area(a, b, c) >= 0) return false; - var ax = a.x, bx = b.x, cx = c.x, ay = a.y, by = b.y, cy = c.y; - var x0 = ax < bx ? ax < cx ? ax : cx : bx < cx ? bx : cx, y0 = ay < by ? ay < cy ? ay : cy : by < cy ? by : cy, x1 = ax > bx ? ax > cx ? ax : cx : bx > cx ? bx : cx, y1 = ay > by ? ay > cy ? ay : cy : by > cy ? by : cy; - var minZ = zOrder(x0, y0, minX, minY, invSize), maxZ = zOrder(x1, y1, minX, minY, invSize); - var p = ear.prevZ, n = ear.nextZ; - while (p && p.z >= minZ && n && n.z <= maxZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - while (p && p.z >= minZ) { - if (p.x >= x0 && p.x <= x1 && p.y >= y0 && p.y <= y1 && p !== a && p !== c && pointInTriangle(ax, ay, bx, by, cx, cy, p.x, p.y) && area(p.prev, p, p.next) >= 0) return false; - p = p.prevZ; - } - while (n && n.z <= maxZ) { - if (n.x >= x0 && n.x <= x1 && n.y >= y0 && n.y <= y1 && n !== a && n !== c && pointInTriangle(ax, ay, bx, by, cx, cy, n.x, n.y) && area(n.prev, n, n.next) >= 0) return false; - n = n.nextZ; - } - return true; -} -function cureLocalIntersections(start, triangles, dim) { - var p = start; - do { - var a = p.prev, b = p.next.next; - if (!equals(a, b) && intersects$1(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) { - triangles.push(a.i / dim | 0); - triangles.push(p.i / dim | 0); - triangles.push(b.i / dim | 0); - removeNode(p); - removeNode(p.next); - p = start = b; - } - p = p.next; - } while (p !== start); - return filterPoints(p); -} -function splitEarcut(start, triangles, dim, minX, minY, invSize) { - var a = start; - do { - var b = a.next.next; - while (b !== a.prev) { - if (a.i !== b.i && isValidDiagonal(a, b)) { - var c = splitPolygon(a, b); - a = filterPoints(a, a.next); - c = filterPoints(c, c.next); - earcutLinked(a, triangles, dim, minX, minY, invSize, 0); - earcutLinked(c, triangles, dim, minX, minY, invSize, 0); - return; - } - b = b.next; - } - a = a.next; - } while (a !== start); -} -function eliminateHoles(data, holeIndices, outerNode, dim) { - var queue2 = [], i, len, start, end, list; - for (i = 0, len = holeIndices.length; i < len; i++) { - start = holeIndices[i] * dim; - end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - list = linkedList(data, start, end, dim, false); - if (list === list.next) list.steiner = true; - queue2.push(getLeftmost(list)); - } - queue2.sort(compareX); - for (i = 0; i < queue2.length; i++) { - outerNode = eliminateHole(queue2[i], outerNode); - } - return outerNode; -} -function compareX(a, b) { - return a.x - b.x; -} -function eliminateHole(hole, outerNode) { - var bridge = findHoleBridge(hole, outerNode); - if (!bridge) { - return outerNode; - } - var bridgeReverse = splitPolygon(bridge, hole); - filterPoints(bridgeReverse, bridgeReverse.next); - return filterPoints(bridge, bridge.next); -} -function findHoleBridge(hole, outerNode) { - var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m; - do { - if (hy <= p.y && hy >= p.next.y && p.next.y !== p.y) { - var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y); - if (x <= hx && x > qx) { - qx = x; - m = p.x < p.next.x ? p : p.next; - if (x === hx) return m; - } - } - p = p.next; - } while (p !== outerNode); - if (!m) return null; - var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan; - p = m; - do { - if (hx >= p.x && p.x >= mx && hx !== p.x && pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) { - tan = Math.abs(hy - p.y) / (hx - p.x); - if (locallyInside(p, hole) && (tan < tanMin || tan === tanMin && (p.x > m.x || p.x === m.x && sectorContainsSector(m, p)))) { - m = p; - tanMin = tan; - } - } - p = p.next; - } while (p !== stop); - return m; -} -function sectorContainsSector(m, p) { - return area(m.prev, m, p.prev) < 0 && area(p.next, m, m.next) < 0; -} -function indexCurve(start, minX, minY, invSize) { - var p = start; - do { - if (p.z === 0) p.z = zOrder(p.x, p.y, minX, minY, invSize); - p.prevZ = p.prev; - p.nextZ = p.next; - p = p.next; - } while (p !== start); - p.prevZ.nextZ = null; - p.prevZ = null; - sortLinked(p); -} -function sortLinked(list) { - var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1; - do { - p = list; - list = null; - tail = null; - numMerges = 0; - while (p) { - numMerges++; - q = p; - pSize = 0; - for (i = 0; i < inSize; i++) { - pSize++; - q = q.nextZ; - if (!q) break; - } - qSize = inSize; - while (pSize > 0 || qSize > 0 && q) { - if (pSize !== 0 && (qSize === 0 || !q || p.z <= q.z)) { - e = p; - p = p.nextZ; - pSize--; - } else { - e = q; - q = q.nextZ; - qSize--; - } - if (tail) tail.nextZ = e; - else list = e; - e.prevZ = tail; - tail = e; - } - p = q; - } - tail.nextZ = null; - inSize *= 2; - } while (numMerges > 1); - return list; -} -function zOrder(x, y, minX, minY, invSize) { - x = (x - minX) * invSize | 0; - y = (y - minY) * invSize | 0; - x = (x | x << 8) & 16711935; - x = (x | x << 4) & 252645135; - x = (x | x << 2) & 858993459; - x = (x | x << 1) & 1431655765; - y = (y | y << 8) & 16711935; - y = (y | y << 4) & 252645135; - y = (y | y << 2) & 858993459; - y = (y | y << 1) & 1431655765; - return x | y << 1; -} -function getLeftmost(start) { - var p = start, leftmost = start; - do { - if (p.x < leftmost.x || p.x === leftmost.x && p.y < leftmost.y) leftmost = p; - p = p.next; - } while (p !== start); - return leftmost; -} -function pointInTriangle(ax, ay, bx, by, cx, cy, px2, py) { - return (cx - px2) * (ay - py) >= (ax - px2) * (cy - py) && (ax - px2) * (by - py) >= (bx - px2) * (ay - py) && (bx - px2) * (cy - py) >= (cx - px2) * (by - py); -} -function isValidDiagonal(a, b) { - return a.next.i !== b.i && a.prev.i !== b.i && !intersectsPolygon(a, b) && // dones't intersect other edges - (locallyInside(a, b) && locallyInside(b, a) && middleInside(a, b) && // locally visible - (area(a.prev, a, b.prev) || area(a, b.prev, b)) || // does not create opposite-facing sectors - equals(a, b) && area(a.prev, a, a.next) > 0 && area(b.prev, b, b.next) > 0); -} -function area(p, q, r) { - return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y); -} -function equals(p1, p2) { - return p1.x === p2.x && p1.y === p2.y; -} -function intersects$1(p1, q1, p2, q2) { - var o1 = sign(area(p1, q1, p2)); - var o2 = sign(area(p1, q1, q2)); - var o3 = sign(area(p2, q2, p1)); - var o4 = sign(area(p2, q2, q1)); - if (o1 !== o2 && o3 !== o4) return true; - if (o1 === 0 && onSegment(p1, p2, q1)) return true; - if (o2 === 0 && onSegment(p1, q2, q1)) return true; - if (o3 === 0 && onSegment(p2, p1, q2)) return true; - if (o4 === 0 && onSegment(p2, q1, q2)) return true; - return false; -} -function onSegment(p, q, r) { - return q.x <= Math.max(p.x, r.x) && q.x >= Math.min(p.x, r.x) && q.y <= Math.max(p.y, r.y) && q.y >= Math.min(p.y, r.y); -} -function sign(num) { - return num > 0 ? 1 : num < 0 ? -1 : 0; -} -function intersectsPolygon(a, b) { - var p = a; - do { - if (p.i !== a.i && p.next.i !== a.i && p.i !== b.i && p.next.i !== b.i && intersects$1(p, p.next, a, b)) return true; - p = p.next; - } while (p !== a); - return false; -} -function locallyInside(a, b) { - return area(a.prev, a, a.next) < 0 ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0 : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0; -} -function middleInside(a, b) { - var p = a, inside = false, px2 = (a.x + b.x) / 2, py = (a.y + b.y) / 2; - do { - if (p.y > py !== p.next.y > py && p.next.y !== p.y && px2 < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x) - inside = !inside; - p = p.next; - } while (p !== a); - return inside; -} -function splitPolygon(a, b) { - var a2 = new Node$2(a.i, a.x, a.y), b2 = new Node$2(b.i, b.x, b.y), an = a.next, bp = b.prev; - a.next = b; - b.prev = a; - a2.next = an; - an.prev = a2; - b2.next = a2; - a2.prev = b2; - bp.next = b2; - b2.prev = bp; - return b2; -} -function insertNode(i, x, y, last) { - var p = new Node$2(i, x, y); - if (!last) { - p.prev = p; - p.next = p; - } else { - p.next = last.next; - p.prev = last; - last.next.prev = p; - last.next = p; - } - return p; -} -function removeNode(p) { - p.next.prev = p.prev; - p.prev.next = p.next; - if (p.prevZ) p.prevZ.nextZ = p.nextZ; - if (p.nextZ) p.nextZ.prevZ = p.prevZ; -} -function Node$2(i, x, y) { - this.i = i; - this.x = x; - this.y = y; - this.prev = null; - this.next = null; - this.z = 0; - this.prevZ = null; - this.nextZ = null; - this.steiner = false; -} -earcut.deviation = function(data, holeIndices, dim, triangles) { - var hasHoles = holeIndices && holeIndices.length; - var outerLen = hasHoles ? holeIndices[0] * dim : data.length; - var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim)); - if (hasHoles) { - for (var i = 0, len = holeIndices.length; i < len; i++) { - var start = holeIndices[i] * dim; - var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length; - polygonArea -= Math.abs(signedArea(data, start, end, dim)); - } - } - var trianglesArea = 0; - for (i = 0; i < triangles.length; i += 3) { - var a = triangles[i] * dim; - var b = triangles[i + 1] * dim; - var c = triangles[i + 2] * dim; - trianglesArea += Math.abs( - (data[a] - data[c]) * (data[b + 1] - data[a + 1]) - (data[a] - data[b]) * (data[c + 1] - data[a + 1]) - ); - } - return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea); -}; -function signedArea(data, start, end, dim) { - var sum = 0; - for (var i = start, j = end - dim; i < end; i += dim) { - sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]); - j = i; - } - return sum; -} -earcut.flatten = function(data) { - var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0; - for (var i = 0; i < data.length; i++) { - for (var j = 0; j < data[i].length; j++) { - for (var d = 0; d < dim; d++) result.vertices.push(data[i][j][d]); - } - if (i > 0) { - holeIndex += data[i - 1].length; - result.holes.push(holeIndex); - } - } - return result; -}; -var earcutExports = earcut$1.exports; -var getBounds$2 = arrayBounds; -var arrayNormalize = normalize$1; -function normalize$1(arr, dim, bounds) { - if (!arr || arr.length == null) throw Error("Argument should be an array"); - if (dim == null) dim = 1; - if (bounds == null) bounds = getBounds$2(arr, dim); - for (var offset = 0; offset < dim; offset++) { - var max = bounds[dim + offset], min = bounds[offset], i = offset, l = arr.length; - if (max === Infinity && min === -Infinity) { - for (i = offset; i < l; i += dim) { - arr[i] = arr[i] === max ? 1 : arr[i] === min ? 0 : 0.5; - } - } else if (max === Infinity) { - for (i = offset; i < l; i += dim) { - arr[i] = arr[i] === max ? 1 : 0; - } - } else if (min === -Infinity) { - for (i = offset; i < l; i += dim) { - arr[i] = arr[i] === min ? 0 : 1; - } - } else { - var range = max - min; - for (i = offset; i < l; i += dim) { - if (!isNaN(arr[i])) { - arr[i] = range === 0 ? 0.5 : (arr[i] - min) / range; - } - } - } - } - return arr; -} -var isImplemented$1 = function() { - var weakMap, obj; - if (typeof WeakMap !== "function") return false; - try { - weakMap = new WeakMap([[obj = {}, "one"], [{}, "two"], [{}, "three"]]); - } catch (e) { - return false; - } - if (String(weakMap) !== "[object WeakMap]") return false; - if (typeof weakMap.set !== "function") return false; - if (weakMap.set({}, 1) !== weakMap) return false; - if (typeof weakMap.delete !== "function") return false; - if (typeof weakMap.has !== "function") return false; - if (weakMap.get(obj) !== "one") return false; - return true; -}; -var isImplemented; -var hasRequiredIsImplemented; -function requireIsImplemented() { - if (hasRequiredIsImplemented) return isImplemented; - hasRequiredIsImplemented = 1; - var create2 = Object.create, getPrototypeOf = Object.getPrototypeOf, plainObject = {}; - isImplemented = function() { - var setPrototypeOf2 = Object.setPrototypeOf, customCreate = arguments[0] || create2; - if (typeof setPrototypeOf2 !== "function") return false; - return getPrototypeOf(setPrototypeOf2(customCreate(null), plainObject)) === plainObject; - }; - return isImplemented; -} -var create_1; -var hasRequiredCreate; -function requireCreate() { - if (hasRequiredCreate) return create_1; - hasRequiredCreate = 1; - var create2 = Object.create, shim2; - if (!requireIsImplemented()()) { - shim2 = requireShim(); - } - create_1 = function() { - var nullObject, polyProps, desc; - if (!shim2) return create2; - if (shim2.level !== 1) return create2; - nullObject = {}; - polyProps = {}; - desc = { configurable: false, enumerable: false, writable: true, value: void 0 }; - Object.getOwnPropertyNames(Object.prototype).forEach(function(name2) { - if (name2 === "__proto__") { - polyProps[name2] = { - configurable: true, - enumerable: false, - writable: true, - value: void 0 - }; - return; - } - polyProps[name2] = desc; - }); - Object.defineProperties(nullObject, polyProps); - Object.defineProperty(shim2, "nullPolyfill", { - configurable: false, - enumerable: false, - writable: false, - value: nullObject - }); - return function(prototype, props) { - return create2(prototype === null ? nullObject : prototype, props); - }; - }(); - return create_1; -} -var shim; -var hasRequiredShim; -function requireShim() { - if (hasRequiredShim) return shim; - hasRequiredShim = 1; - var isObject = index$3.isObject, value2 = index$3.validValue, objIsPrototypeOf = Object.prototype.isPrototypeOf, defineProperty = Object.defineProperty, nullDesc = { configurable: true, enumerable: false, writable: true, value: void 0 }, validate3; - validate3 = function(obj, prototype) { - value2(obj); - if (prototype === null || isObject(prototype)) return obj; - throw new TypeError("Prototype must be null or an object"); - }; - shim = function(status) { - var fn, set; - if (!status) return null; - if (status.level === 2) { - if (status.set) { - set = status.set; - fn = function(obj, prototype) { - set.call(validate3(obj, prototype), prototype); - return obj; - }; - } else { - fn = function(obj, prototype) { - validate3(obj, prototype).__proto__ = prototype; - return obj; - }; - } - } else { - fn = function self2(obj, prototype) { - var isNullBase; - validate3(obj, prototype); - isNullBase = objIsPrototypeOf.call(self2.nullPolyfill, obj); - if (isNullBase) delete self2.nullPolyfill.__proto__; - if (prototype === null) prototype = self2.nullPolyfill; - obj.__proto__ = prototype; - if (isNullBase) defineProperty(self2.nullPolyfill, "__proto__", nullDesc); - return obj; - }; - } - return Object.defineProperty(fn, "level", { - configurable: false, - enumerable: false, - writable: false, - value: status.level - }); - }( - function() { - var tmpObj1 = /* @__PURE__ */ Object.create(null), tmpObj2 = {}, set, desc = Object.getOwnPropertyDescriptor(Object.prototype, "__proto__"); - if (desc) { - try { - set = desc.set; - set.call(tmpObj1, tmpObj2); - } catch (ignore) { - } - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { set, level: 2 }; - } - tmpObj1.__proto__ = tmpObj2; - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 2 }; - tmpObj1 = {}; - tmpObj1.__proto__ = tmpObj2; - if (Object.getPrototypeOf(tmpObj1) === tmpObj2) return { level: 1 }; - return false; - }() - ); - requireCreate(); - return shim; -} -var setPrototypeOf; -var hasRequiredSetPrototypeOf; -function requireSetPrototypeOf() { - if (hasRequiredSetPrototypeOf) return setPrototypeOf; - hasRequiredSetPrototypeOf = 1; - setPrototypeOf = requireIsImplemented()() ? Object.setPrototypeOf : requireShim(); - return setPrototypeOf; -} -var validObject; -var hasRequiredValidObject; -function requireValidObject() { - if (hasRequiredValidObject) return validObject; - hasRequiredValidObject = 1; - var isObject = index$3.isObject; - validObject = function(value2) { - if (!isObject(value2)) throw new TypeError(value2 + " is not an Object"); - return value2; - }; - return validObject; -} -var randomUniq; -var hasRequiredRandomUniq; -function requireRandomUniq() { - if (hasRequiredRandomUniq) return randomUniq; - hasRequiredRandomUniq = 1; - var generated = /* @__PURE__ */ Object.create(null), random = Math.random; - randomUniq = function() { - var str2; - do { - str2 = random().toString(36).slice(2); - } while (generated[str2]); - return str2; - }; - return randomUniq; -} -var array$1 = { exports: {} }; -var clear; -var hasRequiredClear; -function requireClear() { - if (hasRequiredClear) return clear; - hasRequiredClear = 1; - var value2 = index$3.validValue; - clear = function() { - value2(this).length = 0; - return this; - }; - return clear; -} -var coerce; -var hasRequiredCoerce; -function requireCoerce() { - if (hasRequiredCoerce) return coerce; - hasRequiredCoerce = 1; - var isValue = index$3.is, isObject = index$3.is$1; - var objectToString = Object.prototype.toString; - coerce = function(value2) { - if (!isValue(value2)) return null; - if (isObject(value2)) { - var valueToString = value2.toString; - if (typeof valueToString !== "function") return null; - if (valueToString === objectToString) return null; - } - try { - return "" + value2; - } catch (error) { - return null; - } - }; - return coerce; -} -var safeToString; -var hasRequiredSafeToString; -function requireSafeToString() { - if (hasRequiredSafeToString) return safeToString; - hasRequiredSafeToString = 1; - safeToString = function(value2) { - try { - return value2.toString(); - } catch (error) { - try { - return String(value2); - } catch (error2) { - return null; - } - } - }; - return safeToString; -} -var toShortString; -var hasRequiredToShortString; -function requireToShortString() { - if (hasRequiredToShortString) return toShortString; - hasRequiredToShortString = 1; - var safeToString2 = requireSafeToString(); - var reNewLine = /[\n\r\u2028\u2029]/g; - toShortString = function(value2) { - var string2 = safeToString2(value2); - if (string2 === null) return ""; - if (string2.length > 100) string2 = string2.slice(0, 99) + "…"; - string2 = string2.replace(reNewLine, function(char) { - switch (char) { - case "\n": - return "\\n"; - case "\r": - return "\\r"; - case "\u2028": - return "\\u2028"; - case "\u2029": - return "\\u2029"; - default: - throw new Error("Unexpected character"); - } - }); - return string2; - }; - return toShortString; -} -var resolveErrorMessage; -var hasRequiredResolveErrorMessage; -function requireResolveErrorMessage() { - if (hasRequiredResolveErrorMessage) return resolveErrorMessage; - hasRequiredResolveErrorMessage = 1; - var stringCoerce = requireCoerce(), toShortString2 = requireToShortString(); - resolveErrorMessage = function(errorMessage, value2, inputOptions) { - if (inputOptions && inputOptions.errorMessage) { - errorMessage = stringCoerce(inputOptions.errorMessage); - } - var valueInsertIndex = errorMessage.indexOf("%v"); - var valueToken = valueInsertIndex > -1 ? toShortString2(value2) : null; - if (inputOptions && inputOptions.name) { - var nameInsertIndex = errorMessage.indexOf("%n"); - if (nameInsertIndex > -1) { - if (valueInsertIndex > -1) { - var firstToken, secondToken, firstInsertIndex, secondInsertIndex; - if (nameInsertIndex > valueInsertIndex) { - firstToken = valueToken; - firstInsertIndex = valueInsertIndex; - secondToken = inputOptions.name; - secondInsertIndex = nameInsertIndex; - } else { - firstToken = inputOptions.name; - firstInsertIndex = nameInsertIndex; - secondToken = valueToken; - secondInsertIndex = valueInsertIndex; - } - return errorMessage.slice(0, firstInsertIndex) + firstToken + errorMessage.slice(firstInsertIndex + 2, secondInsertIndex) + secondToken + errorMessage.slice(secondInsertIndex + 2); - } - return errorMessage.slice(0, nameInsertIndex) + inputOptions.name + errorMessage.slice(nameInsertIndex + 2); - } - } - if (valueInsertIndex > -1) { - return errorMessage.slice(0, valueInsertIndex) + valueToken + errorMessage.slice(valueInsertIndex + 2); - } - return errorMessage; - }; - return resolveErrorMessage; -} -var resolveException; -var hasRequiredResolveException; -function requireResolveException() { - if (hasRequiredResolveException) return resolveException; - hasRequiredResolveException = 1; - var isValue = index$3.is, resolveErrorMessage2 = requireResolveErrorMessage(); - resolveException = function(value2, defaultMessage, inputOptions) { - if (inputOptions && !isValue(value2)) { - if ("default" in inputOptions) return inputOptions["default"]; - if (inputOptions.isOptional) return null; - } - var ErrorConstructor = inputOptions && inputOptions.Error || TypeError; - var error = new ErrorConstructor(resolveErrorMessage2(defaultMessage, value2, inputOptions)); - if (inputOptions && inputOptions.errorCode) error.code = inputOptions.errorCode; - throw error; - }; - return resolveException; -} -var ensure$1; -var hasRequiredEnsure$1; -function requireEnsure$1() { - if (hasRequiredEnsure$1) return ensure$1; - hasRequiredEnsure$1 = 1; - var resolveException2 = requireResolveException(), is = index$3.is; - ensure$1 = function(value2) { - if (is(value2)) return value2; - var options = arguments[1]; - var errorMessage = options && options.name ? "Expected a value for %n, received %v" : "Cannot use %v"; - return resolveException2(value2, errorMessage, options); - }; - return ensure$1; -} -var ensure; -var hasRequiredEnsure; -function requireEnsure() { - if (hasRequiredEnsure) return ensure; - hasRequiredEnsure = 1; - var resolveException2 = requireResolveException(), is = index$3.is$2; - ensure = function(value2) { - if (is(value2)) return value2; - var options = arguments[1]; - var errorMessage = options && options.name ? "Expected a plain function for %n, received %v" : "%v is not a plain function"; - return resolveException2(value2, errorMessage, options); - }; - return ensure; -} -var copy; -var hasRequiredCopy; -function requireCopy() { - if (hasRequiredCopy) return copy; - hasRequiredCopy = 1; - var aFrom = index$3.requireFrom(), assign = index$3.assign, value2 = index$3.validValue; - copy = function(obj) { - var copy2 = Object(value2(obj)), propertyNames = arguments[1], options = Object(arguments[2]); - if (copy2 !== obj && !propertyNames) return copy2; - var result = {}; - if (propertyNames) { - aFrom(propertyNames, function(propertyName) { - if (options.ensure || propertyName in obj) result[propertyName] = obj[propertyName]; - }); - } else { - assign(result, obj); - } - return result; - }; - return copy; -} -var autoBind; -var hasRequiredAutoBind; -function requireAutoBind() { - if (hasRequiredAutoBind) return autoBind; - hasRequiredAutoBind = 1; - var isValue = index$3.is, ensureValue = requireEnsure$1(), ensurePlainFunction = requireEnsure(), copy2 = requireCopy(), normalizeOptions = index$3.normalizeOptions, map2 = index$3.requireMap(); - var bind = Function.prototype.bind, defineProperty = Object.defineProperty, hasOwnProperty = Object.prototype.hasOwnProperty, define2; - define2 = function(name2, desc, options) { - var value2 = ensureValue(desc) && ensurePlainFunction(desc.value), dgs; - dgs = copy2(desc); - delete dgs.writable; - delete dgs.value; - dgs.get = function() { - if (!options.overwriteDefinition && hasOwnProperty.call(this, name2)) return value2; - desc.value = bind.call(value2, options.resolveContext ? options.resolveContext(this) : this); - defineProperty(this, name2, desc); - return this[name2]; - }; - return dgs; - }; - autoBind = function(props) { - var options = normalizeOptions(arguments[1]); - if (isValue(options.resolveContext)) ensurePlainFunction(options.resolveContext); - return map2(props, function(desc, name2) { - return define2(name2, desc, options); - }); - }; - return autoBind; -} -var es6Iterator; -var hasRequiredEs6Iterator; -function requireEs6Iterator() { - if (hasRequiredEs6Iterator) return es6Iterator; - hasRequiredEs6Iterator = 1; - var clear2 = requireClear(), assign = index$3.assign, callable = index$3.validCallable, value2 = index$3.validValue, d = index$3.dExports, autoBind2 = requireAutoBind(), Symbol2 = index$3.requireEs6Symbol(); - var defineProperty = Object.defineProperty, defineProperties = Object.defineProperties, Iterator; - es6Iterator = Iterator = function(list, context2) { - if (!(this instanceof Iterator)) throw new TypeError("Constructor requires 'new'"); - defineProperties(this, { - __list__: d("w", value2(list)), - __context__: d("w", context2), - __nextIndex__: d("w", 0) - }); - if (!context2) return; - callable(context2.on); - context2.on("_add", this._onAdd); - context2.on("_delete", this._onDelete); - context2.on("_clear", this._onClear); - }; - delete Iterator.prototype.constructor; - defineProperties( - Iterator.prototype, - assign( - { - _next: d(function() { - var i; - if (!this.__list__) return void 0; - if (this.__redo__) { - i = this.__redo__.shift(); - if (i !== void 0) return i; - } - if (this.__nextIndex__ < this.__list__.length) return this.__nextIndex__++; - this._unBind(); - return void 0; - }), - next: d(function() { - return this._createResult(this._next()); - }), - _createResult: d(function(i) { - if (i === void 0) return { done: true, value: void 0 }; - return { done: false, value: this._resolve(i) }; - }), - _resolve: d(function(i) { - return this.__list__[i]; - }), - _unBind: d(function() { - this.__list__ = null; - delete this.__redo__; - if (!this.__context__) return; - this.__context__.off("_add", this._onAdd); - this.__context__.off("_delete", this._onDelete); - this.__context__.off("_clear", this._onClear); - this.__context__ = null; - }), - toString: d(function() { - return "[object " + (this[Symbol2.toStringTag] || "Object") + "]"; - }) - }, - autoBind2({ - _onAdd: d(function(index2) { - if (index2 >= this.__nextIndex__) return; - ++this.__nextIndex__; - if (!this.__redo__) { - defineProperty(this, "__redo__", d("c", [index2])); - return; - } - this.__redo__.forEach(function(redo2, i) { - if (redo2 >= index2) this.__redo__[i] = ++redo2; - }, this); - this.__redo__.push(index2); - }), - _onDelete: d(function(index2) { - var i; - if (index2 >= this.__nextIndex__) return; - --this.__nextIndex__; - if (!this.__redo__) return; - i = this.__redo__.indexOf(index2); - if (i !== -1) this.__redo__.splice(i, 1); - this.__redo__.forEach(function(redo2, j) { - if (redo2 > index2) this.__redo__[j] = --redo2; - }, this); - }), - _onClear: d(function() { - if (this.__redo__) clear2.call(this.__redo__); - this.__nextIndex__ = 0; - }) - }) - ) - ); - defineProperty( - Iterator.prototype, - Symbol2.iterator, - d(function() { - return this; - }) - ); - return es6Iterator; -} -var hasRequiredArray; -function requireArray() { - if (hasRequiredArray) return array$1.exports; - hasRequiredArray = 1; - var setPrototypeOf2 = requireSetPrototypeOf(), contains = index$3.contains, d = index$3.dExports, Symbol2 = index$3.requireEs6Symbol(), Iterator = requireEs6Iterator(); - var defineProperty = Object.defineProperty, ArrayIterator; - ArrayIterator = array$1.exports = function(arr, kind) { - if (!(this instanceof ArrayIterator)) throw new TypeError("Constructor requires 'new'"); - Iterator.call(this, arr); - if (!kind) kind = "value"; - else if (contains.call(kind, "key+value")) kind = "key+value"; - else if (contains.call(kind, "key")) kind = "key"; - else kind = "value"; - defineProperty(this, "__kind__", d("", kind)); - }; - if (setPrototypeOf2) setPrototypeOf2(ArrayIterator, Iterator); - delete ArrayIterator.prototype.constructor; - ArrayIterator.prototype = Object.create(Iterator.prototype, { - _resolve: d(function(i) { - if (this.__kind__ === "value") return this.__list__[i]; - if (this.__kind__ === "key+value") return [i, this.__list__[i]]; - return i; - }) - }); - defineProperty(ArrayIterator.prototype, Symbol2.toStringTag, d("c", "Array Iterator")); - return array$1.exports; -} -var string$1 = { exports: {} }; -var hasRequiredString; -function requireString() { - if (hasRequiredString) return string$1.exports; - hasRequiredString = 1; - var setPrototypeOf2 = requireSetPrototypeOf(), d = index$3.dExports, Symbol2 = index$3.requireEs6Symbol(), Iterator = requireEs6Iterator(); - var defineProperty = Object.defineProperty, StringIterator; - StringIterator = string$1.exports = function(str2) { - if (!(this instanceof StringIterator)) throw new TypeError("Constructor requires 'new'"); - str2 = String(str2); - Iterator.call(this, str2); - defineProperty(this, "__length__", d("", str2.length)); - }; - if (setPrototypeOf2) setPrototypeOf2(StringIterator, Iterator); - delete StringIterator.prototype.constructor; - StringIterator.prototype = Object.create(Iterator.prototype, { - _next: d(function() { - if (!this.__list__) return void 0; - if (this.__nextIndex__ < this.__length__) return this.__nextIndex__++; - this._unBind(); - return void 0; - }), - _resolve: d(function(i) { - var char = this.__list__[i], code2; - if (this.__nextIndex__ === this.__length__) return char; - code2 = char.charCodeAt(0); - if (code2 >= 55296 && code2 <= 56319) return char + this.__list__[this.__nextIndex__++]; - return char; - }) - }); - defineProperty(StringIterator.prototype, Symbol2.toStringTag, d("c", "String Iterator")); - return string$1.exports; -} -var isIterable; -var hasRequiredIsIterable; -function requireIsIterable() { - if (hasRequiredIsIterable) return isIterable; - hasRequiredIsIterable = 1; - var isArguments = index$3.requireIsArguments(), isValue = index$3.isValue, isString = index$3.requireIsString(); - var iteratorSymbol = index$3.requireEs6Symbol().iterator, isArray2 = Array.isArray; - isIterable = function(value2) { - if (!isValue(value2)) return false; - if (isArray2(value2)) return true; - if (isString(value2)) return true; - if (isArguments(value2)) return true; - return typeof value2[iteratorSymbol] === "function"; - }; - return isIterable; -} -var validIterable; -var hasRequiredValidIterable; -function requireValidIterable() { - if (hasRequiredValidIterable) return validIterable; - hasRequiredValidIterable = 1; - var isIterable2 = requireIsIterable(); - validIterable = function(value2) { - if (!isIterable2(value2)) throw new TypeError(value2 + " is not iterable"); - return value2; - }; - return validIterable; -} -var get2; -var hasRequiredGet; -function requireGet() { - if (hasRequiredGet) return get2; - hasRequiredGet = 1; - var isArguments = index$3.requireIsArguments(), isString = index$3.requireIsString(), ArrayIterator = requireArray(), StringIterator = requireString(), iterable = requireValidIterable(), iteratorSymbol = index$3.requireEs6Symbol().iterator; - get2 = function(obj) { - if (typeof iterable(obj)[iteratorSymbol] === "function") return obj[iteratorSymbol](); - if (isArguments(obj)) return new ArrayIterator(obj); - if (isString(obj)) return new StringIterator(obj); - return new ArrayIterator(obj); - }; - return get2; -} -var forOf; -var hasRequiredForOf; -function requireForOf() { - if (hasRequiredForOf) return forOf; - hasRequiredForOf = 1; - var isArguments = index$3.requireIsArguments(), callable = index$3.validCallable, isString = index$3.requireIsString(), get3 = requireGet(); - var isArray2 = Array.isArray, call = Function.prototype.call, some = Array.prototype.some; - forOf = function(iterable, cb) { - var mode, thisArg = arguments[2], result, doBreak, broken, i, length2, char, code2; - if (isArray2(iterable) || isArguments(iterable)) mode = "array"; - else if (isString(iterable)) mode = "string"; - else iterable = get3(iterable); - callable(cb); - doBreak = function() { - broken = true; - }; - if (mode === "array") { - some.call(iterable, function(value2) { - call.call(cb, thisArg, value2, doBreak); - return broken; - }); - return; - } - if (mode === "string") { - length2 = iterable.length; - for (i = 0; i < length2; ++i) { - char = iterable[i]; - if (i + 1 < length2) { - code2 = char.charCodeAt(0); - if (code2 >= 55296 && code2 <= 56319) char += iterable[++i]; - } - call.call(cb, thisArg, char, doBreak); - if (broken) break; - } - return; - } - result = iterable.next(); - while (!result.done) { - call.call(cb, thisArg, result.value, doBreak); - if (broken) return; - result = iterable.next(); - } - }; - return forOf; -} -var isNativeImplemented; -var hasRequiredIsNativeImplemented; -function requireIsNativeImplemented() { - if (hasRequiredIsNativeImplemented) return isNativeImplemented; - hasRequiredIsNativeImplemented = 1; - isNativeImplemented = function() { - if (typeof WeakMap !== "function") return false; - return Object.prototype.toString.call(/* @__PURE__ */ new WeakMap()) === "[object WeakMap]"; - }(); - return isNativeImplemented; -} -var polyfill; -var hasRequiredPolyfill; -function requirePolyfill() { - if (hasRequiredPolyfill) return polyfill; - hasRequiredPolyfill = 1; - var isValue = index$3.isValue, setPrototypeOf2 = requireSetPrototypeOf(), object2 = requireValidObject(), ensureValue = index$3.validValue, randomUniq2 = requireRandomUniq(), d = index$3.dExports, getIterator = requireGet(), forOf2 = requireForOf(), toStringTagSymbol = index$3.requireEs6Symbol().toStringTag, isNative = requireIsNativeImplemented(), isArray2 = Array.isArray, defineProperty = Object.defineProperty, objHasOwnProperty = Object.prototype.hasOwnProperty, getPrototypeOf = Object.getPrototypeOf, WeakMapPoly; - polyfill = WeakMapPoly = function() { - var iterable = arguments[0], self2; - if (!(this instanceof WeakMapPoly)) throw new TypeError("Constructor requires 'new'"); - self2 = isNative && setPrototypeOf2 && WeakMap !== WeakMapPoly ? setPrototypeOf2(/* @__PURE__ */ new WeakMap(), getPrototypeOf(this)) : this; - if (isValue(iterable)) { - if (!isArray2(iterable)) iterable = getIterator(iterable); - } - defineProperty(self2, "__weakMapData__", d("c", "$weakMap$" + randomUniq2())); - if (!iterable) return self2; - forOf2(iterable, function(val) { - ensureValue(val); - self2.set(val[0], val[1]); - }); - return self2; - }; - if (isNative) { - if (setPrototypeOf2) setPrototypeOf2(WeakMapPoly, WeakMap); - WeakMapPoly.prototype = Object.create(WeakMap.prototype, { constructor: d(WeakMapPoly) }); - } - Object.defineProperties(WeakMapPoly.prototype, { - delete: d(function(key) { - if (objHasOwnProperty.call(object2(key), this.__weakMapData__)) { - delete key[this.__weakMapData__]; - return true; - } - return false; - }), - get: d(function(key) { - if (!objHasOwnProperty.call(object2(key), this.__weakMapData__)) return void 0; - return key[this.__weakMapData__]; - }), - has: d(function(key) { - return objHasOwnProperty.call(object2(key), this.__weakMapData__); - }), - set: d(function(key, value2) { - defineProperty(object2(key), this.__weakMapData__, d("c", value2)); - return this; - }), - toString: d(function() { - return "[object WeakMap]"; - }) - }); - defineProperty(WeakMapPoly.prototype, toStringTagSymbol, d("c", "WeakMap")); - return polyfill; -} -var es6WeakMap = isImplemented$1() ? WeakMap : requirePolyfill(); -var arrayFindIndex = function(arr, predicate, ctx2) { - if (typeof Array.prototype.findIndex === "function") { - return arr.findIndex(predicate, ctx2); - } - if (typeof predicate !== "function") { - throw new TypeError("predicate must be a function"); - } - var list = Object(arr); - var len = list.length; - if (len === 0) { - return -1; - } - for (var i = 0; i < len; i++) { - if (predicate.call(ctx2, list[i], i, list)) { - return i; - } - } - return -1; -}; -const rgba$3 = colorNormalize; -const getBounds$1 = arrayBounds; -const extend$3 = index$3.objectAssign; -const pick$4 = pickByAlias; -const flatten$2 = flattenVertexData_1; -const triangulate = earcutExports; -const normalize2 = arrayNormalize; -const { float32: float32$1, fract32: fract32$1 } = toFloat32Exports; -const WeakMap$2 = es6WeakMap; -const parseRect$1 = parseRect_1; -const findIndex = arrayFindIndex; -const rectVert = ` -precision highp float; - -attribute vec2 aCoord, bCoord, aCoordFract, bCoordFract; -attribute vec4 color; -attribute float lineEnd, lineTop; - -uniform vec2 scale, scaleFract, translate, translateFract; -uniform float thickness, pixelRatio, id, depth; -uniform vec4 viewport; - -varying vec4 fragColor; -varying vec2 tangent; - -vec2 project(vec2 position, vec2 positionFract, vec2 scale, vec2 scaleFract, vec2 translate, vec2 translateFract) { - // the order is important - return position * scale + translate - + positionFract * scale + translateFract - + position * scaleFract - + positionFract * scaleFract; -} - -void main() { - float lineStart = 1. - lineEnd; - float lineOffset = lineTop * 2. - 1.; - - vec2 diff = (bCoord + bCoordFract - aCoord - aCoordFract); - tangent = normalize(diff * scale * viewport.zw); - vec2 normal = vec2(-tangent.y, tangent.x); - - vec2 position = project(aCoord, aCoordFract, scale, scaleFract, translate, translateFract) * lineStart - + project(bCoord, bCoordFract, scale, scaleFract, translate, translateFract) * lineEnd - - + thickness * normal * .5 * lineOffset / viewport.zw; - - gl_Position = vec4(position * 2.0 - 1.0, depth, 1); - - fragColor = color / 255.; -} -`; -const rectFrag = ` -precision highp float; - -uniform float dashLength, pixelRatio, thickness, opacity, id; -uniform sampler2D dashTexture; - -varying vec4 fragColor; -varying vec2 tangent; - -void main() { - float alpha = 1.; - - float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25; - float dash = texture2D(dashTexture, vec2(t, .5)).r; - - gl_FragColor = fragColor; - gl_FragColor.a *= alpha * opacity * dash; -} -`; -const fillVert = ` -precision highp float; - -attribute vec2 position, positionFract; - -uniform vec4 color; -uniform vec2 scale, scaleFract, translate, translateFract; -uniform float pixelRatio, id; -uniform vec4 viewport; -uniform float opacity; - -varying vec4 fragColor; - -const float MAX_LINES = 256.; - -void main() { - float depth = (MAX_LINES - 4. - id) / (MAX_LINES); - - vec2 position = position * scale + translate - + positionFract * scale + translateFract - + position * scaleFract - + positionFract * scaleFract; - - gl_Position = vec4(position * 2.0 - 1.0, depth, 1); - - fragColor = color / 255.; - fragColor.a *= opacity; -} -`; -const fillFrag = ` -precision highp float; -varying vec4 fragColor; - -void main() { - gl_FragColor = fragColor; -} -`; -const milterVert = ` -precision highp float; - -attribute vec2 aCoord, bCoord, nextCoord, prevCoord; -attribute vec4 aColor, bColor; -attribute float lineEnd, lineTop; - -uniform vec2 scale, translate; -uniform float thickness, pixelRatio, id, depth; -uniform vec4 viewport; -uniform float miterLimit, miterMode; - -varying vec4 fragColor; -varying vec4 startCutoff, endCutoff; -varying vec2 tangent; -varying vec2 startCoord, endCoord; -varying float enableStartMiter, enableEndMiter; - -const float REVERSE_THRESHOLD = -.875; -const float MIN_DIFF = 1e-6; - -// TODO: possible optimizations: avoid overcalculating all for vertices and calc just one instead -// TODO: precalculate dot products, normalize things beforehead etc. -// TODO: refactor to rectangular algorithm - -float distToLine(vec2 p, vec2 a, vec2 b) { - vec2 diff = b - a; - vec2 perp = normalize(vec2(-diff.y, diff.x)); - return dot(p - a, perp); -} - -bool isNaN( float val ){ - return ( val < 0.0 || 0.0 < val || val == 0.0 ) ? false : true; -} - -void main() { - vec2 aCoord = aCoord, bCoord = bCoord, prevCoord = prevCoord, nextCoord = nextCoord; - - vec2 adjustedScale; - adjustedScale.x = (abs(scale.x) < MIN_DIFF) ? MIN_DIFF : scale.x; - adjustedScale.y = (abs(scale.y) < MIN_DIFF) ? MIN_DIFF : scale.y; - - vec2 scaleRatio = adjustedScale * viewport.zw; - vec2 normalWidth = thickness / scaleRatio; - - float lineStart = 1. - lineEnd; - float lineBot = 1. - lineTop; - - fragColor = (lineStart * aColor + lineEnd * bColor) / 255.; - - if (isNaN(aCoord.x) || isNaN(aCoord.y) || isNaN(bCoord.x) || isNaN(bCoord.y)) return; - - if (aCoord == prevCoord) prevCoord = aCoord + normalize(bCoord - aCoord); - if (bCoord == nextCoord) nextCoord = bCoord - normalize(bCoord - aCoord); - - - vec2 prevDiff = aCoord - prevCoord; - vec2 currDiff = bCoord - aCoord; - vec2 nextDiff = nextCoord - bCoord; - - vec2 prevTangent = normalize(prevDiff * scaleRatio); - vec2 currTangent = normalize(currDiff * scaleRatio); - vec2 nextTangent = normalize(nextDiff * scaleRatio); - - vec2 prevNormal = vec2(-prevTangent.y, prevTangent.x); - vec2 currNormal = vec2(-currTangent.y, currTangent.x); - vec2 nextNormal = vec2(-nextTangent.y, nextTangent.x); - - vec2 startJoinDirection = normalize(prevTangent - currTangent); - vec2 endJoinDirection = normalize(currTangent - nextTangent); - - // collapsed/unidirectional segment cases - // FIXME: there should be more elegant solution - vec2 prevTanDiff = abs(prevTangent - currTangent); - vec2 nextTanDiff = abs(nextTangent - currTangent); - if (max(prevTanDiff.x, prevTanDiff.y) < MIN_DIFF) { - startJoinDirection = currNormal; - } - if (max(nextTanDiff.x, nextTanDiff.y) < MIN_DIFF) { - endJoinDirection = currNormal; - } - if (aCoord == bCoord) { - endJoinDirection = startJoinDirection; - currNormal = prevNormal; - currTangent = prevTangent; - } - - tangent = currTangent; - - //calculate join shifts relative to normals - float startJoinShift = dot(currNormal, startJoinDirection); - float endJoinShift = dot(currNormal, endJoinDirection); - - float startMiterRatio = abs(1. / startJoinShift); - float endMiterRatio = abs(1. / endJoinShift); - - vec2 startJoin = startJoinDirection * startMiterRatio; - vec2 endJoin = endJoinDirection * endMiterRatio; - - vec2 startTopJoin, startBotJoin, endTopJoin, endBotJoin; - startTopJoin = sign(startJoinShift) * startJoin * .5; - startBotJoin = -startTopJoin; - - endTopJoin = sign(endJoinShift) * endJoin * .5; - endBotJoin = -endTopJoin; - - vec2 aTopCoord = aCoord + normalWidth * startTopJoin; - vec2 bTopCoord = bCoord + normalWidth * endTopJoin; - vec2 aBotCoord = aCoord + normalWidth * startBotJoin; - vec2 bBotCoord = bCoord + normalWidth * endBotJoin; - - //miter anti-clipping - float baClipping = distToLine(bCoord, aCoord, aBotCoord) / dot(normalize(normalWidth * endBotJoin), normalize(normalWidth.yx * vec2(-startBotJoin.y, startBotJoin.x))); - float abClipping = distToLine(aCoord, bCoord, bTopCoord) / dot(normalize(normalWidth * startBotJoin), normalize(normalWidth.yx * vec2(-endBotJoin.y, endBotJoin.x))); - - //prevent close to reverse direction switch - bool prevReverse = dot(currTangent, prevTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, prevNormal)) * min(length(prevDiff), length(currDiff)) < length(normalWidth * currNormal); - bool nextReverse = dot(currTangent, nextTangent) <= REVERSE_THRESHOLD && abs(dot(currTangent, nextNormal)) * min(length(nextDiff), length(currDiff)) < length(normalWidth * currNormal); - - if (prevReverse) { - //make join rectangular - vec2 miterShift = normalWidth * startJoinDirection * miterLimit * .5; - float normalAdjust = 1. - min(miterLimit / startMiterRatio, 1.); - aBotCoord = aCoord + miterShift - normalAdjust * normalWidth * currNormal * .5; - aTopCoord = aCoord + miterShift + normalAdjust * normalWidth * currNormal * .5; - } - else if (!nextReverse && baClipping > 0. && baClipping < length(normalWidth * endBotJoin)) { - //handle miter clipping - bTopCoord -= normalWidth * endTopJoin; - bTopCoord += normalize(endTopJoin * normalWidth) * baClipping; - } - - if (nextReverse) { - //make join rectangular - vec2 miterShift = normalWidth * endJoinDirection * miterLimit * .5; - float normalAdjust = 1. - min(miterLimit / endMiterRatio, 1.); - bBotCoord = bCoord + miterShift - normalAdjust * normalWidth * currNormal * .5; - bTopCoord = bCoord + miterShift + normalAdjust * normalWidth * currNormal * .5; - } - else if (!prevReverse && abClipping > 0. && abClipping < length(normalWidth * startBotJoin)) { - //handle miter clipping - aBotCoord -= normalWidth * startBotJoin; - aBotCoord += normalize(startBotJoin * normalWidth) * abClipping; - } - - vec2 aTopPosition = (aTopCoord) * adjustedScale + translate; - vec2 aBotPosition = (aBotCoord) * adjustedScale + translate; - - vec2 bTopPosition = (bTopCoord) * adjustedScale + translate; - vec2 bBotPosition = (bBotCoord) * adjustedScale + translate; - - //position is normalized 0..1 coord on the screen - vec2 position = (aTopPosition * lineTop + aBotPosition * lineBot) * lineStart + (bTopPosition * lineTop + bBotPosition * lineBot) * lineEnd; - - startCoord = aCoord * scaleRatio + translate * viewport.zw + viewport.xy; - endCoord = bCoord * scaleRatio + translate * viewport.zw + viewport.xy; - - gl_Position = vec4(position * 2.0 - 1.0, depth, 1); - - enableStartMiter = step(dot(currTangent, prevTangent), .5); - enableEndMiter = step(dot(currTangent, nextTangent), .5); - - //bevel miter cutoffs - if (miterMode == 1.) { - if (enableStartMiter == 1.) { - vec2 startMiterWidth = vec2(startJoinDirection) * thickness * miterLimit * .5; - startCutoff = vec4(aCoord, aCoord); - startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio; - startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; - startCutoff += viewport.xyxy; - startCutoff += startMiterWidth.xyxy; - } - - if (enableEndMiter == 1.) { - vec2 endMiterWidth = vec2(endJoinDirection) * thickness * miterLimit * .5; - endCutoff = vec4(bCoord, bCoord); - endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio; - endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; - endCutoff += viewport.xyxy; - endCutoff += endMiterWidth.xyxy; - } - } - - //round miter cutoffs - else if (miterMode == 2.) { - if (enableStartMiter == 1.) { - vec2 startMiterWidth = vec2(startJoinDirection) * thickness * abs(dot(startJoinDirection, currNormal)) * .5; - startCutoff = vec4(aCoord, aCoord); - startCutoff.zw += vec2(-startJoinDirection.y, startJoinDirection.x) / scaleRatio; - startCutoff = startCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; - startCutoff += viewport.xyxy; - startCutoff += startMiterWidth.xyxy; - } - - if (enableEndMiter == 1.) { - vec2 endMiterWidth = vec2(endJoinDirection) * thickness * abs(dot(endJoinDirection, currNormal)) * .5; - endCutoff = vec4(bCoord, bCoord); - endCutoff.zw += vec2(-endJoinDirection.y, endJoinDirection.x) / scaleRatio; - endCutoff = endCutoff * scaleRatio.xyxy + translate.xyxy * viewport.zwzw; - endCutoff += viewport.xyxy; - endCutoff += endMiterWidth.xyxy; - } - } -} -`; -const milterFrag = ` -precision highp float; - -uniform float dashLength, pixelRatio, thickness, opacity, id, miterMode; -uniform sampler2D dashTexture; - -varying vec4 fragColor; -varying vec2 tangent; -varying vec4 startCutoff, endCutoff; -varying vec2 startCoord, endCoord; -varying float enableStartMiter, enableEndMiter; - -float distToLine(vec2 p, vec2 a, vec2 b) { - vec2 diff = b - a; - vec2 perp = normalize(vec2(-diff.y, diff.x)); - return dot(p - a, perp); -} - -void main() { - float alpha = 1., distToStart, distToEnd; - float cutoff = thickness * .5; - - //bevel miter - if (miterMode == 1.) { - if (enableStartMiter == 1.) { - distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw); - if (distToStart < -1.) { - discard; - return; - } - alpha *= min(max(distToStart + 1., 0.), 1.); - } - - if (enableEndMiter == 1.) { - distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw); - if (distToEnd < -1.) { - discard; - return; - } - alpha *= min(max(distToEnd + 1., 0.), 1.); - } - } - - // round miter - else if (miterMode == 2.) { - if (enableStartMiter == 1.) { - distToStart = distToLine(gl_FragCoord.xy, startCutoff.xy, startCutoff.zw); - if (distToStart < 0.) { - float radius = length(gl_FragCoord.xy - startCoord); - - if(radius > cutoff + .5) { - discard; - return; - } - - alpha -= smoothstep(cutoff - .5, cutoff + .5, radius); - } - } - - if (enableEndMiter == 1.) { - distToEnd = distToLine(gl_FragCoord.xy, endCutoff.xy, endCutoff.zw); - if (distToEnd < 0.) { - float radius = length(gl_FragCoord.xy - endCoord); - - if(radius > cutoff + .5) { - discard; - return; - } - - alpha -= smoothstep(cutoff - .5, cutoff + .5, radius); - } - } - } - - float t = fract(dot(tangent, gl_FragCoord.xy) / dashLength) * .5 + .25; - float dash = texture2D(dashTexture, vec2(t, .5)).r; - - gl_FragColor = fragColor; - gl_FragColor.a *= alpha * opacity * dash; -} -`; -var reglLine2d = Line2D; -function Line2D(regl, options) { - if (!(this instanceof Line2D)) return new Line2D(regl, options); - if (typeof regl === "function") { - if (!options) options = {}; - options.regl = regl; - } else { - options = regl; - } - if (options.length) options.positions = options; - regl = options.regl; - if (!regl.hasExtension("ANGLE_instanced_arrays")) { - throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled"); - } - this.gl = regl._gl; - this.regl = regl; - this.passes = []; - this.shaders = Line2D.shaders.has(regl) ? Line2D.shaders.get(regl) : Line2D.shaders.set(regl, Line2D.createShaders(regl)).get(regl); - this.update(options); -} -Line2D.dashMult = 2; -Line2D.maxPatternLength = 256; -Line2D.precisionThreshold = 3e6; -Line2D.maxPoints = 1e4; -Line2D.maxLines = 2048; -Line2D.shaders = new WeakMap$2(); -Line2D.createShaders = function(regl) { - let offsetBuffer = regl.buffer({ - usage: "static", - type: "float", - data: [0, 1, 0, 0, 1, 1, 1, 0] - }); - let shaderOptions = { - primitive: "triangle strip", - instances: regl.prop("count"), - count: 4, - offset: 0, - uniforms: { - miterMode: (ctx2, prop) => prop.join === "round" ? 2 : 1, - miterLimit: regl.prop("miterLimit"), - scale: regl.prop("scale"), - scaleFract: regl.prop("scaleFract"), - translateFract: regl.prop("translateFract"), - translate: regl.prop("translate"), - thickness: regl.prop("thickness"), - dashTexture: regl.prop("dashTexture"), - opacity: regl.prop("opacity"), - pixelRatio: regl.context("pixelRatio"), - id: regl.prop("id"), - dashLength: regl.prop("dashLength"), - viewport: (c, p) => [p.viewport.x, p.viewport.y, c.viewportWidth, c.viewportHeight], - depth: regl.prop("depth") - }, - blend: { - enable: true, - color: [0, 0, 0, 0], - equation: { - rgb: "add", - alpha: "add" - }, - func: { - srcRGB: "src alpha", - dstRGB: "one minus src alpha", - srcAlpha: "one minus dst alpha", - dstAlpha: "one" - } - }, - depth: { - enable: (c, p) => { - return !p.overlay; - } - }, - stencil: { enable: false }, - scissor: { - enable: true, - box: regl.prop("viewport") - }, - viewport: regl.prop("viewport") - }; - let drawRectLine = regl(extend$3({ - vert: rectVert, - frag: rectFrag, - attributes: { - // if point is at the end of segment - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - // if point is at the top of segment - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - // beginning of line coordinate - aCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 8, - divisor: 1 - }, - // end of line coordinate - bCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 16, - divisor: 1 - }, - aCoordFract: { - buffer: regl.prop("positionFractBuffer"), - stride: 8, - offset: 8, - divisor: 1 - }, - bCoordFract: { - buffer: regl.prop("positionFractBuffer"), - stride: 8, - offset: 16, - divisor: 1 - }, - color: { - buffer: regl.prop("colorBuffer"), - stride: 4, - offset: 0, - divisor: 1 - } - } - }, shaderOptions)); - let drawMiterLine; - try { - drawMiterLine = regl(extend$3({ - // culling removes polygon creasing - cull: { - enable: true, - face: "back" - }, - vert: milterVert, - frag: milterFrag, - attributes: { - // is line end - lineEnd: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 0 - }, - // is line top - lineTop: { - buffer: offsetBuffer, - divisor: 0, - stride: 8, - offset: 4 - }, - // left color - aColor: { - buffer: regl.prop("colorBuffer"), - stride: 4, - offset: 0, - divisor: 1 - }, - // right color - bColor: { - buffer: regl.prop("colorBuffer"), - stride: 4, - offset: 4, - divisor: 1 - }, - prevCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 0, - divisor: 1 - }, - aCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 8, - divisor: 1 - }, - bCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 16, - divisor: 1 - }, - nextCoord: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 24, - divisor: 1 - } - } - }, shaderOptions)); - } catch (e) { - drawMiterLine = drawRectLine; - } - let drawFill = regl({ - primitive: "triangle", - elements: (ctx2, prop) => prop.triangles, - offset: 0, - vert: fillVert, - frag: fillFrag, - uniforms: { - scale: regl.prop("scale"), - color: regl.prop("fill"), - scaleFract: regl.prop("scaleFract"), - translateFract: regl.prop("translateFract"), - translate: regl.prop("translate"), - opacity: regl.prop("opacity"), - pixelRatio: regl.context("pixelRatio"), - id: regl.prop("id"), - viewport: (ctx2, prop) => [prop.viewport.x, prop.viewport.y, ctx2.viewportWidth, ctx2.viewportHeight] - }, - attributes: { - position: { - buffer: regl.prop("positionBuffer"), - stride: 8, - offset: 8 - }, - positionFract: { - buffer: regl.prop("positionFractBuffer"), - stride: 8, - offset: 8 - } - }, - blend: shaderOptions.blend, - depth: { enable: false }, - scissor: shaderOptions.scissor, - stencil: shaderOptions.stencil, - viewport: shaderOptions.viewport - }); - return { - fill: drawFill, - rect: drawRectLine, - miter: drawMiterLine - }; -}; -Line2D.defaults = { - dashes: null, - join: "miter", - miterLimit: 1, - thickness: 10, - cap: "square", - color: "black", - opacity: 1, - overlay: false, - viewport: null, - range: null, - close: false, - fill: null -}; -Line2D.prototype.render = function(...args) { - if (args.length) { - this.update(...args); - } - this.draw(); -}; -Line2D.prototype.draw = function(...args) { - (args.length ? args : this.passes).forEach((s, i) => { - if (s && Array.isArray(s)) return this.draw(...s); - if (typeof s === "number") s = this.passes[s]; - if (!(s && s.count > 1 && s.opacity)) return; - this.regl._refresh(); - if (s.fill && s.triangles && s.triangles.length > 2) { - this.shaders.fill(s); - } - if (!s.thickness) return; - if (s.scale[0] * s.viewport.width > Line2D.precisionThreshold || s.scale[1] * s.viewport.height > Line2D.precisionThreshold) { - this.shaders.rect(s); - } else if (s.join === "rect" || !s.join && (s.thickness <= 2 || s.count >= Line2D.maxPoints)) { - this.shaders.rect(s); - } else { - this.shaders.miter(s); - } - }); - return this; -}; -Line2D.prototype.update = function(options) { - if (!options) return; - if (options.length != null) { - if (typeof options[0] === "number") options = [{ positions: options }]; - } else if (!Array.isArray(options)) options = [options]; - let { regl, gl } = this; - options.forEach((o, i) => { - let state = this.passes[i]; - if (o === void 0) return; - if (o === null) { - this.passes[i] = null; - return; - } - if (typeof o[0] === "number") o = { positions: o }; - o = pick$4(o, { - positions: "positions points data coords", - thickness: "thickness lineWidth lineWidths line-width linewidth width stroke-width strokewidth strokeWidth", - join: "lineJoin linejoin join type mode", - miterLimit: "miterlimit miterLimit", - dashes: "dash dashes dasharray dash-array dashArray", - color: "color colour stroke colors colours stroke-color strokeColor", - fill: "fill fill-color fillColor", - opacity: "alpha opacity", - overlay: "overlay crease overlap intersect", - close: "closed close closed-path closePath", - range: "range dataBox", - viewport: "viewport viewBox", - hole: "holes hole hollow", - splitNull: "splitNull" - }); - if (!state) { - this.passes[i] = state = { - id: i, - scale: null, - scaleFract: null, - translate: null, - translateFract: null, - count: 0, - hole: [], - depth: 0, - dashLength: 1, - dashTexture: regl.texture({ - channels: 1, - data: new Uint8Array([255]), - width: 1, - height: 1, - mag: "linear", - min: "linear" - }), - colorBuffer: regl.buffer({ - usage: "dynamic", - type: "uint8", - data: new Uint8Array() - }), - positionBuffer: regl.buffer({ - usage: "dynamic", - type: "float", - data: new Uint8Array() - }), - positionFractBuffer: regl.buffer({ - usage: "dynamic", - type: "float", - data: new Uint8Array() - }) - }; - o = extend$3({}, Line2D.defaults, o); - } - if (o.thickness != null) state.thickness = parseFloat(o.thickness); - if (o.opacity != null) state.opacity = parseFloat(o.opacity); - if (o.miterLimit != null) state.miterLimit = parseFloat(o.miterLimit); - if (o.overlay != null) { - state.overlay = !!o.overlay; - if (i < Line2D.maxLines) { - state.depth = 2 * (Line2D.maxLines - 1 - i % Line2D.maxLines) / Line2D.maxLines - 1; - } - } - if (o.join != null) state.join = o.join; - if (o.hole != null) state.hole = o.hole; - if (o.fill != null) state.fill = !o.fill ? null : rgba$3(o.fill, "uint8"); - if (o.viewport != null) state.viewport = parseRect$1(o.viewport); - if (!state.viewport) { - state.viewport = parseRect$1([ - gl.drawingBufferWidth, - gl.drawingBufferHeight - ]); - } - if (o.close != null) state.close = o.close; - if (o.positions === null) o.positions = []; - if (o.positions) { - let positions, count2; - if (o.positions.x && o.positions.y) { - let xPos = o.positions.x; - let yPos = o.positions.y; - count2 = state.count = Math.max( - xPos.length, - yPos.length - ); - positions = new Float64Array(count2 * 2); - for (let i2 = 0; i2 < count2; i2++) { - positions[i2 * 2] = xPos[i2]; - positions[i2 * 2 + 1] = yPos[i2]; - } - } else { - positions = flatten$2(o.positions, "float64"); - count2 = state.count = Math.floor(positions.length / 2); - } - let bounds = state.bounds = getBounds$1(positions, 2); - if (state.fill) { - let pos = []; - let ids = {}; - let lastId = 0; - for (let i2 = 0, ptr = 0, l = state.count; i2 < l; i2++) { - let x = positions[i2 * 2]; - let y = positions[i2 * 2 + 1]; - if (isNaN(x) || isNaN(y) || x == null || y == null) { - x = positions[lastId * 2]; - y = positions[lastId * 2 + 1]; - ids[i2] = lastId; - } else { - lastId = i2; - } - pos[ptr++] = x; - pos[ptr++] = y; - } - if (o.splitNull) { - if (!(state.count - 1 in ids)) ids[state.count] = state.count - 1; - let splits = Object.keys(ids).map(Number).sort((a, b) => a - b); - let split_triangles = []; - let base = 0; - let hole_base = state.hole != null ? state.hole[0] : null; - if (hole_base != null) { - let last_id = findIndex(splits, (e) => e >= hole_base); - splits = splits.slice(0, last_id); - splits.push(hole_base); - } - for (let i2 = 0; i2 < splits.length; i2++) { - let seg_pos = pos.slice(base * 2, splits[i2] * 2).concat( - hole_base ? pos.slice(hole_base * 2) : [] - ); - let hole = (state.hole || []).map((e) => e - hole_base + (splits[i2] - base)); - let triangles = triangulate(seg_pos, hole); - triangles = triangles.map( - (e) => e + base + (e + base < splits[i2] ? 0 : hole_base - splits[i2]) - ); - split_triangles.push(...triangles); - base = splits[i2] + 1; - } - for (let i2 = 0, l = split_triangles.length; i2 < l; i2++) { - if (ids[split_triangles[i2]] != null) split_triangles[i2] = ids[split_triangles[i2]]; - } - state.triangles = split_triangles; - } else { - let triangles = triangulate(pos, state.hole || []); - for (let i2 = 0, l = triangles.length; i2 < l; i2++) { - if (ids[triangles[i2]] != null) triangles[i2] = ids[triangles[i2]]; - } - state.triangles = triangles; - } - } - let npos = new Float64Array(positions); - normalize2(npos, 2, bounds); - let positionData = new Float64Array(count2 * 2 + 6); - if (state.close) { - if (positions[0] === positions[count2 * 2 - 2] && positions[1] === positions[count2 * 2 - 1]) { - positionData[0] = npos[count2 * 2 - 4]; - positionData[1] = npos[count2 * 2 - 3]; - } else { - positionData[0] = npos[count2 * 2 - 2]; - positionData[1] = npos[count2 * 2 - 1]; - } - } else { - positionData[0] = npos[0]; - positionData[1] = npos[1]; - } - positionData.set(npos, 2); - if (state.close) { - if (positions[0] === positions[count2 * 2 - 2] && positions[1] === positions[count2 * 2 - 1]) { - positionData[count2 * 2 + 2] = npos[2]; - positionData[count2 * 2 + 3] = npos[3]; - state.count -= 1; - } else { - positionData[count2 * 2 + 2] = npos[0]; - positionData[count2 * 2 + 3] = npos[1]; - positionData[count2 * 2 + 4] = npos[2]; - positionData[count2 * 2 + 5] = npos[3]; - } - } else { - positionData[count2 * 2 + 2] = npos[count2 * 2 - 2]; - positionData[count2 * 2 + 3] = npos[count2 * 2 - 1]; - positionData[count2 * 2 + 4] = npos[count2 * 2 - 2]; - positionData[count2 * 2 + 5] = npos[count2 * 2 - 1]; - } - var float_data = float32$1(positionData); - state.positionBuffer(float_data); - var frac_data = fract32$1(positionData, float_data); - state.positionFractBuffer(frac_data); - } - if (o.range) { - state.range = o.range; - } else if (!state.range) { - state.range = state.bounds; - } - if ((o.range || o.positions) && state.count) { - let bounds = state.bounds; - let boundsW = bounds[2] - bounds[0], boundsH = bounds[3] - bounds[1]; - let rangeW = state.range[2] - state.range[0], rangeH = state.range[3] - state.range[1]; - state.scale = [ - boundsW / rangeW, - boundsH / rangeH - ]; - state.translate = [ - -state.range[0] / rangeW + bounds[0] / rangeW || 0, - -state.range[1] / rangeH + bounds[1] / rangeH || 0 - ]; - state.scaleFract = fract32$1(state.scale); - state.translateFract = fract32$1(state.translate); - } - if (o.dashes) { - let dashLength = 0, dashData; - if (!o.dashes || o.dashes.length < 2) { - dashLength = 1; - dashData = new Uint8Array([255, 255, 255, 255, 255, 255, 255, 255]); - } else { - dashLength = 0; - for (let i2 = 0; i2 < o.dashes.length; ++i2) { - dashLength += o.dashes[i2]; - } - dashData = new Uint8Array(dashLength * Line2D.dashMult); - let ptr = 0; - let fillColor = 255; - for (let k = 0; k < 2; k++) { - for (let i2 = 0; i2 < o.dashes.length; ++i2) { - for (let j = 0, l = o.dashes[i2] * Line2D.dashMult * 0.5; j < l; ++j) { - dashData[ptr++] = fillColor; - } - fillColor ^= 255; - } - } - } - state.dashLength = dashLength; - state.dashTexture({ - channels: 1, - data: dashData, - width: dashData.length, - height: 1, - mag: "linear", - min: "linear" - }, 0, 0); - } - if (o.color) { - let count2 = state.count; - let colors = o.color; - if (!colors) colors = "transparent"; - let colorData = new Uint8Array(count2 * 4 + 4); - if (!Array.isArray(colors) || typeof colors[0] === "number") { - let c = rgba$3(colors, "uint8"); - for (let i2 = 0; i2 < count2 + 1; i2++) { - colorData.set(c, i2 * 4); - } - } else { - for (let i2 = 0; i2 < count2; i2++) { - let c = rgba$3(colors[i2], "uint8"); - colorData.set(c, i2 * 4); - } - colorData.set(rgba$3(colors[0], "uint8"), count2 * 4); - } - state.colorBuffer({ - usage: "dynamic", - type: "uint8", - data: colorData - }); - } - }); - if (options.length < this.passes.length) { - for (let i = options.length; i < this.passes.length; i++) { - let pass = this.passes[i]; - if (!pass) continue; - pass.colorBuffer.destroy(); - pass.positionBuffer.destroy(); - pass.dashTexture.destroy(); - } - this.passes.length = options.length; - } - let passes = []; - for (let i = 0; i < this.passes.length; i++) { - if (this.passes[i] !== null) passes.push(this.passes[i]); - } - this.passes = passes; - return this; -}; -Line2D.prototype.destroy = function() { - this.passes.forEach((pass) => { - pass.colorBuffer.destroy(); - pass.positionBuffer.destroy(); - pass.dashTexture.destroy(); - }); - this.passes.length = 0; - return this; -}; -const getBounds = arrayBounds; -const rgba$2 = colorNormalize; -const updateDiff2 = updateDiff$2; -const pick$3 = pickByAlias; -const extend$2 = index$3.objectAssign; -const flatten$1 = flattenVertexData_1; -const { float32, fract32 } = toFloat32Exports; -var reglError2d = Error2D; -const WEIGHTS = [ - //direction, lineWidth shift, capSize shift - // x-error bar - [1, 0, 0, 1, 0, 0], - [1, 0, 0, -1, 0, 0], - [-1, 0, 0, -1, 0, 0], - [-1, 0, 0, -1, 0, 0], - [-1, 0, 0, 1, 0, 0], - [1, 0, 0, 1, 0, 0], - // x-error right cap - [1, 0, -1, 0, 0, 1], - [1, 0, -1, 0, 0, -1], - [1, 0, 1, 0, 0, -1], - [1, 0, 1, 0, 0, -1], - [1, 0, 1, 0, 0, 1], - [1, 0, -1, 0, 0, 1], - // x-error left cap - [-1, 0, -1, 0, 0, 1], - [-1, 0, -1, 0, 0, -1], - [-1, 0, 1, 0, 0, -1], - [-1, 0, 1, 0, 0, -1], - [-1, 0, 1, 0, 0, 1], - [-1, 0, -1, 0, 0, 1], - // y-error bar - [0, 1, 1, 0, 0, 0], - [0, 1, -1, 0, 0, 0], - [0, -1, -1, 0, 0, 0], - [0, -1, -1, 0, 0, 0], - [0, 1, 1, 0, 0, 0], - [0, -1, 1, 0, 0, 0], - // y-error top cap - [0, 1, 0, -1, 1, 0], - [0, 1, 0, -1, -1, 0], - [0, 1, 0, 1, -1, 0], - [0, 1, 0, 1, 1, 0], - [0, 1, 0, -1, 1, 0], - [0, 1, 0, 1, -1, 0], - // y-error bottom cap - [0, -1, 0, -1, 1, 0], - [0, -1, 0, -1, -1, 0], - [0, -1, 0, 1, -1, 0], - [0, -1, 0, 1, 1, 0], - [0, -1, 0, -1, 1, 0], - [0, -1, 0, 1, -1, 0] -]; -function Error2D(regl, options) { - if (typeof regl === "function") { - if (!options) options = {}; - options.regl = regl; - } else { - options = regl; - } - if (options.length) options.positions = options; - regl = options.regl; - if (!regl.hasExtension("ANGLE_instanced_arrays")) { - throw Error("regl-error2d: `ANGLE_instanced_arrays` extension should be enabled"); - } - let gl = regl._gl, drawErrors, positionBuffer, positionFractBuffer, colorBuffer, errorBuffer, meshBuffer, defaults2 = { - color: "black", - capSize: 5, - lineWidth: 1, - opacity: 1, - viewport: null, - range: null, - offset: 0, - count: 0, - bounds: null, - positions: [], - errors: [] - }, groups = []; - colorBuffer = regl.buffer({ - usage: "dynamic", - type: "uint8", - data: new Uint8Array(0) - }); - positionBuffer = regl.buffer({ - usage: "dynamic", - type: "float", - data: new Uint8Array(0) - }); - positionFractBuffer = regl.buffer({ - usage: "dynamic", - type: "float", - data: new Uint8Array(0) - }); - errorBuffer = regl.buffer({ - usage: "dynamic", - type: "float", - data: new Uint8Array(0) - }); - meshBuffer = regl.buffer({ - usage: "static", - type: "float", - data: WEIGHTS - }); - update2(options); - drawErrors = regl({ - vert: ` - precision highp float; - - attribute vec2 position, positionFract; - attribute vec4 error; - attribute vec4 color; - - attribute vec2 direction, lineOffset, capOffset; - - uniform vec4 viewport; - uniform float lineWidth, capSize; - uniform vec2 scale, scaleFract, translate, translateFract; - - varying vec4 fragColor; - - void main() { - fragColor = color / 255.; - - vec2 pixelOffset = lineWidth * lineOffset + (capSize + lineWidth) * capOffset; - - vec2 dxy = -step(.5, direction.xy) * error.xz + step(direction.xy, vec2(-.5)) * error.yw; - - vec2 position = position + dxy; - - vec2 pos = (position + translate) * scale - + (positionFract + translateFract) * scale - + (position + translate) * scaleFract - + (positionFract + translateFract) * scaleFract; - - pos += pixelOffset / viewport.zw; - - gl_Position = vec4(pos * 2. - 1., 0, 1); - } - `, - frag: ` - precision highp float; - - varying vec4 fragColor; - - uniform float opacity; - - void main() { - gl_FragColor = fragColor; - gl_FragColor.a *= opacity; - } - `, - uniforms: { - range: regl.prop("range"), - lineWidth: regl.prop("lineWidth"), - capSize: regl.prop("capSize"), - opacity: regl.prop("opacity"), - scale: regl.prop("scale"), - translate: regl.prop("translate"), - scaleFract: regl.prop("scaleFract"), - translateFract: regl.prop("translateFract"), - viewport: (ctx2, prop) => [prop.viewport.x, prop.viewport.y, ctx2.viewportWidth, ctx2.viewportHeight] - }, - attributes: { - //dynamic attributes - color: { - buffer: colorBuffer, - offset: (ctx2, prop) => prop.offset * 4, - divisor: 1 - }, - position: { - buffer: positionBuffer, - offset: (ctx2, prop) => prop.offset * 8, - divisor: 1 - }, - positionFract: { - buffer: positionFractBuffer, - offset: (ctx2, prop) => prop.offset * 8, - divisor: 1 - }, - error: { - buffer: errorBuffer, - offset: (ctx2, prop) => prop.offset * 16, - divisor: 1 - }, - //static attributes - direction: { - buffer: meshBuffer, - stride: 24, - offset: 0 - }, - lineOffset: { - buffer: meshBuffer, - stride: 24, - offset: 8 - }, - capOffset: { - buffer: meshBuffer, - stride: 24, - offset: 16 - } - }, - primitive: "triangles", - blend: { - enable: true, - color: [0, 0, 0, 0], - equation: { - rgb: "add", - alpha: "add" - }, - func: { - srcRGB: "src alpha", - dstRGB: "one minus src alpha", - srcAlpha: "one minus dst alpha", - dstAlpha: "one" - } - }, - depth: { - enable: false - }, - scissor: { - enable: true, - box: regl.prop("viewport") - }, - viewport: regl.prop("viewport"), - stencil: false, - instances: regl.prop("count"), - count: WEIGHTS.length - }); - extend$2(error2d, { - update: update2, - draw: draw8, - destroy: destroy2, - regl, - gl, - canvas: gl.canvas, - groups - }); - return error2d; - function error2d(opts) { - if (opts) { - update2(opts); - } else if (opts === null) { - destroy2(); - } - draw8(); - } - function draw8(options2) { - if (typeof options2 === "number") return drawGroup(options2); - if (options2 && !Array.isArray(options2)) options2 = [options2]; - regl._refresh(); - groups.forEach((s, i) => { - if (!s) return; - if (options2) { - if (!options2[i]) s.draw = false; - else s.draw = true; - } - if (!s.draw) { - s.draw = true; - return; - } - drawGroup(i); - }); - } - function drawGroup(s) { - if (typeof s === "number") s = groups[s]; - if (s == null) return; - if (!(s && s.count && s.color && s.opacity && s.positions && s.positions.length > 1)) return; - s.scaleRatio = [ - s.scale[0] * s.viewport.width, - s.scale[1] * s.viewport.height - ]; - drawErrors(s); - if (s.after) s.after(s); - } - function update2(options2) { - if (!options2) return; - if (options2.length != null) { - if (typeof options2[0] === "number") options2 = [{ positions: options2 }]; - } else if (!Array.isArray(options2)) options2 = [options2]; - let pointCount = 0, errorCount = 0; - error2d.groups = groups = options2.map((options3, i) => { - let group = groups[i]; - if (!options3) return group; - else if (typeof options3 === "function") options3 = { after: options3 }; - else if (typeof options3[0] === "number") options3 = { positions: options3 }; - options3 = pick$3(options3, { - color: "color colors fill", - capSize: "capSize cap capsize cap-size", - lineWidth: "lineWidth line-width width line thickness", - opacity: "opacity alpha", - range: "range dataBox", - viewport: "viewport viewBox", - errors: "errors error", - positions: "positions position data points" - }); - if (!group) { - groups[i] = group = { - id: i, - scale: null, - translate: null, - scaleFract: null, - translateFract: null, - draw: true - }; - options3 = extend$2({}, defaults2, options3); - } - updateDiff2(group, options3, [{ - lineWidth: (v) => +v * 0.5, - capSize: (v) => +v * 0.5, - opacity: parseFloat, - errors: (errors) => { - errors = flatten$1(errors); - errorCount += errors.length; - return errors; - }, - positions: (positions, state) => { - positions = flatten$1(positions, "float64"); - state.count = Math.floor(positions.length / 2); - state.bounds = getBounds(positions, 2); - state.offset = pointCount; - pointCount += state.count; - return positions; - } - }, { - color: (colors, state) => { - let count2 = state.count; - if (!colors) colors = "transparent"; - if (!Array.isArray(colors) || typeof colors[0] === "number") { - let color2 = colors; - colors = Array(count2); - for (let i2 = 0; i2 < count2; i2++) { - colors[i2] = color2; - } - } - if (colors.length < count2) throw Error("Not enough colors"); - let colorData = new Uint8Array(count2 * 4); - for (let i2 = 0; i2 < count2; i2++) { - let c = rgba$2(colors[i2], "uint8"); - colorData.set(c, i2 * 4); - } - return colorData; - }, - range: (range, state, options4) => { - let bounds = state.bounds; - if (!range) range = bounds; - state.scale = [1 / (range[2] - range[0]), 1 / (range[3] - range[1])]; - state.translate = [-range[0], -range[1]]; - state.scaleFract = fract32(state.scale); - state.translateFract = fract32(state.translate); - return range; - }, - viewport: (vp) => { - let viewport; - if (Array.isArray(vp)) { - viewport = { - x: vp[0], - y: vp[1], - width: vp[2] - vp[0], - height: vp[3] - vp[1] - }; - } else if (vp) { - viewport = { - x: vp.x || vp.left || 0, - y: vp.y || vp.top || 0 - }; - if (vp.right) viewport.width = vp.right - viewport.x; - else viewport.width = vp.w || vp.width || 0; - if (vp.bottom) viewport.height = vp.bottom - viewport.y; - else viewport.height = vp.h || vp.height || 0; - } else { - viewport = { - x: 0, - y: 0, - width: gl.drawingBufferWidth, - height: gl.drawingBufferHeight - }; - } - return viewport; - } - }]); - return group; - }); - if (pointCount || errorCount) { - let len = groups.reduce((acc, group, i) => { - return acc + (group ? group.count : 0); - }, 0); - let positionData = new Float64Array(len * 2); - let colorData = new Uint8Array(len * 4); - let errorData = new Float32Array(len * 4); - groups.forEach((group, i) => { - if (!group) return; - let { positions, count: count2, offset, color: color2, errors } = group; - if (!count2) return; - colorData.set(color2, offset * 4); - errorData.set(errors, offset * 4); - positionData.set(positions, offset * 2); - }); - var float_data = float32(positionData); - positionBuffer(float_data); - var frac_data = fract32(positionData, float_data); - positionFractBuffer(frac_data); - colorBuffer(colorData); - errorBuffer(errorData); - } - } - function destroy2() { - positionBuffer.destroy(); - positionFractBuffer.destroy(); - colorBuffer.destroy(); - errorBuffer.destroy(); - meshBuffer.destroy(); - } -} -var reg = /[\'\"]/; -var unquote$1 = function unquote(str2) { - if (!str2) { - return ""; - } - if (reg.test(str2.charAt(0))) { - str2 = str2.substr(1); - } - if (reg.test(str2.charAt(str2.length - 1))) { - str2 = str2.substr(0, str2.length - 1); - } - return str2; -}; -const require$$2$1 = [ - "inherit", - "initial", - "unset" -]; -const require$$3 = [ - "caption", - "icon", - "menu", - "message-box", - "small-caption", - "status-bar" -]; -const require$$4 = [ - "normal", - "bold", - "bolder", - "lighter", - "100", - "200", - "300", - "400", - "500", - "600", - "700", - "800", - "900" -]; -const require$$5 = [ - "normal", - "italic", - "oblique" -]; -const require$$6 = [ - "normal", - "condensed", - "semi-condensed", - "extra-condensed", - "ultra-condensed", - "expanded", - "semi-expanded", - "extra-expanded", - "ultra-expanded" -]; -function parse$1(str2, opts) { - if (typeof str2 !== "string") return [str2]; - var res = [str2]; - if (typeof opts === "string" || Array.isArray(opts)) { - opts = { brackets: opts }; - } else if (!opts) opts = {}; - var brackets = opts.brackets ? Array.isArray(opts.brackets) ? opts.brackets : [opts.brackets] : ["{}", "[]", "()"]; - var escape = opts.escape || "___"; - var flat = !!opts.flat; - brackets.forEach(function(bracket) { - var pRE = new RegExp(["\\", bracket[0], "[^\\", bracket[0], "\\", bracket[1], "]*\\", bracket[1]].join("")); - var ids = []; - function replaceToken(token, idx, str3) { - var refId = res.push(token.slice(bracket[0].length, -bracket[1].length)) - 1; - ids.push(refId); - return escape + refId + escape; - } - res.forEach(function(str3, i) { - var prevStr; - var a = 0; - while (str3 != prevStr) { - prevStr = str3; - str3 = str3.replace(pRE, replaceToken); - if (a++ > 1e4) throw Error("References have circular dependency. Please, check them."); - } - res[i] = str3; - }); - ids = ids.reverse(); - res = res.map(function(str3) { - ids.forEach(function(id) { - str3 = str3.replace(new RegExp("(\\" + escape + id + "\\" + escape + ")", "g"), bracket[0] + "$1" + bracket[1]); - }); - return str3; - }); - }); - var re2 = new RegExp("\\" + escape + "([0-9]+)\\" + escape); - function nest(str3, refs, escape2) { - var res2 = [], match; - var a = 0; - while (match = re2.exec(str3)) { - if (a++ > 1e4) throw Error("Circular references in parenthesis"); - res2.push(str3.slice(0, match.index)); - res2.push(nest(refs[match[1]], refs)); - str3 = str3.slice(match.index + match[0].length); - } - res2.push(str3); - return res2; - } - return flat ? res : nest(res[0], res); -} -function stringify$1(arg, opts) { - if (opts && opts.flat) { - var escape = opts && opts.escape || "___"; - var str2 = arg[0], prevStr; - if (!str2) return ""; - var re2 = new RegExp("\\" + escape + "([0-9]+)\\" + escape); - var a = 0; - while (str2 != prevStr) { - if (a++ > 1e4) throw Error("Circular references in " + arg); - prevStr = str2; - str2 = str2.replace(re2, replaceRef); - } - return str2; - } - return arg.reduce(function f(prev, curr) { - if (Array.isArray(curr)) { - curr = curr.reduce(f, ""); - } - return prev + curr; - }, ""); - function replaceRef(match, idx) { - if (arg[idx] == null) throw Error("Reference " + idx + "is undefined"); - return arg[idx]; - } -} -function parenthesis(arg, opts) { - if (Array.isArray(arg)) { - return stringify$1(arg, opts); - } else { - return parse$1(arg, opts); - } -} -parenthesis.parse = parse$1; -parenthesis.stringify = stringify$1; -var parenthesis_1 = parenthesis; -var paren = parenthesis_1; -var stringSplitBy = function splitBy(string2, separator, o) { - if (string2 == null) throw Error("First argument should be a string"); - if (separator == null) throw Error("Separator should be a string or a RegExp"); - if (!o) o = {}; - else if (typeof o === "string" || Array.isArray(o)) { - o = { ignore: o }; - } - if (o.escape == null) o.escape = true; - if (o.ignore == null) o.ignore = ["[]", "()", "{}", "<>", '""', "''", "``", "“”", "«»"]; - else { - if (typeof o.ignore === "string") { - o.ignore = [o.ignore]; - } - o.ignore = o.ignore.map(function(pair) { - if (pair.length === 1) pair = pair + pair; - return pair; - }); - } - var tokens = paren.parse(string2, { flat: true, brackets: o.ignore }); - var str2 = tokens[0]; - var parts = str2.split(separator); - if (o.escape) { - var cleanParts = []; - for (var i = 0; i < parts.length; i++) { - var prev = parts[i]; - var part = parts[i + 1]; - if (prev[prev.length - 1] === "\\" && prev[prev.length - 2] !== "\\") { - cleanParts.push(prev + separator + part); - i++; - } else { - cleanParts.push(prev); - } - } - parts = cleanParts; - } - for (var i = 0; i < parts.length; i++) { - tokens[0] = parts[i]; - parts[i] = paren.stringify(tokens, { flat: true }); - } - return parts; -}; -const require$$0 = [ - "xx-small", - "x-small", - "small", - "medium", - "large", - "x-large", - "xx-large", - "larger", - "smaller" -]; -var sizes = require$$0; -var util = { - isSize: function isSize(value2) { - return /^[\d\.]/.test(value2) || value2.indexOf("/") !== -1 || sizes.indexOf(value2) !== -1; - } -}; -var unquote2 = unquote$1; -var globalKeywords = require$$2$1; -var systemFontKeywords = require$$3; -var fontWeightKeywords = require$$4; -var fontStyleKeywords = require$$5; -var fontStretchKeywords = require$$6; -var splitBy2 = stringSplitBy; -var isSize$1 = util.isSize; -var parse = parseFont; -var cache = parseFont.cache = {}; -function parseFont(value2) { - if (typeof value2 !== "string") throw new Error("Font argument must be a string."); - if (cache[value2]) return cache[value2]; - if (value2 === "") { - throw new Error("Cannot parse an empty string."); - } - if (systemFontKeywords.indexOf(value2) !== -1) { - return cache[value2] = { system: value2 }; - } - var font2 = { - style: "normal", - variant: "normal", - weight: "normal", - stretch: "normal", - lineHeight: "normal", - size: "1rem", - family: ["serif"] - }; - var tokens = splitBy2(value2, /\s+/); - var token; - while (token = tokens.shift()) { - if (globalKeywords.indexOf(token) !== -1) { - ["style", "variant", "weight", "stretch"].forEach(function(prop) { - font2[prop] = token; - }); - return cache[value2] = font2; - } - if (fontStyleKeywords.indexOf(token) !== -1) { - font2.style = token; - continue; - } - if (token === "normal" || token === "small-caps") { - font2.variant = token; - continue; - } - if (fontStretchKeywords.indexOf(token) !== -1) { - font2.stretch = token; - continue; - } - if (fontWeightKeywords.indexOf(token) !== -1) { - font2.weight = token; - continue; - } - if (isSize$1(token)) { - var parts = splitBy2(token, "/"); - font2.size = parts[0]; - if (parts[1] != null) { - font2.lineHeight = parseLineHeight(parts[1]); - } else if (tokens[0] === "/") { - tokens.shift(); - font2.lineHeight = parseLineHeight(tokens.shift()); - } - if (!tokens.length) { - throw new Error("Missing required font-family."); - } - font2.family = splitBy2(tokens.join(" "), /\s*,\s*/).map(unquote2); - return cache[value2] = font2; - } - throw new Error("Unknown or unsupported font token: " + token); - } - throw new Error("Missing required font-size."); -} -function parseLineHeight(value2) { - var parsed = parseFloat(value2); - if (parsed.toString() === value2) { - return parsed; - } - return value2; -} -var pick$2 = pickByAlias; -var isSize2 = util.isSize; -var globals = a2o(require$$2$1); -var systems = a2o(require$$3); -var weights = a2o(require$$4); -var styles = a2o(require$$5); -var stretches = a2o(require$$6); -var variants = { "normal": 1, "small-caps": 1 }; -var fams = { - "serif": 1, - "sans-serif": 1, - "monospace": 1, - "cursive": 1, - "fantasy": 1, - "system-ui": 1 -}; -var defaults$1 = { - size: "1rem", - family: "serif" -}; -var stringify = function stringifyFont(o) { - o = pick$2(o, { - style: "style fontstyle fontStyle font-style slope distinction", - variant: "variant font-variant fontVariant fontvariant var capitalization", - weight: "weight w font-weight fontWeight fontweight", - stretch: "stretch font-stretch fontStretch fontstretch width", - size: "size s font-size fontSize fontsize height em emSize", - lineHeight: "lh line-height lineHeight lineheight leading", - family: "font family fontFamily font-family fontfamily type typeface face", - system: "system reserved default global" - }); - if (o.system) { - if (o.system) verify(o.system, systems); - return o.system; - } - verify(o.style, styles); - verify(o.variant, variants); - verify(o.weight, weights); - verify(o.stretch, stretches); - if (o.size == null) o.size = defaults$1.size; - if (typeof o.size === "number") o.size += "px"; - if (!isSize2) throw Error("Bad size value `" + o.size + "`"); - if (!o.family) o.family = defaults$1.family; - if (Array.isArray(o.family)) { - if (!o.family.length) o.family = [defaults$1.family]; - o.family = o.family.map(function(f) { - return fams[f] ? f : '"' + f + '"'; - }).join(", "); - } - var result = []; - result.push(o.style); - if (o.variant !== o.style) result.push(o.variant); - if (o.weight !== o.variant && o.weight !== o.style) result.push(o.weight); - if (o.stretch !== o.weight && o.stretch !== o.variant && o.stretch !== o.style) result.push(o.stretch); - result.push(o.size + (o.lineHeight == null || o.lineHeight === "normal" || o.lineHeight + "" === "1" ? "" : "/" + o.lineHeight)); - result.push(o.family); - return result.filter(Boolean).join(" "); -}; -function verify(value2, values) { - if (value2 && !values[value2] && !globals[value2]) throw Error("Unknown keyword `" + value2 + "`"); - return value2; -} -function a2o(a) { - var o = {}; - for (var i = 0; i < a.length; i++) { - o[a[i]] = 1; - } - return o; -} -var cssFont = { - parse, - stringify -}; -var regl_unchecked = { exports: {} }; -(function(module2, exports2) { - (function(global, factory2) { - module2.exports = factory2(); - })(index$3.commonjsGlobal, function() { - var extend2 = function(base, opts) { - var keys = Object.keys(opts); - for (var i = 0; i < keys.length; ++i) { - base[keys[i]] = opts[keys[i]]; - } - return base; - }; - var VARIABLE_COUNTER = 0; - var DYN_FUNC = 0; - var DYN_CONSTANT = 5; - var DYN_ARRAY = 6; - function DynamicVariable(type, data) { - this.id = VARIABLE_COUNTER++; - this.type = type; - this.data = data; - } - function escapeStr(str2) { - return str2.replace(/\\/g, "\\\\").replace(/"/g, '\\"'); - } - function splitParts(str2) { - if (str2.length === 0) { - return []; - } - var firstChar = str2.charAt(0); - var lastChar = str2.charAt(str2.length - 1); - if (str2.length > 1 && firstChar === lastChar && (firstChar === '"' || firstChar === "'")) { - return ['"' + escapeStr(str2.substr(1, str2.length - 2)) + '"']; - } - var parts = /\[(false|true|null|\d+|'[^']*'|"[^"]*")\]/.exec(str2); - if (parts) { - return splitParts(str2.substr(0, parts.index)).concat(splitParts(parts[1])).concat(splitParts(str2.substr(parts.index + parts[0].length))); - } - var subparts = str2.split("."); - if (subparts.length === 1) { - return ['"' + escapeStr(str2) + '"']; - } - var result = []; - for (var i = 0; i < subparts.length; ++i) { - result = result.concat(splitParts(subparts[i])); - } - return result; - } - function toAccessorString(str2) { - return "[" + splitParts(str2).join("][") + "]"; - } - function defineDynamic(type, data) { - return new DynamicVariable(type, toAccessorString(data + "")); - } - function isDynamic(x) { - return typeof x === "function" && !x._reglType || x instanceof DynamicVariable; - } - function unbox(x, path) { - if (typeof x === "function") { - return new DynamicVariable(DYN_FUNC, x); - } else if (typeof x === "number" || typeof x === "boolean") { - return new DynamicVariable(DYN_CONSTANT, x); - } else if (Array.isArray(x)) { - return new DynamicVariable(DYN_ARRAY, x.map(function(y, i) { - return unbox(y); - })); - } else if (x instanceof DynamicVariable) { - return x; - } - } - var dynamic = { - DynamicVariable, - define: defineDynamic, - isDynamic, - unbox, - accessor: toAccessorString - }; - var raf = { - next: typeof requestAnimationFrame === "function" ? function(cb) { - return requestAnimationFrame(cb); - } : function(cb) { - return setTimeout(cb, 16); - }, - cancel: typeof cancelAnimationFrame === "function" ? function(raf2) { - return cancelAnimationFrame(raf2); - } : clearTimeout - }; - var clock = typeof performance !== "undefined" && performance.now ? function() { - return performance.now(); - } : function() { - return +/* @__PURE__ */ new Date(); - }; - function createStringStore() { - var stringIds = { "": 0 }; - var stringValues = [""]; - return { - id: function(str2) { - var result = stringIds[str2]; - if (result) { - return result; - } - result = stringIds[str2] = stringValues.length; - stringValues.push(str2); - return result; - }, - str: function(id) { - return stringValues[id]; - } - }; - } - function createCanvas2(element, onDone, pixelRatio) { - var canvas2 = document.createElement("canvas"); - extend2(canvas2.style, { - border: 0, - margin: 0, - padding: 0, - top: 0, - left: 0, - width: "100%", - height: "100%" - }); - element.appendChild(canvas2); - if (element === document.body) { - canvas2.style.position = "absolute"; - extend2(element.style, { - margin: 0, - padding: 0 - }); - } - function resize2() { - var w = window.innerWidth; - var h = window.innerHeight; - if (element !== document.body) { - var bounds = canvas2.getBoundingClientRect(); - w = bounds.right - bounds.left; - h = bounds.bottom - bounds.top; - } - canvas2.width = pixelRatio * w; - canvas2.height = pixelRatio * h; - } - var resizeObserver; - if (element !== document.body && typeof ResizeObserver === "function") { - resizeObserver = new ResizeObserver(function() { - setTimeout(resize2); - }); - resizeObserver.observe(element); - } else { - window.addEventListener("resize", resize2, false); - } - function onDestroy() { - if (resizeObserver) { - resizeObserver.disconnect(); - } else { - window.removeEventListener("resize", resize2); - } - element.removeChild(canvas2); - } - resize2(); - return { - canvas: canvas2, - onDestroy - }; - } - function createContext(canvas2, contextAttributes) { - function get3(name2) { - try { - return canvas2.getContext(name2, contextAttributes); - } catch (e) { - return null; - } - } - return get3("webgl") || get3("experimental-webgl") || get3("webgl-experimental"); - } - function isHTMLElement(obj) { - return typeof obj.nodeName === "string" && typeof obj.appendChild === "function" && typeof obj.getBoundingClientRect === "function"; - } - function isWebGLContext(obj) { - return typeof obj.drawArrays === "function" || typeof obj.drawElements === "function"; - } - function parseExtensions(input) { - if (typeof input === "string") { - return input.split(); - } - return input; - } - function getElement(desc) { - if (typeof desc === "string") { - return document.querySelector(desc); - } - return desc; - } - function parseArgs(args_) { - var args = args_ || {}; - var element, container, canvas2, gl; - var contextAttributes = {}; - var extensions = []; - var optionalExtensions = []; - var pixelRatio = typeof window === "undefined" ? 1 : window.devicePixelRatio; - var profile = false; - var cachedCode = {}; - var onDone = function(err) { - }; - var onDestroy = function() { - }; - if (typeof args === "string") { - element = document.querySelector(args); - } else if (typeof args === "object") { - if (isHTMLElement(args)) { - element = args; - } else if (isWebGLContext(args)) { - gl = args; - canvas2 = gl.canvas; - } else { - if ("gl" in args) { - gl = args.gl; - } else if ("canvas" in args) { - canvas2 = getElement(args.canvas); - } else if ("container" in args) { - container = getElement(args.container); - } - if ("attributes" in args) { - contextAttributes = args.attributes; - } - if ("extensions" in args) { - extensions = parseExtensions(args.extensions); - } - if ("optionalExtensions" in args) { - optionalExtensions = parseExtensions(args.optionalExtensions); - } - if ("onDone" in args) { - onDone = args.onDone; - } - if ("profile" in args) { - profile = !!args.profile; - } - if ("pixelRatio" in args) { - pixelRatio = +args.pixelRatio; - } - if ("cachedCode" in args) { - cachedCode = args.cachedCode; - } - } - } else ; - if (element) { - if (element.nodeName.toLowerCase() === "canvas") { - canvas2 = element; - } else { - container = element; - } - } - if (!gl) { - if (!canvas2) { - var result = createCanvas2(container || document.body, onDone, pixelRatio); - if (!result) { - return null; - } - canvas2 = result.canvas; - onDestroy = result.onDestroy; - } - if (contextAttributes.premultipliedAlpha === void 0) contextAttributes.premultipliedAlpha = true; - gl = createContext(canvas2, contextAttributes); - } - if (!gl) { - onDestroy(); - onDone("webgl not supported, try upgrading your browser or graphics drivers http://get.webgl.org"); - return null; - } - return { - gl, - canvas: canvas2, - container, - extensions, - optionalExtensions, - pixelRatio, - profile, - cachedCode, - onDone, - onDestroy - }; - } - function createExtensionCache(gl, config) { - var extensions = {}; - function tryLoadExtension(name_) { - var name3 = name_.toLowerCase(); - var ext; - try { - ext = extensions[name3] = gl.getExtension(name3); - } catch (e) { - } - return !!ext; - } - for (var i = 0; i < config.extensions.length; ++i) { - var name2 = config.extensions[i]; - if (!tryLoadExtension(name2)) { - config.onDestroy(); - config.onDone('"' + name2 + '" extension is not supported by the current WebGL context, try upgrading your system or a different browser'); - return null; - } - } - config.optionalExtensions.forEach(tryLoadExtension); - return { - extensions, - restore: function() { - Object.keys(extensions).forEach(function(name3) { - if (extensions[name3] && !tryLoadExtension(name3)) { - throw new Error("(regl): error restoring extension " + name3); - } - }); - } - }; - } - function loop(n, f) { - var result = Array(n); - for (var i = 0; i < n; ++i) { - result[i] = f(i); - } - return result; - } - var GL_BYTE = 5120; - var GL_UNSIGNED_BYTE$1 = 5121; - var GL_SHORT = 5122; - var GL_UNSIGNED_SHORT = 5123; - var GL_INT = 5124; - var GL_UNSIGNED_INT = 5125; - var GL_FLOAT$1 = 5126; - function nextPow16(v) { - for (var i = 16; i <= 1 << 28; i *= 16) { - if (v <= i) { - return i; - } - } - return 0; - } - function log22(v) { - var r, shift; - r = (v > 65535) << 4; - v >>>= r; - shift = (v > 255) << 3; - v >>>= shift; - r |= shift; - shift = (v > 15) << 2; - v >>>= shift; - r |= shift; - shift = (v > 3) << 1; - v >>>= shift; - r |= shift; - return r | v >> 1; - } - function createPool() { - var bufferPool = loop(8, function() { - return []; - }); - function alloc(n) { - var sz = nextPow16(n); - var bin = bufferPool[log22(sz) >> 2]; - if (bin.length > 0) { - return bin.pop(); - } - return new ArrayBuffer(sz); - } - function free2(buf) { - bufferPool[log22(buf.byteLength) >> 2].push(buf); - } - function allocType(type, n) { - var result = null; - switch (type) { - case GL_BYTE: - result = new Int8Array(alloc(n), 0, n); - break; - case GL_UNSIGNED_BYTE$1: - result = new Uint8Array(alloc(n), 0, n); - break; - case GL_SHORT: - result = new Int16Array(alloc(2 * n), 0, n); - break; - case GL_UNSIGNED_SHORT: - result = new Uint16Array(alloc(2 * n), 0, n); - break; - case GL_INT: - result = new Int32Array(alloc(4 * n), 0, n); - break; - case GL_UNSIGNED_INT: - result = new Uint32Array(alloc(4 * n), 0, n); - break; - case GL_FLOAT$1: - result = new Float32Array(alloc(4 * n), 0, n); - break; - default: - return null; - } - if (result.length !== n) { - return result.subarray(0, n); - } - return result; - } - function freeType(array2) { - free2(array2.buffer); - } - return { - alloc, - free: free2, - allocType, - freeType - }; - } - var pool2 = createPool(); - pool2.zero = createPool(); - var GL_SUBPIXEL_BITS = 3408; - var GL_RED_BITS = 3410; - var GL_GREEN_BITS = 3411; - var GL_BLUE_BITS = 3412; - var GL_ALPHA_BITS = 3413; - var GL_DEPTH_BITS = 3414; - var GL_STENCIL_BITS = 3415; - var GL_ALIASED_POINT_SIZE_RANGE = 33901; - var GL_ALIASED_LINE_WIDTH_RANGE = 33902; - var GL_MAX_TEXTURE_SIZE = 3379; - var GL_MAX_VIEWPORT_DIMS = 3386; - var GL_MAX_VERTEX_ATTRIBS = 34921; - var GL_MAX_VERTEX_UNIFORM_VECTORS = 36347; - var GL_MAX_VARYING_VECTORS = 36348; - var GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS = 35661; - var GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS = 35660; - var GL_MAX_TEXTURE_IMAGE_UNITS = 34930; - var GL_MAX_FRAGMENT_UNIFORM_VECTORS = 36349; - var GL_MAX_CUBE_MAP_TEXTURE_SIZE = 34076; - var GL_MAX_RENDERBUFFER_SIZE = 34024; - var GL_VENDOR = 7936; - var GL_RENDERER = 7937; - var GL_VERSION = 7938; - var GL_SHADING_LANGUAGE_VERSION = 35724; - var GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT = 34047; - var GL_MAX_COLOR_ATTACHMENTS_WEBGL = 36063; - var GL_MAX_DRAW_BUFFERS_WEBGL = 34852; - var GL_TEXTURE_2D = 3553; - var GL_TEXTURE_CUBE_MAP = 34067; - var GL_TEXTURE_CUBE_MAP_POSITIVE_X = 34069; - var GL_TEXTURE0 = 33984; - var GL_RGBA = 6408; - var GL_FLOAT = 5126; - var GL_UNSIGNED_BYTE = 5121; - var GL_FRAMEBUFFER = 36160; - var GL_FRAMEBUFFER_COMPLETE = 36053; - var GL_COLOR_ATTACHMENT0 = 36064; - var GL_COLOR_BUFFER_BIT$1 = 16384; - var wrapLimits = function(gl, extensions) { - var maxAnisotropic = 1; - if (extensions.ext_texture_filter_anisotropic) { - maxAnisotropic = gl.getParameter(GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT); - } - var maxDrawbuffers = 1; - var maxColorAttachments = 1; - if (extensions.webgl_draw_buffers) { - maxDrawbuffers = gl.getParameter(GL_MAX_DRAW_BUFFERS_WEBGL); - maxColorAttachments = gl.getParameter(GL_MAX_COLOR_ATTACHMENTS_WEBGL); - } - var readFloat = !!extensions.oes_texture_float; - if (readFloat) { - var readFloatTexture = gl.createTexture(); - gl.bindTexture(GL_TEXTURE_2D, readFloatTexture); - gl.texImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 1, 1, 0, GL_RGBA, GL_FLOAT, null); - var fbo = gl.createFramebuffer(); - gl.bindFramebuffer(GL_FRAMEBUFFER, fbo); - gl.framebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, readFloatTexture, 0); - gl.bindTexture(GL_TEXTURE_2D, null); - if (gl.checkFramebufferStatus(GL_FRAMEBUFFER) !== GL_FRAMEBUFFER_COMPLETE) readFloat = false; - else { - gl.viewport(0, 0, 1, 1); - gl.clearColor(1, 0, 0, 1); - gl.clear(GL_COLOR_BUFFER_BIT$1); - var pixels = pool2.allocType(GL_FLOAT, 4); - gl.readPixels(0, 0, 1, 1, GL_RGBA, GL_FLOAT, pixels); - if (gl.getError()) readFloat = false; - else { - gl.deleteFramebuffer(fbo); - gl.deleteTexture(readFloatTexture); - readFloat = pixels[0] === 1; - } - pool2.freeType(pixels); - } - } - var isIE = typeof navigator !== "undefined" && (/MSIE/.test(navigator.userAgent) || /Trident\//.test(navigator.appVersion) || /Edge/.test(navigator.userAgent)); - var npotTextureCube = true; - if (!isIE) { - var cubeTexture = gl.createTexture(); - var data = pool2.allocType(GL_UNSIGNED_BYTE, 36); - gl.activeTexture(GL_TEXTURE0); - gl.bindTexture(GL_TEXTURE_CUBE_MAP, cubeTexture); - gl.texImage2D(GL_TEXTURE_CUBE_MAP_POSITIVE_X, 0, GL_RGBA, 3, 3, 0, GL_RGBA, GL_UNSIGNED_BYTE, data); - pool2.freeType(data); - gl.bindTexture(GL_TEXTURE_CUBE_MAP, null); - gl.deleteTexture(cubeTexture); - npotTextureCube = !gl.getError(); - } - return { - // drawing buffer bit depth - colorBits: [ - gl.getParameter(GL_RED_BITS), - gl.getParameter(GL_GREEN_BITS), - gl.getParameter(GL_BLUE_BITS), - gl.getParameter(GL_ALPHA_BITS) - ], - depthBits: gl.getParameter(GL_DEPTH_BITS), - stencilBits: gl.getParameter(GL_STENCIL_BITS), - subpixelBits: gl.getParameter(GL_SUBPIXEL_BITS), - // supported extensions - extensions: Object.keys(extensions).filter(function(ext) { - return !!extensions[ext]; - }), - // max aniso samples - maxAnisotropic, - // max draw buffers - maxDrawbuffers, - maxColorAttachments, - // point and line size ranges - pointSizeDims: gl.getParameter(GL_ALIASED_POINT_SIZE_RANGE), - lineWidthDims: gl.getParameter(GL_ALIASED_LINE_WIDTH_RANGE), - maxViewportDims: gl.getParameter(GL_MAX_VIEWPORT_DIMS), - maxCombinedTextureUnits: gl.getParameter(GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS), - maxCubeMapSize: gl.getParameter(GL_MAX_CUBE_MAP_TEXTURE_SIZE), - maxRenderbufferSize: gl.getParameter(GL_MAX_RENDERBUFFER_SIZE), - maxTextureUnits: gl.getParameter(GL_MAX_TEXTURE_IMAGE_UNITS), - maxTextureSize: gl.getParameter(GL_MAX_TEXTURE_SIZE), - maxAttributes: gl.getParameter(GL_MAX_VERTEX_ATTRIBS), - maxVertexUniforms: gl.getParameter(GL_MAX_VERTEX_UNIFORM_VECTORS), - maxVertexTextureUnits: gl.getParameter(GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS), - maxVaryingVectors: gl.getParameter(GL_MAX_VARYING_VECTORS), - maxFragmentUniforms: gl.getParameter(GL_MAX_FRAGMENT_UNIFORM_VECTORS), - // vendor info - glsl: gl.getParameter(GL_SHADING_LANGUAGE_VERSION), - renderer: gl.getParameter(GL_RENDERER), - vendor: gl.getParameter(GL_VENDOR), - version: gl.getParameter(GL_VERSION), - // quirks - readFloat, - npotTextureCube - }; - }; - var isTypedArray2 = function(x) { - return x instanceof Uint8Array || x instanceof Uint16Array || x instanceof Uint32Array || x instanceof Int8Array || x instanceof Int16Array || x instanceof Int32Array || x instanceof Float32Array || x instanceof Float64Array || x instanceof Uint8ClampedArray; - }; - function isNDArrayLike(obj) { - return !!obj && typeof obj === "object" && Array.isArray(obj.shape) && Array.isArray(obj.stride) && typeof obj.offset === "number" && obj.shape.length === obj.stride.length && (Array.isArray(obj.data) || isTypedArray2(obj.data)); - } - var values = function(obj) { - return Object.keys(obj).map(function(key) { - return obj[key]; - }); - }; - var flattenUtils = { - shape: arrayShape$1, - flatten: flattenArray - }; - function flatten1D(array2, nx, out) { - for (var i = 0; i < nx; ++i) { - out[i] = array2[i]; - } - } - function flatten2D(array2, nx, ny, out) { - var ptr = 0; - for (var i = 0; i < nx; ++i) { - var row = array2[i]; - for (var j = 0; j < ny; ++j) { - out[ptr++] = row[j]; - } - } - } - function flatten3D(array2, nx, ny, nz, out, ptr_) { - var ptr = ptr_; - for (var i = 0; i < nx; ++i) { - var row = array2[i]; - for (var j = 0; j < ny; ++j) { - var col = row[j]; - for (var k = 0; k < nz; ++k) { - out[ptr++] = col[k]; - } - } - } - } - function flattenRec(array2, shape, level, out, ptr) { - var stride = 1; - for (var i = level + 1; i < shape.length; ++i) { - stride *= shape[i]; - } - var n = shape[level]; - if (shape.length - level === 4) { - var nx = shape[level + 1]; - var ny = shape[level + 2]; - var nz = shape[level + 3]; - for (i = 0; i < n; ++i) { - flatten3D(array2[i], nx, ny, nz, out, ptr); - ptr += stride; - } - } else { - for (i = 0; i < n; ++i) { - flattenRec(array2[i], shape, level + 1, out, ptr); - ptr += stride; - } - } - } - function flattenArray(array2, shape, type, out_) { - var sz = 1; - if (shape.length) { - for (var i = 0; i < shape.length; ++i) { - sz *= shape[i]; - } - } else { - sz = 0; - } - var out = out_ || pool2.allocType(type, sz); - switch (shape.length) { - case 0: - break; - case 1: - flatten1D(array2, shape[0], out); - break; - case 2: - flatten2D(array2, shape[0], shape[1], out); - break; - case 3: - flatten3D(array2, shape[0], shape[1], shape[2], out, 0); - break; - default: - flattenRec(array2, shape, 0, out, 0); - } - return out; - } - function arrayShape$1(array_) { - var shape = []; - for (var array2 = array_; array2.length; array2 = array2[0]) { - shape.push(array2.length); - } - return shape; - } - var arrayTypes = { - "[object Int8Array]": 5120, - "[object Int16Array]": 5122, - "[object Int32Array]": 5124, - "[object Uint8Array]": 5121, - "[object Uint8ClampedArray]": 5121, - "[object Uint16Array]": 5123, - "[object Uint32Array]": 5125, - "[object Float32Array]": 5126, - "[object Float64Array]": 5121, - "[object ArrayBuffer]": 5121 - }; - var int8 = 5120; - var int16 = 5122; - var int32 = 5124; - var uint8 = 5121; - var uint16 = 5123; - var uint32 = 5125; - var float = 5126; - var float322 = 5126; - var glTypes = { - int8, - int16, - int32, - uint8, - uint16, - uint32, - float, - float32: float322 - }; - var dynamic$1 = 35048; - var stream = 35040; - var usageTypes = { - dynamic: dynamic$1, - stream, - "static": 35044 - }; - var arrayFlatten = flattenUtils.flatten; - var arrayShape = flattenUtils.shape; - var GL_STATIC_DRAW = 35044; - var GL_STREAM_DRAW = 35040; - var GL_UNSIGNED_BYTE$2 = 5121; - var GL_FLOAT$2 = 5126; - var DTYPES_SIZES = []; - DTYPES_SIZES[5120] = 1; - DTYPES_SIZES[5122] = 2; - DTYPES_SIZES[5124] = 4; - DTYPES_SIZES[5121] = 1; - DTYPES_SIZES[5123] = 2; - DTYPES_SIZES[5125] = 4; - DTYPES_SIZES[5126] = 4; - function typedArrayCode(data) { - return arrayTypes[Object.prototype.toString.call(data)] | 0; - } - function copyArray(out, inp) { - for (var i = 0; i < inp.length; ++i) { - out[i] = inp[i]; - } - } - function transpose2(result, data, shapeX, shapeY, strideX, strideY, offset) { - var ptr = 0; - for (var i = 0; i < shapeX; ++i) { - for (var j = 0; j < shapeY; ++j) { - result[ptr++] = data[strideX * i + strideY * j + offset]; - } - } - } - function wrapBufferState(gl, stats3, config, destroyBuffer) { - var bufferCount = 0; - var bufferSet = {}; - function REGLBuffer(type) { - this.id = bufferCount++; - this.buffer = gl.createBuffer(); - this.type = type; - this.usage = GL_STATIC_DRAW; - this.byteLength = 0; - this.dimension = 1; - this.dtype = GL_UNSIGNED_BYTE$2; - this.persistentData = null; - if (config.profile) { - this.stats = { size: 0 }; - } - } - REGLBuffer.prototype.bind = function() { - gl.bindBuffer(this.type, this.buffer); - }; - REGLBuffer.prototype.destroy = function() { - destroy2(this); - }; - var streamPool = []; - function createStream(type, data) { - var buffer2 = streamPool.pop(); - if (!buffer2) { - buffer2 = new REGLBuffer(type); - } - buffer2.bind(); - initBufferFromData(buffer2, data, GL_STREAM_DRAW, 0, 1, false); - return buffer2; - } - function destroyStream(stream$$1) { - streamPool.push(stream$$1); - } - function initBufferFromTypedArray(buffer2, data, usage) { - buffer2.byteLength = data.byteLength; - gl.bufferData(buffer2.type, data, usage); - } - function initBufferFromData(buffer2, data, usage, dtype2, dimension, persist) { - var shape; - buffer2.usage = usage; - if (Array.isArray(data)) { - buffer2.dtype = dtype2 || GL_FLOAT$2; - if (data.length > 0) { - var flatData; - if (Array.isArray(data[0])) { - shape = arrayShape(data); - var dim = 1; - for (var i = 1; i < shape.length; ++i) { - dim *= shape[i]; - } - buffer2.dimension = dim; - flatData = arrayFlatten(data, shape, buffer2.dtype); - initBufferFromTypedArray(buffer2, flatData, usage); - if (persist) { - buffer2.persistentData = flatData; - } else { - pool2.freeType(flatData); - } - } else if (typeof data[0] === "number") { - buffer2.dimension = dimension; - var typedData = pool2.allocType(buffer2.dtype, data.length); - copyArray(typedData, data); - initBufferFromTypedArray(buffer2, typedData, usage); - if (persist) { - buffer2.persistentData = typedData; - } else { - pool2.freeType(typedData); - } - } else if (isTypedArray2(data[0])) { - buffer2.dimension = data[0].length; - buffer2.dtype = dtype2 || typedArrayCode(data[0]) || GL_FLOAT$2; - flatData = arrayFlatten( - data, - [data.length, data[0].length], - buffer2.dtype - ); - initBufferFromTypedArray(buffer2, flatData, usage); - if (persist) { - buffer2.persistentData = flatData; - } else { - pool2.freeType(flatData); - } - } else ; - } - } else if (isTypedArray2(data)) { - buffer2.dtype = dtype2 || typedArrayCode(data); - buffer2.dimension = dimension; - initBufferFromTypedArray(buffer2, data, usage); - if (persist) { - buffer2.persistentData = new Uint8Array(new Uint8Array(data.buffer)); - } - } else if (isNDArrayLike(data)) { - shape = data.shape; - var stride = data.stride; - var offset = data.offset; - var shapeX = 0; - var shapeY = 0; - var strideX = 0; - var strideY = 0; - if (shape.length === 1) { - shapeX = shape[0]; - shapeY = 1; - strideX = stride[0]; - strideY = 0; - } else if (shape.length === 2) { - shapeX = shape[0]; - shapeY = shape[1]; - strideX = stride[0]; - strideY = stride[1]; - } else ; - buffer2.dtype = dtype2 || typedArrayCode(data.data) || GL_FLOAT$2; - buffer2.dimension = shapeY; - var transposeData2 = pool2.allocType(buffer2.dtype, shapeX * shapeY); - transpose2( - transposeData2, - data.data, - shapeX, - shapeY, - strideX, - strideY, - offset - ); - initBufferFromTypedArray(buffer2, transposeData2, usage); - if (persist) { - buffer2.persistentData = transposeData2; - } else { - pool2.freeType(transposeData2); - } - } else if (data instanceof ArrayBuffer) { - buffer2.dtype = GL_UNSIGNED_BYTE$2; - buffer2.dimension = dimension; - initBufferFromTypedArray(buffer2, data, usage); - if (persist) { - buffer2.persistentData = new Uint8Array(new Uint8Array(data)); - } - } else ; - } - function destroy2(buffer2) { - stats3.bufferCount--; - destroyBuffer(buffer2); - var handle = buffer2.buffer; - gl.deleteBuffer(handle); - buffer2.buffer = null; - delete bufferSet[buffer2.id]; - } - function createBuffer(options, type, deferInit, persistent) { - stats3.bufferCount++; - var buffer2 = new REGLBuffer(type); - bufferSet[buffer2.id] = buffer2; - function reglBuffer(options2) { - var usage = GL_STATIC_DRAW; - var data = null; - var byteLength2 = 0; - var dtype2 = 0; - var dimension = 1; - if (Array.isArray(options2) || isTypedArray2(options2) || isNDArrayLike(options2) || options2 instanceof ArrayBuffer) { - data = options2; - } else if (typeof options2 === "number") { - byteLength2 = options2 | 0; - } else if (options2) { - if ("data" in options2) { - data = options2.data; - } - if ("usage" in options2) { - usage = usageTypes[options2.usage]; - } - if ("type" in options2) { - dtype2 = glTypes[options2.type]; - } - if ("dimension" in options2) { - dimension = options2.dimension | 0; - } - if ("length" in options2) { - byteLength2 = options2.length | 0; - } - } - buffer2.bind(); - if (!data) { - if (byteLength2) gl.bufferData(buffer2.type, byteLength2, usage); - buffer2.dtype = dtype2 || GL_UNSIGNED_BYTE$2; - buffer2.usage = usage; - buffer2.dimension = dimension; - buffer2.byteLength = byteLength2; - } else { - initBufferFromData(buffer2, data, usage, dtype2, dimension, persistent); - } - if (config.profile) { - buffer2.stats.size = buffer2.byteLength * DTYPES_SIZES[buffer2.dtype]; - } - return reglBuffer; - } - function setSubData(data, offset) { - gl.bufferSubData(buffer2.type, offset, data); - } - function subdata(data, offset_) { - var offset = (offset_ || 0) | 0; - var shape; - buffer2.bind(); - if (isTypedArray2(data) || data instanceof ArrayBuffer) { - setSubData(data, offset); - } else if (Array.isArray(data)) { - if (data.length > 0) { - if (typeof data[0] === "number") { - var converted = pool2.allocType(buffer2.dtype, data.length); - copyArray(converted, data); - setSubData(converted, offset); - pool2.freeType(converted); - } else if (Array.isArray(data[0]) || isTypedArray2(data[0])) { - shape = arrayShape(data); - var flatData = arrayFlatten(data, shape, buffer2.dtype); - setSubData(flatData, offset); - pool2.freeType(flatData); - } else ; - } - } else if (isNDArrayLike(data)) { - shape = data.shape; - var stride = data.stride; - var shapeX = 0; - var shapeY = 0; - var strideX = 0; - var strideY = 0; - if (shape.length === 1) { - shapeX = shape[0]; - shapeY = 1; - strideX = stride[0]; - strideY = 0; - } else if (shape.length === 2) { - shapeX = shape[0]; - shapeY = shape[1]; - strideX = stride[0]; - strideY = stride[1]; - } else ; - var dtype2 = Array.isArray(data.data) ? buffer2.dtype : typedArrayCode(data.data); - var transposeData2 = pool2.allocType(dtype2, shapeX * shapeY); - transpose2( - transposeData2, - data.data, - shapeX, - shapeY, - strideX, - strideY, - data.offset - ); - setSubData(transposeData2, offset); - pool2.freeType(transposeData2); - } else ; - return reglBuffer; - } - if (!deferInit) { - reglBuffer(options); - } - reglBuffer._reglType = "buffer"; - reglBuffer._buffer = buffer2; - reglBuffer.subdata = subdata; - if (config.profile) { - reglBuffer.stats = buffer2.stats; - } - reglBuffer.destroy = function() { - destroy2(buffer2); - }; - return reglBuffer; - } - function restoreBuffers() { - values(bufferSet).forEach(function(buffer2) { - buffer2.buffer = gl.createBuffer(); - gl.bindBuffer(buffer2.type, buffer2.buffer); - gl.bufferData( - buffer2.type, - buffer2.persistentData || buffer2.byteLength, - buffer2.usage - ); - }); - } - if (config.profile) { - stats3.getTotalBufferSize = function() { - var total = 0; - Object.keys(bufferSet).forEach(function(key) { - total += bufferSet[key].stats.size; - }); - return total; - }; - } - return { - create: createBuffer, - createStream, - destroyStream, - clear: function() { - values(bufferSet).forEach(destroy2); - streamPool.forEach(destroy2); - }, - getBuffer: function(wrapper) { - if (wrapper && wrapper._buffer instanceof REGLBuffer) { - return wrapper._buffer; - } - return null; - }, - restore: restoreBuffers, - _initBuffer: initBufferFromData - }; - } - var points = 0; - var point = 0; - var lines = 1; - var line2 = 1; - var triangles = 4; - var triangle = 4; - var primTypes = { - points, - point, - lines, - line: line2, - triangles, - triangle, - "line loop": 2, - "line strip": 3, - "triangle strip": 5, - "triangle fan": 6 - }; - var GL_POINTS = 0; - var GL_LINES = 1; - var GL_TRIANGLES = 4; - var GL_BYTE$1 = 5120; - var GL_UNSIGNED_BYTE$3 = 5121; - var GL_SHORT$1 = 5122; - var GL_UNSIGNED_SHORT$1 = 5123; - var GL_INT$1 = 5124; - var GL_UNSIGNED_INT$1 = 5125; - var GL_ELEMENT_ARRAY_BUFFER = 34963; - var GL_STREAM_DRAW$1 = 35040; - var GL_STATIC_DRAW$1 = 35044; - function wrapElementsState(gl, extensions, bufferState, stats3) { - var elementSet = {}; - var elementCount = 0; - var elementTypes = { - "uint8": GL_UNSIGNED_BYTE$3, - "uint16": GL_UNSIGNED_SHORT$1 - }; - if (extensions.oes_element_index_uint) { - elementTypes.uint32 = GL_UNSIGNED_INT$1; - } - function REGLElementBuffer(buffer2) { - this.id = elementCount++; - elementSet[this.id] = this; - this.buffer = buffer2; - this.primType = GL_TRIANGLES; - this.vertCount = 0; - this.type = 0; - } - REGLElementBuffer.prototype.bind = function() { - this.buffer.bind(); - }; - var bufferPool = []; - function createElementStream(data) { - var result = bufferPool.pop(); - if (!result) { - result = new REGLElementBuffer(bufferState.create( - null, - GL_ELEMENT_ARRAY_BUFFER, - true, - false - )._buffer); - } - initElements(result, data, GL_STREAM_DRAW$1, -1, -1, 0, 0); - return result; - } - function destroyElementStream(elements) { - bufferPool.push(elements); - } - function initElements(elements, data, usage, prim, count2, byteLength2, type) { - elements.buffer.bind(); - var dtype2; - if (data) { - var predictedType = type; - if (!type && (!isTypedArray2(data) || isNDArrayLike(data) && !isTypedArray2(data.data))) { - predictedType = extensions.oes_element_index_uint ? GL_UNSIGNED_INT$1 : GL_UNSIGNED_SHORT$1; - } - bufferState._initBuffer( - elements.buffer, - data, - usage, - predictedType, - 3 - ); - } else { - gl.bufferData(GL_ELEMENT_ARRAY_BUFFER, byteLength2, usage); - elements.buffer.dtype = dtype2 || GL_UNSIGNED_BYTE$3; - elements.buffer.usage = usage; - elements.buffer.dimension = 3; - elements.buffer.byteLength = byteLength2; - } - dtype2 = type; - if (!type) { - switch (elements.buffer.dtype) { - case GL_UNSIGNED_BYTE$3: - case GL_BYTE$1: - dtype2 = GL_UNSIGNED_BYTE$3; - break; - case GL_UNSIGNED_SHORT$1: - case GL_SHORT$1: - dtype2 = GL_UNSIGNED_SHORT$1; - break; - case GL_UNSIGNED_INT$1: - case GL_INT$1: - dtype2 = GL_UNSIGNED_INT$1; - break; - } - elements.buffer.dtype = dtype2; - } - elements.type = dtype2; - var vertCount = count2; - if (vertCount < 0) { - vertCount = elements.buffer.byteLength; - if (dtype2 === GL_UNSIGNED_SHORT$1) { - vertCount >>= 1; - } else if (dtype2 === GL_UNSIGNED_INT$1) { - vertCount >>= 2; - } - } - elements.vertCount = vertCount; - var primType = prim; - if (prim < 0) { - primType = GL_TRIANGLES; - var dimension = elements.buffer.dimension; - if (dimension === 1) primType = GL_POINTS; - if (dimension === 2) primType = GL_LINES; - if (dimension === 3) primType = GL_TRIANGLES; - } - elements.primType = primType; - } - function destroyElements(elements) { - stats3.elementsCount--; - delete elementSet[elements.id]; - elements.buffer.destroy(); - elements.buffer = null; - } - function createElements(options, persistent) { - var buffer2 = bufferState.create(null, GL_ELEMENT_ARRAY_BUFFER, true); - var elements = new REGLElementBuffer(buffer2._buffer); - stats3.elementsCount++; - function reglElements(options2) { - if (!options2) { - buffer2(); - elements.primType = GL_TRIANGLES; - elements.vertCount = 0; - elements.type = GL_UNSIGNED_BYTE$3; - } else if (typeof options2 === "number") { - buffer2(options2); - elements.primType = GL_TRIANGLES; - elements.vertCount = options2 | 0; - elements.type = GL_UNSIGNED_BYTE$3; - } else { - var data = null; - var usage = GL_STATIC_DRAW$1; - var primType = -1; - var vertCount = -1; - var byteLength2 = 0; - var dtype2 = 0; - if (Array.isArray(options2) || isTypedArray2(options2) || isNDArrayLike(options2)) { - data = options2; - } else { - if ("data" in options2) { - data = options2.data; - } - if ("usage" in options2) { - usage = usageTypes[options2.usage]; - } - if ("primitive" in options2) { - primType = primTypes[options2.primitive]; - } - if ("count" in options2) { - vertCount = options2.count | 0; - } - if ("type" in options2) { - dtype2 = elementTypes[options2.type]; - } - if ("length" in options2) { - byteLength2 = options2.length | 0; - } else { - byteLength2 = vertCount; - if (dtype2 === GL_UNSIGNED_SHORT$1 || dtype2 === GL_SHORT$1) { - byteLength2 *= 2; - } else if (dtype2 === GL_UNSIGNED_INT$1 || dtype2 === GL_INT$1) { - byteLength2 *= 4; - } - } - } - initElements( - elements, - data, - usage, - primType, - vertCount, - byteLength2, - dtype2 - ); - } - return reglElements; - } - reglElements(options); - reglElements._reglType = "elements"; - reglElements._elements = elements; - reglElements.subdata = function(data, offset) { - buffer2.subdata(data, offset); - return reglElements; - }; - reglElements.destroy = function() { - destroyElements(elements); - }; - return reglElements; - } - return { - create: createElements, - createStream: createElementStream, - destroyStream: destroyElementStream, - getElements: function(elements) { - if (typeof elements === "function" && elements._elements instanceof REGLElementBuffer) { - return elements._elements; - } - return null; - }, - clear: function() { - values(elementSet).forEach(destroyElements); - } - }; - } - var FLOAT = new Float32Array(1); - var INT = new Uint32Array(FLOAT.buffer); - var GL_UNSIGNED_SHORT$3 = 5123; - function convertToHalfFloat(array2) { - var ushorts = pool2.allocType(GL_UNSIGNED_SHORT$3, array2.length); - for (var i = 0; i < array2.length; ++i) { - if (isNaN(array2[i])) { - ushorts[i] = 65535; - } else if (array2[i] === Infinity) { - ushorts[i] = 31744; - } else if (array2[i] === -Infinity) { - ushorts[i] = 64512; - } else { - FLOAT[0] = array2[i]; - var x = INT[0]; - var sgn = x >>> 31 << 15; - var exp = (x << 1 >>> 24) - 127; - var frac = x >> 13 & (1 << 10) - 1; - if (exp < -24) { - ushorts[i] = sgn; - } else if (exp < -14) { - var s = -14 - exp; - ushorts[i] = sgn + (frac + (1 << 10) >> s); - } else if (exp > 15) { - ushorts[i] = sgn + 31744; - } else { - ushorts[i] = sgn + (exp + 15 << 10) + frac; - } - } - } - return ushorts; - } - function isArrayLike(s) { - return Array.isArray(s) || isTypedArray2(s); - } - var GL_COMPRESSED_TEXTURE_FORMATS = 34467; - var GL_TEXTURE_2D$1 = 3553; - var GL_TEXTURE_CUBE_MAP$1 = 34067; - var GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 = 34069; - var GL_RGBA$1 = 6408; - var GL_ALPHA = 6406; - var GL_RGB = 6407; - var GL_LUMINANCE = 6409; - var GL_LUMINANCE_ALPHA = 6410; - var GL_RGBA4 = 32854; - var GL_RGB5_A1 = 32855; - var GL_RGB565 = 36194; - var GL_UNSIGNED_SHORT_4_4_4_4 = 32819; - var GL_UNSIGNED_SHORT_5_5_5_1 = 32820; - var GL_UNSIGNED_SHORT_5_6_5 = 33635; - var GL_UNSIGNED_INT_24_8_WEBGL = 34042; - var GL_DEPTH_COMPONENT = 6402; - var GL_DEPTH_STENCIL = 34041; - var GL_SRGB_EXT = 35904; - var GL_SRGB_ALPHA_EXT = 35906; - var GL_HALF_FLOAT_OES = 36193; - var GL_COMPRESSED_RGB_S3TC_DXT1_EXT = 33776; - var GL_COMPRESSED_RGBA_S3TC_DXT1_EXT = 33777; - var GL_COMPRESSED_RGBA_S3TC_DXT3_EXT = 33778; - var GL_COMPRESSED_RGBA_S3TC_DXT5_EXT = 33779; - var GL_COMPRESSED_RGB_ATC_WEBGL = 35986; - var GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL = 35987; - var GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL = 34798; - var GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG = 35840; - var GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG = 35841; - var GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG = 35842; - var GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG = 35843; - var GL_COMPRESSED_RGB_ETC1_WEBGL = 36196; - var GL_UNSIGNED_BYTE$4 = 5121; - var GL_UNSIGNED_SHORT$2 = 5123; - var GL_UNSIGNED_INT$2 = 5125; - var GL_FLOAT$3 = 5126; - var GL_TEXTURE_WRAP_S = 10242; - var GL_TEXTURE_WRAP_T = 10243; - var GL_REPEAT = 10497; - var GL_CLAMP_TO_EDGE = 33071; - var GL_MIRRORED_REPEAT = 33648; - var GL_TEXTURE_MAG_FILTER = 10240; - var GL_TEXTURE_MIN_FILTER = 10241; - var GL_NEAREST = 9728; - var GL_LINEAR = 9729; - var GL_NEAREST_MIPMAP_NEAREST = 9984; - var GL_LINEAR_MIPMAP_NEAREST = 9985; - var GL_NEAREST_MIPMAP_LINEAR = 9986; - var GL_LINEAR_MIPMAP_LINEAR = 9987; - var GL_GENERATE_MIPMAP_HINT = 33170; - var GL_DONT_CARE = 4352; - var GL_FASTEST = 4353; - var GL_NICEST = 4354; - var GL_TEXTURE_MAX_ANISOTROPY_EXT = 34046; - var GL_UNPACK_ALIGNMENT = 3317; - var GL_UNPACK_FLIP_Y_WEBGL = 37440; - var GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL = 37441; - var GL_UNPACK_COLORSPACE_CONVERSION_WEBGL = 37443; - var GL_BROWSER_DEFAULT_WEBGL = 37444; - var GL_TEXTURE0$1 = 33984; - var MIPMAP_FILTERS = [ - GL_NEAREST_MIPMAP_NEAREST, - GL_NEAREST_MIPMAP_LINEAR, - GL_LINEAR_MIPMAP_NEAREST, - GL_LINEAR_MIPMAP_LINEAR - ]; - var CHANNELS_FORMAT = [ - 0, - GL_LUMINANCE, - GL_LUMINANCE_ALPHA, - GL_RGB, - GL_RGBA$1 - ]; - var FORMAT_CHANNELS = {}; - FORMAT_CHANNELS[GL_LUMINANCE] = FORMAT_CHANNELS[GL_ALPHA] = FORMAT_CHANNELS[GL_DEPTH_COMPONENT] = 1; - FORMAT_CHANNELS[GL_DEPTH_STENCIL] = FORMAT_CHANNELS[GL_LUMINANCE_ALPHA] = 2; - FORMAT_CHANNELS[GL_RGB] = FORMAT_CHANNELS[GL_SRGB_EXT] = 3; - FORMAT_CHANNELS[GL_RGBA$1] = FORMAT_CHANNELS[GL_SRGB_ALPHA_EXT] = 4; - function objectName(str2) { - return "[object " + str2 + "]"; - } - var CANVAS_CLASS = objectName("HTMLCanvasElement"); - var OFFSCREENCANVAS_CLASS = objectName("OffscreenCanvas"); - var CONTEXT2D_CLASS = objectName("CanvasRenderingContext2D"); - var BITMAP_CLASS = objectName("ImageBitmap"); - var IMAGE_CLASS = objectName("HTMLImageElement"); - var VIDEO_CLASS = objectName("HTMLVideoElement"); - var PIXEL_CLASSES = Object.keys(arrayTypes).concat([ - CANVAS_CLASS, - OFFSCREENCANVAS_CLASS, - CONTEXT2D_CLASS, - BITMAP_CLASS, - IMAGE_CLASS, - VIDEO_CLASS - ]); - var TYPE_SIZES = []; - TYPE_SIZES[GL_UNSIGNED_BYTE$4] = 1; - TYPE_SIZES[GL_FLOAT$3] = 4; - TYPE_SIZES[GL_HALF_FLOAT_OES] = 2; - TYPE_SIZES[GL_UNSIGNED_SHORT$2] = 2; - TYPE_SIZES[GL_UNSIGNED_INT$2] = 4; - var FORMAT_SIZES_SPECIAL = []; - FORMAT_SIZES_SPECIAL[GL_RGBA4] = 2; - FORMAT_SIZES_SPECIAL[GL_RGB5_A1] = 2; - FORMAT_SIZES_SPECIAL[GL_RGB565] = 2; - FORMAT_SIZES_SPECIAL[GL_DEPTH_STENCIL] = 4; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_S3TC_DXT1_EXT] = 0.5; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT1_EXT] = 0.5; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT3_EXT] = 1; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_S3TC_DXT5_EXT] = 1; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ATC_WEBGL] = 0.5; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL] = 1; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL] = 1; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG] = 0.5; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG] = 0.25; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG] = 0.5; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG] = 0.25; - FORMAT_SIZES_SPECIAL[GL_COMPRESSED_RGB_ETC1_WEBGL] = 0.5; - function isNumericArray(arr) { - return Array.isArray(arr) && (arr.length === 0 || typeof arr[0] === "number"); - } - function isRectArray(arr) { - if (!Array.isArray(arr)) { - return false; - } - var width = arr.length; - if (width === 0 || !isArrayLike(arr[0])) { - return false; - } - return true; - } - function classString(x) { - return Object.prototype.toString.call(x); - } - function isCanvasElement(object2) { - return classString(object2) === CANVAS_CLASS; - } - function isOffscreenCanvas(object2) { - return classString(object2) === OFFSCREENCANVAS_CLASS; - } - function isContext2D(object2) { - return classString(object2) === CONTEXT2D_CLASS; - } - function isBitmap(object2) { - return classString(object2) === BITMAP_CLASS; - } - function isImageElement(object2) { - return classString(object2) === IMAGE_CLASS; - } - function isVideoElement(object2) { - return classString(object2) === VIDEO_CLASS; - } - function isPixelData(object2) { - if (!object2) { - return false; - } - var className = classString(object2); - if (PIXEL_CLASSES.indexOf(className) >= 0) { - return true; - } - return isNumericArray(object2) || isRectArray(object2) || isNDArrayLike(object2); - } - function typedArrayCode$1(data) { - return arrayTypes[Object.prototype.toString.call(data)] | 0; - } - function convertData(result, data) { - var n = data.length; - switch (result.type) { - case GL_UNSIGNED_BYTE$4: - case GL_UNSIGNED_SHORT$2: - case GL_UNSIGNED_INT$2: - case GL_FLOAT$3: - var converted = pool2.allocType(result.type, n); - converted.set(data); - result.data = converted; - break; - case GL_HALF_FLOAT_OES: - result.data = convertToHalfFloat(data); - break; - } - } - function preConvert(image, n) { - return pool2.allocType( - image.type === GL_HALF_FLOAT_OES ? GL_FLOAT$3 : image.type, - n - ); - } - function postConvert(image, data) { - if (image.type === GL_HALF_FLOAT_OES) { - image.data = convertToHalfFloat(data); - pool2.freeType(data); - } else { - image.data = data; - } - } - function transposeData(image, array2, strideX, strideY, strideC, offset) { - var w = image.width; - var h = image.height; - var c = image.channels; - var n = w * h * c; - var data = preConvert(image, n); - var p = 0; - for (var i = 0; i < h; ++i) { - for (var j = 0; j < w; ++j) { - for (var k = 0; k < c; ++k) { - data[p++] = array2[strideX * j + strideY * i + strideC * k + offset]; - } - } - } - postConvert(image, data); - } - function getTextureSize(format2, type, width, height, isMipmap, isCube) { - var s; - if (typeof FORMAT_SIZES_SPECIAL[format2] !== "undefined") { - s = FORMAT_SIZES_SPECIAL[format2]; - } else { - s = FORMAT_CHANNELS[format2] * TYPE_SIZES[type]; - } - if (isCube) { - s *= 6; - } - if (isMipmap) { - var total = 0; - var w = width; - while (w >= 1) { - total += s * w * w; - w /= 2; - } - return total; - } else { - return s * width * height; - } - } - function createTextureSet(gl, extensions, limits, reglPoll, contextState, stats3, config) { - var mipmapHint = { - "don't care": GL_DONT_CARE, - "dont care": GL_DONT_CARE, - "nice": GL_NICEST, - "fast": GL_FASTEST - }; - var wrapModes = { - "repeat": GL_REPEAT, - "clamp": GL_CLAMP_TO_EDGE, - "mirror": GL_MIRRORED_REPEAT - }; - var magFilters = { - "nearest": GL_NEAREST, - "linear": GL_LINEAR - }; - var minFilters = extend2({ - "mipmap": GL_LINEAR_MIPMAP_LINEAR, - "nearest mipmap nearest": GL_NEAREST_MIPMAP_NEAREST, - "linear mipmap nearest": GL_LINEAR_MIPMAP_NEAREST, - "nearest mipmap linear": GL_NEAREST_MIPMAP_LINEAR, - "linear mipmap linear": GL_LINEAR_MIPMAP_LINEAR - }, magFilters); - var colorSpace = { - "none": 0, - "browser": GL_BROWSER_DEFAULT_WEBGL - }; - var textureTypes = { - "uint8": GL_UNSIGNED_BYTE$4, - "rgba4": GL_UNSIGNED_SHORT_4_4_4_4, - "rgb565": GL_UNSIGNED_SHORT_5_6_5, - "rgb5 a1": GL_UNSIGNED_SHORT_5_5_5_1 - }; - var textureFormats = { - "alpha": GL_ALPHA, - "luminance": GL_LUMINANCE, - "luminance alpha": GL_LUMINANCE_ALPHA, - "rgb": GL_RGB, - "rgba": GL_RGBA$1, - "rgba4": GL_RGBA4, - "rgb5 a1": GL_RGB5_A1, - "rgb565": GL_RGB565 - }; - var compressedTextureFormats = {}; - if (extensions.ext_srgb) { - textureFormats.srgb = GL_SRGB_EXT; - textureFormats.srgba = GL_SRGB_ALPHA_EXT; - } - if (extensions.oes_texture_float) { - textureTypes.float32 = textureTypes.float = GL_FLOAT$3; - } - if (extensions.oes_texture_half_float) { - textureTypes["float16"] = textureTypes["half float"] = GL_HALF_FLOAT_OES; - } - if (extensions.webgl_depth_texture) { - extend2(textureFormats, { - "depth": GL_DEPTH_COMPONENT, - "depth stencil": GL_DEPTH_STENCIL - }); - extend2(textureTypes, { - "uint16": GL_UNSIGNED_SHORT$2, - "uint32": GL_UNSIGNED_INT$2, - "depth stencil": GL_UNSIGNED_INT_24_8_WEBGL - }); - } - if (extensions.webgl_compressed_texture_s3tc) { - extend2(compressedTextureFormats, { - "rgb s3tc dxt1": GL_COMPRESSED_RGB_S3TC_DXT1_EXT, - "rgba s3tc dxt1": GL_COMPRESSED_RGBA_S3TC_DXT1_EXT, - "rgba s3tc dxt3": GL_COMPRESSED_RGBA_S3TC_DXT3_EXT, - "rgba s3tc dxt5": GL_COMPRESSED_RGBA_S3TC_DXT5_EXT - }); - } - if (extensions.webgl_compressed_texture_atc) { - extend2(compressedTextureFormats, { - "rgb atc": GL_COMPRESSED_RGB_ATC_WEBGL, - "rgba atc explicit alpha": GL_COMPRESSED_RGBA_ATC_EXPLICIT_ALPHA_WEBGL, - "rgba atc interpolated alpha": GL_COMPRESSED_RGBA_ATC_INTERPOLATED_ALPHA_WEBGL - }); - } - if (extensions.webgl_compressed_texture_pvrtc) { - extend2(compressedTextureFormats, { - "rgb pvrtc 4bppv1": GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG, - "rgb pvrtc 2bppv1": GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG, - "rgba pvrtc 4bppv1": GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG, - "rgba pvrtc 2bppv1": GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG - }); - } - if (extensions.webgl_compressed_texture_etc1) { - compressedTextureFormats["rgb etc1"] = GL_COMPRESSED_RGB_ETC1_WEBGL; - } - var supportedCompressedFormats = Array.prototype.slice.call( - gl.getParameter(GL_COMPRESSED_TEXTURE_FORMATS) - ); - Object.keys(compressedTextureFormats).forEach(function(name2) { - var format2 = compressedTextureFormats[name2]; - if (supportedCompressedFormats.indexOf(format2) >= 0) { - textureFormats[name2] = format2; - } - }); - var supportedFormats = Object.keys(textureFormats); - limits.textureFormats = supportedFormats; - var textureFormatsInvert = []; - Object.keys(textureFormats).forEach(function(key) { - var val = textureFormats[key]; - textureFormatsInvert[val] = key; - }); - var textureTypesInvert = []; - Object.keys(textureTypes).forEach(function(key) { - var val = textureTypes[key]; - textureTypesInvert[val] = key; - }); - var magFiltersInvert = []; - Object.keys(magFilters).forEach(function(key) { - var val = magFilters[key]; - magFiltersInvert[val] = key; - }); - var minFiltersInvert = []; - Object.keys(minFilters).forEach(function(key) { - var val = minFilters[key]; - minFiltersInvert[val] = key; - }); - var wrapModesInvert = []; - Object.keys(wrapModes).forEach(function(key) { - var val = wrapModes[key]; - wrapModesInvert[val] = key; - }); - var colorFormats = supportedFormats.reduce(function(color2, key) { - var glenum = textureFormats[key]; - if (glenum === GL_LUMINANCE || glenum === GL_ALPHA || glenum === GL_LUMINANCE || glenum === GL_LUMINANCE_ALPHA || glenum === GL_DEPTH_COMPONENT || glenum === GL_DEPTH_STENCIL || extensions.ext_srgb && (glenum === GL_SRGB_EXT || glenum === GL_SRGB_ALPHA_EXT)) { - color2[glenum] = glenum; - } else if (glenum === GL_RGB5_A1 || key.indexOf("rgba") >= 0) { - color2[glenum] = GL_RGBA$1; - } else { - color2[glenum] = GL_RGB; - } - return color2; - }, {}); - function TexFlags() { - this.internalformat = GL_RGBA$1; - this.format = GL_RGBA$1; - this.type = GL_UNSIGNED_BYTE$4; - this.compressed = false; - this.premultiplyAlpha = false; - this.flipY = false; - this.unpackAlignment = 1; - this.colorSpace = GL_BROWSER_DEFAULT_WEBGL; - this.width = 0; - this.height = 0; - this.channels = 0; - } - function copyFlags(result, other) { - result.internalformat = other.internalformat; - result.format = other.format; - result.type = other.type; - result.compressed = other.compressed; - result.premultiplyAlpha = other.premultiplyAlpha; - result.flipY = other.flipY; - result.unpackAlignment = other.unpackAlignment; - result.colorSpace = other.colorSpace; - result.width = other.width; - result.height = other.height; - result.channels = other.channels; - } - function parseFlags(flags, options) { - if (typeof options !== "object" || !options) { - return; - } - if ("premultiplyAlpha" in options) { - flags.premultiplyAlpha = options.premultiplyAlpha; - } - if ("flipY" in options) { - flags.flipY = options.flipY; - } - if ("alignment" in options) { - flags.unpackAlignment = options.alignment; - } - if ("colorSpace" in options) { - flags.colorSpace = colorSpace[options.colorSpace]; - } - if ("type" in options) { - var type = options.type; - flags.type = textureTypes[type]; - } - var w = flags.width; - var h = flags.height; - var c = flags.channels; - var hasChannels = false; - if ("shape" in options) { - w = options.shape[0]; - h = options.shape[1]; - if (options.shape.length === 3) { - c = options.shape[2]; - hasChannels = true; - } - } else { - if ("radius" in options) { - w = h = options.radius; - } - if ("width" in options) { - w = options.width; - } - if ("height" in options) { - h = options.height; - } - if ("channels" in options) { - c = options.channels; - hasChannels = true; - } - } - flags.width = w | 0; - flags.height = h | 0; - flags.channels = c | 0; - var hasFormat = false; - if ("format" in options) { - var formatStr = options.format; - var internalformat = flags.internalformat = textureFormats[formatStr]; - flags.format = colorFormats[internalformat]; - if (formatStr in textureTypes) { - if (!("type" in options)) { - flags.type = textureTypes[formatStr]; - } - } - if (formatStr in compressedTextureFormats) { - flags.compressed = true; - } - hasFormat = true; - } - if (!hasChannels && hasFormat) { - flags.channels = FORMAT_CHANNELS[flags.format]; - } else if (hasChannels && !hasFormat) { - if (flags.channels !== CHANNELS_FORMAT[flags.format]) { - flags.format = flags.internalformat = CHANNELS_FORMAT[flags.channels]; - } - } else ; - } - function setFlags(flags) { - gl.pixelStorei(GL_UNPACK_FLIP_Y_WEBGL, flags.flipY); - gl.pixelStorei(GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL, flags.premultiplyAlpha); - gl.pixelStorei(GL_UNPACK_COLORSPACE_CONVERSION_WEBGL, flags.colorSpace); - gl.pixelStorei(GL_UNPACK_ALIGNMENT, flags.unpackAlignment); - } - function TexImage() { - TexFlags.call(this); - this.xOffset = 0; - this.yOffset = 0; - this.data = null; - this.needsFree = false; - this.element = null; - this.needsCopy = false; - } - function parseImage(image, options) { - var data = null; - if (isPixelData(options)) { - data = options; - } else if (options) { - parseFlags(image, options); - if ("x" in options) { - image.xOffset = options.x | 0; - } - if ("y" in options) { - image.yOffset = options.y | 0; - } - if (isPixelData(options.data)) { - data = options.data; - } - } - if (options.copy) { - var viewW = contextState.viewportWidth; - var viewH = contextState.viewportHeight; - image.width = image.width || viewW - image.xOffset; - image.height = image.height || viewH - image.yOffset; - image.needsCopy = true; - } else if (!data) { - image.width = image.width || 1; - image.height = image.height || 1; - image.channels = image.channels || 4; - } else if (isTypedArray2(data)) { - image.channels = image.channels || 4; - image.data = data; - if (!("type" in options) && image.type === GL_UNSIGNED_BYTE$4) { - image.type = typedArrayCode$1(data); - } - } else if (isNumericArray(data)) { - image.channels = image.channels || 4; - convertData(image, data); - image.alignment = 1; - image.needsFree = true; - } else if (isNDArrayLike(data)) { - var array2 = data.data; - if (!Array.isArray(array2) && image.type === GL_UNSIGNED_BYTE$4) { - image.type = typedArrayCode$1(array2); - } - var shape = data.shape; - var stride = data.stride; - var shapeX, shapeY, shapeC, strideX, strideY, strideC; - if (shape.length === 3) { - shapeC = shape[2]; - strideC = stride[2]; - } else { - shapeC = 1; - strideC = 1; - } - shapeX = shape[0]; - shapeY = shape[1]; - strideX = stride[0]; - strideY = stride[1]; - image.alignment = 1; - image.width = shapeX; - image.height = shapeY; - image.channels = shapeC; - image.format = image.internalformat = CHANNELS_FORMAT[shapeC]; - image.needsFree = true; - transposeData(image, array2, strideX, strideY, strideC, data.offset); - } else if (isCanvasElement(data) || isOffscreenCanvas(data) || isContext2D(data)) { - if (isCanvasElement(data) || isOffscreenCanvas(data)) { - image.element = data; - } else { - image.element = data.canvas; - } - image.width = image.element.width; - image.height = image.element.height; - image.channels = 4; - } else if (isBitmap(data)) { - image.element = data; - image.width = data.width; - image.height = data.height; - image.channels = 4; - } else if (isImageElement(data)) { - image.element = data; - image.width = data.naturalWidth; - image.height = data.naturalHeight; - image.channels = 4; - } else if (isVideoElement(data)) { - image.element = data; - image.width = data.videoWidth; - image.height = data.videoHeight; - image.channels = 4; - } else if (isRectArray(data)) { - var w = image.width || data[0].length; - var h = image.height || data.length; - var c = image.channels; - if (isArrayLike(data[0][0])) { - c = c || data[0][0].length; - } else { - c = c || 1; - } - var arrayShape2 = flattenUtils.shape(data); - var n = 1; - for (var dd = 0; dd < arrayShape2.length; ++dd) { - n *= arrayShape2[dd]; - } - var allocData = preConvert(image, n); - flattenUtils.flatten(data, arrayShape2, "", allocData); - postConvert(image, allocData); - image.alignment = 1; - image.width = w; - image.height = h; - image.channels = c; - image.format = image.internalformat = CHANNELS_FORMAT[c]; - image.needsFree = true; - } - if (image.type === GL_FLOAT$3) ; - else if (image.type === GL_HALF_FLOAT_OES) ; - } - function setImage(info, target, miplevel) { - var element = info.element; - var data = info.data; - var internalformat = info.internalformat; - var format2 = info.format; - var type = info.type; - var width = info.width; - var height = info.height; - setFlags(info); - if (element) { - gl.texImage2D(target, miplevel, format2, format2, type, element); - } else if (info.compressed) { - gl.compressedTexImage2D(target, miplevel, internalformat, width, height, 0, data); - } else if (info.needsCopy) { - reglPoll(); - gl.copyTexImage2D( - target, - miplevel, - format2, - info.xOffset, - info.yOffset, - width, - height, - 0 - ); - } else { - gl.texImage2D(target, miplevel, format2, width, height, 0, format2, type, data || null); - } - } - function setSubImage(info, target, x, y, miplevel) { - var element = info.element; - var data = info.data; - var internalformat = info.internalformat; - var format2 = info.format; - var type = info.type; - var width = info.width; - var height = info.height; - setFlags(info); - if (element) { - gl.texSubImage2D( - target, - miplevel, - x, - y, - format2, - type, - element - ); - } else if (info.compressed) { - gl.compressedTexSubImage2D( - target, - miplevel, - x, - y, - internalformat, - width, - height, - data - ); - } else if (info.needsCopy) { - reglPoll(); - gl.copyTexSubImage2D( - target, - miplevel, - x, - y, - info.xOffset, - info.yOffset, - width, - height - ); - } else { - gl.texSubImage2D( - target, - miplevel, - x, - y, - width, - height, - format2, - type, - data - ); - } - } - var imagePool = []; - function allocImage() { - return imagePool.pop() || new TexImage(); - } - function freeImage(image) { - if (image.needsFree) { - pool2.freeType(image.data); - } - TexImage.call(image); - imagePool.push(image); - } - function MipMap() { - TexFlags.call(this); - this.genMipmaps = false; - this.mipmapHint = GL_DONT_CARE; - this.mipmask = 0; - this.images = Array(16); - } - function parseMipMapFromShape(mipmap, width, height) { - var img = mipmap.images[0] = allocImage(); - mipmap.mipmask = 1; - img.width = mipmap.width = width; - img.height = mipmap.height = height; - img.channels = mipmap.channels = 4; - } - function parseMipMapFromObject(mipmap, options) { - var imgData = null; - if (isPixelData(options)) { - imgData = mipmap.images[0] = allocImage(); - copyFlags(imgData, mipmap); - parseImage(imgData, options); - mipmap.mipmask = 1; - } else { - parseFlags(mipmap, options); - if (Array.isArray(options.mipmap)) { - var mipData = options.mipmap; - for (var i = 0; i < mipData.length; ++i) { - imgData = mipmap.images[i] = allocImage(); - copyFlags(imgData, mipmap); - imgData.width >>= i; - imgData.height >>= i; - parseImage(imgData, mipData[i]); - mipmap.mipmask |= 1 << i; - } - } else { - imgData = mipmap.images[0] = allocImage(); - copyFlags(imgData, mipmap); - parseImage(imgData, options); - mipmap.mipmask = 1; - } - } - copyFlags(mipmap, mipmap.images[0]); - if (mipmap.compressed && (mipmap.internalformat === GL_COMPRESSED_RGB_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT1_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT3_EXT || mipmap.internalformat === GL_COMPRESSED_RGBA_S3TC_DXT5_EXT)) ; - } - function setMipMap(mipmap, target) { - var images2 = mipmap.images; - for (var i = 0; i < images2.length; ++i) { - if (!images2[i]) { - return; - } - setImage(images2[i], target, i); - } - } - var mipPool = []; - function allocMipMap() { - var result = mipPool.pop() || new MipMap(); - TexFlags.call(result); - result.mipmask = 0; - for (var i = 0; i < 16; ++i) { - result.images[i] = null; - } - return result; - } - function freeMipMap(mipmap) { - var images2 = mipmap.images; - for (var i = 0; i < images2.length; ++i) { - if (images2[i]) { - freeImage(images2[i]); - } - images2[i] = null; - } - mipPool.push(mipmap); - } - function TexInfo() { - this.minFilter = GL_NEAREST; - this.magFilter = GL_NEAREST; - this.wrapS = GL_CLAMP_TO_EDGE; - this.wrapT = GL_CLAMP_TO_EDGE; - this.anisotropic = 1; - this.genMipmaps = false; - this.mipmapHint = GL_DONT_CARE; - } - function parseTexInfo(info, options) { - if ("min" in options) { - var minFilter = options.min; - info.minFilter = minFilters[minFilter]; - if (MIPMAP_FILTERS.indexOf(info.minFilter) >= 0 && !("faces" in options)) { - info.genMipmaps = true; - } - } - if ("mag" in options) { - var magFilter = options.mag; - info.magFilter = magFilters[magFilter]; - } - var wrapS = info.wrapS; - var wrapT = info.wrapT; - if ("wrap" in options) { - var wrap = options.wrap; - if (typeof wrap === "string") { - wrapS = wrapT = wrapModes[wrap]; - } else if (Array.isArray(wrap)) { - wrapS = wrapModes[wrap[0]]; - wrapT = wrapModes[wrap[1]]; - } - } else { - if ("wrapS" in options) { - var optWrapS = options.wrapS; - wrapS = wrapModes[optWrapS]; - } - if ("wrapT" in options) { - var optWrapT = options.wrapT; - wrapT = wrapModes[optWrapT]; - } - } - info.wrapS = wrapS; - info.wrapT = wrapT; - if ("anisotropic" in options) { - options.anisotropic; - info.anisotropic = options.anisotropic; - } - if ("mipmap" in options) { - var hasMipMap = false; - switch (typeof options.mipmap) { - case "string": - info.mipmapHint = mipmapHint[options.mipmap]; - info.genMipmaps = true; - hasMipMap = true; - break; - case "boolean": - hasMipMap = info.genMipmaps = options.mipmap; - break; - case "object": - info.genMipmaps = false; - hasMipMap = true; - break; - } - if (hasMipMap && !("min" in options)) { - info.minFilter = GL_NEAREST_MIPMAP_NEAREST; - } - } - } - function setTexInfo(info, target) { - gl.texParameteri(target, GL_TEXTURE_MIN_FILTER, info.minFilter); - gl.texParameteri(target, GL_TEXTURE_MAG_FILTER, info.magFilter); - gl.texParameteri(target, GL_TEXTURE_WRAP_S, info.wrapS); - gl.texParameteri(target, GL_TEXTURE_WRAP_T, info.wrapT); - if (extensions.ext_texture_filter_anisotropic) { - gl.texParameteri(target, GL_TEXTURE_MAX_ANISOTROPY_EXT, info.anisotropic); - } - if (info.genMipmaps) { - gl.hint(GL_GENERATE_MIPMAP_HINT, info.mipmapHint); - gl.generateMipmap(target); - } - } - var textureCount = 0; - var textureSet = {}; - var numTexUnits = limits.maxTextureUnits; - var textureUnits = Array(numTexUnits).map(function() { - return null; - }); - function REGLTexture(target) { - TexFlags.call(this); - this.mipmask = 0; - this.internalformat = GL_RGBA$1; - this.id = textureCount++; - this.refCount = 1; - this.target = target; - this.texture = gl.createTexture(); - this.unit = -1; - this.bindCount = 0; - this.texInfo = new TexInfo(); - if (config.profile) { - this.stats = { size: 0 }; - } - } - function tempBind(texture) { - gl.activeTexture(GL_TEXTURE0$1); - gl.bindTexture(texture.target, texture.texture); - } - function tempRestore() { - var prev = textureUnits[0]; - if (prev) { - gl.bindTexture(prev.target, prev.texture); - } else { - gl.bindTexture(GL_TEXTURE_2D$1, null); - } - } - function destroy2(texture) { - var handle = texture.texture; - var unit = texture.unit; - var target = texture.target; - if (unit >= 0) { - gl.activeTexture(GL_TEXTURE0$1 + unit); - gl.bindTexture(target, null); - textureUnits[unit] = null; - } - gl.deleteTexture(handle); - texture.texture = null; - texture.params = null; - texture.pixels = null; - texture.refCount = 0; - delete textureSet[texture.id]; - stats3.textureCount--; - } - extend2(REGLTexture.prototype, { - bind: function() { - var texture = this; - texture.bindCount += 1; - var unit = texture.unit; - if (unit < 0) { - for (var i = 0; i < numTexUnits; ++i) { - var other = textureUnits[i]; - if (other) { - if (other.bindCount > 0) { - continue; - } - other.unit = -1; - } - textureUnits[i] = texture; - unit = i; - break; - } - if (config.profile && stats3.maxTextureUnits < unit + 1) { - stats3.maxTextureUnits = unit + 1; - } - texture.unit = unit; - gl.activeTexture(GL_TEXTURE0$1 + unit); - gl.bindTexture(texture.target, texture.texture); - } - return unit; - }, - unbind: function() { - this.bindCount -= 1; - }, - decRef: function() { - if (--this.refCount <= 0) { - destroy2(this); - } - } - }); - function createTexture2D(a, b) { - var texture = new REGLTexture(GL_TEXTURE_2D$1); - textureSet[texture.id] = texture; - stats3.textureCount++; - function reglTexture2D(a2, b2) { - var texInfo = texture.texInfo; - TexInfo.call(texInfo); - var mipData = allocMipMap(); - if (typeof a2 === "number") { - if (typeof b2 === "number") { - parseMipMapFromShape(mipData, a2 | 0, b2 | 0); - } else { - parseMipMapFromShape(mipData, a2 | 0, a2 | 0); - } - } else if (a2) { - parseTexInfo(texInfo, a2); - parseMipMapFromObject(mipData, a2); - } else { - parseMipMapFromShape(mipData, 1, 1); - } - if (texInfo.genMipmaps) { - mipData.mipmask = (mipData.width << 1) - 1; - } - texture.mipmask = mipData.mipmask; - copyFlags(texture, mipData); - texture.internalformat = mipData.internalformat; - reglTexture2D.width = mipData.width; - reglTexture2D.height = mipData.height; - tempBind(texture); - setMipMap(mipData, GL_TEXTURE_2D$1); - setTexInfo(texInfo, GL_TEXTURE_2D$1); - tempRestore(); - freeMipMap(mipData); - if (config.profile) { - texture.stats.size = getTextureSize( - texture.internalformat, - texture.type, - mipData.width, - mipData.height, - texInfo.genMipmaps, - false - ); - } - reglTexture2D.format = textureFormatsInvert[texture.internalformat]; - reglTexture2D.type = textureTypesInvert[texture.type]; - reglTexture2D.mag = magFiltersInvert[texInfo.magFilter]; - reglTexture2D.min = minFiltersInvert[texInfo.minFilter]; - reglTexture2D.wrapS = wrapModesInvert[texInfo.wrapS]; - reglTexture2D.wrapT = wrapModesInvert[texInfo.wrapT]; - return reglTexture2D; - } - function subimage(image, x_, y_, level_) { - var x = x_ | 0; - var y = y_ | 0; - var level = level_ | 0; - var imageData = allocImage(); - copyFlags(imageData, texture); - imageData.width = 0; - imageData.height = 0; - parseImage(imageData, image); - imageData.width = imageData.width || (texture.width >> level) - x; - imageData.height = imageData.height || (texture.height >> level) - y; - tempBind(texture); - setSubImage(imageData, GL_TEXTURE_2D$1, x, y, level); - tempRestore(); - freeImage(imageData); - return reglTexture2D; - } - function resize2(w_, h_) { - var w = w_ | 0; - var h = h_ | 0 || w; - if (w === texture.width && h === texture.height) { - return reglTexture2D; - } - reglTexture2D.width = texture.width = w; - reglTexture2D.height = texture.height = h; - tempBind(texture); - for (var i = 0; texture.mipmask >> i; ++i) { - var _w = w >> i; - var _h = h >> i; - if (!_w || !_h) break; - gl.texImage2D( - GL_TEXTURE_2D$1, - i, - texture.format, - _w, - _h, - 0, - texture.format, - texture.type, - null - ); - } - tempRestore(); - if (config.profile) { - texture.stats.size = getTextureSize( - texture.internalformat, - texture.type, - w, - h, - false, - false - ); - } - return reglTexture2D; - } - reglTexture2D(a, b); - reglTexture2D.subimage = subimage; - reglTexture2D.resize = resize2; - reglTexture2D._reglType = "texture2d"; - reglTexture2D._texture = texture; - if (config.profile) { - reglTexture2D.stats = texture.stats; - } - reglTexture2D.destroy = function() { - texture.decRef(); - }; - return reglTexture2D; - } - function createTextureCube(a0, a1, a2, a3, a4, a5) { - var texture = new REGLTexture(GL_TEXTURE_CUBE_MAP$1); - textureSet[texture.id] = texture; - stats3.cubeCount++; - var faces = new Array(6); - function reglTextureCube(a02, a12, a22, a32, a42, a52) { - var i; - var texInfo = texture.texInfo; - TexInfo.call(texInfo); - for (i = 0; i < 6; ++i) { - faces[i] = allocMipMap(); - } - if (typeof a02 === "number" || !a02) { - var s = a02 | 0 || 1; - for (i = 0; i < 6; ++i) { - parseMipMapFromShape(faces[i], s, s); - } - } else if (typeof a02 === "object") { - if (a12) { - parseMipMapFromObject(faces[0], a02); - parseMipMapFromObject(faces[1], a12); - parseMipMapFromObject(faces[2], a22); - parseMipMapFromObject(faces[3], a32); - parseMipMapFromObject(faces[4], a42); - parseMipMapFromObject(faces[5], a52); - } else { - parseTexInfo(texInfo, a02); - parseFlags(texture, a02); - if ("faces" in a02) { - var faceInput = a02.faces; - for (i = 0; i < 6; ++i) { - copyFlags(faces[i], texture); - parseMipMapFromObject(faces[i], faceInput[i]); - } - } else { - for (i = 0; i < 6; ++i) { - parseMipMapFromObject(faces[i], a02); - } - } - } - } else ; - copyFlags(texture, faces[0]); - if (texInfo.genMipmaps) { - texture.mipmask = (faces[0].width << 1) - 1; - } else { - texture.mipmask = faces[0].mipmask; - } - texture.internalformat = faces[0].internalformat; - reglTextureCube.width = faces[0].width; - reglTextureCube.height = faces[0].height; - tempBind(texture); - for (i = 0; i < 6; ++i) { - setMipMap(faces[i], GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i); - } - setTexInfo(texInfo, GL_TEXTURE_CUBE_MAP$1); - tempRestore(); - if (config.profile) { - texture.stats.size = getTextureSize( - texture.internalformat, - texture.type, - reglTextureCube.width, - reglTextureCube.height, - texInfo.genMipmaps, - true - ); - } - reglTextureCube.format = textureFormatsInvert[texture.internalformat]; - reglTextureCube.type = textureTypesInvert[texture.type]; - reglTextureCube.mag = magFiltersInvert[texInfo.magFilter]; - reglTextureCube.min = minFiltersInvert[texInfo.minFilter]; - reglTextureCube.wrapS = wrapModesInvert[texInfo.wrapS]; - reglTextureCube.wrapT = wrapModesInvert[texInfo.wrapT]; - for (i = 0; i < 6; ++i) { - freeMipMap(faces[i]); - } - return reglTextureCube; - } - function subimage(face, image, x_, y_, level_) { - var x = x_ | 0; - var y = y_ | 0; - var level = level_ | 0; - var imageData = allocImage(); - copyFlags(imageData, texture); - imageData.width = 0; - imageData.height = 0; - parseImage(imageData, image); - imageData.width = imageData.width || (texture.width >> level) - x; - imageData.height = imageData.height || (texture.height >> level) - y; - tempBind(texture); - setSubImage(imageData, GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + face, x, y, level); - tempRestore(); - freeImage(imageData); - return reglTextureCube; - } - function resize2(radius_) { - var radius = radius_ | 0; - if (radius === texture.width) { - return; - } - reglTextureCube.width = texture.width = radius; - reglTextureCube.height = texture.height = radius; - tempBind(texture); - for (var i = 0; i < 6; ++i) { - for (var j = 0; texture.mipmask >> j; ++j) { - gl.texImage2D( - GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + i, - j, - texture.format, - radius >> j, - radius >> j, - 0, - texture.format, - texture.type, - null - ); - } - } - tempRestore(); - if (config.profile) { - texture.stats.size = getTextureSize( - texture.internalformat, - texture.type, - reglTextureCube.width, - reglTextureCube.height, - false, - true - ); - } - return reglTextureCube; - } - reglTextureCube(a0, a1, a2, a3, a4, a5); - reglTextureCube.subimage = subimage; - reglTextureCube.resize = resize2; - reglTextureCube._reglType = "textureCube"; - reglTextureCube._texture = texture; - if (config.profile) { - reglTextureCube.stats = texture.stats; - } - reglTextureCube.destroy = function() { - texture.decRef(); - }; - return reglTextureCube; - } - function destroyTextures() { - for (var i = 0; i < numTexUnits; ++i) { - gl.activeTexture(GL_TEXTURE0$1 + i); - gl.bindTexture(GL_TEXTURE_2D$1, null); - textureUnits[i] = null; - } - values(textureSet).forEach(destroy2); - stats3.cubeCount = 0; - stats3.textureCount = 0; - } - if (config.profile) { - stats3.getTotalTextureSize = function() { - var total = 0; - Object.keys(textureSet).forEach(function(key) { - total += textureSet[key].stats.size; - }); - return total; - }; - } - function restoreTextures() { - for (var i = 0; i < numTexUnits; ++i) { - var tex = textureUnits[i]; - if (tex) { - tex.bindCount = 0; - tex.unit = -1; - textureUnits[i] = null; - } - } - values(textureSet).forEach(function(texture) { - texture.texture = gl.createTexture(); - gl.bindTexture(texture.target, texture.texture); - for (var i2 = 0; i2 < 32; ++i2) { - if ((texture.mipmask & 1 << i2) === 0) { - continue; - } - if (texture.target === GL_TEXTURE_2D$1) { - gl.texImage2D( - GL_TEXTURE_2D$1, - i2, - texture.internalformat, - texture.width >> i2, - texture.height >> i2, - 0, - texture.internalformat, - texture.type, - null - ); - } else { - for (var j = 0; j < 6; ++j) { - gl.texImage2D( - GL_TEXTURE_CUBE_MAP_POSITIVE_X$1 + j, - i2, - texture.internalformat, - texture.width >> i2, - texture.height >> i2, - 0, - texture.internalformat, - texture.type, - null - ); - } - } - } - setTexInfo(texture.texInfo, texture.target); - }); - } - function refreshTextures() { - for (var i = 0; i < numTexUnits; ++i) { - var tex = textureUnits[i]; - if (tex) { - tex.bindCount = 0; - tex.unit = -1; - textureUnits[i] = null; - } - gl.activeTexture(GL_TEXTURE0$1 + i); - gl.bindTexture(GL_TEXTURE_2D$1, null); - gl.bindTexture(GL_TEXTURE_CUBE_MAP$1, null); - } - } - return { - create2D: createTexture2D, - createCube: createTextureCube, - clear: destroyTextures, - getTexture: function(wrapper) { - return null; - }, - restore: restoreTextures, - refresh: refreshTextures - }; - } - var GL_RENDERBUFFER = 36161; - var GL_RGBA4$1 = 32854; - var GL_RGB5_A1$1 = 32855; - var GL_RGB565$1 = 36194; - var GL_DEPTH_COMPONENT16 = 33189; - var GL_STENCIL_INDEX8 = 36168; - var GL_DEPTH_STENCIL$1 = 34041; - var GL_SRGB8_ALPHA8_EXT = 35907; - var GL_RGBA32F_EXT = 34836; - var GL_RGBA16F_EXT = 34842; - var GL_RGB16F_EXT = 34843; - var FORMAT_SIZES = []; - FORMAT_SIZES[GL_RGBA4$1] = 2; - FORMAT_SIZES[GL_RGB5_A1$1] = 2; - FORMAT_SIZES[GL_RGB565$1] = 2; - FORMAT_SIZES[GL_DEPTH_COMPONENT16] = 2; - FORMAT_SIZES[GL_STENCIL_INDEX8] = 1; - FORMAT_SIZES[GL_DEPTH_STENCIL$1] = 4; - FORMAT_SIZES[GL_SRGB8_ALPHA8_EXT] = 4; - FORMAT_SIZES[GL_RGBA32F_EXT] = 16; - FORMAT_SIZES[GL_RGBA16F_EXT] = 8; - FORMAT_SIZES[GL_RGB16F_EXT] = 6; - function getRenderbufferSize(format2, width, height) { - return FORMAT_SIZES[format2] * width * height; - } - var wrapRenderbuffers = function(gl, extensions, limits, stats3, config) { - var formatTypes2 = { - "rgba4": GL_RGBA4$1, - "rgb565": GL_RGB565$1, - "rgb5 a1": GL_RGB5_A1$1, - "depth": GL_DEPTH_COMPONENT16, - "stencil": GL_STENCIL_INDEX8, - "depth stencil": GL_DEPTH_STENCIL$1 - }; - if (extensions.ext_srgb) { - formatTypes2["srgba"] = GL_SRGB8_ALPHA8_EXT; - } - if (extensions.ext_color_buffer_half_float) { - formatTypes2["rgba16f"] = GL_RGBA16F_EXT; - formatTypes2["rgb16f"] = GL_RGB16F_EXT; - } - if (extensions.webgl_color_buffer_float) { - formatTypes2["rgba32f"] = GL_RGBA32F_EXT; - } - var formatTypesInvert = []; - Object.keys(formatTypes2).forEach(function(key) { - var val = formatTypes2[key]; - formatTypesInvert[val] = key; - }); - var renderbufferCount = 0; - var renderbufferSet = {}; - function REGLRenderbuffer(renderbuffer) { - this.id = renderbufferCount++; - this.refCount = 1; - this.renderbuffer = renderbuffer; - this.format = GL_RGBA4$1; - this.width = 0; - this.height = 0; - if (config.profile) { - this.stats = { size: 0 }; - } - } - REGLRenderbuffer.prototype.decRef = function() { - if (--this.refCount <= 0) { - destroy2(this); - } - }; - function destroy2(rb) { - var handle = rb.renderbuffer; - gl.bindRenderbuffer(GL_RENDERBUFFER, null); - gl.deleteRenderbuffer(handle); - rb.renderbuffer = null; - rb.refCount = 0; - delete renderbufferSet[rb.id]; - stats3.renderbufferCount--; - } - function createRenderbuffer(a, b) { - var renderbuffer = new REGLRenderbuffer(gl.createRenderbuffer()); - renderbufferSet[renderbuffer.id] = renderbuffer; - stats3.renderbufferCount++; - function reglRenderbuffer(a2, b2) { - var w = 0; - var h = 0; - var format2 = GL_RGBA4$1; - if (typeof a2 === "object" && a2) { - var options = a2; - if ("shape" in options) { - var shape = options.shape; - w = shape[0] | 0; - h = shape[1] | 0; - } else { - if ("radius" in options) { - w = h = options.radius | 0; - } - if ("width" in options) { - w = options.width | 0; - } - if ("height" in options) { - h = options.height | 0; - } - } - if ("format" in options) { - format2 = formatTypes2[options.format]; - } - } else if (typeof a2 === "number") { - w = a2 | 0; - if (typeof b2 === "number") { - h = b2 | 0; - } else { - h = w; - } - } else if (!a2) { - w = h = 1; - } else ; - if (w === renderbuffer.width && h === renderbuffer.height && format2 === renderbuffer.format) { - return; - } - reglRenderbuffer.width = renderbuffer.width = w; - reglRenderbuffer.height = renderbuffer.height = h; - renderbuffer.format = format2; - gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer); - gl.renderbufferStorage(GL_RENDERBUFFER, format2, w, h); - if (config.profile) { - renderbuffer.stats.size = getRenderbufferSize(renderbuffer.format, renderbuffer.width, renderbuffer.height); - } - reglRenderbuffer.format = formatTypesInvert[renderbuffer.format]; - return reglRenderbuffer; - } - function resize2(w_, h_) { - var w = w_ | 0; - var h = h_ | 0 || w; - if (w === renderbuffer.width && h === renderbuffer.height) { - return reglRenderbuffer; - } - reglRenderbuffer.width = renderbuffer.width = w; - reglRenderbuffer.height = renderbuffer.height = h; - gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer); - gl.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h); - if (config.profile) { - renderbuffer.stats.size = getRenderbufferSize( - renderbuffer.format, - renderbuffer.width, - renderbuffer.height - ); - } - return reglRenderbuffer; - } - reglRenderbuffer(a, b); - reglRenderbuffer.resize = resize2; - reglRenderbuffer._reglType = "renderbuffer"; - reglRenderbuffer._renderbuffer = renderbuffer; - if (config.profile) { - reglRenderbuffer.stats = renderbuffer.stats; - } - reglRenderbuffer.destroy = function() { - renderbuffer.decRef(); - }; - return reglRenderbuffer; - } - if (config.profile) { - stats3.getTotalRenderbufferSize = function() { - var total = 0; - Object.keys(renderbufferSet).forEach(function(key) { - total += renderbufferSet[key].stats.size; - }); - return total; - }; - } - function restoreRenderbuffers() { - values(renderbufferSet).forEach(function(rb) { - rb.renderbuffer = gl.createRenderbuffer(); - gl.bindRenderbuffer(GL_RENDERBUFFER, rb.renderbuffer); - gl.renderbufferStorage(GL_RENDERBUFFER, rb.format, rb.width, rb.height); - }); - gl.bindRenderbuffer(GL_RENDERBUFFER, null); - } - return { - create: createRenderbuffer, - clear: function() { - values(renderbufferSet).forEach(destroy2); - }, - restore: restoreRenderbuffers - }; - }; - var GL_FRAMEBUFFER$1 = 36160; - var GL_RENDERBUFFER$1 = 36161; - var GL_TEXTURE_2D$2 = 3553; - var GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 = 34069; - var GL_COLOR_ATTACHMENT0$1 = 36064; - var GL_DEPTH_ATTACHMENT = 36096; - var GL_STENCIL_ATTACHMENT = 36128; - var GL_DEPTH_STENCIL_ATTACHMENT = 33306; - var GL_FRAMEBUFFER_COMPLETE$1 = 36053; - var GL_HALF_FLOAT_OES$1 = 36193; - var GL_UNSIGNED_BYTE$5 = 5121; - var GL_FLOAT$4 = 5126; - var GL_RGB$1 = 6407; - var GL_RGBA$2 = 6408; - var textureFormatChannels = []; - textureFormatChannels[GL_RGBA$2] = 4; - textureFormatChannels[GL_RGB$1] = 3; - var textureTypeSizes = []; - textureTypeSizes[GL_UNSIGNED_BYTE$5] = 1; - textureTypeSizes[GL_FLOAT$4] = 4; - textureTypeSizes[GL_HALF_FLOAT_OES$1] = 2; - function wrapFBOState(gl, extensions, limits, textureState, renderbufferState, stats3) { - var framebufferState = { - cur: null, - next: null, - dirty: false, - setFBO: null - }; - var colorTextureFormats = ["rgba"]; - var colorRenderbufferFormats = ["rgba4", "rgb565", "rgb5 a1"]; - if (extensions.ext_srgb) { - colorRenderbufferFormats.push("srgba"); - } - if (extensions.ext_color_buffer_half_float) { - colorRenderbufferFormats.push("rgba16f", "rgb16f"); - } - if (extensions.webgl_color_buffer_float) { - colorRenderbufferFormats.push("rgba32f"); - } - if (extensions.oes_texture_half_float) ; - if (extensions.oes_texture_float) ; - function FramebufferAttachment(target, texture, renderbuffer) { - this.target = target; - this.texture = texture; - this.renderbuffer = renderbuffer; - var w = 0; - var h = 0; - if (texture) { - w = texture.width; - h = texture.height; - } else if (renderbuffer) { - w = renderbuffer.width; - h = renderbuffer.height; - } - this.width = w; - this.height = h; - } - function decRef(attachment) { - if (attachment) { - if (attachment.texture) { - attachment.texture._texture.decRef(); - } - if (attachment.renderbuffer) { - attachment.renderbuffer._renderbuffer.decRef(); - } - } - } - function incRefAndCheckShape(attachment, width, height) { - if (!attachment) { - return; - } - if (attachment.texture) { - var texture = attachment.texture._texture; - Math.max(1, texture.width); - Math.max(1, texture.height); - texture.refCount += 1; - } else { - var renderbuffer = attachment.renderbuffer._renderbuffer; - renderbuffer.refCount += 1; - } - } - function attach(location, attachment) { - if (attachment) { - if (attachment.texture) { - gl.framebufferTexture2D( - GL_FRAMEBUFFER$1, - location, - attachment.target, - attachment.texture._texture.texture, - 0 - ); - } else { - gl.framebufferRenderbuffer( - GL_FRAMEBUFFER$1, - location, - GL_RENDERBUFFER$1, - attachment.renderbuffer._renderbuffer.renderbuffer - ); - } - } - } - function parseAttachment(attachment) { - var target = GL_TEXTURE_2D$2; - var texture = null; - var renderbuffer = null; - var data = attachment; - if (typeof attachment === "object") { - data = attachment.data; - if ("target" in attachment) { - target = attachment.target | 0; - } - } - var type = data._reglType; - if (type === "texture2d") { - texture = data; - } else if (type === "textureCube") { - texture = data; - } else if (type === "renderbuffer") { - renderbuffer = data; - target = GL_RENDERBUFFER$1; - } else ; - return new FramebufferAttachment(target, texture, renderbuffer); - } - function allocAttachment(width, height, isTexture, format2, type) { - if (isTexture) { - var texture = textureState.create2D({ - width, - height, - format: format2, - type - }); - texture._texture.refCount = 0; - return new FramebufferAttachment(GL_TEXTURE_2D$2, texture, null); - } else { - var rb = renderbufferState.create({ - width, - height, - format: format2 - }); - rb._renderbuffer.refCount = 0; - return new FramebufferAttachment(GL_RENDERBUFFER$1, null, rb); - } - } - function unwrapAttachment(attachment) { - return attachment && (attachment.texture || attachment.renderbuffer); - } - function resizeAttachment(attachment, w, h) { - if (attachment) { - if (attachment.texture) { - attachment.texture.resize(w, h); - } else if (attachment.renderbuffer) { - attachment.renderbuffer.resize(w, h); - } - attachment.width = w; - attachment.height = h; - } - } - var framebufferCount = 0; - var framebufferSet = {}; - function REGLFramebuffer() { - this.id = framebufferCount++; - framebufferSet[this.id] = this; - this.framebuffer = gl.createFramebuffer(); - this.width = 0; - this.height = 0; - this.colorAttachments = []; - this.depthAttachment = null; - this.stencilAttachment = null; - this.depthStencilAttachment = null; - } - function decFBORefs(framebuffer) { - framebuffer.colorAttachments.forEach(decRef); - decRef(framebuffer.depthAttachment); - decRef(framebuffer.stencilAttachment); - decRef(framebuffer.depthStencilAttachment); - } - function destroy2(framebuffer) { - var handle = framebuffer.framebuffer; - gl.deleteFramebuffer(handle); - framebuffer.framebuffer = null; - stats3.framebufferCount--; - delete framebufferSet[framebuffer.id]; - } - function updateFramebuffer(framebuffer) { - var i; - gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebuffer.framebuffer); - var colorAttachments = framebuffer.colorAttachments; - for (i = 0; i < colorAttachments.length; ++i) { - attach(GL_COLOR_ATTACHMENT0$1 + i, colorAttachments[i]); - } - for (i = colorAttachments.length; i < limits.maxColorAttachments; ++i) { - gl.framebufferTexture2D( - GL_FRAMEBUFFER$1, - GL_COLOR_ATTACHMENT0$1 + i, - GL_TEXTURE_2D$2, - null, - 0 - ); - } - gl.framebufferTexture2D( - GL_FRAMEBUFFER$1, - GL_DEPTH_STENCIL_ATTACHMENT, - GL_TEXTURE_2D$2, - null, - 0 - ); - gl.framebufferTexture2D( - GL_FRAMEBUFFER$1, - GL_DEPTH_ATTACHMENT, - GL_TEXTURE_2D$2, - null, - 0 - ); - gl.framebufferTexture2D( - GL_FRAMEBUFFER$1, - GL_STENCIL_ATTACHMENT, - GL_TEXTURE_2D$2, - null, - 0 - ); - attach(GL_DEPTH_ATTACHMENT, framebuffer.depthAttachment); - attach(GL_STENCIL_ATTACHMENT, framebuffer.stencilAttachment); - attach(GL_DEPTH_STENCIL_ATTACHMENT, framebuffer.depthStencilAttachment); - var status = gl.checkFramebufferStatus(GL_FRAMEBUFFER$1); - if (!gl.isContextLost() && status !== GL_FRAMEBUFFER_COMPLETE$1) ; - gl.bindFramebuffer(GL_FRAMEBUFFER$1, framebufferState.next ? framebufferState.next.framebuffer : null); - framebufferState.cur = framebufferState.next; - gl.getError(); - } - function createFBO(a0, a1) { - var framebuffer = new REGLFramebuffer(); - stats3.framebufferCount++; - function reglFramebuffer(a, b) { - var i; - var width = 0; - var height = 0; - var needsDepth = true; - var needsStencil = true; - var colorBuffer = null; - var colorTexture = true; - var colorFormat = "rgba"; - var colorType = "uint8"; - var colorCount = 1; - var depthBuffer = null; - var stencilBuffer = null; - var depthStencilBuffer = null; - var depthStencilTexture = false; - if (typeof a === "number") { - width = a | 0; - height = b | 0 || width; - } else if (!a) { - width = height = 1; - } else { - var options = a; - if ("shape" in options) { - var shape = options.shape; - width = shape[0]; - height = shape[1]; - } else { - if ("radius" in options) { - width = height = options.radius; - } - if ("width" in options) { - width = options.width; - } - if ("height" in options) { - height = options.height; - } - } - if ("color" in options || "colors" in options) { - colorBuffer = options.color || options.colors; - } - if (!colorBuffer) { - if ("colorCount" in options) { - colorCount = options.colorCount | 0; - } - if ("colorTexture" in options) { - colorTexture = !!options.colorTexture; - colorFormat = "rgba4"; - } - if ("colorType" in options) { - colorType = options.colorType; - if (!colorTexture) { - if (colorType === "half float" || colorType === "float16") { - colorFormat = "rgba16f"; - } else if (colorType === "float" || colorType === "float32") { - colorFormat = "rgba32f"; - } - } - } - if ("colorFormat" in options) { - colorFormat = options.colorFormat; - if (colorTextureFormats.indexOf(colorFormat) >= 0) { - colorTexture = true; - } else if (colorRenderbufferFormats.indexOf(colorFormat) >= 0) { - colorTexture = false; - } else ; - } - } - if ("depthTexture" in options || "depthStencilTexture" in options) { - depthStencilTexture = !!(options.depthTexture || options.depthStencilTexture); - } - if ("depth" in options) { - if (typeof options.depth === "boolean") { - needsDepth = options.depth; - } else { - depthBuffer = options.depth; - needsStencil = false; - } - } - if ("stencil" in options) { - if (typeof options.stencil === "boolean") { - needsStencil = options.stencil; - } else { - stencilBuffer = options.stencil; - needsDepth = false; - } - } - if ("depthStencil" in options) { - if (typeof options.depthStencil === "boolean") { - needsDepth = needsStencil = options.depthStencil; - } else { - depthStencilBuffer = options.depthStencil; - needsDepth = false; - needsStencil = false; - } - } - } - var colorAttachments = null; - var depthAttachment = null; - var stencilAttachment = null; - var depthStencilAttachment = null; - if (Array.isArray(colorBuffer)) { - colorAttachments = colorBuffer.map(parseAttachment); - } else if (colorBuffer) { - colorAttachments = [parseAttachment(colorBuffer)]; - } else { - colorAttachments = new Array(colorCount); - for (i = 0; i < colorCount; ++i) { - colorAttachments[i] = allocAttachment( - width, - height, - colorTexture, - colorFormat, - colorType - ); - } - } - width = width || colorAttachments[0].width; - height = height || colorAttachments[0].height; - if (depthBuffer) { - depthAttachment = parseAttachment(depthBuffer); - } else if (needsDepth && !needsStencil) { - depthAttachment = allocAttachment( - width, - height, - depthStencilTexture, - "depth", - "uint32" - ); - } - if (stencilBuffer) { - stencilAttachment = parseAttachment(stencilBuffer); - } else if (needsStencil && !needsDepth) { - stencilAttachment = allocAttachment( - width, - height, - false, - "stencil", - "uint8" - ); - } - if (depthStencilBuffer) { - depthStencilAttachment = parseAttachment(depthStencilBuffer); - } else if (!depthBuffer && !stencilBuffer && needsStencil && needsDepth) { - depthStencilAttachment = allocAttachment( - width, - height, - depthStencilTexture, - "depth stencil", - "depth stencil" - ); - } - for (i = 0; i < colorAttachments.length; ++i) { - incRefAndCheckShape(colorAttachments[i]); - if (colorAttachments[i] && colorAttachments[i].texture) { - textureFormatChannels[colorAttachments[i].texture._texture.format] * textureTypeSizes[colorAttachments[i].texture._texture.type]; - } - } - incRefAndCheckShape(depthAttachment); - incRefAndCheckShape(stencilAttachment); - incRefAndCheckShape(depthStencilAttachment); - decFBORefs(framebuffer); - framebuffer.width = width; - framebuffer.height = height; - framebuffer.colorAttachments = colorAttachments; - framebuffer.depthAttachment = depthAttachment; - framebuffer.stencilAttachment = stencilAttachment; - framebuffer.depthStencilAttachment = depthStencilAttachment; - reglFramebuffer.color = colorAttachments.map(unwrapAttachment); - reglFramebuffer.depth = unwrapAttachment(depthAttachment); - reglFramebuffer.stencil = unwrapAttachment(stencilAttachment); - reglFramebuffer.depthStencil = unwrapAttachment(depthStencilAttachment); - reglFramebuffer.width = framebuffer.width; - reglFramebuffer.height = framebuffer.height; - updateFramebuffer(framebuffer); - return reglFramebuffer; - } - function resize2(w_, h_) { - var w = Math.max(w_ | 0, 1); - var h = Math.max(h_ | 0 || w, 1); - if (w === framebuffer.width && h === framebuffer.height) { - return reglFramebuffer; - } - var colorAttachments = framebuffer.colorAttachments; - for (var i = 0; i < colorAttachments.length; ++i) { - resizeAttachment(colorAttachments[i], w, h); - } - resizeAttachment(framebuffer.depthAttachment, w, h); - resizeAttachment(framebuffer.stencilAttachment, w, h); - resizeAttachment(framebuffer.depthStencilAttachment, w, h); - framebuffer.width = reglFramebuffer.width = w; - framebuffer.height = reglFramebuffer.height = h; - updateFramebuffer(framebuffer); - return reglFramebuffer; - } - reglFramebuffer(a0, a1); - return extend2(reglFramebuffer, { - resize: resize2, - _reglType: "framebuffer", - _framebuffer: framebuffer, - destroy: function() { - destroy2(framebuffer); - decFBORefs(framebuffer); - }, - use: function(block) { - framebufferState.setFBO({ - framebuffer: reglFramebuffer - }, block); - } - }); - } - function createCubeFBO(options) { - var faces = Array(6); - function reglFramebufferCube(a) { - var i; - var params = { - color: null - }; - var radius = 0; - var colorBuffer = null; - var colorFormat = "rgba"; - var colorType = "uint8"; - var colorCount = 1; - if (typeof a === "number") { - radius = a | 0; - } else if (!a) { - radius = 1; - } else { - var options2 = a; - if ("shape" in options2) { - var shape = options2.shape; - radius = shape[0]; - } else { - if ("radius" in options2) { - radius = options2.radius | 0; - } - if ("width" in options2) { - radius = options2.width | 0; - } else if ("height" in options2) { - radius = options2.height | 0; - } - } - if ("color" in options2 || "colors" in options2) { - colorBuffer = options2.color || options2.colors; - } - if (!colorBuffer) { - if ("colorCount" in options2) { - colorCount = options2.colorCount | 0; - } - if ("colorType" in options2) { - colorType = options2.colorType; - } - if ("colorFormat" in options2) { - colorFormat = options2.colorFormat; - } - } - if ("depth" in options2) { - params.depth = options2.depth; - } - if ("stencil" in options2) { - params.stencil = options2.stencil; - } - if ("depthStencil" in options2) { - params.depthStencil = options2.depthStencil; - } - } - var colorCubes; - if (colorBuffer) { - if (Array.isArray(colorBuffer)) { - colorCubes = []; - for (i = 0; i < colorBuffer.length; ++i) { - colorCubes[i] = colorBuffer[i]; - } - } else { - colorCubes = [colorBuffer]; - } - } else { - colorCubes = Array(colorCount); - var cubeMapParams = { - radius, - format: colorFormat, - type: colorType - }; - for (i = 0; i < colorCount; ++i) { - colorCubes[i] = textureState.createCube(cubeMapParams); - } - } - params.color = Array(colorCubes.length); - for (i = 0; i < colorCubes.length; ++i) { - var cube = colorCubes[i]; - radius = radius || cube.width; - params.color[i] = { - target: GL_TEXTURE_CUBE_MAP_POSITIVE_X$2, - data: colorCubes[i] - }; - } - for (i = 0; i < 6; ++i) { - for (var j = 0; j < colorCubes.length; ++j) { - params.color[j].target = GL_TEXTURE_CUBE_MAP_POSITIVE_X$2 + i; - } - if (i > 0) { - params.depth = faces[0].depth; - params.stencil = faces[0].stencil; - params.depthStencil = faces[0].depthStencil; - } - if (faces[i]) { - faces[i](params); - } else { - faces[i] = createFBO(params); - } - } - return extend2(reglFramebufferCube, { - width: radius, - height: radius, - color: colorCubes - }); - } - function resize2(radius_) { - var i; - var radius = radius_ | 0; - if (radius === reglFramebufferCube.width) { - return reglFramebufferCube; - } - var colors = reglFramebufferCube.color; - for (i = 0; i < colors.length; ++i) { - colors[i].resize(radius); - } - for (i = 0; i < 6; ++i) { - faces[i].resize(radius); - } - reglFramebufferCube.width = reglFramebufferCube.height = radius; - return reglFramebufferCube; - } - reglFramebufferCube(options); - return extend2(reglFramebufferCube, { - faces, - resize: resize2, - _reglType: "framebufferCube", - destroy: function() { - faces.forEach(function(f) { - f.destroy(); - }); - } - }); - } - function restoreFramebuffers() { - framebufferState.cur = null; - framebufferState.next = null; - framebufferState.dirty = true; - values(framebufferSet).forEach(function(fb) { - fb.framebuffer = gl.createFramebuffer(); - updateFramebuffer(fb); - }); - } - return extend2(framebufferState, { - getFramebuffer: function(object2) { - if (typeof object2 === "function" && object2._reglType === "framebuffer") { - var fbo = object2._framebuffer; - if (fbo instanceof REGLFramebuffer) { - return fbo; - } - } - return null; - }, - create: createFBO, - createCube: createCubeFBO, - clear: function() { - values(framebufferSet).forEach(destroy2); - }, - restore: restoreFramebuffers - }); - } - var GL_FLOAT$5 = 5126; - var GL_ARRAY_BUFFER$1 = 34962; - var GL_ELEMENT_ARRAY_BUFFER$1 = 34963; - function AttributeRecord() { - this.state = 0; - this.x = 0; - this.y = 0; - this.z = 0; - this.w = 0; - this.buffer = null; - this.size = 0; - this.normalized = false; - this.type = GL_FLOAT$5; - this.offset = 0; - this.stride = 0; - this.divisor = 0; - } - function wrapAttributeState(gl, extensions, limits, stats3, bufferState, elementState, drawState) { - var NUM_ATTRIBUTES = limits.maxAttributes; - var attributeBindings = new Array(NUM_ATTRIBUTES); - for (var i = 0; i < NUM_ATTRIBUTES; ++i) { - attributeBindings[i] = new AttributeRecord(); - } - var vaoCount = 0; - var vaoSet = {}; - var state = { - Record: AttributeRecord, - scope: {}, - state: attributeBindings, - currentVAO: null, - targetVAO: null, - restore: extVAO() ? restoreVAO : function() { - }, - createVAO, - getVAO, - destroyBuffer, - setVAO: extVAO() ? setVAOEXT : setVAOEmulated, - clear: extVAO() ? destroyVAOEXT : function() { - } - }; - function destroyBuffer(buffer2) { - for (var i2 = 0; i2 < attributeBindings.length; ++i2) { - var record = attributeBindings[i2]; - if (record.buffer === buffer2) { - gl.disableVertexAttribArray(i2); - record.buffer = null; - } - } - } - function extVAO() { - return extensions.oes_vertex_array_object; - } - function extInstanced() { - return extensions.angle_instanced_arrays; - } - function getVAO(vao) { - if (typeof vao === "function" && vao._vao) { - return vao._vao; - } - return null; - } - function setVAOEXT(vao) { - if (vao === state.currentVAO) { - return; - } - var ext = extVAO(); - if (vao) { - ext.bindVertexArrayOES(vao.vao); - } else { - ext.bindVertexArrayOES(null); - } - state.currentVAO = vao; - } - function setVAOEmulated(vao) { - if (vao === state.currentVAO) { - return; - } - if (vao) { - vao.bindAttrs(); - } else { - var exti = extInstanced(); - for (var i2 = 0; i2 < attributeBindings.length; ++i2) { - var binding = attributeBindings[i2]; - if (binding.buffer) { - gl.enableVertexAttribArray(i2); - binding.buffer.bind(); - gl.vertexAttribPointer(i2, binding.size, binding.type, binding.normalized, binding.stride, binding.offfset); - if (exti && binding.divisor) { - exti.vertexAttribDivisorANGLE(i2, binding.divisor); - } - } else { - gl.disableVertexAttribArray(i2); - gl.vertexAttrib4f(i2, binding.x, binding.y, binding.z, binding.w); - } - } - if (drawState.elements) { - gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, drawState.elements.buffer.buffer); - } else { - gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null); - } - } - state.currentVAO = vao; - } - function destroyVAOEXT() { - values(vaoSet).forEach(function(vao) { - vao.destroy(); - }); - } - function REGLVAO() { - this.id = ++vaoCount; - this.attributes = []; - this.elements = null; - this.ownsElements = false; - this.count = 0; - this.offset = 0; - this.instances = -1; - this.primitive = 4; - var extension = extVAO(); - if (extension) { - this.vao = extension.createVertexArrayOES(); - } else { - this.vao = null; - } - vaoSet[this.id] = this; - this.buffers = []; - } - REGLVAO.prototype.bindAttrs = function() { - var exti = extInstanced(); - var attributes2 = this.attributes; - for (var i2 = 0; i2 < attributes2.length; ++i2) { - var attr = attributes2[i2]; - if (attr.buffer) { - gl.enableVertexAttribArray(i2); - gl.bindBuffer(GL_ARRAY_BUFFER$1, attr.buffer.buffer); - gl.vertexAttribPointer(i2, attr.size, attr.type, attr.normalized, attr.stride, attr.offset); - if (exti && attr.divisor) { - exti.vertexAttribDivisorANGLE(i2, attr.divisor); - } - } else { - gl.disableVertexAttribArray(i2); - gl.vertexAttrib4f(i2, attr.x, attr.y, attr.z, attr.w); - } - } - for (var j = attributes2.length; j < NUM_ATTRIBUTES; ++j) { - gl.disableVertexAttribArray(j); - } - var elements = elementState.getElements(this.elements); - if (elements) { - gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, elements.buffer.buffer); - } else { - gl.bindBuffer(GL_ELEMENT_ARRAY_BUFFER$1, null); - } - }; - REGLVAO.prototype.refresh = function() { - var ext = extVAO(); - if (ext) { - ext.bindVertexArrayOES(this.vao); - this.bindAttrs(); - state.currentVAO = null; - ext.bindVertexArrayOES(null); - } - }; - REGLVAO.prototype.destroy = function() { - if (this.vao) { - var extension = extVAO(); - if (this === state.currentVAO) { - state.currentVAO = null; - extension.bindVertexArrayOES(null); - } - extension.deleteVertexArrayOES(this.vao); - this.vao = null; - } - if (this.ownsElements) { - this.elements.destroy(); - this.elements = null; - this.ownsElements = false; - } - if (vaoSet[this.id]) { - delete vaoSet[this.id]; - stats3.vaoCount -= 1; - } - }; - function restoreVAO() { - var ext = extVAO(); - if (ext) { - values(vaoSet).forEach(function(vao) { - vao.refresh(); - }); - } - } - function createVAO(_attr) { - var vao = new REGLVAO(); - stats3.vaoCount += 1; - function updateVAO(options) { - var attributes2; - if (Array.isArray(options)) { - attributes2 = options; - if (vao.elements && vao.ownsElements) { - vao.elements.destroy(); - } - vao.elements = null; - vao.ownsElements = false; - vao.offset = 0; - vao.count = 0; - vao.instances = -1; - vao.primitive = 4; - } else { - if (options.elements) { - var elements = options.elements; - if (vao.ownsElements) { - if (typeof elements === "function" && elements._reglType === "elements") { - vao.elements.destroy(); - vao.ownsElements = false; - } else { - vao.elements(elements); - vao.ownsElements = false; - } - } else if (elementState.getElements(options.elements)) { - vao.elements = options.elements; - vao.ownsElements = false; - } else { - vao.elements = elementState.create(options.elements); - vao.ownsElements = true; - } - } else { - vao.elements = null; - vao.ownsElements = false; - } - attributes2 = options.attributes; - vao.offset = 0; - vao.count = -1; - vao.instances = -1; - vao.primitive = 4; - if (vao.elements) { - vao.count = vao.elements._elements.vertCount; - vao.primitive = vao.elements._elements.primType; - } - if ("offset" in options) { - vao.offset = options.offset | 0; - } - if ("count" in options) { - vao.count = options.count | 0; - } - if ("instances" in options) { - vao.instances = options.instances | 0; - } - if ("primitive" in options) { - vao.primitive = primTypes[options.primitive]; - } - } - var bufUpdated = {}; - var nattributes = vao.attributes; - nattributes.length = attributes2.length; - for (var i2 = 0; i2 < attributes2.length; ++i2) { - var spec = attributes2[i2]; - var rec = nattributes[i2] = new AttributeRecord(); - var data = spec.data || spec; - if (Array.isArray(data) || isTypedArray2(data) || isNDArrayLike(data)) { - var buf; - if (vao.buffers[i2]) { - buf = vao.buffers[i2]; - if (isTypedArray2(data) && buf._buffer.byteLength >= data.byteLength) { - buf.subdata(data); - } else { - buf.destroy(); - vao.buffers[i2] = null; - } - } - if (!vao.buffers[i2]) { - buf = vao.buffers[i2] = bufferState.create(spec, GL_ARRAY_BUFFER$1, false, true); - } - rec.buffer = bufferState.getBuffer(buf); - rec.size = rec.buffer.dimension | 0; - rec.normalized = false; - rec.type = rec.buffer.dtype; - rec.offset = 0; - rec.stride = 0; - rec.divisor = 0; - rec.state = 1; - bufUpdated[i2] = 1; - } else if (bufferState.getBuffer(spec)) { - rec.buffer = bufferState.getBuffer(spec); - rec.size = rec.buffer.dimension | 0; - rec.normalized = false; - rec.type = rec.buffer.dtype; - rec.offset = 0; - rec.stride = 0; - rec.divisor = 0; - rec.state = 1; - } else if (bufferState.getBuffer(spec.buffer)) { - rec.buffer = bufferState.getBuffer(spec.buffer); - rec.size = (+spec.size || rec.buffer.dimension) | 0; - rec.normalized = !!spec.normalized || false; - if ("type" in spec) { - rec.type = glTypes[spec.type]; - } else { - rec.type = rec.buffer.dtype; - } - rec.offset = (spec.offset || 0) | 0; - rec.stride = (spec.stride || 0) | 0; - rec.divisor = (spec.divisor || 0) | 0; - rec.state = 1; - } else if ("x" in spec) { - rec.x = +spec.x || 0; - rec.y = +spec.y || 0; - rec.z = +spec.z || 0; - rec.w = +spec.w || 0; - rec.state = 2; - } else ; - } - for (var j = 0; j < vao.buffers.length; ++j) { - if (!bufUpdated[j] && vao.buffers[j]) { - vao.buffers[j].destroy(); - vao.buffers[j] = null; - } - } - vao.refresh(); - return updateVAO; - } - updateVAO.destroy = function() { - for (var j = 0; j < vao.buffers.length; ++j) { - if (vao.buffers[j]) { - vao.buffers[j].destroy(); - } - } - vao.buffers.length = 0; - if (vao.ownsElements) { - vao.elements.destroy(); - vao.elements = null; - vao.ownsElements = false; - } - vao.destroy(); - }; - updateVAO._vao = vao; - updateVAO._reglType = "vao"; - return updateVAO(_attr); - } - return state; - } - var GL_FRAGMENT_SHADER = 35632; - var GL_VERTEX_SHADER = 35633; - var GL_ACTIVE_UNIFORMS = 35718; - var GL_ACTIVE_ATTRIBUTES = 35721; - function wrapShaderState(gl, stringStore, stats3, config) { - var fragShaders = {}; - var vertShaders = {}; - function ActiveInfo(name2, id, location, info) { - this.name = name2; - this.id = id; - this.location = location; - this.info = info; - } - function insertActiveInfo(list, info) { - for (var i = 0; i < list.length; ++i) { - if (list[i].id === info.id) { - list[i].location = info.location; - return; - } - } - list.push(info); - } - function getShader(type, id, command2) { - var cache2 = type === GL_FRAGMENT_SHADER ? fragShaders : vertShaders; - var shader = cache2[id]; - if (!shader) { - var source = stringStore.str(id); - shader = gl.createShader(type); - gl.shaderSource(shader, source); - gl.compileShader(shader); - cache2[id] = shader; - } - return shader; - } - var programCache = {}; - var programList = []; - var PROGRAM_COUNTER = 0; - function REGLProgram(fragId, vertId) { - this.id = PROGRAM_COUNTER++; - this.fragId = fragId; - this.vertId = vertId; - this.program = null; - this.uniforms = []; - this.attributes = []; - this.refCount = 1; - if (config.profile) { - this.stats = { - uniformsCount: 0, - attributesCount: 0 - }; - } - } - function linkProgram(desc, command2, attributeLocations) { - var i, info; - var fragShader = getShader(GL_FRAGMENT_SHADER, desc.fragId); - var vertShader = getShader(GL_VERTEX_SHADER, desc.vertId); - var program = desc.program = gl.createProgram(); - gl.attachShader(program, fragShader); - gl.attachShader(program, vertShader); - if (attributeLocations) { - for (i = 0; i < attributeLocations.length; ++i) { - var binding = attributeLocations[i]; - gl.bindAttribLocation(program, binding[0], binding[1]); - } - } - gl.linkProgram(program); - var numUniforms = gl.getProgramParameter(program, GL_ACTIVE_UNIFORMS); - if (config.profile) { - desc.stats.uniformsCount = numUniforms; - } - var uniforms = desc.uniforms; - for (i = 0; i < numUniforms; ++i) { - info = gl.getActiveUniform(program, i); - if (info) { - if (info.size > 1) { - for (var j = 0; j < info.size; ++j) { - var name2 = info.name.replace("[0]", "[" + j + "]"); - insertActiveInfo(uniforms, new ActiveInfo( - name2, - stringStore.id(name2), - gl.getUniformLocation(program, name2), - info - )); - } - } else { - insertActiveInfo(uniforms, new ActiveInfo( - info.name, - stringStore.id(info.name), - gl.getUniformLocation(program, info.name), - info - )); - } - } - } - var numAttributes = gl.getProgramParameter(program, GL_ACTIVE_ATTRIBUTES); - if (config.profile) { - desc.stats.attributesCount = numAttributes; - } - var attributes2 = desc.attributes; - for (i = 0; i < numAttributes; ++i) { - info = gl.getActiveAttrib(program, i); - if (info) { - insertActiveInfo(attributes2, new ActiveInfo( - info.name, - stringStore.id(info.name), - gl.getAttribLocation(program, info.name), - info - )); - } - } - } - if (config.profile) { - stats3.getMaxUniformsCount = function() { - var m = 0; - programList.forEach(function(desc) { - if (desc.stats.uniformsCount > m) { - m = desc.stats.uniformsCount; - } - }); - return m; - }; - stats3.getMaxAttributesCount = function() { - var m = 0; - programList.forEach(function(desc) { - if (desc.stats.attributesCount > m) { - m = desc.stats.attributesCount; - } - }); - return m; - }; - } - function restoreShaders() { - fragShaders = {}; - vertShaders = {}; - for (var i = 0; i < programList.length; ++i) { - linkProgram(programList[i], null, programList[i].attributes.map(function(info) { - return [info.location, info.name]; - })); - } - } - return { - clear: function() { - var deleteShader = gl.deleteShader.bind(gl); - values(fragShaders).forEach(deleteShader); - fragShaders = {}; - values(vertShaders).forEach(deleteShader); - vertShaders = {}; - programList.forEach(function(desc) { - gl.deleteProgram(desc.program); - }); - programList.length = 0; - programCache = {}; - stats3.shaderCount = 0; - }, - program: function(vertId, fragId, command2, attribLocations) { - var cache2 = programCache[fragId]; - if (!cache2) { - cache2 = programCache[fragId] = {}; - } - var prevProgram = cache2[vertId]; - if (prevProgram) { - prevProgram.refCount++; - if (!attribLocations) { - return prevProgram; - } - } - var program = new REGLProgram(fragId, vertId); - stats3.shaderCount++; - linkProgram(program, command2, attribLocations); - if (!prevProgram) { - cache2[vertId] = program; - } - programList.push(program); - return extend2(program, { - destroy: function() { - program.refCount--; - if (program.refCount <= 0) { - gl.deleteProgram(program.program); - var idx = programList.indexOf(program); - programList.splice(idx, 1); - stats3.shaderCount--; - } - if (cache2[program.vertId].refCount <= 0) { - gl.deleteShader(vertShaders[program.vertId]); - delete vertShaders[program.vertId]; - delete programCache[program.fragId][program.vertId]; - } - if (!Object.keys(programCache[program.fragId]).length) { - gl.deleteShader(fragShaders[program.fragId]); - delete fragShaders[program.fragId]; - delete programCache[program.fragId]; - } - } - }); - }, - restore: restoreShaders, - shader: getShader, - frag: -1, - vert: -1 - }; - } - var GL_RGBA$3 = 6408; - var GL_UNSIGNED_BYTE$6 = 5121; - var GL_PACK_ALIGNMENT = 3333; - var GL_FLOAT$6 = 5126; - function wrapReadPixels(gl, framebufferState, reglPoll, context2, glAttributes, extensions, limits) { - function readPixelsImpl(input) { - var type; - if (framebufferState.next === null) { - type = GL_UNSIGNED_BYTE$6; - } else { - type = framebufferState.next.colorAttachments[0].texture._texture.type; - } - var x = 0; - var y = 0; - var width = context2.framebufferWidth; - var height = context2.framebufferHeight; - var data = null; - if (isTypedArray2(input)) { - data = input; - } else if (input) { - x = input.x | 0; - y = input.y | 0; - width = (input.width || context2.framebufferWidth - x) | 0; - height = (input.height || context2.framebufferHeight - y) | 0; - data = input.data || null; - } - reglPoll(); - var size = width * height * 4; - if (!data) { - if (type === GL_UNSIGNED_BYTE$6) { - data = new Uint8Array(size); - } else if (type === GL_FLOAT$6) { - data = data || new Float32Array(size); - } - } - gl.pixelStorei(GL_PACK_ALIGNMENT, 4); - gl.readPixels( - x, - y, - width, - height, - GL_RGBA$3, - type, - data - ); - return data; - } - function readPixelsFBO(options) { - var result; - framebufferState.setFBO({ - framebuffer: options.framebuffer - }, function() { - result = readPixelsImpl(options); - }); - return result; - } - function readPixels(options) { - if (!options || !("framebuffer" in options)) { - return readPixelsImpl(options); - } else { - return readPixelsFBO(options); - } - } - return readPixels; - } - function hex_sha256(s) { - return rstr2hex(rstr_sha256(str2rstr_utf8(s))); - } - function rstr_sha256(s) { - return binb2rstr(binb_sha256(rstr2binb(s), s.length * 8)); - } - function rstr2hex(input) { - var hex_tab = "0123456789abcdef"; - var output = ""; - var x; - for (var i = 0; i < input.length; i++) { - x = input.charCodeAt(i); - output += hex_tab.charAt(x >>> 4 & 15) + hex_tab.charAt(x & 15); - } - return output; - } - function str2rstr_utf8(input) { - var output = ""; - var i = -1; - var x, y; - while (++i < input.length) { - x = input.charCodeAt(i); - y = i + 1 < input.length ? input.charCodeAt(i + 1) : 0; - if (55296 <= x && x <= 56319 && 56320 <= y && y <= 57343) { - x = 65536 + ((x & 1023) << 10) + (y & 1023); - i++; - } - if (x <= 127) - output += String.fromCharCode(x); - else if (x <= 2047) - output += String.fromCharCode( - 192 | x >>> 6 & 31, - 128 | x & 63 - ); - else if (x <= 65535) - output += String.fromCharCode( - 224 | x >>> 12 & 15, - 128 | x >>> 6 & 63, - 128 | x & 63 - ); - else if (x <= 2097151) - output += String.fromCharCode( - 240 | x >>> 18 & 7, - 128 | x >>> 12 & 63, - 128 | x >>> 6 & 63, - 128 | x & 63 - ); - } - return output; - } - function rstr2binb(input) { - var output = Array(input.length >> 2); - for (var i = 0; i < output.length; i++) - output[i] = 0; - for (var i = 0; i < input.length * 8; i += 8) - output[i >> 5] |= (input.charCodeAt(i / 8) & 255) << 24 - i % 32; - return output; - } - function binb2rstr(input) { - var output = ""; - for (var i = 0; i < input.length * 32; i += 8) - output += String.fromCharCode(input[i >> 5] >>> 24 - i % 32 & 255); - return output; - } - function sha256_S(X, n) { - return X >>> n | X << 32 - n; - } - function sha256_R(X, n) { - return X >>> n; - } - function sha256_Ch(x, y, z) { - return x & y ^ ~x & z; - } - function sha256_Maj(x, y, z) { - return x & y ^ x & z ^ y & z; - } - function sha256_Sigma0256(x) { - return sha256_S(x, 2) ^ sha256_S(x, 13) ^ sha256_S(x, 22); - } - function sha256_Sigma1256(x) { - return sha256_S(x, 6) ^ sha256_S(x, 11) ^ sha256_S(x, 25); - } - function sha256_Gamma0256(x) { - return sha256_S(x, 7) ^ sha256_S(x, 18) ^ sha256_R(x, 3); - } - function sha256_Gamma1256(x) { - return sha256_S(x, 17) ^ sha256_S(x, 19) ^ sha256_R(x, 10); - } - var sha256_K = new Array( - 1116352408, - 1899447441, - -1245643825, - -373957723, - 961987163, - 1508970993, - -1841331548, - -1424204075, - -670586216, - 310598401, - 607225278, - 1426881987, - 1925078388, - -2132889090, - -1680079193, - -1046744716, - -459576895, - -272742522, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - -1740746414, - -1473132947, - -1341970488, - -1084653625, - -958395405, - -710438585, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - -2117940946, - -1838011259, - -1564481375, - -1474664885, - -1035236496, - -949202525, - -778901479, - -694614492, - -200395387, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - -2067236844, - -1933114872, - -1866530822, - -1538233109, - -1090935817, - -965641998 - ); - function binb_sha256(m, l) { - var HASH = new Array( - 1779033703, - -1150833019, - 1013904242, - -1521486534, - 1359893119, - -1694144372, - 528734635, - 1541459225 - ); - var W = new Array(64); - var a, b, c, d, e, f, g, h; - var i, j, T1, T2; - m[l >> 5] |= 128 << 24 - l % 32; - m[(l + 64 >> 9 << 4) + 15] = l; - for (i = 0; i < m.length; i += 16) { - a = HASH[0]; - b = HASH[1]; - c = HASH[2]; - d = HASH[3]; - e = HASH[4]; - f = HASH[5]; - g = HASH[6]; - h = HASH[7]; - for (j = 0; j < 64; j++) { - if (j < 16) W[j] = m[j + i]; - else W[j] = safe_add(safe_add( - safe_add(sha256_Gamma1256(W[j - 2]), W[j - 7]), - sha256_Gamma0256(W[j - 15]) - ), W[j - 16]); - T1 = safe_add(safe_add( - safe_add(safe_add(h, sha256_Sigma1256(e)), sha256_Ch(e, f, g)), - sha256_K[j] - ), W[j]); - T2 = safe_add(sha256_Sigma0256(a), sha256_Maj(a, b, c)); - h = g; - g = f; - f = e; - e = safe_add(d, T1); - d = c; - c = b; - b = a; - a = safe_add(T1, T2); - } - HASH[0] = safe_add(a, HASH[0]); - HASH[1] = safe_add(b, HASH[1]); - HASH[2] = safe_add(c, HASH[2]); - HASH[3] = safe_add(d, HASH[3]); - HASH[4] = safe_add(e, HASH[4]); - HASH[5] = safe_add(f, HASH[5]); - HASH[6] = safe_add(g, HASH[6]); - HASH[7] = safe_add(h, HASH[7]); - } - return HASH; - } - function safe_add(x, y) { - var lsw = (x & 65535) + (y & 65535); - var msw = (x >> 16) + (y >> 16) + (lsw >> 16); - return msw << 16 | lsw & 65535; - } - function slice2(x) { - return Array.prototype.slice.call(x); - } - function join(x) { - return slice2(x).join(""); - } - function createEnvironment(options) { - var cache2 = options && options.cache; - var varCounter = 0; - var linkedNames = []; - var linkedValues = []; - var isStable = []; - function link(value2, options2) { - var stable = options2 && options2.stable; - if (!stable) { - for (var i = 0; i < linkedValues.length; ++i) { - if (linkedValues[i] === value2 && !isStable[i]) { - return linkedNames[i]; - } - } - } - var name2 = "g" + varCounter++; - linkedNames.push(name2); - linkedValues.push(value2); - isStable.push(stable); - return name2; - } - function block() { - var code2 = []; - function push() { - code2.push.apply(code2, slice2(arguments)); - } - var vars = []; - function def() { - var name2 = "v" + varCounter++; - vars.push(name2); - if (arguments.length > 0) { - code2.push(name2, "="); - code2.push.apply(code2, slice2(arguments)); - code2.push(";"); - } - return name2; - } - return extend2(push, { - def, - toString: function() { - return join([ - vars.length > 0 ? "var " + vars.join(",") + ";" : "", - join(code2) - ]); - } - }); - } - function scope() { - var entry = block(); - var exit = block(); - var entryToString = entry.toString; - var exitToString = exit.toString; - function save(object2, prop) { - exit(object2, prop, "=", entry.def(object2, prop), ";"); - } - return extend2(function() { - entry.apply(entry, slice2(arguments)); - }, { - def: entry.def, - entry, - exit, - save, - set: function(object2, prop, value2) { - save(object2, prop); - entry(object2, prop, "=", value2, ";"); - }, - toString: function() { - return entryToString() + exitToString(); - } - }); - } - function conditional() { - var pred = join(arguments); - var thenBlock = scope(); - var elseBlock = scope(); - var thenToString = thenBlock.toString; - var elseToString = elseBlock.toString; - return extend2(thenBlock, { - then: function() { - thenBlock.apply(thenBlock, slice2(arguments)); - return this; - }, - else: function() { - elseBlock.apply(elseBlock, slice2(arguments)); - return this; - }, - toString: function() { - var elseClause = elseToString(); - if (elseClause) { - elseClause = "else{" + elseClause + "}"; - } - return join([ - "if(", - pred, - "){", - thenToString(), - "}", - elseClause - ]); - } - }); - } - var globalBlock = block(); - var procedures = {}; - function proc(name2, count2) { - var args = []; - function arg() { - var name3 = "a" + args.length; - args.push(name3); - return name3; - } - count2 = count2 || 0; - for (var i = 0; i < count2; ++i) { - arg(); - } - var body = scope(); - var bodyToString = body.toString; - var result = procedures[name2] = extend2(body, { - arg, - toString: function() { - return join([ - "function(", - args.join(), - "){", - bodyToString(), - "}" - ]); - } - }); - return result; - } - function compile() { - var code2 = [ - '"use strict";', - globalBlock, - "return {" - ]; - Object.keys(procedures).forEach(function(name2) { - code2.push('"', name2, '":', procedures[name2].toString(), ","); - }); - code2.push("}"); - var src2 = join(code2).replace(/;/g, ";\n").replace(/}/g, "}\n").replace(/{/g, "{\n"); - var key; - if (cache2) { - key = hex_sha256(src2); - if (cache2[key]) { - return cache2[key].apply(null, linkedValues); - } - } - var proc2 = Function.apply(null, linkedNames.concat(src2)); - if (cache2) { - cache2[key] = proc2; - } - return proc2.apply(null, linkedValues); - } - return { - global: globalBlock, - link, - block, - proc, - scope, - cond: conditional, - compile - }; - } - var CUTE_COMPONENTS = "xyzw".split(""); - var GL_UNSIGNED_BYTE$7 = 5121; - var ATTRIB_STATE_POINTER = 1; - var ATTRIB_STATE_CONSTANT = 2; - var DYN_FUNC$1 = 0; - var DYN_PROP$1 = 1; - var DYN_CONTEXT$1 = 2; - var DYN_STATE$1 = 3; - var DYN_THUNK = 4; - var DYN_CONSTANT$1 = 5; - var DYN_ARRAY$1 = 6; - var S_DITHER = "dither"; - var S_BLEND_ENABLE = "blend.enable"; - var S_BLEND_COLOR = "blend.color"; - var S_BLEND_EQUATION = "blend.equation"; - var S_BLEND_FUNC = "blend.func"; - var S_DEPTH_ENABLE = "depth.enable"; - var S_DEPTH_FUNC = "depth.func"; - var S_DEPTH_RANGE = "depth.range"; - var S_DEPTH_MASK = "depth.mask"; - var S_COLOR_MASK = "colorMask"; - var S_CULL_ENABLE = "cull.enable"; - var S_CULL_FACE = "cull.face"; - var S_FRONT_FACE = "frontFace"; - var S_LINE_WIDTH = "lineWidth"; - var S_POLYGON_OFFSET_ENABLE = "polygonOffset.enable"; - var S_POLYGON_OFFSET_OFFSET = "polygonOffset.offset"; - var S_SAMPLE_ALPHA = "sample.alpha"; - var S_SAMPLE_ENABLE = "sample.enable"; - var S_SAMPLE_COVERAGE = "sample.coverage"; - var S_STENCIL_ENABLE = "stencil.enable"; - var S_STENCIL_MASK = "stencil.mask"; - var S_STENCIL_FUNC = "stencil.func"; - var S_STENCIL_OPFRONT = "stencil.opFront"; - var S_STENCIL_OPBACK = "stencil.opBack"; - var S_SCISSOR_ENABLE = "scissor.enable"; - var S_SCISSOR_BOX = "scissor.box"; - var S_VIEWPORT = "viewport"; - var S_PROFILE = "profile"; - var S_FRAMEBUFFER = "framebuffer"; - var S_VERT = "vert"; - var S_FRAG = "frag"; - var S_ELEMENTS = "elements"; - var S_PRIMITIVE = "primitive"; - var S_COUNT = "count"; - var S_OFFSET = "offset"; - var S_INSTANCES = "instances"; - var S_VAO = "vao"; - var SUFFIX_WIDTH = "Width"; - var SUFFIX_HEIGHT = "Height"; - var S_FRAMEBUFFER_WIDTH = S_FRAMEBUFFER + SUFFIX_WIDTH; - var S_FRAMEBUFFER_HEIGHT = S_FRAMEBUFFER + SUFFIX_HEIGHT; - var S_VIEWPORT_WIDTH = S_VIEWPORT + SUFFIX_WIDTH; - var S_VIEWPORT_HEIGHT = S_VIEWPORT + SUFFIX_HEIGHT; - var S_DRAWINGBUFFER = "drawingBuffer"; - var S_DRAWINGBUFFER_WIDTH = S_DRAWINGBUFFER + SUFFIX_WIDTH; - var S_DRAWINGBUFFER_HEIGHT = S_DRAWINGBUFFER + SUFFIX_HEIGHT; - var NESTED_OPTIONS = [ - S_BLEND_FUNC, - S_BLEND_EQUATION, - S_STENCIL_FUNC, - S_STENCIL_OPFRONT, - S_STENCIL_OPBACK, - S_SAMPLE_COVERAGE, - S_VIEWPORT, - S_SCISSOR_BOX, - S_POLYGON_OFFSET_OFFSET - ]; - var GL_ARRAY_BUFFER$2 = 34962; - var GL_ELEMENT_ARRAY_BUFFER$2 = 34963; - var GL_CULL_FACE = 2884; - var GL_BLEND = 3042; - var GL_DITHER = 3024; - var GL_STENCIL_TEST = 2960; - var GL_DEPTH_TEST = 2929; - var GL_SCISSOR_TEST = 3089; - var GL_POLYGON_OFFSET_FILL = 32823; - var GL_SAMPLE_ALPHA_TO_COVERAGE = 32926; - var GL_SAMPLE_COVERAGE = 32928; - var GL_FLOAT$7 = 5126; - var GL_FLOAT_VEC2 = 35664; - var GL_FLOAT_VEC3 = 35665; - var GL_FLOAT_VEC4 = 35666; - var GL_INT$2 = 5124; - var GL_INT_VEC2 = 35667; - var GL_INT_VEC3 = 35668; - var GL_INT_VEC4 = 35669; - var GL_BOOL = 35670; - var GL_BOOL_VEC2 = 35671; - var GL_BOOL_VEC3 = 35672; - var GL_BOOL_VEC4 = 35673; - var GL_FLOAT_MAT2 = 35674; - var GL_FLOAT_MAT3 = 35675; - var GL_FLOAT_MAT4 = 35676; - var GL_SAMPLER_2D = 35678; - var GL_SAMPLER_CUBE = 35680; - var GL_TRIANGLES$1 = 4; - var GL_FRONT = 1028; - var GL_BACK = 1029; - var GL_CW = 2304; - var GL_CCW = 2305; - var GL_MIN_EXT = 32775; - var GL_MAX_EXT = 32776; - var GL_ALWAYS = 519; - var GL_KEEP = 7680; - var GL_ZERO = 0; - var GL_ONE = 1; - var GL_FUNC_ADD = 32774; - var GL_LESS = 513; - var GL_FRAMEBUFFER$2 = 36160; - var GL_COLOR_ATTACHMENT0$2 = 36064; - var blendFuncs = { - "0": 0, - "1": 1, - "zero": 0, - "one": 1, - "src color": 768, - "one minus src color": 769, - "src alpha": 770, - "one minus src alpha": 771, - "dst color": 774, - "one minus dst color": 775, - "dst alpha": 772, - "one minus dst alpha": 773, - "constant color": 32769, - "one minus constant color": 32770, - "constant alpha": 32771, - "one minus constant alpha": 32772, - "src alpha saturate": 776 - }; - var compareFuncs = { - "never": 512, - "less": 513, - "<": 513, - "equal": 514, - "=": 514, - "==": 514, - "===": 514, - "lequal": 515, - "<=": 515, - "greater": 516, - ">": 516, - "notequal": 517, - "!=": 517, - "!==": 517, - "gequal": 518, - ">=": 518, - "always": 519 - }; - var stencilOps = { - "0": 0, - "zero": 0, - "keep": 7680, - "replace": 7681, - "increment": 7682, - "decrement": 7683, - "increment wrap": 34055, - "decrement wrap": 34056, - "invert": 5386 - }; - var orientationType = { - "cw": GL_CW, - "ccw": GL_CCW - }; - function isBufferArgs(x) { - return Array.isArray(x) || isTypedArray2(x) || isNDArrayLike(x); - } - function sortState(state) { - return state.sort(function(a, b) { - if (a === S_VIEWPORT) { - return -1; - } else if (b === S_VIEWPORT) { - return 1; - } - return a < b ? -1 : 1; - }); - } - function Declaration(thisDep, contextDep, propDep, append) { - this.thisDep = thisDep; - this.contextDep = contextDep; - this.propDep = propDep; - this.append = append; - } - function isStatic(decl) { - return decl && !(decl.thisDep || decl.contextDep || decl.propDep); - } - function createStaticDecl(append) { - return new Declaration(false, false, false, append); - } - function createDynamicDecl(dyn, append) { - var type = dyn.type; - if (type === DYN_FUNC$1) { - var numArgs = dyn.data.length; - return new Declaration( - true, - numArgs >= 1, - numArgs >= 2, - append - ); - } else if (type === DYN_THUNK) { - var data = dyn.data; - return new Declaration( - data.thisDep, - data.contextDep, - data.propDep, - append - ); - } else if (type === DYN_CONSTANT$1) { - return new Declaration( - false, - false, - false, - append - ); - } else if (type === DYN_ARRAY$1) { - var thisDep = false; - var contextDep = false; - var propDep = false; - for (var i = 0; i < dyn.data.length; ++i) { - var subDyn = dyn.data[i]; - if (subDyn.type === DYN_PROP$1) { - propDep = true; - } else if (subDyn.type === DYN_CONTEXT$1) { - contextDep = true; - } else if (subDyn.type === DYN_STATE$1) { - thisDep = true; - } else if (subDyn.type === DYN_FUNC$1) { - thisDep = true; - var subArgs = subDyn.data; - if (subArgs >= 1) { - contextDep = true; - } - if (subArgs >= 2) { - propDep = true; - } - } else if (subDyn.type === DYN_THUNK) { - thisDep = thisDep || subDyn.data.thisDep; - contextDep = contextDep || subDyn.data.contextDep; - propDep = propDep || subDyn.data.propDep; - } - } - return new Declaration( - thisDep, - contextDep, - propDep, - append - ); - } else { - return new Declaration( - type === DYN_STATE$1, - type === DYN_CONTEXT$1, - type === DYN_PROP$1, - append - ); - } - } - var SCOPE_DECL = new Declaration(false, false, false, function() { - }); - function reglCore(gl, stringStore, extensions, limits, bufferState, elementState, textureState, framebufferState, uniformState, attributeState, shaderState, drawState, contextState, timer, cachedCode, config) { - var AttributeRecord2 = attributeState.Record; - var blendEquations = { - "add": 32774, - "subtract": 32778, - "reverse subtract": 32779 - }; - if (extensions.ext_blend_minmax) { - blendEquations.min = GL_MIN_EXT; - blendEquations.max = GL_MAX_EXT; - } - var extInstancing = extensions.angle_instanced_arrays; - var extDrawBuffers = extensions.webgl_draw_buffers; - var extVertexArrays = extensions.oes_vertex_array_object; - var currentState = { - dirty: true, - profile: config.profile - }; - var nextState = {}; - var GL_STATE_NAMES = []; - var GL_FLAGS = {}; - var GL_VARIABLES = {}; - function propName(name2) { - return name2.replace(".", "_"); - } - function stateFlag(sname, cap, init2) { - var name2 = propName(sname); - GL_STATE_NAMES.push(sname); - nextState[name2] = currentState[name2] = !!init2; - GL_FLAGS[name2] = cap; - } - function stateVariable(sname, func, init2) { - var name2 = propName(sname); - GL_STATE_NAMES.push(sname); - if (Array.isArray(init2)) { - currentState[name2] = init2.slice(); - nextState[name2] = init2.slice(); - } else { - currentState[name2] = nextState[name2] = init2; - } - GL_VARIABLES[name2] = func; - } - function hasVariableReference(exp) { - if (!isNaN(exp)) { - return false; - } - return true; - } - stateFlag(S_DITHER, GL_DITHER); - stateFlag(S_BLEND_ENABLE, GL_BLEND); - stateVariable(S_BLEND_COLOR, "blendColor", [0, 0, 0, 0]); - stateVariable( - S_BLEND_EQUATION, - "blendEquationSeparate", - [GL_FUNC_ADD, GL_FUNC_ADD] - ); - stateVariable( - S_BLEND_FUNC, - "blendFuncSeparate", - [GL_ONE, GL_ZERO, GL_ONE, GL_ZERO] - ); - stateFlag(S_DEPTH_ENABLE, GL_DEPTH_TEST, true); - stateVariable(S_DEPTH_FUNC, "depthFunc", GL_LESS); - stateVariable(S_DEPTH_RANGE, "depthRange", [0, 1]); - stateVariable(S_DEPTH_MASK, "depthMask", true); - stateVariable(S_COLOR_MASK, S_COLOR_MASK, [true, true, true, true]); - stateFlag(S_CULL_ENABLE, GL_CULL_FACE); - stateVariable(S_CULL_FACE, "cullFace", GL_BACK); - stateVariable(S_FRONT_FACE, S_FRONT_FACE, GL_CCW); - stateVariable(S_LINE_WIDTH, S_LINE_WIDTH, 1); - stateFlag(S_POLYGON_OFFSET_ENABLE, GL_POLYGON_OFFSET_FILL); - stateVariable(S_POLYGON_OFFSET_OFFSET, "polygonOffset", [0, 0]); - stateFlag(S_SAMPLE_ALPHA, GL_SAMPLE_ALPHA_TO_COVERAGE); - stateFlag(S_SAMPLE_ENABLE, GL_SAMPLE_COVERAGE); - stateVariable(S_SAMPLE_COVERAGE, "sampleCoverage", [1, false]); - stateFlag(S_STENCIL_ENABLE, GL_STENCIL_TEST); - stateVariable(S_STENCIL_MASK, "stencilMask", -1); - stateVariable(S_STENCIL_FUNC, "stencilFunc", [GL_ALWAYS, 0, -1]); - stateVariable( - S_STENCIL_OPFRONT, - "stencilOpSeparate", - [GL_FRONT, GL_KEEP, GL_KEEP, GL_KEEP] - ); - stateVariable( - S_STENCIL_OPBACK, - "stencilOpSeparate", - [GL_BACK, GL_KEEP, GL_KEEP, GL_KEEP] - ); - stateFlag(S_SCISSOR_ENABLE, GL_SCISSOR_TEST); - stateVariable( - S_SCISSOR_BOX, - "scissor", - [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] - ); - stateVariable( - S_VIEWPORT, - S_VIEWPORT, - [0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight] - ); - var sharedState = { - gl, - context: contextState, - strings: stringStore, - next: nextState, - current: currentState, - draw: drawState, - elements: elementState, - buffer: bufferState, - shader: shaderState, - attributes: attributeState.state, - vao: attributeState, - uniforms: uniformState, - framebuffer: framebufferState, - extensions, - timer, - isBufferArgs - }; - var sharedConstants = { - primTypes, - compareFuncs, - blendFuncs, - blendEquations, - stencilOps, - glTypes, - orientationType - }; - if (extDrawBuffers) { - sharedConstants.backBuffer = [GL_BACK]; - sharedConstants.drawBuffer = loop(limits.maxDrawbuffers, function(i) { - if (i === 0) { - return [0]; - } - return loop(i, function(j) { - return GL_COLOR_ATTACHMENT0$2 + j; - }); - }); - } - var drawCallCounter = 0; - function createREGLEnvironment() { - var env = createEnvironment({ cache: cachedCode }); - var link = env.link; - var global = env.global; - env.id = drawCallCounter++; - env.batchId = "0"; - var SHARED = link(sharedState); - var shared = env.shared = { - props: "a0" - }; - Object.keys(sharedState).forEach(function(prop) { - shared[prop] = global.def(SHARED, ".", prop); - }); - var nextVars = env.next = {}; - var currentVars = env.current = {}; - Object.keys(GL_VARIABLES).forEach(function(variable) { - if (Array.isArray(currentState[variable])) { - nextVars[variable] = global.def(shared.next, ".", variable); - currentVars[variable] = global.def(shared.current, ".", variable); - } - }); - var constants2 = env.constants = {}; - Object.keys(sharedConstants).forEach(function(name2) { - constants2[name2] = global.def(JSON.stringify(sharedConstants[name2])); - }); - env.invoke = function(block, x) { - switch (x.type) { - case DYN_FUNC$1: - var argList = [ - "this", - shared.context, - shared.props, - env.batchId - ]; - return block.def( - link(x.data), - ".call(", - argList.slice(0, Math.max(x.data.length + 1, 4)), - ")" - ); - case DYN_PROP$1: - return block.def(shared.props, x.data); - case DYN_CONTEXT$1: - return block.def(shared.context, x.data); - case DYN_STATE$1: - return block.def("this", x.data); - case DYN_THUNK: - x.data.append(env, block); - return x.data.ref; - case DYN_CONSTANT$1: - return x.data.toString(); - case DYN_ARRAY$1: - return x.data.map(function(y) { - return env.invoke(block, y); - }); - } - }; - env.attribCache = {}; - var scopeAttribs = {}; - env.scopeAttrib = function(name2) { - var id = stringStore.id(name2); - if (id in scopeAttribs) { - return scopeAttribs[id]; - } - var binding = attributeState.scope[id]; - if (!binding) { - binding = attributeState.scope[id] = new AttributeRecord2(); - } - var result = scopeAttribs[id] = link(binding); - return result; - }; - return env; - } - function parseProfile(options) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - var profileEnable; - if (S_PROFILE in staticOptions) { - var value2 = !!staticOptions[S_PROFILE]; - profileEnable = createStaticDecl(function(env, scope) { - return value2; - }); - profileEnable.enable = value2; - } else if (S_PROFILE in dynamicOptions) { - var dyn = dynamicOptions[S_PROFILE]; - profileEnable = createDynamicDecl(dyn, function(env, scope) { - return env.invoke(scope, dyn); - }); - } - return profileEnable; - } - function parseFramebuffer(options, env) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - if (S_FRAMEBUFFER in staticOptions) { - var framebuffer = staticOptions[S_FRAMEBUFFER]; - if (framebuffer) { - framebuffer = framebufferState.getFramebuffer(framebuffer); - return createStaticDecl(function(env2, block) { - var FRAMEBUFFER = env2.link(framebuffer); - var shared = env2.shared; - block.set( - shared.framebuffer, - ".next", - FRAMEBUFFER - ); - var CONTEXT = shared.context; - block.set( - CONTEXT, - "." + S_FRAMEBUFFER_WIDTH, - FRAMEBUFFER + ".width" - ); - block.set( - CONTEXT, - "." + S_FRAMEBUFFER_HEIGHT, - FRAMEBUFFER + ".height" - ); - return FRAMEBUFFER; - }); - } else { - return createStaticDecl(function(env2, scope) { - var shared = env2.shared; - scope.set( - shared.framebuffer, - ".next", - "null" - ); - var CONTEXT = shared.context; - scope.set( - CONTEXT, - "." + S_FRAMEBUFFER_WIDTH, - CONTEXT + "." + S_DRAWINGBUFFER_WIDTH - ); - scope.set( - CONTEXT, - "." + S_FRAMEBUFFER_HEIGHT, - CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT - ); - return "null"; - }); - } - } else if (S_FRAMEBUFFER in dynamicOptions) { - var dyn = dynamicOptions[S_FRAMEBUFFER]; - return createDynamicDecl(dyn, function(env2, scope) { - var FRAMEBUFFER_FUNC = env2.invoke(scope, dyn); - var shared = env2.shared; - var FRAMEBUFFER_STATE = shared.framebuffer; - var FRAMEBUFFER = scope.def( - FRAMEBUFFER_STATE, - ".getFramebuffer(", - FRAMEBUFFER_FUNC, - ")" - ); - scope.set( - FRAMEBUFFER_STATE, - ".next", - FRAMEBUFFER - ); - var CONTEXT = shared.context; - scope.set( - CONTEXT, - "." + S_FRAMEBUFFER_WIDTH, - FRAMEBUFFER + "?" + FRAMEBUFFER + ".width:" + CONTEXT + "." + S_DRAWINGBUFFER_WIDTH - ); - scope.set( - CONTEXT, - "." + S_FRAMEBUFFER_HEIGHT, - FRAMEBUFFER + "?" + FRAMEBUFFER + ".height:" + CONTEXT + "." + S_DRAWINGBUFFER_HEIGHT - ); - return FRAMEBUFFER; - }); - } else { - return null; - } - } - function parseViewportScissor(options, framebuffer, env) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - function parseBox(param) { - if (param in staticOptions) { - var box = staticOptions[param]; - var isStatic2 = true; - var x = box.x | 0; - var y = box.y | 0; - var w, h; - if ("width" in box) { - w = box.width | 0; - } else { - isStatic2 = false; - } - if ("height" in box) { - h = box.height | 0; - } else { - isStatic2 = false; - } - return new Declaration( - !isStatic2 && framebuffer && framebuffer.thisDep, - !isStatic2 && framebuffer && framebuffer.contextDep, - !isStatic2 && framebuffer && framebuffer.propDep, - function(env2, scope) { - var CONTEXT = env2.shared.context; - var BOX_W = w; - if (!("width" in box)) { - BOX_W = scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH, "-", x); - } - var BOX_H = h; - if (!("height" in box)) { - BOX_H = scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT, "-", y); - } - return [x, y, BOX_W, BOX_H]; - } - ); - } else if (param in dynamicOptions) { - var dynBox = dynamicOptions[param]; - var result = createDynamicDecl(dynBox, function(env2, scope) { - var BOX = env2.invoke(scope, dynBox); - var CONTEXT = env2.shared.context; - var BOX_X = scope.def(BOX, ".x|0"); - var BOX_Y = scope.def(BOX, ".y|0"); - var BOX_W = scope.def( - '"width" in ', - BOX, - "?", - BOX, - ".width|0:", - "(", - CONTEXT, - ".", - S_FRAMEBUFFER_WIDTH, - "-", - BOX_X, - ")" - ); - var BOX_H = scope.def( - '"height" in ', - BOX, - "?", - BOX, - ".height|0:", - "(", - CONTEXT, - ".", - S_FRAMEBUFFER_HEIGHT, - "-", - BOX_Y, - ")" - ); - return [BOX_X, BOX_Y, BOX_W, BOX_H]; - }); - if (framebuffer) { - result.thisDep = result.thisDep || framebuffer.thisDep; - result.contextDep = result.contextDep || framebuffer.contextDep; - result.propDep = result.propDep || framebuffer.propDep; - } - return result; - } else if (framebuffer) { - return new Declaration( - framebuffer.thisDep, - framebuffer.contextDep, - framebuffer.propDep, - function(env2, scope) { - var CONTEXT = env2.shared.context; - return [ - 0, - 0, - scope.def(CONTEXT, ".", S_FRAMEBUFFER_WIDTH), - scope.def(CONTEXT, ".", S_FRAMEBUFFER_HEIGHT) - ]; - } - ); - } else { - return null; - } - } - var viewport = parseBox(S_VIEWPORT); - if (viewport) { - var prevViewport = viewport; - viewport = new Declaration( - viewport.thisDep, - viewport.contextDep, - viewport.propDep, - function(env2, scope) { - var VIEWPORT = prevViewport.append(env2, scope); - var CONTEXT = env2.shared.context; - scope.set( - CONTEXT, - "." + S_VIEWPORT_WIDTH, - VIEWPORT[2] - ); - scope.set( - CONTEXT, - "." + S_VIEWPORT_HEIGHT, - VIEWPORT[3] - ); - return VIEWPORT; - } - ); - } - return { - viewport, - scissor_box: parseBox(S_SCISSOR_BOX) - }; - } - function parseAttribLocations(options, attributes2) { - var staticOptions = options.static; - var staticProgram = typeof staticOptions[S_FRAG] === "string" && typeof staticOptions[S_VERT] === "string"; - if (staticProgram) { - if (Object.keys(attributes2.dynamic).length > 0) { - return null; - } - var staticAttributes = attributes2.static; - var sAttributes = Object.keys(staticAttributes); - if (sAttributes.length > 0 && typeof staticAttributes[sAttributes[0]] === "number") { - var bindings = []; - for (var i = 0; i < sAttributes.length; ++i) { - bindings.push([staticAttributes[sAttributes[i]] | 0, sAttributes[i]]); - } - return bindings; - } - } - return null; - } - function parseProgram(options, env, attribLocations) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - function parseShader(name2) { - if (name2 in staticOptions) { - var id = stringStore.id(staticOptions[name2]); - var result = createStaticDecl(function() { - return id; - }); - result.id = id; - return result; - } else if (name2 in dynamicOptions) { - var dyn = dynamicOptions[name2]; - return createDynamicDecl(dyn, function(env2, scope) { - var str2 = env2.invoke(scope, dyn); - var id2 = scope.def(env2.shared.strings, ".id(", str2, ")"); - return id2; - }); - } - return null; - } - var frag = parseShader(S_FRAG); - var vert = parseShader(S_VERT); - var program = null; - var progVar; - if (isStatic(frag) && isStatic(vert)) { - program = shaderState.program(vert.id, frag.id, null, attribLocations); - progVar = createStaticDecl(function(env2, scope) { - return env2.link(program); - }); - } else { - progVar = new Declaration( - frag && frag.thisDep || vert && vert.thisDep, - frag && frag.contextDep || vert && vert.contextDep, - frag && frag.propDep || vert && vert.propDep, - function(env2, scope) { - var SHADER_STATE = env2.shared.shader; - var fragId; - if (frag) { - fragId = frag.append(env2, scope); - } else { - fragId = scope.def(SHADER_STATE, ".", S_FRAG); - } - var vertId; - if (vert) { - vertId = vert.append(env2, scope); - } else { - vertId = scope.def(SHADER_STATE, ".", S_VERT); - } - var progDef = SHADER_STATE + ".program(" + vertId + "," + fragId; - return scope.def(progDef + ")"); - } - ); - } - return { - frag, - vert, - progVar, - program - }; - } - function parseDraw(options, env) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - var staticDraw = {}; - var vaoActive = false; - function parseVAO() { - if (S_VAO in staticOptions) { - var vao2 = staticOptions[S_VAO]; - if (vao2 !== null && attributeState.getVAO(vao2) === null) { - vao2 = attributeState.createVAO(vao2); - } - vaoActive = true; - staticDraw.vao = vao2; - return createStaticDecl(function(env2) { - var vaoRef = attributeState.getVAO(vao2); - if (vaoRef) { - return env2.link(vaoRef); - } else { - return "null"; - } - }); - } else if (S_VAO in dynamicOptions) { - vaoActive = true; - var dyn = dynamicOptions[S_VAO]; - return createDynamicDecl(dyn, function(env2, scope) { - var vaoRef = env2.invoke(scope, dyn); - return scope.def(env2.shared.vao + ".getVAO(" + vaoRef + ")"); - }); - } - return null; - } - var vao = parseVAO(); - var elementsActive = false; - function parseElements() { - if (S_ELEMENTS in staticOptions) { - var elements2 = staticOptions[S_ELEMENTS]; - staticDraw.elements = elements2; - if (isBufferArgs(elements2)) { - var e = staticDraw.elements = elementState.create(elements2, true); - elements2 = elementState.getElements(e); - elementsActive = true; - } else if (elements2) { - elements2 = elementState.getElements(elements2); - elementsActive = true; - } - var result = createStaticDecl(function(env2, scope) { - if (elements2) { - var result2 = env2.link(elements2); - env2.ELEMENTS = result2; - return result2; - } - env2.ELEMENTS = null; - return null; - }); - result.value = elements2; - return result; - } else if (S_ELEMENTS in dynamicOptions) { - elementsActive = true; - var dyn = dynamicOptions[S_ELEMENTS]; - return createDynamicDecl(dyn, function(env2, scope) { - var shared = env2.shared; - var IS_BUFFER_ARGS = shared.isBufferArgs; - var ELEMENT_STATE = shared.elements; - var elementDefn = env2.invoke(scope, dyn); - var elements3 = scope.def("null"); - var elementStream = scope.def(IS_BUFFER_ARGS, "(", elementDefn, ")"); - var ifte = env2.cond(elementStream).then(elements3, "=", ELEMENT_STATE, ".createStream(", elementDefn, ");").else(elements3, "=", ELEMENT_STATE, ".getElements(", elementDefn, ");"); - scope.entry(ifte); - scope.exit( - env2.cond(elementStream).then(ELEMENT_STATE, ".destroyStream(", elements3, ");") - ); - env2.ELEMENTS = elements3; - return elements3; - }); - } else if (vaoActive) { - return new Declaration( - vao.thisDep, - vao.contextDep, - vao.propDep, - function(env2, scope) { - return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.elements + ".getElements(" + env2.shared.vao + ".currentVAO.elements):null"); - } - ); - } - return null; - } - var elements = parseElements(); - function parsePrimitive() { - if (S_PRIMITIVE in staticOptions) { - var primitive2 = staticOptions[S_PRIMITIVE]; - staticDraw.primitive = primitive2; - return createStaticDecl(function(env2, scope) { - return primTypes[primitive2]; - }); - } else if (S_PRIMITIVE in dynamicOptions) { - var dynPrimitive = dynamicOptions[S_PRIMITIVE]; - return createDynamicDecl(dynPrimitive, function(env2, scope) { - var PRIM_TYPES = env2.constants.primTypes; - var prim = env2.invoke(scope, dynPrimitive); - return scope.def(PRIM_TYPES, "[", prim, "]"); - }); - } else if (elementsActive) { - if (isStatic(elements)) { - if (elements.value) { - return createStaticDecl(function(env2, scope) { - return scope.def(env2.ELEMENTS, ".primType"); - }); - } else { - return createStaticDecl(function() { - return GL_TRIANGLES$1; - }); - } - } else { - return new Declaration( - elements.thisDep, - elements.contextDep, - elements.propDep, - function(env2, scope) { - var elements2 = env2.ELEMENTS; - return scope.def(elements2, "?", elements2, ".primType:", GL_TRIANGLES$1); - } - ); - } - } else if (vaoActive) { - return new Declaration( - vao.thisDep, - vao.contextDep, - vao.propDep, - function(env2, scope) { - return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.primitive:" + GL_TRIANGLES$1); - } - ); - } - return null; - } - function parseParam(param, isOffset) { - if (param in staticOptions) { - var value2 = staticOptions[param] | 0; - if (isOffset) { - staticDraw.offset = value2; - } else { - staticDraw.instances = value2; - } - return createStaticDecl(function(env2, scope) { - if (isOffset) { - env2.OFFSET = value2; - } - return value2; - }); - } else if (param in dynamicOptions) { - var dynValue = dynamicOptions[param]; - return createDynamicDecl(dynValue, function(env2, scope) { - var result = env2.invoke(scope, dynValue); - if (isOffset) { - env2.OFFSET = result; - } - return result; - }); - } else if (isOffset) { - if (elementsActive) { - return createStaticDecl(function(env2, scope) { - env2.OFFSET = 0; - return 0; - }); - } else if (vaoActive) { - return new Declaration( - vao.thisDep, - vao.contextDep, - vao.propDep, - function(env2, scope) { - return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.offset:0"); - } - ); - } - } else if (vaoActive) { - return new Declaration( - vao.thisDep, - vao.contextDep, - vao.propDep, - function(env2, scope) { - return scope.def(env2.shared.vao + ".currentVAO?" + env2.shared.vao + ".currentVAO.instances:-1"); - } - ); - } - return null; - } - var OFFSET = parseParam(S_OFFSET, true); - function parseVertCount() { - if (S_COUNT in staticOptions) { - var count3 = staticOptions[S_COUNT] | 0; - staticDraw.count = count3; - return createStaticDecl(function() { - return count3; - }); - } else if (S_COUNT in dynamicOptions) { - var dynCount = dynamicOptions[S_COUNT]; - return createDynamicDecl(dynCount, function(env2, scope) { - var result2 = env2.invoke(scope, dynCount); - return result2; - }); - } else if (elementsActive) { - if (isStatic(elements)) { - if (elements) { - if (OFFSET) { - return new Declaration( - OFFSET.thisDep, - OFFSET.contextDep, - OFFSET.propDep, - function(env2, scope) { - var result2 = scope.def( - env2.ELEMENTS, - ".vertCount-", - env2.OFFSET - ); - return result2; - } - ); - } else { - return createStaticDecl(function(env2, scope) { - return scope.def(env2.ELEMENTS, ".vertCount"); - }); - } - } else { - var result = createStaticDecl(function() { - return -1; - }); - return result; - } - } else { - var variable = new Declaration( - elements.thisDep || OFFSET.thisDep, - elements.contextDep || OFFSET.contextDep, - elements.propDep || OFFSET.propDep, - function(env2, scope) { - var elements2 = env2.ELEMENTS; - if (env2.OFFSET) { - return scope.def( - elements2, - "?", - elements2, - ".vertCount-", - env2.OFFSET, - ":-1" - ); - } - return scope.def(elements2, "?", elements2, ".vertCount:-1"); - } - ); - return variable; - } - } else if (vaoActive) { - var countVariable = new Declaration( - vao.thisDep, - vao.contextDep, - vao.propDep, - function(env2, scope) { - return scope.def(env2.shared.vao, ".currentVAO?", env2.shared.vao, ".currentVAO.count:-1"); - } - ); - return countVariable; - } - return null; - } - var primitive = parsePrimitive(); - var count2 = parseVertCount(); - var instances = parseParam(S_INSTANCES, false); - return { - elements, - primitive, - count: count2, - instances, - offset: OFFSET, - vao, - vaoActive, - elementsActive, - // static draw props - static: staticDraw - }; - } - function parseGLState(options, env) { - var staticOptions = options.static; - var dynamicOptions = options.dynamic; - var STATE = {}; - GL_STATE_NAMES.forEach(function(prop) { - var param = propName(prop); - function parseParam(parseStatic, parseDynamic) { - if (prop in staticOptions) { - var value2 = parseStatic(staticOptions[prop]); - STATE[param] = createStaticDecl(function() { - return value2; - }); - } else if (prop in dynamicOptions) { - var dyn = dynamicOptions[prop]; - STATE[param] = createDynamicDecl(dyn, function(env2, scope) { - return parseDynamic(env2, scope, env2.invoke(scope, dyn)); - }); - } - } - switch (prop) { - case S_CULL_ENABLE: - case S_BLEND_ENABLE: - case S_DITHER: - case S_STENCIL_ENABLE: - case S_DEPTH_ENABLE: - case S_SCISSOR_ENABLE: - case S_POLYGON_OFFSET_ENABLE: - case S_SAMPLE_ALPHA: - case S_SAMPLE_ENABLE: - case S_DEPTH_MASK: - return parseParam( - function(value2) { - return value2; - }, - function(env2, scope, value2) { - return value2; - } - ); - case S_DEPTH_FUNC: - return parseParam( - function(value2) { - return compareFuncs[value2]; - }, - function(env2, scope, value2) { - var COMPARE_FUNCS = env2.constants.compareFuncs; - return scope.def(COMPARE_FUNCS, "[", value2, "]"); - } - ); - case S_DEPTH_RANGE: - return parseParam( - function(value2) { - return value2; - }, - function(env2, scope, value2) { - var Z_NEAR = scope.def("+", value2, "[0]"); - var Z_FAR = scope.def("+", value2, "[1]"); - return [Z_NEAR, Z_FAR]; - } - ); - case S_BLEND_FUNC: - return parseParam( - function(value2) { - var srcRGB = "srcRGB" in value2 ? value2.srcRGB : value2.src; - var srcAlpha = "srcAlpha" in value2 ? value2.srcAlpha : value2.src; - var dstRGB = "dstRGB" in value2 ? value2.dstRGB : value2.dst; - var dstAlpha = "dstAlpha" in value2 ? value2.dstAlpha : value2.dst; - return [ - blendFuncs[srcRGB], - blendFuncs[dstRGB], - blendFuncs[srcAlpha], - blendFuncs[dstAlpha] - ]; - }, - function(env2, scope, value2) { - var BLEND_FUNCS = env2.constants.blendFuncs; - function read(prefix, suffix) { - var func = scope.def( - '"', - prefix, - suffix, - '" in ', - value2, - "?", - value2, - ".", - prefix, - suffix, - ":", - value2, - ".", - prefix - ); - return func; - } - var srcRGB = read("src", "RGB"); - var dstRGB = read("dst", "RGB"); - var SRC_RGB = scope.def(BLEND_FUNCS, "[", srcRGB, "]"); - var SRC_ALPHA = scope.def(BLEND_FUNCS, "[", read("src", "Alpha"), "]"); - var DST_RGB = scope.def(BLEND_FUNCS, "[", dstRGB, "]"); - var DST_ALPHA = scope.def(BLEND_FUNCS, "[", read("dst", "Alpha"), "]"); - return [SRC_RGB, DST_RGB, SRC_ALPHA, DST_ALPHA]; - } - ); - case S_BLEND_EQUATION: - return parseParam( - function(value2) { - if (typeof value2 === "string") { - return [ - blendEquations[value2], - blendEquations[value2] - ]; - } else if (typeof value2 === "object") { - return [ - blendEquations[value2.rgb], - blendEquations[value2.alpha] - ]; - } else ; - }, - function(env2, scope, value2) { - var BLEND_EQUATIONS = env2.constants.blendEquations; - var RGB = scope.def(); - var ALPHA = scope.def(); - var ifte = env2.cond("typeof ", value2, '==="string"'); - ifte.then( - RGB, - "=", - ALPHA, - "=", - BLEND_EQUATIONS, - "[", - value2, - "];" - ); - ifte.else( - RGB, - "=", - BLEND_EQUATIONS, - "[", - value2, - ".rgb];", - ALPHA, - "=", - BLEND_EQUATIONS, - "[", - value2, - ".alpha];" - ); - scope(ifte); - return [RGB, ALPHA]; - } - ); - case S_BLEND_COLOR: - return parseParam( - function(value2) { - return loop(4, function(i) { - return +value2[i]; - }); - }, - function(env2, scope, value2) { - return loop(4, function(i) { - return scope.def("+", value2, "[", i, "]"); - }); - } - ); - case S_STENCIL_MASK: - return parseParam( - function(value2) { - return value2 | 0; - }, - function(env2, scope, value2) { - return scope.def(value2, "|0"); - } - ); - case S_STENCIL_FUNC: - return parseParam( - function(value2) { - var cmp = value2.cmp || "keep"; - var ref2 = value2.ref || 0; - var mask = "mask" in value2 ? value2.mask : -1; - return [ - compareFuncs[cmp], - ref2, - mask - ]; - }, - function(env2, scope, value2) { - var COMPARE_FUNCS = env2.constants.compareFuncs; - var cmp = scope.def( - '"cmp" in ', - value2, - "?", - COMPARE_FUNCS, - "[", - value2, - ".cmp]", - ":", - GL_KEEP - ); - var ref2 = scope.def(value2, ".ref|0"); - var mask = scope.def( - '"mask" in ', - value2, - "?", - value2, - ".mask|0:-1" - ); - return [cmp, ref2, mask]; - } - ); - case S_STENCIL_OPFRONT: - case S_STENCIL_OPBACK: - return parseParam( - function(value2) { - var fail = value2.fail || "keep"; - var zfail = value2.zfail || "keep"; - var zpass = value2.zpass || "keep"; - return [ - prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT, - stencilOps[fail], - stencilOps[zfail], - stencilOps[zpass] - ]; - }, - function(env2, scope, value2) { - var STENCIL_OPS = env2.constants.stencilOps; - function read(name2) { - return scope.def( - '"', - name2, - '" in ', - value2, - "?", - STENCIL_OPS, - "[", - value2, - ".", - name2, - "]:", - GL_KEEP - ); - } - return [ - prop === S_STENCIL_OPBACK ? GL_BACK : GL_FRONT, - read("fail"), - read("zfail"), - read("zpass") - ]; - } - ); - case S_POLYGON_OFFSET_OFFSET: - return parseParam( - function(value2) { - var factor = value2.factor | 0; - var units = value2.units | 0; - return [factor, units]; - }, - function(env2, scope, value2) { - var FACTOR = scope.def(value2, ".factor|0"); - var UNITS = scope.def(value2, ".units|0"); - return [FACTOR, UNITS]; - } - ); - case S_CULL_FACE: - return parseParam( - function(value2) { - var face = 0; - if (value2 === "front") { - face = GL_FRONT; - } else if (value2 === "back") { - face = GL_BACK; - } - return face; - }, - function(env2, scope, value2) { - return scope.def(value2, '==="front"?', GL_FRONT, ":", GL_BACK); - } - ); - case S_LINE_WIDTH: - return parseParam( - function(value2) { - return value2; - }, - function(env2, scope, value2) { - return value2; - } - ); - case S_FRONT_FACE: - return parseParam( - function(value2) { - return orientationType[value2]; - }, - function(env2, scope, value2) { - return scope.def(value2 + '==="cw"?' + GL_CW + ":" + GL_CCW); - } - ); - case S_COLOR_MASK: - return parseParam( - function(value2) { - return value2.map(function(v) { - return !!v; - }); - }, - function(env2, scope, value2) { - return loop(4, function(i) { - return "!!" + value2 + "[" + i + "]"; - }); - } - ); - case S_SAMPLE_COVERAGE: - return parseParam( - function(value2) { - var sampleValue = "value" in value2 ? value2.value : 1; - var sampleInvert = !!value2.invert; - return [sampleValue, sampleInvert]; - }, - function(env2, scope, value2) { - var VALUE2 = scope.def( - '"value" in ', - value2, - "?+", - value2, - ".value:1" - ); - var INVERT = scope.def("!!", value2, ".invert"); - return [VALUE2, INVERT]; - } - ); - } - }); - return STATE; - } - function parseUniforms(uniforms, env) { - var staticUniforms = uniforms.static; - var dynamicUniforms = uniforms.dynamic; - var UNIFORMS = {}; - Object.keys(staticUniforms).forEach(function(name2) { - var value2 = staticUniforms[name2]; - var result; - if (typeof value2 === "number" || typeof value2 === "boolean") { - result = createStaticDecl(function() { - return value2; - }); - } else if (typeof value2 === "function") { - var reglType = value2._reglType; - if (reglType === "texture2d" || reglType === "textureCube") { - result = createStaticDecl(function(env2) { - return env2.link(value2); - }); - } else if (reglType === "framebuffer" || reglType === "framebufferCube") { - result = createStaticDecl(function(env2) { - return env2.link(value2.color[0]); - }); - } else ; - } else if (isArrayLike(value2)) { - result = createStaticDecl(function(env2) { - var ITEM = env2.global.def( - "[", - loop(value2.length, function(i) { - return value2[i]; - }), - "]" - ); - return ITEM; - }); - } else ; - result.value = value2; - UNIFORMS[name2] = result; - }); - Object.keys(dynamicUniforms).forEach(function(key) { - var dyn = dynamicUniforms[key]; - UNIFORMS[key] = createDynamicDecl(dyn, function(env2, scope) { - return env2.invoke(scope, dyn); - }); - }); - return UNIFORMS; - } - function parseAttributes(attributes2, env) { - var staticAttributes = attributes2.static; - var dynamicAttributes = attributes2.dynamic; - var attributeDefs = {}; - Object.keys(staticAttributes).forEach(function(attribute) { - var value2 = staticAttributes[attribute]; - var id = stringStore.id(attribute); - var record = new AttributeRecord2(); - if (isBufferArgs(value2)) { - record.state = ATTRIB_STATE_POINTER; - record.buffer = bufferState.getBuffer( - bufferState.create(value2, GL_ARRAY_BUFFER$2, false, true) - ); - record.type = 0; - } else { - var buffer2 = bufferState.getBuffer(value2); - if (buffer2) { - record.state = ATTRIB_STATE_POINTER; - record.buffer = buffer2; - record.type = 0; - } else { - if ("constant" in value2) { - var constant2 = value2.constant; - record.buffer = "null"; - record.state = ATTRIB_STATE_CONSTANT; - if (typeof constant2 === "number") { - record.x = constant2; - } else { - CUTE_COMPONENTS.forEach(function(c, i) { - if (i < constant2.length) { - record[c] = constant2[i]; - } - }); - } - } else { - if (isBufferArgs(value2.buffer)) { - buffer2 = bufferState.getBuffer( - bufferState.create(value2.buffer, GL_ARRAY_BUFFER$2, false, true) - ); - } else { - buffer2 = bufferState.getBuffer(value2.buffer); - } - var offset = value2.offset | 0; - var stride = value2.stride | 0; - var size = value2.size | 0; - var normalized = !!value2.normalized; - var type = 0; - if ("type" in value2) { - type = glTypes[value2.type]; - } - var divisor = value2.divisor | 0; - record.buffer = buffer2; - record.state = ATTRIB_STATE_POINTER; - record.size = size; - record.normalized = normalized; - record.type = type || buffer2.dtype; - record.offset = offset; - record.stride = stride; - record.divisor = divisor; - } - } - } - attributeDefs[attribute] = createStaticDecl(function(env2, scope) { - var cache2 = env2.attribCache; - if (id in cache2) { - return cache2[id]; - } - var result = { - isStream: false - }; - Object.keys(record).forEach(function(key) { - result[key] = record[key]; - }); - if (record.buffer) { - result.buffer = env2.link(record.buffer); - result.type = result.type || result.buffer + ".dtype"; - } - cache2[id] = result; - return result; - }); - }); - Object.keys(dynamicAttributes).forEach(function(attribute) { - var dyn = dynamicAttributes[attribute]; - function appendAttributeCode(env2, block) { - var VALUE2 = env2.invoke(block, dyn); - var shared = env2.shared; - var constants2 = env2.constants; - var IS_BUFFER_ARGS = shared.isBufferArgs; - var BUFFER_STATE = shared.buffer; - var result = { - isStream: block.def(false) - }; - var defaultRecord = new AttributeRecord2(); - defaultRecord.state = ATTRIB_STATE_POINTER; - Object.keys(defaultRecord).forEach(function(key) { - result[key] = block.def("" + defaultRecord[key]); - }); - var BUFFER2 = result.buffer; - var TYPE = result.type; - block( - "if(", - IS_BUFFER_ARGS, - "(", - VALUE2, - ")){", - result.isStream, - "=true;", - BUFFER2, - "=", - BUFFER_STATE, - ".createStream(", - GL_ARRAY_BUFFER$2, - ",", - VALUE2, - ");", - TYPE, - "=", - BUFFER2, - ".dtype;", - "}else{", - BUFFER2, - "=", - BUFFER_STATE, - ".getBuffer(", - VALUE2, - ");", - "if(", - BUFFER2, - "){", - TYPE, - "=", - BUFFER2, - ".dtype;", - '}else if("constant" in ', - VALUE2, - "){", - result.state, - "=", - ATTRIB_STATE_CONSTANT, - ";", - "if(typeof " + VALUE2 + '.constant === "number"){', - result[CUTE_COMPONENTS[0]], - "=", - VALUE2, - ".constant;", - CUTE_COMPONENTS.slice(1).map(function(n) { - return result[n]; - }).join("="), - "=0;", - "}else{", - CUTE_COMPONENTS.map(function(name2, i) { - return result[name2] + "=" + VALUE2 + ".constant.length>" + i + "?" + VALUE2 + ".constant[" + i + "]:0;"; - }).join(""), - "}}else{", - "if(", - IS_BUFFER_ARGS, - "(", - VALUE2, - ".buffer)){", - BUFFER2, - "=", - BUFFER_STATE, - ".createStream(", - GL_ARRAY_BUFFER$2, - ",", - VALUE2, - ".buffer);", - "}else{", - BUFFER2, - "=", - BUFFER_STATE, - ".getBuffer(", - VALUE2, - ".buffer);", - "}", - TYPE, - '="type" in ', - VALUE2, - "?", - constants2.glTypes, - "[", - VALUE2, - ".type]:", - BUFFER2, - ".dtype;", - result.normalized, - "=!!", - VALUE2, - ".normalized;" - ); - function emitReadRecord(name2) { - block(result[name2], "=", VALUE2, ".", name2, "|0;"); - } - emitReadRecord("size"); - emitReadRecord("offset"); - emitReadRecord("stride"); - emitReadRecord("divisor"); - block("}}"); - block.exit( - "if(", - result.isStream, - "){", - BUFFER_STATE, - ".destroyStream(", - BUFFER2, - ");", - "}" - ); - return result; - } - attributeDefs[attribute] = createDynamicDecl(dyn, appendAttributeCode); - }); - return attributeDefs; - } - function parseContext(context2) { - var staticContext = context2.static; - var dynamicContext = context2.dynamic; - var result = {}; - Object.keys(staticContext).forEach(function(name2) { - var value2 = staticContext[name2]; - result[name2] = createStaticDecl(function(env, scope) { - if (typeof value2 === "number" || typeof value2 === "boolean") { - return "" + value2; - } else { - return env.link(value2); - } - }); - }); - Object.keys(dynamicContext).forEach(function(name2) { - var dyn = dynamicContext[name2]; - result[name2] = createDynamicDecl(dyn, function(env, scope) { - return env.invoke(scope, dyn); - }); - }); - return result; - } - function parseArguments(options, attributes2, uniforms, context2, env) { - options.static; - options.dynamic; - var attribLocations = parseAttribLocations(options, attributes2); - var framebuffer = parseFramebuffer(options); - var viewportAndScissor = parseViewportScissor(options, framebuffer); - var draw8 = parseDraw(options); - var state = parseGLState(options); - var shader = parseProgram(options, env, attribLocations); - function copyBox(name2) { - var defn = viewportAndScissor[name2]; - if (defn) { - state[name2] = defn; - } - } - copyBox(S_VIEWPORT); - copyBox(propName(S_SCISSOR_BOX)); - var dirty = Object.keys(state).length > 0; - var result = { - framebuffer, - draw: draw8, - shader, - state, - dirty, - scopeVAO: null, - drawVAO: null, - useVAO: false, - attributes: {} - }; - result.profile = parseProfile(options); - result.uniforms = parseUniforms(uniforms); - result.drawVAO = result.scopeVAO = draw8.vao; - if (!result.drawVAO && shader.program && !attribLocations && extensions.angle_instanced_arrays && draw8.static.elements) { - var useVAO = true; - var staticBindings = shader.program.attributes.map(function(attr) { - var binding = attributes2.static[attr]; - useVAO = useVAO && !!binding; - return binding; - }); - if (useVAO && staticBindings.length > 0) { - var vao = attributeState.getVAO(attributeState.createVAO({ - attributes: staticBindings, - elements: draw8.static.elements - })); - result.drawVAO = new Declaration(null, null, null, function(env2, scope) { - return env2.link(vao); - }); - result.useVAO = true; - } - } - if (attribLocations) { - result.useVAO = true; - } else { - result.attributes = parseAttributes(attributes2); - } - result.context = parseContext(context2); - return result; - } - function emitContext(env, scope, context2) { - var shared = env.shared; - var CONTEXT = shared.context; - var contextEnter = env.scope(); - Object.keys(context2).forEach(function(name2) { - scope.save(CONTEXT, "." + name2); - var defn = context2[name2]; - var value2 = defn.append(env, scope); - if (Array.isArray(value2)) { - contextEnter(CONTEXT, ".", name2, "=[", value2.join(), "];"); - } else { - contextEnter(CONTEXT, ".", name2, "=", value2, ";"); - } - }); - scope(contextEnter); - } - function emitPollFramebuffer(env, scope, framebuffer, skipCheck) { - var shared = env.shared; - var GL = shared.gl; - var FRAMEBUFFER_STATE = shared.framebuffer; - var EXT_DRAW_BUFFERS; - if (extDrawBuffers) { - EXT_DRAW_BUFFERS = scope.def(shared.extensions, ".webgl_draw_buffers"); - } - var constants2 = env.constants; - var DRAW_BUFFERS = constants2.drawBuffer; - var BACK_BUFFER = constants2.backBuffer; - var NEXT; - if (framebuffer) { - NEXT = framebuffer.append(env, scope); - } else { - NEXT = scope.def(FRAMEBUFFER_STATE, ".next"); - } - if (!skipCheck) { - scope("if(", NEXT, "!==", FRAMEBUFFER_STATE, ".cur){"); - } - scope( - "if(", - NEXT, - "){", - GL, - ".bindFramebuffer(", - GL_FRAMEBUFFER$2, - ",", - NEXT, - ".framebuffer);" - ); - if (extDrawBuffers) { - scope( - EXT_DRAW_BUFFERS, - ".drawBuffersWEBGL(", - DRAW_BUFFERS, - "[", - NEXT, - ".colorAttachments.length]);" - ); - } - scope( - "}else{", - GL, - ".bindFramebuffer(", - GL_FRAMEBUFFER$2, - ",null);" - ); - if (extDrawBuffers) { - scope(EXT_DRAW_BUFFERS, ".drawBuffersWEBGL(", BACK_BUFFER, ");"); - } - scope( - "}", - FRAMEBUFFER_STATE, - ".cur=", - NEXT, - ";" - ); - if (!skipCheck) { - scope("}"); - } - } - function emitPollState(env, scope, args) { - var shared = env.shared; - var GL = shared.gl; - var CURRENT_VARS = env.current; - var NEXT_VARS = env.next; - var CURRENT_STATE = shared.current; - var NEXT_STATE = shared.next; - var block = env.cond(CURRENT_STATE, ".dirty"); - GL_STATE_NAMES.forEach(function(prop) { - var param = propName(prop); - if (param in args.state) { - return; - } - var NEXT, CURRENT; - if (param in NEXT_VARS) { - NEXT = NEXT_VARS[param]; - CURRENT = CURRENT_VARS[param]; - var parts = loop(currentState[param].length, function(i) { - return block.def(NEXT, "[", i, "]"); - }); - block(env.cond(parts.map(function(p, i) { - return p + "!==" + CURRENT + "[" + i + "]"; - }).join("||")).then( - GL, - ".", - GL_VARIABLES[param], - "(", - parts, - ");", - parts.map(function(p, i) { - return CURRENT + "[" + i + "]=" + p; - }).join(";"), - ";" - )); - } else { - NEXT = block.def(NEXT_STATE, ".", param); - var ifte = env.cond(NEXT, "!==", CURRENT_STATE, ".", param); - block(ifte); - if (param in GL_FLAGS) { - ifte( - env.cond(NEXT).then(GL, ".enable(", GL_FLAGS[param], ");").else(GL, ".disable(", GL_FLAGS[param], ");"), - CURRENT_STATE, - ".", - param, - "=", - NEXT, - ";" - ); - } else { - ifte( - GL, - ".", - GL_VARIABLES[param], - "(", - NEXT, - ");", - CURRENT_STATE, - ".", - param, - "=", - NEXT, - ";" - ); - } - } - }); - if (Object.keys(args.state).length === 0) { - block(CURRENT_STATE, ".dirty=false;"); - } - scope(block); - } - function emitSetOptions(env, scope, options, filter2) { - var shared = env.shared; - var CURRENT_VARS = env.current; - var CURRENT_STATE = shared.current; - var GL = shared.gl; - var VALUE2; - sortState(Object.keys(options)).forEach(function(param) { - var defn = options[param]; - if (filter2 && !filter2(defn)) { - return; - } - var variable = defn.append(env, scope); - if (GL_FLAGS[param]) { - var flag = GL_FLAGS[param]; - if (isStatic(defn)) { - VALUE2 = env.link(variable, { stable: true }); - scope(env.cond(VALUE2).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");")); - scope(CURRENT_STATE, ".", param, "=", VALUE2, ";"); - } else { - scope(env.cond(variable).then(GL, ".enable(", flag, ");").else(GL, ".disable(", flag, ");")); - scope(CURRENT_STATE, ".", param, "=", variable, ";"); - } - } else if (isArrayLike(variable)) { - var CURRENT = CURRENT_VARS[param]; - scope( - GL, - ".", - GL_VARIABLES[param], - "(", - variable, - ");", - variable.map(function(v, i) { - return CURRENT + "[" + i + "]=" + v; - }).join(";"), - ";" - ); - } else { - if (isStatic(defn)) { - VALUE2 = env.link(variable, { stable: true }); - scope( - GL, - ".", - GL_VARIABLES[param], - "(", - VALUE2, - ");", - CURRENT_STATE, - ".", - param, - "=", - VALUE2, - ";" - ); - } else { - scope( - GL, - ".", - GL_VARIABLES[param], - "(", - variable, - ");", - CURRENT_STATE, - ".", - param, - "=", - variable, - ";" - ); - } - } - }); - } - function injectExtensions(env, scope) { - if (extInstancing) { - env.instancing = scope.def( - env.shared.extensions, - ".angle_instanced_arrays" - ); - } - } - function emitProfile(env, scope, args, useScope, incrementCounter) { - var shared = env.shared; - var STATS = env.stats; - var CURRENT_STATE = shared.current; - var TIMER = shared.timer; - var profileArg = args.profile; - function perfCounter() { - if (typeof performance === "undefined") { - return "Date.now()"; - } else { - return "performance.now()"; - } - } - var CPU_START, QUERY_COUNTER; - function emitProfileStart(block) { - CPU_START = scope.def(); - block(CPU_START, "=", perfCounter(), ";"); - if (typeof incrementCounter === "string") { - block(STATS, ".count+=", incrementCounter, ";"); - } else { - block(STATS, ".count++;"); - } - if (timer) { - if (useScope) { - QUERY_COUNTER = scope.def(); - block(QUERY_COUNTER, "=", TIMER, ".getNumPendingQueries();"); - } else { - block(TIMER, ".beginQuery(", STATS, ");"); - } - } - } - function emitProfileEnd(block) { - block(STATS, ".cpuTime+=", perfCounter(), "-", CPU_START, ";"); - if (timer) { - if (useScope) { - block( - TIMER, - ".pushScopeStats(", - QUERY_COUNTER, - ",", - TIMER, - ".getNumPendingQueries(),", - STATS, - ");" - ); - } else { - block(TIMER, ".endQuery();"); - } - } - } - function scopeProfile(value2) { - var prev = scope.def(CURRENT_STATE, ".profile"); - scope(CURRENT_STATE, ".profile=", value2, ";"); - scope.exit(CURRENT_STATE, ".profile=", prev, ";"); - } - var USE_PROFILE; - if (profileArg) { - if (isStatic(profileArg)) { - if (profileArg.enable) { - emitProfileStart(scope); - emitProfileEnd(scope.exit); - scopeProfile("true"); - } else { - scopeProfile("false"); - } - return; - } - USE_PROFILE = profileArg.append(env, scope); - scopeProfile(USE_PROFILE); - } else { - USE_PROFILE = scope.def(CURRENT_STATE, ".profile"); - } - var start = env.block(); - emitProfileStart(start); - scope("if(", USE_PROFILE, "){", start, "}"); - var end = env.block(); - emitProfileEnd(end); - scope.exit("if(", USE_PROFILE, "){", end, "}"); - } - function emitAttributes(env, scope, args, attributes2, filter2) { - var shared = env.shared; - function typeLength(x) { - switch (x) { - case GL_FLOAT_VEC2: - case GL_INT_VEC2: - case GL_BOOL_VEC2: - return 2; - case GL_FLOAT_VEC3: - case GL_INT_VEC3: - case GL_BOOL_VEC3: - return 3; - case GL_FLOAT_VEC4: - case GL_INT_VEC4: - case GL_BOOL_VEC4: - return 4; - default: - return 1; - } - } - function emitBindAttribute(ATTRIBUTE, size, record) { - var GL = shared.gl; - var LOCATION = scope.def(ATTRIBUTE, ".location"); - var BINDING = scope.def(shared.attributes, "[", LOCATION, "]"); - var STATE = record.state; - var BUFFER2 = record.buffer; - var CONST_COMPONENTS = [ - record.x, - record.y, - record.z, - record.w - ]; - var COMMON_KEYS = [ - "buffer", - "normalized", - "offset", - "stride" - ]; - function emitBuffer() { - scope( - "if(!", - BINDING, - ".buffer){", - GL, - ".enableVertexAttribArray(", - LOCATION, - ");}" - ); - var TYPE = record.type; - var SIZE; - if (!record.size) { - SIZE = size; - } else { - SIZE = scope.def(record.size, "||", size); - } - scope( - "if(", - BINDING, - ".type!==", - TYPE, - "||", - BINDING, - ".size!==", - SIZE, - "||", - COMMON_KEYS.map(function(key) { - return BINDING + "." + key + "!==" + record[key]; - }).join("||"), - "){", - GL, - ".bindBuffer(", - GL_ARRAY_BUFFER$2, - ",", - BUFFER2, - ".buffer);", - GL, - ".vertexAttribPointer(", - [ - LOCATION, - SIZE, - TYPE, - record.normalized, - record.stride, - record.offset - ], - ");", - BINDING, - ".type=", - TYPE, - ";", - BINDING, - ".size=", - SIZE, - ";", - COMMON_KEYS.map(function(key) { - return BINDING + "." + key + "=" + record[key] + ";"; - }).join(""), - "}" - ); - if (extInstancing) { - var DIVISOR = record.divisor; - scope( - "if(", - BINDING, - ".divisor!==", - DIVISOR, - "){", - env.instancing, - ".vertexAttribDivisorANGLE(", - [LOCATION, DIVISOR], - ");", - BINDING, - ".divisor=", - DIVISOR, - ";}" - ); - } - } - function emitConstant() { - scope( - "if(", - BINDING, - ".buffer){", - GL, - ".disableVertexAttribArray(", - LOCATION, - ");", - BINDING, - ".buffer=null;", - "}if(", - CUTE_COMPONENTS.map(function(c, i) { - return BINDING + "." + c + "!==" + CONST_COMPONENTS[i]; - }).join("||"), - "){", - GL, - ".vertexAttrib4f(", - LOCATION, - ",", - CONST_COMPONENTS, - ");", - CUTE_COMPONENTS.map(function(c, i) { - return BINDING + "." + c + "=" + CONST_COMPONENTS[i] + ";"; - }).join(""), - "}" - ); - } - if (STATE === ATTRIB_STATE_POINTER) { - emitBuffer(); - } else if (STATE === ATTRIB_STATE_CONSTANT) { - emitConstant(); - } else { - scope("if(", STATE, "===", ATTRIB_STATE_POINTER, "){"); - emitBuffer(); - scope("}else{"); - emitConstant(); - scope("}"); - } - } - attributes2.forEach(function(attribute) { - var name2 = attribute.name; - var arg = args.attributes[name2]; - var record; - if (arg) { - if (!filter2(arg)) { - return; - } - record = arg.append(env, scope); - } else { - if (!filter2(SCOPE_DECL)) { - return; - } - var scopeAttrib = env.scopeAttrib(name2); - record = {}; - Object.keys(new AttributeRecord2()).forEach(function(key) { - record[key] = scope.def(scopeAttrib, ".", key); - }); - } - emitBindAttribute( - env.link(attribute), - typeLength(attribute.info.type), - record - ); - }); - } - function emitUniforms(env, scope, args, uniforms, filter2, isBatchInnerLoop) { - var shared = env.shared; - var GL = shared.gl; - var infix; - for (var i = 0; i < uniforms.length; ++i) { - var uniform = uniforms[i]; - var name2 = uniform.name; - var type = uniform.info.type; - var arg = args.uniforms[name2]; - var UNIFORM = env.link(uniform); - var LOCATION = UNIFORM + ".location"; - var VALUE2; - if (arg) { - if (!filter2(arg)) { - continue; - } - if (isStatic(arg)) { - var value2 = arg.value; - if (type === GL_SAMPLER_2D || type === GL_SAMPLER_CUBE) { - var TEX_VALUE = env.link(value2._texture || value2.color[0]._texture); - scope(GL, ".uniform1i(", LOCATION, ",", TEX_VALUE + ".bind());"); - scope.exit(TEX_VALUE, ".unbind();"); - } else if (type === GL_FLOAT_MAT2 || type === GL_FLOAT_MAT3 || type === GL_FLOAT_MAT4) { - var MAT_VALUE = env.global.def("new Float32Array([" + Array.prototype.slice.call(value2) + "])"); - var dim = 2; - if (type === GL_FLOAT_MAT3) { - dim = 3; - } else if (type === GL_FLOAT_MAT4) { - dim = 4; - } - scope( - GL, - ".uniformMatrix", - dim, - "fv(", - LOCATION, - ",false,", - MAT_VALUE, - ");" - ); - } else { - switch (type) { - case GL_FLOAT$7: - infix = "1f"; - break; - case GL_FLOAT_VEC2: - infix = "2f"; - break; - case GL_FLOAT_VEC3: - infix = "3f"; - break; - case GL_FLOAT_VEC4: - infix = "4f"; - break; - case GL_BOOL: - infix = "1i"; - break; - case GL_INT$2: - infix = "1i"; - break; - case GL_BOOL_VEC2: - infix = "2i"; - break; - case GL_INT_VEC2: - infix = "2i"; - break; - case GL_BOOL_VEC3: - infix = "3i"; - break; - case GL_INT_VEC3: - infix = "3i"; - break; - case GL_BOOL_VEC4: - infix = "4i"; - break; - case GL_INT_VEC4: - infix = "4i"; - break; - } - scope( - GL, - ".uniform", - infix, - "(", - LOCATION, - ",", - isArrayLike(value2) ? Array.prototype.slice.call(value2) : value2, - ");" - ); - } - continue; - } else { - VALUE2 = arg.append(env, scope); - } - } else { - if (!filter2(SCOPE_DECL)) { - continue; - } - VALUE2 = scope.def(shared.uniforms, "[", stringStore.id(name2), "]"); - } - if (type === GL_SAMPLER_2D) { - scope( - "if(", - VALUE2, - "&&", - VALUE2, - '._reglType==="framebuffer"){', - VALUE2, - "=", - VALUE2, - ".color[0];", - "}" - ); - } else if (type === GL_SAMPLER_CUBE) { - scope( - "if(", - VALUE2, - "&&", - VALUE2, - '._reglType==="framebufferCube"){', - VALUE2, - "=", - VALUE2, - ".color[0];", - "}" - ); - } - var unroll = 1; - switch (type) { - case GL_SAMPLER_2D: - case GL_SAMPLER_CUBE: - var TEX = scope.def(VALUE2, "._texture"); - scope(GL, ".uniform1i(", LOCATION, ",", TEX, ".bind());"); - scope.exit(TEX, ".unbind();"); - continue; - case GL_INT$2: - case GL_BOOL: - infix = "1i"; - break; - case GL_INT_VEC2: - case GL_BOOL_VEC2: - infix = "2i"; - unroll = 2; - break; - case GL_INT_VEC3: - case GL_BOOL_VEC3: - infix = "3i"; - unroll = 3; - break; - case GL_INT_VEC4: - case GL_BOOL_VEC4: - infix = "4i"; - unroll = 4; - break; - case GL_FLOAT$7: - infix = "1f"; - break; - case GL_FLOAT_VEC2: - infix = "2f"; - unroll = 2; - break; - case GL_FLOAT_VEC3: - infix = "3f"; - unroll = 3; - break; - case GL_FLOAT_VEC4: - infix = "4f"; - unroll = 4; - break; - case GL_FLOAT_MAT2: - infix = "Matrix2fv"; - break; - case GL_FLOAT_MAT3: - infix = "Matrix3fv"; - break; - case GL_FLOAT_MAT4: - infix = "Matrix4fv"; - break; - } - if (infix.charAt(0) === "M") { - scope(GL, ".uniform", infix, "(", LOCATION, ","); - var matSize = Math.pow(type - GL_FLOAT_MAT2 + 2, 2); - var STORAGE = env.global.def("new Float32Array(", matSize, ")"); - if (Array.isArray(VALUE2)) { - scope( - "false,(", - loop(matSize, function(i2) { - return STORAGE + "[" + i2 + "]=" + VALUE2[i2]; - }), - ",", - STORAGE, - ")" - ); - } else { - scope( - "false,(Array.isArray(", - VALUE2, - ")||", - VALUE2, - " instanceof Float32Array)?", - VALUE2, - ":(", - loop(matSize, function(i2) { - return STORAGE + "[" + i2 + "]=" + VALUE2 + "[" + i2 + "]"; - }), - ",", - STORAGE, - ")" - ); - } - scope(");"); - } else if (unroll > 1) { - var prev = []; - var cur = []; - for (var j = 0; j < unroll; ++j) { - if (Array.isArray(VALUE2)) { - cur.push(VALUE2[j]); - } else { - cur.push(scope.def(VALUE2 + "[" + j + "]")); - } - if (isBatchInnerLoop) { - prev.push(scope.def()); - } - } - if (isBatchInnerLoop) { - scope("if(!", env.batchId, "||", prev.map(function(p, i2) { - return p + "!==" + cur[i2]; - }).join("||"), "){", prev.map(function(p, i2) { - return p + "=" + cur[i2] + ";"; - }).join("")); - } - scope(GL, ".uniform", infix, "(", LOCATION, ",", cur.join(","), ");"); - if (isBatchInnerLoop) { - scope("}"); - } - } else { - if (isBatchInnerLoop) { - var prevS = scope.def(); - scope( - "if(!", - env.batchId, - "||", - prevS, - "!==", - VALUE2, - "){", - prevS, - "=", - VALUE2, - ";" - ); - } - scope(GL, ".uniform", infix, "(", LOCATION, ",", VALUE2, ");"); - if (isBatchInnerLoop) { - scope("}"); - } - } - } - } - function emitDraw(env, outer, inner, args) { - var shared = env.shared; - var GL = shared.gl; - var DRAW_STATE = shared.draw; - var drawOptions = args.draw; - function emitElements() { - var defn = drawOptions.elements; - var ELEMENTS2; - var scope = outer; - if (defn) { - if (defn.contextDep && args.contextDynamic || defn.propDep) { - scope = inner; - } - ELEMENTS2 = defn.append(env, scope); - if (drawOptions.elementsActive) { - scope( - "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" - ); - } - } else { - ELEMENTS2 = scope.def(); - scope( - ELEMENTS2, - "=", - DRAW_STATE, - ".", - S_ELEMENTS, - ";", - "if(", - ELEMENTS2, - "){", - GL, - ".bindBuffer(", - GL_ELEMENT_ARRAY_BUFFER$2, - ",", - ELEMENTS2, - ".buffer.buffer);}", - "else if(", - shared.vao, - ".currentVAO){", - ELEMENTS2, - "=", - env.shared.elements + ".getElements(" + shared.vao, - ".currentVAO.elements);", - !extVertexArrays ? "if(" + ELEMENTS2 + ")" + GL + ".bindBuffer(" + GL_ELEMENT_ARRAY_BUFFER$2 + "," + ELEMENTS2 + ".buffer.buffer);" : "", - "}" - ); - } - return ELEMENTS2; - } - function emitCount() { - var defn = drawOptions.count; - var COUNT2; - var scope = outer; - if (defn) { - if (defn.contextDep && args.contextDynamic || defn.propDep) { - scope = inner; - } - COUNT2 = defn.append(env, scope); - } else { - COUNT2 = scope.def(DRAW_STATE, ".", S_COUNT); - } - return COUNT2; - } - var ELEMENTS = emitElements(); - function emitValue(name2) { - var defn = drawOptions[name2]; - if (defn) { - if (defn.contextDep && args.contextDynamic || defn.propDep) { - return defn.append(env, inner); - } else { - return defn.append(env, outer); - } - } else { - return outer.def(DRAW_STATE, ".", name2); - } - } - var PRIMITIVE = emitValue(S_PRIMITIVE); - var OFFSET = emitValue(S_OFFSET); - var COUNT = emitCount(); - if (typeof COUNT === "number") { - if (COUNT === 0) { - return; - } - } else { - inner("if(", COUNT, "){"); - inner.exit("}"); - } - var INSTANCES, EXT_INSTANCING; - if (extInstancing) { - INSTANCES = emitValue(S_INSTANCES); - EXT_INSTANCING = env.instancing; - } - var ELEMENT_TYPE = ELEMENTS + ".type"; - var elementsStatic = drawOptions.elements && isStatic(drawOptions.elements) && !drawOptions.vaoActive; - function emitInstancing() { - function drawElements() { - inner(EXT_INSTANCING, ".drawElementsInstancedANGLE(", [ - PRIMITIVE, - COUNT, - ELEMENT_TYPE, - OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)", - INSTANCES - ], ");"); - } - function drawArrays() { - inner( - EXT_INSTANCING, - ".drawArraysInstancedANGLE(", - [PRIMITIVE, OFFSET, COUNT, INSTANCES], - ");" - ); - } - if (ELEMENTS && ELEMENTS !== "null") { - if (!elementsStatic) { - inner("if(", ELEMENTS, "){"); - drawElements(); - inner("}else{"); - drawArrays(); - inner("}"); - } else { - drawElements(); - } - } else { - drawArrays(); - } - } - function emitRegular() { - function drawElements() { - inner(GL + ".drawElements(" + [ - PRIMITIVE, - COUNT, - ELEMENT_TYPE, - OFFSET + "<<((" + ELEMENT_TYPE + "-" + GL_UNSIGNED_BYTE$7 + ")>>1)" - ] + ");"); - } - function drawArrays() { - inner(GL + ".drawArrays(" + [PRIMITIVE, OFFSET, COUNT] + ");"); - } - if (ELEMENTS && ELEMENTS !== "null") { - if (!elementsStatic) { - inner("if(", ELEMENTS, "){"); - drawElements(); - inner("}else{"); - drawArrays(); - inner("}"); - } else { - drawElements(); - } - } else { - drawArrays(); - } - } - if (extInstancing && (typeof INSTANCES !== "number" || INSTANCES >= 0)) { - if (typeof INSTANCES === "string") { - inner("if(", INSTANCES, ">0){"); - emitInstancing(); - inner("}else if(", INSTANCES, "<0){"); - emitRegular(); - inner("}"); - } else { - emitInstancing(); - } - } else { - emitRegular(); - } - } - function createBody(emitBody, parentEnv, args, program, count2) { - var env = createREGLEnvironment(); - var scope = env.proc("body", count2); - if (extInstancing) { - env.instancing = scope.def( - env.shared.extensions, - ".angle_instanced_arrays" - ); - } - emitBody(env, scope, args, program); - return env.compile().body; - } - function emitDrawBody(env, draw8, args, program) { - injectExtensions(env, draw8); - if (args.useVAO) { - if (args.drawVAO) { - draw8(env.shared.vao, ".setVAO(", args.drawVAO.append(env, draw8), ");"); - } else { - draw8(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);"); - } - } else { - draw8(env.shared.vao, ".setVAO(null);"); - emitAttributes(env, draw8, args, program.attributes, function() { - return true; - }); - } - emitUniforms(env, draw8, args, program.uniforms, function() { - return true; - }, false); - emitDraw(env, draw8, draw8, args); - } - function emitDrawProc(env, args) { - var draw8 = env.proc("draw", 1); - injectExtensions(env, draw8); - emitContext(env, draw8, args.context); - emitPollFramebuffer(env, draw8, args.framebuffer); - emitPollState(env, draw8, args); - emitSetOptions(env, draw8, args.state); - emitProfile(env, draw8, args, false, true); - var program = args.shader.progVar.append(env, draw8); - draw8(env.shared.gl, ".useProgram(", program, ".program);"); - if (args.shader.program) { - emitDrawBody(env, draw8, args, args.shader.program); - } else { - draw8(env.shared.vao, ".setVAO(null);"); - var drawCache = env.global.def("{}"); - var PROG_ID = draw8.def(program, ".id"); - var CACHED_PROC = draw8.def(drawCache, "[", PROG_ID, "]"); - draw8( - env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0);").else( - CACHED_PROC, - "=", - drawCache, - "[", - PROG_ID, - "]=", - env.link(function(program2) { - return createBody(emitDrawBody, env, args, program2, 1); - }), - "(", - program, - ");", - CACHED_PROC, - ".call(this,a0);" - ) - ); - } - if (Object.keys(args.state).length > 0) { - draw8(env.shared.current, ".dirty=true;"); - } - if (env.shared.vao) { - draw8(env.shared.vao, ".setVAO(null);"); - } - } - function emitBatchDynamicShaderBody(env, scope, args, program) { - env.batchId = "a1"; - injectExtensions(env, scope); - function all() { - return true; - } - emitAttributes(env, scope, args, program.attributes, all); - emitUniforms(env, scope, args, program.uniforms, all, false); - emitDraw(env, scope, scope, args); - } - function emitBatchBody(env, scope, args, program) { - injectExtensions(env, scope); - var contextDynamic = args.contextDep; - var BATCH_ID = scope.def(); - var PROP_LIST = "a0"; - var NUM_PROPS = "a1"; - var PROPS = scope.def(); - env.shared.props = PROPS; - env.batchId = BATCH_ID; - var outer = env.scope(); - var inner = env.scope(); - scope( - outer.entry, - "for(", - BATCH_ID, - "=0;", - BATCH_ID, - "<", - NUM_PROPS, - ";++", - BATCH_ID, - "){", - PROPS, - "=", - PROP_LIST, - "[", - BATCH_ID, - "];", - inner, - "}", - outer.exit - ); - function isInnerDefn(defn) { - return defn.contextDep && contextDynamic || defn.propDep; - } - function isOuterDefn(defn) { - return !isInnerDefn(defn); - } - if (args.needsContext) { - emitContext(env, inner, args.context); - } - if (args.needsFramebuffer) { - emitPollFramebuffer(env, inner, args.framebuffer); - } - emitSetOptions(env, inner, args.state, isInnerDefn); - if (args.profile && isInnerDefn(args.profile)) { - emitProfile(env, inner, args, false, true); - } - if (!program) { - var progCache = env.global.def("{}"); - var PROGRAM = args.shader.progVar.append(env, inner); - var PROG_ID = inner.def(PROGRAM, ".id"); - var CACHED_PROC = inner.def(progCache, "[", PROG_ID, "]"); - inner( - env.shared.gl, - ".useProgram(", - PROGRAM, - ".program);", - "if(!", - CACHED_PROC, - "){", - CACHED_PROC, - "=", - progCache, - "[", - PROG_ID, - "]=", - env.link(function(program2) { - return createBody( - emitBatchDynamicShaderBody, - env, - args, - program2, - 2 - ); - }), - "(", - PROGRAM, - ");}", - CACHED_PROC, - ".call(this,a0[", - BATCH_ID, - "],", - BATCH_ID, - ");" - ); - } else { - if (args.useVAO) { - if (args.drawVAO) { - if (isInnerDefn(args.drawVAO)) { - inner(env.shared.vao, ".setVAO(", args.drawVAO.append(env, inner), ");"); - } else { - outer(env.shared.vao, ".setVAO(", args.drawVAO.append(env, outer), ");"); - } - } else { - outer(env.shared.vao, ".setVAO(", env.shared.vao, ".targetVAO);"); - } - } else { - outer(env.shared.vao, ".setVAO(null);"); - emitAttributes(env, outer, args, program.attributes, isOuterDefn); - emitAttributes(env, inner, args, program.attributes, isInnerDefn); - } - emitUniforms(env, outer, args, program.uniforms, isOuterDefn, false); - emitUniforms(env, inner, args, program.uniforms, isInnerDefn, true); - emitDraw(env, outer, inner, args); - } - } - function emitBatchProc(env, args) { - var batch = env.proc("batch", 2); - env.batchId = "0"; - injectExtensions(env, batch); - var contextDynamic = false; - var needsContext = true; - Object.keys(args.context).forEach(function(name2) { - contextDynamic = contextDynamic || args.context[name2].propDep; - }); - if (!contextDynamic) { - emitContext(env, batch, args.context); - needsContext = false; - } - var framebuffer = args.framebuffer; - var needsFramebuffer = false; - if (framebuffer) { - if (framebuffer.propDep) { - contextDynamic = needsFramebuffer = true; - } else if (framebuffer.contextDep && contextDynamic) { - needsFramebuffer = true; - } - if (!needsFramebuffer) { - emitPollFramebuffer(env, batch, framebuffer); - } - } else { - emitPollFramebuffer(env, batch, null); - } - if (args.state.viewport && args.state.viewport.propDep) { - contextDynamic = true; - } - function isInnerDefn(defn) { - return defn.contextDep && contextDynamic || defn.propDep; - } - emitPollState(env, batch, args); - emitSetOptions(env, batch, args.state, function(defn) { - return !isInnerDefn(defn); - }); - if (!args.profile || !isInnerDefn(args.profile)) { - emitProfile(env, batch, args, false, "a1"); - } - args.contextDep = contextDynamic; - args.needsContext = needsContext; - args.needsFramebuffer = needsFramebuffer; - var progDefn = args.shader.progVar; - if (progDefn.contextDep && contextDynamic || progDefn.propDep) { - emitBatchBody( - env, - batch, - args, - null - ); - } else { - var PROGRAM = progDefn.append(env, batch); - batch(env.shared.gl, ".useProgram(", PROGRAM, ".program);"); - if (args.shader.program) { - emitBatchBody( - env, - batch, - args, - args.shader.program - ); - } else { - batch(env.shared.vao, ".setVAO(null);"); - var batchCache = env.global.def("{}"); - var PROG_ID = batch.def(PROGRAM, ".id"); - var CACHED_PROC = batch.def(batchCache, "[", PROG_ID, "]"); - batch( - env.cond(CACHED_PROC).then(CACHED_PROC, ".call(this,a0,a1);").else( - CACHED_PROC, - "=", - batchCache, - "[", - PROG_ID, - "]=", - env.link(function(program) { - return createBody(emitBatchBody, env, args, program, 2); - }), - "(", - PROGRAM, - ");", - CACHED_PROC, - ".call(this,a0,a1);" - ) - ); - } - } - if (Object.keys(args.state).length > 0) { - batch(env.shared.current, ".dirty=true;"); - } - if (env.shared.vao) { - batch(env.shared.vao, ".setVAO(null);"); - } - } - function emitScopeProc(env, args) { - var scope = env.proc("scope", 3); - env.batchId = "a2"; - var shared = env.shared; - var CURRENT_STATE = shared.current; - emitContext(env, scope, args.context); - if (args.framebuffer) { - args.framebuffer.append(env, scope); - } - sortState(Object.keys(args.state)).forEach(function(name2) { - var defn = args.state[name2]; - var value2 = defn.append(env, scope); - if (isArrayLike(value2)) { - value2.forEach(function(v, i) { - if (hasVariableReference(v)) { - scope.set(env.next[name2], "[" + i + "]", v); - } else { - scope.set(env.next[name2], "[" + i + "]", env.link(v, { stable: true })); - } - }); - } else { - if (isStatic(defn)) { - scope.set(shared.next, "." + name2, env.link(value2, { stable: true })); - } else { - scope.set(shared.next, "." + name2, value2); - } - } - }); - emitProfile(env, scope, args, true, true); - [S_ELEMENTS, S_OFFSET, S_COUNT, S_INSTANCES, S_PRIMITIVE].forEach( - function(opt) { - var variable = args.draw[opt]; - if (!variable) { - return; - } - var VARIABLE2 = variable.append(env, scope); - if (hasVariableReference(VARIABLE2)) { - scope.set(shared.draw, "." + opt, VARIABLE2); - } else { - scope.set(shared.draw, "." + opt, env.link(VARIABLE2), { stable: true }); - } - } - ); - Object.keys(args.uniforms).forEach(function(opt) { - var value2 = args.uniforms[opt].append(env, scope); - if (Array.isArray(value2)) { - value2 = "[" + value2.map(function(v) { - if (hasVariableReference(v)) { - return v; - } else { - return env.link(v, { stable: true }); - } - }) + "]"; - } - scope.set( - shared.uniforms, - "[" + env.link(stringStore.id(opt), { stable: true }) + "]", - value2 - ); - }); - Object.keys(args.attributes).forEach(function(name2) { - var record = args.attributes[name2].append(env, scope); - var scopeAttrib = env.scopeAttrib(name2); - Object.keys(new AttributeRecord2()).forEach(function(prop) { - scope.set(scopeAttrib, "." + prop, record[prop]); - }); - }); - if (args.scopeVAO) { - var VARIABLE = args.scopeVAO.append(env, scope); - if (hasVariableReference(VARIABLE)) { - scope.set(shared.vao, ".targetVAO", VARIABLE); - } else { - scope.set(shared.vao, ".targetVAO", env.link(VARIABLE, { stable: true })); - } - } - function saveShader(name2) { - var shader = args.shader[name2]; - if (shader) { - var VARIABLE2 = shader.append(env, scope); - if (hasVariableReference(VARIABLE2)) { - scope.set(shared.shader, "." + name2, VARIABLE2); - } else { - scope.set(shared.shader, "." + name2, env.link(VARIABLE2, { stable: true })); - } - } - } - saveShader(S_VERT); - saveShader(S_FRAG); - if (Object.keys(args.state).length > 0) { - scope(CURRENT_STATE, ".dirty=true;"); - scope.exit(CURRENT_STATE, ".dirty=true;"); - } - scope("a1(", env.shared.context, ",a0,", env.batchId, ");"); - } - function isDynamicObject(object2) { - if (typeof object2 !== "object" || isArrayLike(object2)) { - return; - } - var props = Object.keys(object2); - for (var i = 0; i < props.length; ++i) { - if (dynamic.isDynamic(object2[props[i]])) { - return true; - } - } - return false; - } - function splatObject(env, options, name2) { - var object2 = options.static[name2]; - if (!object2 || !isDynamicObject(object2)) { - return; - } - var globals2 = env.global; - var keys = Object.keys(object2); - var thisDep = false; - var contextDep = false; - var propDep = false; - var objectRef = env.global.def("{}"); - keys.forEach(function(key) { - var value2 = object2[key]; - if (dynamic.isDynamic(value2)) { - if (typeof value2 === "function") { - value2 = object2[key] = dynamic.unbox(value2); - } - var deps = createDynamicDecl(value2, null); - thisDep = thisDep || deps.thisDep; - propDep = propDep || deps.propDep; - contextDep = contextDep || deps.contextDep; - } else { - globals2(objectRef, ".", key, "="); - switch (typeof value2) { - case "number": - globals2(value2); - break; - case "string": - globals2('"', value2, '"'); - break; - case "object": - if (Array.isArray(value2)) { - globals2("[", value2.join(), "]"); - } - break; - default: - globals2(env.link(value2)); - break; - } - globals2(";"); - } - }); - function appendBlock(env2, block) { - keys.forEach(function(key) { - var value2 = object2[key]; - if (!dynamic.isDynamic(value2)) { - return; - } - var ref2 = env2.invoke(block, value2); - block(objectRef, ".", key, "=", ref2, ";"); - }); - } - options.dynamic[name2] = new dynamic.DynamicVariable(DYN_THUNK, { - thisDep, - contextDep, - propDep, - ref: objectRef, - append: appendBlock - }); - delete options.static[name2]; - } - function compileCommand(options, attributes2, uniforms, context2, stats3) { - var env = createREGLEnvironment(); - env.stats = env.link(stats3); - Object.keys(attributes2.static).forEach(function(key) { - splatObject(env, attributes2, key); - }); - NESTED_OPTIONS.forEach(function(name2) { - splatObject(env, options, name2); - }); - var args = parseArguments(options, attributes2, uniforms, context2, env); - if (args.shader.program) { - args.shader.program.attributes.sort(function(a, b) { - return a.name < b.name ? -1 : 1; - }); - args.shader.program.uniforms.sort(function(a, b) { - return a.name < b.name ? -1 : 1; - }); - } - emitDrawProc(env, args); - emitScopeProc(env, args); - emitBatchProc(env, args); - return extend2(env.compile(), { - destroy: function() { - args.shader.program.destroy(); - } - }); - } - return { - next: nextState, - current: currentState, - procs: function() { - var env = createREGLEnvironment(); - var poll = env.proc("poll"); - var refresh = env.proc("refresh"); - var common = env.block(); - poll(common); - refresh(common); - var shared = env.shared; - var GL = shared.gl; - var NEXT_STATE = shared.next; - var CURRENT_STATE = shared.current; - common(CURRENT_STATE, ".dirty=false;"); - emitPollFramebuffer(env, poll); - emitPollFramebuffer(env, refresh, null, true); - var INSTANCING; - if (extInstancing) { - INSTANCING = env.link(extInstancing); - } - if (extensions.oes_vertex_array_object) { - refresh(env.link(extensions.oes_vertex_array_object), ".bindVertexArrayOES(null);"); - } - var BINDING = refresh.def(shared.attributes); - var TEMP_BINDING = refresh.def(0); - var ifte = env.cond(TEMP_BINDING, ".buffer"); - ifte.then( - GL, - ".enableVertexAttribArray(i);", - GL, - ".bindBuffer(", - GL_ARRAY_BUFFER$2, - ",", - TEMP_BINDING, - ".buffer.buffer);", - GL, - ".vertexAttribPointer(i,", - TEMP_BINDING, - ".size,", - TEMP_BINDING, - ".type,", - TEMP_BINDING, - ".normalized,", - TEMP_BINDING, - ".stride,", - TEMP_BINDING, - ".offset);" - ).else( - GL, - ".disableVertexAttribArray(i);", - GL, - ".vertexAttrib4f(i,", - TEMP_BINDING, - ".x,", - TEMP_BINDING, - ".y,", - TEMP_BINDING, - ".z,", - TEMP_BINDING, - ".w);", - TEMP_BINDING, - ".buffer=null;" - ); - var MAX_ATTRIBUTES = env.link(limits.maxAttributes, { stable: true }); - refresh( - "for(var i=0;i<", - MAX_ATTRIBUTES, - ";++i){", - TEMP_BINDING, - "=", - BINDING, - "[i];", - ifte, - "}" - ); - if (extInstancing) { - refresh( - "for(var i=0;i<", - MAX_ATTRIBUTES, - ";++i){", - INSTANCING, - ".vertexAttribDivisorANGLE(i,", - BINDING, - "[i].divisor);", - "}" - ); - } - refresh( - env.shared.vao, - ".currentVAO=null;", - env.shared.vao, - ".setVAO(", - env.shared.vao, - ".targetVAO);" - ); - Object.keys(GL_FLAGS).forEach(function(flag) { - var cap = GL_FLAGS[flag]; - var NEXT = common.def(NEXT_STATE, ".", flag); - var block = env.block(); - block( - "if(", - NEXT, - "){", - GL, - ".enable(", - cap, - ")}else{", - GL, - ".disable(", - cap, - ")}", - CURRENT_STATE, - ".", - flag, - "=", - NEXT, - ";" - ); - refresh(block); - poll( - "if(", - NEXT, - "!==", - CURRENT_STATE, - ".", - flag, - "){", - block, - "}" - ); - }); - Object.keys(GL_VARIABLES).forEach(function(name2) { - var func = GL_VARIABLES[name2]; - var init2 = currentState[name2]; - var NEXT, CURRENT; - var block = env.block(); - block(GL, ".", func, "("); - if (isArrayLike(init2)) { - var n = init2.length; - NEXT = env.global.def(NEXT_STATE, ".", name2); - CURRENT = env.global.def(CURRENT_STATE, ".", name2); - block( - loop(n, function(i) { - return NEXT + "[" + i + "]"; - }), - ");", - loop(n, function(i) { - return CURRENT + "[" + i + "]=" + NEXT + "[" + i + "];"; - }).join("") - ); - poll( - "if(", - loop(n, function(i) { - return NEXT + "[" + i + "]!==" + CURRENT + "[" + i + "]"; - }).join("||"), - "){", - block, - "}" - ); - } else { - NEXT = common.def(NEXT_STATE, ".", name2); - CURRENT = common.def(CURRENT_STATE, ".", name2); - block( - NEXT, - ");", - CURRENT_STATE, - ".", - name2, - "=", - NEXT, - ";" - ); - poll( - "if(", - NEXT, - "!==", - CURRENT, - "){", - block, - "}" - ); - } - refresh(block); - }); - return env.compile(); - }(), - compile: compileCommand - }; - } - function stats2() { - return { - vaoCount: 0, - bufferCount: 0, - elementsCount: 0, - framebufferCount: 0, - shaderCount: 0, - textureCount: 0, - cubeCount: 0, - renderbufferCount: 0, - maxTextureUnits: 0 - }; - } - var GL_QUERY_RESULT_EXT = 34918; - var GL_QUERY_RESULT_AVAILABLE_EXT = 34919; - var GL_TIME_ELAPSED_EXT = 35007; - var createTimer = function(gl, extensions) { - if (!extensions.ext_disjoint_timer_query) { - return null; - } - var queryPool = []; - function allocQuery() { - return queryPool.pop() || extensions.ext_disjoint_timer_query.createQueryEXT(); - } - function freeQuery(query) { - queryPool.push(query); - } - var pendingQueries = []; - function beginQuery(stats3) { - var query = allocQuery(); - extensions.ext_disjoint_timer_query.beginQueryEXT(GL_TIME_ELAPSED_EXT, query); - pendingQueries.push(query); - pushScopeStats(pendingQueries.length - 1, pendingQueries.length, stats3); - } - function endQuery() { - extensions.ext_disjoint_timer_query.endQueryEXT(GL_TIME_ELAPSED_EXT); - } - function PendingStats() { - this.startQueryIndex = -1; - this.endQueryIndex = -1; - this.sum = 0; - this.stats = null; - } - var pendingStatsPool = []; - function allocPendingStats() { - return pendingStatsPool.pop() || new PendingStats(); - } - function freePendingStats(pendingStats2) { - pendingStatsPool.push(pendingStats2); - } - var pendingStats = []; - function pushScopeStats(start, end, stats3) { - var ps = allocPendingStats(); - ps.startQueryIndex = start; - ps.endQueryIndex = end; - ps.sum = 0; - ps.stats = stats3; - pendingStats.push(ps); - } - var timeSum = []; - var queryPtr = []; - function update2() { - var ptr, i; - var n = pendingQueries.length; - if (n === 0) { - return; - } - queryPtr.length = Math.max(queryPtr.length, n + 1); - timeSum.length = Math.max(timeSum.length, n + 1); - timeSum[0] = 0; - queryPtr[0] = 0; - var queryTime = 0; - ptr = 0; - for (i = 0; i < pendingQueries.length; ++i) { - var query = pendingQueries[i]; - if (extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_AVAILABLE_EXT)) { - queryTime += extensions.ext_disjoint_timer_query.getQueryObjectEXT(query, GL_QUERY_RESULT_EXT); - freeQuery(query); - } else { - pendingQueries[ptr++] = query; - } - timeSum[i + 1] = queryTime; - queryPtr[i + 1] = ptr; - } - pendingQueries.length = ptr; - ptr = 0; - for (i = 0; i < pendingStats.length; ++i) { - var stats3 = pendingStats[i]; - var start = stats3.startQueryIndex; - var end = stats3.endQueryIndex; - stats3.sum += timeSum[end] - timeSum[start]; - var startPtr = queryPtr[start]; - var endPtr = queryPtr[end]; - if (endPtr === startPtr) { - stats3.stats.gpuTime += stats3.sum / 1e6; - freePendingStats(stats3); - } else { - stats3.startQueryIndex = startPtr; - stats3.endQueryIndex = endPtr; - pendingStats[ptr++] = stats3; - } - } - pendingStats.length = ptr; - } - return { - beginQuery, - endQuery, - pushScopeStats, - update: update2, - getNumPendingQueries: function() { - return pendingQueries.length; - }, - clear: function() { - queryPool.push.apply(queryPool, pendingQueries); - for (var i = 0; i < queryPool.length; i++) { - extensions.ext_disjoint_timer_query.deleteQueryEXT(queryPool[i]); - } - pendingQueries.length = 0; - queryPool.length = 0; - }, - restore: function() { - pendingQueries.length = 0; - queryPool.length = 0; - } - }; - }; - var GL_COLOR_BUFFER_BIT = 16384; - var GL_DEPTH_BUFFER_BIT = 256; - var GL_STENCIL_BUFFER_BIT = 1024; - var GL_ARRAY_BUFFER = 34962; - var CONTEXT_LOST_EVENT = "webglcontextlost"; - var CONTEXT_RESTORED_EVENT = "webglcontextrestored"; - var DYN_PROP = 1; - var DYN_CONTEXT = 2; - var DYN_STATE = 3; - function find(haystack, needle) { - for (var i = 0; i < haystack.length; ++i) { - if (haystack[i] === needle) { - return i; - } - } - return -1; - } - function wrapREGL(args) { - var config = parseArgs(args); - if (!config) { - return null; - } - var gl = config.gl; - var glAttributes = gl.getContextAttributes(); - gl.isContextLost(); - var extensionState = createExtensionCache(gl, config); - if (!extensionState) { - return null; - } - var stringStore = createStringStore(); - var stats$$1 = stats2(); - var cachedCode = config.cachedCode || {}; - var extensions = extensionState.extensions; - var timer = createTimer(gl, extensions); - var START_TIME = clock(); - var WIDTH = gl.drawingBufferWidth; - var HEIGHT = gl.drawingBufferHeight; - var contextState = { - tick: 0, - time: 0, - viewportWidth: WIDTH, - viewportHeight: HEIGHT, - framebufferWidth: WIDTH, - framebufferHeight: HEIGHT, - drawingBufferWidth: WIDTH, - drawingBufferHeight: HEIGHT, - pixelRatio: config.pixelRatio - }; - var uniformState = {}; - var drawState = { - elements: null, - primitive: 4, - // GL_TRIANGLES - count: -1, - offset: 0, - instances: -1 - }; - var limits = wrapLimits(gl, extensions); - var bufferState = wrapBufferState( - gl, - stats$$1, - config, - destroyBuffer - ); - var elementState = wrapElementsState(gl, extensions, bufferState, stats$$1); - var attributeState = wrapAttributeState( - gl, - extensions, - limits, - stats$$1, - bufferState, - elementState, - drawState - ); - function destroyBuffer(buffer2) { - return attributeState.destroyBuffer(buffer2); - } - var shaderState = wrapShaderState(gl, stringStore, stats$$1, config); - var textureState = createTextureSet( - gl, - extensions, - limits, - function() { - core2.procs.poll(); - }, - contextState, - stats$$1, - config - ); - var renderbufferState = wrapRenderbuffers(gl, extensions, limits, stats$$1, config); - var framebufferState = wrapFBOState( - gl, - extensions, - limits, - textureState, - renderbufferState, - stats$$1 - ); - var core2 = reglCore( - gl, - stringStore, - extensions, - limits, - bufferState, - elementState, - textureState, - framebufferState, - uniformState, - attributeState, - shaderState, - drawState, - contextState, - timer, - cachedCode, - config - ); - var readPixels = wrapReadPixels( - gl, - framebufferState, - core2.procs.poll, - contextState - ); - var nextState = core2.next; - var canvas2 = gl.canvas; - var rafCallbacks = []; - var lossCallbacks = []; - var restoreCallbacks = []; - var destroyCallbacks = [config.onDestroy]; - var activeRAF = null; - function handleRAF() { - if (rafCallbacks.length === 0) { - if (timer) { - timer.update(); - } - activeRAF = null; - return; - } - activeRAF = raf.next(handleRAF); - poll(); - for (var i = rafCallbacks.length - 1; i >= 0; --i) { - var cb = rafCallbacks[i]; - if (cb) { - cb(contextState, null, 0); - } - } - gl.flush(); - if (timer) { - timer.update(); - } - } - function startRAF() { - if (!activeRAF && rafCallbacks.length > 0) { - activeRAF = raf.next(handleRAF); - } - } - function stopRAF() { - if (activeRAF) { - raf.cancel(handleRAF); - activeRAF = null; - } - } - function handleContextLoss(event) { - event.preventDefault(); - stopRAF(); - lossCallbacks.forEach(function(cb) { - cb(); - }); - } - function handleContextRestored(event) { - gl.getError(); - extensionState.restore(); - shaderState.restore(); - bufferState.restore(); - textureState.restore(); - renderbufferState.restore(); - framebufferState.restore(); - attributeState.restore(); - if (timer) { - timer.restore(); - } - core2.procs.refresh(); - startRAF(); - restoreCallbacks.forEach(function(cb) { - cb(); - }); - } - if (canvas2) { - canvas2.addEventListener(CONTEXT_LOST_EVENT, handleContextLoss, false); - canvas2.addEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored, false); - } - function destroy2() { - rafCallbacks.length = 0; - stopRAF(); - if (canvas2) { - canvas2.removeEventListener(CONTEXT_LOST_EVENT, handleContextLoss); - canvas2.removeEventListener(CONTEXT_RESTORED_EVENT, handleContextRestored); - } - shaderState.clear(); - framebufferState.clear(); - renderbufferState.clear(); - attributeState.clear(); - textureState.clear(); - elementState.clear(); - bufferState.clear(); - if (timer) { - timer.clear(); - } - destroyCallbacks.forEach(function(cb) { - cb(); - }); - } - function compileProcedure(options) { - function flattenNestedOptions(options2) { - var result = extend2({}, options2); - delete result.uniforms; - delete result.attributes; - delete result.context; - delete result.vao; - if ("stencil" in result && result.stencil.op) { - result.stencil.opBack = result.stencil.opFront = result.stencil.op; - delete result.stencil.op; - } - function merge(name2) { - if (name2 in result) { - var child = result[name2]; - delete result[name2]; - Object.keys(child).forEach(function(prop) { - result[name2 + "." + prop] = child[prop]; - }); - } - } - merge("blend"); - merge("depth"); - merge("cull"); - merge("stencil"); - merge("polygonOffset"); - merge("scissor"); - merge("sample"); - if ("vao" in options2) { - result.vao = options2.vao; - } - return result; - } - function separateDynamic(object2, useArrays) { - var staticItems = {}; - var dynamicItems = {}; - Object.keys(object2).forEach(function(option) { - var value2 = object2[option]; - if (dynamic.isDynamic(value2)) { - dynamicItems[option] = dynamic.unbox(value2, option); - return; - } else if (useArrays && Array.isArray(value2)) { - for (var i = 0; i < value2.length; ++i) { - if (dynamic.isDynamic(value2[i])) { - dynamicItems[option] = dynamic.unbox(value2, option); - return; - } - } - } - staticItems[option] = value2; - }); - return { - dynamic: dynamicItems, - static: staticItems - }; - } - var context2 = separateDynamic(options.context || {}, true); - var uniforms = separateDynamic(options.uniforms || {}, true); - var attributes2 = separateDynamic(options.attributes || {}, false); - var opts = separateDynamic(flattenNestedOptions(options), false); - var stats$$12 = { - gpuTime: 0, - cpuTime: 0, - count: 0 - }; - var compiled = core2.compile(opts, attributes2, uniforms, context2, stats$$12); - var draw8 = compiled.draw; - var batch = compiled.batch; - var scope = compiled.scope; - var EMPTY_ARRAY = []; - function reserve(count2) { - while (EMPTY_ARRAY.length < count2) { - EMPTY_ARRAY.push(null); - } - return EMPTY_ARRAY; - } - function REGLCommand(args2, body) { - var i; - if (typeof args2 === "function") { - return scope.call(this, null, args2, 0); - } else if (typeof body === "function") { - if (typeof args2 === "number") { - for (i = 0; i < args2; ++i) { - scope.call(this, null, body, i); - } - } else if (Array.isArray(args2)) { - for (i = 0; i < args2.length; ++i) { - scope.call(this, args2[i], body, i); - } - } else { - return scope.call(this, args2, body, 0); - } - } else if (typeof args2 === "number") { - if (args2 > 0) { - return batch.call(this, reserve(args2 | 0), args2 | 0); - } - } else if (Array.isArray(args2)) { - if (args2.length) { - return batch.call(this, args2, args2.length); - } - } else { - return draw8.call(this, args2); - } - } - return extend2(REGLCommand, { - stats: stats$$12, - destroy: function() { - compiled.destroy(); - } - }); - } - var setFBO = framebufferState.setFBO = compileProcedure({ - framebuffer: dynamic.define.call(null, DYN_PROP, "framebuffer") - }); - function clearImpl(_2, options) { - var clearFlags = 0; - core2.procs.poll(); - var c = options.color; - if (c) { - gl.clearColor(+c[0] || 0, +c[1] || 0, +c[2] || 0, +c[3] || 0); - clearFlags |= GL_COLOR_BUFFER_BIT; - } - if ("depth" in options) { - gl.clearDepth(+options.depth); - clearFlags |= GL_DEPTH_BUFFER_BIT; - } - if ("stencil" in options) { - gl.clearStencil(options.stencil | 0); - clearFlags |= GL_STENCIL_BUFFER_BIT; - } - gl.clear(clearFlags); - } - function clear2(options) { - if ("framebuffer" in options) { - if (options.framebuffer && options.framebuffer_reglType === "framebufferCube") { - for (var i = 0; i < 6; ++i) { - setFBO(extend2({ - framebuffer: options.framebuffer.faces[i] - }, options), clearImpl); - } - } else { - setFBO(options, clearImpl); - } - } else { - clearImpl(null, options); - } - } - function frame(cb) { - rafCallbacks.push(cb); - function cancel() { - var i = find(rafCallbacks, cb); - function pendingCancel() { - var index2 = find(rafCallbacks, pendingCancel); - rafCallbacks[index2] = rafCallbacks[rafCallbacks.length - 1]; - rafCallbacks.length -= 1; - if (rafCallbacks.length <= 0) { - stopRAF(); - } - } - rafCallbacks[i] = pendingCancel; - } - startRAF(); - return { - cancel - }; - } - function pollViewport() { - var viewport = nextState.viewport; - var scissorBox = nextState.scissor_box; - viewport[0] = viewport[1] = scissorBox[0] = scissorBox[1] = 0; - contextState.viewportWidth = contextState.framebufferWidth = contextState.drawingBufferWidth = viewport[2] = scissorBox[2] = gl.drawingBufferWidth; - contextState.viewportHeight = contextState.framebufferHeight = contextState.drawingBufferHeight = viewport[3] = scissorBox[3] = gl.drawingBufferHeight; - } - function poll() { - contextState.tick += 1; - contextState.time = now(); - pollViewport(); - core2.procs.poll(); - } - function refresh() { - textureState.refresh(); - pollViewport(); - core2.procs.refresh(); - if (timer) { - timer.update(); - } - } - function now() { - return (clock() - START_TIME) / 1e3; - } - refresh(); - function addListener2(event, callback) { - var callbacks; - switch (event) { - case "frame": - return frame(callback); - case "lost": - callbacks = lossCallbacks; - break; - case "restore": - callbacks = restoreCallbacks; - break; - case "destroy": - callbacks = destroyCallbacks; - break; - } - callbacks.push(callback); - return { - cancel: function() { - for (var i = 0; i < callbacks.length; ++i) { - if (callbacks[i] === callback) { - callbacks[i] = callbacks[callbacks.length - 1]; - callbacks.pop(); - return; - } - } - } - }; - } - function getCachedCode() { - return cachedCode; - } - function preloadCachedCode(moreCache) { - Object.entries(moreCache).forEach(function(kv) { - cachedCode[kv[0]] = kv[1]; - }); - } - var regl = extend2(compileProcedure, { - // Clear current FBO - clear: clear2, - // Short cuts for dynamic variables - prop: dynamic.define.bind(null, DYN_PROP), - context: dynamic.define.bind(null, DYN_CONTEXT), - this: dynamic.define.bind(null, DYN_STATE), - // executes an empty draw command - draw: compileProcedure({}), - // Resources - buffer: function(options) { - return bufferState.create(options, GL_ARRAY_BUFFER, false, false); - }, - elements: function(options) { - return elementState.create(options, false); - }, - texture: textureState.create2D, - cube: textureState.createCube, - renderbuffer: renderbufferState.create, - framebuffer: framebufferState.create, - framebufferCube: framebufferState.createCube, - vao: attributeState.createVAO, - // Expose context attributes - attributes: glAttributes, - // Frame rendering - frame, - on: addListener2, - // System limits - limits, - hasExtension: function(name2) { - return limits.extensions.indexOf(name2.toLowerCase()) >= 0; - }, - // Read pixels - read: readPixels, - // Destroy regl and all associated resources - destroy: destroy2, - // Direct GL state manipulation - _gl: gl, - _refresh: refresh, - poll: function() { - poll(); - if (timer) { - timer.update(); - } - }, - // Current time - now, - // regl Statistics Information - stats: stats$$1, - // cache generated code - getCachedCode, - preloadCachedCode - }); - config.onDone(null, regl); - return regl; - } - return wrapREGL; - }); -})(regl_unchecked); -var regl_uncheckedExports = regl_unchecked.exports; -var pick$1 = pickByAlias; -var context = function setContext(o) { - if (!o) o = {}; - else if (typeof o === "string") o = { container: o }; - if (isCanvas(o)) { - o = { container: o }; - } else if (isElement(o)) { - o = { container: o }; - } else if (isContext(o)) { - o = { gl: o }; - } else { - o = pick$1(o, { - container: "container target element el canvas holder parent parentNode wrapper use ref root node", - gl: "gl context webgl glContext", - attrs: "attributes attrs contextAttributes", - pixelRatio: "pixelRatio pxRatio px ratio pxratio pixelratio", - width: "w width", - height: "h height" - }, true); - } - if (!o.pixelRatio) o.pixelRatio = index$3.commonjsGlobal.pixelRatio || 1; - if (o.gl) { - return o.gl; - } - if (o.canvas) { - o.container = o.canvas.parentNode; - } - if (o.container) { - if (typeof o.container === "string") { - var c = document.querySelector(o.container); - if (!c) throw Error("Element " + o.container + " is not found"); - o.container = c; - } - if (isCanvas(o.container)) { - o.canvas = o.container; - o.container = o.canvas.parentNode; - } else if (!o.canvas) { - o.canvas = createCanvas(); - o.container.appendChild(o.canvas); - resize(o); - } - } else if (!o.canvas) { - if (typeof document !== "undefined") { - o.container = document.body || document.documentElement; - o.canvas = createCanvas(); - o.container.appendChild(o.canvas); - resize(o); - } else { - throw Error("Not DOM environment. Use headless-gl."); - } - } - if (!o.gl) { - ["webgl", "experimental-webgl", "webgl-experimental"].some(function(c2) { - try { - o.gl = o.canvas.getContext(c2, o.attrs); - } catch (e) { - } - return o.gl; - }); - } - return o.gl; -}; -function resize(o) { - if (o.container) { - if (o.container == document.body) { - if (!document.body.style.width) o.canvas.width = o.width || o.pixelRatio * index$3.commonjsGlobal.innerWidth; - if (!document.body.style.height) o.canvas.height = o.height || o.pixelRatio * index$3.commonjsGlobal.innerHeight; - } else { - var bounds = o.container.getBoundingClientRect(); - o.canvas.width = o.width || bounds.right - bounds.left; - o.canvas.height = o.height || bounds.bottom - bounds.top; - } - } -} -function isCanvas(e) { - return typeof e.getContext === "function" && "width" in e && "height" in e; -} -function isElement(e) { - return typeof e.nodeName === "string" && typeof e.appendChild === "function" && typeof e.getBoundingClientRect === "function"; -} -function isContext(e) { - return typeof e.drawArrays === "function" || typeof e.drawElements === "function"; -} -function createCanvas() { - var canvas2 = document.createElement("canvas"); - canvas2.style.position = "absolute"; - canvas2.style.top = 0; - canvas2.style.left = 0; - return canvas2; -} -var stringifyFont2 = stringify; -var defaultChars = [32, 126]; -var fontAtlas$1 = atlas; -function atlas(options) { - options = options || {}; - var shape = options.shape ? options.shape : options.canvas ? [options.canvas.width, options.canvas.height] : [512, 512]; - var canvas2 = options.canvas || document.createElement("canvas"); - var font2 = options.font; - var step = typeof options.step === "number" ? [options.step, options.step] : options.step || [32, 32]; - var chars2 = options.chars || defaultChars; - if (font2 && typeof font2 !== "string") font2 = stringifyFont2(font2); - if (!Array.isArray(chars2)) { - chars2 = String(chars2).split(""); - } else if (chars2.length === 2 && typeof chars2[0] === "number" && typeof chars2[1] === "number") { - var newchars = []; - for (var i = chars2[0], j = 0; i <= chars2[1]; i++) { - newchars[j++] = String.fromCharCode(i); - } - chars2 = newchars; - } - shape = shape.slice(); - canvas2.width = shape[0]; - canvas2.height = shape[1]; - var ctx2 = canvas2.getContext("2d"); - ctx2.fillStyle = "#000"; - ctx2.fillRect(0, 0, canvas2.width, canvas2.height); - ctx2.font = font2; - ctx2.textAlign = "center"; - ctx2.textBaseline = "middle"; - ctx2.fillStyle = "#fff"; - var x = step[0] / 2; - var y = step[1] / 2; - for (var i = 0; i < chars2.length; i++) { - ctx2.fillText(chars2[i], x, y); - if ((x += step[0]) > shape[0] - step[0] / 2) x = step[0] / 2, y += step[1]; - } - return canvas2; -} -var pool$1 = {}; -var twiddle = {}; -var INT_BITS = 32; -twiddle.INT_BITS = INT_BITS; -twiddle.INT_MAX = 2147483647; -twiddle.INT_MIN = -1 << INT_BITS - 1; -twiddle.sign = function(v) { - return (v > 0) - (v < 0); -}; -twiddle.abs = function(v) { - var mask = v >> INT_BITS - 1; - return (v ^ mask) - mask; -}; -twiddle.min = function(x, y) { - return y ^ (x ^ y) & -(x < y); -}; -twiddle.max = function(x, y) { - return x ^ (x ^ y) & -(x < y); -}; -twiddle.isPow2 = function(v) { - return !(v & v - 1) && !!v; -}; -twiddle.log2 = function(v) { - var r, shift; - r = (v > 65535) << 4; - v >>>= r; - shift = (v > 255) << 3; - v >>>= shift; - r |= shift; - shift = (v > 15) << 2; - v >>>= shift; - r |= shift; - shift = (v > 3) << 1; - v >>>= shift; - r |= shift; - return r | v >> 1; -}; -twiddle.log10 = function(v) { - return v >= 1e9 ? 9 : v >= 1e8 ? 8 : v >= 1e7 ? 7 : v >= 1e6 ? 6 : v >= 1e5 ? 5 : v >= 1e4 ? 4 : v >= 1e3 ? 3 : v >= 100 ? 2 : v >= 10 ? 1 : 0; -}; -twiddle.popCount = function(v) { - v = v - (v >>> 1 & 1431655765); - v = (v & 858993459) + (v >>> 2 & 858993459); - return (v + (v >>> 4) & 252645135) * 16843009 >>> 24; -}; -function countTrailingZeros(v) { - var c = 32; - v &= -v; - if (v) c--; - if (v & 65535) c -= 16; - if (v & 16711935) c -= 8; - if (v & 252645135) c -= 4; - if (v & 858993459) c -= 2; - if (v & 1431655765) c -= 1; - return c; -} -twiddle.countTrailingZeros = countTrailingZeros; -twiddle.nextPow2 = function(v) { - v += v === 0; - --v; - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v + 1; -}; -twiddle.prevPow2 = function(v) { - v |= v >>> 1; - v |= v >>> 2; - v |= v >>> 4; - v |= v >>> 8; - v |= v >>> 16; - return v - (v >>> 1); -}; -twiddle.parity = function(v) { - v ^= v >>> 16; - v ^= v >>> 8; - v ^= v >>> 4; - v &= 15; - return 27030 >>> v & 1; -}; -var REVERSE_TABLE = new Array(256); -(function(tab) { - for (var i = 0; i < 256; ++i) { - var v = i, r = i, s = 7; - for (v >>>= 1; v; v >>>= 1) { - r <<= 1; - r |= v & 1; - --s; - } - tab[i] = r << s & 255; - } -})(REVERSE_TABLE); -twiddle.reverse = function(v) { - return REVERSE_TABLE[v & 255] << 24 | REVERSE_TABLE[v >>> 8 & 255] << 16 | REVERSE_TABLE[v >>> 16 & 255] << 8 | REVERSE_TABLE[v >>> 24 & 255]; -}; -twiddle.interleave2 = function(x, y) { - x &= 65535; - x = (x | x << 8) & 16711935; - x = (x | x << 4) & 252645135; - x = (x | x << 2) & 858993459; - x = (x | x << 1) & 1431655765; - y &= 65535; - y = (y | y << 8) & 16711935; - y = (y | y << 4) & 252645135; - y = (y | y << 2) & 858993459; - y = (y | y << 1) & 1431655765; - return x | y << 1; -}; -twiddle.deinterleave2 = function(v, n) { - v = v >>> n & 1431655765; - v = (v | v >>> 1) & 858993459; - v = (v | v >>> 2) & 252645135; - v = (v | v >>> 4) & 16711935; - v = (v | v >>> 16) & 65535; - return v << 16 >> 16; -}; -twiddle.interleave3 = function(x, y, z) { - x &= 1023; - x = (x | x << 16) & 4278190335; - x = (x | x << 8) & 251719695; - x = (x | x << 4) & 3272356035; - x = (x | x << 2) & 1227133513; - y &= 1023; - y = (y | y << 16) & 4278190335; - y = (y | y << 8) & 251719695; - y = (y | y << 4) & 3272356035; - y = (y | y << 2) & 1227133513; - x |= y << 1; - z &= 1023; - z = (z | z << 16) & 4278190335; - z = (z | z << 8) & 251719695; - z = (z | z << 4) & 3272356035; - z = (z | z << 2) & 1227133513; - return x | z << 2; -}; -twiddle.deinterleave3 = function(v, n) { - v = v >>> n & 1227133513; - v = (v | v >>> 2) & 3272356035; - v = (v | v >>> 4) & 251719695; - v = (v | v >>> 8) & 4278190335; - v = (v | v >>> 16) & 1023; - return v << 22 >> 22; -}; -twiddle.nextCombination = function(v) { - var t = v | v - 1; - return t + 1 | (~t & -~t) - 1 >>> countTrailingZeros(v) + 1; -}; -function dupe_array(count2, value2, i) { - var c = count2[i] | 0; - if (c <= 0) { - return []; - } - var result = new Array(c), j; - if (i === count2.length - 1) { - for (j = 0; j < c; ++j) { - result[j] = value2; - } - } else { - for (j = 0; j < c; ++j) { - result[j] = dupe_array(count2, value2, i + 1); - } - } - return result; -} -function dupe_number(count2, value2) { - var result, i; - result = new Array(count2); - for (i = 0; i < count2; ++i) { - result[i] = value2; - } - return result; -} -function dupe(count2, value2) { - if (typeof value2 === "undefined") { - value2 = 0; - } - switch (typeof count2) { - case "number": - if (count2 > 0) { - return dupe_number(count2 | 0, value2); - } - break; - case "object": - if (typeof count2.length === "number") { - return dupe_array(count2, value2, 0); - } - break; - } - return []; -} -var dup$1 = dupe; -var buffer = {}; -var base64Js = {}; -base64Js.byteLength = byteLength; -base64Js.toByteArray = toByteArray; -base64Js.fromByteArray = fromByteArray; -var lookup = []; -var revLookup = []; -var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; -var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; -} -revLookup["-".charCodeAt(0)] = 62; -revLookup["_".charCodeAt(0)] = 63; -function getLens(b64) { - var len = b64.length; - if (len % 4 > 0) { - throw new Error("Invalid string. Length must be a multiple of 4"); - } - var validLen = b64.indexOf("="); - if (validLen === -1) validLen = len; - var placeHoldersLen = validLen === len ? 0 : 4 - validLen % 4; - return [validLen, placeHoldersLen]; -} -function byteLength(b64) { - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; -} -function _byteLength(b64, validLen, placeHoldersLen) { - return (validLen + placeHoldersLen) * 3 / 4 - placeHoldersLen; -} -function toByteArray(b64) { - var tmp; - var lens = getLens(b64); - var validLen = lens[0]; - var placeHoldersLen = lens[1]; - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); - var curByte = 0; - var len = placeHoldersLen > 0 ? validLen - 4 : validLen; - var i; - for (i = 0; i < len; i += 4) { - tmp = revLookup[b64.charCodeAt(i)] << 18 | revLookup[b64.charCodeAt(i + 1)] << 12 | revLookup[b64.charCodeAt(i + 2)] << 6 | revLookup[b64.charCodeAt(i + 3)]; - arr[curByte++] = tmp >> 16 & 255; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 2) { - tmp = revLookup[b64.charCodeAt(i)] << 2 | revLookup[b64.charCodeAt(i + 1)] >> 4; - arr[curByte++] = tmp & 255; - } - if (placeHoldersLen === 1) { - tmp = revLookup[b64.charCodeAt(i)] << 10 | revLookup[b64.charCodeAt(i + 1)] << 4 | revLookup[b64.charCodeAt(i + 2)] >> 2; - arr[curByte++] = tmp >> 8 & 255; - arr[curByte++] = tmp & 255; - } - return arr; -} -function tripletToBase64(num) { - return lookup[num >> 18 & 63] + lookup[num >> 12 & 63] + lookup[num >> 6 & 63] + lookup[num & 63]; -} -function encodeChunk(uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16 & 16711680) + (uint8[i + 1] << 8 & 65280) + (uint8[i + 2] & 255); - output.push(tripletToBase64(tmp)); - } - return output.join(""); -} -function fromByteArray(uint8) { - var tmp; - var len = uint8.length; - var extraBytes = len % 3; - var parts = []; - var maxChunkLength = 16383; - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); - } - if (extraBytes === 1) { - tmp = uint8[len - 1]; - parts.push( - lookup[tmp >> 2] + lookup[tmp << 4 & 63] + "==" - ); - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1]; - parts.push( - lookup[tmp >> 10] + lookup[tmp >> 4 & 63] + lookup[tmp << 2 & 63] + "=" - ); - } - return parts.join(""); -} -var ieee754 = {}; -/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ -ieee754.read = function(buffer2, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? nBytes - 1 : 0; - var d = isLE ? -1 : 1; - var s = buffer2[offset + i]; - i += d; - e = s & (1 << -nBits) - 1; - s >>= -nBits; - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer2[offset + i], i += d, nBits -= 8) { - } - m = e & (1 << -nBits) - 1; - e >>= -nBits; - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer2[offset + i], i += d, nBits -= 8) { - } - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : (s ? -1 : 1) * Infinity; - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen); -}; -ieee754.write = function(buffer2, value2, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; - var i = isLE ? 0 : nBytes - 1; - var d = isLE ? 1 : -1; - var s = value2 < 0 || value2 === 0 && 1 / value2 < 0 ? 1 : 0; - value2 = Math.abs(value2); - if (isNaN(value2) || value2 === Infinity) { - m = isNaN(value2) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value2) / Math.LN2); - if (value2 * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value2 += rt / c; - } else { - value2 += rt * Math.pow(2, 1 - eBias); - } - if (value2 * c >= 2) { - e++; - c /= 2; - } - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value2 * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value2 * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } - for (; mLen >= 8; buffer2[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { - } - e = e << mLen | m; - eLen += mLen; - for (; eLen > 0; buffer2[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { - } - buffer2[offset + i - d] |= s * 128; -}; -/*! - * The buffer module from node.js, for the browser. - * - * @author Feross Aboukhadijeh - * @license MIT - */ -(function(exports2) { - const base64 = base64Js; - const ieee754$1 = ieee754; - const customInspectSymbol = typeof Symbol === "function" && typeof Symbol["for"] === "function" ? Symbol["for"]("nodejs.util.inspect.custom") : null; - exports2.Buffer = Buffer2; - exports2.SlowBuffer = SlowBuffer; - exports2.INSPECT_MAX_BYTES = 50; - const K_MAX_LENGTH = 2147483647; - exports2.kMaxLength = K_MAX_LENGTH; - Buffer2.TYPED_ARRAY_SUPPORT = typedArraySupport(); - if (!Buffer2.TYPED_ARRAY_SUPPORT && typeof console !== "undefined" && typeof console.error === "function") { - console.error( - "This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support." - ); - } - function typedArraySupport() { - try { - const arr = new Uint8Array(1); - const proto2 = { foo: function() { - return 42; - } }; - Object.setPrototypeOf(proto2, Uint8Array.prototype); - Object.setPrototypeOf(arr, proto2); - return arr.foo() === 42; - } catch (e) { - return false; - } - } - Object.defineProperty(Buffer2.prototype, "parent", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) return void 0; - return this.buffer; - } - }); - Object.defineProperty(Buffer2.prototype, "offset", { - enumerable: true, - get: function() { - if (!Buffer2.isBuffer(this)) return void 0; - return this.byteOffset; - } - }); - function createBuffer(length2) { - if (length2 > K_MAX_LENGTH) { - throw new RangeError('The value "' + length2 + '" is invalid for option "size"'); - } - const buf = new Uint8Array(length2); - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function Buffer2(arg, encodingOrOffset, length2) { - if (typeof arg === "number") { - if (typeof encodingOrOffset === "string") { - throw new TypeError( - 'The "string" argument must be of type string. Received type number' - ); - } - return allocUnsafe(arg); - } - return from(arg, encodingOrOffset, length2); - } - Buffer2.poolSize = 8192; - function from(value2, encodingOrOffset, length2) { - if (typeof value2 === "string") { - return fromString(value2, encodingOrOffset); - } - if (ArrayBuffer.isView(value2)) { - return fromArrayView(value2); - } - if (value2 == null) { - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2 - ); - } - if (isInstance(value2, ArrayBuffer) || value2 && isInstance(value2.buffer, ArrayBuffer)) { - return fromArrayBuffer(value2, encodingOrOffset, length2); - } - if (typeof SharedArrayBuffer !== "undefined" && (isInstance(value2, SharedArrayBuffer) || value2 && isInstance(value2.buffer, SharedArrayBuffer))) { - return fromArrayBuffer(value2, encodingOrOffset, length2); - } - if (typeof value2 === "number") { - throw new TypeError( - 'The "value" argument must not be of type number. Received type number' - ); - } - const valueOf = value2.valueOf && value2.valueOf(); - if (valueOf != null && valueOf !== value2) { - return Buffer2.from(valueOf, encodingOrOffset, length2); - } - const b = fromObject(value2); - if (b) return b; - if (typeof Symbol !== "undefined" && Symbol.toPrimitive != null && typeof value2[Symbol.toPrimitive] === "function") { - return Buffer2.from(value2[Symbol.toPrimitive]("string"), encodingOrOffset, length2); - } - throw new TypeError( - "The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type " + typeof value2 - ); - } - Buffer2.from = function(value2, encodingOrOffset, length2) { - return from(value2, encodingOrOffset, length2); - }; - Object.setPrototypeOf(Buffer2.prototype, Uint8Array.prototype); - Object.setPrototypeOf(Buffer2, Uint8Array); - function assertSize(size) { - if (typeof size !== "number") { - throw new TypeError('"size" argument must be of type number'); - } else if (size < 0) { - throw new RangeError('The value "' + size + '" is invalid for option "size"'); - } - } - function alloc(size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(size); - } - if (fill !== void 0) { - return typeof encoding === "string" ? createBuffer(size).fill(fill, encoding) : createBuffer(size).fill(fill); - } - return createBuffer(size); - } - Buffer2.alloc = function(size, fill, encoding) { - return alloc(size, fill, encoding); - }; - function allocUnsafe(size) { - assertSize(size); - return createBuffer(size < 0 ? 0 : checked(size) | 0); - } - Buffer2.allocUnsafe = function(size) { - return allocUnsafe(size); - }; - Buffer2.allocUnsafeSlow = function(size) { - return allocUnsafe(size); - }; - function fromString(string2, encoding) { - if (typeof encoding !== "string" || encoding === "") { - encoding = "utf8"; - } - if (!Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - const length2 = byteLength2(string2, encoding) | 0; - let buf = createBuffer(length2); - const actual = buf.write(string2, encoding); - if (actual !== length2) { - buf = buf.slice(0, actual); - } - return buf; - } - function fromArrayLike(array2) { - const length2 = array2.length < 0 ? 0 : checked(array2.length) | 0; - const buf = createBuffer(length2); - for (let i = 0; i < length2; i += 1) { - buf[i] = array2[i] & 255; - } - return buf; - } - function fromArrayView(arrayView) { - if (isInstance(arrayView, Uint8Array)) { - const copy2 = new Uint8Array(arrayView); - return fromArrayBuffer(copy2.buffer, copy2.byteOffset, copy2.byteLength); - } - return fromArrayLike(arrayView); - } - function fromArrayBuffer(array2, byteOffset, length2) { - if (byteOffset < 0 || array2.byteLength < byteOffset) { - throw new RangeError('"offset" is outside of buffer bounds'); - } - if (array2.byteLength < byteOffset + (length2 || 0)) { - throw new RangeError('"length" is outside of buffer bounds'); - } - let buf; - if (byteOffset === void 0 && length2 === void 0) { - buf = new Uint8Array(array2); - } else if (length2 === void 0) { - buf = new Uint8Array(array2, byteOffset); - } else { - buf = new Uint8Array(array2, byteOffset, length2); - } - Object.setPrototypeOf(buf, Buffer2.prototype); - return buf; - } - function fromObject(obj) { - if (Buffer2.isBuffer(obj)) { - const len = checked(obj.length) | 0; - const buf = createBuffer(len); - if (buf.length === 0) { - return buf; - } - obj.copy(buf, 0, 0, len); - return buf; - } - if (obj.length !== void 0) { - if (typeof obj.length !== "number" || numberIsNaN(obj.length)) { - return createBuffer(0); - } - return fromArrayLike(obj); - } - if (obj.type === "Buffer" && Array.isArray(obj.data)) { - return fromArrayLike(obj.data); - } - } - function checked(length2) { - if (length2 >= K_MAX_LENGTH) { - throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x" + K_MAX_LENGTH.toString(16) + " bytes"); - } - return length2 | 0; - } - function SlowBuffer(length2) { - if (+length2 != length2) { - length2 = 0; - } - return Buffer2.alloc(+length2); - } - Buffer2.isBuffer = function isBuffer(b) { - return b != null && b._isBuffer === true && b !== Buffer2.prototype; - }; - Buffer2.compare = function compare(a, b) { - if (isInstance(a, Uint8Array)) a = Buffer2.from(a, a.offset, a.byteLength); - if (isInstance(b, Uint8Array)) b = Buffer2.from(b, b.offset, b.byteLength); - if (!Buffer2.isBuffer(a) || !Buffer2.isBuffer(b)) { - throw new TypeError( - 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' - ); - } - if (a === b) return 0; - let x = a.length; - let y = b.length; - for (let i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break; - } - } - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - Buffer2.isEncoding = function isEncoding(encoding) { - switch (String(encoding).toLowerCase()) { - case "hex": - case "utf8": - case "utf-8": - case "ascii": - case "latin1": - case "binary": - case "base64": - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return true; - default: - return false; - } - }; - Buffer2.concat = function concat(list, length2) { - if (!Array.isArray(list)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } - if (list.length === 0) { - return Buffer2.alloc(0); - } - let i; - if (length2 === void 0) { - length2 = 0; - for (i = 0; i < list.length; ++i) { - length2 += list[i].length; - } - } - const buffer2 = Buffer2.allocUnsafe(length2); - let pos = 0; - for (i = 0; i < list.length; ++i) { - let buf = list[i]; - if (isInstance(buf, Uint8Array)) { - if (pos + buf.length > buffer2.length) { - if (!Buffer2.isBuffer(buf)) buf = Buffer2.from(buf); - buf.copy(buffer2, pos); - } else { - Uint8Array.prototype.set.call( - buffer2, - buf, - pos - ); - } - } else if (!Buffer2.isBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers'); - } else { - buf.copy(buffer2, pos); - } - pos += buf.length; - } - return buffer2; - }; - function byteLength2(string2, encoding) { - if (Buffer2.isBuffer(string2)) { - return string2.length; - } - if (ArrayBuffer.isView(string2) || isInstance(string2, ArrayBuffer)) { - return string2.byteLength; - } - if (typeof string2 !== "string") { - throw new TypeError( - 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type ' + typeof string2 - ); - } - const len = string2.length; - const mustMatch = arguments.length > 2 && arguments[2] === true; - if (!mustMatch && len === 0) return 0; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "ascii": - case "latin1": - case "binary": - return len; - case "utf8": - case "utf-8": - return utf8ToBytes(string2).length; - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return len * 2; - case "hex": - return len >>> 1; - case "base64": - return base64ToBytes(string2).length; - default: - if (loweredCase) { - return mustMatch ? -1 : utf8ToBytes(string2).length; - } - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.byteLength = byteLength2; - function slowToString(encoding, start, end) { - let loweredCase = false; - if (start === void 0 || start < 0) { - start = 0; - } - if (start > this.length) { - return ""; - } - if (end === void 0 || end > this.length) { - end = this.length; - } - if (end <= 0) { - return ""; - } - end >>>= 0; - start >>>= 0; - if (end <= start) { - return ""; - } - if (!encoding) encoding = "utf8"; - while (true) { - switch (encoding) { - case "hex": - return hexSlice(this, start, end); - case "utf8": - case "utf-8": - return utf8Slice(this, start, end); - case "ascii": - return asciiSlice(this, start, end); - case "latin1": - case "binary": - return latin1Slice(this, start, end); - case "base64": - return base64Slice(this, start, end); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return utf16leSlice(this, start, end); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = (encoding + "").toLowerCase(); - loweredCase = true; - } - } - } - Buffer2.prototype._isBuffer = true; - function swap(b, n, m) { - const i = b[n]; - b[n] = b[m]; - b[m] = i; - } - Buffer2.prototype.swap16 = function swap16() { - const len = this.length; - if (len % 2 !== 0) { - throw new RangeError("Buffer size must be a multiple of 16-bits"); - } - for (let i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this; - }; - Buffer2.prototype.swap32 = function swap32() { - const len = this.length; - if (len % 4 !== 0) { - throw new RangeError("Buffer size must be a multiple of 32-bits"); - } - for (let i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this; - }; - Buffer2.prototype.swap64 = function swap64() { - const len = this.length; - if (len % 8 !== 0) { - throw new RangeError("Buffer size must be a multiple of 64-bits"); - } - for (let i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this; - }; - Buffer2.prototype.toString = function toString2() { - const length2 = this.length; - if (length2 === 0) return ""; - if (arguments.length === 0) return utf8Slice(this, 0, length2); - return slowToString.apply(this, arguments); - }; - Buffer2.prototype.toLocaleString = Buffer2.prototype.toString; - Buffer2.prototype.equals = function equals2(b) { - if (!Buffer2.isBuffer(b)) throw new TypeError("Argument must be a Buffer"); - if (this === b) return true; - return Buffer2.compare(this, b) === 0; - }; - Buffer2.prototype.inspect = function inspect() { - let str2 = ""; - const max = exports2.INSPECT_MAX_BYTES; - str2 = this.toString("hex", 0, max).replace(/(.{2})/g, "$1 ").trim(); - if (this.length > max) str2 += " ... "; - return ""; - }; - if (customInspectSymbol) { - Buffer2.prototype[customInspectSymbol] = Buffer2.prototype.inspect; - } - Buffer2.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { - if (isInstance(target, Uint8Array)) { - target = Buffer2.from(target, target.offset, target.byteLength); - } - if (!Buffer2.isBuffer(target)) { - throw new TypeError( - 'The "target" argument must be one of type Buffer or Uint8Array. Received type ' + typeof target - ); - } - if (start === void 0) { - start = 0; - } - if (end === void 0) { - end = target ? target.length : 0; - } - if (thisStart === void 0) { - thisStart = 0; - } - if (thisEnd === void 0) { - thisEnd = this.length; - } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError("out of range index"); - } - if (thisStart >= thisEnd && start >= end) { - return 0; - } - if (thisStart >= thisEnd) { - return -1; - } - if (start >= end) { - return 1; - } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; - if (this === target) return 0; - let x = thisEnd - thisStart; - let y = end - start; - const len = Math.min(x, y); - const thisCopy = this.slice(thisStart, thisEnd); - const targetCopy = target.slice(start, end); - for (let i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break; - } - } - if (x < y) return -1; - if (y < x) return 1; - return 0; - }; - function bidirectionalIndexOf(buffer2, val, byteOffset, encoding, dir) { - if (buffer2.length === 0) return -1; - if (typeof byteOffset === "string") { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 2147483647) { - byteOffset = 2147483647; - } else if (byteOffset < -2147483648) { - byteOffset = -2147483648; - } - byteOffset = +byteOffset; - if (numberIsNaN(byteOffset)) { - byteOffset = dir ? 0 : buffer2.length - 1; - } - if (byteOffset < 0) byteOffset = buffer2.length + byteOffset; - if (byteOffset >= buffer2.length) { - if (dir) return -1; - else byteOffset = buffer2.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1; - } - if (typeof val === "string") { - val = Buffer2.from(val, encoding); - } - if (Buffer2.isBuffer(val)) { - if (val.length === 0) { - return -1; - } - return arrayIndexOf(buffer2, val, byteOffset, encoding, dir); - } else if (typeof val === "number") { - val = val & 255; - if (typeof Uint8Array.prototype.indexOf === "function") { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer2, val, byteOffset); - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer2, val, byteOffset); - } - } - return arrayIndexOf(buffer2, [val], byteOffset, encoding, dir); - } - throw new TypeError("val must be string, number or Buffer"); - } - function arrayIndexOf(arr, val, byteOffset, encoding, dir) { - let indexSize = 1; - let arrLength = arr.length; - let valLength = val.length; - if (encoding !== void 0) { - encoding = String(encoding).toLowerCase(); - if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { - if (arr.length < 2 || val.length < 2) { - return -1; - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } - function read(buf, i2) { - if (indexSize === 1) { - return buf[i2]; - } else { - return buf.readUInt16BE(i2 * indexSize); - } - } - let i; - if (dir) { - let foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - let found = true; - for (let j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break; - } - } - if (found) return i; - } - } - return -1; - } - Buffer2.prototype.includes = function includes(val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1; - }; - Buffer2.prototype.indexOf = function indexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true); - }; - Buffer2.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false); - }; - function hexWrite(buf, string2, offset, length2) { - offset = Number(offset) || 0; - const remaining = buf.length - offset; - if (!length2) { - length2 = remaining; - } else { - length2 = Number(length2); - if (length2 > remaining) { - length2 = remaining; - } - } - const strLen = string2.length; - if (length2 > strLen / 2) { - length2 = strLen / 2; - } - let i; - for (i = 0; i < length2; ++i) { - const parsed = parseInt(string2.substr(i * 2, 2), 16); - if (numberIsNaN(parsed)) return i; - buf[offset + i] = parsed; - } - return i; - } - function utf8Write(buf, string2, offset, length2) { - return blitBuffer(utf8ToBytes(string2, buf.length - offset), buf, offset, length2); - } - function asciiWrite(buf, string2, offset, length2) { - return blitBuffer(asciiToBytes(string2), buf, offset, length2); - } - function base64Write(buf, string2, offset, length2) { - return blitBuffer(base64ToBytes(string2), buf, offset, length2); - } - function ucs2Write(buf, string2, offset, length2) { - return blitBuffer(utf16leToBytes(string2, buf.length - offset), buf, offset, length2); - } - Buffer2.prototype.write = function write(string2, offset, length2, encoding) { - if (offset === void 0) { - encoding = "utf8"; - length2 = this.length; - offset = 0; - } else if (length2 === void 0 && typeof offset === "string") { - encoding = offset; - length2 = this.length; - offset = 0; - } else if (isFinite(offset)) { - offset = offset >>> 0; - if (isFinite(length2)) { - length2 = length2 >>> 0; - if (encoding === void 0) encoding = "utf8"; - } else { - encoding = length2; - length2 = void 0; - } - } else { - throw new Error( - "Buffer.write(string, encoding, offset[, length]) is no longer supported" - ); - } - const remaining = this.length - offset; - if (length2 === void 0 || length2 > remaining) length2 = remaining; - if (string2.length > 0 && (length2 < 0 || offset < 0) || offset > this.length) { - throw new RangeError("Attempt to write outside buffer bounds"); - } - if (!encoding) encoding = "utf8"; - let loweredCase = false; - for (; ; ) { - switch (encoding) { - case "hex": - return hexWrite(this, string2, offset, length2); - case "utf8": - case "utf-8": - return utf8Write(this, string2, offset, length2); - case "ascii": - case "latin1": - case "binary": - return asciiWrite(this, string2, offset, length2); - case "base64": - return base64Write(this, string2, offset, length2); - case "ucs2": - case "ucs-2": - case "utf16le": - case "utf-16le": - return ucs2Write(this, string2, offset, length2); - default: - if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); - encoding = ("" + encoding).toLowerCase(); - loweredCase = true; - } - } - }; - Buffer2.prototype.toJSON = function toJSON() { - return { - type: "Buffer", - data: Array.prototype.slice.call(this._arr || this, 0) - }; - }; - function base64Slice(buf, start, end) { - if (start === 0 && end === buf.length) { - return base64.fromByteArray(buf); - } else { - return base64.fromByteArray(buf.slice(start, end)); - } - } - function utf8Slice(buf, start, end) { - end = Math.min(buf.length, end); - const res = []; - let i = start; - while (i < end) { - const firstByte = buf[i]; - let codePoint = null; - let bytesPerSequence = firstByte > 239 ? 4 : firstByte > 223 ? 3 : firstByte > 191 ? 2 : 1; - if (i + bytesPerSequence <= end) { - let secondByte, thirdByte, fourthByte, tempCodePoint; - switch (bytesPerSequence) { - case 1: - if (firstByte < 128) { - codePoint = firstByte; - } - break; - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 192) === 128) { - tempCodePoint = (firstByte & 31) << 6 | secondByte & 63; - if (tempCodePoint > 127) { - codePoint = tempCodePoint; - } - } - break; - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 12 | (secondByte & 63) << 6 | thirdByte & 63; - if (tempCodePoint > 2047 && (tempCodePoint < 55296 || tempCodePoint > 57343)) { - codePoint = tempCodePoint; - } - } - break; - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 192) === 128 && (thirdByte & 192) === 128 && (fourthByte & 192) === 128) { - tempCodePoint = (firstByte & 15) << 18 | (secondByte & 63) << 12 | (thirdByte & 63) << 6 | fourthByte & 63; - if (tempCodePoint > 65535 && tempCodePoint < 1114112) { - codePoint = tempCodePoint; - } - } - } - } - if (codePoint === null) { - codePoint = 65533; - bytesPerSequence = 1; - } else if (codePoint > 65535) { - codePoint -= 65536; - res.push(codePoint >>> 10 & 1023 | 55296); - codePoint = 56320 | codePoint & 1023; - } - res.push(codePoint); - i += bytesPerSequence; - } - return decodeCodePointsArray(res); - } - const MAX_ARGUMENTS_LENGTH = 4096; - function decodeCodePointsArray(codePoints) { - const len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints); - } - let res = ""; - let i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res; - } - function asciiSlice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 127); - } - return ret; - } - function latin1Slice(buf, start, end) { - let ret = ""; - end = Math.min(buf.length, end); - for (let i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret; - } - function hexSlice(buf, start, end) { - const len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; - let out = ""; - for (let i = start; i < end; ++i) { - out += hexSliceLookupTable[buf[i]]; - } - return out; - } - function utf16leSlice(buf, start, end) { - const bytes = buf.slice(start, end); - let res = ""; - for (let i = 0; i < bytes.length - 1; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res; - } - Buffer2.prototype.slice = function slice2(start, end) { - const len = this.length; - start = ~~start; - end = end === void 0 ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } - if (end < start) end = start; - const newBuf = this.subarray(start, end); - Object.setPrototypeOf(newBuf, Buffer2.prototype); - return newBuf; - }; - function checkOffset(offset, ext, length2) { - if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); - if (offset + ext > length2) throw new RangeError("Trying to access beyond buffer length"); - } - Buffer2.prototype.readUintLE = Buffer2.prototype.readUIntLE = function readUIntLE(offset, byteLength3, noAssert) { - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset, byteLength3, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength3 && (mul *= 256)) { - val += this[offset + i] * mul; - } - return val; - }; - Buffer2.prototype.readUintBE = Buffer2.prototype.readUIntBE = function readUIntBE(offset, byteLength3, noAssert) { - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - checkOffset(offset, byteLength3, this.length); - } - let val = this[offset + --byteLength3]; - let mul = 1; - while (byteLength3 > 0 && (mul *= 256)) { - val += this[offset + --byteLength3] * mul; - } - return val; - }; - Buffer2.prototype.readUint8 = Buffer2.prototype.readUInt8 = function readUInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset]; - }; - Buffer2.prototype.readUint16LE = Buffer2.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | this[offset + 1] << 8; - }; - Buffer2.prototype.readUint16BE = Buffer2.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] << 8 | this[offset + 1]; - }; - Buffer2.prototype.readUint32LE = Buffer2.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16) + this[offset + 3] * 16777216; - }; - Buffer2.prototype.readUint32BE = Buffer2.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] * 16777216 + (this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]); - }; - Buffer2.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const lo = first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24; - const hi = this[++offset] + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + last * 2 ** 24; - return BigInt(lo) + (BigInt(hi) << BigInt(32)); - }); - Buffer2.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const hi = first * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - const lo = this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last; - return (BigInt(hi) << BigInt(32)) + BigInt(lo); - }); - Buffer2.prototype.readIntLE = function readIntLE(offset, byteLength3, noAssert) { - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset, byteLength3, this.length); - let val = this[offset]; - let mul = 1; - let i = 0; - while (++i < byteLength3 && (mul *= 256)) { - val += this[offset + i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength3); - return val; - }; - Buffer2.prototype.readIntBE = function readIntBE(offset, byteLength3, noAssert) { - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) checkOffset(offset, byteLength3, this.length); - let i = byteLength3; - let mul = 1; - let val = this[offset + --i]; - while (i > 0 && (mul *= 256)) { - val += this[offset + --i] * mul; - } - mul *= 128; - if (val >= mul) val -= Math.pow(2, 8 * byteLength3); - return val; - }; - Buffer2.prototype.readInt8 = function readInt8(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 128)) return this[offset]; - return (255 - this[offset] + 1) * -1; - }; - Buffer2.prototype.readInt16LE = function readInt16LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - const val = this[offset] | this[offset + 1] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt16BE = function readInt16BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 2, this.length); - const val = this[offset + 1] | this[offset] << 8; - return val & 32768 ? val | 4294901760 : val; - }; - Buffer2.prototype.readInt32LE = function readInt32LE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] | this[offset + 1] << 8 | this[offset + 2] << 16 | this[offset + 3] << 24; - }; - Buffer2.prototype.readInt32BE = function readInt32BE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return this[offset] << 24 | this[offset + 1] << 16 | this[offset + 2] << 8 | this[offset + 3]; - }; - Buffer2.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = this[offset + 4] + this[offset + 5] * 2 ** 8 + this[offset + 6] * 2 ** 16 + (last << 24); - return (BigInt(val) << BigInt(32)) + BigInt(first + this[++offset] * 2 ** 8 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 24); - }); - Buffer2.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE(offset) { - offset = offset >>> 0; - validateNumber(offset, "offset"); - const first = this[offset]; - const last = this[offset + 7]; - if (first === void 0 || last === void 0) { - boundsError(offset, this.length - 8); - } - const val = (first << 24) + // Overflow - this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + this[++offset]; - return (BigInt(val) << BigInt(32)) + BigInt(this[++offset] * 2 ** 24 + this[++offset] * 2 ** 16 + this[++offset] * 2 ** 8 + last); - }); - Buffer2.prototype.readFloatLE = function readFloatLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, true, 23, 4); - }; - Buffer2.prototype.readFloatBE = function readFloatBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 4, this.length); - return ieee754$1.read(this, offset, false, 23, 4); - }; - Buffer2.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.read(this, offset, true, 52, 8); - }; - Buffer2.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { - offset = offset >>> 0; - if (!noAssert) checkOffset(offset, 8, this.length); - return ieee754$1.read(this, offset, false, 52, 8); - }; - function checkInt(buf, value2, offset, ext, max, min) { - if (!Buffer2.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); - if (value2 > max || value2 < min) throw new RangeError('"value" argument is out of bounds'); - if (offset + ext > buf.length) throw new RangeError("Index out of range"); - } - Buffer2.prototype.writeUintLE = Buffer2.prototype.writeUIntLE = function writeUIntLE(value2, offset, byteLength3, noAssert) { - value2 = +value2; - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength3) - 1; - checkInt(this, value2, offset, byteLength3, maxBytes, 0); - } - let mul = 1; - let i = 0; - this[offset] = value2 & 255; - while (++i < byteLength3 && (mul *= 256)) { - this[offset + i] = value2 / mul & 255; - } - return offset + byteLength3; - }; - Buffer2.prototype.writeUintBE = Buffer2.prototype.writeUIntBE = function writeUIntBE(value2, offset, byteLength3, noAssert) { - value2 = +value2; - offset = offset >>> 0; - byteLength3 = byteLength3 >>> 0; - if (!noAssert) { - const maxBytes = Math.pow(2, 8 * byteLength3) - 1; - checkInt(this, value2, offset, byteLength3, maxBytes, 0); - } - let i = byteLength3 - 1; - let mul = 1; - this[offset + i] = value2 & 255; - while (--i >= 0 && (mul *= 256)) { - this[offset + i] = value2 / mul & 255; - } - return offset + byteLength3; - }; - Buffer2.prototype.writeUint8 = Buffer2.prototype.writeUInt8 = function writeUInt8(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 1, 255, 0); - this[offset] = value2 & 255; - return offset + 1; - }; - Buffer2.prototype.writeUint16LE = Buffer2.prototype.writeUInt16LE = function writeUInt16LE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0); - this[offset] = value2 & 255; - this[offset + 1] = value2 >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeUint16BE = Buffer2.prototype.writeUInt16BE = function writeUInt16BE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 2, 65535, 0); - this[offset] = value2 >>> 8; - this[offset + 1] = value2 & 255; - return offset + 2; - }; - Buffer2.prototype.writeUint32LE = Buffer2.prototype.writeUInt32LE = function writeUInt32LE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0); - this[offset + 3] = value2 >>> 24; - this[offset + 2] = value2 >>> 16; - this[offset + 1] = value2 >>> 8; - this[offset] = value2 & 255; - return offset + 4; - }; - Buffer2.prototype.writeUint32BE = Buffer2.prototype.writeUInt32BE = function writeUInt32BE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 4, 4294967295, 0); - this[offset] = value2 >>> 24; - this[offset + 1] = value2 >>> 16; - this[offset + 2] = value2 >>> 8; - this[offset + 3] = value2 & 255; - return offset + 4; - }; - function wrtBigUInt64LE(buf, value2, offset, min, max) { - checkIntBI(value2, min, max, buf, offset, 7); - let lo = Number(value2 & BigInt(4294967295)); - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - lo = lo >> 8; - buf[offset++] = lo; - let hi = Number(value2 >> BigInt(32) & BigInt(4294967295)); - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - hi = hi >> 8; - buf[offset++] = hi; - return offset; - } - function wrtBigUInt64BE(buf, value2, offset, min, max) { - checkIntBI(value2, min, max, buf, offset, 7); - let lo = Number(value2 & BigInt(4294967295)); - buf[offset + 7] = lo; - lo = lo >> 8; - buf[offset + 6] = lo; - lo = lo >> 8; - buf[offset + 5] = lo; - lo = lo >> 8; - buf[offset + 4] = lo; - let hi = Number(value2 >> BigInt(32) & BigInt(4294967295)); - buf[offset + 3] = hi; - hi = hi >> 8; - buf[offset + 2] = hi; - hi = hi >> 8; - buf[offset + 1] = hi; - hi = hi >> 8; - buf[offset] = hi; - return offset + 8; - } - Buffer2.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE(value2, offset = 0) { - return wrtBigUInt64LE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE(value2, offset = 0) { - return wrtBigUInt64BE(this, value2, offset, BigInt(0), BigInt("0xffffffffffffffff")); - }); - Buffer2.prototype.writeIntLE = function writeIntLE(value2, offset, byteLength3, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength3 - 1); - checkInt(this, value2, offset, byteLength3, limit - 1, -limit); - } - let i = 0; - let mul = 1; - let sub = 0; - this[offset] = value2 & 255; - while (++i < byteLength3 && (mul *= 256)) { - if (value2 < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = (value2 / mul >> 0) - sub & 255; - } - return offset + byteLength3; - }; - Buffer2.prototype.writeIntBE = function writeIntBE(value2, offset, byteLength3, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) { - const limit = Math.pow(2, 8 * byteLength3 - 1); - checkInt(this, value2, offset, byteLength3, limit - 1, -limit); - } - let i = byteLength3 - 1; - let mul = 1; - let sub = 0; - this[offset + i] = value2 & 255; - while (--i >= 0 && (mul *= 256)) { - if (value2 < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = (value2 / mul >> 0) - sub & 255; - } - return offset + byteLength3; - }; - Buffer2.prototype.writeInt8 = function writeInt8(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 1, 127, -128); - if (value2 < 0) value2 = 255 + value2 + 1; - this[offset] = value2 & 255; - return offset + 1; - }; - Buffer2.prototype.writeInt16LE = function writeInt16LE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768); - this[offset] = value2 & 255; - this[offset + 1] = value2 >>> 8; - return offset + 2; - }; - Buffer2.prototype.writeInt16BE = function writeInt16BE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 2, 32767, -32768); - this[offset] = value2 >>> 8; - this[offset + 1] = value2 & 255; - return offset + 2; - }; - Buffer2.prototype.writeInt32LE = function writeInt32LE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648); - this[offset] = value2 & 255; - this[offset + 1] = value2 >>> 8; - this[offset + 2] = value2 >>> 16; - this[offset + 3] = value2 >>> 24; - return offset + 4; - }; - Buffer2.prototype.writeInt32BE = function writeInt32BE(value2, offset, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) checkInt(this, value2, offset, 4, 2147483647, -2147483648); - if (value2 < 0) value2 = 4294967295 + value2 + 1; - this[offset] = value2 >>> 24; - this[offset + 1] = value2 >>> 16; - this[offset + 2] = value2 >>> 8; - this[offset + 3] = value2 & 255; - return offset + 4; - }; - Buffer2.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE(value2, offset = 0) { - return wrtBigUInt64LE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - Buffer2.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE(value2, offset = 0) { - return wrtBigUInt64BE(this, value2, offset, -BigInt("0x8000000000000000"), BigInt("0x7fffffffffffffff")); - }); - function checkIEEE754(buf, value2, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError("Index out of range"); - if (offset < 0) throw new RangeError("Index out of range"); - } - function writeFloat(buf, value2, offset, littleEndian, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value2, offset, 4); - } - ieee754$1.write(buf, value2, offset, littleEndian, 23, 4); - return offset + 4; - } - Buffer2.prototype.writeFloatLE = function writeFloatLE(value2, offset, noAssert) { - return writeFloat(this, value2, offset, true, noAssert); - }; - Buffer2.prototype.writeFloatBE = function writeFloatBE(value2, offset, noAssert) { - return writeFloat(this, value2, offset, false, noAssert); - }; - function writeDouble(buf, value2, offset, littleEndian, noAssert) { - value2 = +value2; - offset = offset >>> 0; - if (!noAssert) { - checkIEEE754(buf, value2, offset, 8); - } - ieee754$1.write(buf, value2, offset, littleEndian, 52, 8); - return offset + 8; - } - Buffer2.prototype.writeDoubleLE = function writeDoubleLE(value2, offset, noAssert) { - return writeDouble(this, value2, offset, true, noAssert); - }; - Buffer2.prototype.writeDoubleBE = function writeDoubleBE(value2, offset, noAssert) { - return writeDouble(this, value2, offset, false, noAssert); - }; - Buffer2.prototype.copy = function copy2(target, targetStart, start, end) { - if (!Buffer2.isBuffer(target)) throw new TypeError("argument should be a Buffer"); - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - if (end === start) return 0; - if (target.length === 0 || this.length === 0) return 0; - if (targetStart < 0) { - throw new RangeError("targetStart out of bounds"); - } - if (start < 0 || start >= this.length) throw new RangeError("Index out of range"); - if (end < 0) throw new RangeError("sourceEnd out of bounds"); - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } - const len = end - start; - if (this === target && typeof Uint8Array.prototype.copyWithin === "function") { - this.copyWithin(targetStart, start, end); - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, end), - targetStart - ); - } - return len; - }; - Buffer2.prototype.fill = function fill(val, start, end, encoding) { - if (typeof val === "string") { - if (typeof start === "string") { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === "string") { - encoding = end; - end = this.length; - } - if (encoding !== void 0 && typeof encoding !== "string") { - throw new TypeError("encoding must be a string"); - } - if (typeof encoding === "string" && !Buffer2.isEncoding(encoding)) { - throw new TypeError("Unknown encoding: " + encoding); - } - if (val.length === 1) { - const code2 = val.charCodeAt(0); - if (encoding === "utf8" && code2 < 128 || encoding === "latin1") { - val = code2; - } - } - } else if (typeof val === "number") { - val = val & 255; - } else if (typeof val === "boolean") { - val = Number(val); - } - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError("Out of range index"); - } - if (end <= start) { - return this; - } - start = start >>> 0; - end = end === void 0 ? this.length : end >>> 0; - if (!val) val = 0; - let i; - if (typeof val === "number") { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - const bytes = Buffer2.isBuffer(val) ? val : Buffer2.from(val, encoding); - const len = bytes.length; - if (len === 0) { - throw new TypeError('The value "' + val + '" is invalid for argument "value"'); - } - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } - return this; - }; - const errors = {}; - function E2(sym, getMessage, Base) { - errors[sym] = class NodeError extends Base { - constructor() { - super(); - Object.defineProperty(this, "message", { - value: getMessage.apply(this, arguments), - writable: true, - configurable: true - }); - this.name = `${this.name} [${sym}]`; - this.stack; - delete this.name; - } - get code() { - return sym; - } - set code(value2) { - Object.defineProperty(this, "code", { - configurable: true, - enumerable: true, - value: value2, - writable: true - }); - } - toString() { - return `${this.name} [${sym}]: ${this.message}`; - } - }; - } - E2( - "ERR_BUFFER_OUT_OF_BOUNDS", - function(name2) { - if (name2) { - return `${name2} is outside of buffer bounds`; - } - return "Attempt to access memory outside buffer bounds"; - }, - RangeError - ); - E2( - "ERR_INVALID_ARG_TYPE", - function(name2, actual) { - return `The "${name2}" argument must be of type number. Received type ${typeof actual}`; - }, - TypeError - ); - E2( - "ERR_OUT_OF_RANGE", - function(str2, range, input) { - let msg2 = `The value of "${str2}" is out of range.`; - let received = input; - if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { - received = addNumericalSeparator(String(input)); - } else if (typeof input === "bigint") { - received = String(input); - if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { - received = addNumericalSeparator(received); - } - received += "n"; - } - msg2 += ` It must be ${range}. Received ${received}`; - return msg2; - }, - RangeError - ); - function addNumericalSeparator(val) { - let res = ""; - let i = val.length; - const start = val[0] === "-" ? 1 : 0; - for (; i >= start + 4; i -= 3) { - res = `_${val.slice(i - 3, i)}${res}`; - } - return `${val.slice(0, i)}${res}`; - } - function checkBounds(buf, offset, byteLength3) { - validateNumber(offset, "offset"); - if (buf[offset] === void 0 || buf[offset + byteLength3] === void 0) { - boundsError(offset, buf.length - (byteLength3 + 1)); - } - } - function checkIntBI(value2, min, max, buf, offset, byteLength3) { - if (value2 > max || value2 < min) { - const n = typeof min === "bigint" ? "n" : ""; - let range; - { - if (min === 0 || min === BigInt(0)) { - range = `>= 0${n} and < 2${n} ** ${(byteLength3 + 1) * 8}${n}`; - } else { - range = `>= -(2${n} ** ${(byteLength3 + 1) * 8 - 1}${n}) and < 2 ** ${(byteLength3 + 1) * 8 - 1}${n}`; - } - } - throw new errors.ERR_OUT_OF_RANGE("value", range, value2); - } - checkBounds(buf, offset, byteLength3); - } - function validateNumber(value2, name2) { - if (typeof value2 !== "number") { - throw new errors.ERR_INVALID_ARG_TYPE(name2, "number", value2); - } - } - function boundsError(value2, length2, type) { - if (Math.floor(value2) !== value2) { - validateNumber(value2, type); - throw new errors.ERR_OUT_OF_RANGE("offset", "an integer", value2); - } - if (length2 < 0) { - throw new errors.ERR_BUFFER_OUT_OF_BOUNDS(); - } - throw new errors.ERR_OUT_OF_RANGE( - "offset", - `>= ${0} and <= ${length2}`, - value2 - ); - } - const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; - function base64clean(str2) { - str2 = str2.split("=")[0]; - str2 = str2.trim().replace(INVALID_BASE64_RE, ""); - if (str2.length < 2) return ""; - while (str2.length % 4 !== 0) { - str2 = str2 + "="; - } - return str2; - } - function utf8ToBytes(string2, units) { - units = units || Infinity; - let codePoint; - const length2 = string2.length; - let leadSurrogate = null; - const bytes = []; - for (let i = 0; i < length2; ++i) { - codePoint = string2.charCodeAt(i); - if (codePoint > 55295 && codePoint < 57344) { - if (!leadSurrogate) { - if (codePoint > 56319) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - continue; - } else if (i + 1 === length2) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - continue; - } - leadSurrogate = codePoint; - continue; - } - if (codePoint < 56320) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - leadSurrogate = codePoint; - continue; - } - codePoint = (leadSurrogate - 55296 << 10 | codePoint - 56320) + 65536; - } else if (leadSurrogate) { - if ((units -= 3) > -1) bytes.push(239, 191, 189); - } - leadSurrogate = null; - if (codePoint < 128) { - if ((units -= 1) < 0) break; - bytes.push(codePoint); - } else if (codePoint < 2048) { - if ((units -= 2) < 0) break; - bytes.push( - codePoint >> 6 | 192, - codePoint & 63 | 128 - ); - } else if (codePoint < 65536) { - if ((units -= 3) < 0) break; - bytes.push( - codePoint >> 12 | 224, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else if (codePoint < 1114112) { - if ((units -= 4) < 0) break; - bytes.push( - codePoint >> 18 | 240, - codePoint >> 12 & 63 | 128, - codePoint >> 6 & 63 | 128, - codePoint & 63 | 128 - ); - } else { - throw new Error("Invalid code point"); - } - } - return bytes; - } - function asciiToBytes(str2) { - const byteArray = []; - for (let i = 0; i < str2.length; ++i) { - byteArray.push(str2.charCodeAt(i) & 255); - } - return byteArray; - } - function utf16leToBytes(str2, units) { - let c, hi, lo; - const byteArray = []; - for (let i = 0; i < str2.length; ++i) { - if ((units -= 2) < 0) break; - c = str2.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } - return byteArray; - } - function base64ToBytes(str2) { - return base64.toByteArray(base64clean(str2)); - } - function blitBuffer(src2, dst, offset, length2) { - let i; - for (i = 0; i < length2; ++i) { - if (i + offset >= dst.length || i >= src2.length) break; - dst[i + offset] = src2[i]; - } - return i; - } - function isInstance(obj, type) { - return obj instanceof type || obj != null && obj.constructor != null && obj.constructor.name != null && obj.constructor.name === type.name; - } - function numberIsNaN(obj) { - return obj !== obj; - } - const hexSliceLookupTable = function() { - const alphabet = "0123456789abcdef"; - const table = new Array(256); - for (let i = 0; i < 16; ++i) { - const i16 = i * 16; - for (let j = 0; j < 16; ++j) { - table[i16 + j] = alphabet[i] + alphabet[j]; - } - } - return table; - }(); - function defineBigIntMethod(fn) { - return typeof BigInt === "undefined" ? BufferBigIntNotDefined : fn; - } - function BufferBigIntNotDefined() { - throw new Error("BigInt not supported"); - } -})(buffer); -var bits = twiddle; -var dup = dup$1; -var Buffer = buffer.Buffer; -if (!index$3.commonjsGlobal.__TYPEDARRAY_POOL) { - index$3.commonjsGlobal.__TYPEDARRAY_POOL = { - UINT8: dup([32, 0]), - UINT16: dup([32, 0]), - UINT32: dup([32, 0]), - BIGUINT64: dup([32, 0]), - INT8: dup([32, 0]), - INT16: dup([32, 0]), - INT32: dup([32, 0]), - BIGINT64: dup([32, 0]), - FLOAT: dup([32, 0]), - DOUBLE: dup([32, 0]), - DATA: dup([32, 0]), - UINT8C: dup([32, 0]), - BUFFER: dup([32, 0]) - }; -} -var hasUint8C = typeof Uint8ClampedArray !== "undefined"; -var hasBigUint64 = typeof BigUint64Array !== "undefined"; -var hasBigInt64 = typeof BigInt64Array !== "undefined"; -var POOL = index$3.commonjsGlobal.__TYPEDARRAY_POOL; -if (!POOL.UINT8C) { - POOL.UINT8C = dup([32, 0]); -} -if (!POOL.BIGUINT64) { - POOL.BIGUINT64 = dup([32, 0]); -} -if (!POOL.BIGINT64) { - POOL.BIGINT64 = dup([32, 0]); -} -if (!POOL.BUFFER) { - POOL.BUFFER = dup([32, 0]); -} -var DATA = POOL.DATA, BUFFER = POOL.BUFFER; -pool$1.free = function free(array2) { - if (Buffer.isBuffer(array2)) { - BUFFER[bits.log2(array2.length)].push(array2); - } else { - if (Object.prototype.toString.call(array2) !== "[object ArrayBuffer]") { - array2 = array2.buffer; - } - if (!array2) { - return; - } - var n = array2.length || array2.byteLength; - var log_n = bits.log2(n) | 0; - DATA[log_n].push(array2); - } -}; -function freeArrayBuffer(buffer2) { - if (!buffer2) { - return; - } - var n = buffer2.length || buffer2.byteLength; - var log_n = bits.log2(n); - DATA[log_n].push(buffer2); -} -function freeTypedArray(array2) { - freeArrayBuffer(array2.buffer); -} -pool$1.freeUint8 = pool$1.freeUint16 = pool$1.freeUint32 = pool$1.freeBigUint64 = pool$1.freeInt8 = pool$1.freeInt16 = pool$1.freeInt32 = pool$1.freeBigInt64 = pool$1.freeFloat32 = pool$1.freeFloat = pool$1.freeFloat64 = pool$1.freeDouble = pool$1.freeUint8Clamped = pool$1.freeDataView = freeTypedArray; -pool$1.freeArrayBuffer = freeArrayBuffer; -pool$1.freeBuffer = function freeBuffer(array2) { - BUFFER[bits.log2(array2.length)].push(array2); -}; -pool$1.malloc = function malloc(n, dtype2) { - if (dtype2 === void 0 || dtype2 === "arraybuffer") { - return mallocArrayBuffer(n); - } else { - switch (dtype2) { - case "uint8": - return mallocUint8(n); - case "uint16": - return mallocUint16(n); - case "uint32": - return mallocUint32(n); - case "int8": - return mallocInt8(n); - case "int16": - return mallocInt16(n); - case "int32": - return mallocInt32(n); - case "float": - case "float32": - return mallocFloat(n); - case "double": - case "float64": - return mallocDouble(n); - case "uint8_clamped": - return mallocUint8Clamped(n); - case "bigint64": - return mallocBigInt64(n); - case "biguint64": - return mallocBigUint64(n); - case "buffer": - return mallocBuffer(n); - case "data": - case "dataview": - return mallocDataView(n); - default: - return null; - } - } - return null; -}; -function mallocArrayBuffer(n) { - var n = bits.nextPow2(n); - var log_n = bits.log2(n); - var d = DATA[log_n]; - if (d.length > 0) { - return d.pop(); - } - return new ArrayBuffer(n); -} -pool$1.mallocArrayBuffer = mallocArrayBuffer; -function mallocUint8(n) { - return new Uint8Array(mallocArrayBuffer(n), 0, n); -} -pool$1.mallocUint8 = mallocUint8; -function mallocUint16(n) { - return new Uint16Array(mallocArrayBuffer(2 * n), 0, n); -} -pool$1.mallocUint16 = mallocUint16; -function mallocUint32(n) { - return new Uint32Array(mallocArrayBuffer(4 * n), 0, n); -} -pool$1.mallocUint32 = mallocUint32; -function mallocInt8(n) { - return new Int8Array(mallocArrayBuffer(n), 0, n); -} -pool$1.mallocInt8 = mallocInt8; -function mallocInt16(n) { - return new Int16Array(mallocArrayBuffer(2 * n), 0, n); -} -pool$1.mallocInt16 = mallocInt16; -function mallocInt32(n) { - return new Int32Array(mallocArrayBuffer(4 * n), 0, n); -} -pool$1.mallocInt32 = mallocInt32; -function mallocFloat(n) { - return new Float32Array(mallocArrayBuffer(4 * n), 0, n); -} -pool$1.mallocFloat32 = pool$1.mallocFloat = mallocFloat; -function mallocDouble(n) { - return new Float64Array(mallocArrayBuffer(8 * n), 0, n); -} -pool$1.mallocFloat64 = pool$1.mallocDouble = mallocDouble; -function mallocUint8Clamped(n) { - if (hasUint8C) { - return new Uint8ClampedArray(mallocArrayBuffer(n), 0, n); - } else { - return mallocUint8(n); - } -} -pool$1.mallocUint8Clamped = mallocUint8Clamped; -function mallocBigUint64(n) { - if (hasBigUint64) { - return new BigUint64Array(mallocArrayBuffer(8 * n), 0, n); - } else { - return null; - } -} -pool$1.mallocBigUint64 = mallocBigUint64; -function mallocBigInt64(n) { - if (hasBigInt64) { - return new BigInt64Array(mallocArrayBuffer(8 * n), 0, n); - } else { - return null; - } -} -pool$1.mallocBigInt64 = mallocBigInt64; -function mallocDataView(n) { - return new DataView(mallocArrayBuffer(n), 0, n); -} -pool$1.mallocDataView = mallocDataView; -function mallocBuffer(n) { - n = bits.nextPow2(n); - var log_n = bits.log2(n); - var cache2 = BUFFER[log_n]; - if (cache2.length > 0) { - return cache2.pop(); - } - return new Buffer(n); -} -pool$1.mallocBuffer = mallocBuffer; -pool$1.clearCache = function clearCache() { - for (var i = 0; i < 32; ++i) { - POOL.UINT8[i].length = 0; - POOL.UINT16[i].length = 0; - POOL.UINT32[i].length = 0; - POOL.INT8[i].length = 0; - POOL.INT16[i].length = 0; - POOL.INT32[i].length = 0; - POOL.FLOAT[i].length = 0; - POOL.DOUBLE[i].length = 0; - POOL.BIGUINT64[i].length = 0; - POOL.BIGINT64[i].length = 0; - POOL.UINT8C[i].length = 0; - DATA[i].length = 0; - BUFFER[i].length = 0; - } -}; -var toString = Object.prototype.toString; -var isPlainObj = function(x) { - var prototype; - return toString.call(x) === "[object Object]" && (prototype = Object.getPrototypeOf(x), prototype === null || prototype === Object.getPrototypeOf({})); -}; -var parseUnit$2 = function parseUnit(str2, out) { - if (!out) - out = [0, ""]; - str2 = String(str2); - var num = parseFloat(str2, 10); - out[0] = num; - out[1] = str2.match(/[\d.\-\+]*\s*(.*)/)[1] || ""; - return out; -}; -var parseUnit$1 = parseUnit$2; -var topx = toPX; -var PIXELS_PER_INCH = 96; -function getPropertyInPX(element, prop) { - var parts = parseUnit$1(getComputedStyle(element).getPropertyValue(prop)); - return parts[0] * toPX(parts[1], element); -} -function getSizeBrutal(unit, element) { - var testDIV = document.createElement("div"); - testDIV.style["font-size"] = "128" + unit; - element.appendChild(testDIV); - var size = getPropertyInPX(testDIV, "font-size") / 128; - element.removeChild(testDIV); - return size; -} -function toPX(str2, element) { - element = element || document.body; - str2 = (str2 || "px").trim().toLowerCase(); - if (element === window || element === document) { - element = document.body; - } - switch (str2) { - case "%": - return element.clientHeight / 100; - case "ch": - case "ex": - return getSizeBrutal(str2, element); - case "em": - return getPropertyInPX(element, "font-size"); - case "rem": - return getPropertyInPX(document.body, "font-size"); - case "vw": - return window.innerWidth / 100; - case "vh": - return window.innerHeight / 100; - case "vmin": - return Math.min(window.innerWidth, window.innerHeight) / 100; - case "vmax": - return Math.max(window.innerWidth, window.innerHeight) / 100; - case "in": - return PIXELS_PER_INCH; - case "cm": - return PIXELS_PER_INCH / 2.54; - case "mm": - return PIXELS_PER_INCH / 25.4; - case "pt": - return PIXELS_PER_INCH / 72; - case "pc": - return PIXELS_PER_INCH / 6; - } - return 1; -} -var detectKerning = kerning$1; -var canvas = kerning$1.canvas = document.createElement("canvas"); -var ctx = canvas.getContext("2d"); -var asciiPairs = createPairs([32, 126]); -kerning$1.createPairs = createPairs; -kerning$1.ascii = asciiPairs; -function kerning$1(family, o) { - if (Array.isArray(family)) family = family.join(", "); - var table = {}, pairs, fs = 16, threshold = 0.05; - if (o) { - if (o.length === 2 && typeof o[0] === "number") { - pairs = createPairs(o); - } else if (Array.isArray(o)) { - pairs = o; - } else { - if (o.o) pairs = createPairs(o.o); - else if (o.pairs) pairs = o.pairs; - if (o.fontSize) fs = o.fontSize; - if (o.threshold != null) threshold = o.threshold; - } - } - if (!pairs) pairs = asciiPairs; - ctx.font = fs + "px " + family; - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var width = ctx.measureText(pair[0]).width + ctx.measureText(pair[1]).width; - var kerningWidth = ctx.measureText(pair).width; - if (Math.abs(width - kerningWidth) > fs * threshold) { - var emWidth = (kerningWidth - width) / fs; - table[pair] = emWidth * 1e3; - } - } - return table; -} -function createPairs(range) { - var pairs = []; - for (var i = range[0]; i <= range[1]; i++) { - var leftChar = String.fromCharCode(i); - for (var j = range[0]; j < range[1]; j++) { - var rightChar = String.fromCharCode(j); - var pair = leftChar + rightChar; - pairs.push(pair); - } - } - return pairs; -} -var fontMeasure = measure; -measure.canvas = document.createElement("canvas"); -measure.cache = {}; -function measure(font2, o) { - if (!o) o = {}; - if (typeof font2 === "string" || Array.isArray(font2)) { - o.family = font2; - } - var family = Array.isArray(o.family) ? o.family.join(", ") : o.family; - if (!family) throw Error("`family` must be defined"); - var fs = o.size || o.fontSize || o.em || 48; - var weight = o.weight || o.fontWeight || ""; - var style5 = o.style || o.fontStyle || ""; - var font2 = [style5, weight, fs].join(" ") + "px " + family; - var origin = o.origin || "top"; - if (measure.cache[family]) { - if (fs <= measure.cache[family].em) { - return applyOrigin(measure.cache[family], origin); - } - } - var canvas2 = o.canvas || measure.canvas; - var ctx2 = canvas2.getContext("2d"); - var chars2 = { - upper: o.upper !== void 0 ? o.upper : "H", - lower: o.lower !== void 0 ? o.lower : "x", - descent: o.descent !== void 0 ? o.descent : "p", - ascent: o.ascent !== void 0 ? o.ascent : "h", - tittle: o.tittle !== void 0 ? o.tittle : "i", - overshoot: o.overshoot !== void 0 ? o.overshoot : "O" - }; - var l = Math.ceil(fs * 1.5); - canvas2.height = l; - canvas2.width = l * 0.5; - ctx2.font = font2; - var char = "H"; - var result = { - top: 0 - }; - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillStyle = "black"; - ctx2.fillText(char, 0, 0); - var topPx = firstTop(ctx2.getImageData(0, 0, l, l)); - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "bottom"; - ctx2.fillText(char, 0, l); - var bottomPx = firstTop(ctx2.getImageData(0, 0, l, l)); - result.lineHeight = result.bottom = l - bottomPx + topPx; - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "alphabetic"; - ctx2.fillText(char, 0, l); - var baselinePx = firstTop(ctx2.getImageData(0, 0, l, l)); - var baseline = l - baselinePx - 1 + topPx; - result.baseline = result.alphabetic = baseline; - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "middle"; - ctx2.fillText(char, 0, l * 0.5); - var medianPx = firstTop(ctx2.getImageData(0, 0, l, l)); - result.median = result.middle = l - medianPx - 1 + topPx - l * 0.5; - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "hanging"; - ctx2.fillText(char, 0, l * 0.5); - var hangingPx = firstTop(ctx2.getImageData(0, 0, l, l)); - result.hanging = l - hangingPx - 1 + topPx - l * 0.5; - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "ideographic"; - ctx2.fillText(char, 0, l); - var ideographicPx = firstTop(ctx2.getImageData(0, 0, l, l)); - result.ideographic = l - ideographicPx - 1 + topPx; - if (chars2.upper) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.upper, 0, 0); - result.upper = firstTop(ctx2.getImageData(0, 0, l, l)); - result.capHeight = result.baseline - result.upper; - } - if (chars2.lower) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.lower, 0, 0); - result.lower = firstTop(ctx2.getImageData(0, 0, l, l)); - result.xHeight = result.baseline - result.lower; - } - if (chars2.tittle) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.tittle, 0, 0); - result.tittle = firstTop(ctx2.getImageData(0, 0, l, l)); - } - if (chars2.ascent) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.ascent, 0, 0); - result.ascent = firstTop(ctx2.getImageData(0, 0, l, l)); - } - if (chars2.descent) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.descent, 0, 0); - result.descent = firstBottom(ctx2.getImageData(0, 0, l, l)); - } - if (chars2.overshoot) { - ctx2.clearRect(0, 0, l, l); - ctx2.textBaseline = "top"; - ctx2.fillText(chars2.overshoot, 0, 0); - var overshootPx = firstBottom(ctx2.getImageData(0, 0, l, l)); - result.overshoot = overshootPx - baseline; - } - for (var name2 in result) { - result[name2] /= fs; - } - result.em = fs; - measure.cache[family] = result; - return applyOrigin(result, origin); -} -function applyOrigin(obj, origin) { - var res = {}; - if (typeof origin === "string") origin = obj[origin]; - for (var name2 in obj) { - if (name2 === "em") continue; - res[name2] = obj[name2] - origin; - } - return res; -} -function firstTop(iData) { - var l = iData.height; - var data = iData.data; - for (var i = 3; i < data.length; i += 4) { - if (data[i] !== 0) { - return Math.floor((i - 3) * 0.25 / l); - } - } -} -function firstBottom(iData) { - var l = iData.height; - var data = iData.data; - for (var i = data.length - 1; i > 0; i -= 4) { - if (data[i] !== 0) { - return Math.floor((i - 3) * 0.25 / l); - } - } -} -var Font = cssFont; -var pick2 = pickByAlias; -var createRegl$1 = regl_uncheckedExports; -var createGl = context; -var WeakMap$1 = es6WeakMap; -var rgba$1 = colorNormalize; -var fontAtlas = fontAtlas$1; -var pool = pool$1; -var parseRect = parseRect_1; -var isObj = isPlainObj; -var parseUnit2 = parseUnit$2; -var px = topx; -var kerning = detectKerning; -var extend$1 = index$3.objectAssign; -var metrics = fontMeasure; -var flatten = flattenVertexData_1; -var ref = twiddle; -var nextPow2 = ref.nextPow2; -var shaderCache = new WeakMap$1(); -var isStretchSupported = false; -if (document.body) { - var el = document.body.appendChild(document.createElement("div")); - el.style.font = "italic small-caps bold condensed 16px/2 cursive"; - if (getComputedStyle(el).fontStretch) { - isStretchSupported = true; - } - document.body.removeChild(el); -} -var GlText = function GlText2(o) { - if (isRegl(o)) { - o = { regl: o }; - this.gl = o.regl._gl; - } else { - this.gl = createGl(o); - } - this.shader = shaderCache.get(this.gl); - if (!this.shader) { - this.regl = o.regl || createRegl$1({ gl: this.gl }); - } else { - this.regl = this.shader.regl; - } - this.charBuffer = this.regl.buffer({ type: "uint8", usage: "stream" }); - this.sizeBuffer = this.regl.buffer({ type: "float", usage: "stream" }); - if (!this.shader) { - this.shader = this.createShader(); - shaderCache.set(this.gl, this.shader); - } - this.batch = []; - this.fontSize = []; - this.font = []; - this.fontAtlas = []; - this.draw = this.shader.draw.bind(this); - this.render = function() { - this.regl._refresh(); - this.draw(this.batch); - }; - this.canvas = this.gl.canvas; - this.update(isObj(o) ? o : {}); -}; -GlText.prototype.createShader = function createShader() { - var regl = this.regl; - var draw8 = regl({ - blend: { - enable: true, - color: [0, 0, 0, 1], - func: { - srcRGB: "src alpha", - dstRGB: "one minus src alpha", - srcAlpha: "one minus dst alpha", - dstAlpha: "one" - } - }, - stencil: { enable: false }, - depth: { enable: false }, - count: regl.prop("count"), - offset: regl.prop("offset"), - attributes: { - charOffset: { - offset: 4, - stride: 8, - buffer: regl.this("sizeBuffer") - }, - width: { - offset: 0, - stride: 8, - buffer: regl.this("sizeBuffer") - }, - char: regl.this("charBuffer"), - position: regl.this("position") - }, - uniforms: { - atlasSize: function(c, p) { - return [p.atlas.width, p.atlas.height]; - }, - atlasDim: function(c, p) { - return [p.atlas.cols, p.atlas.rows]; - }, - atlas: function(c, p) { - return p.atlas.texture; - }, - charStep: function(c, p) { - return p.atlas.step; - }, - em: function(c, p) { - return p.atlas.em; - }, - color: regl.prop("color"), - opacity: regl.prop("opacity"), - viewport: regl.this("viewportArray"), - scale: regl.this("scale"), - align: regl.prop("align"), - baseline: regl.prop("baseline"), - translate: regl.this("translate"), - positionOffset: regl.prop("positionOffset") - }, - primitive: "points", - viewport: regl.this("viewport"), - vert: "\n precision highp float;\n attribute float width, charOffset, char;\n attribute vec2 position;\n uniform float fontSize, charStep, em, align, baseline;\n uniform vec4 viewport;\n uniform vec4 color;\n uniform vec2 atlasSize, atlasDim, scale, translate, positionOffset;\n varying vec2 charCoord, charId;\n varying float charWidth;\n varying vec4 fontColor;\n void main () {\n vec2 offset = floor(em * (vec2(align + charOffset, baseline)\n + vec2(positionOffset.x, -positionOffset.y)))\n / (viewport.zw * scale.xy);\n\n vec2 position = (position + translate) * scale;\n position += offset * scale;\n\n charCoord = position * viewport.zw + viewport.xy;\n\n gl_Position = vec4(position * 2. - 1., 0, 1);\n\n gl_PointSize = charStep;\n\n charId.x = mod(char, atlasDim.x);\n charId.y = floor(char / atlasDim.x);\n\n charWidth = width * em;\n\n fontColor = color / 255.;\n }", - frag: "\n precision highp float;\n uniform float fontSize, charStep, opacity;\n uniform vec2 atlasSize;\n uniform vec4 viewport;\n uniform sampler2D atlas;\n varying vec4 fontColor;\n varying vec2 charCoord, charId;\n varying float charWidth;\n\n float lightness(vec4 color) {\n return color.r * 0.299 + color.g * 0.587 + color.b * 0.114;\n }\n\n void main () {\n vec2 uv = gl_FragCoord.xy - charCoord + charStep * .5;\n float halfCharStep = floor(charStep * .5 + .5);\n\n // invert y and shift by 1px (FF expecially needs that)\n uv.y = charStep - uv.y;\n\n // ignore points outside of character bounding box\n float halfCharWidth = ceil(charWidth * .5);\n if (floor(uv.x) > halfCharStep + halfCharWidth ||\n floor(uv.x) < halfCharStep - halfCharWidth) return;\n\n uv += charId * charStep;\n uv = uv / atlasSize;\n\n vec4 color = fontColor;\n vec4 mask = texture2D(atlas, uv);\n\n float maskY = lightness(mask);\n // float colorY = lightness(color);\n color.a *= maskY;\n color.a *= opacity;\n\n // color.a += .1;\n\n // antialiasing, see yiq color space y-channel formula\n // color.rgb += (1. - color.rgb) * (1. - mask.rgb);\n\n gl_FragColor = color;\n }" - }); - var atlas2 = {}; - return { regl, draw: draw8, atlas: atlas2 }; -}; -GlText.prototype.update = function update(o) { - var this$1$1 = this; - if (typeof o === "string") { - o = { text: o }; - } else if (!o) { - return; - } - o = pick2(o, { - position: "position positions coord coords coordinates", - font: "font fontFace fontface typeface cssFont css-font family fontFamily", - fontSize: "fontSize fontsize size font-size", - text: "text texts chars characters value values symbols", - align: "align alignment textAlign textbaseline", - baseline: "baseline textBaseline textbaseline", - direction: "dir direction textDirection", - color: "color colour fill fill-color fillColor textColor textcolor", - kerning: "kerning kern", - range: "range dataBox", - viewport: "vp viewport viewBox viewbox viewPort", - opacity: "opacity alpha transparency visible visibility opaque", - offset: "offset positionOffset padding shift indent indentation" - }, true); - if (o.opacity != null) { - if (Array.isArray(o.opacity)) { - this.opacity = o.opacity.map(function(o2) { - return parseFloat(o2); - }); - } else { - this.opacity = parseFloat(o.opacity); - } - } - if (o.viewport != null) { - this.viewport = parseRect(o.viewport); - this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]; - } - if (this.viewport == null) { - this.viewport = { - x: 0, - y: 0, - width: this.gl.drawingBufferWidth, - height: this.gl.drawingBufferHeight - }; - this.viewportArray = [this.viewport.x, this.viewport.y, this.viewport.width, this.viewport.height]; - } - if (o.kerning != null) { - this.kerning = o.kerning; - } - if (o.offset != null) { - if (typeof o.offset === "number") { - o.offset = [o.offset, 0]; - } - this.positionOffset = flatten(o.offset); - } - if (o.direction) { - this.direction = o.direction; - } - if (o.range) { - this.range = o.range; - this.scale = [1 / (o.range[2] - o.range[0]), 1 / (o.range[3] - o.range[1])]; - this.translate = [-o.range[0], -o.range[1]]; - } - if (o.scale) { - this.scale = o.scale; - } - if (o.translate) { - this.translate = o.translate; - } - if (!this.scale) { - this.scale = [1 / this.viewport.width, 1 / this.viewport.height]; - } - if (!this.translate) { - this.translate = [0, 0]; - } - if (!this.font.length && !o.font) { - o.font = GlText.baseFontSize + "px sans-serif"; - } - var newFont = false, newFontSize = false; - if (o.font) { - (Array.isArray(o.font) ? o.font : [o.font]).forEach(function(font3, i2) { - if (typeof font3 === "string") { - try { - font3 = Font.parse(font3); - } catch (e) { - font3 = Font.parse(GlText.baseFontSize + "px " + font3); - } - } else { - var fontStyle = font3.style; - var fontWeight = font3.weight; - var fontStretch = font3.stretch; - var fontVariant = font3.variant; - font3 = Font.parse(Font.stringify(font3)); - if (fontStyle) font3.style = fontStyle; - if (fontWeight) font3.weight = fontWeight; - if (fontStretch) font3.stretch = fontStretch; - if (fontVariant) font3.variant = fontVariant; - } - var baseString = Font.stringify({ - size: GlText.baseFontSize, - family: font3.family, - stretch: isStretchSupported ? font3.stretch : void 0, - variant: font3.variant, - weight: font3.weight, - style: font3.style - }); - var unit = parseUnit2(font3.size); - var fs = Math.round(unit[0] * px(unit[1])); - if (fs !== this$1$1.fontSize[i2]) { - newFontSize = true; - this$1$1.fontSize[i2] = fs; - } - if (!this$1$1.font[i2] || baseString != this$1$1.font[i2].baseString) { - newFont = true; - this$1$1.font[i2] = GlText.fonts[baseString]; - if (!this$1$1.font[i2]) { - var family = font3.family.join(", "); - var style5 = [font3.style]; - if (font3.style != font3.variant) { - style5.push(font3.variant); - } - if (font3.variant != font3.weight) { - style5.push(font3.weight); - } - if (isStretchSupported && font3.weight != font3.stretch) { - style5.push(font3.stretch); - } - this$1$1.font[i2] = { - baseString, - // typeface - family, - weight: font3.weight, - stretch: font3.stretch, - style: font3.style, - variant: font3.variant, - // widths of characters - width: {}, - // kernin pairs offsets - kerning: {}, - metrics: metrics(family, { - origin: "top", - fontSize: GlText.baseFontSize, - fontStyle: style5.join(" ") - }) - }; - GlText.fonts[baseString] = this$1$1.font[i2]; - } - } - }); - } - if (newFont || newFontSize) { - this.font.forEach(function(font3, i2) { - var fontString = Font.stringify({ - size: this$1$1.fontSize[i2], - family: font3.family, - stretch: isStretchSupported ? font3.stretch : void 0, - variant: font3.variant, - weight: font3.weight, - style: font3.style - }); - this$1$1.fontAtlas[i2] = this$1$1.shader.atlas[fontString]; - if (!this$1$1.fontAtlas[i2]) { - var metrics2 = font3.metrics; - this$1$1.shader.atlas[fontString] = this$1$1.fontAtlas[i2] = { - fontString, - // even step is better for rendered characters - step: Math.ceil(this$1$1.fontSize[i2] * metrics2.bottom * 0.5) * 2, - em: this$1$1.fontSize[i2], - cols: 0, - rows: 0, - height: 0, - width: 0, - chars: [], - ids: {}, - texture: this$1$1.regl.texture() - }; - } - if (o.text == null) { - o.text = this$1$1.text; - } - }); - } - if (typeof o.text === "string" && o.position && o.position.length > 2) { - var textArray = Array(o.position.length * 0.5); - for (var i = 0; i < textArray.length; i++) { - textArray[i] = o.text; - } - o.text = textArray; - } - var newAtlasChars; - if (o.text != null || newFont) { - this.textOffsets = [0]; - if (Array.isArray(o.text)) { - this.count = o.text[0].length; - this.counts = [this.count]; - for (var i$1 = 1; i$1 < o.text.length; i$1++) { - this.textOffsets[i$1] = this.textOffsets[i$1 - 1] + o.text[i$1 - 1].length; - this.count += o.text[i$1].length; - this.counts.push(o.text[i$1].length); - } - this.text = o.text.join(""); - } else { - this.text = o.text; - this.count = this.text.length; - this.counts = [this.count]; - } - newAtlasChars = []; - this.font.forEach(function(font3, idx) { - GlText.atlasContext.font = font3.baseString; - var atlas3 = this$1$1.fontAtlas[idx]; - for (var i2 = 0; i2 < this$1$1.text.length; i2++) { - var char2 = this$1$1.text.charAt(i2); - if (atlas3.ids[char2] == null) { - atlas3.ids[char2] = atlas3.chars.length; - atlas3.chars.push(char2); - newAtlasChars.push(char2); - } - if (font3.width[char2] == null) { - font3.width[char2] = GlText.atlasContext.measureText(char2).width / GlText.baseFontSize; - if (this$1$1.kerning) { - var pairs = []; - for (var baseChar in font3.width) { - pairs.push(baseChar + char2, char2 + baseChar); - } - extend$1(font3.kerning, kerning(font3.family, { - pairs - })); - } - } - } - }); - } - if (o.position) { - if (o.position.length > 2) { - var flat = !o.position[0].length; - var positionData = pool.mallocFloat(this.count * 2); - for (var i$2 = 0, ptr = 0; i$2 < this.counts.length; i$2++) { - var count2 = this.counts[i$2]; - if (flat) { - for (var j = 0; j < count2; j++) { - positionData[ptr++] = o.position[i$2 * 2]; - positionData[ptr++] = o.position[i$2 * 2 + 1]; - } - } else { - for (var j$1 = 0; j$1 < count2; j$1++) { - positionData[ptr++] = o.position[i$2][0]; - positionData[ptr++] = o.position[i$2][1]; - } - } - } - if (this.position.call) { - this.position({ - type: "float", - data: positionData - }); - } else { - this.position = this.regl.buffer({ - type: "float", - data: positionData - }); - } - pool.freeFloat(positionData); - } else { - if (this.position.destroy) { - this.position.destroy(); - } - this.position = { - constant: o.position - }; - } - } - if (o.text || newFont) { - var charIds = pool.mallocUint8(this.count); - var sizeData = pool.mallocFloat(this.count * 2); - this.textWidth = []; - for (var i$3 = 0, ptr$1 = 0; i$3 < this.counts.length; i$3++) { - var count$1 = this.counts[i$3]; - var font2 = this.font[i$3] || this.font[0]; - var atlas2 = this.fontAtlas[i$3] || this.fontAtlas[0]; - for (var j$2 = 0; j$2 < count$1; j$2++) { - var char = this.text.charAt(ptr$1); - var prevChar = this.text.charAt(ptr$1 - 1); - charIds[ptr$1] = atlas2.ids[char]; - sizeData[ptr$1 * 2] = font2.width[char]; - if (j$2) { - var prevWidth = sizeData[ptr$1 * 2 - 2]; - var currWidth = sizeData[ptr$1 * 2]; - var prevOffset = sizeData[ptr$1 * 2 - 1]; - var offset = prevOffset + prevWidth * 0.5 + currWidth * 0.5; - if (this.kerning) { - var kerning$12 = font2.kerning[prevChar + char]; - if (kerning$12) { - offset += kerning$12 * 1e-3; - } - } - sizeData[ptr$1 * 2 + 1] = offset; - } else { - sizeData[ptr$1 * 2 + 1] = sizeData[ptr$1 * 2] * 0.5; - } - ptr$1++; - } - this.textWidth.push( - !sizeData.length ? 0 : ( - // last offset + half last width - sizeData[ptr$1 * 2 - 2] * 0.5 + sizeData[ptr$1 * 2 - 1] - ) - ); - } - if (!o.align) { - o.align = this.align; - } - this.charBuffer({ data: charIds, type: "uint8", usage: "stream" }); - this.sizeBuffer({ data: sizeData, type: "float", usage: "stream" }); - pool.freeUint8(charIds); - pool.freeFloat(sizeData); - if (newAtlasChars.length) { - this.font.forEach(function(font3, i2) { - var atlas3 = this$1$1.fontAtlas[i2]; - var step = atlas3.step; - var maxCols = Math.floor(GlText.maxAtlasSize / step); - var cols = Math.min(maxCols, atlas3.chars.length); - var rows = Math.ceil(atlas3.chars.length / cols); - var atlasWidth = nextPow2(cols * step); - var atlasHeight = nextPow2(rows * step); - atlas3.width = atlasWidth; - atlas3.height = atlasHeight; - atlas3.rows = rows; - atlas3.cols = cols; - if (!atlas3.em) { - return; - } - atlas3.texture({ - data: fontAtlas({ - canvas: GlText.atlasCanvas, - font: atlas3.fontString, - chars: atlas3.chars, - shape: [atlasWidth, atlasHeight], - step: [step, step] - }) - }); - }); - } - } - if (o.align) { - this.align = o.align; - this.alignOffset = this.textWidth.map(function(textWidth, i2) { - var align3 = !Array.isArray(this$1$1.align) ? this$1$1.align : this$1$1.align.length > 1 ? this$1$1.align[i2] : this$1$1.align[0]; - if (typeof align3 === "number") { - return align3; - } - switch (align3) { - case "right": - case "end": - return -textWidth; - case "center": - case "centre": - case "middle": - return -textWidth * 0.5; - } - return 0; - }); - } - if (this.baseline == null && o.baseline == null) { - o.baseline = 0; - } - if (o.baseline != null) { - this.baseline = o.baseline; - if (!Array.isArray(this.baseline)) { - this.baseline = [this.baseline]; - } - this.baselineOffset = this.baseline.map(function(baseline, i2) { - var m = (this$1$1.font[i2] || this$1$1.font[0]).metrics; - var base = 0; - base += m.bottom * 0.5; - if (typeof baseline === "number") { - base += baseline - m.baseline; - } else { - base += -m[baseline]; - } - base *= -1; - return base; - }); - } - if (o.color != null) { - if (!o.color) { - o.color = "transparent"; - } - if (typeof o.color === "string" || !isNaN(o.color)) { - this.color = rgba$1(o.color, "uint8"); - } else { - var colorData; - if (typeof o.color[0] === "number" && o.color.length > this.counts.length) { - var l = o.color.length; - colorData = pool.mallocUint8(l); - var sub = (o.color.subarray || o.color.slice).bind(o.color); - for (var i$4 = 0; i$4 < l; i$4 += 4) { - colorData.set(rgba$1(sub(i$4, i$4 + 4), "uint8"), i$4); - } - } else { - var l$1 = o.color.length; - colorData = pool.mallocUint8(l$1 * 4); - for (var i$5 = 0; i$5 < l$1; i$5++) { - colorData.set(rgba$1(o.color[i$5] || 0, "uint8"), i$5 * 4); - } - } - this.color = colorData; - } - } - if (o.position || o.text || o.color || o.baseline || o.align || o.font || o.offset || o.opacity) { - var isBatch = this.color.length > 4 || this.baselineOffset.length > 1 || this.align && this.align.length > 1 || this.fontAtlas.length > 1 || this.positionOffset.length > 2; - if (isBatch) { - var length2 = Math.max( - this.position.length * 0.5 || 0, - this.color.length * 0.25 || 0, - this.baselineOffset.length || 0, - this.alignOffset.length || 0, - this.font.length || 0, - this.opacity.length || 0, - this.positionOffset.length * 0.5 || 0 - ); - this.batch = Array(length2); - for (var i$6 = 0; i$6 < this.batch.length; i$6++) { - this.batch[i$6] = { - count: this.counts.length > 1 ? this.counts[i$6] : this.counts[0], - offset: this.textOffsets.length > 1 ? this.textOffsets[i$6] : this.textOffsets[0], - color: !this.color ? [0, 0, 0, 255] : this.color.length <= 4 ? this.color : this.color.subarray(i$6 * 4, i$6 * 4 + 4), - opacity: Array.isArray(this.opacity) ? this.opacity[i$6] : this.opacity, - baseline: this.baselineOffset[i$6] != null ? this.baselineOffset[i$6] : this.baselineOffset[0], - align: !this.align ? 0 : this.alignOffset[i$6] != null ? this.alignOffset[i$6] : this.alignOffset[0], - atlas: this.fontAtlas[i$6] || this.fontAtlas[0], - positionOffset: this.positionOffset.length > 2 ? this.positionOffset.subarray(i$6 * 2, i$6 * 2 + 2) : this.positionOffset - }; - } - } else { - if (this.count) { - this.batch = [{ - count: this.count, - offset: 0, - color: this.color || [0, 0, 0, 255], - opacity: Array.isArray(this.opacity) ? this.opacity[0] : this.opacity, - baseline: this.baselineOffset[0], - align: this.alignOffset ? this.alignOffset[0] : 0, - atlas: this.fontAtlas[0], - positionOffset: this.positionOffset - }]; - } else { - this.batch = []; - } - } - } -}; -GlText.prototype.destroy = function destroy() { -}; -GlText.prototype.kerning = true; -GlText.prototype.position = { constant: new Float32Array(2) }; -GlText.prototype.translate = null; -GlText.prototype.scale = null; -GlText.prototype.font = null; -GlText.prototype.text = ""; -GlText.prototype.positionOffset = [0, 0]; -GlText.prototype.opacity = 1; -GlText.prototype.color = new Uint8Array([0, 0, 0, 255]); -GlText.prototype.alignOffset = [0, 0]; -GlText.maxAtlasSize = 1024; -GlText.atlasCanvas = document.createElement("canvas"); -GlText.atlasContext = GlText.atlasCanvas.getContext("2d", { alpha: false }); -GlText.baseFontSize = 64; -GlText.fonts = {}; -function isRegl(o) { - return typeof o === "function" && o._gl && o.prop && o.texture && o.buffer; -} -var dist = GlText; -var Color$5 = colorExports; -var noop2 = function() { -}; -var show_no_webgl_msg = function showNoWebGlMsg(scene) { - for (var prop in scene) { - if (typeof scene[prop] === "function") scene[prop] = noop2; - } - scene.destroy = function() { - scene.container.parentNode.removeChild(scene.container); - }; - var div = document.createElement("div"); - div.className = "no-webgl"; - div.style.cursor = "pointer"; - div.style.fontSize = "24px"; - div.style.color = Color$5.defaults[0]; - div.style.position = "absolute"; - div.style.left = div.style.top = "0px"; - div.style.width = div.style.height = "100%"; - div.style["background-color"] = Color$5.lightLine; - div.style["z-index"] = 30; - var p = document.createElement("p"); - p.textContent = "WebGL is not supported by your browser - visit https://get.webgl.org for more info"; - p.style.position = "relative"; - p.style.top = "50%"; - p.style.left = "50%"; - p.style.height = "30%"; - p.style.width = "50%"; - p.style.margin = "-15% 0 0 -25%"; - div.appendChild(p); - scene.container.appendChild(div); - scene.container.style.background = "#FFFFFF"; - scene.container.onclick = function() { - window.open("https://get.webgl.org"); - }; - return false; -}; -var showNoWebGlMsg2 = show_no_webgl_msg; -var createRegl = regl_uncheckedExports; -var prepare_regl = function prepareRegl(gd, extensions, reglPrecompiled2) { - var fullLayout = gd._fullLayout; - var success = true; - fullLayout._glcanvas.each(function(d) { - if (d.regl) { - d.regl.preloadCachedCode(reglPrecompiled2); - return; - } - if (d.pick && !fullLayout._has("parcoords")) return; - try { - d.regl = createRegl({ - canvas: this, - attributes: { - antialias: !d.pick, - preserveDrawingBuffer: true - }, - pixelRatio: gd._context.plotGlPixelRatio || index$3.commonjsGlobal.devicePixelRatio, - extensions: extensions || [], - cachedCode: reglPrecompiled2 || {} - }); - } catch (e) { - success = false; - } - if (!d.regl) success = false; - if (success) { - this.addEventListener("webglcontextlost", function(event) { - if (gd && gd.emit) { - gd.emit("plotly_webglcontextlost", { - event, - layer: d.key - }); - } - }, false); - } - }); - if (!success) { - showNoWebGlMsg2({ container: fullLayout._glcontainer.node() }); - } - return success; -}; -var createScatter = bundle; -var createLine = reglLine2d; -var createError = reglError2d; -var Text = dist; -var Lib$8 = libExports; -var selectMode = helpers$B.selectMode; -var prepareRegl2 = prepare_regl; -var subTypes = subtypes$3; -var linkTraces2 = link_traces; -var styleTextSelection = edit_style.styleTextSelection; -var reglPrecompiled = {}; -function getViewport(fullLayout, xaxis, yaxis, plotGlPixelRatio) { - var gs = fullLayout._size; - var width = fullLayout.width * plotGlPixelRatio; - var height = fullLayout.height * plotGlPixelRatio; - var l = gs.l * plotGlPixelRatio; - var b = gs.b * plotGlPixelRatio; - var r = gs.r * plotGlPixelRatio; - var t = gs.t * plotGlPixelRatio; - var w = gs.w * plotGlPixelRatio; - var h = gs.h * plotGlPixelRatio; - return [ - l + xaxis.domain[0] * w, - b + yaxis.domain[0] * h, - width - r - (1 - xaxis.domain[1]) * w, - height - t - (1 - yaxis.domain[1]) * h - ]; -} -var exports$1 = plot$2.exports = function plot3(gd, subplot, cdata) { - if (!cdata.length) return; - var fullLayout = gd._fullLayout; - var scene = subplot._scene; - var xaxis = subplot.xaxis; - var yaxis = subplot.yaxis; - var i, j; - if (!scene) return; - var success = prepareRegl2(gd, ["ANGLE_instanced_arrays", "OES_element_index_uint"], reglPrecompiled); - if (!success) { - scene.init(); - return; - } - var count2 = scene.count; - var regl = fullLayout._glcanvas.data()[0].regl; - linkTraces2(gd, subplot, cdata); - if (scene.dirty) { - if ((scene.line2d || scene.error2d) && !(scene.scatter2d || scene.fill2d || scene.glText)) { - regl.clear({}); - } - if (scene.error2d === true) { - scene.error2d = createError(regl); - } - if (scene.line2d === true) { - scene.line2d = createLine(regl); - } - if (scene.scatter2d === true) { - scene.scatter2d = createScatter(regl); - } - if (scene.fill2d === true) { - scene.fill2d = createLine(regl); - } - if (scene.glText === true) { - scene.glText = new Array(count2); - for (i = 0; i < count2; i++) { - scene.glText[i] = new Text(regl); - } - } - if (scene.glText) { - if (count2 > scene.glText.length) { - var textsToAdd = count2 - scene.glText.length; - for (i = 0; i < textsToAdd; i++) { - scene.glText.push(new Text(regl)); - } - } else if (count2 < scene.glText.length) { - var textsToRemove = scene.glText.length - count2; - var removedTexts = scene.glText.splice(count2, textsToRemove); - removedTexts.forEach(function(text) { - text.destroy(); - }); - } - for (i = 0; i < count2; i++) { - scene.glText[i].update(scene.textOptions[i]); - } - } - if (scene.line2d) { - scene.line2d.update(scene.lineOptions); - scene.lineOptions = scene.lineOptions.map(function(lineOptions) { - if (lineOptions && lineOptions.positions) { - var srcPos = lineOptions.positions; - var firstptdef = 0; - while (firstptdef < srcPos.length && (isNaN(srcPos[firstptdef]) || isNaN(srcPos[firstptdef + 1]))) { - firstptdef += 2; - } - var lastptdef = srcPos.length - 2; - while (lastptdef > firstptdef && (isNaN(srcPos[lastptdef]) || isNaN(srcPos[lastptdef + 1]))) { - lastptdef -= 2; - } - lineOptions.positions = srcPos.slice(firstptdef, lastptdef + 2); - } - return lineOptions; - }); - scene.line2d.update(scene.lineOptions); - } - if (scene.error2d) { - var errorBatch = (scene.errorXOptions || []).concat(scene.errorYOptions || []); - scene.error2d.update(errorBatch); - } - if (scene.scatter2d) { - scene.scatter2d.update(scene.markerOptions); - } - scene.fillOrder = Lib$8.repeat(null, count2); - if (scene.fill2d) { - scene.fillOptions = scene.fillOptions.map(function(fillOptions, i2) { - var cdscatter = cdata[i2]; - if (!fillOptions || !cdscatter || !cdscatter[0] || !cdscatter[0].trace) return; - var cd = cdscatter[0]; - var trace2 = cd.trace; - var stash2 = cd.t; - var lineOptions = scene.lineOptions[i2]; - var last, j2; - var fillData = []; - if (trace2._ownfill) fillData.push(i2); - if (trace2._nexttrace) fillData.push(i2 + 1); - if (fillData.length) scene.fillOrder[i2] = fillData; - var pos = []; - var srcPos = lineOptions && lineOptions.positions || stash2.positions; - var firstptdef, lastptdef; - if (trace2.fill === "tozeroy") { - firstptdef = 0; - while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef + 1])) { - firstptdef += 2; - } - lastptdef = srcPos.length - 2; - while (lastptdef > firstptdef && isNaN(srcPos[lastptdef + 1])) { - lastptdef -= 2; - } - if (srcPos[firstptdef + 1] !== 0) { - pos = [srcPos[firstptdef], 0]; - } - pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2)); - if (srcPos[lastptdef + 1] !== 0) { - pos = pos.concat([srcPos[lastptdef], 0]); - } - } else if (trace2.fill === "tozerox") { - firstptdef = 0; - while (firstptdef < srcPos.length && isNaN(srcPos[firstptdef])) { - firstptdef += 2; - } - lastptdef = srcPos.length - 2; - while (lastptdef > firstptdef && isNaN(srcPos[lastptdef])) { - lastptdef -= 2; - } - if (srcPos[firstptdef] !== 0) { - pos = [0, srcPos[firstptdef + 1]]; - } - pos = pos.concat(srcPos.slice(firstptdef, lastptdef + 2)); - if (srcPos[lastptdef] !== 0) { - pos = pos.concat([0, srcPos[lastptdef + 1]]); - } - } else if (trace2.fill === "toself" || trace2.fill === "tonext") { - pos = []; - last = 0; - fillOptions.splitNull = true; - for (j2 = 0; j2 < srcPos.length; j2 += 2) { - if (isNaN(srcPos[j2]) || isNaN(srcPos[j2 + 1])) { - pos = pos.concat(srcPos.slice(last, j2)); - pos.push(srcPos[last], srcPos[last + 1]); - pos.push(null, null); - last = j2 + 2; - } - } - pos = pos.concat(srcPos.slice(last)); - if (last) { - pos.push(srcPos[last], srcPos[last + 1]); - } - } else { - var nextTrace = trace2._nexttrace; - if (nextTrace) { - var nextOptions = scene.lineOptions[i2 + 1]; - if (nextOptions) { - var nextPos = nextOptions.positions; - if (trace2.fill === "tonexty") { - pos = srcPos.slice(); - for (i2 = Math.floor(nextPos.length / 2); i2--; ) { - var xx = nextPos[i2 * 2]; - var yy = nextPos[i2 * 2 + 1]; - if (isNaN(xx) || isNaN(yy)) continue; - pos.push(xx, yy); - } - fillOptions.fill = nextTrace.fillcolor; - } - } - } - } - if (trace2._prevtrace && trace2._prevtrace.fill === "tonext") { - var prevLinePos = scene.lineOptions[i2 - 1].positions; - var offset = pos.length / 2; - last = offset; - var hole = [last]; - for (j2 = 0; j2 < prevLinePos.length; j2 += 2) { - if (isNaN(prevLinePos[j2]) || isNaN(prevLinePos[j2 + 1])) { - hole.push(j2 / 2 + offset + 1); - last = j2 + 2; - } - } - pos = pos.concat(prevLinePos); - fillOptions.hole = hole; - } - fillOptions.fillmode = trace2.fill; - fillOptions.opacity = trace2.opacity; - fillOptions.positions = pos; - return fillOptions; - }); - scene.fill2d.update(scene.fillOptions); - } - } - var dragmode = fullLayout.dragmode; - var isSelectMode = selectMode(dragmode); - var clickSelectEnabled = fullLayout.clickmode.indexOf("select") > -1; - for (i = 0; i < count2; i++) { - var cd0 = cdata[i][0]; - var trace = cd0.trace; - var stash = cd0.t; - var index2 = stash.index; - var len = trace._length; - var x = stash.x; - var y = stash.y; - if (trace.selectedpoints || isSelectMode || clickSelectEnabled) { - if (!isSelectMode) isSelectMode = true; - if (trace.selectedpoints) { - var selPts = scene.selectBatch[index2] = Lib$8.selIndices2selPoints(trace); - var selDict = {}; - for (j = 0; j < selPts.length; j++) { - selDict[selPts[j]] = 1; - } - var unselPts = []; - for (j = 0; j < len; j++) { - if (!selDict[j]) unselPts.push(j); - } - scene.unselectBatch[index2] = unselPts; - } - var xpx = stash.xpx = new Array(len); - var ypx = stash.ypx = new Array(len); - for (j = 0; j < len; j++) { - xpx[j] = xaxis.c2p(x[j]); - ypx[j] = yaxis.c2p(y[j]); - } - } else { - stash.xpx = stash.ypx = null; - } - } - if (isSelectMode) { - if (!scene.select2d) { - scene.select2d = createScatter(fullLayout._glcanvas.data()[1].regl); - } - if (scene.scatter2d) { - var unselOpts = new Array(count2); - for (i = 0; i < count2; i++) { - unselOpts[i] = scene.selectBatch[i].length || scene.unselectBatch[i].length ? scene.markerUnselectedOptions[i] : {}; - } - scene.scatter2d.update(unselOpts); - } - if (scene.select2d) { - scene.select2d.update(scene.markerOptions); - scene.select2d.update(scene.markerSelectedOptions); - } - if (scene.glText) { - cdata.forEach(function(cdscatter) { - var trace2 = ((cdscatter || [])[0] || {}).trace || {}; - if (subTypes.hasText(trace2)) { - styleTextSelection(cdscatter); - } - }); - } - } else { - if (scene.scatter2d) { - scene.scatter2d.update(scene.markerOptions); - } - } - var vpRange0 = { - viewport: getViewport(fullLayout, xaxis, yaxis, gd._context.plotGlPixelRatio), - // TODO do we need those fallbacks? - range: [ - (xaxis._rl || xaxis.range)[0], - (yaxis._rl || yaxis.range)[0], - (xaxis._rl || xaxis.range)[1], - (yaxis._rl || yaxis.range)[1] - ] - }; - var vpRange = Lib$8.repeat(vpRange0, scene.count); - if (scene.fill2d) { - scene.fill2d.update(vpRange); - } - if (scene.line2d) { - scene.line2d.update(vpRange); - } - if (scene.error2d) { - scene.error2d.update(vpRange.concat(vpRange)); - } - if (scene.scatter2d) { - scene.scatter2d.update(vpRange); - } - if (scene.select2d) { - scene.select2d.update(vpRange); - } - if (scene.glText) { - scene.glText.forEach(function(text) { - text.update(vpRange0); - }); - } -}; -exports$1.reglPrecompiled = reglPrecompiled; -var plotExports = plot$2.exports; -var index$2 = base_index; -index$2.plot = plotExports; -var scattergl$2 = index$2; -var scattergl = scattergl$2; -const scattergl$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(scattergl); -var base_plot = {}; -(function(exports2) { - var plots2 = plotsExports; - exports2.name = "treemap"; - exports2.plot = function(gd, traces, transitionOpts, makeOnCompleteCallback) { - plots2.plotBasePlot(exports2.name, gd, traces, transitionOpts, makeOnCompleteCallback); - }; - exports2.clean = function(newFullData, newFullLayout, oldFullData, oldFullLayout) { - plots2.cleanBasePlot(exports2.name, newFullData, newFullLayout, oldFullData, oldFullLayout); - }; -})(base_plot); -var constants$6 = { - CLICK_TRANSITION_TIME: 750, - CLICK_TRANSITION_EASING: "linear", - eventDataKeys: [ - // string - "currentPath", - "root", - "entry", - // no need to add 'parent' here - // percentages i.e. ratios - "percentRoot", - "percentEntry", - "percentParent" - ] -}; -var baseAttrs = attributes$O; -var hovertemplateAttrs$1 = template_attributes.hovertemplateAttrs; -var texttemplateAttrs$1 = template_attributes.texttemplateAttrs; -var colorScaleAttrs$1 = attributes$I; -var domainAttrs$1 = domain.attributes; -var pieAttrs$1 = attributes$8; -var constants$5 = constants$6; -var extendFlat$1 = extend$5.extendFlat; -var pattern$1 = attributes$M.pattern; -var attributes$2 = { - labels: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the labels of each of the sectors." - ].join(" ") - }, - parents: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the parent sectors for each of the sectors.", - "Empty string items '' are understood to reference", - "the root node in the hierarchy.", - 'If `ids` is filled, `parents` items are understood to be "ids" themselves.', - "When `ids` is not set, plotly attempts to find matching items in `labels`,", - "but beware they must be unique." - ].join(" ") - }, - values: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the values associated with each of the sectors.", - "Use with `branchvalues` to determine how the values are summed." - ].join(" ") - }, - branchvalues: { - valType: "enumerated", - values: ["remainder", "total"], - dflt: "remainder", - editType: "calc", - description: [ - "Determines how the items in `values` are summed.", - "When set to *total*, items in `values` are taken to be value of all its descendants.", - "When set to *remainder*, items in `values` corresponding to the root and the branches sectors", - "are taken to be the extra part not part of the sum of the values at their leaves." - ].join(" ") - }, - count: { - valType: "flaglist", - flags: [ - "branches", - "leaves" - ], - dflt: "leaves", - editType: "calc", - description: [ - "Determines default for `values` when it is not provided,", - "by inferring a 1 for each of the *leaves* and/or *branches*, otherwise 0." - ].join(" ") - }, - level: { - valType: "any", - editType: "plot", - anim: true, - description: [ - "Sets the level from which this trace hierarchy is rendered.", - "Set `level` to `''` to start from the root node in the hierarchy.", - 'Must be an "id" if `ids` is filled in, otherwise plotly attempts to find a matching', - "item in `labels`." - ].join(" ") - }, - maxdepth: { - valType: "integer", - editType: "plot", - dflt: -1, - description: [ - "Sets the number of rendered sectors from any given `level`.", - "Set `maxdepth` to *-1* to render all the levels in the hierarchy." - ].join(" ") - }, - marker: extendFlat$1( - { - colors: { - valType: "data_array", - editType: "calc", - description: [ - "Sets the color of each sector of this trace.", - "If not specified, the default trace color set is used", - "to pick the sector colors." - ].join(" ") - }, - // colorinheritance: { - // valType: 'enumerated', - // values: ['per-branch', 'per-label', false] - // }, - line: { - color: extendFlat$1({}, pieAttrs$1.marker.line.color, { - dflt: null, - description: [ - "Sets the color of the line enclosing each sector.", - "Defaults to the `paper_bgcolor` value." - ].join(" ") - }), - width: extendFlat$1({}, pieAttrs$1.marker.line.width, { dflt: 1 }), - editType: "calc" - }, - pattern: pattern$1, - editType: "calc" - }, - colorScaleAttrs$1("marker", { - colorAttr: "colors", - anim: false - // TODO: set to anim: true? - }) - ), - text: pieAttrs$1.text, - textinfo: { - valType: "flaglist", - flags: [ - "label", - "text", - "value", - "current path", - "percent root", - "percent entry", - "percent parent" - ], - extras: ["none"], - editType: "plot", - description: [ - "Determines which trace information appear on the graph." - ].join(" ") - }, - // TODO: incorporate `label` and `value` in the eventData - texttemplate: texttemplateAttrs$1({ editType: "plot" }, { - keys: constants$5.eventDataKeys.concat(["label", "value"]) - }), - hovertext: pieAttrs$1.hovertext, - hoverinfo: extendFlat$1({}, baseAttrs.hoverinfo, { - flags: [ - "label", - "text", - "value", - "name", - "current path", - "percent root", - "percent entry", - "percent parent" - ], - dflt: "label+text+value+name" - }), - hovertemplate: hovertemplateAttrs$1({}, { - keys: constants$5.eventDataKeys - }), - textfont: pieAttrs$1.textfont, - insidetextorientation: pieAttrs$1.insidetextorientation, - insidetextfont: pieAttrs$1.insidetextfont, - outsidetextfont: extendFlat$1({}, pieAttrs$1.outsidetextfont, { - description: [ - "Sets the font used for `textinfo` lying outside the sector.", - "This option refers to the root of the hierarchy", - "presented at the center of a sunburst graph.", - "Please note that if a hierarchy has multiple root nodes,", - "this option won't have any effect and `insidetextfont` would be used." - ].join(" ") - }), - sort: pieAttrs$1.sort, - root: { - color: { - valType: "color", - editType: "calc", - dflt: "rgba(0,0,0,0)", - description: [ - "sets the color of the root node for a sunburst/treemap/icicle trace.", - "this has no effect when a colorscale is used to set the markers." - ].join(" ") - }, - editType: "calc" - }, - domain: domainAttrs$1({ name: "sunburst", trace: true, editType: "calc" }) -}; -var constants$4 = { - CLICK_TRANSITION_TIME: 750, - CLICK_TRANSITION_EASING: "poly", - eventDataKeys: [ - // string - "currentPath", - "root", - "entry", - // no need to add 'parent' here - // percentages i.e. ratios - "percentRoot", - "percentEntry", - "percentParent" - ], - gapWithPathbar: 1 - // i.e. one pixel -}; -var hovertemplateAttrs = template_attributes.hovertemplateAttrs; -var texttemplateAttrs = template_attributes.texttemplateAttrs; -var colorScaleAttrs2 = attributes$I; -var domainAttrs = domain.attributes; -var pieAttrs = attributes$8; -var sunburstAttrs = attributes$2; -var constants$3 = constants$4; -var extendFlat = extend$5.extendFlat; -var pattern = attributes$M.pattern; -var attributes$1 = { - labels: sunburstAttrs.labels, - parents: sunburstAttrs.parents, - values: sunburstAttrs.values, - branchvalues: sunburstAttrs.branchvalues, - count: sunburstAttrs.count, - level: sunburstAttrs.level, - maxdepth: sunburstAttrs.maxdepth, - tiling: { - packing: { - valType: "enumerated", - values: [ - "squarify", - "binary", - "dice", - "slice", - "slice-dice", - "dice-slice" - ], - dflt: "squarify", - editType: "plot", - description: [ - "Determines d3 treemap solver.", - "For more info please refer to https://github.com/d3/d3-hierarchy#treemap-tiling" - ].join(" ") - }, - squarifyratio: { - valType: "number", - min: 1, - dflt: 1, - editType: "plot", - description: [ - "When using *squarify* `packing` algorithm, according to https://github.com/d3/d3-hierarchy/blob/v3.1.1/README.md#squarify_ratio", - "this option specifies the desired aspect ratio of the generated rectangles.", - "The ratio must be specified as a number greater than or equal to one.", - "Note that the orientation of the generated rectangles (tall or wide)", - "is not implied by the ratio; for example, a ratio of two will attempt", - "to produce a mixture of rectangles whose width:height ratio is either 2:1 or 1:2.", - "When using *squarify*, unlike d3 which uses the Golden Ratio i.e. 1.618034,", - "Plotly applies 1 to increase squares in treemap layouts." - ].join(" ") - }, - flip: { - valType: "flaglist", - flags: [ - "x", - "y" - ], - dflt: "", - editType: "plot", - description: [ - "Determines if the positions obtained from solver are flipped on each axis." - ].join(" ") - }, - pad: { - valType: "number", - min: 0, - dflt: 3, - editType: "plot", - description: [ - "Sets the inner padding (in px)." - ].join(" ") - }, - editType: "calc" - }, - marker: extendFlat( - { - pad: { - t: { - valType: "number", - min: 0, - editType: "plot", - description: [ - "Sets the padding form the top (in px)." - ].join(" ") - }, - l: { - valType: "number", - min: 0, - editType: "plot", - description: [ - "Sets the padding form the left (in px)." - ].join(" ") - }, - r: { - valType: "number", - min: 0, - editType: "plot", - description: [ - "Sets the padding form the right (in px)." - ].join(" ") - }, - b: { - valType: "number", - min: 0, - editType: "plot", - description: [ - "Sets the padding form the bottom (in px)." - ].join(" ") - }, - editType: "calc" - }, - colors: sunburstAttrs.marker.colors, - pattern, - depthfade: { - valType: "enumerated", - values: [true, false, "reversed"], - editType: "style", - description: [ - "Determines if the sector colors are faded towards", - "the background from the leaves up to the headers.", - "This option is unavailable when a `colorscale` is present,", - "defaults to false when `marker.colors` is set,", - "but otherwise defaults to true.", - "When set to *reversed*, the fading direction is inverted,", - "that is the top elements within hierarchy are drawn with fully saturated colors", - "while the leaves are faded towards the background color." - ].join(" ") - }, - line: sunburstAttrs.marker.line, - cornerradius: { - valType: "number", - min: 0, - dflt: 0, - editType: "plot", - description: [ - "Sets the maximum rounding of corners (in px)." - ].join(" ") - }, - editType: "calc" - }, - colorScaleAttrs2("marker", { - colorAttr: "colors", - anim: false - // TODO: set to anim: true? - }) - ), - pathbar: { - visible: { - valType: "boolean", - dflt: true, - editType: "plot", - description: [ - "Determines if the path bar is drawn", - "i.e. outside the trace `domain` and", - "with one pixel gap." - ].join(" ") - }, - side: { - valType: "enumerated", - values: [ - "top", - "bottom" - ], - dflt: "top", - editType: "plot", - description: [ - "Determines on which side of the the treemap the", - "`pathbar` should be presented." - ].join(" ") - }, - edgeshape: { - valType: "enumerated", - values: [ - ">", - "<", - "|", - "/", - "\\" - ], - dflt: ">", - editType: "plot", - description: [ - "Determines which shape is used for edges between `barpath` labels." - ].join(" ") - }, - thickness: { - valType: "number", - min: 12, - editType: "plot", - description: [ - "Sets the thickness of `pathbar` (in px). If not specified the `pathbar.textfont.size` is used", - "with 3 pixles extra padding on each side." - ].join(" ") - }, - textfont: extendFlat({}, pieAttrs.textfont, { - description: "Sets the font used inside `pathbar`." - }), - editType: "calc" - }, - text: pieAttrs.text, - textinfo: sunburstAttrs.textinfo, - // TODO: incorporate `label` and `value` in the eventData - texttemplate: texttemplateAttrs({ editType: "plot" }, { - keys: constants$3.eventDataKeys.concat(["label", "value"]) - }), - hovertext: pieAttrs.hovertext, - hoverinfo: sunburstAttrs.hoverinfo, - hovertemplate: hovertemplateAttrs({}, { - keys: constants$3.eventDataKeys - }), - textfont: pieAttrs.textfont, - insidetextfont: pieAttrs.insidetextfont, - outsidetextfont: extendFlat({}, pieAttrs.outsidetextfont, { - description: [ - "Sets the font used for `textinfo` lying outside the sector.", - "This option refers to the root of the hierarchy", - "presented on top left corner of a treemap graph.", - "Please note that if a hierarchy has multiple root nodes,", - "this option won't have any effect and `insidetextfont` would be used." - ].join(" ") - }), - textposition: { - valType: "enumerated", - values: [ - "top left", - "top center", - "top right", - "middle left", - "middle center", - "middle right", - "bottom left", - "bottom center", - "bottom right" - ], - dflt: "top left", - editType: "plot", - description: [ - "Sets the positions of the `text` elements." - ].join(" ") - }, - sort: pieAttrs.sort, - root: sunburstAttrs.root, - domain: domainAttrs({ name: "treemap", trace: true, editType: "calc" }) -}; -var layout_attributes = { - treemapcolorway: { - valType: "colorlist", - editType: "calc", - description: [ - "Sets the default treemap slice colors. Defaults to the main", - "`colorway` used for trace colors. If you specify a new", - "list here it can still be extended with lighter and darker", - "colors, see `extendtreemapcolors`." - ].join(" ") - }, - extendtreemapcolors: { - valType: "boolean", - dflt: true, - editType: "calc", - description: [ - "If `true`, the treemap slice colors (whether given by `treemapcolorway` or", - "inherited from `colorway`) will be extended to three times its", - "original length by first repeating every color 20% lighter then", - "each color 20% darker. This is intended to reduce the likelihood", - "of reusing the same color when you have many slices, but you can", - "set `false` to disable.", - "Colors provided in the trace, using `marker.colors`, are never", - "extended." - ].join(" ") - } -}; -var Lib$7 = libExports; -var attributes = attributes$1; -var Color$4 = colorExports; -var handleDomainDefaults = domain.defaults; -var handleText = defaults$6.handleText; -var TEXTPAD$1 = constants$f.TEXTPAD; -var handleMarkerDefaults = defaults$4.handleMarkerDefaults; -var Colorscale = colorscale; -var hasColorscale = Colorscale.hasColorscale; -var colorscaleDefaults = Colorscale.handleDefaults; -var defaults = function supplyDefaults7(traceIn, traceOut, defaultColor, layout) { - function coerce2(attr, dflt) { - return Lib$7.coerce(traceIn, traceOut, attributes, attr, dflt); - } - var labels = coerce2("labels"); - var parents = coerce2("parents"); - if (!labels || !labels.length || !parents || !parents.length) { - traceOut.visible = false; - return; - } - var vals = coerce2("values"); - if (vals && vals.length) { - coerce2("branchvalues"); - } else { - coerce2("count"); - } - coerce2("level"); - coerce2("maxdepth"); - var packing = coerce2("tiling.packing"); - if (packing === "squarify") { - coerce2("tiling.squarifyratio"); - } - coerce2("tiling.flip"); - coerce2("tiling.pad"); - var text = coerce2("text"); - coerce2("texttemplate"); - if (!traceOut.texttemplate) coerce2("textinfo", Lib$7.isArrayOrTypedArray(text) ? "text+label" : "label"); - coerce2("hovertext"); - coerce2("hovertemplate"); - var hasPathbar = coerce2("pathbar.visible"); - var textposition = "auto"; - handleText(traceIn, traceOut, layout, coerce2, textposition, { - hasPathbar, - moduleHasSelected: false, - moduleHasUnselected: false, - moduleHasConstrain: false, - moduleHasCliponaxis: false, - moduleHasTextangle: false, - moduleHasInsideanchor: false - }); - coerce2("textposition"); - var bottomText = traceOut.textposition.indexOf("bottom") !== -1; - handleMarkerDefaults(traceIn, traceOut, layout, coerce2); - var withColorscale = traceOut._hasColorscale = hasColorscale(traceIn, "marker", "colors") || (traceIn.marker || {}).coloraxis; - if (withColorscale) { - colorscaleDefaults(traceIn, traceOut, layout, coerce2, { prefix: "marker.", cLetter: "c" }); - } else { - coerce2("marker.depthfade", !(traceOut.marker.colors || []).length); - } - var headerSize = traceOut.textfont.size * 2; - coerce2("marker.pad.t", bottomText ? headerSize / 4 : headerSize); - coerce2("marker.pad.l", headerSize / 4); - coerce2("marker.pad.r", headerSize / 4); - coerce2("marker.pad.b", bottomText ? headerSize : headerSize / 4); - coerce2("marker.cornerradius"); - traceOut._hovered = { - marker: { - line: { - width: 2, - color: Color$4.contrast(layout.paper_bgcolor) - } - } - }; - if (hasPathbar) { - coerce2("pathbar.thickness", traceOut.pathbar.textfont.size + 2 * TEXTPAD$1); - coerce2("pathbar.side"); - coerce2("pathbar.edgeshape"); - } - coerce2("sort"); - coerce2("root.color"); - handleDomainDefaults(traceOut, layout, coerce2); - traceOut._length = null; -}; -var Lib$6 = libExports; -var layoutAttributes = layout_attributes; -var layout_defaults = function supplyLayoutDefaults9(layoutIn, layoutOut) { - function coerce2(attr, dflt) { - return Lib$6.coerce(layoutIn, layoutOut, layoutAttributes, attr, dflt); - } - coerce2("treemapcolorway", layoutOut.colorway); - coerce2("extendtreemapcolors"); -}; -var calc$2 = {}; -var calc$1 = {}; -function defaultSeparation$1(a, b) { - return a.parent === b.parent ? 1 : 2; -} -function meanX(children) { - return children.reduce(meanXReduce, 0) / children.length; -} -function meanXReduce(x, c) { - return x + c.x; -} -function maxY(children) { - return 1 + children.reduce(maxYReduce, 0); -} -function maxYReduce(y, c) { - return Math.max(y, c.y); -} -function leafLeft(node) { - var children; - while (children = node.children) node = children[0]; - return node; -} -function leafRight(node) { - var children; - while (children = node.children) node = children[children.length - 1]; - return node; -} -function cluster2() { - var separation = defaultSeparation$1, dx = 1, dy = 1, nodeSize = false; - function cluster3(root) { - var previousNode, x = 0; - root.eachAfter(function(node) { - var children = node.children; - if (children) { - node.x = meanX(children); - node.y = maxY(children); - } else { - node.x = previousNode ? x += separation(node, previousNode) : 0; - node.y = 0; - previousNode = node; - } - }); - var left = leafLeft(root), right = leafRight(root), x0 = left.x - separation(left, right) / 2, x1 = right.x + separation(right, left) / 2; - return root.eachAfter(nodeSize ? function(node) { - node.x = (node.x - root.x) * dx; - node.y = (root.y - node.y) * dy; - } : function(node) { - node.x = (node.x - x0) / (x1 - x0) * dx; - node.y = (1 - (root.y ? node.y / root.y : 1)) * dy; - }); - } - cluster3.separation = function(x) { - return arguments.length ? (separation = x, cluster3) : separation; - }; - cluster3.size = function(x) { - return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], cluster3) : nodeSize ? null : [dx, dy]; - }; - cluster3.nodeSize = function(x) { - return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], cluster3) : nodeSize ? [dx, dy] : null; - }; - return cluster3; -} -function count(node) { - var sum = 0, children = node.children, i = children && children.length; - if (!i) sum = 1; - else while (--i >= 0) sum += children[i].value; - node.value = sum; -} -function node_count() { - return this.eachAfter(count); -} -function node_each(callback) { - var node = this, current, next = [node], children, i, n; - do { - current = next.reverse(), next = []; - while (node = current.pop()) { - callback(node), children = node.children; - if (children) for (i = 0, n = children.length; i < n; ++i) { - next.push(children[i]); - } - } - } while (next.length); - return this; -} -function node_eachBefore(callback) { - var node = this, nodes = [node], children, i; - while (node = nodes.pop()) { - callback(node), children = node.children; - if (children) for (i = children.length - 1; i >= 0; --i) { - nodes.push(children[i]); - } - } - return this; -} -function node_eachAfter(callback) { - var node = this, nodes = [node], next = [], children, i, n; - while (node = nodes.pop()) { - next.push(node), children = node.children; - if (children) for (i = 0, n = children.length; i < n; ++i) { - nodes.push(children[i]); - } - } - while (node = next.pop()) { - callback(node); - } - return this; -} -function node_sum(value2) { - return this.eachAfter(function(node) { - var sum = +value2(node.data) || 0, children = node.children, i = children && children.length; - while (--i >= 0) sum += children[i].value; - node.value = sum; - }); -} -function node_sort(compare) { - return this.eachBefore(function(node) { - if (node.children) { - node.children.sort(compare); - } - }); -} -function node_path(end) { - var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start]; - while (start !== ancestor) { - start = start.parent; - nodes.push(start); - } - var k = nodes.length; - while (end !== ancestor) { - nodes.splice(k, 0, end); - end = end.parent; - } - return nodes; -} -function leastCommonAncestor(a, b) { - if (a === b) return a; - var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null; - a = aNodes.pop(); - b = bNodes.pop(); - while (a === b) { - c = a; - a = aNodes.pop(); - b = bNodes.pop(); - } - return c; -} -function node_ancestors() { - var node = this, nodes = [node]; - while (node = node.parent) { - nodes.push(node); - } - return nodes; -} -function node_descendants() { - var nodes = []; - this.each(function(node) { - nodes.push(node); - }); - return nodes; -} -function node_leaves() { - var leaves = []; - this.eachBefore(function(node) { - if (!node.children) { - leaves.push(node); - } - }); - return leaves; -} -function node_links() { - var root = this, links = []; - root.each(function(node) { - if (node !== root) { - links.push({ source: node.parent, target: node }); - } - }); - return links; -} -function hierarchy(data, children) { - var root = new Node$1(data), valued = +data.value && (root.value = data.value), node, nodes = [root], child, childs, i, n; - if (children == null) children = defaultChildren; - while (node = nodes.pop()) { - if (valued) node.value = +node.data.value; - if ((childs = children(node.data)) && (n = childs.length)) { - node.children = new Array(n); - for (i = n - 1; i >= 0; --i) { - nodes.push(child = node.children[i] = new Node$1(childs[i])); - child.parent = node; - child.depth = node.depth + 1; - } - } - } - return root.eachBefore(computeHeight); -} -function node_copy() { - return hierarchy(this).eachBefore(copyData); -} -function defaultChildren(d) { - return d.children; -} -function copyData(node) { - node.data = node.data.data; -} -function computeHeight(node) { - var height = 0; - do - node.height = height; - while ((node = node.parent) && node.height < ++height); -} -function Node$1(data) { - this.data = data; - this.depth = this.height = 0; - this.parent = null; -} -Node$1.prototype = hierarchy.prototype = { - constructor: Node$1, - count: node_count, - each: node_each, - eachAfter: node_eachAfter, - eachBefore: node_eachBefore, - sum: node_sum, - sort: node_sort, - path: node_path, - ancestors: node_ancestors, - descendants: node_descendants, - leaves: node_leaves, - links: node_links, - copy: node_copy -}; -var slice = Array.prototype.slice; -function shuffle(array2) { - var m = array2.length, t, i; - while (m) { - i = Math.random() * m-- | 0; - t = array2[m]; - array2[m] = array2[i]; - array2[i] = t; - } - return array2; -} -function enclose(circles) { - var i = 0, n = (circles = shuffle(slice.call(circles))).length, B2 = [], p, e; - while (i < n) { - p = circles[i]; - if (e && enclosesWeak(e, p)) ++i; - else e = encloseBasis(B2 = extendBasis(B2, p)), i = 0; - } - return e; -} -function extendBasis(B2, p) { - var i, j; - if (enclosesWeakAll(p, B2)) return [p]; - for (i = 0; i < B2.length; ++i) { - if (enclosesNot(p, B2[i]) && enclosesWeakAll(encloseBasis2(B2[i], p), B2)) { - return [B2[i], p]; - } - } - for (i = 0; i < B2.length - 1; ++i) { - for (j = i + 1; j < B2.length; ++j) { - if (enclosesNot(encloseBasis2(B2[i], B2[j]), p) && enclosesNot(encloseBasis2(B2[i], p), B2[j]) && enclosesNot(encloseBasis2(B2[j], p), B2[i]) && enclosesWeakAll(encloseBasis3(B2[i], B2[j], p), B2)) { - return [B2[i], B2[j], p]; - } - } - } - throw new Error(); -} -function enclosesNot(a, b) { - var dr = a.r - b.r, dx = b.x - a.x, dy = b.y - a.y; - return dr < 0 || dr * dr < dx * dx + dy * dy; -} -function enclosesWeak(a, b) { - var dr = a.r - b.r + 1e-6, dx = b.x - a.x, dy = b.y - a.y; - return dr > 0 && dr * dr > dx * dx + dy * dy; -} -function enclosesWeakAll(a, B2) { - for (var i = 0; i < B2.length; ++i) { - if (!enclosesWeak(a, B2[i])) { - return false; - } - } - return true; -} -function encloseBasis(B2) { - switch (B2.length) { - case 1: - return encloseBasis1(B2[0]); - case 2: - return encloseBasis2(B2[0], B2[1]); - case 3: - return encloseBasis3(B2[0], B2[1], B2[2]); - } -} -function encloseBasis1(a) { - return { - x: a.x, - y: a.y, - r: a.r - }; -} -function encloseBasis2(a, b) { - var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1, l = Math.sqrt(x21 * x21 + y21 * y21); - return { - x: (x1 + x2 + x21 / l * r21) / 2, - y: (y1 + y2 + y21 / l * r21) / 2, - r: (l + r1 + r2) / 2 - }; -} -function encloseBasis3(a, b, c) { - var x1 = a.x, y1 = a.y, r1 = a.r, x2 = b.x, y2 = b.y, r2 = b.r, x3 = c.x, y3 = c.y, r3 = c.r, a2 = x1 - x2, a3 = x1 - x3, b2 = y1 - y2, b3 = y1 - y3, c2 = r2 - r1, c3 = r3 - r1, d1 = x1 * x1 + y1 * y1 - r1 * r1, d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2, d32 = d1 - x3 * x3 - y3 * y3 + r3 * r3, ab2 = a3 * b2 - a2 * b3, xa = (b2 * d32 - b3 * d2) / (ab2 * 2) - x1, xb = (b3 * c2 - b2 * c3) / ab2, ya = (a3 * d2 - a2 * d32) / (ab2 * 2) - y1, yb = (a2 * c3 - a3 * c2) / ab2, A2 = xb * xb + yb * yb - 1, B2 = 2 * (r1 + xa * xb + ya * yb), C2 = xa * xa + ya * ya - r1 * r1, r = -(A2 ? (B2 + Math.sqrt(B2 * B2 - 4 * A2 * C2)) / (2 * A2) : C2 / B2); - return { - x: x1 + xa + xb * r, - y: y1 + ya + yb * r, - r - }; -} -function place(b, a, c) { - var dx = b.x - a.x, x, a2, dy = b.y - a.y, y, b2, d2 = dx * dx + dy * dy; - if (d2) { - a2 = a.r + c.r, a2 *= a2; - b2 = b.r + c.r, b2 *= b2; - if (a2 > b2) { - x = (d2 + b2 - a2) / (2 * d2); - y = Math.sqrt(Math.max(0, b2 / d2 - x * x)); - c.x = b.x - x * dx - y * dy; - c.y = b.y - x * dy + y * dx; - } else { - x = (d2 + a2 - b2) / (2 * d2); - y = Math.sqrt(Math.max(0, a2 / d2 - x * x)); - c.x = a.x + x * dx - y * dy; - c.y = a.y + x * dy + y * dx; - } - } else { - c.x = a.x + c.r; - c.y = a.y; - } -} -function intersects(a, b) { - var dr = a.r + b.r - 1e-6, dx = b.x - a.x, dy = b.y - a.y; - return dr > 0 && dr * dr > dx * dx + dy * dy; -} -function score(node) { - var a = node._, b = node.next._, ab2 = a.r + b.r, dx = (a.x * b.r + b.x * a.r) / ab2, dy = (a.y * b.r + b.y * a.r) / ab2; - return dx * dx + dy * dy; -} -function Node(circle) { - this._ = circle; - this.next = null; - this.previous = null; -} -function packEnclose(circles) { - if (!(n = circles.length)) return 0; - var a, b, c, n, aa, ca, i, j, k, sj, sk; - a = circles[0], a.x = 0, a.y = 0; - if (!(n > 1)) return a.r; - b = circles[1], a.x = -b.r, b.x = a.r, b.y = 0; - if (!(n > 2)) return a.r + b.r; - place(b, a, c = circles[2]); - a = new Node(a), b = new Node(b), c = new Node(c); - a.next = c.previous = b; - b.next = a.previous = c; - c.next = b.previous = a; - pack: for (i = 3; i < n; ++i) { - place(a._, b._, c = circles[i]), c = new Node(c); - j = b.next, k = a.previous, sj = b._.r, sk = a._.r; - do { - if (sj <= sk) { - if (intersects(j._, c._)) { - b = j, a.next = b, b.previous = a, --i; - continue pack; - } - sj += j._.r, j = j.next; - } else { - if (intersects(k._, c._)) { - a = k, a.next = b, b.previous = a, --i; - continue pack; - } - sk += k._.r, k = k.previous; - } - } while (j !== k.next); - c.previous = a, c.next = b, a.next = b.previous = b = c; - aa = score(a); - while ((c = c.next) !== b) { - if ((ca = score(c)) < aa) { - a = c, aa = ca; - } - } - b = a.next; - } - a = [b._], c = b; - while ((c = c.next) !== b) a.push(c._); - c = enclose(a); - for (i = 0; i < n; ++i) a = circles[i], a.x -= c.x, a.y -= c.y; - return c.r; -} -function siblings(circles) { - packEnclose(circles); - return circles; -} -function optional(f) { - return f == null ? null : required(f); -} -function required(f) { - if (typeof f !== "function") throw new Error(); - return f; -} -function constantZero() { - return 0; -} -function constant$1(x) { - return function() { - return x; - }; -} -function defaultRadius(d) { - return Math.sqrt(d.value); -} -function index$1() { - var radius = null, dx = 1, dy = 1, padding = constantZero; - function pack(root) { - root.x = dx / 2, root.y = dy / 2; - if (radius) { - root.eachBefore(radiusLeaf(radius)).eachAfter(packChildren(padding, 0.5)).eachBefore(translateChild(1)); - } else { - root.eachBefore(radiusLeaf(defaultRadius)).eachAfter(packChildren(constantZero, 1)).eachAfter(packChildren(padding, root.r / Math.min(dx, dy))).eachBefore(translateChild(Math.min(dx, dy) / (2 * root.r))); - } - return root; - } - pack.radius = function(x) { - return arguments.length ? (radius = optional(x), pack) : radius; - }; - pack.size = function(x) { - return arguments.length ? (dx = +x[0], dy = +x[1], pack) : [dx, dy]; - }; - pack.padding = function(x) { - return arguments.length ? (padding = typeof x === "function" ? x : constant$1(+x), pack) : padding; - }; - return pack; -} -function radiusLeaf(radius) { - return function(node) { - if (!node.children) { - node.r = Math.max(0, +radius(node) || 0); - } - }; -} -function packChildren(padding, k) { - return function(node) { - if (children = node.children) { - var children, i, n = children.length, r = padding(node) * k || 0, e; - if (r) for (i = 0; i < n; ++i) children[i].r += r; - e = packEnclose(children); - if (r) for (i = 0; i < n; ++i) children[i].r -= r; - node.r = e + r; - } - }; -} -function translateChild(k) { - return function(node) { - var parent = node.parent; - node.r *= k; - if (parent) { - node.x = parent.x + k * node.x; - node.y = parent.y + k * node.y; - } - }; -} -function roundNode(node) { - node.x0 = Math.round(node.x0); - node.y0 = Math.round(node.y0); - node.x1 = Math.round(node.x1); - node.y1 = Math.round(node.y1); -} -function treemapDice(parent, x0, y0, x1, y1) { - var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value; - while (++i < n) { - node = nodes[i], node.y0 = y0, node.y1 = y1; - node.x0 = x0, node.x1 = x0 += node.value * k; - } -} -function partition$3() { - var dx = 1, dy = 1, padding = 0, round2 = false; - function partition3(root) { - var n = root.height + 1; - root.x0 = root.y0 = padding; - root.x1 = dx; - root.y1 = dy / n; - root.eachBefore(positionNode(dy, n)); - if (round2) root.eachBefore(roundNode); - return root; - } - function positionNode(dy2, n) { - return function(node) { - if (node.children) { - treemapDice(node, node.x0, dy2 * (node.depth + 1) / n, node.x1, dy2 * (node.depth + 2) / n); - } - var x0 = node.x0, y0 = node.y0, x1 = node.x1 - padding, y1 = node.y1 - padding; - if (x1 < x0) x0 = x1 = (x0 + x1) / 2; - if (y1 < y0) y0 = y1 = (y0 + y1) / 2; - node.x0 = x0; - node.y0 = y0; - node.x1 = x1; - node.y1 = y1; - }; - } - partition3.round = function(x) { - return arguments.length ? (round2 = !!x, partition3) : round2; - }; - partition3.size = function(x) { - return arguments.length ? (dx = +x[0], dy = +x[1], partition3) : [dx, dy]; - }; - partition3.padding = function(x) { - return arguments.length ? (padding = +x, partition3) : padding; - }; - return partition3; -} -var keyPrefix = "$", preroot = { depth: -1 }, ambiguous = {}; -function defaultId(d) { - return d.id; -} -function defaultParentId(d) { - return d.parentId; -} -function stratify() { - var id = defaultId, parentId = defaultParentId; - function stratify2(data) { - var d, i, n = data.length, root, parent, node, nodes = new Array(n), nodeId, nodeKey, nodeByKey = {}; - for (i = 0; i < n; ++i) { - d = data[i], node = nodes[i] = new Node$1(d); - if ((nodeId = id(d, i, data)) != null && (nodeId += "")) { - nodeKey = keyPrefix + (node.id = nodeId); - nodeByKey[nodeKey] = nodeKey in nodeByKey ? ambiguous : node; - } - } - for (i = 0; i < n; ++i) { - node = nodes[i], nodeId = parentId(data[i], i, data); - if (nodeId == null || !(nodeId += "")) { - if (root) throw new Error("multiple roots"); - root = node; - } else { - parent = nodeByKey[keyPrefix + nodeId]; - if (!parent) throw new Error("missing: " + nodeId); - if (parent === ambiguous) throw new Error("ambiguous: " + nodeId); - if (parent.children) parent.children.push(node); - else parent.children = [node]; - node.parent = parent; - } - } - if (!root) throw new Error("no root"); - root.parent = preroot; - root.eachBefore(function(node2) { - node2.depth = node2.parent.depth + 1; - --n; - }).eachBefore(computeHeight); - root.parent = null; - if (n > 0) throw new Error("cycle"); - return root; - } - stratify2.id = function(x) { - return arguments.length ? (id = required(x), stratify2) : id; - }; - stratify2.parentId = function(x) { - return arguments.length ? (parentId = required(x), stratify2) : parentId; - }; - return stratify2; -} -function defaultSeparation(a, b) { - return a.parent === b.parent ? 1 : 2; -} -function nextLeft(v) { - var children = v.children; - return children ? children[0] : v.t; -} -function nextRight(v) { - var children = v.children; - return children ? children[children.length - 1] : v.t; -} -function moveSubtree(wm, wp, shift) { - var change = shift / (wp.i - wm.i); - wp.c -= change; - wp.s += shift; - wm.c += change; - wp.z += shift; - wp.m += shift; -} -function executeShifts(v) { - var shift = 0, change = 0, children = v.children, i = children.length, w; - while (--i >= 0) { - w = children[i]; - w.z += shift; - w.m += shift; - shift += w.s + (change += w.c); - } -} -function nextAncestor(vim, v, ancestor) { - return vim.a.parent === v.parent ? vim.a : ancestor; -} -function TreeNode(node, i) { - this._ = node; - this.parent = null; - this.children = null; - this.A = null; - this.a = this; - this.z = 0; - this.m = 0; - this.c = 0; - this.s = 0; - this.t = null; - this.i = i; -} -TreeNode.prototype = Object.create(Node$1.prototype); -function treeRoot(root) { - var tree2 = new TreeNode(root, 0), node, nodes = [tree2], child, children, i, n; - while (node = nodes.pop()) { - if (children = node._.children) { - node.children = new Array(n = children.length); - for (i = n - 1; i >= 0; --i) { - nodes.push(child = node.children[i] = new TreeNode(children[i], i)); - child.parent = node; - } - } - } - (tree2.parent = new TreeNode(null, 0)).children = [tree2]; - return tree2; -} -function tree() { - var separation = defaultSeparation, dx = 1, dy = 1, nodeSize = null; - function tree2(root) { - var t = treeRoot(root); - t.eachAfter(firstWalk), t.parent.m = -t.z; - t.eachBefore(secondWalk); - if (nodeSize) root.eachBefore(sizeNode); - else { - var left = root, right = root, bottom = root; - root.eachBefore(function(node) { - if (node.x < left.x) left = node; - if (node.x > right.x) right = node; - if (node.depth > bottom.depth) bottom = node; - }); - var s = left === right ? 1 : separation(left, right) / 2, tx = s - left.x, kx = dx / (right.x + s + tx), ky = dy / (bottom.depth || 1); - root.eachBefore(function(node) { - node.x = (node.x + tx) * kx; - node.y = node.depth * ky; - }); - } - return root; - } - function firstWalk(v) { - var children = v.children, siblings2 = v.parent.children, w = v.i ? siblings2[v.i - 1] : null; - if (children) { - executeShifts(v); - var midpoint = (children[0].z + children[children.length - 1].z) / 2; - if (w) { - v.z = w.z + separation(v._, w._); - v.m = v.z - midpoint; - } else { - v.z = midpoint; - } - } else if (w) { - v.z = w.z + separation(v._, w._); - } - v.parent.A = apportion(v, w, v.parent.A || siblings2[0]); - } - function secondWalk(v) { - v._.x = v.z + v.parent.m; - v.m += v.parent.m; - } - function apportion(v, w, ancestor) { - if (w) { - var vip = v, vop = v, vim = w, vom = vip.parent.children[0], sip = vip.m, sop = vop.m, sim = vim.m, som = vom.m, shift; - while (vim = nextRight(vim), vip = nextLeft(vip), vim && vip) { - vom = nextLeft(vom); - vop = nextRight(vop); - vop.a = v; - shift = vim.z + sim - vip.z - sip + separation(vim._, vip._); - if (shift > 0) { - moveSubtree(nextAncestor(vim, v, ancestor), v, shift); - sip += shift; - sop += shift; - } - sim += vim.m; - sip += vip.m; - som += vom.m; - sop += vop.m; - } - if (vim && !nextRight(vop)) { - vop.t = vim; - vop.m += sim - sop; - } - if (vip && !nextLeft(vom)) { - vom.t = vip; - vom.m += sip - som; - ancestor = v; - } - } - return ancestor; - } - function sizeNode(node) { - node.x *= dx; - node.y = node.depth * dy; - } - tree2.separation = function(x) { - return arguments.length ? (separation = x, tree2) : separation; - }; - tree2.size = function(x) { - return arguments.length ? (nodeSize = false, dx = +x[0], dy = +x[1], tree2) : nodeSize ? null : [dx, dy]; - }; - tree2.nodeSize = function(x) { - return arguments.length ? (nodeSize = true, dx = +x[0], dy = +x[1], tree2) : nodeSize ? [dx, dy] : null; - }; - return tree2; -} -function treemapSlice(parent, x0, y0, x1, y1) { - var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value; - while (++i < n) { - node = nodes[i], node.x0 = x0, node.x1 = x1; - node.y0 = y0, node.y1 = y0 += node.value * k; - } -} -var phi = (1 + Math.sqrt(5)) / 2; -function squarifyRatio(ratio, parent, x0, y0, x1, y1) { - var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value2 = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta; - while (i0 < n) { - dx = x1 - x0, dy = y1 - y0; - do - sumValue = nodes[i1++].value; - while (!sumValue && i1 < n); - minValue = maxValue = sumValue; - alpha = Math.max(dy / dx, dx / dy) / (value2 * ratio); - beta = sumValue * sumValue * alpha; - minRatio = Math.max(maxValue / beta, beta / minValue); - for (; i1 < n; ++i1) { - sumValue += nodeValue = nodes[i1].value; - if (nodeValue < minValue) minValue = nodeValue; - if (nodeValue > maxValue) maxValue = nodeValue; - beta = sumValue * sumValue * alpha; - newRatio = Math.max(maxValue / beta, beta / minValue); - if (newRatio > minRatio) { - sumValue -= nodeValue; - break; - } - minRatio = newRatio; - } - rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) }); - if (row.dice) treemapDice(row, x0, y0, x1, value2 ? y0 += dy * sumValue / value2 : y1); - else treemapSlice(row, x0, y0, value2 ? x0 += dx * sumValue / value2 : x1, y1); - value2 -= sumValue, i0 = i1; - } - return rows; -} -const squarify = function custom(ratio) { - function squarify2(parent, x0, y0, x1, y1) { - squarifyRatio(ratio, parent, x0, y0, x1, y1); - } - squarify2.ratio = function(x) { - return custom((x = +x) > 1 ? x : 1); - }; - return squarify2; -}(phi); -function index() { - var tile = squarify, round2 = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero; - function treemap2(root) { - root.x0 = root.y0 = 0; - root.x1 = dx; - root.y1 = dy; - root.eachBefore(positionNode); - paddingStack = [0]; - if (round2) root.eachBefore(roundNode); - return root; - } - function positionNode(node) { - var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p; - if (x1 < x0) x0 = x1 = (x0 + x1) / 2; - if (y1 < y0) y0 = y1 = (y0 + y1) / 2; - node.x0 = x0; - node.y0 = y0; - node.x1 = x1; - node.y1 = y1; - if (node.children) { - p = paddingStack[node.depth + 1] = paddingInner(node) / 2; - x0 += paddingLeft(node) - p; - y0 += paddingTop(node) - p; - x1 -= paddingRight(node) - p; - y1 -= paddingBottom(node) - p; - if (x1 < x0) x0 = x1 = (x0 + x1) / 2; - if (y1 < y0) y0 = y1 = (y0 + y1) / 2; - tile(node, x0, y0, x1, y1); - } - } - treemap2.round = function(x) { - return arguments.length ? (round2 = !!x, treemap2) : round2; - }; - treemap2.size = function(x) { - return arguments.length ? (dx = +x[0], dy = +x[1], treemap2) : [dx, dy]; - }; - treemap2.tile = function(x) { - return arguments.length ? (tile = required(x), treemap2) : tile; - }; - treemap2.padding = function(x) { - return arguments.length ? treemap2.paddingInner(x).paddingOuter(x) : treemap2.paddingInner(); - }; - treemap2.paddingInner = function(x) { - return arguments.length ? (paddingInner = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingInner; - }; - treemap2.paddingOuter = function(x) { - return arguments.length ? treemap2.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap2.paddingTop(); - }; - treemap2.paddingTop = function(x) { - return arguments.length ? (paddingTop = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingTop; - }; - treemap2.paddingRight = function(x) { - return arguments.length ? (paddingRight = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingRight; - }; - treemap2.paddingBottom = function(x) { - return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingBottom; - }; - treemap2.paddingLeft = function(x) { - return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant$1(+x), treemap2) : paddingLeft; - }; - return treemap2; -} -function binary(parent, x0, y0, x1, y1) { - var nodes = parent.children, i, n = nodes.length, sum, sums = new Array(n + 1); - for (sums[0] = sum = i = 0; i < n; ++i) { - sums[i + 1] = sum += nodes[i].value; - } - partition3(0, n, parent.value, x0, y0, x1, y1); - function partition3(i2, j, value2, x02, y02, x12, y12) { - if (i2 >= j - 1) { - var node = nodes[i2]; - node.x0 = x02, node.y0 = y02; - node.x1 = x12, node.y1 = y12; - return; - } - var valueOffset = sums[i2], valueTarget = value2 / 2 + valueOffset, k = i2 + 1, hi = j - 1; - while (k < hi) { - var mid = k + hi >>> 1; - if (sums[mid] < valueTarget) k = mid + 1; - else hi = mid; - } - if (valueTarget - sums[k - 1] < sums[k] - valueTarget && i2 + 1 < k) --k; - var valueLeft = sums[k] - valueOffset, valueRight = value2 - valueLeft; - if (x12 - x02 > y12 - y02) { - var xk = (x02 * valueRight + x12 * valueLeft) / value2; - partition3(i2, k, valueLeft, x02, y02, xk, y12); - partition3(k, j, valueRight, xk, y02, x12, y12); - } else { - var yk = (y02 * valueRight + y12 * valueLeft) / value2; - partition3(i2, k, valueLeft, x02, y02, x12, yk); - partition3(k, j, valueRight, x02, yk, x12, y12); - } - } -} -function sliceDice(parent, x0, y0, x1, y1) { - (parent.depth & 1 ? treemapSlice : treemapDice)(parent, x0, y0, x1, y1); -} -const resquarify = function custom2(ratio) { - function resquarify2(parent, x0, y0, x1, y1) { - if ((rows = parent._squarify) && rows.ratio === ratio) { - var rows, row, nodes, i, j = -1, n, m = rows.length, value2 = parent.value; - while (++j < m) { - row = rows[j], nodes = row.children; - for (i = row.value = 0, n = nodes.length; i < n; ++i) row.value += nodes[i].value; - if (row.dice) treemapDice(row, x0, y0, x1, y0 += (y1 - y0) * row.value / value2); - else treemapSlice(row, x0, y0, x0 += (x1 - x0) * row.value / value2, y1); - value2 -= row.value; - } - } else { - parent._squarify = rows = squarifyRatio(ratio, parent, x0, y0, x1, y1); - rows.ratio = ratio; - } - } - resquarify2.ratio = function(x) { - return custom2((x = +x) > 1 ? x : 1); - }; - return resquarify2; -}(phi); -const src$1 = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - cluster: cluster2, - hierarchy, - pack: index$1, - packEnclose: enclose, - packSiblings: siblings, - partition: partition$3, - stratify, - tree, - treemap: index, - treemapBinary: binary, - treemapDice, - treemapResquarify: resquarify, - treemapSlice, - treemapSliceDice: sliceDice, - treemapSquarify: squarify -}, Symbol.toStringTag, { value: "Module" })); -const require$$1 = /* @__PURE__ */ index$3.getAugmentedNamespace(src$1); -(function(exports2) { - var d3Hierarchy2 = require$$1; - var isNumeric2 = fastIsnumeric; - var Lib2 = libExports; - var makeColorScaleFn = colorscale.makeColorScaleFuncFromTrace; - var makePullColorFn2 = calc_1$1.makePullColorFn; - var generateExtendedColors2 = calc_1$1.generateExtendedColors; - var colorscaleCalc2 = colorscale.calc; - var ALMOST_EQUAL2 = numerical.ALMOST_EQUAL; - var sunburstExtendedColorWays = {}; - var treemapExtendedColorWays = {}; - var icicleExtendedColorWays = {}; - exports2.calc = function(gd, trace) { - var fullLayout = gd._fullLayout; - var ids = trace.ids; - var hasIds = Lib2.isArrayOrTypedArray(ids); - var labels = trace.labels; - var parents = trace.parents; - var values = trace.values; - var hasValues = Lib2.isArrayOrTypedArray(values); - var cd = []; - var parent2children = {}; - var refs = {}; - var addToLookup = function(parent, v) { - if (parent2children[parent]) parent2children[parent].push(v); - else parent2children[parent] = [v]; - refs[v] = 1; - }; - var isValidKey = function(k2) { - return k2 || typeof k2 === "number"; - }; - var isValidVal = function(i2) { - return !hasValues || isNumeric2(values[i2]) && values[i2] >= 0; - }; - var len; - var isValid; - var getId2; - if (hasIds) { - len = Math.min(ids.length, parents.length); - isValid = function(i2) { - return isValidKey(ids[i2]) && isValidVal(i2); - }; - getId2 = function(i2) { - return String(ids[i2]); - }; - } else { - len = Math.min(labels.length, parents.length); - isValid = function(i2) { - return isValidKey(labels[i2]) && isValidVal(i2); - }; - getId2 = function(i2) { - return String(labels[i2]); - }; - } - if (hasValues) len = Math.min(len, values.length); - for (var i = 0; i < len; i++) { - if (isValid(i)) { - var id = getId2(i); - var pid = isValidKey(parents[i]) ? String(parents[i]) : ""; - var cdi = { - i, - id, - pid, - label: isValidKey(labels[i]) ? String(labels[i]) : "" - }; - if (hasValues) cdi.v = +values[i]; - cd.push(cdi); - addToLookup(pid, id); - } - } - if (!parent2children[""]) { - var impliedRoots = []; - var k; - for (k in parent2children) { - if (!refs[k]) { - impliedRoots.push(k); - } - } - if (impliedRoots.length === 1) { - k = impliedRoots[0]; - cd.unshift({ - hasImpliedRoot: true, - id: k, - pid: "", - label: k - }); - } else { - return Lib2.warn([ - "Multiple implied roots, cannot build", - trace.type, - "hierarchy of", - trace.name + ".", - "These roots include:", - impliedRoots.join(", ") - ].join(" ")); - } - } else if (parent2children[""].length > 1) { - var dummyId = Lib2.randstr(); - for (var j = 0; j < cd.length; j++) { - if (cd[j].pid === "") { - cd[j].pid = dummyId; - } - } - cd.unshift({ - hasMultipleRoots: true, - id: dummyId, - pid: "", - label: "" - }); - } - var root; - try { - root = d3Hierarchy2.stratify().id(function(d) { - return d.id; - }).parentId(function(d) { - return d.pid; - })(cd); - } catch (e) { - return Lib2.warn([ - "Failed to build", - trace.type, - "hierarchy of", - trace.name + ".", - "Error:", - e.message - ].join(" ")); - } - var hierarchy2 = d3Hierarchy2.hierarchy(root); - var failed = false; - if (hasValues) { - switch (trace.branchvalues) { - case "remainder": - hierarchy2.sum(function(d) { - return d.data.v; - }); - break; - case "total": - hierarchy2.each(function(d) { - var cdi2 = d.data.data; - var v = cdi2.v; - if (d.children) { - var partialSum = d.children.reduce(function(a, c) { - return a + c.data.data.v; - }, 0); - if (cdi2.hasImpliedRoot || cdi2.hasMultipleRoots) { - v = partialSum; - } - if (v < partialSum * ALMOST_EQUAL2) { - failed = true; - return Lib2.warn([ - "Total value for node", - d.data.data.id, - "of", - trace.name, - "is smaller than the sum of its children.", - "\nparent value =", - v, - "\nchildren sum =", - partialSum - ].join(" ")); - } - } - d.value = v; - }); - break; - } - } else { - countDescendants(hierarchy2, trace, { - branches: trace.count.indexOf("branches") !== -1, - leaves: trace.count.indexOf("leaves") !== -1 - }); - } - if (failed) return; - if (trace.sort) { - hierarchy2.sort(function(a, b) { - return b.value - a.value; - }); - } - var pullColor; - var scaleColor; - var colors = trace.marker.colors || []; - var hasColors = !!colors.length; - if (trace._hasColorscale) { - if (!hasColors) { - colors = hasValues ? trace.values : trace._values; - } - colorscaleCalc2(gd, trace, { - vals: colors, - containerStr: "marker", - cLetter: "c" - }); - scaleColor = makeColorScaleFn(trace.marker); - } else { - pullColor = makePullColorFn2(fullLayout["_" + trace.type + "colormap"]); - } - hierarchy2.each(function(d) { - var cdi2 = d.data.data; - cdi2.color = trace._hasColorscale ? scaleColor(colors[cdi2.i]) : pullColor(colors[cdi2.i], cdi2.id); - }); - cd[0].hierarchy = hierarchy2; - return cd; - }; - exports2._runCrossTraceCalc = function(desiredType, gd) { - var fullLayout = gd._fullLayout; - var calcdata = gd.calcdata; - var colorWay = fullLayout[desiredType + "colorway"]; - var colorMap = fullLayout["_" + desiredType + "colormap"]; - if (fullLayout["extend" + desiredType + "colors"]) { - colorWay = generateExtendedColors2( - colorWay, - desiredType === "icicle" ? icicleExtendedColorWays : desiredType === "treemap" ? treemapExtendedColorWays : sunburstExtendedColorWays - ); - } - var dfltColorCount = 0; - var rootColor; - function pickColor(d) { - var cdi = d.data.data; - var id = cdi.id; - if (cdi.color === false) { - if (colorMap[id]) { - cdi.color = colorMap[id]; - } else if (d.parent) { - if (d.parent.parent) { - cdi.color = d.parent.data.data.color; - } else { - colorMap[id] = cdi.color = colorWay[dfltColorCount % colorWay.length]; - dfltColorCount++; - } - } else { - cdi.color = rootColor; - } - } - } - for (var i = 0; i < calcdata.length; i++) { - var cd = calcdata[i]; - var cd0 = cd[0]; - if (cd0.trace.type === desiredType && cd0.hierarchy) { - rootColor = cd0.trace.root.color; - cd0.hierarchy.each(pickColor); - } - } - }; - exports2.crossTraceCalc = function(gd) { - return exports2._runCrossTraceCalc("sunburst", gd); - }; - function countDescendants(node, trace, opts) { - var nChild = 0; - var children = node.children; - if (children) { - var len = children.length; - for (var i = 0; i < len; i++) { - nChild += countDescendants(children[i], trace, opts); - } - if (opts.branches) nChild++; - } else { - if (opts.leaves) nChild++; - } - node.value = node.data.data.value = nChild; - if (!trace._values) trace._values = []; - trace._values[node.data.data.i] = nChild; - return nChild; - } -})(calc$1); -var calc5 = calc$1; -calc$2.calc = function(gd, trace) { - return calc5.calc(gd, trace); -}; -calc$2.crossTraceCalc = function(gd) { - return calc5._runCrossTraceCalc("treemap", gd); -}; -var helpers$6 = {}; -(function(exports2) { - var Lib2 = libExports; - var Color2 = colorExports; - var setCursor3 = setcursor; - var pieHelpers2 = helpers$F; - exports2.findEntryWithLevel = function(hierarchy2, level) { - var out; - if (level) { - hierarchy2.eachAfter(function(pt) { - if (exports2.getPtId(pt) === level) { - return out = pt.copy(); - } - }); - } - return out || hierarchy2; - }; - exports2.findEntryWithChild = function(hierarchy2, childId) { - var out; - hierarchy2.eachAfter(function(pt) { - var children = pt.children || []; - for (var i = 0; i < children.length; i++) { - var child = children[i]; - if (exports2.getPtId(child) === childId) { - return out = pt.copy(); - } - } - }); - return out || hierarchy2; - }; - exports2.isEntry = function(pt) { - return !pt.parent; - }; - exports2.isLeaf = function(pt) { - return !pt.children; - }; - exports2.getPtId = function(pt) { - return pt.data.data.id; - }; - exports2.getPtLabel = function(pt) { - return pt.data.data.label; - }; - exports2.getValue = function(d) { - return d.value; - }; - exports2.isHierarchyRoot = function(pt) { - return getParentId(pt) === ""; - }; - exports2.setSliceCursor = function(sliceTop, gd, opts) { - var hide = opts.isTransitioning; - if (!hide) { - var pt = sliceTop.datum(); - hide = opts.hideOnRoot && exports2.isHierarchyRoot(pt) || opts.hideOnLeaves && exports2.isLeaf(pt); - } - setCursor3(sliceTop, hide ? null : "pointer"); - }; - function determineOutsideTextFont2(trace, pt, layoutFont) { - return { - color: exports2.getOutsideTextFontKey("color", trace, pt, layoutFont), - family: exports2.getOutsideTextFontKey("family", trace, pt, layoutFont), - size: exports2.getOutsideTextFontKey("size", trace, pt, layoutFont), - weight: exports2.getOutsideTextFontKey("weight", trace, pt, layoutFont), - style: exports2.getOutsideTextFontKey("style", trace, pt, layoutFont), - variant: exports2.getOutsideTextFontKey("variant", trace, pt, layoutFont), - textcase: exports2.getOutsideTextFontKey("textcase", trace, pt, layoutFont), - lineposition: exports2.getOutsideTextFontKey("lineposition", trace, pt, layoutFont), - shadow: exports2.getOutsideTextFontKey("shadow", trace, pt, layoutFont) - }; - } - function determineInsideTextFont2(trace, pt, layoutFont, opts) { - var onPathbar2 = (opts || {}).onPathbar; - var cdi = pt.data.data; - var ptNumber = cdi.i; - var customColor = Lib2.castOption( - trace, - ptNumber, - (onPathbar2 ? "pathbar.textfont" : "insidetextfont") + ".color" - ); - if (!customColor && trace._input.textfont) { - customColor = Lib2.castOption(trace._input, ptNumber, "textfont.color"); - } - return { - color: customColor || Color2.contrast(cdi.color), - family: exports2.getInsideTextFontKey("family", trace, pt, layoutFont, opts), - size: exports2.getInsideTextFontKey("size", trace, pt, layoutFont, opts), - weight: exports2.getInsideTextFontKey("weight", trace, pt, layoutFont, opts), - style: exports2.getInsideTextFontKey("style", trace, pt, layoutFont, opts), - variant: exports2.getInsideTextFontKey("variant", trace, pt, layoutFont, opts), - textcase: exports2.getInsideTextFontKey("textcase", trace, pt, layoutFont, opts), - lineposition: exports2.getInsideTextFontKey("lineposition", trace, pt, layoutFont, opts), - shadow: exports2.getInsideTextFontKey("shadow", trace, pt, layoutFont, opts) - }; - } - exports2.getInsideTextFontKey = function(keyStr, trace, pt, layoutFont, opts) { - var onPathbar2 = (opts || {}).onPathbar; - var cont = onPathbar2 ? "pathbar.textfont" : "insidetextfont"; - var ptNumber = pt.data.data.i; - return Lib2.castOption(trace, ptNumber, cont + "." + keyStr) || Lib2.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size; - }; - exports2.getOutsideTextFontKey = function(keyStr, trace, pt, layoutFont) { - var ptNumber = pt.data.data.i; - return Lib2.castOption(trace, ptNumber, "outsidetextfont." + keyStr) || Lib2.castOption(trace, ptNumber, "textfont." + keyStr) || layoutFont.size; - }; - exports2.isOutsideText = function(trace, pt) { - return !trace._hasColorscale && exports2.isHierarchyRoot(pt); - }; - exports2.determineTextFont = function(trace, pt, layoutFont, opts) { - return exports2.isOutsideText(trace, pt) ? determineOutsideTextFont2(trace, pt, layoutFont) : determineInsideTextFont2(trace, pt, layoutFont, opts); - }; - exports2.hasTransition = function(transitionOpts) { - return !!(transitionOpts && transitionOpts.duration > 0); - }; - exports2.getMaxDepth = function(trace) { - return trace.maxdepth >= 0 ? trace.maxdepth : Infinity; - }; - exports2.isHeader = function(pt, trace) { - return !(exports2.isLeaf(pt) || pt.depth === trace._maxDepth - 1); - }; - function getParentId(pt) { - return pt.data.data.pid; - } - exports2.getParent = function(hierarchy2, pt) { - return exports2.findEntryWithLevel(hierarchy2, getParentId(pt)); - }; - exports2.listPath = function(d, keyStr) { - var parent = d.parent; - if (!parent) return []; - var list = keyStr ? [parent.data[keyStr]] : [parent]; - return exports2.listPath(parent, keyStr).concat(list); - }; - exports2.getPath = function(d) { - return exports2.listPath(d, "label").join("/") + "/"; - }; - exports2.formatValue = pieHelpers2.formatPieValue; - exports2.formatPercent = function(v, separators) { - var tx = Lib2.formatPercent(v, 0); - if (tx === "0%") tx = pieHelpers2.formatPiePercent(v, separators); - return tx; - }; -})(helpers$6); -function define(constructor, factory2, prototype) { - constructor.prototype = factory2.prototype = prototype; - prototype.constructor = constructor; -} -function extend(parent, definition) { - var prototype = Object.create(parent.prototype); - for (var key in definition) prototype[key] = definition[key]; - return prototype; -} -function Color$3() { -} -var darker = 0.7; -var brighter = 1 / darker; -var reI = "\\s*([+-]?\\d+)\\s*", reN = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*", reP = "\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*", reHex = /^#([0-9a-f]{3,8})$/, reRgbInteger = new RegExp(`^rgb\\(${reI},${reI},${reI}\\)$`), reRgbPercent = new RegExp(`^rgb\\(${reP},${reP},${reP}\\)$`), reRgbaInteger = new RegExp(`^rgba\\(${reI},${reI},${reI},${reN}\\)$`), reRgbaPercent = new RegExp(`^rgba\\(${reP},${reP},${reP},${reN}\\)$`), reHslPercent = new RegExp(`^hsl\\(${reN},${reP},${reP}\\)$`), reHslaPercent = new RegExp(`^hsla\\(${reN},${reP},${reP},${reN}\\)$`); -var named = { - aliceblue: 15792383, - antiquewhite: 16444375, - aqua: 65535, - aquamarine: 8388564, - azure: 15794175, - beige: 16119260, - bisque: 16770244, - black: 0, - blanchedalmond: 16772045, - blue: 255, - blueviolet: 9055202, - brown: 10824234, - burlywood: 14596231, - cadetblue: 6266528, - chartreuse: 8388352, - chocolate: 13789470, - coral: 16744272, - cornflowerblue: 6591981, - cornsilk: 16775388, - crimson: 14423100, - cyan: 65535, - darkblue: 139, - darkcyan: 35723, - darkgoldenrod: 12092939, - darkgray: 11119017, - darkgreen: 25600, - darkgrey: 11119017, - darkkhaki: 12433259, - darkmagenta: 9109643, - darkolivegreen: 5597999, - darkorange: 16747520, - darkorchid: 10040012, - darkred: 9109504, - darksalmon: 15308410, - darkseagreen: 9419919, - darkslateblue: 4734347, - darkslategray: 3100495, - darkslategrey: 3100495, - darkturquoise: 52945, - darkviolet: 9699539, - deeppink: 16716947, - deepskyblue: 49151, - dimgray: 6908265, - dimgrey: 6908265, - dodgerblue: 2003199, - firebrick: 11674146, - floralwhite: 16775920, - forestgreen: 2263842, - fuchsia: 16711935, - gainsboro: 14474460, - ghostwhite: 16316671, - gold: 16766720, - goldenrod: 14329120, - gray: 8421504, - green: 32768, - greenyellow: 11403055, - grey: 8421504, - honeydew: 15794160, - hotpink: 16738740, - indianred: 13458524, - indigo: 4915330, - ivory: 16777200, - khaki: 15787660, - lavender: 15132410, - lavenderblush: 16773365, - lawngreen: 8190976, - lemonchiffon: 16775885, - lightblue: 11393254, - lightcoral: 15761536, - lightcyan: 14745599, - lightgoldenrodyellow: 16448210, - lightgray: 13882323, - lightgreen: 9498256, - lightgrey: 13882323, - lightpink: 16758465, - lightsalmon: 16752762, - lightseagreen: 2142890, - lightskyblue: 8900346, - lightslategray: 7833753, - lightslategrey: 7833753, - lightsteelblue: 11584734, - lightyellow: 16777184, - lime: 65280, - limegreen: 3329330, - linen: 16445670, - magenta: 16711935, - maroon: 8388608, - mediumaquamarine: 6737322, - mediumblue: 205, - mediumorchid: 12211667, - mediumpurple: 9662683, - mediumseagreen: 3978097, - mediumslateblue: 8087790, - mediumspringgreen: 64154, - mediumturquoise: 4772300, - mediumvioletred: 13047173, - midnightblue: 1644912, - mintcream: 16121850, - mistyrose: 16770273, - moccasin: 16770229, - navajowhite: 16768685, - navy: 128, - oldlace: 16643558, - olive: 8421376, - olivedrab: 7048739, - orange: 16753920, - orangered: 16729344, - orchid: 14315734, - palegoldenrod: 15657130, - palegreen: 10025880, - paleturquoise: 11529966, - palevioletred: 14381203, - papayawhip: 16773077, - peachpuff: 16767673, - peru: 13468991, - pink: 16761035, - plum: 14524637, - powderblue: 11591910, - purple: 8388736, - rebeccapurple: 6697881, - red: 16711680, - rosybrown: 12357519, - royalblue: 4286945, - saddlebrown: 9127187, - salmon: 16416882, - sandybrown: 16032864, - seagreen: 3050327, - seashell: 16774638, - sienna: 10506797, - silver: 12632256, - skyblue: 8900331, - slateblue: 6970061, - slategray: 7372944, - slategrey: 7372944, - snow: 16775930, - springgreen: 65407, - steelblue: 4620980, - tan: 13808780, - teal: 32896, - thistle: 14204888, - tomato: 16737095, - turquoise: 4251856, - violet: 15631086, - wheat: 16113331, - white: 16777215, - whitesmoke: 16119285, - yellow: 16776960, - yellowgreen: 10145074 -}; -define(Color$3, color, { - copy(channels) { - return Object.assign(new this.constructor(), this, channels); - }, - displayable() { - return this.rgb().displayable(); - }, - hex: color_formatHex, - // Deprecated! Use color.formatHex. - formatHex: color_formatHex, - formatHex8: color_formatHex8, - formatHsl: color_formatHsl, - formatRgb: color_formatRgb, - toString: color_formatRgb -}); -function color_formatHex() { - return this.rgb().formatHex(); -} -function color_formatHex8() { - return this.rgb().formatHex8(); -} -function color_formatHsl() { - return hslConvert(this).formatHsl(); -} -function color_formatRgb() { - return this.rgb().formatRgb(); -} -function color(format2) { - var m, l; - format2 = (format2 + "").trim().toLowerCase(); - return (m = reHex.exec(format2)) ? (l = m[1].length, m = parseInt(m[1], 16), l === 6 ? rgbn(m) : l === 3 ? new Rgb(m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, (m & 15) << 4 | m & 15, 1) : l === 8 ? rgba2(m >> 24 & 255, m >> 16 & 255, m >> 8 & 255, (m & 255) / 255) : l === 4 ? rgba2(m >> 12 & 15 | m >> 8 & 240, m >> 8 & 15 | m >> 4 & 240, m >> 4 & 15 | m & 240, ((m & 15) << 4 | m & 15) / 255) : null) : (m = reRgbInteger.exec(format2)) ? new Rgb(m[1], m[2], m[3], 1) : (m = reRgbPercent.exec(format2)) ? new Rgb(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, 1) : (m = reRgbaInteger.exec(format2)) ? rgba2(m[1], m[2], m[3], m[4]) : (m = reRgbaPercent.exec(format2)) ? rgba2(m[1] * 255 / 100, m[2] * 255 / 100, m[3] * 255 / 100, m[4]) : (m = reHslPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, 1) : (m = reHslaPercent.exec(format2)) ? hsla(m[1], m[2] / 100, m[3] / 100, m[4]) : named.hasOwnProperty(format2) ? rgbn(named[format2]) : format2 === "transparent" ? new Rgb(NaN, NaN, NaN, 0) : null; -} -function rgbn(n) { - return new Rgb(n >> 16 & 255, n >> 8 & 255, n & 255, 1); -} -function rgba2(r, g, b, a) { - if (a <= 0) r = g = b = NaN; - return new Rgb(r, g, b, a); -} -function rgbConvert(o) { - if (!(o instanceof Color$3)) o = color(o); - if (!o) return new Rgb(); - o = o.rgb(); - return new Rgb(o.r, o.g, o.b, o.opacity); -} -function rgb$1(r, g, b, opacity) { - return arguments.length === 1 ? rgbConvert(r) : new Rgb(r, g, b, opacity == null ? 1 : opacity); -} -function Rgb(r, g, b, opacity) { - this.r = +r; - this.g = +g; - this.b = +b; - this.opacity = +opacity; -} -define(Rgb, rgb$1, extend(Color$3, { - brighter(k) { - k = k == null ? brighter : Math.pow(brighter, k); - return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); - }, - darker(k) { - k = k == null ? darker : Math.pow(darker, k); - return new Rgb(this.r * k, this.g * k, this.b * k, this.opacity); - }, - rgb() { - return this; - }, - clamp() { - return new Rgb(clampi(this.r), clampi(this.g), clampi(this.b), clampa(this.opacity)); - }, - displayable() { - return -0.5 <= this.r && this.r < 255.5 && (-0.5 <= this.g && this.g < 255.5) && (-0.5 <= this.b && this.b < 255.5) && (0 <= this.opacity && this.opacity <= 1); - }, - hex: rgb_formatHex, - // Deprecated! Use color.formatHex. - formatHex: rgb_formatHex, - formatHex8: rgb_formatHex8, - formatRgb: rgb_formatRgb, - toString: rgb_formatRgb -})); -function rgb_formatHex() { - return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}`; -} -function rgb_formatHex8() { - return `#${hex(this.r)}${hex(this.g)}${hex(this.b)}${hex((isNaN(this.opacity) ? 1 : this.opacity) * 255)}`; -} -function rgb_formatRgb() { - const a = clampa(this.opacity); - return `${a === 1 ? "rgb(" : "rgba("}${clampi(this.r)}, ${clampi(this.g)}, ${clampi(this.b)}${a === 1 ? ")" : `, ${a})`}`; -} -function clampa(opacity) { - return isNaN(opacity) ? 1 : Math.max(0, Math.min(1, opacity)); -} -function clampi(value2) { - return Math.max(0, Math.min(255, Math.round(value2) || 0)); -} -function hex(value2) { - value2 = clampi(value2); - return (value2 < 16 ? "0" : "") + value2.toString(16); -} -function hsla(h, s, l, a) { - if (a <= 0) h = s = l = NaN; - else if (l <= 0 || l >= 1) h = s = NaN; - else if (s <= 0) h = NaN; - return new Hsl(h, s, l, a); -} -function hslConvert(o) { - if (o instanceof Hsl) return new Hsl(o.h, o.s, o.l, o.opacity); - if (!(o instanceof Color$3)) o = color(o); - if (!o) return new Hsl(); - if (o instanceof Hsl) return o; - o = o.rgb(); - var r = o.r / 255, g = o.g / 255, b = o.b / 255, min = Math.min(r, g, b), max = Math.max(r, g, b), h = NaN, s = max - min, l = (max + min) / 2; - if (s) { - if (r === max) h = (g - b) / s + (g < b) * 6; - else if (g === max) h = (b - r) / s + 2; - else h = (r - g) / s + 4; - s /= l < 0.5 ? max + min : 2 - max - min; - h *= 60; - } else { - s = l > 0 && l < 1 ? 0 : h; - } - return new Hsl(h, s, l, o.opacity); -} -function hsl$2(h, s, l, opacity) { - return arguments.length === 1 ? hslConvert(h) : new Hsl(h, s, l, opacity == null ? 1 : opacity); -} -function Hsl(h, s, l, opacity) { - this.h = +h; - this.s = +s; - this.l = +l; - this.opacity = +opacity; -} -define(Hsl, hsl$2, extend(Color$3, { - brighter(k) { - k = k == null ? brighter : Math.pow(brighter, k); - return new Hsl(this.h, this.s, this.l * k, this.opacity); - }, - darker(k) { - k = k == null ? darker : Math.pow(darker, k); - return new Hsl(this.h, this.s, this.l * k, this.opacity); - }, - rgb() { - var h = this.h % 360 + (this.h < 0) * 360, s = isNaN(h) || isNaN(this.s) ? 0 : this.s, l = this.l, m2 = l + (l < 0.5 ? l : 1 - l) * s, m1 = 2 * l - m2; - return new Rgb( - hsl2rgb(h >= 240 ? h - 240 : h + 120, m1, m2), - hsl2rgb(h, m1, m2), - hsl2rgb(h < 120 ? h + 240 : h - 120, m1, m2), - this.opacity - ); - }, - clamp() { - return new Hsl(clamph(this.h), clampt(this.s), clampt(this.l), clampa(this.opacity)); - }, - displayable() { - return (0 <= this.s && this.s <= 1 || isNaN(this.s)) && (0 <= this.l && this.l <= 1) && (0 <= this.opacity && this.opacity <= 1); - }, - formatHsl() { - const a = clampa(this.opacity); - return `${a === 1 ? "hsl(" : "hsla("}${clamph(this.h)}, ${clampt(this.s) * 100}%, ${clampt(this.l) * 100}%${a === 1 ? ")" : `, ${a})`}`; - } -})); -function clamph(value2) { - value2 = (value2 || 0) % 360; - return value2 < 0 ? value2 + 360 : value2; -} -function clampt(value2) { - return Math.max(0, Math.min(1, value2 || 0)); -} -function hsl2rgb(h, m1, m2) { - return (h < 60 ? m1 + (m2 - m1) * h / 60 : h < 180 ? m2 : h < 240 ? m1 + (m2 - m1) * (240 - h) / 60 : m1) * 255; -} -const radians = Math.PI / 180; -const degrees$1 = 180 / Math.PI; -const K = 18, Xn = 0.96422, Yn = 1, Zn = 0.82521, t0 = 4 / 29, t1 = 6 / 29, t2 = 3 * t1 * t1, t3 = t1 * t1 * t1; -function labConvert(o) { - if (o instanceof Lab) return new Lab(o.l, o.a, o.b, o.opacity); - if (o instanceof Hcl) return hcl2lab(o); - if (!(o instanceof Rgb)) o = rgbConvert(o); - var r = rgb2lrgb(o.r), g = rgb2lrgb(o.g), b = rgb2lrgb(o.b), y = xyz2lab((0.2225045 * r + 0.7168786 * g + 0.0606169 * b) / Yn), x, z; - if (r === g && g === b) x = z = y; - else { - x = xyz2lab((0.4360747 * r + 0.3850649 * g + 0.1430804 * b) / Xn); - z = xyz2lab((0.0139322 * r + 0.0971045 * g + 0.7141733 * b) / Zn); - } - return new Lab(116 * y - 16, 500 * (x - y), 200 * (y - z), o.opacity); -} -function lab$1(l, a, b, opacity) { - return arguments.length === 1 ? labConvert(l) : new Lab(l, a, b, opacity == null ? 1 : opacity); -} -function Lab(l, a, b, opacity) { - this.l = +l; - this.a = +a; - this.b = +b; - this.opacity = +opacity; -} -define(Lab, lab$1, extend(Color$3, { - brighter(k) { - return new Lab(this.l + K * (k == null ? 1 : k), this.a, this.b, this.opacity); - }, - darker(k) { - return new Lab(this.l - K * (k == null ? 1 : k), this.a, this.b, this.opacity); - }, - rgb() { - var y = (this.l + 16) / 116, x = isNaN(this.a) ? y : y + this.a / 500, z = isNaN(this.b) ? y : y - this.b / 200; - x = Xn * lab2xyz(x); - y = Yn * lab2xyz(y); - z = Zn * lab2xyz(z); - return new Rgb( - lrgb2rgb(3.1338561 * x - 1.6168667 * y - 0.4906146 * z), - lrgb2rgb(-0.9787684 * x + 1.9161415 * y + 0.033454 * z), - lrgb2rgb(0.0719453 * x - 0.2289914 * y + 1.4052427 * z), - this.opacity - ); - } -})); -function xyz2lab(t) { - return t > t3 ? Math.pow(t, 1 / 3) : t / t2 + t0; -} -function lab2xyz(t) { - return t > t1 ? t * t * t : t2 * (t - t0); -} -function lrgb2rgb(x) { - return 255 * (x <= 31308e-7 ? 12.92 * x : 1.055 * Math.pow(x, 1 / 2.4) - 0.055); -} -function rgb2lrgb(x) { - return (x /= 255) <= 0.04045 ? x / 12.92 : Math.pow((x + 0.055) / 1.055, 2.4); -} -function hclConvert(o) { - if (o instanceof Hcl) return new Hcl(o.h, o.c, o.l, o.opacity); - if (!(o instanceof Lab)) o = labConvert(o); - if (o.a === 0 && o.b === 0) return new Hcl(NaN, 0 < o.l && o.l < 100 ? 0 : NaN, o.l, o.opacity); - var h = Math.atan2(o.b, o.a) * degrees$1; - return new Hcl(h < 0 ? h + 360 : h, Math.sqrt(o.a * o.a + o.b * o.b), o.l, o.opacity); -} -function hcl$2(h, c, l, opacity) { - return arguments.length === 1 ? hclConvert(h) : new Hcl(h, c, l, opacity == null ? 1 : opacity); -} -function Hcl(h, c, l, opacity) { - this.h = +h; - this.c = +c; - this.l = +l; - this.opacity = +opacity; -} -function hcl2lab(o) { - if (isNaN(o.h)) return new Lab(o.l, 0, 0, o.opacity); - var h = o.h * radians; - return new Lab(o.l, Math.cos(h) * o.c, Math.sin(h) * o.c, o.opacity); -} -define(Hcl, hcl$2, extend(Color$3, { - brighter(k) { - return new Hcl(this.h, this.c, this.l + K * (k == null ? 1 : k), this.opacity); - }, - darker(k) { - return new Hcl(this.h, this.c, this.l - K * (k == null ? 1 : k), this.opacity); - }, - rgb() { - return hcl2lab(this).rgb(); - } -})); -var A = -0.14861, B = 1.78277, C = -0.29227, D = -0.90649, E = 1.97294, ED = E * D, EB = E * B, BC_DA = B * C - D * A; -function cubehelixConvert(o) { - if (o instanceof Cubehelix) return new Cubehelix(o.h, o.s, o.l, o.opacity); - if (!(o instanceof Rgb)) o = rgbConvert(o); - var r = o.r / 255, g = o.g / 255, b = o.b / 255, l = (BC_DA * b + ED * r - EB * g) / (BC_DA + ED - EB), bl = b - l, k = (E * (g - l) - C * bl) / D, s = Math.sqrt(k * k + bl * bl) / (E * l * (1 - l)), h = s ? Math.atan2(k, bl) * degrees$1 - 120 : NaN; - return new Cubehelix(h < 0 ? h + 360 : h, s, l, o.opacity); -} -function cubehelix$2(h, s, l, opacity) { - return arguments.length === 1 ? cubehelixConvert(h) : new Cubehelix(h, s, l, opacity == null ? 1 : opacity); -} -function Cubehelix(h, s, l, opacity) { - this.h = +h; - this.s = +s; - this.l = +l; - this.opacity = +opacity; -} -define(Cubehelix, cubehelix$2, extend(Color$3, { - brighter(k) { - k = k == null ? brighter : Math.pow(brighter, k); - return new Cubehelix(this.h, this.s, this.l * k, this.opacity); - }, - darker(k) { - k = k == null ? darker : Math.pow(darker, k); - return new Cubehelix(this.h, this.s, this.l * k, this.opacity); - }, - rgb() { - var h = isNaN(this.h) ? 0 : (this.h + 120) * radians, l = +this.l, a = isNaN(this.s) ? 0 : this.s * l * (1 - l), cosh2 = Math.cos(h), sinh2 = Math.sin(h); - return new Rgb( - 255 * (l + a * (A * cosh2 + B * sinh2)), - 255 * (l + a * (C * cosh2 + D * sinh2)), - 255 * (l + a * (E * cosh2)), - this.opacity - ); - } -})); -function basis(t12, v0, v1, v2, v3) { - var t22 = t12 * t12, t32 = t22 * t12; - return ((1 - 3 * t12 + 3 * t22 - t32) * v0 + (4 - 6 * t22 + 3 * t32) * v1 + (1 + 3 * t12 + 3 * t22 - 3 * t32) * v2 + t32 * v3) / 6; -} -function basis$1(values) { - var n = values.length - 1; - return function(t) { - var i = t <= 0 ? t = 0 : t >= 1 ? (t = 1, n - 1) : Math.floor(t * n), v1 = values[i], v2 = values[i + 1], v0 = i > 0 ? values[i - 1] : 2 * v1 - v2, v3 = i < n - 1 ? values[i + 2] : 2 * v2 - v1; - return basis((t - i / n) * n, v0, v1, v2, v3); - }; -} -function basisClosed(values) { - var n = values.length; - return function(t) { - var i = Math.floor(((t %= 1) < 0 ? ++t : t) * n), v0 = values[(i + n - 1) % n], v1 = values[i % n], v2 = values[(i + 1) % n], v3 = values[(i + 2) % n]; - return basis((t - i / n) * n, v0, v1, v2, v3); - }; -} -const constant = (x) => () => x; -function linear(a, d) { - return function(t) { - return a + t * d; - }; -} -function exponential(a, b, y) { - return a = Math.pow(a, y), b = Math.pow(b, y) - a, y = 1 / y, function(t) { - return Math.pow(a + t * b, y); - }; -} -function hue$1(a, b) { - var d = b - a; - return d ? linear(a, d > 180 || d < -180 ? d - 360 * Math.round(d / 360) : d) : constant(isNaN(a) ? b : a); -} -function gamma(y) { - return (y = +y) === 1 ? nogamma : function(a, b) { - return b - a ? exponential(a, b, y) : constant(isNaN(a) ? b : a); - }; -} -function nogamma(a, b) { - var d = b - a; - return d ? linear(a, d) : constant(isNaN(a) ? b : a); -} -const rgb = function rgbGamma(y) { - var color2 = gamma(y); - function rgb2(start, end) { - var r = color2((start = rgb$1(start)).r, (end = rgb$1(end)).r), g = color2(start.g, end.g), b = color2(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); - return function(t) { - start.r = r(t); - start.g = g(t); - start.b = b(t); - start.opacity = opacity(t); - return start + ""; - }; - } - rgb2.gamma = rgbGamma; - return rgb2; -}(1); -function rgbSpline(spline) { - return function(colors) { - var n = colors.length, r = new Array(n), g = new Array(n), b = new Array(n), i, color2; - for (i = 0; i < n; ++i) { - color2 = rgb$1(colors[i]); - r[i] = color2.r || 0; - g[i] = color2.g || 0; - b[i] = color2.b || 0; - } - r = spline(r); - g = spline(g); - b = spline(b); - color2.opacity = 1; - return function(t) { - color2.r = r(t); - color2.g = g(t); - color2.b = b(t); - return color2 + ""; - }; - }; -} -var rgbBasis = rgbSpline(basis$1); -var rgbBasisClosed = rgbSpline(basisClosed); -function numberArray(a, b) { - if (!b) b = []; - var n = a ? Math.min(b.length, a.length) : 0, c = b.slice(), i; - return function(t) { - for (i = 0; i < n; ++i) c[i] = a[i] * (1 - t) + b[i] * t; - return c; - }; -} -function isNumberArray(x) { - return ArrayBuffer.isView(x) && !(x instanceof DataView); -} -function array(a, b) { - return (isNumberArray(b) ? numberArray : genericArray)(a, b); -} -function genericArray(a, b) { - var nb = b ? b.length : 0, na = a ? Math.min(nb, a.length) : 0, x = new Array(na), c = new Array(nb), i; - for (i = 0; i < na; ++i) x[i] = value(a[i], b[i]); - for (; i < nb; ++i) c[i] = b[i]; - return function(t) { - for (i = 0; i < na; ++i) c[i] = x[i](t); - return c; - }; -} -function date(a, b) { - var d = /* @__PURE__ */ new Date(); - return a = +a, b = +b, function(t) { - return d.setTime(a * (1 - t) + b * t), d; - }; -} -function number(a, b) { - return a = +a, b = +b, function(t) { - return a * (1 - t) + b * t; - }; -} -function object(a, b) { - var i = {}, c = {}, k; - if (a === null || typeof a !== "object") a = {}; - if (b === null || typeof b !== "object") b = {}; - for (k in b) { - if (k in a) { - i[k] = value(a[k], b[k]); - } else { - c[k] = b[k]; - } - } - return function(t) { - for (k in i) c[k] = i[k](t); - return c; - }; -} -var reA = /[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g, reB = new RegExp(reA.source, "g"); -function zero(b) { - return function() { - return b; - }; -} -function one(b) { - return function(t) { - return b(t) + ""; - }; -} -function string(a, b) { - var bi = reA.lastIndex = reB.lastIndex = 0, am, bm, bs, i = -1, s = [], q = []; - a = a + "", b = b + ""; - while ((am = reA.exec(a)) && (bm = reB.exec(b))) { - if ((bs = bm.index) > bi) { - bs = b.slice(bi, bs); - if (s[i]) s[i] += bs; - else s[++i] = bs; - } - if ((am = am[0]) === (bm = bm[0])) { - if (s[i]) s[i] += bm; - else s[++i] = bm; - } else { - s[++i] = null; - q.push({ i, x: number(am, bm) }); - } - bi = reB.lastIndex; - } - if (bi < b.length) { - bs = b.slice(bi); - if (s[i]) s[i] += bs; - else s[++i] = bs; - } - return s.length < 2 ? q[0] ? one(q[0].x) : zero(b) : (b = q.length, function(t) { - for (var i2 = 0, o; i2 < b; ++i2) s[(o = q[i2]).i] = o.x(t); - return s.join(""); - }); -} -function value(a, b) { - var t = typeof b, c; - return b == null || t === "boolean" ? constant(b) : (t === "number" ? number : t === "string" ? (c = color(b)) ? (b = c, rgb) : string : b instanceof color ? rgb : b instanceof Date ? date : isNumberArray(b) ? numberArray : Array.isArray(b) ? genericArray : typeof b.valueOf !== "function" && typeof b.toString !== "function" || isNaN(b) ? object : number)(a, b); -} -function discrete(range) { - var n = range.length; - return function(t) { - return range[Math.max(0, Math.min(n - 1, Math.floor(t * n)))]; - }; -} -function hue(a, b) { - var i = hue$1(+a, +b); - return function(t) { - var x = i(t); - return x - 360 * Math.floor(x / 360); - }; -} -function round(a, b) { - return a = +a, b = +b, function(t) { - return Math.round(a * (1 - t) + b * t); - }; -} -var degrees = 180 / Math.PI; -var identity2 = { - translateX: 0, - translateY: 0, - rotate: 0, - skewX: 0, - scaleX: 1, - scaleY: 1 -}; -function decompose(a, b, c, d, e, f) { - var scaleX, scaleY, skewX; - if (scaleX = Math.sqrt(a * a + b * b)) a /= scaleX, b /= scaleX; - if (skewX = a * c + b * d) c -= a * skewX, d -= b * skewX; - if (scaleY = Math.sqrt(c * c + d * d)) c /= scaleY, d /= scaleY, skewX /= scaleY; - if (a * d < b * c) a = -a, b = -b, skewX = -skewX, scaleX = -scaleX; - return { - translateX: e, - translateY: f, - rotate: Math.atan2(b, a) * degrees, - skewX: Math.atan(skewX) * degrees, - scaleX, - scaleY - }; -} -var svgNode; -function parseCss(value2) { - const m = new (typeof DOMMatrix === "function" ? DOMMatrix : WebKitCSSMatrix)(value2 + ""); - return m.isIdentity ? identity2 : decompose(m.a, m.b, m.c, m.d, m.e, m.f); -} -function parseSvg(value2) { - if (value2 == null) return identity2; - if (!svgNode) svgNode = document.createElementNS("http://www.w3.org/2000/svg", "g"); - svgNode.setAttribute("transform", value2); - if (!(value2 = svgNode.transform.baseVal.consolidate())) return identity2; - value2 = value2.matrix; - return decompose(value2.a, value2.b, value2.c, value2.d, value2.e, value2.f); -} -function interpolateTransform(parse2, pxComma, pxParen, degParen) { - function pop(s) { - return s.length ? s.pop() + " " : ""; - } - function translate2(xa, ya, xb, yb, s, q) { - if (xa !== xb || ya !== yb) { - var i = s.push("translate(", null, pxComma, null, pxParen); - q.push({ i: i - 4, x: number(xa, xb) }, { i: i - 2, x: number(ya, yb) }); - } else if (xb || yb) { - s.push("translate(" + xb + pxComma + yb + pxParen); - } - } - function rotate2(a, b, s, q) { - if (a !== b) { - if (a - b > 180) b += 360; - else if (b - a > 180) a += 360; - q.push({ i: s.push(pop(s) + "rotate(", null, degParen) - 2, x: number(a, b) }); - } else if (b) { - s.push(pop(s) + "rotate(" + b + degParen); - } - } - function skewX(a, b, s, q) { - if (a !== b) { - q.push({ i: s.push(pop(s) + "skewX(", null, degParen) - 2, x: number(a, b) }); - } else if (b) { - s.push(pop(s) + "skewX(" + b + degParen); - } - } - function scale2(xa, ya, xb, yb, s, q) { - if (xa !== xb || ya !== yb) { - var i = s.push(pop(s) + "scale(", null, ",", null, ")"); - q.push({ i: i - 4, x: number(xa, xb) }, { i: i - 2, x: number(ya, yb) }); - } else if (xb !== 1 || yb !== 1) { - s.push(pop(s) + "scale(" + xb + "," + yb + ")"); - } - } - return function(a, b) { - var s = [], q = []; - a = parse2(a), b = parse2(b); - translate2(a.translateX, a.translateY, b.translateX, b.translateY, s, q); - rotate2(a.rotate, b.rotate, s, q); - skewX(a.skewX, b.skewX, s, q); - scale2(a.scaleX, a.scaleY, b.scaleX, b.scaleY, s, q); - a = b = null; - return function(t) { - var i = -1, n = q.length, o; - while (++i < n) s[(o = q[i]).i] = o.x(t); - return s.join(""); - }; - }; -} -var interpolateTransformCss = interpolateTransform(parseCss, "px, ", "px)", "deg)"); -var interpolateTransformSvg = interpolateTransform(parseSvg, ", ", ")", ")"); -var epsilon2 = 1e-12; -function cosh(x) { - return ((x = Math.exp(x)) + 1 / x) / 2; -} -function sinh(x) { - return ((x = Math.exp(x)) - 1 / x) / 2; -} -function tanh(x) { - return ((x = Math.exp(2 * x)) - 1) / (x + 1); -} -const zoom = function zoomRho(rho, rho2, rho4) { - function zoom2(p0, p1) { - var ux0 = p0[0], uy0 = p0[1], w0 = p0[2], ux1 = p1[0], uy1 = p1[1], w1 = p1[2], dx = ux1 - ux0, dy = uy1 - uy0, d2 = dx * dx + dy * dy, i, S; - if (d2 < epsilon2) { - S = Math.log(w1 / w0) / rho; - i = function(t) { - return [ - ux0 + t * dx, - uy0 + t * dy, - w0 * Math.exp(rho * t * S) - ]; - }; - } else { - var d1 = Math.sqrt(d2), b0 = (w1 * w1 - w0 * w0 + rho4 * d2) / (2 * w0 * rho2 * d1), b1 = (w1 * w1 - w0 * w0 - rho4 * d2) / (2 * w1 * rho2 * d1), r0 = Math.log(Math.sqrt(b0 * b0 + 1) - b0), r1 = Math.log(Math.sqrt(b1 * b1 + 1) - b1); - S = (r1 - r0) / rho; - i = function(t) { - var s = t * S, coshr0 = cosh(r0), u = w0 / (rho2 * d1) * (coshr0 * tanh(rho * s + r0) - sinh(r0)); - return [ - ux0 + u * dx, - uy0 + u * dy, - w0 * coshr0 / cosh(rho * s + r0) - ]; - }; - } - i.duration = S * 1e3 * rho / Math.SQRT2; - return i; - } - zoom2.rho = function(_2) { - var _1 = Math.max(1e-3, +_2), _22 = _1 * _1, _4 = _22 * _22; - return zoomRho(_1, _22, _4); - }; - return zoom2; -}(Math.SQRT2, 2, 4); -function hsl(hue2) { - return function(start, end) { - var h = hue2((start = hsl$2(start)).h, (end = hsl$2(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); - return function(t) { - start.h = h(t); - start.s = s(t); - start.l = l(t); - start.opacity = opacity(t); - return start + ""; - }; - }; -} -const hsl$1 = hsl(hue$1); -var hslLong = hsl(nogamma); -function lab(start, end) { - var l = nogamma((start = lab$1(start)).l, (end = lab$1(end)).l), a = nogamma(start.a, end.a), b = nogamma(start.b, end.b), opacity = nogamma(start.opacity, end.opacity); - return function(t) { - start.l = l(t); - start.a = a(t); - start.b = b(t); - start.opacity = opacity(t); - return start + ""; - }; -} -function hcl(hue2) { - return function(start, end) { - var h = hue2((start = hcl$2(start)).h, (end = hcl$2(end)).h), c = nogamma(start.c, end.c), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); - return function(t) { - start.h = h(t); - start.c = c(t); - start.l = l(t); - start.opacity = opacity(t); - return start + ""; - }; - }; -} -const hcl$1 = hcl(hue$1); -var hclLong = hcl(nogamma); -function cubehelix(hue2) { - return function cubehelixGamma(y) { - y = +y; - function cubehelix2(start, end) { - var h = hue2((start = cubehelix$2(start)).h, (end = cubehelix$2(end)).h), s = nogamma(start.s, end.s), l = nogamma(start.l, end.l), opacity = nogamma(start.opacity, end.opacity); - return function(t) { - start.h = h(t); - start.s = s(t); - start.l = l(Math.pow(t, y)); - start.opacity = opacity(t); - return start + ""; - }; - } - cubehelix2.gamma = cubehelixGamma; - return cubehelix2; - }(1); -} -const cubehelix$1 = cubehelix(hue$1); -var cubehelixLong = cubehelix(nogamma); -function piecewise(interpolate2, values) { - if (values === void 0) values = interpolate2, interpolate2 = value; - var i = 0, n = values.length - 1, v = values[0], I = new Array(n < 0 ? 0 : n); - while (i < n) I[i] = interpolate2(v, v = values[++i]); - return function(t) { - var i2 = Math.max(0, Math.min(n - 1, Math.floor(t *= n))); - return I[i2](t - i2); - }; -} -function quantize(interpolator, n) { - var samples = new Array(n); - for (var i = 0; i < n; ++i) samples[i] = interpolator(i / (n - 1)); - return samples; -} -const src = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({ - __proto__: null, - interpolate: value, - interpolateArray: array, - interpolateBasis: basis$1, - interpolateBasisClosed: basisClosed, - interpolateCubehelix: cubehelix$1, - interpolateCubehelixLong: cubehelixLong, - interpolateDate: date, - interpolateDiscrete: discrete, - interpolateHcl: hcl$1, - interpolateHclLong: hclLong, - interpolateHsl: hsl$1, - interpolateHslLong: hslLong, - interpolateHue: hue, - interpolateLab: lab, - interpolateNumber: number, - interpolateNumberArray: numberArray, - interpolateObject: object, - interpolateRgb: rgb, - interpolateRgbBasis: rgbBasis, - interpolateRgbBasisClosed: rgbBasisClosed, - interpolateRound: round, - interpolateString: string, - interpolateTransformCss, - interpolateTransformSvg, - interpolateZoom: zoom, - piecewise, - quantize -}, Symbol.toStringTag, { value: "Module" })); -const require$$2 = /* @__PURE__ */ index$3.getAugmentedNamespace(src); -var flip_tree = function flipTree(node, size, opts) { - var tmp; - if (opts.swapXY) { - tmp = node.x0; - node.x0 = node.y0; - node.y0 = tmp; - tmp = node.x1; - node.x1 = node.y1; - node.y1 = tmp; - } - if (opts.flipX) { - tmp = node.x0; - node.x0 = size[0] - node.x1; - node.x1 = size[0] - tmp; - } - if (opts.flipY) { - tmp = node.y0; - node.y0 = size[1] - node.y1; - node.y1 = size[1] - tmp; - } - var children = node.children; - if (children) { - for (var i = 0; i < children.length; i++) { - flipTree(children[i], size, opts); - } - } -}; -var d3Hierarchy = require$$1; -var flipTree2 = flip_tree; -var partition$2 = function partition(entry, size, opts) { - var flipX = opts.flipX; - var flipY = opts.flipY; - var swapXY = opts.packing === "dice-slice"; - var top = opts.pad[flipY ? "bottom" : "top"]; - var left = opts.pad[flipX ? "right" : "left"]; - var right = opts.pad[flipX ? "left" : "right"]; - var bottom = opts.pad[flipY ? "top" : "bottom"]; - var tmp; - if (swapXY) { - tmp = left; - left = top; - top = tmp; - tmp = right; - right = bottom; - bottom = tmp; - } - var result = d3Hierarchy.treemap().tile(getTilingMethod(opts.packing, opts.squarifyratio)).paddingInner(opts.pad.inner).paddingLeft(left).paddingRight(right).paddingTop(top).paddingBottom(bottom).size( - swapXY ? [size[1], size[0]] : size - )(entry); - if (swapXY || flipX || flipY) { - flipTree2(result, size, { - swapXY, - flipX, - flipY - }); - } - return result; -}; -function getTilingMethod(key, squarifyratio) { - switch (key) { - case "squarify": - return d3Hierarchy.treemapSquarify.ratio(squarifyratio); - case "binary": - return d3Hierarchy.treemapBinary; - case "dice": - return d3Hierarchy.treemapDice; - case "slice": - return d3Hierarchy.treemapSlice; - default: - return d3Hierarchy.treemapSliceDice; - } -} -var Drawing$2 = drawingExports; -var Color$2 = colorExports; -var fill_one = function fillOne2(s, pt, trace, gd, fadedColor) { - var cdi = pt.data.data; - var ptNumber = cdi.i; - var color2 = fadedColor || cdi.color; - if (ptNumber >= 0) { - pt.i = cdi.i; - var marker2 = trace.marker; - if (marker2.pattern) { - if (!marker2.colors || !marker2.pattern.shape) { - marker2.color = color2; - pt.color = color2; - } - } else { - marker2.color = color2; - pt.color = color2; - } - Drawing$2.pointStyle(s, trace, gd, pt); - } else { - Color$2.fill(s, color2); - } -}; -var d3$5 = d3Exports; -var Color$1 = colorExports; -var Lib$5 = libExports; -var helpers$5 = helpers$6; -var resizeText$1 = uniform_text.resizeText; -var fillOne$1 = fill_one; -function style4(gd) { - var s = gd._fullLayout._treemaplayer.selectAll(".trace"); - resizeText$1(gd, s, "treemap"); - s.each(function(cd) { - var gTrace = d3$5.select(this); - var cd0 = cd[0]; - var trace = cd0.trace; - gTrace.style("opacity", trace.opacity); - gTrace.selectAll("path.surface").each(function(pt) { - d3$5.select(this).call(styleOne$3, pt, trace, gd, { - hovered: false - }); - }); - }); -} -function styleOne$3(s, pt, trace, gd, opts) { - var hovered = (opts || {}).hovered; - var cdi = pt.data.data; - var ptNumber = cdi.i; - var lineColor; - var lineWidth; - var fillColor = cdi.color; - var isRoot = helpers$5.isHierarchyRoot(pt); - var opacity = 1; - if (hovered) { - lineColor = trace._hovered.marker.line.color; - lineWidth = trace._hovered.marker.line.width; - } else { - if (isRoot && fillColor === trace.root.color) { - opacity = 100; - lineColor = "rgba(0,0,0,0)"; - lineWidth = 0; - } else { - lineColor = Lib$5.castOption(trace, ptNumber, "marker.line.color") || Color$1.defaultLine; - lineWidth = Lib$5.castOption(trace, ptNumber, "marker.line.width") || 0; - if (!trace._hasColorscale && !pt.onPathbar) { - var depthfade = trace.marker.depthfade; - if (depthfade) { - var fadedColor = Color$1.combine(Color$1.addOpacity(trace._backgroundColor, 0.75), fillColor); - var n; - if (depthfade === true) { - var maxDepth = helpers$5.getMaxDepth(trace); - if (isFinite(maxDepth)) { - if (helpers$5.isLeaf(pt)) { - n = 0; - } else { - n = trace._maxVisibleLayers - (pt.data.depth - trace._entryDepth); - } - } else { - n = pt.data.height + 1; - } - } else { - n = pt.data.depth - trace._entryDepth; - if (!trace._atRootLevel) n++; - } - if (n > 0) { - for (var i = 0; i < n; i++) { - var ratio = 0.5 * i / n; - fillColor = Color$1.combine(Color$1.addOpacity(fadedColor, ratio), fillColor); - } - } - } - } - } - } - s.call(fillOne$1, pt, trace, gd, fillColor).style("stroke-width", lineWidth).call(Color$1.stroke, lineColor).style("opacity", opacity); -} -var style_1$1 = { - style: style4, - styleOne: styleOne$3 -}; -var d3$4 = d3Exports; -var Registry = registry; -var appendArrayPointValue = helpers$J.appendArrayPointValue; -var Fx = fx$1; -var Lib$4 = libExports; -var Events = events; -var helpers$4 = helpers$6; -var pieHelpers = helpers$F; -var formatValue = pieHelpers.formatPieValue; -var fx = function attachFxHandlers(sliceTop, entry, gd, cd, opts) { - var cd0 = cd[0]; - var trace = cd0.trace; - var hierarchy2 = cd0.hierarchy; - var isSunburst = trace.type === "sunburst"; - var isTreemapOrIcicle = trace.type === "treemap" || trace.type === "icicle"; - if (!("_hasHoverLabel" in trace)) trace._hasHoverLabel = false; - if (!("_hasHoverEvent" in trace)) trace._hasHoverEvent = false; - var onMouseOver = function(pt) { - var fullLayoutNow = gd._fullLayout; - if (gd._dragging || fullLayoutNow.hovermode === false) return; - var traceNow = gd._fullData[trace.index]; - var cdi = pt.data.data; - var ptNumber = cdi.i; - var isRoot = helpers$4.isHierarchyRoot(pt); - var parent = helpers$4.getParent(hierarchy2, pt); - var val = helpers$4.getValue(pt); - var _cast = function(astr) { - return Lib$4.castOption(traceNow, ptNumber, astr); - }; - var hovertemplate = _cast("hovertemplate"); - var hoverinfo = Fx.castHoverinfo(traceNow, fullLayoutNow, ptNumber); - var separators = fullLayoutNow.separators; - var eventData5; - if (hovertemplate || hoverinfo && hoverinfo !== "none" && hoverinfo !== "skip") { - var hoverCenterX; - var hoverCenterY; - if (isSunburst) { - hoverCenterX = cd0.cx + pt.pxmid[0] * (1 - pt.rInscribed); - hoverCenterY = cd0.cy + pt.pxmid[1] * (1 - pt.rInscribed); - } - if (isTreemapOrIcicle) { - hoverCenterX = pt._hoverX; - hoverCenterY = pt._hoverY; - } - var hoverPt = {}; - var parts = []; - var thisText = []; - var hasFlag = function(flag) { - return parts.indexOf(flag) !== -1; - }; - if (hoverinfo) { - parts = hoverinfo === "all" ? traceNow._module.attributes.hoverinfo.flags : hoverinfo.split("+"); - } - hoverPt.label = cdi.label; - if (hasFlag("label") && hoverPt.label) thisText.push(hoverPt.label); - if (cdi.hasOwnProperty("v")) { - hoverPt.value = cdi.v; - hoverPt.valueLabel = formatValue(hoverPt.value, separators); - if (hasFlag("value")) thisText.push(hoverPt.valueLabel); - } - hoverPt.currentPath = pt.currentPath = helpers$4.getPath(pt.data); - if (hasFlag("current path") && !isRoot) { - thisText.push(hoverPt.currentPath); - } - var tx; - var allPercents = []; - var insertPercent = function() { - if (allPercents.indexOf(tx) === -1) { - thisText.push(tx); - allPercents.push(tx); - } - }; - hoverPt.percentParent = pt.percentParent = val / helpers$4.getValue(parent); - hoverPt.parent = pt.parentString = helpers$4.getPtLabel(parent); - if (hasFlag("percent parent")) { - tx = helpers$4.formatPercent(hoverPt.percentParent, separators) + " of " + hoverPt.parent; - insertPercent(); - } - hoverPt.percentEntry = pt.percentEntry = val / helpers$4.getValue(entry); - hoverPt.entry = pt.entry = helpers$4.getPtLabel(entry); - if (hasFlag("percent entry") && !isRoot && !pt.onPathbar) { - tx = helpers$4.formatPercent(hoverPt.percentEntry, separators) + " of " + hoverPt.entry; - insertPercent(); - } - hoverPt.percentRoot = pt.percentRoot = val / helpers$4.getValue(hierarchy2); - hoverPt.root = pt.root = helpers$4.getPtLabel(hierarchy2); - if (hasFlag("percent root") && !isRoot) { - tx = helpers$4.formatPercent(hoverPt.percentRoot, separators) + " of " + hoverPt.root; - insertPercent(); - } - hoverPt.text = _cast("hovertext") || _cast("text"); - if (hasFlag("text")) { - tx = hoverPt.text; - if (Lib$4.isValidTextValue(tx)) thisText.push(tx); - } - eventData5 = [makeEventData(pt, traceNow, opts.eventDataKeys)]; - var hoverItems = { - trace: traceNow, - y: hoverCenterY, - _x0: pt._x0, - _x1: pt._x1, - _y0: pt._y0, - _y1: pt._y1, - text: thisText.join("
"), - name: hovertemplate || hasFlag("name") ? traceNow.name : void 0, - color: _cast("hoverlabel.bgcolor") || cdi.color, - borderColor: _cast("hoverlabel.bordercolor"), - fontFamily: _cast("hoverlabel.font.family"), - fontSize: _cast("hoverlabel.font.size"), - fontColor: _cast("hoverlabel.font.color"), - fontWeight: _cast("hoverlabel.font.weight"), - fontStyle: _cast("hoverlabel.font.style"), - fontVariant: _cast("hoverlabel.font.variant"), - nameLength: _cast("hoverlabel.namelength"), - textAlign: _cast("hoverlabel.align"), - hovertemplate, - hovertemplateLabels: hoverPt, - eventData: eventData5 - }; - if (isSunburst) { - hoverItems.x0 = hoverCenterX - pt.rInscribed * pt.rpx1; - hoverItems.x1 = hoverCenterX + pt.rInscribed * pt.rpx1; - hoverItems.idealAlign = pt.pxmid[0] < 0 ? "left" : "right"; - } - if (isTreemapOrIcicle) { - hoverItems.x = hoverCenterX; - hoverItems.idealAlign = hoverCenterX < 0 ? "left" : "right"; - } - var bbox = []; - Fx.loneHover(hoverItems, { - container: fullLayoutNow._hoverlayer.node(), - outerContainer: fullLayoutNow._paper.node(), - gd, - inOut_bbox: bbox - }); - eventData5[0].bbox = bbox[0]; - trace._hasHoverLabel = true; - } - if (isTreemapOrIcicle) { - var slice2 = sliceTop.select("path.surface"); - opts.styleOne(slice2, pt, traceNow, gd, { - hovered: true - }); - } - trace._hasHoverEvent = true; - gd.emit("plotly_hover", { - points: eventData5 || [makeEventData(pt, traceNow, opts.eventDataKeys)], - event: d3$4.event - }); - }; - var onMouseOut = function(evt) { - var fullLayoutNow = gd._fullLayout; - var traceNow = gd._fullData[trace.index]; - var pt = d3$4.select(this).datum(); - if (trace._hasHoverEvent) { - evt.originalEvent = d3$4.event; - gd.emit("plotly_unhover", { - points: [makeEventData(pt, traceNow, opts.eventDataKeys)], - event: d3$4.event - }); - trace._hasHoverEvent = false; - } - if (trace._hasHoverLabel) { - Fx.loneUnhover(fullLayoutNow._hoverlayer.node()); - trace._hasHoverLabel = false; - } - if (isTreemapOrIcicle) { - var slice2 = sliceTop.select("path.surface"); - opts.styleOne(slice2, pt, traceNow, gd, { - hovered: false - }); - } - }; - var onClick2 = function(pt) { - var fullLayoutNow = gd._fullLayout; - var traceNow = gd._fullData[trace.index]; - var noTransition = isSunburst && (helpers$4.isHierarchyRoot(pt) || helpers$4.isLeaf(pt)); - var id = helpers$4.getPtId(pt); - var nextEntry = helpers$4.isEntry(pt) ? helpers$4.findEntryWithChild(hierarchy2, id) : helpers$4.findEntryWithLevel(hierarchy2, id); - var nextLevel = helpers$4.getPtId(nextEntry); - var typeClickEvtData = { - points: [makeEventData(pt, traceNow, opts.eventDataKeys)], - event: d3$4.event - }; - if (!noTransition) typeClickEvtData.nextLevel = nextLevel; - var clickVal = Events.triggerHandler(gd, "plotly_" + trace.type + "click", typeClickEvtData); - if (clickVal !== false && fullLayoutNow.hovermode) { - gd._hoverdata = [makeEventData(pt, traceNow, opts.eventDataKeys)]; - Fx.click(gd, d3$4.event); - } - if (noTransition) return; - if (clickVal === false) return; - if (gd._dragging) return; - if (gd._transitioning) return; - Registry.call("_storeDirectGUIEdit", traceNow, fullLayoutNow._tracePreGUI[traceNow.uid], { - level: traceNow.level - }); - var frame = { - data: [{ level: nextLevel }], - traces: [trace.index] - }; - var animOpts = { - frame: { - redraw: false, - duration: opts.transitionTime - }, - transition: { - duration: opts.transitionTime, - easing: opts.transitionEasing - }, - mode: "immediate", - fromcurrent: true - }; - Fx.loneUnhover(fullLayoutNow._hoverlayer.node()); - Registry.call("animate", gd, frame, animOpts); - }; - sliceTop.on("mouseover", onMouseOver); - sliceTop.on("mouseout", onMouseOut); - sliceTop.on("click", onClick2); -}; -function makeEventData(pt, trace, keys) { - var cdi = pt.data.data; - var out = { - curveNumber: trace.index, - pointNumber: cdi.i, - data: trace._input, - fullData: trace - // TODO more things like 'children', 'siblings', 'hierarchy? - }; - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key in pt) out[key] = pt[key]; - } - if ("parentString" in pt && !helpers$4.isHierarchyRoot(pt)) out.parent = pt.parentString; - appendArrayPointValue(out, trace, cdi.i); - return out; -} -var d3$3 = d3Exports; -var Lib$3 = libExports; -var Drawing$1 = drawingExports; -var svgTextUtils$1 = svg_text_utils; -var partition$1 = partition$2; -var styleOne$2 = style_1$1.styleOne; -var constants$2 = constants$4; -var helpers$3 = helpers$6; -var attachFxHandlers$1 = fx; -var onPathbar$1 = true; -var draw_ancestors = function drawAncestors(gd, cd, entry, slices, opts) { - var barDifY = opts.barDifY; - var width = opts.width; - var height = opts.height; - var viewX = opts.viewX; - var viewY = opts.viewY; - var pathSlice = opts.pathSlice; - var toMoveInsideSlice = opts.toMoveInsideSlice; - var strTransform = opts.strTransform; - var hasTransition2 = opts.hasTransition; - var handleSlicesExit = opts.handleSlicesExit; - var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator; - var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator; - var refRect = {}; - var isStatic = gd._context.staticPlot; - var fullLayout = gd._fullLayout; - var cd0 = cd[0]; - var trace = cd0.trace; - var hierarchy2 = cd0.hierarchy; - var eachWidth = width / trace._entryDepth; - var pathIds = helpers$3.listPath(entry.data, "id"); - var sliceData = partition$1(hierarchy2.copy(), [width, height], { - packing: "dice", - pad: { - inner: 0, - top: 0, - left: 0, - right: 0, - bottom: 0 - } - }).descendants(); - sliceData = sliceData.filter(function(pt) { - var level = pathIds.indexOf(pt.data.id); - if (level === -1) return false; - pt.x0 = eachWidth * level; - pt.x1 = eachWidth * (level + 1); - pt.y0 = barDifY; - pt.y1 = barDifY + height; - pt.onPathbar = true; - return true; - }); - sliceData.reverse(); - slices = slices.data(sliceData, helpers$3.getPtId); - slices.enter().append("g").classed("pathbar", true); - handleSlicesExit(slices, onPathbar$1, refRect, [width, height], pathSlice); - slices.order(); - var updateSlices = slices; - if (hasTransition2) { - updateSlices = updateSlices.transition().each("end", function() { - var sliceTop = d3$3.select(this); - helpers$3.setSliceCursor(sliceTop, gd, { - hideOnRoot: false, - hideOnLeaves: false, - isTransitioning: false - }); - }); - } - updateSlices.each(function(pt) { - pt._x0 = viewX(pt.x0); - pt._x1 = viewX(pt.x1); - pt._y0 = viewY(pt.y0); - pt._y1 = viewY(pt.y1); - pt._hoverX = viewX(pt.x1 - Math.min(width, height) / 2); - pt._hoverY = viewY(pt.y1 - height / 2); - var sliceTop = d3$3.select(this); - var slicePath = Lib$3.ensureSingle(sliceTop, "path", "surface", function(s) { - s.style("pointer-events", isStatic ? "none" : "all"); - }); - if (hasTransition2) { - slicePath.transition().attrTween("d", function(pt2) { - var interp = makeUpdateSliceInterpolator(pt2, onPathbar$1, refRect, [width, height]); - return function(t) { - return pathSlice(interp(t)); - }; - }); - } else { - slicePath.attr("d", pathSlice); - } - sliceTop.call(attachFxHandlers$1, entry, gd, cd, { - styleOne: styleOne$2, - eventDataKeys: constants$2.eventDataKeys, - transitionTime: constants$2.CLICK_TRANSITION_TIME, - transitionEasing: constants$2.CLICK_TRANSITION_EASING - }).call(helpers$3.setSliceCursor, gd, { - hideOnRoot: false, - hideOnLeaves: false, - isTransitioning: gd._transitioning - }); - slicePath.call(styleOne$2, pt, trace, gd, { - hovered: false - }); - pt._text = (helpers$3.getPtLabel(pt) || "").split("
").join(" ") || ""; - var sliceTextGroup = Lib$3.ensureSingle(sliceTop, "g", "slicetext"); - var sliceText = Lib$3.ensureSingle(sliceTextGroup, "text", "", function(s) { - s.attr("data-notex", 1); - }); - var font2 = Lib$3.ensureUniformFontSize(gd, helpers$3.determineTextFont(trace, pt, fullLayout.font, { - onPathbar: true - })); - sliceText.text(pt._text || " ").classed("slicetext", true).attr("text-anchor", "start").call(Drawing$1.font, font2).call(svgTextUtils$1.convertToTspans, gd); - pt.textBB = Drawing$1.bBox(sliceText.node()); - pt.transform = toMoveInsideSlice(pt, { - fontSize: font2.size, - onPathbar: true - }); - pt.transform.fontSize = font2.size; - if (hasTransition2) { - sliceText.transition().attrTween("transform", function(pt2) { - var interp = makeUpdateTextInterpolator(pt2, onPathbar$1, refRect, [width, height]); - return function(t) { - return strTransform(interp(t)); - }; - }); - } else { - sliceText.attr("transform", strTransform(pt)); - } - }); -}; -var d3$2 = d3Exports; -var interpolate = require$$2.interpolate; -var helpers$2 = helpers$6; -var Lib$2 = libExports; -var TEXTPAD = constants$f.TEXTPAD; -var barPlot = plot_1$1; -var toMoveInsideBar = barPlot.toMoveInsideBar; -var uniformText$1 = uniform_text; -var recordMinTextSize = uniformText$1.recordMinTextSize; -var constants$1 = constants$4; -var drawAncestors2 = draw_ancestors; -function getKey(pt) { - return helpers$2.isHierarchyRoot(pt) ? "" : ( - // don't use the dummyId - helpers$2.getPtId(pt) - ); -} -var plot_one = function plotOne(gd, cd, element, transitionOpts, drawDescendants3) { - var fullLayout = gd._fullLayout; - var cd0 = cd[0]; - var trace = cd0.trace; - var type = trace.type; - var isIcicle = type === "icicle"; - var hierarchy2 = cd0.hierarchy; - var entry = helpers$2.findEntryWithLevel(hierarchy2, trace.level); - var gTrace = d3$2.select(element); - var selAncestors = gTrace.selectAll("g.pathbar"); - var selDescendants = gTrace.selectAll("g.slice"); - if (!entry) { - selAncestors.remove(); - selDescendants.remove(); - return; - } - var isRoot = helpers$2.isHierarchyRoot(entry); - var hasTransition2 = !fullLayout.uniformtext.mode && helpers$2.hasTransition(transitionOpts); - var maxDepth = helpers$2.getMaxDepth(trace); - var hasVisibleDepth = function(pt) { - return pt.data.depth - entry.data.depth < maxDepth; - }; - var gs = fullLayout._size; - var domain2 = trace.domain; - var vpw = gs.w * (domain2.x[1] - domain2.x[0]); - var vph = gs.h * (domain2.y[1] - domain2.y[0]); - var barW = vpw; - var barH = trace.pathbar.thickness; - var barPad = trace.marker.line.width + constants$1.gapWithPathbar; - var barDifY = !trace.pathbar.visible ? 0 : trace.pathbar.side.indexOf("bottom") > -1 ? vph + barPad : -(barH + barPad); - var pathbarOrigin = { - x0: barW, - // slide to the right - x1: barW, - y0: barDifY, - y1: barDifY + barH - }; - var findClosestEdge = function(pt, ref2, size) { - var e = trace.tiling.pad; - var isLeftOfRect = function(x) { - return x - e <= ref2.x0; - }; - var isRightOfRect = function(x) { - return x + e >= ref2.x1; - }; - var isBottomOfRect = function(y) { - return y - e <= ref2.y0; - }; - var isTopOfRect = function(y) { - return y + e >= ref2.y1; - }; - if (pt.x0 === ref2.x0 && pt.x1 === ref2.x1 && pt.y0 === ref2.y0 && pt.y1 === ref2.y1) { - return { - x0: pt.x0, - x1: pt.x1, - y0: pt.y0, - y1: pt.y1 - }; - } - return { - x0: isLeftOfRect(pt.x0 - e) ? 0 : isRightOfRect(pt.x0 - e) ? size[0] : pt.x0, - x1: isLeftOfRect(pt.x1 + e) ? 0 : isRightOfRect(pt.x1 + e) ? size[0] : pt.x1, - y0: isBottomOfRect(pt.y0 - e) ? 0 : isTopOfRect(pt.y0 - e) ? size[1] : pt.y0, - y1: isBottomOfRect(pt.y1 + e) ? 0 : isTopOfRect(pt.y1 + e) ? size[1] : pt.y1 - }; - }; - var prevEntry = null; - var prevLookupPathbar = {}; - var prevLookupSlices = {}; - var nextOfPrevEntry = null; - var getPrev = function(pt, onPathbar2) { - return onPathbar2 ? prevLookupPathbar[getKey(pt)] : prevLookupSlices[getKey(pt)]; - }; - var getOrigin = function(pt, onPathbar2, refRect, size) { - if (onPathbar2) { - return prevLookupPathbar[getKey(hierarchy2)] || pathbarOrigin; - } else { - var ref2 = prevLookupSlices[trace.level] || refRect; - if (hasVisibleDepth(pt)) { - return findClosestEdge(pt, ref2, size); - } - } - return {}; - }; - if (cd0.hasMultipleRoots && isRoot) { - maxDepth++; - } - trace._maxDepth = maxDepth; - trace._backgroundColor = fullLayout.paper_bgcolor; - trace._entryDepth = entry.data.depth; - trace._atRootLevel = isRoot; - var cenX = -vpw / 2 + gs.l + gs.w * (domain2.x[1] + domain2.x[0]) / 2; - var cenY = -vph / 2 + gs.t + gs.h * (1 - (domain2.y[1] + domain2.y[0]) / 2); - var viewMapX = function(x) { - return cenX + x; - }; - var viewMapY = function(y) { - return cenY + y; - }; - var barY0 = viewMapY(0); - var barX0 = viewMapX(0); - var viewBarX = function(x) { - return barX0 + x; - }; - var viewBarY = function(y) { - return barY0 + y; - }; - function pos(x, y) { - return x + "," + y; - } - var xStart = viewBarX(0); - var limitX0 = function(p) { - p.x = Math.max(xStart, p.x); - }; - var edgeshape = trace.pathbar.edgeshape; - var pathAncestor = function(d) { - var _x0 = viewBarX(Math.max(Math.min(d.x0, d.x0), 0)); - var _x1 = viewBarX(Math.min(Math.max(d.x1, d.x1), barW)); - var _y0 = viewBarY(d.y0); - var _y1 = viewBarY(d.y1); - var halfH = barH / 2; - var pL = {}; - var pR = {}; - pL.x = _x0; - pR.x = _x1; - pL.y = pR.y = (_y0 + _y1) / 2; - var pA = { x: _x0, y: _y0 }; - var pB = { x: _x1, y: _y0 }; - var pC = { x: _x1, y: _y1 }; - var pD = { x: _x0, y: _y1 }; - if (edgeshape === ">") { - pA.x -= halfH; - pB.x -= halfH; - pC.x -= halfH; - pD.x -= halfH; - } else if (edgeshape === "/") { - pC.x -= halfH; - pD.x -= halfH; - pL.x -= halfH / 2; - pR.x -= halfH / 2; - } else if (edgeshape === "\\") { - pA.x -= halfH; - pB.x -= halfH; - pL.x -= halfH / 2; - pR.x -= halfH / 2; - } else if (edgeshape === "<") { - pL.x -= halfH; - pR.x -= halfH; - } - limitX0(pA); - limitX0(pD); - limitX0(pL); - limitX0(pB); - limitX0(pC); - limitX0(pR); - return "M" + pos(pA.x, pA.y) + "L" + pos(pB.x, pB.y) + "L" + pos(pR.x, pR.y) + "L" + pos(pC.x, pC.y) + "L" + pos(pD.x, pD.y) + "L" + pos(pL.x, pL.y) + "Z"; - }; - var pad2 = trace[isIcicle ? "tiling" : "marker"].pad; - var hasFlag = function(f) { - return trace.textposition.indexOf(f) !== -1; - }; - var hasTop = hasFlag("top"); - var hasLeft = hasFlag("left"); - var hasRight = hasFlag("right"); - var hasBottom = hasFlag("bottom"); - var pathDescendant = function(d) { - var _x0 = viewMapX(d.x0); - var _x1 = viewMapX(d.x1); - var _y0 = viewMapY(d.y0); - var _y1 = viewMapY(d.y1); - var dx = _x1 - _x0; - var dy = _y1 - _y0; - if (!dx || !dy) return ""; - var cornerradius = trace.marker.cornerradius || 0; - var r = Math.min(cornerradius, dx / 2, dy / 2); - if (r && d.data && d.data.data && d.data.data.label) { - if (hasTop) r = Math.min(r, pad2.t); - if (hasLeft) r = Math.min(r, pad2.l); - if (hasRight) r = Math.min(r, pad2.r); - if (hasBottom) r = Math.min(r, pad2.b); - } - var arc2 = function(rx, ry) { - return r ? "a" + pos(r, r) + " 0 0 1 " + pos(rx, ry) : ""; - }; - return "M" + pos(_x0, _y0 + r) + arc2(r, -r) + "L" + pos(_x1 - r, _y0) + arc2(r, r) + "L" + pos(_x1, _y1 - r) + arc2(-r, r) + "L" + pos(_x0 + r, _y1) + arc2(-r, -r) + "Z"; - }; - var toMoveInsideSlice = function(pt, opts) { - var x0 = pt.x0; - var x1 = pt.x1; - var y0 = pt.y0; - var y1 = pt.y1; - var textBB = pt.textBB; - var _hasTop = hasTop || opts.isHeader && !hasBottom; - var anchor = _hasTop ? "start" : hasBottom ? "end" : "middle"; - var _hasRight = hasFlag("right"); - var _hasLeft = hasFlag("left") || opts.onPathbar; - var leftToRight = _hasLeft ? -1 : _hasRight ? 1 : 0; - if (opts.isHeader) { - x0 += (isIcicle ? pad2 : pad2.l) - TEXTPAD; - x1 -= (isIcicle ? pad2 : pad2.r) - TEXTPAD; - if (x0 >= x1) { - var mid = (x0 + x1) / 2; - x0 = mid; - x1 = mid; - } - var limY; - if (hasBottom) { - limY = y1 - (isIcicle ? pad2 : pad2.b); - if (y0 < limY && limY < y1) y0 = limY; - } else { - limY = y0 + (isIcicle ? pad2 : pad2.t); - if (y0 < limY && limY < y1) y1 = limY; - } - } - var transform = toMoveInsideBar(x0, x1, y0, y1, textBB, { - isHorizontal: false, - constrained: true, - angle: 0, - anchor, - leftToRight - }); - transform.fontSize = opts.fontSize; - transform.targetX = viewMapX(transform.targetX); - transform.targetY = viewMapY(transform.targetY); - if (isNaN(transform.targetX) || isNaN(transform.targetY)) { - return {}; - } - if (x0 !== x1 && y0 !== y1) { - recordMinTextSize(trace.type, transform, fullLayout); - } - return { - scale: transform.scale, - rotate: transform.rotate, - textX: transform.textX, - textY: transform.textY, - anchorX: transform.anchorX, - anchorY: transform.anchorY, - targetX: transform.targetX, - targetY: transform.targetY - }; - }; - var interpFromParent = function(pt, onPathbar2) { - var parentPrev; - var i = 0; - var Q = pt; - while (!parentPrev && i < maxDepth) { - i++; - Q = Q.parent; - if (Q) { - parentPrev = getPrev(Q, onPathbar2); - } else i = maxDepth; - } - return parentPrev || {}; - }; - var makeExitSliceInterpolator = function(pt, onPathbar2, refRect, size) { - var prev = getPrev(pt, onPathbar2); - var next; - if (onPathbar2) { - next = pathbarOrigin; - } else { - var entryPrev = getPrev(entry, onPathbar2); - if (entryPrev) { - next = findClosestEdge(pt, entryPrev, size); - } else { - next = {}; - } - } - return interpolate(prev, next); - }; - var makeUpdateSliceInterpolator = function(pt, onPathbar2, refRect, size, opts) { - var prev0 = getPrev(pt, onPathbar2); - var prev; - if (prev0) { - prev = prev0; - } else { - if (onPathbar2) { - prev = pathbarOrigin; - } else { - if (prevEntry) { - if (pt.parent) { - var ref2 = nextOfPrevEntry || refRect; - if (ref2 && !onPathbar2) { - prev = findClosestEdge(pt, ref2, size); - } else { - prev = {}; - Lib$2.extendFlat(prev, interpFromParent(pt, onPathbar2)); - } - } else { - prev = Lib$2.extendFlat({}, pt); - if (isIcicle) { - if (opts.orientation === "h") { - if (opts.flipX) prev.x0 = pt.x1; - else prev.x1 = 0; - } else { - if (opts.flipY) prev.y0 = pt.y1; - else prev.y1 = 0; - } - } - } - } else { - prev = {}; - } - } - } - return interpolate(prev, { - x0: pt.x0, - x1: pt.x1, - y0: pt.y0, - y1: pt.y1 - }); - }; - var makeUpdateTextInterpolator = function(pt, onPathbar2, refRect, size) { - var prev0 = getPrev(pt, onPathbar2); - var prev = {}; - var origin = getOrigin(pt, onPathbar2, refRect, size); - Lib$2.extendFlat(prev, { - transform: toMoveInsideSlice({ - x0: origin.x0, - x1: origin.x1, - y0: origin.y0, - y1: origin.y1, - textBB: pt.textBB, - _text: pt._text - }, { - isHeader: helpers$2.isHeader(pt, trace) - }) - }); - if (prev0) { - prev = prev0; - } else { - if (pt.parent) { - Lib$2.extendFlat(prev, interpFromParent(pt, onPathbar2)); - } - } - var transform = pt.transform; - if (pt.x0 !== pt.x1 && pt.y0 !== pt.y1) { - recordMinTextSize(trace.type, transform, fullLayout); - } - return interpolate(prev, { - transform: { - scale: transform.scale, - rotate: transform.rotate, - textX: transform.textX, - textY: transform.textY, - anchorX: transform.anchorX, - anchorY: transform.anchorY, - targetX: transform.targetX, - targetY: transform.targetY - } - }); - }; - var handleSlicesExit = function(slices, onPathbar2, refRect, size, pathSlice) { - var width = size[0]; - var height = size[1]; - if (hasTransition2) { - slices.exit().transition().each(function() { - var sliceTop = d3$2.select(this); - var slicePath = sliceTop.select("path.surface"); - slicePath.transition().attrTween("d", function(pt2) { - var interp = makeExitSliceInterpolator(pt2, onPathbar2, refRect, [width, height]); - return function(t) { - return pathSlice(interp(t)); - }; - }); - var sliceTextGroup = sliceTop.select("g.slicetext"); - sliceTextGroup.attr("opacity", 0); - }).remove(); - } else { - slices.exit().remove(); - } - }; - var strTransform = function(d) { - var transform = d.transform; - if (d.x0 !== d.x1 && d.y0 !== d.y1) { - recordMinTextSize(trace.type, transform, fullLayout); - } - return Lib$2.getTextTransform({ - textX: transform.textX, - textY: transform.textY, - anchorX: transform.anchorX, - anchorY: transform.anchorY, - targetX: transform.targetX, - targetY: transform.targetY, - scale: transform.scale, - rotate: transform.rotate - }); - }; - if (hasTransition2) { - selAncestors.each(function(pt) { - prevLookupPathbar[getKey(pt)] = { - x0: pt.x0, - x1: pt.x1, - y0: pt.y0, - y1: pt.y1 - }; - if (pt.transform) { - prevLookupPathbar[getKey(pt)].transform = { - textX: pt.transform.textX, - textY: pt.transform.textY, - anchorX: pt.transform.anchorX, - anchorY: pt.transform.anchorY, - targetX: pt.transform.targetX, - targetY: pt.transform.targetY, - scale: pt.transform.scale, - rotate: pt.transform.rotate - }; - } - }); - selDescendants.each(function(pt) { - prevLookupSlices[getKey(pt)] = { - x0: pt.x0, - x1: pt.x1, - y0: pt.y0, - y1: pt.y1 - }; - if (pt.transform) { - prevLookupSlices[getKey(pt)].transform = { - textX: pt.transform.textX, - textY: pt.transform.textY, - anchorX: pt.transform.anchorX, - anchorY: pt.transform.anchorY, - targetX: pt.transform.targetX, - targetY: pt.transform.targetY, - scale: pt.transform.scale, - rotate: pt.transform.rotate - }; - } - if (!prevEntry && helpers$2.isEntry(pt)) { - prevEntry = pt; - } - }); - } - nextOfPrevEntry = drawDescendants3(gd, cd, entry, selDescendants, { - width: vpw, - height: vph, - viewX: viewMapX, - viewY: viewMapY, - pathSlice: pathDescendant, - toMoveInsideSlice, - prevEntry, - makeUpdateSliceInterpolator, - makeUpdateTextInterpolator, - handleSlicesExit, - hasTransition: hasTransition2, - strTransform - }); - if (trace.pathbar.visible) { - drawAncestors2(gd, cd, entry, selAncestors, { - barDifY, - width: barW, - height: barH, - viewX: viewBarX, - viewY: viewBarY, - pathSlice: pathAncestor, - toMoveInsideSlice, - makeUpdateSliceInterpolator, - makeUpdateTextInterpolator, - handleSlicesExit, - hasTransition: hasTransition2, - strTransform - }); - } else { - selAncestors.remove(); - } -}; -var d3$1 = d3Exports; -var helpers$1 = helpers$6; -var uniformText = uniform_text; -var clearMinTextSize = uniformText.clearMinTextSize; -var resizeText = style_1$2.resizeText; -var plotOne2 = plot_one; -var draw$1 = function _plot(gd, cdmodule, transitionOpts, makeOnCompleteCallback, opts) { - var type = opts.type; - var drawDescendants3 = opts.drawDescendants; - var fullLayout = gd._fullLayout; - var layer = fullLayout["_" + type + "layer"]; - var join, onComplete; - var isFullReplot = !transitionOpts; - clearMinTextSize(type, fullLayout); - join = layer.selectAll("g.trace." + type).data(cdmodule, function(cd) { - return cd[0].trace.uid; - }); - join.enter().append("g").classed("trace", true).classed(type, true); - join.order(); - if (!fullLayout.uniformtext.mode && helpers$1.hasTransition(transitionOpts)) { - if (makeOnCompleteCallback) { - onComplete = makeOnCompleteCallback(); - } - var transition2 = d3$1.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { - onComplete && onComplete(); - }).each("interrupt", function() { - onComplete && onComplete(); - }); - transition2.each(function() { - layer.selectAll("g.trace").each(function(cd) { - plotOne2(gd, cd, this, transitionOpts, drawDescendants3); - }); - }); - } else { - join.each(function(cd) { - plotOne2(gd, cd, this, transitionOpts, drawDescendants3); - }); - if (fullLayout.uniformtext.mode) { - resizeText(gd, layer.selectAll(".trace"), type); - } - } - if (isFullReplot) { - join.exit().remove(); - } -}; -var plot$1 = {}; -var Color = colorExports; -var Lib$1 = libExports; -uniform_text.resizeText; -var fillOne3 = fill_one; -function styleOne$1(s, pt, trace, gd) { - var cdi = pt.data.data; - var isLeaf = !pt.children; - var ptNumber = cdi.i; - var lineColor = Lib$1.castOption(trace, ptNumber, "marker.line.color") || Color.defaultLine; - var lineWidth = Lib$1.castOption(trace, ptNumber, "marker.line.width") || 0; - s.call(fillOne3, pt, trace, gd).style("stroke-width", lineWidth).call(Color.stroke, lineColor).style("opacity", isLeaf ? trace.leaf.opacity : null); -} -var style_1 = { - styleOne: styleOne$1 -}; -(function(exports2) { - var d32 = d3Exports; - var d3Hierarchy2 = require$$1; - var interpolate2 = require$$2.interpolate; - var Drawing2 = drawingExports; - var Lib2 = libExports; - var svgTextUtils2 = svg_text_utils; - var uniformText2 = uniform_text; - var recordMinTextSize2 = uniformText2.recordMinTextSize; - var clearMinTextSize2 = uniformText2.clearMinTextSize; - var piePlot = plot_1; - var getRotationAngle = helpers$F.getRotationAngle; - var computeTransform2 = piePlot.computeTransform; - var transformInsideText2 = piePlot.transformInsideText; - var styleOne3 = style_1.styleOne; - var resizeText2 = style_1$2.resizeText; - var attachFxHandlers3 = fx; - var constants2 = constants$6; - var helpers2 = helpers$6; - exports2.plot = function(gd, cdmodule, transitionOpts, makeOnCompleteCallback) { - var fullLayout = gd._fullLayout; - var layer = fullLayout._sunburstlayer; - var join, onComplete; - var isFullReplot = !transitionOpts; - var hasTransition2 = !fullLayout.uniformtext.mode && helpers2.hasTransition(transitionOpts); - clearMinTextSize2("sunburst", fullLayout); - join = layer.selectAll("g.trace.sunburst").data(cdmodule, function(cd) { - return cd[0].trace.uid; - }); - join.enter().append("g").classed("trace", true).classed("sunburst", true).attr("stroke-linejoin", "round"); - join.order(); - if (hasTransition2) { - if (makeOnCompleteCallback) { - onComplete = makeOnCompleteCallback(); - } - var transition2 = d32.transition().duration(transitionOpts.duration).ease(transitionOpts.easing).each("end", function() { - onComplete && onComplete(); - }).each("interrupt", function() { - onComplete && onComplete(); - }); - transition2.each(function() { - layer.selectAll("g.trace").each(function(cd) { - plotOne3(gd, cd, this, transitionOpts); - }); - }); - } else { - join.each(function(cd) { - plotOne3(gd, cd, this, transitionOpts); - }); - if (fullLayout.uniformtext.mode) { - resizeText2(gd, fullLayout._sunburstlayer.selectAll(".trace"), "sunburst"); - } - } - if (isFullReplot) { - join.exit().remove(); - } - }; - function plotOne3(gd, cd, element, transitionOpts) { - var isStatic = gd._context.staticPlot; - var fullLayout = gd._fullLayout; - var hasTransition2 = !fullLayout.uniformtext.mode && helpers2.hasTransition(transitionOpts); - var gTrace = d32.select(element); - var slices = gTrace.selectAll("g.slice"); - var cd0 = cd[0]; - var trace = cd0.trace; - var hierarchy2 = cd0.hierarchy; - var entry = helpers2.findEntryWithLevel(hierarchy2, trace.level); - var maxDepth = helpers2.getMaxDepth(trace); - var gs = fullLayout._size; - var domain2 = trace.domain; - var vpw = gs.w * (domain2.x[1] - domain2.x[0]); - var vph = gs.h * (domain2.y[1] - domain2.y[0]); - var rMax = 0.5 * Math.min(vpw, vph); - var cx = cd0.cx = gs.l + gs.w * (domain2.x[1] + domain2.x[0]) / 2; - var cy = cd0.cy = gs.t + gs.h * (1 - domain2.y[0]) - vph / 2; - if (!entry) { - return slices.remove(); - } - var prevEntry = null; - var prevLookup = {}; - if (hasTransition2) { - slices.each(function(pt) { - prevLookup[helpers2.getPtId(pt)] = { - rpx0: pt.rpx0, - rpx1: pt.rpx1, - x0: pt.x0, - x1: pt.x1, - transform: pt.transform - }; - if (!prevEntry && helpers2.isEntry(pt)) { - prevEntry = pt; - } - }); - } - var sliceData = partition3(entry).descendants(); - var maxHeight = entry.height + 1; - var yOffset = 0; - var cutoff = maxDepth; - if (cd0.hasMultipleRoots && helpers2.isHierarchyRoot(entry)) { - sliceData = sliceData.slice(1); - maxHeight -= 1; - yOffset = 1; - cutoff += 1; - } - sliceData = sliceData.filter(function(pt) { - return pt.y1 <= cutoff; - }); - var baseX = getRotationAngle(trace.rotation); - if (baseX) { - sliceData.forEach(function(pt) { - pt.x0 += baseX; - pt.x1 += baseX; - }); - } - var maxY2 = Math.min(maxHeight, maxDepth); - var y2rpx = function(y) { - return (y - yOffset) / maxY2 * rMax; - }; - var rx2px = function(r, x) { - return [r * Math.cos(x), -r * Math.sin(x)]; - }; - var pathSlice = function(d) { - return Lib2.pathAnnulus(d.rpx0, d.rpx1, d.x0, d.x1, cx, cy); - }; - var getTargetX = function(d) { - return cx + getTextXY(d)[0] * (d.transform.rCenter || 0) + (d.transform.x || 0); - }; - var getTargetY = function(d) { - return cy + getTextXY(d)[1] * (d.transform.rCenter || 0) + (d.transform.y || 0); - }; - slices = slices.data(sliceData, helpers2.getPtId); - slices.enter().append("g").classed("slice", true); - if (hasTransition2) { - slices.exit().transition().each(function() { - var sliceTop = d32.select(this); - var slicePath = sliceTop.select("path.surface"); - slicePath.transition().attrTween("d", function(pt2) { - var interp = makeExitSliceInterpolator(pt2); - return function(t) { - return pathSlice(interp(t)); - }; - }); - var sliceTextGroup = sliceTop.select("g.slicetext"); - sliceTextGroup.attr("opacity", 0); - }).remove(); - } else { - slices.exit().remove(); - } - slices.order(); - var nextX1ofPrevEntry = null; - if (hasTransition2 && prevEntry) { - var prevEntryId = helpers2.getPtId(prevEntry); - slices.each(function(pt) { - if (nextX1ofPrevEntry === null && helpers2.getPtId(pt) === prevEntryId) { - nextX1ofPrevEntry = pt.x1; - } - }); - } - var updateSlices = slices; - if (hasTransition2) { - updateSlices = updateSlices.transition().each("end", function() { - var sliceTop = d32.select(this); - helpers2.setSliceCursor(sliceTop, gd, { - hideOnRoot: true, - hideOnLeaves: true, - isTransitioning: false - }); - }); - } - updateSlices.each(function(pt) { - var sliceTop = d32.select(this); - var slicePath = Lib2.ensureSingle(sliceTop, "path", "surface", function(s) { - s.style("pointer-events", isStatic ? "none" : "all"); - }); - pt.rpx0 = y2rpx(pt.y0); - pt.rpx1 = y2rpx(pt.y1); - pt.xmid = (pt.x0 + pt.x1) / 2; - pt.pxmid = rx2px(pt.rpx1, pt.xmid); - pt.midangle = -(pt.xmid - Math.PI / 2); - pt.startangle = -(pt.x0 - Math.PI / 2); - pt.stopangle = -(pt.x1 - Math.PI / 2); - pt.halfangle = 0.5 * Math.min(Lib2.angleDelta(pt.x0, pt.x1) || Math.PI, Math.PI); - pt.ring = 1 - pt.rpx0 / pt.rpx1; - pt.rInscribed = getInscribedRadiusFraction2(pt); - if (hasTransition2) { - slicePath.transition().attrTween("d", function(pt2) { - var interp = makeUpdateSliceInterpolator(pt2); - return function(t) { - return pathSlice(interp(t)); - }; - }); - } else { - slicePath.attr("d", pathSlice); - } - sliceTop.call(attachFxHandlers3, entry, gd, cd, { - eventDataKeys: constants2.eventDataKeys, - transitionTime: constants2.CLICK_TRANSITION_TIME, - transitionEasing: constants2.CLICK_TRANSITION_EASING - }).call(helpers2.setSliceCursor, gd, { - hideOnRoot: true, - hideOnLeaves: true, - isTransitioning: gd._transitioning - }); - slicePath.call(styleOne3, pt, trace, gd); - var sliceTextGroup = Lib2.ensureSingle(sliceTop, "g", "slicetext"); - var sliceText = Lib2.ensureSingle(sliceTextGroup, "text", "", function(s) { - s.attr("data-notex", 1); - }); - var font2 = Lib2.ensureUniformFontSize(gd, helpers2.determineTextFont(trace, pt, fullLayout.font)); - sliceText.text(exports2.formatSliceLabel(pt, entry, trace, cd, fullLayout)).classed("slicetext", true).attr("text-anchor", "middle").call(Drawing2.font, font2).call(svgTextUtils2.convertToTspans, gd); - var textBB = Drawing2.bBox(sliceText.node()); - pt.transform = transformInsideText2(textBB, pt, cd0); - pt.transform.targetX = getTargetX(pt); - pt.transform.targetY = getTargetY(pt); - var strTransform = function(d, textBB2) { - var transform = d.transform; - computeTransform2(transform, textBB2); - transform.fontSize = font2.size; - recordMinTextSize2(trace.type, transform, fullLayout); - return Lib2.getTextTransform(transform); - }; - if (hasTransition2) { - sliceText.transition().attrTween("transform", function(pt2) { - var interp = makeUpdateTextInterpolator(pt2); - return function(t) { - return strTransform(interp(t), textBB); - }; - }); - } else { - sliceText.attr("transform", strTransform(pt, textBB)); - } - }); - function makeExitSliceInterpolator(pt) { - var id = helpers2.getPtId(pt); - var prev = prevLookup[id]; - var entryPrev = prevLookup[helpers2.getPtId(entry)]; - var next; - if (entryPrev) { - var a = (pt.x1 > entryPrev.x1 ? 2 * Math.PI : 0) + baseX; - next = pt.rpx1 < entryPrev.rpx1 ? { x0: pt.x0, x1: pt.x1, rpx0: 0, rpx1: 0 } : { x0: a, x1: a, rpx0: pt.rpx0, rpx1: pt.rpx1 }; - } else { - var parent; - var parentId = helpers2.getPtId(pt.parent); - slices.each(function(pt2) { - if (helpers2.getPtId(pt2) === parentId) { - return parent = pt2; - } - }); - var parentChildren = parent.children; - var ci; - parentChildren.forEach(function(pt2, i) { - if (helpers2.getPtId(pt2) === id) { - return ci = i; - } - }); - var n = parentChildren.length; - var interp = interpolate2(parent.x0, parent.x1); - next = { - rpx0: rMax, - rpx1: rMax, - x0: interp(ci / n), - x1: interp((ci + 1) / n) - }; - } - return interpolate2(prev, next); - } - function makeUpdateSliceInterpolator(pt) { - var prev0 = prevLookup[helpers2.getPtId(pt)]; - var prev; - var next = { x0: pt.x0, x1: pt.x1, rpx0: pt.rpx0, rpx1: pt.rpx1 }; - if (prev0) { - prev = prev0; - } else { - if (prevEntry) { - if (pt.parent) { - if (nextX1ofPrevEntry) { - var a = (pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0) + baseX; - prev = { x0: a, x1: a }; - } else { - prev = { rpx0: rMax, rpx1: rMax }; - Lib2.extendFlat(prev, interpX0X1FromParent(pt)); - } - } else { - prev = { rpx0: 0, rpx1: 0 }; - } - } else { - prev = { x0: baseX, x1: baseX }; - } - } - return interpolate2(prev, next); - } - function makeUpdateTextInterpolator(pt) { - var prev0 = prevLookup[helpers2.getPtId(pt)]; - var prev; - var transform = pt.transform; - if (prev0) { - prev = prev0; - } else { - prev = { - rpx1: pt.rpx1, - transform: { - textPosAngle: transform.textPosAngle, - scale: 0, - rotate: transform.rotate, - rCenter: transform.rCenter, - x: transform.x, - y: transform.y - } - }; - if (prevEntry) { - if (pt.parent) { - if (nextX1ofPrevEntry) { - var a = pt.x1 > nextX1ofPrevEntry ? 2 * Math.PI : 0; - prev.x0 = prev.x1 = a; - } else { - Lib2.extendFlat(prev, interpX0X1FromParent(pt)); - } - } else { - prev.x0 = prev.x1 = baseX; - } - } else { - prev.x0 = prev.x1 = baseX; - } - } - var textPosAngleFn = interpolate2(prev.transform.textPosAngle, pt.transform.textPosAngle); - var rpx1Fn = interpolate2(prev.rpx1, pt.rpx1); - var x0Fn2 = interpolate2(prev.x0, pt.x0); - var x1Fn2 = interpolate2(prev.x1, pt.x1); - var scaleFn = interpolate2(prev.transform.scale, transform.scale); - var rotateFn = interpolate2(prev.transform.rotate, transform.rotate); - var pow = transform.rCenter === 0 ? 3 : prev.transform.rCenter === 0 ? 1 / 3 : 1; - var _rCenterFn = interpolate2(prev.transform.rCenter, transform.rCenter); - var rCenterFn = function(t) { - return _rCenterFn(Math.pow(t, pow)); - }; - return function(t) { - var rpx1 = rpx1Fn(t); - x0Fn2(t); - x1Fn2(t); - var rCenter = rCenterFn(t); - var textPosAngle = textPosAngleFn(t); - var d = { - rpx1, - transform: { - textPosAngle, - rCenter, - x: transform.x, - y: transform.y - } - }; - recordMinTextSize2(trace.type, transform, fullLayout); - return { - transform: { - targetX: getTargetX(d), - targetY: getTargetY(d), - scale: scaleFn(t), - rotate: rotateFn(t), - rCenter - } - }; - }; - } - function interpX0X1FromParent(pt) { - var parent = pt.parent; - var parentPrev = prevLookup[helpers2.getPtId(parent)]; - var out = {}; - if (parentPrev) { - var parentChildren = parent.children; - var ci = parentChildren.indexOf(pt); - var n = parentChildren.length; - var interp = interpolate2(parentPrev.x0, parentPrev.x1); - out.x0 = interp(ci / n); - out.x1 = interp(ci / n); - } else { - out.x0 = out.x1 = 0; - } - return out; - } - } - function partition3(entry) { - return d3Hierarchy2.partition().size([2 * Math.PI, entry.height + 1])(entry); - } - exports2.formatSliceLabel = function(pt, entry, trace, cd, fullLayout) { - var texttemplate = trace.texttemplate; - var textinfo = trace.textinfo; - if (!texttemplate && (!textinfo || textinfo === "none")) { - return ""; - } - var separators = fullLayout.separators; - var cd0 = cd[0]; - var cdi = pt.data.data; - var hierarchy2 = cd0.hierarchy; - var isRoot = helpers2.isHierarchyRoot(pt); - var parent = helpers2.getParent(hierarchy2, pt); - var val = helpers2.getValue(pt); - if (!texttemplate) { - var parts = textinfo.split("+"); - var hasFlag = function(flag) { - return parts.indexOf(flag) !== -1; - }; - var thisText = []; - var tx; - if (hasFlag("label") && cdi.label) { - thisText.push(cdi.label); - } - if (cdi.hasOwnProperty("v") && hasFlag("value")) { - thisText.push(helpers2.formatValue(cdi.v, separators)); - } - if (!isRoot) { - if (hasFlag("current path")) { - thisText.push(helpers2.getPath(pt.data)); - } - var nPercent = 0; - if (hasFlag("percent parent")) nPercent++; - if (hasFlag("percent entry")) nPercent++; - if (hasFlag("percent root")) nPercent++; - var hasMultiplePercents = nPercent > 1; - if (nPercent) { - var percent; - var addPercent = function(key) { - tx = helpers2.formatPercent(percent, separators); - if (hasMultiplePercents) tx += " of " + key; - thisText.push(tx); - }; - if (hasFlag("percent parent") && !isRoot) { - percent = val / helpers2.getValue(parent); - addPercent("parent"); - } - if (hasFlag("percent entry")) { - percent = val / helpers2.getValue(entry); - addPercent("entry"); - } - if (hasFlag("percent root")) { - percent = val / helpers2.getValue(hierarchy2); - addPercent("root"); - } - } - } - if (hasFlag("text")) { - tx = Lib2.castOption(trace, cdi.i, "text"); - if (Lib2.isValidTextValue(tx)) thisText.push(tx); - } - return thisText.join("
"); - } - var txt = Lib2.castOption(trace, cdi.i, "texttemplate"); - if (!txt) return ""; - var obj = {}; - if (cdi.label) obj.label = cdi.label; - if (cdi.hasOwnProperty("v")) { - obj.value = cdi.v; - obj.valueLabel = helpers2.formatValue(cdi.v, separators); - } - obj.currentPath = helpers2.getPath(pt.data); - if (!isRoot) { - obj.percentParent = val / helpers2.getValue(parent); - obj.percentParentLabel = helpers2.formatPercent( - obj.percentParent, - separators - ); - obj.parent = helpers2.getPtLabel(parent); - } - obj.percentEntry = val / helpers2.getValue(entry); - obj.percentEntryLabel = helpers2.formatPercent( - obj.percentEntry, - separators - ); - obj.entry = helpers2.getPtLabel(entry); - obj.percentRoot = val / helpers2.getValue(hierarchy2); - obj.percentRootLabel = helpers2.formatPercent( - obj.percentRoot, - separators - ); - obj.root = helpers2.getPtLabel(hierarchy2); - if (cdi.hasOwnProperty("color")) { - obj.color = cdi.color; - } - var ptTx = Lib2.castOption(trace, cdi.i, "text"); - if (Lib2.isValidTextValue(ptTx) || ptTx === "") obj.text = ptTx; - obj.customdata = Lib2.castOption(trace, cdi.i, "customdata"); - return Lib2.texttemplateString(txt, obj, fullLayout._d3locale, obj, trace._meta || {}); - }; - function getInscribedRadiusFraction2(pt) { - if (pt.rpx0 === 0 && Lib2.isFullCircle([pt.x0, pt.x1])) { - return 1; - } else { - return Math.max(0, Math.min( - 1 / (1 + 1 / Math.sin(pt.halfangle)), - pt.ring / 2 - )); - } - } - function getTextXY(d) { - return getCoords2(d.rpx1, d.transform.textPosAngle); - } - function getCoords2(r, angle) { - return [r * Math.sin(angle), -r * Math.cos(angle)]; - } -})(plot$1); -var d3 = d3Exports; -var Lib = libExports; -var Drawing = drawingExports; -var svgTextUtils = svg_text_utils; -var partition2 = partition$2; -var styleOne2 = style_1$1.styleOne; -var constants = constants$4; -var helpers = helpers$6; -var attachFxHandlers2 = fx; -var formatSliceLabel = plot$1.formatSliceLabel; -var onPathbar = false; -var draw_descendants = function drawDescendants(gd, cd, entry, slices, opts) { - var width = opts.width; - var height = opts.height; - var viewX = opts.viewX; - var viewY = opts.viewY; - var pathSlice = opts.pathSlice; - var toMoveInsideSlice = opts.toMoveInsideSlice; - var strTransform = opts.strTransform; - var hasTransition2 = opts.hasTransition; - var handleSlicesExit = opts.handleSlicesExit; - var makeUpdateSliceInterpolator = opts.makeUpdateSliceInterpolator; - var makeUpdateTextInterpolator = opts.makeUpdateTextInterpolator; - var prevEntry = opts.prevEntry; - var refRect = {}; - var isStatic = gd._context.staticPlot; - var fullLayout = gd._fullLayout; - var cd0 = cd[0]; - var trace = cd0.trace; - var hasLeft = trace.textposition.indexOf("left") !== -1; - var hasRight = trace.textposition.indexOf("right") !== -1; - var hasBottom = trace.textposition.indexOf("bottom") !== -1; - var noRoomForHeader = !hasBottom && !trace.marker.pad.t || hasBottom && !trace.marker.pad.b; - var allData = partition2(entry, [width, height], { - packing: trace.tiling.packing, - squarifyratio: trace.tiling.squarifyratio, - flipX: trace.tiling.flip.indexOf("x") > -1, - flipY: trace.tiling.flip.indexOf("y") > -1, - pad: { - inner: trace.tiling.pad, - top: trace.marker.pad.t, - left: trace.marker.pad.l, - right: trace.marker.pad.r, - bottom: trace.marker.pad.b - } - }); - var sliceData = allData.descendants(); - var minVisibleDepth = Infinity; - var maxVisibleDepth = -Infinity; - sliceData.forEach(function(pt) { - var depth = pt.depth; - if (depth >= trace._maxDepth) { - pt.x0 = pt.x1 = (pt.x0 + pt.x1) / 2; - pt.y0 = pt.y1 = (pt.y0 + pt.y1) / 2; - } else { - minVisibleDepth = Math.min(minVisibleDepth, depth); - maxVisibleDepth = Math.max(maxVisibleDepth, depth); - } - }); - slices = slices.data(sliceData, helpers.getPtId); - trace._maxVisibleLayers = isFinite(maxVisibleDepth) ? maxVisibleDepth - minVisibleDepth + 1 : 0; - slices.enter().append("g").classed("slice", true); - handleSlicesExit(slices, onPathbar, refRect, [width, height], pathSlice); - slices.order(); - var nextOfPrevEntry = null; - if (hasTransition2 && prevEntry) { - var prevEntryId = helpers.getPtId(prevEntry); - slices.each(function(pt) { - if (nextOfPrevEntry === null && helpers.getPtId(pt) === prevEntryId) { - nextOfPrevEntry = { - x0: pt.x0, - x1: pt.x1, - y0: pt.y0, - y1: pt.y1 - }; - } - }); - } - var getRefRect = function() { - return nextOfPrevEntry || { - x0: 0, - x1: width, - y0: 0, - y1: height - }; - }; - var updateSlices = slices; - if (hasTransition2) { - updateSlices = updateSlices.transition().each("end", function() { - var sliceTop = d3.select(this); - helpers.setSliceCursor(sliceTop, gd, { - hideOnRoot: true, - hideOnLeaves: false, - isTransitioning: false - }); - }); - } - updateSlices.each(function(pt) { - var isHeader = helpers.isHeader(pt, trace); - pt._x0 = viewX(pt.x0); - pt._x1 = viewX(pt.x1); - pt._y0 = viewY(pt.y0); - pt._y1 = viewY(pt.y1); - pt._hoverX = viewX(pt.x1 - trace.marker.pad.r), pt._hoverY = hasBottom ? viewY(pt.y1 - trace.marker.pad.b / 2) : viewY(pt.y0 + trace.marker.pad.t / 2); - var sliceTop = d3.select(this); - var slicePath = Lib.ensureSingle(sliceTop, "path", "surface", function(s) { - s.style("pointer-events", isStatic ? "none" : "all"); - }); - if (hasTransition2) { - slicePath.transition().attrTween("d", function(pt2) { - var interp = makeUpdateSliceInterpolator(pt2, onPathbar, getRefRect(), [width, height]); - return function(t) { - return pathSlice(interp(t)); - }; - }); - } else { - slicePath.attr("d", pathSlice); - } - sliceTop.call(attachFxHandlers2, entry, gd, cd, { - styleOne: styleOne2, - eventDataKeys: constants.eventDataKeys, - transitionTime: constants.CLICK_TRANSITION_TIME, - transitionEasing: constants.CLICK_TRANSITION_EASING - }).call(helpers.setSliceCursor, gd, { isTransitioning: gd._transitioning }); - slicePath.call(styleOne2, pt, trace, gd, { - hovered: false - }); - if (pt.x0 === pt.x1 || pt.y0 === pt.y1) { - pt._text = ""; - } else { - if (isHeader) { - pt._text = noRoomForHeader ? "" : helpers.getPtLabel(pt) || ""; - } else { - pt._text = formatSliceLabel(pt, entry, trace, cd, fullLayout) || ""; - } - } - var sliceTextGroup = Lib.ensureSingle(sliceTop, "g", "slicetext"); - var sliceText = Lib.ensureSingle(sliceTextGroup, "text", "", function(s) { - s.attr("data-notex", 1); - }); - var font2 = Lib.ensureUniformFontSize(gd, helpers.determineTextFont(trace, pt, fullLayout.font)); - var text = pt._text || " "; - var singleLineHeader = isHeader && text.indexOf("
") === -1; - sliceText.text(text).classed("slicetext", true).attr("text-anchor", hasRight ? "end" : hasLeft || singleLineHeader ? "start" : "middle").call(Drawing.font, font2).call(svgTextUtils.convertToTspans, gd); - pt.textBB = Drawing.bBox(sliceText.node()); - pt.transform = toMoveInsideSlice(pt, { - fontSize: font2.size, - isHeader - }); - pt.transform.fontSize = font2.size; - if (hasTransition2) { - sliceText.transition().attrTween("transform", function(pt2) { - var interp = makeUpdateTextInterpolator(pt2, onPathbar, getRefRect(), [width, height]); - return function(t) { - return strTransform(interp(t)); - }; - }); - } else { - sliceText.attr("transform", strTransform(pt)); - } - }); - return nextOfPrevEntry; -}; -var draw7 = draw$1; -var drawDescendants2 = draw_descendants; -var plot4 = function _plot2(gd, cdmodule, transitionOpts, makeOnCompleteCallback) { - return draw7(gd, cdmodule, transitionOpts, makeOnCompleteCallback, { - type: "treemap", - drawDescendants: drawDescendants2 - }); -}; -var treemap$2 = { - moduleType: "trace", - name: "treemap", - basePlotModule: base_plot, - categories: [], - animatable: true, - attributes: attributes$1, - layoutAttributes: layout_attributes, - supplyDefaults: defaults, - supplyLayoutDefaults: layout_defaults, - calc: calc$2.calc, - crossTraceCalc: calc$2.crossTraceCalc, - plot: plot4, - style: style_1$1.style, - colorbar: marker_colorbar, - meta: { - description: [ - "Visualize hierarchal data from leaves (and/or outer branches) towards root", - "with rectangles. The treemap sectors are determined by the entries in", - "*labels* or *ids* and in *parents*." - ].join(" ") - } -}; -var treemap = treemap$2; -const treemap$1 = /* @__PURE__ */ index$3.getDefaultExportFromCjs(treemap); -Plotly.register([bar$1, histogram$1, pie$1, ohlc$1, scattergl$1, treemap$1]); -function ChartErrorOverlay(_ref) { - var { - errorMessage, - onDiscard, - onConfirm, - onCancel, - "data-testid": dataTestId - } = _ref; - var messageTestId = dataTestId != null ? "".concat(dataTestId, "-message") : void 0; - return /* @__PURE__ */ index$3.jsxRuntimeExports.jsx("div", { - className: "chart-panel-overlay chart-error-overlay", - children: /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { - className: "chart-panel-overlay-content chart-error-overlay-content", - children: [/* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { - className: "info-message", - "data-testid": messageTestId, - children: [errorMessage, /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.CopyButton, { - copy: errorMessage, - style: { - margin: "0" - } - })] - }), /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { - children: [onCancel && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { - onClick: onCancel, - kind: "secondary", - children: "Cancel" - }), onDiscard && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { - onClick: onDiscard, - kind: "secondary", - children: "Dismiss" - }), onConfirm && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(components.Button, { - onClick: onConfirm, - kind: "primary", - children: "Continue" - })] - })] - }) - }); -} -function ownKeys(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function(r2) { - return Object.getOwnPropertyDescriptor(e, r2).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { - _defineProperty(e, r2, t[r2]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { - Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); - }); - } - return e; -} -function _defineProperty(e, r, t) { - return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey(t) { - var i = _toPrimitive(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -var log = Log.module("Chart"); -class Chart extends React.Component { - /** - * Convert a font awesome icon definition to a plotly icon definition - * @param faIcon The icon to convert - */ - static convertIcon(faIcon) { - var [width, , , , path] = faIcon.icon; - var stringPath = "".concat(path); - return { - width, - path: stringPath, - ascent: width, - descent: 0, - transform: "matrix(1, 0, 0, 1, 0, 0)" - }; - } - static downsampleButtonTitle(isDownsampleInProgress, isDownsamplingDisabled) { - if (isDownsampleInProgress) { - return "Downsampling in progress..."; - } - return isDownsamplingDisabled ? "Downsampling disabled, click to enable" : "Downsampling enabled, click to disable"; - } - static downsampleButtonAttr(isDownsampleInProgress, isDownsamplingDisabled) { - if (isDownsampleInProgress) { - return "animation-spin"; - } - return isDownsamplingDisabled ? void 0 : "fill-active"; - } - constructor(props) { - super(props); - _defineProperty(this, "currentSeries", void 0); - _defineProperty(this, "PlotComponent", void 0); - _defineProperty(this, "plot", void 0); - _defineProperty(this, "plotWrapper", void 0); - _defineProperty(this, "plotWrapperMerged", void 0); - _defineProperty(this, "columnFormats", void 0); - _defineProperty(this, "dateTimeFormatterOptions", void 0); - _defineProperty(this, "decimalFormatOptions", void 0); - _defineProperty(this, "integerFormatOptions", void 0); - _defineProperty(this, "webgl", void 0); - _defineProperty(this, "rect", void 0); - _defineProperty(this, "ranges", void 0); - _defineProperty(this, "isSubscribed", void 0); - _defineProperty(this, "isLoadedFired", void 0); - _defineProperty(this, "resizeObserver", void 0); - _defineProperty(this, "getCachedConfig", memoizeOne((downsamplingError, isDownsampleFinished, isDownsampleInProgress, isDownsamplingDisabled, data, error) => { - var customButtons = []; - var hasDownsampleError = Boolean(downsamplingError); - if (hasDownsampleError) { - customButtons.push({ - name: "Downsampling failed: ".concat(downsamplingError), - title: "Downsampling failed", - click: () => { - this.toggleErrorMessage("".concat(downsamplingError)); - }, - icon: Chart.convertIcon(icons.dhWarningFilled), - attr: "fill-warning" - }); - } - var hasError = Boolean(error); - if (hasError) { - customButtons.push({ - name: "Error: ".concat(error), - title: "Error", - click: () => { - this.toggleErrorMessage("".concat(error)); - }, - icon: Chart.convertIcon(icons.dhWarningFilled), - attr: "fill-warning" - }); - } - if (isDownsampleFinished || isDownsampleInProgress || isDownsamplingDisabled || hasDownsampleError) { - var name2 = Chart.downsampleButtonTitle(isDownsampleInProgress, isDownsamplingDisabled); - var attr = Chart.downsampleButtonAttr(isDownsampleInProgress, isDownsamplingDisabled); - var icon = isDownsampleInProgress ? icons.vsLoading : icons.dhGraphLineDown; - customButtons.push({ - name: name2, - title: "Downsampling status", - icon: Chart.convertIcon(icon), - click: this.handleDownsampleClick, - attr - }); - } - var has2D = data.some((_ref) => { - var { - type - } = _ref; - return type != null && !type.includes("3d"); - }); - var has3D = data.some((_ref2) => { - var { - type - } = _ref2; - return type != null && type.includes("3d"); - }); - var buttons2D = ["zoomIn2d", "zoomOut2d", "autoScale2d", "resetScale2d"]; - var buttons3D = ["orbitRotation", "tableRotation", "resetCameraDefault3d"]; - return { - displaylogo: false, - // scales the plot to the container size - // https://github.com/plotly/react-plotly.js/issues/102 - responsive: true, - // Display the mode bar if there's an error or downsampling so user can see progress - // Yes, the value is a boolean or the string 'hover': https://github.com/plotly/plotly.js/blob/master/src/plot_api/plot_config.js#L249 - displayModeBar: ( - // eslint-disable-next-line @typescript-eslint/strict-boolean-expressions - isDownsampleInProgress || hasDownsampleError || hasError ? true : "hover" - ), - // Each array gets grouped together in the mode bar - modeBarButtons: [ - customButtons, - ["toImage"], - ["zoom2d", "pan2d"], - // These work the same for both 2d and 3d - [...has2D ? buttons2D : [], ...has3D ? buttons3D : []] - ] - }; - })); - index$3.bindAllMethods(this); - this.PlotComponent = createPlotlyComponent(props.Plotly); - this.plot = /* @__PURE__ */ React.createRef(); - this.plotWrapper = /* @__PURE__ */ React.createRef(); - this.plotWrapperMerged = mergeRefs(this.plotWrapper, props.containerRef); - this.columnFormats = []; - this.dateTimeFormatterOptions = {}; - this.decimalFormatOptions = {}; - this.integerFormatOptions = {}; - this.isSubscribed = false; - this.isLoadedFired = false; - this.currentSeries = 0; - this.resizeObserver = new window.ResizeObserver(this.handleResize); - this.state = { - data: null, - downsamplingError: null, - isDownsampleFinished: false, - isDownsampleInProgress: false, - isDownsamplingDisabled: false, - error: null, - shownError: null, - layout: { - datarevision: 0 - }, - revision: 0, - shownBlocker: null - }; - } - componentDidMount() { - this.updateDimensions(); - this.updateModelDimensions(); - this.initData(); - this.initFormatter(); - var { - isActive: isActive2, - model - } = this.props; - if (isActive2) { - this.subscribe(model); - } - if (this.plotWrapper.current != null) { - this.resizeObserver.observe(this.plotWrapper.current); - } - this.handleThemeChange(); - } - componentDidUpdate(prevProps) { - var { - isActive: isActive2, - model, - settings, - theme - } = this.props; - this.updateFormatterSettings(settings); - if (model !== prevProps.model) { - this.unsubscribe(prevProps.model); - this.subscribe(model); - } - if (isActive2 !== prevProps.isActive) { - if (isActive2) { - this.updateDimensions(); - this.subscribe(model); - } else { - this.unsubscribe(model); - } - } - if (theme !== prevProps.theme) { - this.handleThemeChange(); - } - } - componentWillUnmount() { - var { - model - } = this.props; - this.unsubscribe(model); - this.resizeObserver.disconnect(); - } - // Listen for resizing of the element and update the canvas appropriately - getPlotRect() { - var _this$plotWrapper$cur, _this$plotWrapper$cur2; - return (_this$plotWrapper$cur = (_this$plotWrapper$cur2 = this.plotWrapper.current) === null || _this$plotWrapper$cur2 === void 0 ? void 0 : _this$plotWrapper$cur2.getBoundingClientRect()) !== null && _this$plotWrapper$cur !== void 0 ? _this$plotWrapper$cur : null; - } - initData() { - var { - model - } = this.props; - this.setState((_ref3) => { - var { - layout - } = _ref3; - return { - data: model.getData(), - layout: _objectSpread(_objectSpread({}, layout), model.getLayout()) - }; - }); - } - subscribe(model) { - if (this.isSubscribed) { - return; - } - if (!this.rect || this.rect.width === 0 || this.rect.height === 0) { - log.debug2("Delaying subscription until model dimensions are set"); - return; - } - model.subscribe(this.handleModelEvent); - this.isSubscribed = true; - } - unsubscribe(model) { - if (!this.isSubscribed) { - return; - } - model.unsubscribe(this.handleModelEvent); - this.isSubscribed = false; - } - handleAfterPlot() { - if (this.plot.current != null) ; - } - handleDownsampleClick() { - this.setState((_ref4) => { - var { - isDownsamplingDisabled - } = _ref4; - return { - downsamplingError: null, - isDownsampleInProgress: false, - isDownsampleFinished: false, - isDownsamplingDisabled: !isDownsamplingDisabled - }; - }, () => { - var { - model - } = this.props; - var { - isDownsamplingDisabled - } = this.state; - model.setDownsamplingDisabled(isDownsamplingDisabled); - }); - } - handleErrorClose() { - this.setState({ - shownError: null - }); - } - handleDownsampleErrorClose() { - this.setState({ - downsamplingError: null - }); - } - handleModelEvent(event) { - var { - type, - detail - } = event; - log.debug2("Received data update", type, detail); - switch (type) { - case index$3.ChartModel.EVENT_UPDATED: { - this.currentSeries += 1; - this.setState((state) => { - var { - layout, - revision - } = state; - if (typeof layout.datarevision === "number") { - layout.datarevision += 1; - } - return { - data: detail, - layout, - revision: revision + 1 - }; - }); - var { - onUpdate - } = this.props; - onUpdate({ - isLoading: !this.isLoadedFired - }); - break; - } - case index$3.ChartModel.EVENT_LOADFINISHED: { - var { - onUpdate: _onUpdate - } = this.props; - this.isLoadedFired = true; - _onUpdate({ - isLoading: false - }); - break; - } - case index$3.ChartModel.EVENT_DISCONNECT: { - var { - onDisconnect - } = this.props; - onDisconnect(); - break; - } - case index$3.ChartModel.EVENT_RECONNECT: { - var { - onReconnect - } = this.props; - onReconnect(); - break; - } - case index$3.ChartModel.EVENT_DOWNSAMPLESTARTED: { - this.setState({ - isDownsampleFinished: false, - isDownsampleInProgress: true, - downsamplingError: null - }); - break; - } - case index$3.ChartModel.EVENT_DOWNSAMPLEFINISHED: { - this.setState({ - isDownsampleFinished: true, - isDownsampleInProgress: false, - downsamplingError: null - }); - break; - } - case index$3.ChartModel.EVENT_DOWNSAMPLENEEDED: - case index$3.ChartModel.EVENT_DOWNSAMPLEFAILED: { - var _message; - var downsamplingError = (_message = detail.message) !== null && _message !== void 0 ? _message : detail; - this.setState({ - isDownsampleFinished: false, - isDownsampleInProgress: false, - isDownsamplingDisabled: false, - downsamplingError - }); - var { - onError - } = this.props; - onError(new DownsamplingError(downsamplingError == null ? void 0 : "".concat(downsamplingError))); - break; - } - case index$3.ChartModel.EVENT_ERROR: { - var _error = "".concat(detail); - this.setState({ - error: _error - }); - var { - onError: _onError - } = this.props; - _onError(new Error(_error)); - break; - } - case index$3.ChartModel.EVENT_BLOCKER: { - var blocker = "".concat(detail); - this.setState({ - shownBlocker: blocker - }); - break; - } - case index$3.ChartModel.EVENT_BLOCKER_CLEAR: { - this.setState({ - shownBlocker: null - }); - break; - } - case index$3.ChartModel.EVENT_LAYOUT_UPDATED: { - var newLayout = detail; - this.setState((_ref5) => { - var { - layout, - revision - } = _ref5; - return { - layout: _objectSpread(_objectSpread({}, layout), newLayout), - revision: revision + 1 - }; - }); - break; - } - default: - log.debug("Unknown event type", type, event); - } - } - handlePlotUpdate(figure) { - var { - layout - } = figure; - var ranges = index$3.ChartUtils.getLayoutRanges(layout); - var isRangesChanged = !deepEqual(ranges, this.ranges); - if (isRangesChanged) { - this.ranges = ranges; - this.updateModelDimensions(true); - } - } - handleRelayout(changes) { - log.debug("handleRelayout", changes); - if (changes.hiddenlabels != null) { - var { - onSettingsChanged - } = this.props; - var hiddenSeries = [...changes.hiddenlabels]; - onSettingsChanged({ - hiddenSeries - }); - } - this.updateModelDimensions(); - } - handleResize() { - this.updateDimensions(); - } - handleRestyle(_ref6) { - var [changes, seriesIndexes] = _ref6; - log.debug("handleRestyle", changes, seriesIndexes); - if (Object.keys(changes).includes("visible")) { - var { - data - } = this.state; - var { - onSettingsChanged - } = this.props; - if (data != null) { - var hiddenSeries = data.reduce((acc, _ref7) => { - var { - name: name2, - visible - } = _ref7; - return name2 != null && visible === "legendonly" ? [...acc, name2] : acc; - }, []); - onSettingsChanged({ - hiddenSeries - }); - } - } - } - handleThemeChange() { - var { - theme, - model - } = this.props; - var { - dh - } = model; - var chartUtils = new index$3.ChartUtils(dh); - this.setState((_ref8) => { - var { - layout - } = _ref8; - return { - layout: _objectSpread(_objectSpread({}, layout), {}, { - template: chartUtils.makeDefaultTemplate(theme) - }) - }; - }); - } - /** - * Toggle the error message. If it is already being displayed, then hide it. - */ - toggleErrorMessage(error) { - this.setState((_ref9) => { - var { - shownError - } = _ref9; - return { - shownError: shownError === error ? null : error - }; - }); - } - /** - * Update the models dimensions and ranges. - * Note that this will update it all whether the plot size changes OR the range - * the user is looking at has changed (eg. panning/zooming). - * Could update each independently, but doing them at the same time keeps the - * ChartModel API a bit cleaner. - * @param force Force a change even if the chart dimensions haven't changed (eg. after pan/zoom) - */ - updateModelDimensions() { - var force = arguments.length > 0 && arguments[0] !== void 0 ? arguments[0] : false; - var rect2 = this.getPlotRect(); - if (!rect2) { - log.warn("Unable to get plotting rect"); - return; - } - var isRectChanged = !this.rect || this.rect.width !== rect2.width || this.rect.height !== rect2.height; - if (isRectChanged || force) { - this.rect = rect2; - var { - isActive: isActive2, - model - } = this.props; - model.setDimensions(rect2); - if (isActive2) { - this.subscribe(model); - } - } - } - initFormatter() { - var { - settings - } = this.props; - this.updateFormatterSettings(settings); - } - updateFormatterSettings(settings) { - var columnFormats = FormatterUtils.getColumnFormats(settings); - var dateTimeFormatterOptions = FormatterUtils.getDateTimeFormatterOptions(settings); - var { - defaultDecimalFormatOptions = {}, - defaultIntegerFormatOptions = {} - } = settings; - if (!deepEqual(this.columnFormats, columnFormats) || !deepEqual(this.dateTimeFormatterOptions, dateTimeFormatterOptions) || !deepEqual(this.decimalFormatOptions, defaultDecimalFormatOptions) || !deepEqual(this.integerFormatOptions, defaultIntegerFormatOptions)) { - this.columnFormats = FormatterUtils.getColumnFormats(settings); - this.dateTimeFormatterOptions = dateTimeFormatterOptions; - this.decimalFormatOptions = defaultDecimalFormatOptions; - this.integerFormatOptions = defaultIntegerFormatOptions; - this.updateFormatter(); - } - if (this.webgl !== settings.webgl) { - this.webgl = settings.webgl; - this.updateRenderOptions(); - } - } - updateFormatter() { - var { - model - } = this.props; - var formatter = new Formatter(model.dh, this.columnFormats, this.dateTimeFormatterOptions, this.decimalFormatOptions, this.integerFormatOptions); - model.setFormatter(formatter); - } - updateRenderOptions() { - var { - model - } = this.props; - var renderOptions = { - webgl: this.webgl - }; - model.setRenderOptions(renderOptions); - } - updateDimensions() { - var rect2 = this.getPlotRect(); - var { - Plotly: PlotlyProp - } = this.props; - if (this.plot.current != null && rect2 != null && rect2.width > 0 && rect2.height > 0) { - PlotlyProp.relayout(this.plot.current.el, { - autosize: true - }).catch((e) => { - log.debug("Unable to resize, promise rejected", e); - }); - } - } - render() { - var { - PlotComponent - } = this; - var { - data, - downsamplingError, - isDownsampleFinished, - isDownsampleInProgress, - isDownsamplingDisabled, - error, - shownError, - layout, - revision, - shownBlocker - } = this.state; - var config = this.getCachedConfig(downsamplingError, isDownsampleFinished, isDownsampleInProgress, isDownsamplingDisabled, data !== null && data !== void 0 ? data : [], error); - var { - model - } = this.props; - var isPlotShown = data != null && shownBlocker == null; - var errorOverlay = null; - if (shownBlocker != null) { - errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { - errorMessage: "".concat(shownBlocker), - onConfirm: () => { - model.fireBlockerClear(); - } - }); - } else if (shownError != null) { - errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { - errorMessage: "".concat(downsamplingError), - onDiscard: () => { - this.handleDownsampleErrorClose(); - }, - onConfirm: () => { - this.handleDownsampleErrorClose(); - this.handleDownsampleClick(); - } - }); - } else if (downsamplingError != null) { - errorOverlay = /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(ChartErrorOverlay, { - errorMessage: "".concat(downsamplingError), - onDiscard: () => { - this.handleDownsampleErrorClose(); - }, - onConfirm: () => { - this.handleDownsampleErrorClose(); - this.handleDownsampleClick(); - } - }); - } - return /* @__PURE__ */ index$3.jsxRuntimeExports.jsxs("div", { - className: "h-100 w-100 chart-wrapper", - ref: this.plotWrapperMerged, - children: [isPlotShown && /* @__PURE__ */ index$3.jsxRuntimeExports.jsx( - PlotComponent, - { - ref: this.plot, - data, - layout, - revision, - config, - onAfterPlot: this.handleAfterPlot, - onError: log.error, - onRelayout: this.handleRelayout, - onUpdate: this.handlePlotUpdate, - onRestyle: this.handleRestyle, - style: { - height: "100%", - width: "100%" - } - } - ), errorOverlay] - }); - } -} -_defineProperty(Chart, "defaultProps", { - isActive: true, - settings: { - timeZone: "America/New_York", - defaultDateTimeFormat: index$3.DateUtils.FULL_DATE_FORMAT, - showTimeZone: false, - showTSeparator: true, - formatter: [], - webgl: true - }, - Plotly, - onDisconnect: () => void 0, - onReconnect: () => void 0, - onUpdate: () => void 0, - onError: () => void 0, - onSettingsChanged: () => void 0 -}); -function ChartContainer(props) { - var chartTheme = useChartTheme(); - return /* @__PURE__ */ index$3.jsxRuntimeExports.jsx(Chart, _objectSpread(_objectSpread({}, props), {}, { - theme: chartTheme - })); -} -exports.default = ChartContainer; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs b/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs deleted file mode 100644 index 1252748af..000000000 --- a/plugins/grid-toolbar/src/js/dist/bundle/index-nioU_Oes.cjs +++ /dev/null @@ -1,12476 +0,0 @@ -"use strict"; -const plugin = require("@deephaven/plugin"); -const React = require("react"); -const Log = require("@deephaven/log"); -const components = require("@deephaven/components"); -var commonjsGlobal = typeof globalThis !== "undefined" ? globalThis : typeof window !== "undefined" ? window : typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : {}; -function getDefaultExportFromCjs(x) { - return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, "default") ? x["default"] : x; -} -function getAugmentedNamespace(n2) { - if (n2.__esModule) return n2; - var f2 = n2.default; - if (typeof f2 == "function") { - var a = function a2() { - if (this instanceof a2) { - return Reflect.construct(f2, arguments, this.constructor); - } - return f2.apply(this, arguments); - }; - a.prototype = f2.prototype; - } else a = {}; - Object.defineProperty(a, "__esModule", { value: true }); - Object.keys(n2).forEach(function(k) { - var d2 = Object.getOwnPropertyDescriptor(n2, k); - Object.defineProperty(a, k, d2.get ? d2 : { - enumerable: true, - get: function() { - return n2[k]; - } - }); - }); - return a; -} -var jsxRuntime = { exports: {} }; -var reactJsxRuntime_production_min = {}; -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty$1 = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; -function toObject(val) { - if (val === null || val === void 0) { - throw new TypeError("Object.assign cannot be called with null or undefined"); - } - return Object(val); -} -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - var test1 = new String("abc"); - test1[5] = "de"; - if (Object.getOwnPropertyNames(test1)[0] === "5") { - return false; - } - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2["_" + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { - return test2[n2]; - }); - if (order2.join("") !== "0123456789") { - return false; - } - var test3 = {}; - "abcdefghijklmnopqrst".split("").forEach(function(letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { - return false; - } - return true; - } catch (err) { - return false; - } -} -var objectAssign = shouldUseNative() ? Object.assign : function(target, source) { - var from2; - var to = toObject(target); - var symbols; - for (var s = 1; s < arguments.length; s++) { - from2 = Object(arguments[s]); - for (var key in from2) { - if (hasOwnProperty$1.call(from2, key)) { - to[key] = from2[key]; - } - } - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from2); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from2, symbols[i])) { - to[symbols[i]] = from2[symbols[i]]; - } - } - } - } - return to; -}; -/** @license React v17.0.2 - * react-jsx-runtime.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var f = React, g = 60103; -reactJsxRuntime_production_min.Fragment = 60107; -if ("function" === typeof Symbol && Symbol.for) { - var h = Symbol.for; - g = h("react.element"); - reactJsxRuntime_production_min.Fragment = h("react.fragment"); -} -var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; -function q(c, a, k) { - var b, d2 = {}, e = null, l = null; - void 0 !== k && (e = "" + k); - void 0 !== a.key && (e = "" + a.key); - void 0 !== a.ref && (l = a.ref); - for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d2[b] = a[b]); - if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d2[b] && (d2[b] = a[b]); - return { $$typeof: g, type: c, key: e, ref: l, props: d2, _owner: m.current }; -} -reactJsxRuntime_production_min.jsx = q; -reactJsxRuntime_production_min.jsxs = q; -{ - jsxRuntime.exports = reactJsxRuntime_production_min; -} -var jsxRuntimeExports = jsxRuntime.exports; -const log$4 = Log.module("@deephaven/js-plugin-grid-toolbar"); -function GridToolbarMiddleware({ - Component, - ...props -}) { - const handleExport = React.useCallback(() => { - log$4.info("Export clicked"); - }, []); - const handleResetFilters = React.useCallback(() => { - log$4.info("[0] Reset Filters clicked", props, Component); - }, [props, Component]); - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleExport, - children: "Export" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) - ] }); -} -function ownKeys$3(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function(r2) { - return Object.getOwnPropertyDescriptor(e, r2).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread$3(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys$3(Object(t), true).forEach(function(r2) { - _defineProperty$9(e, r2, t[r2]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$3(Object(t)).forEach(function(r2) { - Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); - }); - } - return e; -} -function _defineProperty$9(e, r, t) { - return (r = _toPropertyKey$9(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey$9(t) { - var i = _toPrimitive$9(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive$9(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -var Chart = /* @__PURE__ */ React.lazy(() => Promise.resolve().then(() => require("./Chart-DElXbH_b.cjs"))); -function LazyChart(props) { - return /* @__PURE__ */ jsxRuntimeExports.jsx(React.Suspense, { - fallback: /* @__PURE__ */ jsxRuntimeExports.jsx(components.LoadingOverlay, {}), - children: /* @__PURE__ */ jsxRuntimeExports.jsx(Chart, _objectSpread$3({}, props)) - }); -} -function removeNullAndUndefined() { - for (var _len = arguments.length, maybeDefined = new Array(_len), _key = 0; _key < _len; _key++) { - maybeDefined[_key] = arguments[_key]; - } - return maybeDefined.filter((m2) => m2 != null); -} -function _defineProperty$8(obj, key, value2) { - key = _toPropertyKey$8(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$8(arg) { - var key = _toPrimitive$8(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$8(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class CanceledPromiseError extends Error { - constructor() { - super(...arguments); - _defineProperty$8(this, "isCanceled", true); - } -} -function bindAllMethods(instance) { - var traversePrototypeChain = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; - var methodNames = getAllMethodNames(instance, traversePrototypeChain); - methodNames.forEach((methodName) => { - instance[methodName] = instance[methodName].bind(instance); - }); -} -function getAllMethodNames(instance, traversePrototypeChain) { - var methodNames = /* @__PURE__ */ new Set(); - var current = instance; - var level = 0; - while (current != null && current !== Object.prototype && (level <= 1 || traversePrototypeChain)) { - for (var name of Object.getOwnPropertyNames(current)) { - var _Object$getOwnPropert; - if (name !== "constructor" && // Ensure this is a method and not a getter - typeof ((_Object$getOwnPropert = Object.getOwnPropertyDescriptor(current, name)) === null || _Object$getOwnPropert === void 0 ? void 0 : _Object$getOwnPropert.value) === "function") { - methodNames.add(name); - } - } - current = Object.getPrototypeOf(current); - level += 1; - } - return [...methodNames.keys()]; -} -function _defineProperty$7(obj, key, value2) { - key = _toPropertyKey$7(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$7(arg) { - var key = _toPrimitive$7(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$7(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class TimeoutError extends Error { - constructor() { - super(...arguments); - _defineProperty$7(this, "isTimeout", true); - } -} -class PromiseUtils { - /** - * Creates a promise that can be canceled by calling the `cancel` function - * Pass an optional `cleanupFunc` to perform actions on the resolved item after promise is cancelled. - * @param promise The item to resolve - * @param cleanup Function to cleanup the resolved item after cancelation. Called after both this promise is cancelled and the wrapped item was resolved (order does not matter). - */ - static makeCancelable(promise2, cleanup) { - var hasCanceled = false; - var resolved; - var rejectFn; - var wrappedPromise = new Promise((resolve, reject) => { - rejectFn = reject; - Promise.resolve(promise2).then((val) => { - if (hasCanceled) { - if (cleanup) { - cleanup(val); - } - } else { - resolved = val; - resolve(val); - } - }).catch((error) => reject(error)); - }); - wrappedPromise.cancel = () => { - hasCanceled = true; - rejectFn(new CanceledPromiseError()); - if (resolved != null && cleanup) { - cleanup(resolved); - } - }; - return wrappedPromise; - } - static isCanceled(error) { - return error instanceof CanceledPromiseError; - } - static isTimedOut(error) { - return error instanceof TimeoutError; - } - /** - * Wrap a callback call in a Promise + setTimeout. - * @param timeoutMs - * @param callback - */ - static withTimeout(timeoutMs, callback) { - return new Promise((resolve, reject) => { - setTimeout(() => { - try { - resolve(callback()); - } catch (err) { - reject(err); - } - }, timeoutMs); - }); - } -} -function assertInstanceOf(instance, type) { - if (!(instance instanceof type)) { - throw new Error("Expected instance of ".concat(type.name)); - } -} -function assertNotNull(value2) { - var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "Value is null or undefined"; - if (value2 == null) throw new Error(message); -} -class TextUtils { - /** - * Joins a list of strings with a comma, keeping the oxford comma and adding "and" as appropriate. - * Eg. - * One - * One and Two - * One, Two, and Three - * @param items The items to join in a list - * @param conjunction Conjunction to use between the last two items - */ - static join(items) { - var conjunction = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "and"; - if (items == null || items.length === 0) { - return ""; - } - if (items.length === 1) { - return items[0]; - } - if (items.length === 2) { - return "".concat(items[0], " ").concat(conjunction, " ").concat(items[1]); - } - var itemText = items.slice(0, items.length - 1).join(", "); - var lastItem = items[items.length - 1]; - return "".concat(itemText, ", ").concat(conjunction, " ").concat(lastItem); - } - /** - * Converts text to lower case, handling null if necessary and returning an empty string - * @param text The text to convert to lower case - * @param isNullAllowed True if a null string should return an empty string from this function. If false an error is thrown if null is passed in. - */ - static toLower(text) { - var isNullAllowed = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; - if (text == null) { - if (isNullAllowed) { - return ""; - } - throw new Error("Null string passed in to TextUtils.toLower"); - } - return text.toLowerCase(); - } - /** - * - * @param a The string to sort - * @param b Second string to sort - * @param isAscending Whether to sort ascending or descending - */ - static sort(a, b) { - var isAscending = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; - if (a < b) { - return isAscending ? -1 : 1; - } - if (a > b) { - return isAscending ? 1 : -1; - } - return 0; - } -} -function ownKeys$2(object, enumerableOnly) { - var keys2 = Object.keys(object); - if (Object.getOwnPropertySymbols) { - var symbols = Object.getOwnPropertySymbols(object); - enumerableOnly && (symbols = symbols.filter(function(sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - })), keys2.push.apply(keys2, symbols); - } - return keys2; -} -function _objectSpread$2(target) { - for (var i = 1; i < arguments.length; i++) { - var source = null != arguments[i] ? arguments[i] : {}; - i % 2 ? ownKeys$2(Object(source), true).forEach(function(key) { - _defineProperty$6(target, key, source[key]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys$2(Object(source)).forEach(function(key) { - Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); - }); - } - return target; -} -function _defineProperty$6(obj, key, value2) { - key = _toPropertyKey$6(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$6(arg) { - var key = _toPrimitive$6(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$6(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -var DATE_TIME_REGEX = /\s*(\d{4})([-./](\d{1,2}|[a-z]+))?([-./](\d{1,2}))?([tT\s](\d{2})([:](\d{2}))?([:](\d{2}))?([.](\d{1,9}))?)?(.*)/; -class DateUtils { - /** - * - * @param timeZone The time zone to parse this time in. E.g. America/New_York - * @param year The year for the date - * @param month The month, starting at 0 - * @param day The day, starting at 1 - * @param hour The hours - * @param minute The minutes - * @param second The seconds - * @param ns The nanoseconds - */ - static makeDateWrapper(dh, timeZone, year) { - var month = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; - var day = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 1; - var hour = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : 0; - var minute = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : 0; - var second = arguments.length > 7 && arguments[7] !== void 0 ? arguments[7] : 0; - var ns = arguments.length > 8 && arguments[8] !== void 0 ? arguments[8] : 0; - if (!timeZone) { - throw new Error("No timezone provided"); - } - var yearString = "".concat(year).padStart(4, "0"); - var monthString = "".concat(month + 1).padStart(2, "0"); - var dayString = "".concat(day).padStart(2, "0"); - var hourString = "".concat(hour).padStart(2, "0"); - var minuteString = "".concat(minute).padStart(2, "0"); - var secondString = "".concat(second).padStart(2, "0"); - var nanoString = "".concat(ns).padStart(9, "0"); - var dateString = "".concat(yearString, "-").concat(monthString, "-").concat(dayString, " ").concat(hourString, ":").concat(minuteString, ":").concat(secondString, ".").concat(nanoString); - return dh.i18n.DateTimeFormat.parse(DateUtils.FULL_DATE_FORMAT, dateString, dh.i18n.TimeZone.getTimeZone(timeZone)); - } - /** - * Takes the string the user entered and returns the next nanos value - * @param nanoString The nano string to get the next one of - * @returns The value of the next nanos - */ - static getNextNanos(nanoString) { - var sigNanos = parseInt(nanoString, 10); - var zeros = "0".repeat(9 - nanoString.length); - var nextNanoString = "".concat(sigNanos + 1).concat(zeros); - return parseInt(nextNanoString, 10); - } - /** - * @param components The string components that were parsed from the original string - * @param values The values that were parsed from the components - * @param timeZone The time zone to parse the date in. E.g. America/New_York - * @returns Returns the DateWrapper for the next date, or null if a full date was passed in - */ - static getNextDate(dh, components2, values, timeZone) { - var { - year, - month, - date, - hours, - minutes, - seconds, - nanos - } = values; - if (components2.nanos != null) { - if (components2.nanos.length === 9) { - return null; - } - nanos = DateUtils.getNextNanos(components2.nanos); - if (nanos > 999999999) { - seconds += 1; - nanos = 0; - } - } else if (components2.seconds != null) { - seconds += 1; - } else if (components2.minutes != null) { - minutes += 1; - } else if (components2.hours != null) { - hours += 1; - } else if (components2.date != null) { - date += 1; - } else if (components2.month != null) { - month += 1; - } else { - year += 1; - } - var jsDate = new Date(year, month, date, hours, minutes, seconds); - return DateUtils.makeDateWrapper(dh, timeZone, jsDate.getFullYear(), jsDate.getMonth(), jsDate.getDate(), jsDate.getHours(), jsDate.getMinutes(), jsDate.getSeconds(), nanos); - } - /** - * Get the JS month value for the provided string. - * Matches digits or a month name (eg. '1', '01', 'jan', 'january' should all work) - * @param monthString The string to parse to a JS month value - * @returns number The JS month value, which starts at 0 for january, or NaN if nothing could be parsed - */ - static parseMonth(monthString) { - var month = parseInt(monthString, 10); - if (!Number.isNaN(month)) { - if (month >= 1 && month <= 12) { - return month - 1; - } - return NaN; - } - var cleanMonthString = monthString.trim().toLowerCase(); - if (cleanMonthString.length >= 3) { - for (var i = 0; i < DateUtils.months.length; i += 1) { - if (DateUtils.months[i].startsWith(cleanMonthString)) { - return i; - } - } - } - return NaN; - } - /** - * Parse a date object out of the provided string segments. - * Also using `parseMonth` to get month names like Aug/August rather than - * simply doing `parseInt`. - * @param yearString The year part of the string - * @param monthString The month part of the string - * @param dayString The day part of the string - * @param hourString The hour part of the string - * @param minuteString The minute part of the string - * @param secondString The second part of the string - * @param nanoString The milli part of the string - */ - static parseDateValues(yearString, monthString, dayString, hourString, minuteString, secondString, nanoString) { - var year = parseInt(yearString, 10); - var month = monthString != null ? this.parseMonth(monthString) : 0; - var date = dayString != null ? parseInt(dayString, 10) : 1; - var hours = hourString != null ? parseInt(hourString, 10) : 0; - var minutes = minuteString != null ? parseInt(minuteString, 10) : 0; - var seconds = secondString != null ? parseInt(secondString, 10) : 0; - var nanos = nanoString != null ? parseInt(nanoString.padEnd(9, "0"), 10) : 0; - if (Number.isNaN(year) || Number.isNaN(month) || Number.isNaN(date) || Number.isNaN(hours) || Number.isNaN(minutes) || Number.isNaN(seconds) || Number.isNaN(nanos)) { - return null; - } - return { - year, - month, - date, - hours, - minutes, - seconds, - nanos - }; - } - /** - * Parse out a date time string into it's string components. - * Anything that is not captured in the string will be undefined. - * - * @param dateTimeString The date time string to parse - * @param allowOverflow If true, will allow overflow characters after the date - * string - * @returns Containing the date time components - */ - static parseDateTimeString(dateTimeString) { - var allowOverflow = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; - var result = DATE_TIME_REGEX.exec(dateTimeString); - if (result == null) { - throw new Error("Unexpected date string: ".concat(dateTimeString)); - } - var [, year, , month, , date, , hours, , minutes, , seconds, , nanos, overflow] = result; - if (!allowOverflow && overflow != null && overflow.length > 0) { - throw new Error("Unexpected characters after date string '".concat(dateTimeString, "': ").concat(overflow)); - } - var dateParts = { - year, - month, - date, - hours, - minutes, - seconds, - nanos - }; - return allowOverflow ? _objectSpread$2(_objectSpread$2({}, dateParts), {}, { - overflow - }) : dateParts; - } - /** - * Parses the date range provided from a string of text. - * @param text The string to parse the date from. Can be a keyword like "today", or in the format "2018-08-04" - * @param timeZone The time zone to parse this range in. E.g. America/New_York - * @returns A tuple with the start and end value/null for that date range, or both null - */ - static parseDateRange(dh, text, timeZone) { - var cleanText = text.trim().toLowerCase(); - if (cleanText.length === 0) { - throw new Error("Cannot parse date range from empty string"); - } - if (cleanText === "null") { - return [null, null]; - } - if (cleanText === "today") { - var now = new Date(Date.now()); - var _startDate = DateUtils.makeDateWrapper(dh, timeZone, now.getFullYear(), now.getMonth(), now.getDate()); - var tomorrow = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 1); - var _endDate = DateUtils.makeDateWrapper(dh, timeZone, tomorrow.getFullYear(), tomorrow.getMonth(), tomorrow.getDate()); - return [_startDate, _endDate]; - } - if (cleanText === "yesterday") { - var _now = new Date(Date.now()); - var yesterday = new Date(_now.getFullYear(), _now.getMonth(), _now.getDate() - 1); - var _startDate2 = DateUtils.makeDateWrapper(dh, timeZone, yesterday.getFullYear(), yesterday.getMonth(), yesterday.getDate()); - var _endDate2 = DateUtils.makeDateWrapper(dh, timeZone, _now.getFullYear(), _now.getMonth(), _now.getDate()); - return [_startDate2, _endDate2]; - } - if (cleanText === "now") { - var _now2 = new Date(Date.now()); - var date = dh.DateWrapper.ofJsDate(_now2); - return [date, null]; - } - var components2 = DateUtils.parseDateTimeString(cleanText); - if (components2.year == null && components2.month == null && components2.date == null) { - throw new Error("Unable to extract year, month, or day ".concat(cleanText)); - } - var values = DateUtils.parseDateValues(components2.year, components2.month, components2.date, components2.hours, components2.minutes, components2.seconds, components2.nanos); - if (values == null) { - throw new Error("Unable to extract date values from ".concat(components2)); - } - var startDate = DateUtils.makeDateWrapper(dh, timeZone, values.year, values.month, values.date, values.hours, values.minutes, values.seconds, values.nanos); - var endDate = DateUtils.getNextDate(dh, components2, values, timeZone); - return [startDate, endDate]; - } - /** - * Gets the Js Date object from the provided DateWrapper. - * In unit test, DateWrapper is just a number provided in millis, so handles that case. - * @param dateWrapper The DateWrapper object, or time in millis - */ - static getJsDate(dateWrapper) { - if (typeof dateWrapper === "number") { - return new Date(dateWrapper); - } - return dateWrapper.asDate(); - } - /** - * Trim overflow (usually timezone) from a date time string. - * @param dateTimeString The date time string to trim - * @returns The date time string without overflow - */ - static trimDateTimeStringTimeZone(dateTimeString) { - var { - overflow = "" - } = DateUtils.parseDateTimeString(dateTimeString, true); - if (overflow === "") { - return dateTimeString; - } - if (!/^\s[A-Za-z]+/.test(overflow)) { - throw new Error("Unexpected timezone format in overflow: '".concat(dateTimeString, "'")); - } - return dateTimeString.slice(0, -overflow.length); - } -} -_defineProperty$6(DateUtils, "FULL_DATE_FORMAT", "yyyy-MM-dd HH:mm:ss.SSSSSSSSS"); -_defineProperty$6(DateUtils, "months", ["january", "february", "march", "april", "may", "june", "july", "august", "september", "october", "november", "december"]); -function createFilterConditionFactory(columnNames, createColumnCondition) { - var conditionOperator = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : "or"; - return function filterConditionFactory(maybeTable) { - var maybeColumns = maybeTable === null || maybeTable === void 0 ? void 0 : maybeTable.findColumns(typeof columnNames === "string" ? [columnNames] : columnNames); - if (maybeColumns == null || maybeColumns.length === 0) { - return null; - } - var filterConditions = maybeColumns.map(createColumnCondition); - return filterConditions.reduce((current, next) => current[conditionOperator](next)); - }; -} -function createValueFilter(tableUtils, columnNames, value2, operator) { - return createFilterConditionFactory(columnNames, (col) => col.filter()[operator](tableUtils.makeFilterValue(col.type, value2)), "or"); -} -function _defineProperty$5(obj, key, value2) { - key = _toPropertyKey$5(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$5(arg) { - var key = _toPrimitive$5(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$5(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class Operator { -} -_defineProperty$5(Operator, "not", "not"); -_defineProperty$5(Operator, "and", "and"); -_defineProperty$5(Operator, "or", "or"); -function _defineProperty$4(obj, key, value2) { - key = _toPropertyKey$4(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$4(arg) { - var key = _toPrimitive$4(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$4(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -class Type { -} -_defineProperty$4(Type, "eq", "eq"); -_defineProperty$4(Type, "eqIgnoreCase", "eqIgnoreCase"); -_defineProperty$4(Type, "notEq", "notEq"); -_defineProperty$4(Type, "notEqIgnoreCase", "notEqIgnoreCase"); -_defineProperty$4(Type, "greaterThan", "greaterThan"); -_defineProperty$4(Type, "greaterThanOrEqualTo", "greaterThanOrEqualTo"); -_defineProperty$4(Type, "lessThan", "lessThan"); -_defineProperty$4(Type, "lessThanOrEqualTo", "lessThanOrEqualTo"); -_defineProperty$4(Type, "in", "in"); -_defineProperty$4(Type, "inIgnoreCase", "inIgnoreCase"); -_defineProperty$4(Type, "notIn", "notIn"); -_defineProperty$4(Type, "notInIgnoreCase", "notInIgnoreCase"); -_defineProperty$4(Type, "isTrue", "isTrue"); -_defineProperty$4(Type, "isFalse", "isFalse"); -_defineProperty$4(Type, "isNull", "isNull"); -_defineProperty$4(Type, "invoke", "invoke"); -_defineProperty$4(Type, "contains", "contains"); -_defineProperty$4(Type, "notContains", "notContains"); -_defineProperty$4(Type, "containsIgnoreCase", "containsIgnoreCase"); -_defineProperty$4(Type, "startsWith", "startsWith"); -_defineProperty$4(Type, "endsWith", "endsWith"); -_defineProperty$4(Type, "containsAny", "containsAny"); -Log.module("ViewportDataUtils"); -function getSize(table) { - return table == null || isClosed(table) ? 0 : table.size; -} -function isClosed(table) { - if ("isClosed" in table) { - return table.isClosed; - } - return false; -} -function asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, key, arg) { - try { - var info = gen[key](arg); - var value2 = info.value; - } catch (error) { - reject(error); - return; - } - if (info.done) { - resolve(value2); - } else { - Promise.resolve(value2).then(_next, _throw); - } -} -function _asyncToGenerator$1(fn) { - return function() { - var self3 = this, args = arguments; - return new Promise(function(resolve, reject) { - var gen = fn.apply(self3, args); - function _next(value2) { - asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "next", value2); - } - function _throw(err) { - asyncGeneratorStep$1(gen, resolve, reject, _next, _throw, "throw", err); - } - _next(void 0); - }); - }; -} -function _defineProperty$3(obj, key, value2) { - key = _toPropertyKey$3(key); - if (key in obj) { - Object.defineProperty(obj, key, { value: value2, enumerable: true, configurable: true, writable: true }); - } else { - obj[key] = value2; - } - return obj; -} -function _toPropertyKey$3(arg) { - var key = _toPrimitive$3(arg, "string"); - return typeof key === "symbol" ? key : String(key); -} -function _toPrimitive$3(input, hint) { - if (typeof input !== "object" || input === null) return input; - var prim = input[Symbol.toPrimitive]; - if (prim !== void 0) { - var res = prim.call(input, hint); - if (typeof res !== "object") return res; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return (hint === "string" ? String : Number)(input); -} -var log$3 = Log.module("TableUtils"); -class TableUtils { - // Regex looking for a negative or positive integer or decimal number - /** - * Copy a given table and apply filters. - * @param maybeTable Table to copy and apply filters to - * @param filterFactories Filter condition factories to apply - * @returns A derived, filtered table - */ - static copyTableAndApplyFilters(maybeTable) { - var _arguments = arguments; - return _asyncToGenerator$1(function* () { - if (maybeTable == null) { - return null; - } - var derivedTable = yield maybeTable.copy(); - for (var _len = _arguments.length, filterFactories = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - filterFactories[_key - 1] = _arguments[_key]; - } - derivedTable.applyFilter(removeNullAndUndefined(...filterFactories.map((f2) => f2(derivedTable)))); - return derivedTable; - })(); - } - /** - * Executes a callback on a given table and returns a Promise that will resolve - * the next time a particular event type fires on the table. - * @param exec Callback function to execute. - * @param table Table that gets passed to the `exec` function and that is - * subscribed to for a given `eventType`. - * @param eventType The event type to listen for. - * @param timeout If the event doesn't fire within the timeout, the returned - * Promise will be rejected. - * @returns a Promise to the original table that resolves on next `eventType` - * event - */ - static getSortIndex(sort, columnName) { - for (var i = 0; i < sort.length; i += 1) { - var _s$column; - var s = sort[i]; - if (((_s$column = s.column) === null || _s$column === void 0 ? void 0 : _s$column.name) === columnName) { - return i; - } - } - return null; - } - /** - * @param tableSort The sorts from the table to get the sort from - * @param columnName The name of the column to get the sort for - * @returns The sort for the column, or null if it's not sorted - */ - static getSortForColumn(tableSort, columnName) { - var sortIndex = TableUtils.getSortIndex(tableSort, columnName); - if (sortIndex != null) { - return tableSort[sortIndex]; - } - return null; - } - static getFilterText(filter) { - if (filter) { - return filter.toString(); - } - return null; - } - /** Return the valid filter types for the column */ - static getFilterTypes(columnType) { - if (TableUtils.isBooleanType(columnType)) { - return [Type.isTrue, Type.isFalse, Type.isNull]; - } - if (TableUtils.isCharType(columnType) || TableUtils.isNumberType(columnType) || TableUtils.isDateType(columnType)) { - return [Type.eq, Type.notEq, Type.greaterThan, Type.greaterThanOrEqualTo, Type.lessThan, Type.lessThanOrEqualTo]; - } - if (TableUtils.isTextType(columnType)) { - return [Type.eq, Type.eqIgnoreCase, Type.notEq, Type.notEqIgnoreCase, Type.contains, Type.notContains, Type.startsWith, Type.endsWith]; - } - return []; - } - static getNextSort(columns, sorts, columnIndex) { - var column = columns[columnIndex]; - if (column == null) { - return null; - } - var sort = TableUtils.getSortForColumn(sorts, column.name); - if (sort === null) { - return this.makeColumnSort(columns, columnIndex, TableUtils.sortDirection.ascending, false); - } - if (sort.direction === TableUtils.sortDirection.ascending) { - return this.makeColumnSort(columns, columnIndex, TableUtils.sortDirection.descending, false); - } - return null; - } - static makeColumnSort(columns, columnIndex, direction, isAbs) { - var column = columns[columnIndex]; - if (column == null) { - return null; - } - if (direction === TableUtils.sortDirection.none) { - return null; - } - return { - column: { - name: column.name, - type: column.type - }, - isAbs, - direction - }; - } - /** - * Toggles the sort for the specified column - * @param sorts The current sorts from IrisGrid.state - * @param columns The columns to apply the sort to - * @param columnIndex The column index to apply the sort to - * @param addToExisting Add this sort to the existing sort - */ - static toggleSortForColumn(sorts, columns, columnIndex) { - var addToExisting = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false; - if (columns[columnIndex] == null) { - return []; - } - var newSort = TableUtils.getNextSort(columns, sorts, columnIndex); - return TableUtils.setSortForColumn(sorts, columns[columnIndex].name, newSort, addToExisting); - } - static sortColumn(sorts, columns, modelColumn, direction, isAbs, addToExisting) { - if (modelColumn < 0 || modelColumn >= columns.length) { - return []; - } - var newSort = TableUtils.makeColumnSort(columns, modelColumn, direction, isAbs); - return TableUtils.setSortForColumn(sorts, columns[modelColumn].name, newSort, addToExisting); - } - /** - * Sets the sort for the given column *and* removes any reverses - * @param tableSort The current sorts from IrisGrid.state - * @param columnName The column name to apply the sort to - * @param sort The sort object to add - * @param addToExisting Add this sort to the existing sort - * @returns Returns the modified array of sorts - removing reverses - */ - static setSortForColumn(tableSort, columnName, sort) { - var addToExisting = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : false; - var sortIndex = TableUtils.getSortIndex(tableSort, columnName); - var sorts = []; - if (addToExisting) { - sorts = sorts.concat(tableSort.filter((_ref) => { - var { - direction - } = _ref; - return direction !== TableUtils.sortDirection.reverse; - })); - if (sortIndex !== null) { - sorts.splice(sortIndex, 1); - } - } - if (sort !== null) { - sorts.push(sort); - } - return sorts; - } - static getNormalizedType(columnType) { - switch (columnType) { - case "boolean": - case "java.lang.Boolean": - case TableUtils.dataType.BOOLEAN: - return TableUtils.dataType.BOOLEAN; - case "char": - case "java.lang.Character": - case TableUtils.dataType.CHAR: - return TableUtils.dataType.CHAR; - case "java.lang.String": - case TableUtils.dataType.STRING: - return TableUtils.dataType.STRING; - case "io.deephaven.db.tables.utils.DBDateTime": - case "io.deephaven.time.DateTime": - case "com.illumon.iris.db.tables.utils.DBDateTime": - case "java.time.Instant": - case "java.time.ZonedDateTime": - case TableUtils.dataType.DATETIME: - return TableUtils.dataType.DATETIME; - case "double": - case "java.lang.Double": - case "float": - case "java.lang.Float": - case "java.math.BigDecimal": - case TableUtils.dataType.DECIMAL: - return TableUtils.dataType.DECIMAL; - case "int": - case "java.lang.Integer": - case "long": - case "java.lang.Long": - case "short": - case "java.lang.Short": - case "byte": - case "java.lang.Byte": - case "java.math.BigInteger": - case TableUtils.dataType.INT: - return TableUtils.dataType.INT; - default: - return TableUtils.dataType.UNKNOWN; - } - } - static isLongType(columnType) { - switch (columnType) { - case "long": - case "java.lang.Long": - return true; - default: - return false; - } - } - static isDateType(columnType) { - switch (columnType) { - case "io.deephaven.db.tables.utils.DBDateTime": - case "io.deephaven.time.DateTime": - case "java.time.Instant": - case "java.time.ZonedDateTime": - case "com.illumon.iris.db.tables.utils.DBDateTime": - return true; - default: - return false; - } - } - static isNumberType(columnType) { - return TableUtils.isIntegerType(columnType) || TableUtils.isDecimalType(columnType); - } - static isIntegerType(columnType) { - switch (columnType) { - case "int": - case "java.lang.Integer": - case "java.math.BigInteger": - case "long": - case "java.lang.Long": - case "short": - case "java.lang.Short": - case "byte": - case "java.lang.Byte": - return true; - default: - return false; - } - } - static isDecimalType(columnType) { - switch (columnType) { - case "double": - case "java.lang.Double": - case "java.math.BigDecimal": - case "float": - case "java.lang.Float": - return true; - default: - return false; - } - } - static isBigDecimalType(columnType) { - switch (columnType) { - case "java.math.BigDecimal": - return true; - default: - return false; - } - } - static isBigIntegerType(columnType) { - switch (columnType) { - case "java.math.BigInteger": - return true; - default: - return false; - } - } - static isBooleanType(columnType) { - switch (columnType) { - case "boolean": - case "java.lang.Boolean": - return true; - default: - return false; - } - } - static isCharType(columnType) { - switch (columnType) { - case "char": - case "java.lang.Character": - return true; - default: - return false; - } - } - static isStringType(columnType) { - switch (columnType) { - case "java.lang.String": - return true; - default: - return false; - } - } - static isTextType(columnType) { - return this.isStringType(columnType) || this.isCharType(columnType); - } - /** - * Get base column type - * @param columnType Column type - * @returns Element type for array columns, original type for non-array columns - */ - static getBaseType(columnType) { - return columnType.split("[]")[0]; - } - /** - * Check if the column types are compatible - * @param type1 Column type to check - * @param type2 Column type to check - * @returns True, if types are compatible - */ - static isCompatibleType(type1, type2) { - return TableUtils.getNormalizedType(type1) === TableUtils.getNormalizedType(type2); - } - /** - * Adds quotes to a value if they're not already added - * @param value Value to add quotes around - */ - static quoteValue(value2) { - if (value2.length >= 2 && (value2.charAt(0) === '"' && value2.charAt(value2.length - 1) === '"' || value2.charAt(0) === "'" && value2.charAt(value2.length - 1) === "'")) { - return value2; - } - return '"'.concat(value2, '"'); - } - static isRangeOperation(operation) { - switch (operation) { - case "<": - case "<=": - case "=<": - case ">": - case ">=": - case "=>": - return true; - default: - return false; - } - } - /** - * @param filter The column filter to apply the range operation to - * @param operation The range operation to run - * @param value The value to use for the operation - * @returns The condition with the specified operation - */ - static makeRangeFilterWithOperation(filter, operation, value2) { - switch (operation) { - case "=": - return filter.eq(value2); - case "<": - return filter.lessThan(value2); - case "<=": - case "=<": - return filter.lessThanOrEqualTo(value2); - case ">": - return filter.greaterThan(value2); - case ">=": - case "=>": - return filter.greaterThanOrEqualTo(value2); - case "!=": - case "!": - return filter.notEq(value2); - default: - return null; - } - } - /** - * Wraps a table promise in a cancelable promise that will close the table if the promise is cancelled. - * Use in a component that loads a table, and call cancel when unmounting. - * @param table The table promise to wrap - */ - static makeCancelableTablePromise(table) { - return PromiseUtils.makeCancelable(table, (resolved) => { - resolved.close(); - }); - } - /** - * Make a cancelable promise for a one-shot table event with a timeout. - * @param table Table to listen for events on - * @param eventName Event to listen for - * @param timeout Event timeout in milliseconds, defaults to 0 - * @param matcher Optional function to determine if the promise can be resolved or stays pending - * @returns Resolves with the event data - */ - static makeCancelableTableEventPromise(table, eventName) { - var timeout = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : 0; - var matcher = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; - var eventCleanup; - var timeoutId; - var isPending = true; - var wrappedPromise = new Promise((resolve, reject) => { - timeoutId = setTimeout(() => { - eventCleanup(); - isPending = false; - reject(new TimeoutError('Event "'.concat(eventName, '" timed out.'))); - }, timeout); - eventCleanup = table.addEventListener(eventName, (event) => { - if (matcher != null && !matcher(event)) { - log$3.debug2("Event triggered, but matcher returned false."); - return; - } - log$3.debug2("Event triggered, resolving."); - eventCleanup(); - clearTimeout(timeoutId); - isPending = false; - resolve(event); - }); - }); - wrappedPromise.cancel = () => { - if (isPending) { - log$3.debug2("Pending promise cleanup."); - eventCleanup(); - clearTimeout(timeoutId); - isPending = false; - return; - } - log$3.debug2("Ignoring non-pending promise cancel."); - }; - return wrappedPromise; - } - static removeCommas(value2) { - return value2.replace(/[\s|,]/g, ""); - } - static makeBooleanValue(text) { - var allowEmpty = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : false; - if (text === "" && allowEmpty) { - return null; - } - switch (text === null || text === void 0 ? void 0 : text.toLowerCase()) { - case "null": - return null; - case "0": - case "f": - case "fa": - case "fal": - case "fals": - case "false": - case "n": - case "no": - return false; - case "1": - case "t": - case "tr": - case "tru": - case "true": - case "y": - case "ye": - case "yes": - return true; - default: - throw new Error("Invalid boolean '".concat(text, "'")); - } - } - static makeNumberValue(text) { - if (text === "null" || text === "") { - return null; - } - var cleanText = text.toLowerCase().trim(); - if (cleanText === "∞" || cleanText === "infinity" || cleanText === "inf") { - return Number.POSITIVE_INFINITY; - } - if (cleanText === "-∞" || cleanText === "-infinity" || cleanText === "-inf") { - return Number.NEGATIVE_INFINITY; - } - var numberText = TableUtils.removeCommas(cleanText); - if (TableUtils.NUMBER_REGEX.test(numberText)) { - return parseFloat(numberText); - } - throw new Error("Invalid number '".concat(text, "'")); - } - static getFilterOperatorString(operation) { - switch (operation) { - case Type.eq: - return "="; - case Type.notEq: - return "!="; - case Type.greaterThan: - return ">"; - case Type.greaterThanOrEqualTo: - return ">="; - case Type.lessThan: - return "<"; - case Type.lessThanOrEqualTo: - return "<="; - case Type.contains: - return "~"; - case Type.notContains: - return "!~"; - default: - throw new Error("Unexpected filter type ".concat(operation)); - } - } - static isPartitionedTable(table) { - return table != null && table.getMergedTable !== void 0 && table.getKeyTable !== void 0 && table.getKeys !== void 0; - } - static isTreeTable(table) { - return table != null && table.expand !== void 0 && table.collapse !== void 0; - } - /** - * Copies the provided array, sorts by column name case insensitive, and returns the sorted array. - * @param columns The columns to sort - * @param isAscending Whether to sort ascending - */ - static sortColumns(columns) { - var isAscending = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : true; - return [...columns].sort((a, b) => { - var aName = a.name.toUpperCase(); - var bName = b.name.toUpperCase(); - return TextUtils.sort(aName, bName, isAscending); - }); - } - constructor(dh) { - _defineProperty$3(this, "dh", void 0); - this.dh = dh; - bindAllMethods(this); - } - /** - * Create a table containing a distinct list of values for given column name and - * applies the given sort direction. - * @param table Source table to derive table from - * @param columnName Column to dermine distinct values - * @param sortDirection Direction to sort - * @param filterConditionFactories Optional filters to apply. Note that these - * will be applied before the `selectCall` in case we need to base the filtering - * on columns other than the distinct value column - */ - createDistinctSortedColumnTable(table, columnName, sortDirection) { - var _arguments2 = arguments, _this = this; - return _asyncToGenerator$1(function* () { - if (table == null) { - return null; - } - var sourceTable = table; - for (var _len2 = _arguments2.length, filterConditionFactories = new Array(_len2 > 3 ? _len2 - 3 : 0), _key2 = 3; _key2 < _len2; _key2++) { - filterConditionFactories[_key2 - 3] = _arguments2[_key2]; - } - if (filterConditionFactories.length > 0) { - sourceTable = yield table.copy(); - yield sourceTable.applyFilter(removeNullAndUndefined(...filterConditionFactories.map((f2) => f2(sourceTable)))); - } - var column = sourceTable.findColumn(columnName); - var distinctTable = yield sourceTable.selectDistinct([column]); - if (sourceTable !== table) { - sourceTable.close(); - } - var distinctAscColSort = distinctTable.findColumn(columnName).sort()[sortDirection](); - return _this.applySort(distinctTable, [distinctAscColSort]); - })(); - } - /** - * Check if any columns contain a given value. - * @param table Table to search for values - * @param columnNames Column names to search - * @param value Value to search for - * @param isCaseSensitive Whether the value check is case sensitive - */ - doesColumnValueExist(table, columnNames, value2, isCaseSensitive) { - var _this2 = this; - return _asyncToGenerator$1(function* () { - if (table == null) { - return null; - } - var filterConditionFactory = createValueFilter(_this2, columnNames, value2, isCaseSensitive ? "eq" : "eqIgnoreCase"); - var tableCopy = yield table.copy(); - yield _this2.applyFilter(tableCopy, removeNullAndUndefined(filterConditionFactory(tableCopy))); - var size = getSize(tableCopy); - tableCopy.close(); - return size > 0; - })(); - } - /** - * Get the `dh.ValueType` corresponding to the given `dh.Column.type` value. - * @param columnType The column type to get the value type for - * @returns The `dh.ValueType` corresponding to the column type - */ - getValueType(columnType) { - if (columnType == null) { - return this.dh.ValueType.STRING; - } - var columnDataType = TableUtils.getNormalizedType(columnType); - switch (columnDataType) { - case TableUtils.dataType.BOOLEAN: - return this.dh.ValueType.BOOLEAN; - case TableUtils.dataType.CHAR: - case TableUtils.dataType.STRING: - return this.dh.ValueType.STRING; - case TableUtils.dataType.DATETIME: - return this.dh.ValueType.DATETIME; - case TableUtils.dataType.DECIMAL: - case TableUtils.dataType.INT: - if (TableUtils.isBigDecimalType(columnType) || TableUtils.isBigIntegerType(columnType)) { - return this.dh.ValueType.STRING; - } - return this.dh.ValueType.NUMBER; - default: - return this.dh.ValueType.STRING; - } - } - /** - * Create filter with the provided column and text. Handles multiple filters joined with && or || - * @param column The column to set the filter on - * @param text The text string to create the filter from - * @param timeZone The time zone to make this value in if it is a date type. E.g. America/New_York - * @returns Returns the created filter, null if text could not be parsed - */ - makeQuickFilter(column, text, timeZone) { - var orComponents = text.split("||"); - var orFilter = null; - for (var i = 0; i < orComponents.length; i += 1) { - var orComponent = orComponents[i]; - var andComponents = orComponent.split("&&"); - var andFilter = null; - for (var j = 0; j < andComponents.length; j += 1) { - var andComponent = andComponents[j].trim(); - if (andComponent.length > 0) { - var filter = this.makeQuickFilterFromComponent(column, andComponent, timeZone); - if (filter) { - if (andFilter) { - andFilter = andFilter.and(filter); - } else { - andFilter = filter; - } - } else { - throw new Error("Unable to parse quick filter from text ".concat(text)); - } - } - } - if (orFilter && andFilter) { - orFilter = orFilter.or(andFilter); - } else { - orFilter = andFilter; - } - } - return orFilter; - } - /** - * Create filter with the provided column and text of one component (no multiple conditions) - * @param column The column to set the filter on - * @param text The text string to create the filter from - * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York - * @returns Returns the created filter, null if text could not be parsed - */ - makeQuickFilterFromComponent(column, text, timeZone) { - var { - type - } = column; - if (TableUtils.isNumberType(type)) { - return this.makeQuickNumberFilter(column, text); - } - if (TableUtils.isBooleanType(type)) { - return this.makeQuickBooleanFilter(column, text); - } - if (timeZone != null && TableUtils.isDateType(type)) { - return this.makeQuickDateFilter(column, text, timeZone); - } - if (TableUtils.isCharType(type)) { - return this.makeQuickCharFilter(column, text); - } - return this.makeQuickTextFilter(column, text); - } - makeQuickNumberFilter(column, text) { - var columnFilter = column.filter(); - var { - dh - } = this; - var filter = null; - var regex = /\s*(>=|<=|=>|=<|>|<|!=|=|!)?(\s*-\s*)?(\s*\d*(?:,\d{3})*(?:\.\d*)?\s*)?(null|nan|infinity|inf|\u221E)?(.*)/i; - var result = regex.exec(text); - var operation = null; - var negativeSign = null; - var value2 = null; - var abnormalValue = null; - var overflow = null; - if (result !== null && result.length > 3) { - [, operation, negativeSign, value2, abnormalValue, overflow] = result; - } - if (overflow != null && overflow.trim().length > 0) { - return null; - } - if (operation == null) { - operation = "="; - } - if (abnormalValue != null) { - if (!(operation === "=" || operation === "!" || operation === "!=")) { - return null; - } - abnormalValue = abnormalValue.trim().toLowerCase(); - switch (abnormalValue) { - case "null": - filter = columnFilter.isNull(); - break; - case "nan": - filter = dh.FilterCondition.invoke("isNaN", columnFilter); - break; - case "infinity": - case "inf": - case "∞": - if (negativeSign != null) { - filter = dh.FilterCondition.invoke("isInf", columnFilter).and(columnFilter.lessThan(dh.FilterValue.ofNumber(0))); - } else { - filter = dh.FilterCondition.invoke("isInf", columnFilter).and(columnFilter.greaterThan(dh.FilterValue.ofNumber(0))); - } - break; - } - if (filter !== null && (operation === "!" || operation === "!=")) { - filter = filter.not(); - } - return filter; - } - if (value2 == null) { - return null; - } - value2 = TableUtils.removeCommas(value2); - if (TableUtils.isLongType(column.type)) { - try { - value2 = dh.FilterValue.ofNumber(dh.LongWrapper.ofString("".concat(negativeSign != null ? "-" : "").concat(value2))); - } catch (error) { - log$3.warn("Unable to create long filter", error); - return null; - } - } else { - value2 = parseFloat(value2); - if (value2 == null || Number.isNaN(value2)) { - return null; - } - value2 = dh.FilterValue.ofNumber(negativeSign != null ? 0 - value2 : value2); - } - filter = column.filter(); - return TableUtils.makeRangeFilterWithOperation(filter, operation, value2); - } - /** - * Given a text string from a table, escape quick filter operators in string with \ - * ex. =test returns \=test, null returns \null - * @param string quickfilter string to escape - * @returns escaped string - */ - static escapeQuickTextFilter(quickFilterText) { - var _operation, _value2; - if (quickFilterText == null) return null; - var regex = /^(!~|!=|~|=|!)?(.*)/; - var nullRegex = /^\\*null$/; - var result = regex.exec(quickFilterText); - var operation = null; - var value2 = null; - if (result !== null && result.length > 2) { - [, operation, value2] = result; - } - if (operation != null) { - var _value; - return "\\".concat(operation).concat((_value = value2) !== null && _value !== void 0 ? _value : ""); - } - if (value2 != null && nullRegex.test(value2.toLowerCase())) { - return "\\".concat(value2); - } - if (value2 != null && value2.startsWith("*")) { - return "\\".concat(value2); - } - if (value2 != null && value2.endsWith("*") && !value2.endsWith("\\*")) { - value2 = value2.substring(0, value2.length - 1); - return "".concat(value2, "\\*"); - } - return "".concat((_operation = operation) !== null && _operation !== void 0 ? _operation : "").concat((_value2 = value2) !== null && _value2 !== void 0 ? _value2 : ""); - } - /** - * Given an escaped quick filter, unescape the operators for giving it to the js api - * ex. \=test returns =test, \null returns null - * @param string quickfilter string to escape - * @returns escaped string - */ - static unescapeQuickTextFilter(quickFilterText) { - var _operation2, _value3; - var regex = /^(\\!~|\\!=|\\~|\\=|\\!)?(.*)/; - var nullRegex = /^\\*null$/; - var result = regex.exec(quickFilterText); - var operation = null; - var value2 = null; - if (result !== null && result.length > 2) { - [, operation, value2] = result; - } - if (operation != null) { - operation = operation.replace("\\", ""); - } - if (value2 != null && nullRegex.test(value2.toLowerCase())) { - value2 = value2.replace("\\", ""); - } - if (operation == null && value2 != null && value2.startsWith("\\*")) { - value2 = value2.substring(1); - } - if (operation == null && value2 != null && value2.endsWith("\\*")) { - value2 = value2.substring(0, value2.length - 2); - return "".concat(value2, "*"); - } - return "".concat((_operation2 = operation) !== null && _operation2 !== void 0 ? _operation2 : "").concat((_value3 = value2) !== null && _value3 !== void 0 ? _value3 : ""); - } - makeQuickTextFilter(column, text) { - var { - dh - } = this; - var cleanText = "".concat(text).trim(); - var regex = /^(!~|!=|~|=|!)?(.*)/; - var result = regex.exec(cleanText); - var operation = null; - var value2 = null; - if (result !== null && result.length > 2) { - [, operation, value2] = result; - if (value2 != null) { - value2 = value2.trim(); - } - } - if (value2 == null) { - return null; - } - if (value2.length === 0 && !(operation === "=" || operation === "!=")) { - return null; - } - if (operation == null) { - operation = "="; - } - var filter = column.filter(); - if (value2.toLowerCase() === "null") { - switch (operation) { - case "=": - return filter.isNull(); - case "!=": - case "!": - return filter.isNull().not(); - } - } - var prefix = null; - var suffix = null; - if (value2.startsWith("*")) { - prefix = "*"; - value2 = value2.substring(1); - } else if (value2.endsWith("*") && !value2.endsWith("\\*")) { - suffix = "*"; - value2 = value2.substring(0, value2.length - 1); - } - value2 = TableUtils.unescapeQuickTextFilter(value2); - switch (operation) { - case "~": { - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*")))); - } - case "!~": - return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*"))).not()); - case "!=": - if (prefix === "*") { - return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$"))).not()); - } - if (suffix === "*") { - return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*"))).not()); - } - return filter.notEqIgnoreCase(dh.FilterValue.ofString(value2.toLowerCase())); - case "=": - if (prefix === "*") { - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$")))); - } - if (suffix === "*") { - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*")))); - } - return filter.eqIgnoreCase(dh.FilterValue.ofString(value2.toLowerCase())); - } - return null; - } - // eslint-disable-next-line class-methods-use-this - makeQuickBooleanFilter(column, text) { - var regex = /^(!=|=|!)?(.*)/; - var result = regex.exec("".concat(text).trim()); - if (result === null) { - return null; - } - var [, operation, value2] = result; - var notEqual = operation === "!" || operation === "!="; - var cleanValue = value2.trim().toLowerCase(); - var filter = column.filter(); - try { - var boolValue = TableUtils.makeBooleanValue(cleanValue); - if (boolValue != null && boolValue) { - filter = filter.isTrue(); - } else if (boolValue === null) { - filter = filter.isNull(); - } else { - filter = filter.isFalse(); - } - return notEqual ? filter.not() : filter; - } catch (e) { - return null; - } - } - /** - * Builds a date filter parsed from the text string which may or may not include an operator. - * @param column The column to build the filter from, with or without a leading operator. - * @param text The date string text to parse. - * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York - */ - makeQuickDateFilter(column, text, timeZone) { - var cleanText = text.trim(); - var regex = /\s*(>=|<=|=>|=<|>|<|!=|!|=)?(.*)/; - var result = regex.exec(cleanText); - if (result == null || result.length <= 2) { - throw new Error("Unable to parse date filter: ".concat(text)); - } - var operation = null; - var dateText = null; - [, operation, dateText] = result; - var filterOperation = Type.eq; - switch (operation) { - case "<": - filterOperation = Type.lessThan; - break; - case "<=": - case "=<": - filterOperation = Type.lessThanOrEqualTo; - break; - case ">": - filterOperation = Type.greaterThan; - break; - case ">=": - case "=>": - filterOperation = Type.greaterThanOrEqualTo; - break; - case "!=": - case "!": - filterOperation = Type.notEq; - break; - case "=": - case "==": - default: - filterOperation = Type.eq; - break; - } - return this.makeQuickDateFilterWithOperation(column, dateText, filterOperation, timeZone); - } - /** - * Builds a date filter parsed from the text string with the provided filter. - * @param column The column to build the filter from. - * @param text The date string text to parse, without an operator. - * @param operation The filter operation to use. - * @param timeZone The time zone to make this filter with. E.g. America/New_York - */ - makeQuickDateFilterWithOperation(column, text, operation, timeZone) { - var { - dh - } = this; - var [startDate, endDate] = DateUtils.parseDateRange(dh, text, timeZone); - var startValue = startDate != null ? dh.FilterValue.ofNumber(startDate) : null; - var endValue = endDate != null ? dh.FilterValue.ofNumber(endDate) : null; - var filter = column.filter(); - if (startValue == null) { - return operation === Type.notEq ? filter.isNull().not() : filter.isNull(); - } - switch (operation) { - case Type.eq: { - if (endValue != null) { - var startFilter = filter.greaterThanOrEqualTo(startValue); - var endFilter = filter.lessThan(endValue); - return startFilter.and(endFilter); - } - return filter.eq(startValue); - } - case Type.lessThan: { - return filter.lessThan(startValue); - } - case Type.lessThanOrEqualTo: { - if (endValue != null) { - return filter.lessThan(endValue); - } - return filter.lessThanOrEqualTo(startValue); - } - case Type.greaterThan: { - if (endValue != null) { - return filter.greaterThanOrEqualTo(endValue); - } - return filter.greaterThan(startValue); - } - case Type.greaterThanOrEqualTo: - return filter.greaterThanOrEqualTo(startValue); - case Type.notEq: { - if (endValue != null) { - var _startFilter = filter.lessThan(startValue); - var _endFilter = filter.greaterThanOrEqualTo(endValue); - return _startFilter.or(_endFilter); - } - return filter.notEq(startValue); - } - default: - throw new Error("Invalid operator: ".concat(operation)); - } - } - makeQuickCharFilter(column, text) { - var { - dh - } = this; - var cleanText = "".concat(text).trim(); - var regex = /^(>=|<=|=>|=<|>|<|!=|=|!)?(null|"."|'.'|.)?(.*)/; - var result = regex.exec(cleanText); - var operation = null; - var value2 = null; - var overflow = null; - if (result !== null && result.length > 3) { - [, operation, value2, overflow] = result; - } - if (overflow != null && overflow.trim().length > 0) { - return null; - } - if (value2 == null || value2.length === 0) { - return null; - } - if (operation == null) { - operation = "="; - } - var filter = column.filter(); - if (value2.toLowerCase() === "null") { - switch (operation) { - case "=": - return filter.isNull(); - case "!=": - case "!": - return filter.isNull().not(); - default: - return null; - } - } - var filterValue = dh.FilterValue.ofString(TableUtils.isRangeOperation(operation) ? TableUtils.quoteValue(value2) : value2); - return TableUtils.makeRangeFilterWithOperation(filter, operation, filterValue); - } - makeAdvancedFilter(column, options, timeZone) { - var { - filterItems, - filterOperators, - invertSelection, - selectedValues - } = options; - var filter = null; - for (var i = 0; i < filterItems.length; i += 1) { - var filterItem = filterItems[i]; - var { - selectedType, - value: value2 - } = filterItem; - if (selectedType != null && selectedType.length > 0 && value2 != null && value2.length > 0) { - try { - var newFilter = this.makeAdvancedValueFilter(column, selectedType, value2, timeZone); - if (newFilter != null) { - if (i === 0) { - filter = newFilter; - } else if (filter !== null && i - 1 < filterOperators.length) { - var filterOperator = filterOperators[i - 1]; - if (filterOperator === Operator.and) { - filter = filter.and(newFilter); - } else if (filterOperator === Operator.or) { - filter = filter.or(newFilter); - } else { - log$3.error("Unexpected filter operator", filterOperator, newFilter); - filter = null; - break; - } - } - } else { - log$3.debug2("Empty filter ignored for", selectedType, value2); - } - } catch (err) { - log$3.error("Unable to create filter", err); - filter = null; - break; - } - } - } - var selectValueFilter = this.makeSelectValueFilter(column, selectedValues, invertSelection); - if (selectValueFilter != null) { - if (filter != null) { - filter = filter.and(selectValueFilter); - } else { - filter = selectValueFilter; - } - } - return filter; - } - makeAdvancedValueFilter(column, operation, value2, timeZone) { - var { - dh - } = this; - if (TableUtils.isDateType(column.type)) { - return this.makeQuickDateFilterWithOperation(column, value2, operation, timeZone); - } - if (TableUtils.isNumberType(column.type) || TableUtils.isCharType(column.type)) { - return this.makeQuickFilter(column, "".concat(TableUtils.getFilterOperatorString(operation)).concat(value2)); - } - var filterValue = this.makeFilterValue(column.type, value2); - var filter = column.filter(); - switch (operation) { - case Type.eq: - return filter.eq(filterValue); - case Type.eqIgnoreCase: - return filter.eqIgnoreCase(filterValue); - case Type.notEq: - return filter.notEq(filterValue); - case Type.notEqIgnoreCase: - return filter.notEqIgnoreCase(filterValue); - case Type.greaterThan: - return filter.greaterThan(filterValue); - case Type.greaterThanOrEqualTo: - return filter.greaterThanOrEqualTo(filterValue); - case Type.lessThan: - return filter.lessThan(filterValue); - case Type.lessThanOrEqualTo: - return filter.lessThanOrEqualTo(filterValue); - case Type.isTrue: - return filter.isTrue(); - case Type.isFalse: - return filter.isFalse(); - case Type.isNull: - return filter.isNull(); - case Type.contains: - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*")))); - case Type.notContains: - return filter.isNull().or(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E.*"))).not()); - case Type.startsWith: - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i)^\\Q".concat(value2, "\\E.*")))); - case Type.endsWith: - return filter.isNull().not().and(filter.invoke("matches", dh.FilterValue.ofString("(?s)(?i).*\\Q".concat(value2, "\\E$")))); - case Type.in: - case Type.inIgnoreCase: - case Type.notIn: - case Type.notInIgnoreCase: - case Type.invoke: - default: - throw new Error("Unexpected filter operation: ".concat(operation)); - } - } - /** - * Create a filter condition that can search a column by a given `searchText` - * value. - * @param column The column to search - * @param searchText The text to search for - * @param timeZone The time zone to make this filter in if it is a date type. E.g. America/New_York - * @returns The filter condition that can be applied to the column - */ - makeSearchTextFilter(column, searchText, timeZone) { - var valueType = this.getValueType(column.type); - try { - if (valueType === this.dh.ValueType.BOOLEAN) { - var maybeFilterCondition = this.makeQuickBooleanFilter(column, searchText); - assertNotNull(maybeFilterCondition); - return maybeFilterCondition; - } - if (valueType === this.dh.ValueType.DATETIME) { - return this.makeQuickDateFilterWithOperation(column, DateUtils.trimDateTimeStringTimeZone(searchText), "eq", timeZone); - } - if (valueType === this.dh.ValueType.NUMBER) { - var _maybeFilterCondition = this.makeQuickNumberFilter(column, searchText); - assertNotNull(_maybeFilterCondition); - return _maybeFilterCondition; - } - if (TableUtils.isBigDecimalType(column.type) || TableUtils.isBigIntegerType(column.type)) { - return column.filter().eq(this.makeFilterValue(column.type, searchText)); - } - return column.filter().containsIgnoreCase(this.makeFilterValue(column.type, searchText)); - } catch (_unused) { - return this.makeNeverFilter(column); - } - } - /** - * Apply a filter to a table that won't match anything. - * @table The table to apply the filter to - * @columnName The name of the column to apploy the filter to - * @param timeout Timeout before cancelling the promise that waits for the next - * dh.Table.EVENT_FILTERCHANGED event - * @returns a Promise to the Table that resolves after the next - * dh.Table.EVENT_FILTERCHANGED event - */ - applyNeverFilter(table, columnName) { - var _arguments3 = arguments, _this3 = this; - return _asyncToGenerator$1(function* () { - var timeout = _arguments3.length > 2 && _arguments3[2] !== void 0 ? _arguments3[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; - if (table == null) { - return null; - } - var column = table.findColumn(columnName); - var filters = [_this3.makeNeverFilter(column)]; - yield _this3.applyFilter(table, filters, timeout); - return table; - })(); - } - /** - * Apply custom columns to a given table. Return a Promise that resolves with - * the table once the dh.Table.EVENT_CUSTOMCOLUMNSCHANGED event has fired. - * @param table The table to apply custom columns to. - * @param columns The list of column expressions or definitions to apply. - * @returns A Promise that will be resolved with the given table after the - * columns are applied. - */ - applyCustomColumns(table, columns) { - var _arguments4 = arguments, _this4 = this; - return _asyncToGenerator$1(function* () { - var timeout = _arguments4.length > 2 && _arguments4[2] !== void 0 ? _arguments4[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; - var { - dh - } = _this4; - return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applyCustomColumns(columns), table, dh.Table.EVENT_CUSTOMCOLUMNSCHANGED, timeout); - })(); - } - /** - * Apply filters to a given table. - * @param table Table to apply filters to - * @param filters Filters to apply - * @param timeout Timeout before cancelling the promise that waits for the next - * dh.Table.EVENT_FILTERCHANGED event - * @returns a Promise to the Table that resolves after the next - * dh.Table.EVENT_FILTERCHANGED event - */ - applyFilter(table, filters) { - var _arguments5 = arguments, _this5 = this; - return _asyncToGenerator$1(function* () { - var timeout = _arguments5.length > 2 && _arguments5[2] !== void 0 ? _arguments5[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; - var { - dh - } = _this5; - return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applyFilter(filters), table, dh.Table.EVENT_FILTERCHANGED, timeout); - })(); - } - /** - * Apply sorts to a given Table. - * @param table The table to apply sorts to - * @param sorts The sorts to apply - * @param timeout Timeout before cancelling the promise that waits for the next - * dh.Table.EVENT_SORTCHANGED event - * @returns a Promise to the Table that resolves after the next - * dh.Table.EVENT_SORTCHANGED event - */ - applySort(table, sorts) { - var _arguments6 = arguments, _this6 = this; - return _asyncToGenerator$1(function* () { - var timeout = _arguments6.length > 2 && _arguments6[2] !== void 0 ? _arguments6[2] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; - var { - dh - } = _this6; - return TableUtils.executeAndWaitForEvent((t) => t === null || t === void 0 ? void 0 : t.applySort(sorts), table, dh.Table.EVENT_SORTCHANGED, timeout); - })(); - } - /** - * Create a filter condition that results in zero results for a given column - * @param column - */ - makeNeverFilter(column) { - var { - dh - } = this; - var value2 = null; - if (TableUtils.isTextType(column.type)) { - value2 = dh.FilterValue.ofString("a"); - } else if (TableUtils.isBooleanType(column.type)) { - value2 = dh.FilterValue.ofBoolean(true); - } else if (TableUtils.isDateType(column.type)) { - value2 = dh.FilterValue.ofNumber(dh.DateWrapper.ofJsDate(/* @__PURE__ */ new Date())); - } else { - value2 = dh.FilterValue.ofNumber(0); - } - var eqFilter = column.filter().eq(value2); - var notEqFilter = column.filter().notEq(value2); - return eqFilter.and(notEqFilter); - } - /** - * @param columnType The column type to make the filter value from. - * @param value The value to make the filter value from. - * @returns The FilterValue item for this column/value combination - */ - makeFilterValue(columnType, value2) { - var { - dh - } = this; - var type = TableUtils.getBaseType(columnType); - if (TableUtils.isTextType(type)) { - return dh.FilterValue.ofString(value2); - } - if (TableUtils.isLongType(type)) { - return dh.FilterValue.ofNumber(dh.LongWrapper.ofString(TableUtils.removeCommas(value2))); - } - return dh.FilterValue.ofNumber(TableUtils.removeCommas(value2)); - } - /** - * Takes a value and converts it to an `dh.FilterValue` - * - * @param columnType The column type to make the filter value from. - * @param value The value to actually set - * @returns The FilterValue item for this column/value combination - */ - makeFilterRawValue(columnType, rawValue) { - var { - dh - } = this; - if (TableUtils.isCharType(columnType)) { - return dh.FilterValue.ofString(typeof rawValue === "number" ? String.fromCharCode(rawValue) : rawValue); - } - if (TableUtils.isTextType(columnType)) { - return dh.FilterValue.ofString(rawValue); - } - if (TableUtils.isBooleanType(columnType)) { - return dh.FilterValue.ofBoolean(rawValue); - } - return dh.FilterValue.ofNumber(rawValue); - } - /** - * Creates an Eq filter for the given column and raw value - * @param column The column to set the filter on - * @param rawValue The nullable value to filter on - * @returns The filter for this column/value combination - */ - makeNullableEqFilter(column, rawValue) { - if (rawValue == null) { - return column.filter().isNull(); - } - return column.filter().eq(this.makeFilterRawValue(column.type, rawValue)); - } - /** - * Converts a string value to a value appropriate for the column - * @param columnType The column type to make the value for - * @param text The string value to make a type for - * @param timeZone The time zone to make this value in if it is a date type. E.g. America/New_York - */ - makeValue(columnType, text, timeZone) { - var { - dh - } = this; - if (text === "null") { - return null; - } - if (TableUtils.isTextType(columnType)) { - return text; - } - if (TableUtils.isLongType(columnType)) { - return dh.LongWrapper.ofString(TableUtils.removeCommas(text)); - } - if (TableUtils.isBooleanType(columnType)) { - return TableUtils.makeBooleanValue(text, true); - } - if (TableUtils.isDateType(columnType)) { - var [date] = DateUtils.parseDateRange(dh, text, timeZone); - return date; - } - if (TableUtils.isNumberType(columnType)) { - return TableUtils.makeNumberValue(text); - } - log$3.error("Unexpected column type", columnType); - return null; - } - /** - * Create a filter using the selected items - * Has a flag for invertSelection as we start from a "Select All" state and a user just deselects items. - * Since there may be millions of distinct items, it's easier to build an inverse filter. - * @param column The column to set the filter on - * @param selectedValues The values that are selected - * @param invertSelection Invert the selection (eg. All items are selected, then you deselect items) - * @returns Returns a `in` or `notIn` FilterCondition as necessary, or null if no filtering should be applied (everything selected) - */ - makeSelectValueFilter(column, selectedValues, invertSelection) { - var { - dh - } = this; - if (selectedValues.length === 0) { - if (invertSelection) { - return null; - } - return this.makeNeverFilter(column); - } - var values = []; - var isNullSelected = false; - for (var i = 0; i < selectedValues.length; i += 1) { - var value2 = selectedValues[i]; - if (value2 == null) { - isNullSelected = true; - } else if (TableUtils.isTextType(column.type)) { - values.push(dh.FilterValue.ofString(typeof value2 === "number" ? String.fromCharCode(value2) : value2)); - } else if (TableUtils.isBooleanType(column.type)) { - values.push(dh.FilterValue.ofBoolean(Boolean(value2))); - } else { - values.push(dh.FilterValue.ofNumber(value2)); - } - } - if (isNullSelected) { - if (values.length > 0) { - if (invertSelection) { - return column.filter().isNull().not().and(column.filter().notIn(values)); - } - return column.filter().isNull().or(column.filter().in(values)); - } - if (invertSelection) { - return column.filter().isNull().not(); - } - return column.filter().isNull(); - } - if (invertSelection) { - return column.filter().notIn(values); - } - return column.filter().in(values); - } -} -_defineProperty$3(TableUtils, "dataType", { - BOOLEAN: "boolean", - CHAR: "char", - DATETIME: "datetime", - DECIMAL: "decimal", - INT: "int", - STRING: "string", - UNKNOWN: "unknown" -}); -_defineProperty$3(TableUtils, "sortDirection", { - ascending: "ASC", - descending: "DESC", - reverse: "REVERSE", - none: null -}); -_defineProperty$3(TableUtils, "APPLY_TABLE_CHANGE_TIMEOUT_MS", 3e4); -_defineProperty$3(TableUtils, "REVERSE_TYPE", Object.freeze({ - NONE: "none", - PRE_SORT: "pre-sort", - POST_SORT: "post-sort" -})); -_defineProperty$3(TableUtils, "NUMBER_REGEX", /^-?\d+(\.\d+)?$/); -_defineProperty$3(TableUtils, "executeAndWaitForEvent", /* @__PURE__ */ function() { - var _ref2 = _asyncToGenerator$1(function* (exec, table, eventType) { - var timeout = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : TableUtils.APPLY_TABLE_CHANGE_TIMEOUT_MS; - if (table == null) { - return null; - } - var eventPromise = TableUtils.makeCancelableTableEventPromise(table, eventType, timeout); - exec(table); - yield eventPromise; - return table; - }); - return function(_x, _x2, _x3) { - return _ref2.apply(this, arguments); - }; -}()); -var lodash = { exports: {} }; -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -lodash.exports; -(function(module2, exports2) { - (function() { - var undefined$1; - var VERSION = "4.17.21"; - var LARGE_ARRAY_SIZE = 200; - var CORE_ERROR_TEXT = "Unsupported core-js use. Try https://npms.io/search?q=ponyfill.", FUNC_ERROR_TEXT = "Expected a function", INVALID_TEMPL_VAR_ERROR_TEXT = "Invalid `variable` option passed into `_.template`"; - var HASH_UNDEFINED = "__lodash_hash_undefined__"; - var MAX_MEMOIZE_SIZE = 500; - var PLACEHOLDER = "__lodash_placeholder__"; - var CLONE_DEEP_FLAG = 1, CLONE_FLAT_FLAG = 2, CLONE_SYMBOLS_FLAG = 4; - var COMPARE_PARTIAL_FLAG = 1, COMPARE_UNORDERED_FLAG = 2; - var WRAP_BIND_FLAG = 1, WRAP_BIND_KEY_FLAG = 2, WRAP_CURRY_BOUND_FLAG = 4, WRAP_CURRY_FLAG = 8, WRAP_CURRY_RIGHT_FLAG = 16, WRAP_PARTIAL_FLAG = 32, WRAP_PARTIAL_RIGHT_FLAG = 64, WRAP_ARY_FLAG = 128, WRAP_REARG_FLAG = 256, WRAP_FLIP_FLAG = 512; - var DEFAULT_TRUNC_LENGTH = 30, DEFAULT_TRUNC_OMISSION = "..."; - var HOT_COUNT = 800, HOT_SPAN = 16; - var LAZY_FILTER_FLAG = 1, LAZY_MAP_FLAG = 2, LAZY_WHILE_FLAG = 3; - var INFINITY = 1 / 0, MAX_SAFE_INTEGER = 9007199254740991, MAX_INTEGER = 17976931348623157e292, NAN = 0 / 0; - var MAX_ARRAY_LENGTH = 4294967295, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - var wrapFlags = [ - ["ary", WRAP_ARY_FLAG], - ["bind", WRAP_BIND_FLAG], - ["bindKey", WRAP_BIND_KEY_FLAG], - ["curry", WRAP_CURRY_FLAG], - ["curryRight", WRAP_CURRY_RIGHT_FLAG], - ["flip", WRAP_FLIP_FLAG], - ["partial", WRAP_PARTIAL_FLAG], - ["partialRight", WRAP_PARTIAL_RIGHT_FLAG], - ["rearg", WRAP_REARG_FLAG] - ]; - var argsTag = "[object Arguments]", arrayTag = "[object Array]", asyncTag = "[object AsyncFunction]", boolTag = "[object Boolean]", dateTag = "[object Date]", domExcTag = "[object DOMException]", errorTag = "[object Error]", funcTag = "[object Function]", genTag = "[object GeneratorFunction]", mapTag = "[object Map]", numberTag = "[object Number]", nullTag = "[object Null]", objectTag = "[object Object]", promiseTag = "[object Promise]", proxyTag = "[object Proxy]", regexpTag = "[object RegExp]", setTag = "[object Set]", stringTag = "[object String]", symbolTag = "[object Symbol]", undefinedTag = "[object Undefined]", weakMapTag = "[object WeakMap]", weakSetTag = "[object WeakSet]"; - var arrayBufferTag = "[object ArrayBuffer]", dataViewTag = "[object DataView]", float32Tag = "[object Float32Array]", float64Tag = "[object Float64Array]", int8Tag = "[object Int8Array]", int16Tag = "[object Int16Array]", int32Tag = "[object Int32Array]", uint8Tag = "[object Uint8Array]", uint8ClampedTag = "[object Uint8ClampedArray]", uint16Tag = "[object Uint16Array]", uint32Tag = "[object Uint32Array]"; - var reEmptyStringLeading = /\b__p \+= '';/g, reEmptyStringMiddle = /\b(__p \+=) '' \+/g, reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, reUnescapedHtml = /[&<>"']/g, reHasEscapedHtml = RegExp(reEscapedHtml.source), reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - var reEscape = /<%-([\s\S]+?)%>/g, reEvaluate = /<%([\s\S]+?)%>/g, reInterpolate = /<%=([\s\S]+?)%>/g; - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, reHasRegExpChar = RegExp(reRegExpChar.source); - var reTrimStart = /^\s+/; - var reWhitespace = /\s/; - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, reSplitDetails = /,? & /; - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - var reEscapeChar = /\\(\\)?/g; - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - var reFlags = /\w*$/; - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - var reIsBinary = /^0b[01]+$/i; - var reIsHostCtor = /^\[object .+?Constructor\]$/; - var reIsOctal = /^0o[0-7]+$/i; - var reIsUint = /^(?:0|[1-9]\d*)$/; - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - var reNoMatch = /($^)/; - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - var rsAstralRange = "\\ud800-\\udfff", rsComboMarksRange = "\\u0300-\\u036f", reComboHalfMarksRange = "\\ufe20-\\ufe2f", rsComboSymbolsRange = "\\u20d0-\\u20ff", rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, rsDingbatRange = "\\u2700-\\u27bf", rsLowerRange = "a-z\\xdf-\\xf6\\xf8-\\xff", rsMathOpRange = "\\xac\\xb1\\xd7\\xf7", rsNonCharRange = "\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf", rsPunctuationRange = "\\u2000-\\u206f", rsSpaceRange = " \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000", rsUpperRange = "A-Z\\xc0-\\xd6\\xd8-\\xde", rsVarRange = "\\ufe0e\\ufe0f", rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - var rsApos = "['’]", rsAstral = "[" + rsAstralRange + "]", rsBreak = "[" + rsBreakRange + "]", rsCombo = "[" + rsComboRange + "]", rsDigits = "\\d+", rsDingbat = "[" + rsDingbatRange + "]", rsLower = "[" + rsLowerRange + "]", rsMisc = "[^" + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + "]", rsFitz = "\\ud83c[\\udffb-\\udfff]", rsModifier = "(?:" + rsCombo + "|" + rsFitz + ")", rsNonAstral = "[^" + rsAstralRange + "]", rsRegional = "(?:\\ud83c[\\udde6-\\uddff]){2}", rsSurrPair = "[\\ud800-\\udbff][\\udc00-\\udfff]", rsUpper = "[" + rsUpperRange + "]", rsZWJ = "\\u200d"; - var rsMiscLower = "(?:" + rsLower + "|" + rsMisc + ")", rsMiscUpper = "(?:" + rsUpper + "|" + rsMisc + ")", rsOptContrLower = "(?:" + rsApos + "(?:d|ll|m|re|s|t|ve))?", rsOptContrUpper = "(?:" + rsApos + "(?:D|LL|M|RE|S|T|VE))?", reOptMod = rsModifier + "?", rsOptVar = "[" + rsVarRange + "]?", rsOptJoin = "(?:" + rsZWJ + "(?:" + [rsNonAstral, rsRegional, rsSurrPair].join("|") + ")" + rsOptVar + reOptMod + ")*", rsOrdLower = "\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])", rsOrdUpper = "\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])", rsSeq = rsOptVar + reOptMod + rsOptJoin, rsEmoji = "(?:" + [rsDingbat, rsRegional, rsSurrPair].join("|") + ")" + rsSeq, rsSymbol = "(?:" + [rsNonAstral + rsCombo + "?", rsCombo, rsRegional, rsSurrPair, rsAstral].join("|") + ")"; - var reApos = RegExp(rsApos, "g"); - var reComboMark = RegExp(rsCombo, "g"); - var reUnicode = RegExp(rsFitz + "(?=" + rsFitz + ")|" + rsSymbol + rsSeq, "g"); - var reUnicodeWord = RegExp([ - rsUpper + "?" + rsLower + "+" + rsOptContrLower + "(?=" + [rsBreak, rsUpper, "$"].join("|") + ")", - rsMiscUpper + "+" + rsOptContrUpper + "(?=" + [rsBreak, rsUpper + rsMiscLower, "$"].join("|") + ")", - rsUpper + "?" + rsMiscLower + "+" + rsOptContrLower, - rsUpper + "+" + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join("|"), "g"); - var reHasUnicode = RegExp("[" + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + "]"); - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - var contextProps = [ - "Array", - "Buffer", - "DataView", - "Date", - "Error", - "Float32Array", - "Float64Array", - "Function", - "Int8Array", - "Int16Array", - "Int32Array", - "Map", - "Math", - "Object", - "Promise", - "RegExp", - "Set", - "String", - "Symbol", - "TypeError", - "Uint8Array", - "Uint8ClampedArray", - "Uint16Array", - "Uint32Array", - "WeakMap", - "_", - "clearTimeout", - "isFinite", - "parseInt", - "setTimeout" - ]; - var templateCounter = -1; - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[mapTag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[setTag] = cloneableTags[stringTag] = cloneableTags[symbolTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[weakMapTag] = false; - var deburredLetters = { - // Latin-1 Supplement block. - "À": "A", - "Á": "A", - "Â": "A", - "Ã": "A", - "Ä": "A", - "Å": "A", - "à": "a", - "á": "a", - "â": "a", - "ã": "a", - "ä": "a", - "å": "a", - "Ç": "C", - "ç": "c", - "Ð": "D", - "ð": "d", - "È": "E", - "É": "E", - "Ê": "E", - "Ë": "E", - "è": "e", - "é": "e", - "ê": "e", - "ë": "e", - "Ì": "I", - "Í": "I", - "Î": "I", - "Ï": "I", - "ì": "i", - "í": "i", - "î": "i", - "ï": "i", - "Ñ": "N", - "ñ": "n", - "Ò": "O", - "Ó": "O", - "Ô": "O", - "Õ": "O", - "Ö": "O", - "Ø": "O", - "ò": "o", - "ó": "o", - "ô": "o", - "õ": "o", - "ö": "o", - "ø": "o", - "Ù": "U", - "Ú": "U", - "Û": "U", - "Ü": "U", - "ù": "u", - "ú": "u", - "û": "u", - "ü": "u", - "Ý": "Y", - "ý": "y", - "ÿ": "y", - "Æ": "Ae", - "æ": "ae", - "Þ": "Th", - "þ": "th", - "ß": "ss", - // Latin Extended-A block. - "Ā": "A", - "Ă": "A", - "Ą": "A", - "ā": "a", - "ă": "a", - "ą": "a", - "Ć": "C", - "Ĉ": "C", - "Ċ": "C", - "Č": "C", - "ć": "c", - "ĉ": "c", - "ċ": "c", - "č": "c", - "Ď": "D", - "Đ": "D", - "ď": "d", - "đ": "d", - "Ē": "E", - "Ĕ": "E", - "Ė": "E", - "Ę": "E", - "Ě": "E", - "ē": "e", - "ĕ": "e", - "ė": "e", - "ę": "e", - "ě": "e", - "Ĝ": "G", - "Ğ": "G", - "Ġ": "G", - "Ģ": "G", - "ĝ": "g", - "ğ": "g", - "ġ": "g", - "ģ": "g", - "Ĥ": "H", - "Ħ": "H", - "ĥ": "h", - "ħ": "h", - "Ĩ": "I", - "Ī": "I", - "Ĭ": "I", - "Į": "I", - "İ": "I", - "ĩ": "i", - "ī": "i", - "ĭ": "i", - "į": "i", - "ı": "i", - "Ĵ": "J", - "ĵ": "j", - "Ķ": "K", - "ķ": "k", - "ĸ": "k", - "Ĺ": "L", - "Ļ": "L", - "Ľ": "L", - "Ŀ": "L", - "Ł": "L", - "ĺ": "l", - "ļ": "l", - "ľ": "l", - "ŀ": "l", - "ł": "l", - "Ń": "N", - "Ņ": "N", - "Ň": "N", - "Ŋ": "N", - "ń": "n", - "ņ": "n", - "ň": "n", - "ŋ": "n", - "Ō": "O", - "Ŏ": "O", - "Ő": "O", - "ō": "o", - "ŏ": "o", - "ő": "o", - "Ŕ": "R", - "Ŗ": "R", - "Ř": "R", - "ŕ": "r", - "ŗ": "r", - "ř": "r", - "Ś": "S", - "Ŝ": "S", - "Ş": "S", - "Š": "S", - "ś": "s", - "ŝ": "s", - "ş": "s", - "š": "s", - "Ţ": "T", - "Ť": "T", - "Ŧ": "T", - "ţ": "t", - "ť": "t", - "ŧ": "t", - "Ũ": "U", - "Ū": "U", - "Ŭ": "U", - "Ů": "U", - "Ű": "U", - "Ų": "U", - "ũ": "u", - "ū": "u", - "ŭ": "u", - "ů": "u", - "ű": "u", - "ų": "u", - "Ŵ": "W", - "ŵ": "w", - "Ŷ": "Y", - "ŷ": "y", - "Ÿ": "Y", - "Ź": "Z", - "Ż": "Z", - "Ž": "Z", - "ź": "z", - "ż": "z", - "ž": "z", - "IJ": "IJ", - "ij": "ij", - "Œ": "Oe", - "œ": "oe", - "ʼn": "'n", - "ſ": "s" - }; - var htmlEscapes = { - "&": "&", - "<": "<", - ">": ">", - '"': """, - "'": "'" - }; - var htmlUnescapes = { - "&": "&", - "<": "<", - ">": ">", - """: '"', - "'": "'" - }; - var stringEscapes = { - "\\": "\\", - "'": "'", - "\n": "n", - "\r": "r", - "\u2028": "u2028", - "\u2029": "u2029" - }; - var freeParseFloat = parseFloat, freeParseInt = parseInt; - var freeGlobal = typeof commonjsGlobal == "object" && commonjsGlobal && commonjsGlobal.Object === Object && commonjsGlobal; - var freeSelf = typeof self == "object" && self && self.Object === Object && self; - var root = freeGlobal || freeSelf || Function("return this")(); - var freeExports = exports2 && !exports2.nodeType && exports2; - var freeModule = freeExports && true && module2 && !module2.nodeType && module2; - var moduleExports = freeModule && freeModule.exports === freeExports; - var freeProcess = moduleExports && freeGlobal.process; - var nodeUtil = function() { - try { - var types = freeModule && freeModule.require && freeModule.require("util").types; - if (types) { - return types; - } - return freeProcess && freeProcess.binding && freeProcess.binding("util"); - } catch (e) { - } - }(); - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, nodeIsDate = nodeUtil && nodeUtil.isDate, nodeIsMap = nodeUtil && nodeUtil.isMap, nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, nodeIsSet = nodeUtil && nodeUtil.isSet, nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - function apply2(func, thisArg, args) { - switch (args.length) { - case 0: - return func.call(thisArg); - case 1: - return func.call(thisArg, args[0]); - case 2: - return func.call(thisArg, args[0], args[1]); - case 3: - return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); - } - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - var value2 = array[index]; - setter(accumulator, value2, iteratee(value2), array); - } - return accumulator; - } - function arrayEach(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; - } - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; - } - } - return array; - } - function arrayEvery(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; - } - } - return true; - } - function arrayFilter(array, predicate) { - var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result = []; - while (++index < length) { - var value2 = array[index]; - if (predicate(value2, index, array)) { - result[resIndex++] = value2; - } - } - return result; - } - function arrayIncludes(array, value2) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value2, 0) > -1; - } - function arrayIncludesWith(array, value2, comparator) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (comparator(value2, array[index])) { - return true; - } - } - return false; - } - function arrayMap(array, iteratee) { - var index = -1, length = array == null ? 0 : array.length, result = Array(length); - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; - } - function arrayPush(array, values) { - var index = -1, length = values.length, offset = array.length; - while (++index < length) { - array[offset + index] = values[index]; - } - return array; - } - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; - } - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; - } - function arraySome(array, predicate) { - var index = -1, length = array == null ? 0 : array.length; - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; - } - var asciiSize = baseProperty("length"); - function asciiToArray(string) { - return string.split(""); - } - function asciiWords(string) { - return string.match(reAsciiWord) || []; - } - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value2, key, collection2) { - if (predicate(value2, key, collection2)) { - result = key; - return false; - } - }); - return result; - } - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, index = fromIndex + (fromRight ? 1 : -1); - while (fromRight ? index-- : ++index < length) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; - } - function baseIndexOf(array, value2, fromIndex) { - return value2 === value2 ? strictIndexOf(array, value2, fromIndex) : baseFindIndex(array, baseIsNaN, fromIndex); - } - function baseIndexOfWith(array, value2, fromIndex, comparator) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (comparator(array[index], value2)) { - return index; - } - } - return -1; - } - function baseIsNaN(value2) { - return value2 !== value2; - } - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? baseSum(array, iteratee) / length : NAN; - } - function baseProperty(key) { - return function(object) { - return object == null ? undefined$1 : object[key]; - }; - } - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined$1 : object[key]; - }; - } - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value2, index, collection2) { - accumulator = initAccum ? (initAccum = false, value2) : iteratee(accumulator, value2, index, collection2); - }); - return accumulator; - } - function baseSortBy(array, comparer) { - var length = array.length; - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; - } - function baseSum(array, iteratee) { - var result, index = -1, length = array.length; - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined$1) { - result = result === undefined$1 ? current : result + current; - } - } - return result; - } - function baseTimes(n2, iteratee) { - var index = -1, result = Array(n2); - while (++index < n2) { - result[index] = iteratee(index); - } - return result; - } - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); - } - function baseTrim(string) { - return string ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, "") : string; - } - function baseUnary(func) { - return function(value2) { - return func(value2); - }; - } - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); - } - function cacheHas(cache, key) { - return cache.has(key); - } - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, length = strSymbols.length; - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { - } - return index; - } - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) { - } - return index; - } - function countHolders(array, placeholder) { - var length = array.length, result = 0; - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } - var deburrLetter = basePropertyOf(deburredLetters); - var escapeHtmlChar = basePropertyOf(htmlEscapes); - function escapeStringChar(chr) { - return "\\" + stringEscapes[chr]; - } - function getValue(object, key) { - return object == null ? undefined$1 : object[key]; - } - function hasUnicode(string) { - return reHasUnicode.test(string); - } - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - function iteratorToArray(iterator) { - var data, result = []; - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } - function mapToArray(map2) { - var index = -1, result = Array(map2.size); - map2.forEach(function(value2, key) { - result[++index] = [key, value2]; - }); - return result; - } - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } - function replaceHolders(array, placeholder) { - var index = -1, length = array.length, resIndex = 0, result = []; - while (++index < length) { - var value2 = array[index]; - if (value2 === placeholder || value2 === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } - function setToArray(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value2) { - result[++index] = value2; - }); - return result; - } - function setToPairs(set) { - var index = -1, result = Array(set.size); - set.forEach(function(value2) { - result[++index] = [value2, value2]; - }); - return result; - } - function strictIndexOf(array, value2, fromIndex) { - var index = fromIndex - 1, length = array.length; - while (++index < length) { - if (array[index] === value2) { - return index; - } - } - return -1; - } - function strictLastIndexOf(array, value2, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value2) { - return index; - } - } - return index; - } - function stringSize(string) { - return hasUnicode(string) ? unicodeSize(string) : asciiSize(string); - } - function stringToArray(string) { - return hasUnicode(string) ? unicodeToArray(string) : asciiToArray(string); - } - function trimmedEndIndex(string) { - var index = string.length; - while (index-- && reWhitespace.test(string.charAt(index))) { - } - return index; - } - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } - var runInContext = function runInContext2(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - var Array2 = context.Array, Date2 = context.Date, Error2 = context.Error, Function2 = context.Function, Math2 = context.Math, Object2 = context.Object, RegExp2 = context.RegExp, String2 = context.String, TypeError2 = context.TypeError; - var arrayProto = Array2.prototype, funcProto = Function2.prototype, objectProto = Object2.prototype; - var coreJsData = context["__core-js_shared__"]; - var funcToString = funcProto.toString; - var hasOwnProperty2 = objectProto.hasOwnProperty; - var idCounter = 0; - var maskSrcKey = function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ""); - return uid ? "Symbol(src)_1." + uid : ""; - }(); - var nativeObjectToString = objectProto.toString; - var objectCtorString = funcToString.call(Object2); - var oldDash = root._; - var reIsNative = RegExp2( - "^" + funcToString.call(hasOwnProperty2).replace(reRegExpChar, "\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, "$1.*?") + "$" - ); - var Buffer = moduleExports ? context.Buffer : undefined$1, Symbol2 = context.Symbol, Uint8Array = context.Uint8Array, allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined$1, getPrototype = overArg(Object2.getPrototypeOf, Object2), objectCreate = Object2.create, propertyIsEnumerable = objectProto.propertyIsEnumerable, splice = arrayProto.splice, spreadableSymbol = Symbol2 ? Symbol2.isConcatSpreadable : undefined$1, symIterator = Symbol2 ? Symbol2.iterator : undefined$1, symToStringTag = Symbol2 ? Symbol2.toStringTag : undefined$1; - var defineProperty2 = function() { - try { - var func = getNative(Object2, "defineProperty"); - func({}, "", {}); - return func; - } catch (e) { - } - }(); - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, ctxNow = Date2 && Date2.now !== root.Date.now && Date2.now, ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - var nativeCeil = Math2.ceil, nativeFloor = Math2.floor, nativeGetSymbols = Object2.getOwnPropertySymbols, nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined$1, nativeIsFinite = context.isFinite, nativeJoin = arrayProto.join, nativeKeys = overArg(Object2.keys, Object2), nativeMax = Math2.max, nativeMin = Math2.min, nativeNow = Date2.now, nativeParseInt = context.parseInt, nativeRandom = Math2.random, nativeReverse = arrayProto.reverse; - var DataView = getNative(context, "DataView"), Map2 = getNative(context, "Map"), Promise2 = getNative(context, "Promise"), Set2 = getNative(context, "Set"), WeakMap = getNative(context, "WeakMap"), nativeCreate = getNative(Object2, "create"); - var metaMap = WeakMap && new WeakMap(); - var realNames = {}; - var dataViewCtorString = toSource(DataView), mapCtorString = toSource(Map2), promiseCtorString = toSource(Promise2), setCtorString = toSource(Set2), weakMapCtorString = toSource(WeakMap); - var symbolProto = Symbol2 ? Symbol2.prototype : undefined$1, symbolValueOf = symbolProto ? symbolProto.valueOf : undefined$1, symbolToString = symbolProto ? symbolProto.toString : undefined$1; - function lodash2(value2) { - if (isObjectLike(value2) && !isArray2(value2) && !(value2 instanceof LazyWrapper)) { - if (value2 instanceof LodashWrapper) { - return value2; - } - if (hasOwnProperty2.call(value2, "__wrapped__")) { - return wrapperClone(value2); - } - } - return new LodashWrapper(value2); - } - var baseCreate = /* @__PURE__ */ function() { - function object() { - } - return function(proto) { - if (!isObject2(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result2 = new object(); - object.prototype = undefined$1; - return result2; - }; - }(); - function baseLodash() { - } - function LodashWrapper(value2, chainAll) { - this.__wrapped__ = value2; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined$1; - } - lodash2.templateSettings = { - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - "escape": reEscape, - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - "evaluate": reEvaluate, - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - "interpolate": reInterpolate, - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - "variable": "", - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - "imports": { - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - "_": lodash2 - } - }; - lodash2.prototype = baseLodash.prototype; - lodash2.prototype.constructor = lodash2; - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; - function LazyWrapper(value2) { - this.__wrapped__ = value2; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } - function lazyClone() { - var result2 = new LazyWrapper(this.__wrapped__); - result2.__actions__ = copyArray(this.__actions__); - result2.__dir__ = this.__dir__; - result2.__filtered__ = this.__filtered__; - result2.__iteratees__ = copyArray(this.__iteratees__); - result2.__takeCount__ = this.__takeCount__; - result2.__views__ = copyArray(this.__views__); - return result2; - } - function lazyReverse() { - if (this.__filtered__) { - var result2 = new LazyWrapper(this); - result2.__dir__ = -1; - result2.__filtered__ = true; - } else { - result2 = this.clone(); - result2.__dir__ *= -1; - } - return result2; - } - function lazyValue() { - var array = this.__wrapped__.value(), dir = this.__dir__, isArr = isArray2(array), isRight = dir < 0, arrLength = isArr ? array.length : 0, view = getView(0, arrLength, this.__views__), start = view.start, end = view.end, length = end - start, index = isRight ? end : start - 1, iteratees = this.__iteratees__, iterLength = iteratees.length, resIndex = 0, takeCount = nativeMin(length, this.__takeCount__); - if (!isArr || !isRight && arrLength == length && takeCount == length) { - return baseWrapperValue(array, this.__actions__); - } - var result2 = []; - outer: - while (length-- && resIndex < takeCount) { - index += dir; - var iterIndex = -1, value2 = array[index]; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], iteratee2 = data.iteratee, type = data.type, computed = iteratee2(value2); - if (type == LAZY_MAP_FLAG) { - value2 = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result2[resIndex++] = value2; - } - return result2; - } - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; - function Hash(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; - } - function hashDelete(key) { - var result2 = this.has(key) && delete this.__data__[key]; - this.size -= result2 ? 1 : 0; - return result2; - } - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result2 = data[key]; - return result2 === HASH_UNDEFINED ? undefined$1 : result2; - } - return hasOwnProperty2.call(data, key) ? data[key] : undefined$1; - } - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined$1 : hasOwnProperty2.call(data, key); - } - function hashSet(key, value2) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = nativeCreate && value2 === undefined$1 ? HASH_UNDEFINED : value2; - return this; - } - Hash.prototype.clear = hashClear; - Hash.prototype["delete"] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; - function ListCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } - function listCacheDelete(key) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } - function listCacheGet(key) { - var data = this.__data__, index = assocIndexOf(data, key); - return index < 0 ? undefined$1 : data[index][1]; - } - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - function listCacheSet(key, value2) { - var data = this.__data__, index = assocIndexOf(data, key); - if (index < 0) { - ++this.size; - data.push([key, value2]); - } else { - data[index][1] = value2; - } - return this; - } - ListCache.prototype.clear = listCacheClear; - ListCache.prototype["delete"] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; - function MapCache(entries) { - var index = -1, length = entries == null ? 0 : entries.length; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } - function mapCacheClear() { - this.size = 0; - this.__data__ = { - "hash": new Hash(), - "map": new (Map2 || ListCache)(), - "string": new Hash() - }; - } - function mapCacheDelete(key) { - var result2 = getMapData(this, key)["delete"](key); - this.size -= result2 ? 1 : 0; - return result2; - } - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } - function mapCacheSet(key, value2) { - var data = getMapData(this, key), size2 = data.size; - data.set(key, value2); - this.size += data.size == size2 ? 0 : 1; - return this; - } - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype["delete"] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; - function SetCache(values2) { - var index = -1, length = values2 == null ? 0 : values2.length; - this.__data__ = new MapCache(); - while (++index < length) { - this.add(values2[index]); - } - } - function setCacheAdd(value2) { - this.__data__.set(value2, HASH_UNDEFINED); - return this; - } - function setCacheHas(value2) { - return this.__data__.has(value2); - } - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } - function stackClear() { - this.__data__ = new ListCache(); - this.size = 0; - } - function stackDelete(key) { - var data = this.__data__, result2 = data["delete"](key); - this.size = data.size; - return result2; - } - function stackGet(key) { - return this.__data__.get(key); - } - function stackHas(key) { - return this.__data__.has(key); - } - function stackSet(key, value2) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map2 || pairs.length < LARGE_ARRAY_SIZE - 1) { - pairs.push([key, value2]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value2); - this.size = data.size; - return this; - } - Stack.prototype.clear = stackClear; - Stack.prototype["delete"] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - function arrayLikeKeys(value2, inherited) { - var isArr = isArray2(value2), isArg = !isArr && isArguments2(value2), isBuff = !isArr && !isArg && isBuffer(value2), isType = !isArr && !isArg && !isBuff && isTypedArray(value2), skipIndexes = isArr || isArg || isBuff || isType, result2 = skipIndexes ? baseTimes(value2.length, String2) : [], length = result2.length; - for (var key in value2) { - if ((inherited || hasOwnProperty2.call(value2, key)) && !(skipIndexes && // Safari 9 has enumerable `arguments.length` in strict mode. - (key == "length" || // Node.js 0.10 has enumerable non-index properties on buffers. - isBuff && (key == "offset" || key == "parent") || // PhantomJS 2 has enumerable non-index properties on typed arrays. - isType && (key == "buffer" || key == "byteLength" || key == "byteOffset") || // Skip index properties. - isIndex(key, length)))) { - result2.push(key); - } - } - return result2; - } - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined$1; - } - function arraySampleSize(array, n2) { - return shuffleSelf(copyArray(array), baseClamp(n2, 0, array.length)); - } - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } - function assignMergeValue(object, key, value2) { - if (value2 !== undefined$1 && !eq(object[key], value2) || value2 === undefined$1 && !(key in object)) { - baseAssignValue(object, key, value2); - } - } - function assignValue(object, key, value2) { - var objValue = object[key]; - if (!(hasOwnProperty2.call(object, key) && eq(objValue, value2)) || value2 === undefined$1 && !(key in object)) { - baseAssignValue(object, key, value2); - } - } - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } - function baseAggregator(collection, setter, iteratee2, accumulator) { - baseEach(collection, function(value2, key, collection2) { - setter(accumulator, value2, iteratee2(value2), collection2); - }); - return accumulator; - } - function baseAssign(object, source) { - return object && copyObject(source, keys2(source), object); - } - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } - function baseAssignValue(object, key, value2) { - if (key == "__proto__" && defineProperty2) { - defineProperty2(object, key, { - "configurable": true, - "enumerable": true, - "value": value2, - "writable": true - }); - } else { - object[key] = value2; - } - } - function baseAt(object, paths) { - var index = -1, length = paths.length, result2 = Array2(length), skip = object == null; - while (++index < length) { - result2[index] = skip ? undefined$1 : get2(object, paths[index]); - } - return result2; - } - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined$1) { - number = number <= upper ? number : upper; - } - if (lower !== undefined$1) { - number = number >= lower ? number : lower; - } - } - return number; - } - function baseClone(value2, bitmask, customizer, key, object, stack) { - var result2, isDeep = bitmask & CLONE_DEEP_FLAG, isFlat = bitmask & CLONE_FLAT_FLAG, isFull = bitmask & CLONE_SYMBOLS_FLAG; - if (customizer) { - result2 = object ? customizer(value2, key, object, stack) : customizer(value2); - } - if (result2 !== undefined$1) { - return result2; - } - if (!isObject2(value2)) { - return value2; - } - var isArr = isArray2(value2); - if (isArr) { - result2 = initCloneArray(value2); - if (!isDeep) { - return copyArray(value2, result2); - } - } else { - var tag = getTag(value2), isFunc = tag == funcTag || tag == genTag; - if (isBuffer(value2)) { - return cloneBuffer(value2, isDeep); - } - if (tag == objectTag || tag == argsTag || isFunc && !object) { - result2 = isFlat || isFunc ? {} : initCloneObject(value2); - if (!isDeep) { - return isFlat ? copySymbolsIn(value2, baseAssignIn(result2, value2)) : copySymbols(value2, baseAssign(result2, value2)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value2 : {}; - } - result2 = initCloneByTag(value2, tag, isDeep); - } - } - stack || (stack = new Stack()); - var stacked = stack.get(value2); - if (stacked) { - return stacked; - } - stack.set(value2, result2); - if (isSet(value2)) { - value2.forEach(function(subValue) { - result2.add(baseClone(subValue, bitmask, customizer, subValue, value2, stack)); - }); - } else if (isMap(value2)) { - value2.forEach(function(subValue, key2) { - result2.set(key2, baseClone(subValue, bitmask, customizer, key2, value2, stack)); - }); - } - var keysFunc = isFull ? isFlat ? getAllKeysIn : getAllKeys : isFlat ? keysIn : keys2; - var props = isArr ? undefined$1 : keysFunc(value2); - arrayEach(props || value2, function(subValue, key2) { - if (props) { - key2 = subValue; - subValue = value2[key2]; - } - assignValue(result2, key2, baseClone(subValue, bitmask, customizer, key2, value2, stack)); - }); - return result2; - } - function baseConforms(source) { - var props = keys2(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object2(object); - while (length--) { - var key = props[length], predicate = source[key], value2 = object[key]; - if (value2 === undefined$1 && !(key in object) || !predicate(value2)) { - return false; - } - } - return true; - } - function baseDelay(func, wait, args) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return setTimeout2(function() { - func.apply(undefined$1, args); - }, wait); - } - function baseDifference(array, values2, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, isCommon = true, length = array.length, result2 = [], valuesLength = values2.length; - if (!length) { - return result2; - } - if (iteratee2) { - values2 = arrayMap(values2, baseUnary(iteratee2)); - } - if (comparator) { - includes2 = arrayIncludesWith; - isCommon = false; - } else if (values2.length >= LARGE_ARRAY_SIZE) { - includes2 = cacheHas; - isCommon = false; - values2 = new SetCache(values2); - } - outer: - while (++index < length) { - var value2 = array[index], computed = iteratee2 == null ? value2 : iteratee2(value2); - value2 = comparator || value2 !== 0 ? value2 : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values2[valuesIndex] === computed) { - continue outer; - } - } - result2.push(value2); - } else if (!includes2(values2, computed, comparator)) { - result2.push(value2); - } - } - return result2; - } - var baseEach = createBaseEach(baseForOwn); - var baseEachRight = createBaseEach(baseForOwnRight, true); - function baseEvery(collection, predicate) { - var result2 = true; - baseEach(collection, function(value2, index, collection2) { - result2 = !!predicate(value2, index, collection2); - return result2; - }); - return result2; - } - function baseExtremum(array, iteratee2, comparator) { - var index = -1, length = array.length; - while (++index < length) { - var value2 = array[index], current = iteratee2(value2); - if (current != null && (computed === undefined$1 ? current === current && !isSymbol2(current) : comparator(current, computed))) { - var computed = current, result2 = value2; - } - } - return result2; - } - function baseFill(array, value2, start, end) { - var length = array.length; - start = toInteger2(start); - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end === undefined$1 || end > length ? length : toInteger2(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value2; - } - return array; - } - function baseFilter(collection, predicate) { - var result2 = []; - baseEach(collection, function(value2, index, collection2) { - if (predicate(value2, index, collection2)) { - result2.push(value2); - } - }); - return result2; - } - function baseFlatten(array, depth, predicate, isStrict, result2) { - var index = -1, length = array.length; - predicate || (predicate = isFlattenable); - result2 || (result2 = []); - while (++index < length) { - var value2 = array[index]; - if (depth > 0 && predicate(value2)) { - if (depth > 1) { - baseFlatten(value2, depth - 1, predicate, isStrict, result2); - } else { - arrayPush(result2, value2); - } - } else if (!isStrict) { - result2[result2.length] = value2; - } - } - return result2; - } - var baseFor = createBaseFor(); - var baseForRight = createBaseFor(true); - function baseForOwn(object, iteratee2) { - return object && baseFor(object, iteratee2, keys2); - } - function baseForOwnRight(object, iteratee2) { - return object && baseForRight(object, iteratee2, keys2); - } - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction2(object[key]); - }); - } - function baseGet(object, path) { - path = castPath(path, object); - var index = 0, length = path.length; - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return index && index == length ? object : undefined$1; - } - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result2 = keysFunc(object); - return isArray2(object) ? result2 : arrayPush(result2, symbolsFunc(object)); - } - function baseGetTag(value2) { - if (value2 == null) { - return value2 === undefined$1 ? undefinedTag : nullTag; - } - return symToStringTag && symToStringTag in Object2(value2) ? getRawTag(value2) : objectToString(value2); - } - function baseGt(value2, other) { - return value2 > other; - } - function baseHas(object, key) { - return object != null && hasOwnProperty2.call(object, key); - } - function baseHasIn(object, key) { - return object != null && key in Object2(object); - } - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } - function baseIntersection(arrays, iteratee2, comparator) { - var includes2 = comparator ? arrayIncludesWith : arrayIncludes, length = arrays[0].length, othLength = arrays.length, othIndex = othLength, caches = Array2(othLength), maxLength = Infinity, result2 = []; - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee2) { - array = arrayMap(array, baseUnary(iteratee2)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee2 || length >= 120 && array.length >= 120) ? new SetCache(othIndex && array) : undefined$1; - } - array = arrays[0]; - var index = -1, seen = caches[0]; - outer: - while (++index < length && result2.length < maxLength) { - var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; - value2 = comparator || value2 !== 0 ? value2 : 0; - if (!(seen ? cacheHas(seen, computed) : includes2(result2, computed, comparator))) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache ? cacheHas(cache, computed) : includes2(arrays[othIndex], computed, comparator))) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result2.push(value2); - } - } - return result2; - } - function baseInverter(object, setter, iteratee2, accumulator) { - baseForOwn(object, function(value2, key, object2) { - setter(accumulator, iteratee2(value2), key, object2); - }); - return accumulator; - } - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined$1 : apply2(func, object, args); - } - function baseIsArguments(value2) { - return isObjectLike(value2) && baseGetTag(value2) == argsTag; - } - function baseIsArrayBuffer(value2) { - return isObjectLike(value2) && baseGetTag(value2) == arrayBufferTag; - } - function baseIsDate(value2) { - return isObjectLike(value2) && baseGetTag(value2) == dateTag; - } - function baseIsEqual(value2, other, bitmask, customizer, stack) { - if (value2 === other) { - return true; - } - if (value2 == null || other == null || !isObjectLike(value2) && !isObjectLike(other)) { - return value2 !== value2 && other !== other; - } - return baseIsEqualDeep(value2, other, bitmask, customizer, baseIsEqual, stack); - } - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray2(object), othIsArr = isArray2(other), objTag = objIsArr ? arrayTag : getTag(object), othTag = othIsArr ? arrayTag : getTag(other); - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; - var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack()); - return objIsArr || isTypedArray(object) ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty2.call(object, "__wrapped__"), othIsWrapped = othIsObj && hasOwnProperty2.call(other, "__wrapped__"); - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, othUnwrapped = othIsWrapped ? other.value() : other; - stack || (stack = new Stack()); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack()); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } - function baseIsMap(value2) { - return isObjectLike(value2) && getTag(value2) == mapTag; - } - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, length = index, noCustomizer = !customizer; - if (object == null) { - return !length; - } - object = Object2(object); - while (index--) { - var data = matchData[index]; - if (noCustomizer && data[2] ? data[1] !== object[data[0]] : !(data[0] in object)) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], objValue = object[key], srcValue = data[1]; - if (noCustomizer && data[2]) { - if (objValue === undefined$1 && !(key in object)) { - return false; - } - } else { - var stack = new Stack(); - if (customizer) { - var result2 = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result2 === undefined$1 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) : result2)) { - return false; - } - } - } - return true; - } - function baseIsNative(value2) { - if (!isObject2(value2) || isMasked(value2)) { - return false; - } - var pattern = isFunction2(value2) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value2)); - } - function baseIsRegExp(value2) { - return isObjectLike(value2) && baseGetTag(value2) == regexpTag; - } - function baseIsSet(value2) { - return isObjectLike(value2) && getTag(value2) == setTag; - } - function baseIsTypedArray(value2) { - return isObjectLike(value2) && isLength(value2.length) && !!typedArrayTags[baseGetTag(value2)]; - } - function baseIteratee(value2) { - if (typeof value2 == "function") { - return value2; - } - if (value2 == null) { - return identity; - } - if (typeof value2 == "object") { - return isArray2(value2) ? baseMatchesProperty(value2[0], value2[1]) : baseMatches(value2); - } - return property(value2); - } - function baseKeys(object) { - if (!isPrototype2(object)) { - return nativeKeys(object); - } - var result2 = []; - for (var key in Object2(object)) { - if (hasOwnProperty2.call(object, key) && key != "constructor") { - result2.push(key); - } - } - return result2; - } - function baseKeysIn(object) { - if (!isObject2(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype2(object), result2 = []; - for (var key in object) { - if (!(key == "constructor" && (isProto || !hasOwnProperty2.call(object, key)))) { - result2.push(key); - } - } - return result2; - } - function baseLt(value2, other) { - return value2 < other; - } - function baseMap(collection, iteratee2) { - var index = -1, result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value2, key, collection2) { - result2[++index] = iteratee2(value2, key, collection2); - }); - return result2; - } - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get2(object, path); - return objValue === undefined$1 && objValue === srcValue ? hasIn(object, path) : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack()); - if (isObject2(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } else { - var newValue = customizer ? customizer(safeGet(object, key), srcValue, key + "", object, source, stack) : undefined$1; - if (newValue === undefined$1) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), srcValue = safeGet(source, key), stacked = stack.get(srcValue); - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer ? customizer(objValue, srcValue, key + "", object, source, stack) : undefined$1; - var isCommon = newValue === undefined$1; - if (isCommon) { - var isArr = isArray2(srcValue), isBuff = !isArr && isBuffer(srcValue), isTyped = !isArr && !isBuff && isTypedArray(srcValue); - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray2(objValue)) { - newValue = objValue; - } else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } else { - newValue = []; - } - } else if (isPlainObject(srcValue) || isArguments2(srcValue)) { - newValue = objValue; - if (isArguments2(objValue)) { - newValue = toPlainObject(objValue); - } else if (!isObject2(objValue) || isFunction2(objValue)) { - newValue = initCloneObject(srcValue); - } - } else { - isCommon = false; - } - } - if (isCommon) { - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack["delete"](srcValue); - } - assignMergeValue(object, key, newValue); - } - function baseNth(array, n2) { - var length = array.length; - if (!length) { - return; - } - n2 += n2 < 0 ? length : 0; - return isIndex(n2, length) ? array[n2] : undefined$1; - } - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee2) { - if (isArray2(iteratee2)) { - return function(value2) { - return baseGet(value2, iteratee2.length === 1 ? iteratee2[0] : iteratee2); - }; - } - return iteratee2; - }); - } else { - iteratees = [identity]; - } - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - var result2 = baseMap(collection, function(value2, key, collection2) { - var criteria = arrayMap(iteratees, function(iteratee2) { - return iteratee2(value2); - }); - return { "criteria": criteria, "index": ++index, "value": value2 }; - }); - return baseSortBy(result2, function(object, other) { - return compareMultiple(object, other, orders); - }); - } - function basePick(object, paths) { - return basePickBy(object, paths, function(value2, path) { - return hasIn(object, path); - }); - } - function basePickBy(object, paths, predicate) { - var index = -1, length = paths.length, result2 = {}; - while (++index < length) { - var path = paths[index], value2 = baseGet(object, path); - if (predicate(value2, path)) { - baseSet(result2, castPath(path, object), value2); - } - } - return result2; - } - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } - function basePullAll(array, values2, iteratee2, comparator) { - var indexOf2 = comparator ? baseIndexOfWith : baseIndexOf, index = -1, length = values2.length, seen = array; - if (array === values2) { - values2 = copyArray(values2); - } - if (iteratee2) { - seen = arrayMap(array, baseUnary(iteratee2)); - } - while (++index < length) { - var fromIndex = 0, value2 = values2[index], computed = iteratee2 ? iteratee2(value2) : value2; - while ((fromIndex = indexOf2(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, lastIndex = length - 1; - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } - function baseRange(start, end, step, fromRight) { - var index = -1, length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), result2 = Array2(length); - while (length--) { - result2[fromRight ? length : ++index] = start; - start += step; - } - return result2; - } - function baseRepeat(string, n2) { - var result2 = ""; - if (!string || n2 < 1 || n2 > MAX_SAFE_INTEGER) { - return result2; - } - do { - if (n2 % 2) { - result2 += string; - } - n2 = nativeFloor(n2 / 2); - if (n2) { - string += string; - } - } while (n2); - return result2; - } - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ""); - } - function baseSample(collection) { - return arraySample(values(collection)); - } - function baseSampleSize(collection, n2) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n2, 0, array.length)); - } - function baseSet(object, path, value2, customizer) { - if (!isObject2(object)) { - return object; - } - path = castPath(path, object); - var index = -1, length = path.length, lastIndex = length - 1, nested = object; - while (nested != null && ++index < length) { - var key = toKey(path[index]), newValue = value2; - if (key === "__proto__" || key === "constructor" || key === "prototype") { - return object; - } - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined$1; - if (newValue === undefined$1) { - newValue = isObject2(objValue) ? objValue : isIndex(path[index + 1]) ? [] : {}; - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - var baseSetToString = !defineProperty2 ? identity : function(func, string) { - return defineProperty2(func, "toString", { - "configurable": true, - "enumerable": false, - "value": constant(string), - "writable": true - }); - }; - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } - function baseSlice(array, start, end) { - var index = -1, length = array.length; - if (start < 0) { - start = -start > length ? 0 : length + start; - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : end - start >>> 0; - start >>>= 0; - var result2 = Array2(length); - while (++index < length) { - result2[index] = array[index + start]; - } - return result2; - } - function baseSome(collection, predicate) { - var result2; - baseEach(collection, function(value2, index, collection2) { - result2 = predicate(value2, index, collection2); - return !result2; - }); - return !!result2; - } - function baseSortedIndex(array, value2, retHighest) { - var low = 0, high = array == null ? low : array.length; - if (typeof value2 == "number" && value2 === value2 && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = low + high >>> 1, computed = array[mid]; - if (computed !== null && !isSymbol2(computed) && (retHighest ? computed <= value2 : computed < value2)) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value2, identity, retHighest); - } - function baseSortedIndexBy(array, value2, iteratee2, retHighest) { - var low = 0, high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - value2 = iteratee2(value2); - var valIsNaN = value2 !== value2, valIsNull = value2 === null, valIsSymbol = isSymbol2(value2), valIsUndefined = value2 === undefined$1; - while (low < high) { - var mid = nativeFloor((low + high) / 2), computed = iteratee2(array[mid]), othIsDefined = computed !== undefined$1, othIsNull = computed === null, othIsReflexive = computed === computed, othIsSymbol = isSymbol2(computed); - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? computed <= value2 : computed < value2; - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } - function baseSortedUniq(array, iteratee2) { - var index = -1, length = array.length, resIndex = 0, result2 = []; - while (++index < length) { - var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; - if (!index || !eq(computed, seen)) { - var seen = computed; - result2[resIndex++] = value2 === 0 ? 0 : value2; - } - } - return result2; - } - function baseToNumber(value2) { - if (typeof value2 == "number") { - return value2; - } - if (isSymbol2(value2)) { - return NAN; - } - return +value2; - } - function baseToString(value2) { - if (typeof value2 == "string") { - return value2; - } - if (isArray2(value2)) { - return arrayMap(value2, baseToString) + ""; - } - if (isSymbol2(value2)) { - return symbolToString ? symbolToString.call(value2) : ""; - } - var result2 = value2 + ""; - return result2 == "0" && 1 / value2 == -Infinity ? "-0" : result2; - } - function baseUniq(array, iteratee2, comparator) { - var index = -1, includes2 = arrayIncludes, length = array.length, isCommon = true, result2 = [], seen = result2; - if (comparator) { - isCommon = false; - includes2 = arrayIncludesWith; - } else if (length >= LARGE_ARRAY_SIZE) { - var set2 = iteratee2 ? null : createSet(array); - if (set2) { - return setToArray(set2); - } - isCommon = false; - includes2 = cacheHas; - seen = new SetCache(); - } else { - seen = iteratee2 ? [] : result2; - } - outer: - while (++index < length) { - var value2 = array[index], computed = iteratee2 ? iteratee2(value2) : value2; - value2 = comparator || value2 !== 0 ? value2 : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee2) { - seen.push(computed); - } - result2.push(value2); - } else if (!includes2(seen, computed, comparator)) { - if (seen !== result2) { - seen.push(computed); - } - result2.push(value2); - } - } - return result2; - } - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; - } - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, index = fromRight ? length : -1; - while ((fromRight ? index-- : ++index < length) && predicate(array[index], index, array)) { - } - return isDrop ? baseSlice(array, fromRight ? 0 : index, fromRight ? index + 1 : length) : baseSlice(array, fromRight ? index + 1 : 0, fromRight ? length : index); - } - function baseWrapperValue(value2, actions) { - var result2 = value2; - if (result2 instanceof LazyWrapper) { - result2 = result2.value(); - } - return arrayReduce(actions, function(result3, action) { - return action.func.apply(action.thisArg, arrayPush([result3], action.args)); - }, result2); - } - function baseXor(arrays, iteratee2, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, result2 = Array2(length); - while (++index < length) { - var array = arrays[index], othIndex = -1; - while (++othIndex < length) { - if (othIndex != index) { - result2[index] = baseDifference(result2[index] || array, arrays[othIndex], iteratee2, comparator); - } - } - } - return baseUniq(baseFlatten(result2, 1), iteratee2, comparator); - } - function baseZipObject(props, values2, assignFunc) { - var index = -1, length = props.length, valsLength = values2.length, result2 = {}; - while (++index < length) { - var value2 = index < valsLength ? values2[index] : undefined$1; - assignFunc(result2, props[index], value2); - } - return result2; - } - function castArrayLikeObject(value2) { - return isArrayLikeObject(value2) ? value2 : []; - } - function castFunction(value2) { - return typeof value2 == "function" ? value2 : identity; - } - function castPath(value2, object) { - if (isArray2(value2)) { - return value2; - } - return isKey(value2, object) ? [value2] : stringToPath(toString(value2)); - } - var castRest = baseRest; - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined$1 ? length : end; - return !start && end >= length ? array : baseSlice(array, start, end); - } - var clearTimeout2 = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, result2 = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - buffer.copy(result2); - return result2; - } - function cloneArrayBuffer(arrayBuffer) { - var result2 = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result2).set(new Uint8Array(arrayBuffer)); - return result2; - } - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } - function cloneRegExp(regexp) { - var result2 = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result2.lastIndex = regexp.lastIndex; - return result2; - } - function cloneSymbol(symbol) { - return symbolValueOf ? Object2(symbolValueOf.call(symbol)) : {}; - } - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } - function compareAscending(value2, other) { - if (value2 !== other) { - var valIsDefined = value2 !== undefined$1, valIsNull = value2 === null, valIsReflexive = value2 === value2, valIsSymbol = isSymbol2(value2); - var othIsDefined = other !== undefined$1, othIsNull = other === null, othIsReflexive = other === other, othIsSymbol = isSymbol2(other); - if (!othIsNull && !othIsSymbol && !valIsSymbol && value2 > other || valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol || valIsNull && othIsDefined && othIsReflexive || !valIsDefined && othIsReflexive || !valIsReflexive) { - return 1; - } - if (!valIsNull && !valIsSymbol && !othIsSymbol && value2 < other || othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol || othIsNull && valIsDefined && valIsReflexive || !othIsDefined && valIsReflexive || !othIsReflexive) { - return -1; - } - } - return 0; - } - function compareMultiple(object, other, orders) { - var index = -1, objCriteria = object.criteria, othCriteria = other.criteria, length = objCriteria.length, ordersLength = orders.length; - while (++index < length) { - var result2 = compareAscending(objCriteria[index], othCriteria[index]); - if (result2) { - if (index >= ordersLength) { - return result2; - } - var order = orders[index]; - return result2 * (order == "desc" ? -1 : 1); - } - } - return object.index - other.index; - } - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersLength = holders.length, leftIndex = -1, leftLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(leftLength + rangeLength), isUncurried = !isCurried; - while (++leftIndex < leftLength) { - result2[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result2[leftIndex++] = args[argsIndex++]; - } - return result2; - } - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, argsLength = args.length, holdersIndex = -1, holdersLength = holders.length, rightIndex = -1, rightLength = partials.length, rangeLength = nativeMax(argsLength - holdersLength, 0), result2 = Array2(rangeLength + rightLength), isUncurried = !isCurried; - while (++argsIndex < rangeLength) { - result2[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result2[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result2[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result2; - } - function copyArray(source, array) { - var index = -1, length = source.length; - array || (array = Array2(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); - var index = -1, length = props.length; - while (++index < length) { - var key = props[index]; - var newValue = customizer ? customizer(object[key], source[key], key, object, source) : undefined$1; - if (newValue === undefined$1) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } - function createAggregator(setter, initializer) { - return function(collection, iteratee2) { - var func = isArray2(collection) ? arrayAggregator : baseAggregator, accumulator = initializer ? initializer() : {}; - return func(collection, setter, getIteratee(iteratee2, 2), accumulator); - }; - } - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, length = sources.length, customizer = length > 1 ? sources[length - 1] : undefined$1, guard = length > 2 ? sources[2] : undefined$1; - customizer = assigner.length > 3 && typeof customizer == "function" ? (length--, customizer) : undefined$1; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined$1 : customizer; - length = 1; - } - object = Object2(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee2) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee2); - } - var length = collection.length, index = fromRight ? length : -1, iterable = Object2(collection); - while (fromRight ? index-- : ++index < length) { - if (iteratee2(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } - function createBaseFor(fromRight) { - return function(object, iteratee2, keysFunc) { - var index = -1, iterable = Object2(object), props = keysFunc(object), length = props.length; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee2(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var fn = this && this !== root && this instanceof wrapper ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); - var strSymbols = hasUnicode(string) ? stringToArray(string) : undefined$1; - var chr = strSymbols ? strSymbols[0] : string.charAt(0); - var trailing = strSymbols ? castSlice(strSymbols, 1).join("") : string.slice(1); - return chr[methodName]() + trailing; - }; - } - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, "")), callback, ""); - }; - } - function createCtor(Ctor) { - return function() { - var args = arguments; - switch (args.length) { - case 0: - return new Ctor(); - case 1: - return new Ctor(args[0]); - case 2: - return new Ctor(args[0], args[1]); - case 3: - return new Ctor(args[0], args[1], args[2]); - case 4: - return new Ctor(args[0], args[1], args[2], args[3]); - case 5: - return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: - return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), result2 = Ctor.apply(thisBinding, args); - return isObject2(result2) ? result2 : thisBinding; - }; - } - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index = length, placeholder = getHolder(wrapper); - while (index--) { - args[index] = arguments[index]; - } - var holders = length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder ? [] : replaceHolders(args, placeholder); - length -= holders.length; - if (length < arity) { - return createRecurry( - func, - bitmask, - createHybrid, - wrapper.placeholder, - undefined$1, - args, - holders, - undefined$1, - undefined$1, - arity - length - ); - } - var fn = this && this !== root && this instanceof wrapper ? Ctor : func; - return apply2(fn, this, args); - } - return wrapper; - } - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object2(collection); - if (!isArrayLike(collection)) { - var iteratee2 = getIteratee(predicate, 3); - collection = keys2(collection); - predicate = function(key) { - return iteratee2(iterable[key], key, iterable); - }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee2 ? collection[index] : index] : undefined$1; - }; - } - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, index = length, prereq = LodashWrapper.prototype.thru; - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == "wrapper") { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; - var funcName = getFuncName(func), data = funcName == "wrapper" ? getData(func) : undefined$1; - if (data && isLaziable(data[0]) && data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && !data[4].length && data[9] == 1) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = func.length == 1 && isLaziable(func) ? wrapper[funcName]() : wrapper.thru(func); - } - } - return function() { - var args = arguments, value2 = args[0]; - if (wrapper && args.length == 1 && isArray2(value2)) { - return wrapper.plant(value2).value(); - } - var index2 = 0, result2 = length ? funcs[index2].apply(this, args) : value2; - while (++index2 < length) { - result2 = funcs[index2].call(this, result2); - } - return result2; - }; - }); - } - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary2, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, isBind = bitmask & WRAP_BIND_FLAG, isBindKey = bitmask & WRAP_BIND_KEY_FLAG, isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), isFlip = bitmask & WRAP_FLIP_FLAG, Ctor = isBindKey ? undefined$1 : createCtor(func); - function wrapper() { - var length = arguments.length, args = Array2(length), index = length; - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, - bitmask, - createHybrid, - wrapper.placeholder, - thisArg, - args, - newHolders, - argPos, - ary2, - arity - length - ); - } - var thisBinding = isBind ? thisArg : this, fn = isBindKey ? thisBinding[func] : func; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary2 < length) { - args.length = ary2; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); - } - return wrapper; - } - function createInverter(setter, toIteratee) { - return function(object, iteratee2) { - return baseInverter(object, setter, toIteratee(iteratee2), {}); - }; - } - function createMathOperation(operator, defaultValue) { - return function(value2, other) { - var result2; - if (value2 === undefined$1 && other === undefined$1) { - return defaultValue; - } - if (value2 !== undefined$1) { - result2 = value2; - } - if (other !== undefined$1) { - if (result2 === undefined$1) { - return other; - } - if (typeof value2 == "string" || typeof other == "string") { - value2 = baseToString(value2); - other = baseToString(other); - } else { - value2 = baseToNumber(value2); - other = baseToNumber(other); - } - result2 = operator(value2, other); - } - return result2; - }; - } - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee2) { - return apply2(iteratee2, thisArg, args); - }); - }); - }); - } - function createPadding(length, chars) { - chars = chars === undefined$1 ? " " : baseToString(chars); - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; - } - var result2 = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) ? castSlice(stringToArray(result2), 0, length).join("") : result2.slice(0, length); - } - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, Ctor = createCtor(func); - function wrapper() { - var argsIndex = -1, argsLength = arguments.length, leftIndex = -1, leftLength = partials.length, args = Array2(leftLength + argsLength), fn = this && this !== root && this instanceof wrapper ? Ctor : func; - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply2(fn, isBind ? thisArg : this, args); - } - return wrapper; - } - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != "number" && isIterateeCall(start, end, step)) { - end = step = undefined$1; - } - start = toFinite(start); - if (end === undefined$1) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined$1 ? start < end ? 1 : -1 : toFinite(step); - return baseRange(start, end, step, fromRight); - }; - } - function createRelationalOperation(operator) { - return function(value2, other) { - if (!(typeof value2 == "string" && typeof other == "string")) { - value2 = toNumber(value2); - other = toNumber(other); - } - return operator(value2, other); - }; - } - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary2, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, newHolders = isCurry ? holders : undefined$1, newHoldersRight = isCurry ? undefined$1 : holders, newPartials = isCurry ? partials : undefined$1, newPartialsRight = isCurry ? undefined$1 : partials; - bitmask |= isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG; - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= -4; - } - var newData = [ - func, - bitmask, - thisArg, - newPartials, - newHolders, - newPartialsRight, - newHoldersRight, - argPos, - ary2, - arity - ]; - var result2 = wrapFunc.apply(undefined$1, newData); - if (isLaziable(func)) { - setData(result2, newData); - } - result2.placeholder = placeholder; - return setWrapToString(result2, func, bitmask); - } - function createRound(methodName) { - var func = Math2[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger2(precision), 292); - if (precision && nativeIsFinite(number)) { - var pair = (toString(number) + "e").split("e"), value2 = func(pair[0] + "e" + (+pair[1] + precision)); - pair = (toString(value2) + "e").split("e"); - return +(pair[0] + "e" + (+pair[1] - precision)); - } - return func(number); - }; - } - var createSet = !(Set2 && 1 / setToArray(new Set2([, -0]))[1] == INFINITY) ? noop2 : function(values2) { - return new Set2(values2); - }; - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; - } - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary2, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= -97; - partials = holders = undefined$1; - } - ary2 = ary2 === undefined$1 ? ary2 : nativeMax(toInteger2(ary2), 0); - arity = arity === undefined$1 ? arity : toInteger2(arity); - length -= holders ? holders.length : 0; - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, holdersRight = holders; - partials = holders = undefined$1; - } - var data = isBindKey ? undefined$1 : getData(func); - var newData = [ - func, - bitmask, - thisArg, - partials, - holders, - partialsRight, - holdersRight, - argPos, - ary2, - arity - ]; - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined$1 ? isBindKey ? 0 : func.length : nativeMax(newData[9] - length, 0); - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= -25; - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result2 = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result2 = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result2 = createPartial(func, bitmask, thisArg, partials); - } else { - result2 = createHybrid.apply(undefined$1, newData); - } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result2, newData), func, bitmask); - } - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined$1 || eq(objValue, objectProto[key]) && !hasOwnProperty2.call(object, key)) { - return srcValue; - } - return objValue; - } - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject2(objValue) && isObject2(srcValue)) { - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined$1, customDefaultsMerge, stack); - stack["delete"](srcValue); - } - return objValue; - } - function customOmitClone(value2) { - return isPlainObject(value2) ? undefined$1 : value2; - } - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, arrLength = array.length, othLength = other.length; - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, result2 = true, seen = bitmask & COMPARE_UNORDERED_FLAG ? new SetCache() : undefined$1; - stack.set(array, other); - stack.set(other, array); - while (++index < arrLength) { - var arrValue = array[index], othValue = other[index]; - if (customizer) { - var compared = isPartial ? customizer(othValue, arrValue, index, other, array, stack) : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined$1) { - if (compared) { - continue; - } - result2 = false; - break; - } - if (seen) { - if (!arraySome(other, function(othValue2, othIndex) { - if (!cacheHas(seen, othIndex) && (arrValue === othValue2 || equalFunc(arrValue, othValue2, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result2 = false; - break; - } - } else if (!(arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - result2 = false; - break; - } - } - stack["delete"](array); - stack["delete"](other); - return result2; - } - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if (object.byteLength != other.byteLength || object.byteOffset != other.byteOffset) { - return false; - } - object = object.buffer; - other = other.buffer; - case arrayBufferTag: - if (object.byteLength != other.byteLength || !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; - case boolTag: - case dateTag: - case numberTag: - return eq(+object, +other); - case errorTag: - return object.name == other.name && object.message == other.message; - case regexpTag: - case stringTag: - return object == other + ""; - case mapTag: - var convert = mapToArray; - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); - if (object.size != other.size && !isPartial) { - return false; - } - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; - stack.set(object, other); - var result2 = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack["delete"](object); - return result2; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } - } - return false; - } - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, objProps = getAllKeys(object), objLength = objProps.length, othProps = getAllKeys(other), othLength = othProps.length; - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty2.call(other, key))) { - return false; - } - } - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result2 = true; - stack.set(object, other); - stack.set(other, object); - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], othValue = other[key]; - if (customizer) { - var compared = isPartial ? customizer(othValue, objValue, key, other, object, stack) : customizer(objValue, othValue, key, object, other, stack); - } - if (!(compared === undefined$1 ? objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack) : compared)) { - result2 = false; - break; - } - skipCtor || (skipCtor = key == "constructor"); - } - if (result2 && !skipCtor) { - var objCtor = object.constructor, othCtor = other.constructor; - if (objCtor != othCtor && ("constructor" in object && "constructor" in other) && !(typeof objCtor == "function" && objCtor instanceof objCtor && typeof othCtor == "function" && othCtor instanceof othCtor)) { - result2 = false; - } - } - stack["delete"](object); - stack["delete"](other); - return result2; - } - function flatRest(func) { - return setToString(overRest(func, undefined$1, flatten), func + ""); - } - function getAllKeys(object) { - return baseGetAllKeys(object, keys2, getSymbols); - } - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); - } - var getData = !metaMap ? noop2 : function(func) { - return metaMap.get(func); - }; - function getFuncName(func) { - var result2 = func.name + "", array = realNames[result2], length = hasOwnProperty2.call(realNames, result2) ? array.length : 0; - while (length--) { - var data = array[length], otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } - } - return result2; - } - function getHolder(func) { - var object = hasOwnProperty2.call(lodash2, "placeholder") ? lodash2 : func; - return object.placeholder; - } - function getIteratee() { - var result2 = lodash2.iteratee || iteratee; - result2 = result2 === iteratee ? baseIteratee : result2; - return arguments.length ? result2(arguments[0], arguments[1]) : result2; - } - function getMapData(map3, key) { - var data = map3.__data__; - return isKeyable(key) ? data[typeof key == "string" ? "string" : "hash"] : data.map; - } - function getMatchData(object) { - var result2 = keys2(object), length = result2.length; - while (length--) { - var key = result2[length], value2 = object[key]; - result2[length] = [key, value2, isStrictComparable(value2)]; - } - return result2; - } - function getNative(object, key) { - var value2 = getValue(object, key); - return baseIsNative(value2) ? value2 : undefined$1; - } - function getRawTag(value2) { - var isOwn = hasOwnProperty2.call(value2, symToStringTag), tag = value2[symToStringTag]; - try { - value2[symToStringTag] = undefined$1; - var unmasked = true; - } catch (e) { - } - var result2 = nativeObjectToString.call(value2); - if (unmasked) { - if (isOwn) { - value2[symToStringTag] = tag; - } else { - delete value2[symToStringTag]; - } - } - return result2; - } - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object2(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result2 = []; - while (object) { - arrayPush(result2, getSymbols(object)); - object = getPrototype(object); - } - return result2; - }; - var getTag = baseGetTag; - if (DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag || Map2 && getTag(new Map2()) != mapTag || Promise2 && getTag(Promise2.resolve()) != promiseTag || Set2 && getTag(new Set2()) != setTag || WeakMap && getTag(new WeakMap()) != weakMapTag) { - getTag = function(value2) { - var result2 = baseGetTag(value2), Ctor = result2 == objectTag ? value2.constructor : undefined$1, ctorString = Ctor ? toSource(Ctor) : ""; - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: - return dataViewTag; - case mapCtorString: - return mapTag; - case promiseCtorString: - return promiseTag; - case setCtorString: - return setTag; - case weakMapCtorString: - return weakMapTag; - } - } - return result2; - }; - } - function getView(start, end, transforms) { - var index = -1, length = transforms.length; - while (++index < length) { - var data = transforms[index], size2 = data.size; - switch (data.type) { - case "drop": - start += size2; - break; - case "dropRight": - end -= size2; - break; - case "take": - end = nativeMin(end, start + size2); - break; - case "takeRight": - start = nativeMax(start, end - size2); - break; - } - } - return { "start": start, "end": end }; - } - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } - function hasPath(object, path, hasFunc) { - path = castPath(path, object); - var index = -1, length = path.length, result2 = false; - while (++index < length) { - var key = toKey(path[index]); - if (!(result2 = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result2 || ++index != length) { - return result2; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && (isArray2(object) || isArguments2(object)); - } - function initCloneArray(array) { - var length = array.length, result2 = new array.constructor(length); - if (length && typeof array[0] == "string" && hasOwnProperty2.call(array, "index")) { - result2.index = array.index; - result2.input = array.input; - } - return result2; - } - function initCloneObject(object) { - return typeof object.constructor == "function" && !isPrototype2(object) ? baseCreate(getPrototype(object)) : {}; - } - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); - case boolTag: - case dateTag: - return new Ctor(+object); - case dataViewTag: - return cloneDataView(object, isDeep); - case float32Tag: - case float64Tag: - case int8Tag: - case int16Tag: - case int32Tag: - case uint8Tag: - case uint8ClampedTag: - case uint16Tag: - case uint32Tag: - return cloneTypedArray(object, isDeep); - case mapTag: - return new Ctor(); - case numberTag: - case stringTag: - return new Ctor(object); - case regexpTag: - return cloneRegExp(object); - case setTag: - return new Ctor(); - case symbolTag: - return cloneSymbol(object); - } - } - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? "& " : "") + details[lastIndex]; - details = details.join(length > 2 ? ", " : " "); - return source.replace(reWrapComment, "{\n/* [wrapped with " + details + "] */\n"); - } - function isFlattenable(value2) { - return isArray2(value2) || isArguments2(value2) || !!(spreadableSymbol && value2 && value2[spreadableSymbol]); - } - function isIndex(value2, length) { - var type = typeof value2; - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && (type == "number" || type != "symbol" && reIsUint.test(value2)) && (value2 > -1 && value2 % 1 == 0 && value2 < length); - } - function isIterateeCall(value2, index, object) { - if (!isObject2(object)) { - return false; - } - var type = typeof index; - if (type == "number" ? isArrayLike(object) && isIndex(index, object.length) : type == "string" && index in object) { - return eq(object[index], value2); - } - return false; - } - function isKey(value2, object) { - if (isArray2(value2)) { - return false; - } - var type = typeof value2; - if (type == "number" || type == "symbol" || type == "boolean" || value2 == null || isSymbol2(value2)) { - return true; - } - return reIsPlainProp.test(value2) || !reIsDeepProp.test(value2) || object != null && value2 in Object2(object); - } - function isKeyable(value2) { - var type = typeof value2; - return type == "string" || type == "number" || type == "symbol" || type == "boolean" ? value2 !== "__proto__" : value2 === null; - } - function isLaziable(func) { - var funcName = getFuncName(func), other = lodash2[funcName]; - if (typeof other != "function" || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; - } - var data = getData(other); - return !!data && func === data[0]; - } - function isMasked(func) { - return !!maskSrcKey && maskSrcKey in func; - } - var isMaskable = coreJsData ? isFunction2 : stubFalse; - function isPrototype2(value2) { - var Ctor = value2 && value2.constructor, proto = typeof Ctor == "function" && Ctor.prototype || objectProto; - return value2 === proto; - } - function isStrictComparable(value2) { - return value2 === value2 && !isObject2(value2); - } - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && (srcValue !== undefined$1 || key in Object2(object)); - }; - } - function memoizeCapped(func) { - var result2 = memoize2(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); - var cache = result2.cache; - return result2; - } - function mergeData(data, source) { - var bitmask = data[1], srcBitmask = source[1], newBitmask = bitmask | srcBitmask, isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - var isCombo = srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_CURRY_FLAG || srcBitmask == WRAP_ARY_FLAG && bitmask == WRAP_REARG_FLAG && data[7].length <= source[8] || srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG) && source[7].length <= source[8] && bitmask == WRAP_CURRY_FLAG; - if (!(isCommon || isCombo)) { - return data; - } - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - var value2 = source[3]; - if (value2) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value2, source[4]) : value2; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - value2 = source[5]; - if (value2) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value2, source[6]) : value2; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - value2 = source[7]; - if (value2) { - data[7] = value2; - } - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - if (data[9] == null) { - data[9] = source[9]; - } - data[0] = source[0]; - data[1] = newBitmask; - return data; - } - function nativeKeysIn(object) { - var result2 = []; - if (object != null) { - for (var key in Object2(object)) { - result2.push(key); - } - } - return result2; - } - function objectToString(value2) { - return nativeObjectToString.call(value2); - } - function overRest(func, start, transform2) { - start = nativeMax(start === undefined$1 ? func.length - 1 : start, 0); - return function() { - var args = arguments, index = -1, length = nativeMax(args.length - start, 0), array = Array2(length); - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array2(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform2(array); - return apply2(func, this, otherArgs); - }; - } - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); - } - function reorder(array, indexes) { - var arrLength = array.length, length = nativeMin(indexes.length, arrLength), oldArray = copyArray(array); - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined$1; - } - return array; - } - function safeGet(object, key) { - if (key === "constructor" && typeof object[key] === "function") { - return; - } - if (key == "__proto__") { - return; - } - return object[key]; - } - var setData = shortOut(baseSetData); - var setTimeout2 = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; - var setToString = shortOut(baseSetToString); - function setWrapToString(wrapper, reference, bitmask) { - var source = reference + ""; - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); - } - function shortOut(func) { - var count = 0, lastCalled = 0; - return function() { - var stamp = nativeNow(), remaining = HOT_SPAN - (stamp - lastCalled); - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined$1, arguments); - }; - } - function shuffleSelf(array, size2) { - var index = -1, length = array.length, lastIndex = length - 1; - size2 = size2 === undefined$1 ? length : size2; - while (++index < size2) { - var rand = baseRandom(index, lastIndex), value2 = array[rand]; - array[rand] = array[index]; - array[index] = value2; - } - array.length = size2; - return array; - } - var stringToPath = memoizeCapped(function(string) { - var result2 = []; - if (string.charCodeAt(0) === 46) { - result2.push(""); - } - string.replace(rePropName, function(match, number, quote, subString) { - result2.push(quote ? subString.replace(reEscapeChar, "$1") : number || match); - }); - return result2; - }); - function toKey(value2) { - if (typeof value2 == "string" || isSymbol2(value2)) { - return value2; - } - var result2 = value2 + ""; - return result2 == "0" && 1 / value2 == -Infinity ? "-0" : result2; - } - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) { - } - try { - return func + ""; - } catch (e) { - } - } - return ""; - } - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value2 = "_." + pair[0]; - if (bitmask & pair[1] && !arrayIncludes(details, value2)) { - details.push(value2); - } - }); - return details.sort(); - } - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result2 = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result2.__actions__ = copyArray(wrapper.__actions__); - result2.__index__ = wrapper.__index__; - result2.__values__ = wrapper.__values__; - return result2; - } - function chunk(array, size2, guard) { - if (guard ? isIterateeCall(array, size2, guard) : size2 === undefined$1) { - size2 = 1; - } else { - size2 = nativeMax(toInteger2(size2), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size2 < 1) { - return []; - } - var index = 0, resIndex = 0, result2 = Array2(nativeCeil(length / size2)); - while (index < length) { - result2[resIndex++] = baseSlice(array, index, index += size2); - } - return result2; - } - function compact(array) { - var index = -1, length = array == null ? 0 : array.length, resIndex = 0, result2 = []; - while (++index < length) { - var value2 = array[index]; - if (value2) { - result2[resIndex++] = value2; - } - } - return result2; - } - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array2(length - 1), array = arguments[0], index = length; - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray2(array) ? copyArray(array) : [array], baseFlatten(args, 1)); - } - var difference = baseRest(function(array, values2) { - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true)) : []; - }); - var differenceBy = baseRest(function(array, values2) { - var iteratee2 = last(values2); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined$1; - } - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)) : []; - }); - var differenceWith = baseRest(function(array, values2) { - var comparator = last(values2); - if (isArrayLikeObject(comparator)) { - comparator = undefined$1; - } - return isArrayLikeObject(array) ? baseDifference(array, baseFlatten(values2, 1, isArrayLikeObject, true), undefined$1, comparator) : []; - }); - function drop(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); - return baseSlice(array, n2 < 0 ? 0 : n2, length); - } - function dropRight(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); - n2 = length - n2; - return baseSlice(array, 0, n2 < 0 ? 0 : n2); - } - function dropRightWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true, true) : []; - } - function dropWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), true) : []; - } - function fill(array, value2, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != "number" && isIterateeCall(array, value2, start)) { - start = 0; - end = length; - } - return baseFill(array, value2, start, end); - } - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger2(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseFindIndex(array, getIteratee(predicate, 3), index); - } - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined$1) { - index = toInteger2(fromIndex); - index = fromIndex < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); - } - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; - } - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; - } - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - depth = depth === undefined$1 ? 1 : toInteger2(depth); - return baseFlatten(array, depth); - } - function fromPairs(pairs) { - var index = -1, length = pairs == null ? 0 : pairs.length, result2 = {}; - while (++index < length) { - var pair = pairs[index]; - result2[pair[0]] = pair[1]; - } - return result2; - } - function head(array) { - return array && array.length ? array[0] : undefined$1; - } - function indexOf(array, value2, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger2(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); - } - return baseIndexOf(array, value2, index); - } - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; - } - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped) : []; - }); - var intersectionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - if (iteratee2 === last(mapped)) { - iteratee2 = undefined$1; - } else { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, getIteratee(iteratee2, 2)) : []; - }); - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), mapped = arrayMap(arrays, castArrayLikeObject); - comparator = typeof comparator == "function" ? comparator : undefined$1; - if (comparator) { - mapped.pop(); - } - return mapped.length && mapped[0] === arrays[0] ? baseIntersection(mapped, undefined$1, comparator) : []; - }); - function join(array, separator) { - return array == null ? "" : nativeJoin.call(array, separator); - } - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined$1; - } - function lastIndexOf(array, value2, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length; - if (fromIndex !== undefined$1) { - index = toInteger2(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); - } - return value2 === value2 ? strictLastIndexOf(array, value2, index) : baseFindIndex(array, baseIsNaN, index, true); - } - function nth(array, n2) { - return array && array.length ? baseNth(array, toInteger2(n2)) : undefined$1; - } - var pull = baseRest(pullAll); - function pullAll(array, values2) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2) : array; - } - function pullAllBy(array, values2, iteratee2) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2, getIteratee(iteratee2, 2)) : array; - } - function pullAllWith(array, values2, comparator) { - return array && array.length && values2 && values2.length ? basePullAll(array, values2, undefined$1, comparator) : array; - } - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, result2 = baseAt(array, indexes); - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - return result2; - }); - function remove(array, predicate) { - var result2 = []; - if (!(array && array.length)) { - return result2; - } - var index = -1, indexes = [], length = array.length; - predicate = getIteratee(predicate, 3); - while (++index < length) { - var value2 = array[index]; - if (predicate(value2, index, array)) { - result2.push(value2); - indexes.push(index); - } - } - basePullAt(array, indexes); - return result2; - } - function reverse(array) { - return array == null ? array : nativeReverse.call(array); - } - function slice2(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != "number" && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } else { - start = start == null ? 0 : toInteger2(start); - end = end === undefined$1 ? length : toInteger2(end); - } - return baseSlice(array, start, end); - } - function sortedIndex(array, value2) { - return baseSortedIndex(array, value2); - } - function sortedIndexBy(array, value2, iteratee2) { - return baseSortedIndexBy(array, value2, getIteratee(iteratee2, 2)); - } - function sortedIndexOf(array, value2) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value2); - if (index < length && eq(array[index], value2)) { - return index; - } - } - return -1; - } - function sortedLastIndex(array, value2) { - return baseSortedIndex(array, value2, true); - } - function sortedLastIndexBy(array, value2, iteratee2) { - return baseSortedIndexBy(array, value2, getIteratee(iteratee2, 2), true); - } - function sortedLastIndexOf(array, value2) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value2, true) - 1; - if (eq(array[index], value2)) { - return index; - } - } - return -1; - } - function sortedUniq(array) { - return array && array.length ? baseSortedUniq(array) : []; - } - function sortedUniqBy(array, iteratee2) { - return array && array.length ? baseSortedUniq(array, getIteratee(iteratee2, 2)) : []; - } - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; - } - function take(array, n2, guard) { - if (!(array && array.length)) { - return []; - } - n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); - return baseSlice(array, 0, n2 < 0 ? 0 : n2); - } - function takeRight(array, n2, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n2 = guard || n2 === undefined$1 ? 1 : toInteger2(n2); - n2 = length - n2; - return baseSlice(array, n2 < 0 ? 0 : n2, length); - } - function takeRightWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3), false, true) : []; - } - function takeWhile(array, predicate) { - return array && array.length ? baseWhile(array, getIteratee(predicate, 3)) : []; - } - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); - var unionBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined$1; - } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee2, 2)); - }); - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined$1; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined$1, comparator); - }); - function uniq(array) { - return array && array.length ? baseUniq(array) : []; - } - function uniqBy(array, iteratee2) { - return array && array.length ? baseUniq(array, getIteratee(iteratee2, 2)) : []; - } - function uniqWith(array, comparator) { - comparator = typeof comparator == "function" ? comparator : undefined$1; - return array && array.length ? baseUniq(array, undefined$1, comparator) : []; - } - function unzip(array) { - if (!(array && array.length)) { - return []; - } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; - } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); - } - function unzipWith(array, iteratee2) { - if (!(array && array.length)) { - return []; - } - var result2 = unzip(array); - if (iteratee2 == null) { - return result2; - } - return arrayMap(result2, function(group) { - return apply2(iteratee2, undefined$1, group); - }); - } - var without = baseRest(function(array, values2) { - return isArrayLikeObject(array) ? baseDifference(array, values2) : []; - }); - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); - var xorBy = baseRest(function(arrays) { - var iteratee2 = last(arrays); - if (isArrayLikeObject(iteratee2)) { - iteratee2 = undefined$1; - } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee2, 2)); - }); - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == "function" ? comparator : undefined$1; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined$1, comparator); - }); - var zip = baseRest(unzip); - function zipObject(props, values2) { - return baseZipObject(props || [], values2 || [], assignValue); - } - function zipObjectDeep(props, values2) { - return baseZipObject(props || [], values2 || [], baseSet); - } - var zipWith = baseRest(function(arrays) { - var length = arrays.length, iteratee2 = length > 1 ? arrays[length - 1] : undefined$1; - iteratee2 = typeof iteratee2 == "function" ? (arrays.pop(), iteratee2) : undefined$1; - return unzipWith(arrays, iteratee2); - }); - function chain(value2) { - var result2 = lodash2(value2); - result2.__chain__ = true; - return result2; - } - function tap(value2, interceptor) { - interceptor(value2); - return value2; - } - function thru(value2, interceptor) { - return interceptor(value2); - } - var wrapperAt = flatRest(function(paths) { - var length = paths.length, start = length ? paths[0] : 0, value2 = this.__wrapped__, interceptor = function(object) { - return baseAt(object, paths); - }; - if (length > 1 || this.__actions__.length || !(value2 instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value2 = value2.slice(start, +start + (length ? 1 : 0)); - value2.__actions__.push({ - "func": thru, - "args": [interceptor], - "thisArg": undefined$1 - }); - return new LodashWrapper(value2, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined$1); - } - return array; - }); - }); - function wrapperChain() { - return chain(this); - } - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); - } - function wrapperNext() { - if (this.__values__ === undefined$1) { - this.__values__ = toArray2(this.value()); - } - var done = this.__index__ >= this.__values__.length, value2 = done ? undefined$1 : this.__values__[this.__index__++]; - return { "done": done, "value": value2 }; - } - function wrapperToIterator() { - return this; - } - function wrapperPlant(value2) { - var result2, parent2 = this; - while (parent2 instanceof baseLodash) { - var clone2 = wrapperClone(parent2); - clone2.__index__ = 0; - clone2.__values__ = undefined$1; - if (result2) { - previous.__wrapped__ = clone2; - } else { - result2 = clone2; - } - var previous = clone2; - parent2 = parent2.__wrapped__; - } - previous.__wrapped__ = value2; - return result2; - } - function wrapperReverse() { - var value2 = this.__wrapped__; - if (value2 instanceof LazyWrapper) { - var wrapped = value2; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - "func": thru, - "args": [reverse], - "thisArg": undefined$1 - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); - } - var countBy = createAggregator(function(result2, value2, key) { - if (hasOwnProperty2.call(result2, key)) { - ++result2[key]; - } else { - baseAssignValue(result2, key, 1); - } - }); - function every(collection, predicate, guard) { - var func = isArray2(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined$1; - } - return func(collection, getIteratee(predicate, 3)); - } - function filter(collection, predicate) { - var func = isArray2(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); - } - var find = createFind(findIndex); - var findLast = createFind(findLastIndex); - function flatMap(collection, iteratee2) { - return baseFlatten(map2(collection, iteratee2), 1); - } - function flatMapDeep(collection, iteratee2) { - return baseFlatten(map2(collection, iteratee2), INFINITY); - } - function flatMapDepth(collection, iteratee2, depth) { - depth = depth === undefined$1 ? 1 : toInteger2(depth); - return baseFlatten(map2(collection, iteratee2), depth); - } - function forEach2(collection, iteratee2) { - var func = isArray2(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee2, 3)); - } - function forEachRight(collection, iteratee2) { - var func = isArray2(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee2, 3)); - } - var groupBy = createAggregator(function(result2, value2, key) { - if (hasOwnProperty2.call(result2, key)) { - result2[key].push(value2); - } else { - baseAssignValue(result2, key, [value2]); - } - }); - function includes(collection, value2, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = fromIndex && !guard ? toInteger2(fromIndex) : 0; - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); - } - return isString2(collection) ? fromIndex <= length && collection.indexOf(value2, fromIndex) > -1 : !!length && baseIndexOf(collection, value2, fromIndex) > -1; - } - var invokeMap = baseRest(function(collection, path, args) { - var index = -1, isFunc = typeof path == "function", result2 = isArrayLike(collection) ? Array2(collection.length) : []; - baseEach(collection, function(value2) { - result2[++index] = isFunc ? apply2(path, value2, args) : baseInvoke(value2, path, args); - }); - return result2; - }); - var keyBy = createAggregator(function(result2, value2, key) { - baseAssignValue(result2, key, value2); - }); - function map2(collection, iteratee2) { - var func = isArray2(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee2, 3)); - } - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray2(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined$1 : orders; - if (!isArray2(orders)) { - orders = orders == null ? [] : [orders]; - } - return baseOrderBy(collection, iteratees, orders); - } - var partition = createAggregator(function(result2, value2, key) { - result2[key ? 0 : 1].push(value2); - }, function() { - return [[], []]; - }); - function reduce(collection, iteratee2, accumulator) { - var func = isArray2(collection) ? arrayReduce : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEach); - } - function reduceRight(collection, iteratee2, accumulator) { - var func = isArray2(collection) ? arrayReduceRight : baseReduce, initAccum = arguments.length < 3; - return func(collection, getIteratee(iteratee2, 4), accumulator, initAccum, baseEachRight); - } - function reject(collection, predicate) { - var func = isArray2(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); - } - function sample(collection) { - var func = isArray2(collection) ? arraySample : baseSample; - return func(collection); - } - function sampleSize(collection, n2, guard) { - if (guard ? isIterateeCall(collection, n2, guard) : n2 === undefined$1) { - n2 = 1; - } else { - n2 = toInteger2(n2); - } - var func = isArray2(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n2); - } - function shuffle(collection) { - var func = isArray2(collection) ? arrayShuffle : baseShuffle; - return func(collection); - } - function size(collection) { - if (collection == null) { - return 0; - } - if (isArrayLike(collection)) { - return isString2(collection) ? stringSize(collection) : collection.length; - } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; - } - return baseKeys(collection).length; - } - function some(collection, predicate, guard) { - var func = isArray2(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined$1; - } - return func(collection, getIteratee(predicate, 3)); - } - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); - var now = ctxNow || function() { - return root.Date.now(); - }; - function after(n2, func) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger2(n2); - return function() { - if (--n2 < 1) { - return func.apply(this, arguments); - } - }; - } - function ary(func, n2, guard) { - n2 = guard ? undefined$1 : n2; - n2 = func && n2 == null ? func.length : n2; - return createWrap(func, WRAP_ARY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, n2); - } - function before(n2, func) { - var result2; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - n2 = toInteger2(n2); - return function() { - if (--n2 > 0) { - result2 = func.apply(this, arguments); - } - if (n2 <= 1) { - func = undefined$1; - } - return result2; - }; - } - var bind2 = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind2)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(key, bitmask, object, partials, holders); - }); - function curry(func, arity, guard) { - arity = guard ? undefined$1 : arity; - var result2 = createWrap(func, WRAP_CURRY_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); - result2.placeholder = curry.placeholder; - return result2; - } - function curryRight(func, arity, guard) { - arity = guard ? undefined$1 : arity; - var result2 = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined$1, undefined$1, undefined$1, undefined$1, undefined$1, arity); - result2.placeholder = curryRight.placeholder; - return result2; - } - function debounce(func, wait, options) { - var lastArgs, lastThis, maxWait, result2, timerId, lastCallTime, lastInvokeTime = 0, leading = false, maxing = false, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject2(options)) { - leading = !!options.leading; - maxing = "maxWait" in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - function invokeFunc(time) { - var args = lastArgs, thisArg = lastThis; - lastArgs = lastThis = undefined$1; - lastInvokeTime = time; - result2 = func.apply(thisArg, args); - return result2; - } - function leadingEdge(time) { - lastInvokeTime = time; - timerId = setTimeout2(timerExpired, wait); - return leading ? invokeFunc(time) : result2; - } - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime, timeWaiting = wait - timeSinceLastCall; - return maxing ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) : timeWaiting; - } - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, timeSinceLastInvoke = time - lastInvokeTime; - return lastCallTime === undefined$1 || timeSinceLastCall >= wait || timeSinceLastCall < 0 || maxing && timeSinceLastInvoke >= maxWait; - } - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); - } - timerId = setTimeout2(timerExpired, remainingWait(time)); - } - function trailingEdge(time) { - timerId = undefined$1; - if (trailing && lastArgs) { - return invokeFunc(time); - } - lastArgs = lastThis = undefined$1; - return result2; - } - function cancel() { - if (timerId !== undefined$1) { - clearTimeout2(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined$1; - } - function flush() { - return timerId === undefined$1 ? result2 : trailingEdge(now()); - } - function debounced() { - var time = now(), isInvoking = shouldInvoke(time); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; - if (isInvoking) { - if (timerId === undefined$1) { - return leadingEdge(lastCallTime); - } - if (maxing) { - clearTimeout2(timerId); - timerId = setTimeout2(timerExpired, wait); - return invokeFunc(lastCallTime); - } - } - if (timerId === undefined$1) { - timerId = setTimeout2(timerExpired, wait); - } - return result2; - } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; - } - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); - } - function memoize2(func, resolver) { - if (typeof func != "function" || resolver != null && typeof resolver != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, key = resolver ? resolver.apply(this, args) : args[0], cache = memoized.cache; - if (cache.has(key)) { - return cache.get(key); - } - var result2 = func.apply(this, args); - memoized.cache = cache.set(key, result2) || cache; - return result2; - }; - memoized.cache = new (memoize2.Cache || MapCache)(); - return memoized; - } - memoize2.Cache = MapCache; - function negate(predicate) { - if (typeof predicate != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: - return !predicate.call(this); - case 1: - return !predicate.call(this, args[0]); - case 2: - return !predicate.call(this, args[0], args[1]); - case 3: - return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; - } - function once(func) { - return before(2, func); - } - var overArgs = castRest(function(func, transforms) { - transforms = transforms.length == 1 && isArray2(transforms[0]) ? arrayMap(transforms[0], baseUnary(getIteratee())) : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, length = nativeMin(args.length, funcsLength); - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); - } - return apply2(func, this, args); - }); - }); - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined$1, partials, holders); - }); - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined$1, partials, holders); - }); - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined$1, undefined$1, undefined$1, indexes); - }); - function rest(func, start) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start = start === undefined$1 ? start : toInteger2(start); - return baseRest(func, start); - } - function spread(func, start) { - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger2(start), 0); - return baseRest(function(args) { - var array = args[start], otherArgs = castSlice(args, 0, start); - if (array) { - arrayPush(otherArgs, array); - } - return apply2(func, this, otherArgs); - }); - } - function throttle(func, wait, options) { - var leading = true, trailing = true; - if (typeof func != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - if (isObject2(options)) { - leading = "leading" in options ? !!options.leading : leading; - trailing = "trailing" in options ? !!options.trailing : trailing; - } - return debounce(func, wait, { - "leading": leading, - "maxWait": wait, - "trailing": trailing - }); - } - function unary(func) { - return ary(func, 1); - } - function wrap(value2, wrapper) { - return partial(castFunction(wrapper), value2); - } - function castArray() { - if (!arguments.length) { - return []; - } - var value2 = arguments[0]; - return isArray2(value2) ? value2 : [value2]; - } - function clone(value2) { - return baseClone(value2, CLONE_SYMBOLS_FLAG); - } - function cloneWith(value2, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - return baseClone(value2, CLONE_SYMBOLS_FLAG, customizer); - } - function cloneDeep(value2) { - return baseClone(value2, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); - } - function cloneDeepWith(value2, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - return baseClone(value2, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); - } - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys2(source)); - } - function eq(value2, other) { - return value2 === other || value2 !== value2 && other !== other; - } - var gt = createRelationalOperation(baseGt); - var gte = createRelationalOperation(function(value2, other) { - return value2 >= other; - }); - var isArguments2 = baseIsArguments(/* @__PURE__ */ function() { - return arguments; - }()) ? baseIsArguments : function(value2) { - return isObjectLike(value2) && hasOwnProperty2.call(value2, "callee") && !propertyIsEnumerable.call(value2, "callee"); - }; - var isArray2 = Array2.isArray; - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; - function isArrayLike(value2) { - return value2 != null && isLength(value2.length) && !isFunction2(value2); - } - function isArrayLikeObject(value2) { - return isObjectLike(value2) && isArrayLike(value2); - } - function isBoolean(value2) { - return value2 === true || value2 === false || isObjectLike(value2) && baseGetTag(value2) == boolTag; - } - var isBuffer = nativeIsBuffer || stubFalse; - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; - function isElement(value2) { - return isObjectLike(value2) && value2.nodeType === 1 && !isPlainObject(value2); - } - function isEmpty(value2) { - if (value2 == null) { - return true; - } - if (isArrayLike(value2) && (isArray2(value2) || typeof value2 == "string" || typeof value2.splice == "function" || isBuffer(value2) || isTypedArray(value2) || isArguments2(value2))) { - return !value2.length; - } - var tag = getTag(value2); - if (tag == mapTag || tag == setTag) { - return !value2.size; - } - if (isPrototype2(value2)) { - return !baseKeys(value2).length; - } - for (var key in value2) { - if (hasOwnProperty2.call(value2, key)) { - return false; - } - } - return true; - } - function isEqual(value2, other) { - return baseIsEqual(value2, other); - } - function isEqualWith(value2, other, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - var result2 = customizer ? customizer(value2, other) : undefined$1; - return result2 === undefined$1 ? baseIsEqual(value2, other, undefined$1, customizer) : !!result2; - } - function isError(value2) { - if (!isObjectLike(value2)) { - return false; - } - var tag = baseGetTag(value2); - return tag == errorTag || tag == domExcTag || typeof value2.message == "string" && typeof value2.name == "string" && !isPlainObject(value2); - } - function isFinite2(value2) { - return typeof value2 == "number" && nativeIsFinite(value2); - } - function isFunction2(value2) { - if (!isObject2(value2)) { - return false; - } - var tag = baseGetTag(value2); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; - } - function isInteger(value2) { - return typeof value2 == "number" && value2 == toInteger2(value2); - } - function isLength(value2) { - return typeof value2 == "number" && value2 > -1 && value2 % 1 == 0 && value2 <= MAX_SAFE_INTEGER; - } - function isObject2(value2) { - var type = typeof value2; - return value2 != null && (type == "object" || type == "function"); - } - function isObjectLike(value2) { - return value2 != null && typeof value2 == "object"; - } - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); - } - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - return baseIsMatch(object, source, getMatchData(source), customizer); - } - function isNaN2(value2) { - return isNumber(value2) && value2 != +value2; - } - function isNative(value2) { - if (isMaskable(value2)) { - throw new Error2(CORE_ERROR_TEXT); - } - return baseIsNative(value2); - } - function isNull(value2) { - return value2 === null; - } - function isNil(value2) { - return value2 == null; - } - function isNumber(value2) { - return typeof value2 == "number" || isObjectLike(value2) && baseGetTag(value2) == numberTag; - } - function isPlainObject(value2) { - if (!isObjectLike(value2) || baseGetTag(value2) != objectTag) { - return false; - } - var proto = getPrototype(value2); - if (proto === null) { - return true; - } - var Ctor = hasOwnProperty2.call(proto, "constructor") && proto.constructor; - return typeof Ctor == "function" && Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString; - } - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; - function isSafeInteger(value2) { - return isInteger(value2) && value2 >= -9007199254740991 && value2 <= MAX_SAFE_INTEGER; - } - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; - function isString2(value2) { - return typeof value2 == "string" || !isArray2(value2) && isObjectLike(value2) && baseGetTag(value2) == stringTag; - } - function isSymbol2(value2) { - return typeof value2 == "symbol" || isObjectLike(value2) && baseGetTag(value2) == symbolTag; - } - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - function isUndefined(value2) { - return value2 === undefined$1; - } - function isWeakMap(value2) { - return isObjectLike(value2) && getTag(value2) == weakMapTag; - } - function isWeakSet(value2) { - return isObjectLike(value2) && baseGetTag(value2) == weakSetTag; - } - var lt = createRelationalOperation(baseLt); - var lte = createRelationalOperation(function(value2, other) { - return value2 <= other; - }); - function toArray2(value2) { - if (!value2) { - return []; - } - if (isArrayLike(value2)) { - return isString2(value2) ? stringToArray(value2) : copyArray(value2); - } - if (symIterator && value2[symIterator]) { - return iteratorToArray(value2[symIterator]()); - } - var tag = getTag(value2), func = tag == mapTag ? mapToArray : tag == setTag ? setToArray : values; - return func(value2); - } - function toFinite(value2) { - if (!value2) { - return value2 === 0 ? value2 : 0; - } - value2 = toNumber(value2); - if (value2 === INFINITY || value2 === -Infinity) { - var sign2 = value2 < 0 ? -1 : 1; - return sign2 * MAX_INTEGER; - } - return value2 === value2 ? value2 : 0; - } - function toInteger2(value2) { - var result2 = toFinite(value2), remainder = result2 % 1; - return result2 === result2 ? remainder ? result2 - remainder : result2 : 0; - } - function toLength(value2) { - return value2 ? baseClamp(toInteger2(value2), 0, MAX_ARRAY_LENGTH) : 0; - } - function toNumber(value2) { - if (typeof value2 == "number") { - return value2; - } - if (isSymbol2(value2)) { - return NAN; - } - if (isObject2(value2)) { - var other = typeof value2.valueOf == "function" ? value2.valueOf() : value2; - value2 = isObject2(other) ? other + "" : other; - } - if (typeof value2 != "string") { - return value2 === 0 ? value2 : +value2; - } - value2 = baseTrim(value2); - var isBinary = reIsBinary.test(value2); - return isBinary || reIsOctal.test(value2) ? freeParseInt(value2.slice(2), isBinary ? 2 : 8) : reIsBadHex.test(value2) ? NAN : +value2; - } - function toPlainObject(value2) { - return copyObject(value2, keysIn(value2)); - } - function toSafeInteger(value2) { - return value2 ? baseClamp(toInteger2(value2), -9007199254740991, MAX_SAFE_INTEGER) : value2 === 0 ? value2 : 0; - } - function toString(value2) { - return value2 == null ? "" : baseToString(value2); - } - var assign2 = createAssigner(function(object, source) { - if (isPrototype2(source) || isArrayLike(source)) { - copyObject(source, keys2(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty2.call(source, key)) { - assignValue(object, key, source[key]); - } - } - }); - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); - }); - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); - }); - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys2(source), object, customizer); - }); - var at = flatRest(baseAt); - function create2(prototype, properties) { - var result2 = baseCreate(prototype); - return properties == null ? result2 : baseAssign(result2, properties); - } - var defaults = baseRest(function(object, sources) { - object = Object2(object); - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined$1; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value2 = object[key]; - if (value2 === undefined$1 || eq(value2, objectProto[key]) && !hasOwnProperty2.call(object, key)) { - object[key] = source[key]; - } - } - } - return object; - }); - var defaultsDeep = baseRest(function(args) { - args.push(undefined$1, customDefaultsMerge); - return apply2(mergeWith, undefined$1, args); - }); - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); - } - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); - } - function forIn(object, iteratee2) { - return object == null ? object : baseFor(object, getIteratee(iteratee2, 3), keysIn); - } - function forInRight(object, iteratee2) { - return object == null ? object : baseForRight(object, getIteratee(iteratee2, 3), keysIn); - } - function forOwn(object, iteratee2) { - return object && baseForOwn(object, getIteratee(iteratee2, 3)); - } - function forOwnRight(object, iteratee2) { - return object && baseForOwnRight(object, getIteratee(iteratee2, 3)); - } - function functions(object) { - return object == null ? [] : baseFunctions(object, keys2(object)); - } - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); - } - function get2(object, path, defaultValue) { - var result2 = object == null ? undefined$1 : baseGet(object, path); - return result2 === undefined$1 ? defaultValue : result2; - } - function has(object, path) { - return object != null && hasPath(object, path, baseHas); - } - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); - } - var invert = createInverter(function(result2, value2, key) { - if (value2 != null && typeof value2.toString != "function") { - value2 = nativeObjectToString.call(value2); - } - result2[value2] = key; - }, constant(identity)); - var invertBy = createInverter(function(result2, value2, key) { - if (value2 != null && typeof value2.toString != "function") { - value2 = nativeObjectToString.call(value2); - } - if (hasOwnProperty2.call(result2, value2)) { - result2[value2].push(key); - } else { - result2[value2] = [key]; - } - }, getIteratee); - var invoke = baseRest(baseInvoke); - function keys2(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); - } - function mapKeys(object, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object, function(value2, key, object2) { - baseAssignValue(result2, iteratee2(value2, key, object2), value2); - }); - return result2; - } - function mapValues(object, iteratee2) { - var result2 = {}; - iteratee2 = getIteratee(iteratee2, 3); - baseForOwn(object, function(value2, key, object2) { - baseAssignValue(result2, key, iteratee2(value2, key, object2)); - }); - return result2; - } - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); - var omit = flatRest(function(object, paths) { - var result2 = {}; - if (object == null) { - return result2; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result2); - if (isDeep) { - result2 = baseClone(result2, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result2, paths[length]); - } - return result2; - }); - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); - } - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value2, path) { - return predicate(value2, path[0]); - }); - } - function result(object, path, defaultValue) { - path = castPath(path, object); - var index = -1, length = path.length; - if (!length) { - length = 1; - object = undefined$1; - } - while (++index < length) { - var value2 = object == null ? undefined$1 : object[toKey(path[index])]; - if (value2 === undefined$1) { - index = length; - value2 = defaultValue; - } - object = isFunction2(value2) ? value2.call(object) : value2; - } - return object; - } - function set(object, path, value2) { - return object == null ? object : baseSet(object, path, value2); - } - function setWith(object, path, value2, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - return object == null ? object : baseSet(object, path, value2, customizer); - } - var toPairs = createToPairs(keys2); - var toPairsIn = createToPairs(keysIn); - function transform(object, iteratee2, accumulator) { - var isArr = isArray2(object), isArrLike = isArr || isBuffer(object) || isTypedArray(object); - iteratee2 = getIteratee(iteratee2, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor() : []; - } else if (isObject2(object)) { - accumulator = isFunction2(Ctor) ? baseCreate(getPrototype(object)) : {}; - } else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value2, index, object2) { - return iteratee2(accumulator, value2, index, object2); - }); - return accumulator; - } - function unset(object, path) { - return object == null ? true : baseUnset(object, path); - } - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); - } - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == "function" ? customizer : undefined$1; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); - } - function values(object) { - return object == null ? [] : baseValues(object, keys2(object)); - } - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); - } - function clamp(number, lower, upper) { - if (upper === undefined$1) { - upper = lower; - lower = undefined$1; - } - if (upper !== undefined$1) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined$1) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; - } - return baseClamp(toNumber(number), lower, upper); - } - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined$1) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - number = toNumber(number); - return baseInRange(number, start, end); - } - function random(lower, upper, floating) { - if (floating && typeof floating != "boolean" && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined$1; - } - if (floating === undefined$1) { - if (typeof upper == "boolean") { - floating = upper; - upper = undefined$1; - } else if (typeof lower == "boolean") { - floating = lower; - lower = undefined$1; - } - } - if (lower === undefined$1 && upper === undefined$1) { - lower = 0; - upper = 1; - } else { - lower = toFinite(lower); - if (upper === undefined$1) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + rand * (upper - lower + freeParseFloat("1e-" + ((rand + "").length - 1))), upper); - } - return baseRandom(lower, upper); - } - var camelCase = createCompounder(function(result2, word, index) { - word = word.toLowerCase(); - return result2 + (index ? capitalize(word) : word); - }); - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ""); - } - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - var length = string.length; - position = position === undefined$1 ? length : baseClamp(toInteger2(position), 0, length); - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } - function escape(string) { - string = toString(string); - return string && reHasUnescapedHtml.test(string) ? string.replace(reUnescapedHtml, escapeHtmlChar) : string; - } - function escapeRegExp(string) { - string = toString(string); - return string && reHasRegExpChar.test(string) ? string.replace(reRegExpChar, "\\$&") : string; - } - var kebabCase = createCompounder(function(result2, word, index) { - return result2 + (index ? "-" : "") + word.toLowerCase(); - }); - var lowerCase = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + word.toLowerCase(); - }); - var lowerFirst = createCaseFirst("toLowerCase"); - function pad(string, length, chars) { - string = toString(string); - length = toInteger2(length); - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return createPadding(nativeFloor(mid), chars) + string + createPadding(nativeCeil(mid), chars); - } - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger2(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? string + createPadding(length - strLength, chars) : string; - } - function padStart(string, length, chars) { - string = toString(string); - length = toInteger2(length); - var strLength = length ? stringSize(string) : 0; - return length && strLength < length ? createPadding(length - strLength, chars) + string : string; - } - function parseInt2(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ""), radix || 0); - } - function repeat(string, n2, guard) { - if (guard ? isIterateeCall(string, n2, guard) : n2 === undefined$1) { - n2 = 1; - } else { - n2 = toInteger2(n2); - } - return baseRepeat(toString(string), n2); - } - function replace() { - var args = arguments, string = toString(args[0]); - return args.length < 3 ? string : string.replace(args[1], args[2]); - } - var snakeCase = createCompounder(function(result2, word, index) { - return result2 + (index ? "_" : "") + word.toLowerCase(); - }); - function split(string, separator, limit) { - if (limit && typeof limit != "number" && isIterateeCall(string, separator, limit)) { - separator = limit = undefined$1; - } - limit = limit === undefined$1 ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && (typeof separator == "string" || separator != null && !isRegExp(separator))) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); - } - var startCase = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + upperFirst(word); - }); - function startsWith(string, target, position) { - string = toString(string); - position = position == null ? 0 : baseClamp(toInteger2(position), 0, string.length); - target = baseToString(target); - return string.slice(position, position + target.length) == target; - } - function template(string, options, guard) { - var settings = lodash2.templateSettings; - if (guard && isIterateeCall(string, options, guard)) { - options = undefined$1; - } - string = toString(string); - options = assignInWith({}, options, settings, customDefaultsAssignIn); - var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn), importsKeys = keys2(imports), importsValues = baseValues(imports, importsKeys); - var isEscaping, isEvaluating, index = 0, interpolate = options.interpolate || reNoMatch, source = "__p += '"; - var reDelimiters = RegExp2( - (options.escape || reNoMatch).source + "|" + interpolate.source + "|" + (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + "|" + (options.evaluate || reNoMatch).source + "|$", - "g" - ); - var sourceURL = "//# sourceURL=" + (hasOwnProperty2.call(options, "sourceURL") ? (options.sourceURL + "").replace(/\s/g, " ") : "lodash.templateSources[" + ++templateCounter + "]") + "\n"; - string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) { - interpolateValue || (interpolateValue = esTemplateValue); - source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar); - if (escapeValue) { - isEscaping = true; - source += "' +\n__e(" + escapeValue + ") +\n'"; - } - if (evaluateValue) { - isEvaluating = true; - source += "';\n" + evaluateValue + ";\n__p += '"; - } - if (interpolateValue) { - source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'"; - } - index = offset + match.length; - return match; - }); - source += "';\n"; - var variable = hasOwnProperty2.call(options, "variable") && options.variable; - if (!variable) { - source = "with (obj) {\n" + source + "\n}\n"; - } else if (reForbiddenIdentifierChars.test(variable)) { - throw new Error2(INVALID_TEMPL_VAR_ERROR_TEXT); - } - source = (isEvaluating ? source.replace(reEmptyStringLeading, "") : source).replace(reEmptyStringMiddle, "$1").replace(reEmptyStringTrailing, "$1;"); - source = "function(" + (variable || "obj") + ") {\n" + (variable ? "" : "obj || (obj = {});\n") + "var __t, __p = ''" + (isEscaping ? ", __e = _.escape" : "") + (isEvaluating ? ", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n" : ";\n") + source + "return __p\n}"; - var result2 = attempt(function() { - return Function2(importsKeys, sourceURL + "return " + source).apply(undefined$1, importsValues); - }); - result2.source = source; - if (isError(result2)) { - throw result2; - } - return result2; - } - function toLower(value2) { - return toString(value2).toLowerCase(); - } - function toUpper(value2) { - return toString(value2).toUpperCase(); - } - function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined$1)) { - return baseTrim(string); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), chrSymbols = stringToArray(chars), start = charsStartIndex(strSymbols, chrSymbols), end = charsEndIndex(strSymbols, chrSymbols) + 1; - return castSlice(strSymbols, start, end).join(""); - } - function trimEnd(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined$1)) { - return string.slice(0, trimmedEndIndex(string) + 1); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), end = charsEndIndex(strSymbols, stringToArray(chars)) + 1; - return castSlice(strSymbols, 0, end).join(""); - } - function trimStart(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined$1)) { - return string.replace(reTrimStart, ""); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), start = charsStartIndex(strSymbols, stringToArray(chars)); - return castSlice(strSymbols, start).join(""); - } - function truncate(string, options) { - var length = DEFAULT_TRUNC_LENGTH, omission = DEFAULT_TRUNC_OMISSION; - if (isObject2(options)) { - var separator = "separator" in options ? options.separator : separator; - length = "length" in options ? toInteger2(options.length) : length; - omission = "omission" in options ? baseToString(options.omission) : omission; - } - string = toString(string); - var strLength = string.length; - if (hasUnicode(string)) { - var strSymbols = stringToArray(string); - strLength = strSymbols.length; - } - if (length >= strLength) { - return string; - } - var end = length - stringSize(omission); - if (end < 1) { - return omission; - } - var result2 = strSymbols ? castSlice(strSymbols, 0, end).join("") : string.slice(0, end); - if (separator === undefined$1) { - return result2 + omission; - } - if (strSymbols) { - end += result2.length - end; - } - if (isRegExp(separator)) { - if (string.slice(end).search(separator)) { - var match, substring = result2; - if (!separator.global) { - separator = RegExp2(separator.source, toString(reFlags.exec(separator)) + "g"); - } - separator.lastIndex = 0; - while (match = separator.exec(substring)) { - var newEnd = match.index; - } - result2 = result2.slice(0, newEnd === undefined$1 ? end : newEnd); - } - } else if (string.indexOf(baseToString(separator), end) != end) { - var index = result2.lastIndexOf(separator); - if (index > -1) { - result2 = result2.slice(0, index); - } - } - return result2 + omission; - } - function unescape(string) { - string = toString(string); - return string && reHasEscapedHtml.test(string) ? string.replace(reEscapedHtml, unescapeHtmlChar) : string; - } - var upperCase = createCompounder(function(result2, word, index) { - return result2 + (index ? " " : "") + word.toUpperCase(); - }); - var upperFirst = createCaseFirst("toUpperCase"); - function words(string, pattern, guard) { - string = toString(string); - pattern = guard ? undefined$1 : pattern; - if (pattern === undefined$1) { - return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); - } - return string.match(pattern) || []; - } - var attempt = baseRest(function(func, args) { - try { - return apply2(func, undefined$1, args); - } catch (e) { - return isError(e) ? e : new Error2(e); - } - }); - var bindAll = flatRest(function(object, methodNames) { - arrayEach(methodNames, function(key) { - key = toKey(key); - baseAssignValue(object, key, bind2(object[key], object)); - }); - return object; - }); - function cond(pairs) { - var length = pairs == null ? 0 : pairs.length, toIteratee = getIteratee(); - pairs = !length ? [] : arrayMap(pairs, function(pair) { - if (typeof pair[1] != "function") { - throw new TypeError2(FUNC_ERROR_TEXT); - } - return [toIteratee(pair[0]), pair[1]]; - }); - return baseRest(function(args) { - var index = -1; - while (++index < length) { - var pair = pairs[index]; - if (apply2(pair[0], this, args)) { - return apply2(pair[1], this, args); - } - } - }); - } - function conforms(source) { - return baseConforms(baseClone(source, CLONE_DEEP_FLAG)); - } - function constant(value2) { - return function() { - return value2; - }; - } - function defaultTo(value2, defaultValue) { - return value2 == null || value2 !== value2 ? defaultValue : value2; - } - var flow = createFlow(); - var flowRight = createFlow(true); - function identity(value2) { - return value2; - } - function iteratee(func) { - return baseIteratee(typeof func == "function" ? func : baseClone(func, CLONE_DEEP_FLAG)); - } - function matches(source) { - return baseMatches(baseClone(source, CLONE_DEEP_FLAG)); - } - function matchesProperty(path, srcValue) { - return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG)); - } - var method = baseRest(function(path, args) { - return function(object) { - return baseInvoke(object, path, args); - }; - }); - var methodOf = baseRest(function(object, args) { - return function(path) { - return baseInvoke(object, path, args); - }; - }); - function mixin2(object, source, options) { - var props = keys2(source), methodNames = baseFunctions(source, props); - if (options == null && !(isObject2(source) && (methodNames.length || !props.length))) { - options = source; - source = object; - object = this; - methodNames = baseFunctions(source, keys2(source)); - } - var chain2 = !(isObject2(options) && "chain" in options) || !!options.chain, isFunc = isFunction2(object); - arrayEach(methodNames, function(methodName) { - var func = source[methodName]; - object[methodName] = func; - if (isFunc) { - object.prototype[methodName] = function() { - var chainAll = this.__chain__; - if (chain2 || chainAll) { - var result2 = object(this.__wrapped__), actions = result2.__actions__ = copyArray(this.__actions__); - actions.push({ "func": func, "args": arguments, "thisArg": object }); - result2.__chain__ = chainAll; - return result2; - } - return func.apply(object, arrayPush([this.value()], arguments)); - }; - } - }); - return object; - } - function noConflict() { - if (root._ === this) { - root._ = oldDash; - } - return this; - } - function noop2() { - } - function nthArg(n2) { - n2 = toInteger2(n2); - return baseRest(function(args) { - return baseNth(args, n2); - }); - } - var over = createOver(arrayMap); - var overEvery = createOver(arrayEvery); - var overSome = createOver(arraySome); - function property(path) { - return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); - } - function propertyOf(object) { - return function(path) { - return object == null ? undefined$1 : baseGet(object, path); - }; - } - var range = createRange(); - var rangeRight = createRange(true); - function stubArray() { - return []; - } - function stubFalse() { - return false; - } - function stubObject() { - return {}; - } - function stubString() { - return ""; - } - function stubTrue() { - return true; - } - function times(n2, iteratee2) { - n2 = toInteger2(n2); - if (n2 < 1 || n2 > MAX_SAFE_INTEGER) { - return []; - } - var index = MAX_ARRAY_LENGTH, length = nativeMin(n2, MAX_ARRAY_LENGTH); - iteratee2 = getIteratee(iteratee2); - n2 -= MAX_ARRAY_LENGTH; - var result2 = baseTimes(length, iteratee2); - while (++index < n2) { - iteratee2(index); - } - return result2; - } - function toPath(value2) { - if (isArray2(value2)) { - return arrayMap(value2, toKey); - } - return isSymbol2(value2) ? [value2] : copyArray(stringToPath(toString(value2))); - } - function uniqueId(prefix) { - var id = ++idCounter; - return toString(prefix) + id; - } - var add = createMathOperation(function(augend, addend) { - return augend + addend; - }, 0); - var ceil = createRound("ceil"); - var divide = createMathOperation(function(dividend, divisor) { - return dividend / divisor; - }, 1); - var floor2 = createRound("floor"); - function max2(array) { - return array && array.length ? baseExtremum(array, identity, baseGt) : undefined$1; - } - function maxBy(array, iteratee2) { - return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseGt) : undefined$1; - } - function mean(array) { - return baseMean(array, identity); - } - function meanBy(array, iteratee2) { - return baseMean(array, getIteratee(iteratee2, 2)); - } - function min(array) { - return array && array.length ? baseExtremum(array, identity, baseLt) : undefined$1; - } - function minBy(array, iteratee2) { - return array && array.length ? baseExtremum(array, getIteratee(iteratee2, 2), baseLt) : undefined$1; - } - var multiply = createMathOperation(function(multiplier, multiplicand) { - return multiplier * multiplicand; - }, 1); - var round = createRound("round"); - var subtract = createMathOperation(function(minuend, subtrahend) { - return minuend - subtrahend; - }, 0); - function sum(array) { - return array && array.length ? baseSum(array, identity) : 0; - } - function sumBy(array, iteratee2) { - return array && array.length ? baseSum(array, getIteratee(iteratee2, 2)) : 0; - } - lodash2.after = after; - lodash2.ary = ary; - lodash2.assign = assign2; - lodash2.assignIn = assignIn; - lodash2.assignInWith = assignInWith; - lodash2.assignWith = assignWith; - lodash2.at = at; - lodash2.before = before; - lodash2.bind = bind2; - lodash2.bindAll = bindAll; - lodash2.bindKey = bindKey; - lodash2.castArray = castArray; - lodash2.chain = chain; - lodash2.chunk = chunk; - lodash2.compact = compact; - lodash2.concat = concat; - lodash2.cond = cond; - lodash2.conforms = conforms; - lodash2.constant = constant; - lodash2.countBy = countBy; - lodash2.create = create2; - lodash2.curry = curry; - lodash2.curryRight = curryRight; - lodash2.debounce = debounce; - lodash2.defaults = defaults; - lodash2.defaultsDeep = defaultsDeep; - lodash2.defer = defer; - lodash2.delay = delay; - lodash2.difference = difference; - lodash2.differenceBy = differenceBy; - lodash2.differenceWith = differenceWith; - lodash2.drop = drop; - lodash2.dropRight = dropRight; - lodash2.dropRightWhile = dropRightWhile; - lodash2.dropWhile = dropWhile; - lodash2.fill = fill; - lodash2.filter = filter; - lodash2.flatMap = flatMap; - lodash2.flatMapDeep = flatMapDeep; - lodash2.flatMapDepth = flatMapDepth; - lodash2.flatten = flatten; - lodash2.flattenDeep = flattenDeep; - lodash2.flattenDepth = flattenDepth; - lodash2.flip = flip; - lodash2.flow = flow; - lodash2.flowRight = flowRight; - lodash2.fromPairs = fromPairs; - lodash2.functions = functions; - lodash2.functionsIn = functionsIn; - lodash2.groupBy = groupBy; - lodash2.initial = initial; - lodash2.intersection = intersection; - lodash2.intersectionBy = intersectionBy; - lodash2.intersectionWith = intersectionWith; - lodash2.invert = invert; - lodash2.invertBy = invertBy; - lodash2.invokeMap = invokeMap; - lodash2.iteratee = iteratee; - lodash2.keyBy = keyBy; - lodash2.keys = keys2; - lodash2.keysIn = keysIn; - lodash2.map = map2; - lodash2.mapKeys = mapKeys; - lodash2.mapValues = mapValues; - lodash2.matches = matches; - lodash2.matchesProperty = matchesProperty; - lodash2.memoize = memoize2; - lodash2.merge = merge; - lodash2.mergeWith = mergeWith; - lodash2.method = method; - lodash2.methodOf = methodOf; - lodash2.mixin = mixin2; - lodash2.negate = negate; - lodash2.nthArg = nthArg; - lodash2.omit = omit; - lodash2.omitBy = omitBy; - lodash2.once = once; - lodash2.orderBy = orderBy; - lodash2.over = over; - lodash2.overArgs = overArgs; - lodash2.overEvery = overEvery; - lodash2.overSome = overSome; - lodash2.partial = partial; - lodash2.partialRight = partialRight; - lodash2.partition = partition; - lodash2.pick = pick; - lodash2.pickBy = pickBy; - lodash2.property = property; - lodash2.propertyOf = propertyOf; - lodash2.pull = pull; - lodash2.pullAll = pullAll; - lodash2.pullAllBy = pullAllBy; - lodash2.pullAllWith = pullAllWith; - lodash2.pullAt = pullAt; - lodash2.range = range; - lodash2.rangeRight = rangeRight; - lodash2.rearg = rearg; - lodash2.reject = reject; - lodash2.remove = remove; - lodash2.rest = rest; - lodash2.reverse = reverse; - lodash2.sampleSize = sampleSize; - lodash2.set = set; - lodash2.setWith = setWith; - lodash2.shuffle = shuffle; - lodash2.slice = slice2; - lodash2.sortBy = sortBy; - lodash2.sortedUniq = sortedUniq; - lodash2.sortedUniqBy = sortedUniqBy; - lodash2.split = split; - lodash2.spread = spread; - lodash2.tail = tail; - lodash2.take = take; - lodash2.takeRight = takeRight; - lodash2.takeRightWhile = takeRightWhile; - lodash2.takeWhile = takeWhile; - lodash2.tap = tap; - lodash2.throttle = throttle; - lodash2.thru = thru; - lodash2.toArray = toArray2; - lodash2.toPairs = toPairs; - lodash2.toPairsIn = toPairsIn; - lodash2.toPath = toPath; - lodash2.toPlainObject = toPlainObject; - lodash2.transform = transform; - lodash2.unary = unary; - lodash2.union = union; - lodash2.unionBy = unionBy; - lodash2.unionWith = unionWith; - lodash2.uniq = uniq; - lodash2.uniqBy = uniqBy; - lodash2.uniqWith = uniqWith; - lodash2.unset = unset; - lodash2.unzip = unzip; - lodash2.unzipWith = unzipWith; - lodash2.update = update; - lodash2.updateWith = updateWith; - lodash2.values = values; - lodash2.valuesIn = valuesIn; - lodash2.without = without; - lodash2.words = words; - lodash2.wrap = wrap; - lodash2.xor = xor; - lodash2.xorBy = xorBy; - lodash2.xorWith = xorWith; - lodash2.zip = zip; - lodash2.zipObject = zipObject; - lodash2.zipObjectDeep = zipObjectDeep; - lodash2.zipWith = zipWith; - lodash2.entries = toPairs; - lodash2.entriesIn = toPairsIn; - lodash2.extend = assignIn; - lodash2.extendWith = assignInWith; - mixin2(lodash2, lodash2); - lodash2.add = add; - lodash2.attempt = attempt; - lodash2.camelCase = camelCase; - lodash2.capitalize = capitalize; - lodash2.ceil = ceil; - lodash2.clamp = clamp; - lodash2.clone = clone; - lodash2.cloneDeep = cloneDeep; - lodash2.cloneDeepWith = cloneDeepWith; - lodash2.cloneWith = cloneWith; - lodash2.conformsTo = conformsTo; - lodash2.deburr = deburr; - lodash2.defaultTo = defaultTo; - lodash2.divide = divide; - lodash2.endsWith = endsWith; - lodash2.eq = eq; - lodash2.escape = escape; - lodash2.escapeRegExp = escapeRegExp; - lodash2.every = every; - lodash2.find = find; - lodash2.findIndex = findIndex; - lodash2.findKey = findKey; - lodash2.findLast = findLast; - lodash2.findLastIndex = findLastIndex; - lodash2.findLastKey = findLastKey; - lodash2.floor = floor2; - lodash2.forEach = forEach2; - lodash2.forEachRight = forEachRight; - lodash2.forIn = forIn; - lodash2.forInRight = forInRight; - lodash2.forOwn = forOwn; - lodash2.forOwnRight = forOwnRight; - lodash2.get = get2; - lodash2.gt = gt; - lodash2.gte = gte; - lodash2.has = has; - lodash2.hasIn = hasIn; - lodash2.head = head; - lodash2.identity = identity; - lodash2.includes = includes; - lodash2.indexOf = indexOf; - lodash2.inRange = inRange; - lodash2.invoke = invoke; - lodash2.isArguments = isArguments2; - lodash2.isArray = isArray2; - lodash2.isArrayBuffer = isArrayBuffer; - lodash2.isArrayLike = isArrayLike; - lodash2.isArrayLikeObject = isArrayLikeObject; - lodash2.isBoolean = isBoolean; - lodash2.isBuffer = isBuffer; - lodash2.isDate = isDate; - lodash2.isElement = isElement; - lodash2.isEmpty = isEmpty; - lodash2.isEqual = isEqual; - lodash2.isEqualWith = isEqualWith; - lodash2.isError = isError; - lodash2.isFinite = isFinite2; - lodash2.isFunction = isFunction2; - lodash2.isInteger = isInteger; - lodash2.isLength = isLength; - lodash2.isMap = isMap; - lodash2.isMatch = isMatch; - lodash2.isMatchWith = isMatchWith; - lodash2.isNaN = isNaN2; - lodash2.isNative = isNative; - lodash2.isNil = isNil; - lodash2.isNull = isNull; - lodash2.isNumber = isNumber; - lodash2.isObject = isObject2; - lodash2.isObjectLike = isObjectLike; - lodash2.isPlainObject = isPlainObject; - lodash2.isRegExp = isRegExp; - lodash2.isSafeInteger = isSafeInteger; - lodash2.isSet = isSet; - lodash2.isString = isString2; - lodash2.isSymbol = isSymbol2; - lodash2.isTypedArray = isTypedArray; - lodash2.isUndefined = isUndefined; - lodash2.isWeakMap = isWeakMap; - lodash2.isWeakSet = isWeakSet; - lodash2.join = join; - lodash2.kebabCase = kebabCase; - lodash2.last = last; - lodash2.lastIndexOf = lastIndexOf; - lodash2.lowerCase = lowerCase; - lodash2.lowerFirst = lowerFirst; - lodash2.lt = lt; - lodash2.lte = lte; - lodash2.max = max2; - lodash2.maxBy = maxBy; - lodash2.mean = mean; - lodash2.meanBy = meanBy; - lodash2.min = min; - lodash2.minBy = minBy; - lodash2.stubArray = stubArray; - lodash2.stubFalse = stubFalse; - lodash2.stubObject = stubObject; - lodash2.stubString = stubString; - lodash2.stubTrue = stubTrue; - lodash2.multiply = multiply; - lodash2.nth = nth; - lodash2.noConflict = noConflict; - lodash2.noop = noop2; - lodash2.now = now; - lodash2.pad = pad; - lodash2.padEnd = padEnd; - lodash2.padStart = padStart; - lodash2.parseInt = parseInt2; - lodash2.random = random; - lodash2.reduce = reduce; - lodash2.reduceRight = reduceRight; - lodash2.repeat = repeat; - lodash2.replace = replace; - lodash2.result = result; - lodash2.round = round; - lodash2.runInContext = runInContext2; - lodash2.sample = sample; - lodash2.size = size; - lodash2.snakeCase = snakeCase; - lodash2.some = some; - lodash2.sortedIndex = sortedIndex; - lodash2.sortedIndexBy = sortedIndexBy; - lodash2.sortedIndexOf = sortedIndexOf; - lodash2.sortedLastIndex = sortedLastIndex; - lodash2.sortedLastIndexBy = sortedLastIndexBy; - lodash2.sortedLastIndexOf = sortedLastIndexOf; - lodash2.startCase = startCase; - lodash2.startsWith = startsWith; - lodash2.subtract = subtract; - lodash2.sum = sum; - lodash2.sumBy = sumBy; - lodash2.template = template; - lodash2.times = times; - lodash2.toFinite = toFinite; - lodash2.toInteger = toInteger2; - lodash2.toLength = toLength; - lodash2.toLower = toLower; - lodash2.toNumber = toNumber; - lodash2.toSafeInteger = toSafeInteger; - lodash2.toString = toString; - lodash2.toUpper = toUpper; - lodash2.trim = trim; - lodash2.trimEnd = trimEnd; - lodash2.trimStart = trimStart; - lodash2.truncate = truncate; - lodash2.unescape = unescape; - lodash2.uniqueId = uniqueId; - lodash2.upperCase = upperCase; - lodash2.upperFirst = upperFirst; - lodash2.each = forEach2; - lodash2.eachRight = forEachRight; - lodash2.first = head; - mixin2(lodash2, function() { - var source = {}; - baseForOwn(lodash2, function(func, methodName) { - if (!hasOwnProperty2.call(lodash2.prototype, methodName)) { - source[methodName] = func; - } - }); - return source; - }(), { "chain": false }); - lodash2.VERSION = VERSION; - arrayEach(["bind", "bindKey", "curry", "curryRight", "partial", "partialRight"], function(methodName) { - lodash2[methodName].placeholder = lodash2; - }); - arrayEach(["drop", "take"], function(methodName, index) { - LazyWrapper.prototype[methodName] = function(n2) { - n2 = n2 === undefined$1 ? 1 : nativeMax(toInteger2(n2), 0); - var result2 = this.__filtered__ && !index ? new LazyWrapper(this) : this.clone(); - if (result2.__filtered__) { - result2.__takeCount__ = nativeMin(n2, result2.__takeCount__); - } else { - result2.__views__.push({ - "size": nativeMin(n2, MAX_ARRAY_LENGTH), - "type": methodName + (result2.__dir__ < 0 ? "Right" : "") - }); - } - return result2; - }; - LazyWrapper.prototype[methodName + "Right"] = function(n2) { - return this.reverse()[methodName](n2).reverse(); - }; - }); - arrayEach(["filter", "map", "takeWhile"], function(methodName, index) { - var type = index + 1, isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG; - LazyWrapper.prototype[methodName] = function(iteratee2) { - var result2 = this.clone(); - result2.__iteratees__.push({ - "iteratee": getIteratee(iteratee2, 3), - "type": type - }); - result2.__filtered__ = result2.__filtered__ || isFilter; - return result2; - }; - }); - arrayEach(["head", "last"], function(methodName, index) { - var takeName = "take" + (index ? "Right" : ""); - LazyWrapper.prototype[methodName] = function() { - return this[takeName](1).value()[0]; - }; - }); - arrayEach(["initial", "tail"], function(methodName, index) { - var dropName = "drop" + (index ? "" : "Right"); - LazyWrapper.prototype[methodName] = function() { - return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1); - }; - }); - LazyWrapper.prototype.compact = function() { - return this.filter(identity); - }; - LazyWrapper.prototype.find = function(predicate) { - return this.filter(predicate).head(); - }; - LazyWrapper.prototype.findLast = function(predicate) { - return this.reverse().find(predicate); - }; - LazyWrapper.prototype.invokeMap = baseRest(function(path, args) { - if (typeof path == "function") { - return new LazyWrapper(this); - } - return this.map(function(value2) { - return baseInvoke(value2, path, args); - }); - }); - LazyWrapper.prototype.reject = function(predicate) { - return this.filter(negate(getIteratee(predicate))); - }; - LazyWrapper.prototype.slice = function(start, end) { - start = toInteger2(start); - var result2 = this; - if (result2.__filtered__ && (start > 0 || end < 0)) { - return new LazyWrapper(result2); - } - if (start < 0) { - result2 = result2.takeRight(-start); - } else if (start) { - result2 = result2.drop(start); - } - if (end !== undefined$1) { - end = toInteger2(end); - result2 = end < 0 ? result2.dropRight(-end) : result2.take(end - start); - } - return result2; - }; - LazyWrapper.prototype.takeRightWhile = function(predicate) { - return this.reverse().takeWhile(predicate).reverse(); - }; - LazyWrapper.prototype.toArray = function() { - return this.take(MAX_ARRAY_LENGTH); - }; - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName), isTaker = /^(?:head|last)$/.test(methodName), lodashFunc = lodash2[isTaker ? "take" + (methodName == "last" ? "Right" : "") : methodName], retUnwrapped = isTaker || /^find/.test(methodName); - if (!lodashFunc) { - return; - } - lodash2.prototype[methodName] = function() { - var value2 = this.__wrapped__, args = isTaker ? [1] : arguments, isLazy = value2 instanceof LazyWrapper, iteratee2 = args[0], useLazy = isLazy || isArray2(value2); - var interceptor = function(value3) { - var result3 = lodashFunc.apply(lodash2, arrayPush([value3], args)); - return isTaker && chainAll ? result3[0] : result3; - }; - if (useLazy && checkIteratee && typeof iteratee2 == "function" && iteratee2.length != 1) { - isLazy = useLazy = false; - } - var chainAll = this.__chain__, isHybrid = !!this.__actions__.length, isUnwrapped = retUnwrapped && !chainAll, onlyLazy = isLazy && !isHybrid; - if (!retUnwrapped && useLazy) { - value2 = onlyLazy ? value2 : new LazyWrapper(this); - var result2 = func.apply(value2, args); - result2.__actions__.push({ "func": thru, "args": [interceptor], "thisArg": undefined$1 }); - return new LodashWrapper(result2, chainAll); - } - if (isUnwrapped && onlyLazy) { - return func.apply(this, args); - } - result2 = this.thru(interceptor); - return isUnwrapped ? isTaker ? result2.value()[0] : result2.value() : result2; - }; - }); - arrayEach(["pop", "push", "shift", "sort", "splice", "unshift"], function(methodName) { - var func = arrayProto[methodName], chainName = /^(?:push|sort|unshift)$/.test(methodName) ? "tap" : "thru", retUnwrapped = /^(?:pop|shift)$/.test(methodName); - lodash2.prototype[methodName] = function() { - var args = arguments; - if (retUnwrapped && !this.__chain__) { - var value2 = this.value(); - return func.apply(isArray2(value2) ? value2 : [], args); - } - return this[chainName](function(value3) { - return func.apply(isArray2(value3) ? value3 : [], args); - }); - }; - }); - baseForOwn(LazyWrapper.prototype, function(func, methodName) { - var lodashFunc = lodash2[methodName]; - if (lodashFunc) { - var key = lodashFunc.name + ""; - if (!hasOwnProperty2.call(realNames, key)) { - realNames[key] = []; - } - realNames[key].push({ "name": methodName, "func": lodashFunc }); - } - }); - realNames[createHybrid(undefined$1, WRAP_BIND_KEY_FLAG).name] = [{ - "name": "wrapper", - "func": undefined$1 - }]; - LazyWrapper.prototype.clone = lazyClone; - LazyWrapper.prototype.reverse = lazyReverse; - LazyWrapper.prototype.value = lazyValue; - lodash2.prototype.at = wrapperAt; - lodash2.prototype.chain = wrapperChain; - lodash2.prototype.commit = wrapperCommit; - lodash2.prototype.next = wrapperNext; - lodash2.prototype.plant = wrapperPlant; - lodash2.prototype.reverse = wrapperReverse; - lodash2.prototype.toJSON = lodash2.prototype.valueOf = lodash2.prototype.value = wrapperValue; - lodash2.prototype.first = lodash2.prototype.head; - if (symIterator) { - lodash2.prototype[symIterator] = wrapperToIterator; - } - return lodash2; - }; - var _ = runInContext(); - if (freeModule) { - (freeModule.exports = _)._ = _; - freeExports._ = _; - } else { - root._ = _; - } - }).call(commonjsGlobal); -})(lodash, lodash.exports); -var lodashExports = lodash.exports; -function ownKeys$1(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function(r2) { - return Object.getOwnPropertyDescriptor(e, r2).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread$1(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys$1(Object(t), true).forEach(function(r2) { - _defineProperty$2(e, r2, t[r2]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function(r2) { - Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); - }); - } - return e; -} -function _defineProperty$2(e, r, t) { - return (r = _toPropertyKey$2(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey$2(t) { - var i = _toPrimitive$2(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive$2(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -var log$2 = Log.module("ChartUtils"); -var BUSINESS_COLUMN_TYPE = "io.deephaven.time.DateTime"; -var MILLIS_PER_HOUR = 36e5; -var NANOS_PER_MILLI = 1e6; -function isDateWrapper(value2) { - return value2.asDate !== void 0; -} -function isLongWrapper(value2) { - return value2.asNumber !== void 0; -} -function isDateTimeColumnFormatter(value2) { - return value2.dhTimeZone !== void 0; -} -function isRangedPlotlyAxis(value2) { - return value2 != null && value2.range != null && (value2.autorange === false || value2.autorange === void 0); -} -function isWebGLSupported() { - var canvas = document.createElement("canvas"); - var gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); - return gl != null && gl instanceof WebGLRenderingContext; -} -var IS_WEBGL_SUPPORTED = isWebGLSupported(); -class ChartUtils { - /** - * Generate the plotly error bar data from the passed in data. - * Iris passes in the values as absolute, plotly needs them as relative. - * @param x The main data array - * @param xLow The absolute low values - * @param xHigh - * - * @returns The error_x object required by plotly, or null if none is required - */ - static getPlotlyErrorBars(x, xLow, xHigh) { - var array = xHigh.map((value2, i) => value2 - x[i]); - var arrayminus = xLow.map((value2, i) => x[i] - value2); - return { - type: "data", - symmetric: false, - array, - arrayminus - }; - } - static convertNumberPrefix(prefix) { - return prefix.replace(/\u00A4\u00A4/g, "USD").replace(/\u00A4/g, "$"); - } - static getPlotlyNumberFormat(formatter, columnType, formatPattern) { - if (formatPattern == null || formatPattern === "") { - return null; - } - var subpatterns = formatPattern.split(";"); - var matchArray = subpatterns[0].match(/^([^#,0.]*)([#,]*)([0,]*)(\.?)(0*)(#*)(E?0*)(%?)(.*)/); - assertNotNull(matchArray); - var [, prefix, placeholderDigits, zeroDigits, , decimalDigits, optionalDecimalDigits, numberType, percentSign, suffix] = matchArray; - var paddingLength = zeroDigits.replace(",", "").length; - var isCommaSeparated = placeholderDigits.indexOf(",") >= 0 || zeroDigits.indexOf(",") >= 0; - var comma = isCommaSeparated ? "," : ""; - var plotlyNumberType = numberType != null && numberType !== "" ? "e" : "f"; - var type = percentSign !== "" ? percentSign : plotlyNumberType; - var decimalLength = decimalDigits.length + optionalDecimalDigits.length; - var trimOption = ""; - var tickformat = "0".concat(paddingLength).concat(comma, ".").concat(decimalLength).concat(trimOption).concat(type); - var tickprefix = ChartUtils.convertNumberPrefix(prefix); - var ticksuffix = ChartUtils.convertNumberPrefix(suffix); - return { - tickformat, - tickprefix, - ticksuffix, - automargin: true - }; - } - /** - * Adds tick spacing for an axis that has gapBetweenMajorTicks defined. - * - * @param axisFormat the current axis format, may be null - * @param axis the current axis - * @param isDateType indicates if the columns is a date type - */ - static addTickSpacing(axisFormat, axis, isDateType) { - var { - gapBetweenMajorTicks - } = axis; - if (gapBetweenMajorTicks != null && gapBetweenMajorTicks > 0) { - var updatedFormat = axisFormat || {}; - var tickSpacing = gapBetweenMajorTicks; - if (isDateType) { - tickSpacing = gapBetweenMajorTicks / NANOS_PER_MILLI; - } - if (axis.log) { - tickSpacing = Math.log(tickSpacing); - } - updatedFormat.tickmode = "linear"; - updatedFormat.dtick = tickSpacing; - return updatedFormat; - } - return axisFormat; - } - /** - * Retrieve the data source for a given axis in a chart - * @param chart The chart to get the source for - * @param axis The axis to find the source for - * @returns The first source matching this axis - */ - static getSourceForAxis(chart, axis) { - for (var i = 0; i < chart.series.length; i += 1) { - var series = chart.series[i]; - for (var j = 0; j < series.sources.length; j += 1) { - var source = series.sources[j]; - if (source.axis === axis) { - return source; - } - } - } - return null; - } - /** - * Get visibility setting for the series object - * @param name The series name to get the visibility for - * @param settings Chart settings - * @returns True for visible series and 'legendonly' for hidden - */ - static getSeriesVisibility(name, settings) { - if (settings != null && settings.hiddenSeries != null && settings.hiddenSeries.includes(name)) { - return "legendonly"; - } - return true; - } - /** - * Get hidden labels array from chart settings - * @param settings Chart settings - * @returns Array of hidden series names - */ - static getHiddenLabels(settings) { - if (settings !== null && settings !== void 0 && settings.hiddenSeries) { - return [...settings.hiddenSeries]; - } - return []; - } - /** - * Create a default series data object. Apply styling to the object afterward. - * @returns A simple series data object with no styling - */ - static makeSeriesData(type, mode, name, showLegend) { - var orientation = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : ChartUtils.ORIENTATION.VERTICAL; - return { - type, - mode, - name, - orientation, - showlegend: showLegend !== null && showLegend !== void 0 ? showLegend : void 0 - }; - } - /** - * Get the Plotly marker symbol for the provided Deephaven shape - * Deephaven shapes: https://deephaven.io/enterprise/docs/plotting/visual-formatting/#point-formatting - * Plotly shapes: https://plotly.com/javascript/reference/scattergl/#scattergl-marker-symbol - * Table of plotly shapes: https://plotly.com/python/marker-style/#custom-marker-symbols - * @param deephavenShape Deephaven shape to get the marker symbol for - */ - static getMarkerSymbol(deephavenShape) { - switch (deephavenShape) { - case "SQUARE": - return "square"; - case "CIRCLE": - return "circle"; - case "DIAMOND": - return "diamond"; - case "UP_TRIANGLE": - return "triangle-up"; - case "DOWN_TRIANGLE": - return "triangle-down"; - case "RIGHT_TRIANGLE": - return "triangle-right"; - case "LEFT_TRIANGLE": - return "triangle-left"; - case "ELLIPSE": - case "HORIZONTAL_RECTANGLE": - case "VERTICAL_RECTANGLE": - default: - throw new Error("Unrecognized shape ".concat(deephavenShape)); - } - } - /** - * Get all axes for a given `Figure`. Iterates through all charts axes and concatenates them. - * @param figure Figure to get all axes for - */ - static getAllAxes(figure) { - return figure.charts.reduce((axes, chart) => [...axes, ...chart.axes], []); - } - /** - * Get the axis type map for the figure provided - * @param figure Figure to get the type map for - * @returns Axis type map for the figure provided - */ - static getAxisTypeMap(figure) { - var axes = ChartUtils.getAllAxes(figure); - return ChartUtils.groupArray(axes, "type"); - } - /** - * Retrieve the chart that contains the passed in series from the figure - * @param figure The figure to retrieve the chart from - * @param series The series to get the chart for - */ - static getChartForSeries(figure, series) { - var { - charts - } = figure; - for (var i = 0; i < charts.length; i += 1) { - var _chart = charts[i]; - for (var j = 0; j < _chart.series.length; j += 1) { - if (series === _chart.series[j]) { - return _chart; - } - } - } - return null; - } - /** - * Get an object mapping axis to their ranges - * @param layout The plotly layout object to get the ranges from - * @returns An object mapping the axis name to it's range - */ - static getLayoutRanges(layout) { - var ranges = {}; - var keys2 = Object.keys(layout).filter((key2) => key2.indexOf("axis") >= 0); - for (var i = 0; i < keys2.length; i += 1) { - var key = keys2[i]; - var value2 = layout[key]; - if (isRangedPlotlyAxis(value2)) { - ranges[key] = [...value2.range]; - } - } - return ranges; - } - static getAxisLayoutProperty(axisProperty, axisIndex) { - var axisIndexString = axisIndex > 0 ? "".concat(axisIndex + 1) : ""; - return "".concat(axisProperty !== null && axisProperty !== void 0 ? axisProperty : "", "axis").concat(axisIndexString); - } - /** - * Converts an open or close period to a declimal. e.g '09:30" to 9.5 - * - * @param period the open or close value of the period - */ - static periodToDecimal(period) { - var values = period.split(":"); - return Number(values[0]) + Number(values[1]) / 60; - } - /** - * Converts a decimal to a period. e.g 9.5 to '09:30' - * - * @param decimal the decimal value to - */ - static decimalToPeriod(decimal) { - var hours = Math.floor(decimal); - var minutes = Math.round((decimal - hours) * 60); - return "".concat(hours.toString().padStart(2, "0"), ":").concat(minutes.toString().padStart(2, "0")); - } - /** - * Groups an array and returns a map - * @param array The object to group - * @param property The property name to group by - * @returns A map containing the items grouped by their values for the property - */ - static groupArray(array, property) { - return array.reduce((result, item) => { - var _result$get; - var key = item[property]; - var group = (_result$get = result.get(key)) !== null && _result$get !== void 0 ? _result$get : []; - group.push(item); - result.set(key, group); - return result; - }, /* @__PURE__ */ new Map()); - } - /** - * Parses the colorway value of a theme and returns an array of colors - * Value could be a single string with space separated colors or already be an - * array of strings representing the colorway - * @param colorway The colorway value to normalize - * @returns Colorway array for the theme or undefined - */ - static normalizeColorway(colorway) { - if (colorway == null) { - return; - } - if (Array.isArray(colorway)) { - return colorway; - } - if (typeof colorway === "string") { - return colorway.split(" "); - } - log$2.warn("Unexpected colorway format: ".concat(colorway)); - } - static titleFromSettings(settings) { - var { - series, - xAxis, - title = "".concat((series !== null && series !== void 0 ? series : []).join(", "), " by ").concat(xAxis) - } = settings; - return title; - } - static getTimeZoneDiff(calendarTimeZone, formatterTimeZone) { - return formatterTimeZone ? (calendarTimeZone.standardOffset - formatterTimeZone.standardOffset) / 60 : 0; - } - /** - * Creates closed periods for a partial holiday. - * - * @param holidayPeriods the business periods for the holiday - * @param calendarPeriods the business periods for the calendar - * @returns an array of closed ranges for the partial holiday. Should be the ranges during the regular business hours that are _not_ specified by the holiday periods. - */ - static createClosedRangesForPartialHoliday(holidayPeriods, calendarPeriods) { - var calendarRanges = calendarPeriods.map((period) => [ChartUtils.periodToDecimal(period.open), ChartUtils.periodToDecimal(period.close)]); - calendarRanges.sort((a, b) => a[0] - b[0]); - if (calendarRanges.length === 0) { - calendarRanges.push([0, 24]); - } - var holidayRanges = holidayPeriods.map((period) => [ChartUtils.periodToDecimal(period.open), ChartUtils.periodToDecimal(period.close)]); - holidayRanges.sort((a, b) => a[0] - b[0]); - var closedRanges = []; - for (var c = 0; c < calendarRanges.length; c += 1) { - var calendarRange = calendarRanges[c]; - var lastClose = calendarRange[0]; - for (var h = 0; h < holidayRanges.length; h += 1) { - var holidayRange = holidayRanges[h]; - if (holidayRange[1] > lastClose && holidayRange[0] < calendarRange[1]) { - if (holidayRange[0] > lastClose) { - closedRanges.push([lastClose, holidayRange[0]]); - } - lastClose = holidayRange[1]; - } - } - if (lastClose < calendarRange[1]) { - closedRanges.push([lastClose, calendarRange[1]]); - } - } - return closedRanges; - } - constructor(dh) { - _defineProperty$2(this, "dh", void 0); - _defineProperty$2(this, "daysOfWeek", void 0); - this.dh = dh; - this.daysOfWeek = Object.freeze(dh.calendar.DayOfWeek.values()); - bindAllMethods(this); - } - /** - * Retrieve the axis formats from the provided figure. - * Currently defaults to just the x/y axes. - * @param figure The figure to get the axis formats for - * @param formatter The formatter to use when getting the axis format - * @returns A map of axis layout property names to axis formats - */ - getAxisFormats(figure, formatter) { - var axisFormats = /* @__PURE__ */ new Map(); - var nullFormat = { - tickformat: null, - ticksuffix: null - }; - var allAxes = ChartUtils.getAllAxes(figure); - var axisTypeMap = ChartUtils.groupArray(allAxes, "type"); - var { - charts - } = figure; - for (var i = 0; i < charts.length; i += 1) { - var _chart2 = charts[i]; - for (var j = 0; j < _chart2.series.length; j += 1) { - var series = _chart2.series[j]; - var { - sources - } = series; - var axisSources = sources.filter((source2) => source2.axis); - for (var k = 0; k < axisSources.length; k += 1) { - var source = axisSources[k]; - var { - axis: _axis - } = source; - var { - type: axisType - } = _axis; - var typeAxes = axisTypeMap.get(axisType); - assertNotNull(typeAxes); - var axisIndex = typeAxes.indexOf(_axis); - var axisProperty = this.getAxisPropertyName(axisType); - if (axisProperty != null) { - var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); - if (axisFormats.has(axisLayoutProperty)) { - log$2.debug("".concat(axisLayoutProperty, " already added.")); - } else { - log$2.debug("Adding ".concat(axisLayoutProperty, " to axisFormats.")); - var axisFormat = this.getPlotlyAxisFormat(source, formatter); - if (axisFormat === null) { - axisFormats.set(axisLayoutProperty, nullFormat); - } else { - axisFormats.set(axisLayoutProperty, axisFormat); - var { - businessCalendar - } = _axis; - if (businessCalendar != null) { - axisFormat.rangebreaks = this.createRangeBreaksFromBusinessCalendar(businessCalendar, formatter); - } - if (axisFormats.size === _chart2.axes.length) { - return axisFormats; - } - } - } - } - } - } - } - return axisFormats; - } - /** - * Converts the Iris plot style into a plotly chart type - * @param plotStyle The plotStyle to use, see dh.plot.SeriesPlotStyle - * @param isBusinessTime If the plot is using business time for an axis - * @param allowWebGL If WebGL is allowedd - */ - getPlotlyChartType(plotStyle, isBusinessTime) { - var allowWebGL = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; - var { - dh - } = this; - switch (plotStyle) { - case dh.plot.SeriesPlotStyle.SCATTER: - case dh.plot.SeriesPlotStyle.LINE: - return !isBusinessTime && IS_WEBGL_SUPPORTED && allowWebGL ? "scattergl" : "scatter"; - case dh.plot.SeriesPlotStyle.BAR: - case dh.plot.SeriesPlotStyle.STACKED_BAR: - return "bar"; - case dh.plot.SeriesPlotStyle.PIE: - return "pie"; - case dh.plot.SeriesPlotStyle.TREEMAP: - return "treemap"; - case dh.plot.SeriesPlotStyle.HISTOGRAM: - return "histogram"; - case dh.plot.SeriesPlotStyle.OHLC: - return "ohlc"; - default: - return void 0; - } - } - /** - * Converts the Iris plot style into a plotly chart mode - * @param plotStyle The plotStyle to use, see dh.plot.SeriesPlotStyle.* - * @param areLinesVisible Whether lines are visible or not - * @param areShapesVisible Whether shapes are visible or not - */ - getPlotlyChartMode(plotStyle, areLinesVisible, areShapesVisible) { - var { - dh - } = this; - var modes = /* @__PURE__ */ new Set(); - switch (plotStyle) { - case dh.plot.SeriesPlotStyle.SCATTER: - if (areLinesVisible !== null && areLinesVisible !== void 0 ? areLinesVisible : false) { - modes.add(ChartUtils.MODE_LINES); - } - if (areShapesVisible !== null && areShapesVisible !== void 0 ? areShapesVisible : true) { - modes.add(ChartUtils.MODE_MARKERS); - } - break; - case dh.plot.SeriesPlotStyle.LINE: - if (areLinesVisible !== null && areLinesVisible !== void 0 ? areLinesVisible : true) { - modes.add(ChartUtils.MODE_LINES); - } - if (areShapesVisible !== null && areShapesVisible !== void 0 ? areShapesVisible : false) { - modes.add(ChartUtils.MODE_MARKERS); - } - break; - } - return modes.size > 0 ? [...modes].join("+") : void 0; - } - /** - * Get the property to set on the series data for plotly - * @param plotStyle The plot style of the series - * @param sourceType The source type for the series - */ - getPlotlyProperty(plotStyle, sourceType) { - var { - dh - } = this; - switch (plotStyle) { - case dh.plot.SeriesPlotStyle.PIE: - switch (sourceType) { - case dh.plot.SourceType.X: - return "labels"; - case dh.plot.SourceType.Y: - return "values"; - } - break; - case dh.plot.SeriesPlotStyle.OHLC: - switch (sourceType) { - case dh.plot.SourceType.TIME: - return "x"; - } - break; - case dh.plot.SeriesPlotStyle.TREEMAP: - switch (sourceType) { - case dh.plot.SourceType.X: - return "ids"; - case dh.plot.SourceType.Y: - return "values"; - case dh.plot.SourceType.LABEL: - return "labels"; - case dh.plot.SourceType.PARENT: - return "parents"; - case dh.plot.SourceType.COLOR: - return "marker.colors"; - } - break; - } - switch (sourceType) { - case dh.plot.SourceType.X: - return "x"; - case dh.plot.SourceType.Y: - return "y"; - case dh.plot.SourceType.Z: - return "z"; - case dh.plot.SourceType.X_LOW: - return "xLow"; - case dh.plot.SourceType.X_HIGH: - return "xHigh"; - case dh.plot.SourceType.Y_LOW: - return "yLow"; - case dh.plot.SourceType.Y_HIGH: - return "yHigh"; - case dh.plot.SourceType.TIME: - return "time"; - case dh.plot.SourceType.OPEN: - return "open"; - case dh.plot.SourceType.HIGH: - return "high"; - case dh.plot.SourceType.LOW: - return "low"; - case dh.plot.SourceType.CLOSE: - return "close"; - case dh.plot.SourceType.SHAPE: - return "shape"; - case dh.plot.SourceType.SIZE: - return "size"; - case dh.plot.SourceType.LABEL: - return "label"; - case dh.plot.SourceType.COLOR: - return "color"; - case dh.plot.SourceType.PARENT: - return "parent"; - case dh.plot.SourceType.HOVER_TEXT: - return "hovertext"; - case dh.plot.SourceType.TEXT: - return "text"; - default: - throw new Error("Unrecognized source type: ".concat(sourceType)); - } - } - getPlotlySeriesOrientation(series) { - var _sources$, _sources$$axis; - var { - dh - } = this; - var { - sources - } = series; - if (sources.length === 2 && ((_sources$ = sources[0]) === null || _sources$ === void 0 ? void 0 : (_sources$$axis = _sources$.axis) === null || _sources$$axis === void 0 ? void 0 : _sources$$axis.type) === dh.plot.AxisType.Y) { - return ChartUtils.ORIENTATION.HORIZONTAL; - } - return ChartUtils.ORIENTATION.VERTICAL; - } - /** - * Create a data series (trace) for use with plotly - * @param series The series to create the series data with - * @param axisTypeMap The map of axes grouped by type - * @param seriesVisibility Visibility setting for the series - * @returns The series data (trace) object for use with plotly. - */ - makeSeriesDataFromSeries(series, axisTypeMap, seriesVisibility) { - var showLegend = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; - var allowWebGL = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : true; - var { - name, - isLinesVisible, - isShapesVisible, - plotStyle, - lineColor, - shapeColor, - sources, - shape, - shapeSize - } = series; - var isBusinessTime = sources.some((source) => { - var _source$axis; - return (_source$axis = source.axis) === null || _source$axis === void 0 ? void 0 : _source$axis.businessCalendar; - }); - var type = this.getChartType(plotStyle, isBusinessTime, allowWebGL); - var mode = this.getPlotlyChartMode(plotStyle, isLinesVisible !== null && isLinesVisible !== void 0 ? isLinesVisible : void 0, isShapesVisible !== null && isShapesVisible !== void 0 ? isShapesVisible : void 0); - var orientation = this.getPlotlySeriesOrientation(series); - var seriesData = ChartUtils.makeSeriesData(type, mode, name, showLegend, orientation); - this.addSourcesToSeriesData(seriesData, plotStyle, sources, axisTypeMap); - this.addStylingToSeriesData(seriesData, plotStyle, lineColor, shapeColor, shape, shapeSize, seriesVisibility); - return seriesData; - } - addSourcesToSeriesData(seriesDataParam, plotStyle, sources, axisTypeMap) { - var seriesData = seriesDataParam; - for (var k = 0; k < sources.length; k += 1) { - var source = sources[k]; - var { - axis: _axis2, - type: sourceType - } = source; - var dataAttributeName = this.getPlotlyProperty(plotStyle, sourceType); - lodashExports.set(seriesData, dataAttributeName, []); - var axisProperty = _axis2 != null ? this.getAxisPropertyName(_axis2.type) : null; - if (axisProperty != null) { - var axes = axisTypeMap.get(_axis2.type); - if (axes) { - var axisIndex = axes.indexOf(_axis2); - var axisIndexString = axisIndex > 0 ? "".concat(axisIndex + 1) : ""; - seriesData["".concat(axisProperty, "axis")] = "".concat(axisProperty).concat(axisIndexString); - } - } - } - } - addStylingToSeriesData(seriesDataParam, plotStyle) { - var lineColor = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null; - var shapeColor = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : null; - var shape = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : null; - var shapeSize = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : null; - var seriesVisibility = arguments.length > 6 && arguments[6] !== void 0 ? arguments[6] : null; - var { - dh - } = this; - var seriesData = seriesDataParam; - seriesData.marker = { - line: {} - }; - seriesData.line = { - width: 1 - // default line width for lines, should eventually be able to override - }; - if (plotStyle === dh.plot.SeriesPlotStyle.AREA) { - seriesData.fill = "tozeroy"; - } else if (plotStyle === dh.plot.SeriesPlotStyle.STACKED_AREA) { - seriesData.stackgroup = "stack"; - } else if (plotStyle === dh.plot.SeriesPlotStyle.STEP) { - seriesData.line.shape = "hv"; - } else if (plotStyle === dh.plot.SeriesPlotStyle.HISTOGRAM) { - seriesData.width = []; - } else if (plotStyle === dh.plot.SeriesPlotStyle.PIE) { - seriesData.textinfo = "label+percent"; - } else if (plotStyle === dh.plot.SeriesPlotStyle.TREEMAP) { - seriesData.hoverinfo = "text"; - seriesData.textinfo = "label+text"; - seriesData.tiling = { - packing: "squarify", - pad: 0 - }; - seriesData.textposition = "middle center"; - } - if (lineColor != null) { - if (plotStyle === dh.plot.SeriesPlotStyle.BAR) { - seriesData.marker.color = lineColor; - } else { - seriesData.line.color = lineColor; - } - } - if (shapeColor != null) { - seriesData.marker.color = shapeColor; - } - if (shape != null && shape.length > 0) { - try { - seriesData.marker.symbol = ChartUtils.getMarkerSymbol(shape); - } catch (e) { - log$2.warn("Unable to handle shape", shape, ":", e); - } - } - if (shapeSize != null) { - seriesData.marker.size = shapeSize * ChartUtils.DEFAULT_MARKER_SIZE; - } - if (seriesVisibility != null && plotStyle !== dh.plot.SeriesPlotStyle.PIE) { - seriesData.visible = seriesVisibility; - } - } - getChartType(plotStyle, isBusinessTime) { - var allowWebGL = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : true; - var { - dh - } = this; - switch (plotStyle) { - case dh.plot.SeriesPlotStyle.HISTOGRAM: - return "bar"; - default: - return this.getPlotlyChartType(plotStyle, isBusinessTime, allowWebGL); - } - } - /** - * Return the plotly axis property name - * @param axisType The axis type to get the property name for - */ - getAxisPropertyName(axisType) { - var { - dh - } = this; - switch (axisType) { - case dh.plot.AxisType.X: - return "x"; - case dh.plot.AxisType.Y: - return "y"; - default: - return null; - } - } - /** - * Returns the plotly "side" value for the provided axis position - * @param axisPosition The Iris AxisPosition of the axis - */ - getAxisSide(axisPosition) { - var { - dh - } = this; - switch (axisPosition) { - case dh.plot.AxisPosition.BOTTOM: - return "bottom"; - case dh.plot.AxisPosition.TOP: - return "top"; - case dh.plot.AxisPosition.LEFT: - return "left"; - case dh.plot.AxisPosition.RIGHT: - return "right"; - default: - return void 0; - } - } - /** - * Update the layout with all the axes information for the provided figure - * @param figure Figure to update the axes for - * @param layoutParam Layout object to update in place - * @param chartAxisRangeParser Function to retrieve the axis range parser - * @param plotWidth Width of the plot in pixels - * @param plotHeight Height of the plot in pixels - */ - updateFigureAxes(layoutParam, figure, chartAxisRangeParser) { - var plotWidth = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; - var plotHeight = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0; - var layout = layoutParam; - var figureAxes = ChartUtils.getAllAxes(figure); - for (var i = 0; i < figure.charts.length; i += 1) { - var _chart3 = figure.charts[i]; - var axisRangeParser = chartAxisRangeParser === null || chartAxisRangeParser === void 0 ? void 0 : chartAxisRangeParser(_chart3); - var bounds = this.getChartBounds(figure, _chart3, plotWidth, plotHeight); - this.updateLayoutAxes(layout, _chart3.axes, figureAxes, plotWidth, plotHeight, bounds, axisRangeParser); - } - this.removeStaleAxes(layout, figureAxes); - } - getChartBounds(figure, chart, plotWidth, plotHeight) { - var _axisPositionMap$get; - var { - dh - } = this; - var { - cols, - rows - } = figure; - var { - column, - colspan, - row, - rowspan - } = chart; - var endColumn = column + colspan; - var endRow = row + rowspan; - var columnSize = 1 / cols; - var rowSize = 1 / rows; - var xMarginSize = ChartUtils.AXIS_SIZE_PX / plotWidth; - var yMarginSize = ChartUtils.AXIS_SIZE_PX / plotHeight; - var bounds = { - // Need to invert the row positioning so the first one defined shows up on top instead of the bottom, since coordinates start in bottom left - bottom: (rows - endRow) * rowSize + (endRow < rows ? yMarginSize / 2 : 0), - top: (rows - row) * rowSize - (row > 0 ? yMarginSize / 2 : 0), - left: column * columnSize + (column > 0 ? xMarginSize / 2 : 0), - right: endColumn * columnSize - (endColumn < cols ? xMarginSize / 2 : 0) - }; - var axisPositionMap = ChartUtils.groupArray(chart.axes, "position"); - var rightAxes = (_axisPositionMap$get = axisPositionMap.get(dh.plot.AxisPosition.RIGHT)) !== null && _axisPositionMap$get !== void 0 ? _axisPositionMap$get : []; - if (rightAxes.length > 0) { - if (plotWidth > 0) { - bounds.right -= (bounds.right - bounds.left) * Math.max(0, Math.min(ChartUtils.LEGEND_WIDTH_PX / plotWidth, ChartUtils.MAX_LEGEND_SIZE)); - } else { - bounds.right -= (bounds.right - bounds.left) * ChartUtils.DEFAULT_AXIS_SIZE; - } - } - return bounds; - } - getPlotlyDateFormat(formatter, columnType, formatPattern) { - var { - dh - } = this; - var tickformat = formatPattern == null ? void 0 : formatPattern.replace("%", "%%").replace(/S{9}/g, "%9f").replace(/S{8}/g, "%8f").replace(/S{7}/g, "%7f").replace(/S{6}/g, "%6f").replace(/S{5}/g, "%5f").replace(/S{4}/g, "%4f").replace(/S{3}/g, "%3f").replace(/S{2}/g, "%2f").replace(/S{1}/g, "%1f").replace(/y{4}/g, "%Y").replace(/y{2}/g, "%y").replace(/M{4}/g, "%B").replace(/M{3}/g, "%b").replace(/M{2}/g, "%m").replace(/M{1}/g, "%-m").replace(/E{4,}/g, "%A").replace(/E{1,}/g, "%a").replace(/d{2}/g, "%d").replace(/([^%]|^)d{1}/g, "$1%-d").replace(/H{2}/g, "%H").replace(/h{2}/g, "%I").replace(/h{1}/g, "%-I").replace(/m{2}/g, "%M").replace(/s{2}/g, "%S").replace("'T'", "T").replace(" z", ""); - var ticksuffix; - var dataFormatter = formatter === null || formatter === void 0 ? void 0 : formatter.getColumnTypeFormatter(columnType); - if (dataFormatter != null && isDateTimeColumnFormatter(dataFormatter) && dataFormatter.dhTimeZone != null && dataFormatter.showTimeZone) { - ticksuffix = dh.i18n.DateTimeFormat.format(" z", /* @__PURE__ */ new Date(), dataFormatter.dhTimeZone); - } - return { - tickformat, - ticksuffix, - automargin: true - }; - } - /** - * Gets the plotly axis formatting information from the source passed in - * @param source The Source to get the formatter information from - * @param formatter The current formatter for formatting data - */ - getPlotlyAxisFormat(source) { - var formatter = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : null; - var { - dh - } = this; - var { - axis, - columnType - } = source; - var { - formatPattern - } = axis; - var axisFormat = null; - if (TableUtils.isDateType(columnType)) { - axisFormat = this.getPlotlyDateFormat(formatter, columnType, formatPattern); - axisFormat = ChartUtils.addTickSpacing(axisFormat, axis, true); - } else if (TableUtils.isNumberType(columnType)) { - axisFormat = ChartUtils.getPlotlyNumberFormat(formatter, columnType, formatPattern); - axisFormat = ChartUtils.addTickSpacing(axisFormat, axis, false); - } - if (axis.formatType === dh.plot.AxisFormatType.CATEGORY) { - if (axisFormat) { - axisFormat.type = "category"; - } else { - axisFormat = { - type: "category", - tickformat: void 0, - ticksuffix: void 0 - }; - } - } - return axisFormat; - } - /** - * Updates the axes positions and sizes in the layout object provided. - * If the axis did not exist in the layout previously, it is created and added. - * Any axis that no longer exists in axes is removed. - * With Downsampling enabled, will also update the range on the axis itself as appropriate - * @param layoutParam The layout object to update - * @param chartAxes The chart axes to update the layout with - * @param figureAxes All figure axes to update the layout with - * @param plotWidth The width of the plot to calculate the axis sizes for - * @param plotHeight The height of the plot to calculate the axis sizes for - * @param bounds The bounds for this set of axes - * @param axisRangeParser A function to retrieve the range parser for a given axis - */ - updateLayoutAxes(layoutParam, chartAxes, figureAxes) { - var plotWidth = arguments.length > 3 && arguments[3] !== void 0 ? arguments[3] : 0; - var plotHeight = arguments.length > 4 && arguments[4] !== void 0 ? arguments[4] : 0; - var bounds = arguments.length > 5 && arguments[5] !== void 0 ? arguments[5] : { - left: 0, - top: 0, - right: 1, - bottom: 1 - }; - var axisRangeParser = arguments.length > 6 ? arguments[6] : void 0; - var { - dh - } = this; - var xAxisSize = plotWidth > 0 ? Math.max(ChartUtils.MIN_AXIS_SIZE, Math.min(ChartUtils.AXIS_SIZE_PX / plotHeight, ChartUtils.MAX_AXIS_SIZE)) : ChartUtils.DEFAULT_AXIS_SIZE; - var yAxisSize = plotHeight > 0 ? Math.max(ChartUtils.MIN_AXIS_SIZE, Math.min(ChartUtils.AXIS_SIZE_PX / plotWidth, ChartUtils.MAX_AXIS_SIZE)) : ChartUtils.DEFAULT_AXIS_SIZE; - var layout = layoutParam; - var axisPositionMap = ChartUtils.groupArray(chartAxes, "position"); - var axisTypeMap = ChartUtils.groupArray(chartAxes, "type"); - var axisTypes = [...axisTypeMap.keys()]; - var figureAxisTypeMap = ChartUtils.groupArray(figureAxes, "type"); - for (var j = 0; j < axisTypes.length; j += 1) { - var axisType = axisTypes[j]; - var axisProperty = this.getAxisPropertyName(axisType); - if (axisProperty != null) { - var typeAxes = axisTypeMap.get(axisType); - var figureTypeAxes = figureAxisTypeMap.get(axisType); - var isYAxis = axisType === dh.plot.AxisType.Y; - var plotSize = isYAxis ? plotHeight : plotWidth; - assertNotNull(typeAxes); - assertNotNull(figureTypeAxes); - for (var chartAxisIndex = 0; chartAxisIndex < typeAxes.length; chartAxisIndex += 1) { - var _axis3 = typeAxes[chartAxisIndex]; - var figureAxisIndex = figureTypeAxes.indexOf(_axis3); - var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, figureAxisIndex); - if (layout[axisLayoutProperty] == null) { - layout[axisLayoutProperty] = {}; - } - var layoutAxis = layout[axisLayoutProperty]; - if (layoutAxis != null) { - this.updateLayoutAxis(layoutAxis, _axis3, chartAxisIndex, axisPositionMap, xAxisSize, yAxisSize, bounds); - var { - range: _range, - autorange - } = layoutAxis; - if (axisRangeParser != null && _range !== void 0 && (autorange === void 0 || autorange === false)) { - var rangeParser = axisRangeParser(_axis3); - var [rangeStart, rangeEnd] = rangeParser(_range); - log$2.debug("Setting downsample range", plotSize, rangeStart, rangeEnd); - _axis3.range(plotSize, rangeStart, rangeEnd); - } else { - _axis3.range(plotSize); - } - } - } - } - } - } - /** - * Remove any axes from the layout param that no longer belong to any series - * @param layoutParam Layout object to remove stale axes from - * @param axes All axes in the figure - */ - removeStaleAxes(layoutParam, axes) { - var layout = layoutParam; - var figureAxisTypeMap = ChartUtils.groupArray(axes, "type"); - var figureAxisTypes = [...figureAxisTypeMap.keys()]; - for (var i = 0; i < figureAxisTypes.length; i += 1) { - var axisType = figureAxisTypes[i]; - var typeAxes = figureAxisTypeMap.get(axisType); - assertNotNull(typeAxes); - var axisIndex = typeAxes.length; - var axisProperty = this.getAxisPropertyName(axisType); - if (axisProperty != null) { - var axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); - while (layout[axisLayoutProperty] != null) { - delete layout[axisLayoutProperty]; - axisIndex += 1; - axisLayoutProperty = ChartUtils.getAxisLayoutProperty(axisProperty, axisIndex); - } - } - } - } - /** - * Updates the layout axis object in place - * @param layoutAxisParam The plotly layout axis param - * @param axis The Iris Axis to update the plotly layout with - * @param axisIndex The type index for this axis - * @param axisPositionMap All the axes mapped by position - * @param axisSize The size of each axis in percent - * @param bounds The bounds of the axes domains - */ - updateLayoutAxis(layoutAxisParam, axis, axisIndex, axisPositionMap, xAxisSize, yAxisSize, bounds) { - var _axis$label; - var { - dh - } = this; - var isYAxis = axis.type === dh.plot.AxisType.Y; - var axisSize = isYAxis ? yAxisSize : xAxisSize; - var layoutAxis = layoutAxisParam; - var label = (_axis$label = axis.label) !== null && _axis$label !== void 0 ? _axis$label : ""; - if (layoutAxis.title !== void 0 && typeof layoutAxis.title !== "string") { - layoutAxis.title.text = label; - } else { - layoutAxis.title = { - text: label - }; - } - if (axis.log) { - layoutAxis.type = "log"; - } - layoutAxis.side = this.getAxisSide(axis.position); - if (axisIndex > 0) { - var _this$getAxisProperty, _axisPositionMap$get2; - layoutAxis.overlaying = (_this$getAxisProperty = this.getAxisPropertyName(axis.type)) !== null && _this$getAxisProperty !== void 0 ? _this$getAxisProperty : void 0; - var positionAxes = (_axisPositionMap$get2 = axisPositionMap.get(axis.position)) !== null && _axisPositionMap$get2 !== void 0 ? _axisPositionMap$get2 : []; - var sideIndex = positionAxes.indexOf(axis); - if (sideIndex > 0) { - layoutAxis.anchor = "free"; - if (axis.position === dh.plot.AxisPosition.RIGHT) { - layoutAxis.position = bounds.right + (sideIndex - positionAxes.length + 1) * axisSize; - } else if (axis.position === dh.plot.AxisPosition.TOP) { - layoutAxis.position = bounds.top + (sideIndex - positionAxes.length + 1) * axisSize; - } else if (axis.position === dh.plot.AxisPosition.BOTTOM) { - layoutAxis.position = bounds.bottom + (positionAxes.length - sideIndex + 1) * axisSize; - } else if (axis.position === dh.plot.AxisPosition.LEFT) { - layoutAxis.position = bounds.left + (positionAxes.length - sideIndex + 1) * axisSize; - } - } - } else if (axis.type === dh.plot.AxisType.X) { - var leftAxes = axisPositionMap.get(dh.plot.AxisPosition.LEFT) || []; - var rightAxes = axisPositionMap.get(dh.plot.AxisPosition.RIGHT) || []; - var left = Math.max(bounds.left, bounds.left + (leftAxes.length - 1) * yAxisSize); - var right = Math.min(bounds.right - (rightAxes.length - 1) * yAxisSize, bounds.right); - layoutAxis.domain = [left, right]; - } else if (axis.type === dh.plot.AxisType.Y) { - var bottomAxes = axisPositionMap.get(dh.plot.AxisPosition.BOTTOM) || []; - var topAxes = axisPositionMap.get(dh.plot.AxisPosition.TOP) || []; - var bottom = Math.max(bounds.bottom, bounds.bottom + (bottomAxes.length - 1) * xAxisSize); - var top = Math.min(bounds.top - (topAxes.length - 1) * xAxisSize, bounds.top); - layoutAxis.domain = [bottom, top]; - } - var { - minRange, - maxRange, - log: logAxis - } = axis; - if (!Number.isNaN(minRange) || !Number.isNaN(maxRange)) { - layoutAxis.autorangeoptions = {}; - if (!Number.isNaN(minRange)) { - layoutAxis.autorangeoptions.minallowed = logAxis ? Math.log10(minRange) : minRange; - } - if (!Number.isNaN(maxRange)) { - layoutAxis.autorangeoptions.maxallowed = logAxis ? Math.log10(maxRange) : maxRange; - } - } - } - /** - * Creates the bounds for the periods specified. - * For example, if you pass in [['09:00', '17:00']], it will return [17, 9] (closing at 5pm, opening at 9am the next day) - * If you pass [['09:00', '12:00'], ['13:00', '17:00']], it will return [12, 13] (closing at noon, opening at 1pm) and [17, 9] (closing at 5pm, opening at 9am the next day) - * @param periods Periods to map - * @param timeZoneDiff Time zone difference in hours - * @returns Bounds for the periods in plotly format - */ - // eslint-disable-next-line class-methods-use-this - createBoundsFromPeriods(periods) { - var timeZoneDiff = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; - if (periods.length === 0) { - return []; - } - var numberPeriods = periods.map((period2) => [(ChartUtils.periodToDecimal(period2.open) + timeZoneDiff) % 24, (ChartUtils.periodToDecimal(period2.close) + timeZoneDiff) % 24]).sort((a, b) => a[0] - b[0]); - var bounds = []; - for (var i = 0; i < numberPeriods.length; i += 1) { - var period = numberPeriods[i]; - var nextPeriod = numberPeriods[(i + 1) % numberPeriods.length]; - bounds.push([period[1], nextPeriod[0]]); - } - return bounds; - } - /** - * Creates range breaks for plotly from business periods. - * @param periods Business periods to create the breaks for - * @param timeZoneDiff Time zone difference in hours - * @returns Plotly range breaks for the business periods - */ - createBreaksFromPeriods(periods) { - var timeZoneDiff = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : 0; - var bounds = this.createBoundsFromPeriods(periods, timeZoneDiff); - return bounds.map((bound) => ({ - pattern: "hour", - bounds: bound - })); - } - /** - * Creates range break bounds for plotly from business days. - * For example a standard business week of ['MONDAY','TUESDAY','WEDNESDAY','THURSDAY','FRIDAY'] - * will result in [[6,1]] meaning close on Saturday and open on Monday. - * If you remove Wednesday from the array, then you get two closures [[6, 1], [3, 4]] - * - * @param businessDays the days to display on the x-axis - */ - createBoundsFromDays(businessDays) { - var weekLength = this.daysOfWeek.length; - if (businessDays.length === weekLength) { - return []; - } - var businessDaysInt = businessDays.map((day) => this.daysOfWeek.indexOf(day)); - var businessDaysSet = new Set(businessDaysInt); - var closedDays = /* @__PURE__ */ new Set(); - for (var i = 0; i < weekLength; i += 1) { - if (!businessDaysSet.has(i) && businessDaysSet.has((i - 1 + weekLength) % weekLength)) { - closedDays.add(i); - } - } - var boundsArray = []; - closedDays.forEach((closedDay) => { - for (var _i = 0; _i < weekLength; _i += 1) { - var adjustedDay = (closedDay + _i) % weekLength; - if (businessDaysSet.has(adjustedDay)) { - boundsArray.push([closedDay, adjustedDay]); - return; - } - } - throw new Error("Unable to find open day for closed day ".concat(closedDay, ", businessDays: ").concat(businessDays)); - }); - return boundsArray; - } - /** - * Breaks in plotly for business days - * @param businessDays Business days to create the breaks for - * @returns Plotly range breaks for the business days - */ - createBreaksFromDays(businessDays) { - var bounds = this.createBoundsFromDays(businessDays); - return bounds.map((bound) => ({ - pattern: "day of week", - bounds: bound - })); - } - /** - * Creates range breaks for plotly from a business calendar. - * @param businessCalendar Calendar to create the breaks from - * @param formatter Formatter to use for time zones - * @returns Plotly Rangebreaks for the business calendar - */ - createRangeBreaksFromBusinessCalendar(businessCalendar, formatter) { - var rangebreaks = []; - var { - businessPeriods, - businessDays, - holidays, - timeZone: calendarTimeZone - } = businessCalendar; - var typeFormatter = formatter === null || formatter === void 0 ? void 0 : formatter.getColumnTypeFormatter(BUSINESS_COLUMN_TYPE); - var formatterTimeZone; - if (isDateTimeColumnFormatter(typeFormatter)) { - formatterTimeZone = typeFormatter.dhTimeZone; - } - var timeZoneDiff = ChartUtils.getTimeZoneDiff(calendarTimeZone, formatterTimeZone); - if (holidays.length > 0) { - rangebreaks.push(...this.createRangeBreakValuesFromHolidays(holidays, calendarTimeZone, formatterTimeZone, businessCalendar)); - } - rangebreaks.push(...this.createBreaksFromPeriods(businessPeriods, timeZoneDiff)); - rangebreaks.push(...this.createBreaksFromDays(businessDays)); - return rangebreaks; - } - /** - * Creates an array of range breaks for all holidays. - * - * @param holidays an array of holidays - * @param calendarTimeZone the time zone for the business calendar - * @param formatterTimeZone the time zone for the formatter - * @param calendar the calendar the holidays are from - */ - createRangeBreakValuesFromHolidays(holidays, calendarTimeZone, formatterTimeZone, calendar) { - var fullHolidays = []; - var partialHolidays = []; - holidays.forEach((holiday) => { - if (holiday.businessPeriods.length > 0) { - partialHolidays.push(...this.createPartialHoliday(holiday, calendarTimeZone, formatterTimeZone, calendar)); - } else { - fullHolidays.push(this.createFullHoliday(holiday, calendarTimeZone, formatterTimeZone)); - } - }); - return [{ - values: fullHolidays - }, ...partialHolidays]; - } - /** - * Creates the range break value for a full holiday. A full holiday is day that has no business periods. - * - * @param holiday the full holiday - * @param calendarTimeZone the time zone for the business calendar - * @param formatterTimeZone the time zone for the formatter - */ - createFullHoliday(holiday, calendarTimeZone, formatterTimeZone) { - return this.adjustDateForTimeZone("".concat(holiday.date.toString(), " 00:00:00.000000"), calendarTimeZone, formatterTimeZone); - } - /** - * Creates the range break for a partial holiday. A partial holiday is holiday with business periods - * that are different than the default business periods. - * - * @param holiday the partial holiday - * @param calendarTimeZone the time zone for the business calendar - * @param formatterTimeZone the time zone for the formatter - * @param calendar the calendar the holiday is from. Used to check against the default business periods to ensure this holiday needs to be specified - * - * @returns an array of range breaks for the partial holiday - */ - createPartialHoliday(holiday, calendarTimeZone, formatterTimeZone, calendar) { - var _calendar$businessPer; - if (holiday.businessPeriods.length === 0) { - return []; - } - var dateString = holiday.date.toString(); - if (calendar) { - var dayOfWeek = new Date(dateString).getDay(); - var isBusinessDay = calendar.businessDays.includes(this.daysOfWeek[dayOfWeek]); - if (!isBusinessDay) { - return []; - } - } - var closedPeriods = ChartUtils.createClosedRangesForPartialHoliday(holiday.businessPeriods, (_calendar$businessPer = calendar === null || calendar === void 0 ? void 0 : calendar.businessPeriods) !== null && _calendar$businessPer !== void 0 ? _calendar$businessPer : []); - var rangeBreaks = []; - for (var i = 0; i < closedPeriods.length; i += 1) { - var [closeStart, closeEnd] = closedPeriods[i]; - if (closeStart !== closeEnd) { - var values = [this.adjustDateForTimeZone("".concat(dateString, " ").concat(ChartUtils.decimalToPeriod(closeStart), ":00.000000"), calendarTimeZone, formatterTimeZone)]; - var dvalue = MILLIS_PER_HOUR * (closeEnd - closeStart); - rangeBreaks.push({ - values, - dvalue - }); - } - } - return rangeBreaks; - } - /** - * Adjusts a date string from the calendar time zone to the formatter time zone. - * - * @param dateString the date string - * @param calendarTimeZone the time zone for the business calendar - * @param formatterTimeZone the time zone for the formatter - */ - adjustDateForTimeZone(dateString, calendarTimeZone, formatterTimeZone) { - if (formatterTimeZone && formatterTimeZone.standardOffset !== calendarTimeZone.standardOffset) { - return this.unwrapValue(this.wrapValue(dateString, BUSINESS_COLUMN_TYPE, calendarTimeZone), formatterTimeZone); - } - return dateString; - } - /** - * Creates the Figure settings from the Chart Builder settings - * This should be deprecated at some point, and have Chart Builder create the figure settings directly. - * This logic will still need to exist to translate existing charts, but could be part of a migration script - * to translate the data. - * Change when we decide to add more functionality to the Chart Builder. - * @param settings The chart builder settings - * @param settings.title The title for this figure - * @param settings.xAxis The name of the column to use for the x-axis - * @param settings.series The name of the columns to use for the series of this figure - * @param settings.type The plot style for this figure - */ - makeFigureSettings(settings, table) { - var { - dh - } = this; - var { - series, - xAxis: settingsAxis, - type - } = settings; - var title = ChartUtils.titleFromSettings(settings); - var xAxis = { - formatType: "".concat(dh.plot.AxisFormatType.NUMBER), - type: "".concat(dh.plot.AxisType.X), - position: "".concat(dh.plot.AxisPosition.BOTTOM) - }; - var yAxis = { - formatType: "".concat(dh.plot.AxisFormatType.NUMBER), - type: "".concat(dh.plot.AxisType.Y), - position: "".concat(dh.plot.AxisPosition.LEFT) - }; - return { - charts: [{ - chartType: "".concat(dh.plot.ChartType.XY), - axes: [xAxis, yAxis], - series: (series !== null && series !== void 0 ? series : []).map((name) => ({ - plotStyle: "".concat(type), - name, - dataSources: [{ - type: "".concat(dh.plot.SourceType.X), - columnName: settingsAxis !== null && settingsAxis !== void 0 ? settingsAxis : "", - axis: xAxis, - table - }, { - type: "".concat(dh.plot.SourceType.Y), - columnName: name, - axis: yAxis, - table - }] - })) - }], - title - }; - } - /** - * Unwraps a value provided from API to a value plotly can understand - * Eg. Unwraps DateWrapper, LongWrapper objects. - */ - unwrapValue(value2, timeZone) { - var { - dh - } = this; - if (value2 != null) { - if (isDateWrapper(value2)) { - return dh.i18n.DateTimeFormat.format(ChartUtils.DATE_FORMAT, value2, timeZone); - } - if (isLongWrapper(value2)) { - return value2.asNumber(); - } - } - return value2; - } - /** - * - * @param value The value to wrap up - * @param columnType The type of column this value is from - * @param timeZone The time zone if applicable - */ - wrapValue(value2, columnType) { - var timeZone = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : null; - var { - dh - } = this; - if (TableUtils.isDateType(columnType) && typeof value2 === "string") { - var text = value2; - var format = ChartUtils.DATE_FORMAT.substr(0, value2.length); - var date = dh.i18n.DateTimeFormat.parse(format, text); - if (!timeZone) { - return date; - } - var tzFormat = "".concat(format, " Z"); - var estimatedOffset = dh.i18n.DateTimeFormat.format("Z", date, timeZone); - var estimatedDate = dh.i18n.DateTimeFormat.parse(tzFormat, "".concat(text, " ").concat(estimatedOffset)); - var offset = dh.i18n.DateTimeFormat.format("Z", estimatedDate, timeZone); - return dh.i18n.DateTimeFormat.parse(tzFormat, "".concat(text, " ").concat(offset)); - } - return value2; - } - makeLayoutAxis(type, theme) { - var { - dh - } = this; - var axis = { - automargin: true, - gridcolor: theme.gridcolor, - linecolor: theme.linecolor, - rangeslider: { - visible: false - }, - showline: true, - ticks: "outside", - ticklen: 5, - // act as padding, can't find a tick padding - tickcolor: theme.paper_bgcolor, - // hide ticks as padding - tickfont: { - color: theme.zerolinecolor - }, - title: { - font: { - color: theme.title_color - } - }, - legend: { - font: { - color: theme.legend_color - } - } - }; - if (type === dh.plot.AxisType.X) { - Object.assign(axis, { - showgrid: true - }); - } else if (type === dh.plot.AxisType.Y) { - Object.assign(axis, { - zerolinecolor: theme.zerolinecolor, - zerolinewidth: 2 - }); - } - return axis; - } - /** - * Creates a plotly layout template object based on a given theme. - * See https://plotly.com/javascript/reference/layout/#layout-template - * @param theme The theme to use for the layout template - * @returns The layout template object - */ - makeDefaultTemplate(theme) { - var { - error_band_line_color, - ohlc_increasing, - ohlc_decreasing, - title_color, - indicator_increasing, - indicator_decreasing, - indicator_gauge - } = theme; - return { - data: { - bar: [{ - marker: { - line: { - color: "transparent" - } - } - }], - scatter: [{ - error_x: { - color: error_band_line_color - }, - error_y: { - color: error_band_line_color - } - }], - ohlc: [{ - increasing: { - line: { - color: ohlc_increasing - } - }, - decreasing: { - line: { - color: ohlc_decreasing - } - } - }], - pie: [{ - outsidetextfont: { - color: title_color - } - }], - treemap: [{ - outsidetextfont: { - color: title_color - } - }], - indicator: [{ - title: { - font: { - color: title_color - } - }, - delta: { - decreasing: { - color: indicator_decreasing - }, - increasing: { - color: indicator_increasing - } - }, - gauge: { - bar: { - color: indicator_gauge - } - } - }] - }, - /* eslint-enable camelcase */ - layout: this.makeDefaultLayout(theme) - }; - } - /** - * Creates a plotly layout object based on a given theme. - * See https://plotly.com/javascript/reference/layout/ - * @param theme The theme to use for the layout - */ - makeDefaultLayout(theme) { - var { - dh - } = this; - var { - /* Used as top level properties of `Layout` */ - /* eslint-disable camelcase */ - paper_bgcolor, - plot_bgcolor, - title_color, - coastline_color, - land_color, - ocean_color, - lake_color, - river_color - /* eslint-disable camelcase */ - } = theme; - var layout = { - paper_bgcolor, - plot_bgcolor, - autosize: true, - colorway: ChartUtils.normalizeColorway(theme === null || theme === void 0 ? void 0 : theme.colorway), - font: { - family: "'Fira Sans', sans-serif", - color: title_color - }, - title: { - font: { - color: title_color - }, - xanchor: "center", - xref: "paper", - yanchor: "top", - pad: _objectSpread$1({}, ChartUtils.DEFAULT_TITLE_PADDING), - y: 1 - }, - legend: { - font: { - color: title_color - } - }, - margin: _objectSpread$1({}, ChartUtils.DEFAULT_MARGIN), - xaxis: this.makeLayoutAxis(dh.plot.AxisType.X, theme), - yaxis: this.makeLayoutAxis(dh.plot.AxisType.Y, theme), - polar: { - angularaxis: this.makeLayoutAxis(dh.plot.AxisType.SHAPE, theme), - radialaxis: this.makeLayoutAxis(dh.plot.AxisType.SHAPE, theme), - bgcolor: theme.plot_bgcolor - }, - scene: { - xaxis: this.makeLayoutAxis(dh.plot.AxisType.X, theme), - yaxis: this.makeLayoutAxis(dh.plot.AxisType.Y, theme), - zaxis: this.makeLayoutAxis(null, theme) - }, - geo: { - showcoastlines: true, - showframe: false, - showland: true, - showocean: true, - showlakes: true, - showrivers: true, - bgcolor: paper_bgcolor, - coastlinecolor: coastline_color, - landcolor: land_color, - oceancolor: ocean_color, - lakecolor: lake_color, - rivercolor: river_color - } - }; - layout.datarevision = 0; - return layout; - } - /** - * Hydrate settings from a JSONable object - * @param settings Dehydrated settings - */ - hydrateSettings(settings) { - var { - dh - } = this; - return _objectSpread$1(_objectSpread$1({}, settings), {}, { - type: settings.type != null ? dh.plot.SeriesPlotStyle[settings.type] : void 0 - }); - } -} -_defineProperty$2(ChartUtils, "DEFAULT_AXIS_SIZE", 0.15); -_defineProperty$2(ChartUtils, "MIN_AXIS_SIZE", 0.025); -_defineProperty$2(ChartUtils, "MAX_AXIS_SIZE", 0.2); -_defineProperty$2(ChartUtils, "AXIS_SIZE_PX", 75); -_defineProperty$2(ChartUtils, "LEGEND_WIDTH_PX", 50); -_defineProperty$2(ChartUtils, "MAX_LEGEND_SIZE", 0.25); -_defineProperty$2(ChartUtils, "ORIENTATION", Object.freeze({ - HORIZONTAL: "h", - VERTICAL: "v" -})); -_defineProperty$2(ChartUtils, "DATE_FORMAT", "yyyy-MM-dd HH:mm:ss.SSSSSS"); -_defineProperty$2(ChartUtils, "DEFAULT_MARGIN", Object.freeze({ - l: 60, - r: 50, - t: 30, - b: 60, - pad: 0 -})); -_defineProperty$2(ChartUtils, "DEFAULT_TITLE_PADDING", Object.freeze({ - t: 8 -})); -_defineProperty$2(ChartUtils, "SUBTITLE_LINE_HEIGHT", 25); -_defineProperty$2(ChartUtils, "DEFAULT_MARKER_SIZE", 6); -_defineProperty$2(ChartUtils, "MODE_MARKERS", "markers"); -_defineProperty$2(ChartUtils, "MODE_LINES", "lines"); -var noop = function() { -}; -var _undefined$1 = noop(); -var isValue$6 = function(val) { - return val !== _undefined$1 && val !== null; -}; -var isValue$5 = isValue$6; -var forEach$2 = Array.prototype.forEach, create$1 = Object.create; -var process$1 = function(src, obj) { - var key; - for (key in src) obj[key] = src[key]; -}; -var normalizeOptions = function(opts1) { - var result = create$1(null); - forEach$2.call(arguments, function(options) { - if (!isValue$5(options)) return; - process$1(Object(options), result); - }); - return result; -}; -var isImplemented$7 = function() { - var sign2 = Math.sign; - if (typeof sign2 !== "function") return false; - return sign2(10) === 1 && sign2(-20) === -1; -}; -var shim$5; -var hasRequiredShim$5; -function requireShim$5() { - if (hasRequiredShim$5) return shim$5; - hasRequiredShim$5 = 1; - shim$5 = function(value2) { - value2 = Number(value2); - if (isNaN(value2) || value2 === 0) return value2; - return value2 > 0 ? 1 : -1; - }; - return shim$5; -} -var sign$1 = isImplemented$7() ? Math.sign : requireShim$5(); -var sign = sign$1, abs = Math.abs, floor = Math.floor; -var toInteger$1 = function(value2) { - if (isNaN(value2)) return 0; - value2 = Number(value2); - if (value2 === 0 || !isFinite(value2)) return value2; - return sign(value2) * floor(abs(value2)); -}; -var toInteger = toInteger$1, max$1 = Math.max; -var toPosInteger = function(value2) { - return max$1(0, toInteger(value2)); -}; -var toPosInt$1 = toPosInteger; -var resolveLength$2 = function(optsLength, fnLength, isAsync) { - var length; - if (isNaN(optsLength)) { - length = fnLength; - if (!(length >= 0)) return 1; - if (isAsync && length) return length - 1; - return length; - } - if (optsLength === false) return false; - return toPosInt$1(optsLength); -}; -var validCallable = function(fn) { - if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); - return fn; -}; -var isValue$4 = isValue$6; -var validValue = function(value2) { - if (!isValue$4(value2)) throw new TypeError("Cannot use null or undefined"); - return value2; -}; -var callable$3 = validCallable, value = validValue, bind = Function.prototype.bind, call$1 = Function.prototype.call, keys$1 = Object.keys, objPropertyIsEnumerable = Object.prototype.propertyIsEnumerable; -var _iterate = function(method, defVal) { - return function(obj, cb) { - var list, thisArg = arguments[2], compareFn = arguments[3]; - obj = Object(value(obj)); - callable$3(cb); - list = keys$1(obj); - if (compareFn) { - list.sort(typeof compareFn === "function" ? bind.call(compareFn, obj) : void 0); - } - if (typeof method !== "function") method = list[method]; - return call$1.call(method, list, function(key, index) { - if (!objPropertyIsEnumerable.call(obj, key)) return defVal; - return call$1.call(cb, thisArg, obj[key], key, obj, index); - }); - }; -}; -var forEach$1 = _iterate("forEach"); -var registeredExtensions = {}; -var custom = { exports: {} }; -var isImplemented$6 = function() { - var assign2 = Object.assign, obj; - if (typeof assign2 !== "function") return false; - obj = { foo: "raz" }; - assign2(obj, { bar: "dwa" }, { trzy: "trzy" }); - return obj.foo + obj.bar + obj.trzy === "razdwatrzy"; -}; -var isImplemented$5; -var hasRequiredIsImplemented$4; -function requireIsImplemented$4() { - if (hasRequiredIsImplemented$4) return isImplemented$5; - hasRequiredIsImplemented$4 = 1; - isImplemented$5 = function() { - try { - Object.keys("primitive"); - return true; - } catch (e) { - return false; - } - }; - return isImplemented$5; -} -var shim$4; -var hasRequiredShim$4; -function requireShim$4() { - if (hasRequiredShim$4) return shim$4; - hasRequiredShim$4 = 1; - var isValue2 = isValue$6; - var keys2 = Object.keys; - shim$4 = function(object) { - return keys2(isValue2(object) ? Object(object) : object); - }; - return shim$4; -} -var keys; -var hasRequiredKeys; -function requireKeys() { - if (hasRequiredKeys) return keys; - hasRequiredKeys = 1; - keys = requireIsImplemented$4()() ? Object.keys : requireShim$4(); - return keys; -} -var shim$3; -var hasRequiredShim$3; -function requireShim$3() { - if (hasRequiredShim$3) return shim$3; - hasRequiredShim$3 = 1; - var keys2 = requireKeys(), value2 = validValue, max2 = Math.max; - shim$3 = function(dest, src) { - var error, i, length = max2(arguments.length, 2), assign2; - dest = Object(value2(dest)); - assign2 = function(key) { - try { - dest[key] = src[key]; - } catch (e) { - if (!error) error = e; - } - }; - for (i = 1; i < length; ++i) { - src = arguments[i]; - keys2(src).forEach(assign2); - } - if (error !== void 0) throw error; - return dest; - }; - return shim$3; -} -var assign$1 = isImplemented$6() ? Object.assign : requireShim$3(); -var isValue$3 = isValue$6; -var map$1 = { function: true, object: true }; -var isObject$1 = function(value2) { - return isValue$3(value2) && map$1[typeof value2] || false; -}; -(function(module2) { - var assign2 = assign$1, isObject2 = isObject$1, isValue2 = isValue$6, captureStackTrace = Error.captureStackTrace; - module2.exports = function(message) { - var err = new Error(message), code = arguments[1], ext = arguments[2]; - if (!isValue2(ext)) { - if (isObject2(code)) { - ext = code; - code = null; - } - } - if (isValue2(ext)) assign2(err, ext); - if (isValue2(code)) err.code = code; - if (captureStackTrace) captureStackTrace(err, module2.exports); - return err; - }; -})(custom); -var customExports = custom.exports; -var _defineLength = { exports: {} }; -var mixin$1; -var hasRequiredMixin; -function requireMixin() { - if (hasRequiredMixin) return mixin$1; - hasRequiredMixin = 1; - var value2 = validValue, defineProperty2 = Object.defineProperty, getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor, getOwnPropertyNames = Object.getOwnPropertyNames, getOwnPropertySymbols2 = Object.getOwnPropertySymbols; - mixin$1 = function(target, source) { - var error, sourceObject = Object(value2(source)); - target = Object(value2(target)); - getOwnPropertyNames(sourceObject).forEach(function(name) { - try { - defineProperty2(target, name, getOwnPropertyDescriptor(source, name)); - } catch (e) { - error = e; - } - }); - if (typeof getOwnPropertySymbols2 === "function") { - getOwnPropertySymbols2(sourceObject).forEach(function(symbol) { - try { - defineProperty2(target, symbol, getOwnPropertyDescriptor(source, symbol)); - } catch (e) { - error = e; - } - }); - } - if (error !== void 0) throw error; - return target; - }; - return mixin$1; -} -var toPosInt = toPosInteger; -var test = function(arg1, arg2) { - return arg2; -}; -var desc, defineProperty, generate, mixin; -try { - Object.defineProperty(test, "length", { - configurable: true, - writable: false, - enumerable: false, - value: 1 - }); -} catch (ignore) { -} -if (test.length === 1) { - desc = { configurable: true, writable: false, enumerable: false }; - defineProperty = Object.defineProperty; - _defineLength.exports = function(fn, length) { - length = toPosInt(length); - if (fn.length === length) return fn; - desc.value = length; - return defineProperty(fn, "length", desc); - }; -} else { - mixin = requireMixin(); - generate = /* @__PURE__ */ function() { - var cache = []; - return function(length) { - var args, i = 0; - if (cache[length]) return cache[length]; - args = []; - while (length--) args.push("a" + (++i).toString(36)); - return new Function( - "fn", - "return function (" + args.join(", ") + ") { return fn.apply(this, arguments); };" - ); - }; - }(); - _defineLength.exports = function(src, length) { - var target; - length = toPosInt(length); - if (src.length === length) return src; - target = generate(length)(src); - try { - mixin(target, src); - } catch (ignore) { - } - return target; - }; -} -var _defineLengthExports = _defineLength.exports; -var d$2 = { exports: {} }; -var _undefined = void 0; -var is$4 = function(value2) { - return value2 !== _undefined && value2 !== null; -}; -var isValue$2 = is$4; -var possibleTypes = { - "object": true, - "function": true, - "undefined": true - /* document.all */ -}; -var is$3 = function(value2) { - if (!isValue$2(value2)) return false; - return hasOwnProperty.call(possibleTypes, typeof value2); -}; -var isObject = is$3; -var is$2 = function(value2) { - if (!isObject(value2)) return false; - try { - if (!value2.constructor) return false; - return value2.constructor.prototype === value2; - } catch (error) { - return false; - } -}; -var isPrototype = is$2; -var is$1 = function(value2) { - if (typeof value2 !== "function") return false; - if (!hasOwnProperty.call(value2, "length")) return false; - try { - if (typeof value2.length !== "number") return false; - if (typeof value2.call !== "function") return false; - if (typeof value2.apply !== "function") return false; - } catch (error) { - return false; - } - return !isPrototype(value2); -}; -var isFunction$1 = is$1; -var classRe = /^\s*class[\s{/}]/, functionToString = Function.prototype.toString; -var is = function(value2) { - if (!isFunction$1(value2)) return false; - if (classRe.test(functionToString.call(value2))) return false; - return true; -}; -var str = "razdwatrzy"; -var isImplemented$4 = function() { - if (typeof str.contains !== "function") return false; - return str.contains("dwa") === true && str.contains("foo") === false; -}; -var shim$2; -var hasRequiredShim$2; -function requireShim$2() { - if (hasRequiredShim$2) return shim$2; - hasRequiredShim$2 = 1; - var indexOf = String.prototype.indexOf; - shim$2 = function(searchString) { - return indexOf.call(this, searchString, arguments[1]) > -1; - }; - return shim$2; -} -var contains$1 = isImplemented$4() ? String.prototype.contains : requireShim$2(); -var isValue$1 = is$4, isPlainFunction = is, assign = assign$1, normalizeOpts$1 = normalizeOptions, contains = contains$1; -var d$1 = d$2.exports = function(dscr, value2) { - var c, e, w, options, desc2; - if (arguments.length < 2 || typeof dscr !== "string") { - options = value2; - value2 = dscr; - dscr = null; - } else { - options = arguments[2]; - } - if (isValue$1(dscr)) { - c = contains.call(dscr, "c"); - e = contains.call(dscr, "e"); - w = contains.call(dscr, "w"); - } else { - c = w = true; - e = false; - } - desc2 = { value: value2, configurable: c, enumerable: e, writable: w }; - return !options ? desc2 : assign(normalizeOpts$1(options), desc2); -}; -d$1.gs = function(dscr, get2, set) { - var c, e, options, desc2; - if (typeof dscr !== "string") { - options = set; - set = get2; - get2 = dscr; - dscr = null; - } else { - options = arguments[3]; - } - if (!isValue$1(get2)) { - get2 = void 0; - } else if (!isPlainFunction(get2)) { - options = get2; - get2 = set = void 0; - } else if (!isValue$1(set)) { - set = void 0; - } else if (!isPlainFunction(set)) { - options = set; - set = void 0; - } - if (isValue$1(dscr)) { - c = contains.call(dscr, "c"); - e = contains.call(dscr, "e"); - } else { - c = true; - e = false; - } - desc2 = { get: get2, set, configurable: c, enumerable: e }; - return !options ? desc2 : assign(normalizeOpts$1(options), desc2); -}; -var dExports = d$2.exports; -var eventEmitter = { exports: {} }; -(function(module2, exports2) { - var d2 = dExports, callable2 = validCallable, apply2 = Function.prototype.apply, call2 = Function.prototype.call, create2 = Object.create, defineProperty2 = Object.defineProperty, defineProperties2 = Object.defineProperties, hasOwnProperty2 = Object.prototype.hasOwnProperty, descriptor = { configurable: true, enumerable: false, writable: true }, on2, once, off, emit2, methods, descriptors, base; - on2 = function(type, listener) { - var data; - callable2(listener); - if (!hasOwnProperty2.call(this, "__ee__")) { - data = descriptor.value = create2(null); - defineProperty2(this, "__ee__", descriptor); - descriptor.value = null; - } else { - data = this.__ee__; - } - if (!data[type]) data[type] = listener; - else if (typeof data[type] === "object") data[type].push(listener); - else data[type] = [data[type], listener]; - return this; - }; - once = function(type, listener) { - var once2, self3; - callable2(listener); - self3 = this; - on2.call(this, type, once2 = function() { - off.call(self3, type, once2); - apply2.call(listener, this, arguments); - }); - once2.__eeOnceListener__ = listener; - return this; - }; - off = function(type, listener) { - var data, listeners, candidate, i; - callable2(listener); - if (!hasOwnProperty2.call(this, "__ee__")) return this; - data = this.__ee__; - if (!data[type]) return this; - listeners = data[type]; - if (typeof listeners === "object") { - for (i = 0; candidate = listeners[i]; ++i) { - if (candidate === listener || candidate.__eeOnceListener__ === listener) { - if (listeners.length === 2) data[type] = listeners[i ? 0 : 1]; - else listeners.splice(i, 1); - } - } - } else { - if (listeners === listener || listeners.__eeOnceListener__ === listener) { - delete data[type]; - } - } - return this; - }; - emit2 = function(type) { - var i, l, listener, listeners, args; - if (!hasOwnProperty2.call(this, "__ee__")) return; - listeners = this.__ee__[type]; - if (!listeners) return; - if (typeof listeners === "object") { - l = arguments.length; - args = new Array(l - 1); - for (i = 1; i < l; ++i) args[i - 1] = arguments[i]; - listeners = listeners.slice(); - for (i = 0; listener = listeners[i]; ++i) { - apply2.call(listener, this, args); - } - } else { - switch (arguments.length) { - case 1: - call2.call(listeners, this); - break; - case 2: - call2.call(listeners, this, arguments[1]); - break; - case 3: - call2.call(listeners, this, arguments[1], arguments[2]); - break; - default: - l = arguments.length; - args = new Array(l - 1); - for (i = 1; i < l; ++i) { - args[i - 1] = arguments[i]; - } - apply2.call(listeners, this, args); - } - } - }; - methods = { - on: on2, - once, - off, - emit: emit2 - }; - descriptors = { - on: d2(on2), - once: d2(once), - off: d2(off), - emit: d2(emit2) - }; - base = defineProperties2({}, descriptors); - module2.exports = exports2 = function(o) { - return o == null ? create2(base) : defineProperties2(Object(o), descriptors); - }; - exports2.methods = methods; -})(eventEmitter, eventEmitter.exports); -var eventEmitterExports = eventEmitter.exports; -var isImplemented$3; -var hasRequiredIsImplemented$3; -function requireIsImplemented$3() { - if (hasRequiredIsImplemented$3) return isImplemented$3; - hasRequiredIsImplemented$3 = 1; - isImplemented$3 = function() { - var from2 = Array.from, arr, result; - if (typeof from2 !== "function") return false; - arr = ["raz", "dwa"]; - result = from2(arr); - return Boolean(result && result !== arr && result[1] === "dwa"); - }; - return isImplemented$3; -} -var isImplemented$2; -var hasRequiredIsImplemented$2; -function requireIsImplemented$2() { - if (hasRequiredIsImplemented$2) return isImplemented$2; - hasRequiredIsImplemented$2 = 1; - isImplemented$2 = function() { - if (typeof globalThis !== "object") return false; - if (!globalThis) return false; - return globalThis.Array === Array; - }; - return isImplemented$2; -} -var implementation; -var hasRequiredImplementation; -function requireImplementation() { - if (hasRequiredImplementation) return implementation; - hasRequiredImplementation = 1; - var naiveFallback = function() { - if (typeof self === "object" && self) return self; - if (typeof window === "object" && window) return window; - throw new Error("Unable to resolve global `this`"); - }; - implementation = function() { - if (this) return this; - try { - Object.defineProperty(Object.prototype, "__global__", { - get: function() { - return this; - }, - configurable: true - }); - } catch (error) { - return naiveFallback(); - } - try { - if (!__global__) return naiveFallback(); - return __global__; - } finally { - delete Object.prototype.__global__; - } - }(); - return implementation; -} -var globalThis_1; -var hasRequiredGlobalThis; -function requireGlobalThis() { - if (hasRequiredGlobalThis) return globalThis_1; - hasRequiredGlobalThis = 1; - globalThis_1 = requireIsImplemented$2()() ? globalThis : requireImplementation(); - return globalThis_1; -} -var isImplemented$1; -var hasRequiredIsImplemented$1; -function requireIsImplemented$1() { - if (hasRequiredIsImplemented$1) return isImplemented$1; - hasRequiredIsImplemented$1 = 1; - var global2 = requireGlobalThis(), validTypes = { object: true, symbol: true }; - isImplemented$1 = function() { - var Symbol2 = global2.Symbol; - var symbol; - if (typeof Symbol2 !== "function") return false; - symbol = Symbol2("test symbol"); - try { - String(symbol); - } catch (e) { - return false; - } - if (!validTypes[typeof Symbol2.iterator]) return false; - if (!validTypes[typeof Symbol2.toPrimitive]) return false; - if (!validTypes[typeof Symbol2.toStringTag]) return false; - return true; - }; - return isImplemented$1; -} -var isSymbol; -var hasRequiredIsSymbol; -function requireIsSymbol() { - if (hasRequiredIsSymbol) return isSymbol; - hasRequiredIsSymbol = 1; - isSymbol = function(value2) { - if (!value2) return false; - if (typeof value2 === "symbol") return true; - if (!value2.constructor) return false; - if (value2.constructor.name !== "Symbol") return false; - return value2[value2.constructor.toStringTag] === "Symbol"; - }; - return isSymbol; -} -var validateSymbol; -var hasRequiredValidateSymbol; -function requireValidateSymbol() { - if (hasRequiredValidateSymbol) return validateSymbol; - hasRequiredValidateSymbol = 1; - var isSymbol2 = requireIsSymbol(); - validateSymbol = function(value2) { - if (!isSymbol2(value2)) throw new TypeError(value2 + " is not a symbol"); - return value2; - }; - return validateSymbol; -} -var generateName; -var hasRequiredGenerateName; -function requireGenerateName() { - if (hasRequiredGenerateName) return generateName; - hasRequiredGenerateName = 1; - var d2 = dExports; - var create2 = Object.create, defineProperty2 = Object.defineProperty, objPrototype = Object.prototype; - var created = create2(null); - generateName = function(desc2) { - var postfix = 0, name, ie11BugWorkaround; - while (created[desc2 + (postfix || "")]) ++postfix; - desc2 += postfix || ""; - created[desc2] = true; - name = "@@" + desc2; - defineProperty2( - objPrototype, - name, - d2.gs(null, function(value2) { - if (ie11BugWorkaround) return; - ie11BugWorkaround = true; - defineProperty2(this, name, d2(value2)); - ie11BugWorkaround = false; - }) - ); - return name; - }; - return generateName; -} -var standardSymbols; -var hasRequiredStandardSymbols; -function requireStandardSymbols() { - if (hasRequiredStandardSymbols) return standardSymbols; - hasRequiredStandardSymbols = 1; - var d2 = dExports, NativeSymbol = requireGlobalThis().Symbol; - standardSymbols = function(SymbolPolyfill) { - return Object.defineProperties(SymbolPolyfill, { - // To ensure proper interoperability with other native functions (e.g. Array.from) - // fallback to eventual native implementation of given symbol - hasInstance: d2( - "", - NativeSymbol && NativeSymbol.hasInstance || SymbolPolyfill("hasInstance") - ), - isConcatSpreadable: d2( - "", - NativeSymbol && NativeSymbol.isConcatSpreadable || SymbolPolyfill("isConcatSpreadable") - ), - iterator: d2("", NativeSymbol && NativeSymbol.iterator || SymbolPolyfill("iterator")), - match: d2("", NativeSymbol && NativeSymbol.match || SymbolPolyfill("match")), - replace: d2("", NativeSymbol && NativeSymbol.replace || SymbolPolyfill("replace")), - search: d2("", NativeSymbol && NativeSymbol.search || SymbolPolyfill("search")), - species: d2("", NativeSymbol && NativeSymbol.species || SymbolPolyfill("species")), - split: d2("", NativeSymbol && NativeSymbol.split || SymbolPolyfill("split")), - toPrimitive: d2( - "", - NativeSymbol && NativeSymbol.toPrimitive || SymbolPolyfill("toPrimitive") - ), - toStringTag: d2( - "", - NativeSymbol && NativeSymbol.toStringTag || SymbolPolyfill("toStringTag") - ), - unscopables: d2( - "", - NativeSymbol && NativeSymbol.unscopables || SymbolPolyfill("unscopables") - ) - }); - }; - return standardSymbols; -} -var symbolRegistry; -var hasRequiredSymbolRegistry; -function requireSymbolRegistry() { - if (hasRequiredSymbolRegistry) return symbolRegistry; - hasRequiredSymbolRegistry = 1; - var d2 = dExports, validateSymbol2 = requireValidateSymbol(); - var registry = /* @__PURE__ */ Object.create(null); - symbolRegistry = function(SymbolPolyfill) { - return Object.defineProperties(SymbolPolyfill, { - for: d2(function(key) { - if (registry[key]) return registry[key]; - return registry[key] = SymbolPolyfill(String(key)); - }), - keyFor: d2(function(symbol) { - var key; - validateSymbol2(symbol); - for (key in registry) { - if (registry[key] === symbol) return key; - } - return void 0; - }) - }); - }; - return symbolRegistry; -} -var polyfill; -var hasRequiredPolyfill; -function requirePolyfill() { - if (hasRequiredPolyfill) return polyfill; - hasRequiredPolyfill = 1; - var d2 = dExports, validateSymbol2 = requireValidateSymbol(), NativeSymbol = requireGlobalThis().Symbol, generateName2 = requireGenerateName(), setupStandardSymbols = requireStandardSymbols(), setupSymbolRegistry = requireSymbolRegistry(); - var create2 = Object.create, defineProperties2 = Object.defineProperties, defineProperty2 = Object.defineProperty; - var SymbolPolyfill, HiddenSymbol, isNativeSafe; - if (typeof NativeSymbol === "function") { - try { - String(NativeSymbol()); - isNativeSafe = true; - } catch (ignore) { - } - } else { - NativeSymbol = null; - } - HiddenSymbol = function Symbol2(description) { - if (this instanceof HiddenSymbol) throw new TypeError("Symbol is not a constructor"); - return SymbolPolyfill(description); - }; - polyfill = SymbolPolyfill = function Symbol2(description) { - var symbol; - if (this instanceof Symbol2) throw new TypeError("Symbol is not a constructor"); - if (isNativeSafe) return NativeSymbol(description); - symbol = create2(HiddenSymbol.prototype); - description = description === void 0 ? "" : String(description); - return defineProperties2(symbol, { - __description__: d2("", description), - __name__: d2("", generateName2(description)) - }); - }; - setupStandardSymbols(SymbolPolyfill); - setupSymbolRegistry(SymbolPolyfill); - defineProperties2(HiddenSymbol.prototype, { - constructor: d2(SymbolPolyfill), - toString: d2("", function() { - return this.__name__; - }) - }); - defineProperties2(SymbolPolyfill.prototype, { - toString: d2(function() { - return "Symbol (" + validateSymbol2(this).__description__ + ")"; - }), - valueOf: d2(function() { - return validateSymbol2(this); - }) - }); - defineProperty2( - SymbolPolyfill.prototype, - SymbolPolyfill.toPrimitive, - d2("", function() { - var symbol = validateSymbol2(this); - if (typeof symbol === "symbol") return symbol; - return symbol.toString(); - }) - ); - defineProperty2(SymbolPolyfill.prototype, SymbolPolyfill.toStringTag, d2("c", "Symbol")); - defineProperty2( - HiddenSymbol.prototype, - SymbolPolyfill.toStringTag, - d2("c", SymbolPolyfill.prototype[SymbolPolyfill.toStringTag]) - ); - defineProperty2( - HiddenSymbol.prototype, - SymbolPolyfill.toPrimitive, - d2("c", SymbolPolyfill.prototype[SymbolPolyfill.toPrimitive]) - ); - return polyfill; -} -var es6Symbol; -var hasRequiredEs6Symbol; -function requireEs6Symbol() { - if (hasRequiredEs6Symbol) return es6Symbol; - hasRequiredEs6Symbol = 1; - es6Symbol = requireIsImplemented$1()() ? requireGlobalThis().Symbol : requirePolyfill(); - return es6Symbol; -} -var isArguments; -var hasRequiredIsArguments; -function requireIsArguments() { - if (hasRequiredIsArguments) return isArguments; - hasRequiredIsArguments = 1; - var objToString = Object.prototype.toString, id = objToString.call(/* @__PURE__ */ function() { - return arguments; - }()); - isArguments = function(value2) { - return objToString.call(value2) === id; - }; - return isArguments; -} -var isFunction; -var hasRequiredIsFunction; -function requireIsFunction() { - if (hasRequiredIsFunction) return isFunction; - hasRequiredIsFunction = 1; - var objToString = Object.prototype.toString, isFunctionStringTag = RegExp.prototype.test.bind(/^[object [A-Za-z0-9]*Function]$/); - isFunction = function(value2) { - return typeof value2 === "function" && isFunctionStringTag(objToString.call(value2)); - }; - return isFunction; -} -var isString; -var hasRequiredIsString; -function requireIsString() { - if (hasRequiredIsString) return isString; - hasRequiredIsString = 1; - var objToString = Object.prototype.toString, id = objToString.call(""); - isString = function(value2) { - return typeof value2 === "string" || value2 && typeof value2 === "object" && (value2 instanceof String || objToString.call(value2) === id) || false; - }; - return isString; -} -var shim$1; -var hasRequiredShim$1; -function requireShim$1() { - if (hasRequiredShim$1) return shim$1; - hasRequiredShim$1 = 1; - var iteratorSymbol = requireEs6Symbol().iterator, isArguments2 = requireIsArguments(), isFunction2 = requireIsFunction(), toPosInt2 = toPosInteger, callable2 = validCallable, validValue$1 = validValue, isValue2 = isValue$6, isString2 = requireIsString(), isArray2 = Array.isArray, call2 = Function.prototype.call, desc2 = { configurable: true, enumerable: true, writable: true, value: null }, defineProperty2 = Object.defineProperty; - shim$1 = function(arrayLike) { - var mapFn = arguments[1], thisArg = arguments[2], Context, i, j, arr, length, code, iterator, result, getIterator, value2; - arrayLike = Object(validValue$1(arrayLike)); - if (isValue2(mapFn)) callable2(mapFn); - if (!this || this === Array || !isFunction2(this)) { - if (!mapFn) { - if (isArguments2(arrayLike)) { - length = arrayLike.length; - if (length !== 1) return Array.apply(null, arrayLike); - arr = new Array(1); - arr[0] = arrayLike[0]; - return arr; - } - if (isArray2(arrayLike)) { - arr = new Array(length = arrayLike.length); - for (i = 0; i < length; ++i) arr[i] = arrayLike[i]; - return arr; - } - } - arr = []; - } else { - Context = this; - } - if (!isArray2(arrayLike)) { - if ((getIterator = arrayLike[iteratorSymbol]) !== void 0) { - iterator = callable2(getIterator).call(arrayLike); - if (Context) arr = new Context(); - result = iterator.next(); - i = 0; - while (!result.done) { - value2 = mapFn ? call2.call(mapFn, thisArg, result.value, i) : result.value; - if (Context) { - desc2.value = value2; - defineProperty2(arr, i, desc2); - } else { - arr[i] = value2; - } - result = iterator.next(); - ++i; - } - length = i; - } else if (isString2(arrayLike)) { - length = arrayLike.length; - if (Context) arr = new Context(); - for (i = 0, j = 0; i < length; ++i) { - value2 = arrayLike[i]; - if (i + 1 < length) { - code = value2.charCodeAt(0); - if (code >= 55296 && code <= 56319) value2 += arrayLike[++i]; - } - value2 = mapFn ? call2.call(mapFn, thisArg, value2, j) : value2; - if (Context) { - desc2.value = value2; - defineProperty2(arr, j, desc2); - } else { - arr[j] = value2; - } - ++j; - } - length = j; - } - } - if (length === void 0) { - length = toPosInt2(arrayLike.length); - if (Context) arr = new Context(length); - for (i = 0; i < length; ++i) { - value2 = mapFn ? call2.call(mapFn, thisArg, arrayLike[i], i) : arrayLike[i]; - if (Context) { - desc2.value = value2; - defineProperty2(arr, i, desc2); - } else { - arr[i] = value2; - } - } - } - if (Context) { - desc2.value = null; - arr.length = length; - } - return arr; - }; - return shim$1; -} -var from$1; -var hasRequiredFrom; -function requireFrom() { - if (hasRequiredFrom) return from$1; - hasRequiredFrom = 1; - from$1 = requireIsImplemented$3()() ? Array.from : requireShim$1(); - return from$1; -} -var from = requireFrom(), isArray = Array.isArray; -var toArray$1 = function(arrayLike) { - return isArray(arrayLike) ? arrayLike : from(arrayLike); -}; -var toArray = toArray$1, isValue = isValue$6, callable$2 = validCallable; -var slice = Array.prototype.slice, resolveArgs; -resolveArgs = function(args) { - return this.map(function(resolve, i) { - return resolve ? resolve(args[i]) : args[i]; - }).concat( - slice.call(args, this.length) - ); -}; -var resolveResolve$1 = function(resolvers) { - resolvers = toArray(resolvers); - resolvers.forEach(function(resolve) { - if (isValue(resolve)) callable$2(resolve); - }); - return resolveArgs.bind(resolvers); -}; -var callable$1 = validCallable; -var resolveNormalize$1 = function(userNormalizer) { - var normalizer; - if (typeof userNormalizer === "function") return { set: userNormalizer, get: userNormalizer }; - normalizer = { get: callable$1(userNormalizer.get) }; - if (userNormalizer.set !== void 0) { - normalizer.set = callable$1(userNormalizer.set); - if (userNormalizer.delete) normalizer.delete = callable$1(userNormalizer.delete); - if (userNormalizer.clear) normalizer.clear = callable$1(userNormalizer.clear); - return normalizer; - } - normalizer.set = normalizer.get; - return normalizer; -}; -var customError = customExports, defineLength = _defineLengthExports, d = dExports, ee = eventEmitterExports.methods, resolveResolve = resolveResolve$1, resolveNormalize = resolveNormalize$1; -var apply = Function.prototype.apply, call = Function.prototype.call, create = Object.create, defineProperties = Object.defineProperties, on = ee.on, emit = ee.emit; -var configureMap = function(original, length, options) { - var cache = create(null), conf, memLength, get2, set, del, clear, extDel, extGet, extHas, normalizer, getListeners, setListeners, deleteListeners, memoized, resolve; - if (length !== false) memLength = length; - else if (isNaN(original.length)) memLength = 1; - else memLength = original.length; - if (options.normalizer) { - normalizer = resolveNormalize(options.normalizer); - get2 = normalizer.get; - set = normalizer.set; - del = normalizer.delete; - clear = normalizer.clear; - } - if (options.resolvers != null) resolve = resolveResolve(options.resolvers); - if (get2) { - memoized = defineLength(function(arg) { - var id, result, args = arguments; - if (resolve) args = resolve(args); - id = get2(args); - if (id !== null) { - if (hasOwnProperty.call(cache, id)) { - if (getListeners) conf.emit("get", id, args, this); - return cache[id]; - } - } - if (args.length === 1) result = call.call(original, this, args[0]); - else result = apply.call(original, this, args); - if (id === null) { - id = get2(args); - if (id !== null) throw customError("Circular invocation", "CIRCULAR_INVOCATION"); - id = set(args); - } else if (hasOwnProperty.call(cache, id)) { - throw customError("Circular invocation", "CIRCULAR_INVOCATION"); - } - cache[id] = result; - if (setListeners) conf.emit("set", id, null, result); - return result; - }, memLength); - } else if (length === 0) { - memoized = function() { - var result; - if (hasOwnProperty.call(cache, "data")) { - if (getListeners) conf.emit("get", "data", arguments, this); - return cache.data; - } - if (arguments.length) result = apply.call(original, this, arguments); - else result = call.call(original, this); - if (hasOwnProperty.call(cache, "data")) { - throw customError("Circular invocation", "CIRCULAR_INVOCATION"); - } - cache.data = result; - if (setListeners) conf.emit("set", "data", null, result); - return result; - }; - } else { - memoized = function(arg) { - var result, args = arguments, id; - if (resolve) args = resolve(arguments); - id = String(args[0]); - if (hasOwnProperty.call(cache, id)) { - if (getListeners) conf.emit("get", id, args, this); - return cache[id]; - } - if (args.length === 1) result = call.call(original, this, args[0]); - else result = apply.call(original, this, args); - if (hasOwnProperty.call(cache, id)) { - throw customError("Circular invocation", "CIRCULAR_INVOCATION"); - } - cache[id] = result; - if (setListeners) conf.emit("set", id, null, result); - return result; - }; - } - conf = { - original, - memoized, - profileName: options.profileName, - get: function(args) { - if (resolve) args = resolve(args); - if (get2) return get2(args); - return String(args[0]); - }, - has: function(id) { - return hasOwnProperty.call(cache, id); - }, - delete: function(id) { - var result; - if (!hasOwnProperty.call(cache, id)) return; - if (del) del(id); - result = cache[id]; - delete cache[id]; - if (deleteListeners) conf.emit("delete", id, result); - }, - clear: function() { - var oldCache = cache; - if (clear) clear(); - cache = create(null); - conf.emit("clear", oldCache); - }, - on: function(type, listener) { - if (type === "get") getListeners = true; - else if (type === "set") setListeners = true; - else if (type === "delete") deleteListeners = true; - return on.call(this, type, listener); - }, - emit, - updateEnv: function() { - original = conf.original; - } - }; - if (get2) { - extDel = defineLength(function(arg) { - var id, args = arguments; - if (resolve) args = resolve(args); - id = get2(args); - if (id === null) return; - conf.delete(id); - }, memLength); - } else if (length === 0) { - extDel = function() { - return conf.delete("data"); - }; - } else { - extDel = function(arg) { - if (resolve) arg = resolve(arguments)[0]; - return conf.delete(arg); - }; - } - extGet = defineLength(function() { - var id, args = arguments; - if (length === 0) return cache.data; - if (resolve) args = resolve(args); - if (get2) id = get2(args); - else id = String(args[0]); - return cache[id]; - }); - extHas = defineLength(function() { - var id, args = arguments; - if (length === 0) return conf.has("data"); - if (resolve) args = resolve(args); - if (get2) id = get2(args); - else id = String(args[0]); - if (id === null) return false; - return conf.has(id); - }); - defineProperties(memoized, { - __memoized__: d(true), - delete: d(extDel), - clear: d(conf.clear), - _get: d(extGet), - _has: d(extHas) - }); - return conf; -}; -var callable = validCallable, forEach = forEach$1, extensions = registeredExtensions, configure = configureMap, resolveLength$1 = resolveLength$2; -var plain$1 = function self2(fn) { - var options, length, conf; - callable(fn); - options = Object(arguments[1]); - if (options.async && options.promise) { - throw new Error("Options 'async' and 'promise' cannot be used together"); - } - if (hasOwnProperty.call(fn, "__memoized__") && !options.force) return fn; - length = resolveLength$1(options.length, fn.length, options.async && extensions.async); - conf = configure(fn, length, options); - forEach(extensions, function(extFn, name) { - if (options[name]) extFn(options[name], conf, options); - }); - if (self2.__profiler__) self2.__profiler__(conf); - conf.updateEnv(); - return conf.memoized; -}; -var primitive; -var hasRequiredPrimitive; -function requirePrimitive() { - if (hasRequiredPrimitive) return primitive; - hasRequiredPrimitive = 1; - primitive = function(args) { - var id, i, length = args.length; - if (!length) return ""; - id = String(args[i = 0]); - while (--length) id += "" + args[++i]; - return id; - }; - return primitive; -} -var getPrimitiveFixed; -var hasRequiredGetPrimitiveFixed; -function requireGetPrimitiveFixed() { - if (hasRequiredGetPrimitiveFixed) return getPrimitiveFixed; - hasRequiredGetPrimitiveFixed = 1; - getPrimitiveFixed = function(length) { - if (!length) { - return function() { - return ""; - }; - } - return function(args) { - var id = String(args[0]), i = 0, currentLength = length; - while (--currentLength) { - id += "" + args[++i]; - } - return id; - }; - }; - return getPrimitiveFixed; -} -var isImplemented; -var hasRequiredIsImplemented; -function requireIsImplemented() { - if (hasRequiredIsImplemented) return isImplemented; - hasRequiredIsImplemented = 1; - isImplemented = function() { - var numberIsNaN = Number.isNaN; - if (typeof numberIsNaN !== "function") return false; - return !numberIsNaN({}) && numberIsNaN(NaN) && !numberIsNaN(34); - }; - return isImplemented; -} -var shim; -var hasRequiredShim; -function requireShim() { - if (hasRequiredShim) return shim; - hasRequiredShim = 1; - shim = function(value2) { - return value2 !== value2; - }; - return shim; -} -var isNan; -var hasRequiredIsNan; -function requireIsNan() { - if (hasRequiredIsNan) return isNan; - hasRequiredIsNan = 1; - isNan = requireIsImplemented()() ? Number.isNaN : requireShim(); - return isNan; -} -var eIndexOf; -var hasRequiredEIndexOf; -function requireEIndexOf() { - if (hasRequiredEIndexOf) return eIndexOf; - hasRequiredEIndexOf = 1; - var numberIsNaN = requireIsNan(), toPosInt2 = toPosInteger, value2 = validValue, indexOf = Array.prototype.indexOf, objHasOwnProperty = Object.prototype.hasOwnProperty, abs2 = Math.abs, floor2 = Math.floor; - eIndexOf = function(searchElement) { - var i, length, fromIndex, val; - if (!numberIsNaN(searchElement)) return indexOf.apply(this, arguments); - length = toPosInt2(value2(this).length); - fromIndex = arguments[1]; - if (isNaN(fromIndex)) fromIndex = 0; - else if (fromIndex >= 0) fromIndex = floor2(fromIndex); - else fromIndex = toPosInt2(this.length) - floor2(abs2(fromIndex)); - for (i = fromIndex; i < length; ++i) { - if (objHasOwnProperty.call(this, i)) { - val = this[i]; - if (numberIsNaN(val)) return i; - } - } - return -1; - }; - return eIndexOf; -} -var get; -var hasRequiredGet; -function requireGet() { - if (hasRequiredGet) return get; - hasRequiredGet = 1; - var indexOf = requireEIndexOf(); - var create2 = Object.create; - get = function() { - var lastId = 0, map2 = [], cache = create2(null); - return { - get: function(args) { - var index = 0, set = map2, i, length = args.length; - if (length === 0) return set[length] || null; - if (set = set[length]) { - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) return null; - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) return null; - return set[1][i] || null; - } - return null; - }, - set: function(args) { - var index = 0, set = map2, i, length = args.length; - if (length === 0) { - set[length] = ++lastId; - } else { - if (!set[length]) { - set[length] = [[], []]; - } - set = set[length]; - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) { - i = set[0].push(args[index]) - 1; - set[1].push([[], []]); - } - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) { - i = set[0].push(args[index]) - 1; - } - set[1][i] = ++lastId; - } - cache[lastId] = args; - return lastId; - }, - delete: function(id) { - var index = 0, set = map2, i, args = cache[id], length = args.length, path = []; - if (length === 0) { - delete set[length]; - } else if (set = set[length]) { - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) { - return; - } - path.push(set, i); - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) { - return; - } - id = set[1][i]; - set[0].splice(i, 1); - set[1].splice(i, 1); - while (!set[0].length && path.length) { - i = path.pop(); - set = path.pop(); - set[0].splice(i, 1); - set[1].splice(i, 1); - } - } - delete cache[id]; - }, - clear: function() { - map2 = []; - cache = create2(null); - } - }; - }; - return get; -} -var get1; -var hasRequiredGet1; -function requireGet1() { - if (hasRequiredGet1) return get1; - hasRequiredGet1 = 1; - var indexOf = requireEIndexOf(); - get1 = function() { - var lastId = 0, argsMap = [], cache = []; - return { - get: function(args) { - var index = indexOf.call(argsMap, args[0]); - return index === -1 ? null : cache[index]; - }, - set: function(args) { - argsMap.push(args[0]); - cache.push(++lastId); - return lastId; - }, - delete: function(id) { - var index = indexOf.call(cache, id); - if (index !== -1) { - argsMap.splice(index, 1); - cache.splice(index, 1); - } - }, - clear: function() { - argsMap = []; - cache = []; - } - }; - }; - return get1; -} -var getFixed; -var hasRequiredGetFixed; -function requireGetFixed() { - if (hasRequiredGetFixed) return getFixed; - hasRequiredGetFixed = 1; - var indexOf = requireEIndexOf(), create2 = Object.create; - getFixed = function(length) { - var lastId = 0, map2 = [[], []], cache = create2(null); - return { - get: function(args) { - var index = 0, set = map2, i; - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) return null; - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) return null; - return set[1][i] || null; - }, - set: function(args) { - var index = 0, set = map2, i; - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) { - i = set[0].push(args[index]) - 1; - set[1].push([[], []]); - } - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) { - i = set[0].push(args[index]) - 1; - } - set[1][i] = ++lastId; - cache[lastId] = args; - return lastId; - }, - delete: function(id) { - var index = 0, set = map2, i, path = [], args = cache[id]; - while (index < length - 1) { - i = indexOf.call(set[0], args[index]); - if (i === -1) { - return; - } - path.push(set, i); - set = set[1][i]; - ++index; - } - i = indexOf.call(set[0], args[index]); - if (i === -1) { - return; - } - id = set[1][i]; - set[0].splice(i, 1); - set[1].splice(i, 1); - while (!set[0].length && path.length) { - i = path.pop(); - set = path.pop(); - set[0].splice(i, 1); - set[1].splice(i, 1); - } - delete cache[id]; - }, - clear: function() { - map2 = [[], []]; - cache = create2(null); - } - }; - }; - return getFixed; -} -var async = {}; -var map; -var hasRequiredMap; -function requireMap() { - if (hasRequiredMap) return map; - hasRequiredMap = 1; - var callable2 = validCallable, forEach2 = forEach$1, call2 = Function.prototype.call; - map = function(obj, cb) { - var result = {}, thisArg = arguments[2]; - callable2(cb); - forEach2(obj, function(value2, key, targetObj, index) { - result[key] = call2.call(cb, thisArg, value2, key, targetObj, index); - }); - return result; - }; - return map; -} -var nextTick; -var hasRequiredNextTick; -function requireNextTick() { - if (hasRequiredNextTick) return nextTick; - hasRequiredNextTick = 1; - var ensureCallable = function(fn) { - if (typeof fn !== "function") throw new TypeError(fn + " is not a function"); - return fn; - }; - var byObserver = function(Observer) { - var node = document.createTextNode(""), queue, currentQueue, i = 0; - new Observer(function() { - var callback; - if (!queue) { - if (!currentQueue) return; - queue = currentQueue; - } else if (currentQueue) { - queue = currentQueue.concat(queue); - } - currentQueue = queue; - queue = null; - if (typeof currentQueue === "function") { - callback = currentQueue; - currentQueue = null; - callback(); - return; - } - node.data = i = ++i % 2; - while (currentQueue) { - callback = currentQueue.shift(); - if (!currentQueue.length) currentQueue = null; - callback(); - } - }).observe(node, { characterData: true }); - return function(fn) { - ensureCallable(fn); - if (queue) { - if (typeof queue === "function") queue = [queue, fn]; - else queue.push(fn); - return; - } - queue = fn; - node.data = i = ++i % 2; - }; - }; - nextTick = function() { - if (typeof process === "object" && process && typeof process.nextTick === "function") { - return process.nextTick; - } - if (typeof queueMicrotask === "function") { - return function(cb) { - queueMicrotask(ensureCallable(cb)); - }; - } - if (typeof document === "object" && document) { - if (typeof MutationObserver === "function") return byObserver(MutationObserver); - if (typeof WebKitMutationObserver === "function") return byObserver(WebKitMutationObserver); - } - if (typeof setImmediate === "function") { - return function(cb) { - setImmediate(ensureCallable(cb)); - }; - } - if (typeof setTimeout === "function" || typeof setTimeout === "object") { - return function(cb) { - setTimeout(ensureCallable(cb), 0); - }; - } - return null; - }(); - return nextTick; -} -var hasRequiredAsync; -function requireAsync() { - if (hasRequiredAsync) return async; - hasRequiredAsync = 1; - var aFrom = requireFrom(), objectMap = requireMap(), mixin2 = requireMixin(), defineLength2 = _defineLengthExports, nextTick2 = requireNextTick(); - var slice2 = Array.prototype.slice, apply2 = Function.prototype.apply, create2 = Object.create; - registeredExtensions.async = function(tbi, conf) { - var waiting = create2(null), cache = create2(null), base = conf.memoized, original = conf.original, currentCallback, currentContext, currentArgs; - conf.memoized = defineLength2(function(arg) { - var args = arguments, last = args[args.length - 1]; - if (typeof last === "function") { - currentCallback = last; - args = slice2.call(args, 0, -1); - } - return base.apply(currentContext = this, currentArgs = args); - }, base); - try { - mixin2(conf.memoized, base); - } catch (ignore) { - } - conf.on("get", function(id) { - var cb, context, args; - if (!currentCallback) return; - if (waiting[id]) { - if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback]; - else waiting[id].push(currentCallback); - currentCallback = null; - return; - } - cb = currentCallback; - context = currentContext; - args = currentArgs; - currentCallback = currentContext = currentArgs = null; - nextTick2(function() { - var data; - if (hasOwnProperty.call(cache, id)) { - data = cache[id]; - conf.emit("getasync", id, args, context); - apply2.call(cb, data.context, data.args); - } else { - currentCallback = cb; - currentContext = context; - currentArgs = args; - base.apply(context, args); - } - }); - }); - conf.original = function() { - var args, cb, origCb, result; - if (!currentCallback) return apply2.call(original, this, arguments); - args = aFrom(arguments); - cb = function self3(err) { - var cb2, args2, id = self3.id; - if (id == null) { - nextTick2(apply2.bind(self3, this, arguments)); - return void 0; - } - delete self3.id; - cb2 = waiting[id]; - delete waiting[id]; - if (!cb2) { - return void 0; - } - args2 = aFrom(arguments); - if (conf.has(id)) { - if (err) { - conf.delete(id); - } else { - cache[id] = { context: this, args: args2 }; - conf.emit("setasync", id, typeof cb2 === "function" ? 1 : cb2.length); - } - } - if (typeof cb2 === "function") { - result = apply2.call(cb2, this, args2); - } else { - cb2.forEach(function(cb3) { - result = apply2.call(cb3, this, args2); - }, this); - } - return result; - }; - origCb = currentCallback; - currentCallback = currentContext = currentArgs = null; - args.push(cb); - result = apply2.call(original, this, args); - cb.cb = origCb; - currentCallback = cb; - return result; - }; - conf.on("set", function(id) { - if (!currentCallback) { - conf.delete(id); - return; - } - if (waiting[id]) { - if (typeof waiting[id] === "function") waiting[id] = [waiting[id], currentCallback.cb]; - else waiting[id].push(currentCallback.cb); - } else { - waiting[id] = currentCallback.cb; - } - delete currentCallback.cb; - currentCallback.id = id; - currentCallback = null; - }); - conf.on("delete", function(id) { - var result; - if (hasOwnProperty.call(waiting, id)) return; - if (!cache[id]) return; - result = cache[id]; - delete cache[id]; - conf.emit("deleteasync", id, slice2.call(result.args, 1)); - }); - conf.on("clear", function() { - var oldCache = cache; - cache = create2(null); - conf.emit( - "clearasync", - objectMap(oldCache, function(data) { - return slice2.call(data.args, 1); - }) - ); - }); - }; - return async; -} -var promise = {}; -var primitiveSet; -var hasRequiredPrimitiveSet; -function requirePrimitiveSet() { - if (hasRequiredPrimitiveSet) return primitiveSet; - hasRequiredPrimitiveSet = 1; - var forEach2 = Array.prototype.forEach, create2 = Object.create; - primitiveSet = function(arg) { - var set = create2(null); - forEach2.call(arguments, function(name) { - set[name] = true; - }); - return set; - }; - return primitiveSet; -} -var isCallable; -var hasRequiredIsCallable; -function requireIsCallable() { - if (hasRequiredIsCallable) return isCallable; - hasRequiredIsCallable = 1; - isCallable = function(obj) { - return typeof obj === "function"; - }; - return isCallable; -} -var validateStringifiable; -var hasRequiredValidateStringifiable; -function requireValidateStringifiable() { - if (hasRequiredValidateStringifiable) return validateStringifiable; - hasRequiredValidateStringifiable = 1; - var isCallable2 = requireIsCallable(); - validateStringifiable = function(stringifiable) { - try { - if (stringifiable && isCallable2(stringifiable.toString)) return stringifiable.toString(); - return String(stringifiable); - } catch (e) { - throw new TypeError("Passed argument cannot be stringifed"); - } - }; - return validateStringifiable; -} -var validateStringifiableValue; -var hasRequiredValidateStringifiableValue; -function requireValidateStringifiableValue() { - if (hasRequiredValidateStringifiableValue) return validateStringifiableValue; - hasRequiredValidateStringifiableValue = 1; - var ensureValue = validValue, stringifiable = requireValidateStringifiable(); - validateStringifiableValue = function(value2) { - return stringifiable(ensureValue(value2)); - }; - return validateStringifiableValue; -} -var safeToString; -var hasRequiredSafeToString; -function requireSafeToString() { - if (hasRequiredSafeToString) return safeToString; - hasRequiredSafeToString = 1; - var isCallable2 = requireIsCallable(); - safeToString = function(value2) { - try { - if (value2 && isCallable2(value2.toString)) return value2.toString(); - return String(value2); - } catch (e) { - return ""; - } - }; - return safeToString; -} -var toShortStringRepresentation; -var hasRequiredToShortStringRepresentation; -function requireToShortStringRepresentation() { - if (hasRequiredToShortStringRepresentation) return toShortStringRepresentation; - hasRequiredToShortStringRepresentation = 1; - var safeToString2 = requireSafeToString(); - var reNewLine = /[\n\r\u2028\u2029]/g; - toShortStringRepresentation = function(value2) { - var string = safeToString2(value2); - if (string.length > 100) string = string.slice(0, 99) + "…"; - string = string.replace(reNewLine, function(char) { - return JSON.stringify(char).slice(1, -1); - }); - return string; - }; - return toShortStringRepresentation; -} -var isPromise = { exports: {} }; -var hasRequiredIsPromise; -function requireIsPromise() { - if (hasRequiredIsPromise) return isPromise.exports; - hasRequiredIsPromise = 1; - isPromise.exports = isPromise$1; - isPromise.exports.default = isPromise$1; - function isPromise$1(obj) { - return !!obj && (typeof obj === "object" || typeof obj === "function") && typeof obj.then === "function"; - } - return isPromise.exports; -} -var hasRequiredPromise; -function requirePromise() { - if (hasRequiredPromise) return promise; - hasRequiredPromise = 1; - var objectMap = requireMap(), primitiveSet2 = requirePrimitiveSet(), ensureString = requireValidateStringifiableValue(), toShortString = requireToShortStringRepresentation(), isPromise2 = requireIsPromise(), nextTick2 = requireNextTick(); - var create2 = Object.create, supportedModes = primitiveSet2("then", "then:finally", "done", "done:finally"); - registeredExtensions.promise = function(mode, conf) { - var waiting = create2(null), cache = create2(null), promises = create2(null); - if (mode === true) { - mode = null; - } else { - mode = ensureString(mode); - if (!supportedModes[mode]) { - throw new TypeError("'" + toShortString(mode) + "' is not valid promise mode"); - } - } - conf.on("set", function(id, ignore, promise2) { - var isFailed = false; - if (!isPromise2(promise2)) { - cache[id] = promise2; - conf.emit("setasync", id, 1); - return; - } - waiting[id] = 1; - promises[id] = promise2; - var onSuccess = function(result) { - var count = waiting[id]; - if (isFailed) { - throw new Error( - "Memoizee error: Detected unordered then|done & finally resolution, which in turn makes proper detection of success/failure impossible (when in 'done:finally' mode)\nConsider to rely on 'then' or 'done' mode instead." - ); - } - if (!count) return; - delete waiting[id]; - cache[id] = result; - conf.emit("setasync", id, count); - }; - var onFailure = function() { - isFailed = true; - if (!waiting[id]) return; - delete waiting[id]; - delete promises[id]; - conf.delete(id); - }; - var resolvedMode = mode; - if (!resolvedMode) resolvedMode = "then"; - if (resolvedMode === "then") { - var nextTickFailure = function() { - nextTick2(onFailure); - }; - promise2 = promise2.then(function(result) { - nextTick2(onSuccess.bind(this, result)); - }, nextTickFailure); - if (typeof promise2.finally === "function") { - promise2.finally(nextTickFailure); - } - } else if (resolvedMode === "done") { - if (typeof promise2.done !== "function") { - throw new Error( - "Memoizee error: Retrieved promise does not implement 'done' in 'done' mode" - ); - } - promise2.done(onSuccess, onFailure); - } else if (resolvedMode === "done:finally") { - if (typeof promise2.done !== "function") { - throw new Error( - "Memoizee error: Retrieved promise does not implement 'done' in 'done:finally' mode" - ); - } - if (typeof promise2.finally !== "function") { - throw new Error( - "Memoizee error: Retrieved promise does not implement 'finally' in 'done:finally' mode" - ); - } - promise2.done(onSuccess); - promise2.finally(onFailure); - } - }); - conf.on("get", function(id, args, context) { - var promise2; - if (waiting[id]) { - ++waiting[id]; - return; - } - promise2 = promises[id]; - var emit2 = function() { - conf.emit("getasync", id, args, context); - }; - if (isPromise2(promise2)) { - if (typeof promise2.done === "function") promise2.done(emit2); - else { - promise2.then(function() { - nextTick2(emit2); - }); - } - } else { - emit2(); - } - }); - conf.on("delete", function(id) { - delete promises[id]; - if (waiting[id]) { - delete waiting[id]; - return; - } - if (!hasOwnProperty.call(cache, id)) return; - var result = cache[id]; - delete cache[id]; - conf.emit("deleteasync", id, [result]); - }); - conf.on("clear", function() { - var oldCache = cache; - cache = create2(null); - waiting = create2(null); - promises = create2(null); - conf.emit("clearasync", objectMap(oldCache, function(data) { - return [data]; - })); - }); - }; - return promise; -} -var dispose = {}; -var hasRequiredDispose; -function requireDispose() { - if (hasRequiredDispose) return dispose; - hasRequiredDispose = 1; - var callable2 = validCallable, forEach2 = forEach$1, extensions2 = registeredExtensions, apply2 = Function.prototype.apply; - extensions2.dispose = function(dispose2, conf, options) { - var del; - callable2(dispose2); - if (options.async && extensions2.async || options.promise && extensions2.promise) { - conf.on( - "deleteasync", - del = function(id, resultArray) { - apply2.call(dispose2, null, resultArray); - } - ); - conf.on("clearasync", function(cache) { - forEach2(cache, function(result, id) { - del(id, result); - }); - }); - return; - } - conf.on("delete", del = function(id, result) { - dispose2(result); - }); - conf.on("clear", function(cache) { - forEach2(cache, function(result, id) { - del(id, result); - }); - }); - }; - return dispose; -} -var maxAge = {}; -var maxTimeout; -var hasRequiredMaxTimeout; -function requireMaxTimeout() { - if (hasRequiredMaxTimeout) return maxTimeout; - hasRequiredMaxTimeout = 1; - maxTimeout = 2147483647; - return maxTimeout; -} -var validTimeout; -var hasRequiredValidTimeout; -function requireValidTimeout() { - if (hasRequiredValidTimeout) return validTimeout; - hasRequiredValidTimeout = 1; - var toPosInt2 = toPosInteger, maxTimeout2 = requireMaxTimeout(); - validTimeout = function(value2) { - value2 = toPosInt2(value2); - if (value2 > maxTimeout2) throw new TypeError(value2 + " exceeds maximum possible timeout"); - return value2; - }; - return validTimeout; -} -var hasRequiredMaxAge; -function requireMaxAge() { - if (hasRequiredMaxAge) return maxAge; - hasRequiredMaxAge = 1; - var aFrom = requireFrom(), forEach2 = forEach$1, nextTick2 = requireNextTick(), isPromise2 = requireIsPromise(), timeout = requireValidTimeout(), extensions2 = registeredExtensions; - var noop2 = Function.prototype, max2 = Math.max, min = Math.min, create2 = Object.create; - extensions2.maxAge = function(maxAge2, conf, options) { - var timeouts, postfix, preFetchAge, preFetchTimeouts; - maxAge2 = timeout(maxAge2); - if (!maxAge2) return; - timeouts = create2(null); - postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; - conf.on("set" + postfix, function(id) { - timeouts[id] = setTimeout(function() { - conf.delete(id); - }, maxAge2); - if (typeof timeouts[id].unref === "function") timeouts[id].unref(); - if (!preFetchTimeouts) return; - if (preFetchTimeouts[id]) { - if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); - } - preFetchTimeouts[id] = setTimeout(function() { - delete preFetchTimeouts[id]; - }, preFetchAge); - if (typeof preFetchTimeouts[id].unref === "function") preFetchTimeouts[id].unref(); - }); - conf.on("delete" + postfix, function(id) { - clearTimeout(timeouts[id]); - delete timeouts[id]; - if (!preFetchTimeouts) return; - if (preFetchTimeouts[id] !== "nextTick") clearTimeout(preFetchTimeouts[id]); - delete preFetchTimeouts[id]; - }); - if (options.preFetch) { - if (options.preFetch === true || isNaN(options.preFetch)) { - preFetchAge = 0.333; - } else { - preFetchAge = max2(min(Number(options.preFetch), 1), 0); - } - if (preFetchAge) { - preFetchTimeouts = {}; - preFetchAge = (1 - preFetchAge) * maxAge2; - conf.on("get" + postfix, function(id, args, context) { - if (!preFetchTimeouts[id]) { - preFetchTimeouts[id] = "nextTick"; - nextTick2(function() { - var result; - if (preFetchTimeouts[id] !== "nextTick") return; - delete preFetchTimeouts[id]; - conf.delete(id); - if (options.async) { - args = aFrom(args); - args.push(noop2); - } - result = conf.memoized.apply(context, args); - if (options.promise) { - if (isPromise2(result)) { - if (typeof result.done === "function") result.done(noop2, noop2); - else result.then(noop2, noop2); - } - } - }); - } - }); - } - } - conf.on("clear" + postfix, function() { - forEach2(timeouts, function(id) { - clearTimeout(id); - }); - timeouts = {}; - if (preFetchTimeouts) { - forEach2(preFetchTimeouts, function(id) { - if (id !== "nextTick") clearTimeout(id); - }); - preFetchTimeouts = {}; - } - }); - }; - return maxAge; -} -var max = {}; -var lruQueue; -var hasRequiredLruQueue; -function requireLruQueue() { - if (hasRequiredLruQueue) return lruQueue; - hasRequiredLruQueue = 1; - var toPosInt2 = toPosInteger, create2 = Object.create, hasOwnProperty2 = Object.prototype.hasOwnProperty; - lruQueue = function(limit) { - var size = 0, base = 1, queue = create2(null), map2 = create2(null), index = 0, del; - limit = toPosInt2(limit); - return { - hit: function(id) { - var oldIndex = map2[id], nuIndex = ++index; - queue[nuIndex] = id; - map2[id] = nuIndex; - if (!oldIndex) { - ++size; - if (size <= limit) return; - id = queue[base]; - del(id); - return id; - } - delete queue[oldIndex]; - if (base !== oldIndex) return; - while (!hasOwnProperty2.call(queue, ++base)) continue; - }, - delete: del = function(id) { - var oldIndex = map2[id]; - if (!oldIndex) return; - delete queue[oldIndex]; - delete map2[id]; - --size; - if (base !== oldIndex) return; - if (!size) { - index = 0; - base = 1; - return; - } - while (!hasOwnProperty2.call(queue, ++base)) continue; - }, - clear: function() { - size = 0; - base = 1; - queue = create2(null); - map2 = create2(null); - index = 0; - } - }; - }; - return lruQueue; -} -var hasRequiredMax; -function requireMax() { - if (hasRequiredMax) return max; - hasRequiredMax = 1; - var toPosInteger$1 = toPosInteger, lruQueue2 = requireLruQueue(), extensions2 = registeredExtensions; - extensions2.max = function(max2, conf, options) { - var postfix, queue, hit; - max2 = toPosInteger$1(max2); - if (!max2) return; - queue = lruQueue2(max2); - postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; - conf.on( - "set" + postfix, - hit = function(id) { - id = queue.hit(id); - if (id === void 0) return; - conf.delete(id); - } - ); - conf.on("get" + postfix, hit); - conf.on("delete" + postfix, queue.delete); - conf.on("clear" + postfix, queue.clear); - }; - return max; -} -var refCounter = {}; -var hasRequiredRefCounter; -function requireRefCounter() { - if (hasRequiredRefCounter) return refCounter; - hasRequiredRefCounter = 1; - var d2 = dExports, extensions2 = registeredExtensions, create2 = Object.create, defineProperties2 = Object.defineProperties; - extensions2.refCounter = function(ignore, conf, options) { - var cache, postfix; - cache = create2(null); - postfix = options.async && extensions2.async || options.promise && extensions2.promise ? "async" : ""; - conf.on("set" + postfix, function(id, length) { - cache[id] = length || 1; - }); - conf.on("get" + postfix, function(id) { - ++cache[id]; - }); - conf.on("delete" + postfix, function(id) { - delete cache[id]; - }); - conf.on("clear" + postfix, function() { - cache = {}; - }); - defineProperties2(conf.memoized, { - deleteRef: d2(function() { - var id = conf.get(arguments); - if (id === null) return null; - if (!cache[id]) return null; - if (!--cache[id]) { - conf.delete(id); - return true; - } - return false; - }), - getRefCount: d2(function() { - var id = conf.get(arguments); - if (id === null) return 0; - if (!cache[id]) return 0; - return cache[id]; - }) - }); - }; - return refCounter; -} -var normalizeOpts = normalizeOptions, resolveLength = resolveLength$2, plain = plain$1; -var memoizee = function(fn) { - var options = normalizeOpts(arguments[1]), length; - if (!options.normalizer) { - length = options.length = resolveLength(options.length, fn.length, options.async); - if (length !== 0) { - if (options.primitive) { - if (length === false) { - options.normalizer = requirePrimitive(); - } else if (length > 1) { - options.normalizer = requireGetPrimitiveFixed()(length); - } - } else if (length === false) options.normalizer = requireGet()(); - else if (length === 1) options.normalizer = requireGet1()(); - else options.normalizer = requireGetFixed()(length); - } - } - if (options.async) requireAsync(); - if (options.promise) requirePromise(); - if (options.dispose) requireDispose(); - if (options.maxAge) requireMaxAge(); - if (options.max) requireMax(); - if (options.refCounter) requireRefCounter(); - return plain(fn, options); -}; -const memoize = /* @__PURE__ */ getDefaultExportFromCjs(memoizee); -function _defineProperty$1(e, r, t) { - return (r = _toPropertyKey$1(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey$1(t) { - var i = _toPrimitive$1(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive$1(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -class ChartModel { - constructor(dh) { - _defineProperty$1(this, "dh", void 0); - _defineProperty$1(this, "listeners", void 0); - _defineProperty$1(this, "formatter", void 0); - _defineProperty$1(this, "renderOptions", void 0); - _defineProperty$1(this, "rect", void 0); - _defineProperty$1(this, "isDownsamplingDisabled", void 0); - _defineProperty$1(this, "title", void 0); - this.dh = dh; - this.listeners = []; - this.isDownsamplingDisabled = false; - } - /** Formatter settings for the chart, such as how to format dates and numbers */ - getData() { - return []; - } - getDefaultTitle() { - return ""; - } - getLayout() { - return {}; - } - getFilterColumnMap() { - return /* @__PURE__ */ new Map(); - } - isFilterRequired() { - return false; - } - // eslint-disable-next-line @typescript-eslint/no-empty-function - setFilter(filter) { - } - /** - * Close this model, clean up any underlying subscriptions - */ - // eslint-disable-next-line @typescript-eslint/no-empty-function - close() { - } - /** - * Set the formatter to use when charting the data. - * @param formatter The formatter to use to format the charting data - */ - setFormatter(formatter) { - this.formatter = formatter; - } - /** - * Set additional options for rendering the chart - * @param renderOptions Options for rendering the chart - */ - setRenderOptions(renderOptions) { - this.renderOptions = renderOptions; - } - /** - * Disable downsampling - * @param isDownsamplingDisabled True if downsampling should be disabled - */ - setDownsamplingDisabled(isDownsamplingDisabled) { - this.isDownsamplingDisabled = isDownsamplingDisabled; - } - /** - * Set the dimensions of the plot. May be needed to evaluate some of the percents - * @param rect The bounding rectangle of the plot - */ - setDimensions(rect) { - this.rect = rect; - } - setTitle(title) { - this.title = title; - } - /** - * Subscribe to this ChartModel and start listening for all events. - * @param callback Callback when an event occurs - */ - subscribe(callback) { - this.listeners.push(callback); - } - unsubscribe(callback) { - this.listeners = this.listeners.filter((listener) => listener !== callback); - } - fireEvent(event) { - for (var i = 0; i < this.listeners.length; i += 1) { - this.listeners[i](event); - } - } - fireUpdate(data) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_UPDATED, { - detail: data - })); - } - fireDisconnect() { - this.fireEvent(new CustomEvent(ChartModel.EVENT_DISCONNECT)); - } - fireReconnect() { - this.fireEvent(new CustomEvent(ChartModel.EVENT_RECONNECT)); - } - fireDownsampleStart(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLESTARTED, { - detail - })); - } - fireDownsampleFinish(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLEFINISHED, { - detail - })); - } - fireDownsampleFail(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLEFAILED, { - detail - })); - } - fireDownsampleNeeded(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_DOWNSAMPLENEEDED, { - detail - })); - } - fireLoadFinished() { - this.fireEvent(new CustomEvent(ChartModel.EVENT_LOADFINISHED)); - } - fireError(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_ERROR, { - detail - })); - } - fireBlocker(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_BLOCKER, { - detail - })); - } - fireBlockerClear() { - this.fireEvent(new CustomEvent(ChartModel.EVENT_BLOCKER_CLEAR)); - } - fireLayoutUpdated(detail) { - this.fireEvent(new CustomEvent(ChartModel.EVENT_LAYOUT_UPDATED, { - detail - })); - } -} -_defineProperty$1(ChartModel, "EVENT_UPDATED", "ChartModel.EVENT_UPDATED"); -_defineProperty$1(ChartModel, "EVENT_DISCONNECT", "ChartModel.EVENT_DISCONNECT"); -_defineProperty$1(ChartModel, "EVENT_RECONNECT", "ChartModel.EVENT_RECONNECT"); -_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLESTARTED", "ChartModel.EVENT_DOWNSAMPLESTARTED"); -_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLEFINISHED", "ChartModel.EVENT_DOWNSAMPLEFINISHED"); -_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLEFAILED", "ChartModel.EVENT_DOWNSAMPLEFAILED"); -_defineProperty$1(ChartModel, "EVENT_DOWNSAMPLENEEDED", "ChartModel.EVENT_DOWNSAMPLENEEDED"); -_defineProperty$1(ChartModel, "EVENT_LOADFINISHED", "ChartModel.EVENT_LOADFINISHED"); -_defineProperty$1(ChartModel, "EVENT_ERROR", "ChartModel.EVENT_ERROR"); -_defineProperty$1(ChartModel, "EVENT_BLOCKER", "ChartModel.EVENT_BLOCKER"); -_defineProperty$1(ChartModel, "EVENT_BLOCKER_CLEAR", "ChartModel.EVENT_BLOCKER_CLEAR"); -_defineProperty$1(ChartModel, "EVENT_LAYOUT_UPDATED", "ChartModel.EVENT_LAYOUT_UPDATED"); -function ownKeys(e, r) { - var t = Object.keys(e); - if (Object.getOwnPropertySymbols) { - var o = Object.getOwnPropertySymbols(e); - r && (o = o.filter(function(r2) { - return Object.getOwnPropertyDescriptor(e, r2).enumerable; - })), t.push.apply(t, o); - } - return t; -} -function _objectSpread(e) { - for (var r = 1; r < arguments.length; r++) { - var t = null != arguments[r] ? arguments[r] : {}; - r % 2 ? ownKeys(Object(t), true).forEach(function(r2) { - _defineProperty(e, r2, t[r2]); - }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function(r2) { - Object.defineProperty(e, r2, Object.getOwnPropertyDescriptor(t, r2)); - }); - } - return e; -} -function _defineProperty(e, r, t) { - return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: true, configurable: true, writable: true }) : e[r] = t, e; -} -function _toPropertyKey(t) { - var i = _toPrimitive(t, "string"); - return "symbol" == typeof i ? i : i + ""; -} -function _toPrimitive(t, r) { - if ("object" != typeof t || !t) return t; - var e = t[Symbol.toPrimitive]; - if (void 0 !== e) { - var i = e.call(t, r); - if ("object" != typeof i) return i; - throw new TypeError("@@toPrimitive must return a primitive value."); - } - return ("string" === r ? String : Number)(t); -} -var log$1 = Log.module("FigureChartModel"); -class FigureChartModel extends ChartModel { - /** - * @param dh JSAPI instance - * @param figure The figure object created by the API - * @param settings Chart settings - */ - constructor(dh, figure) { - var _this; - var settings = arguments.length > 2 && arguments[2] !== void 0 ? arguments[2] : {}; - super(dh); - _this = this; - _defineProperty(this, "chartUtils", void 0); - _defineProperty(this, "dh", void 0); - _defineProperty(this, "figure", void 0); - _defineProperty(this, "settings", void 0); - _defineProperty(this, "data", void 0); - _defineProperty(this, "layout", void 0); - _defineProperty(this, "seriesDataMap", void 0); - _defineProperty(this, "pendingSeries", void 0); - _defineProperty(this, "oneClicks", void 0); - _defineProperty(this, "filterColumnMap", void 0); - _defineProperty(this, "lastFilter", void 0); - _defineProperty(this, "isConnected", void 0); - _defineProperty(this, "seriesToProcess", void 0); - _defineProperty(this, "addPendingSeries", lodashExports.debounce(() => { - var axisTypeMap = ChartUtils.getAxisTypeMap(this.figure); - var { - pendingSeries - } = this; - var _loop = function _loop2() { - var _chart$showLegend; - var series = pendingSeries[i]; - var chart = _this.figure.charts.find((c) => c.series.includes(series)); - _this.addSeries(series, axisTypeMap, (_chart$showLegend = chart === null || chart === void 0 ? void 0 : chart.showLegend) !== null && _chart$showLegend !== void 0 ? _chart$showLegend : null); - series.subscribe(); - }; - for (var i = 0; i < pendingSeries.length; i += 1) { - _loop(); - } - this.pendingSeries = []; - }, FigureChartModel.ADD_SERIES_DEBOUNCE)); - _defineProperty(this, "getTimeZone", memoize((columnType, formatter) => { - if (formatter != null) { - var dataFormatter = formatter.getColumnTypeFormatter(columnType); - if (dataFormatter != null) { - return dataFormatter.dhTimeZone; - } - } - return void 0; - })); - _defineProperty(this, "getValueTranslator", memoize((columnType, formatter) => { - var timeZone = this.getTimeZone(columnType, formatter); - return (value2) => this.chartUtils.unwrapValue(value2, timeZone); - })); - _defineProperty(this, "getValueParser", memoize((columnType, formatter) => { - var timeZone = this.getTimeZone(columnType, formatter); - return (value2) => this.chartUtils.wrapValue(value2, columnType, timeZone); - })); - _defineProperty(this, "getRangeParser", memoize((columnType, formatter) => (range) => { - var [rangeStart, rangeEnd] = range; - var valueParser = this.getValueParser(columnType, formatter); - rangeStart = valueParser(rangeStart); - rangeEnd = valueParser(rangeEnd); - return [rangeStart, rangeEnd]; - })); - _defineProperty(this, "getAxisRangeParser", memoize((chart, formatter) => (axis) => { - var source = ChartUtils.getSourceForAxis(chart, axis); - if (source != null) { - return this.getRangeParser(source.columnType, formatter); - } - return (range) => range; - })); - this.handleFigureUpdated = this.handleFigureUpdated.bind(this); - this.handleFigureDisconnected = this.handleFigureDisconnected.bind(this); - this.handleFigureReconnected = this.handleFigureReconnected.bind(this); - this.handleFigureSeriesAdded = this.handleFigureSeriesAdded.bind(this); - this.handleDownsampleStart = this.handleDownsampleStart.bind(this); - this.handleDownsampleFinish = this.handleDownsampleFinish.bind(this); - this.handleDownsampleFail = this.handleDownsampleFail.bind(this); - this.handleDownsampleNeeded = this.handleDownsampleNeeded.bind(this); - this.handleRequestFailed = this.handleRequestFailed.bind(this); - this.dh = dh; - this.chartUtils = new ChartUtils(dh); - this.figure = figure; - this.settings = settings; - this.data = []; - this.layout = { - grid: { - rows: figure.rows, - columns: figure.cols, - pattern: "independent" - } - }; - this.seriesDataMap = /* @__PURE__ */ new Map(); - this.pendingSeries = []; - this.oneClicks = []; - this.filterColumnMap = /* @__PURE__ */ new Map(); - this.lastFilter = /* @__PURE__ */ new Map(); - this.isConnected = true; - this.seriesToProcess = /* @__PURE__ */ new Set(); - this.setTitle(this.getDefaultTitle()); - this.initAllSeries(); - this.updateAxisPositions(); - this.startListeningFigure(); - } - // Assume figure is connected to start - close() { - this.figure.close(); - this.addPendingSeries.cancel(); - this.stopListeningFigure(); - } - getDefaultTitle() { - if (this.figure.title != null && this.figure.title.length > 0) { - return this.figure.title; - } - if (this.figure.charts.length === 1) { - var _this$figure$charts$; - return (_this$figure$charts$ = this.figure.charts[0].title) !== null && _this$figure$charts$ !== void 0 ? _this$figure$charts$ : ""; - } - return ""; - } - initAllSeries() { - var _this2 = this; - this.oneClicks = []; - this.filterColumnMap.clear(); - var { - charts - } = this.figure; - var axisTypeMap = ChartUtils.getAxisTypeMap(this.figure); - var activeSeriesNames = []; - this.seriesToProcess = /* @__PURE__ */ new Set(); - var _loop2 = function _loop22() { - var chart = charts[i]; - for (var j = 0; j < chart.series.length; j += 1) { - var series = chart.series[j]; - activeSeriesNames.push(series.name); - _this2.addSeries(series, axisTypeMap, chart.showLegend); - } - var { - axes, - title - } = chart; - if (title != null && title.length > 0 && (charts.length > 1 || _this2.figure.title != null)) { - var xAxis = axes.find((axis) => axis.type === _this2.dh.plot.AxisType.X); - var yAxis = axes.find((axis) => axis.type === _this2.dh.plot.AxisType.Y); - if (xAxis == null || yAxis == null) { - log$1.warn("Chart title provided, but unknown how to map to the correct axes for this chart type", chart); - } else { - var _axisTypeMap$get$find, _axisTypeMap$get, _axisTypeMap$get$find2, _axisTypeMap$get2; - var xAxisIndex = ((_axisTypeMap$get$find = (_axisTypeMap$get = axisTypeMap.get(xAxis.type)) === null || _axisTypeMap$get === void 0 ? void 0 : _axisTypeMap$get.findIndex((a) => a === xAxis)) !== null && _axisTypeMap$get$find !== void 0 ? _axisTypeMap$get$find : 0) + 1; - var yAxisIndex = ((_axisTypeMap$get$find2 = (_axisTypeMap$get2 = axisTypeMap.get(yAxis.type)) === null || _axisTypeMap$get2 === void 0 ? void 0 : _axisTypeMap$get2.findIndex((a) => a === yAxis)) !== null && _axisTypeMap$get$find2 !== void 0 ? _axisTypeMap$get$find2 : 0) + 1; - var annotation = { - align: "center", - x: 0.5, - y: 1, - yshift: 17, - text: title, - showarrow: false, - // Typing is incorrect in Plotly for this, as it doesn't seem to be typed for the "domain" part: https://plotly.com/javascript/reference/layout/annotations/#layout-annotations-items-annotation-xref - xref: "x".concat(xAxisIndex, " domain"), - yref: "y".concat(yAxisIndex, " domain") - }; - if (_this2.layout.annotations == null) { - _this2.layout.annotations = [annotation]; - } else { - _this2.layout.annotations.push(annotation); - } - } - } - }; - for (var i = 0; i < charts.length; i += 1) { - _loop2(); - } - var allSeriesNames = [...this.seriesDataMap.keys()]; - var inactiveSeriesNames = allSeriesNames.filter((seriesName2) => activeSeriesNames.indexOf(seriesName2) < 0); - for (var _i = 0; _i < inactiveSeriesNames.length; _i += 1) { - var seriesName = inactiveSeriesNames[_i]; - this.seriesDataMap.delete(seriesName); - } - } - /** - * Add a series to the model - * @param series Series object to add - * @param axisTypeMap Map of axis type to the axes in this Figure - * @param showLegend Whether this series should show the legend or not - */ - addSeries(series, axisTypeMap, showLegend) { - var _this$renderOptions$w, _this$renderOptions; - var { - dh - } = this; - var seriesData = this.chartUtils.makeSeriesDataFromSeries(series, axisTypeMap, ChartUtils.getSeriesVisibility(series.name, this.settings), showLegend, (_this$renderOptions$w = (_this$renderOptions = this.renderOptions) === null || _this$renderOptions === void 0 ? void 0 : _this$renderOptions.webgl) !== null && _this$renderOptions$w !== void 0 ? _this$renderOptions$w : true); - this.seriesDataMap.set(series.name, seriesData); - this.seriesToProcess.add(series.name); - this.data = [...this.seriesDataMap.values()]; - if (series.plotStyle === dh.plot.SeriesPlotStyle.STACKED_BAR) { - this.layout.barmode = "stack"; - } else if (series.plotStyle === dh.plot.SeriesPlotStyle.PIE) { - this.layout.hiddenlabels = ChartUtils.getHiddenLabels(this.settings); - } - this.layout.showlegend = this.data.length > 1 || series.plotStyle === dh.plot.SeriesPlotStyle.PIE ? showLegend !== null && showLegend !== void 0 ? showLegend : void 0 : false; - if (series.oneClick != null) { - var { - oneClick - } = series; - var { - columns - } = oneClick; - for (var i = 0; i < columns.length; i += 1) { - this.filterColumnMap.set(columns[i].name, columns[i]); - } - this.oneClicks.push(oneClick); - } - this.updateLayoutFormats(); - } - // We need to debounce adding series so we subscribe to them all in the same tick - // This should no longer be necessary after IDS-5049 lands - subscribe(callback) { - super.subscribe(callback); - if (this.listeners.length === 1) { - this.initAllSeries(); - this.subscribeFigure(); - } - } - unsubscribe(callback) { - super.unsubscribe(callback); - if (this.listeners.length === 0) { - this.unsubscribeFigure(); - } - } - subscribeFigure() { - if (!this.isConnected) { - log$1.debug("Ignoring subscribe when figure in disconnected state"); - return; - } - this.figure.subscribe(this.isDownsamplingDisabled ? this.dh.plot.DownsampleOptions.DISABLE : this.dh.plot.DownsampleOptions.DEFAULT); - if (this.figure.errors.length > 0) { - log$1.error("Errors in figure", this.figure.errors); - this.fireError(this.figure.errors); - } - } - unsubscribeFigure() { - this.figure.unsubscribe(); - } - startListeningFigure() { - var { - dh - } = this; - this.figure.addEventListener(dh.plot.Figure.EVENT_UPDATED, this.handleFigureUpdated); - this.figure.addEventListener(dh.plot.Figure.EVENT_SERIES_ADDED, this.handleFigureSeriesAdded); - this.figure.addEventListener(dh.plot.Figure.EVENT_DISCONNECT, this.handleFigureDisconnected); - this.figure.addEventListener(dh.plot.Figure.EVENT_RECONNECT, this.handleFigureReconnected); - this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLESTARTED, this.handleDownsampleStart); - this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFINISHED, this.handleDownsampleFinish); - this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFAILED, this.handleDownsampleFail); - this.figure.addEventListener(dh.plot.Figure.EVENT_DOWNSAMPLENEEDED, this.handleDownsampleNeeded); - this.figure.addEventListener(dh.Client.EVENT_REQUEST_FAILED, this.handleRequestFailed); - } - stopListeningFigure() { - var { - dh - } = this; - this.figure.removeEventListener(dh.plot.Figure.EVENT_UPDATED, this.handleFigureUpdated); - this.figure.removeEventListener(dh.plot.Figure.EVENT_SERIES_ADDED, this.handleFigureSeriesAdded); - this.figure.removeEventListener(dh.plot.Figure.EVENT_DISCONNECT, this.handleFigureDisconnected); - this.figure.removeEventListener(dh.plot.Figure.EVENT_RECONNECT, this.handleFigureReconnected); - this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLESTARTED, this.handleDownsampleStart); - this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFINISHED, this.handleDownsampleFinish); - this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLEFAILED, this.handleDownsampleFail); - this.figure.removeEventListener(dh.plot.Figure.EVENT_DOWNSAMPLENEEDED, this.handleDownsampleNeeded); - this.figure.removeEventListener(dh.Client.EVENT_REQUEST_FAILED, this.handleRequestFailed); - } - /** Gets the parser for a value with the provided column type */ - /** - * Gets the range parser for a particular column type - */ - /** - * Gets the parser for parsing the range from an axis within the given chart - */ - handleDownsampleStart(event) { - log$1.debug("Downsample started", event); - this.fireDownsampleStart(event.detail); - } - handleDownsampleFinish(event) { - log$1.debug("Downsample finished", event); - this.fireDownsampleFinish(event.detail); - } - handleDownsampleFail(event) { - log$1.error("Downsample failed", event); - this.fireDownsampleFail(event.detail); - } - handleDownsampleNeeded(event) { - log$1.info("Downsample needed", event); - this.fireDownsampleNeeded(event.detail); - } - handleFigureUpdated(event) { - var { - detail: figureUpdateEvent - } = event; - var { - series: seriesArray - } = figureUpdateEvent; - log$1.debug2("handleFigureUpdated", seriesArray); - for (var i = 0; i < seriesArray.length; i += 1) { - var series = seriesArray[i]; - log$1.debug2("handleFigureUpdated updating series", series.name); - var { - sources - } = series; - for (var j = 0; j < sources.length; j += 1) { - var source = sources[j]; - var { - columnType, - type - } = source; - var valueTranslator = this.getValueTranslator(columnType, this.formatter); - var dataArray = figureUpdateEvent.getArray(series, type, valueTranslator); - this.setDataArrayForSeries(series, type, dataArray); - } - this.seriesToProcess.delete(series.name); - this.cleanSeries(series); - } - if (this.seriesToProcess.size === 0) { - this.fireLoadFinished(); - } - var { - data - } = this; - this.fireUpdate(data); - } - handleRequestFailed(event) { - log$1.error("Request failed", event); - this.fireError(["".concat(event.detail)]); - } - /** - * Resubscribe to the figure, should be done if settings change - */ - resubscribe() { - if (this.listeners.length > 0) { - this.unsubscribeFigure(); - this.subscribeFigure(); - } - } - setFormatter(formatter) { - super.setFormatter(formatter); - this.updateLayoutFormats(); - this.resubscribe(); - } - setRenderOptions(renderOptions) { - super.setRenderOptions(renderOptions); - this.initAllSeries(); - } - setDownsamplingDisabled(isDownsamplingDisabled) { - super.setDownsamplingDisabled(isDownsamplingDisabled); - this.resubscribe(); - } - handleFigureDisconnected(event) { - log$1.debug("Figure disconnected", event); - this.isConnected = false; - if (this.listeners.length > 0) { - this.unsubscribeFigure(); - } - this.fireDisconnect(); - } - handleFigureReconnected(event) { - log$1.debug("Figure reconnected", event); - this.isConnected = true; - this.initAllSeries(); - this.fireReconnect(); - if (this.listeners.length > 0) { - this.subscribeFigure(); - } - } - handleFigureSeriesAdded(event) { - var { - detail: series - } = event; - log$1.debug("handleFigureSeriesAdded", series); - this.pendingSeries.push(series); - this.addPendingSeries(); - } - setDimensions(rect) { - super.setDimensions(rect); - this.updateAxisPositions(); - } - setTitle(title) { - var _match$length, _match; - super.setTitle(title); - var subtitleCount = (_match$length = (_match = (title !== null && title !== void 0 ? title : "").match(/
/g)) === null || _match === void 0 ? void 0 : _match.length) !== null && _match$length !== void 0 ? _match$length : 0; - var margin = ChartUtils.DEFAULT_MARGIN.t + subtitleCount * ChartUtils.SUBTITLE_LINE_HEIGHT; - if (this.layout.margin) { - this.layout.margin.t = margin; - } else { - this.layout.margin = { - t: margin - }; - } - if (typeof this.layout.title === "string") { - this.layout.title = title; - } else { - this.layout.title = _objectSpread({}, this.layout.title); - this.layout.title.text = title; - this.layout.title.pad = _objectSpread({}, this.layout.title.pad); - this.layout.title.pad.t = ChartUtils.DEFAULT_TITLE_PADDING.t + subtitleCount * ChartUtils.SUBTITLE_LINE_HEIGHT * 0.5; - } - this.fireLayoutUpdated({ - title: this.layout.title - }); - } - getPlotWidth() { - var _this$layout$margin$l, _this$layout$margin, _this$layout$margin$r, _this$layout$margin2; - if (!this.rect || !this.rect.width) { - return 0; - } - return Math.max(this.rect.width - ((_this$layout$margin$l = (_this$layout$margin = this.layout.margin) === null || _this$layout$margin === void 0 ? void 0 : _this$layout$margin.l) !== null && _this$layout$margin$l !== void 0 ? _this$layout$margin$l : 0) - ((_this$layout$margin$r = (_this$layout$margin2 = this.layout.margin) === null || _this$layout$margin2 === void 0 ? void 0 : _this$layout$margin2.r) !== null && _this$layout$margin$r !== void 0 ? _this$layout$margin$r : 0), 0); - } - getPlotHeight() { - var _this$layout$margin$t, _this$layout$margin3, _this$layout$margin$b, _this$layout$margin4; - if (!this.rect || !this.rect.height) { - return 0; - } - return Math.max(this.rect.height - ((_this$layout$margin$t = (_this$layout$margin3 = this.layout.margin) === null || _this$layout$margin3 === void 0 ? void 0 : _this$layout$margin3.t) !== null && _this$layout$margin$t !== void 0 ? _this$layout$margin$t : 0) - ((_this$layout$margin$b = (_this$layout$margin4 = this.layout.margin) === null || _this$layout$margin4 === void 0 ? void 0 : _this$layout$margin4.b) !== null && _this$layout$margin$b !== void 0 ? _this$layout$margin$b : 0), 0); - } - updateAxisPositions() { - var plotWidth = this.getPlotWidth(); - var plotHeight = this.getPlotHeight(); - this.chartUtils.updateFigureAxes(this.layout, this.figure, (chart) => this.getAxisRangeParser(chart, this.formatter), plotWidth, plotHeight); - } - /** - * Updates the format patterns used - */ - updateLayoutFormats() { - if (!this.formatter) { - return; - } - var axisFormats = this.chartUtils.getAxisFormats(this.figure, this.formatter); - axisFormats.forEach((axisFormat, axisLayoutProperty) => { - log$1.debug("Assigning ".concat(axisLayoutProperty), this.layout[axisLayoutProperty], axisFormat); - var props = this.layout[axisLayoutProperty]; - if (props != null) { - Object.assign(props, axisFormat); - } else { - log$1.debug("Ignoring null layout.".concat(axisLayoutProperty)); - } - }); - } - /** - * Set a specific array for the array of series properties specified. - * @param series The series to set the data array for. - * @param sourceType The source type within that series to set the data for. - * @param dataArray The array to use for the data for this series source. - */ - setDataArrayForSeries(series, sourceType, dataArray) { - var { - name, - plotStyle - } = series; - var seriesData = this.seriesDataMap.get(name); - var property = this.chartUtils.getPlotlyProperty(plotStyle, sourceType); - if (seriesData) { - lodashExports.set(seriesData, property, dataArray); - } - } - /** - * After setting all the data in the series data, we may need to adjust some other properties - * Eg. Calculating the width from the xLow/xHigh values; Plot.ly uses `width` instead of a low/high - * value for x. - * @param series The series to clean the data for - */ - cleanSeries(series) { - var { - dh - } = this; - var { - name, - plotStyle - } = series; - var seriesData = this.seriesDataMap.get(name); - if (seriesData == null) { - return; - } - if (plotStyle === dh.plot.SeriesPlotStyle.HISTOGRAM) { - var { - xLow, - xHigh - } = seriesData; - if (xLow && xHigh && xLow.length === xHigh.length) { - var width = []; - for (var i = 0; i < xLow.length; i += 1) { - width.push(xHigh[i] - xLow[i]); - } - seriesData.width = width; - } - } else if (plotStyle === dh.plot.SeriesPlotStyle.LINE || plotStyle === dh.plot.SeriesPlotStyle.ERROR_BAR || plotStyle === dh.plot.SeriesPlotStyle.BAR) { - var { - x, - xLow: _xLow, - xHigh: _xHigh, - y, - yLow, - yHigh - } = seriesData; - if (_xLow && _xHigh && _xLow !== x) { - seriesData.error_x = ChartUtils.getPlotlyErrorBars(x, _xLow, _xHigh); - } - if (yLow && yHigh && yLow !== y) { - seriesData.error_y = ChartUtils.getPlotlyErrorBars(y, yLow, yHigh); - } - } else if (plotStyle === dh.plot.SeriesPlotStyle.TREEMAP) { - var { - ids, - labels - } = seriesData; - if (ids !== void 0 && labels === void 0) { - seriesData.labels = ids; - } - } - } - getData() { - return this.data; - } - getLayout() { - return this.layout; - } - getFilterColumnMap() { - return new Map(this.filterColumnMap); - } - isFilterRequired() { - return this.oneClicks.find((oneClick) => oneClick.requireAllFiltersToDisplay) != null; - } - /** - * Sets the filter on the model. Will only set the values that have changed. - * @param filterMap Map of filter column names to values - */ - setFilter(filterMap) { - var _this3 = this; - if (this.oneClicks.length === 0) { - log$1.warn("Trying to set a filter, but no one click!"); - return; - } - log$1.debug("setFilter", filterMap); - var _loop3 = function _loop32() { - var oneClick = _this3.oneClicks[i]; - var { - columns - } = oneClick; - var keys2 = /* @__PURE__ */ new Set([...filterMap.keys(), ..._this3.lastFilter.keys()]); - keys2.forEach((key) => { - var value2 = filterMap.get(key); - if (_this3.lastFilter.get(key) !== value2 && columns.find((column) => column.name === key) != null) { - oneClick.setValueForColumn(key, value2); - } - }); - }; - for (var i = 0; i < this.oneClicks.length; i += 1) { - _loop3(); - } - this.lastFilter = new Map(filterMap); - } - setFigure(figure) { - this.close(); - this.figure = figure; - this.setTitle(this.getDefaultTitle()); - this.initAllSeries(); - this.updateAxisPositions(); - this.startListeningFigure(); - if (this.listeners.length > 0) { - this.subscribeFigure(); - } - } - updateSettings(settings) { - this.settings = settings; - } -} -_defineProperty(FigureChartModel, "ADD_SERIES_DEBOUNCE", 50); -function asyncGeneratorStep(n2, t, e, r, o, a, c) { - try { - var i = n2[a](c), u = i.value; - } catch (n3) { - return void e(n3); - } - i.done ? t(u) : Promise.resolve(u).then(r, o); -} -function _asyncToGenerator(n2) { - return function() { - var t = this, e = arguments; - return new Promise(function(r, o) { - var a = n2.apply(t, e); - function _next(n3) { - asyncGeneratorStep(a, r, o, _next, _throw, "next", n3); - } - function _throw(n3) { - asyncGeneratorStep(a, r, o, _next, _throw, "throw", n3); - } - _next(void 0); - }); - }; -} -class ChartModelFactory { - /** - * Creates a model from the settings provided. - * Tries to create a Figure in the API with it. - * @param dh JSAPI instance - * @param settings The chart builder settings - * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated - * @param settings.series The column names to use for creating the series of this chart - * @param settings.type Chart builder type, from ChartBuilder.types - * @param settings.xAxis The column name to use for the x-axis - * @param [settings.hiddenSeries] Array of hidden series names - * @param table The table to build the model for - * @returns The ChartModel Promise representing the figure - * CRA sets tsconfig to type check JS based on jsdoc comments. It isn't able to figure out FigureChartModel extends ChartModel - * This causes TS issues in 1 or 2 spots. Once this is TS it can be returned to just FigureChartModel - */ - static makeModelFromSettings(dh, settings, table) { - return _asyncToGenerator(function* () { - var figure = yield ChartModelFactory.makeFigureFromSettings(dh, settings, table); - return new FigureChartModel(dh, figure, settings); - })(); - } - /** - * Creates a model from the settings provided. - * Tries to create a Figure in the API with it. - * @param dh DH JSAPI instance - * @param settings The chart builder settings - * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated - * @param settings.series The column names to use for creating the series of this chart - * @param settings.type Chart builder type, from ChartBuilder.types - * @param settings.xAxis The column name to use for the x-axis - * @param [settings.hiddenSeries] Array of hidden series names - * @param table The table to build the model for - * @returns The Figure created with the settings provided - */ - static makeFigureFromSettings(dh, settings, table) { - return _asyncToGenerator(function* () { - var tableCopy = yield table.copy(); - tableCopy.applyCustomColumns(table.customColumns); - tableCopy.applyFilter(table.filter); - tableCopy.applySort(table.sort); - return dh.plot.Figure.create(new ChartUtils(dh).makeFigureSettings(settings, tableCopy)); - })(); - } - /** - * Creates a model from the settings provided. - * Tries to create a Figure in the API with it. - * @param dh DH JSAPI instance - * @param settings The chart builder settings - * @param settings.isLinked Whether the newly created chart should stay linked with the original table, update when filters are updated - * @param settings.series The column names to use for creating the series of this chart - * @param settings.type Chart builder type, from ChartBuilder.types - * @param settings.xAxis The column name to use for the x-axis - * @param [settings.hiddenSeries] Array of hidden series names - * @param figure The figure to build the model for - * @returns The FigureChartModel representing the figure - * CRA sets tsconfig to type check JS based on jsdoc comments. It isn't able to figure out FigureChartModel extends ChartModel - * This causes TS issues in 1 or 2 spots. Once this is TS it can be returned to just FigureChartModel - */ - static makeModel(dh, settings, figure) { - return _asyncToGenerator(function* () { - return new FigureChartModel(dh, figure, settings); - })(); - } -} -Log.module("@deephaven/jsapi-bootstrap.ApiBootstrap"); -var ApiContext = /* @__PURE__ */ React.createContext(null); -function useContextOrThrow(context) { - var message = arguments.length > 1 && arguments[1] !== void 0 ? arguments[1] : "No value available in context. Was code wrapped in a provider?"; - var value2 = React.useContext(context); - if (value2 == null) { - throw new Error(message); - } - return value2; -} -function useApi() { - return useContextOrThrow(ApiContext, "No API available in useApi. Was code wrapped in ApiBootstrap or ApiContext.Provider?"); -} -const log = Log.module("@deephaven/js-plugin-grid-toolbar"); -const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; -function GridToolbarPanelMiddleware({ - Component, - fetch, - glEventHub, - ...props -}) { - const dh = useApi(); - const [view, setView] = React.useState("grid"); - const [chartModel, setChartModel] = React.useState(null); - const [isBuilding, setIsBuilding] = React.useState(false); - React.useEffect( - () => () => { - chartModel == null ? void 0 : chartModel.close(); - }, - [chartModel] - ); - const handleChart = React.useCallback(async () => { - if (view === "chart") { - setView("grid"); - return; - } - setIsBuilding(true); - try { - const table = await fetch(); - if (!(table == null ? void 0 : table.columns) || table.columns.length < 2) { - log.warn("Table has fewer than 2 columns; cannot build chart"); - return; - } - const settings = { - type: "LINE", - series: [table.columns[1].name], - xAxis: table.columns[0].name - }; - const model = await ChartModelFactory.makeModelFromSettings( - dh, - settings, - table - ); - setChartModel(model); - setView("chart"); - } catch (e) { - log.error("Failed to build chart model", e); - } finally { - setIsBuilding(false); - } - }, [dh, fetch, view]); - const handleResetFilters = React.useCallback(() => { - log.info("Reset Filters clicked"); - glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub]); - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - disabled: isBuilding, - onClick: handleChart, - children: view === "chart" ? "Grid" : "Chart" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === "chart" && chartModel != null ? ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - /* @__PURE__ */ jsxRuntimeExports.jsx(LazyChart, { model: chartModel, className: "h-100 w-100" }) - ) : ( - // eslint-disable-next-line react/jsx-props-no-spreading - /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { fetch, glEventHub, ...props }) - ) }) - ] }); -} -const GridToolbarPlugin = { - name: "@deephaven/js-plugin-grid-toolbar", - type: plugin.PluginType.WIDGET_PLUGIN, - supportedTypes: [ - "Table", - "TreeTable", - "HierarchicalTable", - "PartitionedTable" - ], - component: GridToolbarMiddleware, - panelComponent: GridToolbarPanelMiddleware, - isMiddleware: true -}; -exports.ChartModel = ChartModel; -exports.ChartUtils = ChartUtils; -exports.DateUtils = DateUtils; -exports.GridToolbarMiddleware = GridToolbarMiddleware; -exports.GridToolbarPlugin = GridToolbarPlugin; -exports.TableUtils = TableUtils; -exports.assertInstanceOf = assertInstanceOf; -exports.assign = assign$1; -exports.bindAllMethods = bindAllMethods; -exports.commonjsGlobal = commonjsGlobal; -exports.contains = contains$1; -exports.dExports = dExports; -exports.getAugmentedNamespace = getAugmentedNamespace; -exports.getDefaultExportFromCjs = getDefaultExportFromCjs; -exports.is = is$4; -exports.is$1 = is$3; -exports.is$2 = is; -exports.isObject = isObject$1; -exports.isValue = isValue$6; -exports.jsxRuntimeExports = jsxRuntimeExports; -exports.normalizeOptions = normalizeOptions; -exports.objectAssign = objectAssign; -exports.requireEs6Symbol = requireEs6Symbol; -exports.requireFrom = requireFrom; -exports.requireIsArguments = requireIsArguments; -exports.requireIsString = requireIsString; -exports.requireMap = requireMap; -exports.validCallable = validCallable; -exports.validValue = validValue; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js index fbd8c36ae..a508d4563 100644 --- a/plugins/grid-toolbar/src/js/dist/bundle/index.js +++ b/plugins/grid-toolbar/src/js/dist/bundle/index.js @@ -1,6 +1,241 @@ "use strict"; Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); -const index = require("./index-nioU_Oes.cjs"); -exports.GridToolbarMiddleware = index.GridToolbarMiddleware; -exports.GridToolbarPlugin = index.GridToolbarPlugin; -exports.default = index.GridToolbarPlugin; +const plugin = require("@deephaven/plugin"); +const require$$1 = require("react"); +const Log = require("@deephaven/log"); +const chart = require("@deephaven/chart"); +const jsapiBootstrap = require("@deephaven/jsapi-bootstrap"); +var jsxRuntime = { exports: {} }; +var reactJsxRuntime_production_min = {}; +/* +object-assign +(c) Sindre Sorhus +@license MIT +*/ +var getOwnPropertySymbols = Object.getOwnPropertySymbols; +var hasOwnProperty = Object.prototype.hasOwnProperty; +var propIsEnumerable = Object.prototype.propertyIsEnumerable; +function toObject(val) { + if (val === null || val === void 0) { + throw new TypeError("Object.assign cannot be called with null or undefined"); + } + return Object(val); +} +function shouldUseNative() { + try { + if (!Object.assign) { + return false; + } + var test1 = new String("abc"); + test1[5] = "de"; + if (Object.getOwnPropertyNames(test1)[0] === "5") { + return false; + } + var test2 = {}; + for (var i = 0; i < 10; i++) { + test2["_" + String.fromCharCode(i)] = i; + } + var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { + return test2[n2]; + }); + if (order2.join("") !== "0123456789") { + return false; + } + var test3 = {}; + "abcdefghijklmnopqrst".split("").forEach(function(letter) { + test3[letter] = letter; + }); + if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { + return false; + } + return true; + } catch (err) { + return false; + } +} +shouldUseNative() ? Object.assign : function(target, source) { + var from; + var to = toObject(target); + var symbols; + for (var s = 1; s < arguments.length; s++) { + from = Object(arguments[s]); + for (var key in from) { + if (hasOwnProperty.call(from, key)) { + to[key] = from[key]; + } + } + if (getOwnPropertySymbols) { + symbols = getOwnPropertySymbols(from); + for (var i = 0; i < symbols.length; i++) { + if (propIsEnumerable.call(from, symbols[i])) { + to[symbols[i]] = from[symbols[i]]; + } + } + } + } + return to; +}; +/** @license React v17.0.2 + * react-jsx-runtime.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ +var f = require$$1, g = 60103; +reactJsxRuntime_production_min.Fragment = 60107; +if ("function" === typeof Symbol && Symbol.for) { + var h = Symbol.for; + g = h("react.element"); + reactJsxRuntime_production_min.Fragment = h("react.fragment"); +} +var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; +function q(c, a, k) { + var b, d = {}, e = null, l = null; + void 0 !== k && (e = "" + k); + void 0 !== a.key && (e = "" + a.key); + void 0 !== a.ref && (l = a.ref); + for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); + if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); + return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; +} +reactJsxRuntime_production_min.jsx = q; +reactJsxRuntime_production_min.jsxs = q; +{ + jsxRuntime.exports = reactJsxRuntime_production_min; +} +var jsxRuntimeExports = jsxRuntime.exports; +const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar"); +function GridToolbarMiddleware({ + Component, + ...props +}) { + const handleExport = require$$1.useCallback(() => { + log$1.info("Export clicked"); + }, []); + const handleResetFilters = require$$1.useCallback(() => { + log$1.info("[0] Reset Filters clicked", props, Component); + }, [props, Component]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleExport, + children: "Export" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) + ] }); +} +const log = Log.module("@deephaven/js-plugin-grid-toolbar"); +const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; +function GridToolbarPanelMiddleware({ + Component, + fetch, + glEventHub, + ...props +}) { + const dh = jsapiBootstrap.useApi(); + const [view, setView] = require$$1.useState("grid"); + const [chartModel, setChartModel] = require$$1.useState(null); + const [isBuilding, setIsBuilding] = require$$1.useState(false); + require$$1.useEffect( + () => () => { + chartModel == null ? void 0 : chartModel.close(); + }, + [chartModel] + ); + const handleChart = require$$1.useCallback(async () => { + if (view === "chart") { + setView("grid"); + return; + } + setIsBuilding(true); + try { + const table = await fetch(); + if (!(table == null ? void 0 : table.columns) || table.columns.length < 2) { + log.warn("Table has fewer than 2 columns; cannot build chart"); + return; + } + const settings = { + type: "LINE", + series: [table.columns[1].name], + xAxis: table.columns[0].name + }; + const model = await chart.ChartModelFactory.makeModelFromSettings( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + dh, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + settings, + table + ); + setChartModel(model); + setView("chart"); + } catch (e) { + log.error("Failed to build chart model", e); + } finally { + setIsBuilding(false); + } + }, [dh, fetch, view]); + const handleResetFilters = require$$1.useCallback(() => { + log.info("Reset Filters clicked"); + glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); + }, [glEventHub]); + return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + disabled: isBuilding, + onClick: handleChart, + children: view === "chart" ? "Grid" : "Chart" + } + ), + /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + onClick: handleResetFilters, + children: "Reset Filters" + } + ) + ] }), + /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === "chart" && chartModel != null ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(chart.Chart, { model: chartModel }) }) : ( + // eslint-disable-next-line react/jsx-props-no-spreading + /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { fetch, glEventHub, ...props }) + ) }) + ] }); +} +const GridToolbarPlugin = { + name: "@deephaven/js-plugin-grid-toolbar", + type: plugin.PluginType.WIDGET_PLUGIN, + supportedTypes: [ + "Table", + "TreeTable", + "HierarchicalTable", + "PartitionedTable" + ], + component: GridToolbarMiddleware, + panelComponent: GridToolbarPanelMiddleware, + isMiddleware: true +}; +exports.GridToolbarMiddleware = GridToolbarMiddleware; +exports.GridToolbarPlugin = GridToolbarPlugin; +exports.default = GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/dist/bundle/style.css b/plugins/grid-toolbar/src/js/dist/bundle/style.css deleted file mode 100644 index 0edc904dd..000000000 --- a/plugins/grid-toolbar/src/js/dist/bundle/style.css +++ /dev/null @@ -1,88 +0,0 @@ -.maplibregl-map{font:12px/20px Helvetica Neue,Arial,Helvetica,sans-serif;overflow:hidden;position:relative;-webkit-tap-highlight-color:rgb(0 0 0/0)}.maplibregl-canvas{left:0;position:absolute;top:0}.maplibregl-map:fullscreen{height:100%;width:100%}.maplibregl-ctrl-group button.maplibregl-ctrl-compass{touch-action:none}.maplibregl-canvas-container.maplibregl-interactive,.maplibregl-ctrl-group button.maplibregl-ctrl-compass{cursor:grab;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-canvas-container.maplibregl-interactive.maplibregl-track-pointer{cursor:pointer}.maplibregl-canvas-container.maplibregl-interactive:active,.maplibregl-ctrl-group button.maplibregl-ctrl-compass:active{cursor:grabbing}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-canvas-container.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:pinch-zoom}.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan,.maplibregl-canvas-container.maplibregl-touch-zoom-rotate.maplibregl-touch-drag-pan .maplibregl-canvas{touch-action:none}.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures,.maplibregl-canvas-container.maplibregl-touch-drag-pan.maplibregl-cooperative-gestures .maplibregl-canvas{touch-action:pan-x pan-y}.maplibregl-ctrl-bottom-left,.maplibregl-ctrl-bottom-right,.maplibregl-ctrl-top-left,.maplibregl-ctrl-top-right{pointer-events:none;position:absolute;z-index:2}.maplibregl-ctrl-top-left{left:0;top:0}.maplibregl-ctrl-top-right{right:0;top:0}.maplibregl-ctrl-bottom-left{bottom:0;left:0}.maplibregl-ctrl-bottom-right{bottom:0;right:0}.maplibregl-ctrl{clear:both;pointer-events:auto;transform:translate(0)}.maplibregl-ctrl-top-left .maplibregl-ctrl{float:left;margin:10px 0 0 10px}.maplibregl-ctrl-top-right .maplibregl-ctrl{float:right;margin:10px 10px 0 0}.maplibregl-ctrl-bottom-left .maplibregl-ctrl{float:left;margin:0 0 10px 10px}.maplibregl-ctrl-bottom-right .maplibregl-ctrl{float:right;margin:0 10px 10px 0}.maplibregl-ctrl-group{background:#fff;border-radius:4px}.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px rgba(0,0,0,.1)}@media (forced-colors:active){.maplibregl-ctrl-group:not(:empty){box-shadow:0 0 0 2px ButtonText}}.maplibregl-ctrl-group button{background-color:transparent;border:0;box-sizing:border-box;cursor:pointer;display:block;height:29px;outline:none;padding:0;width:29px}.maplibregl-ctrl-group button+button{border-top:1px solid #ddd}.maplibregl-ctrl button .maplibregl-ctrl-icon{background-position:50%;background-repeat:no-repeat;display:block;height:100%;width:100%}@media (forced-colors:active){.maplibregl-ctrl-icon{background-color:transparent}.maplibregl-ctrl-group button+button{border-top:1px solid ButtonText}}.maplibregl-ctrl button::-moz-focus-inner{border:0;padding:0}.maplibregl-ctrl-attrib-button:focus,.maplibregl-ctrl-group button:focus{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl button:disabled{cursor:not-allowed}.maplibregl-ctrl button:disabled .maplibregl-ctrl-icon{opacity:.25}.maplibregl-ctrl button:not(:disabled):hover{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-group button:focus:focus-visible{box-shadow:0 0 2px 2px #0096ff}.maplibregl-ctrl-group button:focus:not(:focus-visible){box-shadow:none}.maplibregl-ctrl-group button:focus:first-child{border-radius:4px 4px 0 0}.maplibregl-ctrl-group button:focus:last-child{border-radius:0 0 4px 4px}.maplibregl-ctrl-group button:focus:only-child{border-radius:inherit}.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-zoom-out .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M10 13c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h9c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-zoom-in .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M14.5 8.5c-.75 0-1.5.75-1.5 1.5v3h-3c-.75 0-1.5.75-1.5 1.5S9.25 16 10 16h3v3c0 .75.75 1.5 1.5 1.5S16 19.75 16 19v-3h3c.75 0 1.5-.75 1.5-1.5S19.75 13 19 13h-3v-3c0-.75-.75-1.5-1.5-1.5'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-fullscreen .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M24 16v5.5c0 1.75-.75 2.5-2.5 2.5H16v-1l3-1.5-4-5.5 1-1 5.5 4 1.5-3zM6 16l1.5 3 5.5-4 1 1-4 5.5 3 1.5v1H7.5C5.75 24 5 23.25 5 21.5V16zm7-11v1l-3 1.5 4 5.5-1 1-5.5-4L6 13H5V7.5C5 5.75 5.75 5 7.5 5zm11 2.5c0-1.75-.75-2.5-2.5-2.5H16v1l3 1.5-4 5.5 1 1 5.5-4 1.5 3h1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-shrink .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='M18.5 16c-1.75 0-2.5.75-2.5 2.5V24h1l1.5-3 5.5 4 1-1-4-5.5 3-1.5v-1zM13 18.5c0-1.75-.75-2.5-2.5-2.5H5v1l3 1.5L4 24l1 1 5.5-4 1.5 3h1zm3-8c0 1.75.75 2.5 2.5 2.5H24v-1l-3-1.5L25 5l-1-1-5.5 4L17 5h-1zM10.5 13c1.75 0 2.5-.75 2.5-2.5V5h-1l-1.5 3L5 4 4 5l4 5.5L5 12v1z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-compass .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 29 29'%3E%3Cpath d='m10.5 14 4-8 4 8z'/%3E%3Cpath fill='%23ccc' d='m10.5 16 4 8 4-8z'/%3E%3C/svg%3E")}}.maplibregl-ctrl button.maplibregl-ctrl-terrain .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%23333' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-terrain-enabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='22' height='22' fill='%2333b5e5' viewBox='0 0 22 22'%3E%3Cpath d='m1.754 13.406 4.453-4.851 3.09 3.09 3.281 3.277.969-.969-3.309-3.312 3.844-4.121 6.148 6.886h1.082v-.855l-7.207-8.07-4.84 5.187L6.169 6.57l-5.48 5.965v.871ZM.688 16.844h20.625v1.375H.688Zm0 0'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23333' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23aaa' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-waiting .maplibregl-ctrl-icon{animation:maplibregl-spin 2s linear infinite}@media (forced-colors:active){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23fff' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23999' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-active-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e58978' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%2333b5e5' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate.maplibregl-ctrl-geolocate-background-error .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23e54e33' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl button.maplibregl-ctrl-geolocate .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3C/svg%3E")}.maplibregl-ctrl button.maplibregl-ctrl-geolocate:disabled .maplibregl-ctrl-icon{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='29' height='29' fill='%23666' viewBox='0 0 20 20'%3E%3Cpath d='M10 4C9 4 9 5 9 5v.1A5 5 0 0 0 5.1 9H5s-1 0-1 1 1 1 1 1h.1A5 5 0 0 0 9 14.9v.1s0 1 1 1 1-1 1-1v-.1a5 5 0 0 0 3.9-3.9h.1s1 0 1-1-1-1-1-1h-.1A5 5 0 0 0 11 5.1V5s0-1-1-1m0 2.5a3.5 3.5 0 1 1 0 7 3.5 3.5 0 1 1 0-7'/%3E%3Ccircle cx='10' cy='10' r='2'/%3E%3Cpath fill='red' d='m14 5 1 1-9 9-1-1z'/%3E%3C/svg%3E")}}@keyframes maplibregl-spin{0%{transform:rotate(0deg)}to{transform:rotate(1turn)}}a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E");background-repeat:no-repeat;cursor:pointer;display:block;height:23px;margin:0 0 -4px -4px;overflow:hidden;width:88px}a.maplibregl-ctrl-logo.maplibregl-compact{width:14px}@media (forced-colors:active){a.maplibregl-ctrl-logo{background-color:transparent;background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}@media (forced-colors:active) and (prefers-color-scheme:light){a.maplibregl-ctrl-logo{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='88' height='23' fill='none'%3E%3Cpath fill='%23000' fill-opacity='.4' fill-rule='evenodd' d='M17.408 16.796h-1.827l2.501-12.095h.198l3.324 6.533.988 2.19.988-2.19 3.258-6.533h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.929 5.644h-.098l-2.914-5.644-.757-1.71-.345 1.71zm1.958-3.42-.726 3.663a1.255 1.255 0 0 1-1.232 1.011h-1.827a1.255 1.255 0 0 1-1.229-1.509l2.501-12.095a1.255 1.255 0 0 1 1.23-1.001h.197a1.25 1.25 0 0 1 1.12.685l3.19 6.273 3.125-6.263a1.25 1.25 0 0 1 1.123-.695h.181a1.255 1.255 0 0 1 1.227.991l1.443 6.71a5 5 0 0 1 .314-.787l.009-.016a4.6 4.6 0 0 1 1.777-1.887c.782-.46 1.668-.667 2.611-.667a4.6 4.6 0 0 1 1.7.32l.306.134c.21-.16.474-.256.759-.256h1.694a1.255 1.255 0 0 1 1.212.925 1.255 1.255 0 0 1 1.212-.925h1.711c.284 0 .545.094.755.252.613-.3 1.312-.45 2.075-.45 1.356 0 2.557.445 3.482 1.4q.47.48.763 1.064V4.701a1.255 1.255 0 0 1 1.255-1.255h1.86A1.255 1.255 0 0 1 54.44 4.7v9.194h2.217c.19 0 .37.043.532.118v-4.77c0-.356.147-.678.385-.906a2.42 2.42 0 0 1-.682-1.71c0-.665.267-1.253.735-1.7a2.45 2.45 0 0 1 1.722-.674 2.43 2.43 0 0 1 1.705.675q.318.302.504.683V4.7a1.255 1.255 0 0 1 1.255-1.255h1.744A1.255 1.255 0 0 1 65.812 4.7v3.335a4.8 4.8 0 0 1 1.526-.246c.938 0 1.817.214 2.59.69a4.47 4.47 0 0 1 1.67 1.743v-.98a1.255 1.255 0 0 1 1.256-1.256h1.777c.233 0 .451.064.639.174a3.4 3.4 0 0 1 1.567-.372c.346 0 .861.02 1.285.232a1.25 1.25 0 0 1 .689 1.004 4.7 4.7 0 0 1 .853-.588c.795-.44 1.675-.647 2.61-.647 1.385 0 2.65.39 3.525 1.396.836.938 1.168 2.173 1.168 3.528q-.001.515-.056 1.051a1.255 1.255 0 0 1-.947 1.09l.408.952a1.255 1.255 0 0 1-.477 1.552c-.418.268-.92.463-1.458.612-.613.171-1.304.244-2.049.244-1.06 0-2.043-.207-2.886-.698l-.015-.008c-.798-.48-1.419-1.135-1.818-1.963l-.004-.008a5.8 5.8 0 0 1-.548-2.512q0-.429.053-.843a1.3 1.3 0 0 1-.333-.086l-.166-.004c-.223 0-.426.062-.643.228-.03.024-.142.139-.142.59v3.883a1.255 1.255 0 0 1-1.256 1.256h-1.777a1.255 1.255 0 0 1-1.256-1.256V15.69l-.032.057a4.8 4.8 0 0 1-1.86 1.833 5.04 5.04 0 0 1-2.484.634 4.5 4.5 0 0 1-1.935-.424 1.25 1.25 0 0 1-.764.258h-1.71a1.255 1.255 0 0 1-1.256-1.255V7.687a2.4 2.4 0 0 1-.428.625c.253.23.412.561.412.93v7.553a1.255 1.255 0 0 1-1.256 1.255h-1.843a1.25 1.25 0 0 1-.894-.373c-.228.23-.544.373-.894.373H51.32a1.255 1.255 0 0 1-1.256-1.255v-1.251l-.061.117a4.7 4.7 0 0 1-1.782 1.884 4.77 4.77 0 0 1-2.485.67 5.6 5.6 0 0 1-1.485-.188l.009 2.764a1.255 1.255 0 0 1-1.255 1.259h-1.729a1.255 1.255 0 0 1-1.255-1.255v-3.537a1.255 1.255 0 0 1-1.167.793h-1.679a1.25 1.25 0 0 1-.77-.263 4.5 4.5 0 0 1-1.945.429c-.885 0-1.724-.21-2.495-.632l-.017-.01a5 5 0 0 1-1.081-.836 1.255 1.255 0 0 1-1.254 1.312h-1.81a1.255 1.255 0 0 1-1.228-.99l-.782-3.625-2.044 3.939a1.25 1.25 0 0 1-1.115.676h-.098a1.25 1.25 0 0 1-1.116-.68l-2.061-3.994zM35.92 16.63l.207-.114.223-.15q.493-.356.735-.785l.061-.118.033 1.332h1.678V9.242h-1.694l-.033 1.267q-.133-.329-.526-.658l-.032-.028a3.2 3.2 0 0 0-.668-.428l-.27-.12a3.3 3.3 0 0 0-1.235-.23q-1.136-.001-1.974.493a3.36 3.36 0 0 0-1.3 1.382q-.445.89-.444 2.074 0 1.2.51 2.107a3.8 3.8 0 0 0 1.382 1.381 3.9 3.9 0 0 0 1.893.477q.795 0 1.455-.33zm-2.789-5.38q-.576.675-.575 1.762 0 1.102.559 1.794.576.675 1.645.675a2.25 2.25 0 0 0 .934-.19 2.2 2.2 0 0 0 .468-.29l.178-.161a2.2 2.2 0 0 0 .397-.561q.244-.5.244-1.15v-.115q0-.708-.296-1.267l-.043-.077a2.2 2.2 0 0 0-.633-.709l-.13-.086-.047-.028a2.1 2.1 0 0 0-1.073-.285q-1.052 0-1.629.692zm2.316 2.706c.163-.17.28-.407.28-.83v-.114c0-.292-.06-.508-.15-.68a.96.96 0 0 0-.353-.389.85.85 0 0 0-.464-.127c-.4 0-.56.114-.664.239l-.01.012c-.148.174-.275.45-.275.945 0 .506.122.801.27.99.097.11.266.224.68.224.303 0 .504-.09.687-.269zm7.545 1.705a2.6 2.6 0 0 0 .331.423q.319.33.755.548l.173.074q.65.255 1.49.255 1.02 0 1.844-.493a3.45 3.45 0 0 0 1.316-1.4q.493-.904.493-2.089 0-1.909-.988-2.913-.988-1.02-2.584-1.02-.898 0-1.575.347a3 3 0 0 0-.415.262l-.199.166a3.4 3.4 0 0 0-.64.82V9.242h-1.712v11.553h1.729l-.017-5.134zm.53-1.138q.206.29.48.5l.155.11.053.034q.51.296 1.119.297 1.07 0 1.645-.675.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.435 0-.835.16a2 2 0 0 0-.284.136 2 2 0 0 0-.363.254 2.2 2.2 0 0 0-.46.569l-.082.162a2.6 2.6 0 0 0-.213 1.072v.115q0 .707.296 1.267l.135.211zm.964-.818a1.1 1.1 0 0 0 .367.385.94.94 0 0 0 .476.118c.423 0 .59-.117.687-.23.159-.194.28-.478.28-.95 0-.53-.133-.8-.266-.952l-.021-.025c-.078-.094-.231-.221-.68-.221a1 1 0 0 0-.503.135l-.012.007a.86.86 0 0 0-.335.343c-.073.133-.132.324-.132.614v.115a1.4 1.4 0 0 0 .14.66zm15.7-6.222q.347-.346.346-.856a1.05 1.05 0 0 0-.345-.79 1.18 1.18 0 0 0-.84-.329q-.51 0-.855.33a1.05 1.05 0 0 0-.346.79q0 .51.346.855.345.346.856.346.51 0 .839-.346zm4.337 9.314.033-1.332q.191.403.59.747l.098.081a4 4 0 0 0 .316.224l.223.122a3.2 3.2 0 0 0 1.44.322 3.8 3.8 0 0 0 1.875-.477 3.5 3.5 0 0 0 1.382-1.366q.527-.89.526-2.09 0-1.184-.444-2.073a3.24 3.24 0 0 0-1.283-1.399q-.823-.51-1.942-.51a3.5 3.5 0 0 0-1.527.344l-.086.043-.165.09a3 3 0 0 0-.33.214q-.432.315-.656.707a2 2 0 0 0-.099.198l.082-1.283V4.701h-1.744v12.095zm.473-2.509a2.5 2.5 0 0 0 .566.7q.117.098.245.18l.144.08a2.1 2.1 0 0 0 .975.232q1.07 0 1.645-.675.576-.69.576-1.778 0-1.102-.576-1.777-.56-.691-1.645-.692a2.2 2.2 0 0 0-1.015.235q-.22.113-.415.282l-.15.142a2.1 2.1 0 0 0-.42.594q-.223.479-.223 1.1v.115q0 .705.293 1.26zm2.616-.293c.157-.191.28-.479.28-.967 0-.51-.13-.79-.276-.961l-.021-.026c-.082-.1-.232-.225-.67-.225a.87.87 0 0 0-.681.279l-.012.011c-.154.155-.274.38-.274.807v.115c0 .285.057.499.144.669a1.1 1.1 0 0 0 .367.405c.137.082.28.123.455.123.423 0 .59-.118.686-.23zm8.266-3.013q.345-.13.724-.14l.069-.002q.493 0 .642.099l.247-1.794q-.196-.099-.717-.099a2.3 2.3 0 0 0-.545.063 2 2 0 0 0-.411.148 2.2 2.2 0 0 0-.4.249 2.5 2.5 0 0 0-.485.499 2.7 2.7 0 0 0-.32.581l-.05.137v-1.48h-1.778v7.553h1.777v-3.884q0-.546.159-.943a1.5 1.5 0 0 1 .466-.636 2.5 2.5 0 0 1 .399-.253 2 2 0 0 1 .224-.099zm9.784 2.656.05-.922q0-1.743-.856-2.698-.838-.97-2.584-.97-1.119-.001-2.007.493a3.46 3.46 0 0 0-1.4 1.382q-.493.906-.493 2.106 0 1.07.428 1.975.428.89 1.332 1.432.906.526 2.255.526.973 0 1.668-.185l.044-.012.135-.04q.613-.184.984-.421l-.542-1.267q-.3.162-.642.274l-.297.087q-.51.131-1.3.131-.954 0-1.497-.444a1.6 1.6 0 0 1-.192-.193q-.366-.44-.512-1.234l-.004-.021zm-5.427-1.256-.003.022h3.752v-.138q-.011-.727-.288-1.118a1 1 0 0 0-.156-.176q-.46-.428-1.316-.428-.986 0-1.494.604-.379.45-.494 1.234zm-27.053 2.77V4.7h-1.86v12.095h5.333V15.15zm7.103-5.908v7.553h-1.843V9.242h1.843z'/%3E%3Cpath fill='%23fff' d='m19.63 11.151-.757-1.71-.345 1.71-1.12 5.644h-1.827L18.083 4.7h.197l3.325 6.533.988 2.19.988-2.19L26.839 4.7h.181l2.6 12.095h-1.81l-1.218-5.644-.362-1.71-.658 1.71-2.93 5.644h-.098l-2.913-5.644zm14.836 5.81q-1.02 0-1.893-.478a3.8 3.8 0 0 1-1.381-1.382q-.51-.906-.51-2.106 0-1.185.444-2.074a3.36 3.36 0 0 1 1.3-1.382q.839-.494 1.974-.494a3.3 3.3 0 0 1 1.234.231 3.3 3.3 0 0 1 .97.575q.396.33.527.659l.033-1.267h1.694v7.553H37.18l-.033-1.332q-.279.593-1.02 1.053a3.17 3.17 0 0 1-1.662.444zm.296-1.482q.938 0 1.58-.642.642-.66.642-1.711v-.115q0-.708-.296-1.267a2.2 2.2 0 0 0-.807-.872 2.1 2.1 0 0 0-1.119-.313q-1.053 0-1.629.692-.575.675-.575 1.76 0 1.103.559 1.795.577.675 1.645.675zm6.521-6.237h1.711v1.4q.906-1.597 2.83-1.597 1.596 0 2.584 1.02.988 1.005.988 2.914 0 1.185-.493 2.09a3.46 3.46 0 0 1-1.316 1.399 3.5 3.5 0 0 1-1.844.493q-.954 0-1.662-.329a2.67 2.67 0 0 1-1.086-.97l.017 5.134h-1.728zm4.048 6.22q1.07 0 1.645-.674.577-.69.576-1.762 0-1.119-.576-1.777-.558-.675-1.645-.675-.592 0-1.12.296-.51.28-.822.823-.296.527-.296 1.234v.115q0 .708.296 1.267.313.543.823.855.51.296 1.119.297z'/%3E%3Cpath fill='%23e1e3e9' d='M51.325 4.7h1.86v10.45h3.473v1.646h-5.333zm7.12 4.542h1.843v7.553h-1.843zm.905-1.415a1.16 1.16 0 0 1-.856-.346 1.17 1.17 0 0 1-.346-.856 1.05 1.05 0 0 1 .346-.79q.346-.329.856-.329.494 0 .839.33a1.05 1.05 0 0 1 .345.79 1.16 1.16 0 0 1-.345.855q-.33.346-.84.346zm7.875 9.133a3.17 3.17 0 0 1-1.662-.444q-.723-.46-1.004-1.053l-.033 1.332h-1.71V4.701h1.743v4.657l-.082 1.283q.279-.658 1.086-1.119a3.5 3.5 0 0 1 1.778-.477q1.119 0 1.942.51a3.24 3.24 0 0 1 1.283 1.4q.445.888.444 2.072 0 1.201-.526 2.09a3.5 3.5 0 0 1-1.382 1.366 3.8 3.8 0 0 1-1.876.477zm-.296-1.481q1.069 0 1.645-.675.577-.69.577-1.778 0-1.102-.577-1.776-.56-.691-1.645-.692a2.12 2.12 0 0 0-1.58.659q-.642.641-.642 1.694v.115q0 .71.296 1.267a2.4 2.4 0 0 0 .807.872 2.1 2.1 0 0 0 1.119.313zm5.927-6.237h1.777v1.481q.263-.757.856-1.217a2.14 2.14 0 0 1 1.349-.46q.527 0 .724.098l-.247 1.794q-.149-.099-.642-.099-.774 0-1.416.494-.626.493-.626 1.58v3.883h-1.777V9.242zm9.534 7.718q-1.35 0-2.255-.526-.904-.543-1.332-1.432a4.6 4.6 0 0 1-.428-1.975q0-1.2.493-2.106a3.46 3.46 0 0 1 1.4-1.382q.889-.495 2.007-.494 1.744 0 2.584.97.855.956.856 2.7 0 .444-.05.92h-5.43q.18 1.005.708 1.45.542.443 1.497.443.79 0 1.3-.131a4 4 0 0 0 .938-.362l.542 1.267q-.411.263-1.119.46-.708.198-1.711.197zm1.596-4.558q.016-1.02-.444-1.432-.46-.428-1.316-.428-1.728 0-1.991 1.86z'/%3E%3Cpath d='M5.074 15.948a.484.657 0 0 0-.486.659v1.84a.484.657 0 0 0 .486.659h4.101a.484.657 0 0 0 .486-.659v-1.84a.484.657 0 0 0-.486-.659zm3.56 1.16H5.617v.838h3.017z' style='fill:%23fff;fill-rule:evenodd;stroke-width:1.03600001'/%3E%3Cg style='stroke-width:1.12603545'%3E%3Cpath d='M-9.408-1.416c-3.833-.025-7.056 2.912-7.08 6.615-.02 3.08 1.653 4.832 3.107 6.268.903.892 1.721 1.74 2.32 2.902l-.525-.004c-.543-.003-.992.304-1.24.639a1.87 1.87 0 0 0-.362 1.121l-.011 1.877c-.003.402.104.787.347 1.125.244.338.688.653 1.23.656l4.142.028c.542.003.99-.306 1.238-.641a1.87 1.87 0 0 0 .363-1.121l.012-1.875a1.87 1.87 0 0 0-.348-1.127c-.243-.338-.688-.653-1.23-.656l-.518-.004c.597-1.145 1.425-1.983 2.348-2.87 1.473-1.414 3.18-3.149 3.2-6.226-.016-3.59-2.923-6.684-6.993-6.707m-.006 1.1v.002c3.274.02 5.92 2.532 5.9 5.6-.017 2.706-1.39 4.026-2.863 5.44-1.034.994-2.118 2.033-2.814 3.633-.018.041-.052.055-.075.065q-.013.004-.02.01a.34.34 0 0 1-.226.084.34.34 0 0 1-.224-.086l-.092-.077c-.699-1.615-1.768-2.669-2.781-3.67-1.454-1.435-2.797-2.762-2.78-5.478.02-3.067 2.7-5.545 5.975-5.523m-.02 2.826c-1.62-.01-2.944 1.315-2.955 2.96-.01 1.646 1.295 2.988 2.916 2.999h.002c1.621.01 2.943-1.316 2.953-2.961.011-1.646-1.294-2.988-2.916-2.998m-.005 1.1c1.017.006 1.829.83 1.822 1.89s-.83 1.874-1.848 1.867c-1.018-.006-1.829-.83-1.822-1.89s.83-1.874 1.848-1.868m-2.155 11.857 4.14.025c.271.002.49.305.487.676l-.013 1.875c-.003.37-.224.67-.495.668l-4.14-.025c-.27-.002-.487-.306-.485-.676l.012-1.875c.003-.37.224-.67.494-.668' style='color:%23000;font-style:normal;font-variant:normal;font-weight:400;font-stretch:normal;font-size:medium;line-height:normal;font-family:sans-serif;font-variant-ligatures:normal;font-variant-position:normal;font-variant-caps:normal;font-variant-numeric:normal;font-variant-alternates:normal;font-feature-settings:normal;text-indent:0;text-align:start;text-decoration:none;text-decoration-line:none;text-decoration-style:solid;text-decoration-color:%23000;letter-spacing:normal;word-spacing:normal;text-transform:none;writing-mode:lr-tb;direction:ltr;text-orientation:mixed;dominant-baseline:auto;baseline-shift:baseline;text-anchor:start;white-space:normal;shape-padding:0;clip-rule:evenodd;display:inline;overflow:visible;visibility:visible;opacity:1;isolation:auto;mix-blend-mode:normal;color-interpolation:sRGB;color-interpolation-filters:linearRGB;solid-color:%23000;solid-opacity:1;vector-effect:none;fill:%23000;fill-opacity:.4;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-linecap:butt;stroke-linejoin:miter;stroke-miterlimit:4;stroke-dasharray:none;stroke-dashoffset:0;stroke-opacity:1;color-rendering:auto;image-rendering:auto;shape-rendering:auto;text-rendering:auto' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-9.415-.316C-12.69-.338-15.37 2.14-15.39 5.207c-.017 2.716 1.326 4.041 2.78 5.477 1.013 1 2.081 2.055 2.78 3.67l.092.076a.34.34 0 0 0 .225.086.34.34 0 0 0 .227-.083l.019-.01c.022-.009.057-.024.074-.064.697-1.6 1.78-2.64 2.814-3.634 1.473-1.414 2.847-2.733 2.864-5.44.02-3.067-2.627-5.58-5.901-5.601m-.057 8.784c1.621.011 2.944-1.315 2.955-2.96.01-1.646-1.295-2.988-2.916-2.999-1.622-.01-2.945 1.315-2.955 2.96s1.295 2.989 2.916 3' style='clip-rule:evenodd;fill:%23e1e3e9;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3Cpath d='M-11.594 15.465c-.27-.002-.492.297-.494.668l-.012 1.876c-.003.371.214.673.485.675l4.14.027c.271.002.492-.298.495-.668l.012-1.877c.003-.37-.215-.672-.485-.674z' style='clip-rule:evenodd;fill:%23fff;fill-opacity:1;fill-rule:evenodd;stroke:none;stroke-width:2.47727823;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:.4' transform='translate(15.553 2.85)scale(.88807)'/%3E%3C/g%3E%3C/svg%3E")}}.maplibregl-ctrl.maplibregl-ctrl-attrib{background-color:hsla(0,0%,100%,.5);margin:0;padding:0 5px}@media screen{.maplibregl-ctrl-attrib.maplibregl-compact{background-color:#fff;border-radius:12px;box-sizing:content-box;color:#000;margin:10px;min-height:20px;padding:2px 24px 2px 0;position:relative}.maplibregl-ctrl-attrib.maplibregl-compact-show{padding:2px 28px 2px 8px;visibility:visible}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact-show,.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact-show{border-radius:12px;padding:2px 8px 2px 28px}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-inner{display:none}.maplibregl-ctrl-attrib-button{background-color:hsla(0,0%,100%,.5);background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E");border:0;border-radius:12px;box-sizing:border-box;cursor:pointer;display:none;height:24px;outline:none;position:absolute;right:0;top:0;width:24px}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button{-webkit-appearance:none;-moz-appearance:none;appearance:none;list-style:none}.maplibregl-ctrl-attrib summary.maplibregl-ctrl-attrib-button::-webkit-details-marker{display:none}.maplibregl-ctrl-bottom-left .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-top-left .maplibregl-ctrl-attrib-button{left:0}.maplibregl-ctrl-attrib.maplibregl-compact .maplibregl-ctrl-attrib-button,.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-inner{display:block}.maplibregl-ctrl-attrib.maplibregl-compact-show .maplibregl-ctrl-attrib-button{background-color:rgb(0 0 0/5%)}.maplibregl-ctrl-bottom-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;right:0}.maplibregl-ctrl-top-right>.maplibregl-ctrl-attrib.maplibregl-compact:after{right:0;top:0}.maplibregl-ctrl-top-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{left:0;top:0}.maplibregl-ctrl-bottom-left>.maplibregl-ctrl-attrib.maplibregl-compact:after{bottom:0;left:0}}@media screen and (forced-colors:active){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill='%23fff' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}@media screen and (forced-colors:active) and (prefers-color-scheme:light){.maplibregl-ctrl-attrib.maplibregl-compact:after{background-image:url("data:image/svg+xml;charset=utf-8,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' fill-rule='evenodd' viewBox='0 0 20 20'%3E%3Cpath d='M4 10a6 6 0 1 0 12 0 6 6 0 1 0-12 0m5-3a1 1 0 1 0 2 0 1 1 0 1 0-2 0m0 3a1 1 0 1 1 2 0v3a1 1 0 1 1-2 0'/%3E%3C/svg%3E")}}.maplibregl-ctrl-attrib a{color:rgba(0,0,0,.75);text-decoration:none}.maplibregl-ctrl-attrib a:hover{color:inherit;text-decoration:underline}.maplibregl-attrib-empty{display:none}.maplibregl-ctrl-scale{background-color:hsla(0,0%,100%,.75);border:2px solid #333;border-top:#333;box-sizing:border-box;color:#333;font-size:10px;padding:0 5px}.maplibregl-popup{display:flex;left:0;pointer-events:none;position:absolute;top:0;will-change:transform}.maplibregl-popup-anchor-top,.maplibregl-popup-anchor-top-left,.maplibregl-popup-anchor-top-right{flex-direction:column}.maplibregl-popup-anchor-bottom,.maplibregl-popup-anchor-bottom-left,.maplibregl-popup-anchor-bottom-right{flex-direction:column-reverse}.maplibregl-popup-anchor-left{flex-direction:row}.maplibregl-popup-anchor-right{flex-direction:row-reverse}.maplibregl-popup-tip{border:10px solid transparent;height:0;width:0;z-index:1}.maplibregl-popup-anchor-top .maplibregl-popup-tip{align-self:center;border-bottom-color:#fff;border-top:none}.maplibregl-popup-anchor-top-left .maplibregl-popup-tip{align-self:flex-start;border-bottom-color:#fff;border-left:none;border-top:none}.maplibregl-popup-anchor-top-right .maplibregl-popup-tip{align-self:flex-end;border-bottom-color:#fff;border-right:none;border-top:none}.maplibregl-popup-anchor-bottom .maplibregl-popup-tip{align-self:center;border-bottom:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-tip{align-self:flex-start;border-bottom:none;border-left:none;border-top-color:#fff}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-tip{align-self:flex-end;border-bottom:none;border-right:none;border-top-color:#fff}.maplibregl-popup-anchor-left .maplibregl-popup-tip{align-self:center;border-left:none;border-right-color:#fff}.maplibregl-popup-anchor-right .maplibregl-popup-tip{align-self:center;border-left-color:#fff;border-right:none}.maplibregl-popup-close-button{background-color:transparent;border:0;border-radius:0 3px 0 0;cursor:pointer;position:absolute;right:0;top:0}.maplibregl-popup-close-button:hover{background-color:rgb(0 0 0/5%)}.maplibregl-popup-content{background:#fff;border-radius:3px;box-shadow:0 1px 2px rgba(0,0,0,.1);padding:15px 10px;pointer-events:auto;position:relative}.maplibregl-popup-anchor-top-left .maplibregl-popup-content{border-top-left-radius:0}.maplibregl-popup-anchor-top-right .maplibregl-popup-content{border-top-right-radius:0}.maplibregl-popup-anchor-bottom-left .maplibregl-popup-content{border-bottom-left-radius:0}.maplibregl-popup-anchor-bottom-right .maplibregl-popup-content{border-bottom-right-radius:0}.maplibregl-popup-track-pointer{display:none}.maplibregl-popup-track-pointer *{pointer-events:none;-webkit-user-select:none;-moz-user-select:none;user-select:none}.maplibregl-map:hover .maplibregl-popup-track-pointer{display:flex}.maplibregl-map:active .maplibregl-popup-track-pointer{display:none}.maplibregl-marker{left:0;position:absolute;top:0;transition:opacity .2s;will-change:transform}.maplibregl-user-location-dot,.maplibregl-user-location-dot:before{background-color:#1da1f2;border-radius:50%;height:15px;width:15px}.maplibregl-user-location-dot:before{animation:maplibregl-user-location-dot-pulse 2s infinite;content:"";position:absolute}.maplibregl-user-location-dot:after{border:2px solid #fff;border-radius:50%;box-shadow:0 0 3px rgba(0,0,0,.35);box-sizing:border-box;content:"";height:19px;left:-2px;position:absolute;top:-2px;width:19px}@keyframes maplibregl-user-location-dot-pulse{0%{opacity:1;transform:scale(1)}70%{opacity:0;transform:scale(3)}to{opacity:0;transform:scale(1)}}.maplibregl-user-location-dot-stale{background-color:#aaa}.maplibregl-user-location-dot-stale:after{display:none}.maplibregl-user-location-accuracy-circle{background-color:#1da1f233;border-radius:100%;height:1px;width:1px}.maplibregl-crosshair,.maplibregl-crosshair .maplibregl-interactive,.maplibregl-crosshair .maplibregl-interactive:active{cursor:crosshair}.maplibregl-boxzoom{background:#fff;border:2px dotted #202020;height:0;left:0;opacity:.5;position:absolute;top:0;width:0}.maplibregl-cooperative-gesture-screen{align-items:center;background:rgba(0,0,0,.4);color:#fff;display:flex;font-size:1.4em;inset:0;justify-content:center;line-height:1.2;opacity:0;padding:1rem;pointer-events:none;position:absolute;transition:opacity 1s ease 1s;z-index:99999}.maplibregl-cooperative-gesture-screen.maplibregl-show{opacity:1;transition:opacity .05s}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:none}@media (hover:none),(width <= 480px){.maplibregl-cooperative-gesture-screen .maplibregl-desktop-message{display:none}.maplibregl-cooperative-gesture-screen .maplibregl-mobile-message{display:block}}.maplibregl-pseudo-fullscreen{height:100%!important;left:0!important;position:fixed!important;top:0!important;width:100%!important;z-index:99999}/* stylelint-disable scss/at-import-no-partial-leading-underscore */ -/* stylelint-disable-next-line number-max-precision */ -.chart-error-overlay .chart-error-overlay-content .btn { - margin-top: 1rem; - margin-right: 1rem; -} -.chart-error-overlay .chart-error-overlay-content .info-message, -.chart-error-overlay .chart-error-overlay-content .waiting-filter-list { - text-align: left; -} - -/*# sourceMappingURL=ChartErrorOverlay.css.map */ -/* stylelint-disable scss/at-import-no-partial-leading-underscore */ -/* stylelint-disable-next-line number-max-precision */ -.plotly-notifier { - margin-right: 15px; -} - -.plotly-notifier .notifier-note { - color: var(--dh-color-fg, #f0f0ee) !important; - border: 0 !important; - border-radius: 2px !important; - background: var(--dh-color-plotly-notifier-note-bg) !important; - overflow-wrap: normal !important; - hyphens: unset !important; - margin-bottom: 0.5rem !important; - box-shadow: 0 0.1rem 1rem var(--dh-color-dropshadow) !important; -} - -.plotly-notifier .notifier-close { - color: var(--dh-color-gray-600) !important; - transition: all 0.2s ease-in-out !important; -} -.plotly-notifier .notifier-close:hover { - color: var(--dh-color-fg, #f0f0ee) !important; -} - -.chart-wrapper { - background: var(--dh-color-chart-bg); -} -.chart-wrapper .plot-container .cartesianlayer text { - user-select: none; -} -.chart-wrapper .plot-container .hovertext path, -.chart-wrapper .plot-container .axistext path { - stroke: none !important; -} -.chart-wrapper .plot-container .axistext path { - fill: var(--dh-color-plotly-axis-text) !important; - box-shadow: 4px 4px var(--dh-color-black); -} -.chart-wrapper .plot-container .zoomlayer .zoombox { - fill: var(--dh-color-plotly-zoombox) !important; -} -.chart-wrapper .plot-container .zoomlayer .zoombox-corners { - fill: var(--dh-color-plotly-zoombox-corners-fill); - stroke: var(--dh-color-plotly-zoombox-corners-stroke); -} -.chart-wrapper .js-plotly-plot .plotly [data-title]::before { - border-color: transparent transparent var(--dh-color-tooltip-bg); - z-index: 1002; -} -.chart-wrapper .js-plotly-plot .plotly [data-title]::after { - border-radius: 4px; - background: var(--dh-color-tooltip-bg); - color: var(--dh-color-tooltip-fg); - padding: 0.25rem 0.5rem; - box-shadow: var(--dh-color-tooltip-box-shadow); - z-index: 1001; -} -.chart-wrapper .js-plotly-plot .plotly .modebar { - z-index: auto; -} -.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=animation-spin] svg { - animation: fa-spin 2s infinite linear; -} -.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=fill-active] svg path { - fill: var(--dh-color-plotly-modebar-btn-active) !important; -} -.chart-wrapper .js-plotly-plot .plotly .modebar .modebar-btn[data-attr=fill-warning] svg path { - fill: var(--dh-color-plotly-modebar-btn-warning) !important; -} - -.chart-error-popper .popper-content { - padding: 0.25rem; -} - -/*# sourceMappingURL=Chart.css.map */ diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts b/plugins/grid-toolbar/src/js/dist/index.d.ts new file mode 100644 index 000000000..36fa1d61c --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/index.d.ts @@ -0,0 +1,5 @@ +import { GridToolbarPlugin } from './GridToolbarPlugin'; +export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPlugin } from './GridToolbarPlugin'; +export default GridToolbarPlugin; +//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts.map b/plugins/grid-toolbar/src/js/dist/index.d.ts.map new file mode 100644 index 000000000..aebf3c6d1 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/index.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js b/plugins/grid-toolbar/src/js/dist/index.js new file mode 100644 index 000000000..29a5bc503 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/index.js @@ -0,0 +1,5 @@ +import { GridToolbarPlugin } from './GridToolbarPlugin'; +export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPlugin } from './GridToolbarPlugin'; +export default GridToolbarPlugin; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js.map b/plugins/grid-toolbar/src/js/dist/index.js.map new file mode 100644 index 000000000..2dd4b5219 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts new file mode 100644 index 000000000..700d7c752 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts @@ -0,0 +1,31 @@ +/** + * Local type definitions for middleware plugin types. + * + * TODO: Delete this file after deephaven/web-client-ui#2660 is merged and + * @deephaven/plugin is updated with WidgetMiddlewarePlugin types. + * Replace imports with: import { type WidgetMiddlewarePlugin, type WidgetMiddlewareComponentProps } from '@deephaven/plugin'; + */ +import type { WidgetComponentProps, WidgetPanelProps, WidgetPlugin } from '@deephaven/plugin'; +/** + * Props passed to middleware components that wrap a base widget. + */ +export interface WidgetMiddlewareComponentProps extends WidgetComponentProps { + /** The next component in the middleware chain. */ + Component: React.ComponentType>; +} +/** + * Props passed to middleware panel components that wrap a base panel. + */ +export interface WidgetMiddlewarePanelProps extends WidgetPanelProps { + /** The next panel component in the middleware chain. */ + Component: React.ComponentType>; +} +/** + * A middleware plugin that wraps and enhances another widget plugin. + */ +export interface WidgetMiddlewarePlugin extends Omit, 'component' | 'panelComponent'> { + isMiddleware: true; + component: React.ComponentType>; + panelComponent?: React.ComponentType>; +} +//# sourceMappingURL=middlewareTypes.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map new file mode 100644 index 000000000..86ee32da7 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map @@ -0,0 +1 @@ +{"version":3,"file":"middlewareTypes.d.ts","sourceRoot":"","sources":["../src/middlewareTypes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACb,MAAM,mBAAmB,CAAC;AAE3B;;GAEG;AACH,MAAM,WAAW,8BAA8B,CAAC,CAAC,GAAG,OAAO,CACzD,SAAQ,oBAAoB,CAAC,CAAC,CAAC;IAC/B,kDAAkD;IAClD,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC;CACzD;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B,CAAC,CAAC,GAAG,OAAO,CACrD,SAAQ,gBAAgB,CAAC,CAAC,CAAC;IAC3B,wDAAwD;IACxD,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,OAAO,CACjD,SAAQ,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,WAAW,GAAG,gBAAgB,CAAC;IAC7D,YAAY,EAAE,IAAI,CAAC;IACnB,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,8BAA8B,CAAC,CAAC,CAAC,CAAC,CAAC;IAClE,cAAc,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,CAAC;CACrE"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js new file mode 100644 index 000000000..24e1d14ae --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js @@ -0,0 +1,2 @@ +export {}; +//# sourceMappingURL=middlewareTypes.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map new file mode 100644 index 000000000..a54550595 --- /dev/null +++ b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map @@ -0,0 +1 @@ +{"version":3,"file":"middlewareTypes.js","sourceRoot":"","sources":["../src/middlewareTypes.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index 5eed4f9fa..8ba043681 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -48,8 +48,10 @@ export function GridToolbarPanelMiddleware({ xAxis: table.columns[0].name as string, }; const model = await ChartModelFactory.makeModelFromSettings( - dh, - settings, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + dh as any, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + settings as any, table ); setChartModel(model); @@ -87,8 +89,10 @@ export function GridToolbarPanelMiddleware({
{view === 'chart' && chartModel != null ? ( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - +
+ {/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} + +
) : ( // eslint-disable-next-line react/jsx-props-no-spreading From 69b8dea473cfa3bfff5c41444515986fef66fce5 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 12:15:28 -0600 Subject: [PATCH 04/11] gitignore --- plugins/grid-toolbar/src/js/.gitignore | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/plugins/grid-toolbar/src/js/.gitignore b/plugins/grid-toolbar/src/js/.gitignore index e69de29bb..3356dc1ce 100644 --- a/plugins/grid-toolbar/src/js/.gitignore +++ b/plugins/grid-toolbar/src/js/.gitignore @@ -0,0 +1,8 @@ +build/ +dist/ +.venv/ +/venv +*.egg-info/ +.idea +.DS_store +__pycache__/ \ No newline at end of file From 7664ff91624a7d264ea91da452c0373bf5f3e7a9 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 12:19:06 -0600 Subject: [PATCH 05/11] WIP --- plugins/grid-toolbar/{src/js => }/.gitignore | 0 plugins/grid-toolbar/src/js/dist/bundle/index.js | 1 + plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx | 3 +++ 3 files changed, 4 insertions(+) rename plugins/grid-toolbar/{src/js => }/.gitignore (100%) diff --git a/plugins/grid-toolbar/src/js/.gitignore b/plugins/grid-toolbar/.gitignore similarity index 100% rename from plugins/grid-toolbar/src/js/.gitignore rename to plugins/grid-toolbar/.gitignore diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js index a508d4563..494c54b4e 100644 --- a/plugins/grid-toolbar/src/js/dist/bundle/index.js +++ b/plugins/grid-toolbar/src/js/dist/bundle/index.js @@ -207,6 +207,7 @@ function GridToolbarPanelMiddleware({ children: view === "chart" ? "Grid" : "Chart" } ), + /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: "grid-toolbar-btn", children: "Pivot" }), /* @__PURE__ */ jsxRuntimeExports.jsx( "button", { diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index 8ba043681..dea023a39 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -79,6 +79,9 @@ export function GridToolbarPanelMiddleware({ > {view === 'chart' ? 'Grid' : 'Chart'} + ` to the toggle handler + - Disable button while building (`isBuilding` state) + - Toggle button label: show "Grid" when in pivot view + - Guard availability: only enable if `isCorePlusDh(dh)` is true (enterprise check) + +6. **Add pivot rendering branch** in the content area: + - When `view === 'pivot' && pivotModel != null`: + - Render `` with pivot-specific props + - Optionally use `usePivotMouseHandlers()`, `usePivotRenderer()`, `usePivotTheme()` from pivot plugin for full-featured rendering + - When `view === 'grid'`: render `` (existing behavior) + +7. **Handle cleanup**: close `pivotModel` on unmount or when switching away (same pattern as `chartModel?.close()`) + +### Phase 3: Inline Middleware (Optional) + +8. **Update `GridToolbarMiddleware.tsx`** (non-panel inline rendering): Add a simpler pivot toggle if needed for `WidgetView` path. Lower priority — panel middleware is the primary path. + +## Relevant Files + +- `plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx` — main file to modify; wire up Pivot button, add pivot view branch +- `plugins/grid-toolbar/src/js/src/GridToolbarMiddleware.tsx` — optional: add pivot to inline middleware +- `plugins/grid-toolbar/src/js/package.json` — add dependencies +- `plugins/grid-toolbar/src/js/vite.config.ts` — add externals +- `plugins/pivot/src/js/src/IrisGridPivotModel.ts` — reuse: the model class for pivot rendering +- `plugins/pivot/src/js/src/hooks/usePivotMouseHandlers.ts` — reuse: pivot-specific mouse handlers +- `plugins/pivot/src/js/src/hooks/usePivotRenderer.ts` — reuse: pivot cell renderer +- `plugins/pivot/src/js/src/hooks/usePivotTheme.ts` — reuse: pivot grid theme +- `plugins/pivot/src/js/src/hooks/usePivotMetricCalculatorFactory.ts` — reuse: metric calculator +- `plugins/pivot/src/js/src/PivotUtils.ts` — reuse: `isCorePlusDh()` type guard +- `gplus/web/client-api/.../pivotservice.html` — reference: PivotService API usage example + +## Verification + +1. Build the grid-toolbar plugin: `cd plugins/grid-toolbar && python ../../tools/plugin_builder.py --reinstall grid-toolbar` +2. Load a Table in the UI, verify grid-toolbar renders with Chart, Pivot, Reset Filters buttons +3. Click Pivot on a table with mixed numeric/non-numeric columns — should toggle to pivot view with auto-detected layout +4. Click Pivot again (or "Grid" button) — should return to normal grid view +5. Verify Pivot button is disabled/hidden when CorePlus API is not available (community edition) +6. Verify pivot model cleanup on unmount (no leaked subscriptions) +7. Run JS tests: `npm run test:unit -- --testPathPattern="plugins/grid-toolbar"` + +## Key API Reference + +``` +PivotService.getInstance(table: dh.Table): Promise +pivotService.createPivotTable(options: PivotCreationOptions): Promise + +PivotCreationOptions = { + source: dh.Table, + rowKeys: string[], + columnKeys: string[], + aggregations: { [operation]: string[] } // e.g. { Sum: ['Price', 'Qty'] } +} + +Operations: Count, Min, Max, Sum, Var, Avg, Std, First, Last +``` + +## Risks / Open Questions + +1. **PivotService.getInstance(table)**: The pivotservice.html example passes a "psp" (PivotServiceProvider) widget, not a plain Table. The TypeScript types accept `dh.Table`, but runtime behavior may differ. Need to verify `getInstance(table)` works with a raw table from `fetch()`. + +2. **IrisGridPivotModel dependency**: This model is ~1800 lines with complex enterprise logic. Importing it as a dependency couples grid-toolbar to the pivot plugin. Alternative: render a simpler table view of the PivotTable snapshot data without IrisGrid. + +3. **Column auto-detection heuristics**: Simple split of non-numeric→rows/columns, numeric→values may not produce useful pivots for all table shapes. May want to add minimal configuration UI in a follow-up. From 769f6d7aef055ae7d0d2b4510df77afe856bafed Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Tue, 21 Apr 2026 20:12:13 -0600 Subject: [PATCH 08/11] Working Pivot --- package-lock.json | 3 + plans/builder-poc-option-C.md | 223 +++++++++++++ plans/builder-poc-option-D.md | 299 ++++++++++++++++++ .../js/dist/GridToolbarPanelMiddleware.d.ts | 2 +- .../dist/GridToolbarPanelMiddleware.d.ts.map | 2 +- .../src/js/dist/GridToolbarPanelMiddleware.js | 18 +- .../js/dist/GridToolbarPanelMiddleware.js.map | 2 +- .../grid-toolbar/src/js/dist/bundle/index.js | 188 ++++++++++- plugins/grid-toolbar/src/js/dist/index.d.ts | 2 + .../grid-toolbar/src/js/dist/index.d.ts.map | 2 +- plugins/grid-toolbar/src/js/dist/index.js | 2 + plugins/grid-toolbar/src/js/dist/index.js.map | 2 +- plugins/grid-toolbar/src/js/package.json | 3 + .../src/js/src/GridToolbarPanelMiddleware.tsx | 68 +++- plugins/grid-toolbar/src/js/src/index.ts | 2 + .../grid-toolbar/src/js/src/pivotPlugin.d.ts | 27 ++ .../grid-toolbar/src/js/src/usePivotToggle.ts | 195 ++++++++++++ plugins/grid-toolbar/src/js/vite.config.ts | 10 + plugins/pivot/src/js/src/index.ts | 11 + 19 files changed, 1032 insertions(+), 29 deletions(-) create mode 100644 plans/builder-poc-option-C.md create mode 100644 plans/builder-poc-option-D.md create mode 100644 plugins/grid-toolbar/src/js/src/pivotPlugin.d.ts create mode 100644 plugins/grid-toolbar/src/js/src/usePivotToggle.ts diff --git a/package-lock.json b/package-lock.json index a9da966d0..ae9c00d35 100644 --- a/package-lock.json +++ b/package-lock.json @@ -31342,11 +31342,14 @@ "@deephaven/chart": "^0.106.0", "@deephaven/components": "^0.106.0", "@deephaven/icons": "^0.106.0", + "@deephaven/iris-grid": "^0.106.0", + "@deephaven/js-plugin-pivot": "*", "@deephaven/jsapi-bootstrap": "^0.106.0", "@deephaven/log": "^0.106.2", "@deephaven/plugin": "^0.106.4" }, "devDependencies": { + "@deephaven-enterprise/jsapi-coreplus-types": "^1.20240517.518", "@types/react": "^17.0.2", "react": "^17.0.2", "react-dom": "^17.0.2" diff --git a/plans/builder-poc-option-C.md b/plans/builder-poc-option-C.md new file mode 100644 index 000000000..92495ba13 --- /dev/null +++ b/plans/builder-poc-option-C.md @@ -0,0 +1,223 @@ +# Plan: Pivot in Grid-Toolbar — Option C (Expand Host Resolve Map + Bundle Pivot Source) + +## TL;DR + +Make the pivot plugin's source consumable as a normal npm dependency by adding a `tsc` transpile step that outputs individual ESM files. The grid-toolbar's Vite build imports from `@deephaven/js-plugin-pivot` via its ESM entry, bundles only the pivot-internal classes, and externalizes all shared `@deephaven/*` packages. Two packages (`@deephaven/grid`, `@deephaven/utils`) must be added to the host app's resolve map since they're already in the host bundle but not currently exposed to plugins. + +## Background + +### How Plugin Module Resolution Works + +Plugins are CJS bundles loaded by `@paciolan/remote-module-loader`. The host evaluates the JS text with `new Function("require", "module", "exports", code)` and injects a `require` shim that resolves from a **static map** in `packages/app-utils/src/plugins/remote-component.config.ts`: + +```ts +export const resolve = { + react, + 'react-dom': ReactDOM, + '@deephaven/chart': DeephavenChart, + '@deephaven/components': DeephavenComponents, + '@deephaven/iris-grid': DeephavenIrisGrid, + // ... ~20 packages total +}; +``` + +If a plugin calls `require('anything-not-in-map')`, it throws at runtime. There is no plugin-to-plugin dependency mechanism. + +### The Problem + +The grid-toolbar plugin needs `IrisGridPivotModel`, `isCorePlusDh`, and pivot hooks from `@deephaven/js-plugin-pivot`. That package is NOT in the host resolve map. Simply externalizing it causes a runtime `require` failure. Bundling it fails because the pivot plugin only produces a single CJS bundle (`dist/index.js`) — Rollup can't resolve CJS named exports from it. + +### Why This Approach Works + +1. The pivot plugin gets a `tsc` transpile step that outputs individual ESM `.js` files in `dist/` +2. The grid-toolbar's Vite build resolves `@deephaven/js-plugin-pivot` → `dist/index.js` (ESM) → follows individual file imports +3. Vite bundles only the pivot-internal classes (IrisGridPivotModel, renderers, mouse handlers, etc.) into the grid-toolbar output +4. All shared `@deephaven/*` imports within the pivot source (grid, iris-grid, utils, etc.) are externalized → resolved from the host at runtime +5. `@deephaven/grid` and `@deephaven/utils` are added to the host resolve map (they're already in the host bundle as transitive dependencies of `@deephaven/iris-grid`) + +## Changes Required + +### 1. web-client-ui: Expand the resolve map + +**File**: `packages/app-utils/src/plugins/remote-component.config.ts` + +Add two packages that are already in the host bundle but not exposed: + +```ts +import * as DeephavenGrid from '@deephaven/grid'; +import * as DeephavenUtils from '@deephaven/utils'; + +export const resolve = { + // ... existing entries ... + '@deephaven/grid': DeephavenGrid, + '@deephaven/utils': DeephavenUtils, +}; +``` + +Also add `memoize-one` and `lodash.throttle` if needed (IrisGridPivotModel imports them). These are already in the host bundle. Check if they need exposing. + +**Rebuild**: Run `npm install && npm run build` in web-client-ui, then restart the enterprise app. + +### 2. Pivot plugin: Add ESM transpile output + +**File**: `plugins/pivot/src/js/package.json` + +Add `tsc` transpile step and update exports: + +```json +{ + "main": "dist/bundle/index.js", + "exports": { + ".": { + "import": "./dist/index.js", + "require": "./dist/bundle/index.js", + "default": "./dist/bundle/index.js" + }, + "./*.js": "./dist/*.js", + "./*": "./dist/*.js" + }, + "types": "dist/index", + "scripts": { + "start": "vite build --watch", + "build": "run-s build:*", + "build:transpile": "tsc", + "build:bundle": "vite build" + }, + "files": ["dist"] +} +``` + +**File**: `plugins/pivot/src/js/tsconfig.json` + +Already exists with `outDir: "dist/"`. Confirm it produces ESM (it extends `@deephaven/tsconfig` which sets `"module": "esnext"`). + +**File**: `plugins/pivot/src/js/vite.config.js` + +Update `outDir` to `dist/bundle`: + +```js +build: { + outDir: 'dist/bundle', + // ... rest unchanged +} +``` + +**File**: `plugins/pivot/src/js/src/index.ts` + +Add exports for the items the grid-toolbar needs: + +```ts +export { default as IrisGridPivotModel } from './IrisGridPivotModel'; +export { isCorePlusDh } from './PivotUtils'; +export { usePivotMouseHandlers } from './hooks/usePivotMouseHandlers'; +export { usePivotRenderer } from './hooks/usePivotRenderer'; +export { usePivotTheme } from './hooks/usePivotTheme'; +``` + +Add `npm-run-all` devDependency for `run-s` (or use `npm-run-all2`). + +**Rebuild**: `cd plugins/pivot/src/js && npm run build` + +Verify `dist/` contains individual `.js` files (ESM) and `dist/bundle/index.js` contains the CJS bundle. + +### 3. Grid-toolbar: Import from pivot as dependency + +**File**: `plugins/grid-toolbar/src/js/package.json` + +Add dependencies: + +```json +{ + "dependencies": { + "@deephaven/js-plugin-pivot": "*", + "@deephaven/iris-grid": "^0.106.0", + "@deephaven-enterprise/jsapi-coreplus-types": "^1.20240517.518" + } +} +``` + +Move `@deephaven-enterprise/jsapi-coreplus-types` to `devDependencies` (types only). + +**File**: `plugins/grid-toolbar/src/js/vite.config.ts` + +Externalize all host-provided packages but NOT `@deephaven/js-plugin-pivot`: + +```ts +rollupOptions: { + external: [ + 'react', + 'react-dom', + 'redux', + 'react-redux', + 'memoize-one', + 'lodash.throttle', + '@deephaven/chart', + '@deephaven/components', + '@deephaven/grid', + '@deephaven/icons', + '@deephaven/iris-grid', + '@deephaven/jsapi-bootstrap', + '@deephaven/jsapi-utils', + '@deephaven/log', + '@deephaven/plugin', + '@deephaven/react-hooks', + '@deephaven/utils', + ], +}, +``` + +`@deephaven/js-plugin-pivot` is NOT listed — Vite will follow its ESM entry and bundle the pivot-internal code. + +**File**: `plugins/grid-toolbar/src/js/src/usePivotToggle.ts` (new) + +```ts +import { IrisGridPivotModel, isCorePlusDh } from '@deephaven/js-plugin-pivot'; +``` + +Standard package import — Vite resolves via ESM entry at build time, bundles IrisGridPivotModel source into grid-toolbar output. + +**File**: `plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx` + +```ts +import { IrisGrid } from '@deephaven/iris-grid'; +import { + usePivotMouseHandlers, + usePivotRenderer, + usePivotTheme, +} from '@deephaven/js-plugin-pivot'; +``` + +Same pattern — pivot hooks get bundled in, `@deephaven/iris-grid` is external. + +### 4. Build and verify + +1. Build pivot: `cd plugins/pivot/src/js && npm run build` +2. Build grid-toolbar: `cd plugins/grid-toolbar/src/js && npm run build` +3. Start plugin dev server: `npm start` (from deephaven-plugins root) +4. Restart enterprise app after web-client-ui rebuild +5. Open browser at localhost:3000, verify: + - Chart button still works + - Pivot button appears (only when CorePlus API is available) + - Clicking Pivot creates a pivot and renders with IrisGrid + +## Risk Assessment + +| Risk | Likelihood | Mitigation | +|------|-----------|------------| +| `memoize-one` / `lodash.throttle` not in host resolve map | Medium | Add to resolve map, or have Vite bundle them (don't externalize) | +| `nanoid` / `lodash.clamp` not in host resolve map | Medium | Same — bundle them or add to resolve | +| Pivot source has compile errors in tsc without Vite | Low | tsconfig already exists and extends @deephaven/tsconfig | +| Bundle size increase | Low | Pivot internals add ~50-100KB to grid-toolbar bundle; acceptable for POC | + +## Tradeoffs + +**Pros**: +- Standard npm dependency — no fragile relative paths +- Clean build: Vite tree-shakes unused pivot exports +- Follows the same externalization pattern as the Chart button +- Minimal web-client-ui change (just 2-4 lines in resolve map) + +**Cons**: +- Pivot source gets duplicated: bundled into both the pivot plugin's own CJS bundle AND the grid-toolbar's CJS bundle (runtime duplication if both loaded) +- Requires web-client-ui rebuild + enterprise app restart +- Adding packages to the resolve map is a semi-permanent API commitment diff --git a/plans/builder-poc-option-D.md b/plans/builder-poc-option-D.md new file mode 100644 index 000000000..6d90a4e6f --- /dev/null +++ b/plans/builder-poc-option-D.md @@ -0,0 +1,299 @@ +# Plan: Pivot in Grid-Toolbar — Option D (Plugin-to-Plugin Dependency Infrastructure) + +## TL;DR + +Extend the plugin loader in web-client-ui so that loaded plugins can register their exports in the module resolve map, making them available to subsequently loaded plugins via standard `require()`. This eliminates the need to bundle pivot source into the grid-toolbar — the grid-toolbar simply externalizes `@deephaven/js-plugin-pivot` and it resolves at runtime from the already-loaded pivot plugin module. + +This approach is Option C + a plugin registry mechanism. It includes Option C's resolve map expansion (`@deephaven/grid`, `@deephaven/utils`) since the pivot plugin itself externalizes those. + +## Background + +### Current Architecture + +``` +manifest.json + → loadModulePlugins() loads all plugins in parallel via Promise.allSettled() + → Each plugin: XHR fetch JS text → new Function("require","module","exports", text) + → require = createRequires(resolve) ← static, immutable map + → require("@deephaven/chart") → ✓ returns pre-imported module + → require("@deephaven/js-plugin-pivot") → ✗ throws Error +``` + +The resolve map is created once from `remote-component.config.ts` and never modified. Plugins load in parallel, so even if one plugin's exports were added to the map, the order isn't guaranteed. + +### What Changes + +1. The resolve map becomes **mutable** — loaded plugins can register their exports +2. Plugins load **sequentially** (or in dependency-declared order) instead of in parallel +3. Each loaded plugin's exports get added to the resolve map under its package name +4. The manifest optionally declares plugin dependencies to enforce load order + +## Changes Required + +### 1. web-client-ui: Make resolve map mutable and expose it + +**File**: `packages/app-utils/src/plugins/remote-component.config.ts` + +Add `@deephaven/grid` and `@deephaven/utils` (same as Option C): + +```ts +import * as DeephavenGrid from '@deephaven/grid'; +import * as DeephavenUtils from '@deephaven/utils'; + +export const resolve: Record = { + // ... existing entries ... + '@deephaven/grid': DeephavenGrid, + '@deephaven/utils': DeephavenUtils, +}; +``` + +Note: the type changes from an implicit readonly object to `Record` so plugins can be added. + +### 2. web-client-ui: Make loadRemoteModule use a shared mutable resolve + +**File**: `packages/app-utils/src/plugins/loadRemoteModule.ts` + +Currently: +```ts +import createLoadRemoteModule, { createRequires } from '@paciolan/remote-module-loader'; +import { resolve } from './remote-component.config'; + +const requires = createRequires(resolve); +export const loadRemoteModule = createLoadRemoteModule({ requires }); +``` + +The `createRequires` function closes over the resolve object at creation time. Since we're mutating the same object (adding properties), this should work — the closure holds a reference to the object, not a snapshot. Verify this by checking `createRequires` implementation: + +```js +// From @paciolan/remote-module-loader +var createRequires = function (dependencies) { + return function (name) { + if (!(name in dependencies)) { + throw new Error("Could not require '" + name + "'"); + } + return dependencies[name]; + }; +}; +``` + +Yes — it uses `name in dependencies` on the live object. Adding properties to `resolve` after `createRequires` is called will be visible to subsequent `require()` calls. **No change needed to loadRemoteModule.ts** as long as we mutate the same `resolve` object. + +### 3. web-client-ui: Register plugin exports after loading + +**File**: `packages/app-utils/src/plugins/PluginUtils.tsx` + +Change `loadModulePlugins` to: + +1. Load plugins **sequentially** instead of in parallel +2. After each successful load, register the plugin's full module exports in the resolve map + +```ts +import { resolve } from './remote-component.config'; + +export async function loadModulePlugins( + modulePluginsUrl: string +): Promise { + log.debug('Loading plugins...'); + try { + const manifest = await loadJson(`${modulePluginsUrl}/manifest.json`); + + if (!Array.isArray(manifest.plugins)) { + throw new Error('Plugin manifest JSON does not contain plugins array'); + } + + log.debug('Plugin manifest loaded:', manifest); + + const pluginMap: PluginModuleMap = new Map(); + + // Load plugins sequentially so each plugin's exports are available + // to subsequently loaded plugins via require() + for (let i = 0; i < manifest.plugins.length; i += 1) { + const { name, main, version } = manifest.plugins[i]; + const pluginMainUrl = `${modulePluginsUrl}/${name}/${main}`; + try { + const myModule = await loadModulePlugin(pluginMainUrl); + + // Register the full module exports in the resolve map so + // subsequent plugins can require() this plugin by name + resolve[name] = myModule; + log.debug(`Registered plugin '${name}' in module resolve map`); + + const moduleValue = getPluginModuleValue(myModule); + if (moduleValue == null) { + log.error(`Plugin '${name}' is missing an exported value.`); + } else if (isMultiPlugin(moduleValue)) { + log.debug( + `MultiPlugin '${name}' contains ${moduleValue.plugins.length} plugins` + ); + moduleValue.plugins.forEach(innerPlugin => { + registerPlugin(pluginMap, innerPlugin.name, innerPlugin, version); + }); + } else { + registerPlugin(pluginMap, name, moduleValue, version); + } + } catch (e) { + log.error(`Unable to load plugin '${name}'`, e); + } + } + + log.info('Plugins loaded:', pluginMap); + return pluginMap; + } catch (e) { + log.error('Unable to load plugins:', e); + return new Map(); + } +} +``` + +Key differences from current code: +- `for` loop with `await` instead of `Promise.allSettled()` — sequential loading +- `resolve[name] = myModule` — registers the raw module exports (not the PluginModule wrapper) so `require('@deephaven/js-plugin-pivot')` returns the same thing as `import * from '@deephaven/js-plugin-pivot'` + +### 4. Manifest plugin ordering (optional but recommended) + +Plugins load in manifest order. The manifest.json on the dev server is auto-generated by the plugin dev server. Ensure `@deephaven/js-plugin-pivot` appears before `@deephaven/js-plugin-grid-toolbar`. + +For a more robust solution, add a `dependencies` field to manifest entries: + +```json +{ + "plugins": [ + { "name": "@deephaven/js-plugin-pivot", "main": "index.js", "version": "0.4.0" }, + { + "name": "@deephaven/js-plugin-grid-toolbar", + "main": "index.js", + "version": "0.1.0", + "dependencies": ["@deephaven/js-plugin-pivot"] + } + ] +} +``` + +Then topologically sort the plugins before loading. This is optional for the POC — simple ordering in manifest.json is sufficient. + +### 5. Pivot plugin: Export needed items + +**File**: `plugins/pivot/src/js/src/index.ts` + +Add exports (same as Option C): + +```ts +export { default as IrisGridPivotModel } from './IrisGridPivotModel'; +export { isCorePlusDh } from './PivotUtils'; +export { usePivotMouseHandlers } from './hooks/usePivotMouseHandlers'; +export { usePivotRenderer } from './hooks/usePivotRenderer'; +export { usePivotTheme } from './hooks/usePivotTheme'; +``` + +No need for ESM transpile step — the existing CJS bundle is fine since it will be loaded by the host and registered in the resolve map. Other plugins `require()` it at runtime. + +### 6. Grid-toolbar: Standard externalization + +**File**: `plugins/grid-toolbar/src/js/vite.config.ts` + +Externalize `@deephaven/js-plugin-pivot` along with all other host-provided packages: + +```ts +rollupOptions: { + external: [ + 'react', + 'react-dom', + 'redux', + 'react-redux', + 'memoize-one', + 'lodash.throttle', + '@deephaven/chart', + '@deephaven/components', + '@deephaven/grid', + '@deephaven/icons', + '@deephaven/iris-grid', + '@deephaven/js-plugin-pivot', + '@deephaven/jsapi-bootstrap', + '@deephaven/jsapi-utils', + '@deephaven/log', + '@deephaven/plugin', + '@deephaven/react-hooks', + '@deephaven/utils', + ], +}, +``` + +`@deephaven/js-plugin-pivot` IS externalized — at runtime, `require('@deephaven/js-plugin-pivot')` resolves from the resolve map (populated by step 3 when the pivot plugin loaded first). + +**File**: `plugins/grid-toolbar/src/js/package.json` + +Add dependencies for type-checking: + +```json +{ + "dependencies": { + "@deephaven/js-plugin-pivot": "*", + "@deephaven/iris-grid": "^0.106.0" + }, + "devDependencies": { + "@deephaven-enterprise/jsapi-coreplus-types": "^1.20240517.518" + } +} +``` + +**File**: `plugins/grid-toolbar/src/js/src/usePivotToggle.ts` (new) + +Standard imports — same code as before: + +```ts +import { IrisGridPivotModel, isCorePlusDh } from '@deephaven/js-plugin-pivot'; +``` + +At build time, Vite externalizes this. At runtime, `require()` resolves it from the resolve map. + +**File**: `plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx` + +Same — standard imports from `@deephaven/js-plugin-pivot` and `@deephaven/iris-grid`. + +### 7. Build and verify + +1. Rebuild web-client-ui: `cd mainbranch && npm run build` +2. Restart enterprise app: re-run `npm run start-community` +3. Rebuild pivot plugin: `cd plugins/pivot/src/js && npm run build` +4. Build grid-toolbar: `cd plugins/grid-toolbar/src/js && npm run build` +5. Start plugin dev server: `npm start` (from deephaven-plugins root) +6. Open browser at localhost:3000 +7. Verify pivot plugin loads first in console: `Registered plugin '@deephaven/js-plugin-pivot' in module resolve map` +8. Verify grid-toolbar loads and Chart + Pivot buttons work + +## Comparison with Option C + +| Aspect | Option C | Option D | +|--------|----------|----------| +| Pivot code duplication | Yes — bundled into grid-toolbar | No — loaded once, shared via resolve map | +| Grid-toolbar bundle size | Larger (~50-100KB from pivot internals) | Small — only grid-toolbar's own code | +| web-client-ui changes | 2-4 lines (resolve map) | ~30 lines (resolve map + sequential loading) | +| Plugin load time | Parallel (fast) | Sequential (slower, but plugins are small) | +| Plugin ordering | Doesn't matter | Matters — dependencies must load first | +| Reusability | One-off for this POC | General-purpose: any plugin can depend on any other | +| Future maintenance | Need to keep pivot code in sync across two bundles | Single source of truth for pivot code | + +## Risk Assessment + +| Risk | Likelihood | Mitigation | +|------|-----------|------------| +| Sequential loading slows startup | Low | Plugin bundles are small (<500KB each), network latency dominates | +| Plugin load order wrong in manifest | Medium | Verify manifest.json order; add topological sort for production | +| `resolve` mutation not visible to `createRequires` | Very Low | Verified: `createRequires` uses `name in dependencies` on live object | +| Pivot plugin CJS exports don't match import names | Medium | Test with `require('@deephaven/js-plugin-pivot').IrisGridPivotModel`; may need to verify CJS export shape | +| `memoize-one` / `lodash.throttle` not in resolve map | Medium | The pivot plugin bundles these (they're not in its externals list). So they're included in the pivot CJS bundle — no resolve map entry needed. But grid-toolbar also uses them transitively through bundled pivot code... wait, in Option D the pivot code is NOT bundled into grid-toolbar. The pivot CJS bundle already includes memoize-one and lodash.throttle (not externalized). So `require('memoize-one')` inside the pivot bundle resolves internally. No issue. | + +## Tradeoffs + +**Pros**: +- No code duplication — pivot loads once, shared by all plugins +- Clean dependency model — plugins declare and consume dependencies via standard `require()` +- General-purpose — any future plugin can depend on any other plugin +- Grid-toolbar bundle stays small +- No ESM transpile step needed for pivot + +**Cons**: +- More web-client-ui changes than Option C +- Sequential plugin loading (minor perf impact) +- Plugin load order matters — must be managed +- Slightly more complex infrastructure to understand and maintain diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts index 1d574596e..7b1a23e44 100644 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts @@ -1,4 +1,4 @@ import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; -export declare function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, ...props }: WidgetMiddlewarePanelProps): JSX.Element; +export declare function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, metadata, ...props }: WidgetMiddlewarePanelProps): JSX.Element; export default GridToolbarPanelMiddleware; //# sourceMappingURL=GridToolbarPanelMiddleware.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map index 6198b3ce4..d22f35343 100644 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"GridToolbarPanelMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":"AAKA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAOpE,wBAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG,GAAG,CAAC,OAAO,CAqF1C;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file +{"version":3,"file":"GridToolbarPanelMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAQpE,wBAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG,GAAG,CAAC,OAAO,CAkI1C;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js index 114a61fd7..5f4dd0877 100644 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js @@ -12,17 +12,24 @@ var __rest = (this && this.__rest) || function (s, e) { import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; import { useCallback, useEffect, useState } from 'react'; import { Chart, ChartModelFactory } from '@deephaven/chart'; +import { IrisGrid } from '@deephaven/iris-grid'; import { useApi } from '@deephaven/jsapi-bootstrap'; +import { usePivotMouseHandlers, usePivotRenderer, usePivotTheme, } from '@deephaven/js-plugin-pivot'; import Log from '@deephaven/log'; +import { usePivotToggle } from './usePivotToggle'; const log = Log.module('@deephaven/js-plugin-grid-toolbar'); // Matches InputFilterEvent.CLEAR_ALL_FILTERS from @deephaven/dashboard-core-plugins const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; export function GridToolbarPanelMiddleware(_a) { - var { Component, fetch, glEventHub } = _a, props = __rest(_a, ["Component", "fetch", "glEventHub"]); + var { Component, fetch, glEventHub, metadata } = _a, props = __rest(_a, ["Component", "fetch", "glEventHub", "metadata"]); const dh = useApi(); const [view, setView] = useState('grid'); const [chartModel, setChartModel] = useState(null); const [isBuilding, setIsBuilding] = useState(false); + const { isAvailable: isPivotAvailable, pivotModel, isBuilding: isPivotBuilding, handleToggle: handlePivot, } = usePivotToggle(dh, fetch, view === 'pivot', setView, metadata); + const mouseHandlers = usePivotMouseHandlers(); + const renderer = usePivotRenderer(); + const pivotTheme = usePivotTheme(); useEffect(() => () => { chartModel === null || chartModel === void 0 ? void 0 : chartModel.close(); }, [chartModel]); @@ -36,7 +43,7 @@ export function GridToolbarPanelMiddleware(_a) { // fetch is typed as () => Promise; for grid widgets it returns dh.Table // eslint-disable-next-line @typescript-eslint/no-explicit-any const table = (await fetch()); - if (!(table === null || table === void 0 ? void 0 : table.columns) || table.columns.length < 2) { + if ((table === null || table === void 0 ? void 0 : table.columns) == null || table.columns.length < 2) { log.warn('Table has fewer than 2 columns; cannot build chart'); return; } @@ -64,9 +71,10 @@ export function GridToolbarPanelMiddleware(_a) { log.info('Reset Filters clicked'); glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); }, [glEventHub]); - return (_jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: isBuilding, onClick: handleChart, children: view === 'chart' ? 'Grid' : 'Chart' }), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === 'chart' && chartModel != null ? (_jsx("div", { className: "h-100 w-100", children: _jsx(Chart, { model: chartModel }) })) : ( - // eslint-disable-next-line react/jsx-props-no-spreading - _jsx(Component, Object.assign({ fetch: fetch, glEventHub: glEventHub }, props))) })] })); + const anyBuilding = isBuilding || isPivotBuilding; + return (_jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: anyBuilding, onClick: handleChart, children: view === 'chart' ? 'Grid' : 'Chart' }), isPivotAvailable && (_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: anyBuilding, onClick: handlePivot, children: view === 'pivot' ? 'Grid' : 'Pivot' })), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsxs("div", { className: "grid-toolbar-content h-100 w-100", children: [view === 'chart' && chartModel != null && (_jsx("div", { className: "h-100 w-100", children: _jsx(Chart, { model: chartModel }) })), view === 'pivot' && pivotModel != null && (_jsx("div", { className: "h-100 w-100", children: _jsx(IrisGrid, { model: pivotModel, mouseHandlers: mouseHandlers, renderer: renderer, theme: pivotTheme }) })), view !== 'chart' && view !== 'pivot' && ( + // eslint-disable-next-line react/jsx-props-no-spreading + _jsx(Component, Object.assign({ fetch: fetch, glEventHub: glEventHub, metadata: metadata }, props)))] })] })); } export default GridToolbarPanelMiddleware; //# sourceMappingURL=GridToolbarPanelMiddleware.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map index 6f75ad5c1..118af158f 100644 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map +++ b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map @@ -1 +1 @@ -{"version":3,"file":"GridToolbarPanelMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAIjC,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,oFAAoF;AACpF,MAAM,uBAAuB,GAAG,oCAAoC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CAAC,EAKd;QALc,EACzC,SAAS,EACT,KAAK,EACL,UAAU,OAEiB,EADxB,KAAK,cAJiC,oCAK1C,CADS;IAER,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IACpB,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAAmB,MAAM,CAAC,CAAC;IAC3D,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,IAAI,CAAC,CAAC;IACtE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEpD,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,EAAE,CAAC;IACtB,CAAC,EACD,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACrB,OAAO,CAAC,MAAM,CAAC,CAAC;YAChB,OAAO;QACT,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC;YACH,iFAAiF;YACjF,8DAA8D;YAC9D,MAAM,KAAK,GAAG,CAAC,MAAM,KAAK,EAAE,CAAQ,CAAC;YACrC,IAAI,CAAC,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,CAAA,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAChD,GAAG,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;gBAC/D,OAAO;YACT,CAAC;YACD,MAAM,QAAQ,GAAG;gBACf,IAAI,EAAE,MAAe;gBACrB,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc,CAAC;gBACzC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc;aACvC,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,qBAAqB;YACzD,8DAA8D;YAC9D,EAAS;YACT,8DAA8D;YAC9D,QAAe,EACf,KAAK,CACN,CAAC;YACF,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,GAAG,CAAC,KAAK,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;QAC9C,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAClC,UAAU,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,OAAO,CACL,eAAK,SAAS,EAAC,qCAAqC,aAClD,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,UAAU,EACpB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,cAAK,SAAS,EAAC,kCAAkC,YAC9C,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,CAAC,CAAC,CAAC,CACxC,cAAK,SAAS,EAAC,aAAa,YAE1B,KAAC,KAAK,IAAC,KAAK,EAAE,UAAiB,GAAI,GAC/B,CACP,CAAC,CAAC,CAAC;gBACF,wDAAwD;gBACxD,KAAC,SAAS,kBAAC,KAAK,EAAE,KAAK,EAAE,UAAU,EAAE,UAAU,IAAM,KAAK,EAAI,CAC/D,GACG,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file +{"version":3,"file":"GridToolbarPanelMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAGjC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,oFAAoF;AACpF,MAAM,uBAAuB,GAAG,oCAAoC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CAAC,EAMd;QANc,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,QAAQ,OAEmB,EADxB,KAAK,cALiC,gDAM1C,CADS;IAER,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IACpB,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAA6B,MAAM,CAAC,CAAC;IACrE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,IAAI,CAAC,CAAC;IACtE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEpD,MAAM,EACJ,WAAW,EAAE,gBAAgB,EAC7B,UAAU,EACV,UAAU,EAAE,eAAe,EAC3B,YAAY,EAAE,WAAW,GAC1B,GAAG,cAAc,CAChB,EAAE,EACF,KAAK,EACL,IAAI,KAAK,OAAO,EAChB,OAAwC,EACxC,QAAQ,CACT,CAAC;IAEF,MAAM,aAAa,GAAG,qBAAqB,EAAE,CAAC;IAC9C,MAAM,QAAQ,GAAG,gBAAgB,EAAE,CAAC;IACpC,MAAM,UAAU,GAAG,aAAa,EAAE,CAAC;IAEnC,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,EAAE,CAAC;IACtB,CAAC,EACD,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACrB,OAAO,CAAC,MAAM,CAAC,CAAC;YAChB,OAAO;QACT,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC;YACH,iFAAiF;YACjF,8DAA8D;YAC9D,MAAM,KAAK,GAAG,CAAC,MAAM,KAAK,EAAE,CAAQ,CAAC;YACrC,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,KAAI,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvD,GAAG,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;gBAC/D,OAAO;YACT,CAAC;YACD,MAAM,QAAQ,GAAG;gBACf,IAAI,EAAE,MAAe;gBACrB,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc,CAAC;gBACzC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc;aACvC,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,qBAAqB;YACzD,8DAA8D;YAC9D,EAAS;YACT,8DAA8D;YAC9D,QAAe,EACf,KAAK,CACN,CAAC;YACF,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,GAAG,CAAC,KAAK,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;QAC9C,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAClC,UAAU,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,MAAM,WAAW,GAAG,UAAU,IAAI,eAAe,CAAC;IAElD,OAAO,CACL,eAAK,SAAS,EAAC,qCAAqC,aAClD,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,WAAW,EACrB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,EACR,gBAAgB,IAAI,CACnB,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,WAAW,EACrB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,CACV,EACD,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,eAAK,SAAS,EAAC,kCAAkC,aAC9C,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,IAAI,CACzC,cAAK,SAAS,EAAC,aAAa,YAE1B,KAAC,KAAK,IAAC,KAAK,EAAE,UAAiB,GAAI,GAC/B,CACP,EACA,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,IAAI,CACzC,cAAK,SAAS,EAAC,aAAa,YAC1B,KAAC,QAAQ,IACP,KAAK,EAAE,UAAU,EACjB,aAAa,EAAE,aAAa,EAC5B,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE,UAAU,GACjB,GACE,CACP,EACA,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,IAAI;oBACvC,wDAAwD;oBACxD,KAAC,SAAS,kBACR,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,QAAQ,IACd,KAAK,EACT,CACH,IACG,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js index 494c54b4e..256fac680 100644 --- a/plugins/grid-toolbar/src/js/dist/bundle/index.js +++ b/plugins/grid-toolbar/src/js/dist/bundle/index.js @@ -4,7 +4,9 @@ const plugin = require("@deephaven/plugin"); const require$$1 = require("react"); const Log = require("@deephaven/log"); const chart = require("@deephaven/chart"); +const irisGrid = require("@deephaven/iris-grid"); const jsapiBootstrap = require("@deephaven/jsapi-bootstrap"); +const jsPluginPivot = require("@deephaven/js-plugin-pivot"); var jsxRuntime = { exports: {} }; var reactJsxRuntime_production_min = {}; /* @@ -106,16 +108,16 @@ reactJsxRuntime_production_min.jsxs = q; jsxRuntime.exports = reactJsxRuntime_production_min; } var jsxRuntimeExports = jsxRuntime.exports; -const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar"); +const log$2 = Log.module("@deephaven/js-plugin-grid-toolbar"); function GridToolbarMiddleware({ Component, ...props }) { const handleExport = require$$1.useCallback(() => { - log$1.info("Export clicked"); + log$2.info("Export clicked"); }, []); const handleResetFilters = require$$1.useCallback(() => { - log$1.info("[0] Reset Filters clicked", props, Component); + log$2.info("[0] Reset Filters clicked", props, Component); }, [props, Component]); return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ @@ -141,18 +143,154 @@ function GridToolbarMiddleware({ /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) ] }); } +const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar/usePivotToggle"); +const NUMERIC_TYPES = /* @__PURE__ */ new Set([ + "int", + "long", + "short", + "byte", + "double", + "float", + "java.lang.Integer", + "java.lang.Long", + "java.lang.Short", + "java.lang.Byte", + "java.lang.Double", + "java.lang.Float", + "java.math.BigDecimal", + "java.math.BigInteger" +]); +function usePivotToggle(dh, fetch, isPivotView, setView, metadata) { + const [pivotModel, setPivotModel] = require$$1.useState(null); + const [isBuilding, setIsBuilding] = require$$1.useState(false); + const pspDescriptor = require$$1.useMemo(() => { + if (!jsPluginPivot.isCorePlusDh(dh) || metadata == null) { + return { type: "PivotService", name: "__unavailable__" }; + } + return { + ...metadata, + type: "PivotService", + name: "psp" + }; + }, [dh, metadata]); + const pspFetch = jsapiBootstrap.useObjectFetch(pspDescriptor); + const isAvailable = jsPluginPivot.isCorePlusDh(dh) && pspFetch.status === "ready"; + require$$1.useEffect(() => { + if (pspFetch.status === "error") { + log$1.debug("PivotService (psp) not available on this query"); + } + if (pspFetch.status === "ready") { + log$1.info("PivotService (psp) is available on this query"); + } + }, [pspFetch.status]); + const pivotModelRef = require$$1.useRef(null); + require$$1.useEffect(() => { + pivotModelRef.current = pivotModel; + }, [pivotModel]); + require$$1.useEffect( + () => () => { + var _a; + (_a = pivotModelRef.current) == null ? void 0 : _a.close(); + }, + [] + ); + const handleToggle = require$$1.useCallback(async () => { + if (isPivotView) { + pivotModel == null ? void 0 : pivotModel.close(); + setPivotModel(null); + setView("grid"); + return; + } + if (!jsPluginPivot.isCorePlusDh(dh)) { + log$1.error("CorePlus API not available; cannot create pivot"); + return; + } + if (pspFetch.status !== "ready") { + log$1.error("PivotService (psp) not available"); + return; + } + setIsBuilding(true); + try { + const [table, pspWidget] = await Promise.all([ + fetch(), + pspFetch.fetch() + ]); + if ((table == null ? void 0 : table.columns) == null) { + log$1.warn("Fetched object has no columns; cannot build pivot"); + return; + } + const numericColumns = []; + const nonNumericColumns = []; + table.columns.forEach((col) => { + if (NUMERIC_TYPES.has(col.type)) { + numericColumns.push(col.name); + } else { + nonNumericColumns.push(col.name); + } + }); + if (nonNumericColumns.length === 0) { + log$1.warn("Table has no non-numeric columns for row/column keys"); + return; + } + const rowKeys = nonNumericColumns.slice(0, 1); + const columnKeys = nonNumericColumns.length > 1 ? nonNumericColumns.slice(1, 2) : []; + const aggregations = numericColumns.length > 0 ? { Sum: numericColumns } : { Count: [nonNumericColumns[0]] }; + const config = { + source: table, + rowKeys, + columnKeys, + aggregations + }; + log$1.info("Creating pivot with config:", config); + const corePlusDh = dh; + const pivotService = await corePlusDh.coreplus.pivot.PivotService.getInstance(pspWidget); + log$1.info("PivotService obtained:", pivotService); + const pivotTable = await pivotService.createPivotTable(config); + log$1.info("PivotTable created:", pivotTable); + const model = new jsPluginPivot.IrisGridPivotModel(dh, pivotTable); + setPivotModel(model); + setView("pivot"); + } catch (e) { + log$1.error("Failed to create pivot table", e); + } finally { + setIsBuilding(false); + } + }, [dh, fetch, isPivotView, pspFetch, pivotModel, setView]); + return { + isAvailable, + pivotModel, + isBuilding, + handleToggle + }; +} const log = Log.module("@deephaven/js-plugin-grid-toolbar"); const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, + metadata, ...props }) { const dh = jsapiBootstrap.useApi(); const [view, setView] = require$$1.useState("grid"); const [chartModel, setChartModel] = require$$1.useState(null); const [isBuilding, setIsBuilding] = require$$1.useState(false); + const { + isAvailable: isPivotAvailable, + pivotModel, + isBuilding: isPivotBuilding, + handleToggle: handlePivot + } = usePivotToggle( + dh, + fetch, + view === "pivot", + setView, + metadata + ); + const mouseHandlers = jsPluginPivot.usePivotMouseHandlers(); + const renderer = jsPluginPivot.usePivotRenderer(); + const pivotTheme = jsPluginPivot.usePivotTheme(); require$$1.useEffect( () => () => { chartModel == null ? void 0 : chartModel.close(); @@ -167,7 +305,7 @@ function GridToolbarPanelMiddleware({ setIsBuilding(true); try { const table = await fetch(); - if (!(table == null ? void 0 : table.columns) || table.columns.length < 2) { + if ((table == null ? void 0 : table.columns) == null || table.columns.length < 2) { log.warn("Table has fewer than 2 columns; cannot build chart"); return; } @@ -195,6 +333,7 @@ function GridToolbarPanelMiddleware({ log.info("Reset Filters clicked"); glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); }, [glEventHub]); + const anyBuilding = isBuilding || isPivotBuilding; return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ /* @__PURE__ */ jsxRuntimeExports.jsx( @@ -202,12 +341,21 @@ function GridToolbarPanelMiddleware({ { type: "button", className: "grid-toolbar-btn", - disabled: isBuilding, + disabled: anyBuilding, onClick: handleChart, children: view === "chart" ? "Grid" : "Chart" } ), - /* @__PURE__ */ jsxRuntimeExports.jsx("button", { type: "button", className: "grid-toolbar-btn", children: "Pivot" }), + isPivotAvailable && /* @__PURE__ */ jsxRuntimeExports.jsx( + "button", + { + type: "button", + className: "grid-toolbar-btn", + disabled: anyBuilding, + onClick: handlePivot, + children: view === "pivot" ? "Grid" : "Pivot" + } + ), /* @__PURE__ */ jsxRuntimeExports.jsx( "button", { @@ -218,10 +366,28 @@ function GridToolbarPanelMiddleware({ } ) ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content h-100 w-100", children: view === "chart" && chartModel != null ? /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(chart.Chart, { model: chartModel }) }) : ( - // eslint-disable-next-line react/jsx-props-no-spreading - /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { fetch, glEventHub, ...props }) - ) }) + /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-content h-100 w-100", children: [ + view === "chart" && chartModel != null && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(chart.Chart, { model: chartModel }) }), + view === "pivot" && pivotModel != null && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx( + irisGrid.IrisGrid, + { + model: pivotModel, + mouseHandlers, + renderer, + theme: pivotTheme + } + ) }), + view !== "chart" && view !== "pivot" && // eslint-disable-next-line react/jsx-props-no-spreading + /* @__PURE__ */ jsxRuntimeExports.jsx( + Component, + { + fetch, + glEventHub, + metadata, + ...props + } + ) + ] }) ] }); } const GridToolbarPlugin = { @@ -238,5 +404,7 @@ const GridToolbarPlugin = { isMiddleware: true }; exports.GridToolbarMiddleware = GridToolbarMiddleware; +exports.GridToolbarPanelMiddleware = GridToolbarPanelMiddleware; exports.GridToolbarPlugin = GridToolbarPlugin; exports.default = GridToolbarPlugin; +exports.usePivotToggle = usePivotToggle; diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts b/plugins/grid-toolbar/src/js/dist/index.d.ts index 36fa1d61c..460041db5 100644 --- a/plugins/grid-toolbar/src/js/dist/index.d.ts +++ b/plugins/grid-toolbar/src/js/dist/index.d.ts @@ -1,5 +1,7 @@ import { GridToolbarPlugin } from './GridToolbarPlugin'; export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; export { GridToolbarPlugin } from './GridToolbarPlugin'; +export { usePivotToggle } from './usePivotToggle'; export default GridToolbarPlugin; //# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts.map b/plugins/grid-toolbar/src/js/dist/index.d.ts.map index aebf3c6d1..88543f78b 100644 --- a/plugins/grid-toolbar/src/js/dist/index.d.ts.map +++ b/plugins/grid-toolbar/src/js/dist/index.d.ts.map @@ -1 +1 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,eAAe,iBAAiB,CAAC"} \ No newline at end of file +{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js b/plugins/grid-toolbar/src/js/dist/index.js index 29a5bc503..a6f6784ae 100644 --- a/plugins/grid-toolbar/src/js/dist/index.js +++ b/plugins/grid-toolbar/src/js/dist/index.js @@ -1,5 +1,7 @@ import { GridToolbarPlugin } from './GridToolbarPlugin'; export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; export { GridToolbarPlugin } from './GridToolbarPlugin'; +export { usePivotToggle } from './usePivotToggle'; export default GridToolbarPlugin; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js.map b/plugins/grid-toolbar/src/js/dist/index.js.map index 2dd4b5219..ef7210b22 100644 --- a/plugins/grid-toolbar/src/js/dist/index.js.map +++ b/plugins/grid-toolbar/src/js/dist/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,eAAe,iBAAiB,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/package.json b/plugins/grid-toolbar/src/js/package.json index 3805b2095..3ea9ae484 100644 --- a/plugins/grid-toolbar/src/js/package.json +++ b/plugins/grid-toolbar/src/js/package.json @@ -38,6 +38,7 @@ "build:bundle": "vite build" }, "devDependencies": { + "@deephaven-enterprise/jsapi-coreplus-types": "^1.20240517.518", "@types/react": "^17.0.2", "react": "^17.0.2", "react-dom": "^17.0.2" @@ -50,6 +51,8 @@ "@deephaven/chart": "^0.106.0", "@deephaven/components": "^0.106.0", "@deephaven/icons": "^0.106.0", + "@deephaven/iris-grid": "^0.106.0", + "@deephaven/js-plugin-pivot": "*", "@deephaven/jsapi-bootstrap": "^0.106.0", "@deephaven/log": "^0.106.2", "@deephaven/plugin": "^0.106.4" diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index dea023a39..4372fecfb 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -1,9 +1,16 @@ import { useCallback, useEffect, useState } from 'react'; import { Chart, type ChartModel, ChartModelFactory } from '@deephaven/chart'; +import { IrisGrid } from '@deephaven/iris-grid'; import { useApi } from '@deephaven/jsapi-bootstrap'; +import { + usePivotMouseHandlers, + usePivotRenderer, + usePivotTheme, +} from '@deephaven/js-plugin-pivot'; import Log from '@deephaven/log'; // TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; +import { usePivotToggle } from './usePivotToggle'; const log = Log.module('@deephaven/js-plugin-grid-toolbar'); @@ -14,13 +21,31 @@ export function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, + metadata, ...props }: WidgetMiddlewarePanelProps): JSX.Element { const dh = useApi(); - const [view, setView] = useState<'grid' | 'chart'>('grid'); + const [view, setView] = useState<'grid' | 'chart' | 'pivot'>('grid'); const [chartModel, setChartModel] = useState(null); const [isBuilding, setIsBuilding] = useState(false); + const { + isAvailable: isPivotAvailable, + pivotModel, + isBuilding: isPivotBuilding, + handleToggle: handlePivot, + } = usePivotToggle( + dh, + fetch, + view === 'pivot', + setView as (v: 'grid' | 'pivot') => void, + metadata + ); + + const mouseHandlers = usePivotMouseHandlers(); + const renderer = usePivotRenderer(); + const pivotTheme = usePivotTheme(); + useEffect( () => () => { chartModel?.close(); @@ -38,7 +63,7 @@ export function GridToolbarPanelMiddleware({ // fetch is typed as () => Promise; for grid widgets it returns dh.Table // eslint-disable-next-line @typescript-eslint/no-explicit-any const table = (await fetch()) as any; - if (!table?.columns || table.columns.length < 2) { + if (table?.columns == null || table.columns.length < 2) { log.warn('Table has fewer than 2 columns; cannot build chart'); return; } @@ -68,20 +93,29 @@ export function GridToolbarPanelMiddleware({ glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); }, [glEventHub]); + const anyBuilding = isBuilding || isPivotBuilding; + return (
- + {isPivotAvailable && ( + + )}
- {view === 'chart' && chartModel != null ? ( + {view === 'chart' && chartModel != null && (
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */}
- ) : ( + )} + {view === 'pivot' && pivotModel != null && ( +
+ +
+ )} + {view !== 'chart' && view !== 'pivot' && ( // eslint-disable-next-line react/jsx-props-no-spreading - + )}
diff --git a/plugins/grid-toolbar/src/js/src/index.ts b/plugins/grid-toolbar/src/js/src/index.ts index b2fde617c..98b7307d8 100644 --- a/plugins/grid-toolbar/src/js/src/index.ts +++ b/plugins/grid-toolbar/src/js/src/index.ts @@ -1,6 +1,8 @@ import { GridToolbarPlugin } from './GridToolbarPlugin'; export { GridToolbarMiddleware } from './GridToolbarMiddleware'; +export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; export { GridToolbarPlugin } from './GridToolbarPlugin'; +export { usePivotToggle } from './usePivotToggle'; export default GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/src/pivotPlugin.d.ts b/plugins/grid-toolbar/src/js/src/pivotPlugin.d.ts new file mode 100644 index 000000000..61eef97af --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/pivotPlugin.d.ts @@ -0,0 +1,27 @@ +/** + * Ambient type declarations for @deephaven/js-plugin-pivot. + * The pivot plugin's CJS bundle doesn't ship .d.ts files. + * These declarations provide minimal typing for the exports we consume. + */ +declare module '@deephaven/js-plugin-pivot' { + import type { IrisGridModel } from '@deephaven/iris-grid'; + + export class IrisGridPivotModel extends IrisGridModel { + constructor( + dh: unknown, + pivotTable: unknown, + formatter?: unknown, + config?: unknown + ); + } + + export function isIrisGridPivotModel(model: unknown): boolean; + export function isCorePlusDh(dh: unknown): boolean; + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function usePivotMouseHandlers(): any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function usePivotRenderer(): any; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + export function usePivotTheme(): any; +} diff --git a/plugins/grid-toolbar/src/js/src/usePivotToggle.ts b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts new file mode 100644 index 000000000..9ace1da56 --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts @@ -0,0 +1,195 @@ +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; +import { type dh as DhType } from '@deephaven/jsapi-types'; +import { type dh as CorePlusDhType } from '@deephaven-enterprise/jsapi-coreplus-types'; +import { type IrisGridModel } from '@deephaven/iris-grid'; +import { useObjectFetch } from '@deephaven/jsapi-bootstrap'; +import { IrisGridPivotModel, isCorePlusDh } from '@deephaven/js-plugin-pivot'; +import Log from '@deephaven/log'; + +const log = Log.module('@deephaven/js-plugin-grid-toolbar/usePivotToggle'); + +const NUMERIC_TYPES = new Set([ + 'int', + 'long', + 'short', + 'byte', + 'double', + 'float', + 'java.lang.Integer', + 'java.lang.Long', + 'java.lang.Short', + 'java.lang.Byte', + 'java.lang.Double', + 'java.lang.Float', + 'java.math.BigDecimal', + 'java.math.BigInteger', +]); + +export interface PivotToggleResult { + /** Whether CorePlus pivot API is available */ + isAvailable: boolean; + /** The IrisGridModel for the pivot table, or null if not in pivot view */ + pivotModel: IrisGridModel | null; + /** Whether pivot creation is in progress */ + isBuilding: boolean; + /** Toggle between grid and pivot views */ + handleToggle: () => void; +} + +/** + * Hook to toggle between grid and pivot views. + * Creates a PivotTable from the fetched table using PivotService with auto-detected defaults. + */ +export function usePivotToggle( + dh: typeof DhType | typeof CorePlusDhType, + fetch: () => Promise, + isPivotView: boolean, + setView: (view: 'grid' | 'pivot') => void, + metadata?: DhType.ide.VariableDescriptor +): PivotToggleResult { + const [pivotModel, setPivotModel] = useState(null); + const [isBuilding, setIsBuilding] = useState(false); + + // Build a descriptor for the PivotService variable on the same query. + // The convention is that PivotServicePlugin is exported as 'psp'. + // We copy querySerial from the table's metadata so the ObjectFetchManager + // routes to the same query/worker. + const pspDescriptor = useMemo(() => { + if (!isCorePlusDh(dh) || metadata == null) { + return { type: 'PivotService', name: '__unavailable__' }; + } + return { + ...metadata, + type: 'PivotService', + name: 'psp', + }; + }, [dh, metadata]); + + const pspFetch = useObjectFetch(pspDescriptor); + + const isAvailable = isCorePlusDh(dh) && pspFetch.status === 'ready'; + + useEffect(() => { + if (pspFetch.status === 'error') { + log.debug('PivotService (psp) not available on this query'); + } + if (pspFetch.status === 'ready') { + log.info('PivotService (psp) is available on this query'); + } + }, [pspFetch.status]); + + // Track the current model ref for cleanup + const pivotModelRef = useRef(null); + + useEffect(() => { + pivotModelRef.current = pivotModel; + }, [pivotModel]); + + // Cleanup pivot model on unmount + useEffect( + () => () => { + pivotModelRef.current?.close(); + }, + [] + ); + + const handleToggle = useCallback(async () => { + if (isPivotView) { + // Switch back to grid + pivotModel?.close(); + setPivotModel(null); + setView('grid'); + return; + } + + if (!isCorePlusDh(dh)) { + log.error('CorePlus API not available; cannot create pivot'); + return; + } + + if (pspFetch.status !== 'ready') { + log.error('PivotService (psp) not available'); + return; + } + + setIsBuilding(true); + try { + // Fetch the source table and the PivotService widget in parallel + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const [table, pspWidget] = (await Promise.all([ + fetch(), + pspFetch.fetch(), + ])) as [any, any]; + + if (table?.columns == null) { + log.warn('Fetched object has no columns; cannot build pivot'); + return; + } + + // Auto-detect column categories + const numericColumns: string[] = []; + const nonNumericColumns: string[] = []; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + table.columns.forEach((col: any) => { + if (NUMERIC_TYPES.has(col.type)) { + numericColumns.push(col.name); + } else { + nonNumericColumns.push(col.name); + } + }); + + if (nonNumericColumns.length === 0) { + log.warn('Table has no non-numeric columns for row/column keys'); + return; + } + + // Split non-numeric columns: first goes to rows, rest to columns + const rowKeys = nonNumericColumns.slice(0, 1); + const columnKeys = + nonNumericColumns.length > 1 ? nonNumericColumns.slice(1, 2) : []; + + // Use all numeric columns as values with Sum aggregation + // If no numeric columns, use Count on the first non-numeric column + const aggregations: Record = + numericColumns.length > 0 + ? { Sum: numericColumns } + : { Count: [nonNumericColumns[0]] }; + + const config = { + source: table, + rowKeys, + columnKeys, + aggregations, + }; + + log.info('Creating pivot with config:', config); + + // Get PivotService from the psp widget, then create PivotTable + const corePlusDh = dh as typeof CorePlusDhType; + const pivotService = + await corePlusDh.coreplus.pivot.PivotService.getInstance(pspWidget); + log.info('PivotService obtained:', pivotService); + const pivotTable = await pivotService.createPivotTable(config); + log.info('PivotTable created:', pivotTable); + + // Create the IrisGridPivotModel + const model = new IrisGridPivotModel(dh, pivotTable); + + setPivotModel(model); + setView('pivot'); + } catch (e) { + log.error('Failed to create pivot table', e); + } finally { + setIsBuilding(false); + } + }, [dh, fetch, isPivotView, pspFetch, pivotModel, setView]); + + return { + isAvailable, + pivotModel, + isBuilding, + handleToggle, + }; +} + +export default usePivotToggle; diff --git a/plugins/grid-toolbar/src/js/vite.config.ts b/plugins/grid-toolbar/src/js/vite.config.ts index aeb899f36..4bf49299a 100644 --- a/plugins/grid-toolbar/src/js/vite.config.ts +++ b/plugins/grid-toolbar/src/js/vite.config.ts @@ -16,12 +16,22 @@ export default defineConfig(({ mode }) => ({ external: [ 'react', 'react-dom', + 'redux', + 'react-redux', + 'memoize-one', + 'lodash.throttle', '@deephaven/chart', '@deephaven/components', + '@deephaven/grid', '@deephaven/icons', + '@deephaven/iris-grid', + '@deephaven/js-plugin-pivot', '@deephaven/jsapi-bootstrap', + '@deephaven/jsapi-utils', '@deephaven/log', '@deephaven/plugin', + '@deephaven/react-hooks', + '@deephaven/utils', ], }, }, diff --git a/plugins/pivot/src/js/src/index.ts b/plugins/pivot/src/js/src/index.ts index 878b1f931..83b74c26c 100644 --- a/plugins/pivot/src/js/src/index.ts +++ b/plugins/pivot/src/js/src/index.ts @@ -3,4 +3,15 @@ import { PivotPlugin } from './PivotPlugin'; // Export legacy dashboard plugin as named export for compatibility with Grizzly export * from './DashboardPlugin'; +// Export pivot model and utilities for use by other plugins +export { default as IrisGridPivotModel } from './IrisGridPivotModel'; +export { isIrisGridPivotModel } from './IrisGridPivotModel'; +export { isCorePlusDh } from './PivotUtils'; +export { useIrisGridPivotModel } from './useIrisGridPivotModel'; +export { usePivotTableFetch } from './hooks/usePivotTableFetch'; +export { usePivotMouseHandlers } from './hooks/usePivotMouseHandlers'; +export { usePivotRenderer } from './hooks/usePivotRenderer'; +export { usePivotTheme } from './hooks/usePivotTheme'; +export { default as usePivotMetricCalculatorFactory } from './hooks/usePivotMetricCalculatorFactory'; + export default PivotPlugin; From fac62a4070fea2f44d8fadc239e64a4802842df4 Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Thu, 23 Apr 2026 22:58:59 -0600 Subject: [PATCH 09/11] PivotBuilder VIP --- plugins/grid-toolbar/.gitignore | 8 - plugins/grid-toolbar/pyproject.toml | 3 - plugins/grid-toolbar/setup.cfg | 33 -- plugins/grid-toolbar/setup.py | 3 - plugins/grid-toolbar/src/js/.gitignore | 5 + .../src/js/dist/GridToolbarMiddleware.d.ts | 4 - .../js/dist/GridToolbarMiddleware.d.ts.map | 1 - .../src/js/dist/GridToolbarMiddleware.js | 27 -- .../src/js/dist/GridToolbarMiddleware.js.map | 1 - .../js/dist/GridToolbarPanelMiddleware.d.ts | 4 - .../dist/GridToolbarPanelMiddleware.d.ts.map | 1 - .../src/js/dist/GridToolbarPanelMiddleware.js | 80 ---- .../js/dist/GridToolbarPanelMiddleware.js.map | 1 - .../src/js/dist/GridToolbarPlugin.d.ts | 4 - .../src/js/dist/GridToolbarPlugin.d.ts.map | 1 - .../src/js/dist/GridToolbarPlugin.js | 18 - .../src/js/dist/GridToolbarPlugin.js.map | 1 - .../grid-toolbar/src/js/dist/bundle/index.js | 410 ----------------- plugins/grid-toolbar/src/js/dist/index.d.ts | 7 - .../grid-toolbar/src/js/dist/index.d.ts.map | 1 - plugins/grid-toolbar/src/js/dist/index.js | 7 - plugins/grid-toolbar/src/js/dist/index.js.map | 1 - .../src/js/dist/middlewareTypes.d.ts | 31 -- .../src/js/dist/middlewareTypes.d.ts.map | 1 - .../src/js/dist/middlewareTypes.js | 2 - .../src/js/dist/middlewareTypes.js.map | 1 - .../src/js/src/GridToolbarPanelMiddleware.tsx | 69 ++- .../src/js/src/PivotBuilderDialog.css | 176 ++++++++ .../src/js/src/PivotBuilderDialog.tsx | 411 ++++++++++++++++++ plugins/grid-toolbar/src/js/src/index.ts | 2 + .../grid-toolbar/src/js/src/usePivotToggle.ts | 179 ++++---- plugins/grid-toolbar/tox.ini | 24 - plugins/manifest.json | 6 +- 33 files changed, 747 insertions(+), 776 deletions(-) delete mode 100644 plugins/grid-toolbar/.gitignore delete mode 100644 plugins/grid-toolbar/pyproject.toml delete mode 100644 plugins/grid-toolbar/setup.cfg delete mode 100644 plugins/grid-toolbar/setup.py create mode 100644 plugins/grid-toolbar/src/js/.gitignore delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js delete mode 100644 plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map delete mode 100644 plugins/grid-toolbar/src/js/dist/bundle/index.js delete mode 100644 plugins/grid-toolbar/src/js/dist/index.d.ts delete mode 100644 plugins/grid-toolbar/src/js/dist/index.d.ts.map delete mode 100644 plugins/grid-toolbar/src/js/dist/index.js delete mode 100644 plugins/grid-toolbar/src/js/dist/index.js.map delete mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts delete mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map delete mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.js delete mode 100644 plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map create mode 100644 plugins/grid-toolbar/src/js/src/PivotBuilderDialog.css create mode 100644 plugins/grid-toolbar/src/js/src/PivotBuilderDialog.tsx delete mode 100644 plugins/grid-toolbar/tox.ini diff --git a/plugins/grid-toolbar/.gitignore b/plugins/grid-toolbar/.gitignore deleted file mode 100644 index 3356dc1ce..000000000 --- a/plugins/grid-toolbar/.gitignore +++ /dev/null @@ -1,8 +0,0 @@ -build/ -dist/ -.venv/ -/venv -*.egg-info/ -.idea -.DS_store -__pycache__/ \ No newline at end of file diff --git a/plugins/grid-toolbar/pyproject.toml b/plugins/grid-toolbar/pyproject.toml deleted file mode 100644 index 62df2b006..000000000 --- a/plugins/grid-toolbar/pyproject.toml +++ /dev/null @@ -1,3 +0,0 @@ -[build-system] -requires = ["setuptools>=43.0.0", "wheel"] -build-backend = "setuptools.build_meta" diff --git a/plugins/grid-toolbar/setup.cfg b/plugins/grid-toolbar/setup.cfg deleted file mode 100644 index d5ff78c2a..000000000 --- a/plugins/grid-toolbar/setup.cfg +++ /dev/null @@ -1,33 +0,0 @@ -[metadata] -name = deephaven-plugin-grid-toolbar -description = Deephaven Grid Toolbar Plugin -long_description = file: README.md -long_description_content_type = text/markdown -version = 0.0.1 -url = https://github.com/deephaven/deephaven-plugins -project_urls = - Source Code = https://github.com/deephaven/deephaven-plugins - Bug Tracker = https://github.com/deephaven/deephaven-plugins/issues -classifiers = - Programming Language :: Python :: 3 - License :: OSI Approved :: Apache Software License - Operating System :: OS Independent - Environment :: Plugins - Topic :: Scientific/Engineering :: Visualization - Development Status :: 3 - Alpha -keywords = deephaven, plugin, grid-toolbar, toolbar, middleware -author = Deephaven Data Labs -author_email = support@deephaven.io -platforms = any - -[options] -package_dir= - =src -packages=find_namespace: -install_requires = - deephaven-core>=0.37.0 - deephaven-plugin>=0.6.0 -include_package_data = True - -[options.packages.find] -where=src diff --git a/plugins/grid-toolbar/setup.py b/plugins/grid-toolbar/setup.py deleted file mode 100644 index 606849326..000000000 --- a/plugins/grid-toolbar/setup.py +++ /dev/null @@ -1,3 +0,0 @@ -from setuptools import setup - -setup() diff --git a/plugins/grid-toolbar/src/js/.gitignore b/plugins/grid-toolbar/src/js/.gitignore new file mode 100644 index 000000000..d22612a8d --- /dev/null +++ b/plugins/grid-toolbar/src/js/.gitignore @@ -0,0 +1,5 @@ +# Ignore npm dependencies +/node_modules + +# Ignore output directory +/dist diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts deleted file mode 100644 index eb2cc87c5..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { WidgetMiddlewareComponentProps } from './middlewareTypes'; -export declare function GridToolbarMiddleware({ Component, ...props }: WidgetMiddlewareComponentProps): JSX.Element; -export default GridToolbarMiddleware; -//# sourceMappingURL=GridToolbarMiddleware.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map deleted file mode 100644 index 72f5481fd..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarMiddleware.tsx"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,8BAA8B,EAAE,MAAM,mBAAmB,CAAC;AAIxE,wBAAgB,qBAAqB,CAAC,EACpC,SAAS,EACT,GAAG,KAAK,EACT,EAAE,8BAA8B,GAAG,GAAG,CAAC,OAAO,CAiC9C;AAED,eAAe,qBAAqB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js deleted file mode 100644 index 749c688f5..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js +++ /dev/null @@ -1,27 +0,0 @@ -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; -import { useCallback } from 'react'; -import Log from '@deephaven/log'; -const log = Log.module('@deephaven/js-plugin-grid-toolbar'); -export function GridToolbarMiddleware(_a) { - var { Component } = _a, props = __rest(_a, ["Component"]); - const handleExport = useCallback(() => { - log.info('Export clicked'); - }, []); - const handleResetFilters = useCallback(() => { - log.info('[0] Reset Filters clicked', props, Component); - }, [props, Component]); - return (_jsxs("div", { className: "grid-toolbar-middleware", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleExport, children: "Export" }), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsx("div", { className: "grid-toolbar-content", children: _jsx(Component, Object.assign({}, props)) })] })); -} -export default GridToolbarMiddleware; -//# sourceMappingURL=GridToolbarMiddleware.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map deleted file mode 100644 index 275683a2a..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarMiddleware.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,OAAO,CAAC;AACpC,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAIjC,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,MAAM,UAAU,qBAAqB,CAAC,EAGL;QAHK,EACpC,SAAS,OAEsB,EAD5B,KAAK,cAF4B,aAGrC,CADS;IAER,MAAM,YAAY,GAAG,WAAW,CAAC,GAAG,EAAE;QACpC,GAAG,CAAC,IAAI,CAAC,gBAAgB,CAAC,CAAC;IAC7B,CAAC,EAAE,EAAE,CAAC,CAAC;IAEP,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,2BAA2B,EAAE,KAAK,EAAE,SAAS,CAAC,CAAC;IAC1D,CAAC,EAAE,CAAC,KAAK,EAAE,SAAS,CAAC,CAAC,CAAC;IAEvB,OAAO,CACL,eAAK,SAAS,EAAC,yBAAyB,aACtC,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,YAAY,uBAGd,EACT,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,cAAK,SAAS,EAAC,sBAAsB,YAEnC,KAAC,SAAS,oBAAK,KAAK,EAAI,GACpB,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,qBAAqB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts deleted file mode 100644 index 7b1a23e44..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; -export declare function GridToolbarPanelMiddleware({ Component, fetch, glEventHub, metadata, ...props }: WidgetMiddlewarePanelProps): JSX.Element; -export default GridToolbarPanelMiddleware; -//# sourceMappingURL=GridToolbarPanelMiddleware.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map deleted file mode 100644 index d22f35343..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarPanelMiddleware.d.ts","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":"AAWA,OAAO,KAAK,EAAE,0BAA0B,EAAE,MAAM,mBAAmB,CAAC;AAQpE,wBAAgB,0BAA0B,CAAC,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,QAAQ,EACR,GAAG,KAAK,EACT,EAAE,0BAA0B,GAAG,GAAG,CAAC,OAAO,CAkI1C;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js deleted file mode 100644 index 5f4dd0877..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js +++ /dev/null @@ -1,80 +0,0 @@ -var __rest = (this && this.__rest) || function (s, e) { - var t = {}; - for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) - t[p] = s[p]; - if (s != null && typeof Object.getOwnPropertySymbols === "function") - for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { - if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) - t[p[i]] = s[p[i]]; - } - return t; -}; -import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime"; -import { useCallback, useEffect, useState } from 'react'; -import { Chart, ChartModelFactory } from '@deephaven/chart'; -import { IrisGrid } from '@deephaven/iris-grid'; -import { useApi } from '@deephaven/jsapi-bootstrap'; -import { usePivotMouseHandlers, usePivotRenderer, usePivotTheme, } from '@deephaven/js-plugin-pivot'; -import Log from '@deephaven/log'; -import { usePivotToggle } from './usePivotToggle'; -const log = Log.module('@deephaven/js-plugin-grid-toolbar'); -// Matches InputFilterEvent.CLEAR_ALL_FILTERS from @deephaven/dashboard-core-plugins -const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; -export function GridToolbarPanelMiddleware(_a) { - var { Component, fetch, glEventHub, metadata } = _a, props = __rest(_a, ["Component", "fetch", "glEventHub", "metadata"]); - const dh = useApi(); - const [view, setView] = useState('grid'); - const [chartModel, setChartModel] = useState(null); - const [isBuilding, setIsBuilding] = useState(false); - const { isAvailable: isPivotAvailable, pivotModel, isBuilding: isPivotBuilding, handleToggle: handlePivot, } = usePivotToggle(dh, fetch, view === 'pivot', setView, metadata); - const mouseHandlers = usePivotMouseHandlers(); - const renderer = usePivotRenderer(); - const pivotTheme = usePivotTheme(); - useEffect(() => () => { - chartModel === null || chartModel === void 0 ? void 0 : chartModel.close(); - }, [chartModel]); - const handleChart = useCallback(async () => { - if (view === 'chart') { - setView('grid'); - return; - } - setIsBuilding(true); - try { - // fetch is typed as () => Promise; for grid widgets it returns dh.Table - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const table = (await fetch()); - if ((table === null || table === void 0 ? void 0 : table.columns) == null || table.columns.length < 2) { - log.warn('Table has fewer than 2 columns; cannot build chart'); - return; - } - const settings = { - type: 'LINE', - series: [table.columns[1].name], - xAxis: table.columns[0].name, - }; - const model = await ChartModelFactory.makeModelFromSettings( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - dh, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - settings, table); - setChartModel(model); - setView('chart'); - } - catch (e) { - log.error('Failed to build chart model', e); - } - finally { - setIsBuilding(false); - } - }, [dh, fetch, view]); - const handleResetFilters = useCallback(() => { - log.info('Reset Filters clicked'); - glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub]); - const anyBuilding = isBuilding || isPivotBuilding; - return (_jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [_jsxs("div", { className: "grid-toolbar", children: [_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: anyBuilding, onClick: handleChart, children: view === 'chart' ? 'Grid' : 'Chart' }), isPivotAvailable && (_jsx("button", { type: "button", className: "grid-toolbar-btn", disabled: anyBuilding, onClick: handlePivot, children: view === 'pivot' ? 'Grid' : 'Pivot' })), _jsx("button", { type: "button", className: "grid-toolbar-btn", onClick: handleResetFilters, children: "Reset Filters" })] }), _jsxs("div", { className: "grid-toolbar-content h-100 w-100", children: [view === 'chart' && chartModel != null && (_jsx("div", { className: "h-100 w-100", children: _jsx(Chart, { model: chartModel }) })), view === 'pivot' && pivotModel != null && (_jsx("div", { className: "h-100 w-100", children: _jsx(IrisGrid, { model: pivotModel, mouseHandlers: mouseHandlers, renderer: renderer, theme: pivotTheme }) })), view !== 'chart' && view !== 'pivot' && ( - // eslint-disable-next-line react/jsx-props-no-spreading - _jsx(Component, Object.assign({ fetch: fetch, glEventHub: glEventHub, metadata: metadata }, props)))] })] })); -} -export default GridToolbarPanelMiddleware; -//# sourceMappingURL=GridToolbarPanelMiddleware.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map deleted file mode 100644 index 118af158f..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPanelMiddleware.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarPanelMiddleware.js","sourceRoot":"","sources":["../src/GridToolbarPanelMiddleware.tsx"],"names":[],"mappings":";;;;;;;;;;;;AAAA,OAAO,EAAE,WAAW,EAAE,SAAS,EAAE,QAAQ,EAAE,MAAM,OAAO,CAAC;AACzD,OAAO,EAAE,KAAK,EAAmB,iBAAiB,EAAE,MAAM,kBAAkB,CAAC;AAC7E,OAAO,EAAE,QAAQ,EAAE,MAAM,sBAAsB,CAAC;AAChD,OAAO,EAAE,MAAM,EAAE,MAAM,4BAA4B,CAAC;AACpD,OAAO,EACL,qBAAqB,EACrB,gBAAgB,EAChB,aAAa,GACd,MAAM,4BAA4B,CAAC;AACpC,OAAO,GAAG,MAAM,gBAAgB,CAAC;AAGjC,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,MAAM,GAAG,GAAG,GAAG,CAAC,MAAM,CAAC,mCAAmC,CAAC,CAAC;AAE5D,oFAAoF;AACpF,MAAM,uBAAuB,GAAG,oCAAoC,CAAC;AAErE,MAAM,UAAU,0BAA0B,CAAC,EAMd;QANc,EACzC,SAAS,EACT,KAAK,EACL,UAAU,EACV,QAAQ,OAEmB,EADxB,KAAK,cALiC,gDAM1C,CADS;IAER,MAAM,EAAE,GAAG,MAAM,EAAE,CAAC;IACpB,MAAM,CAAC,IAAI,EAAE,OAAO,CAAC,GAAG,QAAQ,CAA6B,MAAM,CAAC,CAAC;IACrE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAoB,IAAI,CAAC,CAAC;IACtE,MAAM,CAAC,UAAU,EAAE,aAAa,CAAC,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAEpD,MAAM,EACJ,WAAW,EAAE,gBAAgB,EAC7B,UAAU,EACV,UAAU,EAAE,eAAe,EAC3B,YAAY,EAAE,WAAW,GAC1B,GAAG,cAAc,CAChB,EAAE,EACF,KAAK,EACL,IAAI,KAAK,OAAO,EAChB,OAAwC,EACxC,QAAQ,CACT,CAAC;IAEF,MAAM,aAAa,GAAG,qBAAqB,EAAE,CAAC;IAC9C,MAAM,QAAQ,GAAG,gBAAgB,EAAE,CAAC;IACpC,MAAM,UAAU,GAAG,aAAa,EAAE,CAAC;IAEnC,SAAS,CACP,GAAG,EAAE,CAAC,GAAG,EAAE;QACT,UAAU,aAAV,UAAU,uBAAV,UAAU,CAAE,KAAK,EAAE,CAAC;IACtB,CAAC,EACD,CAAC,UAAU,CAAC,CACb,CAAC;IAEF,MAAM,WAAW,GAAG,WAAW,CAAC,KAAK,IAAI,EAAE;QACzC,IAAI,IAAI,KAAK,OAAO,EAAE,CAAC;YACrB,OAAO,CAAC,MAAM,CAAC,CAAC;YAChB,OAAO;QACT,CAAC;QACD,aAAa,CAAC,IAAI,CAAC,CAAC;QACpB,IAAI,CAAC;YACH,iFAAiF;YACjF,8DAA8D;YAC9D,MAAM,KAAK,GAAG,CAAC,MAAM,KAAK,EAAE,CAAQ,CAAC;YACrC,IAAI,CAAA,KAAK,aAAL,KAAK,uBAAL,KAAK,CAAE,OAAO,KAAI,IAAI,IAAI,KAAK,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBACvD,GAAG,CAAC,IAAI,CAAC,oDAAoD,CAAC,CAAC;gBAC/D,OAAO;YACT,CAAC;YACD,MAAM,QAAQ,GAAG;gBACf,IAAI,EAAE,MAAe;gBACrB,MAAM,EAAE,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc,CAAC;gBACzC,KAAK,EAAE,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,IAAc;aACvC,CAAC;YACF,MAAM,KAAK,GAAG,MAAM,iBAAiB,CAAC,qBAAqB;YACzD,8DAA8D;YAC9D,EAAS;YACT,8DAA8D;YAC9D,QAAe,EACf,KAAK,CACN,CAAC;YACF,aAAa,CAAC,KAAK,CAAC,CAAC;YACrB,OAAO,CAAC,OAAO,CAAC,CAAC;QACnB,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,GAAG,CAAC,KAAK,CAAC,6BAA6B,EAAE,CAAC,CAAC,CAAC;QAC9C,CAAC;gBAAS,CAAC;YACT,aAAa,CAAC,KAAK,CAAC,CAAC;QACvB,CAAC;IACH,CAAC,EAAE,CAAC,EAAE,EAAE,KAAK,EAAE,IAAI,CAAC,CAAC,CAAC;IAEtB,MAAM,kBAAkB,GAAG,WAAW,CAAC,GAAG,EAAE;QAC1C,GAAG,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;QAClC,UAAU,CAAC,IAAI,CAAC,uBAAuB,CAAC,CAAC;IAC3C,CAAC,EAAE,CAAC,UAAU,CAAC,CAAC,CAAC;IAEjB,MAAM,WAAW,GAAG,UAAU,IAAI,eAAe,CAAC;IAElD,OAAO,CACL,eAAK,SAAS,EAAC,qCAAqC,aAClD,eAAK,SAAS,EAAC,cAAc,aAC3B,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,WAAW,EACrB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,EACR,gBAAgB,IAAI,CACnB,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,QAAQ,EAAE,WAAW,EACrB,OAAO,EAAE,WAAW,YAEnB,IAAI,KAAK,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,OAAO,GAC7B,CACV,EACD,iBACE,IAAI,EAAC,QAAQ,EACb,SAAS,EAAC,kBAAkB,EAC5B,OAAO,EAAE,kBAAkB,8BAGpB,IACL,EACN,eAAK,SAAS,EAAC,kCAAkC,aAC9C,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,IAAI,CACzC,cAAK,SAAS,EAAC,aAAa,YAE1B,KAAC,KAAK,IAAC,KAAK,EAAE,UAAiB,GAAI,GAC/B,CACP,EACA,IAAI,KAAK,OAAO,IAAI,UAAU,IAAI,IAAI,IAAI,CACzC,cAAK,SAAS,EAAC,aAAa,YAC1B,KAAC,QAAQ,IACP,KAAK,EAAE,UAAU,EACjB,aAAa,EAAE,aAAa,EAC5B,QAAQ,EAAE,QAAQ,EAClB,KAAK,EAAE,UAAU,GACjB,GACE,CACP,EACA,IAAI,KAAK,OAAO,IAAI,IAAI,KAAK,OAAO,IAAI;oBACvC,wDAAwD;oBACxD,KAAC,SAAS,kBACR,KAAK,EAAE,KAAK,EACZ,UAAU,EAAE,UAAU,EACtB,QAAQ,EAAE,QAAQ,IACd,KAAK,EACT,CACH,IACG,IACF,CACP,CAAC;AACJ,CAAC;AAED,eAAe,0BAA0B,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts deleted file mode 100644 index 5c1b2fd45..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts +++ /dev/null @@ -1,4 +0,0 @@ -import type { WidgetMiddlewarePlugin } from './middlewareTypes'; -export declare const GridToolbarPlugin: WidgetMiddlewarePlugin; -export default GridToolbarPlugin; -//# sourceMappingURL=GridToolbarPlugin.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map deleted file mode 100644 index c7248911b..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarPlugin.d.ts","sourceRoot":"","sources":["../src/GridToolbarPlugin.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,sBAAsB,EAAE,MAAM,mBAAmB,CAAC;AAIhE,eAAO,MAAM,iBAAiB,EAAE,sBAY/B,CAAC;AAEF,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js deleted file mode 100644 index 21c81114b..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js +++ /dev/null @@ -1,18 +0,0 @@ -import { PluginType } from '@deephaven/plugin'; -import { GridToolbarMiddleware } from './GridToolbarMiddleware'; -import { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; -export const GridToolbarPlugin = { - name: '@deephaven/js-plugin-grid-toolbar', - type: PluginType.WIDGET_PLUGIN, - supportedTypes: [ - 'Table', - 'TreeTable', - 'HierarchicalTable', - 'PartitionedTable', - ], - component: GridToolbarMiddleware, - panelComponent: GridToolbarPanelMiddleware, - isMiddleware: true, -}; -export default GridToolbarPlugin; -//# sourceMappingURL=GridToolbarPlugin.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map b/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map deleted file mode 100644 index 15c6a18ac..000000000 --- a/plugins/grid-toolbar/src/js/dist/GridToolbarPlugin.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"GridToolbarPlugin.js","sourceRoot":"","sources":["../src/GridToolbarPlugin.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,mBAAmB,CAAC;AAG/C,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAE1E,MAAM,CAAC,MAAM,iBAAiB,GAA2B;IACvD,IAAI,EAAE,mCAAmC;IACzC,IAAI,EAAE,UAAU,CAAC,aAAa;IAC9B,cAAc,EAAE;QACd,OAAO;QACP,WAAW;QACX,mBAAmB;QACnB,kBAAkB;KACnB;IACD,SAAS,EAAE,qBAAqB;IAChC,cAAc,EAAE,0BAA0B;IAC1C,YAAY,EAAE,IAAI;CACnB,CAAC;AAEF,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/bundle/index.js b/plugins/grid-toolbar/src/js/dist/bundle/index.js deleted file mode 100644 index 256fac680..000000000 --- a/plugins/grid-toolbar/src/js/dist/bundle/index.js +++ /dev/null @@ -1,410 +0,0 @@ -"use strict"; -Object.defineProperties(exports, { __esModule: { value: true }, [Symbol.toStringTag]: { value: "Module" } }); -const plugin = require("@deephaven/plugin"); -const require$$1 = require("react"); -const Log = require("@deephaven/log"); -const chart = require("@deephaven/chart"); -const irisGrid = require("@deephaven/iris-grid"); -const jsapiBootstrap = require("@deephaven/jsapi-bootstrap"); -const jsPluginPivot = require("@deephaven/js-plugin-pivot"); -var jsxRuntime = { exports: {} }; -var reactJsxRuntime_production_min = {}; -/* -object-assign -(c) Sindre Sorhus -@license MIT -*/ -var getOwnPropertySymbols = Object.getOwnPropertySymbols; -var hasOwnProperty = Object.prototype.hasOwnProperty; -var propIsEnumerable = Object.prototype.propertyIsEnumerable; -function toObject(val) { - if (val === null || val === void 0) { - throw new TypeError("Object.assign cannot be called with null or undefined"); - } - return Object(val); -} -function shouldUseNative() { - try { - if (!Object.assign) { - return false; - } - var test1 = new String("abc"); - test1[5] = "de"; - if (Object.getOwnPropertyNames(test1)[0] === "5") { - return false; - } - var test2 = {}; - for (var i = 0; i < 10; i++) { - test2["_" + String.fromCharCode(i)] = i; - } - var order2 = Object.getOwnPropertyNames(test2).map(function(n2) { - return test2[n2]; - }); - if (order2.join("") !== "0123456789") { - return false; - } - var test3 = {}; - "abcdefghijklmnopqrst".split("").forEach(function(letter) { - test3[letter] = letter; - }); - if (Object.keys(Object.assign({}, test3)).join("") !== "abcdefghijklmnopqrst") { - return false; - } - return true; - } catch (err) { - return false; - } -} -shouldUseNative() ? Object.assign : function(target, source) { - var from; - var to = toObject(target); - var symbols; - for (var s = 1; s < arguments.length; s++) { - from = Object(arguments[s]); - for (var key in from) { - if (hasOwnProperty.call(from, key)) { - to[key] = from[key]; - } - } - if (getOwnPropertySymbols) { - symbols = getOwnPropertySymbols(from); - for (var i = 0; i < symbols.length; i++) { - if (propIsEnumerable.call(from, symbols[i])) { - to[symbols[i]] = from[symbols[i]]; - } - } - } - } - return to; -}; -/** @license React v17.0.2 - * react-jsx-runtime.production.min.js - * - * Copyright (c) Facebook, Inc. and its affiliates. - * - * This source code is licensed under the MIT license found in the - * LICENSE file in the root directory of this source tree. - */ -var f = require$$1, g = 60103; -reactJsxRuntime_production_min.Fragment = 60107; -if ("function" === typeof Symbol && Symbol.for) { - var h = Symbol.for; - g = h("react.element"); - reactJsxRuntime_production_min.Fragment = h("react.fragment"); -} -var m = f.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner, n = Object.prototype.hasOwnProperty, p = { key: true, ref: true, __self: true, __source: true }; -function q(c, a, k) { - var b, d = {}, e = null, l = null; - void 0 !== k && (e = "" + k); - void 0 !== a.key && (e = "" + a.key); - void 0 !== a.ref && (l = a.ref); - for (b in a) n.call(a, b) && !p.hasOwnProperty(b) && (d[b] = a[b]); - if (c && c.defaultProps) for (b in a = c.defaultProps, a) void 0 === d[b] && (d[b] = a[b]); - return { $$typeof: g, type: c, key: e, ref: l, props: d, _owner: m.current }; -} -reactJsxRuntime_production_min.jsx = q; -reactJsxRuntime_production_min.jsxs = q; -{ - jsxRuntime.exports = reactJsxRuntime_production_min; -} -var jsxRuntimeExports = jsxRuntime.exports; -const log$2 = Log.module("@deephaven/js-plugin-grid-toolbar"); -function GridToolbarMiddleware({ - Component, - ...props -}) { - const handleExport = require$$1.useCallback(() => { - log$2.info("Export clicked"); - }, []); - const handleResetFilters = require$$1.useCallback(() => { - log$2.info("[0] Reset Filters clicked", props, Component); - }, [props, Component]); - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleExport, - children: "Export" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "grid-toolbar-content", children: /* @__PURE__ */ jsxRuntimeExports.jsx(Component, { ...props }) }) - ] }); -} -const log$1 = Log.module("@deephaven/js-plugin-grid-toolbar/usePivotToggle"); -const NUMERIC_TYPES = /* @__PURE__ */ new Set([ - "int", - "long", - "short", - "byte", - "double", - "float", - "java.lang.Integer", - "java.lang.Long", - "java.lang.Short", - "java.lang.Byte", - "java.lang.Double", - "java.lang.Float", - "java.math.BigDecimal", - "java.math.BigInteger" -]); -function usePivotToggle(dh, fetch, isPivotView, setView, metadata) { - const [pivotModel, setPivotModel] = require$$1.useState(null); - const [isBuilding, setIsBuilding] = require$$1.useState(false); - const pspDescriptor = require$$1.useMemo(() => { - if (!jsPluginPivot.isCorePlusDh(dh) || metadata == null) { - return { type: "PivotService", name: "__unavailable__" }; - } - return { - ...metadata, - type: "PivotService", - name: "psp" - }; - }, [dh, metadata]); - const pspFetch = jsapiBootstrap.useObjectFetch(pspDescriptor); - const isAvailable = jsPluginPivot.isCorePlusDh(dh) && pspFetch.status === "ready"; - require$$1.useEffect(() => { - if (pspFetch.status === "error") { - log$1.debug("PivotService (psp) not available on this query"); - } - if (pspFetch.status === "ready") { - log$1.info("PivotService (psp) is available on this query"); - } - }, [pspFetch.status]); - const pivotModelRef = require$$1.useRef(null); - require$$1.useEffect(() => { - pivotModelRef.current = pivotModel; - }, [pivotModel]); - require$$1.useEffect( - () => () => { - var _a; - (_a = pivotModelRef.current) == null ? void 0 : _a.close(); - }, - [] - ); - const handleToggle = require$$1.useCallback(async () => { - if (isPivotView) { - pivotModel == null ? void 0 : pivotModel.close(); - setPivotModel(null); - setView("grid"); - return; - } - if (!jsPluginPivot.isCorePlusDh(dh)) { - log$1.error("CorePlus API not available; cannot create pivot"); - return; - } - if (pspFetch.status !== "ready") { - log$1.error("PivotService (psp) not available"); - return; - } - setIsBuilding(true); - try { - const [table, pspWidget] = await Promise.all([ - fetch(), - pspFetch.fetch() - ]); - if ((table == null ? void 0 : table.columns) == null) { - log$1.warn("Fetched object has no columns; cannot build pivot"); - return; - } - const numericColumns = []; - const nonNumericColumns = []; - table.columns.forEach((col) => { - if (NUMERIC_TYPES.has(col.type)) { - numericColumns.push(col.name); - } else { - nonNumericColumns.push(col.name); - } - }); - if (nonNumericColumns.length === 0) { - log$1.warn("Table has no non-numeric columns for row/column keys"); - return; - } - const rowKeys = nonNumericColumns.slice(0, 1); - const columnKeys = nonNumericColumns.length > 1 ? nonNumericColumns.slice(1, 2) : []; - const aggregations = numericColumns.length > 0 ? { Sum: numericColumns } : { Count: [nonNumericColumns[0]] }; - const config = { - source: table, - rowKeys, - columnKeys, - aggregations - }; - log$1.info("Creating pivot with config:", config); - const corePlusDh = dh; - const pivotService = await corePlusDh.coreplus.pivot.PivotService.getInstance(pspWidget); - log$1.info("PivotService obtained:", pivotService); - const pivotTable = await pivotService.createPivotTable(config); - log$1.info("PivotTable created:", pivotTable); - const model = new jsPluginPivot.IrisGridPivotModel(dh, pivotTable); - setPivotModel(model); - setView("pivot"); - } catch (e) { - log$1.error("Failed to create pivot table", e); - } finally { - setIsBuilding(false); - } - }, [dh, fetch, isPivotView, pspFetch, pivotModel, setView]); - return { - isAvailable, - pivotModel, - isBuilding, - handleToggle - }; -} -const log = Log.module("@deephaven/js-plugin-grid-toolbar"); -const CLEAR_ALL_FILTERS_EVENT = "InputFilterEvent.CLEAR_ALL_FILTERS"; -function GridToolbarPanelMiddleware({ - Component, - fetch, - glEventHub, - metadata, - ...props -}) { - const dh = jsapiBootstrap.useApi(); - const [view, setView] = require$$1.useState("grid"); - const [chartModel, setChartModel] = require$$1.useState(null); - const [isBuilding, setIsBuilding] = require$$1.useState(false); - const { - isAvailable: isPivotAvailable, - pivotModel, - isBuilding: isPivotBuilding, - handleToggle: handlePivot - } = usePivotToggle( - dh, - fetch, - view === "pivot", - setView, - metadata - ); - const mouseHandlers = jsPluginPivot.usePivotMouseHandlers(); - const renderer = jsPluginPivot.usePivotRenderer(); - const pivotTheme = jsPluginPivot.usePivotTheme(); - require$$1.useEffect( - () => () => { - chartModel == null ? void 0 : chartModel.close(); - }, - [chartModel] - ); - const handleChart = require$$1.useCallback(async () => { - if (view === "chart") { - setView("grid"); - return; - } - setIsBuilding(true); - try { - const table = await fetch(); - if ((table == null ? void 0 : table.columns) == null || table.columns.length < 2) { - log.warn("Table has fewer than 2 columns; cannot build chart"); - return; - } - const settings = { - type: "LINE", - series: [table.columns[1].name], - xAxis: table.columns[0].name - }; - const model = await chart.ChartModelFactory.makeModelFromSettings( - // eslint-disable-next-line @typescript-eslint/no-explicit-any - dh, - // eslint-disable-next-line @typescript-eslint/no-explicit-any - settings, - table - ); - setChartModel(model); - setView("chart"); - } catch (e) { - log.error("Failed to build chart model", e); - } finally { - setIsBuilding(false); - } - }, [dh, fetch, view]); - const handleResetFilters = require$$1.useCallback(() => { - log.info("Reset Filters clicked"); - glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub]); - const anyBuilding = isBuilding || isPivotBuilding; - return /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-middleware h-100 w-100", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar", children: [ - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - disabled: anyBuilding, - onClick: handleChart, - children: view === "chart" ? "Grid" : "Chart" - } - ), - isPivotAvailable && /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - disabled: anyBuilding, - onClick: handlePivot, - children: view === "pivot" ? "Grid" : "Pivot" - } - ), - /* @__PURE__ */ jsxRuntimeExports.jsx( - "button", - { - type: "button", - className: "grid-toolbar-btn", - onClick: handleResetFilters, - children: "Reset Filters" - } - ) - ] }), - /* @__PURE__ */ jsxRuntimeExports.jsxs("div", { className: "grid-toolbar-content h-100 w-100", children: [ - view === "chart" && chartModel != null && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx(chart.Chart, { model: chartModel }) }), - view === "pivot" && pivotModel != null && /* @__PURE__ */ jsxRuntimeExports.jsx("div", { className: "h-100 w-100", children: /* @__PURE__ */ jsxRuntimeExports.jsx( - irisGrid.IrisGrid, - { - model: pivotModel, - mouseHandlers, - renderer, - theme: pivotTheme - } - ) }), - view !== "chart" && view !== "pivot" && // eslint-disable-next-line react/jsx-props-no-spreading - /* @__PURE__ */ jsxRuntimeExports.jsx( - Component, - { - fetch, - glEventHub, - metadata, - ...props - } - ) - ] }) - ] }); -} -const GridToolbarPlugin = { - name: "@deephaven/js-plugin-grid-toolbar", - type: plugin.PluginType.WIDGET_PLUGIN, - supportedTypes: [ - "Table", - "TreeTable", - "HierarchicalTable", - "PartitionedTable" - ], - component: GridToolbarMiddleware, - panelComponent: GridToolbarPanelMiddleware, - isMiddleware: true -}; -exports.GridToolbarMiddleware = GridToolbarMiddleware; -exports.GridToolbarPanelMiddleware = GridToolbarPanelMiddleware; -exports.GridToolbarPlugin = GridToolbarPlugin; -exports.default = GridToolbarPlugin; -exports.usePivotToggle = usePivotToggle; diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts b/plugins/grid-toolbar/src/js/dist/index.d.ts deleted file mode 100644 index 460041db5..000000000 --- a/plugins/grid-toolbar/src/js/dist/index.d.ts +++ /dev/null @@ -1,7 +0,0 @@ -import { GridToolbarPlugin } from './GridToolbarPlugin'; -export { GridToolbarMiddleware } from './GridToolbarMiddleware'; -export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; -export { GridToolbarPlugin } from './GridToolbarPlugin'; -export { usePivotToggle } from './usePivotToggle'; -export default GridToolbarPlugin; -//# sourceMappingURL=index.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.d.ts.map b/plugins/grid-toolbar/src/js/dist/index.d.ts.map deleted file mode 100644 index 88543f78b..000000000 --- a/plugins/grid-toolbar/src/js/dist/index.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js b/plugins/grid-toolbar/src/js/dist/index.js deleted file mode 100644 index a6f6784ae..000000000 --- a/plugins/grid-toolbar/src/js/dist/index.js +++ /dev/null @@ -1,7 +0,0 @@ -import { GridToolbarPlugin } from './GridToolbarPlugin'; -export { GridToolbarMiddleware } from './GridToolbarMiddleware'; -export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; -export { GridToolbarPlugin } from './GridToolbarPlugin'; -export { usePivotToggle } from './usePivotToggle'; -export default GridToolbarPlugin; -//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/index.js.map b/plugins/grid-toolbar/src/js/dist/index.js.map deleted file mode 100644 index ef7210b22..000000000 --- a/plugins/grid-toolbar/src/js/dist/index.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AAExD,OAAO,EAAE,qBAAqB,EAAE,MAAM,yBAAyB,CAAC;AAChE,OAAO,EAAE,0BAA0B,EAAE,MAAM,8BAA8B,CAAC;AAC1E,OAAO,EAAE,iBAAiB,EAAE,MAAM,qBAAqB,CAAC;AACxD,OAAO,EAAE,cAAc,EAAE,MAAM,kBAAkB,CAAC;AAElD,eAAe,iBAAiB,CAAC"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts deleted file mode 100644 index 700d7c752..000000000 --- a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts +++ /dev/null @@ -1,31 +0,0 @@ -/** - * Local type definitions for middleware plugin types. - * - * TODO: Delete this file after deephaven/web-client-ui#2660 is merged and - * @deephaven/plugin is updated with WidgetMiddlewarePlugin types. - * Replace imports with: import { type WidgetMiddlewarePlugin, type WidgetMiddlewareComponentProps } from '@deephaven/plugin'; - */ -import type { WidgetComponentProps, WidgetPanelProps, WidgetPlugin } from '@deephaven/plugin'; -/** - * Props passed to middleware components that wrap a base widget. - */ -export interface WidgetMiddlewareComponentProps extends WidgetComponentProps { - /** The next component in the middleware chain. */ - Component: React.ComponentType>; -} -/** - * Props passed to middleware panel components that wrap a base panel. - */ -export interface WidgetMiddlewarePanelProps extends WidgetPanelProps { - /** The next panel component in the middleware chain. */ - Component: React.ComponentType>; -} -/** - * A middleware plugin that wraps and enhances another widget plugin. - */ -export interface WidgetMiddlewarePlugin extends Omit, 'component' | 'panelComponent'> { - isMiddleware: true; - component: React.ComponentType>; - panelComponent?: React.ComponentType>; -} -//# sourceMappingURL=middlewareTypes.d.ts.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map b/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map deleted file mode 100644 index 86ee32da7..000000000 --- a/plugins/grid-toolbar/src/js/dist/middlewareTypes.d.ts.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middlewareTypes.d.ts","sourceRoot":"","sources":["../src/middlewareTypes.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AACH,OAAO,KAAK,EACV,oBAAoB,EACpB,gBAAgB,EAChB,YAAY,EACb,MAAM,mBAAmB,CAAC;AAE3B;;GAEG;AACH,MAAM,WAAW,8BAA8B,CAAC,CAAC,GAAG,OAAO,CACzD,SAAQ,oBAAoB,CAAC,CAAC,CAAC;IAC/B,kDAAkD;IAClD,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,oBAAoB,CAAC,CAAC,CAAC,CAAC,CAAC;CACzD;AAED;;GAEG;AACH,MAAM,WAAW,0BAA0B,CAAC,CAAC,GAAG,OAAO,CACrD,SAAQ,gBAAgB,CAAC,CAAC,CAAC;IAC3B,wDAAwD;IACxD,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,gBAAgB,CAAC,CAAC,CAAC,CAAC,CAAC;CACrD;AAED;;GAEG;AACH,MAAM,WAAW,sBAAsB,CAAC,CAAC,GAAG,OAAO,CACjD,SAAQ,IAAI,CAAC,YAAY,CAAC,CAAC,CAAC,EAAE,WAAW,GAAG,gBAAgB,CAAC;IAC7D,YAAY,EAAE,IAAI,CAAC;IACnB,SAAS,EAAE,KAAK,CAAC,aAAa,CAAC,8BAA8B,CAAC,CAAC,CAAC,CAAC,CAAC;IAClE,cAAc,CAAC,EAAE,KAAK,CAAC,aAAa,CAAC,0BAA0B,CAAC,CAAC,CAAC,CAAC,CAAC;CACrE"} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js deleted file mode 100644 index 24e1d14ae..000000000 --- a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js +++ /dev/null @@ -1,2 +0,0 @@ -export {}; -//# sourceMappingURL=middlewareTypes.js.map \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map b/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map deleted file mode 100644 index a54550595..000000000 --- a/plugins/grid-toolbar/src/js/dist/middlewareTypes.js.map +++ /dev/null @@ -1 +0,0 @@ -{"version":3,"file":"middlewareTypes.js","sourceRoot":"","sources":["../src/middlewareTypes.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index 4372fecfb..1eb97ca68 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -11,6 +11,8 @@ import Log from '@deephaven/log'; // TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; import { usePivotToggle } from './usePivotToggle'; +import type { ColumnInfo, PivotConfig } from './usePivotToggle'; +import { PivotBuilderDialog } from './PivotBuilderDialog'; const log = Log.module('@deephaven/js-plugin-grid-toolbar'); @@ -28,16 +30,22 @@ export function GridToolbarPanelMiddleware({ const [view, setView] = useState<'grid' | 'chart' | 'pivot'>('grid'); const [chartModel, setChartModel] = useState(null); const [isBuilding, setIsBuilding] = useState(false); + const [showPivotBuilder, setShowPivotBuilder] = useState(false); + const [pivotColumns, setPivotColumns] = useState(null); + const [lastPivotConfig, setLastPivotConfig] = useState( + null + ); const { isAvailable: isPivotAvailable, pivotModel, isBuilding: isPivotBuilding, - handleToggle: handlePivot, + fetchColumns, + buildPivot, + closePivot, } = usePivotToggle( dh, fetch, - view === 'pivot', setView as (v: 'grid' | 'pivot') => void, metadata ); @@ -93,6 +101,35 @@ export function GridToolbarPanelMiddleware({ glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); }, [glEventHub]); + const handlePivotClick = useCallback(async () => { + // Always open the builder dialog, even when already in pivot view, + // so the user can change settings on the existing pivot. + try { + const columns = await fetchColumns(); + setPivotColumns(columns); + setShowPivotBuilder(true); + } catch (e) { + log.error('Failed to fetch columns for pivot builder', e); + } + }, [fetchColumns]); + + const handlePivotApply = useCallback( + async (config: PivotConfig) => { + setShowPivotBuilder(false); + setPivotColumns(null); + setLastPivotConfig(config); + // Close existing pivot model before building a new one + closePivot(); + await buildPivot(config); + }, + [buildPivot, closePivot] + ); + + const handlePivotCancel = useCallback(() => { + setShowPivotBuilder(false); + setPivotColumns(null); + }, []); + const anyBuilding = isBuilding || isPivotBuilding; return ( @@ -106,16 +143,14 @@ export function GridToolbarPanelMiddleware({ > {view === 'chart' ? 'Grid' : 'Chart'} - {isPivotAvailable && ( - - )} +
+ {showPivotBuilder && pivotColumns != null && ( + + )} ); } diff --git a/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.css b/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.css new file mode 100644 index 000000000..68dec6dae --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.css @@ -0,0 +1,176 @@ +.pivot-builder-overlay { + position: absolute; + inset: 0; + background: rgba(0, 0, 0, 0.5); + display: flex; + align-items: center; + justify-content: center; + z-index: 1000; +} + +.pivot-builder-dialog { + background: var(--dh-color-bg, #1a1a2e); + color: var(--dh-color-text, #c8c8c8); + border: 1px solid var(--dh-color-border, #444); + border-radius: 6px; + padding: 16px; + min-width: 500px; + max-width: 700px; + max-height: 80vh; + overflow-y: auto; + box-shadow: 0 4px 24px rgba(0, 0, 0, 0.4); +} + +.pivot-builder-title { + margin: 0 0 12px; + font-size: 16px; +} + +.pivot-builder-layout { + display: flex; + gap: 12px; +} + +.pivot-builder-section { + flex: 1; +} + +.pivot-builder-section h4 { + margin: 0 0 6px; + font-size: 12px; + text-transform: uppercase; + letter-spacing: 0.05em; + color: var(--dh-color-text-muted, #999); +} + +.pivot-builder-list { + border: 1px solid var(--dh-color-border, #444); + border-radius: 4px; + min-height: 80px; + max-height: 200px; + overflow-y: auto; + padding: 4px; +} + +.pivot-builder-item { + display: flex; + align-items: center; + justify-content: space-between; + padding: 3px 6px; + border-radius: 3px; + font-size: 12px; +} + +.pivot-builder-item:hover { + background: var(--dh-color-highlight, rgba(255, 255, 255, 0.05)); +} + +.pivot-builder-col-name { + display: flex; + align-items: center; + gap: 6px; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; +} + +.pivot-builder-col-type { + font-size: 10px; + color: var(--dh-color-text-muted, #888); +} + +.pivot-builder-item-actions { + display: flex; + gap: 2px; + flex-shrink: 0; +} + +.pivot-builder-add-btn, +.pivot-builder-remove-btn { + background: transparent; + border: 1px solid var(--dh-color-border, #555); + color: var(--dh-color-text, #c8c8c8); + border-radius: 3px; + cursor: pointer; + font-size: 10px; + padding: 1px 4px; + line-height: 1.3; +} + +.pivot-builder-add-btn:hover, +.pivot-builder-remove-btn:hover { + background: var(--dh-color-highlight, rgba(255, 255, 255, 0.1)); +} + +.pivot-builder-remove-btn { + font-size: 14px; + padding: 0 4px; + line-height: 1; +} + +.pivot-builder-empty { + font-size: 11px; + color: var(--dh-color-text-muted, #777); + padding: 8px; + text-align: center; + font-style: italic; +} + +.pivot-builder-targets { + flex: 1; + display: flex; + flex-direction: column; + gap: 8px; +} + +.pivot-builder-agg { + margin-top: 6px; + font-size: 12px; +} + +.pivot-builder-agg select { + background: var(--dh-color-bg, #1a1a2e); + color: var(--dh-color-text, #c8c8c8); + border: 1px solid var(--dh-color-border, #555); + border-radius: 3px; + padding: 2px 4px; + font-size: 12px; +} + +.pivot-builder-actions { + display: flex; + justify-content: flex-end; + gap: 8px; + margin-top: 16px; + padding-top: 12px; + border-top: 1px solid var(--dh-color-border, #444); +} + +.pivot-builder-btn { + background: transparent; + color: var(--dh-color-text, #c8c8c8); + border: 1px solid var(--dh-color-border, #555); + border-radius: 4px; + padding: 6px 16px; + cursor: pointer; + font-size: 13px; +} + +.pivot-builder-btn:hover { + background: var(--dh-color-highlight, rgba(255, 255, 255, 0.08)); +} + +.pivot-builder-btn-primary { + background: var(--dh-color-accent, #4c6ef5); + border-color: var(--dh-color-accent, #4c6ef5); + color: #fff; +} + +.pivot-builder-btn-primary:hover { + opacity: 0.9; +} + +.pivot-builder-btn-primary:disabled { + opacity: 0.4; + cursor: not-allowed; +} diff --git a/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.tsx b/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.tsx new file mode 100644 index 000000000..2dba6ed0b --- /dev/null +++ b/plugins/grid-toolbar/src/js/src/PivotBuilderDialog.tsx @@ -0,0 +1,411 @@ +import { + type CSSProperties, + useCallback, + useEffect, + useMemo, + useState, +} from 'react'; +import type { PivotConfig, ColumnInfo } from './usePivotToggle'; + +const AGGREGATION_TYPES = [ + 'Sum', + 'Count', + 'Avg', + 'Min', + 'Max', + 'First', + 'Last', +] as const; + +// Inline styles so the dialog works in dynamically-loaded plugin bundles +// where a separate CSS file would not be injected automatically. +const styles = { + overlay: { + position: 'fixed', + inset: 0, + background: 'rgba(0,0,0,0.5)', + display: 'flex', + alignItems: 'center', + justifyContent: 'center', + zIndex: 1000, + } satisfies CSSProperties, + dialog: { + background: 'var(--dh-color-bg, #1a1a2e)', + color: 'var(--dh-color-text, #c8c8c8)', + border: '1px solid var(--dh-color-border, #444)', + borderRadius: 6, + padding: 16, + minWidth: 500, + maxWidth: 700, + maxHeight: '80vh', + overflowY: 'auto', + boxShadow: '0 4px 24px rgba(0,0,0,0.4)', + } satisfies CSSProperties, + title: { margin: '0 0 12px', fontSize: 16 } satisfies CSSProperties, + layout: { display: 'flex', gap: 12 } satisfies CSSProperties, + section: { flex: 1 } satisfies CSSProperties, + sectionHeader: { + margin: '0 0 6px', + fontSize: 12, + textTransform: 'uppercase', + letterSpacing: '0.05em', + color: 'var(--dh-color-text-muted, #999)', + } satisfies CSSProperties, + list: { + border: '1px solid var(--dh-color-border, #444)', + borderRadius: 4, + minHeight: 80, + maxHeight: 200, + overflowY: 'auto', + padding: 4, + } satisfies CSSProperties, + item: { + display: 'flex', + alignItems: 'center', + justifyContent: 'space-between', + padding: '3px 6px', + borderRadius: 3, + fontSize: 12, + } satisfies CSSProperties, + colName: { + display: 'flex', + alignItems: 'center', + gap: 6, + overflow: 'hidden', + textOverflow: 'ellipsis', + whiteSpace: 'nowrap', + } satisfies CSSProperties, + colType: { + fontSize: 10, + color: 'var(--dh-color-text-muted, #888)', + } satisfies CSSProperties, + itemActions: { + display: 'flex', + gap: 2, + flexShrink: 0, + } satisfies CSSProperties, + smallBtn: { + background: 'transparent', + border: '1px solid var(--dh-color-border, #555)', + color: 'var(--dh-color-text, #c8c8c8)', + borderRadius: 3, + cursor: 'pointer', + fontSize: 10, + padding: '1px 4px', + lineHeight: 1.3, + } satisfies CSSProperties, + removeBtn: { + background: 'transparent', + border: '1px solid var(--dh-color-border, #555)', + color: 'var(--dh-color-text, #c8c8c8)', + borderRadius: 3, + cursor: 'pointer', + fontSize: 14, + padding: '0 4px', + lineHeight: 1, + } satisfies CSSProperties, + empty: { + fontSize: 11, + color: 'var(--dh-color-text-muted, #777)', + padding: 8, + textAlign: 'center', + fontStyle: 'italic', + } satisfies CSSProperties, + targets: { + flex: 1, + display: 'flex', + flexDirection: 'column', + gap: 8, + } satisfies CSSProperties, + agg: { marginTop: 6, fontSize: 12 } satisfies CSSProperties, + aggSelect: { + background: 'var(--dh-color-bg, #1a1a2e)', + color: 'var(--dh-color-text, #c8c8c8)', + border: '1px solid var(--dh-color-border, #555)', + borderRadius: 3, + padding: '2px 4px', + fontSize: 12, + } satisfies CSSProperties, + actions: { + display: 'flex', + justifyContent: 'flex-end', + gap: 8, + marginTop: 16, + paddingTop: 12, + borderTop: '1px solid var(--dh-color-border, #444)', + } satisfies CSSProperties, + btn: { + background: 'transparent', + color: 'var(--dh-color-text, #c8c8c8)', + border: '1px solid var(--dh-color-border, #555)', + borderRadius: 4, + padding: '6px 16px', + cursor: 'pointer', + fontSize: 13, + } satisfies CSSProperties, + btnPrimary: { + background: 'var(--dh-color-accent, #4c6ef5)', + color: '#fff', + border: '1px solid var(--dh-color-accent, #4c6ef5)', + borderRadius: 4, + padding: '6px 16px', + cursor: 'pointer', + fontSize: 13, + } satisfies CSSProperties, +}; + +interface PivotBuilderDialogProps { + columns: ColumnInfo[]; + initialConfig: PivotConfig | null; + onApply: (config: PivotConfig) => void; + onCancel: () => void; +} + +export function PivotBuilderDialog({ + columns, + initialConfig, + onApply, + onCancel, +}: PivotBuilderDialogProps): JSX.Element { + const [rowKeys, setRowKeys] = useState([]); + const [columnKeys, setColumnKeys] = useState([]); + const [valueColumns, setValueColumns] = useState([]); + const [aggregationType, setAggregationType] = + useState<(typeof AGGREGATION_TYPES)[number]>('Sum'); + + // Restore previous config if available, otherwise auto-populate from column types + useEffect(() => { + if (initialConfig != null) { + const columnNames = new Set(columns.map(c => c.name)); + // Filter to only columns that still exist in the table + setRowKeys(initialConfig.rowKeys.filter(n => columnNames.has(n))); + setColumnKeys(initialConfig.columnKeys.filter(n => columnNames.has(n))); + const aggType = Object.keys(initialConfig.aggregations)[0] as + | (typeof AGGREGATION_TYPES)[number] + | undefined; + const vals = aggType != null ? initialConfig.aggregations[aggType] : []; + setValueColumns((vals ?? []).filter(n => columnNames.has(n))); + if (aggType != null) { + setAggregationType(aggType); + } + return; + } + const numeric = columns.filter(c => c.isNumeric).map(c => c.name); + const nonNumeric = columns + .filter(c => c.isNumeric === false) + .map(c => c.name); + setRowKeys(nonNumeric.slice(0, 1)); + setColumnKeys(nonNumeric.length > 1 ? nonNumeric.slice(1, 2) : []); + setValueColumns(numeric); + if (numeric.length === 0) { + setAggregationType('Count'); + } + }, [columns, initialConfig]); + + const availableColumns = useMemo( + () => + columns.filter( + c => + !rowKeys.includes(c.name) && + !columnKeys.includes(c.name) && + !valueColumns.includes(c.name) + ), + [columns, rowKeys, columnKeys, valueColumns] + ); + + const addTo = useCallback((target: 'row' | 'col' | 'value', name: string) => { + if (target === 'row') setRowKeys(prev => [...prev, name]); + else if (target === 'col') setColumnKeys(prev => [...prev, name]); + else setValueColumns(prev => [...prev, name]); + }, []); + + const removeFrom = useCallback( + (target: 'row' | 'col' | 'value', name: string) => { + if (target === 'row') setRowKeys(prev => prev.filter(n => n !== name)); + else if (target === 'col') { + setColumnKeys(prev => prev.filter(n => n !== name)); + } else setValueColumns(prev => prev.filter(n => n !== name)); + }, + [] + ); + + const canApply = rowKeys.length > 0 && valueColumns.length > 0; + + const handleApply = useCallback(() => { + onApply({ + rowKeys, + columnKeys, + aggregations: { [aggregationType]: valueColumns }, + }); + }, [onApply, rowKeys, columnKeys, valueColumns, aggregationType]); + + return ( + // eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions +
+ {/* eslint-disable-next-line jsx-a11y/click-events-have-key-events, jsx-a11y/no-static-element-interactions */} +
e.stopPropagation()}> +

Build Pivot Table

+ +
+ {/* Available columns */} +
+

Available Columns

+
+ {availableColumns.length === 0 && ( +
All columns assigned
+ )} + {availableColumns.map(col => ( +
+ + {col.name} + {col.type} + + + + + + +
+ ))} +
+
+ + {/* Target buckets */} +
+
+

Row Keys

+
+ {rowKeys.length === 0 && ( +
At least one required
+ )} + {rowKeys.map(name => ( +
+ {name} + +
+ ))} +
+
+ +
+

Column Keys

+
+ {columnKeys.length === 0 && ( +
None
+ )} + {columnKeys.map(name => ( +
+ {name} + +
+ ))} +
+
+ +
+

Values

+
+ {valueColumns.length === 0 && ( +
At least one required
+ )} + {valueColumns.map(name => ( +
+ {name} + +
+ ))} +
+
+ +
+
+
+
+ +
+ + +
+
+
+ ); +} + +export default PivotBuilderDialog; diff --git a/plugins/grid-toolbar/src/js/src/index.ts b/plugins/grid-toolbar/src/js/src/index.ts index 98b7307d8..521bda0b1 100644 --- a/plugins/grid-toolbar/src/js/src/index.ts +++ b/plugins/grid-toolbar/src/js/src/index.ts @@ -3,6 +3,8 @@ import { GridToolbarPlugin } from './GridToolbarPlugin'; export { GridToolbarMiddleware } from './GridToolbarMiddleware'; export { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; export { GridToolbarPlugin } from './GridToolbarPlugin'; +export { PivotBuilderDialog } from './PivotBuilderDialog'; export { usePivotToggle } from './usePivotToggle'; +export type { ColumnInfo, PivotConfig } from './usePivotToggle'; export default GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/src/usePivotToggle.ts b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts index 9ace1da56..2d200f399 100644 --- a/plugins/grid-toolbar/src/js/src/usePivotToggle.ts +++ b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts @@ -8,7 +8,7 @@ import Log from '@deephaven/log'; const log = Log.module('@deephaven/js-plugin-grid-toolbar/usePivotToggle'); -const NUMERIC_TYPES = new Set([ +export const NUMERIC_TYPES = new Set([ 'int', 'long', 'short', @@ -25,6 +25,20 @@ const NUMERIC_TYPES = new Set([ 'java.math.BigInteger', ]); +/** Column metadata exposed to the pivot builder dialog */ +export interface ColumnInfo { + name: string; + type: string; + isNumeric: boolean; +} + +/** User-configured pivot settings from the builder dialog */ +export interface PivotConfig { + rowKeys: string[]; + columnKeys: string[]; + aggregations: Record; +} + export interface PivotToggleResult { /** Whether CorePlus pivot API is available */ isAvailable: boolean; @@ -32,8 +46,12 @@ export interface PivotToggleResult { pivotModel: IrisGridModel | null; /** Whether pivot creation is in progress */ isBuilding: boolean; - /** Toggle between grid and pivot views */ - handleToggle: () => void; + /** Fetch column metadata from the source table */ + fetchColumns: () => Promise; + /** Build a pivot table with the given config */ + buildPivot: (config: PivotConfig) => Promise; + /** Close the current pivot view and return to grid */ + closePivot: () => void; } /** @@ -43,7 +61,6 @@ export interface PivotToggleResult { export function usePivotToggle( dh: typeof DhType | typeof CorePlusDhType, fetch: () => Promise, - isPivotView: boolean, setView: (view: 'grid' | 'pivot') => void, metadata?: DhType.ide.VariableDescriptor ): PivotToggleResult { @@ -93,102 +110,92 @@ export function usePivotToggle( [] ); - const handleToggle = useCallback(async () => { - if (isPivotView) { - // Switch back to grid - pivotModel?.close(); - setPivotModel(null); - setView('grid'); - return; - } - - if (!isCorePlusDh(dh)) { - log.error('CorePlus API not available; cannot create pivot'); - return; - } - - if (pspFetch.status !== 'ready') { - log.error('PivotService (psp) not available'); - return; + const fetchColumns = useCallback(async (): Promise => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const table = (await fetch()) as any; + if (table?.columns == null) { + log.warn('Fetched object has no columns'); + return []; } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return table.columns.map((col: any) => ({ + name: col.name as string, + type: col.type as string, + isNumeric: NUMERIC_TYPES.has(col.type), + })); + }, [fetch]); + + const buildPivot = useCallback( + async (config: PivotConfig) => { + if (!isCorePlusDh(dh)) { + log.error('CorePlus API not available; cannot create pivot'); + return; + } - setIsBuilding(true); - try { - // Fetch the source table and the PivotService widget in parallel - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const [table, pspWidget] = (await Promise.all([ - fetch(), - pspFetch.fetch(), - ])) as [any, any]; - - if (table?.columns == null) { - log.warn('Fetched object has no columns; cannot build pivot'); + if (pspFetch.status !== 'ready') { + log.error('PivotService (psp) not available'); return; } - // Auto-detect column categories - const numericColumns: string[] = []; - const nonNumericColumns: string[] = []; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - table.columns.forEach((col: any) => { - if (NUMERIC_TYPES.has(col.type)) { - numericColumns.push(col.name); - } else { - nonNumericColumns.push(col.name); + setIsBuilding(true); + try { + // Fetch the source table and the PivotService widget in parallel + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const [table, pspWidget] = (await Promise.all([ + fetch(), + pspFetch.fetch(), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + ])) as [any, any]; + + if (table?.columns == null) { + log.warn('Fetched object has no columns; cannot build pivot'); + return; } - }); - if (nonNumericColumns.length === 0) { - log.warn('Table has no non-numeric columns for row/column keys'); - return; + const pivotConfig = { + source: table, + rowKeys: config.rowKeys, + columnKeys: config.columnKeys, + aggregations: config.aggregations, + }; + + log.info('Creating pivot with config:', pivotConfig); + + // Get PivotService from the psp widget, then create PivotTable + const corePlusDh = dh as typeof CorePlusDhType; + const pivotService = + await corePlusDh.coreplus.pivot.PivotService.getInstance(pspWidget); + log.info('PivotService obtained:', pivotService); + const pivotTable = await pivotService.createPivotTable(pivotConfig); + log.info('PivotTable created:', pivotTable); + + // Create the IrisGridPivotModel + const model = new IrisGridPivotModel(dh, pivotTable); + + setPivotModel(model); + setView('pivot'); + } catch (e) { + log.error('Failed to create pivot table', e); + } finally { + setIsBuilding(false); } + }, + [dh, fetch, pspFetch, setView] + ); - // Split non-numeric columns: first goes to rows, rest to columns - const rowKeys = nonNumericColumns.slice(0, 1); - const columnKeys = - nonNumericColumns.length > 1 ? nonNumericColumns.slice(1, 2) : []; - - // Use all numeric columns as values with Sum aggregation - // If no numeric columns, use Count on the first non-numeric column - const aggregations: Record = - numericColumns.length > 0 - ? { Sum: numericColumns } - : { Count: [nonNumericColumns[0]] }; - - const config = { - source: table, - rowKeys, - columnKeys, - aggregations, - }; - - log.info('Creating pivot with config:', config); - - // Get PivotService from the psp widget, then create PivotTable - const corePlusDh = dh as typeof CorePlusDhType; - const pivotService = - await corePlusDh.coreplus.pivot.PivotService.getInstance(pspWidget); - log.info('PivotService obtained:', pivotService); - const pivotTable = await pivotService.createPivotTable(config); - log.info('PivotTable created:', pivotTable); - - // Create the IrisGridPivotModel - const model = new IrisGridPivotModel(dh, pivotTable); - - setPivotModel(model); - setView('pivot'); - } catch (e) { - log.error('Failed to create pivot table', e); - } finally { - setIsBuilding(false); - } - }, [dh, fetch, isPivotView, pspFetch, pivotModel, setView]); + const closePivot = useCallback(() => { + pivotModel?.close(); + setPivotModel(null); + setView('grid'); + }, [pivotModel, setView]); return { isAvailable, pivotModel, isBuilding, - handleToggle, + fetchColumns, + buildPivot, + closePivot, }; } diff --git a/plugins/grid-toolbar/tox.ini b/plugins/grid-toolbar/tox.ini deleted file mode 100644 index ab2ea314a..000000000 --- a/plugins/grid-toolbar/tox.ini +++ /dev/null @@ -1,24 +0,0 @@ -[tox] -isolated_build = True - -[testenv] -deps = - deephaven-server -commands = - python -m unittest {posargs} -basepython = python3.9 - -[testenv:py3.9] -basepython = python3.9 - -[testenv:py3.10] -basepython = python3.10 - -[testenv:py3.11] -basepython = python3.11 - -[testenv:py3.12] -basepython = python3.12 - -[testenv:py3.13] -basepython = python3.13 diff --git a/plugins/manifest.json b/plugins/manifest.json index d13fe5588..74be350ff 100644 --- a/plugins/manifest.json +++ b/plugins/manifest.json @@ -39,12 +39,14 @@ { "name": "pivot", "version": "0.0.0", - "main": "src/js/dist/index.js" + "main": "src/js/dist/index.js", + "package": "@deephaven/js-plugin-pivot" }, { "name": "grid-toolbar", "version": "0.0.0", - "main": "src/js/dist/bundle/index.js" + "main": "src/js/dist/bundle/index.js", + "dependencies": ["@deephaven/js-plugin-pivot"] } ] } From d83400fd009764241547551366fe73768bbaff7e Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Fri, 24 Apr 2026 11:17:33 -0600 Subject: [PATCH 10/11] Pivot builder toolbar POC --- .../src/js/src/GridToolbarPanelMiddleware.tsx | 220 +++++++++++++----- .../grid-toolbar/src/js/src/pivotPlugin.d.ts | 2 + .../src/js/src/pluginAugmentations.d.ts | 27 +++ .../grid-toolbar/src/js/src/usePivotToggle.ts | 47 +++- 4 files changed, 231 insertions(+), 65 deletions(-) create mode 100644 plugins/grid-toolbar/src/js/src/pluginAugmentations.d.ts diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx index 1eb97ca68..15b425fbc 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPanelMiddleware.tsx @@ -1,13 +1,16 @@ -import { useCallback, useEffect, useState } from 'react'; +import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import { Chart, type ChartModel, ChartModelFactory } from '@deephaven/chart'; +import { ActionGroup, Item, LoadingOverlay } from '@deephaven/components'; import { IrisGrid } from '@deephaven/iris-grid'; import { useApi } from '@deephaven/jsapi-bootstrap'; import { + usePivotMetricCalculatorFactory, usePivotMouseHandlers, usePivotRenderer, usePivotTheme, } from '@deephaven/js-plugin-pivot'; import Log from '@deephaven/log'; +import { usePersistentState } from '@deephaven/plugin'; // TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges import type { WidgetMiddlewarePanelProps } from './middlewareTypes'; import { usePivotToggle } from './usePivotToggle'; @@ -16,8 +19,18 @@ import { PivotBuilderDialog } from './PivotBuilderDialog'; const log = Log.module('@deephaven/js-plugin-grid-toolbar'); -// Matches InputFilterEvent.CLEAR_ALL_FILTERS from @deephaven/dashboard-core-plugins -const CLEAR_ALL_FILTERS_EVENT = 'InputFilterEvent.CLEAR_ALL_FILTERS'; +interface GridToolbarState { + view: 'grid' | 'chart' | 'pivot'; + pivotConfig: PivotConfig | null; +} + +const PERSISTENT_STATE_CONFIG = { + type: 'GridToolbar', + version: 1, + deleteOnUnmount: false, +}; + +const DEFAULT_STATE: GridToolbarState = { view: 'grid', pivotConfig: null }; export function GridToolbarPanelMiddleware({ Component, @@ -27,13 +40,28 @@ export function GridToolbarPanelMiddleware({ ...props }: WidgetMiddlewarePanelProps): JSX.Element { const dh = useApi(); - const [view, setView] = useState<'grid' | 'chart' | 'pivot'>('grid'); + const [persistedState, setPersistedState] = + usePersistentState( + DEFAULT_STATE, + PERSISTENT_STATE_CONFIG + ); + const [view, setView] = useState<'grid' | 'chart' | 'pivot'>( + persistedState.view + ); const [chartModel, setChartModel] = useState(null); const [isBuilding, setIsBuilding] = useState(false); + const [isQueryReady, setIsQueryReady] = useState(false); const [showPivotBuilder, setShowPivotBuilder] = useState(false); const [pivotColumns, setPivotColumns] = useState(null); - const [lastPivotConfig, setLastPivotConfig] = useState( - null + const lastPivotConfig = persistedState.pivotConfig; + const setLastPivotConfig = useCallback( + (config: PivotConfig | null) => { + setPersistedState((prev: GridToolbarState) => ({ + ...prev, + pivotConfig: config, + })); + }, + [setPersistedState] ); const { @@ -53,19 +81,34 @@ export function GridToolbarPanelMiddleware({ const mouseHandlers = usePivotMouseHandlers(); const renderer = usePivotRenderer(); const pivotTheme = usePivotTheme(); + const getPivotMetricCalculator = usePivotMetricCalculatorFactory(); - useEffect( - () => () => { - chartModel?.close(); - }, - [chartModel] - ); + // Probe the query on mount to determine if it's running + useEffect(() => { + let cancelled = false; + fetch() + .then(() => { + if (!cancelled) setIsQueryReady(true); + }) + .catch(() => { + if (!cancelled) setIsQueryReady(false); + }); + return () => { + cancelled = true; + }; + }, [fetch]); - const handleChart = useCallback(async () => { - if (view === 'chart') { - setView('grid'); - return; - } + // Persist the current view mode whenever it changes + useEffect(() => { + setPersistedState((prev: GridToolbarState) => + prev.view !== view ? { ...prev, view } : prev + ); + }, [view, setPersistedState]); + + // On mount, restore pivot view if persisted state has a pivot config + const hasRestoredRef = useRef(false); + + const buildChart = useCallback(async () => { setIsBuilding(true); try { // fetch is typed as () => Promise; for grid widgets it returns dh.Table @@ -94,16 +137,58 @@ export function GridToolbarPanelMiddleware({ } finally { setIsBuilding(false); } - }, [dh, fetch, view]); + }, [dh, fetch]); + + useEffect(() => { + if (hasRestoredRef.current) { + return; + } + if (persistedState.view === 'pivot') { + if (persistedState.pivotConfig == null || !isPivotAvailable) { + return; + } + hasRestoredRef.current = true; + buildPivot(persistedState.pivotConfig).catch(e => { + log.error('Failed to restore pivot from persisted state', e); + }); + } else if (persistedState.view === 'chart') { + hasRestoredRef.current = true; + buildChart().catch(e => { + log.error('Failed to restore chart from persisted state', e); + }); + } else { + hasRestoredRef.current = true; + } + // Only run on mount / when pivot becomes available + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [isPivotAvailable]); + + useEffect( + () => () => { + chartModel?.close(); + }, + [chartModel] + ); - const handleResetFilters = useCallback(() => { - log.info('Reset Filters clicked'); - glEventHub.emit(CLEAR_ALL_FILTERS_EVENT); - }, [glEventHub]); + const handleGrid = useCallback(() => { + setView('grid'); + }, []); + + const handleChart = useCallback(async () => { + if (view === 'chart') { + return; + } + await buildChart(); + }, [view, buildChart]); const handlePivotClick = useCallback(async () => { - // Always open the builder dialog, even when already in pivot view, - // so the user can change settings on the existing pivot. + // If already in pivot view, open the dialog to change settings. + // If switching to pivot with existing config, reuse it directly. + // If no config yet (first time), open the dialog. + if (view !== 'pivot' && lastPivotConfig != null) { + await buildPivot(lastPivotConfig); + return; + } try { const columns = await fetchColumns(); setPivotColumns(columns); @@ -111,18 +196,51 @@ export function GridToolbarPanelMiddleware({ } catch (e) { log.error('Failed to fetch columns for pivot builder', e); } - }, [fetchColumns]); + }, [view, lastPivotConfig, fetchColumns, buildPivot]); + + const handleViewAction = useCallback( + (key: React.Key) => { + switch (key) { + case 'grid': + handleGrid(); + break; + case 'chart': + handleChart(); + break; + case 'pivot': + handlePivotClick(); + break; + default: + break; + } + }, + [handleGrid, handleChart, handlePivotClick] + ); + + const anyBuilding = isBuilding || isPivotBuilding; + + const disabledKeys = useMemo(() => { + if (!isQueryReady) { + return ['grid', 'chart', 'pivot']; + } + const keys: string[] = []; + if (anyBuilding) { + keys.push('chart', 'pivot'); + } + if (!isPivotAvailable) { + keys.push('pivot'); + } + return keys; + }, [isQueryReady, anyBuilding, isPivotAvailable]); const handlePivotApply = useCallback( async (config: PivotConfig) => { setShowPivotBuilder(false); setPivotColumns(null); setLastPivotConfig(config); - // Close existing pivot model before building a new one - closePivot(); await buildPivot(config); }, - [buildPivot, closePivot] + [buildPivot, setLastPivotConfig] ); const handlePivotCancel = useCallback(() => { @@ -130,36 +248,25 @@ export function GridToolbarPanelMiddleware({ setPivotColumns(null); }, []); - const anyBuilding = isBuilding || isPivotBuilding; - return (
-
- - - + Grid + Chart + Pivot +
-
+
{view === 'chart' && chartModel != null && (
{/* eslint-disable-next-line @typescript-eslint/no-explicit-any */} @@ -173,6 +280,10 @@ export function GridToolbarPanelMiddleware({ mouseHandlers={mouseHandlers} renderer={renderer} theme={pivotTheme} + // getMetricCalculator exists on IrisGrid at runtime but is not + // in the type declarations for the current @deephaven/iris-grid version + // eslint-disable-next-line @typescript-eslint/no-explicit-any, react/jsx-props-no-spreading + {...({ getMetricCalculator: getPivotMetricCalculator } as any)} />
)} @@ -185,6 +296,7 @@ export function GridToolbarPanelMiddleware({ {...props} /> )} +
{showPivotBuilder && pivotColumns != null && ( ( + initialState: S | (() => S), + config: { + type: string; + version: number; + migrations?: Array<{ + from: number; + migrate: (state: unknown) => unknown; + }>; + deleteOnUnmount?: boolean; + } + ): [state: S, setState: Dispatch>]; +} diff --git a/plugins/grid-toolbar/src/js/src/usePivotToggle.ts b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts index 2d200f399..7d2689cc1 100644 --- a/plugins/grid-toolbar/src/js/src/usePivotToggle.ts +++ b/plugins/grid-toolbar/src/js/src/usePivotToggle.ts @@ -66,11 +66,13 @@ export function usePivotToggle( ): PivotToggleResult { const [pivotModel, setPivotModel] = useState(null); const [isBuilding, setIsBuilding] = useState(false); + // Whether we've probed the PivotService and confirmed it exists + const [isPivotServiceConfirmed, setIsPivotServiceConfirmed] = useState(false); // Build a descriptor for the PivotService variable on the same query. - // The convention is that PivotServicePlugin is exported as 'psp'. - // We copy querySerial from the table's metadata so the ObjectFetchManager - // routes to the same query/worker. + // The PivotService may be exported under any name (commonly 'psp'), + // so we use a well-known name for the initial subscription and then + // probe eagerly to confirm the service actually exists. const pspDescriptor = useMemo(() => { if (!isCorePlusDh(dh) || metadata == null) { return { type: 'PivotService', name: '__unavailable__' }; @@ -84,16 +86,37 @@ export function usePivotToggle( const pspFetch = useObjectFetch(pspDescriptor); - const isAvailable = isCorePlusDh(dh) && pspFetch.status === 'ready'; - + // Eagerly probe the PivotService when the fetch becomes ready. + // The ObjectFetchManager only checks if the query is running, not whether + // the specific variable exists. We do a real fetch to confirm availability. useEffect(() => { - if (pspFetch.status === 'error') { - log.debug('PivotService (psp) not available on this query'); - } - if (pspFetch.status === 'ready') { - log.info('PivotService (psp) is available on this query'); + if (pspFetch.status !== 'ready') { + setIsPivotServiceConfirmed(false); + return; } - }, [pspFetch.status]); + let cancelled = false; + pspFetch + .fetch() + .then(() => { + if (!cancelled) { + log.info('PivotService confirmed available on this query'); + setIsPivotServiceConfirmed(true); + } + }) + .catch(() => { + if (!cancelled) { + log.debug( + 'PivotService not found on this query (fetch probe failed)' + ); + setIsPivotServiceConfirmed(false); + } + }); + return () => { + cancelled = true; + }; + }, [pspFetch]); + + const isAvailable = isCorePlusDh(dh) && isPivotServiceConfirmed; // Track the current model ref for cleanup const pivotModelRef = useRef(null); @@ -172,6 +195,8 @@ export function usePivotToggle( // Create the IrisGridPivotModel const model = new IrisGridPivotModel(dh, pivotTable); + // Close the previous model before replacing it + pivotModelRef.current?.close(); setPivotModel(model); setView('pivot'); } catch (e) { From 99592815a4a0f92366a9269b8ad4eb33fc6ed36a Mon Sep 17 00:00:00 2001 From: Vlad Babich Date: Fri, 24 Apr 2026 11:52:22 -0600 Subject: [PATCH 11/11] Use plugin type instead of middleware flag --- .../src/js/src/GridToolbarPlugin.ts | 11 ++++---- .../src/js/src/middlewareTypes.ts | 26 ++++++++++++------- 2 files changed, 23 insertions(+), 14 deletions(-) diff --git a/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts b/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts index 49145d6f7..314c1b5ca 100644 --- a/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts +++ b/plugins/grid-toolbar/src/js/src/GridToolbarPlugin.ts @@ -1,12 +1,14 @@ -import { PluginType } from '@deephaven/plugin'; -// TODO: Replace with import from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges -import type { WidgetMiddlewarePlugin } from './middlewareTypes'; +// TODO: Replace with imports from '@deephaven/plugin' after deephaven/web-client-ui#2660 merges +import { + MIDDLEWARE_PLUGIN_TYPE, + type WidgetMiddlewarePlugin, +} from './middlewareTypes'; import { GridToolbarMiddleware } from './GridToolbarMiddleware'; import { GridToolbarPanelMiddleware } from './GridToolbarPanelMiddleware'; export const GridToolbarPlugin: WidgetMiddlewarePlugin = { name: '@deephaven/js-plugin-grid-toolbar', - type: PluginType.WIDGET_PLUGIN, + type: MIDDLEWARE_PLUGIN_TYPE, supportedTypes: [ 'Table', 'TreeTable', @@ -15,7 +17,6 @@ export const GridToolbarPlugin: WidgetMiddlewarePlugin = { ], component: GridToolbarMiddleware, panelComponent: GridToolbarPanelMiddleware, - isMiddleware: true, }; export default GridToolbarPlugin; diff --git a/plugins/grid-toolbar/src/js/src/middlewareTypes.ts b/plugins/grid-toolbar/src/js/src/middlewareTypes.ts index 342f8cee7..0245ea753 100644 --- a/plugins/grid-toolbar/src/js/src/middlewareTypes.ts +++ b/plugins/grid-toolbar/src/js/src/middlewareTypes.ts @@ -3,13 +3,15 @@ * * TODO: Delete this file after deephaven/web-client-ui#2660 is merged and * @deephaven/plugin is updated with WidgetMiddlewarePlugin types. - * Replace imports with: import { type WidgetMiddlewarePlugin, type WidgetMiddlewareComponentProps } from '@deephaven/plugin'; + * Replace imports with: import { type WidgetMiddlewarePlugin, type WidgetMiddlewareComponentProps, PluginType } from '@deephaven/plugin'; */ -import type { - WidgetComponentProps, - WidgetPanelProps, - WidgetPlugin, -} from '@deephaven/plugin'; +import type { WidgetComponentProps, WidgetPanelProps } from '@deephaven/plugin'; + +/** + * Discriminator value for middleware plugins. Matches + * `PluginType.MIDDLEWARE_PLUGIN` in the upcoming @deephaven/plugin release. + */ +export const MIDDLEWARE_PLUGIN_TYPE = 'MiddlewarePlugin' as const; /** * Props passed to middleware components that wrap a base widget. @@ -31,10 +33,16 @@ export interface WidgetMiddlewarePanelProps /** * A middleware plugin that wraps and enhances another widget plugin. + * + * Note: does not `extend Plugin` because the published @deephaven/plugin's + * `Plugin.type` is a strict union that doesn't yet include the new + * `MIDDLEWARE_PLUGIN` discriminator. After web-client-ui#2660 merges this + * file is deleted and consumers import from @deephaven/plugin directly. */ -export interface WidgetMiddlewarePlugin - extends Omit, 'component' | 'panelComponent'> { - isMiddleware: true; +export interface WidgetMiddlewarePlugin { + name: string; + type: typeof MIDDLEWARE_PLUGIN_TYPE; + supportedTypes: string | string[]; component: React.ComponentType>; panelComponent?: React.ComponentType>; }