diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js b/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js
new file mode 100644
index 0000000000000000000000000000000000000000..609225370119769e38724eab2560e1f61c39a570
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js
@@ -0,0 +1,194 @@
+"use strict";
+var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ var desc = Object.getOwnPropertyDescriptor(m, k);
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
+ desc = { enumerable: true, get: function() { return m[k]; } };
+ }
+ Object.defineProperty(o, k2, desc);
+}) : (function(o, m, k, k2) {
+ if (k2 === undefined) k2 = k;
+ o[k2] = m[k];
+}));
+var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
+}) : function(o, v) {
+ o["default"] = v;
+});
+var __importStar = (this && this.__importStar) || (function () {
+ var ownKeys = function(o) {
+ ownKeys = Object.getOwnPropertyNames || function (o) {
+ var ar = [];
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
+ return ar;
+ };
+ return ownKeys(o);
+ };
+ return function (mod) {
+ if (mod && mod.__esModule) return mod;
+ var result = {};
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
+ __setModuleDefault(result, mod);
+ return result;
+ };
+})();
+Object.defineProperty(exports, "__esModule", { value: true });
+exports.visitorKeys = void 0;
+const eslintVisitorKeys = __importStar(require("eslint-visitor-keys"));
+/*
+ ********************************** IMPORTANT NOTE ********************************
+ * *
+ * The key arrays should be sorted in the order in which you would want to visit *
+ * the child keys. *
+ * *
+ * DO NOT SORT THEM ALPHABETICALLY! *
+ * *
+ * They should be sorted in the order that they appear in the source code. *
+ * For example: *
+ * *
+ * class Foo extends Bar { prop: 1 } *
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClassDeclaration *
+ * ^^^ id ^^^ superClass *
+ * ^^^^^^^^^^^ body *
+ * *
+ * It would be incorrect to provide the visitor keys ['body', 'id', 'superClass'] *
+ * because the body comes AFTER everything else in the source code. *
+ * Instead the correct ordering would be ['id', 'superClass', 'body']. *
+ * *
+ **********************************************************************************
+ */
+const SharedVisitorKeys = (() => {
+ const FunctionType = ['typeParameters', 'params', 'returnType'];
+ const AnonymousFunction = [...FunctionType, 'body'];
+ const AbstractPropertyDefinition = [
+ 'decorators',
+ 'key',
+ 'typeAnnotation',
+ ];
+ return {
+ AbstractPropertyDefinition: ['decorators', 'key', 'typeAnnotation'],
+ AnonymousFunction,
+ AsExpression: ['expression', 'typeAnnotation'],
+ ClassDeclaration: [
+ 'decorators',
+ 'id',
+ 'typeParameters',
+ 'superClass',
+ 'superTypeArguments',
+ 'implements',
+ 'body',
+ ],
+ Function: ['id', ...AnonymousFunction],
+ FunctionType,
+ PropertyDefinition: [...AbstractPropertyDefinition, 'value'],
+ };
+})();
+const additionalKeys = {
+ AccessorProperty: SharedVisitorKeys.PropertyDefinition,
+ ArrayPattern: ['decorators', 'elements', 'typeAnnotation'],
+ ArrowFunctionExpression: SharedVisitorKeys.AnonymousFunction,
+ AssignmentPattern: ['decorators', 'left', 'right', 'typeAnnotation'],
+ CallExpression: ['callee', 'typeArguments', 'arguments'],
+ ClassDeclaration: SharedVisitorKeys.ClassDeclaration,
+ ClassExpression: SharedVisitorKeys.ClassDeclaration,
+ Decorator: ['expression'],
+ ExportAllDeclaration: ['exported', 'source', 'attributes'],
+ ExportNamedDeclaration: ['declaration', 'specifiers', 'source', 'attributes'],
+ FunctionDeclaration: SharedVisitorKeys.Function,
+ FunctionExpression: SharedVisitorKeys.Function,
+ Identifier: ['decorators', 'typeAnnotation'],
+ ImportAttribute: ['key', 'value'],
+ ImportDeclaration: ['specifiers', 'source', 'attributes'],
+ ImportExpression: ['source', 'options'],
+ JSXClosingFragment: [],
+ JSXOpeningElement: ['name', 'typeArguments', 'attributes'],
+ JSXOpeningFragment: [],
+ JSXSpreadChild: ['expression'],
+ MethodDefinition: ['decorators', 'key', 'value'],
+ NewExpression: ['callee', 'typeArguments', 'arguments'],
+ ObjectPattern: ['decorators', 'properties', 'typeAnnotation'],
+ PropertyDefinition: SharedVisitorKeys.PropertyDefinition,
+ RestElement: ['decorators', 'argument', 'typeAnnotation'],
+ StaticBlock: ['body'],
+ TaggedTemplateExpression: ['tag', 'typeArguments', 'quasi'],
+ TSAbstractAccessorProperty: SharedVisitorKeys.AbstractPropertyDefinition,
+ TSAbstractKeyword: [],
+ TSAbstractMethodDefinition: ['key', 'value'],
+ TSAbstractPropertyDefinition: SharedVisitorKeys.AbstractPropertyDefinition,
+ TSAnyKeyword: [],
+ TSArrayType: ['elementType'],
+ TSAsExpression: SharedVisitorKeys.AsExpression,
+ TSAsyncKeyword: [],
+ TSBigIntKeyword: [],
+ TSBooleanKeyword: [],
+ TSCallSignatureDeclaration: SharedVisitorKeys.FunctionType,
+ TSClassImplements: ['expression', 'typeArguments'],
+ TSConditionalType: ['checkType', 'extendsType', 'trueType', 'falseType'],
+ TSConstructorType: SharedVisitorKeys.FunctionType,
+ TSConstructSignatureDeclaration: SharedVisitorKeys.FunctionType,
+ TSDeclareFunction: SharedVisitorKeys.Function,
+ TSDeclareKeyword: [],
+ TSEmptyBodyFunctionExpression: ['id', ...SharedVisitorKeys.FunctionType],
+ TSEnumBody: ['members'],
+ TSEnumDeclaration: ['id', 'body'],
+ TSEnumMember: ['id', 'initializer'],
+ TSExportAssignment: ['expression'],
+ TSExportKeyword: [],
+ TSExternalModuleReference: ['expression'],
+ TSFunctionType: SharedVisitorKeys.FunctionType,
+ TSImportEqualsDeclaration: ['id', 'moduleReference'],
+ TSImportType: ['source', 'options', 'qualifier', 'typeArguments'],
+ TSIndexedAccessType: ['objectType', 'indexType'],
+ TSIndexSignature: ['parameters', 'typeAnnotation'],
+ TSInferType: ['typeParameter'],
+ TSInstantiationExpression: ['expression', 'typeArguments'],
+ TSInterfaceBody: ['body'],
+ TSInterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'],
+ TSInterfaceHeritage: ['expression', 'typeArguments'],
+ TSIntersectionType: ['types'],
+ TSIntrinsicKeyword: [],
+ TSLiteralType: ['literal'],
+ TSMappedType: ['key', 'constraint', 'nameType', 'typeAnnotation'],
+ TSMethodSignature: ['key', 'typeParameters', 'params', 'returnType'],
+ TSModuleBlock: ['body'],
+ TSModuleDeclaration: ['id', 'body'],
+ TSNamedTupleMember: ['label', 'elementType'],
+ TSNamespaceExportDeclaration: ['id'],
+ TSNeverKeyword: [],
+ TSNonNullExpression: ['expression'],
+ TSNullKeyword: [],
+ TSNumberKeyword: [],
+ TSObjectKeyword: [],
+ TSOptionalType: ['typeAnnotation'],
+ TSParameterProperty: ['decorators', 'parameter'],
+ TSPrivateKeyword: [],
+ TSPropertySignature: ['key', 'typeAnnotation'],
+ TSProtectedKeyword: [],
+ TSPublicKeyword: [],
+ TSQualifiedName: ['left', 'right'],
+ TSReadonlyKeyword: [],
+ TSRestType: ['typeAnnotation'],
+ TSSatisfiesExpression: SharedVisitorKeys.AsExpression,
+ TSStaticKeyword: [],
+ TSStringKeyword: [],
+ TSSymbolKeyword: [],
+ TSTemplateLiteralType: ['quasis', 'types'],
+ TSThisType: [],
+ TSTupleType: ['elementTypes'],
+ TSTypeAliasDeclaration: ['id', 'typeParameters', 'typeAnnotation'],
+ TSTypeAnnotation: ['typeAnnotation'],
+ TSTypeAssertion: ['typeAnnotation', 'expression'],
+ TSTypeLiteral: ['members'],
+ TSTypeOperator: ['typeAnnotation'],
+ TSTypeParameter: ['name', 'constraint', 'default'],
+ TSTypeParameterDeclaration: ['params'],
+ TSTypeParameterInstantiation: ['params'],
+ TSTypePredicate: ['parameterName', 'typeAnnotation'],
+ TSTypeQuery: ['exprName', 'typeArguments'],
+ TSTypeReference: ['typeName', 'typeArguments'],
+ TSUndefinedKeyword: [],
+ TSUnionType: ['types'],
+ TSUnknownKeyword: [],
+ TSVoidKeyword: [],
+};
+exports.visitorKeys = eslintVisitorKeys.unionWith(additionalKeys);
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..17a25538d9bd634bc079642d35d7a6422a0d850d
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Liability. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "{}"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright contributors
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..94894e2e10dce80ee1eb53459b297b449e4b2ea0
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md
@@ -0,0 +1,123 @@
+# eslint-visitor-keys
+
+[](https://www.npmjs.com/package/eslint-visitor-keys)
+[](http://www.npmtrends.com/eslint-visitor-keys)
+[](https://github.com/eslint/js/actions)
+
+Constants and utilities about visitor keys to traverse AST.
+
+## 💿 Installation
+
+Use [npm] to install.
+
+```bash
+$ npm install eslint-visitor-keys
+```
+
+### Requirements
+
+- [Node.js] `^20.19.0`, `^22.13.0`, or `>=24`
+
+## 📖 Usage
+
+To use in an ESM file:
+
+```js
+import * as evk from "eslint-visitor-keys";
+```
+
+To use in a CommonJS file:
+
+```js
+const evk = require("eslint-visitor-keys");
+```
+
+### evk.KEYS
+
+> type: `{ [type: string]: string[] | undefined }`
+
+Visitor keys. This keys are frozen.
+
+This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
+
+For example:
+
+```
+console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
+```
+
+### evk.getKeys(node)
+
+> type: `(node: object) => string[]`
+
+Get the visitor keys of a given AST node.
+
+This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
+
+This will be used to traverse unknown nodes.
+
+For example:
+
+```js
+const node = {
+ type: "AssignmentExpression",
+ left: { type: "Identifier", name: "foo" },
+ right: { type: "Literal", value: 0 },
+};
+console.log(evk.getKeys(node)); // → ["type", "left", "right"]
+```
+
+### evk.unionWith(additionalKeys)
+
+> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
+
+Make the union set with `evk.KEYS` and the given keys.
+
+- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
+- It removes duplicated keys as keeping the first one.
+
+For example:
+
+```js
+console.log(
+ evk.unionWith({
+ MethodDefinition: ["decorators"],
+ }),
+); // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
+```
+
+## 📰 Change log
+
+See [GitHub releases](https://github.com/eslint/js/releases).
+
+## 🍻 Contributing
+
+Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
+
+### Development commands
+
+- `npm test` runs tests and measures code coverage.
+- `npm run lint` checks source codes with ESLint.
+- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
+
+[npm]: https://www.npmjs.com/
+[Node.js]: https://nodejs.org/
+[ESTree]: https://github.com/estree/estree
+
+
+
+
+## Sponsors
+
+The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
+to get your logo on our READMEs and [website](https://eslint.org/sponsors).
+
+
Platinum Sponsors
+
Gold Sponsors
+
Silver Sponsors
+
Bronze Sponsors
+
+
Technology Sponsors
+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
+
+
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs
new file mode 100644
index 0000000000000000000000000000000000000000..8f48952b679bf61ac7d91351fb36597c400b7805
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs
@@ -0,0 +1,187 @@
+'use strict';
+
+/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
+*/
+/**
+ * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys
+ */
+/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */
+
+/**
+ * @type {VisitorKeys}
+ */
+const KEYS = {
+ ArrayExpression: ["elements"],
+ ArrayPattern: ["elements"],
+ ArrowFunctionExpression: ["params", "body"],
+ AssignmentExpression: ["left", "right"],
+ AssignmentPattern: ["left", "right"],
+ AwaitExpression: ["argument"],
+ BinaryExpression: ["left", "right"],
+ BlockStatement: ["body"],
+ BreakStatement: ["label"],
+ CallExpression: ["callee", "arguments"],
+ CatchClause: ["param", "body"],
+ ChainExpression: ["expression"],
+ ClassBody: ["body"],
+ ClassDeclaration: ["id", "superClass", "body"],
+ ClassExpression: ["id", "superClass", "body"],
+ ConditionalExpression: ["test", "consequent", "alternate"],
+ ContinueStatement: ["label"],
+ DebuggerStatement: [],
+ DoWhileStatement: ["body", "test"],
+ EmptyStatement: [],
+ ExperimentalRestProperty: ["argument"],
+ ExperimentalSpreadProperty: ["argument"],
+ ExportAllDeclaration: ["exported", "source", "attributes"],
+ ExportDefaultDeclaration: ["declaration"],
+ ExportNamedDeclaration: [
+ "declaration",
+ "specifiers",
+ "source",
+ "attributes",
+ ],
+ ExportSpecifier: ["local", "exported"],
+ ExpressionStatement: ["expression"],
+ ForInStatement: ["left", "right", "body"],
+ ForOfStatement: ["left", "right", "body"],
+ ForStatement: ["init", "test", "update", "body"],
+ FunctionDeclaration: ["id", "params", "body"],
+ FunctionExpression: ["id", "params", "body"],
+ Identifier: [],
+ IfStatement: ["test", "consequent", "alternate"],
+ ImportAttribute: ["key", "value"],
+ ImportDeclaration: ["specifiers", "source", "attributes"],
+ ImportDefaultSpecifier: ["local"],
+ ImportExpression: ["source", "options"],
+ ImportNamespaceSpecifier: ["local"],
+ ImportSpecifier: ["imported", "local"],
+ JSXAttribute: ["name", "value"],
+ JSXClosingElement: ["name"],
+ JSXClosingFragment: [],
+ JSXElement: ["openingElement", "children", "closingElement"],
+ JSXEmptyExpression: [],
+ JSXExpressionContainer: ["expression"],
+ JSXFragment: ["openingFragment", "children", "closingFragment"],
+ JSXIdentifier: [],
+ JSXMemberExpression: ["object", "property"],
+ JSXNamespacedName: ["namespace", "name"],
+ JSXOpeningElement: ["name", "attributes"],
+ JSXOpeningFragment: [],
+ JSXSpreadAttribute: ["argument"],
+ JSXSpreadChild: ["expression"],
+ JSXText: [],
+ LabeledStatement: ["label", "body"],
+ Literal: [],
+ LogicalExpression: ["left", "right"],
+ MemberExpression: ["object", "property"],
+ MetaProperty: ["meta", "property"],
+ MethodDefinition: ["key", "value"],
+ NewExpression: ["callee", "arguments"],
+ ObjectExpression: ["properties"],
+ ObjectPattern: ["properties"],
+ PrivateIdentifier: [],
+ Program: ["body"],
+ Property: ["key", "value"],
+ PropertyDefinition: ["key", "value"],
+ RestElement: ["argument"],
+ ReturnStatement: ["argument"],
+ SequenceExpression: ["expressions"],
+ SpreadElement: ["argument"],
+ StaticBlock: ["body"],
+ Super: [],
+ SwitchCase: ["test", "consequent"],
+ SwitchStatement: ["discriminant", "cases"],
+ TaggedTemplateExpression: ["tag", "quasi"],
+ TemplateElement: [],
+ TemplateLiteral: ["quasis", "expressions"],
+ ThisExpression: [],
+ ThrowStatement: ["argument"],
+ TryStatement: ["block", "handler", "finalizer"],
+ UnaryExpression: ["argument"],
+ UpdateExpression: ["argument"],
+ VariableDeclaration: ["declarations"],
+ VariableDeclarator: ["id", "init"],
+ WhileStatement: ["test", "body"],
+ WithStatement: ["object", "body"],
+ YieldExpression: ["argument"],
+};
+
+// Types.
+const NODE_TYPES = Object.keys(KEYS);
+
+// Freeze the keys.
+for (const type of NODE_TYPES) {
+ Object.freeze(KEYS[type]);
+}
+Object.freeze(KEYS);
+
+/**
+ * @author Toru Nagashima
+ * See LICENSE file in root directory for full license.
+ */
+
+/**
+ * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
+ */
+
+// List to ignore keys.
+const KEY_BLACKLIST = new Set([
+ "parent",
+ "leadingComments",
+ "trailingComments",
+]);
+
+/**
+ * Check whether a given key should be used or not.
+ * @param {string} key The key to check.
+ * @returns {boolean} `true` if the key should be used.
+ */
+function filterKey(key) {
+ return !KEY_BLACKLIST.has(key) && key[0] !== "_";
+}
+
+/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
+*/
+/**
+ * Get visitor keys of a given node.
+ * @param {Object} node The AST node to get keys.
+ * @returns {readonly string[]} Visitor keys of the node.
+ */
+function getKeys(node) {
+ return Object.keys(node).filter(filterKey);
+}
+/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */
+
+/**
+ * Make the union set with `KEYS` and given keys.
+ * @param {VisitorKeys} additionalKeys The additional keys.
+ * @returns {VisitorKeys} The union set.
+ */
+function unionWith(additionalKeys) {
+ const retv =
+ /** @type {{ [type: string]: ReadonlyArray }} */
+ (Object.assign({}, KEYS));
+
+ for (const type of Object.keys(additionalKeys)) {
+ if (Object.hasOwn(retv, type)) {
+ const keys = new Set(additionalKeys[type]);
+
+ for (const key of retv[type]) {
+ keys.add(key);
+ }
+
+ retv[type] = Object.freeze(Array.from(keys));
+ } else {
+ retv[type] = Object.freeze(Array.from(additionalKeys[type]));
+ }
+ }
+
+ return Object.freeze(retv);
+}
+
+exports.KEYS = KEYS;
+exports.getKeys = getKeys;
+exports.unionWith = unionWith;
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts
new file mode 100644
index 0000000000000000000000000000000000000000..34253c96c3dd5035555c8ce96acd1b801f393935
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts
@@ -0,0 +1,28 @@
+type VisitorKeys$1 = {
+ readonly [type: string]: ReadonlyArray;
+};
+/**
+ * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys
+ */
+/**
+ * @type {VisitorKeys}
+ */
+declare const KEYS: VisitorKeys$1;
+
+/**
+ * Get visitor keys of a given node.
+ * @param {Object} node The AST node to get keys.
+ * @returns {readonly string[]} Visitor keys of the node.
+ */
+declare function getKeys(node: Object): readonly string[];
+/**
+ * Make the union set with `KEYS` and given keys.
+ * @param {VisitorKeys} additionalKeys The additional keys.
+ * @returns {VisitorKeys} The union set.
+ */
+declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
+
+type VisitorKeys = VisitorKeys$1;
+
+export { KEYS, getKeys, unionWith };
+export type { VisitorKeys };
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts
new file mode 100644
index 0000000000000000000000000000000000000000..e65b7da338d3095bc7073a4f2e94c39b9c67223f
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts
@@ -0,0 +1,16 @@
+/**
+ * Get visitor keys of a given node.
+ * @param {Object} node The AST node to get keys.
+ * @returns {readonly string[]} Visitor keys of the node.
+ */
+export function getKeys(node: Object): readonly string[];
+/**
+ * Make the union set with `KEYS` and given keys.
+ * @param {VisitorKeys} additionalKeys The additional keys.
+ * @returns {VisitorKeys} The union set.
+ */
+export function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
+export { KEYS };
+export type VisitorKeys = import("./visitor-keys.js").VisitorKeys;
+import KEYS from "./visitor-keys.js";
+//# sourceMappingURL=index.d.ts.map
\ No newline at end of file
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts
new file mode 100644
index 0000000000000000000000000000000000000000..2d7ada2f1d5d0cdd0253e1f0e04be4407f91f20f
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts
@@ -0,0 +1,12 @@
+export default KEYS;
+export type VisitorKeys = {
+ readonly [type: string]: ReadonlyArray;
+};
+/**
+ * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys
+ */
+/**
+ * @type {VisitorKeys}
+ */
+declare const KEYS: VisitorKeys;
+//# sourceMappingURL=visitor-keys.d.ts.map
\ No newline at end of file
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..6e5269cf634aee25664de5b5559b723e27472675
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js
@@ -0,0 +1,67 @@
+/**
+ * @author Toru Nagashima
+ * See LICENSE file in root directory for full license.
+ */
+import KEYS from "./visitor-keys.js";
+
+/**
+ * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
+ */
+
+// List to ignore keys.
+const KEY_BLACKLIST = new Set([
+ "parent",
+ "leadingComments",
+ "trailingComments",
+]);
+
+/**
+ * Check whether a given key should be used or not.
+ * @param {string} key The key to check.
+ * @returns {boolean} `true` if the key should be used.
+ */
+function filterKey(key) {
+ return !KEY_BLACKLIST.has(key) && key[0] !== "_";
+}
+
+/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
+*/
+/**
+ * Get visitor keys of a given node.
+ * @param {Object} node The AST node to get keys.
+ * @returns {readonly string[]} Visitor keys of the node.
+ */
+export function getKeys(node) {
+ return Object.keys(node).filter(filterKey);
+}
+/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */
+
+/**
+ * Make the union set with `KEYS` and given keys.
+ * @param {VisitorKeys} additionalKeys The additional keys.
+ * @returns {VisitorKeys} The union set.
+ */
+export function unionWith(additionalKeys) {
+ const retv =
+ /** @type {{ [type: string]: ReadonlyArray }} */
+ (Object.assign({}, KEYS));
+
+ for (const type of Object.keys(additionalKeys)) {
+ if (Object.hasOwn(retv, type)) {
+ const keys = new Set(additionalKeys[type]);
+
+ for (const key of retv[type]) {
+ keys.add(key);
+ }
+
+ retv[type] = Object.freeze(Array.from(keys));
+ } else {
+ retv[type] = Object.freeze(Array.from(additionalKeys[type]));
+ }
+ }
+
+ return Object.freeze(retv);
+}
+
+export { KEYS };
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js
new file mode 100644
index 0000000000000000000000000000000000000000..cddbcd9c0d94262b31e80b1c8c5d2967c12f522a
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js
@@ -0,0 +1,118 @@
+/* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
+*/
+/**
+ * @typedef {{ readonly [type: string]: ReadonlyArray }} VisitorKeys
+ */
+/* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */
+
+/**
+ * @type {VisitorKeys}
+ */
+const KEYS = {
+ ArrayExpression: ["elements"],
+ ArrayPattern: ["elements"],
+ ArrowFunctionExpression: ["params", "body"],
+ AssignmentExpression: ["left", "right"],
+ AssignmentPattern: ["left", "right"],
+ AwaitExpression: ["argument"],
+ BinaryExpression: ["left", "right"],
+ BlockStatement: ["body"],
+ BreakStatement: ["label"],
+ CallExpression: ["callee", "arguments"],
+ CatchClause: ["param", "body"],
+ ChainExpression: ["expression"],
+ ClassBody: ["body"],
+ ClassDeclaration: ["id", "superClass", "body"],
+ ClassExpression: ["id", "superClass", "body"],
+ ConditionalExpression: ["test", "consequent", "alternate"],
+ ContinueStatement: ["label"],
+ DebuggerStatement: [],
+ DoWhileStatement: ["body", "test"],
+ EmptyStatement: [],
+ ExperimentalRestProperty: ["argument"],
+ ExperimentalSpreadProperty: ["argument"],
+ ExportAllDeclaration: ["exported", "source", "attributes"],
+ ExportDefaultDeclaration: ["declaration"],
+ ExportNamedDeclaration: [
+ "declaration",
+ "specifiers",
+ "source",
+ "attributes",
+ ],
+ ExportSpecifier: ["local", "exported"],
+ ExpressionStatement: ["expression"],
+ ForInStatement: ["left", "right", "body"],
+ ForOfStatement: ["left", "right", "body"],
+ ForStatement: ["init", "test", "update", "body"],
+ FunctionDeclaration: ["id", "params", "body"],
+ FunctionExpression: ["id", "params", "body"],
+ Identifier: [],
+ IfStatement: ["test", "consequent", "alternate"],
+ ImportAttribute: ["key", "value"],
+ ImportDeclaration: ["specifiers", "source", "attributes"],
+ ImportDefaultSpecifier: ["local"],
+ ImportExpression: ["source", "options"],
+ ImportNamespaceSpecifier: ["local"],
+ ImportSpecifier: ["imported", "local"],
+ JSXAttribute: ["name", "value"],
+ JSXClosingElement: ["name"],
+ JSXClosingFragment: [],
+ JSXElement: ["openingElement", "children", "closingElement"],
+ JSXEmptyExpression: [],
+ JSXExpressionContainer: ["expression"],
+ JSXFragment: ["openingFragment", "children", "closingFragment"],
+ JSXIdentifier: [],
+ JSXMemberExpression: ["object", "property"],
+ JSXNamespacedName: ["namespace", "name"],
+ JSXOpeningElement: ["name", "attributes"],
+ JSXOpeningFragment: [],
+ JSXSpreadAttribute: ["argument"],
+ JSXSpreadChild: ["expression"],
+ JSXText: [],
+ LabeledStatement: ["label", "body"],
+ Literal: [],
+ LogicalExpression: ["left", "right"],
+ MemberExpression: ["object", "property"],
+ MetaProperty: ["meta", "property"],
+ MethodDefinition: ["key", "value"],
+ NewExpression: ["callee", "arguments"],
+ ObjectExpression: ["properties"],
+ ObjectPattern: ["properties"],
+ PrivateIdentifier: [],
+ Program: ["body"],
+ Property: ["key", "value"],
+ PropertyDefinition: ["key", "value"],
+ RestElement: ["argument"],
+ ReturnStatement: ["argument"],
+ SequenceExpression: ["expressions"],
+ SpreadElement: ["argument"],
+ StaticBlock: ["body"],
+ Super: [],
+ SwitchCase: ["test", "consequent"],
+ SwitchStatement: ["discriminant", "cases"],
+ TaggedTemplateExpression: ["tag", "quasi"],
+ TemplateElement: [],
+ TemplateLiteral: ["quasis", "expressions"],
+ ThisExpression: [],
+ ThrowStatement: ["argument"],
+ TryStatement: ["block", "handler", "finalizer"],
+ UnaryExpression: ["argument"],
+ UpdateExpression: ["argument"],
+ VariableDeclaration: ["declarations"],
+ VariableDeclarator: ["id", "init"],
+ WhileStatement: ["test", "body"],
+ WithStatement: ["object", "body"],
+ YieldExpression: ["argument"],
+};
+
+// Types.
+const NODE_TYPES = Object.keys(KEYS);
+
+// Freeze the keys.
+for (const type of NODE_TYPES) {
+ Object.freeze(KEYS[type]);
+}
+Object.freeze(KEYS);
+
+export default KEYS;
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..d61f90619c2d85199adcafbc2f4d293fe6142384
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json
@@ -0,0 +1,57 @@
+{
+ "name": "eslint-visitor-keys",
+ "version": "5.0.1",
+ "description": "Constants and utilities about visitor keys to traverse AST.",
+ "type": "module",
+ "main": "dist/eslint-visitor-keys.cjs",
+ "types": "./dist/index.d.ts",
+ "exports": {
+ ".": [
+ {
+ "import": "./lib/index.js",
+ "require": "./dist/eslint-visitor-keys.cjs"
+ },
+ "./dist/eslint-visitor-keys.cjs"
+ ],
+ "./package.json": "./package.json"
+ },
+ "files": [
+ "dist/index.d.ts",
+ "dist/visitor-keys.d.ts",
+ "dist/eslint-visitor-keys.cjs",
+ "dist/eslint-visitor-keys.d.cts",
+ "lib"
+ ],
+ "engines": {
+ "node": "^20.19.0 || ^22.13.0 || >=24"
+ },
+ "devDependencies": {
+ "rollup-plugin-dts": "^6.2.3",
+ "tsd": "^0.33.0"
+ },
+ "scripts": {
+ "build": "npm run build:cjs && npm run build:types",
+ "build:cjs": "rollup -c",
+ "build:debug": "npm run build:cjs -- -m && npm run build:types",
+ "build:types": "tsc -v && tsc",
+ "test": "mocha \"tests/**/*.test.cjs\" && mocha \"tests/**/*.test.js\" && npm run test:types",
+ "test:coverage": "c8 npm test",
+ "test:types": "tsd"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/eslint/js.git",
+ "directory": "packages/eslint-visitor-keys"
+ },
+ "funding": "https://opencollective.com/eslint",
+ "keywords": [
+ "eslint"
+ ],
+ "author": "Toru Nagashima (https://github.com/mysticatea)",
+ "license": "Apache-2.0",
+ "bugs": {
+ "url": "https://github.com/eslint/js/issues"
+ },
+ "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md",
+ "sideEffects": false
+}
diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/package.json b/tools/ui/node_modules/@typescript-eslint/visitor-keys/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..c76db72bf850e77cf6b5266c79664366dc93fc39
--- /dev/null
+++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/package.json
@@ -0,0 +1,76 @@
+{
+ "name": "@typescript-eslint/visitor-keys",
+ "version": "8.60.1",
+ "description": "Visitor keys used to help traverse the TypeScript-ESTree AST",
+ "files": [
+ "dist",
+ "!**/*.tsbuildinfo",
+ "package.json",
+ "README.md",
+ "LICENSE"
+ ],
+ "type": "commonjs",
+ "exports": {
+ ".": {
+ "types": "./dist/index.d.ts",
+ "default": "./dist/index.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "types": "./dist/index.d.ts",
+ "engines": {
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
+ },
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/typescript-eslint/typescript-eslint.git",
+ "directory": "packages/visitor-keys"
+ },
+ "bugs": {
+ "url": "https://github.com/typescript-eslint/typescript-eslint/issues"
+ },
+ "homepage": "https://typescript-eslint.io",
+ "license": "MIT",
+ "keywords": [
+ "eslint",
+ "typescript",
+ "estree"
+ ],
+ "dependencies": {
+ "eslint-visitor-keys": "^5.0.0",
+ "@typescript-eslint/types": "8.60.1"
+ },
+ "devDependencies": {
+ "@typescript/native-preview": "7.0.0-dev.20260518.1",
+ "@vitest/coverage-v8": "^4.0.18",
+ "eslint": "^10.0.0",
+ "rimraf": "^5.0.10",
+ "typescript": ">=4.8.4 <6.1.0",
+ "vitest": "^4.0.18"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/typescript-eslint"
+ },
+ "nx": {
+ "name": "visitor-keys",
+ "includedScripts": [
+ "clean"
+ ],
+ "targets": {
+ "lint": {
+ "command": "eslint"
+ },
+ "typecheck:tsgo": {}
+ }
+ },
+ "scripts": {
+ "build": "pnpm exec nx build",
+ "clean": "rimraf dist/ coverage/",
+ "format": "pnpm -w run format",
+ "lint": "pnpm -w exec nx lint",
+ "test": "pnpm -w exec nx test",
+ "typecheck": "pnpm -w exec nx typecheck",
+ "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo"
+ }
+}
\ No newline at end of file
diff --git a/tools/ui/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml b/tools/ui/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml
new file mode 100644
index 0000000000000000000000000000000000000000..73cf8d65218202c9eccdd6de6c29482fefae3e60
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml
@@ -0,0 +1,31 @@
+# This workflow will do a clean install of node dependencies, cache/restore them, build the source code and run tests across different versions of node
+# For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
+
+name: build
+
+on: [push, pull_request]
+
+jobs:
+ build:
+
+ runs-on: ubuntu-latest
+
+ strategy:
+ matrix:
+ node-version: [16]
+
+ steps:
+ - uses: actions/checkout@v2
+ - name: Use Node.js ${{ matrix.node-version }}
+ uses: actions/setup-node@v2
+ with:
+ node-version: ${{ matrix.node-version }}
+ cache: 'npm'
+ - run: npm ci
+ - run: npm run build --if-present
+ - run: npm test
+ - run: npm run coverage --if-present
+ - name: Coveralls
+ uses: coverallsapp/github-action@master
+ with:
+ github-token: ${{ secrets.GITHUB_TOKEN }}
diff --git a/tools/ui/node_modules/@ungap/structured-clone/LICENSE b/tools/ui/node_modules/@ungap/structured-clone/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..48afbe52afb5895b682e9b877bae10f96049a446
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/LICENSE
@@ -0,0 +1,15 @@
+ISC License
+
+Copyright (c) 2021, Andrea Giammarchi, @WebReflection
+
+Permission to use, copy, modify, and/or distribute this software for any
+purpose with or without fee is hereby granted, provided that the above
+copyright notice and this permission notice appear in all copies.
+
+THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
+REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
+AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
+INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
+LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
+OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
+PERFORMANCE OF THIS SOFTWARE.
diff --git a/tools/ui/node_modules/@ungap/structured-clone/README.md b/tools/ui/node_modules/@ungap/structured-clone/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..07d15a25f4646bab1792f28012305823ed675570
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/README.md
@@ -0,0 +1,95 @@
+# structuredClone polyfill
+
+[](https://www.npmjs.com/package/@ungap/structured-clone) [](https://github.com/ungap/structured-clone/actions) [](https://coveralls.io/github/ungap/structured-clone?branch=main)
+
+An env agnostic serializer and deserializer with recursion ability and types beyond *JSON* from the *HTML* standard itself.
+
+ * [Supported Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types)
+ * *not supported yet*: Blob, File, FileList, ImageBitmap, ImageData or others non *JS* types but typed arrays are supported without major issues, but u/int8, u/int16, and u/int32 are the only safely suppored (right now).
+ * *not possible to implement*: the `{transfer: []}` option can be passed but it's completely ignored.
+ * [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)
+ * [Serializer](https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal)
+ * [Deserializer](https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize)
+
+Serialized values can be safely stringified as *JSON* too, and deserialization resurrect all values, even recursive, or more complex than what *JSON* allows.
+
+
+### Examples
+
+Check the [100% test coverage](./test/index.js) to know even more.
+
+```js
+// as default export
+import structuredClone from '@ungap/structured-clone';
+const cloned = structuredClone({any: 'serializable'});
+
+// as independent serializer/deserializer
+import {serialize, deserialize} from '@ungap/structured-clone';
+
+// the result can be stringified as JSON without issues
+// even if there is recursive data, bigint values,
+// typed arrays, and so on
+const serialized = serialize({any: 'serializable'});
+
+// the result will be a replica of the original object
+const deserialized = deserialize(serialized);
+```
+
+#### Global Polyfill
+Note: Only monkey patch the global if needed. This polyfill works just fine as an explicit import: `import structuredClone from "@ungap/structured-clone"`
+```js
+// Attach the polyfill as a Global function
+import structuredClone from "@ungap/structured-clone";
+if (!("structuredClone" in globalThis)) {
+ globalThis.structuredClone = structuredClone;
+}
+
+// Or don't monkey patch
+import structuredClone from "@ungap/structured-clone"
+// Just use it in the file
+structuredClone()
+```
+
+**Note**: Do not attach this module's default export directly to the global scope, whithout a conditional guard to detect a native implementation. In environments where there is a native global implementation of `structuredClone()` already, assignment to the global object will result in an infinite loop when `globalThis.structuredClone()` is called. See the example above for a safe way to provide the polyfill globally in your project.
+
+### Extra Features
+
+There is no middle-ground between the structured clone algorithm and JSON:
+
+ * JSON is more relaxed about incompatible values: it just ignores these
+ * Structured clone is inflexible regarding incompatible values, yet it makes specialized instances impossible to reconstruct, plus it doesn't offer any helper, such as `toJSON()`, to make serialization possible, or better, with specific cases
+
+This module specialized `serialize` export offers, within the optional extra argument, a **lossy** property to avoid throwing when incompatible types are found down the road (function, symbol, ...), so that it is possible to send with less worrying about thrown errors.
+
+```js
+// as default export
+import structuredClone from '@ungap/structured-clone';
+const cloned = structuredClone(
+ {
+ method() {
+ // ignored, won't be cloned
+ },
+ special: Symbol('also ignored')
+ },
+ {
+ // avoid throwing
+ lossy: true,
+ // avoid throwing *and* looks for toJSON
+ json: true
+ }
+);
+```
+
+The behavior is the same found in *JSON* when it comes to *Array*, so that unsupported values will result as `null` placeholders instead.
+
+#### toJSON
+
+If `lossy` option is not enough, `json` will actually enforce `lossy` and also check for `toJSON` method when objects are parsed.
+
+Alternative, the `json` exports combines all features:
+
+```js
+import {stringify, parse} from '@ungap/structured-clone/json';
+
+parse(stringify({any: 'serializable'}));
+```
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/deserialize.js b/tools/ui/node_modules/@ungap/structured-clone/cjs/deserialize.js
new file mode 100644
index 0000000000000000000000000000000000000000..6ce37b076a7f09b731d0e7e440831cec2acbcd58
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/deserialize.js
@@ -0,0 +1,97 @@
+'use strict';
+const {
+ VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
+} = require('./types.js');
+
+const env = typeof self === 'object' ? self : globalThis;
+
+const guard = (name, init) => {
+ switch (name) {
+ case 'Function':
+ case 'SharedWorker':
+ case 'Worker':
+ case 'eval':
+ case 'setInterval':
+ case 'setTimeout':
+ throw new TypeError('unable to deserialize ' + name);
+ }
+ return new env[name](init);
+};
+
+const deserializer = ($, _) => {
+ const as = (out, index) => {
+ $.set(index, out);
+ return out;
+ };
+
+ const unpair = index => {
+ if ($.has(index))
+ return $.get(index);
+
+ const [type, value] = _[index];
+ switch (type) {
+ case PRIMITIVE:
+ case VOID:
+ return as(value, index);
+ case ARRAY: {
+ const arr = as([], index);
+ for (const index of value)
+ arr.push(unpair(index));
+ return arr;
+ }
+ case OBJECT: {
+ const object = as({}, index);
+ for (const [key, index] of value)
+ object[unpair(key)] = unpair(index);
+ return object;
+ }
+ case DATE:
+ return as(new Date(value), index);
+ case REGEXP: {
+ const {source, flags} = value;
+ return as(new RegExp(source, flags), index);
+ }
+ case MAP: {
+ const map = as(new Map, index);
+ for (const [key, index] of value)
+ map.set(unpair(key), unpair(index));
+ return map;
+ }
+ case SET: {
+ const set = as(new Set, index);
+ for (const index of value)
+ set.add(unpair(index));
+ return set;
+ }
+ case ERROR: {
+ const {name, message} = value;
+ return as(guard(name, message), index);
+ }
+ case BIGINT:
+ return as(BigInt(value), index);
+ case 'BigInt':
+ return as(Object(BigInt(value)), index);
+ case 'ArrayBuffer':
+ return as(new Uint8Array(value).buffer, value);
+ case 'DataView': {
+ const { buffer } = new Uint8Array(value);
+ return as(new DataView(buffer), value);
+ }
+ }
+ return as(guard(type, value), index);
+ };
+
+ return unpair;
+};
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns a deserialized value from a serialized array of Records.
+ * @param {Record[]} serialized a previously serialized value.
+ * @returns {any}
+ */
+const deserialize = serialized => deserializer(new Map, serialized)(0);
+exports.deserialize = deserialize;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/index.js b/tools/ui/node_modules/@ungap/structured-clone/cjs/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..13d747c5937db606221cf597d3345dba76a26aec
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/index.js
@@ -0,0 +1,27 @@
+'use strict';
+const {deserialize} = require('./deserialize.js');
+const {serialize} = require('./serialize.js');
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns an array of serialized Records.
+ * @param {any} any a serializable value.
+ * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
+ * a transfer option (ignored when polyfilled) and/or non standard fields that
+ * fallback to the polyfill if present.
+ * @returns {Record[]}
+ */
+Object.defineProperty(exports, '__esModule', {value: true}).default = typeof structuredClone === "function" ?
+ /* c8 ignore start */
+ (any, options) => (
+ options && ('json' in options || 'lossy' in options) ?
+ deserialize(serialize(any, options)) : structuredClone(any)
+ ) :
+ (any, options) => deserialize(serialize(any, options));
+ /* c8 ignore stop */
+
+exports.deserialize = deserialize;
+exports.serialize = serialize;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/json.js b/tools/ui/node_modules/@ungap/structured-clone/cjs/json.js
new file mode 100644
index 0000000000000000000000000000000000000000..0038dcf9ca530fe4506c0b3adec60f99d9d260c0
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/json.js
@@ -0,0 +1,24 @@
+'use strict';
+/*! (c) Andrea Giammarchi - ISC */
+
+const {deserialize} = require('./deserialize.js');
+const {serialize} = require('./serialize.js');
+
+const {parse: $parse, stringify: $stringify} = JSON;
+const options = {json: true, lossy: true};
+
+/**
+ * Revive a previously stringified structured clone.
+ * @param {string} str previously stringified data as string.
+ * @returns {any} whatever was previously stringified as clone.
+ */
+const parse = str => deserialize($parse(str));
+exports.parse = parse;
+
+/**
+ * Represent a structured clone value as string.
+ * @param {any} any some clone-able value to stringify.
+ * @returns {string} the value stringified.
+ */
+const stringify = any => $stringify(serialize(any, options));
+exports.stringify = stringify;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/package.json b/tools/ui/node_modules/@ungap/structured-clone/cjs/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..0292b9956f2e40d6eb3d0f3998e710d973113aaa
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/package.json
@@ -0,0 +1 @@
+{"type":"commonjs"}
\ No newline at end of file
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/serialize.js b/tools/ui/node_modules/@ungap/structured-clone/cjs/serialize.js
new file mode 100644
index 0000000000000000000000000000000000000000..59b2d38371c6c656b9a8e7d7657922b1af359a62
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/serialize.js
@@ -0,0 +1,170 @@
+'use strict';
+const {
+ VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
+} = require('./types.js');
+
+const EMPTY = '';
+
+const {toString} = {};
+const {keys} = Object;
+
+const typeOf = value => {
+ const type = typeof value;
+ if (type !== 'object' || !value)
+ return [PRIMITIVE, type];
+
+ const asString = toString.call(value).slice(8, -1);
+ switch (asString) {
+ case 'Array':
+ return [ARRAY, EMPTY];
+ case 'Object':
+ return [OBJECT, EMPTY];
+ case 'Date':
+ return [DATE, EMPTY];
+ case 'RegExp':
+ return [REGEXP, EMPTY];
+ case 'Map':
+ return [MAP, EMPTY];
+ case 'Set':
+ return [SET, EMPTY];
+ case 'DataView':
+ return [ARRAY, asString];
+ }
+
+ if (asString.includes('Array'))
+ return [ARRAY, asString];
+
+ if (asString.includes('Error'))
+ return [ERROR, asString];
+
+ return [OBJECT, asString];
+};
+
+const shouldSkip = ([TYPE, type]) => (
+ TYPE === PRIMITIVE &&
+ (type === 'function' || type === 'symbol')
+);
+
+const serializer = (strict, json, $, _) => {
+
+ const as = (out, value) => {
+ const index = _.push(out) - 1;
+ $.set(value, index);
+ return index;
+ };
+
+ const pair = value => {
+ if ($.has(value))
+ return $.get(value);
+
+ let [TYPE, type] = typeOf(value);
+ switch (TYPE) {
+ case PRIMITIVE: {
+ let entry = value;
+ switch (type) {
+ case 'bigint':
+ TYPE = BIGINT;
+ entry = value.toString();
+ break;
+ case 'function':
+ case 'symbol':
+ if (strict)
+ throw new TypeError('unable to serialize ' + type);
+ entry = null;
+ break;
+ case 'undefined':
+ return as([VOID], value);
+ }
+ return as([TYPE, entry], value);
+ }
+ case ARRAY: {
+ if (type) {
+ let spread = value;
+ if (type === 'DataView') {
+ spread = new Uint8Array(value.buffer);
+ }
+ else if (type === 'ArrayBuffer') {
+ spread = new Uint8Array(value);
+ }
+ return as([type, [...spread]], value);
+ }
+
+ const arr = [];
+ const index = as([TYPE, arr], value);
+ for (const entry of value)
+ arr.push(pair(entry));
+ return index;
+ }
+ case OBJECT: {
+ if (type) {
+ switch (type) {
+ case 'BigInt':
+ return as([type, value.toString()], value);
+ case 'Boolean':
+ case 'Number':
+ case 'String':
+ return as([type, value.valueOf()], value);
+ }
+ }
+
+ if (json && ('toJSON' in value))
+ return pair(value.toJSON());
+
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const key of keys(value)) {
+ if (strict || !shouldSkip(typeOf(value[key])))
+ entries.push([pair(key), pair(value[key])]);
+ }
+ return index;
+ }
+ case DATE:
+ return as([TYPE, value.toISOString()], value);
+ case REGEXP: {
+ const {source, flags} = value;
+ return as([TYPE, {source, flags}], value);
+ }
+ case MAP: {
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const [key, entry] of value) {
+ if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
+ entries.push([pair(key), pair(entry)]);
+ }
+ return index;
+ }
+ case SET: {
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const entry of value) {
+ if (strict || !shouldSkip(typeOf(entry)))
+ entries.push(pair(entry));
+ }
+ return index;
+ }
+ }
+
+ const {message} = value;
+ return as([TYPE, {name: type, message}], value);
+ };
+
+ return pair;
+};
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns an array of serialized Records.
+ * @param {any} value a serializable value.
+ * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
+ * if `true`, will not throw errors on incompatible types, and behave more
+ * like JSON stringify would behave. Symbol and Function will be discarded.
+ * @returns {Record[]}
+ */
+ const serialize = (value, {json, lossy} = {}) => {
+ const _ = [];
+ return serializer(!(json || lossy), !!json, new Map, _)(value), _;
+};
+exports.serialize = serialize;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/cjs/types.js b/tools/ui/node_modules/@ungap/structured-clone/cjs/types.js
new file mode 100644
index 0000000000000000000000000000000000000000..8284be3d69a407829b84aea17965338d0b8efde3
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/cjs/types.js
@@ -0,0 +1,22 @@
+'use strict';
+const VOID = -1;
+exports.VOID = VOID;
+const PRIMITIVE = 0;
+exports.PRIMITIVE = PRIMITIVE;
+const ARRAY = 1;
+exports.ARRAY = ARRAY;
+const OBJECT = 2;
+exports.OBJECT = OBJECT;
+const DATE = 3;
+exports.DATE = DATE;
+const REGEXP = 4;
+exports.REGEXP = REGEXP;
+const MAP = 5;
+exports.MAP = MAP;
+const SET = 6;
+exports.SET = SET;
+const ERROR = 7;
+exports.ERROR = ERROR;
+const BIGINT = 8;
+exports.BIGINT = BIGINT;
+// export const SYMBOL = 9;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/esm/deserialize.js b/tools/ui/node_modules/@ungap/structured-clone/esm/deserialize.js
new file mode 100644
index 0000000000000000000000000000000000000000..440fb30152f1226c7295f37ee0c97deef9ff4884
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/esm/deserialize.js
@@ -0,0 +1,98 @@
+import {
+ VOID, PRIMITIVE,
+ ARRAY, OBJECT,
+ DATE, REGEXP, MAP, SET,
+ ERROR, BIGINT
+} from './types.js';
+
+const env = typeof self === 'object' ? self : globalThis;
+
+const guard = (name, init) => {
+ switch (name) {
+ case 'Function':
+ case 'SharedWorker':
+ case 'Worker':
+ case 'eval':
+ case 'setInterval':
+ case 'setTimeout':
+ throw new TypeError('unable to deserialize ' + name);
+ }
+ return new env[name](init);
+};
+
+const deserializer = ($, _) => {
+ const as = (out, index) => {
+ $.set(index, out);
+ return out;
+ };
+
+ const unpair = index => {
+ if ($.has(index))
+ return $.get(index);
+
+ const [type, value] = _[index];
+ switch (type) {
+ case PRIMITIVE:
+ case VOID:
+ return as(value, index);
+ case ARRAY: {
+ const arr = as([], index);
+ for (const index of value)
+ arr.push(unpair(index));
+ return arr;
+ }
+ case OBJECT: {
+ const object = as({}, index);
+ for (const [key, index] of value)
+ object[unpair(key)] = unpair(index);
+ return object;
+ }
+ case DATE:
+ return as(new Date(value), index);
+ case REGEXP: {
+ const {source, flags} = value;
+ return as(new RegExp(source, flags), index);
+ }
+ case MAP: {
+ const map = as(new Map, index);
+ for (const [key, index] of value)
+ map.set(unpair(key), unpair(index));
+ return map;
+ }
+ case SET: {
+ const set = as(new Set, index);
+ for (const index of value)
+ set.add(unpair(index));
+ return set;
+ }
+ case ERROR: {
+ const {name, message} = value;
+ return as(guard(name, message), index);
+ }
+ case BIGINT:
+ return as(BigInt(value), index);
+ case 'BigInt':
+ return as(Object(BigInt(value)), index);
+ case 'ArrayBuffer':
+ return as(new Uint8Array(value).buffer, value);
+ case 'DataView': {
+ const { buffer } = new Uint8Array(value);
+ return as(new DataView(buffer), value);
+ }
+ }
+ return as(guard(type, value), index);
+ };
+
+ return unpair;
+};
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns a deserialized value from a serialized array of Records.
+ * @param {Record[]} serialized a previously serialized value.
+ * @returns {any}
+ */
+export const deserialize = serialized => deserializer(new Map, serialized)(0);
diff --git a/tools/ui/node_modules/@ungap/structured-clone/esm/index.js b/tools/ui/node_modules/@ungap/structured-clone/esm/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..d3b47479adfc55679022b9098fa0b968fed8d818
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/esm/index.js
@@ -0,0 +1,25 @@
+import {deserialize} from './deserialize.js';
+import {serialize} from './serialize.js';
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns an array of serialized Records.
+ * @param {any} any a serializable value.
+ * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
+ * a transfer option (ignored when polyfilled) and/or non standard fields that
+ * fallback to the polyfill if present.
+ * @returns {Record[]}
+ */
+export default typeof structuredClone === "function" ?
+ /* c8 ignore start */
+ (any, options) => (
+ options && ('json' in options || 'lossy' in options) ?
+ deserialize(serialize(any, options)) : structuredClone(any)
+ ) :
+ (any, options) => deserialize(serialize(any, options));
+ /* c8 ignore stop */
+
+export {deserialize, serialize};
diff --git a/tools/ui/node_modules/@ungap/structured-clone/esm/json.js b/tools/ui/node_modules/@ungap/structured-clone/esm/json.js
new file mode 100644
index 0000000000000000000000000000000000000000..23eb95222d1a318faba1bffcd907b5038405ae38
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/esm/json.js
@@ -0,0 +1,21 @@
+/*! (c) Andrea Giammarchi - ISC */
+
+import {deserialize} from './deserialize.js';
+import {serialize} from './serialize.js';
+
+const {parse: $parse, stringify: $stringify} = JSON;
+const options = {json: true, lossy: true};
+
+/**
+ * Revive a previously stringified structured clone.
+ * @param {string} str previously stringified data as string.
+ * @returns {any} whatever was previously stringified as clone.
+ */
+export const parse = str => deserialize($parse(str));
+
+/**
+ * Represent a structured clone value as string.
+ * @param {any} any some clone-able value to stringify.
+ * @returns {string} the value stringified.
+ */
+export const stringify = any => $stringify(serialize(any, options));
diff --git a/tools/ui/node_modules/@ungap/structured-clone/esm/serialize.js b/tools/ui/node_modules/@ungap/structured-clone/esm/serialize.js
new file mode 100644
index 0000000000000000000000000000000000000000..6286047a841fffa4019daaa8967d3a9db5725610
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/esm/serialize.js
@@ -0,0 +1,171 @@
+import {
+ VOID, PRIMITIVE,
+ ARRAY, OBJECT,
+ DATE, REGEXP, MAP, SET,
+ ERROR, BIGINT
+} from './types.js';
+
+const EMPTY = '';
+
+const {toString} = {};
+const {keys} = Object;
+
+const typeOf = value => {
+ const type = typeof value;
+ if (type !== 'object' || !value)
+ return [PRIMITIVE, type];
+
+ const asString = toString.call(value).slice(8, -1);
+ switch (asString) {
+ case 'Array':
+ return [ARRAY, EMPTY];
+ case 'Object':
+ return [OBJECT, EMPTY];
+ case 'Date':
+ return [DATE, EMPTY];
+ case 'RegExp':
+ return [REGEXP, EMPTY];
+ case 'Map':
+ return [MAP, EMPTY];
+ case 'Set':
+ return [SET, EMPTY];
+ case 'DataView':
+ return [ARRAY, asString];
+ }
+
+ if (asString.includes('Array'))
+ return [ARRAY, asString];
+
+ if (asString.includes('Error'))
+ return [ERROR, asString];
+
+ return [OBJECT, asString];
+};
+
+const shouldSkip = ([TYPE, type]) => (
+ TYPE === PRIMITIVE &&
+ (type === 'function' || type === 'symbol')
+);
+
+const serializer = (strict, json, $, _) => {
+
+ const as = (out, value) => {
+ const index = _.push(out) - 1;
+ $.set(value, index);
+ return index;
+ };
+
+ const pair = value => {
+ if ($.has(value))
+ return $.get(value);
+
+ let [TYPE, type] = typeOf(value);
+ switch (TYPE) {
+ case PRIMITIVE: {
+ let entry = value;
+ switch (type) {
+ case 'bigint':
+ TYPE = BIGINT;
+ entry = value.toString();
+ break;
+ case 'function':
+ case 'symbol':
+ if (strict)
+ throw new TypeError('unable to serialize ' + type);
+ entry = null;
+ break;
+ case 'undefined':
+ return as([VOID], value);
+ }
+ return as([TYPE, entry], value);
+ }
+ case ARRAY: {
+ if (type) {
+ let spread = value;
+ if (type === 'DataView') {
+ spread = new Uint8Array(value.buffer);
+ }
+ else if (type === 'ArrayBuffer') {
+ spread = new Uint8Array(value);
+ }
+ return as([type, [...spread]], value);
+ }
+
+ const arr = [];
+ const index = as([TYPE, arr], value);
+ for (const entry of value)
+ arr.push(pair(entry));
+ return index;
+ }
+ case OBJECT: {
+ if (type) {
+ switch (type) {
+ case 'BigInt':
+ return as([type, value.toString()], value);
+ case 'Boolean':
+ case 'Number':
+ case 'String':
+ return as([type, value.valueOf()], value);
+ }
+ }
+
+ if (json && ('toJSON' in value))
+ return pair(value.toJSON());
+
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const key of keys(value)) {
+ if (strict || !shouldSkip(typeOf(value[key])))
+ entries.push([pair(key), pair(value[key])]);
+ }
+ return index;
+ }
+ case DATE:
+ return as([TYPE, value.toISOString()], value);
+ case REGEXP: {
+ const {source, flags} = value;
+ return as([TYPE, {source, flags}], value);
+ }
+ case MAP: {
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const [key, entry] of value) {
+ if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
+ entries.push([pair(key), pair(entry)]);
+ }
+ return index;
+ }
+ case SET: {
+ const entries = [];
+ const index = as([TYPE, entries], value);
+ for (const entry of value) {
+ if (strict || !shouldSkip(typeOf(entry)))
+ entries.push(pair(entry));
+ }
+ return index;
+ }
+ }
+
+ const {message} = value;
+ return as([TYPE, {name: type, message}], value);
+ };
+
+ return pair;
+};
+
+/**
+ * @typedef {Array} Record a type representation
+ */
+
+/**
+ * Returns an array of serialized Records.
+ * @param {any} value a serializable value.
+ * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
+ * if `true`, will not throw errors on incompatible types, and behave more
+ * like JSON stringify would behave. Symbol and Function will be discarded.
+ * @returns {Record[]}
+ */
+ export const serialize = (value, {json, lossy} = {}) => {
+ const _ = [];
+ return serializer(!(json || lossy), !!json, new Map, _)(value), _;
+};
diff --git a/tools/ui/node_modules/@ungap/structured-clone/esm/types.js b/tools/ui/node_modules/@ungap/structured-clone/esm/types.js
new file mode 100644
index 0000000000000000000000000000000000000000..50e60ca067667f4df09393a3898137f0c933604e
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/esm/types.js
@@ -0,0 +1,11 @@
+export const VOID = -1;
+export const PRIMITIVE = 0;
+export const ARRAY = 1;
+export const OBJECT = 2;
+export const DATE = 3;
+export const REGEXP = 4;
+export const MAP = 5;
+export const SET = 6;
+export const ERROR = 7;
+export const BIGINT = 8;
+// export const SYMBOL = 9;
diff --git a/tools/ui/node_modules/@ungap/structured-clone/package.json b/tools/ui/node_modules/@ungap/structured-clone/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..3adc31103dafff9d76867959dd226062fca27a9e
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/package.json
@@ -0,0 +1,54 @@
+{
+ "name": "@ungap/structured-clone",
+ "version": "1.3.1",
+ "description": "A structuredClone polyfill",
+ "main": "./cjs/index.js",
+ "scripts": {
+ "build": "npm run cjs && npm run rollup:json && npm run test",
+ "cjs": "ascjs esm cjs",
+ "coverage": "c8 report --reporter=text-lcov > ./coverage/lcov.info",
+ "rollup:json": "rollup --config rollup/json.config.js",
+ "test": "c8 node test/index.js"
+ },
+ "keywords": [
+ "recursion",
+ "structured",
+ "clone",
+ "algorithm"
+ ],
+ "author": "Andrea Giammarchi",
+ "license": "ISC",
+ "devDependencies": {
+ "@rollup/plugin-node-resolve": "^16.0.3",
+ "@rollup/plugin-terser": "^1.0.0",
+ "ascjs": "^6.0.3",
+ "c8": "^11.0.0",
+ "coveralls": "^3.1.1",
+ "rollup": "^4.60.3"
+ },
+ "module": "./esm/index.js",
+ "type": "module",
+ "sideEffects": false,
+ "exports": {
+ ".": {
+ "import": "./esm/index.js",
+ "default": "./cjs/index.js"
+ },
+ "./json": {
+ "import": "./esm/json.js",
+ "default": "./cjs/json.js"
+ },
+ "./package.json": "./package.json"
+ },
+ "directories": {
+ "test": "test"
+ },
+ "repository": {
+ "type": "git",
+ "url": "git+https://github.com/ungap/structured-clone.git"
+ },
+ "bugs": {
+ "url": "https://github.com/ungap/structured-clone/issues"
+ },
+ "homepage": "https://github.com/ungap/structured-clone#readme"
+}
diff --git a/tools/ui/node_modules/@ungap/structured-clone/structured-json.js b/tools/ui/node_modules/@ungap/structured-clone/structured-json.js
new file mode 100644
index 0000000000000000000000000000000000000000..81373cf4a595d659a4fb2cf299374e618068a8c7
--- /dev/null
+++ b/tools/ui/node_modules/@ungap/structured-clone/structured-json.js
@@ -0,0 +1 @@
+var StructuredJSON=function(e){"use strict";const r="object"==typeof self?self:globalThis,t=(e,t)=>{switch(e){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+e)}return new r[e](t)},n=e=>((e,r)=>{const n=(r,t)=>(e.set(t,r),r),s=c=>{if(e.has(c))return e.get(c);const[a,o]=r[c];switch(a){case 0:case-1:return n(o,c);case 1:{const e=n([],c);for(const r of o)e.push(s(r));return e}case 2:{const e=n({},c);for(const[r,t]of o)e[s(r)]=s(t);return e}case 3:return n(new Date(o),c);case 4:{const{source:e,flags:r}=o;return n(new RegExp(e,r),c)}case 5:{const e=n(new Map,c);for(const[r,t]of o)e.set(s(r),s(t));return e}case 6:{const e=n(new Set,c);for(const r of o)e.add(s(r));return e}case 7:{const{name:e,message:r}=o;return n(t(e,r),c)}case 8:return n(BigInt(o),c);case"BigInt":return n(Object(BigInt(o)),c);case"ArrayBuffer":return n(new Uint8Array(o).buffer,o);case"DataView":{const{buffer:e}=new Uint8Array(o);return n(new DataView(e),o)}}return n(t(a,o),c)};return s})(new Map,e)(0),s="",{toString:c}={},{keys:a}=Object,o=e=>{const r=typeof e;if("object"!==r||!e)return[0,r];const t=c.call(e).slice(8,-1);switch(t){case"Array":return[1,s];case"Object":return[2,s];case"Date":return[3,s];case"RegExp":return[4,s];case"Map":return[5,s];case"Set":return[6,s];case"DataView":return[1,t]}return t.includes("Array")?[1,t]:t.includes("Error")?[7,t]:[2,t]},u=([e,r])=>0===e&&("function"===r||"symbol"===r),i=(e,{json:r,lossy:t}={})=>{const n=[];return((e,r,t,n)=>{const s=(e,r)=>{const s=n.push(e)-1;return t.set(r,s),s},c=n=>{if(t.has(n))return t.get(n);let[i,f]=o(n);switch(i){case 0:{let r=n;switch(f){case"bigint":i=8,r=n.toString();break;case"function":case"symbol":if(e)throw new TypeError("unable to serialize "+f);r=null;break;case"undefined":return s([-1],n)}return s([i,r],n)}case 1:{if(f){let e=n;return"DataView"===f?e=new Uint8Array(n.buffer):"ArrayBuffer"===f&&(e=new Uint8Array(n)),s([f,[...e]],n)}const e=[],r=s([i,e],n);for(const r of n)e.push(c(r));return r}case 2:{if(f)switch(f){case"BigInt":return s([f,n.toString()],n);case"Boolean":case"Number":case"String":return s([f,n.valueOf()],n)}if(r&&"toJSON"in n)return c(n.toJSON());const t=[],l=s([i,t],n);for(const r of a(n))!e&&u(o(n[r]))||t.push([c(r),c(n[r])]);return l}case 3:return s([i,n.toISOString()],n);case 4:{const{source:e,flags:r}=n;return s([i,{source:e,flags:r}],n)}case 5:{const r=[],t=s([i,r],n);for(const[t,s]of n)(e||!u(o(t))&&!u(o(s)))&&r.push([c(t),c(s)]);return t}case 6:{const r=[],t=s([i,r],n);for(const t of n)!e&&u(o(t))||r.push(c(t));return t}}const{message:l}=n;return s([i,{name:f,message:l}],n)};return c})(!(r||t),!!r,new Map,n)(e),n},{parse:f,stringify:l}=JSON,w={json:!0,lossy:!0};return e.parse=e=>n(f(e)),e.stringify=e=>l(i(e,w)),e}({});
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/LICENSE b/tools/ui/node_modules/@upsetjs/venn.js/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..ad6e7d77393120c8916b8a5a6312b3e84ce305a0
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/LICENSE
@@ -0,0 +1,22 @@
+MIT License
+
+Copyright (c) 2013 Ben Frederickson
+Copyright (c) 2021 Samuel Gratzl
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/README.md b/tools/ui/node_modules/@upsetjs/venn.js/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..9699095a3a792948e0fd0fa45b7ea4ea786367af
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/README.md
@@ -0,0 +1,267 @@
+# venn.js
+
+[![License: MIT][mit-image]][mit-url] [![NPM Package][npm-image]][npm-url] [![Github Actions][github-actions-image]][github-actions-url]
+
+This is a maintained fork of [https://github.com/benfred/venn.js](https://github.com/benfred/venn.js).
+
+A javascript library for laying out area proportional venn and euler diagrams.
+
+Details of how this library works can be found on the [blog
+post](https://www.benfrederickson.com/venn-diagrams-with-d3.js/)
+the original author wrote about this. A follow up post [discusses testing strategy and
+algorithmic improvements](https://www.benfrederickson.com/better-venn-diagrams/).
+
+## Install
+
+```bash
+npm install --save @upsetjs/venn.js
+```
+
+## Usage
+
+There are two modes in which this library can be used.
+First, in a managed case by using the `VennDiagram` function that will render the data using D3.
+Second, in a manual case as a layout library that is just preparing the data for you.
+
+In the following, these set data are used:
+
+```js
+const sets = [
+ { sets: ['A'], size: 12 },
+ { sets: ['B'], size: 12 },
+ { sets: ['A', 'B'], size: 2 },
+];
+```
+
+### Managed Usage
+
+This library depends on [d3.js](https://d3js.org/) to display the venn
+diagrams.
+
+##### Simple layout
+
+To lay out a simple diagram, just define the sets and their sizes along with the sizes
+of all the set intersections.
+
+The VennDiagram object will calculate a layout that is proportional to the
+input sizes, and display it in the appropriate selection when called:
+
+```js
+const chart = venn.VennDiagram();
+d3.select('#venn').datum(sets).call(chart);
+```
+
+[View this example](https://upset.js.org/venn.js/examples/simple.html)
+
+[![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/RwrKPEe)
+
+##### Changing the Style
+
+The style of the Venn Diagram can be customized by using D3 after the diagram
+has been drawn. For instance to draw a Venn Diagram with white text and a darker fill:
+
+```js
+const chart = venn.VennDiagram();
+d3.select('#inverted').datum(sets).call(chart);
+
+d3.selectAll('#inverted .venn-circle path').style('fill-opacity', 0.8);
+
+d3.selectAll('#inverted text').style('fill', 'white');
+```
+
+[View this example, along with other possible styles](https://upset.js.org/venn.js/examples/styled.html)
+
+The position of text within each circle of the diagram may also be modified via the `symmetricalTextCentre` property (defaults to `false`):
+
+```js
+// draw a diagram with text symmetrically positioned in each circle's centre
+const chart = venn.VennDiagram({ symmetricalTextCentre: true });
+```
+
+##### Dynamic layout
+
+To have a layout that reacts to a change in input, all that you need to do is
+update the dataset and call the chart again:
+
+```js
+// draw the initial diagram
+const chart = venn.VennDiagram();
+d3.select('#venn').datum(getSetIntersections()).call(chart);
+
+// redraw the diagram on any change in input
+d3.selectAll('input').on('change', function () {
+ d3.select('#venn').datum(getSetIntersections()).call(chart);
+});
+```
+
+[View this example](https://upset.js.org/venn.js/examples/dynamic.html)
+
+##### Making the diagram interactive
+
+Making the diagram interactive is basically the same idea as changing the style: just add event listeners to the elements in the venn diagram. To change the text size and circle colours on mouseenter:
+
+```js
+d3.selectAll('#rings .venn-circle')
+ .on('mouseenter', function () {
+ const node = d3.select(this).transition();
+ node.select('path').style('fill-opacity', 0.2);
+ node.select('text').style('font-weight', '100').style('font-size', '36px');
+ })
+ .on('mouseleave', function () {
+ const node = d3.select(this).transition();
+ node.select('path').style('fill-opacity', 0);
+ node.select('text').style('font-weight', '100').style('font-size', '24px');
+ });
+```
+
+[View this example](https://upset.js.org/venn.js/examples/interactive.html)
+
+The colour scheme for the diagram's circles may also be modified via the `colorScheme` option, and the text within each circle can have its fill modified via the `textFill` option:
+
+```js
+const chart = venn.VennDiagram({
+ colorScheme: ['rgb(235, 237, 238)', '#F26250'],
+ textFill: '#FFF',
+});
+```
+
+##### Adding tooltips
+
+Another common case is adding a tooltip when hovering over the elements in the diagram. The only
+tricky thing here is maintaining the correct Z-order so that the smallest intersection areas
+are on top, while still making the area that is being hovered over appear on top of the others:
+
+```js
+// draw venn diagram
+const div = d3.select('#venn');
+div.datum(sets).call(venn.VennDiagram());
+
+// add a tooltip
+const tooltip = d3.select('body').append('div').attr('class', 'venntooltip');
+
+// add listeners to all the groups to display tooltip on mouseenter
+div
+ .selectAll('g')
+ .on('mouseenter', function (d) {
+ // sort all the areas relative to the current item
+ venn.sortAreas(div, d);
+
+ // Display a tooltip with the current size
+ tooltip.transition().duration(400).style('opacity', 0.9);
+ tooltip.text(d.size + ' users');
+
+ // highlight the current path
+ const selection = d3.select(this).transition('tooltip').duration(400);
+ selection
+ .select('path')
+ .style('stroke-width', 3)
+ .style('fill-opacity', d.sets.length == 1 ? 0.4 : 0.1)
+ .style('stroke-opacity', 1);
+ })
+
+ .on('mousemove', function () {
+ tooltip.style('left', d3.event.pageX + 'px').style('top', d3.event.pageY - 28 + 'px');
+ })
+
+ .on('mouseleave', function (d) {
+ tooltip.transition().duration(400).style('opacity', 0);
+ const selection = d3.select(this).transition('tooltip').duration(400);
+ selection
+ .select('path')
+ .style('stroke-width', 0)
+ .style('fill-opacity', d.sets.length == 1 ? 0.25 : 0.0)
+ .style('stroke-opacity', 0);
+ });
+```
+
+[View this example](https://upset.js.org/venn.js/examples/intersection_tooltip.html)
+
+## Manual Usage
+
+Besides the handy `VennDiagram` wrapper, the library can used as a pure layout function using the `layout` method.
+One can render the result manually in D3 or even in HTML Canvas.
+
+The signature of the function can be found as part of the TypeScript typings at [index.ds.ts](https://github.com/upsetjs/venn.js/blob/master/src/index.d.ts)
+
+### Custom D3 Rendering
+
+```js
+// compute layout data
+const data = venn.layout(sets);
+// custom data binding and rendering
+const g = d3
+ .select('#venn')
+ .selectAll('g')
+ .data(data)
+ .join((enter) => {
+ const g = enter.append('g');
+ g.append('title');
+ g.append('path');
+ g.append('text');
+ return g;
+ });
+g.select('title').text((d) => d.data.sets.toString());
+g.select('text')
+ .text((d) => d.data.sets.toString())
+ .attr('x', (d) => d.text.x)
+ .attr('y', (d) => d.text.y);
+g.select('path')
+ .attr('d', (d) => d.path)
+ .style('fill', (d, i) => (d.circles.length === 1 ? d3.schemeCategory10[i] : undefined));
+```
+
+[![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/xxZgGeP)
+
+### Canvas Rendering
+
+```js
+const data = venn.layout(sets, { width: 600, height: 350 });
+const ctx = document.querySelector('canvas').getContext('2d');
+
+data.forEach((d, i) => {
+ ctx.fillStyle = `hsla(${(360 * i) / data.length},80%,50%,0.6)`;
+ ctx.fill(new Path2D(d.path));
+});
+
+ctx.font = '16px Helvetica Neue, Helvetica, Arial, sans-serif';
+ctx.textAlign = 'center';
+ctx.textBaseline = 'central';
+ctx.fillStyle = 'white';
+
+data.forEach((d, i) => {
+ ctx.fillText(d.data.sets.toString(), d.text.x, d.text.y);
+});
+```
+
+[![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/NWxdqZW)
+
+## License
+
+Released under the MIT License.
+
+## Development Environment
+
+```sh
+npm i -g yarn
+yarn install
+yarn sdks vscode
+```
+
+### Common commands
+
+```sh
+yarn test
+yarn lint
+yarn format
+yarn build
+yarn release
+yarn release:pre
+```
+
+[mit-image]: https://img.shields.io/badge/License-MIT-yellow.svg
+[mit-url]: https://opensource.org/licenses/MIT
+[npm-image]: https://badge.fury.io/js/%40upsetjs%2Fvenn.js.svg
+[npm-url]: https://npmjs.org/package/@upsetjs/venn.js
+[github-actions-image]: https://github.com/upsetjs/venn.js/workflows/ci/badge.svg
+[github-actions-url]: https://github.com/upsetjs/venn.js/actions
+[codepen]: https://img.shields.io/badge/CodePen-open-blue?logo=codepen
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/build/venn.esm.js b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.esm.js
new file mode 100644
index 0000000000000000000000000000000000000000..3c12c37dd9ab87f766678db5d2eb2dea36b55481
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.esm.js
@@ -0,0 +1,2214 @@
+const SMALL$1 = 1e-10;
+
+/**
+ * Returns the intersection area of a bunch of circles (where each circle
+ * is an object having an x,y and radius property)
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @param {undefined | { area?: number, arcArea?: number, polygonArea?: number, arcs?: ReadonlyArray<{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }>, innerPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+}>, intersectionPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+}> }} stats
+ * @returns {number}
+ */
+function intersectionArea(circles, stats) {
+ // get all the intersection points of the circles
+ const intersectionPoints = getIntersectionPoints(circles);
+
+ // filter out points that aren't included in all the circles
+ const innerPoints = intersectionPoints.filter((p) => containedInCircles(p, circles));
+
+ let arcArea = 0;
+ let polygonArea = 0;
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
+ const arcs = [];
+
+ // if we have intersection points that are within all the circles,
+ // then figure out the area contained by them
+ if (innerPoints.length > 1) {
+ // sort the points by angle from the center of the polygon, which lets
+ // us just iterate over points to get the edges
+ const center = getCenter(innerPoints);
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p = innerPoints[i];
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
+ }
+ innerPoints.sort((a, b) => b.angle - a.angle);
+
+ // iterate over all points, get arc between the points
+ // and update the areas
+ let p2 = innerPoints[innerPoints.length - 1];
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p1 = innerPoints[i];
+
+ // polygon area updates easily ...
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
+
+ // updating the arc area is a little more involved
+ const midPoint = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
+ let arc = null;
+
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
+ // figure out the angle halfway between the two points
+ // on the current circle
+ const circle = circles[p1.parentIndex[j]];
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
+
+ let angleDiff = a2 - a1;
+ if (angleDiff < 0) {
+ angleDiff += 2 * Math.PI;
+ }
+
+ // and use that angle to figure out the width of the
+ // arc
+ const a = a2 - angleDiff / 2;
+ let width = distance(midPoint, {
+ x: circle.x + circle.radius * Math.sin(a),
+ y: circle.y + circle.radius * Math.cos(a),
+ });
+
+ // clamp the width to the largest is can actually be
+ // (sometimes slightly overflows because of FP errors)
+ if (width > circle.radius * 2) {
+ width = circle.radius * 2;
+ }
+
+ // pick the circle whose arc has the smallest width
+ if (arc == null || arc.width > width) {
+ arc = { circle, width, p1, p2, large: width > circle.radius, sweep: true };
+ }
+ }
+ }
+
+ if (arc != null) {
+ arcs.push(arc);
+ arcArea += circleArea(arc.circle.radius, arc.width);
+ p2 = p1;
+ }
+ }
+ } else {
+ // no intersection points, is either disjoint - or is completely
+ // overlapped. figure out which by examining the smallest circle
+ let smallest = circles[0];
+ for (let i = 1; i < circles.length; ++i) {
+ if (circles[i].radius < smallest.radius) {
+ smallest = circles[i];
+ }
+ }
+
+ // make sure the smallest circle is completely contained in all
+ // the other circles
+ let disjoint = false;
+ for (let i = 0; i < circles.length; ++i) {
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
+ disjoint = true;
+ break;
+ }
+ }
+
+ if (disjoint) {
+ arcArea = polygonArea = 0;
+ } else {
+ arcArea = smallest.radius * smallest.radius * Math.PI;
+ arcs.push({
+ circle: smallest,
+ p1: { x: smallest.x, y: smallest.y + smallest.radius },
+ p2: { x: smallest.x - SMALL$1, y: smallest.y + smallest.radius },
+ width: smallest.radius * 2,
+ large: true,
+ sweep: true,
+ });
+ }
+ }
+
+ polygonArea /= 2;
+
+ if (stats) {
+ stats.area = arcArea + polygonArea;
+ stats.arcArea = arcArea;
+ stats.polygonArea = polygonArea;
+ stats.arcs = arcs;
+ stats.innerPoints = innerPoints;
+ stats.intersectionPoints = intersectionPoints;
+ }
+
+ return arcArea + polygonArea;
+}
+
+/**
+ * returns whether a point is contained by all of a list of circles
+ * @param {{x: number, y: number}} point
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {boolean}
+ */
+function containedInCircles(point, circles) {
+ return circles.every((circle) => distance(point, circle) < circle.radius + SMALL$1);
+}
+
+/**
+ * Gets all intersection points between a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
+ */
+function getIntersectionPoints(circles) {
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
+ const ret = [];
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
+ for (const p of intersect) {
+ p.parentIndex = [i, j];
+ ret.push(p);
+ }
+ }
+ }
+ return ret;
+}
+
+/**
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
+ * @param {number} r
+ * @param {number} width
+ * @returns {number}
+ **/
+function circleArea(r, width) {
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
+}
+
+/**
+ * euclidean distance between two points
+ * @param {{x: number, y: number}} p1
+ * @param {{x: number, y: number}} p2
+ * @returns {number}
+ **/
+function distance(p1, p2) {
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
+}
+
+/**
+ * Returns the overlap area of two circles of radius r1 and r2 - that
+ * have their centers separated by distance d. Simpler faster
+ * circle intersection for only two circles
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} d
+ * @returns {number}
+ */
+function circleOverlap(r1, r2, d) {
+ // no overlap
+ if (d >= r1 + r2) {
+ return 0;
+ }
+
+ // completely overlapped
+ if (d <= Math.abs(r1 - r2)) {
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
+ }
+
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
+ return circleArea(r1, w1) + circleArea(r2, w2);
+}
+
+/**
+ * Given two circles (containing a x/y/radius attributes),
+ * returns the intersecting points if possible
+ * note: doesn't handle cases where there are infinitely many
+ * intersection points (circles are equivalent):, or only one intersection point
+ * @param {{x: number, y: number, radius: number}} p1
+ * @param {{x: number, y: number, radius: number}} p2
+ * @returns {ReadonlyArray<{x: number, y: number}>}
+ **/
+function circleCircleIntersection(p1, p2) {
+ const d = distance(p1, p2);
+ const r1 = p1.radius;
+ const r2 = p2.radius;
+
+ // if to far away, or self contained - can't be done
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
+ return [];
+ }
+
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
+ const h = Math.sqrt(r1 * r1 - a * a);
+ const x0 = p1.x + (a * (p2.x - p1.x)) / d;
+ const y0 = p1.y + (a * (p2.y - p1.y)) / d;
+ const rx = -(p2.y - p1.y) * (h / d);
+ const ry = -(p2.x - p1.x) * (h / d);
+
+ return [
+ { x: x0 + rx, y: y0 - ry },
+ { x: x0 - rx, y: y0 + ry },
+ ];
+}
+
+/**
+ * Returns the center of a bunch of points
+ * @param {ReadonlyArray<{x: number, y: number}>} points
+ * @returns {{x: number, y: number}}
+ */
+function getCenter(points) {
+ const center = { x: 0, y: 0 };
+ for (const point of points) {
+ center.x += point.x;
+ center.y += point.y;
+ }
+ center.x /= points.length;
+ center.y /= points.length;
+ return center;
+}
+
+/** finds the zeros of a function, given two starting points (which must
+ * have opposite signs */
+function bisect(f, a, b, parameters) {
+ parameters = parameters || {};
+ const maxIterations = parameters.maxIterations || 100;
+ const tolerance = parameters.tolerance || 1e-10;
+ const fA = f(a);
+ const fB = f(b);
+ let delta = b - a;
+
+ if (fA * fB > 0) {
+ throw 'Initial bisect points must have opposite signs';
+ }
+
+ if (fA === 0) return a;
+ if (fB === 0) return b;
+
+ for (let i = 0; i < maxIterations; ++i) {
+ delta /= 2;
+ const mid = a + delta;
+ const fMid = f(mid);
+
+ if (fMid * fA >= 0) {
+ a = mid;
+ }
+
+ if (Math.abs(delta) < tolerance || fMid === 0) {
+ return mid;
+ }
+ }
+ return a + delta;
+}
+
+// need some basic operations on vectors, rather than adding a dependency,
+// just define here
+function zeros(x) {
+ const r = new Array(x);
+ for (let i = 0; i < x; ++i) {
+ r[i] = 0;
+ }
+ return r;
+}
+function zerosM(x, y) {
+ return zeros(x).map(() => zeros(y));
+}
+
+function dot(a, b) {
+ let ret = 0;
+ for (let i = 0; i < a.length; ++i) {
+ ret += a[i] * b[i];
+ }
+ return ret;
+}
+
+function norm2(a) {
+ return Math.sqrt(dot(a, a));
+}
+
+function scale(ret, value, c) {
+ for (let i = 0; i < value.length; ++i) {
+ ret[i] = value[i] * c;
+ }
+}
+
+function weightedSum(ret, w1, v1, w2, v2) {
+ for (let j = 0; j < ret.length; ++j) {
+ ret[j] = w1 * v1[j] + w2 * v2[j];
+ }
+}
+
+/** minimizes a function using the downhill simplex method */
+function nelderMead(f, x0, parameters) {
+ parameters = parameters || {};
+
+ const maxIterations = parameters.maxIterations || x0.length * 200;
+ const nonZeroDelta = parameters.nonZeroDelta || 1.05;
+ const zeroDelta = parameters.zeroDelta || 0.001;
+ const minErrorDelta = parameters.minErrorDelta || 1e-6;
+ const minTolerance = parameters.minErrorDelta || 1e-5;
+ const rho = parameters.rho !== undefined ? parameters.rho : 1;
+ const chi = parameters.chi !== undefined ? parameters.chi : 2;
+ const psi = parameters.psi !== undefined ? parameters.psi : -0.5;
+ const sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5;
+ let maxDiff;
+
+ // initialize simplex.
+ const N = x0.length;
+ const simplex = new Array(N + 1);
+ simplex[0] = x0;
+ simplex[0].fx = f(x0);
+ simplex[0].id = 0;
+ for (let i = 0; i < N; ++i) {
+ const point = x0.slice();
+ point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
+ simplex[i + 1] = point;
+ simplex[i + 1].fx = f(point);
+ simplex[i + 1].id = i + 1;
+ }
+
+ function updateSimplex(value) {
+ for (let i = 0; i < value.length; i++) {
+ simplex[N][i] = value[i];
+ }
+ simplex[N].fx = value.fx;
+ }
+
+ const sortOrder = (a, b) => a.fx - b.fx;
+
+ const centroid = x0.slice();
+ const reflected = x0.slice();
+ const contracted = x0.slice();
+ const expanded = x0.slice();
+
+ for (let iteration = 0; iteration < maxIterations; ++iteration) {
+ simplex.sort(sortOrder);
+
+ if (parameters.history) {
+ // copy the simplex (since later iterations will mutate) and
+ // sort it to have a consistent order between iterations
+ const sortedSimplex = simplex.map((x) => {
+ const state = x.slice();
+ state.fx = x.fx;
+ state.id = x.id;
+ return state;
+ });
+ sortedSimplex.sort((a, b) => a.id - b.id);
+
+ parameters.history.push({
+ x: simplex[0].slice(),
+ fx: simplex[0].fx,
+ simplex: sortedSimplex,
+ });
+ }
+
+ maxDiff = 0;
+ for (let i = 0; i < N; ++i) {
+ maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
+ }
+
+ if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
+ break;
+ }
+
+ // compute the centroid of all but the worst point in the simplex
+ for (let i = 0; i < N; ++i) {
+ centroid[i] = 0;
+ for (let j = 0; j < N; ++j) {
+ centroid[i] += simplex[j][i];
+ }
+ centroid[i] /= N;
+ }
+
+ // reflect the worst point past the centroid and compute loss at reflected
+ // point
+ const worst = simplex[N];
+ weightedSum(reflected, 1 + rho, centroid, -rho, worst);
+ reflected.fx = f(reflected);
+
+ // if the reflected point is the best seen, then possibly expand
+ if (reflected.fx < simplex[0].fx) {
+ weightedSum(expanded, 1 + chi, centroid, -chi, worst);
+ expanded.fx = f(expanded);
+ if (expanded.fx < reflected.fx) {
+ updateSimplex(expanded);
+ } else {
+ updateSimplex(reflected);
+ }
+ }
+
+ // if the reflected point is worse than the second worst, we need to
+ // contract
+ else if (reflected.fx >= simplex[N - 1].fx) {
+ let shouldReduce = false;
+
+ if (reflected.fx > worst.fx) {
+ // do an inside contraction
+ weightedSum(contracted, 1 + psi, centroid, -psi, worst);
+ contracted.fx = f(contracted);
+ if (contracted.fx < worst.fx) {
+ updateSimplex(contracted);
+ } else {
+ shouldReduce = true;
+ }
+ } else {
+ // do an outside contraction
+ weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
+ contracted.fx = f(contracted);
+ if (contracted.fx < reflected.fx) {
+ updateSimplex(contracted);
+ } else {
+ shouldReduce = true;
+ }
+ }
+
+ if (shouldReduce) {
+ // if we don't contract here, we're done
+ if (sigma >= 1) break;
+
+ // do a reduction
+ for (let i = 1; i < simplex.length; ++i) {
+ weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
+ simplex[i].fx = f(simplex[i]);
+ }
+ }
+ } else {
+ updateSimplex(reflected);
+ }
+ }
+
+ simplex.sort(sortOrder);
+ return { fx: simplex[0].fx, x: simplex[0] };
+}
+
+/// searches along line 'pk' for a point that satifies the wolfe conditions
+/// See 'Numerical Optimization' by Nocedal and Wright p59-60
+/// f : objective function
+/// pk : search direction
+/// current: object containing current gradient/loss
+/// next: output: contains next gradient/loss
+/// returns a: step size taken
+function wolfeLineSearch(f, pk, current, next, a, c1, c2) {
+ const phi0 = current.fx;
+ const phiPrime0 = dot(current.fxprime, pk);
+ let phi = phi0;
+ let phi_old = phi0;
+ let phiPrime = phiPrime0;
+ let a0 = 0;
+
+ a = a || 1;
+ c1 = c1 || 1e-6;
+ c2 = c2 || 0.1;
+
+ function zoom(a_lo, a_high, phi_lo) {
+ for (let iteration = 0; iteration < 16; ++iteration) {
+ a = (a_lo + a_high) / 2;
+ weightedSum(next.x, 1.0, current.x, a, pk);
+ phi = next.fx = f(next.x, next.fxprime);
+ phiPrime = dot(next.fxprime, pk);
+
+ if (phi > phi0 + c1 * a * phiPrime0 || phi >= phi_lo) {
+ a_high = a;
+ } else {
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
+ return a;
+ }
+
+ if (phiPrime * (a_high - a_lo) >= 0) {
+ a_high = a_lo;
+ }
+
+ a_lo = a;
+ phi_lo = phi;
+ }
+ }
+
+ return 0;
+ }
+
+ for (let iteration = 0; iteration < 10; ++iteration) {
+ weightedSum(next.x, 1.0, current.x, a, pk);
+ phi = next.fx = f(next.x, next.fxprime);
+ phiPrime = dot(next.fxprime, pk);
+ if (phi > phi0 + c1 * a * phiPrime0 || (iteration && phi >= phi_old)) {
+ return zoom(a0, a, phi_old);
+ }
+
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
+ return a;
+ }
+
+ if (phiPrime >= 0) {
+ return zoom(a, a0, phi);
+ }
+
+ phi_old = phi;
+ a0 = a;
+ a *= 2;
+ }
+
+ return a;
+}
+
+function conjugateGradient(f, initial, params) {
+ // allocate all memory up front here, keep out of the loop for perfomance
+ // reasons
+ let current = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
+ let next = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
+ const yk = initial.slice();
+ let pk;
+ let temp;
+ let a = 1;
+ let maxIterations;
+
+ params = params || {};
+ maxIterations = params.maxIterations || initial.length * 20;
+
+ current.fx = f(current.x, current.fxprime);
+ pk = current.fxprime.slice();
+ scale(pk, current.fxprime, -1);
+
+ for (let i = 0; i < maxIterations; ++i) {
+ a = wolfeLineSearch(f, pk, current, next, a);
+
+ // todo: history in wrong spot?
+ if (params.history) {
+ params.history.push({
+ x: current.x.slice(),
+ fx: current.fx,
+ fxprime: current.fxprime.slice(),
+ alpha: a,
+ });
+ }
+
+ if (!a) {
+ // faiiled to find point that satifies wolfe conditions.
+ // reset direction for next iteration
+ scale(pk, current.fxprime, -1);
+ } else {
+ // update direction using Polak–Ribiere CG method
+ weightedSum(yk, 1, next.fxprime, -1, current.fxprime);
+
+ const delta_k = dot(current.fxprime, current.fxprime);
+ const beta_k = Math.max(0, dot(yk, next.fxprime) / delta_k);
+
+ weightedSum(pk, beta_k, pk, -1, next.fxprime);
+
+ temp = current;
+ current = next;
+ next = temp;
+ }
+
+ if (norm2(current.fxprime) <= 1e-5) {
+ break;
+ }
+ }
+
+ if (params.history) {
+ params.history.push({
+ x: current.x.slice(),
+ fx: current.fx,
+ fxprime: current.fxprime.slice(),
+ alpha: a,
+ });
+ }
+
+ return current;
+}
+
+/**
+ * given a list of set objects, and their corresponding overlaps
+ * updates the (x, y, radius) attribute on each set such that their positions
+ * roughly correspond to the desired overlaps
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+function venn(sets, parameters = {}) {
+ parameters.maxIterations = parameters.maxIterations || 500;
+
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
+ const loss = parameters.lossFunction || lossFunction;
+
+ // add in missing pairwise areas as having 0 size
+ const areas = addMissingAreas(sets, parameters);
+
+ // initial layout is done greedily
+ const circles = initialLayout(areas, parameters);
+
+ // transform x/y coordinates to a vector to optimize
+ const setids = Object.keys(circles);
+ /** @type {number[]} */
+ const initial = [];
+ for (const setid of setids) {
+ initial.push(circles[setid].x);
+ initial.push(circles[setid].y);
+ }
+
+ // optimize initial layout from our loss function
+ const solution = nelderMead(
+ (values) => {
+ const current = {};
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ current[setid] = {
+ x: values[2 * i],
+ y: values[2 * i + 1],
+ radius: circles[setid].radius,
+ // size : circles[setid].size
+ };
+ }
+ return loss(current, areas);
+ },
+ initial,
+ parameters
+ );
+
+ // transform solution vector back to x/y points
+ const positions = solution.x;
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ circles[setid].x = positions[2 * i];
+ circles[setid].y = positions[2 * i + 1];
+ }
+
+ return circles;
+}
+
+const SMALL = 1e-10;
+
+/**
+ * Returns the distance necessary for two circles of radius r1 + r2 to
+ * have the overlap area 'overlap'
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} overlap
+ * @returns {number}
+ */
+function distanceFromIntersectArea(r1, r2, overlap) {
+ // handle complete overlapped circles
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
+ return Math.abs(r1 - r2);
+ }
+
+ return bisect((distance) => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
+}
+
+/**
+ * Missing pair-wise intersection area data can cause problems:
+ * treating as an unknown means that sets will be laid out overlapping,
+ * which isn't what people expect. To reflect that we want disjoint sets
+ * here, set the overlap to 0 for all missing pairwise set intersections
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {ReadonlyArray<{sets: ReadonlyArray, size: number}>}
+ */
+function addMissingAreas(areas, parameters = {}) {
+ const distinct = parameters.distinct;
+ const r = areas.map((s) => Object.assign({}, s));
+
+ function toKey(arr) {
+ return arr.join(';');
+ }
+
+ if (distinct) {
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
+ /** @types Map */
+ const count = new Map();
+ for (const area of r) {
+ for (let i = 0; i < area.sets.length; i++) {
+ const si = String(area.sets[i]);
+ count.set(si, area.size + (count.get(si) || 0));
+ for (let j = i + 1; j < area.sets.length; j++) {
+ const sj = String(area.sets[j]);
+ const k1 = `${si};${sj}`;
+ const k2 = `${sj};${si}`;
+ count.set(k1, area.size + (count.get(k1) || 0));
+ count.set(k2, area.size + (count.get(k2) || 0));
+ }
+ }
+ }
+ for (const area of r) {
+ if (area.sets.length < 3) {
+ area.size = count.get(toKey(area.sets));
+ }
+ }
+ }
+
+ // two circle intersections that aren't defined
+ const ids = [];
+
+ /** @type {Set} */
+ const pairs = new Set();
+ for (const area of r) {
+ if (area.sets.length === 1) {
+ ids.push(area.sets[0]);
+ } else if (area.sets.length === 2) {
+ const a = area.sets[0];
+ const b = area.sets[1];
+ pairs.add(toKey(area.sets));
+ pairs.add(toKey([b, a]));
+ }
+ }
+
+ ids.sort((a, b) => (a === b ? 0 : a < b ? -1 : +1));
+
+ for (let i = 0; i < ids.length; ++i) {
+ const a = ids[i];
+ for (let j = i + 1; j < ids.length; ++j) {
+ const b = ids[j];
+ if (!pairs.has(toKey([a, b]))) {
+ r.push({ sets: [a, b], size: 0 });
+ }
+ }
+ }
+ return r;
+}
+
+/**
+ * Returns two matrices, one of the euclidean distances between the sets
+ * and the other indicating if there are subset or disjoint set relationships
+ * @param {ReadonlyArray<{sets: ReadonlyArray}>} areas
+ * @param {ReadonlyArray<{size: number}>} sets
+ * @param {ReadonlyArray} setids
+ */
+function getDistanceMatrices(areas, sets, setids) {
+ // initialize an empty distance matrix between all the points
+ /**
+ * @type {number[][]}
+ */
+ const distances = zerosM(sets.length, sets.length);
+ /**
+ * @type {number[][]}
+ */
+ const constraints = zerosM(sets.length, sets.length);
+
+ // compute required distances between all the sets such that
+ // the areas match
+ areas
+ .filter((x) => x.sets.length === 2)
+ .forEach((current) => {
+ const left = setids[current.sets[0]];
+ const right = setids[current.sets[1]];
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
+
+ distances[left][right] = distances[right][left] = distance;
+
+ // also update constraints to indicate if its a subset or disjoint
+ // relationship
+ let c = 0;
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
+ c = 1;
+ } else if (current.size <= 1e-10) {
+ c = -1;
+ }
+ constraints[left][right] = constraints[right][left] = c;
+ });
+
+ return { distances, constraints };
+}
+
+/// computes the gradient and loss simultaneously for our constrained MDS optimizer
+function constrainedMDSGradient(x, fxprime, distances, constraints) {
+ for (let i = 0; i < fxprime.length; ++i) {
+ fxprime[i] = 0;
+ }
+
+ let loss = 0;
+ for (let i = 0; i < distances.length; ++i) {
+ const xi = x[2 * i];
+ const yi = x[2 * i + 1];
+ for (let j = i + 1; j < distances.length; ++j) {
+ const xj = x[2 * j];
+ const yj = x[2 * j + 1];
+ const dij = distances[i][j];
+ const constraint = constraints[i][j];
+
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
+ const distance = Math.sqrt(squaredDistance);
+ const delta = squaredDistance - dij * dij;
+
+ if ((constraint > 0 && distance <= dij) || (constraint < 0 && distance >= dij)) {
+ continue;
+ }
+
+ loss += 2 * delta * delta;
+
+ fxprime[2 * i] += 4 * delta * (xi - xj);
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
+
+ fxprime[2 * j] += 4 * delta * (xj - xi);
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
+ }
+ }
+ return loss;
+}
+
+/**
+ * takes the best working variant of either constrained MDS or greedy
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ */
+function bestInitialLayout(areas, params = {}) {
+ let initial = greedyLayout(areas, params);
+ const loss = params.lossFunction || lossFunction;
+
+ // greedylayout is sufficient for all 2/3 circle cases. try out
+ // constrained MDS for higher order problems, take its output
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
+ // since it axis aligns)
+ if (areas.length >= 8) {
+ const constrained = constrainedMDSLayout(areas, params);
+ const constrainedLoss = loss(constrained, areas);
+ const greedyLoss = loss(initial, areas);
+
+ if (constrainedLoss + 1e-8 < greedyLoss) {
+ initial = constrained;
+ }
+ }
+ return initial;
+}
+
+/**
+ * use the constrained MDS variant to generate an initial layout
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+function constrainedMDSLayout(areas, params = {}) {
+ const restarts = params.restarts || 10;
+
+ // bidirectionally map sets to a rowid (so we can create a matrix)
+ const sets = [];
+ const setids = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ setids[area.sets[0]] = sets.length;
+ sets.push(area);
+ }
+ }
+
+ let { distances, constraints } = getDistanceMatrices(areas, sets, setids);
+
+ // keep distances bounded, things get messed up otherwise.
+ // TODO: proper preconditioner?
+ const norm = norm2(distances.map(norm2)) / distances.length;
+ distances = distances.map((row) => row.map((value) => value / norm));
+
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
+
+ let best = null;
+ for (let i = 0; i < restarts; ++i) {
+ const initial = zeros(distances.length * 2).map(Math.random);
+
+ const current = conjugateGradient(obj, initial, params);
+ if (!best || current.fx < best.fx) {
+ best = current;
+ }
+ }
+
+ const positions = best.x;
+
+ // translate rows back to (x,y,radius) coordinates
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ for (let i = 0; i < sets.length; ++i) {
+ const set = sets[i];
+ circles[set.sets[0]] = {
+ x: positions[2 * i] * norm,
+ y: positions[2 * i + 1] * norm,
+ radius: Math.sqrt(set.size / Math.PI),
+ };
+ }
+
+ if (params.history) {
+ for (const h of params.history) {
+ scale(h.x, norm);
+ }
+ }
+ return circles;
+}
+
+/**
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
+ * least overlapped, attempting to position each new set such that the
+ * overlapping areas to already positioned sets are basically right
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray}>} areas
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+function greedyLayout(areas, params) {
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
+
+ // define a circle for each set
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
+ const setOverlaps = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ const set = area.sets[0];
+ circles[set] = {
+ x: 1e10,
+ y: 1e10,
+ rowid: circles.length,
+ size: area.size,
+ radius: Math.sqrt(area.size / Math.PI),
+ };
+ setOverlaps[set] = [];
+ }
+ }
+
+ areas = areas.filter((a) => a.sets.length === 2);
+
+ // map each set to a list of all the other sets that overlap it
+ for (const current of areas) {
+ let weight = current.weight != null ? current.weight : 1.0;
+ const left = current.sets[0];
+ const right = current.sets[1];
+
+ // completely overlapped circles shouldn't be positioned early here
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
+ weight = 0;
+ }
+
+ setOverlaps[left].push({ set: right, size: current.size, weight });
+ setOverlaps[right].push({ set: left, size: current.size, weight });
+ }
+
+ // get list of most overlapped sets
+ const mostOverlapped = [];
+ Object.keys(setOverlaps).forEach((set) => {
+ let size = 0;
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
+ }
+
+ mostOverlapped.push({ set, size });
+ });
+
+ // sort by size desc
+ function sortOrder(a, b) {
+ return b.size - a.size;
+ }
+ mostOverlapped.sort(sortOrder);
+
+ // keep track of what sets have been laid out
+ const positioned = {};
+ function isPositioned(element) {
+ return element.set in positioned;
+ }
+
+ /**
+ * adds a point to the output
+ * @param {{x: number, y: number}} point
+ * @param {number} index
+ */
+ function positionSet(point, index) {
+ circles[index].x = point.x;
+ circles[index].y = point.y;
+ positioned[index] = true;
+ }
+
+ // add most overlapped set at (0,0)
+ positionSet({ x: 0, y: 0 }, mostOverlapped[0].set);
+
+ // get distances between all points. TODO, necessary?
+ // answer: probably not
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
+ for (let i = 1; i < mostOverlapped.length; ++i) {
+ const setIndex = mostOverlapped[i].set;
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
+ const set = circles[setIndex];
+ overlap.sort(sortOrder);
+
+ if (overlap.length === 0) {
+ // this shouldn't happen anymore with addMissingAreas
+ throw 'ERROR: missing pairwise overlap information';
+ }
+
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (var j = 0; j < overlap.length; ++j) {
+ // get appropriate distance from most overlapped already added set
+ const p1 = circles[overlap[j].set];
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
+
+ // sample positions at 90 degrees for maximum aesthetics
+ points.push({ x: p1.x + d1, y: p1.y });
+ points.push({ x: p1.x - d1, y: p1.y });
+ points.push({ y: p1.y + d1, x: p1.x });
+ points.push({ y: p1.y - d1, x: p1.x });
+
+ // if we have at least 2 overlaps, then figure out where the
+ // set should be positioned analytically and try those too
+ for (let k = j + 1; k < overlap.length; ++k) {
+ const p2 = circles[overlap[k].set];
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
+
+ const extraPoints = circleCircleIntersection(
+ { x: p1.x, y: p1.y, radius: d1 },
+ { x: p2.x, y: p2.y, radius: d2 }
+ );
+ points.push(...extraPoints);
+ }
+ }
+
+ // we have some candidate positions for the set, examine loss
+ // at each position to figure out where to put it at
+ let bestLoss = 1e50;
+ let bestPoint = points[0];
+ for (const point of points) {
+ circles[setIndex].x = point.x;
+ circles[setIndex].y = point.y;
+ const localLoss = loss(circles, areas);
+ if (localLoss < bestLoss) {
+ bestLoss = localLoss;
+ bestPoint = point;
+ }
+ }
+
+ positionSet(bestPoint, setIndex);
+ }
+
+ return circles;
+}
+
+/**
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
+ * the distance from the actual overlaps to the desired overlaps. Note that
+ * this method ignores overlaps of more than 2 circles
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray, weight?: number}>} overlaps
+ * @returns {number}
+ */
+function lossFunction(circles, overlaps) {
+ let output = 0;
+
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
+ }
+
+ const weight = area.weight != null ? area.weight : 1.0;
+ output += weight * (overlap - area.size) * (overlap - area.size);
+ }
+
+ return output;
+}
+
+function logRatioLossFunction(circles, overlaps) {
+ let output = 0;
+
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
+ }
+
+ const weight = area.weight != null ? area.weight : 1.0;
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
+ output += weight * differenceFromIdeal * differenceFromIdeal;
+ }
+
+ return output;
+}
+
+/**
+ * orientates a bunch of circles to point in orientation
+ * @param {{x :number, y: number, radius: number}[]} circles
+ * @param {number | undefined} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ */
+function orientateCircles(circles, orientation, orientationOrder) {
+ if (orientationOrder == null) {
+ circles.sort((a, b) => b.radius - a.radius);
+ } else {
+ circles.sort(orientationOrder);
+ }
+
+ // shift circles so largest circle is at (0, 0)
+ if (circles.length > 0) {
+ const largestX = circles[0].x;
+ const largestY = circles[0].y;
+
+ for (const circle of circles) {
+ circle.x -= largestX;
+ circle.y -= largestY;
+ }
+ }
+
+ if (circles.length === 2) {
+ // if the second circle is a subset of the first, arrange so that
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
+ const dist = distance(circles[0], circles[1]);
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
+ circles[1].y = circles[0].y;
+ }
+ }
+
+ // rotate circles so that second largest is at an angle of 'orientation'
+ // from largest
+ if (circles.length > 1) {
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+
+ for (const circle of circles) {
+ const x = circle.x;
+ const y = circle.y;
+ circle.x = c * x - s * y;
+ circle.y = s * x + c * y;
+ }
+ }
+
+ // mirror solution if third solution is above plane specified by
+ // first two circles
+ if (circles.length > 2) {
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
+ while (angle < 0) {
+ angle += 2 * Math.PI;
+ }
+ while (angle > 2 * Math.PI) {
+ angle -= 2 * Math.PI;
+ }
+ if (angle > Math.PI) {
+ const slope = circles[1].y / (1e-10 + circles[1].x);
+ for (const circle of circles) {
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
+ circle.x = 2 * d - circle.x;
+ circle.y = 2 * d * slope - circle.y;
+ }
+ }
+ }
+}
+
+/**
+ *
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {{x: number, y: number, radius: number}[][]}
+ */
+function disjointCluster(circles) {
+ // union-find clustering to get disjoint sets
+ circles.forEach((circle) => {
+ circle.parent = circle;
+ });
+
+ // path compression step in union find
+ function find(circle) {
+ if (circle.parent !== circle) {
+ circle.parent = find(circle.parent);
+ }
+ return circle.parent;
+ }
+
+ function union(x, y) {
+ const xRoot = find(x);
+ const yRoot = find(y);
+ xRoot.parent = yRoot;
+ }
+
+ // get the union of all overlapping sets
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const maxDistance = circles[i].radius + circles[j].radius;
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
+ union(circles[j], circles[i]);
+ }
+ }
+ }
+
+ // find all the disjoint clusters and group them together
+ /** @type {Map} */
+ const disjointClusters = new Map();
+ for (let i = 0; i < circles.length; ++i) {
+ const setid = find(circles[i]).parent.setid;
+ if (!disjointClusters.has(setid)) {
+ disjointClusters.set(setid, []);
+ }
+ disjointClusters.get(setid).push(circles[i]);
+ }
+
+ // cleanup bookkeeping
+ circles.forEach((circle) => {
+ delete circle.parent;
+ });
+
+ // return in more usable form
+ return Array.from(disjointClusters.values());
+}
+
+/**
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
+ */
+function getBoundingBox(circles) {
+ const minMax = (d) => {
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
+ return { max: hi, min: lo };
+ };
+ return { xRange: minMax('x'), yRange: minMax('y') };
+}
+
+/**
+ *
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {undefined | number} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+function normalizeSolution(solution, orientation, orientationOrder) {
+ if (orientation == null) {
+ orientation = Math.PI / 2;
+ }
+
+ // work with a list instead of a dictionary, and take a copy so we
+ // don't mutate input
+ let circles = fromObjectNotation(solution).map((d) => Object.assign({}, d));
+
+ // get all the disjoint clusters
+ const clusters = disjointCluster(circles);
+
+ // orientate all disjoint sets, get sizes
+ for (const cluster of clusters) {
+ orientateCircles(cluster, orientation, orientationOrder);
+ const bounds = getBoundingBox(cluster);
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
+ cluster.bounds = bounds;
+ }
+ clusters.sort((a, b) => b.size - a.size);
+
+ // orientate the largest at 0,0, and get the bounds
+ circles = clusters[0];
+ let returnBounds = circles.bounds;
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
+
+ /**
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
+ * @param {boolean} right
+ * @param {boolean} bottom
+ */
+ function addCluster(cluster, right, bottom) {
+ if (!cluster) {
+ return;
+ }
+
+ const bounds = cluster.bounds;
+ /** @type {number} */
+ let xOffset;
+ /** @type {number} */
+ let yOffset;
+
+ if (right) {
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
+ } else {
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
+ const centreing =
+ (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
+ if (centreing < 0) {
+ xOffset += centreing;
+ }
+ }
+
+ if (bottom) {
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
+ } else {
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
+ const centreing =
+ (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
+ if (centreing < 0) {
+ yOffset += centreing;
+ }
+ }
+
+ for (const c of cluster) {
+ c.x += xOffset;
+ c.y += yOffset;
+ circles.push(c);
+ }
+ }
+
+ let index = 1;
+ while (index < clusters.length) {
+ addCluster(clusters[index], true, false);
+ addCluster(clusters[index + 1], false, true);
+ addCluster(clusters[index + 2], true, true);
+ index += 3;
+
+ // have one cluster (in top left). lay out next three relative
+ // to it in a grid
+ returnBounds = getBoundingBox(circles);
+ }
+
+ // convert back to solution form
+ return toObjectNotation(circles);
+}
+
+/**
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
+ * a rectangle of width/height - with padding around the borders. also
+ * centers the diagram in the available space at the same time.
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {number} width
+ * @param {number} height
+ * @param {number} padding
+ * @param {boolean} scaleToFit
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+function scaleSolution(solution, width, height, padding, scaleToFit) {
+ const circles = fromObjectNotation(solution);
+
+ width -= 2 * padding;
+ height -= 2 * padding;
+
+ const { xRange, yRange } = getBoundingBox(circles);
+
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
+ console.log('not scaling solution: zero size detected');
+ return solution;
+ }
+
+ /** @type {number} */
+ let xScaling;
+ /** @type {number} */
+ let yScaling;
+ if (scaleToFit) {
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
+ xScaling = width / toScaleDiameter;
+ yScaling = height / toScaleDiameter;
+ } else {
+ xScaling = width / (xRange.max - xRange.min);
+ yScaling = height / (yRange.max - yRange.min);
+ }
+
+ const scaling = Math.min(yScaling, xScaling);
+ // while we're at it, center the diagram too
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
+
+ return toObjectNotation(
+ circles.map((circle) => ({
+ radius: scaling * circle.radius,
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
+ setid: circle.setid,
+ }))
+ );
+}
+
+/**
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
+ */
+function toObjectNotation(circles) {
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
+ const r = {};
+ for (const circle of circles) {
+ r[circle.setid] = circle;
+ }
+ return r;
+}
+/**
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
+ */
+function fromObjectNotation(solution) {
+ const setids = Object.keys(solution);
+ return setids.map((id) => Object.assign(solution[id], { setid: id }));
+}
+
+/**
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
+ *
+ * `colourScheme: Array`
+ * A list of color values to be applied when coloring diagram circles.
+ *
+ * `symmetricalTextCentre: Boolean`
+ * Whether to symmetrically center each circle's text horizontally and vertically.
+ * Defaults to `false`.
+ *
+ * `textFill: String`
+ * The color to be applied to the text within each circle.
+ *
+ * @param {object} options
+ */
+function VennDiagram(options = {}) {
+ let useViewBox = false,
+ width = 600,
+ height = 350,
+ padding = 15,
+ duration = 1000,
+ orientation = Math.PI / 2,
+ normalize = true,
+ scaleToFit = null,
+ wrap = true,
+ styled = true,
+ fontSize = null,
+ orientationOrder = null,
+ distinct = false,
+ round = null,
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
+ // mimic the behaviour of d3.scale.category10 from the previous
+ // version of d3
+ colourMap = {},
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
+ // since we can support older versions of d3 as long as we don't force this,
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
+ colourScheme =
+ options && options.colourScheme
+ ? options.colourScheme
+ : options && options.colorScheme
+ ? options.colorScheme
+ : [
+ '#1f77b4',
+ '#ff7f0e',
+ '#2ca02c',
+ '#d62728',
+ '#9467bd',
+ '#8c564b',
+ '#e377c2',
+ '#7f7f7f',
+ '#bcbd22',
+ '#17becf',
+ ],
+ colourIndex = 0,
+ colours = function (key) {
+ if (key in colourMap) {
+ return colourMap[key];
+ }
+ var ret = (colourMap[key] = colourScheme[colourIndex]);
+ colourIndex += 1;
+ if (colourIndex >= colourScheme.length) {
+ colourIndex = 0;
+ }
+ return ret;
+ },
+ layoutFunction = venn,
+ loss = lossFunction;
+
+ function chart(selection) {
+ let data = selection.datum();
+
+ // handle 0-sized sets by removing from input
+ const toRemove = new Set();
+ data.forEach((datum) => {
+ if (datum.size == 0 && datum.sets.length == 1) {
+ toRemove.add(datum.sets[0]);
+ }
+ });
+ data = data.filter((datum) => !datum.sets.some((set) => toRemove.has(set)));
+
+ let circles = {};
+ let textCentres = {};
+
+ if (data.length > 0) {
+ let solution = layoutFunction(data, { lossFunction: loss, distinct });
+
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+ }
+
+ // Figure out the current label for each set. These can change
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
+ const labels = {};
+ data.forEach((datum) => {
+ if (datum.label) {
+ labels[datum.sets] = datum.label;
+ }
+ });
+
+ function label(d) {
+ if (d.sets in labels) {
+ return labels[d.sets];
+ }
+ if (d.sets.length == 1) {
+ return '' + d.sets[0];
+ }
+ }
+
+ // create svg if not already existing
+ selection.selectAll('svg').data([circles]).enter().append('svg');
+
+ const svg = selection.select('svg');
+
+ if (useViewBox) {
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
+ } else {
+ svg.attr('width', width).attr('height', height);
+ }
+
+ // to properly transition intersection areas, we need the
+ // previous circles locations. load from elements
+ const previous = {};
+ let hasPrevious = false;
+ svg.selectAll('.venn-area path').each(function (d) {
+ const path = this.getAttribute('d');
+ if (d.sets.length == 1 && path && !distinct) {
+ hasPrevious = true;
+ previous[d.sets[0]] = circleFromPath(path);
+ }
+ });
+ // interpolate intersection area paths between previous and
+ // current paths
+ function pathTween(d) {
+ return (t) => {
+ const c = d.sets.map((set) => {
+ let start = previous[set];
+ let end = circles[set];
+ if (!start) {
+ start = { x: width / 2, y: height / 2, radius: 1 };
+ }
+ if (!end) {
+ end = { x: width / 2, y: height / 2, radius: 1 };
+ }
+ return {
+ x: start.x * (1 - t) + end.x * t,
+ y: start.y * (1 - t) + end.y * t,
+ radius: start.radius * (1 - t) + end.radius * t,
+ };
+ });
+ return intersectionAreaPath(c, round);
+ };
+ }
+
+ // update data, joining on the set ids
+ const nodes = svg.selectAll('.venn-area').data(data, (d) => d.sets);
+
+ // create new nodes
+ const enter = nodes
+ .enter()
+ .append('g')
+ .attr(
+ 'class',
+ (d) =>
+ `venn-area venn-${d.sets.length == 1 ? 'circle' : 'intersection'}${
+ d.colour || d.color ? ' venn-coloured' : ''
+ }`
+ )
+ .attr('data-venn-sets', (d) => d.sets.join('_'));
+
+ const enterPath = enter.append('path');
+ const enterText = enter
+ .append('text')
+ .attr('class', 'label')
+ .text((d) => label(d))
+ .attr('text-anchor', 'middle')
+ .attr('dy', '.35em')
+ .attr('x', width / 2)
+ .attr('y', height / 2);
+
+ // apply minimal style if wanted
+ if (styled) {
+ enterPath
+ .style('fill-opacity', '0')
+ .filter((d) => d.sets.length == 1)
+ .style('fill', (d) => (d.colour ? d.colour : d.color ? d.color : colours(d.sets)))
+ .style('fill-opacity', '.25');
+
+ enterText.style('fill', (d) => {
+ if (d.colour || d.color) {
+ return '#FFF';
+ }
+ if (options.textFill) {
+ return options.textFill;
+ }
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
+ });
+ }
+
+ function asTransition(s) {
+ if (typeof s.transition === 'function') {
+ return s.transition('venn').duration(duration);
+ }
+ return s;
+ }
+
+ // update existing, using pathTween if necessary
+ let update = selection;
+ if (hasPrevious && typeof update.transition === 'function') {
+ update = asTransition(selection);
+ update.selectAll('path').attrTween('d', pathTween);
+ } else {
+ update.selectAll('path').attr('d', (d) => intersectionAreaPath(d.sets.map((set) => circles[set])), round);
+ }
+
+ const updateText = update
+ .selectAll('text')
+ .filter((d) => d.sets in textCentres)
+ .text((d) => label(d))
+ .attr('x', (d) => Math.floor(textCentres[d.sets].x))
+ .attr('y', (d) => Math.floor(textCentres[d.sets].y));
+
+ if (wrap) {
+ if (hasPrevious) {
+ // d3 4.0 uses 'on' for events on transitions,
+ // but d3 3.0 used 'each' instead. switch appropriately
+ if ('on' in updateText) {
+ updateText.on('end', wrapText(circles, label));
+ } else {
+ updateText.each('end', wrapText(circles, label));
+ }
+ } else {
+ updateText.each(wrapText(circles, label));
+ }
+ }
+
+ // remove old
+ const exit = asTransition(nodes.exit()).remove();
+ if (typeof nodes.transition === 'function') {
+ exit.selectAll('path').attrTween('d', pathTween);
+ }
+
+ const exitText = exit
+ .selectAll('text')
+ .attr('x', width / 2)
+ .attr('y', height / 2);
+
+ // if we've been passed a fontSize explicitly, use it to
+ // transition
+ if (fontSize !== null) {
+ enterText.style('font-size', '0px');
+ updateText.style('font-size', fontSize);
+ exitText.style('font-size', '0px');
+ }
+
+ return { circles, textCentres, nodes, enter, update, exit };
+ }
+
+ chart.wrap = function (_) {
+ if (!arguments.length) return wrap;
+ wrap = _;
+ return chart;
+ };
+
+ chart.useViewBox = function () {
+ useViewBox = true;
+ return chart;
+ };
+
+ chart.width = function (_) {
+ if (!arguments.length) return width;
+ width = _;
+ return chart;
+ };
+
+ chart.height = function (_) {
+ if (!arguments.length) return height;
+ height = _;
+ return chart;
+ };
+
+ chart.padding = function (_) {
+ if (!arguments.length) return padding;
+ padding = _;
+ return chart;
+ };
+
+ chart.distinct = function (_) {
+ if (!arguments.length) return distinct;
+ distinct = _;
+ return chart;
+ };
+
+ chart.colours = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+
+ chart.colors = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+
+ chart.fontSize = function (_) {
+ if (!arguments.length) return fontSize;
+ fontSize = _;
+ return chart;
+ };
+
+ chart.round = function (_) {
+ if (!arguments.length) return round;
+ round = _;
+ return chart;
+ };
+
+ chart.duration = function (_) {
+ if (!arguments.length) return duration;
+ duration = _;
+ return chart;
+ };
+
+ chart.layoutFunction = function (_) {
+ if (!arguments.length) return layoutFunction;
+ layoutFunction = _;
+ return chart;
+ };
+
+ chart.normalize = function (_) {
+ if (!arguments.length) return normalize;
+ normalize = _;
+ return chart;
+ };
+
+ chart.scaleToFit = function (_) {
+ if (!arguments.length) return scaleToFit;
+ scaleToFit = _;
+ return chart;
+ };
+
+ chart.styled = function (_) {
+ if (!arguments.length) return styled;
+ styled = _;
+ return chart;
+ };
+
+ chart.orientation = function (_) {
+ if (!arguments.length) return orientation;
+ orientation = _;
+ return chart;
+ };
+
+ chart.orientationOrder = function (_) {
+ if (!arguments.length) return orientationOrder;
+ orientationOrder = _;
+ return chart;
+ };
+
+ chart.lossFunction = function (_) {
+ if (!arguments.length) return loss;
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
+ return chart;
+ };
+
+ return chart;
+}
+
+// sometimes text doesn't fit inside the circle, if thats the case lets wrap
+// the text here such that it fits
+// todo: looks like this might be merged into d3 (
+// https://github.com/mbostock/d3/issues/1642),
+// also worth checking out is
+// http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
+// this seems to be one of those things that should be easy but isn't
+function wrapText(circles, labeller) {
+ return function (data) {
+ const text = this;
+ const width = circles[data.sets[0]].radius || 50;
+ const label = labeller(data) || '';
+
+ const words = label.split(/\s+/).reverse();
+ const maxLines = 3;
+ const minChars = (label.length + words.length) / maxLines;
+
+ let word = words.pop();
+ let line = [word];
+ let lineNumber = 0;
+ const lineHeight = 1.1; // ems
+ text.textContent = null; // clear
+ const tspans = [];
+
+ function append(word) {
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
+ tspan.textContent = word;
+ tspans.push(tspan);
+ text.append(tspan);
+ return tspan;
+ }
+ let tspan = append(word);
+
+ while (true) {
+ word = words.pop();
+ if (!word) {
+ break;
+ }
+ line.push(word);
+ const joined = line.join(' ');
+ tspan.textContent = joined;
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
+ line.pop();
+ tspan.textContent = line.join(' ');
+ line = [word];
+ tspan = append(word);
+ lineNumber++;
+ }
+ }
+
+ const initial = 0.35 - (lineNumber * lineHeight) / 2;
+ const x = text.getAttribute('x');
+ const y = text.getAttribute('y');
+ tspans.forEach((t, i) => {
+ t.setAttribute('x', x);
+ t.setAttribute('y', y);
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
+ });
+ };
+}
+
+/**
+ *
+ * @param {{x: number, y: number}} current
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
+ * @returns {number}
+ */
+function circleMargin(current, interior, exterior) {
+ let margin = interior[0].radius - distance(interior[0], current);
+
+ for (let i = 1; i < interior.length; ++i) {
+ const m = interior[i].radius - distance(interior[i], current);
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+
+ for (let i = 0; i < exterior.length; ++i) {
+ const m = distance(exterior[i], current) - exterior[i].radius;
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+ return margin;
+}
+
+/**
+ * compute the center of some circles by maximizing the margin of
+ * the center point relative to the circles (interior) after subtracting
+ * nearby circles (exterior)
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
+ * @param {boolean} symmetricalTextCentre
+ * @returns {{x:number, y: number}}
+ */
+function computeTextCentre(interior, exterior, symmetricalTextCentre) {
+ // get an initial estimate by sampling around the interior circles
+ // and taking the point with the biggest margin
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (const c of interior) {
+ points.push({ x: c.x, y: c.y });
+ points.push({ x: c.x + c.radius / 2, y: c.y });
+ points.push({ x: c.x - c.radius / 2, y: c.y });
+ points.push({ x: c.x, y: c.y + c.radius / 2 });
+ points.push({ x: c.x, y: c.y - c.radius / 2 });
+ }
+
+ let initial = points[0];
+ let margin = circleMargin(points[0], interior, exterior);
+
+ for (let i = 1; i < points.length; ++i) {
+ const m = circleMargin(points[i], interior, exterior);
+ if (m >= margin) {
+ initial = points[i];
+ margin = m;
+ }
+ }
+
+ // maximize the margin numerically
+ const solution = nelderMead(
+ (p) => -1 * circleMargin({ x: p[0], y: p[1] }, interior, exterior),
+ [initial.x, initial.y],
+ { maxIterations: 500, minErrorDelta: 1e-10 }
+ ).x;
+
+ const ret = { x: symmetricalTextCentre ? 0 : solution[0], y: solution[1] };
+
+ // check solution, fallback as needed (happens if fully overlapped
+ // etc)
+ let valid = true;
+ for (const i of interior) {
+ if (distance(ret, i) > i.radius) {
+ valid = false;
+ break;
+ }
+ }
+
+ for (const e of exterior) {
+ if (distance(ret, e) < e.radius) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid) {
+ return ret;
+ }
+
+ if (interior.length == 1) {
+ return { x: interior[0].x, y: interior[0].y };
+ }
+ const areaStats = {};
+ intersectionArea(interior, areaStats);
+
+ if (areaStats.arcs.length === 0) {
+ return { x: 0, y: -1000, disjoint: true };
+ }
+ if (areaStats.arcs.length == 1) {
+ return { x: areaStats.arcs[0].circle.x, y: areaStats.arcs[0].circle.y };
+ }
+ if (exterior.length) {
+ // try again without other circles
+ return computeTextCentre(interior, []);
+ }
+ // take average of all the points in the intersection
+ // polygon. this should basically never happen
+ // and has some issues:
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
+ return getCenter(areaStats.arcs.map((a) => a.p1));
+}
+
+// given a dictionary of {setid : circle}, returns
+// a dictionary of setid to list of circles that completely overlap it
+function getOverlappingCircles(circles) {
+ const ret = {};
+ const circleids = Object.keys(circles);
+ for (const circleid of circleids) {
+ ret[circleid] = [];
+ }
+ for (let i = 0; i < circleids.length; i++) {
+ const ci = circleids[i];
+ const a = circles[ci];
+ for (let j = i + 1; j < circleids.length; ++j) {
+ const cj = circleids[j];
+ const b = circles[cj];
+ const d = distance(a, b);
+
+ if (d + b.radius <= a.radius + 1e-10) {
+ ret[cj].push(ci);
+ } else if (d + a.radius <= b.radius + 1e-10) {
+ ret[ci].push(cj);
+ }
+ }
+ }
+ return ret;
+}
+
+function computeTextCentres(circles, areas, symmetricalTextCentre) {
+ const ret = {};
+ const overlapped = getOverlappingCircles(circles);
+ for (let i = 0; i < areas.length; ++i) {
+ const area = areas[i].sets;
+ const areaids = {};
+ const exclude = {};
+
+ for (let j = 0; j < area.length; ++j) {
+ areaids[area[j]] = true;
+ const overlaps = overlapped[area[j]];
+ // keep track of any circles that overlap this area,
+ // and don't consider for purposes of computing the text
+ // centre
+ for (let k = 0; k < overlaps.length; ++k) {
+ exclude[overlaps[k]] = true;
+ }
+ }
+
+ const interior = [];
+ const exterior = [];
+ for (let setid in circles) {
+ if (setid in areaids) {
+ interior.push(circles[setid]);
+ } else if (!(setid in exclude)) {
+ exterior.push(circles[setid]);
+ }
+ }
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
+ ret[area] = centre;
+ if (centre.disjoint && areas[i].size > 0) {
+ console.log('WARNING: area ' + area + ' not represented on screen');
+ }
+ }
+ return ret;
+}
+
+// sorts all areas in the venn diagram, so that
+// a particular area is on top (relativeTo) - and
+// all other areas are so that the smallest areas are on top
+function sortAreas(div, relativeTo) {
+ // figure out sets that are completely overlapped by relativeTo
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
+ const exclude = new Set();
+ for (const check of relativeTo.sets) {
+ for (let setid in overlaps) {
+ const overlap = overlaps[setid];
+ for (let j = 0; j < overlap.length; ++j) {
+ if (overlap[j] == check) {
+ exclude.add(setid);
+ break;
+ }
+ }
+ }
+ }
+
+ // checks that all sets are in exclude;
+ function shouldExclude(sets) {
+ return sets.every((set) => !exclude.has(set));
+ }
+
+ // need to sort div's so that Z order is correct
+ div.selectAll('g').sort((a, b) => {
+ // highest order set intersections first
+ if (a.sets.length != b.sets.length) {
+ return a.sets.length - b.sets.length;
+ }
+
+ if (a == relativeTo) {
+ return shouldExclude(b.sets) ? -1 : 1;
+ }
+ if (b == relativeTo) {
+ return shouldExclude(a.sets) ? 1 : -1;
+ }
+
+ // finally by size
+ return b.size - a.size;
+ });
+}
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} r
+ * @returns {string}
+ */
+function circlePath(x, y, r) {
+ const ret = [];
+ ret.push('\nM', x, y);
+ ret.push('\nm', -r, 0);
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
+ return ret.join(' ');
+}
+
+/**
+ * inverse of the circlePath function, returns a circle object from an svg path
+ * @param {string} path
+ * @returns {{x: number, y: number, radius: number}}
+ */
+function circleFromPath(path) {
+ const tokens = path.split(' ');
+ return { x: Number.parseFloat(tokens[1]), y: Number.parseFloat(tokens[2]), radius: -Number.parseFloat(tokens[4]) };
+}
+
+function intersectionAreaArcs(circles) {
+ if (circles.length === 0) {
+ return [];
+ }
+ const stats = {};
+ intersectionArea(circles, stats);
+ return stats.arcs;
+}
+
+function arcsToPath(arcs, round) {
+ if (arcs.length === 0) {
+ return 'M 0 0';
+ }
+ const rFactor = Math.pow(10, round || 0);
+ const r = round != null ? (v) => Math.round(v * rFactor) / rFactor : (v) => v;
+ if (arcs.length == 1) {
+ const circle = arcs[0].circle;
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
+ }
+ // draw path around arcs
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
+ for (const arc of arcs) {
+ const radius = r(arc.circle.radius);
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
+ }
+ return ret.join(' ');
+}
+
+/**
+ * returns a svg path of the intersection area of a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {string}
+ */
+function intersectionAreaPath(circles, round) {
+ return arcsToPath(intersectionAreaArcs(circles), round);
+}
+
+function layout(data, options = {}) {
+ const {
+ lossFunction: loss,
+ layoutFunction: layout = venn,
+ normalize = true,
+ orientation = Math.PI / 2,
+ orientationOrder,
+ width = 600,
+ height = 350,
+ padding = 15,
+ scaleToFit = false,
+ symmetricalTextCentre = false,
+ distinct,
+ round = 2,
+ } = options;
+
+ let solution = layout(data, {
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
+ distinct,
+ });
+
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+
+ const circleLookup = new Map(
+ Object.keys(circles).map((set) => [
+ set,
+ {
+ set,
+ x: circles[set].x,
+ y: circles[set].y,
+ radius: circles[set].radius,
+ },
+ ])
+ );
+ const helpers = data.map((area) => {
+ const circles = area.sets.map((s) => circleLookup.get(s));
+ const arcs = intersectionAreaArcs(circles);
+ const path = arcsToPath(arcs, round);
+ return { circles, arcs, path, area, has: new Set(area.sets) };
+ });
+
+ function genDistinctPath(sets) {
+ let r = '';
+ for (const e of helpers) {
+ if (e.has.size > sets.length && sets.every((s) => e.has.has(s))) {
+ r += ' ' + e.path;
+ }
+ }
+ return r;
+ }
+
+ return helpers.map(({ circles, arcs, path, area }) => {
+ return {
+ data: area,
+ text: textCentres[area.sets],
+ circles,
+ arcs,
+ path,
+ distinctPath: path + genDistinctPath(area.sets),
+ };
+ });
+}
+
+export { VennDiagram, bestInitialLayout, circleArea, circleCircleIntersection, circleFromPath, circleOverlap, circlePath, computeTextCentre, computeTextCentres, disjointCluster, distance, distanceFromIntersectArea, greedyLayout, intersectionArea, intersectionAreaPath, layout, logRatioLossFunction, lossFunction, normalizeSolution, scaleSolution, sortAreas, venn, wrapText };
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/build/venn.js b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.js
new file mode 100644
index 0000000000000000000000000000000000000000..7cbd8c9fe834334f451a123ce4bdedb3fc8627d3
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.js
@@ -0,0 +1,2166 @@
+(function (global, factory) {
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.venn = {}));
+})(this, (function (exports) { 'use strict';
+
+ const SMALL$1 = 1e-10;
+
+ /**
+ * Returns the intersection area of a bunch of circles (where each circle
+ * is an object having an x,y and radius property)
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @param {undefined | { area?: number, arcArea?: number, polygonArea?: number, arcs?: ReadonlyArray<{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }>, innerPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+ }>, intersectionPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+ }> }} stats
+ * @returns {number}
+ */
+ function intersectionArea(circles, stats) {
+ // get all the intersection points of the circles
+ const intersectionPoints = getIntersectionPoints(circles);
+
+ // filter out points that aren't included in all the circles
+ const innerPoints = intersectionPoints.filter(p => containedInCircles(p, circles));
+ let arcArea = 0;
+ let polygonArea = 0;
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
+ const arcs = [];
+
+ // if we have intersection points that are within all the circles,
+ // then figure out the area contained by them
+ if (innerPoints.length > 1) {
+ // sort the points by angle from the center of the polygon, which lets
+ // us just iterate over points to get the edges
+ const center = getCenter(innerPoints);
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p = innerPoints[i];
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
+ }
+ innerPoints.sort((a, b) => b.angle - a.angle);
+
+ // iterate over all points, get arc between the points
+ // and update the areas
+ let p2 = innerPoints[innerPoints.length - 1];
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p1 = innerPoints[i];
+
+ // polygon area updates easily ...
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
+
+ // updating the arc area is a little more involved
+ const midPoint = {
+ x: (p1.x + p2.x) / 2,
+ y: (p1.y + p2.y) / 2
+ };
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
+ let arc = null;
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
+ // figure out the angle halfway between the two points
+ // on the current circle
+ const circle = circles[p1.parentIndex[j]];
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
+ let angleDiff = a2 - a1;
+ if (angleDiff < 0) {
+ angleDiff += 2 * Math.PI;
+ }
+
+ // and use that angle to figure out the width of the
+ // arc
+ const a = a2 - angleDiff / 2;
+ let width = distance(midPoint, {
+ x: circle.x + circle.radius * Math.sin(a),
+ y: circle.y + circle.radius * Math.cos(a)
+ });
+
+ // clamp the width to the largest is can actually be
+ // (sometimes slightly overflows because of FP errors)
+ if (width > circle.radius * 2) {
+ width = circle.radius * 2;
+ }
+
+ // pick the circle whose arc has the smallest width
+ if (arc == null || arc.width > width) {
+ arc = {
+ circle,
+ width,
+ p1,
+ p2,
+ large: width > circle.radius,
+ sweep: true
+ };
+ }
+ }
+ }
+ if (arc != null) {
+ arcs.push(arc);
+ arcArea += circleArea(arc.circle.radius, arc.width);
+ p2 = p1;
+ }
+ }
+ } else {
+ // no intersection points, is either disjoint - or is completely
+ // overlapped. figure out which by examining the smallest circle
+ let smallest = circles[0];
+ for (let i = 1; i < circles.length; ++i) {
+ if (circles[i].radius < smallest.radius) {
+ smallest = circles[i];
+ }
+ }
+
+ // make sure the smallest circle is completely contained in all
+ // the other circles
+ let disjoint = false;
+ for (let i = 0; i < circles.length; ++i) {
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
+ disjoint = true;
+ break;
+ }
+ }
+ if (disjoint) {
+ arcArea = polygonArea = 0;
+ } else {
+ arcArea = smallest.radius * smallest.radius * Math.PI;
+ arcs.push({
+ circle: smallest,
+ p1: {
+ x: smallest.x,
+ y: smallest.y + smallest.radius
+ },
+ p2: {
+ x: smallest.x - SMALL$1,
+ y: smallest.y + smallest.radius
+ },
+ width: smallest.radius * 2,
+ large: true,
+ sweep: true
+ });
+ }
+ }
+ polygonArea /= 2;
+ if (stats) {
+ stats.area = arcArea + polygonArea;
+ stats.arcArea = arcArea;
+ stats.polygonArea = polygonArea;
+ stats.arcs = arcs;
+ stats.innerPoints = innerPoints;
+ stats.intersectionPoints = intersectionPoints;
+ }
+ return arcArea + polygonArea;
+ }
+
+ /**
+ * returns whether a point is contained by all of a list of circles
+ * @param {{x: number, y: number}} point
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {boolean}
+ */
+ function containedInCircles(point, circles) {
+ return circles.every(circle => distance(point, circle) < circle.radius + SMALL$1);
+ }
+
+ /**
+ * Gets all intersection points between a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
+ */
+ function getIntersectionPoints(circles) {
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
+ const ret = [];
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
+ for (const p of intersect) {
+ p.parentIndex = [i, j];
+ ret.push(p);
+ }
+ }
+ }
+ return ret;
+ }
+
+ /**
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
+ * @param {number} r
+ * @param {number} width
+ * @returns {number}
+ **/
+ function circleArea(r, width) {
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
+ }
+
+ /**
+ * euclidean distance between two points
+ * @param {{x: number, y: number}} p1
+ * @param {{x: number, y: number}} p2
+ * @returns {number}
+ **/
+ function distance(p1, p2) {
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
+ }
+
+ /**
+ * Returns the overlap area of two circles of radius r1 and r2 - that
+ * have their centers separated by distance d. Simpler faster
+ * circle intersection for only two circles
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} d
+ * @returns {number}
+ */
+ function circleOverlap(r1, r2, d) {
+ // no overlap
+ if (d >= r1 + r2) {
+ return 0;
+ }
+
+ // completely overlapped
+ if (d <= Math.abs(r1 - r2)) {
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
+ }
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
+ return circleArea(r1, w1) + circleArea(r2, w2);
+ }
+
+ /**
+ * Given two circles (containing a x/y/radius attributes),
+ * returns the intersecting points if possible
+ * note: doesn't handle cases where there are infinitely many
+ * intersection points (circles are equivalent):, or only one intersection point
+ * @param {{x: number, y: number, radius: number}} p1
+ * @param {{x: number, y: number, radius: number}} p2
+ * @returns {ReadonlyArray<{x: number, y: number}>}
+ **/
+ function circleCircleIntersection(p1, p2) {
+ const d = distance(p1, p2);
+ const r1 = p1.radius;
+ const r2 = p2.radius;
+
+ // if to far away, or self contained - can't be done
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
+ return [];
+ }
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
+ const h = Math.sqrt(r1 * r1 - a * a);
+ const x0 = p1.x + a * (p2.x - p1.x) / d;
+ const y0 = p1.y + a * (p2.y - p1.y) / d;
+ const rx = -(p2.y - p1.y) * (h / d);
+ const ry = -(p2.x - p1.x) * (h / d);
+ return [{
+ x: x0 + rx,
+ y: y0 - ry
+ }, {
+ x: x0 - rx,
+ y: y0 + ry
+ }];
+ }
+
+ /**
+ * Returns the center of a bunch of points
+ * @param {ReadonlyArray<{x: number, y: number}>} points
+ * @returns {{x: number, y: number}}
+ */
+ function getCenter(points) {
+ const center = {
+ x: 0,
+ y: 0
+ };
+ for (const point of points) {
+ center.x += point.x;
+ center.y += point.y;
+ }
+ center.x /= points.length;
+ center.y /= points.length;
+ return center;
+ }
+
+ /** finds the zeros of a function, given two starting points (which must
+ * have opposite signs */
+ function bisect(f, a, b, parameters) {
+ parameters = parameters || {};
+ const maxIterations = parameters.maxIterations || 100;
+ const tolerance = parameters.tolerance || 1e-10;
+ const fA = f(a);
+ const fB = f(b);
+ let delta = b - a;
+ if (fA * fB > 0) {
+ throw 'Initial bisect points must have opposite signs';
+ }
+ if (fA === 0) return a;
+ if (fB === 0) return b;
+ for (let i = 0; i < maxIterations; ++i) {
+ delta /= 2;
+ const mid = a + delta;
+ const fMid = f(mid);
+ if (fMid * fA >= 0) {
+ a = mid;
+ }
+ if (Math.abs(delta) < tolerance || fMid === 0) {
+ return mid;
+ }
+ }
+ return a + delta;
+ }
+
+ // need some basic operations on vectors, rather than adding a dependency,
+ // just define here
+ function zeros(x) {
+ const r = new Array(x);
+ for (let i = 0; i < x; ++i) {
+ r[i] = 0;
+ }
+ return r;
+ }
+ function zerosM(x, y) {
+ return zeros(x).map(() => zeros(y));
+ }
+ function dot(a, b) {
+ let ret = 0;
+ for (let i = 0; i < a.length; ++i) {
+ ret += a[i] * b[i];
+ }
+ return ret;
+ }
+ function norm2(a) {
+ return Math.sqrt(dot(a, a));
+ }
+ function scale(ret, value, c) {
+ for (let i = 0; i < value.length; ++i) {
+ ret[i] = value[i] * c;
+ }
+ }
+ function weightedSum(ret, w1, v1, w2, v2) {
+ for (let j = 0; j < ret.length; ++j) {
+ ret[j] = w1 * v1[j] + w2 * v2[j];
+ }
+ }
+
+ /** minimizes a function using the downhill simplex method */
+ function nelderMead(f, x0, parameters) {
+ parameters = parameters || {};
+ const maxIterations = parameters.maxIterations || x0.length * 200;
+ const nonZeroDelta = parameters.nonZeroDelta || 1.05;
+ const zeroDelta = parameters.zeroDelta || 0.001;
+ const minErrorDelta = parameters.minErrorDelta || 1e-6;
+ const minTolerance = parameters.minErrorDelta || 1e-5;
+ const rho = parameters.rho !== undefined ? parameters.rho : 1;
+ const chi = parameters.chi !== undefined ? parameters.chi : 2;
+ const psi = parameters.psi !== undefined ? parameters.psi : -0.5;
+ const sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5;
+ let maxDiff;
+
+ // initialize simplex.
+ const N = x0.length;
+ const simplex = new Array(N + 1);
+ simplex[0] = x0;
+ simplex[0].fx = f(x0);
+ simplex[0].id = 0;
+ for (let i = 0; i < N; ++i) {
+ const point = x0.slice();
+ point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
+ simplex[i + 1] = point;
+ simplex[i + 1].fx = f(point);
+ simplex[i + 1].id = i + 1;
+ }
+ function updateSimplex(value) {
+ for (let i = 0; i < value.length; i++) {
+ simplex[N][i] = value[i];
+ }
+ simplex[N].fx = value.fx;
+ }
+ const sortOrder = (a, b) => a.fx - b.fx;
+ const centroid = x0.slice();
+ const reflected = x0.slice();
+ const contracted = x0.slice();
+ const expanded = x0.slice();
+ for (let iteration = 0; iteration < maxIterations; ++iteration) {
+ simplex.sort(sortOrder);
+ if (parameters.history) {
+ // copy the simplex (since later iterations will mutate) and
+ // sort it to have a consistent order between iterations
+ const sortedSimplex = simplex.map(x => {
+ const state = x.slice();
+ state.fx = x.fx;
+ state.id = x.id;
+ return state;
+ });
+ sortedSimplex.sort((a, b) => a.id - b.id);
+ parameters.history.push({
+ x: simplex[0].slice(),
+ fx: simplex[0].fx,
+ simplex: sortedSimplex
+ });
+ }
+ maxDiff = 0;
+ for (let i = 0; i < N; ++i) {
+ maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
+ }
+ if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
+ break;
+ }
+
+ // compute the centroid of all but the worst point in the simplex
+ for (let i = 0; i < N; ++i) {
+ centroid[i] = 0;
+ for (let j = 0; j < N; ++j) {
+ centroid[i] += simplex[j][i];
+ }
+ centroid[i] /= N;
+ }
+
+ // reflect the worst point past the centroid and compute loss at reflected
+ // point
+ const worst = simplex[N];
+ weightedSum(reflected, 1 + rho, centroid, -rho, worst);
+ reflected.fx = f(reflected);
+
+ // if the reflected point is the best seen, then possibly expand
+ if (reflected.fx < simplex[0].fx) {
+ weightedSum(expanded, 1 + chi, centroid, -chi, worst);
+ expanded.fx = f(expanded);
+ if (expanded.fx < reflected.fx) {
+ updateSimplex(expanded);
+ } else {
+ updateSimplex(reflected);
+ }
+ }
+
+ // if the reflected point is worse than the second worst, we need to
+ // contract
+ else if (reflected.fx >= simplex[N - 1].fx) {
+ let shouldReduce = false;
+ if (reflected.fx > worst.fx) {
+ // do an inside contraction
+ weightedSum(contracted, 1 + psi, centroid, -psi, worst);
+ contracted.fx = f(contracted);
+ if (contracted.fx < worst.fx) {
+ updateSimplex(contracted);
+ } else {
+ shouldReduce = true;
+ }
+ } else {
+ // do an outside contraction
+ weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
+ contracted.fx = f(contracted);
+ if (contracted.fx < reflected.fx) {
+ updateSimplex(contracted);
+ } else {
+ shouldReduce = true;
+ }
+ }
+ if (shouldReduce) {
+ // if we don't contract here, we're done
+ if (sigma >= 1) break;
+
+ // do a reduction
+ for (let i = 1; i < simplex.length; ++i) {
+ weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
+ simplex[i].fx = f(simplex[i]);
+ }
+ }
+ } else {
+ updateSimplex(reflected);
+ }
+ }
+ simplex.sort(sortOrder);
+ return {
+ fx: simplex[0].fx,
+ x: simplex[0]
+ };
+ }
+
+ /// searches along line 'pk' for a point that satifies the wolfe conditions
+ /// See 'Numerical Optimization' by Nocedal and Wright p59-60
+ /// f : objective function
+ /// pk : search direction
+ /// current: object containing current gradient/loss
+ /// next: output: contains next gradient/loss
+ /// returns a: step size taken
+ function wolfeLineSearch(f, pk, current, next, a, c1, c2) {
+ const phi0 = current.fx;
+ const phiPrime0 = dot(current.fxprime, pk);
+ let phi = phi0;
+ let phi_old = phi0;
+ let phiPrime = phiPrime0;
+ let a0 = 0;
+ a = a || 1;
+ c1 = c1 || 1e-6;
+ c2 = c2 || 0.1;
+ function zoom(a_lo, a_high, phi_lo) {
+ for (let iteration = 0; iteration < 16; ++iteration) {
+ a = (a_lo + a_high) / 2;
+ weightedSum(next.x, 1.0, current.x, a, pk);
+ phi = next.fx = f(next.x, next.fxprime);
+ phiPrime = dot(next.fxprime, pk);
+ if (phi > phi0 + c1 * a * phiPrime0 || phi >= phi_lo) {
+ a_high = a;
+ } else {
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
+ return a;
+ }
+ if (phiPrime * (a_high - a_lo) >= 0) {
+ a_high = a_lo;
+ }
+ a_lo = a;
+ phi_lo = phi;
+ }
+ }
+ return 0;
+ }
+ for (let iteration = 0; iteration < 10; ++iteration) {
+ weightedSum(next.x, 1.0, current.x, a, pk);
+ phi = next.fx = f(next.x, next.fxprime);
+ phiPrime = dot(next.fxprime, pk);
+ if (phi > phi0 + c1 * a * phiPrime0 || iteration && phi >= phi_old) {
+ return zoom(a0, a, phi_old);
+ }
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
+ return a;
+ }
+ if (phiPrime >= 0) {
+ return zoom(a, a0, phi);
+ }
+ phi_old = phi;
+ a0 = a;
+ a *= 2;
+ }
+ return a;
+ }
+
+ function conjugateGradient(f, initial, params) {
+ // allocate all memory up front here, keep out of the loop for perfomance
+ // reasons
+ let current = {
+ x: initial.slice(),
+ fx: 0,
+ fxprime: initial.slice()
+ };
+ let next = {
+ x: initial.slice(),
+ fx: 0,
+ fxprime: initial.slice()
+ };
+ const yk = initial.slice();
+ let pk;
+ let temp;
+ let a = 1;
+ let maxIterations;
+ params = params || {};
+ maxIterations = params.maxIterations || initial.length * 20;
+ current.fx = f(current.x, current.fxprime);
+ pk = current.fxprime.slice();
+ scale(pk, current.fxprime, -1);
+ for (let i = 0; i < maxIterations; ++i) {
+ a = wolfeLineSearch(f, pk, current, next, a);
+
+ // todo: history in wrong spot?
+ if (params.history) {
+ params.history.push({
+ x: current.x.slice(),
+ fx: current.fx,
+ fxprime: current.fxprime.slice(),
+ alpha: a
+ });
+ }
+ if (!a) {
+ // faiiled to find point that satifies wolfe conditions.
+ // reset direction for next iteration
+ scale(pk, current.fxprime, -1);
+ } else {
+ // update direction using Polak–Ribiere CG method
+ weightedSum(yk, 1, next.fxprime, -1, current.fxprime);
+ const delta_k = dot(current.fxprime, current.fxprime);
+ const beta_k = Math.max(0, dot(yk, next.fxprime) / delta_k);
+ weightedSum(pk, beta_k, pk, -1, next.fxprime);
+ temp = current;
+ current = next;
+ next = temp;
+ }
+ if (norm2(current.fxprime) <= 1e-5) {
+ break;
+ }
+ }
+ if (params.history) {
+ params.history.push({
+ x: current.x.slice(),
+ fx: current.fx,
+ fxprime: current.fxprime.slice(),
+ alpha: a
+ });
+ }
+ return current;
+ }
+
+ /**
+ * given a list of set objects, and their corresponding overlaps
+ * updates the (x, y, radius) attribute on each set such that their positions
+ * roughly correspond to the desired overlaps
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+ function venn(sets, parameters = {}) {
+ parameters.maxIterations = parameters.maxIterations || 500;
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
+ const loss = parameters.lossFunction || lossFunction;
+
+ // add in missing pairwise areas as having 0 size
+ const areas = addMissingAreas(sets, parameters);
+
+ // initial layout is done greedily
+ const circles = initialLayout(areas, parameters);
+
+ // transform x/y coordinates to a vector to optimize
+ const setids = Object.keys(circles);
+ /** @type {number[]} */
+ const initial = [];
+ for (const setid of setids) {
+ initial.push(circles[setid].x);
+ initial.push(circles[setid].y);
+ }
+
+ // optimize initial layout from our loss function
+ const solution = nelderMead(values => {
+ const current = {};
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ current[setid] = {
+ x: values[2 * i],
+ y: values[2 * i + 1],
+ radius: circles[setid].radius
+ // size : circles[setid].size
+ };
+ }
+ return loss(current, areas);
+ }, initial, parameters);
+
+ // transform solution vector back to x/y points
+ const positions = solution.x;
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ circles[setid].x = positions[2 * i];
+ circles[setid].y = positions[2 * i + 1];
+ }
+ return circles;
+ }
+ const SMALL = 1e-10;
+
+ /**
+ * Returns the distance necessary for two circles of radius r1 + r2 to
+ * have the overlap area 'overlap'
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} overlap
+ * @returns {number}
+ */
+ function distanceFromIntersectArea(r1, r2, overlap) {
+ // handle complete overlapped circles
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
+ return Math.abs(r1 - r2);
+ }
+ return bisect(distance => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
+ }
+
+ /**
+ * Missing pair-wise intersection area data can cause problems:
+ * treating as an unknown means that sets will be laid out overlapping,
+ * which isn't what people expect. To reflect that we want disjoint sets
+ * here, set the overlap to 0 for all missing pairwise set intersections
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {ReadonlyArray<{sets: ReadonlyArray, size: number}>}
+ */
+ function addMissingAreas(areas, parameters = {}) {
+ const distinct = parameters.distinct;
+ const r = areas.map(s => Object.assign({}, s));
+ function toKey(arr) {
+ return arr.join(';');
+ }
+ if (distinct) {
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
+ /** @types Map */
+ const count = new Map();
+ for (const area of r) {
+ for (let i = 0; i < area.sets.length; i++) {
+ const si = String(area.sets[i]);
+ count.set(si, area.size + (count.get(si) || 0));
+ for (let j = i + 1; j < area.sets.length; j++) {
+ const sj = String(area.sets[j]);
+ const k1 = `${si};${sj}`;
+ const k2 = `${sj};${si}`;
+ count.set(k1, area.size + (count.get(k1) || 0));
+ count.set(k2, area.size + (count.get(k2) || 0));
+ }
+ }
+ }
+ for (const area of r) {
+ if (area.sets.length < 3) {
+ area.size = count.get(toKey(area.sets));
+ }
+ }
+ }
+
+ // two circle intersections that aren't defined
+ const ids = [];
+
+ /** @type {Set} */
+ const pairs = new Set();
+ for (const area of r) {
+ if (area.sets.length === 1) {
+ ids.push(area.sets[0]);
+ } else if (area.sets.length === 2) {
+ const a = area.sets[0];
+ const b = area.sets[1];
+ pairs.add(toKey(area.sets));
+ pairs.add(toKey([b, a]));
+ }
+ }
+ ids.sort((a, b) => a === b ? 0 : a < b ? -1 : +1);
+ for (let i = 0; i < ids.length; ++i) {
+ const a = ids[i];
+ for (let j = i + 1; j < ids.length; ++j) {
+ const b = ids[j];
+ if (!pairs.has(toKey([a, b]))) {
+ r.push({
+ sets: [a, b],
+ size: 0
+ });
+ }
+ }
+ }
+ return r;
+ }
+
+ /**
+ * Returns two matrices, one of the euclidean distances between the sets
+ * and the other indicating if there are subset or disjoint set relationships
+ * @param {ReadonlyArray<{sets: ReadonlyArray}>} areas
+ * @param {ReadonlyArray<{size: number}>} sets
+ * @param {ReadonlyArray} setids
+ */
+ function getDistanceMatrices(areas, sets, setids) {
+ // initialize an empty distance matrix between all the points
+ /**
+ * @type {number[][]}
+ */
+ const distances = zerosM(sets.length, sets.length);
+ /**
+ * @type {number[][]}
+ */
+ const constraints = zerosM(sets.length, sets.length);
+
+ // compute required distances between all the sets such that
+ // the areas match
+ areas.filter(x => x.sets.length === 2).forEach(current => {
+ const left = setids[current.sets[0]];
+ const right = setids[current.sets[1]];
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
+ distances[left][right] = distances[right][left] = distance;
+
+ // also update constraints to indicate if its a subset or disjoint
+ // relationship
+ let c = 0;
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
+ c = 1;
+ } else if (current.size <= 1e-10) {
+ c = -1;
+ }
+ constraints[left][right] = constraints[right][left] = c;
+ });
+ return {
+ distances,
+ constraints
+ };
+ }
+
+ /// computes the gradient and loss simultaneously for our constrained MDS optimizer
+ function constrainedMDSGradient(x, fxprime, distances, constraints) {
+ for (let i = 0; i < fxprime.length; ++i) {
+ fxprime[i] = 0;
+ }
+ let loss = 0;
+ for (let i = 0; i < distances.length; ++i) {
+ const xi = x[2 * i];
+ const yi = x[2 * i + 1];
+ for (let j = i + 1; j < distances.length; ++j) {
+ const xj = x[2 * j];
+ const yj = x[2 * j + 1];
+ const dij = distances[i][j];
+ const constraint = constraints[i][j];
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
+ const distance = Math.sqrt(squaredDistance);
+ const delta = squaredDistance - dij * dij;
+ if (constraint > 0 && distance <= dij || constraint < 0 && distance >= dij) {
+ continue;
+ }
+ loss += 2 * delta * delta;
+ fxprime[2 * i] += 4 * delta * (xi - xj);
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
+ fxprime[2 * j] += 4 * delta * (xj - xi);
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
+ }
+ }
+ return loss;
+ }
+
+ /**
+ * takes the best working variant of either constrained MDS or greedy
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ */
+ function bestInitialLayout(areas, params = {}) {
+ let initial = greedyLayout(areas, params);
+ const loss = params.lossFunction || lossFunction;
+
+ // greedylayout is sufficient for all 2/3 circle cases. try out
+ // constrained MDS for higher order problems, take its output
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
+ // since it axis aligns)
+ if (areas.length >= 8) {
+ const constrained = constrainedMDSLayout(areas, params);
+ const constrainedLoss = loss(constrained, areas);
+ const greedyLoss = loss(initial, areas);
+ if (constrainedLoss + 1e-8 < greedyLoss) {
+ initial = constrained;
+ }
+ }
+ return initial;
+ }
+
+ /**
+ * use the constrained MDS variant to generate an initial layout
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+ function constrainedMDSLayout(areas, params = {}) {
+ const restarts = params.restarts || 10;
+
+ // bidirectionally map sets to a rowid (so we can create a matrix)
+ const sets = [];
+ const setids = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ setids[area.sets[0]] = sets.length;
+ sets.push(area);
+ }
+ }
+ let {
+ distances,
+ constraints
+ } = getDistanceMatrices(areas, sets, setids);
+
+ // keep distances bounded, things get messed up otherwise.
+ // TODO: proper preconditioner?
+ const norm = norm2(distances.map(norm2)) / distances.length;
+ distances = distances.map(row => row.map(value => value / norm));
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
+ let best = null;
+ for (let i = 0; i < restarts; ++i) {
+ const initial = zeros(distances.length * 2).map(Math.random);
+ const current = conjugateGradient(obj, initial, params);
+ if (!best || current.fx < best.fx) {
+ best = current;
+ }
+ }
+ const positions = best.x;
+
+ // translate rows back to (x,y,radius) coordinates
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ for (let i = 0; i < sets.length; ++i) {
+ const set = sets[i];
+ circles[set.sets[0]] = {
+ x: positions[2 * i] * norm,
+ y: positions[2 * i + 1] * norm,
+ radius: Math.sqrt(set.size / Math.PI)
+ };
+ }
+ if (params.history) {
+ for (const h of params.history) {
+ scale(h.x, norm);
+ }
+ }
+ return circles;
+ }
+
+ /**
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
+ * least overlapped, attempting to position each new set such that the
+ * overlapping areas to already positioned sets are basically right
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray}>} areas
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+ function greedyLayout(areas, params) {
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
+
+ // define a circle for each set
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
+ const setOverlaps = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ const set = area.sets[0];
+ circles[set] = {
+ x: 1e10,
+ y: 1e10,
+ rowid: circles.length,
+ size: area.size,
+ radius: Math.sqrt(area.size / Math.PI)
+ };
+ setOverlaps[set] = [];
+ }
+ }
+ areas = areas.filter(a => a.sets.length === 2);
+
+ // map each set to a list of all the other sets that overlap it
+ for (const current of areas) {
+ let weight = current.weight != null ? current.weight : 1.0;
+ const left = current.sets[0];
+ const right = current.sets[1];
+
+ // completely overlapped circles shouldn't be positioned early here
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
+ weight = 0;
+ }
+ setOverlaps[left].push({
+ set: right,
+ size: current.size,
+ weight
+ });
+ setOverlaps[right].push({
+ set: left,
+ size: current.size,
+ weight
+ });
+ }
+
+ // get list of most overlapped sets
+ const mostOverlapped = [];
+ Object.keys(setOverlaps).forEach(set => {
+ let size = 0;
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
+ }
+ mostOverlapped.push({
+ set,
+ size
+ });
+ });
+
+ // sort by size desc
+ function sortOrder(a, b) {
+ return b.size - a.size;
+ }
+ mostOverlapped.sort(sortOrder);
+
+ // keep track of what sets have been laid out
+ const positioned = {};
+ function isPositioned(element) {
+ return element.set in positioned;
+ }
+
+ /**
+ * adds a point to the output
+ * @param {{x: number, y: number}} point
+ * @param {number} index
+ */
+ function positionSet(point, index) {
+ circles[index].x = point.x;
+ circles[index].y = point.y;
+ positioned[index] = true;
+ }
+
+ // add most overlapped set at (0,0)
+ positionSet({
+ x: 0,
+ y: 0
+ }, mostOverlapped[0].set);
+
+ // get distances between all points. TODO, necessary?
+ // answer: probably not
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
+ for (let i = 1; i < mostOverlapped.length; ++i) {
+ const setIndex = mostOverlapped[i].set;
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
+ const set = circles[setIndex];
+ overlap.sort(sortOrder);
+ if (overlap.length === 0) {
+ // this shouldn't happen anymore with addMissingAreas
+ throw 'ERROR: missing pairwise overlap information';
+ }
+
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (var j = 0; j < overlap.length; ++j) {
+ // get appropriate distance from most overlapped already added set
+ const p1 = circles[overlap[j].set];
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
+
+ // sample positions at 90 degrees for maximum aesthetics
+ points.push({
+ x: p1.x + d1,
+ y: p1.y
+ });
+ points.push({
+ x: p1.x - d1,
+ y: p1.y
+ });
+ points.push({
+ y: p1.y + d1,
+ x: p1.x
+ });
+ points.push({
+ y: p1.y - d1,
+ x: p1.x
+ });
+
+ // if we have at least 2 overlaps, then figure out where the
+ // set should be positioned analytically and try those too
+ for (let k = j + 1; k < overlap.length; ++k) {
+ const p2 = circles[overlap[k].set];
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
+ const extraPoints = circleCircleIntersection({
+ x: p1.x,
+ y: p1.y,
+ radius: d1
+ }, {
+ x: p2.x,
+ y: p2.y,
+ radius: d2
+ });
+ points.push(...extraPoints);
+ }
+ }
+
+ // we have some candidate positions for the set, examine loss
+ // at each position to figure out where to put it at
+ let bestLoss = 1e50;
+ let bestPoint = points[0];
+ for (const point of points) {
+ circles[setIndex].x = point.x;
+ circles[setIndex].y = point.y;
+ const localLoss = loss(circles, areas);
+ if (localLoss < bestLoss) {
+ bestLoss = localLoss;
+ bestPoint = point;
+ }
+ }
+ positionSet(bestPoint, setIndex);
+ }
+ return circles;
+ }
+
+ /**
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
+ * the distance from the actual overlaps to the desired overlaps. Note that
+ * this method ignores overlaps of more than 2 circles
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray, weight?: number}>} overlaps
+ * @returns {number}
+ */
+ function lossFunction(circles, overlaps) {
+ let output = 0;
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map(d => circles[d]));
+ }
+ const weight = area.weight != null ? area.weight : 1.0;
+ output += weight * (overlap - area.size) * (overlap - area.size);
+ }
+ return output;
+ }
+ function logRatioLossFunction(circles, overlaps) {
+ let output = 0;
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map(d => circles[d]));
+ }
+ const weight = area.weight != null ? area.weight : 1.0;
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
+ output += weight * differenceFromIdeal * differenceFromIdeal;
+ }
+ return output;
+ }
+
+ /**
+ * orientates a bunch of circles to point in orientation
+ * @param {{x :number, y: number, radius: number}[]} circles
+ * @param {number | undefined} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ */
+ function orientateCircles(circles, orientation, orientationOrder) {
+ if (orientationOrder == null) {
+ circles.sort((a, b) => b.radius - a.radius);
+ } else {
+ circles.sort(orientationOrder);
+ }
+
+ // shift circles so largest circle is at (0, 0)
+ if (circles.length > 0) {
+ const largestX = circles[0].x;
+ const largestY = circles[0].y;
+ for (const circle of circles) {
+ circle.x -= largestX;
+ circle.y -= largestY;
+ }
+ }
+ if (circles.length === 2) {
+ // if the second circle is a subset of the first, arrange so that
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
+ const dist = distance(circles[0], circles[1]);
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
+ circles[1].y = circles[0].y;
+ }
+ }
+
+ // rotate circles so that second largest is at an angle of 'orientation'
+ // from largest
+ if (circles.length > 1) {
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+ for (const circle of circles) {
+ const x = circle.x;
+ const y = circle.y;
+ circle.x = c * x - s * y;
+ circle.y = s * x + c * y;
+ }
+ }
+
+ // mirror solution if third solution is above plane specified by
+ // first two circles
+ if (circles.length > 2) {
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
+ while (angle < 0) {
+ angle += 2 * Math.PI;
+ }
+ while (angle > 2 * Math.PI) {
+ angle -= 2 * Math.PI;
+ }
+ if (angle > Math.PI) {
+ const slope = circles[1].y / (1e-10 + circles[1].x);
+ for (const circle of circles) {
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
+ circle.x = 2 * d - circle.x;
+ circle.y = 2 * d * slope - circle.y;
+ }
+ }
+ }
+ }
+
+ /**
+ *
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {{x: number, y: number, radius: number}[][]}
+ */
+ function disjointCluster(circles) {
+ // union-find clustering to get disjoint sets
+ circles.forEach(circle => {
+ circle.parent = circle;
+ });
+
+ // path compression step in union find
+ function find(circle) {
+ if (circle.parent !== circle) {
+ circle.parent = find(circle.parent);
+ }
+ return circle.parent;
+ }
+ function union(x, y) {
+ const xRoot = find(x);
+ const yRoot = find(y);
+ xRoot.parent = yRoot;
+ }
+
+ // get the union of all overlapping sets
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const maxDistance = circles[i].radius + circles[j].radius;
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
+ union(circles[j], circles[i]);
+ }
+ }
+ }
+
+ // find all the disjoint clusters and group them together
+ /** @type {Map} */
+ const disjointClusters = new Map();
+ for (let i = 0; i < circles.length; ++i) {
+ const setid = find(circles[i]).parent.setid;
+ if (!disjointClusters.has(setid)) {
+ disjointClusters.set(setid, []);
+ }
+ disjointClusters.get(setid).push(circles[i]);
+ }
+
+ // cleanup bookkeeping
+ circles.forEach(circle => {
+ delete circle.parent;
+ });
+
+ // return in more usable form
+ return Array.from(disjointClusters.values());
+ }
+
+ /**
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
+ */
+ function getBoundingBox(circles) {
+ const minMax = d => {
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
+ return {
+ max: hi,
+ min: lo
+ };
+ };
+ return {
+ xRange: minMax('x'),
+ yRange: minMax('y')
+ };
+ }
+
+ /**
+ *
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {undefined | number} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+ function normalizeSolution(solution, orientation, orientationOrder) {
+ if (orientation == null) {
+ orientation = Math.PI / 2;
+ }
+
+ // work with a list instead of a dictionary, and take a copy so we
+ // don't mutate input
+ let circles = fromObjectNotation(solution).map(d => Object.assign({}, d));
+
+ // get all the disjoint clusters
+ const clusters = disjointCluster(circles);
+
+ // orientate all disjoint sets, get sizes
+ for (const cluster of clusters) {
+ orientateCircles(cluster, orientation, orientationOrder);
+ const bounds = getBoundingBox(cluster);
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
+ cluster.bounds = bounds;
+ }
+ clusters.sort((a, b) => b.size - a.size);
+
+ // orientate the largest at 0,0, and get the bounds
+ circles = clusters[0];
+ let returnBounds = circles.bounds;
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
+
+ /**
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
+ * @param {boolean} right
+ * @param {boolean} bottom
+ */
+ function addCluster(cluster, right, bottom) {
+ if (!cluster) {
+ return;
+ }
+ const bounds = cluster.bounds;
+ /** @type {number} */
+ let xOffset;
+ /** @type {number} */
+ let yOffset;
+ if (right) {
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
+ } else {
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
+ const centreing = (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
+ if (centreing < 0) {
+ xOffset += centreing;
+ }
+ }
+ if (bottom) {
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
+ } else {
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
+ const centreing = (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
+ if (centreing < 0) {
+ yOffset += centreing;
+ }
+ }
+ for (const c of cluster) {
+ c.x += xOffset;
+ c.y += yOffset;
+ circles.push(c);
+ }
+ }
+ let index = 1;
+ while (index < clusters.length) {
+ addCluster(clusters[index], true, false);
+ addCluster(clusters[index + 1], false, true);
+ addCluster(clusters[index + 2], true, true);
+ index += 3;
+
+ // have one cluster (in top left). lay out next three relative
+ // to it in a grid
+ returnBounds = getBoundingBox(circles);
+ }
+
+ // convert back to solution form
+ return toObjectNotation(circles);
+ }
+
+ /**
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
+ * a rectangle of width/height - with padding around the borders. also
+ * centers the diagram in the available space at the same time.
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {number} width
+ * @param {number} height
+ * @param {number} padding
+ * @param {boolean} scaleToFit
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+ function scaleSolution(solution, width, height, padding, scaleToFit) {
+ const circles = fromObjectNotation(solution);
+ width -= 2 * padding;
+ height -= 2 * padding;
+ const {
+ xRange,
+ yRange
+ } = getBoundingBox(circles);
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
+ console.log('not scaling solution: zero size detected');
+ return solution;
+ }
+
+ /** @type {number} */
+ let xScaling;
+ /** @type {number} */
+ let yScaling;
+ if (scaleToFit) {
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
+ xScaling = width / toScaleDiameter;
+ yScaling = height / toScaleDiameter;
+ } else {
+ xScaling = width / (xRange.max - xRange.min);
+ yScaling = height / (yRange.max - yRange.min);
+ }
+ const scaling = Math.min(yScaling, xScaling);
+ // while we're at it, center the diagram too
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
+ return toObjectNotation(circles.map(circle => ({
+ radius: scaling * circle.radius,
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
+ setid: circle.setid
+ })));
+ }
+
+ /**
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
+ */
+ function toObjectNotation(circles) {
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
+ const r = {};
+ for (const circle of circles) {
+ r[circle.setid] = circle;
+ }
+ return r;
+ }
+ /**
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
+ */
+ function fromObjectNotation(solution) {
+ const setids = Object.keys(solution);
+ return setids.map(id => Object.assign(solution[id], {
+ setid: id
+ }));
+ }
+
+ /**
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
+ *
+ * `colourScheme: Array`
+ * A list of color values to be applied when coloring diagram circles.
+ *
+ * `symmetricalTextCentre: Boolean`
+ * Whether to symmetrically center each circle's text horizontally and vertically.
+ * Defaults to `false`.
+ *
+ * `textFill: String`
+ * The color to be applied to the text within each circle.
+ *
+ * @param {object} options
+ */
+ function VennDiagram(options = {}) {
+ let useViewBox = false,
+ width = 600,
+ height = 350,
+ padding = 15,
+ duration = 1000,
+ orientation = Math.PI / 2,
+ normalize = true,
+ scaleToFit = null,
+ wrap = true,
+ styled = true,
+ fontSize = null,
+ orientationOrder = null,
+ distinct = false,
+ round = null,
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
+ // mimic the behaviour of d3.scale.category10 from the previous
+ // version of d3
+ colourMap = {},
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
+ // since we can support older versions of d3 as long as we don't force this,
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
+ colourScheme = options && options.colourScheme ? options.colourScheme : options && options.colorScheme ? options.colorScheme : ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],
+ colourIndex = 0,
+ colours = function (key) {
+ if (key in colourMap) {
+ return colourMap[key];
+ }
+ var ret = colourMap[key] = colourScheme[colourIndex];
+ colourIndex += 1;
+ if (colourIndex >= colourScheme.length) {
+ colourIndex = 0;
+ }
+ return ret;
+ },
+ layoutFunction = venn,
+ loss = lossFunction;
+ function chart(selection) {
+ let data = selection.datum();
+
+ // handle 0-sized sets by removing from input
+ const toRemove = new Set();
+ data.forEach(datum => {
+ if (datum.size == 0 && datum.sets.length == 1) {
+ toRemove.add(datum.sets[0]);
+ }
+ });
+ data = data.filter(datum => !datum.sets.some(set => toRemove.has(set)));
+ let circles = {};
+ let textCentres = {};
+ if (data.length > 0) {
+ let solution = layoutFunction(data, {
+ lossFunction: loss,
+ distinct
+ });
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+ }
+
+ // Figure out the current label for each set. These can change
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
+ const labels = {};
+ data.forEach(datum => {
+ if (datum.label) {
+ labels[datum.sets] = datum.label;
+ }
+ });
+ function label(d) {
+ if (d.sets in labels) {
+ return labels[d.sets];
+ }
+ if (d.sets.length == 1) {
+ return '' + d.sets[0];
+ }
+ }
+
+ // create svg if not already existing
+ selection.selectAll('svg').data([circles]).enter().append('svg');
+ const svg = selection.select('svg');
+ if (useViewBox) {
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
+ } else {
+ svg.attr('width', width).attr('height', height);
+ }
+
+ // to properly transition intersection areas, we need the
+ // previous circles locations. load from elements
+ const previous = {};
+ let hasPrevious = false;
+ svg.selectAll('.venn-area path').each(function (d) {
+ const path = this.getAttribute('d');
+ if (d.sets.length == 1 && path && !distinct) {
+ hasPrevious = true;
+ previous[d.sets[0]] = circleFromPath(path);
+ }
+ });
+ // interpolate intersection area paths between previous and
+ // current paths
+ function pathTween(d) {
+ return t => {
+ const c = d.sets.map(set => {
+ let start = previous[set];
+ let end = circles[set];
+ if (!start) {
+ start = {
+ x: width / 2,
+ y: height / 2,
+ radius: 1
+ };
+ }
+ if (!end) {
+ end = {
+ x: width / 2,
+ y: height / 2,
+ radius: 1
+ };
+ }
+ return {
+ x: start.x * (1 - t) + end.x * t,
+ y: start.y * (1 - t) + end.y * t,
+ radius: start.radius * (1 - t) + end.radius * t
+ };
+ });
+ return intersectionAreaPath(c, round);
+ };
+ }
+
+ // update data, joining on the set ids
+ const nodes = svg.selectAll('.venn-area').data(data, d => d.sets);
+
+ // create new nodes
+ const enter = nodes.enter().append('g').attr('class', d => `venn-area venn-${d.sets.length == 1 ? 'circle' : 'intersection'}${d.colour || d.color ? ' venn-coloured' : ''}`).attr('data-venn-sets', d => d.sets.join('_'));
+ const enterPath = enter.append('path');
+ const enterText = enter.append('text').attr('class', 'label').text(d => label(d)).attr('text-anchor', 'middle').attr('dy', '.35em').attr('x', width / 2).attr('y', height / 2);
+
+ // apply minimal style if wanted
+ if (styled) {
+ enterPath.style('fill-opacity', '0').filter(d => d.sets.length == 1).style('fill', d => d.colour ? d.colour : d.color ? d.color : colours(d.sets)).style('fill-opacity', '.25');
+ enterText.style('fill', d => {
+ if (d.colour || d.color) {
+ return '#FFF';
+ }
+ if (options.textFill) {
+ return options.textFill;
+ }
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
+ });
+ }
+ function asTransition(s) {
+ if (typeof s.transition === 'function') {
+ return s.transition('venn').duration(duration);
+ }
+ return s;
+ }
+
+ // update existing, using pathTween if necessary
+ let update = selection;
+ if (hasPrevious && typeof update.transition === 'function') {
+ update = asTransition(selection);
+ update.selectAll('path').attrTween('d', pathTween);
+ } else {
+ update.selectAll('path').attr('d', d => intersectionAreaPath(d.sets.map(set => circles[set])), round);
+ }
+ const updateText = update.selectAll('text').filter(d => d.sets in textCentres).text(d => label(d)).attr('x', d => Math.floor(textCentres[d.sets].x)).attr('y', d => Math.floor(textCentres[d.sets].y));
+ if (wrap) {
+ if (hasPrevious) {
+ // d3 4.0 uses 'on' for events on transitions,
+ // but d3 3.0 used 'each' instead. switch appropriately
+ if ('on' in updateText) {
+ updateText.on('end', wrapText(circles, label));
+ } else {
+ updateText.each('end', wrapText(circles, label));
+ }
+ } else {
+ updateText.each(wrapText(circles, label));
+ }
+ }
+
+ // remove old
+ const exit = asTransition(nodes.exit()).remove();
+ if (typeof nodes.transition === 'function') {
+ exit.selectAll('path').attrTween('d', pathTween);
+ }
+ const exitText = exit.selectAll('text').attr('x', width / 2).attr('y', height / 2);
+
+ // if we've been passed a fontSize explicitly, use it to
+ // transition
+ if (fontSize !== null) {
+ enterText.style('font-size', '0px');
+ updateText.style('font-size', fontSize);
+ exitText.style('font-size', '0px');
+ }
+ return {
+ circles,
+ textCentres,
+ nodes,
+ enter,
+ update,
+ exit
+ };
+ }
+ chart.wrap = function (_) {
+ if (!arguments.length) return wrap;
+ wrap = _;
+ return chart;
+ };
+ chart.useViewBox = function () {
+ useViewBox = true;
+ return chart;
+ };
+ chart.width = function (_) {
+ if (!arguments.length) return width;
+ width = _;
+ return chart;
+ };
+ chart.height = function (_) {
+ if (!arguments.length) return height;
+ height = _;
+ return chart;
+ };
+ chart.padding = function (_) {
+ if (!arguments.length) return padding;
+ padding = _;
+ return chart;
+ };
+ chart.distinct = function (_) {
+ if (!arguments.length) return distinct;
+ distinct = _;
+ return chart;
+ };
+ chart.colours = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+ chart.colors = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+ chart.fontSize = function (_) {
+ if (!arguments.length) return fontSize;
+ fontSize = _;
+ return chart;
+ };
+ chart.round = function (_) {
+ if (!arguments.length) return round;
+ round = _;
+ return chart;
+ };
+ chart.duration = function (_) {
+ if (!arguments.length) return duration;
+ duration = _;
+ return chart;
+ };
+ chart.layoutFunction = function (_) {
+ if (!arguments.length) return layoutFunction;
+ layoutFunction = _;
+ return chart;
+ };
+ chart.normalize = function (_) {
+ if (!arguments.length) return normalize;
+ normalize = _;
+ return chart;
+ };
+ chart.scaleToFit = function (_) {
+ if (!arguments.length) return scaleToFit;
+ scaleToFit = _;
+ return chart;
+ };
+ chart.styled = function (_) {
+ if (!arguments.length) return styled;
+ styled = _;
+ return chart;
+ };
+ chart.orientation = function (_) {
+ if (!arguments.length) return orientation;
+ orientation = _;
+ return chart;
+ };
+ chart.orientationOrder = function (_) {
+ if (!arguments.length) return orientationOrder;
+ orientationOrder = _;
+ return chart;
+ };
+ chart.lossFunction = function (_) {
+ if (!arguments.length) return loss;
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
+ return chart;
+ };
+ return chart;
+ }
+
+ // sometimes text doesn't fit inside the circle, if thats the case lets wrap
+ // the text here such that it fits
+ // todo: looks like this might be merged into d3 (
+ // https://github.com/mbostock/d3/issues/1642),
+ // also worth checking out is
+ // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
+ // this seems to be one of those things that should be easy but isn't
+ function wrapText(circles, labeller) {
+ return function (data) {
+ const text = this;
+ const width = circles[data.sets[0]].radius || 50;
+ const label = labeller(data) || '';
+ const words = label.split(/\s+/).reverse();
+ const maxLines = 3;
+ const minChars = (label.length + words.length) / maxLines;
+ let word = words.pop();
+ let line = [word];
+ let lineNumber = 0;
+ const lineHeight = 1.1; // ems
+ text.textContent = null; // clear
+ const tspans = [];
+ function append(word) {
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
+ tspan.textContent = word;
+ tspans.push(tspan);
+ text.append(tspan);
+ return tspan;
+ }
+ let tspan = append(word);
+ while (true) {
+ word = words.pop();
+ if (!word) {
+ break;
+ }
+ line.push(word);
+ const joined = line.join(' ');
+ tspan.textContent = joined;
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
+ line.pop();
+ tspan.textContent = line.join(' ');
+ line = [word];
+ tspan = append(word);
+ lineNumber++;
+ }
+ }
+ const initial = 0.35 - lineNumber * lineHeight / 2;
+ const x = text.getAttribute('x');
+ const y = text.getAttribute('y');
+ tspans.forEach((t, i) => {
+ t.setAttribute('x', x);
+ t.setAttribute('y', y);
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
+ });
+ };
+ }
+
+ /**
+ *
+ * @param {{x: number, y: number}} current
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
+ * @returns {number}
+ */
+ function circleMargin(current, interior, exterior) {
+ let margin = interior[0].radius - distance(interior[0], current);
+ for (let i = 1; i < interior.length; ++i) {
+ const m = interior[i].radius - distance(interior[i], current);
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+ for (let i = 0; i < exterior.length; ++i) {
+ const m = distance(exterior[i], current) - exterior[i].radius;
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+ return margin;
+ }
+
+ /**
+ * compute the center of some circles by maximizing the margin of
+ * the center point relative to the circles (interior) after subtracting
+ * nearby circles (exterior)
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
+ * @param {boolean} symmetricalTextCentre
+ * @returns {{x:number, y: number}}
+ */
+ function computeTextCentre(interior, exterior, symmetricalTextCentre) {
+ // get an initial estimate by sampling around the interior circles
+ // and taking the point with the biggest margin
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (const c of interior) {
+ points.push({
+ x: c.x,
+ y: c.y
+ });
+ points.push({
+ x: c.x + c.radius / 2,
+ y: c.y
+ });
+ points.push({
+ x: c.x - c.radius / 2,
+ y: c.y
+ });
+ points.push({
+ x: c.x,
+ y: c.y + c.radius / 2
+ });
+ points.push({
+ x: c.x,
+ y: c.y - c.radius / 2
+ });
+ }
+ let initial = points[0];
+ let margin = circleMargin(points[0], interior, exterior);
+ for (let i = 1; i < points.length; ++i) {
+ const m = circleMargin(points[i], interior, exterior);
+ if (m >= margin) {
+ initial = points[i];
+ margin = m;
+ }
+ }
+
+ // maximize the margin numerically
+ const solution = nelderMead(p => -1 * circleMargin({
+ x: p[0],
+ y: p[1]
+ }, interior, exterior), [initial.x, initial.y], {
+ maxIterations: 500,
+ minErrorDelta: 1e-10
+ }).x;
+ const ret = {
+ x: symmetricalTextCentre ? 0 : solution[0],
+ y: solution[1]
+ };
+
+ // check solution, fallback as needed (happens if fully overlapped
+ // etc)
+ let valid = true;
+ for (const i of interior) {
+ if (distance(ret, i) > i.radius) {
+ valid = false;
+ break;
+ }
+ }
+ for (const e of exterior) {
+ if (distance(ret, e) < e.radius) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid) {
+ return ret;
+ }
+ if (interior.length == 1) {
+ return {
+ x: interior[0].x,
+ y: interior[0].y
+ };
+ }
+ const areaStats = {};
+ intersectionArea(interior, areaStats);
+ if (areaStats.arcs.length === 0) {
+ return {
+ x: 0,
+ y: -1000,
+ disjoint: true
+ };
+ }
+ if (areaStats.arcs.length == 1) {
+ return {
+ x: areaStats.arcs[0].circle.x,
+ y: areaStats.arcs[0].circle.y
+ };
+ }
+ if (exterior.length) {
+ // try again without other circles
+ return computeTextCentre(interior, []);
+ }
+ // take average of all the points in the intersection
+ // polygon. this should basically never happen
+ // and has some issues:
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
+ return getCenter(areaStats.arcs.map(a => a.p1));
+ }
+
+ // given a dictionary of {setid : circle}, returns
+ // a dictionary of setid to list of circles that completely overlap it
+ function getOverlappingCircles(circles) {
+ const ret = {};
+ const circleids = Object.keys(circles);
+ for (const circleid of circleids) {
+ ret[circleid] = [];
+ }
+ for (let i = 0; i < circleids.length; i++) {
+ const ci = circleids[i];
+ const a = circles[ci];
+ for (let j = i + 1; j < circleids.length; ++j) {
+ const cj = circleids[j];
+ const b = circles[cj];
+ const d = distance(a, b);
+ if (d + b.radius <= a.radius + 1e-10) {
+ ret[cj].push(ci);
+ } else if (d + a.radius <= b.radius + 1e-10) {
+ ret[ci].push(cj);
+ }
+ }
+ }
+ return ret;
+ }
+ function computeTextCentres(circles, areas, symmetricalTextCentre) {
+ const ret = {};
+ const overlapped = getOverlappingCircles(circles);
+ for (let i = 0; i < areas.length; ++i) {
+ const area = areas[i].sets;
+ const areaids = {};
+ const exclude = {};
+ for (let j = 0; j < area.length; ++j) {
+ areaids[area[j]] = true;
+ const overlaps = overlapped[area[j]];
+ // keep track of any circles that overlap this area,
+ // and don't consider for purposes of computing the text
+ // centre
+ for (let k = 0; k < overlaps.length; ++k) {
+ exclude[overlaps[k]] = true;
+ }
+ }
+ const interior = [];
+ const exterior = [];
+ for (let setid in circles) {
+ if (setid in areaids) {
+ interior.push(circles[setid]);
+ } else if (!(setid in exclude)) {
+ exterior.push(circles[setid]);
+ }
+ }
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
+ ret[area] = centre;
+ if (centre.disjoint && areas[i].size > 0) {
+ console.log('WARNING: area ' + area + ' not represented on screen');
+ }
+ }
+ return ret;
+ }
+
+ // sorts all areas in the venn diagram, so that
+ // a particular area is on top (relativeTo) - and
+ // all other areas are so that the smallest areas are on top
+ function sortAreas(div, relativeTo) {
+ // figure out sets that are completely overlapped by relativeTo
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
+ const exclude = new Set();
+ for (const check of relativeTo.sets) {
+ for (let setid in overlaps) {
+ const overlap = overlaps[setid];
+ for (let j = 0; j < overlap.length; ++j) {
+ if (overlap[j] == check) {
+ exclude.add(setid);
+ break;
+ }
+ }
+ }
+ }
+
+ // checks that all sets are in exclude;
+ function shouldExclude(sets) {
+ return sets.every(set => !exclude.has(set));
+ }
+
+ // need to sort div's so that Z order is correct
+ div.selectAll('g').sort((a, b) => {
+ // highest order set intersections first
+ if (a.sets.length != b.sets.length) {
+ return a.sets.length - b.sets.length;
+ }
+ if (a == relativeTo) {
+ return shouldExclude(b.sets) ? -1 : 1;
+ }
+ if (b == relativeTo) {
+ return shouldExclude(a.sets) ? 1 : -1;
+ }
+
+ // finally by size
+ return b.size - a.size;
+ });
+ }
+
+ /**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} r
+ * @returns {string}
+ */
+ function circlePath(x, y, r) {
+ const ret = [];
+ ret.push('\nM', x, y);
+ ret.push('\nm', -r, 0);
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
+ return ret.join(' ');
+ }
+
+ /**
+ * inverse of the circlePath function, returns a circle object from an svg path
+ * @param {string} path
+ * @returns {{x: number, y: number, radius: number}}
+ */
+ function circleFromPath(path) {
+ const tokens = path.split(' ');
+ return {
+ x: Number.parseFloat(tokens[1]),
+ y: Number.parseFloat(tokens[2]),
+ radius: -Number.parseFloat(tokens[4])
+ };
+ }
+ function intersectionAreaArcs(circles) {
+ if (circles.length === 0) {
+ return [];
+ }
+ const stats = {};
+ intersectionArea(circles, stats);
+ return stats.arcs;
+ }
+ function arcsToPath(arcs, round) {
+ if (arcs.length === 0) {
+ return 'M 0 0';
+ }
+ const rFactor = Math.pow(10, round || 0);
+ const r = round != null ? v => Math.round(v * rFactor) / rFactor : v => v;
+ if (arcs.length == 1) {
+ const circle = arcs[0].circle;
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
+ }
+ // draw path around arcs
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
+ for (const arc of arcs) {
+ const radius = r(arc.circle.radius);
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
+ }
+ return ret.join(' ');
+ }
+
+ /**
+ * returns a svg path of the intersection area of a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {string}
+ */
+ function intersectionAreaPath(circles, round) {
+ return arcsToPath(intersectionAreaArcs(circles), round);
+ }
+ function layout(data, options = {}) {
+ const {
+ lossFunction: loss,
+ layoutFunction: layout = venn,
+ normalize = true,
+ orientation = Math.PI / 2,
+ orientationOrder,
+ width = 600,
+ height = 350,
+ padding = 15,
+ scaleToFit = false,
+ symmetricalTextCentre = false,
+ distinct,
+ round = 2
+ } = options;
+ let solution = layout(data, {
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
+ distinct
+ });
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+ const circleLookup = new Map(Object.keys(circles).map(set => [set, {
+ set,
+ x: circles[set].x,
+ y: circles[set].y,
+ radius: circles[set].radius
+ }]));
+ const helpers = data.map(area => {
+ const circles = area.sets.map(s => circleLookup.get(s));
+ const arcs = intersectionAreaArcs(circles);
+ const path = arcsToPath(arcs, round);
+ return {
+ circles,
+ arcs,
+ path,
+ area,
+ has: new Set(area.sets)
+ };
+ });
+ function genDistinctPath(sets) {
+ let r = '';
+ for (const e of helpers) {
+ if (e.has.size > sets.length && sets.every(s => e.has.has(s))) {
+ r += ' ' + e.path;
+ }
+ }
+ return r;
+ }
+ return helpers.map(({
+ circles,
+ arcs,
+ path,
+ area
+ }) => {
+ return {
+ data: area,
+ text: textCentres[area.sets],
+ circles,
+ arcs,
+ path,
+ distinctPath: path + genDistinctPath(area.sets)
+ };
+ });
+ }
+
+ exports.VennDiagram = VennDiagram;
+ exports.bestInitialLayout = bestInitialLayout;
+ exports.circleArea = circleArea;
+ exports.circleCircleIntersection = circleCircleIntersection;
+ exports.circleFromPath = circleFromPath;
+ exports.circleOverlap = circleOverlap;
+ exports.circlePath = circlePath;
+ exports.computeTextCentre = computeTextCentre;
+ exports.computeTextCentres = computeTextCentres;
+ exports.disjointCluster = disjointCluster;
+ exports.distance = distance;
+ exports.distanceFromIntersectArea = distanceFromIntersectArea;
+ exports.greedyLayout = greedyLayout;
+ exports.intersectionArea = intersectionArea;
+ exports.intersectionAreaPath = intersectionAreaPath;
+ exports.layout = layout;
+ exports.logRatioLossFunction = logRatioLossFunction;
+ exports.lossFunction = lossFunction;
+ exports.normalizeSolution = normalizeSolution;
+ exports.scaleSolution = scaleSolution;
+ exports.sortAreas = sortAreas;
+ exports.venn = venn;
+ exports.wrapText = wrapText;
+
+}));
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/build/venn.min.js b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.min.js
new file mode 100644
index 0000000000000000000000000000000000000000..9640b57fbbec5bdedf68aae614a53aaf8c6e8518
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/build/venn.min.js
@@ -0,0 +1 @@
+!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).venn={})}(this,(function(t){"use strict";const e=1e-10;function n(t,n){const o=function(t){const e=[];for(let n=0;nfunction(t,n){return n.every((n=>r(t,n)1){const e=a(l);for(let t=0;te.angle-t.angle));let n=l[l.length-1];for(let e=0;e2*s.radius&&(h=2*s.radius),(null==a||a.width>h)&&(a={circle:s,width:h,p1:o,p2:n,large:h>s.radius,sweep:!0})}null!=a&&(f.push(a),c+=s(a.circle.radius,a.width),n=o)}}else{let n=t[0];for(let e=1;eMath.abs(n.radius-t[e].radius)){s=!0;break}s?c=u=0:(c=n.radius*n.radius*Math.PI,f.push({circle:n,p1:{x:n.x,y:n.y+n.radius},p2:{x:n.x-e,y:n.y+n.radius},width:2*n.radius,large:!0,sweep:!0}))}return u/=2,n&&(n.area=c+u,n.arcArea=c,n.polygonArea=u,n.arcs=f,n.innerPoints=l,n.intersectionPoints=o),c+u}function s(t,e){return t*t*Math.acos(1-e/t)-(t-e)*Math.sqrt(e*(2*t-e))}function r(t,e){return Math.sqrt((t.x-e.x)*(t.x-e.x)+(t.y-e.y)*(t.y-e.y))}function o(t,e,n){if(n>=t+e)return 0;if(n<=Math.abs(t-e))return Math.PI*Math.min(t,e)*Math.min(t,e);const r=e-(n*n-t*t+e*e)/(2*n);return s(t,t-(n*n-e*e+t*t)/(2*n))+s(e,r)}function i(t,e){const n=r(t,e),s=t.radius,o=e.radius;if(n>=s+o||n<=Math.abs(s-o))return[];const i=(s*s-o*o+n*n)/(2*n),a=Math.sqrt(s*s-i*i),l=t.x+i*(e.x-t.x)/n,c=t.y+i*(e.y-t.y)/n,u=-(e.y-t.y)*(a/n),f=-(e.x-t.x)*(a/n);return[{x:l+u,y:c-f},{x:l-u,y:c+f}]}function a(t){const e={x:0,y:0};for(const n of t)e.x+=n.x,e.y+=n.y;return e.x/=t.length,e.y/=t.length,e}function l(t){const e=new Array(t);for(let n=0;nl(e)))}function u(t,e){let n=0;for(let s=0;st.fx-e.fx,m=e.slice(),M=e.slice(),b=e.slice(),z=e.slice();for(let e=0;e{const e=t.slice();return e.fx=t.fx,e.id=t.id,e}));t.sort(((t,e)=>t.id-e.id)),n.history.push({x:d[0].slice(),fx:d[0].fx,simplex:t})}h=0;for(let t=0;t=d[g-1].fx){let n=!1;if(M.fx>e.fx?(x(b,1+u,m,-u,e),b.fx=t(b),b.fx=1)break;for(let e=1;ea+o*r*l||c>=d)g=r;else{if(Math.abs(h)<=-i*l)return r;h*(g-f)>=0&&(g=f),f=r,d=c}return 0}r=r||1,o=o||1e-6,i=i||.1;for(let p=0;p<10;++p){if(x(s.x,1,n.x,r,e),c=s.fx=t(s.x,s.fxprime),h=u(s.fxprime,e),c>a+o*r*l||p&&c>=f)return d(g,r,f);if(Math.abs(h)<=-i*l)return r;if(h>=0)return d(r,g,c);f=c,g=r,r*=2}return r}function p(t,e,n){let s={x:e.slice(),fx:0,fxprime:e.slice()},r={x:e.slice(),fx:0,fxprime:e.slice()};const o=e.slice();let i,a,l,c=1;l=(n=n||{}).maxIterations||20*e.length,s.fx=t(s.x,s.fxprime),i=s.fxprime.slice(),h(i,s.fxprime,-1);for(let e=0;eObject.assign({},t)));function r(t){return t.join(";")}if(n){const t=new Map;for(const e of s)for(let n=0;nt===e?0:t{const e={};for(let n=0;n0)throw"Initial bisect points must have opposite signs";if(0===i)return e;if(0===a)return n;for(let n=0;n=0&&(e=n),Math.abs(l)o(t,e,s)-n),0,t+e)}function b(t,e={}){let n=z(t,e);const s=e.lossFunction||I;if(t.length>=8){const r=function(t,e={}){const n=e.restarts||10,s=[],r={};for(const e of t)1===e.sets.length&&(r[e.sets[0]]=s.length,s.push(e));let{distances:o,constraints:i}=function(t,e,n){const s=c(e.length,e.length),r=c(e.length,e.length);return t.filter((t=>2===t.sets.length)).forEach((t=>{const o=n[t.sets[0]],i=n[t.sets[1]],a=M(Math.sqrt(e[o].size/Math.PI),Math.sqrt(e[i].size/Math.PI),t.size);s[o][i]=s[i][o]=a;let l=0;t.size+1e-10>=Math.min(e[o].size,e[i].size)?l=1:t.size<=1e-10&&(l=-1),r[o][i]=r[i][o]=l})),{distances:s,constraints:r}}(t,s,r);const a=f(o.map(f))/o.length;o=o.map((t=>t.map((t=>t/a))));const u=(t,e)=>function(t,e,n,s){for(let t=0;t0&&g<=f||h<0&&g>=f||(r+=2*d*d,e[2*o]+=4*d*(i-c),e[2*o+1]+=4*d*(a-u),e[2*l]+=4*d*(c-i),e[2*l+1]+=4*d*(u-a))}}return r}(t,e,o,i);let x=null;for(let t=0;t2===t.sets.length));for(const e of t){let t=null!=e.weight?e.weight:1;const n=e.sets[0],o=e.sets[1];e.size+m>=Math.min(s[n].size,s[o].size)&&(t=0),r[n].push({set:o,size:e.size,weight:t}),r[o].push({set:n,size:e.size,weight:t})}const o=[];function a(t,e){return e.size-t.size}Object.keys(r).forEach((t=>{let e=0;for(let n=0;nt[e])));s+=(null!=i.weight?i.weight:1)*(e-i.size)*(e-i.size)}return s}function w(t,e){let s=0;for(const i of e){if(1===i.sets.length)continue;let e;if(2===i.sets.length){const n=t[i.sets[0]],s=t[i.sets[1]];e=o(n.radius,s.radius,r(n,s))}else e=n(i.sets.map((e=>t[e])));const a=null!=i.weight?i.weight:1,l=Math.log((e+1)/(i.size+1));s+=a*l*l}return s}function R(t,e,n){if(null==n?t.sort(((t,e)=>e.radius-t.radius)):t.sort(n),t.length>0){const e=t[0].x,n=t[0].y;for(const s of t)s.x-=e,s.y-=n}if(2===t.length){r(t[0],t[1])1){const n=Math.atan2(t[1].x,t[1].y)-e,s=Math.cos(n),r=Math.sin(n);for(const e of t){const t=e.x,n=e.y;e.x=s*t-r*n,e.y=r*t+s*n}}if(t.length>2){let n=Math.atan2(t[2].x,t[2].y)-e;for(;n<0;)n+=2*Math.PI;for(;n>2*Math.PI;)n-=2*Math.PI;if(n>Math.PI){const e=t[1].y/(1e-10+t[1].x);for(const n of t){var s=(n.x+e*n.y)/(1+e*e);n.x=2*s-n.x,n.y=2*s*e-n.y}}}}function v(t){function e(t){return t.parent!==t&&(t.parent=e(t.parent)),t.parent}function n(t,n){const s=e(t),r=e(n);s.parent=r}t.forEach((t=>{t.parent=t}));for(let e=0;e{delete t.parent})),Array.from(s.values())}function A(t){const e=e=>({max:t.reduce(((t,n)=>Math.max(t,n[e]+n.radius)),Number.NEGATIVE_INFINITY),min:t.reduce(((t,n)=>Math.min(t,n[e]-n.radius)),Number.POSITIVE_INFINITY)});return{xRange:e("x"),yRange:e("y")}}function F(t,e,n){null==e&&(e=Math.PI/2);let s=T(t).map((t=>Object.assign({},t)));const r=v(s);for(const t of r){R(t,e,n);const s=A(t);t.size=(s.xRange.max-s.xRange.min)*(s.yRange.max-s.yRange.min),t.bounds=s}r.sort(((t,e)=>e.size-t.size)),s=r[0];let o=s.bounds;const i=(o.xRange.max-o.xRange.min)/50;function a(t,e,n){if(!t)return;const r=t.bounds;let a,l;if(e)a=o.xRange.max-r.xRange.min+i;else{a=o.xRange.max-r.xRange.max;const t=(r.xRange.max-r.xRange.min)/2-(o.xRange.max-o.xRange.min)/2;t<0&&(a+=t)}if(n)l=o.yRange.max-r.yRange.min+i;else{l=o.yRange.max-r.yRange.max;const t=(r.yRange.max-r.yRange.min)/2-(o.yRange.max-o.yRange.min)/2;t<0&&(l+=t)}for(const e of t)e.x+=a,e.y+=l,s.push(e)}let l=1;for(;l({radius:u*t.radius,x:s+f+(t.x-i.min)*u,y:s+h+(t.y-a.min)*u,setid:t.setid}))))}function j(t){const e={};for(const n of t)e[n.setid]=n;return e}function T(t){return Object.keys(t).map((e=>Object.assign(t[e],{setid:e})))}function E(t,e){return function(n){const s=this,r=t[n.sets[0]].radius||50,o=e(n)||"",i=o.split(/\s+/).reverse(),a=(o.length+i.length)/3;let l=i.pop(),c=[l],u=0;s.textContent=null;const f=[];function h(t){const e=s.ownerDocument.createElementNS(s.namespaceURI,"tspan");return e.textContent=t,f.push(e),s.append(e),e}let x=h(l);for(;l=i.pop(),l;){c.push(l);const t=c.join(" ");x.textContent=t,t.length>a&&x.getComputedTextLength()>r&&(c.pop(),x.textContent=c.join(" "),c=[l],x=h(l),u++)}const g=.35-1.1*u/2,d=s.getAttribute("x"),p=s.getAttribute("y");f.forEach(((t,e)=>{t.setAttribute("x",d),t.setAttribute("y",p),t.setAttribute("dy",`${g+1.1*e}em`)}))}}function S(t,e,n){let s=e[0].radius-r(e[0],t);for(let n=1;n=l&&(i=o[n],l=s)}const c=g((n=>-1*S({x:n[0],y:n[1]},t,e)),[i.x,i.y],{maxIterations:500,minErrorDelta:1e-10}).x,u={x:s?0:c[0],y:c[1]};let f=!0;for(const e of t)if(r(u,e)>e.radius){f=!1;break}for(const t of e)if(r(u,t)t.p1)))}function N(t){const e={},n=Object.keys(t);for(const t of n)e[t]=[];for(let s=0;s0&&console.log("WARNING: area "+i+" not represented on screen")}return s}function k(t,e,n){const s=[];return s.push("\nM",t,e),s.push("\nm",-n,0),s.push("\na",n,n,0,1,0,2*n,0),s.push("\na",n,n,0,1,0,2*-n,0),s.join(" ")}function q(t){const e=t.split(" ");return{x:Number.parseFloat(e[1]),y:Number.parseFloat(e[2]),radius:-Number.parseFloat(e[4])}}function $(t){if(0===t.length)return[];const e={};return n(t,e),e.arcs}function D(t,e){if(0===t.length)return"M 0 0";const n=Math.pow(10,e||0),s=null!=e?t=>Math.round(t*n)/n:t=>t;if(1==t.length){const e=t[0].circle;return k(s(e.x),s(e.y),s(e.radius))}const r=["\nM",s(t[0].p2.x),s(t[0].p2.y)];for(const e of t){const t=s(e.circle.radius);r.push("\nA",t,t,0,e.large?1:0,e.sweep?1:0,s(e.p1.x),s(e.p1.y))}return r.join(" ")}function L(t,e){return D($(t),e)}t.VennDiagram=function(t={}){let e=!1,n=600,s=350,r=15,o=1e3,i=Math.PI/2,a=!0,l=null,c=!0,u=!0,f=null,h=null,x=!1,g=null,d=!(!t||!t.symmetricalTextCentre)&&t.symmetricalTextCentre,p={},m=t&&t.colourScheme?t.colourScheme:t&&t.colorScheme?t.colorScheme:["#1f77b4","#ff7f0e","#2ca02c","#d62728","#9467bd","#8c564b","#e377c2","#7f7f7f","#bcbd22","#17becf"],M=0,b=function(t){if(t in p)return p[t];var e=p[t]=m[M];return M+=1,M>=m.length&&(M=0),e},z=y,R=I;function v(p){let y=p.datum();const m=new Set;y.forEach((t=>{0==t.size&&1==t.sets.length&&m.add(t.sets[0])})),y=y.filter((t=>!t.sets.some((t=>m.has(t)))));let M={},I={};if(y.length>0){let t=z(y,{lossFunction:R,distinct:x});a&&(t=F(t,i,h)),M=P(t,n,s,r,l),I=O(M,y,d)}const w={};function v(t){return t.sets in w?w[t.sets]:1==t.sets.length?""+t.sets[0]:void 0}y.forEach((t=>{t.label&&(w[t.sets]=t.label)})),p.selectAll("svg").data([M]).enter().append("svg");const A=p.select("svg");e?A.attr("viewBox",`0 0 ${n} ${s}`):A.attr("width",n).attr("height",s);const j={};let T=!1;function S(t){return e=>L(t.sets.map((t=>{let r=j[t],o=M[t];return r||(r={x:n/2,y:s/2,radius:1}),o||(o={x:n/2,y:s/2,radius:1}),{x:r.x*(1-e)+o.x*e,y:r.y*(1-e)+o.y*e,radius:r.radius*(1-e)+o.radius*e}})),g)}A.selectAll(".venn-area path").each((function(t){const e=this.getAttribute("d");1==t.sets.length&&e&&!x&&(T=!0,j[t.sets[0]]=q(e))}));const C=A.selectAll(".venn-area").data(y,(t=>t.sets)),N=C.enter().append("g").attr("class",(t=>`venn-area venn-${1==t.sets.length?"circle":"intersection"}${t.colour||t.color?" venn-coloured":""}`)).attr("data-venn-sets",(t=>t.sets.join("_"))),k=N.append("path"),$=N.append("text").attr("class","label").text((t=>v(t))).attr("text-anchor","middle").attr("dy",".35em").attr("x",n/2).attr("y",s/2);function D(t){return"function"==typeof t.transition?t.transition("venn").duration(o):t}u&&(k.style("fill-opacity","0").filter((t=>1==t.sets.length)).style("fill",(t=>t.colour?t.colour:t.color?t.color:b(t.sets))).style("fill-opacity",".25"),$.style("fill",(e=>e.colour||e.color?"#FFF":t.textFill?t.textFill:1==e.sets.length?b(e.sets):"#444")));let V=p;T&&"function"==typeof V.transition?(V=D(p),V.selectAll("path").attrTween("d",S)):V.selectAll("path").attr("d",(t=>L(t.sets.map((t=>M[t])))),g);const _=V.selectAll("text").filter((t=>t.sets in I)).text((t=>v(t))).attr("x",(t=>Math.floor(I[t.sets].x))).attr("y",(t=>Math.floor(I[t.sets].y)));c&&(T?"on"in _?_.on("end",E(M,v)):_.each("end",E(M,v)):_.each(E(M,v)));const B=D(C.exit()).remove();"function"==typeof C.transition&&B.selectAll("path").attrTween("d",S);const G=B.selectAll("text").attr("x",n/2).attr("y",s/2);return null!==f&&($.style("font-size","0px"),_.style("font-size",f),G.style("font-size","0px")),{circles:M,textCentres:I,nodes:C,enter:N,update:V,exit:B}}return v.wrap=function(t){return arguments.length?(c=t,v):c},v.useViewBox=function(){return e=!0,v},v.width=function(t){return arguments.length?(n=t,v):n},v.height=function(t){return arguments.length?(s=t,v):s},v.padding=function(t){return arguments.length?(r=t,v):r},v.distinct=function(t){return arguments.length?(x=t,v):x},v.colours=function(t){return arguments.length?(b=t,v):b},v.colors=function(t){return arguments.length?(b=t,v):b},v.fontSize=function(t){return arguments.length?(f=t,v):f},v.round=function(t){return arguments.length?(g=t,v):g},v.duration=function(t){return arguments.length?(o=t,v):o},v.layoutFunction=function(t){return arguments.length?(z=t,v):z},v.normalize=function(t){return arguments.length?(a=t,v):a},v.scaleToFit=function(t){return arguments.length?(l=t,v):l},v.styled=function(t){return arguments.length?(u=t,v):u},v.orientation=function(t){return arguments.length?(i=t,v):i},v.orientationOrder=function(t){return arguments.length?(h=t,v):h},v.lossFunction=function(t){return arguments.length?(R="default"===t?I:"logRatio"===t?w:t,v):R},v},t.bestInitialLayout=b,t.circleArea=s,t.circleCircleIntersection=i,t.circleFromPath=q,t.circleOverlap=o,t.circlePath=k,t.computeTextCentre=C,t.computeTextCentres=O,t.disjointCluster=v,t.distance=r,t.distanceFromIntersectArea=M,t.greedyLayout=z,t.intersectionArea=n,t.intersectionAreaPath=L,t.layout=function(t,e={}){const{lossFunction:n,layoutFunction:s=y,normalize:r=!0,orientation:o=Math.PI/2,orientationOrder:i,width:a=600,height:l=350,padding:c=15,scaleToFit:u=!1,symmetricalTextCentre:f=!1,distinct:h,round:x=2}=e;let g=s(t,{lossFunction:"default"!==n&&n?"logRatio"===n?w:n:I,distinct:h});r&&(g=F(g,o,i));const d=P(g,a,l,c,u),p=O(d,t,f),m=new Map(Object.keys(d).map((t=>[t,{set:t,x:d[t].x,y:d[t].y,radius:d[t].radius}]))),M=t.map((t=>{const e=t.sets.map((t=>m.get(t))),n=$(e);return{circles:e,arcs:n,path:D(n,x),area:t,has:new Set(t.sets)}}));function b(t){let e="";for(const n of M)n.has.size>t.length&&t.every((t=>n.has.has(t)))&&(e+=" "+n.path);return e}return M.map((({circles:t,arcs:e,path:n,area:s})=>({data:s,text:p[s.sets],circles:t,arcs:e,path:n,distinctPath:n+b(s.sets)})))},t.logRatioLossFunction=w,t.lossFunction=I,t.normalizeSolution=F,t.scaleSolution=P,t.sortAreas=function(t,e){const n=N(t.selectAll("svg").datum()),s=new Set;for(const t of e.sets)for(let e in n){const r=n[e];for(let n=0;n!s.has(t)))}t.selectAll("g").sort(((t,n)=>t.sets.length!=n.sets.length?t.sets.length-n.sets.length:t==e?r(n.sets)?-1:1:n==e?r(t.sets)?1:-1:n.size-t.size))},t.venn=y,t.wrapText=E}));
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/package.json b/tools/ui/node_modules/@upsetjs/venn.js/package.json
new file mode 100644
index 0000000000000000000000000000000000000000..1ecc13ca3af8c2d2e37ca9f101c52df14fd474dd
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/package.json
@@ -0,0 +1,105 @@
+{
+ "name": "@upsetjs/venn.js",
+ "description": "Area Proportional Venn and Euler Diagrams",
+ "version": "2.0.0",
+ "publishConfig": {
+ "access": "public"
+ },
+ "author": {
+ "name": "Ben Frederickson",
+ "email": "ben@benfrederickson.com",
+ "url": "https://www.benfrederickson.com"
+ },
+ "contributors": [
+ {
+ "name": "Samuel Gratzl",
+ "email": "samu@sgratzl.com",
+ "url": "https://wwww.sgratzl.com"
+ }
+ ],
+ "license": "MIT",
+ "homepage": "https://github.com/upsetjs/venn.js",
+ "bugs": {
+ "url": "https://github.com/upsetjs/venn.js/issues"
+ },
+ "keywords": [
+ "Venn",
+ "Euler"
+ ],
+ "repository": {
+ "type": "git",
+ "url": "https://github.com/upsetjs/venn.js.git"
+ },
+ "directories": {
+ "example": "examples",
+ "test": "tests"
+ },
+ "type": "module",
+ "main": "build/venn.esm.js",
+ "module": "build/venn.esm.js",
+ "require": "build/venn.js",
+ "unpkg": "build/venn.min.js",
+ "jsdelivr": "build/venn.min.js",
+ "types": "src/index.d.ts",
+ "exports": {
+ ".": {
+ "import": "./build/venn.esm.js",
+ "require": "./build/index.js",
+ "scripts": "./build/venn.min.js",
+ "types": "./src/index.d.ts"
+ }
+ },
+ "sideEffects": false,
+ "files": [
+ "build",
+ "src/**/*.js",
+ "src/**/*.d.ts"
+ ],
+ "browserslist": [
+ "Firefox ESR",
+ "last 2 Chrome versions",
+ "last 2 Firefox versions"
+ ],
+ "optionalDependencies": {
+ "d3-selection": "^3.0.0",
+ "d3-transition": "^3.0.1"
+ },
+ "devDependencies": {
+ "@babel/core": "^7.26.0",
+ "@babel/plugin-transform-runtime": "^7.25.9",
+ "@babel/preset-env": "^7.26.0",
+ "@eslint/js": "^9.15.0",
+ "@rollup/plugin-babel": "^6.0.4",
+ "@rollup/plugin-commonjs": "^28.0.1",
+ "@rollup/plugin-node-resolve": "^15.3.0",
+ "@yarnpkg/sdks": "^3.2.0",
+ "canvas": "^2.11.2",
+ "d3-selection": "^3.0.0",
+ "d3-transition": "^3.0.1",
+ "eslint": "^9.15.0",
+ "eslint-config-prettier": "^9.1.0",
+ "eslint-plugin-prettier": "^5.2.1",
+ "fmin": "patch:fmin@npm%3A0.0.4#~/.yarn/patches/fmin-npm-0.0.4-e439f499bd.patch",
+ "globals": "^15.12.0",
+ "jest-image-snapshot": "^6.4.0",
+ "jsdom": "^25.0.1",
+ "prettier": "^3.3.3",
+ "rimraf": "^6.0.1",
+ "rollup": "^4.27.2",
+ "rollup-plugin-terser": "^7.0.2",
+ "vite": "^5.4.11",
+ "vitest": "^2.1.5"
+ },
+ "scripts": {
+ "clean": "rimraf --glob build *.tgz",
+ "watch": "rollup -c -w",
+ "lint": "eslint src",
+ "test": "vitest --passWithNoTests",
+ "test:watch": "vitest --watch",
+ "posttest": "npm run lint",
+ "prebuild": "npm run clean && npm test",
+ "build": "rollup -c",
+ "format": "prettier --write examples \"*.{md,json,js,yml}\" \"{.github,src,examples}/**\""
+ },
+ "packageManager": "yarn@4.5.1"
+}
\ No newline at end of file
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.js b/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.js
new file mode 100644
index 0000000000000000000000000000000000000000..e67fdb2c36d59602ef020cb8cdaaeebd66b43a8f
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.js
@@ -0,0 +1,266 @@
+const SMALL = 1e-10;
+
+/**
+ * Returns the intersection area of a bunch of circles (where each circle
+ * is an object having an x,y and radius property)
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @param {undefined | { area?: number, arcArea?: number, polygonArea?: number, arcs?: ReadonlyArray<{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }>, innerPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+}>, intersectionPoints: ReadonlyArray<{
+ x: number;
+ y: number;
+ parentIndex: [number, number];
+}> }} stats
+ * @returns {number}
+ */
+export function intersectionArea(circles, stats) {
+ // get all the intersection points of the circles
+ const intersectionPoints = getIntersectionPoints(circles);
+
+ // filter out points that aren't included in all the circles
+ const innerPoints = intersectionPoints.filter((p) => containedInCircles(p, circles));
+
+ let arcArea = 0;
+ let polygonArea = 0;
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
+ const arcs = [];
+
+ // if we have intersection points that are within all the circles,
+ // then figure out the area contained by them
+ if (innerPoints.length > 1) {
+ // sort the points by angle from the center of the polygon, which lets
+ // us just iterate over points to get the edges
+ const center = getCenter(innerPoints);
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p = innerPoints[i];
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
+ }
+ innerPoints.sort((a, b) => b.angle - a.angle);
+
+ // iterate over all points, get arc between the points
+ // and update the areas
+ let p2 = innerPoints[innerPoints.length - 1];
+ for (let i = 0; i < innerPoints.length; ++i) {
+ const p1 = innerPoints[i];
+
+ // polygon area updates easily ...
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
+
+ // updating the arc area is a little more involved
+ const midPoint = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
+ let arc = null;
+
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
+ // figure out the angle halfway between the two points
+ // on the current circle
+ const circle = circles[p1.parentIndex[j]];
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
+
+ let angleDiff = a2 - a1;
+ if (angleDiff < 0) {
+ angleDiff += 2 * Math.PI;
+ }
+
+ // and use that angle to figure out the width of the
+ // arc
+ const a = a2 - angleDiff / 2;
+ let width = distance(midPoint, {
+ x: circle.x + circle.radius * Math.sin(a),
+ y: circle.y + circle.radius * Math.cos(a),
+ });
+
+ // clamp the width to the largest is can actually be
+ // (sometimes slightly overflows because of FP errors)
+ if (width > circle.radius * 2) {
+ width = circle.radius * 2;
+ }
+
+ // pick the circle whose arc has the smallest width
+ if (arc == null || arc.width > width) {
+ arc = { circle, width, p1, p2, large: width > circle.radius, sweep: true };
+ }
+ }
+ }
+
+ if (arc != null) {
+ arcs.push(arc);
+ arcArea += circleArea(arc.circle.radius, arc.width);
+ p2 = p1;
+ }
+ }
+ } else {
+ // no intersection points, is either disjoint - or is completely
+ // overlapped. figure out which by examining the smallest circle
+ let smallest = circles[0];
+ for (let i = 1; i < circles.length; ++i) {
+ if (circles[i].radius < smallest.radius) {
+ smallest = circles[i];
+ }
+ }
+
+ // make sure the smallest circle is completely contained in all
+ // the other circles
+ let disjoint = false;
+ for (let i = 0; i < circles.length; ++i) {
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
+ disjoint = true;
+ break;
+ }
+ }
+
+ if (disjoint) {
+ arcArea = polygonArea = 0;
+ } else {
+ arcArea = smallest.radius * smallest.radius * Math.PI;
+ arcs.push({
+ circle: smallest,
+ p1: { x: smallest.x, y: smallest.y + smallest.radius },
+ p2: { x: smallest.x - SMALL, y: smallest.y + smallest.radius },
+ width: smallest.radius * 2,
+ large: true,
+ sweep: true,
+ });
+ }
+ }
+
+ polygonArea /= 2;
+
+ if (stats) {
+ stats.area = arcArea + polygonArea;
+ stats.arcArea = arcArea;
+ stats.polygonArea = polygonArea;
+ stats.arcs = arcs;
+ stats.innerPoints = innerPoints;
+ stats.intersectionPoints = intersectionPoints;
+ }
+
+ return arcArea + polygonArea;
+}
+
+/**
+ * returns whether a point is contained by all of a list of circles
+ * @param {{x: number, y: number}} point
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {boolean}
+ */
+export function containedInCircles(point, circles) {
+ return circles.every((circle) => distance(point, circle) < circle.radius + SMALL);
+}
+
+/**
+ * Gets all intersection points between a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
+ */
+function getIntersectionPoints(circles) {
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
+ const ret = [];
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
+ for (const p of intersect) {
+ p.parentIndex = [i, j];
+ ret.push(p);
+ }
+ }
+ }
+ return ret;
+}
+
+/**
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
+ * @param {number} r
+ * @param {number} width
+ * @returns {number}
+ **/
+export function circleArea(r, width) {
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
+}
+
+/**
+ * euclidean distance between two points
+ * @param {{x: number, y: number}} p1
+ * @param {{x: number, y: number}} p2
+ * @returns {number}
+ **/
+export function distance(p1, p2) {
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
+}
+
+/**
+ * Returns the overlap area of two circles of radius r1 and r2 - that
+ * have their centers separated by distance d. Simpler faster
+ * circle intersection for only two circles
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} d
+ * @returns {number}
+ */
+export function circleOverlap(r1, r2, d) {
+ // no overlap
+ if (d >= r1 + r2) {
+ return 0;
+ }
+
+ // completely overlapped
+ if (d <= Math.abs(r1 - r2)) {
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
+ }
+
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
+ return circleArea(r1, w1) + circleArea(r2, w2);
+}
+
+/**
+ * Given two circles (containing a x/y/radius attributes),
+ * returns the intersecting points if possible
+ * note: doesn't handle cases where there are infinitely many
+ * intersection points (circles are equivalent):, or only one intersection point
+ * @param {{x: number, y: number, radius: number}} p1
+ * @param {{x: number, y: number, radius: number}} p2
+ * @returns {ReadonlyArray<{x: number, y: number}>}
+ **/
+export function circleCircleIntersection(p1, p2) {
+ const d = distance(p1, p2);
+ const r1 = p1.radius;
+ const r2 = p2.radius;
+
+ // if to far away, or self contained - can't be done
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
+ return [];
+ }
+
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
+ const h = Math.sqrt(r1 * r1 - a * a);
+ const x0 = p1.x + (a * (p2.x - p1.x)) / d;
+ const y0 = p1.y + (a * (p2.y - p1.y)) / d;
+ const rx = -(p2.y - p1.y) * (h / d);
+ const ry = -(p2.x - p1.x) * (h / d);
+
+ return [
+ { x: x0 + rx, y: y0 - ry },
+ { x: x0 - rx, y: y0 + ry },
+ ];
+}
+
+/**
+ * Returns the center of a bunch of points
+ * @param {ReadonlyArray<{x: number, y: number}>} points
+ * @returns {{x: number, y: number}}
+ */
+export function getCenter(points) {
+ const center = { x: 0, y: 0 };
+ for (const point of points) {
+ center.x += point.x;
+ center.y += point.y;
+ }
+ center.x /= points.length;
+ center.y /= points.length;
+ return center;
+}
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.spec.js b/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..4bb062b0ffd9bfb7928d357b170f7994e0610f5c
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.spec.js
@@ -0,0 +1,125 @@
+import { distance, intersectionArea, circleCircleIntersection, circleOverlap, circleArea } from './circleintersection';
+import { describe, test, expect } from 'vitest';
+
+describe('circleArea', () => {
+ test('empty circle test', () => {
+ expect(circleArea(10, 0)).toBeCloseTo(0);
+ });
+ test('half circle test', () => {
+ expect(circleArea(10, 10)).toBeCloseTo((Math.PI * 10 * 10) / 2);
+ });
+ test('full circle test', () => {
+ expect(circleArea(10, 20)).toBeCloseTo(Math.PI * 10 * 10);
+ });
+});
+
+describe('circleOverlap', () => {
+ test('non overlapping circles test', () => {
+ expect(circleOverlap(10, 10, 200)).toBeCloseTo(0);
+ });
+
+ test('full overlapping circles test', () => {
+ expect(circleOverlap(10, 10, 0)).toBeCloseTo(Math.PI * 10 * 10);
+ expect(circleOverlap(10, 5, 5)).toBeCloseTo(Math.PI * 5 * 5);
+ });
+});
+
+describe('circleCircleIntersection', () => {
+ function testIntersection(p1, p2) {
+ const points = circleCircleIntersection(p1, p2);
+ // make sure that points are appropriately spaced
+ for (let i = 0; i < points.length; i++) {
+ const point = points[i];
+ expect(distance(point, p1)).toBeCloseTo(p1.radius);
+ expect(distance(point, p2)).toBeCloseTo(p2.radius);
+ }
+
+ return points;
+ }
+
+ test('fully contained', () => {
+ expect(circleCircleIntersection({ x: 0, y: 3, radius: 10 }, { x: 3, y: 0, radius: 20 })).toHaveLength(0);
+ });
+
+ test('fully disjoint', () => {
+ expect(circleCircleIntersection({ x: 0, y: 0, radius: 10 }, { x: 21, y: 0, radius: 10 })).toHaveLength(0);
+ });
+
+ test('midway between 2 points on y axis', () => {
+ const points = testIntersection(
+ { x: 0, y: 0, radius: 10 },
+ { x: 10, y: 0, radius: 10 },
+ 'test midway intersection'
+ );
+ expect(points).toHaveLength(2);
+ expect(points[0].x).toBeCloseTo(5);
+ expect(points[1].x).toBeCloseTo(5);
+ expect(points[0].y).toBeCloseTo(-1 * points[1].y);
+ });
+ test('failing case from input', () => {
+ const points = testIntersection({ radius: 10, x: 15, y: 5 }, { radius: 10, x: 20, y: 0 }, 'test intersection2');
+ expect(points).toHaveLength(2);
+ });
+});
+
+describe('intersectionArea', () => {
+ test('0', () => {
+ // each one of these circles overlaps all the others, but the total overlap is still 0
+ const circles = [
+ { x: 0.909, y: 0.905, radius: 0.548 },
+ { x: 0.765, y: 0.382, radius: 0.703 },
+ { x: 0.63, y: 0.019, radius: 0.449 },
+ { x: 0.21, y: 0.755, radius: 0.656 },
+ { x: 0.276, y: 0.723, radius: 1.145 },
+ { x: 0.141, y: 0.585, radius: 0.419 },
+ ];
+
+ const area = intersectionArea(circles);
+ expect(area).toBe(0);
+ });
+ test('1', () => {
+ // no intersection points, but the smallest circle is completely overlapped by each of the others
+ const circles = [
+ { x: 0.426, y: 0.882, radius: 0.944 },
+ { x: 0.24, y: 0.685, radius: 0.992 },
+ { x: 0.01, y: 0.909, radius: 1.161 },
+ { x: 0.54, y: 0.475, radius: 0.41 },
+ ];
+
+ expect(circles[3].radius * circles[3].radius * Math.PI).toBeCloseTo(intersectionArea(circles));
+ });
+});
+
+describe('randomFailures', () => {
+ test('0', () => {
+ const circles = [
+ { x: 0.501, y: 0.32, radius: 0.629 },
+ { x: 0.945, y: 0.022, radius: 1.015 },
+ { x: 0.021, y: 0.863, radius: 0.261 },
+ { x: 0.528, y: 0.09, radius: 0.676 },
+ ];
+ const area = intersectionArea(circles);
+
+ expect(Math.abs(area - 0.0008914)).toBeLessThan(0.0001);
+ });
+ test('1', () => {
+ const circles = [
+ { x: 9.154829758385864, y: 0, size: 226, radius: 8.481629223064205 },
+ { x: 5.806079662851866, y: 7.4438023223126795, size: 733, radius: 15.274853405932202 },
+ { x: 9.484491297623553, y: 4.064806303558571, size: 332, radius: 10.280023453913834 },
+ { x: 10.56492833796709, y: 3.0723147554880175, size: 244, radius: 8.812923024107548 },
+ ];
+
+ const area = intersectionArea(circles);
+ expect(area).toBeCloseTo(10.96362);
+ });
+ test('2', () => {
+ const circles = [
+ { x: -0.0014183481763938425, y: 0.0006071174738860746, radius: 510.3115834996166 },
+ { x: 875.0163281608848, y: 0.0007003612396158774, radius: 465.1793581792228 },
+ { x: 462.7394999567192, y: 387.9359963330729, radius: 172.62633992134658 },
+ ];
+ const area = intersectionArea(circles);
+ expect(area).not.toBeNaN();
+ });
+});
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.js b/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.js
new file mode 100644
index 0000000000000000000000000000000000000000..4165ef2a5a9820217d09f3f388bf83d58cd6a9fd
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.js
@@ -0,0 +1,783 @@
+import { venn, lossFunction, logRatioLossFunction, normalizeSolution, scaleSolution } from './layout';
+import { intersectionArea, distance, getCenter } from './circleintersection';
+import { nelderMead } from 'fmin';
+
+/**
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
+ *
+ * `colourScheme: Array`
+ * A list of color values to be applied when coloring diagram circles.
+ *
+ * `symmetricalTextCentre: Boolean`
+ * Whether to symmetrically center each circle's text horizontally and vertically.
+ * Defaults to `false`.
+ *
+ * `textFill: String`
+ * The color to be applied to the text within each circle.
+ *
+ * @param {object} options
+ */
+export function VennDiagram(options = {}) {
+ let useViewBox = false,
+ width = 600,
+ height = 350,
+ padding = 15,
+ duration = 1000,
+ orientation = Math.PI / 2,
+ normalize = true,
+ scaleToFit = null,
+ wrap = true,
+ styled = true,
+ fontSize = null,
+ orientationOrder = null,
+ distinct = false,
+ round = null,
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
+ // mimic the behaviour of d3.scale.category10 from the previous
+ // version of d3
+ colourMap = {},
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
+ // since we can support older versions of d3 as long as we don't force this,
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
+ colourScheme =
+ options && options.colourScheme
+ ? options.colourScheme
+ : options && options.colorScheme
+ ? options.colorScheme
+ : [
+ '#1f77b4',
+ '#ff7f0e',
+ '#2ca02c',
+ '#d62728',
+ '#9467bd',
+ '#8c564b',
+ '#e377c2',
+ '#7f7f7f',
+ '#bcbd22',
+ '#17becf',
+ ],
+ colourIndex = 0,
+ colours = function (key) {
+ if (key in colourMap) {
+ return colourMap[key];
+ }
+ var ret = (colourMap[key] = colourScheme[colourIndex]);
+ colourIndex += 1;
+ if (colourIndex >= colourScheme.length) {
+ colourIndex = 0;
+ }
+ return ret;
+ },
+ layoutFunction = venn,
+ loss = lossFunction;
+
+ function chart(selection) {
+ let data = selection.datum();
+
+ // handle 0-sized sets by removing from input
+ const toRemove = new Set();
+ data.forEach((datum) => {
+ if (datum.size == 0 && datum.sets.length == 1) {
+ toRemove.add(datum.sets[0]);
+ }
+ });
+ data = data.filter((datum) => !datum.sets.some((set) => toRemove.has(set)));
+
+ let circles = {};
+ let textCentres = {};
+
+ if (data.length > 0) {
+ let solution = layoutFunction(data, { lossFunction: loss, distinct });
+
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+ }
+
+ // Figure out the current label for each set. These can change
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
+ const labels = {};
+ data.forEach((datum) => {
+ if (datum.label) {
+ labels[datum.sets] = datum.label;
+ }
+ });
+
+ function label(d) {
+ if (d.sets in labels) {
+ return labels[d.sets];
+ }
+ if (d.sets.length == 1) {
+ return '' + d.sets[0];
+ }
+ }
+
+ // create svg if not already existing
+ selection.selectAll('svg').data([circles]).enter().append('svg');
+
+ const svg = selection.select('svg');
+
+ if (useViewBox) {
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
+ } else {
+ svg.attr('width', width).attr('height', height);
+ }
+
+ // to properly transition intersection areas, we need the
+ // previous circles locations. load from elements
+ const previous = {};
+ let hasPrevious = false;
+ svg.selectAll('.venn-area path').each(function (d) {
+ const path = this.getAttribute('d');
+ if (d.sets.length == 1 && path && !distinct) {
+ hasPrevious = true;
+ previous[d.sets[0]] = circleFromPath(path);
+ }
+ });
+ // interpolate intersection area paths between previous and
+ // current paths
+ function pathTween(d) {
+ return (t) => {
+ const c = d.sets.map((set) => {
+ let start = previous[set];
+ let end = circles[set];
+ if (!start) {
+ start = { x: width / 2, y: height / 2, radius: 1 };
+ }
+ if (!end) {
+ end = { x: width / 2, y: height / 2, radius: 1 };
+ }
+ return {
+ x: start.x * (1 - t) + end.x * t,
+ y: start.y * (1 - t) + end.y * t,
+ radius: start.radius * (1 - t) + end.radius * t,
+ };
+ });
+ return intersectionAreaPath(c, round);
+ };
+ }
+
+ // update data, joining on the set ids
+ const nodes = svg.selectAll('.venn-area').data(data, (d) => d.sets);
+
+ // create new nodes
+ const enter = nodes
+ .enter()
+ .append('g')
+ .attr(
+ 'class',
+ (d) =>
+ `venn-area venn-${d.sets.length == 1 ? 'circle' : 'intersection'}${
+ d.colour || d.color ? ' venn-coloured' : ''
+ }`
+ )
+ .attr('data-venn-sets', (d) => d.sets.join('_'));
+
+ const enterPath = enter.append('path');
+ const enterText = enter
+ .append('text')
+ .attr('class', 'label')
+ .text((d) => label(d))
+ .attr('text-anchor', 'middle')
+ .attr('dy', '.35em')
+ .attr('x', width / 2)
+ .attr('y', height / 2);
+
+ // apply minimal style if wanted
+ if (styled) {
+ enterPath
+ .style('fill-opacity', '0')
+ .filter((d) => d.sets.length == 1)
+ .style('fill', (d) => (d.colour ? d.colour : d.color ? d.color : colours(d.sets)))
+ .style('fill-opacity', '.25');
+
+ enterText.style('fill', (d) => {
+ if (d.colour || d.color) {
+ return '#FFF';
+ }
+ if (options.textFill) {
+ return options.textFill;
+ }
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
+ });
+ }
+
+ function asTransition(s) {
+ if (typeof s.transition === 'function') {
+ return s.transition('venn').duration(duration);
+ }
+ return s;
+ }
+
+ // update existing, using pathTween if necessary
+ let update = selection;
+ if (hasPrevious && typeof update.transition === 'function') {
+ update = asTransition(selection);
+ update.selectAll('path').attrTween('d', pathTween);
+ } else {
+ update.selectAll('path').attr('d', (d) => intersectionAreaPath(d.sets.map((set) => circles[set])), round);
+ }
+
+ const updateText = update
+ .selectAll('text')
+ .filter((d) => d.sets in textCentres)
+ .text((d) => label(d))
+ .attr('x', (d) => Math.floor(textCentres[d.sets].x))
+ .attr('y', (d) => Math.floor(textCentres[d.sets].y));
+
+ if (wrap) {
+ if (hasPrevious) {
+ // d3 4.0 uses 'on' for events on transitions,
+ // but d3 3.0 used 'each' instead. switch appropriately
+ if ('on' in updateText) {
+ updateText.on('end', wrapText(circles, label));
+ } else {
+ updateText.each('end', wrapText(circles, label));
+ }
+ } else {
+ updateText.each(wrapText(circles, label));
+ }
+ }
+
+ // remove old
+ const exit = asTransition(nodes.exit()).remove();
+ if (typeof nodes.transition === 'function') {
+ exit.selectAll('path').attrTween('d', pathTween);
+ }
+
+ const exitText = exit
+ .selectAll('text')
+ .attr('x', width / 2)
+ .attr('y', height / 2);
+
+ // if we've been passed a fontSize explicitly, use it to
+ // transition
+ if (fontSize !== null) {
+ enterText.style('font-size', '0px');
+ updateText.style('font-size', fontSize);
+ exitText.style('font-size', '0px');
+ }
+
+ return { circles, textCentres, nodes, enter, update, exit };
+ }
+
+ chart.wrap = function (_) {
+ if (!arguments.length) return wrap;
+ wrap = _;
+ return chart;
+ };
+
+ chart.useViewBox = function () {
+ useViewBox = true;
+ return chart;
+ };
+
+ chart.width = function (_) {
+ if (!arguments.length) return width;
+ width = _;
+ return chart;
+ };
+
+ chart.height = function (_) {
+ if (!arguments.length) return height;
+ height = _;
+ return chart;
+ };
+
+ chart.padding = function (_) {
+ if (!arguments.length) return padding;
+ padding = _;
+ return chart;
+ };
+
+ chart.distinct = function (_) {
+ if (!arguments.length) return distinct;
+ distinct = _;
+ return chart;
+ };
+
+ chart.colours = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+
+ chart.colors = function (_) {
+ if (!arguments.length) return colours;
+ colours = _;
+ return chart;
+ };
+
+ chart.fontSize = function (_) {
+ if (!arguments.length) return fontSize;
+ fontSize = _;
+ return chart;
+ };
+
+ chart.round = function (_) {
+ if (!arguments.length) return round;
+ round = _;
+ return chart;
+ };
+
+ chart.duration = function (_) {
+ if (!arguments.length) return duration;
+ duration = _;
+ return chart;
+ };
+
+ chart.layoutFunction = function (_) {
+ if (!arguments.length) return layoutFunction;
+ layoutFunction = _;
+ return chart;
+ };
+
+ chart.normalize = function (_) {
+ if (!arguments.length) return normalize;
+ normalize = _;
+ return chart;
+ };
+
+ chart.scaleToFit = function (_) {
+ if (!arguments.length) return scaleToFit;
+ scaleToFit = _;
+ return chart;
+ };
+
+ chart.styled = function (_) {
+ if (!arguments.length) return styled;
+ styled = _;
+ return chart;
+ };
+
+ chart.orientation = function (_) {
+ if (!arguments.length) return orientation;
+ orientation = _;
+ return chart;
+ };
+
+ chart.orientationOrder = function (_) {
+ if (!arguments.length) return orientationOrder;
+ orientationOrder = _;
+ return chart;
+ };
+
+ chart.lossFunction = function (_) {
+ if (!arguments.length) return loss;
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
+ return chart;
+ };
+
+ return chart;
+}
+
+// sometimes text doesn't fit inside the circle, if thats the case lets wrap
+// the text here such that it fits
+// todo: looks like this might be merged into d3 (
+// https://github.com/mbostock/d3/issues/1642),
+// also worth checking out is
+// http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
+// this seems to be one of those things that should be easy but isn't
+export function wrapText(circles, labeller) {
+ return function (data) {
+ const text = this;
+ const width = circles[data.sets[0]].radius || 50;
+ const label = labeller(data) || '';
+
+ const words = label.split(/\s+/).reverse();
+ const maxLines = 3;
+ const minChars = (label.length + words.length) / maxLines;
+
+ let word = words.pop();
+ let line = [word];
+ let lineNumber = 0;
+ const lineHeight = 1.1; // ems
+ text.textContent = null; // clear
+ const tspans = [];
+
+ function append(word) {
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
+ tspan.textContent = word;
+ tspans.push(tspan);
+ text.append(tspan);
+ return tspan;
+ }
+ let tspan = append(word);
+
+ while (true) {
+ word = words.pop();
+ if (!word) {
+ break;
+ }
+ line.push(word);
+ const joined = line.join(' ');
+ tspan.textContent = joined;
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
+ line.pop();
+ tspan.textContent = line.join(' ');
+ line = [word];
+ tspan = append(word);
+ lineNumber++;
+ }
+ }
+
+ const initial = 0.35 - (lineNumber * lineHeight) / 2;
+ const x = text.getAttribute('x');
+ const y = text.getAttribute('y');
+ tspans.forEach((t, i) => {
+ t.setAttribute('x', x);
+ t.setAttribute('y', y);
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
+ });
+ };
+}
+
+/**
+ *
+ * @param {{x: number, y: number}} current
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
+ * @returns {number}
+ */
+function circleMargin(current, interior, exterior) {
+ let margin = interior[0].radius - distance(interior[0], current);
+
+ for (let i = 1; i < interior.length; ++i) {
+ const m = interior[i].radius - distance(interior[i], current);
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+
+ for (let i = 0; i < exterior.length; ++i) {
+ const m = distance(exterior[i], current) - exterior[i].radius;
+ if (m <= margin) {
+ margin = m;
+ }
+ }
+ return margin;
+}
+
+/**
+ * compute the center of some circles by maximizing the margin of
+ * the center point relative to the circles (interior) after subtracting
+ * nearby circles (exterior)
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
+ * @param {boolean} symmetricalTextCentre
+ * @returns {{x:number, y: number}}
+ */
+export function computeTextCentre(interior, exterior, symmetricalTextCentre) {
+ // get an initial estimate by sampling around the interior circles
+ // and taking the point with the biggest margin
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (const c of interior) {
+ points.push({ x: c.x, y: c.y });
+ points.push({ x: c.x + c.radius / 2, y: c.y });
+ points.push({ x: c.x - c.radius / 2, y: c.y });
+ points.push({ x: c.x, y: c.y + c.radius / 2 });
+ points.push({ x: c.x, y: c.y - c.radius / 2 });
+ }
+
+ let initial = points[0];
+ let margin = circleMargin(points[0], interior, exterior);
+
+ for (let i = 1; i < points.length; ++i) {
+ const m = circleMargin(points[i], interior, exterior);
+ if (m >= margin) {
+ initial = points[i];
+ margin = m;
+ }
+ }
+
+ // maximize the margin numerically
+ const solution = nelderMead(
+ (p) => -1 * circleMargin({ x: p[0], y: p[1] }, interior, exterior),
+ [initial.x, initial.y],
+ { maxIterations: 500, minErrorDelta: 1e-10 }
+ ).x;
+
+ const ret = { x: symmetricalTextCentre ? 0 : solution[0], y: solution[1] };
+
+ // check solution, fallback as needed (happens if fully overlapped
+ // etc)
+ let valid = true;
+ for (const i of interior) {
+ if (distance(ret, i) > i.radius) {
+ valid = false;
+ break;
+ }
+ }
+
+ for (const e of exterior) {
+ if (distance(ret, e) < e.radius) {
+ valid = false;
+ break;
+ }
+ }
+ if (valid) {
+ return ret;
+ }
+
+ if (interior.length == 1) {
+ return { x: interior[0].x, y: interior[0].y };
+ }
+ const areaStats = {};
+ intersectionArea(interior, areaStats);
+
+ if (areaStats.arcs.length === 0) {
+ return { x: 0, y: -1000, disjoint: true };
+ }
+ if (areaStats.arcs.length == 1) {
+ return { x: areaStats.arcs[0].circle.x, y: areaStats.arcs[0].circle.y };
+ }
+ if (exterior.length) {
+ // try again without other circles
+ return computeTextCentre(interior, []);
+ }
+ // take average of all the points in the intersection
+ // polygon. this should basically never happen
+ // and has some issues:
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
+ return getCenter(areaStats.arcs.map((a) => a.p1));
+}
+
+// given a dictionary of {setid : circle}, returns
+// a dictionary of setid to list of circles that completely overlap it
+function getOverlappingCircles(circles) {
+ const ret = {};
+ const circleids = Object.keys(circles);
+ for (const circleid of circleids) {
+ ret[circleid] = [];
+ }
+ for (let i = 0; i < circleids.length; i++) {
+ const ci = circleids[i];
+ const a = circles[ci];
+ for (let j = i + 1; j < circleids.length; ++j) {
+ const cj = circleids[j];
+ const b = circles[cj];
+ const d = distance(a, b);
+
+ if (d + b.radius <= a.radius + 1e-10) {
+ ret[cj].push(ci);
+ } else if (d + a.radius <= b.radius + 1e-10) {
+ ret[ci].push(cj);
+ }
+ }
+ }
+ return ret;
+}
+
+export function computeTextCentres(circles, areas, symmetricalTextCentre) {
+ const ret = {};
+ const overlapped = getOverlappingCircles(circles);
+ for (let i = 0; i < areas.length; ++i) {
+ const area = areas[i].sets;
+ const areaids = {};
+ const exclude = {};
+
+ for (let j = 0; j < area.length; ++j) {
+ areaids[area[j]] = true;
+ const overlaps = overlapped[area[j]];
+ // keep track of any circles that overlap this area,
+ // and don't consider for purposes of computing the text
+ // centre
+ for (let k = 0; k < overlaps.length; ++k) {
+ exclude[overlaps[k]] = true;
+ }
+ }
+
+ const interior = [];
+ const exterior = [];
+ for (let setid in circles) {
+ if (setid in areaids) {
+ interior.push(circles[setid]);
+ } else if (!(setid in exclude)) {
+ exterior.push(circles[setid]);
+ }
+ }
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
+ ret[area] = centre;
+ if (centre.disjoint && areas[i].size > 0) {
+ console.log('WARNING: area ' + area + ' not represented on screen');
+ }
+ }
+ return ret;
+}
+
+// sorts all areas in the venn diagram, so that
+// a particular area is on top (relativeTo) - and
+// all other areas are so that the smallest areas are on top
+export function sortAreas(div, relativeTo) {
+ // figure out sets that are completely overlapped by relativeTo
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
+ const exclude = new Set();
+ for (const check of relativeTo.sets) {
+ for (let setid in overlaps) {
+ const overlap = overlaps[setid];
+ for (let j = 0; j < overlap.length; ++j) {
+ if (overlap[j] == check) {
+ exclude.add(setid);
+ break;
+ }
+ }
+ }
+ }
+
+ // checks that all sets are in exclude;
+ function shouldExclude(sets) {
+ return sets.every((set) => !exclude.has(set));
+ }
+
+ // need to sort div's so that Z order is correct
+ div.selectAll('g').sort((a, b) => {
+ // highest order set intersections first
+ if (a.sets.length != b.sets.length) {
+ return a.sets.length - b.sets.length;
+ }
+
+ if (a == relativeTo) {
+ return shouldExclude(b.sets) ? -1 : 1;
+ }
+ if (b == relativeTo) {
+ return shouldExclude(a.sets) ? 1 : -1;
+ }
+
+ // finally by size
+ return b.size - a.size;
+ });
+}
+
+/**
+ * @param {number} x
+ * @param {number} y
+ * @param {number} r
+ * @returns {string}
+ */
+export function circlePath(x, y, r) {
+ const ret = [];
+ ret.push('\nM', x, y);
+ ret.push('\nm', -r, 0);
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
+ return ret.join(' ');
+}
+
+/**
+ * inverse of the circlePath function, returns a circle object from an svg path
+ * @param {string} path
+ * @returns {{x: number, y: number, radius: number}}
+ */
+export function circleFromPath(path) {
+ const tokens = path.split(' ');
+ return { x: Number.parseFloat(tokens[1]), y: Number.parseFloat(tokens[2]), radius: -Number.parseFloat(tokens[4]) };
+}
+
+function intersectionAreaArcs(circles) {
+ if (circles.length === 0) {
+ return [];
+ }
+ const stats = {};
+ intersectionArea(circles, stats);
+ return stats.arcs;
+}
+
+function arcsToPath(arcs, round) {
+ if (arcs.length === 0) {
+ return 'M 0 0';
+ }
+ const rFactor = Math.pow(10, round || 0);
+ const r = round != null ? (v) => Math.round(v * rFactor) / rFactor : (v) => v;
+ if (arcs.length == 1) {
+ const circle = arcs[0].circle;
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
+ }
+ // draw path around arcs
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
+ for (const arc of arcs) {
+ const radius = r(arc.circle.radius);
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
+ }
+ return ret.join(' ');
+}
+
+/**
+ * returns a svg path of the intersection area of a bunch of circles
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {string}
+ */
+export function intersectionAreaPath(circles, round) {
+ return arcsToPath(intersectionAreaArcs(circles), round);
+}
+
+export function layout(data, options = {}) {
+ const {
+ lossFunction: loss,
+ layoutFunction: layout = venn,
+ normalize = true,
+ orientation = Math.PI / 2,
+ orientationOrder,
+ width = 600,
+ height = 350,
+ padding = 15,
+ scaleToFit = false,
+ symmetricalTextCentre = false,
+ distinct,
+ round = 2,
+ } = options;
+
+ let solution = layout(data, {
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
+ distinct,
+ });
+
+ if (normalize) {
+ solution = normalizeSolution(solution, orientation, orientationOrder);
+ }
+
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
+
+ const circleLookup = new Map(
+ Object.keys(circles).map((set) => [
+ set,
+ {
+ set,
+ x: circles[set].x,
+ y: circles[set].y,
+ radius: circles[set].radius,
+ },
+ ])
+ );
+ const helpers = data.map((area) => {
+ const circles = area.sets.map((s) => circleLookup.get(s));
+ const arcs = intersectionAreaArcs(circles);
+ const path = arcsToPath(arcs, round);
+ return { circles, arcs, path, area, has: new Set(area.sets) };
+ });
+
+ function genDistinctPath(sets) {
+ let r = '';
+ for (const e of helpers) {
+ if (e.has.size > sets.length && sets.every((s) => e.has.has(s))) {
+ r += ' ' + e.path;
+ }
+ }
+ return r;
+ }
+
+ return helpers.map(({ circles, arcs, path, area }) => {
+ return {
+ data: area,
+ text: textCentres[area.sets],
+ circles,
+ arcs,
+ path,
+ distinctPath: path + genDistinctPath(area.sets),
+ };
+ });
+}
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.spec.js b/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..dc51258d23850fd8bc290a3009af55a1a530e736
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/diagram.spec.js
@@ -0,0 +1,16 @@
+import { computeTextCentre } from './diagram';
+import { describe, test, expect } from 'vitest';
+
+describe('computeTextCentre', () => {
+ test('0', () => {
+ const center = computeTextCentre([{ x: 0, y: 0, radius: 1 }], []);
+ expect(center.x).toBeCloseTo(0);
+ expect(center.y).toBeCloseTo(0);
+ });
+
+ test('1', () => {
+ const center = computeTextCentre([{ x: 0, y: 0, radius: 1 }], [{ x: 0, y: 1, radius: 1 }]);
+ expect(center.x).toBeCloseTo(0, 4);
+ expect(center.y).toBeCloseTo(-0.5);
+ });
+});
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/index.d.ts b/tools/ui/node_modules/@upsetjs/venn.js/src/index.d.ts
new file mode 100644
index 0000000000000000000000000000000000000000..7060d6820b92bbd57470ffa0669bab5daad987f3
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/index.d.ts
@@ -0,0 +1,319 @@
+import { Selection } from 'd3-selection';
+
+export interface ISetOverlap {
+ sets: readonly string[];
+ size: number;
+ weight?: number;
+}
+
+export interface IPoint {
+ x: number;
+ y: number;
+}
+
+export interface IHierarchyPoint extends IPoint {
+ parentIndex: [number, number];
+}
+
+export interface ICircle {
+ x: number;
+ y: number;
+ radius: number;
+ setid: string;
+}
+
+export interface ISolution {
+ [set: string]: ICircle;
+}
+
+/**
+ * given a list of set objects, and their corresponding overlaps
+ * updates the(x, y, radius) attribute on each set such that their positions
+ * roughly correspond to the desired overlaps
+ */
+export function venn(areas: readonly ISetOverlap[], parameters?: any): ISolution;
+
+/**
+ * Returns the distance necessary for two circles of radius r1 + r2 to
+ * have the overlap area 'overlap'
+ */
+export function distanceFromIntersectArea(r1: number, r2: number, overlap: number): number;
+
+/**
+ * takes the best working variant of either constrained MDS or greedy
+ */
+export function bestInitialLayout(areas: readonly ISetOverlap[], params?: any): ISolution;
+
+/**
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
+ * least overlapped, attempting to position each new set such that the
+ * overlapping areas to already positioned sets are basically right
+ */
+export function greedyLayout(areas: readonly ISetOverlap[], params?: any): ISolution;
+
+/**
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
+ * the distance from the actual overlaps to the desired overlaps. Note that
+ * this method ignores overlaps of more than 2 circles
+ */
+export function lossFunction(circles: ISolution, areas: readonly ISetOverlap[]): number;
+
+export function logRatioLossFunction(circles: ISolution, areas: readonly ISetOverlap[]): number;
+
+export function disjointCluster(circles: ICircle[]): ICircle[][];
+
+export function normalizeSolution(
+ solution: ISolution,
+ orientation?: number,
+ orientationOrder?: (a: ICircle, b: ICircle) => number
+): ISolution;
+
+/**
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
+ * a rectangle of width/height - with padding around the borders. also
+ * centers the diagram in the available space at the same time.
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
+ */
+export function scaleSolution(
+ solution: ISolution,
+ width: number,
+ height: number,
+ padding: number,
+ scaleToFit?: boolean
+): ISolution;
+
+/**
+ * Returns the intersection area of a bunch of circles (where each circle
+ * is an object having an x,y and radius property)
+ */
+export function intersectionArea(
+ circles: readonly ICircle[],
+ stats?: {
+ area?: number;
+ areaArea?: number;
+ polygonArea?: number;
+ arcs?: readonly { circle: ICircle; width: number; p1: IPoint; p2: IPoint }[];
+ innerPoints?: readonly IHierarchyPoint[];
+ intersectionPoints?: readonly IHierarchyPoint[];
+ }
+): number;
+
+/**
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
+ */
+export function circleArea(r: number, width: number): number;
+
+/**
+ * euclidean distance between two points
+ */
+export function distance(p1: IPoint, p2: IPoint): number;
+
+/**
+ * Returns the overlap area of two circles of radius r1 and r2 - that
+ * have their centers separated by distance d. Simpler faster
+ * circle intersection for only two circles
+ */
+export function circleOverlap(r1: number, r2: number, d: number): number;
+
+/**
+ * Given two circles (containing a x/y/radius attributes),
+ * returns the intersecting points if possible
+ * note: doesn't handle cases where there are infinitely many
+ * intersection points (circles are equivalent):, or only one intersection point
+ */
+export function circleCircleIntersection(p1: ICircle, p2: ICircle): readonly IPoint[];
+
+// sometimes text doesn't fit inside the circle, if thats the case lets wrap
+// the text here such that it fits
+// todo: looks like this might be merged into d3 (
+// https://github.com/mbostock/d3/issues/1642),
+// also worth checking out is
+// http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
+// this seems to be one of those things that should be easy but isn't
+export function wrapText(circles: ISolution, labeller: (d: any) => string): (this: SVGTextElement) => void;
+
+/**
+ * compute the center of some circles by maximizing the margin of
+ * the center point relative to the circles (interior) after subtracting
+ * nearby circles (exterior)
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
+ * @param {boolean} symmetricalTextCentre
+ * @returns {{x:number, y: number}}
+ */
+export function computeTextCentre(
+ interior: readonly ICircle[],
+ exterior: readonly ICircle[],
+ symmetricalTextCentre?: boolean
+): IPoint;
+
+export function computeTextCentres(
+ circles: ISolution,
+ areas: readonly ISetOverlap[],
+ symmetricalTextCentre?: boolean
+): { [set: string]: IPoint };
+
+// sorts all areas in the venn diagram, so that
+// a particular area is on top (relativeTo) - and
+// all other areas are so that the smallest areas are on top
+export function sortAreas(div: Selection, relativeTo: { sets: readonly string[] }): void;
+
+export function circlePath(x: number, y: number, r: number): string;
+
+/**
+ * inverse of the circlePath function, returns a circle object from an svg path
+ */
+export function circleFromPath(path: string): ICircle;
+
+/**
+ * returns a svg path of the intersection area of a bunch of circles
+ */
+export function intersectionAreaPath(circles: readonly ICircle[]): string;
+
+export interface IVennDiagramOptions {
+ colourScheme?: readonly string[];
+ colorScheme?: readonly string[];
+ symmetricalTextCentre?: boolean;
+ textFill?: string;
+}
+
+export interface IStyledSetOverlap extends ISetOverlap {
+ color?: string;
+ colour?: string;
+}
+
+export interface IVennDiagram {
+ (selection: Selection): {
+ circles: ISolution;
+ textCentres: { [set: string]: IPoint };
+ nodes: Selection;
+ enter: Selection;
+ update: Selection;
+ exit: Selection;
+ };
+
+ /**
+ * wrap the labels
+ * @default true
+ */
+ wrap(): boolean;
+ wrap(v: boolean): this;
+ /**
+ * use a view box instead of specifying with and height
+ * @default false
+ */
+ useViewBox(): this;
+
+ width(): number;
+ width(v: number): this;
+ height(): number;
+ height(v: number): this;
+ padding(): number;
+ padding(v: number): this;
+ colours(): (key: string) => string;
+ colours(v: (key: string) => string): this;
+ colors(): (key: string) => string;
+ colors(v: (key: string) => string): this;
+ fontSize(): string | null;
+ fontSize(v: string | null): this;
+
+ duration(): number;
+ duration(v: number): this;
+
+ /**
+ * normalize the solution
+ * @default true
+ */
+ normalize(): boolean;
+ normalize(v: boolean): this;
+ layoutFunction(): typeof venn;
+ layoutFunction(v: typeof venn): this;
+
+ scaleToFit(): boolean;
+ scaleToFit(v: boolean): this;
+
+ styled(): boolean;
+ styled(v: boolean): this;
+
+ /**
+ * round generate path to the given number of digits or null to disable
+ * @default null
+ */
+ round(): number | null;
+ round(v: number | null): this;
+
+ /**
+ * interpret the data as distinct sets, so set A is actually set A \ B u C
+ * thus A is (A \ (B u C)) u (A ^ B \ C) u (A ^ C \ B) u (A ^ B ^ C)
+ * @default false
+ */
+ distinct(): boolean;
+ distinct(v: boolean): this;
+
+ orientation(): number;
+ orientation(v: number): this;
+ orientationOrder(): null | ((a: ICircle, b: ICircle) => number);
+ orientationOrder(v: null | ((a: ICircle, b: ICircle) => number)): this;
+
+ lossFunction(): typeof lossFunction;
+ lossFunction(v: 'logRatio'): this;
+ lossFunction(v: 'default'): this;
+ lossFunction(v: typeof lossFunction): this;
+}
+
+/**
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
+ *
+ * `colourScheme: Array`
+ * A list of color values to be applied when coloring diagram circles.
+ *
+ * `symmetricalTextCentre: Boolean`
+ * Whether to symmetrically center each circle's text horizontally and vertically.
+ * Defaults to `false`.
+ *
+ * `textFill: String`
+ * The color to be applied to the text within each circle.
+ */
+export function VennDiagram(options?: IVennDiagramOptions): IVennDiagram;
+
+export interface IComputeVennLayoutOptions {
+ width?: number;
+ height?: number;
+ padding?: number;
+ /**
+ * @default true
+ */
+ normalize?: boolean;
+ layoutFunction?: typeof venn;
+ lossFunction?: typeof lossFunction | 'logRatio';
+ scaleToFit?: boolean;
+ orientation?: number;
+ distinct?: boolean;
+ /**
+ * @default 2
+ */
+ round?: number;
+ orientationOrder?: (a: ICircle, b: ICircle) => number;
+}
+
+export interface IVennLayout {
+ data: T;
+ /**
+ * text location
+ */
+ text: IPoint;
+ circles: readonly (ICircle & { set: string })[];
+ arcs: readonly { circle: ICircle; width: number; p1: IPoint; p2: IPoint; large: boolean; sweep: boolean }[];
+ /**
+ * SVG path
+ */
+ path: string;
+ /**
+ * distinct SVG path, render with `fill-rule: evenodd`;
+ */
+ distinctPath: string;
+}
+export function layout(
+ data: readonly T[],
+ options?: IComputeVennLayoutOptions
+): IVennLayout[];
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/index.js b/tools/ui/node_modules/@upsetjs/venn.js/src/index.js
new file mode 100644
index 0000000000000000000000000000000000000000..1365c9eee45a33d4357c50b33d07f48f8db0deb5
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/index.js
@@ -0,0 +1,23 @@
+export { intersectionArea, circleCircleIntersection, circleOverlap, circleArea, distance } from './circleintersection';
+export {
+ venn,
+ greedyLayout,
+ scaleSolution,
+ normalizeSolution,
+ bestInitialLayout,
+ lossFunction,
+ logRatioLossFunction,
+ disjointCluster,
+ distanceFromIntersectArea,
+} from './layout';
+export {
+ VennDiagram,
+ wrapText,
+ computeTextCentres,
+ computeTextCentre,
+ sortAreas,
+ circlePath,
+ circleFromPath,
+ intersectionAreaPath,
+ layout,
+} from './diagram';
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/layout.js b/tools/ui/node_modules/@upsetjs/venn.js/src/layout.js
new file mode 100644
index 0000000000000000000000000000000000000000..7d846add3b4afc715e197cfe6aa3c1aac137a067
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/layout.js
@@ -0,0 +1,820 @@
+import { nelderMead, bisect, conjugateGradient, zeros, zerosM, norm2, scale } from 'fmin';
+import { intersectionArea, circleOverlap, circleCircleIntersection, distance } from './circleintersection';
+
+/**
+ * given a list of set objects, and their corresponding overlaps
+ * updates the (x, y, radius) attribute on each set such that their positions
+ * roughly correspond to the desired overlaps
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+export function venn(sets, parameters = {}) {
+ parameters.maxIterations = parameters.maxIterations || 500;
+
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
+ const loss = parameters.lossFunction || lossFunction;
+
+ // add in missing pairwise areas as having 0 size
+ const areas = addMissingAreas(sets, parameters);
+
+ // initial layout is done greedily
+ const circles = initialLayout(areas, parameters);
+
+ // transform x/y coordinates to a vector to optimize
+ const setids = Object.keys(circles);
+ /** @type {number[]} */
+ const initial = [];
+ for (const setid of setids) {
+ initial.push(circles[setid].x);
+ initial.push(circles[setid].y);
+ }
+
+ // optimize initial layout from our loss function
+ const solution = nelderMead(
+ (values) => {
+ const current = {};
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ current[setid] = {
+ x: values[2 * i],
+ y: values[2 * i + 1],
+ radius: circles[setid].radius,
+ // size : circles[setid].size
+ };
+ }
+ return loss(current, areas);
+ },
+ initial,
+ parameters
+ );
+
+ // transform solution vector back to x/y points
+ const positions = solution.x;
+ for (let i = 0; i < setids.length; ++i) {
+ const setid = setids[i];
+ circles[setid].x = positions[2 * i];
+ circles[setid].y = positions[2 * i + 1];
+ }
+
+ return circles;
+}
+
+const SMALL = 1e-10;
+
+/**
+ * Returns the distance necessary for two circles of radius r1 + r2 to
+ * have the overlap area 'overlap'
+ * @param {number} r1
+ * @param {number} r2
+ * @param {number} overlap
+ * @returns {number}
+ */
+export function distanceFromIntersectArea(r1, r2, overlap) {
+ // handle complete overlapped circles
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
+ return Math.abs(r1 - r2);
+ }
+
+ return bisect((distance) => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
+}
+
+/**
+ * Missing pair-wise intersection area data can cause problems:
+ * treating as an unknown means that sets will be laid out overlapping,
+ * which isn't what people expect. To reflect that we want disjoint sets
+ * here, set the overlap to 0 for all missing pairwise set intersections
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {ReadonlyArray<{sets: ReadonlyArray, size: number}>}
+ */
+function addMissingAreas(areas, parameters = {}) {
+ const distinct = parameters.distinct;
+ const r = areas.map((s) => Object.assign({}, s));
+
+ function toKey(arr) {
+ return arr.join(';');
+ }
+
+ if (distinct) {
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
+ /** @types Map */
+ const count = new Map();
+ for (const area of r) {
+ for (let i = 0; i < area.sets.length; i++) {
+ const si = String(area.sets[i]);
+ count.set(si, area.size + (count.get(si) || 0));
+ for (let j = i + 1; j < area.sets.length; j++) {
+ const sj = String(area.sets[j]);
+ const k1 = `${si};${sj}`;
+ const k2 = `${sj};${si}`;
+ count.set(k1, area.size + (count.get(k1) || 0));
+ count.set(k2, area.size + (count.get(k2) || 0));
+ }
+ }
+ }
+ for (const area of r) {
+ if (area.sets.length < 3) {
+ area.size = count.get(toKey(area.sets));
+ }
+ }
+ }
+
+ // two circle intersections that aren't defined
+ const ids = [];
+
+ /** @type {Set} */
+ const pairs = new Set();
+ for (const area of r) {
+ if (area.sets.length === 1) {
+ ids.push(area.sets[0]);
+ } else if (area.sets.length === 2) {
+ const a = area.sets[0];
+ const b = area.sets[1];
+ pairs.add(toKey(area.sets));
+ pairs.add(toKey([b, a]));
+ }
+ }
+
+ ids.sort((a, b) => (a === b ? 0 : a < b ? -1 : +1));
+
+ for (let i = 0; i < ids.length; ++i) {
+ const a = ids[i];
+ for (let j = i + 1; j < ids.length; ++j) {
+ const b = ids[j];
+ if (!pairs.has(toKey([a, b]))) {
+ r.push({ sets: [a, b], size: 0 });
+ }
+ }
+ }
+ return r;
+}
+
+/**
+ * Returns two matrices, one of the euclidean distances between the sets
+ * and the other indicating if there are subset or disjoint set relationships
+ * @param {ReadonlyArray<{sets: ReadonlyArray}>} areas
+ * @param {ReadonlyArray<{size: number}>} sets
+ * @param {ReadonlyArray} setids
+ */
+export function getDistanceMatrices(areas, sets, setids) {
+ // initialize an empty distance matrix between all the points
+ /**
+ * @type {number[][]}
+ */
+ const distances = zerosM(sets.length, sets.length);
+ /**
+ * @type {number[][]}
+ */
+ const constraints = zerosM(sets.length, sets.length);
+
+ // compute required distances between all the sets such that
+ // the areas match
+ areas
+ .filter((x) => x.sets.length === 2)
+ .forEach((current) => {
+ const left = setids[current.sets[0]];
+ const right = setids[current.sets[1]];
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
+
+ distances[left][right] = distances[right][left] = distance;
+
+ // also update constraints to indicate if its a subset or disjoint
+ // relationship
+ let c = 0;
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
+ c = 1;
+ } else if (current.size <= 1e-10) {
+ c = -1;
+ }
+ constraints[left][right] = constraints[right][left] = c;
+ });
+
+ return { distances, constraints };
+}
+
+/// computes the gradient and loss simultaneously for our constrained MDS optimizer
+function constrainedMDSGradient(x, fxprime, distances, constraints) {
+ for (let i = 0; i < fxprime.length; ++i) {
+ fxprime[i] = 0;
+ }
+
+ let loss = 0;
+ for (let i = 0; i < distances.length; ++i) {
+ const xi = x[2 * i];
+ const yi = x[2 * i + 1];
+ for (let j = i + 1; j < distances.length; ++j) {
+ const xj = x[2 * j];
+ const yj = x[2 * j + 1];
+ const dij = distances[i][j];
+ const constraint = constraints[i][j];
+
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
+ const distance = Math.sqrt(squaredDistance);
+ const delta = squaredDistance - dij * dij;
+
+ if ((constraint > 0 && distance <= dij) || (constraint < 0 && distance >= dij)) {
+ continue;
+ }
+
+ loss += 2 * delta * delta;
+
+ fxprime[2 * i] += 4 * delta * (xi - xj);
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
+
+ fxprime[2 * j] += 4 * delta * (xj - xi);
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
+ }
+ }
+ return loss;
+}
+
+/**
+ * takes the best working variant of either constrained MDS or greedy
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ */
+export function bestInitialLayout(areas, params = {}) {
+ let initial = greedyLayout(areas, params);
+ const loss = params.lossFunction || lossFunction;
+
+ // greedylayout is sufficient for all 2/3 circle cases. try out
+ // constrained MDS for higher order problems, take its output
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
+ // since it axis aligns)
+ if (areas.length >= 8) {
+ const constrained = constrainedMDSLayout(areas, params);
+ const constrainedLoss = loss(constrained, areas);
+ const greedyLoss = loss(initial, areas);
+
+ if (constrainedLoss + 1e-8 < greedyLoss) {
+ initial = constrained;
+ }
+ }
+ return initial;
+}
+
+/**
+ * use the constrained MDS variant to generate an initial layout
+ * @param {ReadonlyArray<{sets: ReadonlyArray, size: number}>} areas
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+export function constrainedMDSLayout(areas, params = {}) {
+ const restarts = params.restarts || 10;
+
+ // bidirectionally map sets to a rowid (so we can create a matrix)
+ const sets = [];
+ const setids = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ setids[area.sets[0]] = sets.length;
+ sets.push(area);
+ }
+ }
+
+ let { distances, constraints } = getDistanceMatrices(areas, sets, setids);
+
+ // keep distances bounded, things get messed up otherwise.
+ // TODO: proper preconditioner?
+ const norm = norm2(distances.map(norm2)) / distances.length;
+ distances = distances.map((row) => row.map((value) => value / norm));
+
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
+
+ let best = null;
+ for (let i = 0; i < restarts; ++i) {
+ const initial = zeros(distances.length * 2).map(Math.random);
+
+ const current = conjugateGradient(obj, initial, params);
+ if (!best || current.fx < best.fx) {
+ best = current;
+ }
+ }
+
+ const positions = best.x;
+
+ // translate rows back to (x,y,radius) coordinates
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ for (let i = 0; i < sets.length; ++i) {
+ const set = sets[i];
+ circles[set.sets[0]] = {
+ x: positions[2 * i] * norm,
+ y: positions[2 * i + 1] * norm,
+ radius: Math.sqrt(set.size / Math.PI),
+ };
+ }
+
+ if (params.history) {
+ for (const h of params.history) {
+ scale(h.x, norm);
+ }
+ }
+ return circles;
+}
+
+/**
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
+ * least overlapped, attempting to position each new set such that the
+ * overlapping areas to already positioned sets are basically right
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray}>} areas
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
+ */
+export function greedyLayout(areas, params) {
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
+
+ // define a circle for each set
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
+ const circles = {};
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
+ const setOverlaps = {};
+ for (const area of areas) {
+ if (area.sets.length === 1) {
+ const set = area.sets[0];
+ circles[set] = {
+ x: 1e10,
+ y: 1e10,
+ rowid: circles.length,
+ size: area.size,
+ radius: Math.sqrt(area.size / Math.PI),
+ };
+ setOverlaps[set] = [];
+ }
+ }
+
+ areas = areas.filter((a) => a.sets.length === 2);
+
+ // map each set to a list of all the other sets that overlap it
+ for (const current of areas) {
+ let weight = current.weight != null ? current.weight : 1.0;
+ const left = current.sets[0];
+ const right = current.sets[1];
+
+ // completely overlapped circles shouldn't be positioned early here
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
+ weight = 0;
+ }
+
+ setOverlaps[left].push({ set: right, size: current.size, weight });
+ setOverlaps[right].push({ set: left, size: current.size, weight });
+ }
+
+ // get list of most overlapped sets
+ const mostOverlapped = [];
+ Object.keys(setOverlaps).forEach((set) => {
+ let size = 0;
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
+ }
+
+ mostOverlapped.push({ set, size });
+ });
+
+ // sort by size desc
+ function sortOrder(a, b) {
+ return b.size - a.size;
+ }
+ mostOverlapped.sort(sortOrder);
+
+ // keep track of what sets have been laid out
+ const positioned = {};
+ function isPositioned(element) {
+ return element.set in positioned;
+ }
+
+ /**
+ * adds a point to the output
+ * @param {{x: number, y: number}} point
+ * @param {number} index
+ */
+ function positionSet(point, index) {
+ circles[index].x = point.x;
+ circles[index].y = point.y;
+ positioned[index] = true;
+ }
+
+ // add most overlapped set at (0,0)
+ positionSet({ x: 0, y: 0 }, mostOverlapped[0].set);
+
+ // get distances between all points. TODO, necessary?
+ // answer: probably not
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
+ for (let i = 1; i < mostOverlapped.length; ++i) {
+ const setIndex = mostOverlapped[i].set;
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
+ const set = circles[setIndex];
+ overlap.sort(sortOrder);
+
+ if (overlap.length === 0) {
+ // this shouldn't happen anymore with addMissingAreas
+ throw 'ERROR: missing pairwise overlap information';
+ }
+
+ /** @type {{x: number, y: number}[]} */
+ const points = [];
+ for (var j = 0; j < overlap.length; ++j) {
+ // get appropriate distance from most overlapped already added set
+ const p1 = circles[overlap[j].set];
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
+
+ // sample positions at 90 degrees for maximum aesthetics
+ points.push({ x: p1.x + d1, y: p1.y });
+ points.push({ x: p1.x - d1, y: p1.y });
+ points.push({ y: p1.y + d1, x: p1.x });
+ points.push({ y: p1.y - d1, x: p1.x });
+
+ // if we have at least 2 overlaps, then figure out where the
+ // set should be positioned analytically and try those too
+ for (let k = j + 1; k < overlap.length; ++k) {
+ const p2 = circles[overlap[k].set];
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
+
+ const extraPoints = circleCircleIntersection(
+ { x: p1.x, y: p1.y, radius: d1 },
+ { x: p2.x, y: p2.y, radius: d2 }
+ );
+ points.push(...extraPoints);
+ }
+ }
+
+ // we have some candidate positions for the set, examine loss
+ // at each position to figure out where to put it at
+ let bestLoss = 1e50;
+ let bestPoint = points[0];
+ for (const point of points) {
+ circles[setIndex].x = point.x;
+ circles[setIndex].y = point.y;
+ const localLoss = loss(circles, areas);
+ if (localLoss < bestLoss) {
+ bestLoss = localLoss;
+ bestPoint = point;
+ }
+ }
+
+ positionSet(bestPoint, setIndex);
+ }
+
+ return circles;
+}
+
+/**
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
+ * the distance from the actual overlaps to the desired overlaps. Note that
+ * this method ignores overlaps of more than 2 circles
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray, weight?: number}>} overlaps
+ * @returns {number}
+ */
+export function lossFunction(circles, overlaps) {
+ let output = 0;
+
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
+ }
+
+ const weight = area.weight != null ? area.weight : 1.0;
+ output += weight * (overlap - area.size) * (overlap - area.size);
+ }
+
+ return output;
+}
+
+export function logRatioLossFunction(circles, overlaps) {
+ let output = 0;
+
+ for (const area of overlaps) {
+ if (area.sets.length === 1) {
+ continue;
+ }
+ /** @type {number} */
+ let overlap;
+ if (area.sets.length === 2) {
+ const left = circles[area.sets[0]];
+ const right = circles[area.sets[1]];
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
+ } else {
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
+ }
+
+ const weight = area.weight != null ? area.weight : 1.0;
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
+ output += weight * differenceFromIdeal * differenceFromIdeal;
+ }
+
+ return output;
+}
+
+/**
+ * orientates a bunch of circles to point in orientation
+ * @param {{x :number, y: number, radius: number}[]} circles
+ * @param {number | undefined} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ */
+function orientateCircles(circles, orientation, orientationOrder) {
+ if (orientationOrder == null) {
+ circles.sort((a, b) => b.radius - a.radius);
+ } else {
+ circles.sort(orientationOrder);
+ }
+
+ // shift circles so largest circle is at (0, 0)
+ if (circles.length > 0) {
+ const largestX = circles[0].x;
+ const largestY = circles[0].y;
+
+ for (const circle of circles) {
+ circle.x -= largestX;
+ circle.y -= largestY;
+ }
+ }
+
+ if (circles.length === 2) {
+ // if the second circle is a subset of the first, arrange so that
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
+ const dist = distance(circles[0], circles[1]);
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
+ circles[1].y = circles[0].y;
+ }
+ }
+
+ // rotate circles so that second largest is at an angle of 'orientation'
+ // from largest
+ if (circles.length > 1) {
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
+ const c = Math.cos(rotation);
+ const s = Math.sin(rotation);
+
+ for (const circle of circles) {
+ const x = circle.x;
+ const y = circle.y;
+ circle.x = c * x - s * y;
+ circle.y = s * x + c * y;
+ }
+ }
+
+ // mirror solution if third solution is above plane specified by
+ // first two circles
+ if (circles.length > 2) {
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
+ while (angle < 0) {
+ angle += 2 * Math.PI;
+ }
+ while (angle > 2 * Math.PI) {
+ angle -= 2 * Math.PI;
+ }
+ if (angle > Math.PI) {
+ const slope = circles[1].y / (1e-10 + circles[1].x);
+ for (const circle of circles) {
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
+ circle.x = 2 * d - circle.x;
+ circle.y = 2 * d * slope - circle.y;
+ }
+ }
+ }
+}
+
+/**
+ *
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
+ * @returns {{x: number, y: number, radius: number}[][]}
+ */
+export function disjointCluster(circles) {
+ // union-find clustering to get disjoint sets
+ circles.forEach((circle) => {
+ circle.parent = circle;
+ });
+
+ // path compression step in union find
+ function find(circle) {
+ if (circle.parent !== circle) {
+ circle.parent = find(circle.parent);
+ }
+ return circle.parent;
+ }
+
+ function union(x, y) {
+ const xRoot = find(x);
+ const yRoot = find(y);
+ xRoot.parent = yRoot;
+ }
+
+ // get the union of all overlapping sets
+ for (let i = 0; i < circles.length; ++i) {
+ for (let j = i + 1; j < circles.length; ++j) {
+ const maxDistance = circles[i].radius + circles[j].radius;
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
+ union(circles[j], circles[i]);
+ }
+ }
+ }
+
+ // find all the disjoint clusters and group them together
+ /** @type {Map} */
+ const disjointClusters = new Map();
+ for (let i = 0; i < circles.length; ++i) {
+ const setid = find(circles[i]).parent.setid;
+ if (!disjointClusters.has(setid)) {
+ disjointClusters.set(setid, []);
+ }
+ disjointClusters.get(setid).push(circles[i]);
+ }
+
+ // cleanup bookkeeping
+ circles.forEach((circle) => {
+ delete circle.parent;
+ });
+
+ // return in more usable form
+ return Array.from(disjointClusters.values());
+}
+
+/**
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
+ */
+function getBoundingBox(circles) {
+ const minMax = (d) => {
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
+ return { max: hi, min: lo };
+ };
+ return { xRange: minMax('x'), yRange: minMax('y') };
+}
+
+/**
+ *
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {undefined | number} orientation
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+export function normalizeSolution(solution, orientation, orientationOrder) {
+ if (orientation == null) {
+ orientation = Math.PI / 2;
+ }
+
+ // work with a list instead of a dictionary, and take a copy so we
+ // don't mutate input
+ let circles = fromObjectNotation(solution).map((d) => Object.assign({}, d));
+
+ // get all the disjoint clusters
+ const clusters = disjointCluster(circles);
+
+ // orientate all disjoint sets, get sizes
+ for (const cluster of clusters) {
+ orientateCircles(cluster, orientation, orientationOrder);
+ const bounds = getBoundingBox(cluster);
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
+ cluster.bounds = bounds;
+ }
+ clusters.sort((a, b) => b.size - a.size);
+
+ // orientate the largest at 0,0, and get the bounds
+ circles = clusters[0];
+ let returnBounds = circles.bounds;
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
+
+ /**
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
+ * @param {boolean} right
+ * @param {boolean} bottom
+ */
+ function addCluster(cluster, right, bottom) {
+ if (!cluster) {
+ return;
+ }
+
+ const bounds = cluster.bounds;
+ /** @type {number} */
+ let xOffset;
+ /** @type {number} */
+ let yOffset;
+
+ if (right) {
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
+ } else {
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
+ const centreing =
+ (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
+ if (centreing < 0) {
+ xOffset += centreing;
+ }
+ }
+
+ if (bottom) {
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
+ } else {
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
+ const centreing =
+ (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
+ if (centreing < 0) {
+ yOffset += centreing;
+ }
+ }
+
+ for (const c of cluster) {
+ c.x += xOffset;
+ c.y += yOffset;
+ circles.push(c);
+ }
+ }
+
+ let index = 1;
+ while (index < clusters.length) {
+ addCluster(clusters[index], true, false);
+ addCluster(clusters[index + 1], false, true);
+ addCluster(clusters[index + 2], true, true);
+ index += 3;
+
+ // have one cluster (in top left). lay out next three relative
+ // to it in a grid
+ returnBounds = getBoundingBox(circles);
+ }
+
+ // convert back to solution form
+ return toObjectNotation(circles);
+}
+
+/**
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
+ * a rectangle of width/height - with padding around the borders. also
+ * centers the diagram in the available space at the same time.
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @param {number} width
+ * @param {number} height
+ * @param {number} padding
+ * @param {boolean} scaleToFit
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
+ */
+export function scaleSolution(solution, width, height, padding, scaleToFit) {
+ const circles = fromObjectNotation(solution);
+
+ width -= 2 * padding;
+ height -= 2 * padding;
+
+ const { xRange, yRange } = getBoundingBox(circles);
+
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
+ console.log('not scaling solution: zero size detected');
+ return solution;
+ }
+
+ /** @type {number} */
+ let xScaling;
+ /** @type {number} */
+ let yScaling;
+ if (scaleToFit) {
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
+ xScaling = width / toScaleDiameter;
+ yScaling = height / toScaleDiameter;
+ } else {
+ xScaling = width / (xRange.max - xRange.min);
+ yScaling = height / (yRange.max - yRange.min);
+ }
+
+ const scaling = Math.min(yScaling, xScaling);
+ // while we're at it, center the diagram too
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
+
+ return toObjectNotation(
+ circles.map((circle) => ({
+ radius: scaling * circle.radius,
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
+ setid: circle.setid,
+ }))
+ );
+}
+
+/**
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
+ */
+function toObjectNotation(circles) {
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
+ const r = {};
+ for (const circle of circles) {
+ r[circle.setid] = circle;
+ }
+ return r;
+}
+/**
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
+ */
+function fromObjectNotation(solution) {
+ const setids = Object.keys(solution);
+ return setids.map((id) => Object.assign(solution[id], { setid: id }));
+}
diff --git a/tools/ui/node_modules/@upsetjs/venn.js/src/layout.spec.js b/tools/ui/node_modules/@upsetjs/venn.js/src/layout.spec.js
new file mode 100644
index 0000000000000000000000000000000000000000..91d8a5b9c64f14658021eb82139dcd577613b152
--- /dev/null
+++ b/tools/ui/node_modules/@upsetjs/venn.js/src/layout.spec.js
@@ -0,0 +1,119 @@
+import { disjointCluster, normalizeSolution, greedyLayout, lossFunction, distanceFromIntersectArea } from './layout';
+import { distance, circleOverlap } from './circleintersection';
+import { describe, test, expect } from 'vitest';
+
+describe('greedyLayout', () => {
+ test('0', () => {
+ const areas = [
+ { sets: [0], size: 0.7746543297103429 },
+ { sets: [1], size: 0.1311252856844238 },
+ { sets: [2], size: 0.2659942131443344 },
+ { sets: [3], size: 0.44600866168641723 },
+ { sets: [0, 1], size: 0.02051532092950205 },
+ { sets: [0, 2], size: 0 },
+ { sets: [0, 3], size: 0 },
+ { sets: [1, 2], size: 0 },
+ { sets: [1, 3], size: 0.07597023820511245 },
+ { sets: [2, 3], size: 0 },
+ ];
+ const circles = greedyLayout(areas);
+ const loss = lossFunction(circles, areas);
+ expect(loss).toBeCloseTo(0);
+ });
+
+ test('1', () => {
+ const areas = [
+ { sets: [0], size: 0.5299368855059736 },
+ { sets: [1], size: 0.03364187025606481 },
+ { sets: [2], size: 0.3121450394871512 },
+ { sets: [3], size: 0.0514397361783036 },
+ { sets: [0, 1], size: 0.013912447645582351 },
+ { sets: [0, 2], size: 0.005903647141469598 },
+ { sets: [0, 3], size: 0.0514397361783036 },
+ { sets: [1, 2], size: 0.012138157839477597 },
+ { sets: [1, 3], size: 0.008010688232481479 },
+ { sets: [2, 3], size: 0 },
+ ];
+
+ const circles = greedyLayout(areas);
+ const loss = lossFunction(circles, areas);
+ expect(loss).toBeCloseTo(0);
+ });
+
+ test('3', () => {
+ // one small circle completely overlapped in the intersection
+ // area of two larger circles
+ const areas = [
+ { sets: [0], size: 1.7288584050841396 },
+ { sets: [1], size: 0.040875831658950056 },
+ { sets: [2], size: 2.587146019782323 },
+ { sets: [0, 1], size: 0.040875831658950056 },
+ { sets: [0, 2], size: 0.5114617575187569 },
+ { sets: [1, 2], size: 0.040875831658950056 },
+ ];
+
+ const circles = greedyLayout(areas);
+ const loss = lossFunction(circles, areas);
+ expect(loss).toBeCloseTo(0);
+ });
+});
+
+test('distanceFromIntersectArea', () => {
+ function testDistanceFromIntersectArea(r1, r2, overlap) {
+ const distance = distanceFromIntersectArea(r1, r2, overlap);
+ expect(circleOverlap(r1, r2, distance)).toBeCloseTo(overlap);
+ }
+
+ testDistanceFromIntersectArea(1.9544100476116797, 2.256758334191025, 11);
+
+ testDistanceFromIntersectArea(111.06512962798197, 113.32348546565727, 1218);
+
+ testDistanceFromIntersectArea(44.456564007075, 149.4335753619362, 2799);
+
+ testDistanceFromIntersectArea(592.89, 134.75, 56995);
+
+ testDistanceFromIntersectArea(139.50778247443944, 32.892784970851956, 3399);
+
+ testDistanceFromIntersectArea(4.886025119029199, 5.077706251929807, 75);
+});
+
+test('normalizeSolution', () => {
+ // test two circles that are far apart
+ const solution = [
+ { x: 0, y: 0, radius: 0.5 },
+ { x: 1e10, y: 0, radius: 1.5 },
+ ];
+
+ // should be placed close together
+ const normalized = normalizeSolution(solution);
+ // distance should be 2, but we space things out
+ expect(distance(normalized[0], normalized[1])).toBeLessThan(2.1);
+});
+
+test('disjointClusters', () => {
+ const input = [
+ {
+ x: 0.8047033110633492,
+ y: 0.9396705999970436,
+ radius: 0.47156485118903224,
+ },
+ {
+ x: 0.7961132447235286,
+ y: 0.014027722179889679,
+ radius: 0.14554832570720466,
+ },
+ {
+ x: 0.28841276094317436,
+ y: 0.98081015329808,
+ radius: 0.9851036085514352,
+ },
+ {
+ x: 0.7689983483869582,
+ y: 0.2899463507346809,
+ radius: 0.7210563338827342,
+ },
+ ];
+
+ const clusters = disjointCluster(input);
+ expect(clusters).toHaveLength(1);
+});
diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/LICENSE b/tools/ui/node_modules/@vite-pwa/assets-generator/LICENSE
new file mode 100644
index 0000000000000000000000000000000000000000..2bbbc782e52a2224f8d622854205f1a6325f3996
--- /dev/null
+++ b/tools/ui/node_modules/@vite-pwa/assets-generator/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) 2023-PRESENT Anthony Fu
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/README.md b/tools/ui/node_modules/@vite-pwa/assets-generator/README.md
new file mode 100644
index 0000000000000000000000000000000000000000..52061e898965e9fe8b7c2608f6f38f2f4b22a6bb
--- /dev/null
+++ b/tools/ui/node_modules/@vite-pwa/assets-generator/README.md
@@ -0,0 +1,96 @@
+