Brunobkr commited on
Commit
a4fa9c0
·
verified ·
1 Parent(s): 7c0069c

Upload folder using huggingface_hub (part 24)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js +194 -0
  2. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE +201 -0
  3. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md +123 -0
  4. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs +187 -0
  5. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts +28 -0
  6. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts +16 -0
  7. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts +12 -0
  8. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js +67 -0
  9. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js +118 -0
  10. tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json +57 -0
  11. tools/ui/node_modules/@typescript-eslint/visitor-keys/package.json +76 -0
  12. tools/ui/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml +31 -0
  13. tools/ui/node_modules/@ungap/structured-clone/LICENSE +15 -0
  14. tools/ui/node_modules/@ungap/structured-clone/README.md +95 -0
  15. tools/ui/node_modules/@ungap/structured-clone/cjs/deserialize.js +97 -0
  16. tools/ui/node_modules/@ungap/structured-clone/cjs/index.js +27 -0
  17. tools/ui/node_modules/@ungap/structured-clone/cjs/json.js +24 -0
  18. tools/ui/node_modules/@ungap/structured-clone/cjs/package.json +1 -0
  19. tools/ui/node_modules/@ungap/structured-clone/cjs/serialize.js +170 -0
  20. tools/ui/node_modules/@ungap/structured-clone/cjs/types.js +22 -0
  21. tools/ui/node_modules/@ungap/structured-clone/esm/deserialize.js +98 -0
  22. tools/ui/node_modules/@ungap/structured-clone/esm/index.js +25 -0
  23. tools/ui/node_modules/@ungap/structured-clone/esm/json.js +21 -0
  24. tools/ui/node_modules/@ungap/structured-clone/esm/serialize.js +171 -0
  25. tools/ui/node_modules/@ungap/structured-clone/esm/types.js +11 -0
  26. tools/ui/node_modules/@ungap/structured-clone/package.json +54 -0
  27. tools/ui/node_modules/@ungap/structured-clone/structured-json.js +1 -0
  28. tools/ui/node_modules/@upsetjs/venn.js/LICENSE +22 -0
  29. tools/ui/node_modules/@upsetjs/venn.js/README.md +267 -0
  30. tools/ui/node_modules/@upsetjs/venn.js/build/venn.esm.js +2214 -0
  31. tools/ui/node_modules/@upsetjs/venn.js/build/venn.js +2166 -0
  32. tools/ui/node_modules/@upsetjs/venn.js/build/venn.min.js +1 -0
  33. tools/ui/node_modules/@upsetjs/venn.js/package.json +105 -0
  34. tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.js +266 -0
  35. tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.spec.js +125 -0
  36. tools/ui/node_modules/@upsetjs/venn.js/src/diagram.js +783 -0
  37. tools/ui/node_modules/@upsetjs/venn.js/src/diagram.spec.js +16 -0
  38. tools/ui/node_modules/@upsetjs/venn.js/src/index.d.ts +319 -0
  39. tools/ui/node_modules/@upsetjs/venn.js/src/index.js +23 -0
  40. tools/ui/node_modules/@upsetjs/venn.js/src/layout.js +820 -0
  41. tools/ui/node_modules/@upsetjs/venn.js/src/layout.spec.js +119 -0
  42. tools/ui/node_modules/@vite-pwa/assets-generator/LICENSE +21 -0
  43. tools/ui/node_modules/@vite-pwa/assets-generator/README.md +96 -0
  44. tools/ui/node_modules/@vite-pwa/assets-generator/bin/pwa-assets-generator.mjs +3 -0
  45. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.cjs +24 -0
  46. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.cts +21 -0
  47. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.mts +21 -0
  48. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.ts +21 -0
  49. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.mjs +5 -0
  50. tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.cjs +30 -0
tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.visitorKeys = void 0;
37
+ const eslintVisitorKeys = __importStar(require("eslint-visitor-keys"));
38
+ /*
39
+ ********************************** IMPORTANT NOTE ********************************
40
+ * *
41
+ * The key arrays should be sorted in the order in which you would want to visit *
42
+ * the child keys. *
43
+ * *
44
+ * DO NOT SORT THEM ALPHABETICALLY! *
45
+ * *
46
+ * They should be sorted in the order that they appear in the source code. *
47
+ * For example: *
48
+ * *
49
+ * class Foo extends Bar { prop: 1 } *
50
+ * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClassDeclaration *
51
+ * ^^^ id ^^^ superClass *
52
+ * ^^^^^^^^^^^ body *
53
+ * *
54
+ * It would be incorrect to provide the visitor keys ['body', 'id', 'superClass'] *
55
+ * because the body comes AFTER everything else in the source code. *
56
+ * Instead the correct ordering would be ['id', 'superClass', 'body']. *
57
+ * *
58
+ **********************************************************************************
59
+ */
60
+ const SharedVisitorKeys = (() => {
61
+ const FunctionType = ['typeParameters', 'params', 'returnType'];
62
+ const AnonymousFunction = [...FunctionType, 'body'];
63
+ const AbstractPropertyDefinition = [
64
+ 'decorators',
65
+ 'key',
66
+ 'typeAnnotation',
67
+ ];
68
+ return {
69
+ AbstractPropertyDefinition: ['decorators', 'key', 'typeAnnotation'],
70
+ AnonymousFunction,
71
+ AsExpression: ['expression', 'typeAnnotation'],
72
+ ClassDeclaration: [
73
+ 'decorators',
74
+ 'id',
75
+ 'typeParameters',
76
+ 'superClass',
77
+ 'superTypeArguments',
78
+ 'implements',
79
+ 'body',
80
+ ],
81
+ Function: ['id', ...AnonymousFunction],
82
+ FunctionType,
83
+ PropertyDefinition: [...AbstractPropertyDefinition, 'value'],
84
+ };
85
+ })();
86
+ const additionalKeys = {
87
+ AccessorProperty: SharedVisitorKeys.PropertyDefinition,
88
+ ArrayPattern: ['decorators', 'elements', 'typeAnnotation'],
89
+ ArrowFunctionExpression: SharedVisitorKeys.AnonymousFunction,
90
+ AssignmentPattern: ['decorators', 'left', 'right', 'typeAnnotation'],
91
+ CallExpression: ['callee', 'typeArguments', 'arguments'],
92
+ ClassDeclaration: SharedVisitorKeys.ClassDeclaration,
93
+ ClassExpression: SharedVisitorKeys.ClassDeclaration,
94
+ Decorator: ['expression'],
95
+ ExportAllDeclaration: ['exported', 'source', 'attributes'],
96
+ ExportNamedDeclaration: ['declaration', 'specifiers', 'source', 'attributes'],
97
+ FunctionDeclaration: SharedVisitorKeys.Function,
98
+ FunctionExpression: SharedVisitorKeys.Function,
99
+ Identifier: ['decorators', 'typeAnnotation'],
100
+ ImportAttribute: ['key', 'value'],
101
+ ImportDeclaration: ['specifiers', 'source', 'attributes'],
102
+ ImportExpression: ['source', 'options'],
103
+ JSXClosingFragment: [],
104
+ JSXOpeningElement: ['name', 'typeArguments', 'attributes'],
105
+ JSXOpeningFragment: [],
106
+ JSXSpreadChild: ['expression'],
107
+ MethodDefinition: ['decorators', 'key', 'value'],
108
+ NewExpression: ['callee', 'typeArguments', 'arguments'],
109
+ ObjectPattern: ['decorators', 'properties', 'typeAnnotation'],
110
+ PropertyDefinition: SharedVisitorKeys.PropertyDefinition,
111
+ RestElement: ['decorators', 'argument', 'typeAnnotation'],
112
+ StaticBlock: ['body'],
113
+ TaggedTemplateExpression: ['tag', 'typeArguments', 'quasi'],
114
+ TSAbstractAccessorProperty: SharedVisitorKeys.AbstractPropertyDefinition,
115
+ TSAbstractKeyword: [],
116
+ TSAbstractMethodDefinition: ['key', 'value'],
117
+ TSAbstractPropertyDefinition: SharedVisitorKeys.AbstractPropertyDefinition,
118
+ TSAnyKeyword: [],
119
+ TSArrayType: ['elementType'],
120
+ TSAsExpression: SharedVisitorKeys.AsExpression,
121
+ TSAsyncKeyword: [],
122
+ TSBigIntKeyword: [],
123
+ TSBooleanKeyword: [],
124
+ TSCallSignatureDeclaration: SharedVisitorKeys.FunctionType,
125
+ TSClassImplements: ['expression', 'typeArguments'],
126
+ TSConditionalType: ['checkType', 'extendsType', 'trueType', 'falseType'],
127
+ TSConstructorType: SharedVisitorKeys.FunctionType,
128
+ TSConstructSignatureDeclaration: SharedVisitorKeys.FunctionType,
129
+ TSDeclareFunction: SharedVisitorKeys.Function,
130
+ TSDeclareKeyword: [],
131
+ TSEmptyBodyFunctionExpression: ['id', ...SharedVisitorKeys.FunctionType],
132
+ TSEnumBody: ['members'],
133
+ TSEnumDeclaration: ['id', 'body'],
134
+ TSEnumMember: ['id', 'initializer'],
135
+ TSExportAssignment: ['expression'],
136
+ TSExportKeyword: [],
137
+ TSExternalModuleReference: ['expression'],
138
+ TSFunctionType: SharedVisitorKeys.FunctionType,
139
+ TSImportEqualsDeclaration: ['id', 'moduleReference'],
140
+ TSImportType: ['source', 'options', 'qualifier', 'typeArguments'],
141
+ TSIndexedAccessType: ['objectType', 'indexType'],
142
+ TSIndexSignature: ['parameters', 'typeAnnotation'],
143
+ TSInferType: ['typeParameter'],
144
+ TSInstantiationExpression: ['expression', 'typeArguments'],
145
+ TSInterfaceBody: ['body'],
146
+ TSInterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'],
147
+ TSInterfaceHeritage: ['expression', 'typeArguments'],
148
+ TSIntersectionType: ['types'],
149
+ TSIntrinsicKeyword: [],
150
+ TSLiteralType: ['literal'],
151
+ TSMappedType: ['key', 'constraint', 'nameType', 'typeAnnotation'],
152
+ TSMethodSignature: ['key', 'typeParameters', 'params', 'returnType'],
153
+ TSModuleBlock: ['body'],
154
+ TSModuleDeclaration: ['id', 'body'],
155
+ TSNamedTupleMember: ['label', 'elementType'],
156
+ TSNamespaceExportDeclaration: ['id'],
157
+ TSNeverKeyword: [],
158
+ TSNonNullExpression: ['expression'],
159
+ TSNullKeyword: [],
160
+ TSNumberKeyword: [],
161
+ TSObjectKeyword: [],
162
+ TSOptionalType: ['typeAnnotation'],
163
+ TSParameterProperty: ['decorators', 'parameter'],
164
+ TSPrivateKeyword: [],
165
+ TSPropertySignature: ['key', 'typeAnnotation'],
166
+ TSProtectedKeyword: [],
167
+ TSPublicKeyword: [],
168
+ TSQualifiedName: ['left', 'right'],
169
+ TSReadonlyKeyword: [],
170
+ TSRestType: ['typeAnnotation'],
171
+ TSSatisfiesExpression: SharedVisitorKeys.AsExpression,
172
+ TSStaticKeyword: [],
173
+ TSStringKeyword: [],
174
+ TSSymbolKeyword: [],
175
+ TSTemplateLiteralType: ['quasis', 'types'],
176
+ TSThisType: [],
177
+ TSTupleType: ['elementTypes'],
178
+ TSTypeAliasDeclaration: ['id', 'typeParameters', 'typeAnnotation'],
179
+ TSTypeAnnotation: ['typeAnnotation'],
180
+ TSTypeAssertion: ['typeAnnotation', 'expression'],
181
+ TSTypeLiteral: ['members'],
182
+ TSTypeOperator: ['typeAnnotation'],
183
+ TSTypeParameter: ['name', 'constraint', 'default'],
184
+ TSTypeParameterDeclaration: ['params'],
185
+ TSTypeParameterInstantiation: ['params'],
186
+ TSTypePredicate: ['parameterName', 'typeAnnotation'],
187
+ TSTypeQuery: ['exprName', 'typeArguments'],
188
+ TSTypeReference: ['typeName', 'typeArguments'],
189
+ TSUndefinedKeyword: [],
190
+ TSUnionType: ['types'],
191
+ TSUnknownKeyword: [],
192
+ TSVoidKeyword: [],
193
+ };
194
+ exports.visitorKeys = eslintVisitorKeys.unionWith(additionalKeys);
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE ADDED
@@ -0,0 +1,201 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright contributors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md ADDED
@@ -0,0 +1,123 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # eslint-visitor-keys
2
+
3
+ [![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys)
4
+ [![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys)
5
+ [![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions)
6
+
7
+ Constants and utilities about visitor keys to traverse AST.
8
+
9
+ ## 💿 Installation
10
+
11
+ Use [npm] to install.
12
+
13
+ ```bash
14
+ $ npm install eslint-visitor-keys
15
+ ```
16
+
17
+ ### Requirements
18
+
19
+ - [Node.js] `^20.19.0`, `^22.13.0`, or `>=24`
20
+
21
+ ## 📖 Usage
22
+
23
+ To use in an ESM file:
24
+
25
+ ```js
26
+ import * as evk from "eslint-visitor-keys";
27
+ ```
28
+
29
+ To use in a CommonJS file:
30
+
31
+ ```js
32
+ const evk = require("eslint-visitor-keys");
33
+ ```
34
+
35
+ ### evk.KEYS
36
+
37
+ > type: `{ [type: string]: string[] | undefined }`
38
+
39
+ Visitor keys. This keys are frozen.
40
+
41
+ This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
42
+
43
+ For example:
44
+
45
+ ```
46
+ console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
47
+ ```
48
+
49
+ ### evk.getKeys(node)
50
+
51
+ > type: `(node: object) => string[]`
52
+
53
+ Get the visitor keys of a given AST node.
54
+
55
+ This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
56
+
57
+ This will be used to traverse unknown nodes.
58
+
59
+ For example:
60
+
61
+ ```js
62
+ const node = {
63
+ type: "AssignmentExpression",
64
+ left: { type: "Identifier", name: "foo" },
65
+ right: { type: "Literal", value: 0 },
66
+ };
67
+ console.log(evk.getKeys(node)); // → ["type", "left", "right"]
68
+ ```
69
+
70
+ ### evk.unionWith(additionalKeys)
71
+
72
+ > type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
73
+
74
+ Make the union set with `evk.KEYS` and the given keys.
75
+
76
+ - The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
77
+ - It removes duplicated keys as keeping the first one.
78
+
79
+ For example:
80
+
81
+ ```js
82
+ console.log(
83
+ evk.unionWith({
84
+ MethodDefinition: ["decorators"],
85
+ }),
86
+ ); // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
87
+ ```
88
+
89
+ ## 📰 Change log
90
+
91
+ See [GitHub releases](https://github.com/eslint/js/releases).
92
+
93
+ ## 🍻 Contributing
94
+
95
+ Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
96
+
97
+ ### Development commands
98
+
99
+ - `npm test` runs tests and measures code coverage.
100
+ - `npm run lint` checks source codes with ESLint.
101
+ - `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
102
+
103
+ [npm]: https://www.npmjs.com/
104
+ [Node.js]: https://nodejs.org/
105
+ [ESTree]: https://github.com/estree/estree
106
+
107
+ <!-- NOTE: This section is autogenerated. Do not manually edit.-->
108
+ <!--sponsorsstart-->
109
+
110
+ ## Sponsors
111
+
112
+ The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
113
+ to get your logo on our READMEs and [website](https://eslint.org/sponsors).
114
+
115
+ <h3>Platinum Sponsors</h3>
116
+ <p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a></p><h3>Gold Sponsors</h3>
117
+ <p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
118
+ <p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/d472863/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/2d6c3b6/logo.png" alt="Liftoff" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
119
+ <p><a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://opensource.sap.com"><img src="https://avatars.githubusercontent.com/u/2531208" alt="SAP" height="32"></a> <a href="https://www.crawljobs.com/"><img src="https://images.opencollective.com/crawljobs-poland/fa43a17/logo.png" alt="CrawlJobs" height="32"></a> <a href="https://depot.dev"><img src="https://images.opencollective.com/depot/39125a1/logo.png" alt="Depot" height="32"></a> <a href="https://www.n-ix.com/"><img src="https://images.opencollective.com/n-ix-ltd/575a7a5/logo.png" alt="N-iX Ltd" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="TestMu AI Open Source Office (Formerly LambdaTest)" height="32"></a></p>
120
+ <h3>Technology Sponsors</h3>
121
+ 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.
122
+ <p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
123
+ <!--sponsorsend-->
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.cjs ADDED
@@ -0,0 +1,187 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ /* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
4
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
5
+ */
6
+ /**
7
+ * @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
8
+ */
9
+ /* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */
10
+
11
+ /**
12
+ * @type {VisitorKeys}
13
+ */
14
+ const KEYS = {
15
+ ArrayExpression: ["elements"],
16
+ ArrayPattern: ["elements"],
17
+ ArrowFunctionExpression: ["params", "body"],
18
+ AssignmentExpression: ["left", "right"],
19
+ AssignmentPattern: ["left", "right"],
20
+ AwaitExpression: ["argument"],
21
+ BinaryExpression: ["left", "right"],
22
+ BlockStatement: ["body"],
23
+ BreakStatement: ["label"],
24
+ CallExpression: ["callee", "arguments"],
25
+ CatchClause: ["param", "body"],
26
+ ChainExpression: ["expression"],
27
+ ClassBody: ["body"],
28
+ ClassDeclaration: ["id", "superClass", "body"],
29
+ ClassExpression: ["id", "superClass", "body"],
30
+ ConditionalExpression: ["test", "consequent", "alternate"],
31
+ ContinueStatement: ["label"],
32
+ DebuggerStatement: [],
33
+ DoWhileStatement: ["body", "test"],
34
+ EmptyStatement: [],
35
+ ExperimentalRestProperty: ["argument"],
36
+ ExperimentalSpreadProperty: ["argument"],
37
+ ExportAllDeclaration: ["exported", "source", "attributes"],
38
+ ExportDefaultDeclaration: ["declaration"],
39
+ ExportNamedDeclaration: [
40
+ "declaration",
41
+ "specifiers",
42
+ "source",
43
+ "attributes",
44
+ ],
45
+ ExportSpecifier: ["local", "exported"],
46
+ ExpressionStatement: ["expression"],
47
+ ForInStatement: ["left", "right", "body"],
48
+ ForOfStatement: ["left", "right", "body"],
49
+ ForStatement: ["init", "test", "update", "body"],
50
+ FunctionDeclaration: ["id", "params", "body"],
51
+ FunctionExpression: ["id", "params", "body"],
52
+ Identifier: [],
53
+ IfStatement: ["test", "consequent", "alternate"],
54
+ ImportAttribute: ["key", "value"],
55
+ ImportDeclaration: ["specifiers", "source", "attributes"],
56
+ ImportDefaultSpecifier: ["local"],
57
+ ImportExpression: ["source", "options"],
58
+ ImportNamespaceSpecifier: ["local"],
59
+ ImportSpecifier: ["imported", "local"],
60
+ JSXAttribute: ["name", "value"],
61
+ JSXClosingElement: ["name"],
62
+ JSXClosingFragment: [],
63
+ JSXElement: ["openingElement", "children", "closingElement"],
64
+ JSXEmptyExpression: [],
65
+ JSXExpressionContainer: ["expression"],
66
+ JSXFragment: ["openingFragment", "children", "closingFragment"],
67
+ JSXIdentifier: [],
68
+ JSXMemberExpression: ["object", "property"],
69
+ JSXNamespacedName: ["namespace", "name"],
70
+ JSXOpeningElement: ["name", "attributes"],
71
+ JSXOpeningFragment: [],
72
+ JSXSpreadAttribute: ["argument"],
73
+ JSXSpreadChild: ["expression"],
74
+ JSXText: [],
75
+ LabeledStatement: ["label", "body"],
76
+ Literal: [],
77
+ LogicalExpression: ["left", "right"],
78
+ MemberExpression: ["object", "property"],
79
+ MetaProperty: ["meta", "property"],
80
+ MethodDefinition: ["key", "value"],
81
+ NewExpression: ["callee", "arguments"],
82
+ ObjectExpression: ["properties"],
83
+ ObjectPattern: ["properties"],
84
+ PrivateIdentifier: [],
85
+ Program: ["body"],
86
+ Property: ["key", "value"],
87
+ PropertyDefinition: ["key", "value"],
88
+ RestElement: ["argument"],
89
+ ReturnStatement: ["argument"],
90
+ SequenceExpression: ["expressions"],
91
+ SpreadElement: ["argument"],
92
+ StaticBlock: ["body"],
93
+ Super: [],
94
+ SwitchCase: ["test", "consequent"],
95
+ SwitchStatement: ["discriminant", "cases"],
96
+ TaggedTemplateExpression: ["tag", "quasi"],
97
+ TemplateElement: [],
98
+ TemplateLiteral: ["quasis", "expressions"],
99
+ ThisExpression: [],
100
+ ThrowStatement: ["argument"],
101
+ TryStatement: ["block", "handler", "finalizer"],
102
+ UnaryExpression: ["argument"],
103
+ UpdateExpression: ["argument"],
104
+ VariableDeclaration: ["declarations"],
105
+ VariableDeclarator: ["id", "init"],
106
+ WhileStatement: ["test", "body"],
107
+ WithStatement: ["object", "body"],
108
+ YieldExpression: ["argument"],
109
+ };
110
+
111
+ // Types.
112
+ const NODE_TYPES = Object.keys(KEYS);
113
+
114
+ // Freeze the keys.
115
+ for (const type of NODE_TYPES) {
116
+ Object.freeze(KEYS[type]);
117
+ }
118
+ Object.freeze(KEYS);
119
+
120
+ /**
121
+ * @author Toru Nagashima <https://github.com/mysticatea>
122
+ * See LICENSE file in root directory for full license.
123
+ */
124
+
125
+ /**
126
+ * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
127
+ */
128
+
129
+ // List to ignore keys.
130
+ const KEY_BLACKLIST = new Set([
131
+ "parent",
132
+ "leadingComments",
133
+ "trailingComments",
134
+ ]);
135
+
136
+ /**
137
+ * Check whether a given key should be used or not.
138
+ * @param {string} key The key to check.
139
+ * @returns {boolean} `true` if the key should be used.
140
+ */
141
+ function filterKey(key) {
142
+ return !KEY_BLACKLIST.has(key) && key[0] !== "_";
143
+ }
144
+
145
+ /* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
146
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
147
+ */
148
+ /**
149
+ * Get visitor keys of a given node.
150
+ * @param {Object} node The AST node to get keys.
151
+ * @returns {readonly string[]} Visitor keys of the node.
152
+ */
153
+ function getKeys(node) {
154
+ return Object.keys(node).filter(filterKey);
155
+ }
156
+ /* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */
157
+
158
+ /**
159
+ * Make the union set with `KEYS` and given keys.
160
+ * @param {VisitorKeys} additionalKeys The additional keys.
161
+ * @returns {VisitorKeys} The union set.
162
+ */
163
+ function unionWith(additionalKeys) {
164
+ const retv =
165
+ /** @type {{ [type: string]: ReadonlyArray<string> }} */
166
+ (Object.assign({}, KEYS));
167
+
168
+ for (const type of Object.keys(additionalKeys)) {
169
+ if (Object.hasOwn(retv, type)) {
170
+ const keys = new Set(additionalKeys[type]);
171
+
172
+ for (const key of retv[type]) {
173
+ keys.add(key);
174
+ }
175
+
176
+ retv[type] = Object.freeze(Array.from(keys));
177
+ } else {
178
+ retv[type] = Object.freeze(Array.from(additionalKeys[type]));
179
+ }
180
+ }
181
+
182
+ return Object.freeze(retv);
183
+ }
184
+
185
+ exports.KEYS = KEYS;
186
+ exports.getKeys = getKeys;
187
+ exports.unionWith = unionWith;
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/eslint-visitor-keys.d.cts ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ type VisitorKeys$1 = {
2
+ readonly [type: string]: ReadonlyArray<string>;
3
+ };
4
+ /**
5
+ * @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
6
+ */
7
+ /**
8
+ * @type {VisitorKeys}
9
+ */
10
+ declare const KEYS: VisitorKeys$1;
11
+
12
+ /**
13
+ * Get visitor keys of a given node.
14
+ * @param {Object} node The AST node to get keys.
15
+ * @returns {readonly string[]} Visitor keys of the node.
16
+ */
17
+ declare function getKeys(node: Object): readonly string[];
18
+ /**
19
+ * Make the union set with `KEYS` and given keys.
20
+ * @param {VisitorKeys} additionalKeys The additional keys.
21
+ * @returns {VisitorKeys} The union set.
22
+ */
23
+ declare function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
24
+
25
+ type VisitorKeys = VisitorKeys$1;
26
+
27
+ export { KEYS, getKeys, unionWith };
28
+ export type { VisitorKeys };
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/index.d.ts ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Get visitor keys of a given node.
3
+ * @param {Object} node The AST node to get keys.
4
+ * @returns {readonly string[]} Visitor keys of the node.
5
+ */
6
+ export function getKeys(node: Object): readonly string[];
7
+ /**
8
+ * Make the union set with `KEYS` and given keys.
9
+ * @param {VisitorKeys} additionalKeys The additional keys.
10
+ * @returns {VisitorKeys} The union set.
11
+ */
12
+ export function unionWith(additionalKeys: VisitorKeys): VisitorKeys;
13
+ export { KEYS };
14
+ export type VisitorKeys = import("./visitor-keys.js").VisitorKeys;
15
+ import KEYS from "./visitor-keys.js";
16
+ //# sourceMappingURL=index.d.ts.map
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/dist/visitor-keys.d.ts ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export default KEYS;
2
+ export type VisitorKeys = {
3
+ readonly [type: string]: ReadonlyArray<string>;
4
+ };
5
+ /**
6
+ * @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
7
+ */
8
+ /**
9
+ * @type {VisitorKeys}
10
+ */
11
+ declare const KEYS: VisitorKeys;
12
+ //# sourceMappingURL=visitor-keys.d.ts.map
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/index.js ADDED
@@ -0,0 +1,67 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * @author Toru Nagashima <https://github.com/mysticatea>
3
+ * See LICENSE file in root directory for full license.
4
+ */
5
+ import KEYS from "./visitor-keys.js";
6
+
7
+ /**
8
+ * @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
9
+ */
10
+
11
+ // List to ignore keys.
12
+ const KEY_BLACKLIST = new Set([
13
+ "parent",
14
+ "leadingComments",
15
+ "trailingComments",
16
+ ]);
17
+
18
+ /**
19
+ * Check whether a given key should be used or not.
20
+ * @param {string} key The key to check.
21
+ * @returns {boolean} `true` if the key should be used.
22
+ */
23
+ function filterKey(key) {
24
+ return !KEY_BLACKLIST.has(key) && key[0] !== "_";
25
+ }
26
+
27
+ /* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
28
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
29
+ */
30
+ /**
31
+ * Get visitor keys of a given node.
32
+ * @param {Object} node The AST node to get keys.
33
+ * @returns {readonly string[]} Visitor keys of the node.
34
+ */
35
+ export function getKeys(node) {
36
+ return Object.keys(node).filter(filterKey);
37
+ }
38
+ /* eslint-enable jsdoc/valid-types -- doesn't allow `readonly` */
39
+
40
+ /**
41
+ * Make the union set with `KEYS` and given keys.
42
+ * @param {VisitorKeys} additionalKeys The additional keys.
43
+ * @returns {VisitorKeys} The union set.
44
+ */
45
+ export function unionWith(additionalKeys) {
46
+ const retv =
47
+ /** @type {{ [type: string]: ReadonlyArray<string> }} */
48
+ (Object.assign({}, KEYS));
49
+
50
+ for (const type of Object.keys(additionalKeys)) {
51
+ if (Object.hasOwn(retv, type)) {
52
+ const keys = new Set(additionalKeys[type]);
53
+
54
+ for (const key of retv[type]) {
55
+ keys.add(key);
56
+ }
57
+
58
+ retv[type] = Object.freeze(Array.from(keys));
59
+ } else {
60
+ retv[type] = Object.freeze(Array.from(additionalKeys[type]));
61
+ }
62
+ }
63
+
64
+ return Object.freeze(retv);
65
+ }
66
+
67
+ export { KEYS };
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/lib/visitor-keys.js ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /* eslint-disable jsdoc/valid-types -- doesn't allow `readonly`.
2
+ TODO: remove eslint-disable when https://github.com/jsdoc-type-pratt-parser/jsdoc-type-pratt-parser/issues/164 is fixed
3
+ */
4
+ /**
5
+ * @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
6
+ */
7
+ /* eslint-enable jsdoc/valid-types -- doesn't allow `readonly string[]`. TODO: check why */
8
+
9
+ /**
10
+ * @type {VisitorKeys}
11
+ */
12
+ const KEYS = {
13
+ ArrayExpression: ["elements"],
14
+ ArrayPattern: ["elements"],
15
+ ArrowFunctionExpression: ["params", "body"],
16
+ AssignmentExpression: ["left", "right"],
17
+ AssignmentPattern: ["left", "right"],
18
+ AwaitExpression: ["argument"],
19
+ BinaryExpression: ["left", "right"],
20
+ BlockStatement: ["body"],
21
+ BreakStatement: ["label"],
22
+ CallExpression: ["callee", "arguments"],
23
+ CatchClause: ["param", "body"],
24
+ ChainExpression: ["expression"],
25
+ ClassBody: ["body"],
26
+ ClassDeclaration: ["id", "superClass", "body"],
27
+ ClassExpression: ["id", "superClass", "body"],
28
+ ConditionalExpression: ["test", "consequent", "alternate"],
29
+ ContinueStatement: ["label"],
30
+ DebuggerStatement: [],
31
+ DoWhileStatement: ["body", "test"],
32
+ EmptyStatement: [],
33
+ ExperimentalRestProperty: ["argument"],
34
+ ExperimentalSpreadProperty: ["argument"],
35
+ ExportAllDeclaration: ["exported", "source", "attributes"],
36
+ ExportDefaultDeclaration: ["declaration"],
37
+ ExportNamedDeclaration: [
38
+ "declaration",
39
+ "specifiers",
40
+ "source",
41
+ "attributes",
42
+ ],
43
+ ExportSpecifier: ["local", "exported"],
44
+ ExpressionStatement: ["expression"],
45
+ ForInStatement: ["left", "right", "body"],
46
+ ForOfStatement: ["left", "right", "body"],
47
+ ForStatement: ["init", "test", "update", "body"],
48
+ FunctionDeclaration: ["id", "params", "body"],
49
+ FunctionExpression: ["id", "params", "body"],
50
+ Identifier: [],
51
+ IfStatement: ["test", "consequent", "alternate"],
52
+ ImportAttribute: ["key", "value"],
53
+ ImportDeclaration: ["specifiers", "source", "attributes"],
54
+ ImportDefaultSpecifier: ["local"],
55
+ ImportExpression: ["source", "options"],
56
+ ImportNamespaceSpecifier: ["local"],
57
+ ImportSpecifier: ["imported", "local"],
58
+ JSXAttribute: ["name", "value"],
59
+ JSXClosingElement: ["name"],
60
+ JSXClosingFragment: [],
61
+ JSXElement: ["openingElement", "children", "closingElement"],
62
+ JSXEmptyExpression: [],
63
+ JSXExpressionContainer: ["expression"],
64
+ JSXFragment: ["openingFragment", "children", "closingFragment"],
65
+ JSXIdentifier: [],
66
+ JSXMemberExpression: ["object", "property"],
67
+ JSXNamespacedName: ["namespace", "name"],
68
+ JSXOpeningElement: ["name", "attributes"],
69
+ JSXOpeningFragment: [],
70
+ JSXSpreadAttribute: ["argument"],
71
+ JSXSpreadChild: ["expression"],
72
+ JSXText: [],
73
+ LabeledStatement: ["label", "body"],
74
+ Literal: [],
75
+ LogicalExpression: ["left", "right"],
76
+ MemberExpression: ["object", "property"],
77
+ MetaProperty: ["meta", "property"],
78
+ MethodDefinition: ["key", "value"],
79
+ NewExpression: ["callee", "arguments"],
80
+ ObjectExpression: ["properties"],
81
+ ObjectPattern: ["properties"],
82
+ PrivateIdentifier: [],
83
+ Program: ["body"],
84
+ Property: ["key", "value"],
85
+ PropertyDefinition: ["key", "value"],
86
+ RestElement: ["argument"],
87
+ ReturnStatement: ["argument"],
88
+ SequenceExpression: ["expressions"],
89
+ SpreadElement: ["argument"],
90
+ StaticBlock: ["body"],
91
+ Super: [],
92
+ SwitchCase: ["test", "consequent"],
93
+ SwitchStatement: ["discriminant", "cases"],
94
+ TaggedTemplateExpression: ["tag", "quasi"],
95
+ TemplateElement: [],
96
+ TemplateLiteral: ["quasis", "expressions"],
97
+ ThisExpression: [],
98
+ ThrowStatement: ["argument"],
99
+ TryStatement: ["block", "handler", "finalizer"],
100
+ UnaryExpression: ["argument"],
101
+ UpdateExpression: ["argument"],
102
+ VariableDeclaration: ["declarations"],
103
+ VariableDeclarator: ["id", "init"],
104
+ WhileStatement: ["test", "body"],
105
+ WithStatement: ["object", "body"],
106
+ YieldExpression: ["argument"],
107
+ };
108
+
109
+ // Types.
110
+ const NODE_TYPES = Object.keys(KEYS);
111
+
112
+ // Freeze the keys.
113
+ for (const type of NODE_TYPES) {
114
+ Object.freeze(KEYS[type]);
115
+ }
116
+ Object.freeze(KEYS);
117
+
118
+ export default KEYS;
tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/package.json ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "eslint-visitor-keys",
3
+ "version": "5.0.1",
4
+ "description": "Constants and utilities about visitor keys to traverse AST.",
5
+ "type": "module",
6
+ "main": "dist/eslint-visitor-keys.cjs",
7
+ "types": "./dist/index.d.ts",
8
+ "exports": {
9
+ ".": [
10
+ {
11
+ "import": "./lib/index.js",
12
+ "require": "./dist/eslint-visitor-keys.cjs"
13
+ },
14
+ "./dist/eslint-visitor-keys.cjs"
15
+ ],
16
+ "./package.json": "./package.json"
17
+ },
18
+ "files": [
19
+ "dist/index.d.ts",
20
+ "dist/visitor-keys.d.ts",
21
+ "dist/eslint-visitor-keys.cjs",
22
+ "dist/eslint-visitor-keys.d.cts",
23
+ "lib"
24
+ ],
25
+ "engines": {
26
+ "node": "^20.19.0 || ^22.13.0 || >=24"
27
+ },
28
+ "devDependencies": {
29
+ "rollup-plugin-dts": "^6.2.3",
30
+ "tsd": "^0.33.0"
31
+ },
32
+ "scripts": {
33
+ "build": "npm run build:cjs && npm run build:types",
34
+ "build:cjs": "rollup -c",
35
+ "build:debug": "npm run build:cjs -- -m && npm run build:types",
36
+ "build:types": "tsc -v && tsc",
37
+ "test": "mocha \"tests/**/*.test.cjs\" && mocha \"tests/**/*.test.js\" && npm run test:types",
38
+ "test:coverage": "c8 npm test",
39
+ "test:types": "tsd"
40
+ },
41
+ "repository": {
42
+ "type": "git",
43
+ "url": "https://github.com/eslint/js.git",
44
+ "directory": "packages/eslint-visitor-keys"
45
+ },
46
+ "funding": "https://opencollective.com/eslint",
47
+ "keywords": [
48
+ "eslint"
49
+ ],
50
+ "author": "Toru Nagashima (https://github.com/mysticatea)",
51
+ "license": "Apache-2.0",
52
+ "bugs": {
53
+ "url": "https://github.com/eslint/js/issues"
54
+ },
55
+ "homepage": "https://github.com/eslint/js/blob/main/packages/eslint-visitor-keys/README.md",
56
+ "sideEffects": false
57
+ }
tools/ui/node_modules/@typescript-eslint/visitor-keys/package.json ADDED
@@ -0,0 +1,76 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@typescript-eslint/visitor-keys",
3
+ "version": "8.60.1",
4
+ "description": "Visitor keys used to help traverse the TypeScript-ESTree AST",
5
+ "files": [
6
+ "dist",
7
+ "!**/*.tsbuildinfo",
8
+ "package.json",
9
+ "README.md",
10
+ "LICENSE"
11
+ ],
12
+ "type": "commonjs",
13
+ "exports": {
14
+ ".": {
15
+ "types": "./dist/index.d.ts",
16
+ "default": "./dist/index.js"
17
+ },
18
+ "./package.json": "./package.json"
19
+ },
20
+ "types": "./dist/index.d.ts",
21
+ "engines": {
22
+ "node": "^18.18.0 || ^20.9.0 || >=21.1.0"
23
+ },
24
+ "repository": {
25
+ "type": "git",
26
+ "url": "https://github.com/typescript-eslint/typescript-eslint.git",
27
+ "directory": "packages/visitor-keys"
28
+ },
29
+ "bugs": {
30
+ "url": "https://github.com/typescript-eslint/typescript-eslint/issues"
31
+ },
32
+ "homepage": "https://typescript-eslint.io",
33
+ "license": "MIT",
34
+ "keywords": [
35
+ "eslint",
36
+ "typescript",
37
+ "estree"
38
+ ],
39
+ "dependencies": {
40
+ "eslint-visitor-keys": "^5.0.0",
41
+ "@typescript-eslint/types": "8.60.1"
42
+ },
43
+ "devDependencies": {
44
+ "@typescript/native-preview": "7.0.0-dev.20260518.1",
45
+ "@vitest/coverage-v8": "^4.0.18",
46
+ "eslint": "^10.0.0",
47
+ "rimraf": "^5.0.10",
48
+ "typescript": ">=4.8.4 <6.1.0",
49
+ "vitest": "^4.0.18"
50
+ },
51
+ "funding": {
52
+ "type": "opencollective",
53
+ "url": "https://opencollective.com/typescript-eslint"
54
+ },
55
+ "nx": {
56
+ "name": "visitor-keys",
57
+ "includedScripts": [
58
+ "clean"
59
+ ],
60
+ "targets": {
61
+ "lint": {
62
+ "command": "eslint"
63
+ },
64
+ "typecheck:tsgo": {}
65
+ }
66
+ },
67
+ "scripts": {
68
+ "build": "pnpm exec nx build",
69
+ "clean": "rimraf dist/ coverage/",
70
+ "format": "pnpm -w run format",
71
+ "lint": "pnpm -w exec nx lint",
72
+ "test": "pnpm -w exec nx test",
73
+ "typecheck": "pnpm -w exec nx typecheck",
74
+ "typecheck:tsgo": "pnpm -w exec nx typecheck:tsgo"
75
+ }
76
+ }
tools/ui/node_modules/@ungap/structured-clone/.github/workflows/node.js.yml ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 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
2
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3
+
4
+ name: build
5
+
6
+ on: [push, pull_request]
7
+
8
+ jobs:
9
+ build:
10
+
11
+ runs-on: ubuntu-latest
12
+
13
+ strategy:
14
+ matrix:
15
+ node-version: [16]
16
+
17
+ steps:
18
+ - uses: actions/checkout@v2
19
+ - name: Use Node.js ${{ matrix.node-version }}
20
+ uses: actions/setup-node@v2
21
+ with:
22
+ node-version: ${{ matrix.node-version }}
23
+ cache: 'npm'
24
+ - run: npm ci
25
+ - run: npm run build --if-present
26
+ - run: npm test
27
+ - run: npm run coverage --if-present
28
+ - name: Coveralls
29
+ uses: coverallsapp/github-action@master
30
+ with:
31
+ github-token: ${{ secrets.GITHUB_TOKEN }}
tools/ui/node_modules/@ungap/structured-clone/LICENSE ADDED
@@ -0,0 +1,15 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ISC License
2
+
3
+ Copyright (c) 2021, Andrea Giammarchi, @WebReflection
4
+
5
+ Permission to use, copy, modify, and/or distribute this software for any
6
+ purpose with or without fee is hereby granted, provided that the above
7
+ copyright notice and this permission notice appear in all copies.
8
+
9
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
10
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
11
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
12
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
13
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
14
+ OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
15
+ PERFORMANCE OF THIS SOFTWARE.
tools/ui/node_modules/@ungap/structured-clone/README.md ADDED
@@ -0,0 +1,95 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # structuredClone polyfill
2
+
3
+ [![Downloads](https://img.shields.io/npm/dm/@ungap/structured-clone.svg)](https://www.npmjs.com/package/@ungap/structured-clone) [![build status](https://github.com/ungap/structured-clone/actions/workflows/node.js.yml/badge.svg)](https://github.com/ungap/structured-clone/actions) [![Coverage Status](https://coveralls.io/repos/github/ungap/structured-clone/badge.svg?branch=main)](https://coveralls.io/github/ungap/structured-clone?branch=main)
4
+
5
+ An env agnostic serializer and deserializer with recursion ability and types beyond *JSON* from the *HTML* standard itself.
6
+
7
+ * [Supported Types](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types)
8
+ * *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).
9
+ * *not possible to implement*: the `{transfer: []}` option can be passed but it's completely ignored.
10
+ * [MDN Documentation](https://developer.mozilla.org/en-US/docs/Web/API/structuredClone)
11
+ * [Serializer](https://html.spec.whatwg.org/multipage/structured-data.html#structuredserializeinternal)
12
+ * [Deserializer](https://html.spec.whatwg.org/multipage/structured-data.html#structureddeserialize)
13
+
14
+ Serialized values can be safely stringified as *JSON* too, and deserialization resurrect all values, even recursive, or more complex than what *JSON* allows.
15
+
16
+
17
+ ### Examples
18
+
19
+ Check the [100% test coverage](./test/index.js) to know even more.
20
+
21
+ ```js
22
+ // as default export
23
+ import structuredClone from '@ungap/structured-clone';
24
+ const cloned = structuredClone({any: 'serializable'});
25
+
26
+ // as independent serializer/deserializer
27
+ import {serialize, deserialize} from '@ungap/structured-clone';
28
+
29
+ // the result can be stringified as JSON without issues
30
+ // even if there is recursive data, bigint values,
31
+ // typed arrays, and so on
32
+ const serialized = serialize({any: 'serializable'});
33
+
34
+ // the result will be a replica of the original object
35
+ const deserialized = deserialize(serialized);
36
+ ```
37
+
38
+ #### Global Polyfill
39
+ Note: Only monkey patch the global if needed. This polyfill works just fine as an explicit import: `import structuredClone from "@ungap/structured-clone"`
40
+ ```js
41
+ // Attach the polyfill as a Global function
42
+ import structuredClone from "@ungap/structured-clone";
43
+ if (!("structuredClone" in globalThis)) {
44
+ globalThis.structuredClone = structuredClone;
45
+ }
46
+
47
+ // Or don't monkey patch
48
+ import structuredClone from "@ungap/structured-clone"
49
+ // Just use it in the file
50
+ structuredClone()
51
+ ```
52
+
53
+ **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.
54
+
55
+ ### Extra Features
56
+
57
+ There is no middle-ground between the structured clone algorithm and JSON:
58
+
59
+ * JSON is more relaxed about incompatible values: it just ignores these
60
+ * 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
61
+
62
+ 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.
63
+
64
+ ```js
65
+ // as default export
66
+ import structuredClone from '@ungap/structured-clone';
67
+ const cloned = structuredClone(
68
+ {
69
+ method() {
70
+ // ignored, won't be cloned
71
+ },
72
+ special: Symbol('also ignored')
73
+ },
74
+ {
75
+ // avoid throwing
76
+ lossy: true,
77
+ // avoid throwing *and* looks for toJSON
78
+ json: true
79
+ }
80
+ );
81
+ ```
82
+
83
+ The behavior is the same found in *JSON* when it comes to *Array*, so that unsupported values will result as `null` placeholders instead.
84
+
85
+ #### toJSON
86
+
87
+ If `lossy` option is not enough, `json` will actually enforce `lossy` and also check for `toJSON` method when objects are parsed.
88
+
89
+ Alternative, the `json` exports combines all features:
90
+
91
+ ```js
92
+ import {stringify, parse} from '@ungap/structured-clone/json';
93
+
94
+ parse(stringify({any: 'serializable'}));
95
+ ```
tools/ui/node_modules/@ungap/structured-clone/cjs/deserialize.js ADDED
@@ -0,0 +1,97 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const {
3
+ VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
4
+ } = require('./types.js');
5
+
6
+ const env = typeof self === 'object' ? self : globalThis;
7
+
8
+ const guard = (name, init) => {
9
+ switch (name) {
10
+ case 'Function':
11
+ case 'SharedWorker':
12
+ case 'Worker':
13
+ case 'eval':
14
+ case 'setInterval':
15
+ case 'setTimeout':
16
+ throw new TypeError('unable to deserialize ' + name);
17
+ }
18
+ return new env[name](init);
19
+ };
20
+
21
+ const deserializer = ($, _) => {
22
+ const as = (out, index) => {
23
+ $.set(index, out);
24
+ return out;
25
+ };
26
+
27
+ const unpair = index => {
28
+ if ($.has(index))
29
+ return $.get(index);
30
+
31
+ const [type, value] = _[index];
32
+ switch (type) {
33
+ case PRIMITIVE:
34
+ case VOID:
35
+ return as(value, index);
36
+ case ARRAY: {
37
+ const arr = as([], index);
38
+ for (const index of value)
39
+ arr.push(unpair(index));
40
+ return arr;
41
+ }
42
+ case OBJECT: {
43
+ const object = as({}, index);
44
+ for (const [key, index] of value)
45
+ object[unpair(key)] = unpair(index);
46
+ return object;
47
+ }
48
+ case DATE:
49
+ return as(new Date(value), index);
50
+ case REGEXP: {
51
+ const {source, flags} = value;
52
+ return as(new RegExp(source, flags), index);
53
+ }
54
+ case MAP: {
55
+ const map = as(new Map, index);
56
+ for (const [key, index] of value)
57
+ map.set(unpair(key), unpair(index));
58
+ return map;
59
+ }
60
+ case SET: {
61
+ const set = as(new Set, index);
62
+ for (const index of value)
63
+ set.add(unpair(index));
64
+ return set;
65
+ }
66
+ case ERROR: {
67
+ const {name, message} = value;
68
+ return as(guard(name, message), index);
69
+ }
70
+ case BIGINT:
71
+ return as(BigInt(value), index);
72
+ case 'BigInt':
73
+ return as(Object(BigInt(value)), index);
74
+ case 'ArrayBuffer':
75
+ return as(new Uint8Array(value).buffer, value);
76
+ case 'DataView': {
77
+ const { buffer } = new Uint8Array(value);
78
+ return as(new DataView(buffer), value);
79
+ }
80
+ }
81
+ return as(guard(type, value), index);
82
+ };
83
+
84
+ return unpair;
85
+ };
86
+
87
+ /**
88
+ * @typedef {Array<string,any>} Record a type representation
89
+ */
90
+
91
+ /**
92
+ * Returns a deserialized value from a serialized array of Records.
93
+ * @param {Record[]} serialized a previously serialized value.
94
+ * @returns {any}
95
+ */
96
+ const deserialize = serialized => deserializer(new Map, serialized)(0);
97
+ exports.deserialize = deserialize;
tools/ui/node_modules/@ungap/structured-clone/cjs/index.js ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const {deserialize} = require('./deserialize.js');
3
+ const {serialize} = require('./serialize.js');
4
+
5
+ /**
6
+ * @typedef {Array<string,any>} Record a type representation
7
+ */
8
+
9
+ /**
10
+ * Returns an array of serialized Records.
11
+ * @param {any} any a serializable value.
12
+ * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
13
+ * a transfer option (ignored when polyfilled) and/or non standard fields that
14
+ * fallback to the polyfill if present.
15
+ * @returns {Record[]}
16
+ */
17
+ Object.defineProperty(exports, '__esModule', {value: true}).default = typeof structuredClone === "function" ?
18
+ /* c8 ignore start */
19
+ (any, options) => (
20
+ options && ('json' in options || 'lossy' in options) ?
21
+ deserialize(serialize(any, options)) : structuredClone(any)
22
+ ) :
23
+ (any, options) => deserialize(serialize(any, options));
24
+ /* c8 ignore stop */
25
+
26
+ exports.deserialize = deserialize;
27
+ exports.serialize = serialize;
tools/ui/node_modules/@ungap/structured-clone/cjs/json.js ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ /*! (c) Andrea Giammarchi - ISC */
3
+
4
+ const {deserialize} = require('./deserialize.js');
5
+ const {serialize} = require('./serialize.js');
6
+
7
+ const {parse: $parse, stringify: $stringify} = JSON;
8
+ const options = {json: true, lossy: true};
9
+
10
+ /**
11
+ * Revive a previously stringified structured clone.
12
+ * @param {string} str previously stringified data as string.
13
+ * @returns {any} whatever was previously stringified as clone.
14
+ */
15
+ const parse = str => deserialize($parse(str));
16
+ exports.parse = parse;
17
+
18
+ /**
19
+ * Represent a structured clone value as string.
20
+ * @param {any} any some clone-able value to stringify.
21
+ * @returns {string} the value stringified.
22
+ */
23
+ const stringify = any => $stringify(serialize(any, options));
24
+ exports.stringify = stringify;
tools/ui/node_modules/@ungap/structured-clone/cjs/package.json ADDED
@@ -0,0 +1 @@
 
 
1
+ {"type":"commonjs"}
tools/ui/node_modules/@ungap/structured-clone/cjs/serialize.js ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const {
3
+ VOID, PRIMITIVE, ARRAY, OBJECT, DATE, REGEXP, MAP, SET, ERROR, BIGINT
4
+ } = require('./types.js');
5
+
6
+ const EMPTY = '';
7
+
8
+ const {toString} = {};
9
+ const {keys} = Object;
10
+
11
+ const typeOf = value => {
12
+ const type = typeof value;
13
+ if (type !== 'object' || !value)
14
+ return [PRIMITIVE, type];
15
+
16
+ const asString = toString.call(value).slice(8, -1);
17
+ switch (asString) {
18
+ case 'Array':
19
+ return [ARRAY, EMPTY];
20
+ case 'Object':
21
+ return [OBJECT, EMPTY];
22
+ case 'Date':
23
+ return [DATE, EMPTY];
24
+ case 'RegExp':
25
+ return [REGEXP, EMPTY];
26
+ case 'Map':
27
+ return [MAP, EMPTY];
28
+ case 'Set':
29
+ return [SET, EMPTY];
30
+ case 'DataView':
31
+ return [ARRAY, asString];
32
+ }
33
+
34
+ if (asString.includes('Array'))
35
+ return [ARRAY, asString];
36
+
37
+ if (asString.includes('Error'))
38
+ return [ERROR, asString];
39
+
40
+ return [OBJECT, asString];
41
+ };
42
+
43
+ const shouldSkip = ([TYPE, type]) => (
44
+ TYPE === PRIMITIVE &&
45
+ (type === 'function' || type === 'symbol')
46
+ );
47
+
48
+ const serializer = (strict, json, $, _) => {
49
+
50
+ const as = (out, value) => {
51
+ const index = _.push(out) - 1;
52
+ $.set(value, index);
53
+ return index;
54
+ };
55
+
56
+ const pair = value => {
57
+ if ($.has(value))
58
+ return $.get(value);
59
+
60
+ let [TYPE, type] = typeOf(value);
61
+ switch (TYPE) {
62
+ case PRIMITIVE: {
63
+ let entry = value;
64
+ switch (type) {
65
+ case 'bigint':
66
+ TYPE = BIGINT;
67
+ entry = value.toString();
68
+ break;
69
+ case 'function':
70
+ case 'symbol':
71
+ if (strict)
72
+ throw new TypeError('unable to serialize ' + type);
73
+ entry = null;
74
+ break;
75
+ case 'undefined':
76
+ return as([VOID], value);
77
+ }
78
+ return as([TYPE, entry], value);
79
+ }
80
+ case ARRAY: {
81
+ if (type) {
82
+ let spread = value;
83
+ if (type === 'DataView') {
84
+ spread = new Uint8Array(value.buffer);
85
+ }
86
+ else if (type === 'ArrayBuffer') {
87
+ spread = new Uint8Array(value);
88
+ }
89
+ return as([type, [...spread]], value);
90
+ }
91
+
92
+ const arr = [];
93
+ const index = as([TYPE, arr], value);
94
+ for (const entry of value)
95
+ arr.push(pair(entry));
96
+ return index;
97
+ }
98
+ case OBJECT: {
99
+ if (type) {
100
+ switch (type) {
101
+ case 'BigInt':
102
+ return as([type, value.toString()], value);
103
+ case 'Boolean':
104
+ case 'Number':
105
+ case 'String':
106
+ return as([type, value.valueOf()], value);
107
+ }
108
+ }
109
+
110
+ if (json && ('toJSON' in value))
111
+ return pair(value.toJSON());
112
+
113
+ const entries = [];
114
+ const index = as([TYPE, entries], value);
115
+ for (const key of keys(value)) {
116
+ if (strict || !shouldSkip(typeOf(value[key])))
117
+ entries.push([pair(key), pair(value[key])]);
118
+ }
119
+ return index;
120
+ }
121
+ case DATE:
122
+ return as([TYPE, value.toISOString()], value);
123
+ case REGEXP: {
124
+ const {source, flags} = value;
125
+ return as([TYPE, {source, flags}], value);
126
+ }
127
+ case MAP: {
128
+ const entries = [];
129
+ const index = as([TYPE, entries], value);
130
+ for (const [key, entry] of value) {
131
+ if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
132
+ entries.push([pair(key), pair(entry)]);
133
+ }
134
+ return index;
135
+ }
136
+ case SET: {
137
+ const entries = [];
138
+ const index = as([TYPE, entries], value);
139
+ for (const entry of value) {
140
+ if (strict || !shouldSkip(typeOf(entry)))
141
+ entries.push(pair(entry));
142
+ }
143
+ return index;
144
+ }
145
+ }
146
+
147
+ const {message} = value;
148
+ return as([TYPE, {name: type, message}], value);
149
+ };
150
+
151
+ return pair;
152
+ };
153
+
154
+ /**
155
+ * @typedef {Array<string,any>} Record a type representation
156
+ */
157
+
158
+ /**
159
+ * Returns an array of serialized Records.
160
+ * @param {any} value a serializable value.
161
+ * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
162
+ * if `true`, will not throw errors on incompatible types, and behave more
163
+ * like JSON stringify would behave. Symbol and Function will be discarded.
164
+ * @returns {Record[]}
165
+ */
166
+ const serialize = (value, {json, lossy} = {}) => {
167
+ const _ = [];
168
+ return serializer(!(json || lossy), !!json, new Map, _)(value), _;
169
+ };
170
+ exports.serialize = serialize;
tools/ui/node_modules/@ungap/structured-clone/cjs/types.js ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+ const VOID = -1;
3
+ exports.VOID = VOID;
4
+ const PRIMITIVE = 0;
5
+ exports.PRIMITIVE = PRIMITIVE;
6
+ const ARRAY = 1;
7
+ exports.ARRAY = ARRAY;
8
+ const OBJECT = 2;
9
+ exports.OBJECT = OBJECT;
10
+ const DATE = 3;
11
+ exports.DATE = DATE;
12
+ const REGEXP = 4;
13
+ exports.REGEXP = REGEXP;
14
+ const MAP = 5;
15
+ exports.MAP = MAP;
16
+ const SET = 6;
17
+ exports.SET = SET;
18
+ const ERROR = 7;
19
+ exports.ERROR = ERROR;
20
+ const BIGINT = 8;
21
+ exports.BIGINT = BIGINT;
22
+ // export const SYMBOL = 9;
tools/ui/node_modules/@ungap/structured-clone/esm/deserialize.js ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ VOID, PRIMITIVE,
3
+ ARRAY, OBJECT,
4
+ DATE, REGEXP, MAP, SET,
5
+ ERROR, BIGINT
6
+ } from './types.js';
7
+
8
+ const env = typeof self === 'object' ? self : globalThis;
9
+
10
+ const guard = (name, init) => {
11
+ switch (name) {
12
+ case 'Function':
13
+ case 'SharedWorker':
14
+ case 'Worker':
15
+ case 'eval':
16
+ case 'setInterval':
17
+ case 'setTimeout':
18
+ throw new TypeError('unable to deserialize ' + name);
19
+ }
20
+ return new env[name](init);
21
+ };
22
+
23
+ const deserializer = ($, _) => {
24
+ const as = (out, index) => {
25
+ $.set(index, out);
26
+ return out;
27
+ };
28
+
29
+ const unpair = index => {
30
+ if ($.has(index))
31
+ return $.get(index);
32
+
33
+ const [type, value] = _[index];
34
+ switch (type) {
35
+ case PRIMITIVE:
36
+ case VOID:
37
+ return as(value, index);
38
+ case ARRAY: {
39
+ const arr = as([], index);
40
+ for (const index of value)
41
+ arr.push(unpair(index));
42
+ return arr;
43
+ }
44
+ case OBJECT: {
45
+ const object = as({}, index);
46
+ for (const [key, index] of value)
47
+ object[unpair(key)] = unpair(index);
48
+ return object;
49
+ }
50
+ case DATE:
51
+ return as(new Date(value), index);
52
+ case REGEXP: {
53
+ const {source, flags} = value;
54
+ return as(new RegExp(source, flags), index);
55
+ }
56
+ case MAP: {
57
+ const map = as(new Map, index);
58
+ for (const [key, index] of value)
59
+ map.set(unpair(key), unpair(index));
60
+ return map;
61
+ }
62
+ case SET: {
63
+ const set = as(new Set, index);
64
+ for (const index of value)
65
+ set.add(unpair(index));
66
+ return set;
67
+ }
68
+ case ERROR: {
69
+ const {name, message} = value;
70
+ return as(guard(name, message), index);
71
+ }
72
+ case BIGINT:
73
+ return as(BigInt(value), index);
74
+ case 'BigInt':
75
+ return as(Object(BigInt(value)), index);
76
+ case 'ArrayBuffer':
77
+ return as(new Uint8Array(value).buffer, value);
78
+ case 'DataView': {
79
+ const { buffer } = new Uint8Array(value);
80
+ return as(new DataView(buffer), value);
81
+ }
82
+ }
83
+ return as(guard(type, value), index);
84
+ };
85
+
86
+ return unpair;
87
+ };
88
+
89
+ /**
90
+ * @typedef {Array<string,any>} Record a type representation
91
+ */
92
+
93
+ /**
94
+ * Returns a deserialized value from a serialized array of Records.
95
+ * @param {Record[]} serialized a previously serialized value.
96
+ * @returns {any}
97
+ */
98
+ export const deserialize = serialized => deserializer(new Map, serialized)(0);
tools/ui/node_modules/@ungap/structured-clone/esm/index.js ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {deserialize} from './deserialize.js';
2
+ import {serialize} from './serialize.js';
3
+
4
+ /**
5
+ * @typedef {Array<string,any>} Record a type representation
6
+ */
7
+
8
+ /**
9
+ * Returns an array of serialized Records.
10
+ * @param {any} any a serializable value.
11
+ * @param {{transfer?: any[], json?: boolean, lossy?: boolean}?} options an object with
12
+ * a transfer option (ignored when polyfilled) and/or non standard fields that
13
+ * fallback to the polyfill if present.
14
+ * @returns {Record[]}
15
+ */
16
+ export default typeof structuredClone === "function" ?
17
+ /* c8 ignore start */
18
+ (any, options) => (
19
+ options && ('json' in options || 'lossy' in options) ?
20
+ deserialize(serialize(any, options)) : structuredClone(any)
21
+ ) :
22
+ (any, options) => deserialize(serialize(any, options));
23
+ /* c8 ignore stop */
24
+
25
+ export {deserialize, serialize};
tools/ui/node_modules/@ungap/structured-clone/esm/json.js ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /*! (c) Andrea Giammarchi - ISC */
2
+
3
+ import {deserialize} from './deserialize.js';
4
+ import {serialize} from './serialize.js';
5
+
6
+ const {parse: $parse, stringify: $stringify} = JSON;
7
+ const options = {json: true, lossy: true};
8
+
9
+ /**
10
+ * Revive a previously stringified structured clone.
11
+ * @param {string} str previously stringified data as string.
12
+ * @returns {any} whatever was previously stringified as clone.
13
+ */
14
+ export const parse = str => deserialize($parse(str));
15
+
16
+ /**
17
+ * Represent a structured clone value as string.
18
+ * @param {any} any some clone-able value to stringify.
19
+ * @returns {string} the value stringified.
20
+ */
21
+ export const stringify = any => $stringify(serialize(any, options));
tools/ui/node_modules/@ungap/structured-clone/esm/serialize.js ADDED
@@ -0,0 +1,171 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import {
2
+ VOID, PRIMITIVE,
3
+ ARRAY, OBJECT,
4
+ DATE, REGEXP, MAP, SET,
5
+ ERROR, BIGINT
6
+ } from './types.js';
7
+
8
+ const EMPTY = '';
9
+
10
+ const {toString} = {};
11
+ const {keys} = Object;
12
+
13
+ const typeOf = value => {
14
+ const type = typeof value;
15
+ if (type !== 'object' || !value)
16
+ return [PRIMITIVE, type];
17
+
18
+ const asString = toString.call(value).slice(8, -1);
19
+ switch (asString) {
20
+ case 'Array':
21
+ return [ARRAY, EMPTY];
22
+ case 'Object':
23
+ return [OBJECT, EMPTY];
24
+ case 'Date':
25
+ return [DATE, EMPTY];
26
+ case 'RegExp':
27
+ return [REGEXP, EMPTY];
28
+ case 'Map':
29
+ return [MAP, EMPTY];
30
+ case 'Set':
31
+ return [SET, EMPTY];
32
+ case 'DataView':
33
+ return [ARRAY, asString];
34
+ }
35
+
36
+ if (asString.includes('Array'))
37
+ return [ARRAY, asString];
38
+
39
+ if (asString.includes('Error'))
40
+ return [ERROR, asString];
41
+
42
+ return [OBJECT, asString];
43
+ };
44
+
45
+ const shouldSkip = ([TYPE, type]) => (
46
+ TYPE === PRIMITIVE &&
47
+ (type === 'function' || type === 'symbol')
48
+ );
49
+
50
+ const serializer = (strict, json, $, _) => {
51
+
52
+ const as = (out, value) => {
53
+ const index = _.push(out) - 1;
54
+ $.set(value, index);
55
+ return index;
56
+ };
57
+
58
+ const pair = value => {
59
+ if ($.has(value))
60
+ return $.get(value);
61
+
62
+ let [TYPE, type] = typeOf(value);
63
+ switch (TYPE) {
64
+ case PRIMITIVE: {
65
+ let entry = value;
66
+ switch (type) {
67
+ case 'bigint':
68
+ TYPE = BIGINT;
69
+ entry = value.toString();
70
+ break;
71
+ case 'function':
72
+ case 'symbol':
73
+ if (strict)
74
+ throw new TypeError('unable to serialize ' + type);
75
+ entry = null;
76
+ break;
77
+ case 'undefined':
78
+ return as([VOID], value);
79
+ }
80
+ return as([TYPE, entry], value);
81
+ }
82
+ case ARRAY: {
83
+ if (type) {
84
+ let spread = value;
85
+ if (type === 'DataView') {
86
+ spread = new Uint8Array(value.buffer);
87
+ }
88
+ else if (type === 'ArrayBuffer') {
89
+ spread = new Uint8Array(value);
90
+ }
91
+ return as([type, [...spread]], value);
92
+ }
93
+
94
+ const arr = [];
95
+ const index = as([TYPE, arr], value);
96
+ for (const entry of value)
97
+ arr.push(pair(entry));
98
+ return index;
99
+ }
100
+ case OBJECT: {
101
+ if (type) {
102
+ switch (type) {
103
+ case 'BigInt':
104
+ return as([type, value.toString()], value);
105
+ case 'Boolean':
106
+ case 'Number':
107
+ case 'String':
108
+ return as([type, value.valueOf()], value);
109
+ }
110
+ }
111
+
112
+ if (json && ('toJSON' in value))
113
+ return pair(value.toJSON());
114
+
115
+ const entries = [];
116
+ const index = as([TYPE, entries], value);
117
+ for (const key of keys(value)) {
118
+ if (strict || !shouldSkip(typeOf(value[key])))
119
+ entries.push([pair(key), pair(value[key])]);
120
+ }
121
+ return index;
122
+ }
123
+ case DATE:
124
+ return as([TYPE, value.toISOString()], value);
125
+ case REGEXP: {
126
+ const {source, flags} = value;
127
+ return as([TYPE, {source, flags}], value);
128
+ }
129
+ case MAP: {
130
+ const entries = [];
131
+ const index = as([TYPE, entries], value);
132
+ for (const [key, entry] of value) {
133
+ if (strict || !(shouldSkip(typeOf(key)) || shouldSkip(typeOf(entry))))
134
+ entries.push([pair(key), pair(entry)]);
135
+ }
136
+ return index;
137
+ }
138
+ case SET: {
139
+ const entries = [];
140
+ const index = as([TYPE, entries], value);
141
+ for (const entry of value) {
142
+ if (strict || !shouldSkip(typeOf(entry)))
143
+ entries.push(pair(entry));
144
+ }
145
+ return index;
146
+ }
147
+ }
148
+
149
+ const {message} = value;
150
+ return as([TYPE, {name: type, message}], value);
151
+ };
152
+
153
+ return pair;
154
+ };
155
+
156
+ /**
157
+ * @typedef {Array<string,any>} Record a type representation
158
+ */
159
+
160
+ /**
161
+ * Returns an array of serialized Records.
162
+ * @param {any} value a serializable value.
163
+ * @param {{json?: boolean, lossy?: boolean}?} options an object with a `lossy` or `json` property that,
164
+ * if `true`, will not throw errors on incompatible types, and behave more
165
+ * like JSON stringify would behave. Symbol and Function will be discarded.
166
+ * @returns {Record[]}
167
+ */
168
+ export const serialize = (value, {json, lossy} = {}) => {
169
+ const _ = [];
170
+ return serializer(!(json || lossy), !!json, new Map, _)(value), _;
171
+ };
tools/ui/node_modules/@ungap/structured-clone/esm/types.js ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export const VOID = -1;
2
+ export const PRIMITIVE = 0;
3
+ export const ARRAY = 1;
4
+ export const OBJECT = 2;
5
+ export const DATE = 3;
6
+ export const REGEXP = 4;
7
+ export const MAP = 5;
8
+ export const SET = 6;
9
+ export const ERROR = 7;
10
+ export const BIGINT = 8;
11
+ // export const SYMBOL = 9;
tools/ui/node_modules/@ungap/structured-clone/package.json ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@ungap/structured-clone",
3
+ "version": "1.3.1",
4
+ "description": "A structuredClone polyfill",
5
+ "main": "./cjs/index.js",
6
+ "scripts": {
7
+ "build": "npm run cjs && npm run rollup:json && npm run test",
8
+ "cjs": "ascjs esm cjs",
9
+ "coverage": "c8 report --reporter=text-lcov > ./coverage/lcov.info",
10
+ "rollup:json": "rollup --config rollup/json.config.js",
11
+ "test": "c8 node test/index.js"
12
+ },
13
+ "keywords": [
14
+ "recursion",
15
+ "structured",
16
+ "clone",
17
+ "algorithm"
18
+ ],
19
+ "author": "Andrea Giammarchi",
20
+ "license": "ISC",
21
+ "devDependencies": {
22
+ "@rollup/plugin-node-resolve": "^16.0.3",
23
+ "@rollup/plugin-terser": "^1.0.0",
24
+ "ascjs": "^6.0.3",
25
+ "c8": "^11.0.0",
26
+ "coveralls": "^3.1.1",
27
+ "rollup": "^4.60.3"
28
+ },
29
+ "module": "./esm/index.js",
30
+ "type": "module",
31
+ "sideEffects": false,
32
+ "exports": {
33
+ ".": {
34
+ "import": "./esm/index.js",
35
+ "default": "./cjs/index.js"
36
+ },
37
+ "./json": {
38
+ "import": "./esm/json.js",
39
+ "default": "./cjs/json.js"
40
+ },
41
+ "./package.json": "./package.json"
42
+ },
43
+ "directories": {
44
+ "test": "test"
45
+ },
46
+ "repository": {
47
+ "type": "git",
48
+ "url": "git+https://github.com/ungap/structured-clone.git"
49
+ },
50
+ "bugs": {
51
+ "url": "https://github.com/ungap/structured-clone/issues"
52
+ },
53
+ "homepage": "https://github.com/ungap/structured-clone#readme"
54
+ }
tools/ui/node_modules/@ungap/structured-clone/structured-json.js ADDED
@@ -0,0 +1 @@
 
 
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}({});
tools/ui/node_modules/@upsetjs/venn.js/LICENSE ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2013 Ben Frederickson
4
+ Copyright (c) 2021 Samuel Gratzl
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
tools/ui/node_modules/@upsetjs/venn.js/README.md ADDED
@@ -0,0 +1,267 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # venn.js
2
+
3
+ [![License: MIT][mit-image]][mit-url] [![NPM Package][npm-image]][npm-url] [![Github Actions][github-actions-image]][github-actions-url]
4
+
5
+ This is a maintained fork of [https://github.com/benfred/venn.js](https://github.com/benfred/venn.js).
6
+
7
+ A javascript library for laying out area proportional venn and euler diagrams.
8
+
9
+ Details of how this library works can be found on the [blog
10
+ post](https://www.benfrederickson.com/venn-diagrams-with-d3.js/)
11
+ the original author wrote about this. A follow up post [discusses testing strategy and
12
+ algorithmic improvements](https://www.benfrederickson.com/better-venn-diagrams/).
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ npm install --save @upsetjs/venn.js
18
+ ```
19
+
20
+ ## Usage
21
+
22
+ There are two modes in which this library can be used.
23
+ First, in a managed case by using the `VennDiagram` function that will render the data using D3.
24
+ Second, in a manual case as a layout library that is just preparing the data for you.
25
+
26
+ In the following, these set data are used:
27
+
28
+ ```js
29
+ const sets = [
30
+ { sets: ['A'], size: 12 },
31
+ { sets: ['B'], size: 12 },
32
+ { sets: ['A', 'B'], size: 2 },
33
+ ];
34
+ ```
35
+
36
+ ### Managed Usage
37
+
38
+ This library depends on [d3.js](https://d3js.org/) to display the venn
39
+ diagrams.
40
+
41
+ ##### Simple layout
42
+
43
+ To lay out a simple diagram, just define the sets and their sizes along with the sizes
44
+ of all the set intersections.
45
+
46
+ The VennDiagram object will calculate a layout that is proportional to the
47
+ input sizes, and display it in the appropriate selection when called:
48
+
49
+ ```js
50
+ const chart = venn.VennDiagram();
51
+ d3.select('#venn').datum(sets).call(chart);
52
+ ```
53
+
54
+ [View this example](https://upset.js.org/venn.js/examples/simple.html)
55
+
56
+ [![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/RwrKPEe)
57
+
58
+ ##### Changing the Style
59
+
60
+ The style of the Venn Diagram can be customized by using D3 after the diagram
61
+ has been drawn. For instance to draw a Venn Diagram with white text and a darker fill:
62
+
63
+ ```js
64
+ const chart = venn.VennDiagram();
65
+ d3.select('#inverted').datum(sets).call(chart);
66
+
67
+ d3.selectAll('#inverted .venn-circle path').style('fill-opacity', 0.8);
68
+
69
+ d3.selectAll('#inverted text').style('fill', 'white');
70
+ ```
71
+
72
+ [View this example, along with other possible styles](https://upset.js.org/venn.js/examples/styled.html)
73
+
74
+ The position of text within each circle of the diagram may also be modified via the `symmetricalTextCentre` property (defaults to `false`):
75
+
76
+ ```js
77
+ // draw a diagram with text symmetrically positioned in each circle's centre
78
+ const chart = venn.VennDiagram({ symmetricalTextCentre: true });
79
+ ```
80
+
81
+ ##### Dynamic layout
82
+
83
+ To have a layout that reacts to a change in input, all that you need to do is
84
+ update the dataset and call the chart again:
85
+
86
+ ```js
87
+ // draw the initial diagram
88
+ const chart = venn.VennDiagram();
89
+ d3.select('#venn').datum(getSetIntersections()).call(chart);
90
+
91
+ // redraw the diagram on any change in input
92
+ d3.selectAll('input').on('change', function () {
93
+ d3.select('#venn').datum(getSetIntersections()).call(chart);
94
+ });
95
+ ```
96
+
97
+ [View this example](https://upset.js.org/venn.js/examples/dynamic.html)
98
+
99
+ ##### Making the diagram interactive
100
+
101
+ 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:
102
+
103
+ ```js
104
+ d3.selectAll('#rings .venn-circle')
105
+ .on('mouseenter', function () {
106
+ const node = d3.select(this).transition();
107
+ node.select('path').style('fill-opacity', 0.2);
108
+ node.select('text').style('font-weight', '100').style('font-size', '36px');
109
+ })
110
+ .on('mouseleave', function () {
111
+ const node = d3.select(this).transition();
112
+ node.select('path').style('fill-opacity', 0);
113
+ node.select('text').style('font-weight', '100').style('font-size', '24px');
114
+ });
115
+ ```
116
+
117
+ [View this example](https://upset.js.org/venn.js/examples/interactive.html)
118
+
119
+ 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:
120
+
121
+ ```js
122
+ const chart = venn.VennDiagram({
123
+ colorScheme: ['rgb(235, 237, 238)', '#F26250'],
124
+ textFill: '#FFF',
125
+ });
126
+ ```
127
+
128
+ ##### Adding tooltips
129
+
130
+ Another common case is adding a tooltip when hovering over the elements in the diagram. The only
131
+ tricky thing here is maintaining the correct Z-order so that the smallest intersection areas
132
+ are on top, while still making the area that is being hovered over appear on top of the others:
133
+
134
+ ```js
135
+ // draw venn diagram
136
+ const div = d3.select('#venn');
137
+ div.datum(sets).call(venn.VennDiagram());
138
+
139
+ // add a tooltip
140
+ const tooltip = d3.select('body').append('div').attr('class', 'venntooltip');
141
+
142
+ // add listeners to all the groups to display tooltip on mouseenter
143
+ div
144
+ .selectAll('g')
145
+ .on('mouseenter', function (d) {
146
+ // sort all the areas relative to the current item
147
+ venn.sortAreas(div, d);
148
+
149
+ // Display a tooltip with the current size
150
+ tooltip.transition().duration(400).style('opacity', 0.9);
151
+ tooltip.text(d.size + ' users');
152
+
153
+ // highlight the current path
154
+ const selection = d3.select(this).transition('tooltip').duration(400);
155
+ selection
156
+ .select('path')
157
+ .style('stroke-width', 3)
158
+ .style('fill-opacity', d.sets.length == 1 ? 0.4 : 0.1)
159
+ .style('stroke-opacity', 1);
160
+ })
161
+
162
+ .on('mousemove', function () {
163
+ tooltip.style('left', d3.event.pageX + 'px').style('top', d3.event.pageY - 28 + 'px');
164
+ })
165
+
166
+ .on('mouseleave', function (d) {
167
+ tooltip.transition().duration(400).style('opacity', 0);
168
+ const selection = d3.select(this).transition('tooltip').duration(400);
169
+ selection
170
+ .select('path')
171
+ .style('stroke-width', 0)
172
+ .style('fill-opacity', d.sets.length == 1 ? 0.25 : 0.0)
173
+ .style('stroke-opacity', 0);
174
+ });
175
+ ```
176
+
177
+ [View this example](https://upset.js.org/venn.js/examples/intersection_tooltip.html)
178
+
179
+ ## Manual Usage
180
+
181
+ Besides the handy `VennDiagram` wrapper, the library can used as a pure layout function using the `layout` method.
182
+ One can render the result manually in D3 or even in HTML Canvas.
183
+
184
+ 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)
185
+
186
+ ### Custom D3 Rendering
187
+
188
+ ```js
189
+ // compute layout data
190
+ const data = venn.layout(sets);
191
+ // custom data binding and rendering
192
+ const g = d3
193
+ .select('#venn')
194
+ .selectAll('g')
195
+ .data(data)
196
+ .join((enter) => {
197
+ const g = enter.append('g');
198
+ g.append('title');
199
+ g.append('path');
200
+ g.append('text');
201
+ return g;
202
+ });
203
+ g.select('title').text((d) => d.data.sets.toString());
204
+ g.select('text')
205
+ .text((d) => d.data.sets.toString())
206
+ .attr('x', (d) => d.text.x)
207
+ .attr('y', (d) => d.text.y);
208
+ g.select('path')
209
+ .attr('d', (d) => d.path)
210
+ .style('fill', (d, i) => (d.circles.length === 1 ? d3.schemeCategory10[i] : undefined));
211
+ ```
212
+
213
+ [![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/xxZgGeP)
214
+
215
+ ### Canvas Rendering
216
+
217
+ ```js
218
+ const data = venn.layout(sets, { width: 600, height: 350 });
219
+ const ctx = document.querySelector('canvas').getContext('2d');
220
+
221
+ data.forEach((d, i) => {
222
+ ctx.fillStyle = `hsla(${(360 * i) / data.length},80%,50%,0.6)`;
223
+ ctx.fill(new Path2D(d.path));
224
+ });
225
+
226
+ ctx.font = '16px Helvetica Neue, Helvetica, Arial, sans-serif';
227
+ ctx.textAlign = 'center';
228
+ ctx.textBaseline = 'central';
229
+ ctx.fillStyle = 'white';
230
+
231
+ data.forEach((d, i) => {
232
+ ctx.fillText(d.data.sets.toString(), d.text.x, d.text.y);
233
+ });
234
+ ```
235
+
236
+ [![Open in CodePen][codepen]](https://codepen.io/sgratzl/pen/NWxdqZW)
237
+
238
+ ## License
239
+
240
+ Released under the MIT License.
241
+
242
+ ## Development Environment
243
+
244
+ ```sh
245
+ npm i -g yarn
246
+ yarn install
247
+ yarn sdks vscode
248
+ ```
249
+
250
+ ### Common commands
251
+
252
+ ```sh
253
+ yarn test
254
+ yarn lint
255
+ yarn format
256
+ yarn build
257
+ yarn release
258
+ yarn release:pre
259
+ ```
260
+
261
+ [mit-image]: https://img.shields.io/badge/License-MIT-yellow.svg
262
+ [mit-url]: https://opensource.org/licenses/MIT
263
+ [npm-image]: https://badge.fury.io/js/%40upsetjs%2Fvenn.js.svg
264
+ [npm-url]: https://npmjs.org/package/@upsetjs/venn.js
265
+ [github-actions-image]: https://github.com/upsetjs/venn.js/workflows/ci/badge.svg
266
+ [github-actions-url]: https://github.com/upsetjs/venn.js/actions
267
+ [codepen]: https://img.shields.io/badge/CodePen-open-blue?logo=codepen
tools/ui/node_modules/@upsetjs/venn.js/build/venn.esm.js ADDED
@@ -0,0 +1,2214 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const SMALL$1 = 1e-10;
2
+
3
+ /**
4
+ * Returns the intersection area of a bunch of circles (where each circle
5
+ * is an object having an x,y and radius property)
6
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
7
+ * @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<{
8
+ x: number;
9
+ y: number;
10
+ parentIndex: [number, number];
11
+ }>, intersectionPoints: ReadonlyArray<{
12
+ x: number;
13
+ y: number;
14
+ parentIndex: [number, number];
15
+ }> }} stats
16
+ * @returns {number}
17
+ */
18
+ function intersectionArea(circles, stats) {
19
+ // get all the intersection points of the circles
20
+ const intersectionPoints = getIntersectionPoints(circles);
21
+
22
+ // filter out points that aren't included in all the circles
23
+ const innerPoints = intersectionPoints.filter((p) => containedInCircles(p, circles));
24
+
25
+ let arcArea = 0;
26
+ let polygonArea = 0;
27
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
28
+ const arcs = [];
29
+
30
+ // if we have intersection points that are within all the circles,
31
+ // then figure out the area contained by them
32
+ if (innerPoints.length > 1) {
33
+ // sort the points by angle from the center of the polygon, which lets
34
+ // us just iterate over points to get the edges
35
+ const center = getCenter(innerPoints);
36
+ for (let i = 0; i < innerPoints.length; ++i) {
37
+ const p = innerPoints[i];
38
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
39
+ }
40
+ innerPoints.sort((a, b) => b.angle - a.angle);
41
+
42
+ // iterate over all points, get arc between the points
43
+ // and update the areas
44
+ let p2 = innerPoints[innerPoints.length - 1];
45
+ for (let i = 0; i < innerPoints.length; ++i) {
46
+ const p1 = innerPoints[i];
47
+
48
+ // polygon area updates easily ...
49
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
50
+
51
+ // updating the arc area is a little more involved
52
+ const midPoint = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
53
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
54
+ let arc = null;
55
+
56
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
57
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
58
+ // figure out the angle halfway between the two points
59
+ // on the current circle
60
+ const circle = circles[p1.parentIndex[j]];
61
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
62
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
63
+
64
+ let angleDiff = a2 - a1;
65
+ if (angleDiff < 0) {
66
+ angleDiff += 2 * Math.PI;
67
+ }
68
+
69
+ // and use that angle to figure out the width of the
70
+ // arc
71
+ const a = a2 - angleDiff / 2;
72
+ let width = distance(midPoint, {
73
+ x: circle.x + circle.radius * Math.sin(a),
74
+ y: circle.y + circle.radius * Math.cos(a),
75
+ });
76
+
77
+ // clamp the width to the largest is can actually be
78
+ // (sometimes slightly overflows because of FP errors)
79
+ if (width > circle.radius * 2) {
80
+ width = circle.radius * 2;
81
+ }
82
+
83
+ // pick the circle whose arc has the smallest width
84
+ if (arc == null || arc.width > width) {
85
+ arc = { circle, width, p1, p2, large: width > circle.radius, sweep: true };
86
+ }
87
+ }
88
+ }
89
+
90
+ if (arc != null) {
91
+ arcs.push(arc);
92
+ arcArea += circleArea(arc.circle.radius, arc.width);
93
+ p2 = p1;
94
+ }
95
+ }
96
+ } else {
97
+ // no intersection points, is either disjoint - or is completely
98
+ // overlapped. figure out which by examining the smallest circle
99
+ let smallest = circles[0];
100
+ for (let i = 1; i < circles.length; ++i) {
101
+ if (circles[i].radius < smallest.radius) {
102
+ smallest = circles[i];
103
+ }
104
+ }
105
+
106
+ // make sure the smallest circle is completely contained in all
107
+ // the other circles
108
+ let disjoint = false;
109
+ for (let i = 0; i < circles.length; ++i) {
110
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
111
+ disjoint = true;
112
+ break;
113
+ }
114
+ }
115
+
116
+ if (disjoint) {
117
+ arcArea = polygonArea = 0;
118
+ } else {
119
+ arcArea = smallest.radius * smallest.radius * Math.PI;
120
+ arcs.push({
121
+ circle: smallest,
122
+ p1: { x: smallest.x, y: smallest.y + smallest.radius },
123
+ p2: { x: smallest.x - SMALL$1, y: smallest.y + smallest.radius },
124
+ width: smallest.radius * 2,
125
+ large: true,
126
+ sweep: true,
127
+ });
128
+ }
129
+ }
130
+
131
+ polygonArea /= 2;
132
+
133
+ if (stats) {
134
+ stats.area = arcArea + polygonArea;
135
+ stats.arcArea = arcArea;
136
+ stats.polygonArea = polygonArea;
137
+ stats.arcs = arcs;
138
+ stats.innerPoints = innerPoints;
139
+ stats.intersectionPoints = intersectionPoints;
140
+ }
141
+
142
+ return arcArea + polygonArea;
143
+ }
144
+
145
+ /**
146
+ * returns whether a point is contained by all of a list of circles
147
+ * @param {{x: number, y: number}} point
148
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
149
+ * @returns {boolean}
150
+ */
151
+ function containedInCircles(point, circles) {
152
+ return circles.every((circle) => distance(point, circle) < circle.radius + SMALL$1);
153
+ }
154
+
155
+ /**
156
+ * Gets all intersection points between a bunch of circles
157
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
158
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
159
+ */
160
+ function getIntersectionPoints(circles) {
161
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
162
+ const ret = [];
163
+ for (let i = 0; i < circles.length; ++i) {
164
+ for (let j = i + 1; j < circles.length; ++j) {
165
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
166
+ for (const p of intersect) {
167
+ p.parentIndex = [i, j];
168
+ ret.push(p);
169
+ }
170
+ }
171
+ }
172
+ return ret;
173
+ }
174
+
175
+ /**
176
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
177
+ * @param {number} r
178
+ * @param {number} width
179
+ * @returns {number}
180
+ **/
181
+ function circleArea(r, width) {
182
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
183
+ }
184
+
185
+ /**
186
+ * euclidean distance between two points
187
+ * @param {{x: number, y: number}} p1
188
+ * @param {{x: number, y: number}} p2
189
+ * @returns {number}
190
+ **/
191
+ function distance(p1, p2) {
192
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
193
+ }
194
+
195
+ /**
196
+ * Returns the overlap area of two circles of radius r1 and r2 - that
197
+ * have their centers separated by distance d. Simpler faster
198
+ * circle intersection for only two circles
199
+ * @param {number} r1
200
+ * @param {number} r2
201
+ * @param {number} d
202
+ * @returns {number}
203
+ */
204
+ function circleOverlap(r1, r2, d) {
205
+ // no overlap
206
+ if (d >= r1 + r2) {
207
+ return 0;
208
+ }
209
+
210
+ // completely overlapped
211
+ if (d <= Math.abs(r1 - r2)) {
212
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
213
+ }
214
+
215
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
216
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
217
+ return circleArea(r1, w1) + circleArea(r2, w2);
218
+ }
219
+
220
+ /**
221
+ * Given two circles (containing a x/y/radius attributes),
222
+ * returns the intersecting points if possible
223
+ * note: doesn't handle cases where there are infinitely many
224
+ * intersection points (circles are equivalent):, or only one intersection point
225
+ * @param {{x: number, y: number, radius: number}} p1
226
+ * @param {{x: number, y: number, radius: number}} p2
227
+ * @returns {ReadonlyArray<{x: number, y: number}>}
228
+ **/
229
+ function circleCircleIntersection(p1, p2) {
230
+ const d = distance(p1, p2);
231
+ const r1 = p1.radius;
232
+ const r2 = p2.radius;
233
+
234
+ // if to far away, or self contained - can't be done
235
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
236
+ return [];
237
+ }
238
+
239
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
240
+ const h = Math.sqrt(r1 * r1 - a * a);
241
+ const x0 = p1.x + (a * (p2.x - p1.x)) / d;
242
+ const y0 = p1.y + (a * (p2.y - p1.y)) / d;
243
+ const rx = -(p2.y - p1.y) * (h / d);
244
+ const ry = -(p2.x - p1.x) * (h / d);
245
+
246
+ return [
247
+ { x: x0 + rx, y: y0 - ry },
248
+ { x: x0 - rx, y: y0 + ry },
249
+ ];
250
+ }
251
+
252
+ /**
253
+ * Returns the center of a bunch of points
254
+ * @param {ReadonlyArray<{x: number, y: number}>} points
255
+ * @returns {{x: number, y: number}}
256
+ */
257
+ function getCenter(points) {
258
+ const center = { x: 0, y: 0 };
259
+ for (const point of points) {
260
+ center.x += point.x;
261
+ center.y += point.y;
262
+ }
263
+ center.x /= points.length;
264
+ center.y /= points.length;
265
+ return center;
266
+ }
267
+
268
+ /** finds the zeros of a function, given two starting points (which must
269
+ * have opposite signs */
270
+ function bisect(f, a, b, parameters) {
271
+ parameters = parameters || {};
272
+ const maxIterations = parameters.maxIterations || 100;
273
+ const tolerance = parameters.tolerance || 1e-10;
274
+ const fA = f(a);
275
+ const fB = f(b);
276
+ let delta = b - a;
277
+
278
+ if (fA * fB > 0) {
279
+ throw 'Initial bisect points must have opposite signs';
280
+ }
281
+
282
+ if (fA === 0) return a;
283
+ if (fB === 0) return b;
284
+
285
+ for (let i = 0; i < maxIterations; ++i) {
286
+ delta /= 2;
287
+ const mid = a + delta;
288
+ const fMid = f(mid);
289
+
290
+ if (fMid * fA >= 0) {
291
+ a = mid;
292
+ }
293
+
294
+ if (Math.abs(delta) < tolerance || fMid === 0) {
295
+ return mid;
296
+ }
297
+ }
298
+ return a + delta;
299
+ }
300
+
301
+ // need some basic operations on vectors, rather than adding a dependency,
302
+ // just define here
303
+ function zeros(x) {
304
+ const r = new Array(x);
305
+ for (let i = 0; i < x; ++i) {
306
+ r[i] = 0;
307
+ }
308
+ return r;
309
+ }
310
+ function zerosM(x, y) {
311
+ return zeros(x).map(() => zeros(y));
312
+ }
313
+
314
+ function dot(a, b) {
315
+ let ret = 0;
316
+ for (let i = 0; i < a.length; ++i) {
317
+ ret += a[i] * b[i];
318
+ }
319
+ return ret;
320
+ }
321
+
322
+ function norm2(a) {
323
+ return Math.sqrt(dot(a, a));
324
+ }
325
+
326
+ function scale(ret, value, c) {
327
+ for (let i = 0; i < value.length; ++i) {
328
+ ret[i] = value[i] * c;
329
+ }
330
+ }
331
+
332
+ function weightedSum(ret, w1, v1, w2, v2) {
333
+ for (let j = 0; j < ret.length; ++j) {
334
+ ret[j] = w1 * v1[j] + w2 * v2[j];
335
+ }
336
+ }
337
+
338
+ /** minimizes a function using the downhill simplex method */
339
+ function nelderMead(f, x0, parameters) {
340
+ parameters = parameters || {};
341
+
342
+ const maxIterations = parameters.maxIterations || x0.length * 200;
343
+ const nonZeroDelta = parameters.nonZeroDelta || 1.05;
344
+ const zeroDelta = parameters.zeroDelta || 0.001;
345
+ const minErrorDelta = parameters.minErrorDelta || 1e-6;
346
+ const minTolerance = parameters.minErrorDelta || 1e-5;
347
+ const rho = parameters.rho !== undefined ? parameters.rho : 1;
348
+ const chi = parameters.chi !== undefined ? parameters.chi : 2;
349
+ const psi = parameters.psi !== undefined ? parameters.psi : -0.5;
350
+ const sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5;
351
+ let maxDiff;
352
+
353
+ // initialize simplex.
354
+ const N = x0.length;
355
+ const simplex = new Array(N + 1);
356
+ simplex[0] = x0;
357
+ simplex[0].fx = f(x0);
358
+ simplex[0].id = 0;
359
+ for (let i = 0; i < N; ++i) {
360
+ const point = x0.slice();
361
+ point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
362
+ simplex[i + 1] = point;
363
+ simplex[i + 1].fx = f(point);
364
+ simplex[i + 1].id = i + 1;
365
+ }
366
+
367
+ function updateSimplex(value) {
368
+ for (let i = 0; i < value.length; i++) {
369
+ simplex[N][i] = value[i];
370
+ }
371
+ simplex[N].fx = value.fx;
372
+ }
373
+
374
+ const sortOrder = (a, b) => a.fx - b.fx;
375
+
376
+ const centroid = x0.slice();
377
+ const reflected = x0.slice();
378
+ const contracted = x0.slice();
379
+ const expanded = x0.slice();
380
+
381
+ for (let iteration = 0; iteration < maxIterations; ++iteration) {
382
+ simplex.sort(sortOrder);
383
+
384
+ if (parameters.history) {
385
+ // copy the simplex (since later iterations will mutate) and
386
+ // sort it to have a consistent order between iterations
387
+ const sortedSimplex = simplex.map((x) => {
388
+ const state = x.slice();
389
+ state.fx = x.fx;
390
+ state.id = x.id;
391
+ return state;
392
+ });
393
+ sortedSimplex.sort((a, b) => a.id - b.id);
394
+
395
+ parameters.history.push({
396
+ x: simplex[0].slice(),
397
+ fx: simplex[0].fx,
398
+ simplex: sortedSimplex,
399
+ });
400
+ }
401
+
402
+ maxDiff = 0;
403
+ for (let i = 0; i < N; ++i) {
404
+ maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
405
+ }
406
+
407
+ if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
408
+ break;
409
+ }
410
+
411
+ // compute the centroid of all but the worst point in the simplex
412
+ for (let i = 0; i < N; ++i) {
413
+ centroid[i] = 0;
414
+ for (let j = 0; j < N; ++j) {
415
+ centroid[i] += simplex[j][i];
416
+ }
417
+ centroid[i] /= N;
418
+ }
419
+
420
+ // reflect the worst point past the centroid and compute loss at reflected
421
+ // point
422
+ const worst = simplex[N];
423
+ weightedSum(reflected, 1 + rho, centroid, -rho, worst);
424
+ reflected.fx = f(reflected);
425
+
426
+ // if the reflected point is the best seen, then possibly expand
427
+ if (reflected.fx < simplex[0].fx) {
428
+ weightedSum(expanded, 1 + chi, centroid, -chi, worst);
429
+ expanded.fx = f(expanded);
430
+ if (expanded.fx < reflected.fx) {
431
+ updateSimplex(expanded);
432
+ } else {
433
+ updateSimplex(reflected);
434
+ }
435
+ }
436
+
437
+ // if the reflected point is worse than the second worst, we need to
438
+ // contract
439
+ else if (reflected.fx >= simplex[N - 1].fx) {
440
+ let shouldReduce = false;
441
+
442
+ if (reflected.fx > worst.fx) {
443
+ // do an inside contraction
444
+ weightedSum(contracted, 1 + psi, centroid, -psi, worst);
445
+ contracted.fx = f(contracted);
446
+ if (contracted.fx < worst.fx) {
447
+ updateSimplex(contracted);
448
+ } else {
449
+ shouldReduce = true;
450
+ }
451
+ } else {
452
+ // do an outside contraction
453
+ weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
454
+ contracted.fx = f(contracted);
455
+ if (contracted.fx < reflected.fx) {
456
+ updateSimplex(contracted);
457
+ } else {
458
+ shouldReduce = true;
459
+ }
460
+ }
461
+
462
+ if (shouldReduce) {
463
+ // if we don't contract here, we're done
464
+ if (sigma >= 1) break;
465
+
466
+ // do a reduction
467
+ for (let i = 1; i < simplex.length; ++i) {
468
+ weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
469
+ simplex[i].fx = f(simplex[i]);
470
+ }
471
+ }
472
+ } else {
473
+ updateSimplex(reflected);
474
+ }
475
+ }
476
+
477
+ simplex.sort(sortOrder);
478
+ return { fx: simplex[0].fx, x: simplex[0] };
479
+ }
480
+
481
+ /// searches along line 'pk' for a point that satifies the wolfe conditions
482
+ /// See 'Numerical Optimization' by Nocedal and Wright p59-60
483
+ /// f : objective function
484
+ /// pk : search direction
485
+ /// current: object containing current gradient/loss
486
+ /// next: output: contains next gradient/loss
487
+ /// returns a: step size taken
488
+ function wolfeLineSearch(f, pk, current, next, a, c1, c2) {
489
+ const phi0 = current.fx;
490
+ const phiPrime0 = dot(current.fxprime, pk);
491
+ let phi = phi0;
492
+ let phi_old = phi0;
493
+ let phiPrime = phiPrime0;
494
+ let a0 = 0;
495
+
496
+ a = a || 1;
497
+ c1 = c1 || 1e-6;
498
+ c2 = c2 || 0.1;
499
+
500
+ function zoom(a_lo, a_high, phi_lo) {
501
+ for (let iteration = 0; iteration < 16; ++iteration) {
502
+ a = (a_lo + a_high) / 2;
503
+ weightedSum(next.x, 1.0, current.x, a, pk);
504
+ phi = next.fx = f(next.x, next.fxprime);
505
+ phiPrime = dot(next.fxprime, pk);
506
+
507
+ if (phi > phi0 + c1 * a * phiPrime0 || phi >= phi_lo) {
508
+ a_high = a;
509
+ } else {
510
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
511
+ return a;
512
+ }
513
+
514
+ if (phiPrime * (a_high - a_lo) >= 0) {
515
+ a_high = a_lo;
516
+ }
517
+
518
+ a_lo = a;
519
+ phi_lo = phi;
520
+ }
521
+ }
522
+
523
+ return 0;
524
+ }
525
+
526
+ for (let iteration = 0; iteration < 10; ++iteration) {
527
+ weightedSum(next.x, 1.0, current.x, a, pk);
528
+ phi = next.fx = f(next.x, next.fxprime);
529
+ phiPrime = dot(next.fxprime, pk);
530
+ if (phi > phi0 + c1 * a * phiPrime0 || (iteration && phi >= phi_old)) {
531
+ return zoom(a0, a, phi_old);
532
+ }
533
+
534
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
535
+ return a;
536
+ }
537
+
538
+ if (phiPrime >= 0) {
539
+ return zoom(a, a0, phi);
540
+ }
541
+
542
+ phi_old = phi;
543
+ a0 = a;
544
+ a *= 2;
545
+ }
546
+
547
+ return a;
548
+ }
549
+
550
+ function conjugateGradient(f, initial, params) {
551
+ // allocate all memory up front here, keep out of the loop for perfomance
552
+ // reasons
553
+ let current = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
554
+ let next = { x: initial.slice(), fx: 0, fxprime: initial.slice() };
555
+ const yk = initial.slice();
556
+ let pk;
557
+ let temp;
558
+ let a = 1;
559
+ let maxIterations;
560
+
561
+ params = params || {};
562
+ maxIterations = params.maxIterations || initial.length * 20;
563
+
564
+ current.fx = f(current.x, current.fxprime);
565
+ pk = current.fxprime.slice();
566
+ scale(pk, current.fxprime, -1);
567
+
568
+ for (let i = 0; i < maxIterations; ++i) {
569
+ a = wolfeLineSearch(f, pk, current, next, a);
570
+
571
+ // todo: history in wrong spot?
572
+ if (params.history) {
573
+ params.history.push({
574
+ x: current.x.slice(),
575
+ fx: current.fx,
576
+ fxprime: current.fxprime.slice(),
577
+ alpha: a,
578
+ });
579
+ }
580
+
581
+ if (!a) {
582
+ // faiiled to find point that satifies wolfe conditions.
583
+ // reset direction for next iteration
584
+ scale(pk, current.fxprime, -1);
585
+ } else {
586
+ // update direction using Polak–Ribiere CG method
587
+ weightedSum(yk, 1, next.fxprime, -1, current.fxprime);
588
+
589
+ const delta_k = dot(current.fxprime, current.fxprime);
590
+ const beta_k = Math.max(0, dot(yk, next.fxprime) / delta_k);
591
+
592
+ weightedSum(pk, beta_k, pk, -1, next.fxprime);
593
+
594
+ temp = current;
595
+ current = next;
596
+ next = temp;
597
+ }
598
+
599
+ if (norm2(current.fxprime) <= 1e-5) {
600
+ break;
601
+ }
602
+ }
603
+
604
+ if (params.history) {
605
+ params.history.push({
606
+ x: current.x.slice(),
607
+ fx: current.fx,
608
+ fxprime: current.fxprime.slice(),
609
+ alpha: a,
610
+ });
611
+ }
612
+
613
+ return current;
614
+ }
615
+
616
+ /**
617
+ * given a list of set objects, and their corresponding overlaps
618
+ * updates the (x, y, radius) attribute on each set such that their positions
619
+ * roughly correspond to the desired overlaps
620
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
621
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
622
+ */
623
+ function venn(sets, parameters = {}) {
624
+ parameters.maxIterations = parameters.maxIterations || 500;
625
+
626
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
627
+ const loss = parameters.lossFunction || lossFunction;
628
+
629
+ // add in missing pairwise areas as having 0 size
630
+ const areas = addMissingAreas(sets, parameters);
631
+
632
+ // initial layout is done greedily
633
+ const circles = initialLayout(areas, parameters);
634
+
635
+ // transform x/y coordinates to a vector to optimize
636
+ const setids = Object.keys(circles);
637
+ /** @type {number[]} */
638
+ const initial = [];
639
+ for (const setid of setids) {
640
+ initial.push(circles[setid].x);
641
+ initial.push(circles[setid].y);
642
+ }
643
+
644
+ // optimize initial layout from our loss function
645
+ const solution = nelderMead(
646
+ (values) => {
647
+ const current = {};
648
+ for (let i = 0; i < setids.length; ++i) {
649
+ const setid = setids[i];
650
+ current[setid] = {
651
+ x: values[2 * i],
652
+ y: values[2 * i + 1],
653
+ radius: circles[setid].radius,
654
+ // size : circles[setid].size
655
+ };
656
+ }
657
+ return loss(current, areas);
658
+ },
659
+ initial,
660
+ parameters
661
+ );
662
+
663
+ // transform solution vector back to x/y points
664
+ const positions = solution.x;
665
+ for (let i = 0; i < setids.length; ++i) {
666
+ const setid = setids[i];
667
+ circles[setid].x = positions[2 * i];
668
+ circles[setid].y = positions[2 * i + 1];
669
+ }
670
+
671
+ return circles;
672
+ }
673
+
674
+ const SMALL = 1e-10;
675
+
676
+ /**
677
+ * Returns the distance necessary for two circles of radius r1 + r2 to
678
+ * have the overlap area 'overlap'
679
+ * @param {number} r1
680
+ * @param {number} r2
681
+ * @param {number} overlap
682
+ * @returns {number}
683
+ */
684
+ function distanceFromIntersectArea(r1, r2, overlap) {
685
+ // handle complete overlapped circles
686
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
687
+ return Math.abs(r1 - r2);
688
+ }
689
+
690
+ return bisect((distance) => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
691
+ }
692
+
693
+ /**
694
+ * Missing pair-wise intersection area data can cause problems:
695
+ * treating as an unknown means that sets will be laid out overlapping,
696
+ * which isn't what people expect. To reflect that we want disjoint sets
697
+ * here, set the overlap to 0 for all missing pairwise set intersections
698
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
699
+ * @returns {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>}
700
+ */
701
+ function addMissingAreas(areas, parameters = {}) {
702
+ const distinct = parameters.distinct;
703
+ const r = areas.map((s) => Object.assign({}, s));
704
+
705
+ function toKey(arr) {
706
+ return arr.join(';');
707
+ }
708
+
709
+ if (distinct) {
710
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
711
+ /** @types Map<string, number> */
712
+ const count = new Map();
713
+ for (const area of r) {
714
+ for (let i = 0; i < area.sets.length; i++) {
715
+ const si = String(area.sets[i]);
716
+ count.set(si, area.size + (count.get(si) || 0));
717
+ for (let j = i + 1; j < area.sets.length; j++) {
718
+ const sj = String(area.sets[j]);
719
+ const k1 = `${si};${sj}`;
720
+ const k2 = `${sj};${si}`;
721
+ count.set(k1, area.size + (count.get(k1) || 0));
722
+ count.set(k2, area.size + (count.get(k2) || 0));
723
+ }
724
+ }
725
+ }
726
+ for (const area of r) {
727
+ if (area.sets.length < 3) {
728
+ area.size = count.get(toKey(area.sets));
729
+ }
730
+ }
731
+ }
732
+
733
+ // two circle intersections that aren't defined
734
+ const ids = [];
735
+
736
+ /** @type {Set<string>} */
737
+ const pairs = new Set();
738
+ for (const area of r) {
739
+ if (area.sets.length === 1) {
740
+ ids.push(area.sets[0]);
741
+ } else if (area.sets.length === 2) {
742
+ const a = area.sets[0];
743
+ const b = area.sets[1];
744
+ pairs.add(toKey(area.sets));
745
+ pairs.add(toKey([b, a]));
746
+ }
747
+ }
748
+
749
+ ids.sort((a, b) => (a === b ? 0 : a < b ? -1 : +1));
750
+
751
+ for (let i = 0; i < ids.length; ++i) {
752
+ const a = ids[i];
753
+ for (let j = i + 1; j < ids.length; ++j) {
754
+ const b = ids[j];
755
+ if (!pairs.has(toKey([a, b]))) {
756
+ r.push({ sets: [a, b], size: 0 });
757
+ }
758
+ }
759
+ }
760
+ return r;
761
+ }
762
+
763
+ /**
764
+ * Returns two matrices, one of the euclidean distances between the sets
765
+ * and the other indicating if there are subset or disjoint set relationships
766
+ * @param {ReadonlyArray<{sets: ReadonlyArray<number>}>} areas
767
+ * @param {ReadonlyArray<{size: number}>} sets
768
+ * @param {ReadonlyArray<number>} setids
769
+ */
770
+ function getDistanceMatrices(areas, sets, setids) {
771
+ // initialize an empty distance matrix between all the points
772
+ /**
773
+ * @type {number[][]}
774
+ */
775
+ const distances = zerosM(sets.length, sets.length);
776
+ /**
777
+ * @type {number[][]}
778
+ */
779
+ const constraints = zerosM(sets.length, sets.length);
780
+
781
+ // compute required distances between all the sets such that
782
+ // the areas match
783
+ areas
784
+ .filter((x) => x.sets.length === 2)
785
+ .forEach((current) => {
786
+ const left = setids[current.sets[0]];
787
+ const right = setids[current.sets[1]];
788
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
789
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
790
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
791
+
792
+ distances[left][right] = distances[right][left] = distance;
793
+
794
+ // also update constraints to indicate if its a subset or disjoint
795
+ // relationship
796
+ let c = 0;
797
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
798
+ c = 1;
799
+ } else if (current.size <= 1e-10) {
800
+ c = -1;
801
+ }
802
+ constraints[left][right] = constraints[right][left] = c;
803
+ });
804
+
805
+ return { distances, constraints };
806
+ }
807
+
808
+ /// computes the gradient and loss simultaneously for our constrained MDS optimizer
809
+ function constrainedMDSGradient(x, fxprime, distances, constraints) {
810
+ for (let i = 0; i < fxprime.length; ++i) {
811
+ fxprime[i] = 0;
812
+ }
813
+
814
+ let loss = 0;
815
+ for (let i = 0; i < distances.length; ++i) {
816
+ const xi = x[2 * i];
817
+ const yi = x[2 * i + 1];
818
+ for (let j = i + 1; j < distances.length; ++j) {
819
+ const xj = x[2 * j];
820
+ const yj = x[2 * j + 1];
821
+ const dij = distances[i][j];
822
+ const constraint = constraints[i][j];
823
+
824
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
825
+ const distance = Math.sqrt(squaredDistance);
826
+ const delta = squaredDistance - dij * dij;
827
+
828
+ if ((constraint > 0 && distance <= dij) || (constraint < 0 && distance >= dij)) {
829
+ continue;
830
+ }
831
+
832
+ loss += 2 * delta * delta;
833
+
834
+ fxprime[2 * i] += 4 * delta * (xi - xj);
835
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
836
+
837
+ fxprime[2 * j] += 4 * delta * (xj - xi);
838
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
839
+ }
840
+ }
841
+ return loss;
842
+ }
843
+
844
+ /**
845
+ * takes the best working variant of either constrained MDS or greedy
846
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
847
+ */
848
+ function bestInitialLayout(areas, params = {}) {
849
+ let initial = greedyLayout(areas, params);
850
+ const loss = params.lossFunction || lossFunction;
851
+
852
+ // greedylayout is sufficient for all 2/3 circle cases. try out
853
+ // constrained MDS for higher order problems, take its output
854
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
855
+ // since it axis aligns)
856
+ if (areas.length >= 8) {
857
+ const constrained = constrainedMDSLayout(areas, params);
858
+ const constrainedLoss = loss(constrained, areas);
859
+ const greedyLoss = loss(initial, areas);
860
+
861
+ if (constrainedLoss + 1e-8 < greedyLoss) {
862
+ initial = constrained;
863
+ }
864
+ }
865
+ return initial;
866
+ }
867
+
868
+ /**
869
+ * use the constrained MDS variant to generate an initial layout
870
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
871
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
872
+ */
873
+ function constrainedMDSLayout(areas, params = {}) {
874
+ const restarts = params.restarts || 10;
875
+
876
+ // bidirectionally map sets to a rowid (so we can create a matrix)
877
+ const sets = [];
878
+ const setids = {};
879
+ for (const area of areas) {
880
+ if (area.sets.length === 1) {
881
+ setids[area.sets[0]] = sets.length;
882
+ sets.push(area);
883
+ }
884
+ }
885
+
886
+ let { distances, constraints } = getDistanceMatrices(areas, sets, setids);
887
+
888
+ // keep distances bounded, things get messed up otherwise.
889
+ // TODO: proper preconditioner?
890
+ const norm = norm2(distances.map(norm2)) / distances.length;
891
+ distances = distances.map((row) => row.map((value) => value / norm));
892
+
893
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
894
+
895
+ let best = null;
896
+ for (let i = 0; i < restarts; ++i) {
897
+ const initial = zeros(distances.length * 2).map(Math.random);
898
+
899
+ const current = conjugateGradient(obj, initial, params);
900
+ if (!best || current.fx < best.fx) {
901
+ best = current;
902
+ }
903
+ }
904
+
905
+ const positions = best.x;
906
+
907
+ // translate rows back to (x,y,radius) coordinates
908
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
909
+ const circles = {};
910
+ for (let i = 0; i < sets.length; ++i) {
911
+ const set = sets[i];
912
+ circles[set.sets[0]] = {
913
+ x: positions[2 * i] * norm,
914
+ y: positions[2 * i + 1] * norm,
915
+ radius: Math.sqrt(set.size / Math.PI),
916
+ };
917
+ }
918
+
919
+ if (params.history) {
920
+ for (const h of params.history) {
921
+ scale(h.x, norm);
922
+ }
923
+ }
924
+ return circles;
925
+ }
926
+
927
+ /**
928
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
929
+ * least overlapped, attempting to position each new set such that the
930
+ * overlapping areas to already positioned sets are basically right
931
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>}>} areas
932
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
933
+ */
934
+ function greedyLayout(areas, params) {
935
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
936
+
937
+ // define a circle for each set
938
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
939
+ const circles = {};
940
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
941
+ const setOverlaps = {};
942
+ for (const area of areas) {
943
+ if (area.sets.length === 1) {
944
+ const set = area.sets[0];
945
+ circles[set] = {
946
+ x: 1e10,
947
+ y: 1e10,
948
+ rowid: circles.length,
949
+ size: area.size,
950
+ radius: Math.sqrt(area.size / Math.PI),
951
+ };
952
+ setOverlaps[set] = [];
953
+ }
954
+ }
955
+
956
+ areas = areas.filter((a) => a.sets.length === 2);
957
+
958
+ // map each set to a list of all the other sets that overlap it
959
+ for (const current of areas) {
960
+ let weight = current.weight != null ? current.weight : 1.0;
961
+ const left = current.sets[0];
962
+ const right = current.sets[1];
963
+
964
+ // completely overlapped circles shouldn't be positioned early here
965
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
966
+ weight = 0;
967
+ }
968
+
969
+ setOverlaps[left].push({ set: right, size: current.size, weight });
970
+ setOverlaps[right].push({ set: left, size: current.size, weight });
971
+ }
972
+
973
+ // get list of most overlapped sets
974
+ const mostOverlapped = [];
975
+ Object.keys(setOverlaps).forEach((set) => {
976
+ let size = 0;
977
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
978
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
979
+ }
980
+
981
+ mostOverlapped.push({ set, size });
982
+ });
983
+
984
+ // sort by size desc
985
+ function sortOrder(a, b) {
986
+ return b.size - a.size;
987
+ }
988
+ mostOverlapped.sort(sortOrder);
989
+
990
+ // keep track of what sets have been laid out
991
+ const positioned = {};
992
+ function isPositioned(element) {
993
+ return element.set in positioned;
994
+ }
995
+
996
+ /**
997
+ * adds a point to the output
998
+ * @param {{x: number, y: number}} point
999
+ * @param {number} index
1000
+ */
1001
+ function positionSet(point, index) {
1002
+ circles[index].x = point.x;
1003
+ circles[index].y = point.y;
1004
+ positioned[index] = true;
1005
+ }
1006
+
1007
+ // add most overlapped set at (0,0)
1008
+ positionSet({ x: 0, y: 0 }, mostOverlapped[0].set);
1009
+
1010
+ // get distances between all points. TODO, necessary?
1011
+ // answer: probably not
1012
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
1013
+ for (let i = 1; i < mostOverlapped.length; ++i) {
1014
+ const setIndex = mostOverlapped[i].set;
1015
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
1016
+ const set = circles[setIndex];
1017
+ overlap.sort(sortOrder);
1018
+
1019
+ if (overlap.length === 0) {
1020
+ // this shouldn't happen anymore with addMissingAreas
1021
+ throw 'ERROR: missing pairwise overlap information';
1022
+ }
1023
+
1024
+ /** @type {{x: number, y: number}[]} */
1025
+ const points = [];
1026
+ for (var j = 0; j < overlap.length; ++j) {
1027
+ // get appropriate distance from most overlapped already added set
1028
+ const p1 = circles[overlap[j].set];
1029
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
1030
+
1031
+ // sample positions at 90 degrees for maximum aesthetics
1032
+ points.push({ x: p1.x + d1, y: p1.y });
1033
+ points.push({ x: p1.x - d1, y: p1.y });
1034
+ points.push({ y: p1.y + d1, x: p1.x });
1035
+ points.push({ y: p1.y - d1, x: p1.x });
1036
+
1037
+ // if we have at least 2 overlaps, then figure out where the
1038
+ // set should be positioned analytically and try those too
1039
+ for (let k = j + 1; k < overlap.length; ++k) {
1040
+ const p2 = circles[overlap[k].set];
1041
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
1042
+
1043
+ const extraPoints = circleCircleIntersection(
1044
+ { x: p1.x, y: p1.y, radius: d1 },
1045
+ { x: p2.x, y: p2.y, radius: d2 }
1046
+ );
1047
+ points.push(...extraPoints);
1048
+ }
1049
+ }
1050
+
1051
+ // we have some candidate positions for the set, examine loss
1052
+ // at each position to figure out where to put it at
1053
+ let bestLoss = 1e50;
1054
+ let bestPoint = points[0];
1055
+ for (const point of points) {
1056
+ circles[setIndex].x = point.x;
1057
+ circles[setIndex].y = point.y;
1058
+ const localLoss = loss(circles, areas);
1059
+ if (localLoss < bestLoss) {
1060
+ bestLoss = localLoss;
1061
+ bestPoint = point;
1062
+ }
1063
+ }
1064
+
1065
+ positionSet(bestPoint, setIndex);
1066
+ }
1067
+
1068
+ return circles;
1069
+ }
1070
+
1071
+ /**
1072
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
1073
+ * the distance from the actual overlaps to the desired overlaps. Note that
1074
+ * this method ignores overlaps of more than 2 circles
1075
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
1076
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>, weight?: number}>} overlaps
1077
+ * @returns {number}
1078
+ */
1079
+ function lossFunction(circles, overlaps) {
1080
+ let output = 0;
1081
+
1082
+ for (const area of overlaps) {
1083
+ if (area.sets.length === 1) {
1084
+ continue;
1085
+ }
1086
+ /** @type {number} */
1087
+ let overlap;
1088
+ if (area.sets.length === 2) {
1089
+ const left = circles[area.sets[0]];
1090
+ const right = circles[area.sets[1]];
1091
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
1092
+ } else {
1093
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
1094
+ }
1095
+
1096
+ const weight = area.weight != null ? area.weight : 1.0;
1097
+ output += weight * (overlap - area.size) * (overlap - area.size);
1098
+ }
1099
+
1100
+ return output;
1101
+ }
1102
+
1103
+ function logRatioLossFunction(circles, overlaps) {
1104
+ let output = 0;
1105
+
1106
+ for (const area of overlaps) {
1107
+ if (area.sets.length === 1) {
1108
+ continue;
1109
+ }
1110
+ /** @type {number} */
1111
+ let overlap;
1112
+ if (area.sets.length === 2) {
1113
+ const left = circles[area.sets[0]];
1114
+ const right = circles[area.sets[1]];
1115
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
1116
+ } else {
1117
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
1118
+ }
1119
+
1120
+ const weight = area.weight != null ? area.weight : 1.0;
1121
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
1122
+ output += weight * differenceFromIdeal * differenceFromIdeal;
1123
+ }
1124
+
1125
+ return output;
1126
+ }
1127
+
1128
+ /**
1129
+ * orientates a bunch of circles to point in orientation
1130
+ * @param {{x :number, y: number, radius: number}[]} circles
1131
+ * @param {number | undefined} orientation
1132
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
1133
+ */
1134
+ function orientateCircles(circles, orientation, orientationOrder) {
1135
+ if (orientationOrder == null) {
1136
+ circles.sort((a, b) => b.radius - a.radius);
1137
+ } else {
1138
+ circles.sort(orientationOrder);
1139
+ }
1140
+
1141
+ // shift circles so largest circle is at (0, 0)
1142
+ if (circles.length > 0) {
1143
+ const largestX = circles[0].x;
1144
+ const largestY = circles[0].y;
1145
+
1146
+ for (const circle of circles) {
1147
+ circle.x -= largestX;
1148
+ circle.y -= largestY;
1149
+ }
1150
+ }
1151
+
1152
+ if (circles.length === 2) {
1153
+ // if the second circle is a subset of the first, arrange so that
1154
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
1155
+ const dist = distance(circles[0], circles[1]);
1156
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
1157
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
1158
+ circles[1].y = circles[0].y;
1159
+ }
1160
+ }
1161
+
1162
+ // rotate circles so that second largest is at an angle of 'orientation'
1163
+ // from largest
1164
+ if (circles.length > 1) {
1165
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
1166
+ const c = Math.cos(rotation);
1167
+ const s = Math.sin(rotation);
1168
+
1169
+ for (const circle of circles) {
1170
+ const x = circle.x;
1171
+ const y = circle.y;
1172
+ circle.x = c * x - s * y;
1173
+ circle.y = s * x + c * y;
1174
+ }
1175
+ }
1176
+
1177
+ // mirror solution if third solution is above plane specified by
1178
+ // first two circles
1179
+ if (circles.length > 2) {
1180
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
1181
+ while (angle < 0) {
1182
+ angle += 2 * Math.PI;
1183
+ }
1184
+ while (angle > 2 * Math.PI) {
1185
+ angle -= 2 * Math.PI;
1186
+ }
1187
+ if (angle > Math.PI) {
1188
+ const slope = circles[1].y / (1e-10 + circles[1].x);
1189
+ for (const circle of circles) {
1190
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
1191
+ circle.x = 2 * d - circle.x;
1192
+ circle.y = 2 * d * slope - circle.y;
1193
+ }
1194
+ }
1195
+ }
1196
+ }
1197
+
1198
+ /**
1199
+ *
1200
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
1201
+ * @returns {{x: number, y: number, radius: number}[][]}
1202
+ */
1203
+ function disjointCluster(circles) {
1204
+ // union-find clustering to get disjoint sets
1205
+ circles.forEach((circle) => {
1206
+ circle.parent = circle;
1207
+ });
1208
+
1209
+ // path compression step in union find
1210
+ function find(circle) {
1211
+ if (circle.parent !== circle) {
1212
+ circle.parent = find(circle.parent);
1213
+ }
1214
+ return circle.parent;
1215
+ }
1216
+
1217
+ function union(x, y) {
1218
+ const xRoot = find(x);
1219
+ const yRoot = find(y);
1220
+ xRoot.parent = yRoot;
1221
+ }
1222
+
1223
+ // get the union of all overlapping sets
1224
+ for (let i = 0; i < circles.length; ++i) {
1225
+ for (let j = i + 1; j < circles.length; ++j) {
1226
+ const maxDistance = circles[i].radius + circles[j].radius;
1227
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
1228
+ union(circles[j], circles[i]);
1229
+ }
1230
+ }
1231
+ }
1232
+
1233
+ // find all the disjoint clusters and group them together
1234
+ /** @type {Map<string, {x: number, y: number, radius: number}[]>} */
1235
+ const disjointClusters = new Map();
1236
+ for (let i = 0; i < circles.length; ++i) {
1237
+ const setid = find(circles[i]).parent.setid;
1238
+ if (!disjointClusters.has(setid)) {
1239
+ disjointClusters.set(setid, []);
1240
+ }
1241
+ disjointClusters.get(setid).push(circles[i]);
1242
+ }
1243
+
1244
+ // cleanup bookkeeping
1245
+ circles.forEach((circle) => {
1246
+ delete circle.parent;
1247
+ });
1248
+
1249
+ // return in more usable form
1250
+ return Array.from(disjointClusters.values());
1251
+ }
1252
+
1253
+ /**
1254
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
1255
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
1256
+ */
1257
+ function getBoundingBox(circles) {
1258
+ const minMax = (d) => {
1259
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
1260
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
1261
+ return { max: hi, min: lo };
1262
+ };
1263
+ return { xRange: minMax('x'), yRange: minMax('y') };
1264
+ }
1265
+
1266
+ /**
1267
+ *
1268
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1269
+ * @param {undefined | number} orientation
1270
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
1271
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
1272
+ */
1273
+ function normalizeSolution(solution, orientation, orientationOrder) {
1274
+ if (orientation == null) {
1275
+ orientation = Math.PI / 2;
1276
+ }
1277
+
1278
+ // work with a list instead of a dictionary, and take a copy so we
1279
+ // don't mutate input
1280
+ let circles = fromObjectNotation(solution).map((d) => Object.assign({}, d));
1281
+
1282
+ // get all the disjoint clusters
1283
+ const clusters = disjointCluster(circles);
1284
+
1285
+ // orientate all disjoint sets, get sizes
1286
+ for (const cluster of clusters) {
1287
+ orientateCircles(cluster, orientation, orientationOrder);
1288
+ const bounds = getBoundingBox(cluster);
1289
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
1290
+ cluster.bounds = bounds;
1291
+ }
1292
+ clusters.sort((a, b) => b.size - a.size);
1293
+
1294
+ // orientate the largest at 0,0, and get the bounds
1295
+ circles = clusters[0];
1296
+ let returnBounds = circles.bounds;
1297
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
1298
+
1299
+ /**
1300
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
1301
+ * @param {boolean} right
1302
+ * @param {boolean} bottom
1303
+ */
1304
+ function addCluster(cluster, right, bottom) {
1305
+ if (!cluster) {
1306
+ return;
1307
+ }
1308
+
1309
+ const bounds = cluster.bounds;
1310
+ /** @type {number} */
1311
+ let xOffset;
1312
+ /** @type {number} */
1313
+ let yOffset;
1314
+
1315
+ if (right) {
1316
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
1317
+ } else {
1318
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
1319
+ const centreing =
1320
+ (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
1321
+ if (centreing < 0) {
1322
+ xOffset += centreing;
1323
+ }
1324
+ }
1325
+
1326
+ if (bottom) {
1327
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
1328
+ } else {
1329
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
1330
+ const centreing =
1331
+ (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
1332
+ if (centreing < 0) {
1333
+ yOffset += centreing;
1334
+ }
1335
+ }
1336
+
1337
+ for (const c of cluster) {
1338
+ c.x += xOffset;
1339
+ c.y += yOffset;
1340
+ circles.push(c);
1341
+ }
1342
+ }
1343
+
1344
+ let index = 1;
1345
+ while (index < clusters.length) {
1346
+ addCluster(clusters[index], true, false);
1347
+ addCluster(clusters[index + 1], false, true);
1348
+ addCluster(clusters[index + 2], true, true);
1349
+ index += 3;
1350
+
1351
+ // have one cluster (in top left). lay out next three relative
1352
+ // to it in a grid
1353
+ returnBounds = getBoundingBox(circles);
1354
+ }
1355
+
1356
+ // convert back to solution form
1357
+ return toObjectNotation(circles);
1358
+ }
1359
+
1360
+ /**
1361
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
1362
+ * a rectangle of width/height - with padding around the borders. also
1363
+ * centers the diagram in the available space at the same time.
1364
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
1365
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1366
+ * @param {number} width
1367
+ * @param {number} height
1368
+ * @param {number} padding
1369
+ * @param {boolean} scaleToFit
1370
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
1371
+ */
1372
+ function scaleSolution(solution, width, height, padding, scaleToFit) {
1373
+ const circles = fromObjectNotation(solution);
1374
+
1375
+ width -= 2 * padding;
1376
+ height -= 2 * padding;
1377
+
1378
+ const { xRange, yRange } = getBoundingBox(circles);
1379
+
1380
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
1381
+ console.log('not scaling solution: zero size detected');
1382
+ return solution;
1383
+ }
1384
+
1385
+ /** @type {number} */
1386
+ let xScaling;
1387
+ /** @type {number} */
1388
+ let yScaling;
1389
+ if (scaleToFit) {
1390
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
1391
+ xScaling = width / toScaleDiameter;
1392
+ yScaling = height / toScaleDiameter;
1393
+ } else {
1394
+ xScaling = width / (xRange.max - xRange.min);
1395
+ yScaling = height / (yRange.max - yRange.min);
1396
+ }
1397
+
1398
+ const scaling = Math.min(yScaling, xScaling);
1399
+ // while we're at it, center the diagram too
1400
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
1401
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
1402
+
1403
+ return toObjectNotation(
1404
+ circles.map((circle) => ({
1405
+ radius: scaling * circle.radius,
1406
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
1407
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
1408
+ setid: circle.setid,
1409
+ }))
1410
+ );
1411
+ }
1412
+
1413
+ /**
1414
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
1415
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
1416
+ */
1417
+ function toObjectNotation(circles) {
1418
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
1419
+ const r = {};
1420
+ for (const circle of circles) {
1421
+ r[circle.setid] = circle;
1422
+ }
1423
+ return r;
1424
+ }
1425
+ /**
1426
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1427
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
1428
+ */
1429
+ function fromObjectNotation(solution) {
1430
+ const setids = Object.keys(solution);
1431
+ return setids.map((id) => Object.assign(solution[id], { setid: id }));
1432
+ }
1433
+
1434
+ /**
1435
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
1436
+ *
1437
+ * `colourScheme: Array<String>`
1438
+ * A list of color values to be applied when coloring diagram circles.
1439
+ *
1440
+ * `symmetricalTextCentre: Boolean`
1441
+ * Whether to symmetrically center each circle's text horizontally and vertically.
1442
+ * Defaults to `false`.
1443
+ *
1444
+ * `textFill: String`
1445
+ * The color to be applied to the text within each circle.
1446
+ *
1447
+ * @param {object} options
1448
+ */
1449
+ function VennDiagram(options = {}) {
1450
+ let useViewBox = false,
1451
+ width = 600,
1452
+ height = 350,
1453
+ padding = 15,
1454
+ duration = 1000,
1455
+ orientation = Math.PI / 2,
1456
+ normalize = true,
1457
+ scaleToFit = null,
1458
+ wrap = true,
1459
+ styled = true,
1460
+ fontSize = null,
1461
+ orientationOrder = null,
1462
+ distinct = false,
1463
+ round = null,
1464
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
1465
+ // mimic the behaviour of d3.scale.category10 from the previous
1466
+ // version of d3
1467
+ colourMap = {},
1468
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
1469
+ // since we can support older versions of d3 as long as we don't force this,
1470
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
1471
+ colourScheme =
1472
+ options && options.colourScheme
1473
+ ? options.colourScheme
1474
+ : options && options.colorScheme
1475
+ ? options.colorScheme
1476
+ : [
1477
+ '#1f77b4',
1478
+ '#ff7f0e',
1479
+ '#2ca02c',
1480
+ '#d62728',
1481
+ '#9467bd',
1482
+ '#8c564b',
1483
+ '#e377c2',
1484
+ '#7f7f7f',
1485
+ '#bcbd22',
1486
+ '#17becf',
1487
+ ],
1488
+ colourIndex = 0,
1489
+ colours = function (key) {
1490
+ if (key in colourMap) {
1491
+ return colourMap[key];
1492
+ }
1493
+ var ret = (colourMap[key] = colourScheme[colourIndex]);
1494
+ colourIndex += 1;
1495
+ if (colourIndex >= colourScheme.length) {
1496
+ colourIndex = 0;
1497
+ }
1498
+ return ret;
1499
+ },
1500
+ layoutFunction = venn,
1501
+ loss = lossFunction;
1502
+
1503
+ function chart(selection) {
1504
+ let data = selection.datum();
1505
+
1506
+ // handle 0-sized sets by removing from input
1507
+ const toRemove = new Set();
1508
+ data.forEach((datum) => {
1509
+ if (datum.size == 0 && datum.sets.length == 1) {
1510
+ toRemove.add(datum.sets[0]);
1511
+ }
1512
+ });
1513
+ data = data.filter((datum) => !datum.sets.some((set) => toRemove.has(set)));
1514
+
1515
+ let circles = {};
1516
+ let textCentres = {};
1517
+
1518
+ if (data.length > 0) {
1519
+ let solution = layoutFunction(data, { lossFunction: loss, distinct });
1520
+
1521
+ if (normalize) {
1522
+ solution = normalizeSolution(solution, orientation, orientationOrder);
1523
+ }
1524
+
1525
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
1526
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
1527
+ }
1528
+
1529
+ // Figure out the current label for each set. These can change
1530
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
1531
+ const labels = {};
1532
+ data.forEach((datum) => {
1533
+ if (datum.label) {
1534
+ labels[datum.sets] = datum.label;
1535
+ }
1536
+ });
1537
+
1538
+ function label(d) {
1539
+ if (d.sets in labels) {
1540
+ return labels[d.sets];
1541
+ }
1542
+ if (d.sets.length == 1) {
1543
+ return '' + d.sets[0];
1544
+ }
1545
+ }
1546
+
1547
+ // create svg if not already existing
1548
+ selection.selectAll('svg').data([circles]).enter().append('svg');
1549
+
1550
+ const svg = selection.select('svg');
1551
+
1552
+ if (useViewBox) {
1553
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
1554
+ } else {
1555
+ svg.attr('width', width).attr('height', height);
1556
+ }
1557
+
1558
+ // to properly transition intersection areas, we need the
1559
+ // previous circles locations. load from elements
1560
+ const previous = {};
1561
+ let hasPrevious = false;
1562
+ svg.selectAll('.venn-area path').each(function (d) {
1563
+ const path = this.getAttribute('d');
1564
+ if (d.sets.length == 1 && path && !distinct) {
1565
+ hasPrevious = true;
1566
+ previous[d.sets[0]] = circleFromPath(path);
1567
+ }
1568
+ });
1569
+ // interpolate intersection area paths between previous and
1570
+ // current paths
1571
+ function pathTween(d) {
1572
+ return (t) => {
1573
+ const c = d.sets.map((set) => {
1574
+ let start = previous[set];
1575
+ let end = circles[set];
1576
+ if (!start) {
1577
+ start = { x: width / 2, y: height / 2, radius: 1 };
1578
+ }
1579
+ if (!end) {
1580
+ end = { x: width / 2, y: height / 2, radius: 1 };
1581
+ }
1582
+ return {
1583
+ x: start.x * (1 - t) + end.x * t,
1584
+ y: start.y * (1 - t) + end.y * t,
1585
+ radius: start.radius * (1 - t) + end.radius * t,
1586
+ };
1587
+ });
1588
+ return intersectionAreaPath(c, round);
1589
+ };
1590
+ }
1591
+
1592
+ // update data, joining on the set ids
1593
+ const nodes = svg.selectAll('.venn-area').data(data, (d) => d.sets);
1594
+
1595
+ // create new nodes
1596
+ const enter = nodes
1597
+ .enter()
1598
+ .append('g')
1599
+ .attr(
1600
+ 'class',
1601
+ (d) =>
1602
+ `venn-area venn-${d.sets.length == 1 ? 'circle' : 'intersection'}${
1603
+ d.colour || d.color ? ' venn-coloured' : ''
1604
+ }`
1605
+ )
1606
+ .attr('data-venn-sets', (d) => d.sets.join('_'));
1607
+
1608
+ const enterPath = enter.append('path');
1609
+ const enterText = enter
1610
+ .append('text')
1611
+ .attr('class', 'label')
1612
+ .text((d) => label(d))
1613
+ .attr('text-anchor', 'middle')
1614
+ .attr('dy', '.35em')
1615
+ .attr('x', width / 2)
1616
+ .attr('y', height / 2);
1617
+
1618
+ // apply minimal style if wanted
1619
+ if (styled) {
1620
+ enterPath
1621
+ .style('fill-opacity', '0')
1622
+ .filter((d) => d.sets.length == 1)
1623
+ .style('fill', (d) => (d.colour ? d.colour : d.color ? d.color : colours(d.sets)))
1624
+ .style('fill-opacity', '.25');
1625
+
1626
+ enterText.style('fill', (d) => {
1627
+ if (d.colour || d.color) {
1628
+ return '#FFF';
1629
+ }
1630
+ if (options.textFill) {
1631
+ return options.textFill;
1632
+ }
1633
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
1634
+ });
1635
+ }
1636
+
1637
+ function asTransition(s) {
1638
+ if (typeof s.transition === 'function') {
1639
+ return s.transition('venn').duration(duration);
1640
+ }
1641
+ return s;
1642
+ }
1643
+
1644
+ // update existing, using pathTween if necessary
1645
+ let update = selection;
1646
+ if (hasPrevious && typeof update.transition === 'function') {
1647
+ update = asTransition(selection);
1648
+ update.selectAll('path').attrTween('d', pathTween);
1649
+ } else {
1650
+ update.selectAll('path').attr('d', (d) => intersectionAreaPath(d.sets.map((set) => circles[set])), round);
1651
+ }
1652
+
1653
+ const updateText = update
1654
+ .selectAll('text')
1655
+ .filter((d) => d.sets in textCentres)
1656
+ .text((d) => label(d))
1657
+ .attr('x', (d) => Math.floor(textCentres[d.sets].x))
1658
+ .attr('y', (d) => Math.floor(textCentres[d.sets].y));
1659
+
1660
+ if (wrap) {
1661
+ if (hasPrevious) {
1662
+ // d3 4.0 uses 'on' for events on transitions,
1663
+ // but d3 3.0 used 'each' instead. switch appropriately
1664
+ if ('on' in updateText) {
1665
+ updateText.on('end', wrapText(circles, label));
1666
+ } else {
1667
+ updateText.each('end', wrapText(circles, label));
1668
+ }
1669
+ } else {
1670
+ updateText.each(wrapText(circles, label));
1671
+ }
1672
+ }
1673
+
1674
+ // remove old
1675
+ const exit = asTransition(nodes.exit()).remove();
1676
+ if (typeof nodes.transition === 'function') {
1677
+ exit.selectAll('path').attrTween('d', pathTween);
1678
+ }
1679
+
1680
+ const exitText = exit
1681
+ .selectAll('text')
1682
+ .attr('x', width / 2)
1683
+ .attr('y', height / 2);
1684
+
1685
+ // if we've been passed a fontSize explicitly, use it to
1686
+ // transition
1687
+ if (fontSize !== null) {
1688
+ enterText.style('font-size', '0px');
1689
+ updateText.style('font-size', fontSize);
1690
+ exitText.style('font-size', '0px');
1691
+ }
1692
+
1693
+ return { circles, textCentres, nodes, enter, update, exit };
1694
+ }
1695
+
1696
+ chart.wrap = function (_) {
1697
+ if (!arguments.length) return wrap;
1698
+ wrap = _;
1699
+ return chart;
1700
+ };
1701
+
1702
+ chart.useViewBox = function () {
1703
+ useViewBox = true;
1704
+ return chart;
1705
+ };
1706
+
1707
+ chart.width = function (_) {
1708
+ if (!arguments.length) return width;
1709
+ width = _;
1710
+ return chart;
1711
+ };
1712
+
1713
+ chart.height = function (_) {
1714
+ if (!arguments.length) return height;
1715
+ height = _;
1716
+ return chart;
1717
+ };
1718
+
1719
+ chart.padding = function (_) {
1720
+ if (!arguments.length) return padding;
1721
+ padding = _;
1722
+ return chart;
1723
+ };
1724
+
1725
+ chart.distinct = function (_) {
1726
+ if (!arguments.length) return distinct;
1727
+ distinct = _;
1728
+ return chart;
1729
+ };
1730
+
1731
+ chart.colours = function (_) {
1732
+ if (!arguments.length) return colours;
1733
+ colours = _;
1734
+ return chart;
1735
+ };
1736
+
1737
+ chart.colors = function (_) {
1738
+ if (!arguments.length) return colours;
1739
+ colours = _;
1740
+ return chart;
1741
+ };
1742
+
1743
+ chart.fontSize = function (_) {
1744
+ if (!arguments.length) return fontSize;
1745
+ fontSize = _;
1746
+ return chart;
1747
+ };
1748
+
1749
+ chart.round = function (_) {
1750
+ if (!arguments.length) return round;
1751
+ round = _;
1752
+ return chart;
1753
+ };
1754
+
1755
+ chart.duration = function (_) {
1756
+ if (!arguments.length) return duration;
1757
+ duration = _;
1758
+ return chart;
1759
+ };
1760
+
1761
+ chart.layoutFunction = function (_) {
1762
+ if (!arguments.length) return layoutFunction;
1763
+ layoutFunction = _;
1764
+ return chart;
1765
+ };
1766
+
1767
+ chart.normalize = function (_) {
1768
+ if (!arguments.length) return normalize;
1769
+ normalize = _;
1770
+ return chart;
1771
+ };
1772
+
1773
+ chart.scaleToFit = function (_) {
1774
+ if (!arguments.length) return scaleToFit;
1775
+ scaleToFit = _;
1776
+ return chart;
1777
+ };
1778
+
1779
+ chart.styled = function (_) {
1780
+ if (!arguments.length) return styled;
1781
+ styled = _;
1782
+ return chart;
1783
+ };
1784
+
1785
+ chart.orientation = function (_) {
1786
+ if (!arguments.length) return orientation;
1787
+ orientation = _;
1788
+ return chart;
1789
+ };
1790
+
1791
+ chart.orientationOrder = function (_) {
1792
+ if (!arguments.length) return orientationOrder;
1793
+ orientationOrder = _;
1794
+ return chart;
1795
+ };
1796
+
1797
+ chart.lossFunction = function (_) {
1798
+ if (!arguments.length) return loss;
1799
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
1800
+ return chart;
1801
+ };
1802
+
1803
+ return chart;
1804
+ }
1805
+
1806
+ // sometimes text doesn't fit inside the circle, if thats the case lets wrap
1807
+ // the text here such that it fits
1808
+ // todo: looks like this might be merged into d3 (
1809
+ // https://github.com/mbostock/d3/issues/1642),
1810
+ // also worth checking out is
1811
+ // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
1812
+ // this seems to be one of those things that should be easy but isn't
1813
+ function wrapText(circles, labeller) {
1814
+ return function (data) {
1815
+ const text = this;
1816
+ const width = circles[data.sets[0]].radius || 50;
1817
+ const label = labeller(data) || '';
1818
+
1819
+ const words = label.split(/\s+/).reverse();
1820
+ const maxLines = 3;
1821
+ const minChars = (label.length + words.length) / maxLines;
1822
+
1823
+ let word = words.pop();
1824
+ let line = [word];
1825
+ let lineNumber = 0;
1826
+ const lineHeight = 1.1; // ems
1827
+ text.textContent = null; // clear
1828
+ const tspans = [];
1829
+
1830
+ function append(word) {
1831
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
1832
+ tspan.textContent = word;
1833
+ tspans.push(tspan);
1834
+ text.append(tspan);
1835
+ return tspan;
1836
+ }
1837
+ let tspan = append(word);
1838
+
1839
+ while (true) {
1840
+ word = words.pop();
1841
+ if (!word) {
1842
+ break;
1843
+ }
1844
+ line.push(word);
1845
+ const joined = line.join(' ');
1846
+ tspan.textContent = joined;
1847
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
1848
+ line.pop();
1849
+ tspan.textContent = line.join(' ');
1850
+ line = [word];
1851
+ tspan = append(word);
1852
+ lineNumber++;
1853
+ }
1854
+ }
1855
+
1856
+ const initial = 0.35 - (lineNumber * lineHeight) / 2;
1857
+ const x = text.getAttribute('x');
1858
+ const y = text.getAttribute('y');
1859
+ tspans.forEach((t, i) => {
1860
+ t.setAttribute('x', x);
1861
+ t.setAttribute('y', y);
1862
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
1863
+ });
1864
+ };
1865
+ }
1866
+
1867
+ /**
1868
+ *
1869
+ * @param {{x: number, y: number}} current
1870
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
1871
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
1872
+ * @returns {number}
1873
+ */
1874
+ function circleMargin(current, interior, exterior) {
1875
+ let margin = interior[0].radius - distance(interior[0], current);
1876
+
1877
+ for (let i = 1; i < interior.length; ++i) {
1878
+ const m = interior[i].radius - distance(interior[i], current);
1879
+ if (m <= margin) {
1880
+ margin = m;
1881
+ }
1882
+ }
1883
+
1884
+ for (let i = 0; i < exterior.length; ++i) {
1885
+ const m = distance(exterior[i], current) - exterior[i].radius;
1886
+ if (m <= margin) {
1887
+ margin = m;
1888
+ }
1889
+ }
1890
+ return margin;
1891
+ }
1892
+
1893
+ /**
1894
+ * compute the center of some circles by maximizing the margin of
1895
+ * the center point relative to the circles (interior) after subtracting
1896
+ * nearby circles (exterior)
1897
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
1898
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
1899
+ * @param {boolean} symmetricalTextCentre
1900
+ * @returns {{x:number, y: number}}
1901
+ */
1902
+ function computeTextCentre(interior, exterior, symmetricalTextCentre) {
1903
+ // get an initial estimate by sampling around the interior circles
1904
+ // and taking the point with the biggest margin
1905
+ /** @type {{x: number, y: number}[]} */
1906
+ const points = [];
1907
+ for (const c of interior) {
1908
+ points.push({ x: c.x, y: c.y });
1909
+ points.push({ x: c.x + c.radius / 2, y: c.y });
1910
+ points.push({ x: c.x - c.radius / 2, y: c.y });
1911
+ points.push({ x: c.x, y: c.y + c.radius / 2 });
1912
+ points.push({ x: c.x, y: c.y - c.radius / 2 });
1913
+ }
1914
+
1915
+ let initial = points[0];
1916
+ let margin = circleMargin(points[0], interior, exterior);
1917
+
1918
+ for (let i = 1; i < points.length; ++i) {
1919
+ const m = circleMargin(points[i], interior, exterior);
1920
+ if (m >= margin) {
1921
+ initial = points[i];
1922
+ margin = m;
1923
+ }
1924
+ }
1925
+
1926
+ // maximize the margin numerically
1927
+ const solution = nelderMead(
1928
+ (p) => -1 * circleMargin({ x: p[0], y: p[1] }, interior, exterior),
1929
+ [initial.x, initial.y],
1930
+ { maxIterations: 500, minErrorDelta: 1e-10 }
1931
+ ).x;
1932
+
1933
+ const ret = { x: symmetricalTextCentre ? 0 : solution[0], y: solution[1] };
1934
+
1935
+ // check solution, fallback as needed (happens if fully overlapped
1936
+ // etc)
1937
+ let valid = true;
1938
+ for (const i of interior) {
1939
+ if (distance(ret, i) > i.radius) {
1940
+ valid = false;
1941
+ break;
1942
+ }
1943
+ }
1944
+
1945
+ for (const e of exterior) {
1946
+ if (distance(ret, e) < e.radius) {
1947
+ valid = false;
1948
+ break;
1949
+ }
1950
+ }
1951
+ if (valid) {
1952
+ return ret;
1953
+ }
1954
+
1955
+ if (interior.length == 1) {
1956
+ return { x: interior[0].x, y: interior[0].y };
1957
+ }
1958
+ const areaStats = {};
1959
+ intersectionArea(interior, areaStats);
1960
+
1961
+ if (areaStats.arcs.length === 0) {
1962
+ return { x: 0, y: -1000, disjoint: true };
1963
+ }
1964
+ if (areaStats.arcs.length == 1) {
1965
+ return { x: areaStats.arcs[0].circle.x, y: areaStats.arcs[0].circle.y };
1966
+ }
1967
+ if (exterior.length) {
1968
+ // try again without other circles
1969
+ return computeTextCentre(interior, []);
1970
+ }
1971
+ // take average of all the points in the intersection
1972
+ // polygon. this should basically never happen
1973
+ // and has some issues:
1974
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
1975
+ return getCenter(areaStats.arcs.map((a) => a.p1));
1976
+ }
1977
+
1978
+ // given a dictionary of {setid : circle}, returns
1979
+ // a dictionary of setid to list of circles that completely overlap it
1980
+ function getOverlappingCircles(circles) {
1981
+ const ret = {};
1982
+ const circleids = Object.keys(circles);
1983
+ for (const circleid of circleids) {
1984
+ ret[circleid] = [];
1985
+ }
1986
+ for (let i = 0; i < circleids.length; i++) {
1987
+ const ci = circleids[i];
1988
+ const a = circles[ci];
1989
+ for (let j = i + 1; j < circleids.length; ++j) {
1990
+ const cj = circleids[j];
1991
+ const b = circles[cj];
1992
+ const d = distance(a, b);
1993
+
1994
+ if (d + b.radius <= a.radius + 1e-10) {
1995
+ ret[cj].push(ci);
1996
+ } else if (d + a.radius <= b.radius + 1e-10) {
1997
+ ret[ci].push(cj);
1998
+ }
1999
+ }
2000
+ }
2001
+ return ret;
2002
+ }
2003
+
2004
+ function computeTextCentres(circles, areas, symmetricalTextCentre) {
2005
+ const ret = {};
2006
+ const overlapped = getOverlappingCircles(circles);
2007
+ for (let i = 0; i < areas.length; ++i) {
2008
+ const area = areas[i].sets;
2009
+ const areaids = {};
2010
+ const exclude = {};
2011
+
2012
+ for (let j = 0; j < area.length; ++j) {
2013
+ areaids[area[j]] = true;
2014
+ const overlaps = overlapped[area[j]];
2015
+ // keep track of any circles that overlap this area,
2016
+ // and don't consider for purposes of computing the text
2017
+ // centre
2018
+ for (let k = 0; k < overlaps.length; ++k) {
2019
+ exclude[overlaps[k]] = true;
2020
+ }
2021
+ }
2022
+
2023
+ const interior = [];
2024
+ const exterior = [];
2025
+ for (let setid in circles) {
2026
+ if (setid in areaids) {
2027
+ interior.push(circles[setid]);
2028
+ } else if (!(setid in exclude)) {
2029
+ exterior.push(circles[setid]);
2030
+ }
2031
+ }
2032
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
2033
+ ret[area] = centre;
2034
+ if (centre.disjoint && areas[i].size > 0) {
2035
+ console.log('WARNING: area ' + area + ' not represented on screen');
2036
+ }
2037
+ }
2038
+ return ret;
2039
+ }
2040
+
2041
+ // sorts all areas in the venn diagram, so that
2042
+ // a particular area is on top (relativeTo) - and
2043
+ // all other areas are so that the smallest areas are on top
2044
+ function sortAreas(div, relativeTo) {
2045
+ // figure out sets that are completely overlapped by relativeTo
2046
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
2047
+ const exclude = new Set();
2048
+ for (const check of relativeTo.sets) {
2049
+ for (let setid in overlaps) {
2050
+ const overlap = overlaps[setid];
2051
+ for (let j = 0; j < overlap.length; ++j) {
2052
+ if (overlap[j] == check) {
2053
+ exclude.add(setid);
2054
+ break;
2055
+ }
2056
+ }
2057
+ }
2058
+ }
2059
+
2060
+ // checks that all sets are in exclude;
2061
+ function shouldExclude(sets) {
2062
+ return sets.every((set) => !exclude.has(set));
2063
+ }
2064
+
2065
+ // need to sort div's so that Z order is correct
2066
+ div.selectAll('g').sort((a, b) => {
2067
+ // highest order set intersections first
2068
+ if (a.sets.length != b.sets.length) {
2069
+ return a.sets.length - b.sets.length;
2070
+ }
2071
+
2072
+ if (a == relativeTo) {
2073
+ return shouldExclude(b.sets) ? -1 : 1;
2074
+ }
2075
+ if (b == relativeTo) {
2076
+ return shouldExclude(a.sets) ? 1 : -1;
2077
+ }
2078
+
2079
+ // finally by size
2080
+ return b.size - a.size;
2081
+ });
2082
+ }
2083
+
2084
+ /**
2085
+ * @param {number} x
2086
+ * @param {number} y
2087
+ * @param {number} r
2088
+ * @returns {string}
2089
+ */
2090
+ function circlePath(x, y, r) {
2091
+ const ret = [];
2092
+ ret.push('\nM', x, y);
2093
+ ret.push('\nm', -r, 0);
2094
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
2095
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
2096
+ return ret.join(' ');
2097
+ }
2098
+
2099
+ /**
2100
+ * inverse of the circlePath function, returns a circle object from an svg path
2101
+ * @param {string} path
2102
+ * @returns {{x: number, y: number, radius: number}}
2103
+ */
2104
+ function circleFromPath(path) {
2105
+ const tokens = path.split(' ');
2106
+ return { x: Number.parseFloat(tokens[1]), y: Number.parseFloat(tokens[2]), radius: -Number.parseFloat(tokens[4]) };
2107
+ }
2108
+
2109
+ function intersectionAreaArcs(circles) {
2110
+ if (circles.length === 0) {
2111
+ return [];
2112
+ }
2113
+ const stats = {};
2114
+ intersectionArea(circles, stats);
2115
+ return stats.arcs;
2116
+ }
2117
+
2118
+ function arcsToPath(arcs, round) {
2119
+ if (arcs.length === 0) {
2120
+ return 'M 0 0';
2121
+ }
2122
+ const rFactor = Math.pow(10, round || 0);
2123
+ const r = round != null ? (v) => Math.round(v * rFactor) / rFactor : (v) => v;
2124
+ if (arcs.length == 1) {
2125
+ const circle = arcs[0].circle;
2126
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
2127
+ }
2128
+ // draw path around arcs
2129
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
2130
+ for (const arc of arcs) {
2131
+ const radius = r(arc.circle.radius);
2132
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
2133
+ }
2134
+ return ret.join(' ');
2135
+ }
2136
+
2137
+ /**
2138
+ * returns a svg path of the intersection area of a bunch of circles
2139
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
2140
+ * @returns {string}
2141
+ */
2142
+ function intersectionAreaPath(circles, round) {
2143
+ return arcsToPath(intersectionAreaArcs(circles), round);
2144
+ }
2145
+
2146
+ function layout(data, options = {}) {
2147
+ const {
2148
+ lossFunction: loss,
2149
+ layoutFunction: layout = venn,
2150
+ normalize = true,
2151
+ orientation = Math.PI / 2,
2152
+ orientationOrder,
2153
+ width = 600,
2154
+ height = 350,
2155
+ padding = 15,
2156
+ scaleToFit = false,
2157
+ symmetricalTextCentre = false,
2158
+ distinct,
2159
+ round = 2,
2160
+ } = options;
2161
+
2162
+ let solution = layout(data, {
2163
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
2164
+ distinct,
2165
+ });
2166
+
2167
+ if (normalize) {
2168
+ solution = normalizeSolution(solution, orientation, orientationOrder);
2169
+ }
2170
+
2171
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
2172
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
2173
+
2174
+ const circleLookup = new Map(
2175
+ Object.keys(circles).map((set) => [
2176
+ set,
2177
+ {
2178
+ set,
2179
+ x: circles[set].x,
2180
+ y: circles[set].y,
2181
+ radius: circles[set].radius,
2182
+ },
2183
+ ])
2184
+ );
2185
+ const helpers = data.map((area) => {
2186
+ const circles = area.sets.map((s) => circleLookup.get(s));
2187
+ const arcs = intersectionAreaArcs(circles);
2188
+ const path = arcsToPath(arcs, round);
2189
+ return { circles, arcs, path, area, has: new Set(area.sets) };
2190
+ });
2191
+
2192
+ function genDistinctPath(sets) {
2193
+ let r = '';
2194
+ for (const e of helpers) {
2195
+ if (e.has.size > sets.length && sets.every((s) => e.has.has(s))) {
2196
+ r += ' ' + e.path;
2197
+ }
2198
+ }
2199
+ return r;
2200
+ }
2201
+
2202
+ return helpers.map(({ circles, arcs, path, area }) => {
2203
+ return {
2204
+ data: area,
2205
+ text: textCentres[area.sets],
2206
+ circles,
2207
+ arcs,
2208
+ path,
2209
+ distinctPath: path + genDistinctPath(area.sets),
2210
+ };
2211
+ });
2212
+ }
2213
+
2214
+ export { VennDiagram, bestInitialLayout, circleArea, circleCircleIntersection, circleFromPath, circleOverlap, circlePath, computeTextCentre, computeTextCentres, disjointCluster, distance, distanceFromIntersectArea, greedyLayout, intersectionArea, intersectionAreaPath, layout, logRatioLossFunction, lossFunction, normalizeSolution, scaleSolution, sortAreas, venn, wrapText };
tools/ui/node_modules/@upsetjs/venn.js/build/venn.js ADDED
@@ -0,0 +1,2166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ (function (global, factory) {
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
3
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.venn = {}));
5
+ })(this, (function (exports) { 'use strict';
6
+
7
+ const SMALL$1 = 1e-10;
8
+
9
+ /**
10
+ * Returns the intersection area of a bunch of circles (where each circle
11
+ * is an object having an x,y and radius property)
12
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
13
+ * @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<{
14
+ x: number;
15
+ y: number;
16
+ parentIndex: [number, number];
17
+ }>, intersectionPoints: ReadonlyArray<{
18
+ x: number;
19
+ y: number;
20
+ parentIndex: [number, number];
21
+ }> }} stats
22
+ * @returns {number}
23
+ */
24
+ function intersectionArea(circles, stats) {
25
+ // get all the intersection points of the circles
26
+ const intersectionPoints = getIntersectionPoints(circles);
27
+
28
+ // filter out points that aren't included in all the circles
29
+ const innerPoints = intersectionPoints.filter(p => containedInCircles(p, circles));
30
+ let arcArea = 0;
31
+ let polygonArea = 0;
32
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
33
+ const arcs = [];
34
+
35
+ // if we have intersection points that are within all the circles,
36
+ // then figure out the area contained by them
37
+ if (innerPoints.length > 1) {
38
+ // sort the points by angle from the center of the polygon, which lets
39
+ // us just iterate over points to get the edges
40
+ const center = getCenter(innerPoints);
41
+ for (let i = 0; i < innerPoints.length; ++i) {
42
+ const p = innerPoints[i];
43
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
44
+ }
45
+ innerPoints.sort((a, b) => b.angle - a.angle);
46
+
47
+ // iterate over all points, get arc between the points
48
+ // and update the areas
49
+ let p2 = innerPoints[innerPoints.length - 1];
50
+ for (let i = 0; i < innerPoints.length; ++i) {
51
+ const p1 = innerPoints[i];
52
+
53
+ // polygon area updates easily ...
54
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
55
+
56
+ // updating the arc area is a little more involved
57
+ const midPoint = {
58
+ x: (p1.x + p2.x) / 2,
59
+ y: (p1.y + p2.y) / 2
60
+ };
61
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
62
+ let arc = null;
63
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
64
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
65
+ // figure out the angle halfway between the two points
66
+ // on the current circle
67
+ const circle = circles[p1.parentIndex[j]];
68
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
69
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
70
+ let angleDiff = a2 - a1;
71
+ if (angleDiff < 0) {
72
+ angleDiff += 2 * Math.PI;
73
+ }
74
+
75
+ // and use that angle to figure out the width of the
76
+ // arc
77
+ const a = a2 - angleDiff / 2;
78
+ let width = distance(midPoint, {
79
+ x: circle.x + circle.radius * Math.sin(a),
80
+ y: circle.y + circle.radius * Math.cos(a)
81
+ });
82
+
83
+ // clamp the width to the largest is can actually be
84
+ // (sometimes slightly overflows because of FP errors)
85
+ if (width > circle.radius * 2) {
86
+ width = circle.radius * 2;
87
+ }
88
+
89
+ // pick the circle whose arc has the smallest width
90
+ if (arc == null || arc.width > width) {
91
+ arc = {
92
+ circle,
93
+ width,
94
+ p1,
95
+ p2,
96
+ large: width > circle.radius,
97
+ sweep: true
98
+ };
99
+ }
100
+ }
101
+ }
102
+ if (arc != null) {
103
+ arcs.push(arc);
104
+ arcArea += circleArea(arc.circle.radius, arc.width);
105
+ p2 = p1;
106
+ }
107
+ }
108
+ } else {
109
+ // no intersection points, is either disjoint - or is completely
110
+ // overlapped. figure out which by examining the smallest circle
111
+ let smallest = circles[0];
112
+ for (let i = 1; i < circles.length; ++i) {
113
+ if (circles[i].radius < smallest.radius) {
114
+ smallest = circles[i];
115
+ }
116
+ }
117
+
118
+ // make sure the smallest circle is completely contained in all
119
+ // the other circles
120
+ let disjoint = false;
121
+ for (let i = 0; i < circles.length; ++i) {
122
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
123
+ disjoint = true;
124
+ break;
125
+ }
126
+ }
127
+ if (disjoint) {
128
+ arcArea = polygonArea = 0;
129
+ } else {
130
+ arcArea = smallest.radius * smallest.radius * Math.PI;
131
+ arcs.push({
132
+ circle: smallest,
133
+ p1: {
134
+ x: smallest.x,
135
+ y: smallest.y + smallest.radius
136
+ },
137
+ p2: {
138
+ x: smallest.x - SMALL$1,
139
+ y: smallest.y + smallest.radius
140
+ },
141
+ width: smallest.radius * 2,
142
+ large: true,
143
+ sweep: true
144
+ });
145
+ }
146
+ }
147
+ polygonArea /= 2;
148
+ if (stats) {
149
+ stats.area = arcArea + polygonArea;
150
+ stats.arcArea = arcArea;
151
+ stats.polygonArea = polygonArea;
152
+ stats.arcs = arcs;
153
+ stats.innerPoints = innerPoints;
154
+ stats.intersectionPoints = intersectionPoints;
155
+ }
156
+ return arcArea + polygonArea;
157
+ }
158
+
159
+ /**
160
+ * returns whether a point is contained by all of a list of circles
161
+ * @param {{x: number, y: number}} point
162
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
163
+ * @returns {boolean}
164
+ */
165
+ function containedInCircles(point, circles) {
166
+ return circles.every(circle => distance(point, circle) < circle.radius + SMALL$1);
167
+ }
168
+
169
+ /**
170
+ * Gets all intersection points between a bunch of circles
171
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
172
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
173
+ */
174
+ function getIntersectionPoints(circles) {
175
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
176
+ const ret = [];
177
+ for (let i = 0; i < circles.length; ++i) {
178
+ for (let j = i + 1; j < circles.length; ++j) {
179
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
180
+ for (const p of intersect) {
181
+ p.parentIndex = [i, j];
182
+ ret.push(p);
183
+ }
184
+ }
185
+ }
186
+ return ret;
187
+ }
188
+
189
+ /**
190
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
191
+ * @param {number} r
192
+ * @param {number} width
193
+ * @returns {number}
194
+ **/
195
+ function circleArea(r, width) {
196
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
197
+ }
198
+
199
+ /**
200
+ * euclidean distance between two points
201
+ * @param {{x: number, y: number}} p1
202
+ * @param {{x: number, y: number}} p2
203
+ * @returns {number}
204
+ **/
205
+ function distance(p1, p2) {
206
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
207
+ }
208
+
209
+ /**
210
+ * Returns the overlap area of two circles of radius r1 and r2 - that
211
+ * have their centers separated by distance d. Simpler faster
212
+ * circle intersection for only two circles
213
+ * @param {number} r1
214
+ * @param {number} r2
215
+ * @param {number} d
216
+ * @returns {number}
217
+ */
218
+ function circleOverlap(r1, r2, d) {
219
+ // no overlap
220
+ if (d >= r1 + r2) {
221
+ return 0;
222
+ }
223
+
224
+ // completely overlapped
225
+ if (d <= Math.abs(r1 - r2)) {
226
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
227
+ }
228
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
229
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
230
+ return circleArea(r1, w1) + circleArea(r2, w2);
231
+ }
232
+
233
+ /**
234
+ * Given two circles (containing a x/y/radius attributes),
235
+ * returns the intersecting points if possible
236
+ * note: doesn't handle cases where there are infinitely many
237
+ * intersection points (circles are equivalent):, or only one intersection point
238
+ * @param {{x: number, y: number, radius: number}} p1
239
+ * @param {{x: number, y: number, radius: number}} p2
240
+ * @returns {ReadonlyArray<{x: number, y: number}>}
241
+ **/
242
+ function circleCircleIntersection(p1, p2) {
243
+ const d = distance(p1, p2);
244
+ const r1 = p1.radius;
245
+ const r2 = p2.radius;
246
+
247
+ // if to far away, or self contained - can't be done
248
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
249
+ return [];
250
+ }
251
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
252
+ const h = Math.sqrt(r1 * r1 - a * a);
253
+ const x0 = p1.x + a * (p2.x - p1.x) / d;
254
+ const y0 = p1.y + a * (p2.y - p1.y) / d;
255
+ const rx = -(p2.y - p1.y) * (h / d);
256
+ const ry = -(p2.x - p1.x) * (h / d);
257
+ return [{
258
+ x: x0 + rx,
259
+ y: y0 - ry
260
+ }, {
261
+ x: x0 - rx,
262
+ y: y0 + ry
263
+ }];
264
+ }
265
+
266
+ /**
267
+ * Returns the center of a bunch of points
268
+ * @param {ReadonlyArray<{x: number, y: number}>} points
269
+ * @returns {{x: number, y: number}}
270
+ */
271
+ function getCenter(points) {
272
+ const center = {
273
+ x: 0,
274
+ y: 0
275
+ };
276
+ for (const point of points) {
277
+ center.x += point.x;
278
+ center.y += point.y;
279
+ }
280
+ center.x /= points.length;
281
+ center.y /= points.length;
282
+ return center;
283
+ }
284
+
285
+ /** finds the zeros of a function, given two starting points (which must
286
+ * have opposite signs */
287
+ function bisect(f, a, b, parameters) {
288
+ parameters = parameters || {};
289
+ const maxIterations = parameters.maxIterations || 100;
290
+ const tolerance = parameters.tolerance || 1e-10;
291
+ const fA = f(a);
292
+ const fB = f(b);
293
+ let delta = b - a;
294
+ if (fA * fB > 0) {
295
+ throw 'Initial bisect points must have opposite signs';
296
+ }
297
+ if (fA === 0) return a;
298
+ if (fB === 0) return b;
299
+ for (let i = 0; i < maxIterations; ++i) {
300
+ delta /= 2;
301
+ const mid = a + delta;
302
+ const fMid = f(mid);
303
+ if (fMid * fA >= 0) {
304
+ a = mid;
305
+ }
306
+ if (Math.abs(delta) < tolerance || fMid === 0) {
307
+ return mid;
308
+ }
309
+ }
310
+ return a + delta;
311
+ }
312
+
313
+ // need some basic operations on vectors, rather than adding a dependency,
314
+ // just define here
315
+ function zeros(x) {
316
+ const r = new Array(x);
317
+ for (let i = 0; i < x; ++i) {
318
+ r[i] = 0;
319
+ }
320
+ return r;
321
+ }
322
+ function zerosM(x, y) {
323
+ return zeros(x).map(() => zeros(y));
324
+ }
325
+ function dot(a, b) {
326
+ let ret = 0;
327
+ for (let i = 0; i < a.length; ++i) {
328
+ ret += a[i] * b[i];
329
+ }
330
+ return ret;
331
+ }
332
+ function norm2(a) {
333
+ return Math.sqrt(dot(a, a));
334
+ }
335
+ function scale(ret, value, c) {
336
+ for (let i = 0; i < value.length; ++i) {
337
+ ret[i] = value[i] * c;
338
+ }
339
+ }
340
+ function weightedSum(ret, w1, v1, w2, v2) {
341
+ for (let j = 0; j < ret.length; ++j) {
342
+ ret[j] = w1 * v1[j] + w2 * v2[j];
343
+ }
344
+ }
345
+
346
+ /** minimizes a function using the downhill simplex method */
347
+ function nelderMead(f, x0, parameters) {
348
+ parameters = parameters || {};
349
+ const maxIterations = parameters.maxIterations || x0.length * 200;
350
+ const nonZeroDelta = parameters.nonZeroDelta || 1.05;
351
+ const zeroDelta = parameters.zeroDelta || 0.001;
352
+ const minErrorDelta = parameters.minErrorDelta || 1e-6;
353
+ const minTolerance = parameters.minErrorDelta || 1e-5;
354
+ const rho = parameters.rho !== undefined ? parameters.rho : 1;
355
+ const chi = parameters.chi !== undefined ? parameters.chi : 2;
356
+ const psi = parameters.psi !== undefined ? parameters.psi : -0.5;
357
+ const sigma = parameters.sigma !== undefined ? parameters.sigma : 0.5;
358
+ let maxDiff;
359
+
360
+ // initialize simplex.
361
+ const N = x0.length;
362
+ const simplex = new Array(N + 1);
363
+ simplex[0] = x0;
364
+ simplex[0].fx = f(x0);
365
+ simplex[0].id = 0;
366
+ for (let i = 0; i < N; ++i) {
367
+ const point = x0.slice();
368
+ point[i] = point[i] ? point[i] * nonZeroDelta : zeroDelta;
369
+ simplex[i + 1] = point;
370
+ simplex[i + 1].fx = f(point);
371
+ simplex[i + 1].id = i + 1;
372
+ }
373
+ function updateSimplex(value) {
374
+ for (let i = 0; i < value.length; i++) {
375
+ simplex[N][i] = value[i];
376
+ }
377
+ simplex[N].fx = value.fx;
378
+ }
379
+ const sortOrder = (a, b) => a.fx - b.fx;
380
+ const centroid = x0.slice();
381
+ const reflected = x0.slice();
382
+ const contracted = x0.slice();
383
+ const expanded = x0.slice();
384
+ for (let iteration = 0; iteration < maxIterations; ++iteration) {
385
+ simplex.sort(sortOrder);
386
+ if (parameters.history) {
387
+ // copy the simplex (since later iterations will mutate) and
388
+ // sort it to have a consistent order between iterations
389
+ const sortedSimplex = simplex.map(x => {
390
+ const state = x.slice();
391
+ state.fx = x.fx;
392
+ state.id = x.id;
393
+ return state;
394
+ });
395
+ sortedSimplex.sort((a, b) => a.id - b.id);
396
+ parameters.history.push({
397
+ x: simplex[0].slice(),
398
+ fx: simplex[0].fx,
399
+ simplex: sortedSimplex
400
+ });
401
+ }
402
+ maxDiff = 0;
403
+ for (let i = 0; i < N; ++i) {
404
+ maxDiff = Math.max(maxDiff, Math.abs(simplex[0][i] - simplex[1][i]));
405
+ }
406
+ if (Math.abs(simplex[0].fx - simplex[N].fx) < minErrorDelta && maxDiff < minTolerance) {
407
+ break;
408
+ }
409
+
410
+ // compute the centroid of all but the worst point in the simplex
411
+ for (let i = 0; i < N; ++i) {
412
+ centroid[i] = 0;
413
+ for (let j = 0; j < N; ++j) {
414
+ centroid[i] += simplex[j][i];
415
+ }
416
+ centroid[i] /= N;
417
+ }
418
+
419
+ // reflect the worst point past the centroid and compute loss at reflected
420
+ // point
421
+ const worst = simplex[N];
422
+ weightedSum(reflected, 1 + rho, centroid, -rho, worst);
423
+ reflected.fx = f(reflected);
424
+
425
+ // if the reflected point is the best seen, then possibly expand
426
+ if (reflected.fx < simplex[0].fx) {
427
+ weightedSum(expanded, 1 + chi, centroid, -chi, worst);
428
+ expanded.fx = f(expanded);
429
+ if (expanded.fx < reflected.fx) {
430
+ updateSimplex(expanded);
431
+ } else {
432
+ updateSimplex(reflected);
433
+ }
434
+ }
435
+
436
+ // if the reflected point is worse than the second worst, we need to
437
+ // contract
438
+ else if (reflected.fx >= simplex[N - 1].fx) {
439
+ let shouldReduce = false;
440
+ if (reflected.fx > worst.fx) {
441
+ // do an inside contraction
442
+ weightedSum(contracted, 1 + psi, centroid, -psi, worst);
443
+ contracted.fx = f(contracted);
444
+ if (contracted.fx < worst.fx) {
445
+ updateSimplex(contracted);
446
+ } else {
447
+ shouldReduce = true;
448
+ }
449
+ } else {
450
+ // do an outside contraction
451
+ weightedSum(contracted, 1 - psi * rho, centroid, psi * rho, worst);
452
+ contracted.fx = f(contracted);
453
+ if (contracted.fx < reflected.fx) {
454
+ updateSimplex(contracted);
455
+ } else {
456
+ shouldReduce = true;
457
+ }
458
+ }
459
+ if (shouldReduce) {
460
+ // if we don't contract here, we're done
461
+ if (sigma >= 1) break;
462
+
463
+ // do a reduction
464
+ for (let i = 1; i < simplex.length; ++i) {
465
+ weightedSum(simplex[i], 1 - sigma, simplex[0], sigma, simplex[i]);
466
+ simplex[i].fx = f(simplex[i]);
467
+ }
468
+ }
469
+ } else {
470
+ updateSimplex(reflected);
471
+ }
472
+ }
473
+ simplex.sort(sortOrder);
474
+ return {
475
+ fx: simplex[0].fx,
476
+ x: simplex[0]
477
+ };
478
+ }
479
+
480
+ /// searches along line 'pk' for a point that satifies the wolfe conditions
481
+ /// See 'Numerical Optimization' by Nocedal and Wright p59-60
482
+ /// f : objective function
483
+ /// pk : search direction
484
+ /// current: object containing current gradient/loss
485
+ /// next: output: contains next gradient/loss
486
+ /// returns a: step size taken
487
+ function wolfeLineSearch(f, pk, current, next, a, c1, c2) {
488
+ const phi0 = current.fx;
489
+ const phiPrime0 = dot(current.fxprime, pk);
490
+ let phi = phi0;
491
+ let phi_old = phi0;
492
+ let phiPrime = phiPrime0;
493
+ let a0 = 0;
494
+ a = a || 1;
495
+ c1 = c1 || 1e-6;
496
+ c2 = c2 || 0.1;
497
+ function zoom(a_lo, a_high, phi_lo) {
498
+ for (let iteration = 0; iteration < 16; ++iteration) {
499
+ a = (a_lo + a_high) / 2;
500
+ weightedSum(next.x, 1.0, current.x, a, pk);
501
+ phi = next.fx = f(next.x, next.fxprime);
502
+ phiPrime = dot(next.fxprime, pk);
503
+ if (phi > phi0 + c1 * a * phiPrime0 || phi >= phi_lo) {
504
+ a_high = a;
505
+ } else {
506
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
507
+ return a;
508
+ }
509
+ if (phiPrime * (a_high - a_lo) >= 0) {
510
+ a_high = a_lo;
511
+ }
512
+ a_lo = a;
513
+ phi_lo = phi;
514
+ }
515
+ }
516
+ return 0;
517
+ }
518
+ for (let iteration = 0; iteration < 10; ++iteration) {
519
+ weightedSum(next.x, 1.0, current.x, a, pk);
520
+ phi = next.fx = f(next.x, next.fxprime);
521
+ phiPrime = dot(next.fxprime, pk);
522
+ if (phi > phi0 + c1 * a * phiPrime0 || iteration && phi >= phi_old) {
523
+ return zoom(a0, a, phi_old);
524
+ }
525
+ if (Math.abs(phiPrime) <= -c2 * phiPrime0) {
526
+ return a;
527
+ }
528
+ if (phiPrime >= 0) {
529
+ return zoom(a, a0, phi);
530
+ }
531
+ phi_old = phi;
532
+ a0 = a;
533
+ a *= 2;
534
+ }
535
+ return a;
536
+ }
537
+
538
+ function conjugateGradient(f, initial, params) {
539
+ // allocate all memory up front here, keep out of the loop for perfomance
540
+ // reasons
541
+ let current = {
542
+ x: initial.slice(),
543
+ fx: 0,
544
+ fxprime: initial.slice()
545
+ };
546
+ let next = {
547
+ x: initial.slice(),
548
+ fx: 0,
549
+ fxprime: initial.slice()
550
+ };
551
+ const yk = initial.slice();
552
+ let pk;
553
+ let temp;
554
+ let a = 1;
555
+ let maxIterations;
556
+ params = params || {};
557
+ maxIterations = params.maxIterations || initial.length * 20;
558
+ current.fx = f(current.x, current.fxprime);
559
+ pk = current.fxprime.slice();
560
+ scale(pk, current.fxprime, -1);
561
+ for (let i = 0; i < maxIterations; ++i) {
562
+ a = wolfeLineSearch(f, pk, current, next, a);
563
+
564
+ // todo: history in wrong spot?
565
+ if (params.history) {
566
+ params.history.push({
567
+ x: current.x.slice(),
568
+ fx: current.fx,
569
+ fxprime: current.fxprime.slice(),
570
+ alpha: a
571
+ });
572
+ }
573
+ if (!a) {
574
+ // faiiled to find point that satifies wolfe conditions.
575
+ // reset direction for next iteration
576
+ scale(pk, current.fxprime, -1);
577
+ } else {
578
+ // update direction using Polak–Ribiere CG method
579
+ weightedSum(yk, 1, next.fxprime, -1, current.fxprime);
580
+ const delta_k = dot(current.fxprime, current.fxprime);
581
+ const beta_k = Math.max(0, dot(yk, next.fxprime) / delta_k);
582
+ weightedSum(pk, beta_k, pk, -1, next.fxprime);
583
+ temp = current;
584
+ current = next;
585
+ next = temp;
586
+ }
587
+ if (norm2(current.fxprime) <= 1e-5) {
588
+ break;
589
+ }
590
+ }
591
+ if (params.history) {
592
+ params.history.push({
593
+ x: current.x.slice(),
594
+ fx: current.fx,
595
+ fxprime: current.fxprime.slice(),
596
+ alpha: a
597
+ });
598
+ }
599
+ return current;
600
+ }
601
+
602
+ /**
603
+ * given a list of set objects, and their corresponding overlaps
604
+ * updates the (x, y, radius) attribute on each set such that their positions
605
+ * roughly correspond to the desired overlaps
606
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
607
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
608
+ */
609
+ function venn(sets, parameters = {}) {
610
+ parameters.maxIterations = parameters.maxIterations || 500;
611
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
612
+ const loss = parameters.lossFunction || lossFunction;
613
+
614
+ // add in missing pairwise areas as having 0 size
615
+ const areas = addMissingAreas(sets, parameters);
616
+
617
+ // initial layout is done greedily
618
+ const circles = initialLayout(areas, parameters);
619
+
620
+ // transform x/y coordinates to a vector to optimize
621
+ const setids = Object.keys(circles);
622
+ /** @type {number[]} */
623
+ const initial = [];
624
+ for (const setid of setids) {
625
+ initial.push(circles[setid].x);
626
+ initial.push(circles[setid].y);
627
+ }
628
+
629
+ // optimize initial layout from our loss function
630
+ const solution = nelderMead(values => {
631
+ const current = {};
632
+ for (let i = 0; i < setids.length; ++i) {
633
+ const setid = setids[i];
634
+ current[setid] = {
635
+ x: values[2 * i],
636
+ y: values[2 * i + 1],
637
+ radius: circles[setid].radius
638
+ // size : circles[setid].size
639
+ };
640
+ }
641
+ return loss(current, areas);
642
+ }, initial, parameters);
643
+
644
+ // transform solution vector back to x/y points
645
+ const positions = solution.x;
646
+ for (let i = 0; i < setids.length; ++i) {
647
+ const setid = setids[i];
648
+ circles[setid].x = positions[2 * i];
649
+ circles[setid].y = positions[2 * i + 1];
650
+ }
651
+ return circles;
652
+ }
653
+ const SMALL = 1e-10;
654
+
655
+ /**
656
+ * Returns the distance necessary for two circles of radius r1 + r2 to
657
+ * have the overlap area 'overlap'
658
+ * @param {number} r1
659
+ * @param {number} r2
660
+ * @param {number} overlap
661
+ * @returns {number}
662
+ */
663
+ function distanceFromIntersectArea(r1, r2, overlap) {
664
+ // handle complete overlapped circles
665
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
666
+ return Math.abs(r1 - r2);
667
+ }
668
+ return bisect(distance => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
669
+ }
670
+
671
+ /**
672
+ * Missing pair-wise intersection area data can cause problems:
673
+ * treating as an unknown means that sets will be laid out overlapping,
674
+ * which isn't what people expect. To reflect that we want disjoint sets
675
+ * here, set the overlap to 0 for all missing pairwise set intersections
676
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
677
+ * @returns {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>}
678
+ */
679
+ function addMissingAreas(areas, parameters = {}) {
680
+ const distinct = parameters.distinct;
681
+ const r = areas.map(s => Object.assign({}, s));
682
+ function toKey(arr) {
683
+ return arr.join(';');
684
+ }
685
+ if (distinct) {
686
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
687
+ /** @types Map<string, number> */
688
+ const count = new Map();
689
+ for (const area of r) {
690
+ for (let i = 0; i < area.sets.length; i++) {
691
+ const si = String(area.sets[i]);
692
+ count.set(si, area.size + (count.get(si) || 0));
693
+ for (let j = i + 1; j < area.sets.length; j++) {
694
+ const sj = String(area.sets[j]);
695
+ const k1 = `${si};${sj}`;
696
+ const k2 = `${sj};${si}`;
697
+ count.set(k1, area.size + (count.get(k1) || 0));
698
+ count.set(k2, area.size + (count.get(k2) || 0));
699
+ }
700
+ }
701
+ }
702
+ for (const area of r) {
703
+ if (area.sets.length < 3) {
704
+ area.size = count.get(toKey(area.sets));
705
+ }
706
+ }
707
+ }
708
+
709
+ // two circle intersections that aren't defined
710
+ const ids = [];
711
+
712
+ /** @type {Set<string>} */
713
+ const pairs = new Set();
714
+ for (const area of r) {
715
+ if (area.sets.length === 1) {
716
+ ids.push(area.sets[0]);
717
+ } else if (area.sets.length === 2) {
718
+ const a = area.sets[0];
719
+ const b = area.sets[1];
720
+ pairs.add(toKey(area.sets));
721
+ pairs.add(toKey([b, a]));
722
+ }
723
+ }
724
+ ids.sort((a, b) => a === b ? 0 : a < b ? -1 : +1);
725
+ for (let i = 0; i < ids.length; ++i) {
726
+ const a = ids[i];
727
+ for (let j = i + 1; j < ids.length; ++j) {
728
+ const b = ids[j];
729
+ if (!pairs.has(toKey([a, b]))) {
730
+ r.push({
731
+ sets: [a, b],
732
+ size: 0
733
+ });
734
+ }
735
+ }
736
+ }
737
+ return r;
738
+ }
739
+
740
+ /**
741
+ * Returns two matrices, one of the euclidean distances between the sets
742
+ * and the other indicating if there are subset or disjoint set relationships
743
+ * @param {ReadonlyArray<{sets: ReadonlyArray<number>}>} areas
744
+ * @param {ReadonlyArray<{size: number}>} sets
745
+ * @param {ReadonlyArray<number>} setids
746
+ */
747
+ function getDistanceMatrices(areas, sets, setids) {
748
+ // initialize an empty distance matrix between all the points
749
+ /**
750
+ * @type {number[][]}
751
+ */
752
+ const distances = zerosM(sets.length, sets.length);
753
+ /**
754
+ * @type {number[][]}
755
+ */
756
+ const constraints = zerosM(sets.length, sets.length);
757
+
758
+ // compute required distances between all the sets such that
759
+ // the areas match
760
+ areas.filter(x => x.sets.length === 2).forEach(current => {
761
+ const left = setids[current.sets[0]];
762
+ const right = setids[current.sets[1]];
763
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
764
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
765
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
766
+ distances[left][right] = distances[right][left] = distance;
767
+
768
+ // also update constraints to indicate if its a subset or disjoint
769
+ // relationship
770
+ let c = 0;
771
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
772
+ c = 1;
773
+ } else if (current.size <= 1e-10) {
774
+ c = -1;
775
+ }
776
+ constraints[left][right] = constraints[right][left] = c;
777
+ });
778
+ return {
779
+ distances,
780
+ constraints
781
+ };
782
+ }
783
+
784
+ /// computes the gradient and loss simultaneously for our constrained MDS optimizer
785
+ function constrainedMDSGradient(x, fxprime, distances, constraints) {
786
+ for (let i = 0; i < fxprime.length; ++i) {
787
+ fxprime[i] = 0;
788
+ }
789
+ let loss = 0;
790
+ for (let i = 0; i < distances.length; ++i) {
791
+ const xi = x[2 * i];
792
+ const yi = x[2 * i + 1];
793
+ for (let j = i + 1; j < distances.length; ++j) {
794
+ const xj = x[2 * j];
795
+ const yj = x[2 * j + 1];
796
+ const dij = distances[i][j];
797
+ const constraint = constraints[i][j];
798
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
799
+ const distance = Math.sqrt(squaredDistance);
800
+ const delta = squaredDistance - dij * dij;
801
+ if (constraint > 0 && distance <= dij || constraint < 0 && distance >= dij) {
802
+ continue;
803
+ }
804
+ loss += 2 * delta * delta;
805
+ fxprime[2 * i] += 4 * delta * (xi - xj);
806
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
807
+ fxprime[2 * j] += 4 * delta * (xj - xi);
808
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
809
+ }
810
+ }
811
+ return loss;
812
+ }
813
+
814
+ /**
815
+ * takes the best working variant of either constrained MDS or greedy
816
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
817
+ */
818
+ function bestInitialLayout(areas, params = {}) {
819
+ let initial = greedyLayout(areas, params);
820
+ const loss = params.lossFunction || lossFunction;
821
+
822
+ // greedylayout is sufficient for all 2/3 circle cases. try out
823
+ // constrained MDS for higher order problems, take its output
824
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
825
+ // since it axis aligns)
826
+ if (areas.length >= 8) {
827
+ const constrained = constrainedMDSLayout(areas, params);
828
+ const constrainedLoss = loss(constrained, areas);
829
+ const greedyLoss = loss(initial, areas);
830
+ if (constrainedLoss + 1e-8 < greedyLoss) {
831
+ initial = constrained;
832
+ }
833
+ }
834
+ return initial;
835
+ }
836
+
837
+ /**
838
+ * use the constrained MDS variant to generate an initial layout
839
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
840
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
841
+ */
842
+ function constrainedMDSLayout(areas, params = {}) {
843
+ const restarts = params.restarts || 10;
844
+
845
+ // bidirectionally map sets to a rowid (so we can create a matrix)
846
+ const sets = [];
847
+ const setids = {};
848
+ for (const area of areas) {
849
+ if (area.sets.length === 1) {
850
+ setids[area.sets[0]] = sets.length;
851
+ sets.push(area);
852
+ }
853
+ }
854
+ let {
855
+ distances,
856
+ constraints
857
+ } = getDistanceMatrices(areas, sets, setids);
858
+
859
+ // keep distances bounded, things get messed up otherwise.
860
+ // TODO: proper preconditioner?
861
+ const norm = norm2(distances.map(norm2)) / distances.length;
862
+ distances = distances.map(row => row.map(value => value / norm));
863
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
864
+ let best = null;
865
+ for (let i = 0; i < restarts; ++i) {
866
+ const initial = zeros(distances.length * 2).map(Math.random);
867
+ const current = conjugateGradient(obj, initial, params);
868
+ if (!best || current.fx < best.fx) {
869
+ best = current;
870
+ }
871
+ }
872
+ const positions = best.x;
873
+
874
+ // translate rows back to (x,y,radius) coordinates
875
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
876
+ const circles = {};
877
+ for (let i = 0; i < sets.length; ++i) {
878
+ const set = sets[i];
879
+ circles[set.sets[0]] = {
880
+ x: positions[2 * i] * norm,
881
+ y: positions[2 * i + 1] * norm,
882
+ radius: Math.sqrt(set.size / Math.PI)
883
+ };
884
+ }
885
+ if (params.history) {
886
+ for (const h of params.history) {
887
+ scale(h.x, norm);
888
+ }
889
+ }
890
+ return circles;
891
+ }
892
+
893
+ /**
894
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
895
+ * least overlapped, attempting to position each new set such that the
896
+ * overlapping areas to already positioned sets are basically right
897
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>}>} areas
898
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
899
+ */
900
+ function greedyLayout(areas, params) {
901
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
902
+
903
+ // define a circle for each set
904
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
905
+ const circles = {};
906
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
907
+ const setOverlaps = {};
908
+ for (const area of areas) {
909
+ if (area.sets.length === 1) {
910
+ const set = area.sets[0];
911
+ circles[set] = {
912
+ x: 1e10,
913
+ y: 1e10,
914
+ rowid: circles.length,
915
+ size: area.size,
916
+ radius: Math.sqrt(area.size / Math.PI)
917
+ };
918
+ setOverlaps[set] = [];
919
+ }
920
+ }
921
+ areas = areas.filter(a => a.sets.length === 2);
922
+
923
+ // map each set to a list of all the other sets that overlap it
924
+ for (const current of areas) {
925
+ let weight = current.weight != null ? current.weight : 1.0;
926
+ const left = current.sets[0];
927
+ const right = current.sets[1];
928
+
929
+ // completely overlapped circles shouldn't be positioned early here
930
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
931
+ weight = 0;
932
+ }
933
+ setOverlaps[left].push({
934
+ set: right,
935
+ size: current.size,
936
+ weight
937
+ });
938
+ setOverlaps[right].push({
939
+ set: left,
940
+ size: current.size,
941
+ weight
942
+ });
943
+ }
944
+
945
+ // get list of most overlapped sets
946
+ const mostOverlapped = [];
947
+ Object.keys(setOverlaps).forEach(set => {
948
+ let size = 0;
949
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
950
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
951
+ }
952
+ mostOverlapped.push({
953
+ set,
954
+ size
955
+ });
956
+ });
957
+
958
+ // sort by size desc
959
+ function sortOrder(a, b) {
960
+ return b.size - a.size;
961
+ }
962
+ mostOverlapped.sort(sortOrder);
963
+
964
+ // keep track of what sets have been laid out
965
+ const positioned = {};
966
+ function isPositioned(element) {
967
+ return element.set in positioned;
968
+ }
969
+
970
+ /**
971
+ * adds a point to the output
972
+ * @param {{x: number, y: number}} point
973
+ * @param {number} index
974
+ */
975
+ function positionSet(point, index) {
976
+ circles[index].x = point.x;
977
+ circles[index].y = point.y;
978
+ positioned[index] = true;
979
+ }
980
+
981
+ // add most overlapped set at (0,0)
982
+ positionSet({
983
+ x: 0,
984
+ y: 0
985
+ }, mostOverlapped[0].set);
986
+
987
+ // get distances between all points. TODO, necessary?
988
+ // answer: probably not
989
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
990
+ for (let i = 1; i < mostOverlapped.length; ++i) {
991
+ const setIndex = mostOverlapped[i].set;
992
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
993
+ const set = circles[setIndex];
994
+ overlap.sort(sortOrder);
995
+ if (overlap.length === 0) {
996
+ // this shouldn't happen anymore with addMissingAreas
997
+ throw 'ERROR: missing pairwise overlap information';
998
+ }
999
+
1000
+ /** @type {{x: number, y: number}[]} */
1001
+ const points = [];
1002
+ for (var j = 0; j < overlap.length; ++j) {
1003
+ // get appropriate distance from most overlapped already added set
1004
+ const p1 = circles[overlap[j].set];
1005
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
1006
+
1007
+ // sample positions at 90 degrees for maximum aesthetics
1008
+ points.push({
1009
+ x: p1.x + d1,
1010
+ y: p1.y
1011
+ });
1012
+ points.push({
1013
+ x: p1.x - d1,
1014
+ y: p1.y
1015
+ });
1016
+ points.push({
1017
+ y: p1.y + d1,
1018
+ x: p1.x
1019
+ });
1020
+ points.push({
1021
+ y: p1.y - d1,
1022
+ x: p1.x
1023
+ });
1024
+
1025
+ // if we have at least 2 overlaps, then figure out where the
1026
+ // set should be positioned analytically and try those too
1027
+ for (let k = j + 1; k < overlap.length; ++k) {
1028
+ const p2 = circles[overlap[k].set];
1029
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
1030
+ const extraPoints = circleCircleIntersection({
1031
+ x: p1.x,
1032
+ y: p1.y,
1033
+ radius: d1
1034
+ }, {
1035
+ x: p2.x,
1036
+ y: p2.y,
1037
+ radius: d2
1038
+ });
1039
+ points.push(...extraPoints);
1040
+ }
1041
+ }
1042
+
1043
+ // we have some candidate positions for the set, examine loss
1044
+ // at each position to figure out where to put it at
1045
+ let bestLoss = 1e50;
1046
+ let bestPoint = points[0];
1047
+ for (const point of points) {
1048
+ circles[setIndex].x = point.x;
1049
+ circles[setIndex].y = point.y;
1050
+ const localLoss = loss(circles, areas);
1051
+ if (localLoss < bestLoss) {
1052
+ bestLoss = localLoss;
1053
+ bestPoint = point;
1054
+ }
1055
+ }
1056
+ positionSet(bestPoint, setIndex);
1057
+ }
1058
+ return circles;
1059
+ }
1060
+
1061
+ /**
1062
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
1063
+ * the distance from the actual overlaps to the desired overlaps. Note that
1064
+ * this method ignores overlaps of more than 2 circles
1065
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
1066
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>, weight?: number}>} overlaps
1067
+ * @returns {number}
1068
+ */
1069
+ function lossFunction(circles, overlaps) {
1070
+ let output = 0;
1071
+ for (const area of overlaps) {
1072
+ if (area.sets.length === 1) {
1073
+ continue;
1074
+ }
1075
+ /** @type {number} */
1076
+ let overlap;
1077
+ if (area.sets.length === 2) {
1078
+ const left = circles[area.sets[0]];
1079
+ const right = circles[area.sets[1]];
1080
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
1081
+ } else {
1082
+ overlap = intersectionArea(area.sets.map(d => circles[d]));
1083
+ }
1084
+ const weight = area.weight != null ? area.weight : 1.0;
1085
+ output += weight * (overlap - area.size) * (overlap - area.size);
1086
+ }
1087
+ return output;
1088
+ }
1089
+ function logRatioLossFunction(circles, overlaps) {
1090
+ let output = 0;
1091
+ for (const area of overlaps) {
1092
+ if (area.sets.length === 1) {
1093
+ continue;
1094
+ }
1095
+ /** @type {number} */
1096
+ let overlap;
1097
+ if (area.sets.length === 2) {
1098
+ const left = circles[area.sets[0]];
1099
+ const right = circles[area.sets[1]];
1100
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
1101
+ } else {
1102
+ overlap = intersectionArea(area.sets.map(d => circles[d]));
1103
+ }
1104
+ const weight = area.weight != null ? area.weight : 1.0;
1105
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
1106
+ output += weight * differenceFromIdeal * differenceFromIdeal;
1107
+ }
1108
+ return output;
1109
+ }
1110
+
1111
+ /**
1112
+ * orientates a bunch of circles to point in orientation
1113
+ * @param {{x :number, y: number, radius: number}[]} circles
1114
+ * @param {number | undefined} orientation
1115
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
1116
+ */
1117
+ function orientateCircles(circles, orientation, orientationOrder) {
1118
+ if (orientationOrder == null) {
1119
+ circles.sort((a, b) => b.radius - a.radius);
1120
+ } else {
1121
+ circles.sort(orientationOrder);
1122
+ }
1123
+
1124
+ // shift circles so largest circle is at (0, 0)
1125
+ if (circles.length > 0) {
1126
+ const largestX = circles[0].x;
1127
+ const largestY = circles[0].y;
1128
+ for (const circle of circles) {
1129
+ circle.x -= largestX;
1130
+ circle.y -= largestY;
1131
+ }
1132
+ }
1133
+ if (circles.length === 2) {
1134
+ // if the second circle is a subset of the first, arrange so that
1135
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
1136
+ const dist = distance(circles[0], circles[1]);
1137
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
1138
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
1139
+ circles[1].y = circles[0].y;
1140
+ }
1141
+ }
1142
+
1143
+ // rotate circles so that second largest is at an angle of 'orientation'
1144
+ // from largest
1145
+ if (circles.length > 1) {
1146
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
1147
+ const c = Math.cos(rotation);
1148
+ const s = Math.sin(rotation);
1149
+ for (const circle of circles) {
1150
+ const x = circle.x;
1151
+ const y = circle.y;
1152
+ circle.x = c * x - s * y;
1153
+ circle.y = s * x + c * y;
1154
+ }
1155
+ }
1156
+
1157
+ // mirror solution if third solution is above plane specified by
1158
+ // first two circles
1159
+ if (circles.length > 2) {
1160
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
1161
+ while (angle < 0) {
1162
+ angle += 2 * Math.PI;
1163
+ }
1164
+ while (angle > 2 * Math.PI) {
1165
+ angle -= 2 * Math.PI;
1166
+ }
1167
+ if (angle > Math.PI) {
1168
+ const slope = circles[1].y / (1e-10 + circles[1].x);
1169
+ for (const circle of circles) {
1170
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
1171
+ circle.x = 2 * d - circle.x;
1172
+ circle.y = 2 * d * slope - circle.y;
1173
+ }
1174
+ }
1175
+ }
1176
+ }
1177
+
1178
+ /**
1179
+ *
1180
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
1181
+ * @returns {{x: number, y: number, radius: number}[][]}
1182
+ */
1183
+ function disjointCluster(circles) {
1184
+ // union-find clustering to get disjoint sets
1185
+ circles.forEach(circle => {
1186
+ circle.parent = circle;
1187
+ });
1188
+
1189
+ // path compression step in union find
1190
+ function find(circle) {
1191
+ if (circle.parent !== circle) {
1192
+ circle.parent = find(circle.parent);
1193
+ }
1194
+ return circle.parent;
1195
+ }
1196
+ function union(x, y) {
1197
+ const xRoot = find(x);
1198
+ const yRoot = find(y);
1199
+ xRoot.parent = yRoot;
1200
+ }
1201
+
1202
+ // get the union of all overlapping sets
1203
+ for (let i = 0; i < circles.length; ++i) {
1204
+ for (let j = i + 1; j < circles.length; ++j) {
1205
+ const maxDistance = circles[i].radius + circles[j].radius;
1206
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
1207
+ union(circles[j], circles[i]);
1208
+ }
1209
+ }
1210
+ }
1211
+
1212
+ // find all the disjoint clusters and group them together
1213
+ /** @type {Map<string, {x: number, y: number, radius: number}[]>} */
1214
+ const disjointClusters = new Map();
1215
+ for (let i = 0; i < circles.length; ++i) {
1216
+ const setid = find(circles[i]).parent.setid;
1217
+ if (!disjointClusters.has(setid)) {
1218
+ disjointClusters.set(setid, []);
1219
+ }
1220
+ disjointClusters.get(setid).push(circles[i]);
1221
+ }
1222
+
1223
+ // cleanup bookkeeping
1224
+ circles.forEach(circle => {
1225
+ delete circle.parent;
1226
+ });
1227
+
1228
+ // return in more usable form
1229
+ return Array.from(disjointClusters.values());
1230
+ }
1231
+
1232
+ /**
1233
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
1234
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
1235
+ */
1236
+ function getBoundingBox(circles) {
1237
+ const minMax = d => {
1238
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
1239
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
1240
+ return {
1241
+ max: hi,
1242
+ min: lo
1243
+ };
1244
+ };
1245
+ return {
1246
+ xRange: minMax('x'),
1247
+ yRange: minMax('y')
1248
+ };
1249
+ }
1250
+
1251
+ /**
1252
+ *
1253
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1254
+ * @param {undefined | number} orientation
1255
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
1256
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
1257
+ */
1258
+ function normalizeSolution(solution, orientation, orientationOrder) {
1259
+ if (orientation == null) {
1260
+ orientation = Math.PI / 2;
1261
+ }
1262
+
1263
+ // work with a list instead of a dictionary, and take a copy so we
1264
+ // don't mutate input
1265
+ let circles = fromObjectNotation(solution).map(d => Object.assign({}, d));
1266
+
1267
+ // get all the disjoint clusters
1268
+ const clusters = disjointCluster(circles);
1269
+
1270
+ // orientate all disjoint sets, get sizes
1271
+ for (const cluster of clusters) {
1272
+ orientateCircles(cluster, orientation, orientationOrder);
1273
+ const bounds = getBoundingBox(cluster);
1274
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
1275
+ cluster.bounds = bounds;
1276
+ }
1277
+ clusters.sort((a, b) => b.size - a.size);
1278
+
1279
+ // orientate the largest at 0,0, and get the bounds
1280
+ circles = clusters[0];
1281
+ let returnBounds = circles.bounds;
1282
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
1283
+
1284
+ /**
1285
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
1286
+ * @param {boolean} right
1287
+ * @param {boolean} bottom
1288
+ */
1289
+ function addCluster(cluster, right, bottom) {
1290
+ if (!cluster) {
1291
+ return;
1292
+ }
1293
+ const bounds = cluster.bounds;
1294
+ /** @type {number} */
1295
+ let xOffset;
1296
+ /** @type {number} */
1297
+ let yOffset;
1298
+ if (right) {
1299
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
1300
+ } else {
1301
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
1302
+ const centreing = (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
1303
+ if (centreing < 0) {
1304
+ xOffset += centreing;
1305
+ }
1306
+ }
1307
+ if (bottom) {
1308
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
1309
+ } else {
1310
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
1311
+ const centreing = (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
1312
+ if (centreing < 0) {
1313
+ yOffset += centreing;
1314
+ }
1315
+ }
1316
+ for (const c of cluster) {
1317
+ c.x += xOffset;
1318
+ c.y += yOffset;
1319
+ circles.push(c);
1320
+ }
1321
+ }
1322
+ let index = 1;
1323
+ while (index < clusters.length) {
1324
+ addCluster(clusters[index], true, false);
1325
+ addCluster(clusters[index + 1], false, true);
1326
+ addCluster(clusters[index + 2], true, true);
1327
+ index += 3;
1328
+
1329
+ // have one cluster (in top left). lay out next three relative
1330
+ // to it in a grid
1331
+ returnBounds = getBoundingBox(circles);
1332
+ }
1333
+
1334
+ // convert back to solution form
1335
+ return toObjectNotation(circles);
1336
+ }
1337
+
1338
+ /**
1339
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
1340
+ * a rectangle of width/height - with padding around the borders. also
1341
+ * centers the diagram in the available space at the same time.
1342
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
1343
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1344
+ * @param {number} width
1345
+ * @param {number} height
1346
+ * @param {number} padding
1347
+ * @param {boolean} scaleToFit
1348
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
1349
+ */
1350
+ function scaleSolution(solution, width, height, padding, scaleToFit) {
1351
+ const circles = fromObjectNotation(solution);
1352
+ width -= 2 * padding;
1353
+ height -= 2 * padding;
1354
+ const {
1355
+ xRange,
1356
+ yRange
1357
+ } = getBoundingBox(circles);
1358
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
1359
+ console.log('not scaling solution: zero size detected');
1360
+ return solution;
1361
+ }
1362
+
1363
+ /** @type {number} */
1364
+ let xScaling;
1365
+ /** @type {number} */
1366
+ let yScaling;
1367
+ if (scaleToFit) {
1368
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
1369
+ xScaling = width / toScaleDiameter;
1370
+ yScaling = height / toScaleDiameter;
1371
+ } else {
1372
+ xScaling = width / (xRange.max - xRange.min);
1373
+ yScaling = height / (yRange.max - yRange.min);
1374
+ }
1375
+ const scaling = Math.min(yScaling, xScaling);
1376
+ // while we're at it, center the diagram too
1377
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
1378
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
1379
+ return toObjectNotation(circles.map(circle => ({
1380
+ radius: scaling * circle.radius,
1381
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
1382
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
1383
+ setid: circle.setid
1384
+ })));
1385
+ }
1386
+
1387
+ /**
1388
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
1389
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
1390
+ */
1391
+ function toObjectNotation(circles) {
1392
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
1393
+ const r = {};
1394
+ for (const circle of circles) {
1395
+ r[circle.setid] = circle;
1396
+ }
1397
+ return r;
1398
+ }
1399
+ /**
1400
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
1401
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
1402
+ */
1403
+ function fromObjectNotation(solution) {
1404
+ const setids = Object.keys(solution);
1405
+ return setids.map(id => Object.assign(solution[id], {
1406
+ setid: id
1407
+ }));
1408
+ }
1409
+
1410
+ /**
1411
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
1412
+ *
1413
+ * `colourScheme: Array<String>`
1414
+ * A list of color values to be applied when coloring diagram circles.
1415
+ *
1416
+ * `symmetricalTextCentre: Boolean`
1417
+ * Whether to symmetrically center each circle's text horizontally and vertically.
1418
+ * Defaults to `false`.
1419
+ *
1420
+ * `textFill: String`
1421
+ * The color to be applied to the text within each circle.
1422
+ *
1423
+ * @param {object} options
1424
+ */
1425
+ function VennDiagram(options = {}) {
1426
+ let useViewBox = false,
1427
+ width = 600,
1428
+ height = 350,
1429
+ padding = 15,
1430
+ duration = 1000,
1431
+ orientation = Math.PI / 2,
1432
+ normalize = true,
1433
+ scaleToFit = null,
1434
+ wrap = true,
1435
+ styled = true,
1436
+ fontSize = null,
1437
+ orientationOrder = null,
1438
+ distinct = false,
1439
+ round = null,
1440
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
1441
+ // mimic the behaviour of d3.scale.category10 from the previous
1442
+ // version of d3
1443
+ colourMap = {},
1444
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
1445
+ // since we can support older versions of d3 as long as we don't force this,
1446
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
1447
+ colourScheme = options && options.colourScheme ? options.colourScheme : options && options.colorScheme ? options.colorScheme : ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'],
1448
+ colourIndex = 0,
1449
+ colours = function (key) {
1450
+ if (key in colourMap) {
1451
+ return colourMap[key];
1452
+ }
1453
+ var ret = colourMap[key] = colourScheme[colourIndex];
1454
+ colourIndex += 1;
1455
+ if (colourIndex >= colourScheme.length) {
1456
+ colourIndex = 0;
1457
+ }
1458
+ return ret;
1459
+ },
1460
+ layoutFunction = venn,
1461
+ loss = lossFunction;
1462
+ function chart(selection) {
1463
+ let data = selection.datum();
1464
+
1465
+ // handle 0-sized sets by removing from input
1466
+ const toRemove = new Set();
1467
+ data.forEach(datum => {
1468
+ if (datum.size == 0 && datum.sets.length == 1) {
1469
+ toRemove.add(datum.sets[0]);
1470
+ }
1471
+ });
1472
+ data = data.filter(datum => !datum.sets.some(set => toRemove.has(set)));
1473
+ let circles = {};
1474
+ let textCentres = {};
1475
+ if (data.length > 0) {
1476
+ let solution = layoutFunction(data, {
1477
+ lossFunction: loss,
1478
+ distinct
1479
+ });
1480
+ if (normalize) {
1481
+ solution = normalizeSolution(solution, orientation, orientationOrder);
1482
+ }
1483
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
1484
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
1485
+ }
1486
+
1487
+ // Figure out the current label for each set. These can change
1488
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
1489
+ const labels = {};
1490
+ data.forEach(datum => {
1491
+ if (datum.label) {
1492
+ labels[datum.sets] = datum.label;
1493
+ }
1494
+ });
1495
+ function label(d) {
1496
+ if (d.sets in labels) {
1497
+ return labels[d.sets];
1498
+ }
1499
+ if (d.sets.length == 1) {
1500
+ return '' + d.sets[0];
1501
+ }
1502
+ }
1503
+
1504
+ // create svg if not already existing
1505
+ selection.selectAll('svg').data([circles]).enter().append('svg');
1506
+ const svg = selection.select('svg');
1507
+ if (useViewBox) {
1508
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
1509
+ } else {
1510
+ svg.attr('width', width).attr('height', height);
1511
+ }
1512
+
1513
+ // to properly transition intersection areas, we need the
1514
+ // previous circles locations. load from elements
1515
+ const previous = {};
1516
+ let hasPrevious = false;
1517
+ svg.selectAll('.venn-area path').each(function (d) {
1518
+ const path = this.getAttribute('d');
1519
+ if (d.sets.length == 1 && path && !distinct) {
1520
+ hasPrevious = true;
1521
+ previous[d.sets[0]] = circleFromPath(path);
1522
+ }
1523
+ });
1524
+ // interpolate intersection area paths between previous and
1525
+ // current paths
1526
+ function pathTween(d) {
1527
+ return t => {
1528
+ const c = d.sets.map(set => {
1529
+ let start = previous[set];
1530
+ let end = circles[set];
1531
+ if (!start) {
1532
+ start = {
1533
+ x: width / 2,
1534
+ y: height / 2,
1535
+ radius: 1
1536
+ };
1537
+ }
1538
+ if (!end) {
1539
+ end = {
1540
+ x: width / 2,
1541
+ y: height / 2,
1542
+ radius: 1
1543
+ };
1544
+ }
1545
+ return {
1546
+ x: start.x * (1 - t) + end.x * t,
1547
+ y: start.y * (1 - t) + end.y * t,
1548
+ radius: start.radius * (1 - t) + end.radius * t
1549
+ };
1550
+ });
1551
+ return intersectionAreaPath(c, round);
1552
+ };
1553
+ }
1554
+
1555
+ // update data, joining on the set ids
1556
+ const nodes = svg.selectAll('.venn-area').data(data, d => d.sets);
1557
+
1558
+ // create new nodes
1559
+ 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('_'));
1560
+ const enterPath = enter.append('path');
1561
+ 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);
1562
+
1563
+ // apply minimal style if wanted
1564
+ if (styled) {
1565
+ 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');
1566
+ enterText.style('fill', d => {
1567
+ if (d.colour || d.color) {
1568
+ return '#FFF';
1569
+ }
1570
+ if (options.textFill) {
1571
+ return options.textFill;
1572
+ }
1573
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
1574
+ });
1575
+ }
1576
+ function asTransition(s) {
1577
+ if (typeof s.transition === 'function') {
1578
+ return s.transition('venn').duration(duration);
1579
+ }
1580
+ return s;
1581
+ }
1582
+
1583
+ // update existing, using pathTween if necessary
1584
+ let update = selection;
1585
+ if (hasPrevious && typeof update.transition === 'function') {
1586
+ update = asTransition(selection);
1587
+ update.selectAll('path').attrTween('d', pathTween);
1588
+ } else {
1589
+ update.selectAll('path').attr('d', d => intersectionAreaPath(d.sets.map(set => circles[set])), round);
1590
+ }
1591
+ 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));
1592
+ if (wrap) {
1593
+ if (hasPrevious) {
1594
+ // d3 4.0 uses 'on' for events on transitions,
1595
+ // but d3 3.0 used 'each' instead. switch appropriately
1596
+ if ('on' in updateText) {
1597
+ updateText.on('end', wrapText(circles, label));
1598
+ } else {
1599
+ updateText.each('end', wrapText(circles, label));
1600
+ }
1601
+ } else {
1602
+ updateText.each(wrapText(circles, label));
1603
+ }
1604
+ }
1605
+
1606
+ // remove old
1607
+ const exit = asTransition(nodes.exit()).remove();
1608
+ if (typeof nodes.transition === 'function') {
1609
+ exit.selectAll('path').attrTween('d', pathTween);
1610
+ }
1611
+ const exitText = exit.selectAll('text').attr('x', width / 2).attr('y', height / 2);
1612
+
1613
+ // if we've been passed a fontSize explicitly, use it to
1614
+ // transition
1615
+ if (fontSize !== null) {
1616
+ enterText.style('font-size', '0px');
1617
+ updateText.style('font-size', fontSize);
1618
+ exitText.style('font-size', '0px');
1619
+ }
1620
+ return {
1621
+ circles,
1622
+ textCentres,
1623
+ nodes,
1624
+ enter,
1625
+ update,
1626
+ exit
1627
+ };
1628
+ }
1629
+ chart.wrap = function (_) {
1630
+ if (!arguments.length) return wrap;
1631
+ wrap = _;
1632
+ return chart;
1633
+ };
1634
+ chart.useViewBox = function () {
1635
+ useViewBox = true;
1636
+ return chart;
1637
+ };
1638
+ chart.width = function (_) {
1639
+ if (!arguments.length) return width;
1640
+ width = _;
1641
+ return chart;
1642
+ };
1643
+ chart.height = function (_) {
1644
+ if (!arguments.length) return height;
1645
+ height = _;
1646
+ return chart;
1647
+ };
1648
+ chart.padding = function (_) {
1649
+ if (!arguments.length) return padding;
1650
+ padding = _;
1651
+ return chart;
1652
+ };
1653
+ chart.distinct = function (_) {
1654
+ if (!arguments.length) return distinct;
1655
+ distinct = _;
1656
+ return chart;
1657
+ };
1658
+ chart.colours = function (_) {
1659
+ if (!arguments.length) return colours;
1660
+ colours = _;
1661
+ return chart;
1662
+ };
1663
+ chart.colors = function (_) {
1664
+ if (!arguments.length) return colours;
1665
+ colours = _;
1666
+ return chart;
1667
+ };
1668
+ chart.fontSize = function (_) {
1669
+ if (!arguments.length) return fontSize;
1670
+ fontSize = _;
1671
+ return chart;
1672
+ };
1673
+ chart.round = function (_) {
1674
+ if (!arguments.length) return round;
1675
+ round = _;
1676
+ return chart;
1677
+ };
1678
+ chart.duration = function (_) {
1679
+ if (!arguments.length) return duration;
1680
+ duration = _;
1681
+ return chart;
1682
+ };
1683
+ chart.layoutFunction = function (_) {
1684
+ if (!arguments.length) return layoutFunction;
1685
+ layoutFunction = _;
1686
+ return chart;
1687
+ };
1688
+ chart.normalize = function (_) {
1689
+ if (!arguments.length) return normalize;
1690
+ normalize = _;
1691
+ return chart;
1692
+ };
1693
+ chart.scaleToFit = function (_) {
1694
+ if (!arguments.length) return scaleToFit;
1695
+ scaleToFit = _;
1696
+ return chart;
1697
+ };
1698
+ chart.styled = function (_) {
1699
+ if (!arguments.length) return styled;
1700
+ styled = _;
1701
+ return chart;
1702
+ };
1703
+ chart.orientation = function (_) {
1704
+ if (!arguments.length) return orientation;
1705
+ orientation = _;
1706
+ return chart;
1707
+ };
1708
+ chart.orientationOrder = function (_) {
1709
+ if (!arguments.length) return orientationOrder;
1710
+ orientationOrder = _;
1711
+ return chart;
1712
+ };
1713
+ chart.lossFunction = function (_) {
1714
+ if (!arguments.length) return loss;
1715
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
1716
+ return chart;
1717
+ };
1718
+ return chart;
1719
+ }
1720
+
1721
+ // sometimes text doesn't fit inside the circle, if thats the case lets wrap
1722
+ // the text here such that it fits
1723
+ // todo: looks like this might be merged into d3 (
1724
+ // https://github.com/mbostock/d3/issues/1642),
1725
+ // also worth checking out is
1726
+ // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
1727
+ // this seems to be one of those things that should be easy but isn't
1728
+ function wrapText(circles, labeller) {
1729
+ return function (data) {
1730
+ const text = this;
1731
+ const width = circles[data.sets[0]].radius || 50;
1732
+ const label = labeller(data) || '';
1733
+ const words = label.split(/\s+/).reverse();
1734
+ const maxLines = 3;
1735
+ const minChars = (label.length + words.length) / maxLines;
1736
+ let word = words.pop();
1737
+ let line = [word];
1738
+ let lineNumber = 0;
1739
+ const lineHeight = 1.1; // ems
1740
+ text.textContent = null; // clear
1741
+ const tspans = [];
1742
+ function append(word) {
1743
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
1744
+ tspan.textContent = word;
1745
+ tspans.push(tspan);
1746
+ text.append(tspan);
1747
+ return tspan;
1748
+ }
1749
+ let tspan = append(word);
1750
+ while (true) {
1751
+ word = words.pop();
1752
+ if (!word) {
1753
+ break;
1754
+ }
1755
+ line.push(word);
1756
+ const joined = line.join(' ');
1757
+ tspan.textContent = joined;
1758
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
1759
+ line.pop();
1760
+ tspan.textContent = line.join(' ');
1761
+ line = [word];
1762
+ tspan = append(word);
1763
+ lineNumber++;
1764
+ }
1765
+ }
1766
+ const initial = 0.35 - lineNumber * lineHeight / 2;
1767
+ const x = text.getAttribute('x');
1768
+ const y = text.getAttribute('y');
1769
+ tspans.forEach((t, i) => {
1770
+ t.setAttribute('x', x);
1771
+ t.setAttribute('y', y);
1772
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
1773
+ });
1774
+ };
1775
+ }
1776
+
1777
+ /**
1778
+ *
1779
+ * @param {{x: number, y: number}} current
1780
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
1781
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
1782
+ * @returns {number}
1783
+ */
1784
+ function circleMargin(current, interior, exterior) {
1785
+ let margin = interior[0].radius - distance(interior[0], current);
1786
+ for (let i = 1; i < interior.length; ++i) {
1787
+ const m = interior[i].radius - distance(interior[i], current);
1788
+ if (m <= margin) {
1789
+ margin = m;
1790
+ }
1791
+ }
1792
+ for (let i = 0; i < exterior.length; ++i) {
1793
+ const m = distance(exterior[i], current) - exterior[i].radius;
1794
+ if (m <= margin) {
1795
+ margin = m;
1796
+ }
1797
+ }
1798
+ return margin;
1799
+ }
1800
+
1801
+ /**
1802
+ * compute the center of some circles by maximizing the margin of
1803
+ * the center point relative to the circles (interior) after subtracting
1804
+ * nearby circles (exterior)
1805
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
1806
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
1807
+ * @param {boolean} symmetricalTextCentre
1808
+ * @returns {{x:number, y: number}}
1809
+ */
1810
+ function computeTextCentre(interior, exterior, symmetricalTextCentre) {
1811
+ // get an initial estimate by sampling around the interior circles
1812
+ // and taking the point with the biggest margin
1813
+ /** @type {{x: number, y: number}[]} */
1814
+ const points = [];
1815
+ for (const c of interior) {
1816
+ points.push({
1817
+ x: c.x,
1818
+ y: c.y
1819
+ });
1820
+ points.push({
1821
+ x: c.x + c.radius / 2,
1822
+ y: c.y
1823
+ });
1824
+ points.push({
1825
+ x: c.x - c.radius / 2,
1826
+ y: c.y
1827
+ });
1828
+ points.push({
1829
+ x: c.x,
1830
+ y: c.y + c.radius / 2
1831
+ });
1832
+ points.push({
1833
+ x: c.x,
1834
+ y: c.y - c.radius / 2
1835
+ });
1836
+ }
1837
+ let initial = points[0];
1838
+ let margin = circleMargin(points[0], interior, exterior);
1839
+ for (let i = 1; i < points.length; ++i) {
1840
+ const m = circleMargin(points[i], interior, exterior);
1841
+ if (m >= margin) {
1842
+ initial = points[i];
1843
+ margin = m;
1844
+ }
1845
+ }
1846
+
1847
+ // maximize the margin numerically
1848
+ const solution = nelderMead(p => -1 * circleMargin({
1849
+ x: p[0],
1850
+ y: p[1]
1851
+ }, interior, exterior), [initial.x, initial.y], {
1852
+ maxIterations: 500,
1853
+ minErrorDelta: 1e-10
1854
+ }).x;
1855
+ const ret = {
1856
+ x: symmetricalTextCentre ? 0 : solution[0],
1857
+ y: solution[1]
1858
+ };
1859
+
1860
+ // check solution, fallback as needed (happens if fully overlapped
1861
+ // etc)
1862
+ let valid = true;
1863
+ for (const i of interior) {
1864
+ if (distance(ret, i) > i.radius) {
1865
+ valid = false;
1866
+ break;
1867
+ }
1868
+ }
1869
+ for (const e of exterior) {
1870
+ if (distance(ret, e) < e.radius) {
1871
+ valid = false;
1872
+ break;
1873
+ }
1874
+ }
1875
+ if (valid) {
1876
+ return ret;
1877
+ }
1878
+ if (interior.length == 1) {
1879
+ return {
1880
+ x: interior[0].x,
1881
+ y: interior[0].y
1882
+ };
1883
+ }
1884
+ const areaStats = {};
1885
+ intersectionArea(interior, areaStats);
1886
+ if (areaStats.arcs.length === 0) {
1887
+ return {
1888
+ x: 0,
1889
+ y: -1000,
1890
+ disjoint: true
1891
+ };
1892
+ }
1893
+ if (areaStats.arcs.length == 1) {
1894
+ return {
1895
+ x: areaStats.arcs[0].circle.x,
1896
+ y: areaStats.arcs[0].circle.y
1897
+ };
1898
+ }
1899
+ if (exterior.length) {
1900
+ // try again without other circles
1901
+ return computeTextCentre(interior, []);
1902
+ }
1903
+ // take average of all the points in the intersection
1904
+ // polygon. this should basically never happen
1905
+ // and has some issues:
1906
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
1907
+ return getCenter(areaStats.arcs.map(a => a.p1));
1908
+ }
1909
+
1910
+ // given a dictionary of {setid : circle}, returns
1911
+ // a dictionary of setid to list of circles that completely overlap it
1912
+ function getOverlappingCircles(circles) {
1913
+ const ret = {};
1914
+ const circleids = Object.keys(circles);
1915
+ for (const circleid of circleids) {
1916
+ ret[circleid] = [];
1917
+ }
1918
+ for (let i = 0; i < circleids.length; i++) {
1919
+ const ci = circleids[i];
1920
+ const a = circles[ci];
1921
+ for (let j = i + 1; j < circleids.length; ++j) {
1922
+ const cj = circleids[j];
1923
+ const b = circles[cj];
1924
+ const d = distance(a, b);
1925
+ if (d + b.radius <= a.radius + 1e-10) {
1926
+ ret[cj].push(ci);
1927
+ } else if (d + a.radius <= b.radius + 1e-10) {
1928
+ ret[ci].push(cj);
1929
+ }
1930
+ }
1931
+ }
1932
+ return ret;
1933
+ }
1934
+ function computeTextCentres(circles, areas, symmetricalTextCentre) {
1935
+ const ret = {};
1936
+ const overlapped = getOverlappingCircles(circles);
1937
+ for (let i = 0; i < areas.length; ++i) {
1938
+ const area = areas[i].sets;
1939
+ const areaids = {};
1940
+ const exclude = {};
1941
+ for (let j = 0; j < area.length; ++j) {
1942
+ areaids[area[j]] = true;
1943
+ const overlaps = overlapped[area[j]];
1944
+ // keep track of any circles that overlap this area,
1945
+ // and don't consider for purposes of computing the text
1946
+ // centre
1947
+ for (let k = 0; k < overlaps.length; ++k) {
1948
+ exclude[overlaps[k]] = true;
1949
+ }
1950
+ }
1951
+ const interior = [];
1952
+ const exterior = [];
1953
+ for (let setid in circles) {
1954
+ if (setid in areaids) {
1955
+ interior.push(circles[setid]);
1956
+ } else if (!(setid in exclude)) {
1957
+ exterior.push(circles[setid]);
1958
+ }
1959
+ }
1960
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
1961
+ ret[area] = centre;
1962
+ if (centre.disjoint && areas[i].size > 0) {
1963
+ console.log('WARNING: area ' + area + ' not represented on screen');
1964
+ }
1965
+ }
1966
+ return ret;
1967
+ }
1968
+
1969
+ // sorts all areas in the venn diagram, so that
1970
+ // a particular area is on top (relativeTo) - and
1971
+ // all other areas are so that the smallest areas are on top
1972
+ function sortAreas(div, relativeTo) {
1973
+ // figure out sets that are completely overlapped by relativeTo
1974
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
1975
+ const exclude = new Set();
1976
+ for (const check of relativeTo.sets) {
1977
+ for (let setid in overlaps) {
1978
+ const overlap = overlaps[setid];
1979
+ for (let j = 0; j < overlap.length; ++j) {
1980
+ if (overlap[j] == check) {
1981
+ exclude.add(setid);
1982
+ break;
1983
+ }
1984
+ }
1985
+ }
1986
+ }
1987
+
1988
+ // checks that all sets are in exclude;
1989
+ function shouldExclude(sets) {
1990
+ return sets.every(set => !exclude.has(set));
1991
+ }
1992
+
1993
+ // need to sort div's so that Z order is correct
1994
+ div.selectAll('g').sort((a, b) => {
1995
+ // highest order set intersections first
1996
+ if (a.sets.length != b.sets.length) {
1997
+ return a.sets.length - b.sets.length;
1998
+ }
1999
+ if (a == relativeTo) {
2000
+ return shouldExclude(b.sets) ? -1 : 1;
2001
+ }
2002
+ if (b == relativeTo) {
2003
+ return shouldExclude(a.sets) ? 1 : -1;
2004
+ }
2005
+
2006
+ // finally by size
2007
+ return b.size - a.size;
2008
+ });
2009
+ }
2010
+
2011
+ /**
2012
+ * @param {number} x
2013
+ * @param {number} y
2014
+ * @param {number} r
2015
+ * @returns {string}
2016
+ */
2017
+ function circlePath(x, y, r) {
2018
+ const ret = [];
2019
+ ret.push('\nM', x, y);
2020
+ ret.push('\nm', -r, 0);
2021
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
2022
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
2023
+ return ret.join(' ');
2024
+ }
2025
+
2026
+ /**
2027
+ * inverse of the circlePath function, returns a circle object from an svg path
2028
+ * @param {string} path
2029
+ * @returns {{x: number, y: number, radius: number}}
2030
+ */
2031
+ function circleFromPath(path) {
2032
+ const tokens = path.split(' ');
2033
+ return {
2034
+ x: Number.parseFloat(tokens[1]),
2035
+ y: Number.parseFloat(tokens[2]),
2036
+ radius: -Number.parseFloat(tokens[4])
2037
+ };
2038
+ }
2039
+ function intersectionAreaArcs(circles) {
2040
+ if (circles.length === 0) {
2041
+ return [];
2042
+ }
2043
+ const stats = {};
2044
+ intersectionArea(circles, stats);
2045
+ return stats.arcs;
2046
+ }
2047
+ function arcsToPath(arcs, round) {
2048
+ if (arcs.length === 0) {
2049
+ return 'M 0 0';
2050
+ }
2051
+ const rFactor = Math.pow(10, round || 0);
2052
+ const r = round != null ? v => Math.round(v * rFactor) / rFactor : v => v;
2053
+ if (arcs.length == 1) {
2054
+ const circle = arcs[0].circle;
2055
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
2056
+ }
2057
+ // draw path around arcs
2058
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
2059
+ for (const arc of arcs) {
2060
+ const radius = r(arc.circle.radius);
2061
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
2062
+ }
2063
+ return ret.join(' ');
2064
+ }
2065
+
2066
+ /**
2067
+ * returns a svg path of the intersection area of a bunch of circles
2068
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
2069
+ * @returns {string}
2070
+ */
2071
+ function intersectionAreaPath(circles, round) {
2072
+ return arcsToPath(intersectionAreaArcs(circles), round);
2073
+ }
2074
+ function layout(data, options = {}) {
2075
+ const {
2076
+ lossFunction: loss,
2077
+ layoutFunction: layout = venn,
2078
+ normalize = true,
2079
+ orientation = Math.PI / 2,
2080
+ orientationOrder,
2081
+ width = 600,
2082
+ height = 350,
2083
+ padding = 15,
2084
+ scaleToFit = false,
2085
+ symmetricalTextCentre = false,
2086
+ distinct,
2087
+ round = 2
2088
+ } = options;
2089
+ let solution = layout(data, {
2090
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
2091
+ distinct
2092
+ });
2093
+ if (normalize) {
2094
+ solution = normalizeSolution(solution, orientation, orientationOrder);
2095
+ }
2096
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
2097
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
2098
+ const circleLookup = new Map(Object.keys(circles).map(set => [set, {
2099
+ set,
2100
+ x: circles[set].x,
2101
+ y: circles[set].y,
2102
+ radius: circles[set].radius
2103
+ }]));
2104
+ const helpers = data.map(area => {
2105
+ const circles = area.sets.map(s => circleLookup.get(s));
2106
+ const arcs = intersectionAreaArcs(circles);
2107
+ const path = arcsToPath(arcs, round);
2108
+ return {
2109
+ circles,
2110
+ arcs,
2111
+ path,
2112
+ area,
2113
+ has: new Set(area.sets)
2114
+ };
2115
+ });
2116
+ function genDistinctPath(sets) {
2117
+ let r = '';
2118
+ for (const e of helpers) {
2119
+ if (e.has.size > sets.length && sets.every(s => e.has.has(s))) {
2120
+ r += ' ' + e.path;
2121
+ }
2122
+ }
2123
+ return r;
2124
+ }
2125
+ return helpers.map(({
2126
+ circles,
2127
+ arcs,
2128
+ path,
2129
+ area
2130
+ }) => {
2131
+ return {
2132
+ data: area,
2133
+ text: textCentres[area.sets],
2134
+ circles,
2135
+ arcs,
2136
+ path,
2137
+ distinctPath: path + genDistinctPath(area.sets)
2138
+ };
2139
+ });
2140
+ }
2141
+
2142
+ exports.VennDiagram = VennDiagram;
2143
+ exports.bestInitialLayout = bestInitialLayout;
2144
+ exports.circleArea = circleArea;
2145
+ exports.circleCircleIntersection = circleCircleIntersection;
2146
+ exports.circleFromPath = circleFromPath;
2147
+ exports.circleOverlap = circleOverlap;
2148
+ exports.circlePath = circlePath;
2149
+ exports.computeTextCentre = computeTextCentre;
2150
+ exports.computeTextCentres = computeTextCentres;
2151
+ exports.disjointCluster = disjointCluster;
2152
+ exports.distance = distance;
2153
+ exports.distanceFromIntersectArea = distanceFromIntersectArea;
2154
+ exports.greedyLayout = greedyLayout;
2155
+ exports.intersectionArea = intersectionArea;
2156
+ exports.intersectionAreaPath = intersectionAreaPath;
2157
+ exports.layout = layout;
2158
+ exports.logRatioLossFunction = logRatioLossFunction;
2159
+ exports.lossFunction = lossFunction;
2160
+ exports.normalizeSolution = normalizeSolution;
2161
+ exports.scaleSolution = scaleSolution;
2162
+ exports.sortAreas = sortAreas;
2163
+ exports.venn = venn;
2164
+ exports.wrapText = wrapText;
2165
+
2166
+ }));
tools/ui/node_modules/@upsetjs/venn.js/build/venn.min.js ADDED
@@ -0,0 +1 @@
 
 
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;n<t.length;++n)for(let s=n+1;s<t.length;++s){const r=i(t[n],t[s]);for(const t of r)t.parentIndex=[n,s],e.push(t)}return e}(t),l=o.filter((n=>function(t,n){return n.every((n=>r(t,n)<n.radius+e))}(n,t)));let c=0,u=0;const f=[];if(l.length>1){const e=a(l);for(let t=0;t<l.length;++t){const n=l[t];n.angle=Math.atan2(n.x-e.x,n.y-e.y)}l.sort(((t,e)=>e.angle-t.angle));let n=l[l.length-1];for(let e=0;e<l.length;++e){const o=l[e];u+=(n.x+o.x)*(o.y-n.y);const i={x:(o.x+n.x)/2,y:(o.y+n.y)/2};let a=null;for(let e=0;e<o.parentIndex.length;++e)if(n.parentIndex.includes(o.parentIndex[e])){const s=t[o.parentIndex[e]],l=Math.atan2(o.x-s.x,o.y-s.y),c=Math.atan2(n.x-s.x,n.y-s.y);let u=c-l;u<0&&(u+=2*Math.PI);const f=c-u/2;let h=r(i,{x:s.x+s.radius*Math.sin(f),y:s.y+s.radius*Math.cos(f)});h>2*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;e<t.length;++e)t[e].radius<n.radius&&(n=t[e]);let s=!1;for(let e=0;e<t.length;++e)if(r(t[e],n)>Math.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;n<t;++n)e[n]=0;return e}function c(t,e){return l(t).map((()=>l(e)))}function u(t,e){let n=0;for(let s=0;s<t.length;++s)n+=t[s]*e[s];return n}function f(t){return Math.sqrt(u(t,t))}function h(t,e,n){for(let s=0;s<e.length;++s)t[s]=e[s]*n}function x(t,e,n,s,r){for(let o=0;o<t.length;++o)t[o]=e*n[o]+s*r[o]}function g(t,e,n){const s=(n=n||{}).maxIterations||200*e.length,r=n.nonZeroDelta||1.05,o=n.zeroDelta||.001,i=n.minErrorDelta||1e-6,a=n.minErrorDelta||1e-5,l=void 0!==n.rho?n.rho:1,c=void 0!==n.chi?n.chi:2,u=void 0!==n.psi?n.psi:-.5,f=void 0!==n.sigma?n.sigma:.5;let h;const g=e.length,d=new Array(g+1);d[0]=e,d[0].fx=t(e),d[0].id=0;for(let n=0;n<g;++n){const s=e.slice();s[n]=s[n]?s[n]*r:o,d[n+1]=s,d[n+1].fx=t(s),d[n+1].id=n+1}function p(t){for(let e=0;e<t.length;e++)d[g][e]=t[e];d[g].fx=t.fx}const y=(t,e)=>t.fx-e.fx,m=e.slice(),M=e.slice(),b=e.slice(),z=e.slice();for(let e=0;e<s;++e){if(d.sort(y),n.history){const t=d.map((t=>{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<g;++t)h=Math.max(h,Math.abs(d[0][t]-d[1][t]));if(Math.abs(d[0].fx-d[g].fx)<i&&h<a)break;for(let t=0;t<g;++t){m[t]=0;for(let e=0;e<g;++e)m[t]+=d[e][t];m[t]/=g}const e=d[g];if(x(M,1+l,m,-l,e),M.fx=t(M),M.fx<d[0].fx)x(z,1+c,m,-c,e),z.fx=t(z),z.fx<M.fx?p(z):p(M);else if(M.fx>=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<e.fx?p(b):n=!0):(x(b,1-u*l,m,u*l,e),b.fx=t(b),b.fx<M.fx?p(b):n=!0),n){if(f>=1)break;for(let e=1;e<d.length;++e)x(d[e],1-f,d[0],f,d[e]),d[e].fx=t(d[e])}}else p(M)}return d.sort(y),{fx:d[0].fx,x:d[0]}}function d(t,e,n,s,r,o,i){const a=n.fx,l=u(n.fxprime,e);let c=a,f=a,h=l,g=0;function d(f,g,d){for(let p=0;p<16;++p)if(r=(f+g)/2,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||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;e<l;++e){if(c=d(t,i,s,r,c),n.history&&n.history.push({x:s.x.slice(),fx:s.fx,fxprime:s.fxprime.slice(),alpha:c}),c){x(o,1,r.fxprime,-1,s.fxprime);const t=u(s.fxprime,s.fxprime);x(i,Math.max(0,u(o,r.fxprime)/t),i,-1,r.fxprime),a=s,s=r,r=a}else h(i,s.fxprime,-1);if(f(s.fxprime)<=1e-5)break}return n.history&&n.history.push({x:s.x.slice(),fx:s.fx,fxprime:s.fxprime.slice(),alpha:c}),s}function y(t,e={}){e.maxIterations=e.maxIterations||500;const n=e.initialLayout||b,s=e.lossFunction||I,r=function(t,e={}){const n=e.distinct,s=t.map((t=>Object.assign({},t)));function r(t){return t.join(";")}if(n){const t=new Map;for(const e of s)for(let n=0;n<e.sets.length;n++){const s=String(e.sets[n]);t.set(s,e.size+(t.get(s)||0));for(let r=n+1;r<e.sets.length;r++){const n=String(e.sets[r]),o=`${s};${n}`,i=`${n};${s}`;t.set(o,e.size+(t.get(o)||0)),t.set(i,e.size+(t.get(i)||0))}}for(const e of s)e.sets.length<3&&(e.size=t.get(r(e.sets)))}const o=[],i=new Set;for(const t of s)if(1===t.sets.length)o.push(t.sets[0]);else if(2===t.sets.length){const e=t.sets[0],n=t.sets[1];i.add(r(t.sets)),i.add(r([n,e]))}o.sort(((t,e)=>t===e?0:t<e?-1:1));for(let t=0;t<o.length;++t){const e=o[t];for(let n=t+1;n<o.length;++n){const t=o[n];i.has(r([e,t]))||s.push({sets:[e,t],size:0})}}return s}(t,e),o=n(r,e),i=Object.keys(o),a=[];for(const t of i)a.push(o[t].x),a.push(o[t].y);const l=g((t=>{const e={};for(let n=0;n<i.length;++n){const s=i[n];e[s]={x:t[2*n],y:t[2*n+1],radius:o[s].radius}}return s(e,r)}),a,e).x;for(let t=0;t<i.length;++t){const e=i[t];o[e].x=l[2*t],o[e].y=l[2*t+1]}return o}const m=1e-10;function M(t,e,n){return Math.min(t,e)*Math.min(t,e)*Math.PI<=n+m?Math.abs(t-e):function(t,e,n,s){const r=(s=s||{}).maxIterations||100,o=s.tolerance||1e-10,i=t(e),a=t(n);let l=n-e;if(i*a>0)throw"Initial bisect points must have opposite signs";if(0===i)return e;if(0===a)return n;for(let n=0;n<r;++n){l/=2;const n=e+l,s=t(n);if(s*i>=0&&(e=n),Math.abs(l)<o||0===s)return n}return e+l}((s=>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;t<e.length;++t)e[t]=0;let r=0;for(let o=0;o<n.length;++o){const i=t[2*o],a=t[2*o+1];for(let l=o+1;l<n.length;++l){const c=t[2*l],u=t[2*l+1],f=n[o][l],h=s[o][l],x=(c-i)*(c-i)+(u-a)*(u-a),g=Math.sqrt(x),d=x-f*f;h>0&&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;t<n;++t){const t=p(u,l(2*o.length).map(Math.random),e);(!x||t.fx<x.fx)&&(x=t)}const g=x.x,d={};for(let t=0;t<s.length;++t){const e=s[t];d[e.sets[0]]={x:g[2*t]*a,y:g[2*t+1]*a,radius:Math.sqrt(e.size/Math.PI)}}if(e.history)for(const t of e.history)h(t.x,a);return d}(t,e);s(r,t)+1e-8<s(n,t)&&(n=r)}return n}function z(t,e){const n=e&&e.lossFunction?e.lossFunction:I,s={},r={};for(const e of t)if(1===e.sets.length){const t=e.sets[0];s[t]={x:1e10,y:1e10,rowid:s.length,size:e.size,radius:Math.sqrt(e.size/Math.PI)},r[t]=[]}t=t.filter((t=>2===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;n<r[t].length;++n)e+=r[t][n].size*r[t][n].weight;o.push({set:t,size:e})})),o.sort(a);const l={};function c(t){return t.set in l}function u(t,e){s[e].x=t.x,s[e].y=t.y,l[e]=!0}u({x:0,y:0},o[0].set);for(let e=1;e<o.length;++e){const l=o[e].set,h=r[l].filter(c),x=s[l];if(h.sort(a),0===h.length)throw"ERROR: missing pairwise overlap information";const g=[];for(var f=0;f<h.length;++f){const t=s[h[f].set],e=M(x.radius,t.radius,h[f].size);g.push({x:t.x+e,y:t.y}),g.push({x:t.x-e,y:t.y}),g.push({y:t.y+e,x:t.x}),g.push({y:t.y-e,x:t.x});for(let n=f+1;n<h.length;++n){const r=s[h[n].set],o=M(x.radius,r.radius,h[n].size),a=i({x:t.x,y:t.y,radius:e},{x:r.x,y:r.y,radius:o});g.push(...a)}}let d=1e50,p=g[0];for(const e of g){s[l].x=e.x,s[l].y=e.y;const r=n(s,t);r<d&&(d=r,p=e)}u(p,l)}return s}function I(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])));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])<Math.abs(t[1].radius-t[0].radius)&&(t[1].x=t[0].x+t[0].radius-t[1].radius-1e-10,t[1].y=t[0].y)}if(t.length>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<t.length;++e)for(let s=e+1;s<t.length;++s){const o=t[e].radius+t[s].radius;r(t[e],t[s])+1e-10<o&&n(t[s],t[e])}const s=new Map;for(let n=0;n<t.length;++n){const r=e(t[n]).parent.setid;s.has(r)||s.set(r,[]),s.get(r).push(t[n])}return t.forEach((t=>{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<r.length;)a(r[l],!0,!1),a(r[l+1],!1,!0),a(r[l+2],!0,!0),l+=3,o=A(s);return j(s)}function P(t,e,n,s,r){const o=T(t);e-=2*s,n-=2*s;const{xRange:i,yRange:a}=A(o);if(i.max===i.min||a.max===a.min)return console.log("not scaling solution: zero size detected"),t;let l,c;if(r){const t=2*Math.sqrt(r/Math.PI);l=e/t,c=n/t}else l=e/(i.max-i.min),c=n/(a.max-a.min);const u=Math.min(c,l),f=(e-(i.max-i.min)*u)/2,h=(n-(a.max-a.min)*u)/2;return j(o.map((t=>({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<e.length;++n){const o=e[n].radius-r(e[n],t);o<=s&&(s=o)}for(let e=0;e<n.length;++e){const o=r(n[e],t)-n[e].radius;o<=s&&(s=o)}return s}function C(t,e,s){const o=[];for(const e of t)o.push({x:e.x,y:e.y}),o.push({x:e.x+e.radius/2,y:e.y}),o.push({x:e.x-e.radius/2,y:e.y}),o.push({x:e.x,y:e.y+e.radius/2}),o.push({x:e.x,y:e.y-e.radius/2});let i=o[0],l=S(o[0],t,e);for(let n=1;n<o.length;++n){const s=S(o[n],t,e);s>=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.radius){f=!1;break}if(f)return u;if(1==t.length)return{x:t[0].x,y:t[0].y};const h={};return n(t,h),0===h.arcs.length?{x:0,y:-1e3,disjoint:!0}:1==h.arcs.length?{x:h.arcs[0].circle.x,y:h.arcs[0].circle.y}:e.length?C(t,[]):a(h.arcs.map((t=>t.p1)))}function N(t){const e={},n=Object.keys(t);for(const t of n)e[t]=[];for(let s=0;s<n.length;s++){const o=n[s],i=t[o];for(let a=s+1;a<n.length;++a){const s=n[a],l=t[s],c=r(i,l);c+l.radius<=i.radius+1e-10?e[s].push(o):c+i.radius<=l.radius+1e-10&&e[o].push(s)}}return e}function O(t,e,n){const s={},r=N(t);for(let o=0;o<e.length;++o){const i=e[o].sets,a={},l={};for(let t=0;t<i.length;++t){a[i[t]]=!0;const e=r[i[t]];for(let t=0;t<e.length;++t)l[e[t]]=!0}const c=[],u=[];for(let e in t)e in a?c.push(t[e]):e in l||u.push(t[e]);const f=C(c,u,n);s[i]=f,f.disjoint&&e[o].size>0&&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<r.length;++n)if(r[n]==t){s.add(e);break}}function r(t){return t.every((t=>!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}));
tools/ui/node_modules/@upsetjs/venn.js/package.json ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "name": "@upsetjs/venn.js",
3
+ "description": "Area Proportional Venn and Euler Diagrams",
4
+ "version": "2.0.0",
5
+ "publishConfig": {
6
+ "access": "public"
7
+ },
8
+ "author": {
9
+ "name": "Ben Frederickson",
10
+ "email": "ben@benfrederickson.com",
11
+ "url": "https://www.benfrederickson.com"
12
+ },
13
+ "contributors": [
14
+ {
15
+ "name": "Samuel Gratzl",
16
+ "email": "samu@sgratzl.com",
17
+ "url": "https://wwww.sgratzl.com"
18
+ }
19
+ ],
20
+ "license": "MIT",
21
+ "homepage": "https://github.com/upsetjs/venn.js",
22
+ "bugs": {
23
+ "url": "https://github.com/upsetjs/venn.js/issues"
24
+ },
25
+ "keywords": [
26
+ "Venn",
27
+ "Euler"
28
+ ],
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "https://github.com/upsetjs/venn.js.git"
32
+ },
33
+ "directories": {
34
+ "example": "examples",
35
+ "test": "tests"
36
+ },
37
+ "type": "module",
38
+ "main": "build/venn.esm.js",
39
+ "module": "build/venn.esm.js",
40
+ "require": "build/venn.js",
41
+ "unpkg": "build/venn.min.js",
42
+ "jsdelivr": "build/venn.min.js",
43
+ "types": "src/index.d.ts",
44
+ "exports": {
45
+ ".": {
46
+ "import": "./build/venn.esm.js",
47
+ "require": "./build/index.js",
48
+ "scripts": "./build/venn.min.js",
49
+ "types": "./src/index.d.ts"
50
+ }
51
+ },
52
+ "sideEffects": false,
53
+ "files": [
54
+ "build",
55
+ "src/**/*.js",
56
+ "src/**/*.d.ts"
57
+ ],
58
+ "browserslist": [
59
+ "Firefox ESR",
60
+ "last 2 Chrome versions",
61
+ "last 2 Firefox versions"
62
+ ],
63
+ "optionalDependencies": {
64
+ "d3-selection": "^3.0.0",
65
+ "d3-transition": "^3.0.1"
66
+ },
67
+ "devDependencies": {
68
+ "@babel/core": "^7.26.0",
69
+ "@babel/plugin-transform-runtime": "^7.25.9",
70
+ "@babel/preset-env": "^7.26.0",
71
+ "@eslint/js": "^9.15.0",
72
+ "@rollup/plugin-babel": "^6.0.4",
73
+ "@rollup/plugin-commonjs": "^28.0.1",
74
+ "@rollup/plugin-node-resolve": "^15.3.0",
75
+ "@yarnpkg/sdks": "^3.2.0",
76
+ "canvas": "^2.11.2",
77
+ "d3-selection": "^3.0.0",
78
+ "d3-transition": "^3.0.1",
79
+ "eslint": "^9.15.0",
80
+ "eslint-config-prettier": "^9.1.0",
81
+ "eslint-plugin-prettier": "^5.2.1",
82
+ "fmin": "patch:fmin@npm%3A0.0.4#~/.yarn/patches/fmin-npm-0.0.4-e439f499bd.patch",
83
+ "globals": "^15.12.0",
84
+ "jest-image-snapshot": "^6.4.0",
85
+ "jsdom": "^25.0.1",
86
+ "prettier": "^3.3.3",
87
+ "rimraf": "^6.0.1",
88
+ "rollup": "^4.27.2",
89
+ "rollup-plugin-terser": "^7.0.2",
90
+ "vite": "^5.4.11",
91
+ "vitest": "^2.1.5"
92
+ },
93
+ "scripts": {
94
+ "clean": "rimraf --glob build *.tgz",
95
+ "watch": "rollup -c -w",
96
+ "lint": "eslint src",
97
+ "test": "vitest --passWithNoTests",
98
+ "test:watch": "vitest --watch",
99
+ "posttest": "npm run lint",
100
+ "prebuild": "npm run clean && npm test",
101
+ "build": "rollup -c",
102
+ "format": "prettier --write examples \"*.{md,json,js,yml}\" \"{.github,src,examples}/**\""
103
+ },
104
+ "packageManager": "yarn@4.5.1"
105
+ }
tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.js ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ const SMALL = 1e-10;
2
+
3
+ /**
4
+ * Returns the intersection area of a bunch of circles (where each circle
5
+ * is an object having an x,y and radius property)
6
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
7
+ * @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<{
8
+ x: number;
9
+ y: number;
10
+ parentIndex: [number, number];
11
+ }>, intersectionPoints: ReadonlyArray<{
12
+ x: number;
13
+ y: number;
14
+ parentIndex: [number, number];
15
+ }> }} stats
16
+ * @returns {number}
17
+ */
18
+ export function intersectionArea(circles, stats) {
19
+ // get all the intersection points of the circles
20
+ const intersectionPoints = getIntersectionPoints(circles);
21
+
22
+ // filter out points that aren't included in all the circles
23
+ const innerPoints = intersectionPoints.filter((p) => containedInCircles(p, circles));
24
+
25
+ let arcArea = 0;
26
+ let polygonArea = 0;
27
+ /** @type {{ circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} }[]} */
28
+ const arcs = [];
29
+
30
+ // if we have intersection points that are within all the circles,
31
+ // then figure out the area contained by them
32
+ if (innerPoints.length > 1) {
33
+ // sort the points by angle from the center of the polygon, which lets
34
+ // us just iterate over points to get the edges
35
+ const center = getCenter(innerPoints);
36
+ for (let i = 0; i < innerPoints.length; ++i) {
37
+ const p = innerPoints[i];
38
+ p.angle = Math.atan2(p.x - center.x, p.y - center.y);
39
+ }
40
+ innerPoints.sort((a, b) => b.angle - a.angle);
41
+
42
+ // iterate over all points, get arc between the points
43
+ // and update the areas
44
+ let p2 = innerPoints[innerPoints.length - 1];
45
+ for (let i = 0; i < innerPoints.length; ++i) {
46
+ const p1 = innerPoints[i];
47
+
48
+ // polygon area updates easily ...
49
+ polygonArea += (p2.x + p1.x) * (p1.y - p2.y);
50
+
51
+ // updating the arc area is a little more involved
52
+ const midPoint = { x: (p1.x + p2.x) / 2, y: (p1.y + p2.y) / 2 };
53
+ /** @types null | { circle: {x: number, y: number, radius: number}, width: number, p1: {x: number, y: number}, p2: {x: number, y: number} } */
54
+ let arc = null;
55
+
56
+ for (let j = 0; j < p1.parentIndex.length; ++j) {
57
+ if (p2.parentIndex.includes(p1.parentIndex[j])) {
58
+ // figure out the angle halfway between the two points
59
+ // on the current circle
60
+ const circle = circles[p1.parentIndex[j]];
61
+ const a1 = Math.atan2(p1.x - circle.x, p1.y - circle.y);
62
+ const a2 = Math.atan2(p2.x - circle.x, p2.y - circle.y);
63
+
64
+ let angleDiff = a2 - a1;
65
+ if (angleDiff < 0) {
66
+ angleDiff += 2 * Math.PI;
67
+ }
68
+
69
+ // and use that angle to figure out the width of the
70
+ // arc
71
+ const a = a2 - angleDiff / 2;
72
+ let width = distance(midPoint, {
73
+ x: circle.x + circle.radius * Math.sin(a),
74
+ y: circle.y + circle.radius * Math.cos(a),
75
+ });
76
+
77
+ // clamp the width to the largest is can actually be
78
+ // (sometimes slightly overflows because of FP errors)
79
+ if (width > circle.radius * 2) {
80
+ width = circle.radius * 2;
81
+ }
82
+
83
+ // pick the circle whose arc has the smallest width
84
+ if (arc == null || arc.width > width) {
85
+ arc = { circle, width, p1, p2, large: width > circle.radius, sweep: true };
86
+ }
87
+ }
88
+ }
89
+
90
+ if (arc != null) {
91
+ arcs.push(arc);
92
+ arcArea += circleArea(arc.circle.radius, arc.width);
93
+ p2 = p1;
94
+ }
95
+ }
96
+ } else {
97
+ // no intersection points, is either disjoint - or is completely
98
+ // overlapped. figure out which by examining the smallest circle
99
+ let smallest = circles[0];
100
+ for (let i = 1; i < circles.length; ++i) {
101
+ if (circles[i].radius < smallest.radius) {
102
+ smallest = circles[i];
103
+ }
104
+ }
105
+
106
+ // make sure the smallest circle is completely contained in all
107
+ // the other circles
108
+ let disjoint = false;
109
+ for (let i = 0; i < circles.length; ++i) {
110
+ if (distance(circles[i], smallest) > Math.abs(smallest.radius - circles[i].radius)) {
111
+ disjoint = true;
112
+ break;
113
+ }
114
+ }
115
+
116
+ if (disjoint) {
117
+ arcArea = polygonArea = 0;
118
+ } else {
119
+ arcArea = smallest.radius * smallest.radius * Math.PI;
120
+ arcs.push({
121
+ circle: smallest,
122
+ p1: { x: smallest.x, y: smallest.y + smallest.radius },
123
+ p2: { x: smallest.x - SMALL, y: smallest.y + smallest.radius },
124
+ width: smallest.radius * 2,
125
+ large: true,
126
+ sweep: true,
127
+ });
128
+ }
129
+ }
130
+
131
+ polygonArea /= 2;
132
+
133
+ if (stats) {
134
+ stats.area = arcArea + polygonArea;
135
+ stats.arcArea = arcArea;
136
+ stats.polygonArea = polygonArea;
137
+ stats.arcs = arcs;
138
+ stats.innerPoints = innerPoints;
139
+ stats.intersectionPoints = intersectionPoints;
140
+ }
141
+
142
+ return arcArea + polygonArea;
143
+ }
144
+
145
+ /**
146
+ * returns whether a point is contained by all of a list of circles
147
+ * @param {{x: number, y: number}} point
148
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
149
+ * @returns {boolean}
150
+ */
151
+ export function containedInCircles(point, circles) {
152
+ return circles.every((circle) => distance(point, circle) < circle.radius + SMALL);
153
+ }
154
+
155
+ /**
156
+ * Gets all intersection points between a bunch of circles
157
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
158
+ * @returns {ReadonlyArray<{x: number, y: number, parentIndex: [number, number]}>}
159
+ */
160
+ function getIntersectionPoints(circles) {
161
+ /** @type {{x: number, y: number, parentIndex: [number, number]}[]} */
162
+ const ret = [];
163
+ for (let i = 0; i < circles.length; ++i) {
164
+ for (let j = i + 1; j < circles.length; ++j) {
165
+ const intersect = circleCircleIntersection(circles[i], circles[j]);
166
+ for (const p of intersect) {
167
+ p.parentIndex = [i, j];
168
+ ret.push(p);
169
+ }
170
+ }
171
+ }
172
+ return ret;
173
+ }
174
+
175
+ /**
176
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
177
+ * @param {number} r
178
+ * @param {number} width
179
+ * @returns {number}
180
+ **/
181
+ export function circleArea(r, width) {
182
+ return r * r * Math.acos(1 - width / r) - (r - width) * Math.sqrt(width * (2 * r - width));
183
+ }
184
+
185
+ /**
186
+ * euclidean distance between two points
187
+ * @param {{x: number, y: number}} p1
188
+ * @param {{x: number, y: number}} p2
189
+ * @returns {number}
190
+ **/
191
+ export function distance(p1, p2) {
192
+ return Math.sqrt((p1.x - p2.x) * (p1.x - p2.x) + (p1.y - p2.y) * (p1.y - p2.y));
193
+ }
194
+
195
+ /**
196
+ * Returns the overlap area of two circles of radius r1 and r2 - that
197
+ * have their centers separated by distance d. Simpler faster
198
+ * circle intersection for only two circles
199
+ * @param {number} r1
200
+ * @param {number} r2
201
+ * @param {number} d
202
+ * @returns {number}
203
+ */
204
+ export function circleOverlap(r1, r2, d) {
205
+ // no overlap
206
+ if (d >= r1 + r2) {
207
+ return 0;
208
+ }
209
+
210
+ // completely overlapped
211
+ if (d <= Math.abs(r1 - r2)) {
212
+ return Math.PI * Math.min(r1, r2) * Math.min(r1, r2);
213
+ }
214
+
215
+ const w1 = r1 - (d * d - r2 * r2 + r1 * r1) / (2 * d);
216
+ const w2 = r2 - (d * d - r1 * r1 + r2 * r2) / (2 * d);
217
+ return circleArea(r1, w1) + circleArea(r2, w2);
218
+ }
219
+
220
+ /**
221
+ * Given two circles (containing a x/y/radius attributes),
222
+ * returns the intersecting points if possible
223
+ * note: doesn't handle cases where there are infinitely many
224
+ * intersection points (circles are equivalent):, or only one intersection point
225
+ * @param {{x: number, y: number, radius: number}} p1
226
+ * @param {{x: number, y: number, radius: number}} p2
227
+ * @returns {ReadonlyArray<{x: number, y: number}>}
228
+ **/
229
+ export function circleCircleIntersection(p1, p2) {
230
+ const d = distance(p1, p2);
231
+ const r1 = p1.radius;
232
+ const r2 = p2.radius;
233
+
234
+ // if to far away, or self contained - can't be done
235
+ if (d >= r1 + r2 || d <= Math.abs(r1 - r2)) {
236
+ return [];
237
+ }
238
+
239
+ const a = (r1 * r1 - r2 * r2 + d * d) / (2 * d);
240
+ const h = Math.sqrt(r1 * r1 - a * a);
241
+ const x0 = p1.x + (a * (p2.x - p1.x)) / d;
242
+ const y0 = p1.y + (a * (p2.y - p1.y)) / d;
243
+ const rx = -(p2.y - p1.y) * (h / d);
244
+ const ry = -(p2.x - p1.x) * (h / d);
245
+
246
+ return [
247
+ { x: x0 + rx, y: y0 - ry },
248
+ { x: x0 - rx, y: y0 + ry },
249
+ ];
250
+ }
251
+
252
+ /**
253
+ * Returns the center of a bunch of points
254
+ * @param {ReadonlyArray<{x: number, y: number}>} points
255
+ * @returns {{x: number, y: number}}
256
+ */
257
+ export function getCenter(points) {
258
+ const center = { x: 0, y: 0 };
259
+ for (const point of points) {
260
+ center.x += point.x;
261
+ center.y += point.y;
262
+ }
263
+ center.x /= points.length;
264
+ center.y /= points.length;
265
+ return center;
266
+ }
tools/ui/node_modules/@upsetjs/venn.js/src/circleintersection.spec.js ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { distance, intersectionArea, circleCircleIntersection, circleOverlap, circleArea } from './circleintersection';
2
+ import { describe, test, expect } from 'vitest';
3
+
4
+ describe('circleArea', () => {
5
+ test('empty circle test', () => {
6
+ expect(circleArea(10, 0)).toBeCloseTo(0);
7
+ });
8
+ test('half circle test', () => {
9
+ expect(circleArea(10, 10)).toBeCloseTo((Math.PI * 10 * 10) / 2);
10
+ });
11
+ test('full circle test', () => {
12
+ expect(circleArea(10, 20)).toBeCloseTo(Math.PI * 10 * 10);
13
+ });
14
+ });
15
+
16
+ describe('circleOverlap', () => {
17
+ test('non overlapping circles test', () => {
18
+ expect(circleOverlap(10, 10, 200)).toBeCloseTo(0);
19
+ });
20
+
21
+ test('full overlapping circles test', () => {
22
+ expect(circleOverlap(10, 10, 0)).toBeCloseTo(Math.PI * 10 * 10);
23
+ expect(circleOverlap(10, 5, 5)).toBeCloseTo(Math.PI * 5 * 5);
24
+ });
25
+ });
26
+
27
+ describe('circleCircleIntersection', () => {
28
+ function testIntersection(p1, p2) {
29
+ const points = circleCircleIntersection(p1, p2);
30
+ // make sure that points are appropriately spaced
31
+ for (let i = 0; i < points.length; i++) {
32
+ const point = points[i];
33
+ expect(distance(point, p1)).toBeCloseTo(p1.radius);
34
+ expect(distance(point, p2)).toBeCloseTo(p2.radius);
35
+ }
36
+
37
+ return points;
38
+ }
39
+
40
+ test('fully contained', () => {
41
+ expect(circleCircleIntersection({ x: 0, y: 3, radius: 10 }, { x: 3, y: 0, radius: 20 })).toHaveLength(0);
42
+ });
43
+
44
+ test('fully disjoint', () => {
45
+ expect(circleCircleIntersection({ x: 0, y: 0, radius: 10 }, { x: 21, y: 0, radius: 10 })).toHaveLength(0);
46
+ });
47
+
48
+ test('midway between 2 points on y axis', () => {
49
+ const points = testIntersection(
50
+ { x: 0, y: 0, radius: 10 },
51
+ { x: 10, y: 0, radius: 10 },
52
+ 'test midway intersection'
53
+ );
54
+ expect(points).toHaveLength(2);
55
+ expect(points[0].x).toBeCloseTo(5);
56
+ expect(points[1].x).toBeCloseTo(5);
57
+ expect(points[0].y).toBeCloseTo(-1 * points[1].y);
58
+ });
59
+ test('failing case from input', () => {
60
+ const points = testIntersection({ radius: 10, x: 15, y: 5 }, { radius: 10, x: 20, y: 0 }, 'test intersection2');
61
+ expect(points).toHaveLength(2);
62
+ });
63
+ });
64
+
65
+ describe('intersectionArea', () => {
66
+ test('0', () => {
67
+ // each one of these circles overlaps all the others, but the total overlap is still 0
68
+ const circles = [
69
+ { x: 0.909, y: 0.905, radius: 0.548 },
70
+ { x: 0.765, y: 0.382, radius: 0.703 },
71
+ { x: 0.63, y: 0.019, radius: 0.449 },
72
+ { x: 0.21, y: 0.755, radius: 0.656 },
73
+ { x: 0.276, y: 0.723, radius: 1.145 },
74
+ { x: 0.141, y: 0.585, radius: 0.419 },
75
+ ];
76
+
77
+ const area = intersectionArea(circles);
78
+ expect(area).toBe(0);
79
+ });
80
+ test('1', () => {
81
+ // no intersection points, but the smallest circle is completely overlapped by each of the others
82
+ const circles = [
83
+ { x: 0.426, y: 0.882, radius: 0.944 },
84
+ { x: 0.24, y: 0.685, radius: 0.992 },
85
+ { x: 0.01, y: 0.909, radius: 1.161 },
86
+ { x: 0.54, y: 0.475, radius: 0.41 },
87
+ ];
88
+
89
+ expect(circles[3].radius * circles[3].radius * Math.PI).toBeCloseTo(intersectionArea(circles));
90
+ });
91
+ });
92
+
93
+ describe('randomFailures', () => {
94
+ test('0', () => {
95
+ const circles = [
96
+ { x: 0.501, y: 0.32, radius: 0.629 },
97
+ { x: 0.945, y: 0.022, radius: 1.015 },
98
+ { x: 0.021, y: 0.863, radius: 0.261 },
99
+ { x: 0.528, y: 0.09, radius: 0.676 },
100
+ ];
101
+ const area = intersectionArea(circles);
102
+
103
+ expect(Math.abs(area - 0.0008914)).toBeLessThan(0.0001);
104
+ });
105
+ test('1', () => {
106
+ const circles = [
107
+ { x: 9.154829758385864, y: 0, size: 226, radius: 8.481629223064205 },
108
+ { x: 5.806079662851866, y: 7.4438023223126795, size: 733, radius: 15.274853405932202 },
109
+ { x: 9.484491297623553, y: 4.064806303558571, size: 332, radius: 10.280023453913834 },
110
+ { x: 10.56492833796709, y: 3.0723147554880175, size: 244, radius: 8.812923024107548 },
111
+ ];
112
+
113
+ const area = intersectionArea(circles);
114
+ expect(area).toBeCloseTo(10.96362);
115
+ });
116
+ test('2', () => {
117
+ const circles = [
118
+ { x: -0.0014183481763938425, y: 0.0006071174738860746, radius: 510.3115834996166 },
119
+ { x: 875.0163281608848, y: 0.0007003612396158774, radius: 465.1793581792228 },
120
+ { x: 462.7394999567192, y: 387.9359963330729, radius: 172.62633992134658 },
121
+ ];
122
+ const area = intersectionArea(circles);
123
+ expect(area).not.toBeNaN();
124
+ });
125
+ });
tools/ui/node_modules/@upsetjs/venn.js/src/diagram.js ADDED
@@ -0,0 +1,783 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { venn, lossFunction, logRatioLossFunction, normalizeSolution, scaleSolution } from './layout';
2
+ import { intersectionArea, distance, getCenter } from './circleintersection';
3
+ import { nelderMead } from 'fmin';
4
+
5
+ /**
6
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
7
+ *
8
+ * `colourScheme: Array<String>`
9
+ * A list of color values to be applied when coloring diagram circles.
10
+ *
11
+ * `symmetricalTextCentre: Boolean`
12
+ * Whether to symmetrically center each circle's text horizontally and vertically.
13
+ * Defaults to `false`.
14
+ *
15
+ * `textFill: String`
16
+ * The color to be applied to the text within each circle.
17
+ *
18
+ * @param {object} options
19
+ */
20
+ export function VennDiagram(options = {}) {
21
+ let useViewBox = false,
22
+ width = 600,
23
+ height = 350,
24
+ padding = 15,
25
+ duration = 1000,
26
+ orientation = Math.PI / 2,
27
+ normalize = true,
28
+ scaleToFit = null,
29
+ wrap = true,
30
+ styled = true,
31
+ fontSize = null,
32
+ orientationOrder = null,
33
+ distinct = false,
34
+ round = null,
35
+ symmetricalTextCentre = options && options.symmetricalTextCentre ? options.symmetricalTextCentre : false,
36
+ // mimic the behaviour of d3.scale.category10 from the previous
37
+ // version of d3
38
+ colourMap = {},
39
+ // so this is the same as d3.schemeCategory10, which is only defined in d3 4.0
40
+ // since we can support older versions of d3 as long as we don't force this,
41
+ // I'm hackily redefining below. TODO: remove this and change to d3.schemeCategory10
42
+ colourScheme =
43
+ options && options.colourScheme
44
+ ? options.colourScheme
45
+ : options && options.colorScheme
46
+ ? options.colorScheme
47
+ : [
48
+ '#1f77b4',
49
+ '#ff7f0e',
50
+ '#2ca02c',
51
+ '#d62728',
52
+ '#9467bd',
53
+ '#8c564b',
54
+ '#e377c2',
55
+ '#7f7f7f',
56
+ '#bcbd22',
57
+ '#17becf',
58
+ ],
59
+ colourIndex = 0,
60
+ colours = function (key) {
61
+ if (key in colourMap) {
62
+ return colourMap[key];
63
+ }
64
+ var ret = (colourMap[key] = colourScheme[colourIndex]);
65
+ colourIndex += 1;
66
+ if (colourIndex >= colourScheme.length) {
67
+ colourIndex = 0;
68
+ }
69
+ return ret;
70
+ },
71
+ layoutFunction = venn,
72
+ loss = lossFunction;
73
+
74
+ function chart(selection) {
75
+ let data = selection.datum();
76
+
77
+ // handle 0-sized sets by removing from input
78
+ const toRemove = new Set();
79
+ data.forEach((datum) => {
80
+ if (datum.size == 0 && datum.sets.length == 1) {
81
+ toRemove.add(datum.sets[0]);
82
+ }
83
+ });
84
+ data = data.filter((datum) => !datum.sets.some((set) => toRemove.has(set)));
85
+
86
+ let circles = {};
87
+ let textCentres = {};
88
+
89
+ if (data.length > 0) {
90
+ let solution = layoutFunction(data, { lossFunction: loss, distinct });
91
+
92
+ if (normalize) {
93
+ solution = normalizeSolution(solution, orientation, orientationOrder);
94
+ }
95
+
96
+ circles = scaleSolution(solution, width, height, padding, scaleToFit);
97
+ textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
98
+ }
99
+
100
+ // Figure out the current label for each set. These can change
101
+ // and D3 won't necessarily update (fixes https://github.com/benfred/venn.js/issues/103)
102
+ const labels = {};
103
+ data.forEach((datum) => {
104
+ if (datum.label) {
105
+ labels[datum.sets] = datum.label;
106
+ }
107
+ });
108
+
109
+ function label(d) {
110
+ if (d.sets in labels) {
111
+ return labels[d.sets];
112
+ }
113
+ if (d.sets.length == 1) {
114
+ return '' + d.sets[0];
115
+ }
116
+ }
117
+
118
+ // create svg if not already existing
119
+ selection.selectAll('svg').data([circles]).enter().append('svg');
120
+
121
+ const svg = selection.select('svg');
122
+
123
+ if (useViewBox) {
124
+ svg.attr('viewBox', `0 0 ${width} ${height}`);
125
+ } else {
126
+ svg.attr('width', width).attr('height', height);
127
+ }
128
+
129
+ // to properly transition intersection areas, we need the
130
+ // previous circles locations. load from elements
131
+ const previous = {};
132
+ let hasPrevious = false;
133
+ svg.selectAll('.venn-area path').each(function (d) {
134
+ const path = this.getAttribute('d');
135
+ if (d.sets.length == 1 && path && !distinct) {
136
+ hasPrevious = true;
137
+ previous[d.sets[0]] = circleFromPath(path);
138
+ }
139
+ });
140
+ // interpolate intersection area paths between previous and
141
+ // current paths
142
+ function pathTween(d) {
143
+ return (t) => {
144
+ const c = d.sets.map((set) => {
145
+ let start = previous[set];
146
+ let end = circles[set];
147
+ if (!start) {
148
+ start = { x: width / 2, y: height / 2, radius: 1 };
149
+ }
150
+ if (!end) {
151
+ end = { x: width / 2, y: height / 2, radius: 1 };
152
+ }
153
+ return {
154
+ x: start.x * (1 - t) + end.x * t,
155
+ y: start.y * (1 - t) + end.y * t,
156
+ radius: start.radius * (1 - t) + end.radius * t,
157
+ };
158
+ });
159
+ return intersectionAreaPath(c, round);
160
+ };
161
+ }
162
+
163
+ // update data, joining on the set ids
164
+ const nodes = svg.selectAll('.venn-area').data(data, (d) => d.sets);
165
+
166
+ // create new nodes
167
+ const enter = nodes
168
+ .enter()
169
+ .append('g')
170
+ .attr(
171
+ 'class',
172
+ (d) =>
173
+ `venn-area venn-${d.sets.length == 1 ? 'circle' : 'intersection'}${
174
+ d.colour || d.color ? ' venn-coloured' : ''
175
+ }`
176
+ )
177
+ .attr('data-venn-sets', (d) => d.sets.join('_'));
178
+
179
+ const enterPath = enter.append('path');
180
+ const enterText = enter
181
+ .append('text')
182
+ .attr('class', 'label')
183
+ .text((d) => label(d))
184
+ .attr('text-anchor', 'middle')
185
+ .attr('dy', '.35em')
186
+ .attr('x', width / 2)
187
+ .attr('y', height / 2);
188
+
189
+ // apply minimal style if wanted
190
+ if (styled) {
191
+ enterPath
192
+ .style('fill-opacity', '0')
193
+ .filter((d) => d.sets.length == 1)
194
+ .style('fill', (d) => (d.colour ? d.colour : d.color ? d.color : colours(d.sets)))
195
+ .style('fill-opacity', '.25');
196
+
197
+ enterText.style('fill', (d) => {
198
+ if (d.colour || d.color) {
199
+ return '#FFF';
200
+ }
201
+ if (options.textFill) {
202
+ return options.textFill;
203
+ }
204
+ return d.sets.length == 1 ? colours(d.sets) : '#444';
205
+ });
206
+ }
207
+
208
+ function asTransition(s) {
209
+ if (typeof s.transition === 'function') {
210
+ return s.transition('venn').duration(duration);
211
+ }
212
+ return s;
213
+ }
214
+
215
+ // update existing, using pathTween if necessary
216
+ let update = selection;
217
+ if (hasPrevious && typeof update.transition === 'function') {
218
+ update = asTransition(selection);
219
+ update.selectAll('path').attrTween('d', pathTween);
220
+ } else {
221
+ update.selectAll('path').attr('d', (d) => intersectionAreaPath(d.sets.map((set) => circles[set])), round);
222
+ }
223
+
224
+ const updateText = update
225
+ .selectAll('text')
226
+ .filter((d) => d.sets in textCentres)
227
+ .text((d) => label(d))
228
+ .attr('x', (d) => Math.floor(textCentres[d.sets].x))
229
+ .attr('y', (d) => Math.floor(textCentres[d.sets].y));
230
+
231
+ if (wrap) {
232
+ if (hasPrevious) {
233
+ // d3 4.0 uses 'on' for events on transitions,
234
+ // but d3 3.0 used 'each' instead. switch appropriately
235
+ if ('on' in updateText) {
236
+ updateText.on('end', wrapText(circles, label));
237
+ } else {
238
+ updateText.each('end', wrapText(circles, label));
239
+ }
240
+ } else {
241
+ updateText.each(wrapText(circles, label));
242
+ }
243
+ }
244
+
245
+ // remove old
246
+ const exit = asTransition(nodes.exit()).remove();
247
+ if (typeof nodes.transition === 'function') {
248
+ exit.selectAll('path').attrTween('d', pathTween);
249
+ }
250
+
251
+ const exitText = exit
252
+ .selectAll('text')
253
+ .attr('x', width / 2)
254
+ .attr('y', height / 2);
255
+
256
+ // if we've been passed a fontSize explicitly, use it to
257
+ // transition
258
+ if (fontSize !== null) {
259
+ enterText.style('font-size', '0px');
260
+ updateText.style('font-size', fontSize);
261
+ exitText.style('font-size', '0px');
262
+ }
263
+
264
+ return { circles, textCentres, nodes, enter, update, exit };
265
+ }
266
+
267
+ chart.wrap = function (_) {
268
+ if (!arguments.length) return wrap;
269
+ wrap = _;
270
+ return chart;
271
+ };
272
+
273
+ chart.useViewBox = function () {
274
+ useViewBox = true;
275
+ return chart;
276
+ };
277
+
278
+ chart.width = function (_) {
279
+ if (!arguments.length) return width;
280
+ width = _;
281
+ return chart;
282
+ };
283
+
284
+ chart.height = function (_) {
285
+ if (!arguments.length) return height;
286
+ height = _;
287
+ return chart;
288
+ };
289
+
290
+ chart.padding = function (_) {
291
+ if (!arguments.length) return padding;
292
+ padding = _;
293
+ return chart;
294
+ };
295
+
296
+ chart.distinct = function (_) {
297
+ if (!arguments.length) return distinct;
298
+ distinct = _;
299
+ return chart;
300
+ };
301
+
302
+ chart.colours = function (_) {
303
+ if (!arguments.length) return colours;
304
+ colours = _;
305
+ return chart;
306
+ };
307
+
308
+ chart.colors = function (_) {
309
+ if (!arguments.length) return colours;
310
+ colours = _;
311
+ return chart;
312
+ };
313
+
314
+ chart.fontSize = function (_) {
315
+ if (!arguments.length) return fontSize;
316
+ fontSize = _;
317
+ return chart;
318
+ };
319
+
320
+ chart.round = function (_) {
321
+ if (!arguments.length) return round;
322
+ round = _;
323
+ return chart;
324
+ };
325
+
326
+ chart.duration = function (_) {
327
+ if (!arguments.length) return duration;
328
+ duration = _;
329
+ return chart;
330
+ };
331
+
332
+ chart.layoutFunction = function (_) {
333
+ if (!arguments.length) return layoutFunction;
334
+ layoutFunction = _;
335
+ return chart;
336
+ };
337
+
338
+ chart.normalize = function (_) {
339
+ if (!arguments.length) return normalize;
340
+ normalize = _;
341
+ return chart;
342
+ };
343
+
344
+ chart.scaleToFit = function (_) {
345
+ if (!arguments.length) return scaleToFit;
346
+ scaleToFit = _;
347
+ return chart;
348
+ };
349
+
350
+ chart.styled = function (_) {
351
+ if (!arguments.length) return styled;
352
+ styled = _;
353
+ return chart;
354
+ };
355
+
356
+ chart.orientation = function (_) {
357
+ if (!arguments.length) return orientation;
358
+ orientation = _;
359
+ return chart;
360
+ };
361
+
362
+ chart.orientationOrder = function (_) {
363
+ if (!arguments.length) return orientationOrder;
364
+ orientationOrder = _;
365
+ return chart;
366
+ };
367
+
368
+ chart.lossFunction = function (_) {
369
+ if (!arguments.length) return loss;
370
+ loss = _ === 'default' ? lossFunction : _ === 'logRatio' ? logRatioLossFunction : _;
371
+ return chart;
372
+ };
373
+
374
+ return chart;
375
+ }
376
+
377
+ // sometimes text doesn't fit inside the circle, if thats the case lets wrap
378
+ // the text here such that it fits
379
+ // todo: looks like this might be merged into d3 (
380
+ // https://github.com/mbostock/d3/issues/1642),
381
+ // also worth checking out is
382
+ // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
383
+ // this seems to be one of those things that should be easy but isn't
384
+ export function wrapText(circles, labeller) {
385
+ return function (data) {
386
+ const text = this;
387
+ const width = circles[data.sets[0]].radius || 50;
388
+ const label = labeller(data) || '';
389
+
390
+ const words = label.split(/\s+/).reverse();
391
+ const maxLines = 3;
392
+ const minChars = (label.length + words.length) / maxLines;
393
+
394
+ let word = words.pop();
395
+ let line = [word];
396
+ let lineNumber = 0;
397
+ const lineHeight = 1.1; // ems
398
+ text.textContent = null; // clear
399
+ const tspans = [];
400
+
401
+ function append(word) {
402
+ const tspan = text.ownerDocument.createElementNS(text.namespaceURI, 'tspan');
403
+ tspan.textContent = word;
404
+ tspans.push(tspan);
405
+ text.append(tspan);
406
+ return tspan;
407
+ }
408
+ let tspan = append(word);
409
+
410
+ while (true) {
411
+ word = words.pop();
412
+ if (!word) {
413
+ break;
414
+ }
415
+ line.push(word);
416
+ const joined = line.join(' ');
417
+ tspan.textContent = joined;
418
+ if (joined.length > minChars && tspan.getComputedTextLength() > width) {
419
+ line.pop();
420
+ tspan.textContent = line.join(' ');
421
+ line = [word];
422
+ tspan = append(word);
423
+ lineNumber++;
424
+ }
425
+ }
426
+
427
+ const initial = 0.35 - (lineNumber * lineHeight) / 2;
428
+ const x = text.getAttribute('x');
429
+ const y = text.getAttribute('y');
430
+ tspans.forEach((t, i) => {
431
+ t.setAttribute('x', x);
432
+ t.setAttribute('y', y);
433
+ t.setAttribute('dy', `${initial + i * lineHeight}em`);
434
+ });
435
+ };
436
+ }
437
+
438
+ /**
439
+ *
440
+ * @param {{x: number, y: number}} current
441
+ * @param {ReadonlyArray<{x: number, y: number}>} interior
442
+ * @param {ReadonlyArray<{x: number, y: number}>} exterior
443
+ * @returns {number}
444
+ */
445
+ function circleMargin(current, interior, exterior) {
446
+ let margin = interior[0].radius - distance(interior[0], current);
447
+
448
+ for (let i = 1; i < interior.length; ++i) {
449
+ const m = interior[i].radius - distance(interior[i], current);
450
+ if (m <= margin) {
451
+ margin = m;
452
+ }
453
+ }
454
+
455
+ for (let i = 0; i < exterior.length; ++i) {
456
+ const m = distance(exterior[i], current) - exterior[i].radius;
457
+ if (m <= margin) {
458
+ margin = m;
459
+ }
460
+ }
461
+ return margin;
462
+ }
463
+
464
+ /**
465
+ * compute the center of some circles by maximizing the margin of
466
+ * the center point relative to the circles (interior) after subtracting
467
+ * nearby circles (exterior)
468
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
469
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
470
+ * @param {boolean} symmetricalTextCentre
471
+ * @returns {{x:number, y: number}}
472
+ */
473
+ export function computeTextCentre(interior, exterior, symmetricalTextCentre) {
474
+ // get an initial estimate by sampling around the interior circles
475
+ // and taking the point with the biggest margin
476
+ /** @type {{x: number, y: number}[]} */
477
+ const points = [];
478
+ for (const c of interior) {
479
+ points.push({ x: c.x, y: c.y });
480
+ points.push({ x: c.x + c.radius / 2, y: c.y });
481
+ points.push({ x: c.x - c.radius / 2, y: c.y });
482
+ points.push({ x: c.x, y: c.y + c.radius / 2 });
483
+ points.push({ x: c.x, y: c.y - c.radius / 2 });
484
+ }
485
+
486
+ let initial = points[0];
487
+ let margin = circleMargin(points[0], interior, exterior);
488
+
489
+ for (let i = 1; i < points.length; ++i) {
490
+ const m = circleMargin(points[i], interior, exterior);
491
+ if (m >= margin) {
492
+ initial = points[i];
493
+ margin = m;
494
+ }
495
+ }
496
+
497
+ // maximize the margin numerically
498
+ const solution = nelderMead(
499
+ (p) => -1 * circleMargin({ x: p[0], y: p[1] }, interior, exterior),
500
+ [initial.x, initial.y],
501
+ { maxIterations: 500, minErrorDelta: 1e-10 }
502
+ ).x;
503
+
504
+ const ret = { x: symmetricalTextCentre ? 0 : solution[0], y: solution[1] };
505
+
506
+ // check solution, fallback as needed (happens if fully overlapped
507
+ // etc)
508
+ let valid = true;
509
+ for (const i of interior) {
510
+ if (distance(ret, i) > i.radius) {
511
+ valid = false;
512
+ break;
513
+ }
514
+ }
515
+
516
+ for (const e of exterior) {
517
+ if (distance(ret, e) < e.radius) {
518
+ valid = false;
519
+ break;
520
+ }
521
+ }
522
+ if (valid) {
523
+ return ret;
524
+ }
525
+
526
+ if (interior.length == 1) {
527
+ return { x: interior[0].x, y: interior[0].y };
528
+ }
529
+ const areaStats = {};
530
+ intersectionArea(interior, areaStats);
531
+
532
+ if (areaStats.arcs.length === 0) {
533
+ return { x: 0, y: -1000, disjoint: true };
534
+ }
535
+ if (areaStats.arcs.length == 1) {
536
+ return { x: areaStats.arcs[0].circle.x, y: areaStats.arcs[0].circle.y };
537
+ }
538
+ if (exterior.length) {
539
+ // try again without other circles
540
+ return computeTextCentre(interior, []);
541
+ }
542
+ // take average of all the points in the intersection
543
+ // polygon. this should basically never happen
544
+ // and has some issues:
545
+ // https://github.com/benfred/venn.js/issues/48#issuecomment-146069777
546
+ return getCenter(areaStats.arcs.map((a) => a.p1));
547
+ }
548
+
549
+ // given a dictionary of {setid : circle}, returns
550
+ // a dictionary of setid to list of circles that completely overlap it
551
+ function getOverlappingCircles(circles) {
552
+ const ret = {};
553
+ const circleids = Object.keys(circles);
554
+ for (const circleid of circleids) {
555
+ ret[circleid] = [];
556
+ }
557
+ for (let i = 0; i < circleids.length; i++) {
558
+ const ci = circleids[i];
559
+ const a = circles[ci];
560
+ for (let j = i + 1; j < circleids.length; ++j) {
561
+ const cj = circleids[j];
562
+ const b = circles[cj];
563
+ const d = distance(a, b);
564
+
565
+ if (d + b.radius <= a.radius + 1e-10) {
566
+ ret[cj].push(ci);
567
+ } else if (d + a.radius <= b.radius + 1e-10) {
568
+ ret[ci].push(cj);
569
+ }
570
+ }
571
+ }
572
+ return ret;
573
+ }
574
+
575
+ export function computeTextCentres(circles, areas, symmetricalTextCentre) {
576
+ const ret = {};
577
+ const overlapped = getOverlappingCircles(circles);
578
+ for (let i = 0; i < areas.length; ++i) {
579
+ const area = areas[i].sets;
580
+ const areaids = {};
581
+ const exclude = {};
582
+
583
+ for (let j = 0; j < area.length; ++j) {
584
+ areaids[area[j]] = true;
585
+ const overlaps = overlapped[area[j]];
586
+ // keep track of any circles that overlap this area,
587
+ // and don't consider for purposes of computing the text
588
+ // centre
589
+ for (let k = 0; k < overlaps.length; ++k) {
590
+ exclude[overlaps[k]] = true;
591
+ }
592
+ }
593
+
594
+ const interior = [];
595
+ const exterior = [];
596
+ for (let setid in circles) {
597
+ if (setid in areaids) {
598
+ interior.push(circles[setid]);
599
+ } else if (!(setid in exclude)) {
600
+ exterior.push(circles[setid]);
601
+ }
602
+ }
603
+ const centre = computeTextCentre(interior, exterior, symmetricalTextCentre);
604
+ ret[area] = centre;
605
+ if (centre.disjoint && areas[i].size > 0) {
606
+ console.log('WARNING: area ' + area + ' not represented on screen');
607
+ }
608
+ }
609
+ return ret;
610
+ }
611
+
612
+ // sorts all areas in the venn diagram, so that
613
+ // a particular area is on top (relativeTo) - and
614
+ // all other areas are so that the smallest areas are on top
615
+ export function sortAreas(div, relativeTo) {
616
+ // figure out sets that are completely overlapped by relativeTo
617
+ const overlaps = getOverlappingCircles(div.selectAll('svg').datum());
618
+ const exclude = new Set();
619
+ for (const check of relativeTo.sets) {
620
+ for (let setid in overlaps) {
621
+ const overlap = overlaps[setid];
622
+ for (let j = 0; j < overlap.length; ++j) {
623
+ if (overlap[j] == check) {
624
+ exclude.add(setid);
625
+ break;
626
+ }
627
+ }
628
+ }
629
+ }
630
+
631
+ // checks that all sets are in exclude;
632
+ function shouldExclude(sets) {
633
+ return sets.every((set) => !exclude.has(set));
634
+ }
635
+
636
+ // need to sort div's so that Z order is correct
637
+ div.selectAll('g').sort((a, b) => {
638
+ // highest order set intersections first
639
+ if (a.sets.length != b.sets.length) {
640
+ return a.sets.length - b.sets.length;
641
+ }
642
+
643
+ if (a == relativeTo) {
644
+ return shouldExclude(b.sets) ? -1 : 1;
645
+ }
646
+ if (b == relativeTo) {
647
+ return shouldExclude(a.sets) ? 1 : -1;
648
+ }
649
+
650
+ // finally by size
651
+ return b.size - a.size;
652
+ });
653
+ }
654
+
655
+ /**
656
+ * @param {number} x
657
+ * @param {number} y
658
+ * @param {number} r
659
+ * @returns {string}
660
+ */
661
+ export function circlePath(x, y, r) {
662
+ const ret = [];
663
+ ret.push('\nM', x, y);
664
+ ret.push('\nm', -r, 0);
665
+ ret.push('\na', r, r, 0, 1, 0, r * 2, 0);
666
+ ret.push('\na', r, r, 0, 1, 0, -r * 2, 0);
667
+ return ret.join(' ');
668
+ }
669
+
670
+ /**
671
+ * inverse of the circlePath function, returns a circle object from an svg path
672
+ * @param {string} path
673
+ * @returns {{x: number, y: number, radius: number}}
674
+ */
675
+ export function circleFromPath(path) {
676
+ const tokens = path.split(' ');
677
+ return { x: Number.parseFloat(tokens[1]), y: Number.parseFloat(tokens[2]), radius: -Number.parseFloat(tokens[4]) };
678
+ }
679
+
680
+ function intersectionAreaArcs(circles) {
681
+ if (circles.length === 0) {
682
+ return [];
683
+ }
684
+ const stats = {};
685
+ intersectionArea(circles, stats);
686
+ return stats.arcs;
687
+ }
688
+
689
+ function arcsToPath(arcs, round) {
690
+ if (arcs.length === 0) {
691
+ return 'M 0 0';
692
+ }
693
+ const rFactor = Math.pow(10, round || 0);
694
+ const r = round != null ? (v) => Math.round(v * rFactor) / rFactor : (v) => v;
695
+ if (arcs.length == 1) {
696
+ const circle = arcs[0].circle;
697
+ return circlePath(r(circle.x), r(circle.y), r(circle.radius));
698
+ }
699
+ // draw path around arcs
700
+ const ret = ['\nM', r(arcs[0].p2.x), r(arcs[0].p2.y)];
701
+ for (const arc of arcs) {
702
+ const radius = r(arc.circle.radius);
703
+ ret.push('\nA', radius, radius, 0, arc.large ? 1 : 0, arc.sweep ? 1 : 0, r(arc.p1.x), r(arc.p1.y));
704
+ }
705
+ return ret.join(' ');
706
+ }
707
+
708
+ /**
709
+ * returns a svg path of the intersection area of a bunch of circles
710
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
711
+ * @returns {string}
712
+ */
713
+ export function intersectionAreaPath(circles, round) {
714
+ return arcsToPath(intersectionAreaArcs(circles), round);
715
+ }
716
+
717
+ export function layout(data, options = {}) {
718
+ const {
719
+ lossFunction: loss,
720
+ layoutFunction: layout = venn,
721
+ normalize = true,
722
+ orientation = Math.PI / 2,
723
+ orientationOrder,
724
+ width = 600,
725
+ height = 350,
726
+ padding = 15,
727
+ scaleToFit = false,
728
+ symmetricalTextCentre = false,
729
+ distinct,
730
+ round = 2,
731
+ } = options;
732
+
733
+ let solution = layout(data, {
734
+ lossFunction: loss === 'default' || !loss ? lossFunction : loss === 'logRatio' ? logRatioLossFunction : loss,
735
+ distinct,
736
+ });
737
+
738
+ if (normalize) {
739
+ solution = normalizeSolution(solution, orientation, orientationOrder);
740
+ }
741
+
742
+ const circles = scaleSolution(solution, width, height, padding, scaleToFit);
743
+ const textCentres = computeTextCentres(circles, data, symmetricalTextCentre);
744
+
745
+ const circleLookup = new Map(
746
+ Object.keys(circles).map((set) => [
747
+ set,
748
+ {
749
+ set,
750
+ x: circles[set].x,
751
+ y: circles[set].y,
752
+ radius: circles[set].radius,
753
+ },
754
+ ])
755
+ );
756
+ const helpers = data.map((area) => {
757
+ const circles = area.sets.map((s) => circleLookup.get(s));
758
+ const arcs = intersectionAreaArcs(circles);
759
+ const path = arcsToPath(arcs, round);
760
+ return { circles, arcs, path, area, has: new Set(area.sets) };
761
+ });
762
+
763
+ function genDistinctPath(sets) {
764
+ let r = '';
765
+ for (const e of helpers) {
766
+ if (e.has.size > sets.length && sets.every((s) => e.has.has(s))) {
767
+ r += ' ' + e.path;
768
+ }
769
+ }
770
+ return r;
771
+ }
772
+
773
+ return helpers.map(({ circles, arcs, path, area }) => {
774
+ return {
775
+ data: area,
776
+ text: textCentres[area.sets],
777
+ circles,
778
+ arcs,
779
+ path,
780
+ distinctPath: path + genDistinctPath(area.sets),
781
+ };
782
+ });
783
+ }
tools/ui/node_modules/@upsetjs/venn.js/src/diagram.spec.js ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { computeTextCentre } from './diagram';
2
+ import { describe, test, expect } from 'vitest';
3
+
4
+ describe('computeTextCentre', () => {
5
+ test('0', () => {
6
+ const center = computeTextCentre([{ x: 0, y: 0, radius: 1 }], []);
7
+ expect(center.x).toBeCloseTo(0);
8
+ expect(center.y).toBeCloseTo(0);
9
+ });
10
+
11
+ test('1', () => {
12
+ const center = computeTextCentre([{ x: 0, y: 0, radius: 1 }], [{ x: 0, y: 1, radius: 1 }]);
13
+ expect(center.x).toBeCloseTo(0, 4);
14
+ expect(center.y).toBeCloseTo(-0.5);
15
+ });
16
+ });
tools/ui/node_modules/@upsetjs/venn.js/src/index.d.ts ADDED
@@ -0,0 +1,319 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { Selection } from 'd3-selection';
2
+
3
+ export interface ISetOverlap {
4
+ sets: readonly string[];
5
+ size: number;
6
+ weight?: number;
7
+ }
8
+
9
+ export interface IPoint {
10
+ x: number;
11
+ y: number;
12
+ }
13
+
14
+ export interface IHierarchyPoint extends IPoint {
15
+ parentIndex: [number, number];
16
+ }
17
+
18
+ export interface ICircle {
19
+ x: number;
20
+ y: number;
21
+ radius: number;
22
+ setid: string;
23
+ }
24
+
25
+ export interface ISolution {
26
+ [set: string]: ICircle;
27
+ }
28
+
29
+ /**
30
+ * given a list of set objects, and their corresponding overlaps
31
+ * updates the(x, y, radius) attribute on each set such that their positions
32
+ * roughly correspond to the desired overlaps
33
+ */
34
+ export function venn(areas: readonly ISetOverlap[], parameters?: any): ISolution;
35
+
36
+ /**
37
+ * Returns the distance necessary for two circles of radius r1 + r2 to
38
+ * have the overlap area 'overlap'
39
+ */
40
+ export function distanceFromIntersectArea(r1: number, r2: number, overlap: number): number;
41
+
42
+ /**
43
+ * takes the best working variant of either constrained MDS or greedy
44
+ */
45
+ export function bestInitialLayout(areas: readonly ISetOverlap[], params?: any): ISolution;
46
+
47
+ /**
48
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
49
+ * least overlapped, attempting to position each new set such that the
50
+ * overlapping areas to already positioned sets are basically right
51
+ */
52
+ export function greedyLayout(areas: readonly ISetOverlap[], params?: any): ISolution;
53
+
54
+ /**
55
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
56
+ * the distance from the actual overlaps to the desired overlaps. Note that
57
+ * this method ignores overlaps of more than 2 circles
58
+ */
59
+ export function lossFunction(circles: ISolution, areas: readonly ISetOverlap[]): number;
60
+
61
+ export function logRatioLossFunction(circles: ISolution, areas: readonly ISetOverlap[]): number;
62
+
63
+ export function disjointCluster(circles: ICircle[]): ICircle[][];
64
+
65
+ export function normalizeSolution(
66
+ solution: ISolution,
67
+ orientation?: number,
68
+ orientationOrder?: (a: ICircle, b: ICircle) => number
69
+ ): ISolution;
70
+
71
+ /**
72
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
73
+ * a rectangle of width/height - with padding around the borders. also
74
+ * centers the diagram in the available space at the same time.
75
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
76
+ */
77
+ export function scaleSolution(
78
+ solution: ISolution,
79
+ width: number,
80
+ height: number,
81
+ padding: number,
82
+ scaleToFit?: boolean
83
+ ): ISolution;
84
+
85
+ /**
86
+ * Returns the intersection area of a bunch of circles (where each circle
87
+ * is an object having an x,y and radius property)
88
+ */
89
+ export function intersectionArea(
90
+ circles: readonly ICircle[],
91
+ stats?: {
92
+ area?: number;
93
+ areaArea?: number;
94
+ polygonArea?: number;
95
+ arcs?: readonly { circle: ICircle; width: number; p1: IPoint; p2: IPoint }[];
96
+ innerPoints?: readonly IHierarchyPoint[];
97
+ intersectionPoints?: readonly IHierarchyPoint[];
98
+ }
99
+ ): number;
100
+
101
+ /**
102
+ * Circular segment area calculation. See http://mathworld.wolfram.com/CircularSegment.html
103
+ */
104
+ export function circleArea(r: number, width: number): number;
105
+
106
+ /**
107
+ * euclidean distance between two points
108
+ */
109
+ export function distance(p1: IPoint, p2: IPoint): number;
110
+
111
+ /**
112
+ * Returns the overlap area of two circles of radius r1 and r2 - that
113
+ * have their centers separated by distance d. Simpler faster
114
+ * circle intersection for only two circles
115
+ */
116
+ export function circleOverlap(r1: number, r2: number, d: number): number;
117
+
118
+ /**
119
+ * Given two circles (containing a x/y/radius attributes),
120
+ * returns the intersecting points if possible
121
+ * note: doesn't handle cases where there are infinitely many
122
+ * intersection points (circles are equivalent):, or only one intersection point
123
+ */
124
+ export function circleCircleIntersection(p1: ICircle, p2: ICircle): readonly IPoint[];
125
+
126
+ // sometimes text doesn't fit inside the circle, if thats the case lets wrap
127
+ // the text here such that it fits
128
+ // todo: looks like this might be merged into d3 (
129
+ // https://github.com/mbostock/d3/issues/1642),
130
+ // also worth checking out is
131
+ // http://engineering.findthebest.com/wrapping-axis-labels-in-d3-js/
132
+ // this seems to be one of those things that should be easy but isn't
133
+ export function wrapText(circles: ISolution, labeller: (d: any) => string): (this: SVGTextElement) => void;
134
+
135
+ /**
136
+ * compute the center of some circles by maximizing the margin of
137
+ * the center point relative to the circles (interior) after subtracting
138
+ * nearby circles (exterior)
139
+ * @param {readonly {x: number, y: number, radius: number}[]} interior
140
+ * @param {readonly {x: number, y: number, radius: number}[]} exterior
141
+ * @param {boolean} symmetricalTextCentre
142
+ * @returns {{x:number, y: number}}
143
+ */
144
+ export function computeTextCentre(
145
+ interior: readonly ICircle[],
146
+ exterior: readonly ICircle[],
147
+ symmetricalTextCentre?: boolean
148
+ ): IPoint;
149
+
150
+ export function computeTextCentres(
151
+ circles: ISolution,
152
+ areas: readonly ISetOverlap[],
153
+ symmetricalTextCentre?: boolean
154
+ ): { [set: string]: IPoint };
155
+
156
+ // sorts all areas in the venn diagram, so that
157
+ // a particular area is on top (relativeTo) - and
158
+ // all other areas are so that the smallest areas are on top
159
+ export function sortAreas(div: Selection<any, any, any, unknown>, relativeTo: { sets: readonly string[] }): void;
160
+
161
+ export function circlePath(x: number, y: number, r: number): string;
162
+
163
+ /**
164
+ * inverse of the circlePath function, returns a circle object from an svg path
165
+ */
166
+ export function circleFromPath(path: string): ICircle;
167
+
168
+ /**
169
+ * returns a svg path of the intersection area of a bunch of circles
170
+ */
171
+ export function intersectionAreaPath(circles: readonly ICircle[]): string;
172
+
173
+ export interface IVennDiagramOptions {
174
+ colourScheme?: readonly string[];
175
+ colorScheme?: readonly string[];
176
+ symmetricalTextCentre?: boolean;
177
+ textFill?: string;
178
+ }
179
+
180
+ export interface IStyledSetOverlap extends ISetOverlap {
181
+ color?: string;
182
+ colour?: string;
183
+ }
184
+
185
+ export interface IVennDiagram {
186
+ (selection: Selection<HTMLElement, readonly IStyledSetOverlap[], any, any>): {
187
+ circles: ISolution;
188
+ textCentres: { [set: string]: IPoint };
189
+ nodes: Selection<SVGGElement, IStyledSetOverlap, any, unknown>;
190
+ enter: Selection<SVGGElement, IStyledSetOverlap, any, unknown>;
191
+ update: Selection<SVGGElement, IStyledSetOverlap, any, unknown>;
192
+ exit: Selection<SVGGElement, IStyledSetOverlap, any, unknown>;
193
+ };
194
+
195
+ /**
196
+ * wrap the labels
197
+ * @default true
198
+ */
199
+ wrap(): boolean;
200
+ wrap(v: boolean): this;
201
+ /**
202
+ * use a view box instead of specifying with and height
203
+ * @default false
204
+ */
205
+ useViewBox(): this;
206
+
207
+ width(): number;
208
+ width(v: number): this;
209
+ height(): number;
210
+ height(v: number): this;
211
+ padding(): number;
212
+ padding(v: number): this;
213
+ colours(): (key: string) => string;
214
+ colours(v: (key: string) => string): this;
215
+ colors(): (key: string) => string;
216
+ colors(v: (key: string) => string): this;
217
+ fontSize(): string | null;
218
+ fontSize(v: string | null): this;
219
+
220
+ duration(): number;
221
+ duration(v: number): this;
222
+
223
+ /**
224
+ * normalize the solution
225
+ * @default true
226
+ */
227
+ normalize(): boolean;
228
+ normalize(v: boolean): this;
229
+ layoutFunction(): typeof venn;
230
+ layoutFunction(v: typeof venn): this;
231
+
232
+ scaleToFit(): boolean;
233
+ scaleToFit(v: boolean): this;
234
+
235
+ styled(): boolean;
236
+ styled(v: boolean): this;
237
+
238
+ /**
239
+ * round generate path to the given number of digits or null to disable
240
+ * @default null
241
+ */
242
+ round(): number | null;
243
+ round(v: number | null): this;
244
+
245
+ /**
246
+ * interpret the data as distinct sets, so set A is actually set A \ B u C
247
+ * thus A is (A \ (B u C)) u (A ^ B \ C) u (A ^ C \ B) u (A ^ B ^ C)
248
+ * @default false
249
+ */
250
+ distinct(): boolean;
251
+ distinct(v: boolean): this;
252
+
253
+ orientation(): number;
254
+ orientation(v: number): this;
255
+ orientationOrder(): null | ((a: ICircle, b: ICircle) => number);
256
+ orientationOrder(v: null | ((a: ICircle, b: ICircle) => number)): this;
257
+
258
+ lossFunction(): typeof lossFunction;
259
+ lossFunction(v: 'logRatio'): this;
260
+ lossFunction(v: 'default'): this;
261
+ lossFunction(v: typeof lossFunction): this;
262
+ }
263
+
264
+ /**
265
+ * VennDiagram includes an optional `options` parameter containing the following option(s):
266
+ *
267
+ * `colourScheme: Array<String>`
268
+ * A list of color values to be applied when coloring diagram circles.
269
+ *
270
+ * `symmetricalTextCentre: Boolean`
271
+ * Whether to symmetrically center each circle's text horizontally and vertically.
272
+ * Defaults to `false`.
273
+ *
274
+ * `textFill: String`
275
+ * The color to be applied to the text within each circle.
276
+ */
277
+ export function VennDiagram(options?: IVennDiagramOptions): IVennDiagram;
278
+
279
+ export interface IComputeVennLayoutOptions {
280
+ width?: number;
281
+ height?: number;
282
+ padding?: number;
283
+ /**
284
+ * @default true
285
+ */
286
+ normalize?: boolean;
287
+ layoutFunction?: typeof venn;
288
+ lossFunction?: typeof lossFunction | 'logRatio';
289
+ scaleToFit?: boolean;
290
+ orientation?: number;
291
+ distinct?: boolean;
292
+ /**
293
+ * @default 2
294
+ */
295
+ round?: number;
296
+ orientationOrder?: (a: ICircle, b: ICircle) => number;
297
+ }
298
+
299
+ export interface IVennLayout<T> {
300
+ data: T;
301
+ /**
302
+ * text location
303
+ */
304
+ text: IPoint;
305
+ circles: readonly (ICircle & { set: string })[];
306
+ arcs: readonly { circle: ICircle; width: number; p1: IPoint; p2: IPoint; large: boolean; sweep: boolean }[];
307
+ /**
308
+ * SVG path
309
+ */
310
+ path: string;
311
+ /**
312
+ * distinct SVG path, render with `fill-rule: evenodd`;
313
+ */
314
+ distinctPath: string;
315
+ }
316
+ export function layout<T extends ISetOverlap>(
317
+ data: readonly T[],
318
+ options?: IComputeVennLayoutOptions
319
+ ): IVennLayout<T>[];
tools/ui/node_modules/@upsetjs/venn.js/src/index.js ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ export { intersectionArea, circleCircleIntersection, circleOverlap, circleArea, distance } from './circleintersection';
2
+ export {
3
+ venn,
4
+ greedyLayout,
5
+ scaleSolution,
6
+ normalizeSolution,
7
+ bestInitialLayout,
8
+ lossFunction,
9
+ logRatioLossFunction,
10
+ disjointCluster,
11
+ distanceFromIntersectArea,
12
+ } from './layout';
13
+ export {
14
+ VennDiagram,
15
+ wrapText,
16
+ computeTextCentres,
17
+ computeTextCentre,
18
+ sortAreas,
19
+ circlePath,
20
+ circleFromPath,
21
+ intersectionAreaPath,
22
+ layout,
23
+ } from './diagram';
tools/ui/node_modules/@upsetjs/venn.js/src/layout.js ADDED
@@ -0,0 +1,820 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { nelderMead, bisect, conjugateGradient, zeros, zerosM, norm2, scale } from 'fmin';
2
+ import { intersectionArea, circleOverlap, circleCircleIntersection, distance } from './circleintersection';
3
+
4
+ /**
5
+ * given a list of set objects, and their corresponding overlaps
6
+ * updates the (x, y, radius) attribute on each set such that their positions
7
+ * roughly correspond to the desired overlaps
8
+ * @param {readonly {sets: readonly string[]; size: number; weight?: number}[]} sets
9
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
10
+ */
11
+ export function venn(sets, parameters = {}) {
12
+ parameters.maxIterations = parameters.maxIterations || 500;
13
+
14
+ const initialLayout = parameters.initialLayout || bestInitialLayout;
15
+ const loss = parameters.lossFunction || lossFunction;
16
+
17
+ // add in missing pairwise areas as having 0 size
18
+ const areas = addMissingAreas(sets, parameters);
19
+
20
+ // initial layout is done greedily
21
+ const circles = initialLayout(areas, parameters);
22
+
23
+ // transform x/y coordinates to a vector to optimize
24
+ const setids = Object.keys(circles);
25
+ /** @type {number[]} */
26
+ const initial = [];
27
+ for (const setid of setids) {
28
+ initial.push(circles[setid].x);
29
+ initial.push(circles[setid].y);
30
+ }
31
+
32
+ // optimize initial layout from our loss function
33
+ const solution = nelderMead(
34
+ (values) => {
35
+ const current = {};
36
+ for (let i = 0; i < setids.length; ++i) {
37
+ const setid = setids[i];
38
+ current[setid] = {
39
+ x: values[2 * i],
40
+ y: values[2 * i + 1],
41
+ radius: circles[setid].radius,
42
+ // size : circles[setid].size
43
+ };
44
+ }
45
+ return loss(current, areas);
46
+ },
47
+ initial,
48
+ parameters
49
+ );
50
+
51
+ // transform solution vector back to x/y points
52
+ const positions = solution.x;
53
+ for (let i = 0; i < setids.length; ++i) {
54
+ const setid = setids[i];
55
+ circles[setid].x = positions[2 * i];
56
+ circles[setid].y = positions[2 * i + 1];
57
+ }
58
+
59
+ return circles;
60
+ }
61
+
62
+ const SMALL = 1e-10;
63
+
64
+ /**
65
+ * Returns the distance necessary for two circles of radius r1 + r2 to
66
+ * have the overlap area 'overlap'
67
+ * @param {number} r1
68
+ * @param {number} r2
69
+ * @param {number} overlap
70
+ * @returns {number}
71
+ */
72
+ export function distanceFromIntersectArea(r1, r2, overlap) {
73
+ // handle complete overlapped circles
74
+ if (Math.min(r1, r2) * Math.min(r1, r2) * Math.PI <= overlap + SMALL) {
75
+ return Math.abs(r1 - r2);
76
+ }
77
+
78
+ return bisect((distance) => circleOverlap(r1, r2, distance) - overlap, 0, r1 + r2);
79
+ }
80
+
81
+ /**
82
+ * Missing pair-wise intersection area data can cause problems:
83
+ * treating as an unknown means that sets will be laid out overlapping,
84
+ * which isn't what people expect. To reflect that we want disjoint sets
85
+ * here, set the overlap to 0 for all missing pairwise set intersections
86
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
87
+ * @returns {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>}
88
+ */
89
+ function addMissingAreas(areas, parameters = {}) {
90
+ const distinct = parameters.distinct;
91
+ const r = areas.map((s) => Object.assign({}, s));
92
+
93
+ function toKey(arr) {
94
+ return arr.join(';');
95
+ }
96
+
97
+ if (distinct) {
98
+ // recreate the full ones by adding things up but just to level two since the rest doesn't matter
99
+ /** @types Map<string, number> */
100
+ const count = new Map();
101
+ for (const area of r) {
102
+ for (let i = 0; i < area.sets.length; i++) {
103
+ const si = String(area.sets[i]);
104
+ count.set(si, area.size + (count.get(si) || 0));
105
+ for (let j = i + 1; j < area.sets.length; j++) {
106
+ const sj = String(area.sets[j]);
107
+ const k1 = `${si};${sj}`;
108
+ const k2 = `${sj};${si}`;
109
+ count.set(k1, area.size + (count.get(k1) || 0));
110
+ count.set(k2, area.size + (count.get(k2) || 0));
111
+ }
112
+ }
113
+ }
114
+ for (const area of r) {
115
+ if (area.sets.length < 3) {
116
+ area.size = count.get(toKey(area.sets));
117
+ }
118
+ }
119
+ }
120
+
121
+ // two circle intersections that aren't defined
122
+ const ids = [];
123
+
124
+ /** @type {Set<string>} */
125
+ const pairs = new Set();
126
+ for (const area of r) {
127
+ if (area.sets.length === 1) {
128
+ ids.push(area.sets[0]);
129
+ } else if (area.sets.length === 2) {
130
+ const a = area.sets[0];
131
+ const b = area.sets[1];
132
+ pairs.add(toKey(area.sets));
133
+ pairs.add(toKey([b, a]));
134
+ }
135
+ }
136
+
137
+ ids.sort((a, b) => (a === b ? 0 : a < b ? -1 : +1));
138
+
139
+ for (let i = 0; i < ids.length; ++i) {
140
+ const a = ids[i];
141
+ for (let j = i + 1; j < ids.length; ++j) {
142
+ const b = ids[j];
143
+ if (!pairs.has(toKey([a, b]))) {
144
+ r.push({ sets: [a, b], size: 0 });
145
+ }
146
+ }
147
+ }
148
+ return r;
149
+ }
150
+
151
+ /**
152
+ * Returns two matrices, one of the euclidean distances between the sets
153
+ * and the other indicating if there are subset or disjoint set relationships
154
+ * @param {ReadonlyArray<{sets: ReadonlyArray<number>}>} areas
155
+ * @param {ReadonlyArray<{size: number}>} sets
156
+ * @param {ReadonlyArray<number>} setids
157
+ */
158
+ export function getDistanceMatrices(areas, sets, setids) {
159
+ // initialize an empty distance matrix between all the points
160
+ /**
161
+ * @type {number[][]}
162
+ */
163
+ const distances = zerosM(sets.length, sets.length);
164
+ /**
165
+ * @type {number[][]}
166
+ */
167
+ const constraints = zerosM(sets.length, sets.length);
168
+
169
+ // compute required distances between all the sets such that
170
+ // the areas match
171
+ areas
172
+ .filter((x) => x.sets.length === 2)
173
+ .forEach((current) => {
174
+ const left = setids[current.sets[0]];
175
+ const right = setids[current.sets[1]];
176
+ const r1 = Math.sqrt(sets[left].size / Math.PI);
177
+ const r2 = Math.sqrt(sets[right].size / Math.PI);
178
+ const distance = distanceFromIntersectArea(r1, r2, current.size);
179
+
180
+ distances[left][right] = distances[right][left] = distance;
181
+
182
+ // also update constraints to indicate if its a subset or disjoint
183
+ // relationship
184
+ let c = 0;
185
+ if (current.size + 1e-10 >= Math.min(sets[left].size, sets[right].size)) {
186
+ c = 1;
187
+ } else if (current.size <= 1e-10) {
188
+ c = -1;
189
+ }
190
+ constraints[left][right] = constraints[right][left] = c;
191
+ });
192
+
193
+ return { distances, constraints };
194
+ }
195
+
196
+ /// computes the gradient and loss simultaneously for our constrained MDS optimizer
197
+ function constrainedMDSGradient(x, fxprime, distances, constraints) {
198
+ for (let i = 0; i < fxprime.length; ++i) {
199
+ fxprime[i] = 0;
200
+ }
201
+
202
+ let loss = 0;
203
+ for (let i = 0; i < distances.length; ++i) {
204
+ const xi = x[2 * i];
205
+ const yi = x[2 * i + 1];
206
+ for (let j = i + 1; j < distances.length; ++j) {
207
+ const xj = x[2 * j];
208
+ const yj = x[2 * j + 1];
209
+ const dij = distances[i][j];
210
+ const constraint = constraints[i][j];
211
+
212
+ const squaredDistance = (xj - xi) * (xj - xi) + (yj - yi) * (yj - yi);
213
+ const distance = Math.sqrt(squaredDistance);
214
+ const delta = squaredDistance - dij * dij;
215
+
216
+ if ((constraint > 0 && distance <= dij) || (constraint < 0 && distance >= dij)) {
217
+ continue;
218
+ }
219
+
220
+ loss += 2 * delta * delta;
221
+
222
+ fxprime[2 * i] += 4 * delta * (xi - xj);
223
+ fxprime[2 * i + 1] += 4 * delta * (yi - yj);
224
+
225
+ fxprime[2 * j] += 4 * delta * (xj - xi);
226
+ fxprime[2 * j + 1] += 4 * delta * (yj - yi);
227
+ }
228
+ }
229
+ return loss;
230
+ }
231
+
232
+ /**
233
+ * takes the best working variant of either constrained MDS or greedy
234
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
235
+ */
236
+ export function bestInitialLayout(areas, params = {}) {
237
+ let initial = greedyLayout(areas, params);
238
+ const loss = params.lossFunction || lossFunction;
239
+
240
+ // greedylayout is sufficient for all 2/3 circle cases. try out
241
+ // constrained MDS for higher order problems, take its output
242
+ // if it outperforms. (greedy is aesthetically better on 2/3 circles
243
+ // since it axis aligns)
244
+ if (areas.length >= 8) {
245
+ const constrained = constrainedMDSLayout(areas, params);
246
+ const constrainedLoss = loss(constrained, areas);
247
+ const greedyLoss = loss(initial, areas);
248
+
249
+ if (constrainedLoss + 1e-8 < greedyLoss) {
250
+ initial = constrained;
251
+ }
252
+ }
253
+ return initial;
254
+ }
255
+
256
+ /**
257
+ * use the constrained MDS variant to generate an initial layout
258
+ * @param {ReadonlyArray<{sets: ReadonlyArray<string>, size: number}>} areas
259
+ * @returns {{[key: string]: {x: number, y: number, radius: number}}}
260
+ */
261
+ export function constrainedMDSLayout(areas, params = {}) {
262
+ const restarts = params.restarts || 10;
263
+
264
+ // bidirectionally map sets to a rowid (so we can create a matrix)
265
+ const sets = [];
266
+ const setids = {};
267
+ for (const area of areas) {
268
+ if (area.sets.length === 1) {
269
+ setids[area.sets[0]] = sets.length;
270
+ sets.push(area);
271
+ }
272
+ }
273
+
274
+ let { distances, constraints } = getDistanceMatrices(areas, sets, setids);
275
+
276
+ // keep distances bounded, things get messed up otherwise.
277
+ // TODO: proper preconditioner?
278
+ const norm = norm2(distances.map(norm2)) / distances.length;
279
+ distances = distances.map((row) => row.map((value) => value / norm));
280
+
281
+ const obj = (x, fxprime) => constrainedMDSGradient(x, fxprime, distances, constraints);
282
+
283
+ let best = null;
284
+ for (let i = 0; i < restarts; ++i) {
285
+ const initial = zeros(distances.length * 2).map(Math.random);
286
+
287
+ const current = conjugateGradient(obj, initial, params);
288
+ if (!best || current.fx < best.fx) {
289
+ best = current;
290
+ }
291
+ }
292
+
293
+ const positions = best.x;
294
+
295
+ // translate rows back to (x,y,radius) coordinates
296
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
297
+ const circles = {};
298
+ for (let i = 0; i < sets.length; ++i) {
299
+ const set = sets[i];
300
+ circles[set.sets[0]] = {
301
+ x: positions[2 * i] * norm,
302
+ y: positions[2 * i + 1] * norm,
303
+ radius: Math.sqrt(set.size / Math.PI),
304
+ };
305
+ }
306
+
307
+ if (params.history) {
308
+ for (const h of params.history) {
309
+ scale(h.x, norm);
310
+ }
311
+ }
312
+ return circles;
313
+ }
314
+
315
+ /**
316
+ * Lays out a Venn diagram greedily, going from most overlapped sets to
317
+ * least overlapped, attempting to position each new set such that the
318
+ * overlapping areas to already positioned sets are basically right
319
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>}>} areas
320
+ * @return {{[key: string]: {x: number, y: number, radius: number}}}
321
+ */
322
+ export function greedyLayout(areas, params) {
323
+ const loss = params && params.lossFunction ? params.lossFunction : lossFunction;
324
+
325
+ // define a circle for each set
326
+ /** @type {{[key: string]: {x: number, y: number, radius: number}}} */
327
+ const circles = {};
328
+ /** @type {{[key: string]: {set: string, size: number, weight: number}[]}} */
329
+ const setOverlaps = {};
330
+ for (const area of areas) {
331
+ if (area.sets.length === 1) {
332
+ const set = area.sets[0];
333
+ circles[set] = {
334
+ x: 1e10,
335
+ y: 1e10,
336
+ rowid: circles.length,
337
+ size: area.size,
338
+ radius: Math.sqrt(area.size / Math.PI),
339
+ };
340
+ setOverlaps[set] = [];
341
+ }
342
+ }
343
+
344
+ areas = areas.filter((a) => a.sets.length === 2);
345
+
346
+ // map each set to a list of all the other sets that overlap it
347
+ for (const current of areas) {
348
+ let weight = current.weight != null ? current.weight : 1.0;
349
+ const left = current.sets[0];
350
+ const right = current.sets[1];
351
+
352
+ // completely overlapped circles shouldn't be positioned early here
353
+ if (current.size + SMALL >= Math.min(circles[left].size, circles[right].size)) {
354
+ weight = 0;
355
+ }
356
+
357
+ setOverlaps[left].push({ set: right, size: current.size, weight });
358
+ setOverlaps[right].push({ set: left, size: current.size, weight });
359
+ }
360
+
361
+ // get list of most overlapped sets
362
+ const mostOverlapped = [];
363
+ Object.keys(setOverlaps).forEach((set) => {
364
+ let size = 0;
365
+ for (let i = 0; i < setOverlaps[set].length; ++i) {
366
+ size += setOverlaps[set][i].size * setOverlaps[set][i].weight;
367
+ }
368
+
369
+ mostOverlapped.push({ set, size });
370
+ });
371
+
372
+ // sort by size desc
373
+ function sortOrder(a, b) {
374
+ return b.size - a.size;
375
+ }
376
+ mostOverlapped.sort(sortOrder);
377
+
378
+ // keep track of what sets have been laid out
379
+ const positioned = {};
380
+ function isPositioned(element) {
381
+ return element.set in positioned;
382
+ }
383
+
384
+ /**
385
+ * adds a point to the output
386
+ * @param {{x: number, y: number}} point
387
+ * @param {number} index
388
+ */
389
+ function positionSet(point, index) {
390
+ circles[index].x = point.x;
391
+ circles[index].y = point.y;
392
+ positioned[index] = true;
393
+ }
394
+
395
+ // add most overlapped set at (0,0)
396
+ positionSet({ x: 0, y: 0 }, mostOverlapped[0].set);
397
+
398
+ // get distances between all points. TODO, necessary?
399
+ // answer: probably not
400
+ // var distances = venn.getDistanceMatrices(circles, areas).distances;
401
+ for (let i = 1; i < mostOverlapped.length; ++i) {
402
+ const setIndex = mostOverlapped[i].set;
403
+ const overlap = setOverlaps[setIndex].filter(isPositioned);
404
+ const set = circles[setIndex];
405
+ overlap.sort(sortOrder);
406
+
407
+ if (overlap.length === 0) {
408
+ // this shouldn't happen anymore with addMissingAreas
409
+ throw 'ERROR: missing pairwise overlap information';
410
+ }
411
+
412
+ /** @type {{x: number, y: number}[]} */
413
+ const points = [];
414
+ for (var j = 0; j < overlap.length; ++j) {
415
+ // get appropriate distance from most overlapped already added set
416
+ const p1 = circles[overlap[j].set];
417
+ const d1 = distanceFromIntersectArea(set.radius, p1.radius, overlap[j].size);
418
+
419
+ // sample positions at 90 degrees for maximum aesthetics
420
+ points.push({ x: p1.x + d1, y: p1.y });
421
+ points.push({ x: p1.x - d1, y: p1.y });
422
+ points.push({ y: p1.y + d1, x: p1.x });
423
+ points.push({ y: p1.y - d1, x: p1.x });
424
+
425
+ // if we have at least 2 overlaps, then figure out where the
426
+ // set should be positioned analytically and try those too
427
+ for (let k = j + 1; k < overlap.length; ++k) {
428
+ const p2 = circles[overlap[k].set];
429
+ const d2 = distanceFromIntersectArea(set.radius, p2.radius, overlap[k].size);
430
+
431
+ const extraPoints = circleCircleIntersection(
432
+ { x: p1.x, y: p1.y, radius: d1 },
433
+ { x: p2.x, y: p2.y, radius: d2 }
434
+ );
435
+ points.push(...extraPoints);
436
+ }
437
+ }
438
+
439
+ // we have some candidate positions for the set, examine loss
440
+ // at each position to figure out where to put it at
441
+ let bestLoss = 1e50;
442
+ let bestPoint = points[0];
443
+ for (const point of points) {
444
+ circles[setIndex].x = point.x;
445
+ circles[setIndex].y = point.y;
446
+ const localLoss = loss(circles, areas);
447
+ if (localLoss < bestLoss) {
448
+ bestLoss = localLoss;
449
+ bestPoint = point;
450
+ }
451
+ }
452
+
453
+ positionSet(bestPoint, setIndex);
454
+ }
455
+
456
+ return circles;
457
+ }
458
+
459
+ /**
460
+ * Given a bunch of sets, and the desired overlaps between these sets - computes
461
+ * the distance from the actual overlaps to the desired overlaps. Note that
462
+ * this method ignores overlaps of more than 2 circles
463
+ * @param {{[key: string]: <{x: number, y: number, radius: number}>}} circles
464
+ * @param {ReadonlyArray<{size: number, sets: ReadonlyArray<string>, weight?: number}>} overlaps
465
+ * @returns {number}
466
+ */
467
+ export function lossFunction(circles, overlaps) {
468
+ let output = 0;
469
+
470
+ for (const area of overlaps) {
471
+ if (area.sets.length === 1) {
472
+ continue;
473
+ }
474
+ /** @type {number} */
475
+ let overlap;
476
+ if (area.sets.length === 2) {
477
+ const left = circles[area.sets[0]];
478
+ const right = circles[area.sets[1]];
479
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
480
+ } else {
481
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
482
+ }
483
+
484
+ const weight = area.weight != null ? area.weight : 1.0;
485
+ output += weight * (overlap - area.size) * (overlap - area.size);
486
+ }
487
+
488
+ return output;
489
+ }
490
+
491
+ export function logRatioLossFunction(circles, overlaps) {
492
+ let output = 0;
493
+
494
+ for (const area of overlaps) {
495
+ if (area.sets.length === 1) {
496
+ continue;
497
+ }
498
+ /** @type {number} */
499
+ let overlap;
500
+ if (area.sets.length === 2) {
501
+ const left = circles[area.sets[0]];
502
+ const right = circles[area.sets[1]];
503
+ overlap = circleOverlap(left.radius, right.radius, distance(left, right));
504
+ } else {
505
+ overlap = intersectionArea(area.sets.map((d) => circles[d]));
506
+ }
507
+
508
+ const weight = area.weight != null ? area.weight : 1.0;
509
+ const differenceFromIdeal = Math.log((overlap + 1) / (area.size + 1));
510
+ output += weight * differenceFromIdeal * differenceFromIdeal;
511
+ }
512
+
513
+ return output;
514
+ }
515
+
516
+ /**
517
+ * orientates a bunch of circles to point in orientation
518
+ * @param {{x :number, y: number, radius: number}[]} circles
519
+ * @param {number | undefined} orientation
520
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
521
+ */
522
+ function orientateCircles(circles, orientation, orientationOrder) {
523
+ if (orientationOrder == null) {
524
+ circles.sort((a, b) => b.radius - a.radius);
525
+ } else {
526
+ circles.sort(orientationOrder);
527
+ }
528
+
529
+ // shift circles so largest circle is at (0, 0)
530
+ if (circles.length > 0) {
531
+ const largestX = circles[0].x;
532
+ const largestY = circles[0].y;
533
+
534
+ for (const circle of circles) {
535
+ circle.x -= largestX;
536
+ circle.y -= largestY;
537
+ }
538
+ }
539
+
540
+ if (circles.length === 2) {
541
+ // if the second circle is a subset of the first, arrange so that
542
+ // it is off to one side. hack for https://github.com/benfred/venn.js/issues/120
543
+ const dist = distance(circles[0], circles[1]);
544
+ if (dist < Math.abs(circles[1].radius - circles[0].radius)) {
545
+ circles[1].x = circles[0].x + circles[0].radius - circles[1].radius - 1e-10;
546
+ circles[1].y = circles[0].y;
547
+ }
548
+ }
549
+
550
+ // rotate circles so that second largest is at an angle of 'orientation'
551
+ // from largest
552
+ if (circles.length > 1) {
553
+ const rotation = Math.atan2(circles[1].x, circles[1].y) - orientation;
554
+ const c = Math.cos(rotation);
555
+ const s = Math.sin(rotation);
556
+
557
+ for (const circle of circles) {
558
+ const x = circle.x;
559
+ const y = circle.y;
560
+ circle.x = c * x - s * y;
561
+ circle.y = s * x + c * y;
562
+ }
563
+ }
564
+
565
+ // mirror solution if third solution is above plane specified by
566
+ // first two circles
567
+ if (circles.length > 2) {
568
+ let angle = Math.atan2(circles[2].x, circles[2].y) - orientation;
569
+ while (angle < 0) {
570
+ angle += 2 * Math.PI;
571
+ }
572
+ while (angle > 2 * Math.PI) {
573
+ angle -= 2 * Math.PI;
574
+ }
575
+ if (angle > Math.PI) {
576
+ const slope = circles[1].y / (1e-10 + circles[1].x);
577
+ for (const circle of circles) {
578
+ var d = (circle.x + slope * circle.y) / (1 + slope * slope);
579
+ circle.x = 2 * d - circle.x;
580
+ circle.y = 2 * d * slope - circle.y;
581
+ }
582
+ }
583
+ }
584
+ }
585
+
586
+ /**
587
+ *
588
+ * @param {ReadonlyArray<{x: number, y: number, radius: number}>} circles
589
+ * @returns {{x: number, y: number, radius: number}[][]}
590
+ */
591
+ export function disjointCluster(circles) {
592
+ // union-find clustering to get disjoint sets
593
+ circles.forEach((circle) => {
594
+ circle.parent = circle;
595
+ });
596
+
597
+ // path compression step in union find
598
+ function find(circle) {
599
+ if (circle.parent !== circle) {
600
+ circle.parent = find(circle.parent);
601
+ }
602
+ return circle.parent;
603
+ }
604
+
605
+ function union(x, y) {
606
+ const xRoot = find(x);
607
+ const yRoot = find(y);
608
+ xRoot.parent = yRoot;
609
+ }
610
+
611
+ // get the union of all overlapping sets
612
+ for (let i = 0; i < circles.length; ++i) {
613
+ for (let j = i + 1; j < circles.length; ++j) {
614
+ const maxDistance = circles[i].radius + circles[j].radius;
615
+ if (distance(circles[i], circles[j]) + 1e-10 < maxDistance) {
616
+ union(circles[j], circles[i]);
617
+ }
618
+ }
619
+ }
620
+
621
+ // find all the disjoint clusters and group them together
622
+ /** @type {Map<string, {x: number, y: number, radius: number}[]>} */
623
+ const disjointClusters = new Map();
624
+ for (let i = 0; i < circles.length; ++i) {
625
+ const setid = find(circles[i]).parent.setid;
626
+ if (!disjointClusters.has(setid)) {
627
+ disjointClusters.set(setid, []);
628
+ }
629
+ disjointClusters.get(setid).push(circles[i]);
630
+ }
631
+
632
+ // cleanup bookkeeping
633
+ circles.forEach((circle) => {
634
+ delete circle.parent;
635
+ });
636
+
637
+ // return in more usable form
638
+ return Array.from(disjointClusters.values());
639
+ }
640
+
641
+ /**
642
+ * @param {ReadonlyArray<{x :number, y: number, radius: number}>} circles
643
+ * @returns {{xRange: [number, number], yRange: [number, number]}}
644
+ */
645
+ function getBoundingBox(circles) {
646
+ const minMax = (d) => {
647
+ const hi = circles.reduce((acc, c) => Math.max(acc, c[d] + c.radius), Number.NEGATIVE_INFINITY);
648
+ const lo = circles.reduce((acc, c) => Math.min(acc, c[d] - c.radius), Number.POSITIVE_INFINITY);
649
+ return { max: hi, min: lo };
650
+ };
651
+ return { xRange: minMax('x'), yRange: minMax('y') };
652
+ }
653
+
654
+ /**
655
+ *
656
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
657
+ * @param {undefined | number} orientation
658
+ * @param {((a: {x :number, y: number, radius: number}, b: {x :number, y: number, radius: number}) => number) | undefined} orientationOrder
659
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
660
+ */
661
+ export function normalizeSolution(solution, orientation, orientationOrder) {
662
+ if (orientation == null) {
663
+ orientation = Math.PI / 2;
664
+ }
665
+
666
+ // work with a list instead of a dictionary, and take a copy so we
667
+ // don't mutate input
668
+ let circles = fromObjectNotation(solution).map((d) => Object.assign({}, d));
669
+
670
+ // get all the disjoint clusters
671
+ const clusters = disjointCluster(circles);
672
+
673
+ // orientate all disjoint sets, get sizes
674
+ for (const cluster of clusters) {
675
+ orientateCircles(cluster, orientation, orientationOrder);
676
+ const bounds = getBoundingBox(cluster);
677
+ cluster.size = (bounds.xRange.max - bounds.xRange.min) * (bounds.yRange.max - bounds.yRange.min);
678
+ cluster.bounds = bounds;
679
+ }
680
+ clusters.sort((a, b) => b.size - a.size);
681
+
682
+ // orientate the largest at 0,0, and get the bounds
683
+ circles = clusters[0];
684
+ let returnBounds = circles.bounds;
685
+ const spacing = (returnBounds.xRange.max - returnBounds.xRange.min) / 50;
686
+
687
+ /**
688
+ * @param {ReadonlyArray<{x: number, y: number, radius: number, setid: string}>} cluster
689
+ * @param {boolean} right
690
+ * @param {boolean} bottom
691
+ */
692
+ function addCluster(cluster, right, bottom) {
693
+ if (!cluster) {
694
+ return;
695
+ }
696
+
697
+ const bounds = cluster.bounds;
698
+ /** @type {number} */
699
+ let xOffset;
700
+ /** @type {number} */
701
+ let yOffset;
702
+
703
+ if (right) {
704
+ xOffset = returnBounds.xRange.max - bounds.xRange.min + spacing;
705
+ } else {
706
+ xOffset = returnBounds.xRange.max - bounds.xRange.max;
707
+ const centreing =
708
+ (bounds.xRange.max - bounds.xRange.min) / 2 - (returnBounds.xRange.max - returnBounds.xRange.min) / 2;
709
+ if (centreing < 0) {
710
+ xOffset += centreing;
711
+ }
712
+ }
713
+
714
+ if (bottom) {
715
+ yOffset = returnBounds.yRange.max - bounds.yRange.min + spacing;
716
+ } else {
717
+ yOffset = returnBounds.yRange.max - bounds.yRange.max;
718
+ const centreing =
719
+ (bounds.yRange.max - bounds.yRange.min) / 2 - (returnBounds.yRange.max - returnBounds.yRange.min) / 2;
720
+ if (centreing < 0) {
721
+ yOffset += centreing;
722
+ }
723
+ }
724
+
725
+ for (const c of cluster) {
726
+ c.x += xOffset;
727
+ c.y += yOffset;
728
+ circles.push(c);
729
+ }
730
+ }
731
+
732
+ let index = 1;
733
+ while (index < clusters.length) {
734
+ addCluster(clusters[index], true, false);
735
+ addCluster(clusters[index + 1], false, true);
736
+ addCluster(clusters[index + 2], true, true);
737
+ index += 3;
738
+
739
+ // have one cluster (in top left). lay out next three relative
740
+ // to it in a grid
741
+ returnBounds = getBoundingBox(circles);
742
+ }
743
+
744
+ // convert back to solution form
745
+ return toObjectNotation(circles);
746
+ }
747
+
748
+ /**
749
+ * Scales a solution from venn.venn or venn.greedyLayout such that it fits in
750
+ * a rectangle of width/height - with padding around the borders. also
751
+ * centers the diagram in the available space at the same time.
752
+ * If the scale parameter is not null, this automatic scaling is ignored in favor of this custom one
753
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
754
+ * @param {number} width
755
+ * @param {number} height
756
+ * @param {number} padding
757
+ * @param {boolean} scaleToFit
758
+ * @returns {{[setid: string]: {x: number, y: number, radius: number}}}
759
+ */
760
+ export function scaleSolution(solution, width, height, padding, scaleToFit) {
761
+ const circles = fromObjectNotation(solution);
762
+
763
+ width -= 2 * padding;
764
+ height -= 2 * padding;
765
+
766
+ const { xRange, yRange } = getBoundingBox(circles);
767
+
768
+ if (xRange.max === xRange.min || yRange.max === yRange.min) {
769
+ console.log('not scaling solution: zero size detected');
770
+ return solution;
771
+ }
772
+
773
+ /** @type {number} */
774
+ let xScaling;
775
+ /** @type {number} */
776
+ let yScaling;
777
+ if (scaleToFit) {
778
+ const toScaleDiameter = Math.sqrt(scaleToFit / Math.PI) * 2;
779
+ xScaling = width / toScaleDiameter;
780
+ yScaling = height / toScaleDiameter;
781
+ } else {
782
+ xScaling = width / (xRange.max - xRange.min);
783
+ yScaling = height / (yRange.max - yRange.min);
784
+ }
785
+
786
+ const scaling = Math.min(yScaling, xScaling);
787
+ // while we're at it, center the diagram too
788
+ const xOffset = (width - (xRange.max - xRange.min) * scaling) / 2;
789
+ const yOffset = (height - (yRange.max - yRange.min) * scaling) / 2;
790
+
791
+ return toObjectNotation(
792
+ circles.map((circle) => ({
793
+ radius: scaling * circle.radius,
794
+ x: padding + xOffset + (circle.x - xRange.min) * scaling,
795
+ y: padding + yOffset + (circle.y - yRange.min) * scaling,
796
+ setid: circle.setid,
797
+ }))
798
+ );
799
+ }
800
+
801
+ /**
802
+ * @param {readonly {x: number, y: number, radius: number, setid: string}[]} circles
803
+ * @returns {{[setid: string]: {x: number, y: number, radius: number, setid: string}}}
804
+ */
805
+ function toObjectNotation(circles) {
806
+ /** @type {{[setid: string]: {x: number, y: number, radius: number, setid: string}}} */
807
+ const r = {};
808
+ for (const circle of circles) {
809
+ r[circle.setid] = circle;
810
+ }
811
+ return r;
812
+ }
813
+ /**
814
+ * @param {{[setid: string]: {x: number, y: number, radius: number}}} solution
815
+ * @returns {{x: number, y: number, radius: number, setid: string}[]}}
816
+ */
817
+ function fromObjectNotation(solution) {
818
+ const setids = Object.keys(solution);
819
+ return setids.map((id) => Object.assign(solution[id], { setid: id }));
820
+ }
tools/ui/node_modules/@upsetjs/venn.js/src/layout.spec.js ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { disjointCluster, normalizeSolution, greedyLayout, lossFunction, distanceFromIntersectArea } from './layout';
2
+ import { distance, circleOverlap } from './circleintersection';
3
+ import { describe, test, expect } from 'vitest';
4
+
5
+ describe('greedyLayout', () => {
6
+ test('0', () => {
7
+ const areas = [
8
+ { sets: [0], size: 0.7746543297103429 },
9
+ { sets: [1], size: 0.1311252856844238 },
10
+ { sets: [2], size: 0.2659942131443344 },
11
+ { sets: [3], size: 0.44600866168641723 },
12
+ { sets: [0, 1], size: 0.02051532092950205 },
13
+ { sets: [0, 2], size: 0 },
14
+ { sets: [0, 3], size: 0 },
15
+ { sets: [1, 2], size: 0 },
16
+ { sets: [1, 3], size: 0.07597023820511245 },
17
+ { sets: [2, 3], size: 0 },
18
+ ];
19
+ const circles = greedyLayout(areas);
20
+ const loss = lossFunction(circles, areas);
21
+ expect(loss).toBeCloseTo(0);
22
+ });
23
+
24
+ test('1', () => {
25
+ const areas = [
26
+ { sets: [0], size: 0.5299368855059736 },
27
+ { sets: [1], size: 0.03364187025606481 },
28
+ { sets: [2], size: 0.3121450394871512 },
29
+ { sets: [3], size: 0.0514397361783036 },
30
+ { sets: [0, 1], size: 0.013912447645582351 },
31
+ { sets: [0, 2], size: 0.005903647141469598 },
32
+ { sets: [0, 3], size: 0.0514397361783036 },
33
+ { sets: [1, 2], size: 0.012138157839477597 },
34
+ { sets: [1, 3], size: 0.008010688232481479 },
35
+ { sets: [2, 3], size: 0 },
36
+ ];
37
+
38
+ const circles = greedyLayout(areas);
39
+ const loss = lossFunction(circles, areas);
40
+ expect(loss).toBeCloseTo(0);
41
+ });
42
+
43
+ test('3', () => {
44
+ // one small circle completely overlapped in the intersection
45
+ // area of two larger circles
46
+ const areas = [
47
+ { sets: [0], size: 1.7288584050841396 },
48
+ { sets: [1], size: 0.040875831658950056 },
49
+ { sets: [2], size: 2.587146019782323 },
50
+ { sets: [0, 1], size: 0.040875831658950056 },
51
+ { sets: [0, 2], size: 0.5114617575187569 },
52
+ { sets: [1, 2], size: 0.040875831658950056 },
53
+ ];
54
+
55
+ const circles = greedyLayout(areas);
56
+ const loss = lossFunction(circles, areas);
57
+ expect(loss).toBeCloseTo(0);
58
+ });
59
+ });
60
+
61
+ test('distanceFromIntersectArea', () => {
62
+ function testDistanceFromIntersectArea(r1, r2, overlap) {
63
+ const distance = distanceFromIntersectArea(r1, r2, overlap);
64
+ expect(circleOverlap(r1, r2, distance)).toBeCloseTo(overlap);
65
+ }
66
+
67
+ testDistanceFromIntersectArea(1.9544100476116797, 2.256758334191025, 11);
68
+
69
+ testDistanceFromIntersectArea(111.06512962798197, 113.32348546565727, 1218);
70
+
71
+ testDistanceFromIntersectArea(44.456564007075, 149.4335753619362, 2799);
72
+
73
+ testDistanceFromIntersectArea(592.89, 134.75, 56995);
74
+
75
+ testDistanceFromIntersectArea(139.50778247443944, 32.892784970851956, 3399);
76
+
77
+ testDistanceFromIntersectArea(4.886025119029199, 5.077706251929807, 75);
78
+ });
79
+
80
+ test('normalizeSolution', () => {
81
+ // test two circles that are far apart
82
+ const solution = [
83
+ { x: 0, y: 0, radius: 0.5 },
84
+ { x: 1e10, y: 0, radius: 1.5 },
85
+ ];
86
+
87
+ // should be placed close together
88
+ const normalized = normalizeSolution(solution);
89
+ // distance should be 2, but we space things out
90
+ expect(distance(normalized[0], normalized[1])).toBeLessThan(2.1);
91
+ });
92
+
93
+ test('disjointClusters', () => {
94
+ const input = [
95
+ {
96
+ x: 0.8047033110633492,
97
+ y: 0.9396705999970436,
98
+ radius: 0.47156485118903224,
99
+ },
100
+ {
101
+ x: 0.7961132447235286,
102
+ y: 0.014027722179889679,
103
+ radius: 0.14554832570720466,
104
+ },
105
+ {
106
+ x: 0.28841276094317436,
107
+ y: 0.98081015329808,
108
+ radius: 0.9851036085514352,
109
+ },
110
+ {
111
+ x: 0.7689983483869582,
112
+ y: 0.2899463507346809,
113
+ radius: 0.7210563338827342,
114
+ },
115
+ ];
116
+
117
+ const clusters = disjointCluster(input);
118
+ expect(clusters).toHaveLength(1);
119
+ });
tools/ui/node_modules/@vite-pwa/assets-generator/LICENSE ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ MIT License
2
+
3
+ Copyright (c) 2023-PRESENT Anthony Fu <https://github.com/antfu>
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
tools/ui/node_modules/@vite-pwa/assets-generator/README.md ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ <p align='center'>
2
+ <img src='./hero.svg' alt="@vite-pwa/assets-generator - Zero-config PWA Assets Generator"><br>
3
+ Zero-config PWA Assets Generator
4
+ </p>
5
+
6
+ <p align='center'>
7
+ <a href='https://www.npmjs.com/package/@vite-pwa/assets-generator' target="__blank">
8
+ <img src='https://img.shields.io/npm/v/@vite-pwa/assets-generator?color=33A6B8&label=' alt="NPM version">
9
+ </a>
10
+ <a href="https://www.npmjs.com/package/@vite-pwa/assets-generator" target="__blank">
11
+ <img alt="NPM Downloads" src="https://img.shields.io/npm/dm/@vite-pwa/assets-generator?color=476582&label=">
12
+ </a>
13
+ <a href="https://vite-pwa-org.netlify.app/assets-generator" target="__blank">
14
+ <img src="https://img.shields.io/static/v1?label=&message=docs%20%26%20guides&color=2e859c" alt="Docs & Guides">
15
+ </a>
16
+ <br>
17
+ <a href="https://github.com/vite-pwa/assets-generator" target="__blank">
18
+ <img alt="GitHub stars" src="https://img.shields.io/github/stars/vite-pwa/assets-generator?style=social">
19
+ </a>
20
+ </p>
21
+
22
+ <br>
23
+
24
+ <p align="center">
25
+ <a href="https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg">
26
+ <img src='https://cdn.jsdelivr.net/gh/antfu/static/sponsors.svg'/>
27
+ </a>
28
+ </p>
29
+
30
+ ## 🚀 Features
31
+
32
+ - 📖 [**Documentation & guides**](https://vite-pwa-org.netlify.app/)
33
+ - 👌 **Zero-Config**: sensible built-in default configs for common use cases
34
+ - 🔩 **Extensible**: expose the full ability to customize the behavior of the plugin
35
+ - 🦾 **Type Strong**: written in [TypeScript](https://www.typescriptlang.org/)
36
+ - 🔌 **Offline Support**: generate service worker with offline support (via Workbox)
37
+ - ⚡ **Fully tree shakable**: auto inject Web App Manifest
38
+ - 💬 **Prompt for new content**: built-in support for Vanilla JavaScript, Vue 3, React, Svelte, SolidJS and Preact
39
+ - ⚙️ **Stale-while-revalidate**: automatic reload when new content is available
40
+ - ✨ **Static assets handling**: configure static assets for offline support
41
+ - 🐞 **Development Support**: debug your custom service worker logic as you develop your application
42
+ - 🛠️ **Versatile**: integration with meta frameworks: [îles](https://github.com/ElMassimo/iles), [SvelteKit](https://github.com/sveltejs/kit), [VitePress](https://github.com/vuejs/vitepress), [Astro](https://github.com/withastro/astro), [Nuxt 3](https://github.com/nuxt/nuxt) and [Remix](https://github.com/remix-run/remix)
43
+ - 💥 **PWA Assets Generator**: generate all the PWA assets from a single command and a single source image
44
+ - 🚀 **PWA Assets Integration**: serving, generating and injecting PWA Assets on the fly in your application
45
+
46
+ ## 📦 Install
47
+
48
+ ```bash
49
+ # npm
50
+ npm i @vite-pwa/assets-generator -D
51
+
52
+ # yarn
53
+ yarn add @vite-pwa/assets-generator -D
54
+
55
+ # pnpm
56
+ pnpm add @vite-pwa/assets-generator -D
57
+ ```
58
+
59
+ ## 🦄 Usage
60
+
61
+ Create `pwa-assets.config.js` or `pwa-assets.config.ts` file in your root project folder and configure a preset and the images to use to generate the PWA assets:
62
+
63
+ ```ts
64
+ import { defineConfig, minimal2023Preset as preset } from '@vite-pwa/assets-generator/config'
65
+
66
+ export default defineConfig({
67
+ preset,
68
+ images: [
69
+ 'public/logo.svg',
70
+ 'public-dev/logo.svg'
71
+ ]
72
+ })
73
+ ```
74
+
75
+ then, add the following script to your `package.json` and run it:
76
+
77
+ ```json
78
+ {
79
+ "scripts": {
80
+ "generate-pwa-assets": "pwa-assets-generator"
81
+ }
82
+ }
83
+ ```
84
+
85
+ Read the [📖 documentation](https://vite-pwa-org.netlify.app/assets-generator) for a complete guide on how to configure and use
86
+ `@vite-pwa/assets-generator` CLI.
87
+
88
+ To use this library programmatically, check out the [API documentation](https://vite-pwa-org.netlify.app/assets-generator/api).
89
+
90
+ ## 👀 Full config
91
+
92
+ Check out the type declaration [src/config.ts](./src/config.ts) for more details.
93
+
94
+ ## 📄 License
95
+
96
+ [MIT](./LICENSE) License &copy; 2023-PRESENT [Anthony Fu](https://github.com/antfu)
tools/ui/node_modules/@vite-pwa/assets-generator/bin/pwa-assets-generator.mjs ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/usr/bin/env node
2
+ 'use strict'
3
+ import('../dist/cli.mjs')
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.cjs ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const index = require('./index.cjs');
4
+ const favicon = require('./shared/assets-generator.D6uDklIq.cjs');
5
+ require('./shared/assets-generator.4HPlJg00.cjs');
6
+ require('sharp');
7
+ require('sharp-ico');
8
+
9
+
10
+
11
+ exports.createPngCompressionOptions = index.createPngCompressionOptions;
12
+ exports.createResizeOptions = index.createResizeOptions;
13
+ exports.defaultDarkResizeOptions = index.defaultDarkResizeOptions;
14
+ exports.defaultPngCompressionOptions = index.defaultPngCompressionOptions;
15
+ exports.defaultPngOptions = index.defaultPngOptions;
16
+ exports.defaultResizeOptions = index.defaultResizeOptions;
17
+ exports.createAppleSplashScreenHtmlLink = favicon.createAppleSplashScreenHtmlLink;
18
+ exports.createAppleTouchIconHtmlLink = favicon.createAppleTouchIconHtmlLink;
19
+ exports.createFaviconHtmlLink = favicon.createFaviconHtmlLink;
20
+ exports.createSharp = favicon.createSharp;
21
+ exports.extractAssetSize = favicon.extractAssetSize;
22
+ exports.generateFavicon = favicon.generateFavicon;
23
+ exports.generateMaskableAsset = favicon.generateMaskableAsset;
24
+ exports.generateTransparentAsset = favicon.generateTransparentAsset;
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.cts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.CTKvG_gr.cjs';
2
+ export { g as GenerateOptions, h as GenerateOutputOptions, k as IconAsset, I as ImageAssets, a as ImageAssetsInstructions, i as ManifestIcon, j as ManifestIcons, b as ManifestIconsOptionsType, M as ManifestIconsType } from './shared/assets-generator.CTKvG_gr.cjs';
3
+ import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.cjs';
4
+ export { l as AppleSplahScreenHtmlLinkOptions, A as AppleSplashScreenLink, F as FaviconLink, k as HtmlIconLinkOptions, H as HtmlLink, a as HtmlLinkPreset, j as HtmlLinkReturnType, i as HtmlLinkType, o as createAppleSplashScreenHtmlLink, n as createAppleTouchIconHtmlLink, m as createFaviconHtmlLink, h as createPngCompressionOptions, g as createResizeOptions, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions } from './shared/assets-generator.DnoqiTld.cjs';
5
+ import * as sharp from 'sharp';
6
+ import sharp__default from 'sharp';
7
+ import 'unconfig';
8
+
9
+ declare function extractAssetSize(size: ResolvedAssetSize, padding: number): {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ declare function createSharp<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType<OutputType>, channels?: sharp__default.Channels): Promise<sharp__default.Sharp>;
14
+
15
+ declare function generateMaskableAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
16
+
17
+ declare function generateTransparentAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
18
+
19
+ declare function generateFavicon<Format extends GenerateFaviconType>(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType<Format>): Promise<Buffer>;
20
+
21
+ export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset };
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.mts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.Bot_1kJ_.mjs';
2
+ export { g as GenerateOptions, h as GenerateOutputOptions, k as IconAsset, I as ImageAssets, a as ImageAssetsInstructions, i as ManifestIcon, j as ManifestIcons, b as ManifestIconsOptionsType, M as ManifestIconsType } from './shared/assets-generator.Bot_1kJ_.mjs';
3
+ import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.mjs';
4
+ export { l as AppleSplahScreenHtmlLinkOptions, A as AppleSplashScreenLink, F as FaviconLink, k as HtmlIconLinkOptions, H as HtmlLink, a as HtmlLinkPreset, j as HtmlLinkReturnType, i as HtmlLinkType, o as createAppleSplashScreenHtmlLink, n as createAppleTouchIconHtmlLink, m as createFaviconHtmlLink, h as createPngCompressionOptions, g as createResizeOptions, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions } from './shared/assets-generator.DnoqiTld.mjs';
5
+ import * as sharp from 'sharp';
6
+ import sharp__default from 'sharp';
7
+ import 'unconfig';
8
+
9
+ declare function extractAssetSize(size: ResolvedAssetSize, padding: number): {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ declare function createSharp<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType<OutputType>, channels?: sharp__default.Channels): Promise<sharp__default.Sharp>;
14
+
15
+ declare function generateMaskableAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
16
+
17
+ declare function generateTransparentAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
18
+
19
+ declare function generateFavicon<Format extends GenerateFaviconType>(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType<Format>): Promise<Buffer>;
20
+
21
+ export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset };
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.ts ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.BQ3PQ6A_.js';
2
+ export { g as GenerateOptions, h as GenerateOutputOptions, k as IconAsset, I as ImageAssets, a as ImageAssetsInstructions, i as ManifestIcon, j as ManifestIcons, b as ManifestIconsOptionsType, M as ManifestIconsType } from './shared/assets-generator.BQ3PQ6A_.js';
3
+ import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.js';
4
+ export { l as AppleSplahScreenHtmlLinkOptions, A as AppleSplashScreenLink, F as FaviconLink, k as HtmlIconLinkOptions, H as HtmlLink, a as HtmlLinkPreset, j as HtmlLinkReturnType, i as HtmlLinkType, o as createAppleSplashScreenHtmlLink, n as createAppleTouchIconHtmlLink, m as createFaviconHtmlLink, h as createPngCompressionOptions, g as createResizeOptions, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions } from './shared/assets-generator.DnoqiTld.js';
5
+ import * as sharp from 'sharp';
6
+ import sharp__default from 'sharp';
7
+ import 'unconfig';
8
+
9
+ declare function extractAssetSize(size: ResolvedAssetSize, padding: number): {
10
+ width: number;
11
+ height: number;
12
+ };
13
+ declare function createSharp<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType<OutputType>, channels?: sharp__default.Channels): Promise<sharp__default.Sharp>;
14
+
15
+ declare function generateMaskableAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
16
+
17
+ declare function generateTransparentAsset<OutputType extends GenerateOptionsType>(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType<OutputType>): Promise<sharp.Sharp>;
18
+
19
+ declare function generateFavicon<Format extends GenerateFaviconType>(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType<Format>): Promise<Buffer>;
20
+
21
+ export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset };
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.mjs ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ export { createPngCompressionOptions, createResizeOptions, defaultDarkResizeOptions, defaultPngCompressionOptions, defaultPngOptions, defaultResizeOptions } from './index.mjs';
2
+ export { d as createAppleSplashScreenHtmlLink, b as createAppleTouchIconHtmlLink, a as createFaviconHtmlLink, c as createSharp, e as extractAssetSize, h as generateFavicon, g as generateMaskableAsset, f as generateTransparentAsset } from './shared/assets-generator.D-6RJH5l.mjs';
3
+ import './shared/assets-generator.CUAsp7yq.mjs';
4
+ import 'sharp';
5
+ import 'sharp-ico';
tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.cjs ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 'use strict';
2
+
3
+ const node_fs = require('node:fs');
4
+ const promises = require('node:fs/promises');
5
+ const node_path = require('node:path');
6
+
7
+ async function generateAssets(instruction, overrideAssets, folder, log) {
8
+ const transparent = Array.from(Object.values(instruction.transparent));
9
+ await Promise.all(transparent.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log)));
10
+ const maskable = Array.from(Object.values(instruction.maskable));
11
+ await Promise.all(maskable.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log)));
12
+ const apple = Array.from(Object.values(instruction.apple));
13
+ await Promise.all(apple.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log)));
14
+ const favicon = Array.from(Object.values(instruction.favicon));
15
+ await Promise.all(favicon.filter((icon) => !icon.name.endsWith(".svg")).map((icon) => generateAsset("ICO", icon, folder, overrideAssets, log)));
16
+ const appleSplashScreen = Array.from(Object.values(instruction.appleSplashScreen));
17
+ await Promise.all(appleSplashScreen.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log)));
18
+ }
19
+ async function generateAsset(type, icon, folder, overrideAssets, log) {
20
+ const filePath = node_path.resolve(folder, icon.name);
21
+ if (!overrideAssets && node_fs.existsSync(filePath)) {
22
+ log?.(`Skipping, ${type} file already exists: ${filePath}`, true);
23
+ return;
24
+ }
25
+ await icon.buffer().then((b) => promises.writeFile(node_path.resolve(folder, icon.name), new Uint8Array(b))).then(() => {
26
+ });
27
+ log?.(`Generated ${type} file: ${filePath}`, false);
28
+ }
29
+
30
+ exports.generateAssets = generateAssets;