diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js b/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js new file mode 100644 index 0000000000000000000000000000000000000000..609225370119769e38724eab2560e1f61c39a570 --- /dev/null +++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/dist/visitor-keys.js @@ -0,0 +1,194 @@ +"use strict"; +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || (function () { + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + return function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; +})(); +Object.defineProperty(exports, "__esModule", { value: true }); +exports.visitorKeys = void 0; +const eslintVisitorKeys = __importStar(require("eslint-visitor-keys")); +/* + ********************************** IMPORTANT NOTE ******************************** + * * + * The key arrays should be sorted in the order in which you would want to visit * + * the child keys. * + * * + * DO NOT SORT THEM ALPHABETICALLY! * + * * + * They should be sorted in the order that they appear in the source code. * + * For example: * + * * + * class Foo extends Bar { prop: 1 } * + * ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ ClassDeclaration * + * ^^^ id ^^^ superClass * + * ^^^^^^^^^^^ body * + * * + * It would be incorrect to provide the visitor keys ['body', 'id', 'superClass'] * + * because the body comes AFTER everything else in the source code. * + * Instead the correct ordering would be ['id', 'superClass', 'body']. * + * * + ********************************************************************************** + */ +const SharedVisitorKeys = (() => { + const FunctionType = ['typeParameters', 'params', 'returnType']; + const AnonymousFunction = [...FunctionType, 'body']; + const AbstractPropertyDefinition = [ + 'decorators', + 'key', + 'typeAnnotation', + ]; + return { + AbstractPropertyDefinition: ['decorators', 'key', 'typeAnnotation'], + AnonymousFunction, + AsExpression: ['expression', 'typeAnnotation'], + ClassDeclaration: [ + 'decorators', + 'id', + 'typeParameters', + 'superClass', + 'superTypeArguments', + 'implements', + 'body', + ], + Function: ['id', ...AnonymousFunction], + FunctionType, + PropertyDefinition: [...AbstractPropertyDefinition, 'value'], + }; +})(); +const additionalKeys = { + AccessorProperty: SharedVisitorKeys.PropertyDefinition, + ArrayPattern: ['decorators', 'elements', 'typeAnnotation'], + ArrowFunctionExpression: SharedVisitorKeys.AnonymousFunction, + AssignmentPattern: ['decorators', 'left', 'right', 'typeAnnotation'], + CallExpression: ['callee', 'typeArguments', 'arguments'], + ClassDeclaration: SharedVisitorKeys.ClassDeclaration, + ClassExpression: SharedVisitorKeys.ClassDeclaration, + Decorator: ['expression'], + ExportAllDeclaration: ['exported', 'source', 'attributes'], + ExportNamedDeclaration: ['declaration', 'specifiers', 'source', 'attributes'], + FunctionDeclaration: SharedVisitorKeys.Function, + FunctionExpression: SharedVisitorKeys.Function, + Identifier: ['decorators', 'typeAnnotation'], + ImportAttribute: ['key', 'value'], + ImportDeclaration: ['specifiers', 'source', 'attributes'], + ImportExpression: ['source', 'options'], + JSXClosingFragment: [], + JSXOpeningElement: ['name', 'typeArguments', 'attributes'], + JSXOpeningFragment: [], + JSXSpreadChild: ['expression'], + MethodDefinition: ['decorators', 'key', 'value'], + NewExpression: ['callee', 'typeArguments', 'arguments'], + ObjectPattern: ['decorators', 'properties', 'typeAnnotation'], + PropertyDefinition: SharedVisitorKeys.PropertyDefinition, + RestElement: ['decorators', 'argument', 'typeAnnotation'], + StaticBlock: ['body'], + TaggedTemplateExpression: ['tag', 'typeArguments', 'quasi'], + TSAbstractAccessorProperty: SharedVisitorKeys.AbstractPropertyDefinition, + TSAbstractKeyword: [], + TSAbstractMethodDefinition: ['key', 'value'], + TSAbstractPropertyDefinition: SharedVisitorKeys.AbstractPropertyDefinition, + TSAnyKeyword: [], + TSArrayType: ['elementType'], + TSAsExpression: SharedVisitorKeys.AsExpression, + TSAsyncKeyword: [], + TSBigIntKeyword: [], + TSBooleanKeyword: [], + TSCallSignatureDeclaration: SharedVisitorKeys.FunctionType, + TSClassImplements: ['expression', 'typeArguments'], + TSConditionalType: ['checkType', 'extendsType', 'trueType', 'falseType'], + TSConstructorType: SharedVisitorKeys.FunctionType, + TSConstructSignatureDeclaration: SharedVisitorKeys.FunctionType, + TSDeclareFunction: SharedVisitorKeys.Function, + TSDeclareKeyword: [], + TSEmptyBodyFunctionExpression: ['id', ...SharedVisitorKeys.FunctionType], + TSEnumBody: ['members'], + TSEnumDeclaration: ['id', 'body'], + TSEnumMember: ['id', 'initializer'], + TSExportAssignment: ['expression'], + TSExportKeyword: [], + TSExternalModuleReference: ['expression'], + TSFunctionType: SharedVisitorKeys.FunctionType, + TSImportEqualsDeclaration: ['id', 'moduleReference'], + TSImportType: ['source', 'options', 'qualifier', 'typeArguments'], + TSIndexedAccessType: ['objectType', 'indexType'], + TSIndexSignature: ['parameters', 'typeAnnotation'], + TSInferType: ['typeParameter'], + TSInstantiationExpression: ['expression', 'typeArguments'], + TSInterfaceBody: ['body'], + TSInterfaceDeclaration: ['id', 'typeParameters', 'extends', 'body'], + TSInterfaceHeritage: ['expression', 'typeArguments'], + TSIntersectionType: ['types'], + TSIntrinsicKeyword: [], + TSLiteralType: ['literal'], + TSMappedType: ['key', 'constraint', 'nameType', 'typeAnnotation'], + TSMethodSignature: ['key', 'typeParameters', 'params', 'returnType'], + TSModuleBlock: ['body'], + TSModuleDeclaration: ['id', 'body'], + TSNamedTupleMember: ['label', 'elementType'], + TSNamespaceExportDeclaration: ['id'], + TSNeverKeyword: [], + TSNonNullExpression: ['expression'], + TSNullKeyword: [], + TSNumberKeyword: [], + TSObjectKeyword: [], + TSOptionalType: ['typeAnnotation'], + TSParameterProperty: ['decorators', 'parameter'], + TSPrivateKeyword: [], + TSPropertySignature: ['key', 'typeAnnotation'], + TSProtectedKeyword: [], + TSPublicKeyword: [], + TSQualifiedName: ['left', 'right'], + TSReadonlyKeyword: [], + TSRestType: ['typeAnnotation'], + TSSatisfiesExpression: SharedVisitorKeys.AsExpression, + TSStaticKeyword: [], + TSStringKeyword: [], + TSSymbolKeyword: [], + TSTemplateLiteralType: ['quasis', 'types'], + TSThisType: [], + TSTupleType: ['elementTypes'], + TSTypeAliasDeclaration: ['id', 'typeParameters', 'typeAnnotation'], + TSTypeAnnotation: ['typeAnnotation'], + TSTypeAssertion: ['typeAnnotation', 'expression'], + TSTypeLiteral: ['members'], + TSTypeOperator: ['typeAnnotation'], + TSTypeParameter: ['name', 'constraint', 'default'], + TSTypeParameterDeclaration: ['params'], + TSTypeParameterInstantiation: ['params'], + TSTypePredicate: ['parameterName', 'typeAnnotation'], + TSTypeQuery: ['exprName', 'typeArguments'], + TSTypeReference: ['typeName', 'typeArguments'], + TSUndefinedKeyword: [], + TSUnionType: ['types'], + TSUnknownKeyword: [], + TSVoidKeyword: [], +}; +exports.visitorKeys = eslintVisitorKeys.unionWith(additionalKeys); diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..17a25538d9bd634bc079642d35d7a6422a0d850d --- /dev/null +++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright contributors + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md new file mode 100644 index 0000000000000000000000000000000000000000..94894e2e10dce80ee1eb53459b297b449e4b2ea0 --- /dev/null +++ b/tools/ui/node_modules/@typescript-eslint/visitor-keys/node_modules/eslint-visitor-keys/README.md @@ -0,0 +1,123 @@ +# eslint-visitor-keys + +[![npm version](https://img.shields.io/npm/v/eslint-visitor-keys.svg)](https://www.npmjs.com/package/eslint-visitor-keys) +[![Downloads/month](https://img.shields.io/npm/dm/eslint-visitor-keys.svg)](http://www.npmtrends.com/eslint-visitor-keys) +[![Build Status](https://github.com/eslint/js/workflows/CI/badge.svg)](https://github.com/eslint/js/actions) + +Constants and utilities about visitor keys to traverse AST. + +## 💿 Installation + +Use [npm] to install. + +```bash +$ npm install eslint-visitor-keys +``` + +### Requirements + +- [Node.js] `^20.19.0`, `^22.13.0`, or `>=24` + +## 📖 Usage + +To use in an ESM file: + +```js +import * as evk from "eslint-visitor-keys"; +``` + +To use in a CommonJS file: + +```js +const evk = require("eslint-visitor-keys"); +``` + +### evk.KEYS + +> type: `{ [type: string]: string[] | undefined }` + +Visitor keys. This keys are frozen. + +This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes. + +For example: + +``` +console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"] +``` + +### evk.getKeys(node) + +> type: `(node: object) => string[]` + +Get the visitor keys of a given AST node. + +This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`. + +This will be used to traverse unknown nodes. + +For example: + +```js +const node = { + type: "AssignmentExpression", + left: { type: "Identifier", name: "foo" }, + right: { type: "Literal", value: 0 }, +}; +console.log(evk.getKeys(node)); // → ["type", "left", "right"] +``` + +### evk.unionWith(additionalKeys) + +> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }` + +Make the union set with `evk.KEYS` and the given keys. + +- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that. +- It removes duplicated keys as keeping the first one. + +For example: + +```js +console.log( + evk.unionWith({ + MethodDefinition: ["decorators"], + }), +); // → { ..., MethodDefinition: ["decorators", "key", "value"], ... } +``` + +## 📰 Change log + +See [GitHub releases](https://github.com/eslint/js/releases). + +## 🍻 Contributing + +Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/). + +### Development commands + +- `npm test` runs tests and measures code coverage. +- `npm run lint` checks source codes with ESLint. +- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser. + +[npm]: https://www.npmjs.com/ +[Node.js]: https://nodejs.org/ +[ESTree]: https://github.com/estree/estree + + + + +## Sponsors + +The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate) +to get your logo on our READMEs and [website](https://eslint.org/sponsors). + +

Platinum Sponsors

+

Automattic

Gold Sponsors

+

Qlty Software Shopify

Silver Sponsors

+

Vite Liftoff StackBlitz

Bronze Sponsors

+

Cybozu SAP CrawlJobs Depot N-iX Ltd Icons8 Discord GitBook HeroCoders TestMu AI Open Source Office (Formerly LambdaTest)

+

Technology Sponsors

+Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work. +

Netlify Algolia 1Password

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

+@vite-pwa/assets-generator - Zero-config PWA Assets Generator
+Zero-config PWA Assets Generator +

+ +

+ +NPM version + + + NPM Downloads + + + Docs & Guides + +
+ +GitHub stars + +

+ +
+ +

+ + + +

+ +## 🚀 Features + +- 📖 [**Documentation & guides**](https://vite-pwa-org.netlify.app/) +- 👌 **Zero-Config**: sensible built-in default configs for common use cases +- 🔩 **Extensible**: expose the full ability to customize the behavior of the plugin +- 🦾 **Type Strong**: written in [TypeScript](https://www.typescriptlang.org/) +- 🔌 **Offline Support**: generate service worker with offline support (via Workbox) +- ⚡ **Fully tree shakable**: auto inject Web App Manifest +- 💬 **Prompt for new content**: built-in support for Vanilla JavaScript, Vue 3, React, Svelte, SolidJS and Preact +- ⚙️ **Stale-while-revalidate**: automatic reload when new content is available +- ✨ **Static assets handling**: configure static assets for offline support +- 🐞 **Development Support**: debug your custom service worker logic as you develop your application +- 🛠️ **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) +- 💥 **PWA Assets Generator**: generate all the PWA assets from a single command and a single source image +- 🚀 **PWA Assets Integration**: serving, generating and injecting PWA Assets on the fly in your application + +## 📦 Install + +```bash +# npm +npm i @vite-pwa/assets-generator -D + +# yarn +yarn add @vite-pwa/assets-generator -D + +# pnpm +pnpm add @vite-pwa/assets-generator -D +``` + +## 🦄 Usage + +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: + +```ts +import { defineConfig, minimal2023Preset as preset } from '@vite-pwa/assets-generator/config' + +export default defineConfig({ + preset, + images: [ + 'public/logo.svg', + 'public-dev/logo.svg' + ] +}) +``` + +then, add the following script to your `package.json` and run it: + +```json +{ + "scripts": { + "generate-pwa-assets": "pwa-assets-generator" + } +} +``` + +Read the [📖 documentation](https://vite-pwa-org.netlify.app/assets-generator) for a complete guide on how to configure and use +`@vite-pwa/assets-generator` CLI. + +To use this library programmatically, check out the [API documentation](https://vite-pwa-org.netlify.app/assets-generator/api). + +## 👀 Full config + +Check out the type declaration [src/config.ts](./src/config.ts) for more details. + +## 📄 License + +[MIT](./LICENSE) License © 2023-PRESENT [Anthony Fu](https://github.com/antfu) diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/bin/pwa-assets-generator.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/bin/pwa-assets-generator.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d5caadbe4d51e3844cce2da12757164a91c7f474 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/bin/pwa-assets-generator.mjs @@ -0,0 +1,3 @@ +#!/usr/bin/env node +'use strict' +import('../dist/cli.mjs') diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.cjs new file mode 100644 index 0000000000000000000000000000000000000000..54e4c8fcac1b13a12476d7468d006a053ebaf4f0 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.cjs @@ -0,0 +1,24 @@ +'use strict'; + +const index = require('./index.cjs'); +const favicon = require('./shared/assets-generator.D6uDklIq.cjs'); +require('./shared/assets-generator.4HPlJg00.cjs'); +require('sharp'); +require('sharp-ico'); + + + +exports.createPngCompressionOptions = index.createPngCompressionOptions; +exports.createResizeOptions = index.createResizeOptions; +exports.defaultDarkResizeOptions = index.defaultDarkResizeOptions; +exports.defaultPngCompressionOptions = index.defaultPngCompressionOptions; +exports.defaultPngOptions = index.defaultPngOptions; +exports.defaultResizeOptions = index.defaultResizeOptions; +exports.createAppleSplashScreenHtmlLink = favicon.createAppleSplashScreenHtmlLink; +exports.createAppleTouchIconHtmlLink = favicon.createAppleTouchIconHtmlLink; +exports.createFaviconHtmlLink = favicon.createFaviconHtmlLink; +exports.createSharp = favicon.createSharp; +exports.extractAssetSize = favicon.extractAssetSize; +exports.generateFavicon = favicon.generateFavicon; +exports.generateMaskableAsset = favicon.generateMaskableAsset; +exports.generateTransparentAsset = favicon.generateTransparentAsset; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..a116cef8c2933f3f59cf38e4e4d8aed29daba159 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.cts @@ -0,0 +1,21 @@ +import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.CTKvG_gr.cjs'; +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'; +import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.cjs'; +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'; +import * as sharp from 'sharp'; +import sharp__default from 'sharp'; +import 'unconfig'; + +declare function extractAssetSize(size: ResolvedAssetSize, padding: number): { + width: number; + height: number; +}; +declare function createSharp(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType, channels?: sharp__default.Channels): Promise; + +declare function generateMaskableAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateTransparentAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateFavicon(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType): Promise; + +export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..56f25e70b9f802eb313ea11d46bbab29b237c2df --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.mts @@ -0,0 +1,21 @@ +import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.Bot_1kJ_.mjs'; +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'; +import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.mjs'; +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'; +import * as sharp from 'sharp'; +import sharp__default from 'sharp'; +import 'unconfig'; + +declare function extractAssetSize(size: ResolvedAssetSize, padding: number): { + width: number; + height: number; +}; +declare function createSharp(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType, channels?: sharp__default.Channels): Promise; + +declare function generateMaskableAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateTransparentAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateFavicon(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType): Promise; + +export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..b7d648f1b45c6121e66dbc3be501800e6b260b27 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.d.ts @@ -0,0 +1,21 @@ +import { G as GenerateOptionsType, c as ImageSourceInput, d as GenerateOptionsOptionType, e as GenerateFaviconType, f as GenerateFaviconOptionsType } from './shared/assets-generator.BQ3PQ6A_.js'; +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'; +import { R as ResolvedAssetSize, b as AssetSize } from './shared/assets-generator.DnoqiTld.js'; +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'; +import * as sharp from 'sharp'; +import sharp__default from 'sharp'; +import 'unconfig'; + +declare function extractAssetSize(size: ResolvedAssetSize, padding: number): { + width: number; + height: number; +}; +declare function createSharp(type: OutputType, image: ImageSourceInput, size: AssetSize, background: sharp__default.Color, options?: GenerateOptionsOptionType, channels?: sharp__default.Channels): Promise; + +declare function generateMaskableAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateTransparentAsset(type: OutputType, image: ImageSourceInput, size: AssetSize, options?: GenerateOptionsOptionType): Promise; + +declare function generateFavicon(format: Format, image: ImageSourceInput, options?: GenerateFaviconOptionsType): Promise; + +export { GenerateFaviconOptionsType, GenerateFaviconType, GenerateOptionsOptionType, GenerateOptionsType, ImageSourceInput, createSharp, extractAssetSize, generateFavicon, generateMaskableAsset, generateTransparentAsset }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.mjs new file mode 100644 index 0000000000000000000000000000000000000000..bd188dc0a2c39935f4a32aaf4f8b860db22c37b1 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api.mjs @@ -0,0 +1,5 @@ +export { createPngCompressionOptions, createResizeOptions, defaultDarkResizeOptions, defaultPngCompressionOptions, defaultPngOptions, defaultResizeOptions } from './index.mjs'; +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'; +import './shared/assets-generator.CUAsp7yq.mjs'; +import 'sharp'; +import 'sharp-ico'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.cjs new file mode 100644 index 0000000000000000000000000000000000000000..58108175a36555830ad03d8d8d17dc03136862fe --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.cjs @@ -0,0 +1,30 @@ +'use strict'; + +const node_fs = require('node:fs'); +const promises = require('node:fs/promises'); +const node_path = require('node:path'); + +async function generateAssets(instruction, overrideAssets, folder, log) { + const transparent = Array.from(Object.values(instruction.transparent)); + await Promise.all(transparent.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const maskable = Array.from(Object.values(instruction.maskable)); + await Promise.all(maskable.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const apple = Array.from(Object.values(instruction.apple)); + await Promise.all(apple.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const favicon = Array.from(Object.values(instruction.favicon)); + await Promise.all(favicon.filter((icon) => !icon.name.endsWith(".svg")).map((icon) => generateAsset("ICO", icon, folder, overrideAssets, log))); + const appleSplashScreen = Array.from(Object.values(instruction.appleSplashScreen)); + await Promise.all(appleSplashScreen.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); +} +async function generateAsset(type, icon, folder, overrideAssets, log) { + const filePath = node_path.resolve(folder, icon.name); + if (!overrideAssets && node_fs.existsSync(filePath)) { + log?.(`Skipping, ${type} file already exists: ${filePath}`, true); + return; + } + await icon.buffer().then((b) => promises.writeFile(node_path.resolve(folder, icon.name), new Uint8Array(b))).then(() => { + }); + log?.(`Generated ${type} file: ${filePath}`, false); +} + +exports.generateAssets = generateAssets; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..9ece193841e1a203e3e96be7eb9496acdead9822 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.cts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.CTKvG_gr.cjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.cjs'; +import 'unconfig'; + +declare function generateAssets(instruction: ImageAssetsInstructions, overrideAssets: boolean, folder: string, log?: (message: string, ignored: boolean) => void): Promise; + +export { generateAssets }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..08b8061356732b77269f6c4689ff2b45c94b7eb7 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.mts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.Bot_1kJ_.mjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.mjs'; +import 'unconfig'; + +declare function generateAssets(instruction: ImageAssetsInstructions, overrideAssets: boolean, folder: string, log?: (message: string, ignored: boolean) => void): Promise; + +export { generateAssets }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..2fec062d8b96afeaa04083bc2810a2a46c143f3f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.d.ts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.BQ3PQ6A_.js'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.js'; +import 'unconfig'; + +declare function generateAssets(instruction: ImageAssetsInstructions, overrideAssets: boolean, folder: string, log?: (message: string, ignored: boolean) => void): Promise; + +export { generateAssets }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.mjs new file mode 100644 index 0000000000000000000000000000000000000000..66b7f0899bc710c6766b1e5f81ae8219a9c0b456 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-assets.mjs @@ -0,0 +1,28 @@ +import { existsSync } from 'node:fs'; +import { writeFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; + +async function generateAssets(instruction, overrideAssets, folder, log) { + const transparent = Array.from(Object.values(instruction.transparent)); + await Promise.all(transparent.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const maskable = Array.from(Object.values(instruction.maskable)); + await Promise.all(maskable.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const apple = Array.from(Object.values(instruction.apple)); + await Promise.all(apple.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); + const favicon = Array.from(Object.values(instruction.favicon)); + await Promise.all(favicon.filter((icon) => !icon.name.endsWith(".svg")).map((icon) => generateAsset("ICO", icon, folder, overrideAssets, log))); + const appleSplashScreen = Array.from(Object.values(instruction.appleSplashScreen)); + await Promise.all(appleSplashScreen.map((icon) => generateAsset("PNG", icon, folder, overrideAssets, log))); +} +async function generateAsset(type, icon, folder, overrideAssets, log) { + const filePath = resolve(folder, icon.name); + if (!overrideAssets && existsSync(filePath)) { + log?.(`Skipping, ${type} file already exists: ${filePath}`, true); + return; + } + await icon.buffer().then((b) => writeFile(resolve(folder, icon.name), new Uint8Array(b))).then(() => { + }); + log?.(`Generated ${type} file: ${filePath}`, false); +} + +export { generateAssets }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b260f03640ad52cfe758a2bde094548c5a3908a6 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.cjs @@ -0,0 +1,14 @@ +'use strict'; + +function generateHtmlMarkup(instruction) { + const apple = Array.from(Object.values(instruction.apple)); + const favicon = Array.from(Object.values(instruction.favicon)); + const appleSplashScreen = Array.from(Object.values(instruction.appleSplashScreen)); + const links = []; + favicon.forEach((icon) => icon.link?.length && links.push(icon.link)); + apple.forEach((icon) => icon.link?.length && links.push(icon.link)); + appleSplashScreen.forEach((icon) => icon.link?.length && links.push(icon.link)); + return links; +} + +exports.generateHtmlMarkup = generateHtmlMarkup; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..e98dfe629d698d580932f36b5e2b37a32f66dbb7 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.cts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.CTKvG_gr.cjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.cjs'; +import 'unconfig'; + +declare function generateHtmlMarkup(instruction: ImageAssetsInstructions): string[]; + +export { generateHtmlMarkup }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..5890bee96591c2f7ad3bb1ce3b84b3b76315fff4 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.mts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.Bot_1kJ_.mjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.mjs'; +import 'unconfig'; + +declare function generateHtmlMarkup(instruction: ImageAssetsInstructions): string[]; + +export { generateHtmlMarkup }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..4e598425cfafdd7def558a5bdc8152bd4371c68c --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.d.ts @@ -0,0 +1,8 @@ +import { a as ImageAssetsInstructions } from '../shared/assets-generator.BQ3PQ6A_.js'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.js'; +import 'unconfig'; + +declare function generateHtmlMarkup(instruction: ImageAssetsInstructions): string[]; + +export { generateHtmlMarkup }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.mjs new file mode 100644 index 0000000000000000000000000000000000000000..6ace22ddb6e2b11943fdd1db35f55699aa2a5931 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-html-markup.mjs @@ -0,0 +1,12 @@ +function generateHtmlMarkup(instruction) { + const apple = Array.from(Object.values(instruction.apple)); + const favicon = Array.from(Object.values(instruction.favicon)); + const appleSplashScreen = Array.from(Object.values(instruction.appleSplashScreen)); + const links = []; + favicon.forEach((icon) => icon.link?.length && links.push(icon.link)); + apple.forEach((icon) => icon.link?.length && links.push(icon.link)); + appleSplashScreen.forEach((icon) => icon.link?.length && links.push(icon.link)); + return links; +} + +export { generateHtmlMarkup }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.cjs new file mode 100644 index 0000000000000000000000000000000000000000..ffe352e2932849b21865e8a7b3b4beb127a18092 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.cjs @@ -0,0 +1,23 @@ +'use strict'; + +function generateManifestIconsEntry(format, instruction) { + const icons = { icons: [] }; + for (const icon of Object.values(instruction.transparent)) { + icons.icons.push({ + src: icon.name, + sizes: `${icon.width}x${icon.height}`, + type: icon.mimeType + }); + } + for (const icon of Object.values(instruction.maskable)) { + icons.icons.push({ + src: icon.name, + sizes: `${icon.width}x${icon.height}`, + type: icon.mimeType, + purpose: "maskable" + }); + } + return format === "string" ? JSON.stringify(icons, null, 2) : icons; +} + +exports.generateManifestIconsEntry = generateManifestIconsEntry; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..c71a1925dc1c2ed2cb7771ee72d80e5339e086ca --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.cts @@ -0,0 +1,8 @@ +import { M as ManifestIconsType, a as ImageAssetsInstructions, b as ManifestIconsOptionsType } from '../shared/assets-generator.CTKvG_gr.cjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.cjs'; +import 'unconfig'; + +declare function generateManifestIconsEntry(format: Format, instruction: ImageAssetsInstructions): ManifestIconsOptionsType; + +export { generateManifestIconsEntry }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9d139a03de533888982a70a2598931a7e15e1296 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.mts @@ -0,0 +1,8 @@ +import { M as ManifestIconsType, a as ImageAssetsInstructions, b as ManifestIconsOptionsType } from '../shared/assets-generator.Bot_1kJ_.mjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.mjs'; +import 'unconfig'; + +declare function generateManifestIconsEntry(format: Format, instruction: ImageAssetsInstructions): ManifestIconsOptionsType; + +export { generateManifestIconsEntry }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..92ccf77005b9d720826ac92f152e44deafdaf6dc --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.d.ts @@ -0,0 +1,8 @@ +import { M as ManifestIconsType, a as ImageAssetsInstructions, b as ManifestIconsOptionsType } from '../shared/assets-generator.BQ3PQ6A_.js'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.js'; +import 'unconfig'; + +declare function generateManifestIconsEntry(format: Format, instruction: ImageAssetsInstructions): ManifestIconsOptionsType; + +export { generateManifestIconsEntry }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.mjs new file mode 100644 index 0000000000000000000000000000000000000000..455d67ed66eb9f15d16bb1aaf9ef2c6bead18b0f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/generate-manifest-icons-entry.mjs @@ -0,0 +1,21 @@ +function generateManifestIconsEntry(format, instruction) { + const icons = { icons: [] }; + for (const icon of Object.values(instruction.transparent)) { + icons.icons.push({ + src: icon.name, + sizes: `${icon.width}x${icon.height}`, + type: icon.mimeType + }); + } + for (const icon of Object.values(instruction.maskable)) { + icons.icons.push({ + src: icon.name, + sizes: `${icon.width}x${icon.height}`, + type: icon.mimeType, + purpose: "maskable" + }); + } + return format === "string" ? JSON.stringify(icons, null, 2) : icons; +} + +export { generateManifestIconsEntry }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.cjs new file mode 100644 index 0000000000000000000000000000000000000000..25ebff8d18133a4828f5c6ffd4b0c4f4dbc25f6c --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.cjs @@ -0,0 +1,7 @@ +'use strict'; + +async function instructions(imageAssets) { + return await import('../chunks/instructions-resolver.cjs').then(({ resolveInstructions }) => resolveInstructions(imageAssets)); +} + +exports.instructions = instructions; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..5ba72a2b251b1e0b97c581c82338ce116caa902f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.cts @@ -0,0 +1,8 @@ +import { I as ImageAssets, a as ImageAssetsInstructions } from '../shared/assets-generator.CTKvG_gr.cjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.cjs'; +import 'unconfig'; + +declare function instructions(imageAssets: ImageAssets): Promise; + +export { instructions }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..60346958daa77332be16b3d54694276aa2d8291c --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.mts @@ -0,0 +1,8 @@ +import { I as ImageAssets, a as ImageAssetsInstructions } from '../shared/assets-generator.Bot_1kJ_.mjs'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.mjs'; +import 'unconfig'; + +declare function instructions(imageAssets: ImageAssets): Promise; + +export { instructions }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e52024be13c4be4321c8c9df9305e4ddaee6ca50 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.d.ts @@ -0,0 +1,8 @@ +import { I as ImageAssets, a as ImageAssetsInstructions } from '../shared/assets-generator.BQ3PQ6A_.js'; +import 'sharp'; +import '../shared/assets-generator.DnoqiTld.js'; +import 'unconfig'; + +declare function instructions(imageAssets: ImageAssets): Promise; + +export { instructions }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.mjs new file mode 100644 index 0000000000000000000000000000000000000000..7ca4af9c21a7d7ffe292df32edafcb9b87567226 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/api/instructions.mjs @@ -0,0 +1,5 @@ +async function instructions(imageAssets) { + return await import('../chunks/instructions-resolver.mjs').then(({ resolveInstructions }) => resolveInstructions(imageAssets)); +} + +export { instructions }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.cjs new file mode 100644 index 0000000000000000000000000000000000000000..908943986f5b0b1f9713d5ce8d56701e947ef380 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.cjs @@ -0,0 +1,404 @@ +'use strict'; + +const index = require('../index.cjs'); +const splash = require('../shared/assets-generator.4HPlJg00.cjs'); +const favicon = require('../shared/assets-generator.D6uDklIq.cjs'); +require('sharp'); +require('sharp-ico'); + +function resolveAppleSplashScreensInstructions(image, imageAssets, instructions, useAppleSplashScreens) { + const appleSplashScreens = resolveAppleSplashScreens( + imageAssets, + useAppleSplashScreens + ); + if (!appleSplashScreens || !appleSplashScreens.sizes.length) + return; + const { linkMediaOptions, name: resolveName, sizes, png } = appleSplashScreens; + const sizesMap = /* @__PURE__ */ new Map(); + const splashScreens = sizes.reduce((acc, size) => { + if (sizesMap.get(size.width) === size.height) + return acc; + sizesMap.set(size.width, size.height); + const { width: height, height: width, ...restSize } = size; + const { + width: lheight, + height: lwidth, + ...restResizeOptions + } = size.resizeOptions || {}; + const landscapeSize = { + ...restSize, + width, + height, + resizeOptions: { + ...restResizeOptions, + width: lwidth, + height: lheight + } + }; + acc.push({ + size, + landscape: false, + dark: size.darkResizeOptions ? false : void 0, + resizeOptions: size.resizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + acc.push({ + size: landscapeSize, + landscape: true, + dark: size.darkResizeOptions ? false : void 0, + resizeOptions: landscapeSize.resizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + if (size.darkResizeOptions) { + const { + width: dlheight, + height: dlwidth, + ...restDarkResizeOptions + } = size.darkResizeOptions; + const landscapeDarkResizeOptions = { ...restDarkResizeOptions, width: dlwidth, height: dlheight }; + const landscapeDarkSize = { + ...restSize, + width, + height, + resizeOptions: landscapeDarkResizeOptions, + darkResizeOptions: void 0 + }; + acc.push({ + size, + landscape: false, + dark: true, + resizeOptions: size.darkResizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + acc.push({ + size: landscapeDarkSize, + landscape: true, + dark: true, + resizeOptions: landscapeDarkResizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + } + return acc; + }, []); + sizesMap.clear(); + const cache = {}; + const originalName = imageAssets.originalName; + const imageResolver = (dark) => { + if (!dark || typeof appleSplashScreens.darkImageResolver !== "function") + return Promise.resolve(image); + const cached = cache[originalName]; + if (cached) + return cached; + return cache[originalName] = appleSplashScreens.darkImageResolver(originalName).then((darkImage) => Promise.resolve(darkImage ?? image)); + }; + for (const size of splashScreens) { + const basePath = linkMediaOptions.basePath; + const name = resolveName(size.landscape, size.size, size.dark); + const url = `${basePath}${name}`; + const promise = () => imageResolver(size.dark === true).then((i) => favicon.generateMaskableAsset("png", i, size.size, { + padding: size.padding, + resizeOptions: { + ...size.resizeOptions, + background: size.resizeOptions?.background ?? (size.dark ? "black" : "white") + }, + outputOptions: size.png + })); + instructions.appleSplashScreen[url] = { + name, + url, + width: size.size.width, + height: size.size.height, + mimeType: "image/png", + link: favicon.createAppleSplashScreenHtmlLink("string", { + size: size.size, + landscape: size.landscape, + addMediaScreen: linkMediaOptions.addMediaScreen, + xhtml: linkMediaOptions.xhtml, + name: resolveName, + basePath, + dark: size.dark, + includeId: imageAssets.htmlLinks.includeId + }), + linkObject: favicon.createAppleSplashScreenHtmlLink("link", { + size: size.size, + landscape: size.landscape, + addMediaScreen: linkMediaOptions.addMediaScreen, + xhtml: linkMediaOptions.xhtml, + name: resolveName, + basePath, + dark: size.dark, + includeId: imageAssets.htmlLinks.includeId + }), + buffer: () => promise().then((m) => m.toBuffer()) + }; + } +} +function resolveAppleSplashScreens(imageAssets, useAppleSplashScreens) { + let appleSplashScreens; + if (useAppleSplashScreens) { + const { + padding = 0.3, + resizeOptions: useResizeOptions = {}, + darkResizeOptions: useDarkResizeOptions, + linkMediaOptions: useLinkMediaOptions = {}, + sizes, + name = splash.defaultSplashScreenName, + png: usePng = {}, + darkImageResolver + } = useAppleSplashScreens; + const resizeOptions = index.createResizeOptions(false, useResizeOptions); + const darkResizeOptions = useDarkResizeOptions ? index.createResizeOptions(true, useDarkResizeOptions) : void 0; + const png = index.createPngCompressionOptions(usePng); + for (const size of sizes) { + if (typeof size.padding === "undefined") + size.padding = padding; + if (typeof size.png === "undefined") + size.png = png; + if (typeof size.resizeOptions === "undefined") + size.resizeOptions = resizeOptions; + if (typeof size.darkResizeOptions === "undefined" && darkResizeOptions) + size.darkResizeOptions = darkResizeOptions; + } + const { + log = true, + addMediaScreen = true, + basePath = imageAssets.basePath ?? "/", + xhtml = false + } = useLinkMediaOptions; + appleSplashScreens = { + darkImageResolver, + padding, + sizes, + linkMediaOptions: { + log, + addMediaScreen, + basePath, + xhtml + }, + name, + png + }; + } + return appleSplashScreens; +} + +function resolveTransparentIcons(imageAssets, image, assets, htmlPreset, instructions) { + const asset = assets.assets.transparent; + const { sizes, padding, resizeOptions } = asset; + const { basePath, htmlLinks: { xhtml, includeId } } = imageAssets; + for (const size of sizes) { + const name = assets.assetName("transparent", size); + const url = `${basePath}${name}`; + const promise = () => favicon.generateTransparentAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }); + instructions.transparent[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + buffer: () => promise().then((m) => m.toBuffer()) + }; + } + const favicons = asset.favicons; + if (!favicons) + return; + for (const [size, name] of favicons) { + const url = `${basePath}${name}`; + const promise = () => favicon.generateTransparentAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }).then((m) => m.toBuffer()).then((b) => favicon.generateFavicon("png", b)); + const resolvedSize = index.toResolvedSize(size); + instructions.favicon[url] = { + name, + url, + width: resolvedSize.width, + height: resolvedSize.height, + mimeType: "image/x-icon", + link: favicon.createFaviconHtmlLink("string", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: favicon.createFaviconHtmlLink("link", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + buffer: () => promise() + }; + } +} +function resolveMaskableIcons(type, imageAssets, image, assets, htmlPreset, instructions) { + const asset = assets.assets[type]; + const { sizes, padding, resizeOptions } = asset; + const { basePath, htmlLinks: { xhtml, includeId } } = imageAssets; + for (const size of sizes) { + const name = assets.assetName(type, size); + const url = `${basePath}${name}`; + const promise = () => favicon.generateMaskableAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }); + const buffer = () => promise().then((m) => m.toBuffer()); + if (type === "apple") { + instructions.apple[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + link: favicon.createAppleTouchIconHtmlLink("string", { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: favicon.createAppleTouchIconHtmlLink("link", { + name, + size, + basePath, + xhtml, + includeId + }), + buffer + }; + } else { + instructions.maskable[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + buffer + }; + } + } + const favicons = asset.favicons; + if (!favicons) + return; + for (const [size, name] of favicons) { + const url = `${basePath}${name}`; + const resolvedSize = index.toResolvedSize(size); + instructions.favicon[url] = { + name, + url, + width: resolvedSize.width, + height: resolvedSize.height, + mimeType: "image/x-icon", + link: favicon.createFaviconHtmlLink("string", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: favicon.createFaviconHtmlLink("link", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + buffer: () => favicon.generateMaskableAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }).then((m) => m.toBuffer()).then((b) => favicon.generateFavicon("png", b)) + }; + } +} + +async function resolveInstructions(imageAssets) { + const { + imageResolver, + imageName, + originalName, + preset = "minimal", + faviconPreset + } = imageAssets; + const [usePreset, htmlPreset] = await resolvePreset(preset, faviconPreset); + const { + assetName = index.defaultAssetName, + png = index.defaultPngCompressionOptions, + appleSplashScreens: useAppleSplashScreens + } = usePreset; + const assets = { + assets: { + transparent: index.toResolvedAsset("transparent", usePreset.transparent), + maskable: index.toResolvedAsset("maskable", usePreset.maskable), + apple: index.toResolvedAsset("apple", usePreset.apple) + }, + png, + assetName + }; + const instructions = { + image: imageName, + originalName, + favicon: {}, + transparent: {}, + maskable: {}, + apple: {}, + appleSplashScreen: {} + }; + const image = await imageResolver(); + resolveTransparentIcons(imageAssets, image, assets, htmlPreset, instructions); + resolveMaskableIcons("maskable", imageAssets, image, assets, htmlPreset, instructions); + resolveMaskableIcons("apple", imageAssets, image, assets, htmlPreset, instructions); + if (imageName.endsWith(".svg")) { + const name = imageAssets.resolveSvgName(imageName); + const url = `${imageAssets.basePath}${name}`; + instructions.favicon[url] = { + name, + url, + width: 0, + height: 0, + mimeType: "image/svg+xml", + link: favicon.createFaviconHtmlLink("string", htmlPreset, { + name, + basePath: imageAssets.basePath, + xhtml: imageAssets.htmlLinks.xhtml, + includeId: imageAssets.htmlLinks.includeId + }), + linkObject: favicon.createFaviconHtmlLink("link", htmlPreset, { + name, + basePath: imageAssets.basePath, + xhtml: imageAssets.htmlLinks.xhtml, + includeId: imageAssets.htmlLinks.includeId + }), + buffer: () => Promise.resolve(image) + }; + } + resolveAppleSplashScreensInstructions(image, imageAssets, instructions, useAppleSplashScreens); + return instructions; +} +async function resolvePreset(preset, faviconPreset) { + const htmlLinkPreset = faviconPreset ?? "default"; + if (typeof preset === "object") + return [preset, htmlLinkPreset]; + switch (preset) { + case "minimal": + return [await import('../presets/minimal.cjs').then((m) => m.minimalPreset), htmlLinkPreset]; + case "minimal-2023": + return [await import('../presets/minimal-2023.cjs').then((m) => m.minimal2023Preset), faviconPreset ?? "2023"]; + default: + throw new Error(`Preset ${preset} not yet implemented`); + } +} + +exports.resolveInstructions = resolveInstructions; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.mjs new file mode 100644 index 0000000000000000000000000000000000000000..53f2ddb6b92c6ca94b576ecf992ffd92e77fa1c1 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/chunks/instructions-resolver.mjs @@ -0,0 +1,402 @@ +import { createResizeOptions, createPngCompressionOptions, toResolvedSize, defaultAssetName, defaultPngCompressionOptions, toResolvedAsset } from '../index.mjs'; +import { d as defaultSplashScreenName } from '../shared/assets-generator.CUAsp7yq.mjs'; +import { d as createAppleSplashScreenHtmlLink, g as generateMaskableAsset, f as generateTransparentAsset, a as createFaviconHtmlLink, b as createAppleTouchIconHtmlLink, h as generateFavicon } from '../shared/assets-generator.D-6RJH5l.mjs'; +import 'sharp'; +import 'sharp-ico'; + +function resolveAppleSplashScreensInstructions(image, imageAssets, instructions, useAppleSplashScreens) { + const appleSplashScreens = resolveAppleSplashScreens( + imageAssets, + useAppleSplashScreens + ); + if (!appleSplashScreens || !appleSplashScreens.sizes.length) + return; + const { linkMediaOptions, name: resolveName, sizes, png } = appleSplashScreens; + const sizesMap = /* @__PURE__ */ new Map(); + const splashScreens = sizes.reduce((acc, size) => { + if (sizesMap.get(size.width) === size.height) + return acc; + sizesMap.set(size.width, size.height); + const { width: height, height: width, ...restSize } = size; + const { + width: lheight, + height: lwidth, + ...restResizeOptions + } = size.resizeOptions || {}; + const landscapeSize = { + ...restSize, + width, + height, + resizeOptions: { + ...restResizeOptions, + width: lwidth, + height: lheight + } + }; + acc.push({ + size, + landscape: false, + dark: size.darkResizeOptions ? false : void 0, + resizeOptions: size.resizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + acc.push({ + size: landscapeSize, + landscape: true, + dark: size.darkResizeOptions ? false : void 0, + resizeOptions: landscapeSize.resizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + if (size.darkResizeOptions) { + const { + width: dlheight, + height: dlwidth, + ...restDarkResizeOptions + } = size.darkResizeOptions; + const landscapeDarkResizeOptions = { ...restDarkResizeOptions, width: dlwidth, height: dlheight }; + const landscapeDarkSize = { + ...restSize, + width, + height, + resizeOptions: landscapeDarkResizeOptions, + darkResizeOptions: void 0 + }; + acc.push({ + size, + landscape: false, + dark: true, + resizeOptions: size.darkResizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + acc.push({ + size: landscapeDarkSize, + landscape: true, + dark: true, + resizeOptions: landscapeDarkResizeOptions, + padding: size.padding ?? 0.3, + png: size.png ?? png + }); + } + return acc; + }, []); + sizesMap.clear(); + const cache = {}; + const originalName = imageAssets.originalName; + const imageResolver = (dark) => { + if (!dark || typeof appleSplashScreens.darkImageResolver !== "function") + return Promise.resolve(image); + const cached = cache[originalName]; + if (cached) + return cached; + return cache[originalName] = appleSplashScreens.darkImageResolver(originalName).then((darkImage) => Promise.resolve(darkImage ?? image)); + }; + for (const size of splashScreens) { + const basePath = linkMediaOptions.basePath; + const name = resolveName(size.landscape, size.size, size.dark); + const url = `${basePath}${name}`; + const promise = () => imageResolver(size.dark === true).then((i) => generateMaskableAsset("png", i, size.size, { + padding: size.padding, + resizeOptions: { + ...size.resizeOptions, + background: size.resizeOptions?.background ?? (size.dark ? "black" : "white") + }, + outputOptions: size.png + })); + instructions.appleSplashScreen[url] = { + name, + url, + width: size.size.width, + height: size.size.height, + mimeType: "image/png", + link: createAppleSplashScreenHtmlLink("string", { + size: size.size, + landscape: size.landscape, + addMediaScreen: linkMediaOptions.addMediaScreen, + xhtml: linkMediaOptions.xhtml, + name: resolveName, + basePath, + dark: size.dark, + includeId: imageAssets.htmlLinks.includeId + }), + linkObject: createAppleSplashScreenHtmlLink("link", { + size: size.size, + landscape: size.landscape, + addMediaScreen: linkMediaOptions.addMediaScreen, + xhtml: linkMediaOptions.xhtml, + name: resolveName, + basePath, + dark: size.dark, + includeId: imageAssets.htmlLinks.includeId + }), + buffer: () => promise().then((m) => m.toBuffer()) + }; + } +} +function resolveAppleSplashScreens(imageAssets, useAppleSplashScreens) { + let appleSplashScreens; + if (useAppleSplashScreens) { + const { + padding = 0.3, + resizeOptions: useResizeOptions = {}, + darkResizeOptions: useDarkResizeOptions, + linkMediaOptions: useLinkMediaOptions = {}, + sizes, + name = defaultSplashScreenName, + png: usePng = {}, + darkImageResolver + } = useAppleSplashScreens; + const resizeOptions = createResizeOptions(false, useResizeOptions); + const darkResizeOptions = useDarkResizeOptions ? createResizeOptions(true, useDarkResizeOptions) : void 0; + const png = createPngCompressionOptions(usePng); + for (const size of sizes) { + if (typeof size.padding === "undefined") + size.padding = padding; + if (typeof size.png === "undefined") + size.png = png; + if (typeof size.resizeOptions === "undefined") + size.resizeOptions = resizeOptions; + if (typeof size.darkResizeOptions === "undefined" && darkResizeOptions) + size.darkResizeOptions = darkResizeOptions; + } + const { + log = true, + addMediaScreen = true, + basePath = imageAssets.basePath ?? "/", + xhtml = false + } = useLinkMediaOptions; + appleSplashScreens = { + darkImageResolver, + padding, + sizes, + linkMediaOptions: { + log, + addMediaScreen, + basePath, + xhtml + }, + name, + png + }; + } + return appleSplashScreens; +} + +function resolveTransparentIcons(imageAssets, image, assets, htmlPreset, instructions) { + const asset = assets.assets.transparent; + const { sizes, padding, resizeOptions } = asset; + const { basePath, htmlLinks: { xhtml, includeId } } = imageAssets; + for (const size of sizes) { + const name = assets.assetName("transparent", size); + const url = `${basePath}${name}`; + const promise = () => generateTransparentAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }); + instructions.transparent[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + buffer: () => promise().then((m) => m.toBuffer()) + }; + } + const favicons = asset.favicons; + if (!favicons) + return; + for (const [size, name] of favicons) { + const url = `${basePath}${name}`; + const promise = () => generateTransparentAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }).then((m) => m.toBuffer()).then((b) => generateFavicon("png", b)); + const resolvedSize = toResolvedSize(size); + instructions.favicon[url] = { + name, + url, + width: resolvedSize.width, + height: resolvedSize.height, + mimeType: "image/x-icon", + link: createFaviconHtmlLink("string", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: createFaviconHtmlLink("link", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + buffer: () => promise() + }; + } +} +function resolveMaskableIcons(type, imageAssets, image, assets, htmlPreset, instructions) { + const asset = assets.assets[type]; + const { sizes, padding, resizeOptions } = asset; + const { basePath, htmlLinks: { xhtml, includeId } } = imageAssets; + for (const size of sizes) { + const name = assets.assetName(type, size); + const url = `${basePath}${name}`; + const promise = () => generateMaskableAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }); + const buffer = () => promise().then((m) => m.toBuffer()); + if (type === "apple") { + instructions.apple[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + link: createAppleTouchIconHtmlLink("string", { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: createAppleTouchIconHtmlLink("link", { + name, + size, + basePath, + xhtml, + includeId + }), + buffer + }; + } else { + instructions.maskable[url] = { + name, + url, + width: size.width, + height: size.height, + mimeType: "image/png", + buffer + }; + } + } + const favicons = asset.favicons; + if (!favicons) + return; + for (const [size, name] of favicons) { + const url = `${basePath}${name}`; + const resolvedSize = toResolvedSize(size); + instructions.favicon[url] = { + name, + url, + width: resolvedSize.width, + height: resolvedSize.height, + mimeType: "image/x-icon", + link: createFaviconHtmlLink("string", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + linkObject: createFaviconHtmlLink("link", htmlPreset, { + name, + size, + basePath, + xhtml, + includeId + }), + buffer: () => generateMaskableAsset("png", image, size, { + padding, + resizeOptions, + outputOptions: assets.png + }).then((m) => m.toBuffer()).then((b) => generateFavicon("png", b)) + }; + } +} + +async function resolveInstructions(imageAssets) { + const { + imageResolver, + imageName, + originalName, + preset = "minimal", + faviconPreset + } = imageAssets; + const [usePreset, htmlPreset] = await resolvePreset(preset, faviconPreset); + const { + assetName = defaultAssetName, + png = defaultPngCompressionOptions, + appleSplashScreens: useAppleSplashScreens + } = usePreset; + const assets = { + assets: { + transparent: toResolvedAsset("transparent", usePreset.transparent), + maskable: toResolvedAsset("maskable", usePreset.maskable), + apple: toResolvedAsset("apple", usePreset.apple) + }, + png, + assetName + }; + const instructions = { + image: imageName, + originalName, + favicon: {}, + transparent: {}, + maskable: {}, + apple: {}, + appleSplashScreen: {} + }; + const image = await imageResolver(); + resolveTransparentIcons(imageAssets, image, assets, htmlPreset, instructions); + resolveMaskableIcons("maskable", imageAssets, image, assets, htmlPreset, instructions); + resolveMaskableIcons("apple", imageAssets, image, assets, htmlPreset, instructions); + if (imageName.endsWith(".svg")) { + const name = imageAssets.resolveSvgName(imageName); + const url = `${imageAssets.basePath}${name}`; + instructions.favicon[url] = { + name, + url, + width: 0, + height: 0, + mimeType: "image/svg+xml", + link: createFaviconHtmlLink("string", htmlPreset, { + name, + basePath: imageAssets.basePath, + xhtml: imageAssets.htmlLinks.xhtml, + includeId: imageAssets.htmlLinks.includeId + }), + linkObject: createFaviconHtmlLink("link", htmlPreset, { + name, + basePath: imageAssets.basePath, + xhtml: imageAssets.htmlLinks.xhtml, + includeId: imageAssets.htmlLinks.includeId + }), + buffer: () => Promise.resolve(image) + }; + } + resolveAppleSplashScreensInstructions(image, imageAssets, instructions, useAppleSplashScreens); + return instructions; +} +async function resolvePreset(preset, faviconPreset) { + const htmlLinkPreset = faviconPreset ?? "default"; + if (typeof preset === "object") + return [preset, htmlLinkPreset]; + switch (preset) { + case "minimal": + return [await import('../presets/minimal.mjs').then((m) => m.minimalPreset), htmlLinkPreset]; + case "minimal-2023": + return [await import('../presets/minimal-2023.mjs').then((m) => m.minimal2023Preset), faviconPreset ?? "2023"]; + default: + throw new Error(`Preset ${preset} not yet implemented`); + } +} + +export { resolveInstructions }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/cli.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/cli.mjs new file mode 100644 index 0000000000000000000000000000000000000000..8f3f9028166fe5d4a65df48e0b1100ba0f480ecc --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/cli.mjs @@ -0,0 +1,136 @@ +import { readFile } from 'node:fs/promises'; +import { basename, resolve, dirname } from 'node:path'; +import process from 'node:process'; +import cac from 'cac'; +import { green, yellow } from 'colorette'; +import { consola } from 'consola'; +import { generateAssets } from './api/generate-assets.mjs'; +import { generateHtmlMarkup } from './api/generate-html-markup.mjs'; +import { generateManifestIconsEntry } from './api/generate-manifest-icons-entry.mjs'; +import { resolveInstructions } from './chunks/instructions-resolver.mjs'; +import { loadConfig } from './config.mjs'; +import 'node:fs'; +import './index.mjs'; +import './shared/assets-generator.CUAsp7yq.mjs'; +import './shared/assets-generator.D-6RJH5l.mjs'; +import 'sharp'; +import 'sharp-ico'; +import 'unconfig'; +import './presets/minimal.mjs'; +import './presets/minimal-2023.mjs'; + +const version = "1.0.2"; + +async function startCli(args = process.argv) { + const cli = cac("pwa-assets-generator"); + cli.version(version).option("-r, --root ", "Root path").option("-c, --config ", "Path to config file").option("-p, --preset ", "Built-in preset name: minimal, android, windows, ios or all").option("-o, --override", "Override assets? Defaults to true").option("-m, --manifest", "Generate generate PWA web manifest icons entry? Defaults to true").option("--html [options]", "Available options: --html.basePath , --html.preset , --html.xhtml , --html.includeId ").help().command( + "[...images]", + "Generate PWA assets from images files" + ).action((images, options) => run(images, options)); + cli.parse(args); +} +function cleanupCliOptions(cliOptions) { + delete cliOptions["--"]; + delete cliOptions.r; + delete cliOptions.c; + delete cliOptions.p; + delete cliOptions.o; + delete cliOptions.m; + if (typeof cliOptions.html === "object") { + cliOptions.headLinkOptions = { ...cliOptions.html }; + if (typeof cliOptions.headLinkOptions.preset === "number") + cliOptions.headLinkOptions.preset = `${cliOptions.headLinkOptions.preset}`; + if (typeof cliOptions.headLinkOptions.xhtml === "string") + cliOptions.headLinkOptions.xhtml = cliOptions.headLinkOptions.xhtml === "true"; + if (typeof cliOptions.headLinkOptions.includeId === "string") + cliOptions.headLinkOptions.includeId = cliOptions.headLinkOptions.includeId === "true"; + delete cliOptions.html; + } +} +async function run(images = [], cliOptions = {}) { + consola.log(green(`Zero Config PWA Assets Generator v${version}`)); + consola.start("Preparing to generate PWA assets..."); + cleanupCliOptions(cliOptions); + const root = cliOptions.root ?? process.cwd(); + const { config } = await loadConfig(root, cliOptions); + if (!config.preset) + throw new Error("No preset found"); + if (images?.length) + config.images = images; + if (!config.images?.length) + throw new Error("No images provided"); + const { + logLevel = "info", + overrideAssets = true, + preset, + images: configImages, + headLinkOptions: userHeadLinkOptions, + manifestIconsEntry = true + } = config; + const useOverrideAssets = cliOptions.override === false ? false : overrideAssets; + const useManifestIconsEntry = cliOptions.manifest === false ? false : manifestIconsEntry; + const useImages = Array.isArray(configImages) ? configImages : [configImages]; + const xhtml = userHeadLinkOptions?.xhtml === true; + const includeId = userHeadLinkOptions?.includeId === true; + consola.start("Resolving instructions..."); + const instructions = await Promise.all(useImages.map((i) => resolveInstructions({ + imageResolver: () => readFile(resolve(root, i)), + imageName: resolve(root, i), + originalName: i, + preset, + faviconPreset: userHeadLinkOptions?.preset, + htmlLinks: { xhtml, includeId }, + basePath: userHeadLinkOptions?.basePath ?? "/", + resolveSvgName: userHeadLinkOptions?.resolveSvgName ?? ((name) => basename(name)) + }))); + consola.ready("PWA assets ready to be generated, instructions resolved"); + consola.start(`Generating PWA assets from ${useImages.join(", ")} image${useImages.length > 1 ? "s" : ""}`); + const log = logLevel !== "silent"; + for (const instruction of instructions) { + consola.start(`Generating assets for ${instruction.originalName}...`); + await generateAssets( + instruction, + useOverrideAssets, + dirname(instruction.image), + log ? (message, ignored) => { + if (ignored) + consola.log(yellow(message)); + else + consola.ready(green(message)); + } : void 0 + ); + consola.ready(`Assets generated for ${instruction.originalName}`); + if (logLevel !== "silent") { + const links = generateHtmlMarkup(instruction); + if (links.length) { + consola.start("Generating Html Head Links..."); + links.forEach((link) => console.log(link)); + consola.ready("Html Head Links generated"); + } + if (useManifestIconsEntry) { + consola.start("Generating PWA web manifest icons entry..."); + console.log(generateManifestIconsEntry("string", instruction)); + consola.ready("PWA web manifest icons entry generated"); + } + } + } + consola.ready("PWA assets generated"); +} + +class PrettyError extends Error { + constructor(message) { + super(message); + this.name = this.constructor.name; + if (typeof Error.captureStackTrace === "function") + Error.captureStackTrace(this, this.constructor); + else + this.stack = new Error(message).stack; + } +} +function handleError(error) { + if (error instanceof PrettyError) + consola.error(error.message); + process.exitCode = 1; +} + +startCli().catch(handleError); diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.cjs new file mode 100644 index 0000000000000000000000000000000000000000..74a39d2b7d5e3e0513529fade780ba77d86087ca --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.cjs @@ -0,0 +1,75 @@ +'use strict'; + +const node_fs = require('node:fs'); +const node_path = require('node:path'); +const process = require('node:process'); +const unconfig = require('unconfig'); +const index = require('./index.cjs'); +const splash = require('./shared/assets-generator.4HPlJg00.cjs'); +const presets_minimal = require('./presets/minimal.cjs'); +const presets_minimal2023 = require('./presets/minimal-2023.cjs'); + +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } + +const process__default = /*#__PURE__*/_interopDefaultCompat(process); + +function defineConfig(config) { + return config; +} +async function loadConfig(cwd = process__default.cwd(), configOrPath = cwd, extraConfigSources = [], defaults = { overrideAssets: true, logLevel: "info" }) { + let inlineConfig = {}; + if (typeof configOrPath !== "string") { + inlineConfig = configOrPath; + if (inlineConfig.config === false) { + return { + config: inlineConfig, + sources: [] + }; + } else { + configOrPath = inlineConfig.config || process__default.cwd(); + } + } + const resolved = node_path.resolve(cwd, configOrPath); + let isFile = false; + if (node_fs.existsSync(resolved) && node_fs.statSync(resolved).isFile()) { + isFile = true; + cwd = node_path.dirname(resolved).replace(/\\/g, "/"); + } + const loader = unconfig.createConfigLoader({ + sources: isFile ? [ + { + files: resolved, + extensions: [] + } + ] : [ + { + files: [ + "pwa-assets.config" + ] + }, + ...extraConfigSources + ], + cwd, + defaults: inlineConfig + }); + const result = await loader.load(); + result.config = Object.assign(defaults, result.config || inlineConfig); + return result; +} + +exports.createPngCompressionOptions = index.createPngCompressionOptions; +exports.createResizeOptions = index.createResizeOptions; +exports.defaultAssetName = index.defaultAssetName; +exports.defaultDarkResizeOptions = index.defaultDarkResizeOptions; +exports.defaultPngCompressionOptions = index.defaultPngCompressionOptions; +exports.defaultPngOptions = index.defaultPngOptions; +exports.defaultResizeOptions = index.defaultResizeOptions; +exports.AllAppleDeviceNames = splash.AllAppleDeviceNames; +exports.appleSplashScreenSizes = splash.appleSplashScreenSizes; +exports.combinePresetAndAppleSplashScreens = splash.combinePresetAndAppleSplashScreens; +exports.createAppleSplashScreens = splash.createAppleSplashScreens; +exports.defaultSplashScreenName = splash.defaultSplashScreenName; +exports.minimalPreset = presets_minimal.minimalPreset; +exports.minimal2023Preset = presets_minimal2023.minimal2023Preset; +exports.defineConfig = defineConfig; +exports.loadConfig = loadConfig; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..299348cced43547d506ca09fd9f185c8d27ff794 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.cts @@ -0,0 +1,3 @@ +export { LoadConfigResult, LoadConfigSource } from 'unconfig'; +export { C as AllAppleDeviceNames, w as AppleDeviceName, J as AppleDeviceSize, x as AppleSplashScreen, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, B as BuiltInPreset, G as Favicon, r as HeadLinkOptions, V as LogLevel, P as Preset, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, s as ResolvedConfig, U as UserConfig, y as appleSplashScreenSizes, E as combinePresetAndAppleSplashScreens, D as createAppleSplashScreens, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, z as defaultSplashScreenName, t as defineConfig, u as loadConfig, q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.cjs'; +import 'sharp'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..63e40cba10cac2b1f7ea376d703bcd6a22edd54f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.mts @@ -0,0 +1,3 @@ +export { LoadConfigResult, LoadConfigSource } from 'unconfig'; +export { C as AllAppleDeviceNames, w as AppleDeviceName, J as AppleDeviceSize, x as AppleSplashScreen, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, B as BuiltInPreset, G as Favicon, r as HeadLinkOptions, V as LogLevel, P as Preset, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, s as ResolvedConfig, U as UserConfig, y as appleSplashScreenSizes, E as combinePresetAndAppleSplashScreens, D as createAppleSplashScreens, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, z as defaultSplashScreenName, t as defineConfig, u as loadConfig, q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.mjs'; +import 'sharp'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..c4828a06e11911af52ac9d5a7415daa8bf2fb909 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.d.ts @@ -0,0 +1,3 @@ +export { LoadConfigResult, LoadConfigSource } from 'unconfig'; +export { C as AllAppleDeviceNames, w as AppleDeviceName, J as AppleDeviceSize, x as AppleSplashScreen, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, B as BuiltInPreset, G as Favicon, r as HeadLinkOptions, V as LogLevel, P as Preset, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, s as ResolvedConfig, U as UserConfig, y as appleSplashScreenSizes, E as combinePresetAndAppleSplashScreens, D as createAppleSplashScreens, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, z as defaultSplashScreenName, t as defineConfig, u as loadConfig, q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.js'; +import 'sharp'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.mjs new file mode 100644 index 0000000000000000000000000000000000000000..12146ffed6971d0e346def58940fcd255ae09b28 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/config.mjs @@ -0,0 +1,54 @@ +import { existsSync, statSync } from 'node:fs'; +import { resolve, dirname } from 'node:path'; +import process from 'node:process'; +import { createConfigLoader } from 'unconfig'; +export { createPngCompressionOptions, createResizeOptions, defaultAssetName, defaultDarkResizeOptions, defaultPngCompressionOptions, defaultPngOptions, defaultResizeOptions } from './index.mjs'; +export { A as AllAppleDeviceNames, a as appleSplashScreenSizes, b as combinePresetAndAppleSplashScreens, c as createAppleSplashScreens, d as defaultSplashScreenName } from './shared/assets-generator.CUAsp7yq.mjs'; +export { minimalPreset } from './presets/minimal.mjs'; +export { minimal2023Preset } from './presets/minimal-2023.mjs'; + +function defineConfig(config) { + return config; +} +async function loadConfig(cwd = process.cwd(), configOrPath = cwd, extraConfigSources = [], defaults = { overrideAssets: true, logLevel: "info" }) { + let inlineConfig = {}; + if (typeof configOrPath !== "string") { + inlineConfig = configOrPath; + if (inlineConfig.config === false) { + return { + config: inlineConfig, + sources: [] + }; + } else { + configOrPath = inlineConfig.config || process.cwd(); + } + } + const resolved = resolve(cwd, configOrPath); + let isFile = false; + if (existsSync(resolved) && statSync(resolved).isFile()) { + isFile = true; + cwd = dirname(resolved).replace(/\\/g, "/"); + } + const loader = createConfigLoader({ + sources: isFile ? [ + { + files: resolved, + extensions: [] + } + ] : [ + { + files: [ + "pwa-assets.config" + ] + }, + ...extraConfigSources + ], + cwd, + defaults: inlineConfig + }); + const result = await loader.load(); + result.config = Object.assign(defaults, result.config || inlineConfig); + return result; +} + +export { defineConfig, loadConfig }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.cjs new file mode 100644 index 0000000000000000000000000000000000000000..3b6b52d6c13ecda616e31cba56d405b43e19d531 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.cjs @@ -0,0 +1,94 @@ +'use strict'; + +const defaultResizeOptions = { + fit: "contain", + background: "white" +}; +const defaultDarkResizeOptions = { + fit: "contain", + background: "black" +}; +const defaultPngCompressionOptions = { + compressionLevel: 9, + quality: 60 +}; +const defaultPngOptions = { + transparent: { padding: 0.05, resizeOptions: { fit: "contain", background: "transparent" } }, + maskable: { padding: 0.3, resizeOptions: { fit: "contain", background: "white" } }, + apple: { padding: 0.3, resizeOptions: { fit: "contain", background: "white" } } +}; +function createResizeOptions(dark, options) { + return { + ...dark ? defaultDarkResizeOptions : defaultResizeOptions, + ...options + }; +} +function createPngCompressionOptions(options) { + return { + ...defaultPngCompressionOptions, + ...options + }; +} + +function toResolvedSize(size) { + return { + original: size, + width: typeof size === "number" ? size : size.width, + height: typeof size === "number" ? size : size.height + }; +} +function toResolvedAsset(type, asset) { + return { + padding: defaultPngOptions[type].padding, + resizeOptions: defaultPngOptions[type].resizeOptions, + ...asset, + sizes: asset.sizes.map(toResolvedSize) + }; +} +function defaultAssetName(type, size) { + switch (type) { + case "transparent": + return `pwa-${size.width}x${size.height}.png`; + case "maskable": + return `maskable-icon-${size.width}x${size.height}.png`; + case "apple": + return `apple-touch-icon-${size.width}x${size.height}.png`; + } +} +function sameAssetSize(a, b) { + if (typeof a === "number" && typeof b.original === "number") + return a === b.original; + if (typeof a !== "number" && typeof b.original !== "number") + return a.width === b.width && a.height === b.height; + return false; +} +function cloneResolvedAssetsSizes({ png, assetName, assets }) { + return { + assets: { + transparent: cloneResolvedAssetSizes(assets.transparent), + maskable: cloneResolvedAssetSizes(assets.maskable), + apple: cloneResolvedAssetSizes(assets.apple) + }, + png, + assetName + }; +} +function cloneResolvedAssetSizes({ sizes, ...asset }) { + return { + ...asset, + sizes: [...sizes] + }; +} + +exports.cloneResolvedAssetSizes = cloneResolvedAssetSizes; +exports.cloneResolvedAssetsSizes = cloneResolvedAssetsSizes; +exports.createPngCompressionOptions = createPngCompressionOptions; +exports.createResizeOptions = createResizeOptions; +exports.defaultAssetName = defaultAssetName; +exports.defaultDarkResizeOptions = defaultDarkResizeOptions; +exports.defaultPngCompressionOptions = defaultPngCompressionOptions; +exports.defaultPngOptions = defaultPngOptions; +exports.defaultResizeOptions = defaultResizeOptions; +exports.sameAssetSize = sameAssetSize; +exports.toResolvedAsset = toResolvedAsset; +exports.toResolvedSize = toResolvedSize; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..4514373fd6cb2e2cb367d6be46bc1fc9b6c9ab2a --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.cts @@ -0,0 +1,3 @@ +export { J as AppleDeviceSize, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, G as Favicon, V as LogLevel, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, a0 as cloneResolvedAssetSizes, $ as cloneResolvedAssetsSizes, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, _ as sameAssetSize, Z as toResolvedAsset, Y as toResolvedSize } from './shared/assets-generator.DnoqiTld.cjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9636ce0da3d2fa49411bccc4b7abcc2adc237c5a --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.mts @@ -0,0 +1,3 @@ +export { J as AppleDeviceSize, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, G as Favicon, V as LogLevel, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, a0 as cloneResolvedAssetSizes, $ as cloneResolvedAssetsSizes, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, _ as sameAssetSize, Z as toResolvedAsset, Y as toResolvedSize } from './shared/assets-generator.DnoqiTld.mjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5292caca8d50e541e951cbae1bff3e704691ab9c --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.d.ts @@ -0,0 +1,3 @@ +export { J as AppleDeviceSize, K as AppleSplashScreenName, M as AppleSplashScreens, L as AppleTouchStartupImageOptions, I as Asset, b as AssetSize, O as AssetType, S as Assets, W as BuildOptions, G as Favicon, V as LogLevel, N as ResolvedAppleSplashScreens, Q as ResolvedAsset, R as ResolvedAssetSize, T as ResolvedAssets, X as ResolvedBuildOptions, a0 as cloneResolvedAssetSizes, $ as cloneResolvedAssetsSizes, h as createPngCompressionOptions, g as createResizeOptions, v as defaultAssetName, c as defaultDarkResizeOptions, e as defaultPngCompressionOptions, f as defaultPngOptions, d as defaultResizeOptions, _ as sameAssetSize, Z as toResolvedAsset, Y as toResolvedSize } from './shared/assets-generator.DnoqiTld.js'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..827b2bd15ee6e9d179cd65d6980274864b715041 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/index.mjs @@ -0,0 +1,81 @@ +const defaultResizeOptions = { + fit: "contain", + background: "white" +}; +const defaultDarkResizeOptions = { + fit: "contain", + background: "black" +}; +const defaultPngCompressionOptions = { + compressionLevel: 9, + quality: 60 +}; +const defaultPngOptions = { + transparent: { padding: 0.05, resizeOptions: { fit: "contain", background: "transparent" } }, + maskable: { padding: 0.3, resizeOptions: { fit: "contain", background: "white" } }, + apple: { padding: 0.3, resizeOptions: { fit: "contain", background: "white" } } +}; +function createResizeOptions(dark, options) { + return { + ...dark ? defaultDarkResizeOptions : defaultResizeOptions, + ...options + }; +} +function createPngCompressionOptions(options) { + return { + ...defaultPngCompressionOptions, + ...options + }; +} + +function toResolvedSize(size) { + return { + original: size, + width: typeof size === "number" ? size : size.width, + height: typeof size === "number" ? size : size.height + }; +} +function toResolvedAsset(type, asset) { + return { + padding: defaultPngOptions[type].padding, + resizeOptions: defaultPngOptions[type].resizeOptions, + ...asset, + sizes: asset.sizes.map(toResolvedSize) + }; +} +function defaultAssetName(type, size) { + switch (type) { + case "transparent": + return `pwa-${size.width}x${size.height}.png`; + case "maskable": + return `maskable-icon-${size.width}x${size.height}.png`; + case "apple": + return `apple-touch-icon-${size.width}x${size.height}.png`; + } +} +function sameAssetSize(a, b) { + if (typeof a === "number" && typeof b.original === "number") + return a === b.original; + if (typeof a !== "number" && typeof b.original !== "number") + return a.width === b.width && a.height === b.height; + return false; +} +function cloneResolvedAssetsSizes({ png, assetName, assets }) { + return { + assets: { + transparent: cloneResolvedAssetSizes(assets.transparent), + maskable: cloneResolvedAssetSizes(assets.maskable), + apple: cloneResolvedAssetSizes(assets.apple) + }, + png, + assetName + }; +} +function cloneResolvedAssetSizes({ sizes, ...asset }) { + return { + ...asset, + sizes: [...sizes] + }; +} + +export { cloneResolvedAssetSizes, cloneResolvedAssetsSizes, createPngCompressionOptions, createResizeOptions, defaultAssetName, defaultDarkResizeOptions, defaultPngCompressionOptions, defaultPngOptions, defaultResizeOptions, sameAssetSize, toResolvedAsset, toResolvedSize }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.cjs new file mode 100644 index 0000000000000000000000000000000000000000..d3a05e26bab92465670d34b92900b5025a833c63 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.cjs @@ -0,0 +1,9 @@ +'use strict'; + +const presets_minimal = require('./presets/minimal.cjs'); +const presets_minimal2023 = require('./presets/minimal-2023.cjs'); + + + +exports.minimalPreset = presets_minimal.minimalPreset; +exports.minimal2023Preset = presets_minimal2023.minimal2023Preset; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..f8e7ac5e416ae0668432c5f653831d4ac2df4fb5 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.cts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.cjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..c14d74fcac40ae0c7b4be281632134e7ce184a7f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.mts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.mjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..ffe366030c7efa61347a3677e3d03dff1a92f630 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.d.ts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset, p as minimalPreset } from './shared/assets-generator.DnoqiTld.js'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d77fc0739fe2c7a4a8c8355b32ac46ffa0673517 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets.mjs @@ -0,0 +1,2 @@ +export { minimalPreset } from './presets/minimal.mjs'; +export { minimal2023Preset } from './presets/minimal-2023.mjs'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.cjs new file mode 100644 index 0000000000000000000000000000000000000000..5a9771e34d7df4269450c7e374287cbb8a7b1143 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.cjs @@ -0,0 +1,16 @@ +'use strict'; + +const minimal2023Preset = { + transparent: { + sizes: [64, 192, 512], + favicons: [[48, "favicon.ico"]] + }, + maskable: { + sizes: [512] + }, + apple: { + sizes: [180] + } +}; + +exports.minimal2023Preset = minimal2023Preset; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..298798a17e655d247123b3c6ae82c688aeca68e6 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.cts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset } from '../shared/assets-generator.DnoqiTld.cjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..94998496477ed6523fa1588379f7fb2814685324 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.mts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset } from '../shared/assets-generator.DnoqiTld.mjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..789fc30534fd0739352c16c03167fabff62ecb98 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.d.ts @@ -0,0 +1,3 @@ +export { q as minimal2023Preset } from '../shared/assets-generator.DnoqiTld.js'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.mjs new file mode 100644 index 0000000000000000000000000000000000000000..17cde77d0fdf66b98d5f1922b108355d0f943f59 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal-2023.mjs @@ -0,0 +1,14 @@ +const minimal2023Preset = { + transparent: { + sizes: [64, 192, 512], + favicons: [[48, "favicon.ico"]] + }, + maskable: { + sizes: [512] + }, + apple: { + sizes: [180] + } +}; + +export { minimal2023Preset }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b639d90018330e74687694226ca78d644d9e1d28 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.cjs @@ -0,0 +1,16 @@ +'use strict'; + +const minimalPreset = { + transparent: { + sizes: [64, 192, 512], + favicons: [[64, "favicon.ico"]] + }, + maskable: { + sizes: [512] + }, + apple: { + sizes: [180] + } +}; + +exports.minimalPreset = minimalPreset; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..ddcb5a25592f9a868ae39dac2212df963647e03f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.cts @@ -0,0 +1,3 @@ +export { p as minimalPreset } from '../shared/assets-generator.DnoqiTld.cjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..1f7dcc6151e0eb479539a27d23de7589a7bc4daa --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.mts @@ -0,0 +1,3 @@ +export { p as minimalPreset } from '../shared/assets-generator.DnoqiTld.mjs'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..e1454600e24c67b9b19ac194ed26bfc33fccb73e --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.d.ts @@ -0,0 +1,3 @@ +export { p as minimalPreset } from '../shared/assets-generator.DnoqiTld.js'; +import 'sharp'; +import 'unconfig'; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.mjs new file mode 100644 index 0000000000000000000000000000000000000000..d5bee28c8b88b6243d86414684d336a0caf2e561 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/presets/minimal.mjs @@ -0,0 +1,14 @@ +const minimalPreset = { + transparent: { + sizes: [64, 192, 512], + favicons: [[64, "favicon.ico"]] + }, + maskable: { + sizes: [512] + }, + apple: { + sizes: [180] + } +}; + +export { minimalPreset }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.4HPlJg00.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.4HPlJg00.cjs new file mode 100644 index 0000000000000000000000000000000000000000..59b2ab30d0282c572b4aa00fa5a65d64110285bc --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.4HPlJg00.cjs @@ -0,0 +1,94 @@ +'use strict'; + +const appleSplashScreenSizes = { + 'iPad Pro 12.9"': { width: 2048, height: 2732, scaleFactor: 2 }, + 'iPad Pro 11"': { width: 1668, height: 2388, scaleFactor: 2 }, + 'iPad Pro 10.5"': { width: 1668, height: 2388, scaleFactor: 2 }, + 'iPad Pro 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad Air 13"': { width: 2048, height: 2732, scaleFactor: 2 }, + 'iPad Air 11"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad Air 10.9"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad Air 10.5"': { width: 1668, height: 2224, scaleFactor: 2 }, + 'iPad Air 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad 11"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad 10.2"': { width: 1620, height: 2160, scaleFactor: 2 }, + 'iPad 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad mini 8.3"': { width: 1488, height: 2266, scaleFactor: 2 }, + 'iPad mini 7.9"': { width: 1536, height: 2048, scaleFactor: 2 }, + "iPhone 16 Pro Max": { width: 1320, height: 2868, scaleFactor: 3 }, + "iPhone 16 Pro": { width: 1206, height: 2622, scaleFactor: 3 }, + "iPhone 16 Plus": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 16": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 16e": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 15 Pro Max": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 15 Pro": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 15 Plus": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 15": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 14 Pro Max": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 14 Pro": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 14 Plus": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 14": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13 Pro Max": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 13 Pro": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13 mini": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 12 Pro Max": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 12 Pro": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 12": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 12 mini": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 11 Pro Max": { width: 1242, height: 2688, scaleFactor: 3 }, + "iPhone 11 Pro": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 11": { width: 828, height: 1792, scaleFactor: 2 }, + "iPhone XS Max": { width: 1242, height: 2688, scaleFactor: 3 }, + "iPhone XS": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone XR": { width: 828, height: 1792, scaleFactor: 2 }, + "iPhone X": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 8 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 8": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 7 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 7": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 6s Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 6s": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 6 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 6": { width: 750, height: 1334, scaleFactor: 2 }, + 'iPhone SE 4.7"': { width: 750, height: 1334, scaleFactor: 2 }, + 'iPhone SE 4"': { width: 640, height: 1136, scaleFactor: 2 }, + "iPod touch 5th generation and later": { width: 640, height: 1136, scaleFactor: 2 } +}; +function defaultSplashScreenName(landscape, size, dark) { + return `apple-splash-${landscape ? "landscape" : "portrait"}-${typeof dark === "boolean" ? dark ? "dark-" : "light-" : ""}${size.width}x${size.height}.png`; +} +const AllAppleDeviceNames = Array.from(Object.keys(appleSplashScreenSizes).map((k) => k)); +function createAppleSplashScreens(options = {}, devices = AllAppleDeviceNames) { + const { + darkImageResolver, + padding, + resizeOptions, + darkResizeOptions, + linkMediaOptions, + png, + name + } = options; + return { + darkImageResolver, + sizes: devices.map((deviceName) => appleSplashScreenSizes[deviceName]), + padding, + resizeOptions, + darkResizeOptions, + linkMediaOptions, + png, + name + }; +} +function combinePresetAndAppleSplashScreens(preset, options = {}, devices = AllAppleDeviceNames) { + return { + ...preset, + appleSplashScreens: createAppleSplashScreens(options, devices) + }; +} + +exports.AllAppleDeviceNames = AllAppleDeviceNames; +exports.appleSplashScreenSizes = appleSplashScreenSizes; +exports.combinePresetAndAppleSplashScreens = combinePresetAndAppleSplashScreens; +exports.createAppleSplashScreens = createAppleSplashScreens; +exports.defaultSplashScreenName = defaultSplashScreenName; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.BQ3PQ6A_.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.BQ3PQ6A_.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..f6bc91ed02fe1019ce33885a03b2d5ee9d4d2140 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.BQ3PQ6A_.d.ts @@ -0,0 +1,170 @@ +import sharp__default, { PngOptions, WebpOptions } from 'sharp'; +import { H as HtmlLink, B as BuiltInPreset, P as Preset, a as HtmlLinkPreset, F as FaviconLink, A as AppleSplashScreenLink } from './assets-generator.DnoqiTld.js'; + +type ImageSourceInput = Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string; +interface GenerateOptions { + /** + * @default 0 + */ + padding?: number; + outputOptions?: any; + resizeOptions?: sharp__default.ResizeOptions; +} +type GenerateOptionsType = 'png' | 'webp' | 'none'; +type GenerateOptionsOptionType = T extends 'png' ? GenerateOutputOptions : T extends 'webp' ? GenerateOutputOptions : T extends 'none' ? GenerateOptions : never; +interface GenerateOutputOptions extends GenerateOptions { + outputOptions: T; +} +type GenerateFaviconType = 'png' | 'webp'; +type GenerateFaviconOptionsType = T extends 'png' ? PngOptions : T extends 'webp' ? WebpOptions : never; +/** + * PWA web manifest icon. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcon { + src: string; + type?: string; + sizes?: string; + purpose?: string; +} +/** + * PWA web manifest icons. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcons { + icons: ManifestIcon[]; +} +type ManifestIconsType = 'string' | 'object'; +type ManifestIconsOptionsType = T extends 'string' ? string : T extends 'object' ? ManifestIcons : never; +interface IconAsset { + /** + * The name of the icon asset. + */ + name: string; + /** + * The icon asset url. + */ + url: string; + /** + * The icon asset width. + * + * For the SVG image favicon icon, it will be set to 0. + */ + width: number; + /** + * The icon asset height. + * + * For the SVG image favicon icon, it will be set to 0. + */ + height: number; + /** + * The icon asset mime type. + */ + mimeType: 'image/png' | 'image/webp' | 'image/svg+xml' | 'image/x-icon'; + /** + * The html head link. + */ + link?: string; + /** + * The html head link. + */ + linkObject?: T; + /** + * Creates the icon asset. + */ + buffer: () => Promise; +} +/** + * PWA assets generation and injection options. + */ +interface ImageAssets { + /** + * The image to use for generating the icon assets. + */ + imageResolver: () => Buffer | Promise; + /** + * The name of the image. + */ + imageName: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The preset to use. + */ + preset: BuiltInPreset | Preset; + /** + * The preset for the favicons. + * + * If using the built-in preset option (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + faviconPreset?: HtmlLinkPreset; + /** + * Html link options. + */ + htmlLinks: { + xhtml: boolean; + includeId: boolean; + }; + /** + * Base path to generate the html head links. + */ + basePath: string; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName: (name: string) => string; +} +interface ImageAssetsInstructions { + /** + * The image path when providing an absolute path, otherwise the image name provided to `instructions`. + */ + image: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The favicon icons instructions. + * + * The key is the favicon url of the icon asset. + */ + favicon: Record>; + /** + * The transparents icons instructions. + * + * The key is the icon url of the icon asset. + */ + transparent: Record>; + /** + * The maskable icons instructions. + * + * The key is the icon url of the icon asset. + */ + maskable: Record>; + /** + * The apple icons instructions. + * + * The key is the icon url of the icon asset. + */ + apple: Record>; + /** + * The apple splash screens icons instructions. + * + * The key is the favicon icons of the icon asset. + */ + appleSplashScreen: Record>; +} + +export type { GenerateOptionsType as G, ImageAssets as I, ManifestIconsType as M, ImageAssetsInstructions as a, ManifestIconsOptionsType as b, ImageSourceInput as c, GenerateOptionsOptionType as d, GenerateFaviconType as e, GenerateFaviconOptionsType as f, GenerateOptions as g, GenerateOutputOptions as h, ManifestIcon as i, ManifestIcons as j, IconAsset as k }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.Bot_1kJ_.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.Bot_1kJ_.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..61d4a55776aea41eec7ab4ee3b587769e633d3b0 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.Bot_1kJ_.d.mts @@ -0,0 +1,170 @@ +import sharp__default, { PngOptions, WebpOptions } from 'sharp'; +import { H as HtmlLink, B as BuiltInPreset, P as Preset, a as HtmlLinkPreset, F as FaviconLink, A as AppleSplashScreenLink } from './assets-generator.DnoqiTld.mjs'; + +type ImageSourceInput = Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string; +interface GenerateOptions { + /** + * @default 0 + */ + padding?: number; + outputOptions?: any; + resizeOptions?: sharp__default.ResizeOptions; +} +type GenerateOptionsType = 'png' | 'webp' | 'none'; +type GenerateOptionsOptionType = T extends 'png' ? GenerateOutputOptions : T extends 'webp' ? GenerateOutputOptions : T extends 'none' ? GenerateOptions : never; +interface GenerateOutputOptions extends GenerateOptions { + outputOptions: T; +} +type GenerateFaviconType = 'png' | 'webp'; +type GenerateFaviconOptionsType = T extends 'png' ? PngOptions : T extends 'webp' ? WebpOptions : never; +/** + * PWA web manifest icon. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcon { + src: string; + type?: string; + sizes?: string; + purpose?: string; +} +/** + * PWA web manifest icons. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcons { + icons: ManifestIcon[]; +} +type ManifestIconsType = 'string' | 'object'; +type ManifestIconsOptionsType = T extends 'string' ? string : T extends 'object' ? ManifestIcons : never; +interface IconAsset { + /** + * The name of the icon asset. + */ + name: string; + /** + * The icon asset url. + */ + url: string; + /** + * The icon asset width. + * + * For the SVG image favicon icon, it will be set to 0. + */ + width: number; + /** + * The icon asset height. + * + * For the SVG image favicon icon, it will be set to 0. + */ + height: number; + /** + * The icon asset mime type. + */ + mimeType: 'image/png' | 'image/webp' | 'image/svg+xml' | 'image/x-icon'; + /** + * The html head link. + */ + link?: string; + /** + * The html head link. + */ + linkObject?: T; + /** + * Creates the icon asset. + */ + buffer: () => Promise; +} +/** + * PWA assets generation and injection options. + */ +interface ImageAssets { + /** + * The image to use for generating the icon assets. + */ + imageResolver: () => Buffer | Promise; + /** + * The name of the image. + */ + imageName: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The preset to use. + */ + preset: BuiltInPreset | Preset; + /** + * The preset for the favicons. + * + * If using the built-in preset option (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + faviconPreset?: HtmlLinkPreset; + /** + * Html link options. + */ + htmlLinks: { + xhtml: boolean; + includeId: boolean; + }; + /** + * Base path to generate the html head links. + */ + basePath: string; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName: (name: string) => string; +} +interface ImageAssetsInstructions { + /** + * The image path when providing an absolute path, otherwise the image name provided to `instructions`. + */ + image: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The favicon icons instructions. + * + * The key is the favicon url of the icon asset. + */ + favicon: Record>; + /** + * The transparents icons instructions. + * + * The key is the icon url of the icon asset. + */ + transparent: Record>; + /** + * The maskable icons instructions. + * + * The key is the icon url of the icon asset. + */ + maskable: Record>; + /** + * The apple icons instructions. + * + * The key is the icon url of the icon asset. + */ + apple: Record>; + /** + * The apple splash screens icons instructions. + * + * The key is the favicon icons of the icon asset. + */ + appleSplashScreen: Record>; +} + +export type { GenerateOptionsType as G, ImageAssets as I, ManifestIconsType as M, ImageAssetsInstructions as a, ManifestIconsOptionsType as b, ImageSourceInput as c, GenerateOptionsOptionType as d, GenerateFaviconType as e, GenerateFaviconOptionsType as f, GenerateOptions as g, GenerateOutputOptions as h, ManifestIcon as i, ManifestIcons as j, IconAsset as k }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CTKvG_gr.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CTKvG_gr.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..284152ab2c073142d4ad9507a7f2ef2ad2499917 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CTKvG_gr.d.cts @@ -0,0 +1,170 @@ +import sharp__default, { PngOptions, WebpOptions } from 'sharp'; +import { H as HtmlLink, B as BuiltInPreset, P as Preset, a as HtmlLinkPreset, F as FaviconLink, A as AppleSplashScreenLink } from './assets-generator.DnoqiTld.cjs'; + +type ImageSourceInput = Buffer | ArrayBuffer | Uint8Array | Uint8ClampedArray | Int8Array | Uint16Array | Int16Array | Uint32Array | Int32Array | Float32Array | Float64Array | string; +interface GenerateOptions { + /** + * @default 0 + */ + padding?: number; + outputOptions?: any; + resizeOptions?: sharp__default.ResizeOptions; +} +type GenerateOptionsType = 'png' | 'webp' | 'none'; +type GenerateOptionsOptionType = T extends 'png' ? GenerateOutputOptions : T extends 'webp' ? GenerateOutputOptions : T extends 'none' ? GenerateOptions : never; +interface GenerateOutputOptions extends GenerateOptions { + outputOptions: T; +} +type GenerateFaviconType = 'png' | 'webp'; +type GenerateFaviconOptionsType = T extends 'png' ? PngOptions : T extends 'webp' ? WebpOptions : never; +/** + * PWA web manifest icon. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcon { + src: string; + type?: string; + sizes?: string; + purpose?: string; +} +/** + * PWA web manifest icons. + * + * @see https://developer.mozilla.org/en-US/docs/Web/Manifest/icons + * @see https://w3c.github.io/manifest/#icons-member + */ +interface ManifestIcons { + icons: ManifestIcon[]; +} +type ManifestIconsType = 'string' | 'object'; +type ManifestIconsOptionsType = T extends 'string' ? string : T extends 'object' ? ManifestIcons : never; +interface IconAsset { + /** + * The name of the icon asset. + */ + name: string; + /** + * The icon asset url. + */ + url: string; + /** + * The icon asset width. + * + * For the SVG image favicon icon, it will be set to 0. + */ + width: number; + /** + * The icon asset height. + * + * For the SVG image favicon icon, it will be set to 0. + */ + height: number; + /** + * The icon asset mime type. + */ + mimeType: 'image/png' | 'image/webp' | 'image/svg+xml' | 'image/x-icon'; + /** + * The html head link. + */ + link?: string; + /** + * The html head link. + */ + linkObject?: T; + /** + * Creates the icon asset. + */ + buffer: () => Promise; +} +/** + * PWA assets generation and injection options. + */ +interface ImageAssets { + /** + * The image to use for generating the icon assets. + */ + imageResolver: () => Buffer | Promise; + /** + * The name of the image. + */ + imageName: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The preset to use. + */ + preset: BuiltInPreset | Preset; + /** + * The preset for the favicons. + * + * If using the built-in preset option (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + faviconPreset?: HtmlLinkPreset; + /** + * Html link options. + */ + htmlLinks: { + xhtml: boolean; + includeId: boolean; + }; + /** + * Base path to generate the html head links. + */ + basePath: string; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName: (name: string) => string; +} +interface ImageAssetsInstructions { + /** + * The image path when providing an absolute path, otherwise the image name provided to `instructions`. + */ + image: string; + /** + * The original name of the image. + */ + originalName?: string; + /** + * The favicon icons instructions. + * + * The key is the favicon url of the icon asset. + */ + favicon: Record>; + /** + * The transparents icons instructions. + * + * The key is the icon url of the icon asset. + */ + transparent: Record>; + /** + * The maskable icons instructions. + * + * The key is the icon url of the icon asset. + */ + maskable: Record>; + /** + * The apple icons instructions. + * + * The key is the icon url of the icon asset. + */ + apple: Record>; + /** + * The apple splash screens icons instructions. + * + * The key is the favicon icons of the icon asset. + */ + appleSplashScreen: Record>; +} + +export type { GenerateOptionsType as G, ImageAssets as I, ManifestIconsType as M, ImageAssetsInstructions as a, ManifestIconsOptionsType as b, ImageSourceInput as c, GenerateOptionsOptionType as d, GenerateFaviconType as e, GenerateFaviconOptionsType as f, GenerateOptions as g, GenerateOutputOptions as h, ManifestIcon as i, ManifestIcons as j, IconAsset as k }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CUAsp7yq.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CUAsp7yq.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e491da05a9becb07dbec9bc770cc6b1d8c51d0c7 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.CUAsp7yq.mjs @@ -0,0 +1,88 @@ +const appleSplashScreenSizes = { + 'iPad Pro 12.9"': { width: 2048, height: 2732, scaleFactor: 2 }, + 'iPad Pro 11"': { width: 1668, height: 2388, scaleFactor: 2 }, + 'iPad Pro 10.5"': { width: 1668, height: 2388, scaleFactor: 2 }, + 'iPad Pro 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad Air 13"': { width: 2048, height: 2732, scaleFactor: 2 }, + 'iPad Air 11"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad Air 10.9"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad Air 10.5"': { width: 1668, height: 2224, scaleFactor: 2 }, + 'iPad Air 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad 11"': { width: 1640, height: 2360, scaleFactor: 2 }, + 'iPad 10.2"': { width: 1620, height: 2160, scaleFactor: 2 }, + 'iPad 9.7"': { width: 1536, height: 2048, scaleFactor: 2 }, + 'iPad mini 8.3"': { width: 1488, height: 2266, scaleFactor: 2 }, + 'iPad mini 7.9"': { width: 1536, height: 2048, scaleFactor: 2 }, + "iPhone 16 Pro Max": { width: 1320, height: 2868, scaleFactor: 3 }, + "iPhone 16 Pro": { width: 1206, height: 2622, scaleFactor: 3 }, + "iPhone 16 Plus": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 16": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 16e": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 15 Pro Max": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 15 Pro": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 15 Plus": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 15": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 14 Pro Max": { width: 1290, height: 2796, scaleFactor: 3 }, + "iPhone 14 Pro": { width: 1179, height: 2556, scaleFactor: 3 }, + "iPhone 14 Plus": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 14": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13 Pro Max": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 13 Pro": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 13 mini": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 12 Pro Max": { width: 1284, height: 2778, scaleFactor: 3 }, + "iPhone 12 Pro": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 12": { width: 1170, height: 2532, scaleFactor: 3 }, + "iPhone 12 mini": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 11 Pro Max": { width: 1242, height: 2688, scaleFactor: 3 }, + "iPhone 11 Pro": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 11": { width: 828, height: 1792, scaleFactor: 2 }, + "iPhone XS Max": { width: 1242, height: 2688, scaleFactor: 3 }, + "iPhone XS": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone XR": { width: 828, height: 1792, scaleFactor: 2 }, + "iPhone X": { width: 1125, height: 2436, scaleFactor: 3 }, + "iPhone 8 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 8": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 7 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 7": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 6s Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 6s": { width: 750, height: 1334, scaleFactor: 2 }, + "iPhone 6 Plus": { width: 1242, height: 2208, scaleFactor: 3 }, + "iPhone 6": { width: 750, height: 1334, scaleFactor: 2 }, + 'iPhone SE 4.7"': { width: 750, height: 1334, scaleFactor: 2 }, + 'iPhone SE 4"': { width: 640, height: 1136, scaleFactor: 2 }, + "iPod touch 5th generation and later": { width: 640, height: 1136, scaleFactor: 2 } +}; +function defaultSplashScreenName(landscape, size, dark) { + return `apple-splash-${landscape ? "landscape" : "portrait"}-${typeof dark === "boolean" ? dark ? "dark-" : "light-" : ""}${size.width}x${size.height}.png`; +} +const AllAppleDeviceNames = Array.from(Object.keys(appleSplashScreenSizes).map((k) => k)); +function createAppleSplashScreens(options = {}, devices = AllAppleDeviceNames) { + const { + darkImageResolver, + padding, + resizeOptions, + darkResizeOptions, + linkMediaOptions, + png, + name + } = options; + return { + darkImageResolver, + sizes: devices.map((deviceName) => appleSplashScreenSizes[deviceName]), + padding, + resizeOptions, + darkResizeOptions, + linkMediaOptions, + png, + name + }; +} +function combinePresetAndAppleSplashScreens(preset, options = {}, devices = AllAppleDeviceNames) { + return { + ...preset, + appleSplashScreens: createAppleSplashScreens(options, devices) + }; +} + +export { AllAppleDeviceNames as A, appleSplashScreenSizes as a, combinePresetAndAppleSplashScreens as b, createAppleSplashScreens as c, defaultSplashScreenName as d }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D-6RJH5l.mjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D-6RJH5l.mjs new file mode 100644 index 0000000000000000000000000000000000000000..121196b1c908baa86d1bfd89dc851abc9b892e5f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D-6RJH5l.mjs @@ -0,0 +1,168 @@ +import { d as defaultSplashScreenName } from './assets-generator.CUAsp7yq.mjs'; +import { toResolvedSize } from '../index.mjs'; +import sharp from 'sharp'; +import { encode } from 'sharp-ico'; + +function extractAssetSize(size, padding) { + const width = typeof size.original === "number" ? size.original : size.original.width; + const height = typeof size.original === "number" ? size.original : size.original.height; + return { + width: Math.round(width * (1 - padding)), + height: Math.round(height * (1 - padding)) + }; +} +async function createSharp(type, image, size, background, options, channels) { + const { padding = 0 } = options ?? {}; + const useSize = toResolvedSize(size); + const { width, height } = extractAssetSize(useSize, padding); + const result = sharp({ + create: { + width: useSize.width, + height: useSize.height, + channels: channels ?? 4, + background + } + }).composite([{ + input: await sharp(image).resize( + width, + height, + options?.resizeOptions + ).toBuffer() + }]); + if (type === "none" || !options) + return result; + return type === "png" ? result.png(options.outputOptions) : result.webp(options.outputOptions); +} + +function createFaviconHtmlLink(format, preset, icon) { + const result = createFaviconLink(preset, icon); + if (format === "string") { + let favicon = ``; + return favicon; + } + return result; +} +function createAppleTouchIconHtmlLink(format, icon) { + const href = `${icon.basePath ?? "/"}${icon.name}`; + const { width, height } = toResolvedSize(icon.size); + const id = `ati-${width}-${height}`; + if (format === "string") + return ``; + return { + id, + rel: "apple-touch-icon", + href + }; +} +function createAppleSplashScreenHtmlLink(format, options) { + const link = createAppleSplashScreenLink( + createRequiredHtmlLinkOptions(options) + ); + return format === "string" ? `` : link; +} +function createFaviconLink(preset, icon) { + const href = `${icon.basePath ?? "/"}${icon.name}`; + if (icon.name.endsWith(".svg")) { + if (preset === "2023") { + return { + id: "fav-svg", + type: "image/svg+xml", + href, + rel: "icon", + sizes: "any" + }; + } + return { + id: "fav-svg", + type: "image/svg+xml", + href, + rel: "icon" + }; + } + const { width, height } = toResolvedSize(icon.size); + if (preset === "2023") { + return { + id: `fav-${width}x${height}`, + href, + rel: "icon", + sizes: `${width}x${height}` + }; + } + return { + id: `fav-${height}x${height}`, + href, + rel: "icon", + sizes: "any" + }; +} +function createAppleSplashScreenLink(options) { + const { + size, + landscape, + addMediaScreen, + name, + basePath, + dark + } = options; + const { width, height, scaleFactor } = size; + const tokens = [ + `(device-width: ${(landscape ? height : width) / scaleFactor}px)`, + `(device-height: ${(landscape ? width : height) / scaleFactor}px)`, + `(-webkit-device-pixel-ratio: ${scaleFactor})`, + `(orientation: ${landscape ? "landscape" : "portrait"})` + ]; + if (dark) + tokens.unshift("(prefers-color-scheme: dark)"); + if (addMediaScreen) + tokens.unshift("screen"); + return { + id: `atsi-${landscape ? height : width}-${landscape ? width : height}-${scaleFactor}-${dark ? "dark" : "light"}`, + rel: "apple-touch-startup-image", + media: tokens.join(" and "), + href: `${basePath}${name(landscape, size, dark)}` + }; +} +function createRequiredHtmlLinkOptions(options) { + return { + size: options.size, + landscape: options.landscape, + addMediaScreen: options.addMediaScreen, + name: options.name ?? defaultSplashScreenName, + basePath: options.basePath ?? "/", + dark: options.dark === true, + includeId: options.includeId === true + }; +} + +async function generateMaskableAsset(type, image, size, options) { + return await createSharp( + type, + image, + size, + options?.resizeOptions?.background ?? "white", + options, + 4 + ); +} + +async function generateTransparentAsset(type, image, size, options) { + return await createSharp( + type, + image, + size, + { r: 0, g: 0, b: 0, alpha: 0 }, + options, + 4 + ); +} + +async function generateFavicon(format, image, options) { + return encode([await sharp(image).toFormat(format, options).toBuffer()]); +} + +export { createFaviconHtmlLink as a, createAppleTouchIconHtmlLink as b, createSharp as c, createAppleSplashScreenHtmlLink as d, extractAssetSize as e, generateTransparentAsset as f, generateMaskableAsset as g, generateFavicon as h }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D6uDklIq.cjs b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D6uDklIq.cjs new file mode 100644 index 0000000000000000000000000000000000000000..b5552c97f1764d66fe8ccfa096cd8a91ecd24bac --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.D6uDklIq.cjs @@ -0,0 +1,181 @@ +'use strict'; + +const splash = require('./assets-generator.4HPlJg00.cjs'); +const index = require('../index.cjs'); +const sharp = require('sharp'); +const sharpIco = require('sharp-ico'); + +function _interopDefaultCompat (e) { return e && typeof e === 'object' && 'default' in e ? e.default : e; } + +const sharp__default = /*#__PURE__*/_interopDefaultCompat(sharp); + +function extractAssetSize(size, padding) { + const width = typeof size.original === "number" ? size.original : size.original.width; + const height = typeof size.original === "number" ? size.original : size.original.height; + return { + width: Math.round(width * (1 - padding)), + height: Math.round(height * (1 - padding)) + }; +} +async function createSharp(type, image, size, background, options, channels) { + const { padding = 0 } = options ?? {}; + const useSize = index.toResolvedSize(size); + const { width, height } = extractAssetSize(useSize, padding); + const result = sharp__default({ + create: { + width: useSize.width, + height: useSize.height, + channels: channels ?? 4, + background + } + }).composite([{ + input: await sharp__default(image).resize( + width, + height, + options?.resizeOptions + ).toBuffer() + }]); + if (type === "none" || !options) + return result; + return type === "png" ? result.png(options.outputOptions) : result.webp(options.outputOptions); +} + +function createFaviconHtmlLink(format, preset, icon) { + const result = createFaviconLink(preset, icon); + if (format === "string") { + let favicon = ``; + return favicon; + } + return result; +} +function createAppleTouchIconHtmlLink(format, icon) { + const href = `${icon.basePath ?? "/"}${icon.name}`; + const { width, height } = index.toResolvedSize(icon.size); + const id = `ati-${width}-${height}`; + if (format === "string") + return ``; + return { + id, + rel: "apple-touch-icon", + href + }; +} +function createAppleSplashScreenHtmlLink(format, options) { + const link = createAppleSplashScreenLink( + createRequiredHtmlLinkOptions(options) + ); + return format === "string" ? `` : link; +} +function createFaviconLink(preset, icon) { + const href = `${icon.basePath ?? "/"}${icon.name}`; + if (icon.name.endsWith(".svg")) { + if (preset === "2023") { + return { + id: "fav-svg", + type: "image/svg+xml", + href, + rel: "icon", + sizes: "any" + }; + } + return { + id: "fav-svg", + type: "image/svg+xml", + href, + rel: "icon" + }; + } + const { width, height } = index.toResolvedSize(icon.size); + if (preset === "2023") { + return { + id: `fav-${width}x${height}`, + href, + rel: "icon", + sizes: `${width}x${height}` + }; + } + return { + id: `fav-${height}x${height}`, + href, + rel: "icon", + sizes: "any" + }; +} +function createAppleSplashScreenLink(options) { + const { + size, + landscape, + addMediaScreen, + name, + basePath, + dark + } = options; + const { width, height, scaleFactor } = size; + const tokens = [ + `(device-width: ${(landscape ? height : width) / scaleFactor}px)`, + `(device-height: ${(landscape ? width : height) / scaleFactor}px)`, + `(-webkit-device-pixel-ratio: ${scaleFactor})`, + `(orientation: ${landscape ? "landscape" : "portrait"})` + ]; + if (dark) + tokens.unshift("(prefers-color-scheme: dark)"); + if (addMediaScreen) + tokens.unshift("screen"); + return { + id: `atsi-${landscape ? height : width}-${landscape ? width : height}-${scaleFactor}-${dark ? "dark" : "light"}`, + rel: "apple-touch-startup-image", + media: tokens.join(" and "), + href: `${basePath}${name(landscape, size, dark)}` + }; +} +function createRequiredHtmlLinkOptions(options) { + return { + size: options.size, + landscape: options.landscape, + addMediaScreen: options.addMediaScreen, + name: options.name ?? splash.defaultSplashScreenName, + basePath: options.basePath ?? "/", + dark: options.dark === true, + includeId: options.includeId === true + }; +} + +async function generateMaskableAsset(type, image, size, options) { + return await createSharp( + type, + image, + size, + options?.resizeOptions?.background ?? "white", + options, + 4 + ); +} + +async function generateTransparentAsset(type, image, size, options) { + return await createSharp( + type, + image, + size, + { r: 0, g: 0, b: 0, alpha: 0 }, + options, + 4 + ); +} + +async function generateFavicon(format, image, options) { + return sharpIco.encode([await sharp__default(image).toFormat(format, options).toBuffer()]); +} + +exports.createAppleSplashScreenHtmlLink = createAppleSplashScreenHtmlLink; +exports.createAppleTouchIconHtmlLink = createAppleTouchIconHtmlLink; +exports.createFaviconHtmlLink = createFaviconHtmlLink; +exports.createSharp = createSharp; +exports.extractAssetSize = extractAssetSize; +exports.generateFavicon = generateFavicon; +exports.generateMaskableAsset = generateMaskableAsset; +exports.generateTransparentAsset = generateTransparentAsset; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.cts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.cts new file mode 100644 index 0000000000000000000000000000000000000000..dde2d35749c50af0bb99cb25d613cace68bdad62 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.cts @@ -0,0 +1,502 @@ +import * as sharp from 'sharp'; +import { PngOptions, ResizeOptions } from 'sharp'; +import { LoadConfigSource, LoadConfigResult } from 'unconfig'; + +type HtmlLinkPreset = 'default' | '2023'; +interface HtmlLink { + id: string; + rel: 'apple-touch-startup-image' | 'apple-touch-icon' | 'icon'; + href: string; +} +interface AppleSplashScreenLink extends HtmlLink { + media: string; +} +interface FaviconLink extends HtmlLink { + sizes?: string; + type?: string; +} +type HtmlLinkType = 'string' | 'link'; +type HtmlLinkReturnType = T extends 'string' ? string : T extends 'link' ? R : never; +interface HtmlIconLinkOptions { + name: string; + /** + * Required only for non SVG favicon + */ + size?: AssetSize; + xhtml?: boolean; + basePath?: string; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +interface AppleSplahScreenHtmlLinkOptions { + size: AppleDeviceSize; + landscape: boolean; + addMediaScreen: boolean; + xhtml?: boolean; + name?: AppleSplashScreenName; + basePath?: string; + dark?: boolean; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +declare function createFaviconHtmlLink(format: Format, preset: HtmlLinkPreset, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleTouchIconHtmlLink(format: Format, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleSplashScreenHtmlLink(format: Format, options: AppleSplahScreenHtmlLinkOptions): HtmlLinkReturnType; + +declare const defaultResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultDarkResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultPngCompressionOptions: PngOptions; +declare const defaultPngOptions: Record; +declare function createResizeOptions(dark: boolean, options: ResizeOptions): { + width?: number | undefined; + height?: number | undefined; + fit: keyof sharp.FitEnum; + position?: number | string | undefined; + background: sharp.Color; + kernel?: keyof sharp.KernelEnum | undefined; + withoutEnlargement?: boolean | undefined; + withoutReduction?: boolean | undefined; + fastShrinkOnLoad?: boolean | undefined; +}; +declare function createPngCompressionOptions(options: PngOptions): { + progressive?: boolean | undefined; + compressionLevel?: number | undefined; + adaptiveFiltering?: boolean | undefined; + quality?: number | undefined; + effort?: number | undefined; + palette?: boolean | undefined; + colours?: number | undefined; + colors?: number | undefined; + dither?: number | undefined; + force?: boolean | undefined; +}; + +interface Preset extends Assets { +} + +/** + * Minimal preset. + * + * @deprecated use `minimal-2023` instead + * @see https://www.leereamsnyder.com/favicons-in-2021 + */ +declare const minimalPreset: Preset; + +/** + * Minimal preset for 2023. + * + * @see https://dev.to/masakudamatsu/favicon-nightmare-how-to-maintain-sanity-3al7 + */ +declare const minimal2023Preset: Preset; + +type AppleDeviceName = 'iPad Pro 12.9"' | 'iPad Pro 11"' | 'iPad Pro 10.5"' | 'iPad Pro 9.7"' | 'iPad Air 13"' | 'iPad Air 11"' | 'iPad Air 10.9"' | 'iPad Air 10.5"' | 'iPad Air 9.7"' | 'iPad 11"' | 'iPad 10.2"' | 'iPad 9.7"' | 'iPad mini 8.3"' | 'iPad mini 7.9"' | 'iPhone 16 Pro Max' | 'iPhone 16 Pro' | 'iPhone 16 Plus' | 'iPhone 16' | 'iPhone 16e' | 'iPhone 15 Pro Max' | 'iPhone 15 Pro' | 'iPhone 15 Plus' | 'iPhone 15' | 'iPhone 14 Pro Max' | 'iPhone 14 Pro' | 'iPhone 14 Plus' | 'iPhone 14' | 'iPhone 13 Pro Max' | 'iPhone 13 Pro' | 'iPhone 13' | 'iPhone 13 mini' | 'iPhone 12 Pro Max' | 'iPhone 12 Pro' | 'iPhone 12' | 'iPhone 12 mini' | 'iPhone 11 Pro Max' | 'iPhone 11 Pro' | 'iPhone 11' | 'iPhone XS Max' | 'iPhone XS' | 'iPhone XR' | 'iPhone X' | 'iPhone 8 Plus' | 'iPhone 8' | 'iPhone 7 Plus' | 'iPhone 7' | 'iPhone 6s Plus' | 'iPhone 6s' | 'iPhone 6 Plus' | 'iPhone 6' | 'iPhone SE 4.7"' | 'iPhone SE 4"' | 'iPod touch 5th generation and later'; +interface AppleSplashScreen extends Record { +} +/** + * Apple device names and resolutions. + * @see https://developer.apple.com/design/human-interface-guidelines/layout#iOS-iPadOS-device-screen-dimensions + */ +declare const appleSplashScreenSizes: AppleSplashScreen; +declare function defaultSplashScreenName(landscape: boolean, size: AppleDeviceSize, dark?: boolean): string; +declare const AllAppleDeviceNames: AppleDeviceName[]; +declare function createAppleSplashScreens(options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; +}; +declare function combinePresetAndAppleSplashScreens(preset: Preset, options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + appleSplashScreens: { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; + }; + png?: PngOptions; + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + transparent: Asset; + maskable: Asset; + apple: Asset; +}; + +declare function toResolvedSize(size: AssetSize): { + original: AssetSize; + width: number; + height: number; +}; +declare function toResolvedAsset(type: AssetType, asset: Asset): { + sizes: { + original: AssetSize; + width: number; + height: number; + }[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + favicons?: Favicon[]; +}; +declare function defaultAssetName(type: AssetType, size: ResolvedAssetSize): string; +declare function sameAssetSize(a: AssetSize, b: ResolvedAssetSize): boolean; +declare function cloneResolvedAssetsSizes({ png, assetName, assets }: ResolvedAssets): { + assets: { + transparent: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + maskable: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + apple: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + }; + png: sharp.PngOptions; + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +}; +declare function cloneResolvedAssetSizes({ sizes, ...asset }: ResolvedAsset): { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; +}; + +/** + * Built-in presets. + * - `minimal-2023`: Only generate the bare minimum assets. + * - `minimal`: Only generate the bare minimum assets (deprecated). + * - `android`: Generate assets for Android. + * - `windows`: Generate assets for Windows. + * - `ios`: Generate assets for iOS. + * - `all`: `android`, `windows` and `ios` presets combined. + */ +type BuiltInPreset = 'minimal' | 'minimal-2023' | 'android' | 'windows' | 'ios' | 'all'; +interface HeadLinkOptions { + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * The preset to use. + * + * If using the built-in presets from CLI (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + preset?: HtmlLinkPreset; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName?: (name: string) => string; + /** + * Generate an id when generating the html head links. + * + * @default false + */ + xhtml?: boolean; + /** + * Include the id when generating the html head links. + * + * @default false + */ + includeId?: boolean; +} +interface UserConfig { + /** + * Project root directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default process.cwd() + */ + root?: string; + /** + * Path to the config file. + * + * Default resolving to `pwa-assets.config.[js|mjs|cjs]` + * + * Setting to `false` will disable config resolving. + */ + config?: string | false; + /** + * Override assets? + * + * @default true + */ + overrideAssets?: boolean; + /** + * Log level. + * + * @default 'info' + */ + logLevel?: LogLevel; + /** + * Path relative to `root` where to find the images to use for generating PWA assets. + * + * PWA Assets will be generated in the same directory. + */ + images?: string | string[]; + /** + * Preset to use. + * + * @default 'minimal' + */ + preset?: BuiltInPreset | Preset; + /** + * Options for generating the html head links for `apple-touch-icon` and favicons. + */ + headLinkOptions?: HeadLinkOptions; + /** + * Show the PWA web manifest icons' entry. + * + * @default true + */ + manifestIconsEntry?: boolean; +} +interface ResolvedConfig extends Required> { + preset: Preset; +} +declare function defineConfig(config: UserConfig): UserConfig; +declare function loadConfig(cwd?: string, configOrPath?: string | U, extraConfigSources?: LoadConfigSource[], defaults?: UserConfig): Promise>; + +/** + * Icon size. + */ +type AssetSize = number | { + width: number; + height: number; +}; +/** + * Icon size with resolved width and height. + */ +interface ResolvedAssetSize { + original: AssetSize; + width: number; + height: number; +} +/** + * Favicon size and name. + */ +type Favicon = [size: AssetSize, name: string]; +interface Asset { + sizes: AssetSize[]; + padding?: number; + resizeOptions?: ResizeOptions; + favicons?: Favicon[]; +} +interface AppleDeviceSize { + width: number; + height: number; + scaleFactor: number; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; +} +type AppleSplashScreenName = (landscape: boolean, size: AppleDeviceSize, dark?: boolean) => string; +interface AppleTouchStartupImageOptions { + /** + * Show the html head links? + * + * @default true + */ + log?: boolean; + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * Add media screen to the `apple-touch-startup-image` rel link? + * + * @default true + */ + addMediaScreen?: boolean; + /** + * Using XHTML? + * + * @default false + */ + xhtml?: boolean; +} +interface AppleSplashScreens { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + sizes: AppleDeviceSize[]; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * Global png options. + * + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; + /** + * Options to generate the html head links. + */ + linkMediaOptions?: AppleTouchStartupImageOptions; + /** + * Customize the splash screen name. + * + * @param landscape Is the splash screen landscape? + * @param size The splash screen size. + * @param dark Is the splash screen dark? + * @returns The splash screen name. + * + * @default (landscape, size, dark?: boolean) => `apple-splash-${landscape ? 'landscape' : 'portrait'}-${typeof dark === 'boolean' ? (dark ? 'dark-' : 'light-') : ''}${size.width}x${size.height}.png` + */ + name?: AppleSplashScreenName; +} +interface ResolvedAppleSplashScreens { + darkImageResolver?: (imageName: string) => Promise; + padding: number; + sizes: AppleDeviceSize[]; + linkMediaOptions: Required; + name: AppleSplashScreenName; + png: PngOptions; +} +type AssetType = 'transparent' | 'maskable' | 'apple'; +interface ResolvedAsset extends Required> { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; +} +interface Assets extends Record { + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + /** + * Splash screens. + */ + appleSplashScreens?: AppleSplashScreens; +} +interface ResolvedAssets { + assets: Record; + png: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +} +type LogLevel = 'info' | 'warn' | 'silent'; +interface BuildOptions { + root: string; + logLevel?: LogLevel; + overrideAssets?: boolean; + headLinkOptions: Required; +} +interface ResolvedBuildOptions extends Required { +} + +export { cloneResolvedAssetsSizes as $, AllAppleDeviceNames as C, createAppleSplashScreens as D, combinePresetAndAppleSplashScreens as E, toResolvedSize as Y, toResolvedAsset as Z, sameAssetSize as _, cloneResolvedAssetSizes as a0, defaultDarkResizeOptions as c, defaultResizeOptions as d, defaultPngCompressionOptions as e, defaultPngOptions as f, createResizeOptions as g, createPngCompressionOptions as h, createFaviconHtmlLink as m, createAppleTouchIconHtmlLink as n, createAppleSplashScreenHtmlLink as o, minimalPreset as p, minimal2023Preset as q, defineConfig as t, loadConfig as u, defaultAssetName as v, appleSplashScreenSizes as y, defaultSplashScreenName as z }; +export type { AppleSplashScreenLink as A, BuiltInPreset as B, FaviconLink as F, Favicon as G, HtmlLink as H, Asset as I, AppleDeviceSize as J, AppleSplashScreenName as K, AppleTouchStartupImageOptions as L, AppleSplashScreens as M, ResolvedAppleSplashScreens as N, AssetType as O, Preset as P, ResolvedAsset as Q, ResolvedAssetSize as R, Assets as S, ResolvedAssets as T, UserConfig as U, LogLevel as V, BuildOptions as W, ResolvedBuildOptions as X, HtmlLinkPreset as a, AssetSize as b, HtmlLinkType as i, HtmlLinkReturnType as j, HtmlIconLinkOptions as k, AppleSplahScreenHtmlLinkOptions as l, HeadLinkOptions as r, ResolvedConfig as s, AppleDeviceName as w, AppleSplashScreen as x }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.mts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..dde2d35749c50af0bb99cb25d613cace68bdad62 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.mts @@ -0,0 +1,502 @@ +import * as sharp from 'sharp'; +import { PngOptions, ResizeOptions } from 'sharp'; +import { LoadConfigSource, LoadConfigResult } from 'unconfig'; + +type HtmlLinkPreset = 'default' | '2023'; +interface HtmlLink { + id: string; + rel: 'apple-touch-startup-image' | 'apple-touch-icon' | 'icon'; + href: string; +} +interface AppleSplashScreenLink extends HtmlLink { + media: string; +} +interface FaviconLink extends HtmlLink { + sizes?: string; + type?: string; +} +type HtmlLinkType = 'string' | 'link'; +type HtmlLinkReturnType = T extends 'string' ? string : T extends 'link' ? R : never; +interface HtmlIconLinkOptions { + name: string; + /** + * Required only for non SVG favicon + */ + size?: AssetSize; + xhtml?: boolean; + basePath?: string; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +interface AppleSplahScreenHtmlLinkOptions { + size: AppleDeviceSize; + landscape: boolean; + addMediaScreen: boolean; + xhtml?: boolean; + name?: AppleSplashScreenName; + basePath?: string; + dark?: boolean; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +declare function createFaviconHtmlLink(format: Format, preset: HtmlLinkPreset, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleTouchIconHtmlLink(format: Format, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleSplashScreenHtmlLink(format: Format, options: AppleSplahScreenHtmlLinkOptions): HtmlLinkReturnType; + +declare const defaultResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultDarkResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultPngCompressionOptions: PngOptions; +declare const defaultPngOptions: Record; +declare function createResizeOptions(dark: boolean, options: ResizeOptions): { + width?: number | undefined; + height?: number | undefined; + fit: keyof sharp.FitEnum; + position?: number | string | undefined; + background: sharp.Color; + kernel?: keyof sharp.KernelEnum | undefined; + withoutEnlargement?: boolean | undefined; + withoutReduction?: boolean | undefined; + fastShrinkOnLoad?: boolean | undefined; +}; +declare function createPngCompressionOptions(options: PngOptions): { + progressive?: boolean | undefined; + compressionLevel?: number | undefined; + adaptiveFiltering?: boolean | undefined; + quality?: number | undefined; + effort?: number | undefined; + palette?: boolean | undefined; + colours?: number | undefined; + colors?: number | undefined; + dither?: number | undefined; + force?: boolean | undefined; +}; + +interface Preset extends Assets { +} + +/** + * Minimal preset. + * + * @deprecated use `minimal-2023` instead + * @see https://www.leereamsnyder.com/favicons-in-2021 + */ +declare const minimalPreset: Preset; + +/** + * Minimal preset for 2023. + * + * @see https://dev.to/masakudamatsu/favicon-nightmare-how-to-maintain-sanity-3al7 + */ +declare const minimal2023Preset: Preset; + +type AppleDeviceName = 'iPad Pro 12.9"' | 'iPad Pro 11"' | 'iPad Pro 10.5"' | 'iPad Pro 9.7"' | 'iPad Air 13"' | 'iPad Air 11"' | 'iPad Air 10.9"' | 'iPad Air 10.5"' | 'iPad Air 9.7"' | 'iPad 11"' | 'iPad 10.2"' | 'iPad 9.7"' | 'iPad mini 8.3"' | 'iPad mini 7.9"' | 'iPhone 16 Pro Max' | 'iPhone 16 Pro' | 'iPhone 16 Plus' | 'iPhone 16' | 'iPhone 16e' | 'iPhone 15 Pro Max' | 'iPhone 15 Pro' | 'iPhone 15 Plus' | 'iPhone 15' | 'iPhone 14 Pro Max' | 'iPhone 14 Pro' | 'iPhone 14 Plus' | 'iPhone 14' | 'iPhone 13 Pro Max' | 'iPhone 13 Pro' | 'iPhone 13' | 'iPhone 13 mini' | 'iPhone 12 Pro Max' | 'iPhone 12 Pro' | 'iPhone 12' | 'iPhone 12 mini' | 'iPhone 11 Pro Max' | 'iPhone 11 Pro' | 'iPhone 11' | 'iPhone XS Max' | 'iPhone XS' | 'iPhone XR' | 'iPhone X' | 'iPhone 8 Plus' | 'iPhone 8' | 'iPhone 7 Plus' | 'iPhone 7' | 'iPhone 6s Plus' | 'iPhone 6s' | 'iPhone 6 Plus' | 'iPhone 6' | 'iPhone SE 4.7"' | 'iPhone SE 4"' | 'iPod touch 5th generation and later'; +interface AppleSplashScreen extends Record { +} +/** + * Apple device names and resolutions. + * @see https://developer.apple.com/design/human-interface-guidelines/layout#iOS-iPadOS-device-screen-dimensions + */ +declare const appleSplashScreenSizes: AppleSplashScreen; +declare function defaultSplashScreenName(landscape: boolean, size: AppleDeviceSize, dark?: boolean): string; +declare const AllAppleDeviceNames: AppleDeviceName[]; +declare function createAppleSplashScreens(options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; +}; +declare function combinePresetAndAppleSplashScreens(preset: Preset, options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + appleSplashScreens: { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; + }; + png?: PngOptions; + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + transparent: Asset; + maskable: Asset; + apple: Asset; +}; + +declare function toResolvedSize(size: AssetSize): { + original: AssetSize; + width: number; + height: number; +}; +declare function toResolvedAsset(type: AssetType, asset: Asset): { + sizes: { + original: AssetSize; + width: number; + height: number; + }[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + favicons?: Favicon[]; +}; +declare function defaultAssetName(type: AssetType, size: ResolvedAssetSize): string; +declare function sameAssetSize(a: AssetSize, b: ResolvedAssetSize): boolean; +declare function cloneResolvedAssetsSizes({ png, assetName, assets }: ResolvedAssets): { + assets: { + transparent: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + maskable: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + apple: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + }; + png: sharp.PngOptions; + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +}; +declare function cloneResolvedAssetSizes({ sizes, ...asset }: ResolvedAsset): { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; +}; + +/** + * Built-in presets. + * - `minimal-2023`: Only generate the bare minimum assets. + * - `minimal`: Only generate the bare minimum assets (deprecated). + * - `android`: Generate assets for Android. + * - `windows`: Generate assets for Windows. + * - `ios`: Generate assets for iOS. + * - `all`: `android`, `windows` and `ios` presets combined. + */ +type BuiltInPreset = 'minimal' | 'minimal-2023' | 'android' | 'windows' | 'ios' | 'all'; +interface HeadLinkOptions { + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * The preset to use. + * + * If using the built-in presets from CLI (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + preset?: HtmlLinkPreset; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName?: (name: string) => string; + /** + * Generate an id when generating the html head links. + * + * @default false + */ + xhtml?: boolean; + /** + * Include the id when generating the html head links. + * + * @default false + */ + includeId?: boolean; +} +interface UserConfig { + /** + * Project root directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default process.cwd() + */ + root?: string; + /** + * Path to the config file. + * + * Default resolving to `pwa-assets.config.[js|mjs|cjs]` + * + * Setting to `false` will disable config resolving. + */ + config?: string | false; + /** + * Override assets? + * + * @default true + */ + overrideAssets?: boolean; + /** + * Log level. + * + * @default 'info' + */ + logLevel?: LogLevel; + /** + * Path relative to `root` where to find the images to use for generating PWA assets. + * + * PWA Assets will be generated in the same directory. + */ + images?: string | string[]; + /** + * Preset to use. + * + * @default 'minimal' + */ + preset?: BuiltInPreset | Preset; + /** + * Options for generating the html head links for `apple-touch-icon` and favicons. + */ + headLinkOptions?: HeadLinkOptions; + /** + * Show the PWA web manifest icons' entry. + * + * @default true + */ + manifestIconsEntry?: boolean; +} +interface ResolvedConfig extends Required> { + preset: Preset; +} +declare function defineConfig(config: UserConfig): UserConfig; +declare function loadConfig(cwd?: string, configOrPath?: string | U, extraConfigSources?: LoadConfigSource[], defaults?: UserConfig): Promise>; + +/** + * Icon size. + */ +type AssetSize = number | { + width: number; + height: number; +}; +/** + * Icon size with resolved width and height. + */ +interface ResolvedAssetSize { + original: AssetSize; + width: number; + height: number; +} +/** + * Favicon size and name. + */ +type Favicon = [size: AssetSize, name: string]; +interface Asset { + sizes: AssetSize[]; + padding?: number; + resizeOptions?: ResizeOptions; + favicons?: Favicon[]; +} +interface AppleDeviceSize { + width: number; + height: number; + scaleFactor: number; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; +} +type AppleSplashScreenName = (landscape: boolean, size: AppleDeviceSize, dark?: boolean) => string; +interface AppleTouchStartupImageOptions { + /** + * Show the html head links? + * + * @default true + */ + log?: boolean; + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * Add media screen to the `apple-touch-startup-image` rel link? + * + * @default true + */ + addMediaScreen?: boolean; + /** + * Using XHTML? + * + * @default false + */ + xhtml?: boolean; +} +interface AppleSplashScreens { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + sizes: AppleDeviceSize[]; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * Global png options. + * + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; + /** + * Options to generate the html head links. + */ + linkMediaOptions?: AppleTouchStartupImageOptions; + /** + * Customize the splash screen name. + * + * @param landscape Is the splash screen landscape? + * @param size The splash screen size. + * @param dark Is the splash screen dark? + * @returns The splash screen name. + * + * @default (landscape, size, dark?: boolean) => `apple-splash-${landscape ? 'landscape' : 'portrait'}-${typeof dark === 'boolean' ? (dark ? 'dark-' : 'light-') : ''}${size.width}x${size.height}.png` + */ + name?: AppleSplashScreenName; +} +interface ResolvedAppleSplashScreens { + darkImageResolver?: (imageName: string) => Promise; + padding: number; + sizes: AppleDeviceSize[]; + linkMediaOptions: Required; + name: AppleSplashScreenName; + png: PngOptions; +} +type AssetType = 'transparent' | 'maskable' | 'apple'; +interface ResolvedAsset extends Required> { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; +} +interface Assets extends Record { + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + /** + * Splash screens. + */ + appleSplashScreens?: AppleSplashScreens; +} +interface ResolvedAssets { + assets: Record; + png: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +} +type LogLevel = 'info' | 'warn' | 'silent'; +interface BuildOptions { + root: string; + logLevel?: LogLevel; + overrideAssets?: boolean; + headLinkOptions: Required; +} +interface ResolvedBuildOptions extends Required { +} + +export { cloneResolvedAssetsSizes as $, AllAppleDeviceNames as C, createAppleSplashScreens as D, combinePresetAndAppleSplashScreens as E, toResolvedSize as Y, toResolvedAsset as Z, sameAssetSize as _, cloneResolvedAssetSizes as a0, defaultDarkResizeOptions as c, defaultResizeOptions as d, defaultPngCompressionOptions as e, defaultPngOptions as f, createResizeOptions as g, createPngCompressionOptions as h, createFaviconHtmlLink as m, createAppleTouchIconHtmlLink as n, createAppleSplashScreenHtmlLink as o, minimalPreset as p, minimal2023Preset as q, defineConfig as t, loadConfig as u, defaultAssetName as v, appleSplashScreenSizes as y, defaultSplashScreenName as z }; +export type { AppleSplashScreenLink as A, BuiltInPreset as B, FaviconLink as F, Favicon as G, HtmlLink as H, Asset as I, AppleDeviceSize as J, AppleSplashScreenName as K, AppleTouchStartupImageOptions as L, AppleSplashScreens as M, ResolvedAppleSplashScreens as N, AssetType as O, Preset as P, ResolvedAsset as Q, ResolvedAssetSize as R, Assets as S, ResolvedAssets as T, UserConfig as U, LogLevel as V, BuildOptions as W, ResolvedBuildOptions as X, HtmlLinkPreset as a, AssetSize as b, HtmlLinkType as i, HtmlLinkReturnType as j, HtmlIconLinkOptions as k, AppleSplahScreenHtmlLinkOptions as l, HeadLinkOptions as r, ResolvedConfig as s, AppleDeviceName as w, AppleSplashScreen as x }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.ts b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..dde2d35749c50af0bb99cb25d613cace68bdad62 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/dist/shared/assets-generator.DnoqiTld.d.ts @@ -0,0 +1,502 @@ +import * as sharp from 'sharp'; +import { PngOptions, ResizeOptions } from 'sharp'; +import { LoadConfigSource, LoadConfigResult } from 'unconfig'; + +type HtmlLinkPreset = 'default' | '2023'; +interface HtmlLink { + id: string; + rel: 'apple-touch-startup-image' | 'apple-touch-icon' | 'icon'; + href: string; +} +interface AppleSplashScreenLink extends HtmlLink { + media: string; +} +interface FaviconLink extends HtmlLink { + sizes?: string; + type?: string; +} +type HtmlLinkType = 'string' | 'link'; +type HtmlLinkReturnType = T extends 'string' ? string : T extends 'link' ? R : never; +interface HtmlIconLinkOptions { + name: string; + /** + * Required only for non SVG favicon + */ + size?: AssetSize; + xhtml?: boolean; + basePath?: string; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +interface AppleSplahScreenHtmlLinkOptions { + size: AppleDeviceSize; + landscape: boolean; + addMediaScreen: boolean; + xhtml?: boolean; + name?: AppleSplashScreenName; + basePath?: string; + dark?: boolean; + /** + * Render the id attribute when using string format? + * + * The id will always be present in object notation. + * + * @default false + */ + includeId?: boolean; +} +declare function createFaviconHtmlLink(format: Format, preset: HtmlLinkPreset, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleTouchIconHtmlLink(format: Format, icon: HtmlIconLinkOptions): HtmlLinkReturnType; +declare function createAppleSplashScreenHtmlLink(format: Format, options: AppleSplahScreenHtmlLinkOptions): HtmlLinkReturnType; + +declare const defaultResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultDarkResizeOptions: { + fit: "contain"; + background: string; +}; +declare const defaultPngCompressionOptions: PngOptions; +declare const defaultPngOptions: Record; +declare function createResizeOptions(dark: boolean, options: ResizeOptions): { + width?: number | undefined; + height?: number | undefined; + fit: keyof sharp.FitEnum; + position?: number | string | undefined; + background: sharp.Color; + kernel?: keyof sharp.KernelEnum | undefined; + withoutEnlargement?: boolean | undefined; + withoutReduction?: boolean | undefined; + fastShrinkOnLoad?: boolean | undefined; +}; +declare function createPngCompressionOptions(options: PngOptions): { + progressive?: boolean | undefined; + compressionLevel?: number | undefined; + adaptiveFiltering?: boolean | undefined; + quality?: number | undefined; + effort?: number | undefined; + palette?: boolean | undefined; + colours?: number | undefined; + colors?: number | undefined; + dither?: number | undefined; + force?: boolean | undefined; +}; + +interface Preset extends Assets { +} + +/** + * Minimal preset. + * + * @deprecated use `minimal-2023` instead + * @see https://www.leereamsnyder.com/favicons-in-2021 + */ +declare const minimalPreset: Preset; + +/** + * Minimal preset for 2023. + * + * @see https://dev.to/masakudamatsu/favicon-nightmare-how-to-maintain-sanity-3al7 + */ +declare const minimal2023Preset: Preset; + +type AppleDeviceName = 'iPad Pro 12.9"' | 'iPad Pro 11"' | 'iPad Pro 10.5"' | 'iPad Pro 9.7"' | 'iPad Air 13"' | 'iPad Air 11"' | 'iPad Air 10.9"' | 'iPad Air 10.5"' | 'iPad Air 9.7"' | 'iPad 11"' | 'iPad 10.2"' | 'iPad 9.7"' | 'iPad mini 8.3"' | 'iPad mini 7.9"' | 'iPhone 16 Pro Max' | 'iPhone 16 Pro' | 'iPhone 16 Plus' | 'iPhone 16' | 'iPhone 16e' | 'iPhone 15 Pro Max' | 'iPhone 15 Pro' | 'iPhone 15 Plus' | 'iPhone 15' | 'iPhone 14 Pro Max' | 'iPhone 14 Pro' | 'iPhone 14 Plus' | 'iPhone 14' | 'iPhone 13 Pro Max' | 'iPhone 13 Pro' | 'iPhone 13' | 'iPhone 13 mini' | 'iPhone 12 Pro Max' | 'iPhone 12 Pro' | 'iPhone 12' | 'iPhone 12 mini' | 'iPhone 11 Pro Max' | 'iPhone 11 Pro' | 'iPhone 11' | 'iPhone XS Max' | 'iPhone XS' | 'iPhone XR' | 'iPhone X' | 'iPhone 8 Plus' | 'iPhone 8' | 'iPhone 7 Plus' | 'iPhone 7' | 'iPhone 6s Plus' | 'iPhone 6s' | 'iPhone 6 Plus' | 'iPhone 6' | 'iPhone SE 4.7"' | 'iPhone SE 4"' | 'iPod touch 5th generation and later'; +interface AppleSplashScreen extends Record { +} +/** + * Apple device names and resolutions. + * @see https://developer.apple.com/design/human-interface-guidelines/layout#iOS-iPadOS-device-screen-dimensions + */ +declare const appleSplashScreenSizes: AppleSplashScreen; +declare function defaultSplashScreenName(landscape: boolean, size: AppleDeviceSize, dark?: boolean): string; +declare const AllAppleDeviceNames: AppleDeviceName[]; +declare function createAppleSplashScreens(options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; +}; +declare function combinePresetAndAppleSplashScreens(preset: Preset, options?: { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + padding?: number; + resizeOptions?: ResizeOptions; + darkResizeOptions?: ResizeOptions; + linkMediaOptions?: AppleTouchStartupImageOptions; + png?: PngOptions; + name?: AppleSplashScreenName; +}, devices?: AppleDeviceName[]): { + appleSplashScreens: { + darkImageResolver: ((imageName: string) => Promise) | undefined; + sizes: AppleDeviceSize[]; + padding: number | undefined; + resizeOptions: ResizeOptions | undefined; + darkResizeOptions: ResizeOptions | undefined; + linkMediaOptions: AppleTouchStartupImageOptions | undefined; + png: PngOptions | undefined; + name: AppleSplashScreenName | undefined; + }; + png?: PngOptions; + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + transparent: Asset; + maskable: Asset; + apple: Asset; +}; + +declare function toResolvedSize(size: AssetSize): { + original: AssetSize; + width: number; + height: number; +}; +declare function toResolvedAsset(type: AssetType, asset: Asset): { + sizes: { + original: AssetSize; + width: number; + height: number; + }[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + favicons?: Favicon[]; +}; +declare function defaultAssetName(type: AssetType, size: ResolvedAssetSize): string; +declare function sameAssetSize(a: AssetSize, b: ResolvedAssetSize): boolean; +declare function cloneResolvedAssetsSizes({ png, assetName, assets }: ResolvedAssets): { + assets: { + transparent: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + maskable: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + apple: { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; + }; + }; + png: sharp.PngOptions; + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +}; +declare function cloneResolvedAssetSizes({ sizes, ...asset }: ResolvedAsset): { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; + padding: number; + resizeOptions: sharp.ResizeOptions; +}; + +/** + * Built-in presets. + * - `minimal-2023`: Only generate the bare minimum assets. + * - `minimal`: Only generate the bare minimum assets (deprecated). + * - `android`: Generate assets for Android. + * - `windows`: Generate assets for Windows. + * - `ios`: Generate assets for iOS. + * - `all`: `android`, `windows` and `ios` presets combined. + */ +type BuiltInPreset = 'minimal' | 'minimal-2023' | 'android' | 'windows' | 'ios' | 'all'; +interface HeadLinkOptions { + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * The preset to use. + * + * If using the built-in presets from CLI (`minimal` or `minimal-2023`), this option will be ignored (will be set to `default` or `2023` for `minimal` and `minimal-2023` respectively). + * + * @default 'default' + */ + preset?: HtmlLinkPreset; + /** + * By default, the SVG favicon will use the SVG file name as the name. + * + * For example, if you provide `public/logo.svg` as the image source, the href in the link will be `logo.svg`. + * + * @param name The name of the SVG icons. + */ + resolveSvgName?: (name: string) => string; + /** + * Generate an id when generating the html head links. + * + * @default false + */ + xhtml?: boolean; + /** + * Include the id when generating the html head links. + * + * @default false + */ + includeId?: boolean; +} +interface UserConfig { + /** + * Project root directory. Can be an absolute path, or a path relative from + * the location of the config file itself. + * @default process.cwd() + */ + root?: string; + /** + * Path to the config file. + * + * Default resolving to `pwa-assets.config.[js|mjs|cjs]` + * + * Setting to `false` will disable config resolving. + */ + config?: string | false; + /** + * Override assets? + * + * @default true + */ + overrideAssets?: boolean; + /** + * Log level. + * + * @default 'info' + */ + logLevel?: LogLevel; + /** + * Path relative to `root` where to find the images to use for generating PWA assets. + * + * PWA Assets will be generated in the same directory. + */ + images?: string | string[]; + /** + * Preset to use. + * + * @default 'minimal' + */ + preset?: BuiltInPreset | Preset; + /** + * Options for generating the html head links for `apple-touch-icon` and favicons. + */ + headLinkOptions?: HeadLinkOptions; + /** + * Show the PWA web manifest icons' entry. + * + * @default true + */ + manifestIconsEntry?: boolean; +} +interface ResolvedConfig extends Required> { + preset: Preset; +} +declare function defineConfig(config: UserConfig): UserConfig; +declare function loadConfig(cwd?: string, configOrPath?: string | U, extraConfigSources?: LoadConfigSource[], defaults?: UserConfig): Promise>; + +/** + * Icon size. + */ +type AssetSize = number | { + width: number; + height: number; +}; +/** + * Icon size with resolved width and height. + */ +interface ResolvedAssetSize { + original: AssetSize; + width: number; + height: number; +} +/** + * Favicon size and name. + */ +type Favicon = [size: AssetSize, name: string]; +interface Asset { + sizes: AssetSize[]; + padding?: number; + resizeOptions?: ResizeOptions; + favicons?: Favicon[]; +} +interface AppleDeviceSize { + width: number; + height: number; + scaleFactor: number; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; +} +type AppleSplashScreenName = (landscape: boolean, size: AppleDeviceSize, dark?: boolean) => string; +interface AppleTouchStartupImageOptions { + /** + * Show the html head links? + * + * @default true + */ + log?: boolean; + /** + * Base path to generate the html head links. + * + * @default '/' + */ + basePath?: string; + /** + * Add media screen to the `apple-touch-startup-image` rel link? + * + * @default true + */ + addMediaScreen?: boolean; + /** + * Using XHTML? + * + * @default false + */ + xhtml?: boolean; +} +interface AppleSplashScreens { + /** + * The image to use for generating dark apple splash screens assets. + * + * By default, it will use the original image. + * + * @param imageName The image name configured in images. + */ + darkImageResolver?: (imageName: string) => Promise; + sizes: AppleDeviceSize[]; + /** + * The padding to add to the splash screen. + * + * @default 0.3 + */ + padding?: number; + /** + * Global png options. + * + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * Resize options: by default, `sharp` will use white background color. + */ + resizeOptions?: ResizeOptions; + /** + * Dark resize options. + * + * If you want to also add a dark splash screen, change the background color with this another option. + */ + darkResizeOptions?: ResizeOptions; + /** + * Options to generate the html head links. + */ + linkMediaOptions?: AppleTouchStartupImageOptions; + /** + * Customize the splash screen name. + * + * @param landscape Is the splash screen landscape? + * @param size The splash screen size. + * @param dark Is the splash screen dark? + * @returns The splash screen name. + * + * @default (landscape, size, dark?: boolean) => `apple-splash-${landscape ? 'landscape' : 'portrait'}-${typeof dark === 'boolean' ? (dark ? 'dark-' : 'light-') : ''}${size.width}x${size.height}.png` + */ + name?: AppleSplashScreenName; +} +interface ResolvedAppleSplashScreens { + darkImageResolver?: (imageName: string) => Promise; + padding: number; + sizes: AppleDeviceSize[]; + linkMediaOptions: Required; + name: AppleSplashScreenName; + png: PngOptions; +} +type AssetType = 'transparent' | 'maskable' | 'apple'; +interface ResolvedAsset extends Required> { + sizes: ResolvedAssetSize[]; + favicons?: Favicon[]; +} +interface Assets extends Record { + /** + * @default { compressionLevel: 9, quality: 60 } + */ + png?: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName?: (type: AssetType, size: ResolvedAssetSize) => string; + /** + * Splash screens. + */ + appleSplashScreens?: AppleSplashScreens; +} +interface ResolvedAssets { + assets: Record; + png: PngOptions; + /** + * @default `pwa-x.png`, `maskable-icon-x.png`, `apple-touch-icon-x.png` + */ + assetName: (type: AssetType, size: ResolvedAssetSize) => string; +} +type LogLevel = 'info' | 'warn' | 'silent'; +interface BuildOptions { + root: string; + logLevel?: LogLevel; + overrideAssets?: boolean; + headLinkOptions: Required; +} +interface ResolvedBuildOptions extends Required { +} + +export { cloneResolvedAssetsSizes as $, AllAppleDeviceNames as C, createAppleSplashScreens as D, combinePresetAndAppleSplashScreens as E, toResolvedSize as Y, toResolvedAsset as Z, sameAssetSize as _, cloneResolvedAssetSizes as a0, defaultDarkResizeOptions as c, defaultResizeOptions as d, defaultPngCompressionOptions as e, defaultPngOptions as f, createResizeOptions as g, createPngCompressionOptions as h, createFaviconHtmlLink as m, createAppleTouchIconHtmlLink as n, createAppleSplashScreenHtmlLink as o, minimalPreset as p, minimal2023Preset as q, defineConfig as t, loadConfig as u, defaultAssetName as v, appleSplashScreenSizes as y, defaultSplashScreenName as z }; +export type { AppleSplashScreenLink as A, BuiltInPreset as B, FaviconLink as F, Favicon as G, HtmlLink as H, Asset as I, AppleDeviceSize as J, AppleSplashScreenName as K, AppleTouchStartupImageOptions as L, AppleSplashScreens as M, ResolvedAppleSplashScreens as N, AssetType as O, Preset as P, ResolvedAsset as Q, ResolvedAssetSize as R, Assets as S, ResolvedAssets as T, UserConfig as U, LogLevel as V, BuildOptions as W, ResolvedBuildOptions as X, HtmlLinkPreset as a, AssetSize as b, HtmlLinkType as i, HtmlLinkReturnType as j, HtmlIconLinkOptions as k, AppleSplahScreenHtmlLinkOptions as l, HeadLinkOptions as r, ResolvedConfig as s, AppleDeviceName as w, AppleSplashScreen as x }; diff --git a/tools/ui/node_modules/@vite-pwa/assets-generator/package.json b/tools/ui/node_modules/@vite-pwa/assets-generator/package.json new file mode 100644 index 0000000000000000000000000000000000000000..96ff1574abafa68b08c659b81d124ddc279096d9 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/assets-generator/package.json @@ -0,0 +1,116 @@ +{ + "name": "@vite-pwa/assets-generator", + "type": "module", + "version": "1.0.2", + "description": "Zero-config PWA Assets Generator", + "author": "antfu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/vite-pwa/assets-generator#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vite-pwa/assets-generator.git" + }, + "bugs": "https://github.com/vite-pwa/assets-generator/issues", + "keywords": [ + "sharp", + "sharp-ico", + "pwa", + "pwa icons generator", + "pwa assets generator" + ], + "sideEffects": false, + "exports": { + ".": { + "import": "./dist/index.mjs", + "require": "./dist/index.cjs" + }, + "./config": { + "import": "./dist/config.mjs", + "require": "./dist/config.cjs" + }, + "./presets": { + "import": "./dist/presets.mjs", + "require": "./dist/presets.cjs" + }, + "./presets/minimal": { + "import": "./dist/presets/minimal.mjs", + "require": "./dist/presets/minimal.cjs" + }, + "./presets/minimal-2023": { + "import": "./dist/presets/minimal-2023.mjs", + "require": "./dist/presets/minimal-2023.cjs" + }, + "./api": { + "import": "./dist/api.mjs", + "require": "./dist/api.cjs" + }, + "./api/instructions": { + "import": "./dist/api/instructions.mjs", + "require": "./dist/api/instructions.cjs" + }, + "./api/generate-html-markup": { + "import": "./dist/api/generate-html-markup.mjs", + "require": "./dist/api/generate-html-markup.cjs" + }, + "./api/generate-manifest-icons-entry": { + "import": "./dist/api/generate-manifest-icons-entry.mjs", + "require": "./dist/api/generate-manifest-icons-entry.cjs" + }, + "./api/generate-assets": { + "import": "./dist/api/generate-assets.mjs", + "require": "./dist/api/generate-assets.cjs" + }, + "./package.json": "./package.json", + "./*": "./*" + }, + "main": "dist/index.cjs", + "module": "dist/index.mjs", + "types": "dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "./dist/*", + "./*" + ] + } + }, + "bin": { + "pwa-assets-generator": "./bin/pwa-assets-generator.mjs" + }, + "files": [ + "bin", + "dist" + ], + "engines": { + "node": ">=16.14.0" + }, + "dependencies": { + "cac": "^6.7.14", + "colorette": "^2.0.20", + "consola": "^3.4.2", + "sharp": "^0.33.5", + "sharp-ico": "^0.1.5", + "unconfig": "^7.3.1" + }, + "devDependencies": { + "@antfu/eslint-config": "^5.4.1", + "@antfu/ni": "^26.1.0", + "@types/debug": "^4.1.12", + "@types/node": "^18.17.15", + "bumpp": "^10.3.1", + "eslint": "^9.37.0", + "esno": "^4.8.0", + "typescript": "^5.8.2", + "unbuild": "^3.5.0", + "vitest": "^3.0.9" + }, + "scripts": { + "build": "unbuild && tsx scripts/postbuild.ts", + "lint": "eslint .", + "lint:fix": "nr lint --fix", + "release": "bumpp", + "run-playground": "pnpm -C playground run build", + "test": "vitest run" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/LICENSE b/tools/ui/node_modules/@vite-pwa/sveltekit/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..de8f285e30e90e4db56c1824d652f50ed7732ff1 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2022-PRESENT Anthony Fu + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/README.md b/tools/ui/node_modules/@vite-pwa/sveltekit/README.md new file mode 100644 index 0000000000000000000000000000000000000000..f34ae37cb7b46f19a0799714414af7f5cbf3296c --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/README.md @@ -0,0 +1,91 @@ +

+@vite-pwa/sveltekit - Zero-config PWA for SvelteKit
+Zero-config PWA Plugin for SvelteKit +

+ +

+ +NPM version + + + NPM Downloads + + + Docs & Guides + +
+ +GitHub stars + +

+ +
+ +

+ + + +

+ +## 🚀 Features + +- 📖 [**Documentation & guides**](https://vite-pwa-org.netlify.app/) +- 👌 **Zero-Config**: sensible built-in default configs for common use cases +- 🔩 **Extensible**: expose the full ability to customize the behavior of the plugin +- 🦾 **Type Strong**: written in [TypeScript](https://www.typescriptlang.org/) +- 🔌 **Offline Support**: generate service worker with offline support (via Workbox) +- ⚡ **Fully tree shakable**: auto inject Web App Manifest +- 💬 **Prompt for new content**: built-in support for Vanilla JavaScript, Vue 3, React, Svelte, SolidJS and Preact +- ⚙️ **Stale-while-revalidate**: automatic reload when new content is available +- ✨ **Static assets handling**: configure static assets for offline support +- 🐞 **Development Support**: debug your custom service worker logic as you develop your application +- 🛠️ **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) +- 💥 **PWA Assets Generator**: generate all the PWA assets from a single command and a single source image +- 🚀 **PWA Assets Integration**: serving, generating and injecting PWA Assets on the fly in your application + +## 📦 Install + +> From v0.3.0, `@vite-pwa/sveltekit` supports SvelteKit 2 (should also support SvelteKit 1). + +> From v0.2.0, `@vite-pwa/sveltekit` requires **SvelteKit 1.3.1 or above**. + +```bash +npm i @vite-pwa/sveltekit -D + +# yarn +yarn add @vite-pwa/sveltekit -D + +# pnpm +pnpm add @vite-pwa/sveltekit -D +``` + +## 🦄 Usage + +Add `SvelteKitPWA` plugin to `vite.config.js / vite.config.ts` and configure it: + +```ts +// vite.config.js / vite.config.ts +import { sveltekit } from '@sveltejs/kit/vite' +import { SvelteKitPWA } from '@vite-pwa/sveltekit' + +export default { + plugins: [ + sveltekit(), + SvelteKitPWA() + ] +} +``` + +Read the [📖 documentation](https://vite-pwa-org.netlify.app/frameworks/sveltekit) for a complete guide on how to configure and use +this plugin. + +## 👀 Full config + +Check out the type declaration [src/types.ts](./src/types.ts) and the following links for more details. + +- [Web app manifests](https://developer.mozilla.org/en-US/docs/Web/Manifest) +- [Workbox](https://developers.google.com/web/tools/workbox) + +## 📄 License + +[MIT](./LICENSE) License © 2022-PRESENT [Anthony Fu](https://github.com/antfu) diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/dist/chunks/log.mjs b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/chunks/log.mjs new file mode 100644 index 0000000000000000000000000000000000000000..e1fdd5e941f018604f943724d0f24af73a40dd8e --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/chunks/log.mjs @@ -0,0 +1,36 @@ +import { relative } from 'node:path'; +import { cyan, magenta, green, dim, yellow } from 'kolorist'; + +const version = "1.1.0"; + +function logWorkboxResult(strategy, viteOptions, buildResult) { + const { root, logLevel = "info" } = viteOptions; + if (logLevel === "silent") + return; + if (!buildResult) { + console.info([ + "", + `${cyan(`SvelteKit VitePWA v${version}`)}`, + `mode ${magenta(strategy)}` + ].join("\n")); + return; + } + const { count, size, filePaths, warnings } = buildResult; + if (logLevel === "info") { + console.info([ + "", + `${cyan(`SvelteKit VitePWA v${version}`)}`, + `mode ${magenta(strategy)}`, + `precache ${green(`${count} entries`)} ${dim(`(${(size / 1024).toFixed(2)} KiB)`)}`, + "files generated", + ...filePaths.map((p) => ` ${dim(relative(root, p))}`) + ].join("\n")); + } + warnings && warnings.length > 0 && console.warn(yellow([ + "warnings", + ...warnings.map((w) => ` ${w}`), + "" + ].join("\n"))); +} + +export { logWorkboxResult }; diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.mts b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.mts new file mode 100644 index 0000000000000000000000000000000000000000..9b87d93f65f29f79a814ff7f074c6470df9db64d --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.mts @@ -0,0 +1,77 @@ +import { Plugin } from 'vite'; +import { VitePWAOptions } from 'vite-plugin-pwa'; + +interface KitOptions { + /** + * The base path for your application: by default will use the Vite base. + * + * @deprecated since ^0.1.0 version, the plugin has SvelteKit ^1.0.0 as peer dependency, Vite's base is now properly configured. + * @default '/' + * @see https://kit.svelte.dev/docs/configuration#paths + */ + base?: string; + /** + * The static folder for your application. + * + * @default 'static' + * @see https://kit.svelte.dev/docs/configuration#files + */ + assets?: string; + /** + * @default '.svelte-kit' + * @see https://kit.svelte.dev/docs/configuration#outdir + */ + outDir?: string; + /** + * @see https://kit.svelte.dev/docs/adapter-static#options-fallback + */ + adapterFallback?: string; + /** + * Check your SvelteKit version, `trailingSlash` should be used in `+page[jt]s` files or `+layout.[jt]s. + * @default 'never' + */ + trailingSlash?: 'never' | 'always' | 'ignore'; + /** + * @default `_app` + * @see https://kit.svelte.dev/docs/configuration#appdir + */ + appDir?: string; + /** + * Include `${appDir}/version.json` in the service worker precache manifest? + * + * @default false + */ + includeVersionFile?: boolean; + /** + * Enable SPA mode for the application. + * + * By default, the plugin will use `adapterFallback` to include the entry in the service worker + * precache manifest. + * + * If you are using a logical name for the fallback, you can use the object syntax with the + * `fallbackMapping`. + * + * For example, if you're using `fallback: 'app.html'` in your static adapter and your server + * is redirecting to `/app`, you can configure `fallbackMapping: '/app'`. + * + * Since the static adapter will run after the PWA plugin generates the service worker, + * the PWA plugin doesn't have access to the adapter fallback page to include the revision in the + * service worker precache manifest. + * To generate the revision for the fallback page, the PWA plugin will use the + * `.svelte-kit/output/client/_app/version.json` file. + * You can configure the `fallbackRevision` to generate a custom revision. + * + * @see https://svelte.dev/docs/kit/single-page-apps + */ + spa?: true | { + fallbackMapping?: string; + fallbackRevision?: () => Promise; + }; +} +interface SvelteKitPWAOptions extends Partial { + kit?: KitOptions; +} + +declare function SvelteKitPWA(userOptions?: Partial): Plugin[]; + +export { type KitOptions, SvelteKitPWA, type SvelteKitPWAOptions }; diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.ts b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9b87d93f65f29f79a814ff7f074c6470df9db64d --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.d.ts @@ -0,0 +1,77 @@ +import { Plugin } from 'vite'; +import { VitePWAOptions } from 'vite-plugin-pwa'; + +interface KitOptions { + /** + * The base path for your application: by default will use the Vite base. + * + * @deprecated since ^0.1.0 version, the plugin has SvelteKit ^1.0.0 as peer dependency, Vite's base is now properly configured. + * @default '/' + * @see https://kit.svelte.dev/docs/configuration#paths + */ + base?: string; + /** + * The static folder for your application. + * + * @default 'static' + * @see https://kit.svelte.dev/docs/configuration#files + */ + assets?: string; + /** + * @default '.svelte-kit' + * @see https://kit.svelte.dev/docs/configuration#outdir + */ + outDir?: string; + /** + * @see https://kit.svelte.dev/docs/adapter-static#options-fallback + */ + adapterFallback?: string; + /** + * Check your SvelteKit version, `trailingSlash` should be used in `+page[jt]s` files or `+layout.[jt]s. + * @default 'never' + */ + trailingSlash?: 'never' | 'always' | 'ignore'; + /** + * @default `_app` + * @see https://kit.svelte.dev/docs/configuration#appdir + */ + appDir?: string; + /** + * Include `${appDir}/version.json` in the service worker precache manifest? + * + * @default false + */ + includeVersionFile?: boolean; + /** + * Enable SPA mode for the application. + * + * By default, the plugin will use `adapterFallback` to include the entry in the service worker + * precache manifest. + * + * If you are using a logical name for the fallback, you can use the object syntax with the + * `fallbackMapping`. + * + * For example, if you're using `fallback: 'app.html'` in your static adapter and your server + * is redirecting to `/app`, you can configure `fallbackMapping: '/app'`. + * + * Since the static adapter will run after the PWA plugin generates the service worker, + * the PWA plugin doesn't have access to the adapter fallback page to include the revision in the + * service worker precache manifest. + * To generate the revision for the fallback page, the PWA plugin will use the + * `.svelte-kit/output/client/_app/version.json` file. + * You can configure the `fallbackRevision` to generate a custom revision. + * + * @see https://svelte.dev/docs/kit/single-page-apps + */ + spa?: true | { + fallbackMapping?: string; + fallbackRevision?: () => Promise; + }; +} +interface SvelteKitPWAOptions extends Partial { + kit?: KitOptions; +} + +declare function SvelteKitPWA(userOptions?: Partial): Plugin[]; + +export { type KitOptions, SvelteKitPWA, type SvelteKitPWAOptions }; diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.mjs b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.mjs new file mode 100644 index 0000000000000000000000000000000000000000..db9a8436597cc862f63a1eb04b73d62c7386826f --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/dist/index.mjs @@ -0,0 +1,319 @@ +import { VitePWA } from 'vite-plugin-pwa'; +import { resolve, join } from 'node:path'; +import { mkdir, rm, readFile, writeFile, rename, lstat } from 'node:fs/promises'; +import { glob } from 'tinyglobby'; + +function configureSvelteKitOptions(kit, viteOptions, options) { + const { + base = viteOptions.base ?? "/", + adapterFallback, + outDir = `${viteOptions.root}/.svelte-kit`, + assets = "static" + } = kit; + if (typeof options.includeManifestIcons === "undefined") + options.includeManifestIcons = false; + let config; + if (options.strategies === "injectManifest") { + if (!options.srcDir) + options.srcDir = "src"; + if (!options.filename) + options.filename = "service-worker.js"; + options.injectManifest = options.injectManifest ?? {}; + config = options.injectManifest; + } else { + options.workbox = options.workbox ?? {}; + if (!("navigateFallback" in options.workbox)) + options.workbox.navigateFallback = adapterFallback ?? base; + config = options.workbox; + } + if (!config.globDirectory) + config.globDirectory = `${outDir}/output`; + let buildAssetsDir = kit.appDir ?? "_app/"; + if (buildAssetsDir[0] === "/") + buildAssetsDir = buildAssetsDir.slice(1); + if (buildAssetsDir[buildAssetsDir.length - 1] !== "/") + buildAssetsDir += "/"; + if (!config.modifyURLPrefix) { + config.globPatterns = buildGlobPatterns(config.globPatterns); + if (kit.includeVersionFile) + config.globPatterns.push(`client/${buildAssetsDir}version.json`); + } + config.globIgnores = buildGlobIgnores(config.globIgnores); + if (!("dontCacheBustURLsMatching" in config)) + config.dontCacheBustURLsMatching = new RegExp(`${buildAssetsDir}immutable/`); + if (!config.manifestTransforms) { + config.manifestTransforms = [createManifestTransform( + base, + config.globDirectory, + options.strategies === "injectManifest" ? void 0 : options.manifestFilename ?? "manifest.webmanifest", + kit + )]; + } + if (options.pwaAssets) { + options.pwaAssets.integration = { + baseUrl: base, + publicDir: resolve(viteOptions.root, assets), + outDir: resolve(outDir, "output/client") + }; + } +} +function createManifestTransform(base, outDir, webManifestName, options) { + return async (entries) => { + const defaultAdapterFallback = "prerendered/fallback.html"; + const suffix = options?.trailingSlash === "always" ? "/" : ""; + let adapterFallback = options?.adapterFallback; + let excludeFallback = false; + if (!adapterFallback) { + adapterFallback = defaultAdapterFallback; + excludeFallback = true; + } + const manifest = entries.filter(({ url }) => !(excludeFallback && url === defaultAdapterFallback)).map((e) => { + let url = e.url; + if (url.startsWith("client/")) + url = url.slice(7); + else if (url.startsWith("prerendered/dependencies/")) + url = url.slice(25); + else if (url.startsWith("prerendered/pages/")) + url = url.slice(18); + else if (url === defaultAdapterFallback) + url = adapterFallback; + if (url.endsWith(".html")) { + if (url.startsWith("/")) + url = url.slice(1); + if (url === "index.html") { + url = base; + } else { + const idx = url.lastIndexOf("/"); + if (idx > -1) { + if (url.endsWith("/index.html")) + url = `${url.slice(0, idx)}${suffix}`; + else + url = `${url.substring(0, url.lastIndexOf("."))}${suffix}`; + } else { + url = `${url.substring(0, url.lastIndexOf("."))}${suffix}`; + } + } + } + e.url = url; + return e; + }); + if (options?.spa && options?.adapterFallback) { + const name = typeof options.spa === "object" && options.spa.fallbackMapping ? options.spa.fallbackMapping : options.adapterFallback; + if (typeof options.spa === "object" && typeof options.spa.fallbackRevision === "function") { + manifest.push({ + url: name, + revision: await options.spa.fallbackRevision(), + size: 0 + }); + } else { + manifest.push(await buildManifestEntry( + name, + resolve(outDir, "client/_app/version.json") + )); + } + } + if (!webManifestName) + return { manifest }; + return { manifest: manifest.filter((e) => e.url !== webManifestName) }; + }; +} +function buildGlobPatterns(globPatterns) { + if (globPatterns) { + if (!globPatterns.some((g) => g.startsWith("prerendered/"))) + globPatterns.push("prerendered/**/*.{html,json}"); + if (!globPatterns.some((g) => g.startsWith("client/"))) + globPatterns.push("client/**/*.{js,css,ico,png,svg,webp,webmanifest}"); + if (!globPatterns.some((g) => g.includes("webmanifest"))) + globPatterns.push("client/*.webmanifest"); + return globPatterns; + } + return ["client/**/*.{js,css,ico,png,svg,webp,webmanifest}", "prerendered/**/*.{html,json}"]; +} +function buildGlobIgnores(globIgnores) { + if (globIgnores) { + if (!globIgnores.some((g) => g.startsWith("server/"))) + globIgnores.push("server/**"); + return globIgnores; + } + return ["server/**"]; +} +async function buildManifestEntry(url, path) { + const [crypto, createReadStream] = await Promise.all([ + import('node:crypto').then((m) => m.default), + import('node:fs').then((m) => m.createReadStream) + ]); + return new Promise((resolve2, reject) => { + const cHash = crypto.createHash("MD5"); + const stream = createReadStream(path); + stream.on("error", (err) => { + reject(err); + }); + stream.on("data", (chunk) => { + cHash.update(chunk); + }); + stream.on("end", () => { + return resolve2({ + url, + size: 0, + revision: `${cHash.digest("hex")}` + }); + }); + }); +} + +function SvelteKitPlugin(options, apiResolver) { + let viteConfig; + return { + name: "vite-plugin-pwa:sveltekit:build", + apply: "build", + enforce: "pre", + configResolved(config) { + viteConfig = config; + }, + async generateBundle(_, bundle) { + if (viteConfig.build.ssr) + return; + const api = apiResolver(); + if (!api) + return; + const assetsGenerator = await api.pwaAssetsGenerator(); + if (assetsGenerator) + assetsGenerator.injectManifestIcons(); + api.generateBundle(bundle, this); + }, + writeBundle: { + sequential: true, + enforce: "pre", + async handler() { + const api = apiResolver(); + if (!api || viteConfig.build.ssr) + return; + const assetsGenerator = await api.pwaAssetsGenerator(); + if (assetsGenerator) + await assetsGenerator.generate(); + } + }, + closeBundle: { + sequential: true, + enforce: "pre", + async handler() { + const api = apiResolver(); + if (api && !api.disabled && viteConfig.build.ssr) { + const webManifest = options.manifestFilename ?? "manifest.webmanifest"; + let swName = options.filename ?? "sw.js"; + const outDir = options.outDir ?? `${viteConfig.root}/.svelte-kit/output`; + const clientOutputDir = join(outDir, "client"); + await mkdir(clientOutputDir, { recursive: true }); + if (!options.strategies || options.strategies === "generateSW" || options.selfDestroying) { + let path; + let existsFile; + if (options.selfDestroying && options.strategies === "injectManifest") { + if (swName.endsWith(".ts")) + swName = swName.replace(/\.ts$/, ".js"); + path = join(clientOutputDir, "service-worker.js").replace("\\/g", "/"); + existsFile = await isFile(path); + if (existsFile) + await rm(path); + } + await api.generateSW(); + const serverOutputDir = join(outDir, "server"); + path = join(serverOutputDir, swName).replace(/\\/g, "/"); + existsFile = await isFile(path); + if (existsFile) { + const sw = await readFile(path, "utf-8"); + await writeFile( + join(clientOutputDir, swName).replace("\\/g", "/"), + sw, + "utf-8" + ); + await rm(path); + } + const result = await glob({ + patterns: ["workbox-*.js"], + cwd: serverOutputDir, + onlyFiles: true, + expandDirectories: false + }); + if (result && result.length > 0) { + path = join(serverOutputDir, result[0]).replace(/\\/g, "/"); + await writeFile( + join(clientOutputDir, result[0]).replace("\\/g", "/"), + await readFile(path, "utf-8"), + "utf-8" + ); + await rm(path); + } + path = join(serverOutputDir, webManifest).replace(/\\/g, "/"); + existsFile = await isFile(path); + if (existsFile) + await rm(path); + return; + } + if (swName.endsWith(".ts")) + swName = swName.replace(/\.ts$/, ".js"); + const injectionPoint = !options.injectManifest || !("injectionPoint" in options.injectManifest) || !!options.injectManifest.injectionPoint; + if (injectionPoint) { + const injectManifestOptions = { + globDirectory: outDir.replace(/\\/g, "/"), + ...options.injectManifest ?? {}, + swSrc: join(clientOutputDir, "service-worker.js").replace(/\\/g, "/"), + swDest: join(clientOutputDir, "service-worker.js").replace(/\\/g, "/") + }; + const [injectManifest, logWorkboxResult] = await Promise.all([ + import('workbox-build').then((m) => m.injectManifest), + import('./chunks/log.mjs').then((m) => m.logWorkboxResult) + ]); + const buildResult = await injectManifest(injectManifestOptions); + logWorkboxResult("injectManifest", viteConfig, buildResult); + if (swName !== "service-worker.js") { + await rename( + join(clientOutputDir, "service-worker.js").replace("\\/g", "/"), + join(clientOutputDir, swName).replace("\\/g", "/") + ); + } + } else { + const { logWorkboxResult } = await import('./chunks/log.mjs'); + logWorkboxResult("injectManifest", viteConfig); + if (swName !== "service-worker.js") { + await rename( + join(clientOutputDir, "service-worker.js").replace("\\/g", "/"), + join(clientOutputDir, swName).replace("\\/g", "/") + ); + } + } + } + } + } + }; +} +async function isFile(path) { + try { + const stats = await lstat(path); + return stats.isFile(); + } catch { + return false; + } +} + +function SvelteKitPWA(userOptions = {}) { + if (!userOptions.integration) + userOptions.integration = {}; + userOptions.integration.closeBundleOrder = "pre"; + userOptions.integration.configureOptions = (viteConfig, options) => configureSvelteKitOptions( + userOptions.kit ?? {}, + viteConfig, + options + ); + const plugins = VitePWA(userOptions); + const plugin = plugins.find((p) => p && typeof p === "object" && "name" in p && p.name === "vite-plugin-pwa"); + const resolveVitePluginPWAAPI = () => { + return plugin?.api; + }; + return [ + // remove the build plugin: we're using a custom one + ...plugins.filter((p) => p && typeof p === "object" && "name" in p && p.name !== "vite-plugin-pwa:build"), + SvelteKitPlugin(userOptions, resolveVitePluginPWAAPI) + ]; +} + +export { SvelteKitPWA }; diff --git a/tools/ui/node_modules/@vite-pwa/sveltekit/package.json b/tools/ui/node_modules/@vite-pwa/sveltekit/package.json new file mode 100644 index 0000000000000000000000000000000000000000..c6214fd1f130f9e8a258e17cbf0bb3c8af0ca089 --- /dev/null +++ b/tools/ui/node_modules/@vite-pwa/sveltekit/package.json @@ -0,0 +1,77 @@ +{ + "name": "@vite-pwa/sveltekit", + "type": "module", + "version": "1.1.0", + "description": "Zero-config PWA for SvelteKit", + "author": "antfu ", + "license": "MIT", + "funding": "https://github.com/sponsors/antfu", + "homepage": "https://github.com/vite-pwa/sveltekit#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/vite-pwa/sveltekit.git" + }, + "bugs": "https://github.com/vite-pwa/sveltekit/issues", + "keywords": [ + "sveltekit", + "workbox", + "pwa", + "vite", + "vite-plugin" + ], + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.mjs" + }, + "./package.json": "./package.json" + }, + "types": "dist/index.d.ts", + "typesVersions": { + "*": { + "*": [ + "./dist/index.d.ts" + ] + } + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=18.13" + }, + "peerDependencies": { + "@sveltejs/kit": "^1.3.1 || ^2.0.1", + "@vite-pwa/assets-generator": "^1.0.0" + }, + "peerDependenciesMeta": { + "@vite-pwa/assets-generator": { + "optional": true + } + }, + "dependencies": { + "kolorist": "^1.8.0", + "tinyglobby": "^0.2.9", + "vite-plugin-pwa": "^1.2.0" + }, + "devDependencies": { + "@antfu/eslint-config": "^4.11.0", + "@antfu/ni": "^0.23.2", + "@types/debug": "^4.1.8", + "@types/node": "^18.17.15", + "@typescript-eslint/eslint-plugin": "^6.13.2", + "bumpp": "^9.2.0", + "eslint": "^9.23.0", + "eslint-plugin-svelte": "^3.3.3", + "typescript": "^5.7.2", + "unbuild": "^3.2.0", + "vite": "^5.0.10" + }, + "scripts": { + "build": "unbuild", + "lint": "eslint .", + "lint:fix": "nr lint --fix", + "release": "bumpp", + "test": "pnpm run -C examples/sveltekit-ts test && pnpm run -C examples/sveltekit-ts-assets-generator test" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@vitest/browser-playwright/LICENSE b/tools/ui/node_modules/@vitest/browser-playwright/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/ui/node_modules/@vitest/browser-playwright/README.md b/tools/ui/node_modules/@vitest/browser-playwright/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a30006535d377cf5a9d05a965c6a4d3020805501 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/README.md @@ -0,0 +1,48 @@ +# @vitest/browser-playwright + +[![NPM version](https://img.shields.io/npm/v/@vitest/browser-playwright?color=a1b858&label=)](https://npmx.dev/package/@vitest/browser-playwright) + +Run your Vitest [browser tests](https://vitest.dev/guide/browser/) using [playwright](https://playwright.dev/docs/api/class-playwright) API. Note that Vitest does not use playwright as a test runner, but only as a browser provider. + +We recommend using this package if you are already using playwright in your project or if you do not have any E2E tests yet. + +## Installation + +Install the package with your favorite package manager: + +```sh +npm install -D @vitest/browser-playwright +# or +yarn add -D @vitest/browser-playwright +# or +pnpm add -D @vitest/browser-playwright +``` + +Then specify it in the `browser.provider` field of your Vitest configuration: + +```ts +// vitest.config.ts +import { defineConfig } from 'vitest/config' +import { playwright } from '@vitest/browser-playwright' + +export default defineConfig({ + test: { + browser: { + provider: playwright({ + // ...custom playwright options + }), + instances: [ + { browser: 'chromium' }, + ], + }, + }, +}) +``` + +Then run Vitest in the browser mode: + +```sh +npx vitest --browser +``` + +[GitHub](https://github.com/vitest-dev/vitest/tree/main/packages/browser-playwright) | [Documentation](https://vitest.dev/config/browser/playwright) diff --git a/tools/ui/node_modules/@vitest/browser-playwright/context.d.ts b/tools/ui/node_modules/@vitest/browser-playwright/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..a022f2f1045678107643964ff5a2e37de1d0fdc1 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/context.d.ts @@ -0,0 +1 @@ +export * from '@vitest/browser/context' diff --git a/tools/ui/node_modules/@vitest/browser-playwright/dist/index.d.ts b/tools/ui/node_modules/@vitest/browser-playwright/dist/index.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..01da2c3bd3d0c5d356c421737afbd5f08a1bc05b --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/dist/index.d.ts @@ -0,0 +1,124 @@ +import { CustomComparatorsRegistry } from '@vitest/browser'; +export { defineBrowserCommand } from '@vitest/browser'; +import { Page, Frame, FrameLocator, BrowserContext, CDPSession, Browser, LaunchOptions, ConnectOptions, BrowserContextOptions } from 'playwright'; +import { ScreenshotMatcherOptions, ScreenshotComparatorRegistry, Locator } from 'vitest/browser'; +import { BrowserProvider, BrowserModuleMocker, TestProject, CDPSession as CDPSession$1, BrowserProviderOption } from 'vitest/node'; + +declare const playwrightBrowsers: readonly ["firefox", "webkit", "chromium"]; +type PlaywrightBrowser = (typeof playwrightBrowsers)[number]; +interface PlaywrightProviderOptions { + /** + * The options passed down to [`playwright.connect`](https://playwright.dev/docs/api/class-browsertype#browser-type-launch) method. + * @see {@link https://playwright.dev/docs/api/class-browsertype#browser-type-launch} + */ + launchOptions?: Omit; + /** + * The options passed down to [`playwright.connect`](https://playwright.dev/docs/api/class-browsertype#browser-type-connect) method. + * + * This is used only if you connect remotely to the playwright instance via a WebSocket connection. + * @see {@link https://playwright.dev/docs/api/class-browsertype#browser-type-connect} + */ + connectOptions?: ConnectOptions & { + wsEndpoint: string; + }; + /** + * The options passed down to [`browser.newContext`](https://playwright.dev/docs/api/class-browser#browser-new-context) method. + * @see {@link https://playwright.dev/docs/api/class-browser#browser-new-context} + */ + contextOptions?: Omit; + /** + * The maximum time in milliseconds to wait for `userEvent` action to complete. + * @default 0 (no timeout) + */ + actionTimeout?: number; + /** + * Use a persistent context instead of a regular browser context. + * This allows browser state (cookies, localStorage, DevTools settings, etc.) to persist between test runs. + * When set to `true`, the user data is stored in `./node_modules/.cache/vitest-playwright-user-data`. + * When set to a string, the value is used as the path to the user data directory. + * + * Note: This option is ignored when running tests in parallel (e.g. headless with fileParallelism enabled) + * because persistent context cannot be shared across parallel sessions. + * @default false + * @see {@link https://playwright.dev/docs/api/class-browsertype#browser-type-launch-persistent-context} + */ + persistentContext?: boolean | string; +} +declare function playwright(options?: PlaywrightProviderOptions): BrowserProviderOption; +declare class PlaywrightBrowserProvider implements BrowserProvider { + private project; + private options; + name: "playwright"; + supportsParallelism: boolean; + browser: Browser | null; + persistentContext: BrowserContext | null; + contexts: Map; + pages: Map; + mocker: BrowserModuleMocker; + browserName: PlaywrightBrowser; + private browserPromise; + private closing; + tracingContexts: Set; + pendingTraces: Map; + initScripts: string[]; + constructor(project: TestProject, options: PlaywrightProviderOptions); + private onSIGTERM; + private openBrowser; + private createMocker; + private createContext; + private getContextOptions; + getPage(sessionId: string): Page; + getCommandsContext(sessionId: string): { + page: Page; + context: BrowserContext; + frame: () => Promise; + readonly iframe: FrameLocator; + }; + private openBrowserPage; + openPage(sessionId: string, url: string, options: { + parallel: boolean; + }): Promise; + private _throwIfClosing; + getCDPSession(sessionid: string): Promise; + close(): Promise; +} +declare module "vitest/node" { + interface BrowserCommandContext { + page: Page; + frame(): Promise; + iframe: FrameLocator; + context: BrowserContext; + } + interface _BrowserNames { + playwright: PlaywrightBrowser; + } + interface ToMatchScreenshotOptions extends Omit, CustomComparatorsRegistry {} + interface ToMatchScreenshotComparators extends ScreenshotComparatorRegistry {} +} +type PWHoverOptions = NonNullable[1]>; +type PWClickOptions = NonNullable[1]>; +type PWDoubleClickOptions = NonNullable[1]>; +type PWFillOptions = NonNullable[2]>; +type PWScreenshotOptions = NonNullable[0]>; +type PWSelectOptions = NonNullable[2]>; +type PWDragAndDropOptions = NonNullable[2]>; +type PWSetInputFiles = NonNullable[2]>; +type PWCDPSession = Pick; + +declare module "vitest/browser" { + interface UserEventHoverOptions extends PWHoverOptions {} + interface UserEventClickOptions extends PWClickOptions {} + interface UserEventDoubleClickOptions extends PWDoubleClickOptions {} + interface UserEventTripleClickOptions extends PWClickOptions {} + interface UserEventFillOptions extends PWFillOptions {} + interface UserEventSelectOptions extends PWSelectOptions {} + interface UserEventDragAndDropOptions extends PWDragAndDropOptions {} + interface UserEventUploadOptions extends PWSetInputFiles {} + interface ScreenshotOptions extends Omit { + mask?: ReadonlyArray | undefined; + } + interface CDPSession extends PWCDPSession {} +} + +export { PlaywrightBrowserProvider, playwright }; +export type { PWCDPSession as CDPSession, PlaywrightProviderOptions }; diff --git a/tools/ui/node_modules/@vitest/browser-playwright/dist/index.js b/tools/ui/node_modules/@vitest/browser-playwright/dist/index.js new file mode 100644 index 0000000000000000000000000000000000000000..c37e31e6e145ceffe47da38dfd53ca39fe73a359 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/dist/index.js @@ -0,0 +1,1235 @@ +import { asLocator, parseKeyDef, resolveScreenshotPath, assertBrowserApiWrite, assertBrowserFileAccess, defineBrowserProvider } from '@vitest/browser'; +export { defineBrowserCommand } from '@vitest/browser'; +import { createManualModuleSource } from '@vitest/mocker/node'; +import c from 'tinyrainbow'; +import { createDebugger, isCSSRequest } from 'vitest/node'; +import { mkdir, unlink } from 'node:fs/promises'; +import { fileURLToPath } from 'node:url'; + +const _DRIVE_LETTER_START_RE = /^[A-Za-z]:\//; +function normalizeWindowsPath(input = "") { + if (!input) { + return input; + } + return input.replace(/\\/g, "/").replace(_DRIVE_LETTER_START_RE, (r) => r.toUpperCase()); +} + +const _UNC_REGEX = /^[/\\]{2}/; +const _IS_ABSOLUTE_RE = /^[/\\](?![/\\])|^[/\\]{2}(?!\.)|^[A-Za-z]:[/\\]/; +const _DRIVE_LETTER_RE = /^[A-Za-z]:$/; +const _ROOT_FOLDER_RE = /^\/([A-Za-z]:)?$/; +const normalize = function(path) { + if (path.length === 0) { + return "."; + } + path = normalizeWindowsPath(path); + const isUNCPath = path.match(_UNC_REGEX); + const isPathAbsolute = isAbsolute(path); + const trailingSeparator = path[path.length - 1] === "/"; + path = normalizeString(path, !isPathAbsolute); + if (path.length === 0) { + if (isPathAbsolute) { + return "/"; + } + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) { + path += "/"; + } + if (_DRIVE_LETTER_RE.test(path)) { + path += "/"; + } + if (isUNCPath) { + if (!isPathAbsolute) { + return `//./${path}`; + } + return `//${path}`; + } + return isPathAbsolute && !isAbsolute(path) ? `/${path}` : path; +}; +function cwd() { + if (typeof process !== "undefined" && typeof process.cwd === "function") { + return process.cwd().replace(/\\/g, "/"); + } + return "/"; +} +const resolve = function(...arguments_) { + arguments_ = arguments_.map((argument) => normalizeWindowsPath(argument)); + let resolvedPath = ""; + let resolvedAbsolute = false; + for (let index = arguments_.length - 1; index >= -1 && !resolvedAbsolute; index--) { + const path = index >= 0 ? arguments_[index] : cwd(); + if (!path || path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = isAbsolute(path); + } + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute); + if (resolvedAbsolute && !isAbsolute(resolvedPath)) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : "."; +}; +function normalizeString(path, allowAboveRoot) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let char = null; + for (let index = 0; index <= path.length; ++index) { + if (index < path.length) { + char = path[index]; + } else if (char === "/") { + break; + } else { + char = "/"; + } + if (char === "/") { + if (lastSlash === index - 1 || dots === 1) ; else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res[res.length - 1] !== "." || res[res.length - 2] !== ".") { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf("/"); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf("/"); + } + lastSlash = index; + dots = 0; + continue; + } else if (res.length > 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = index; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? "/.." : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `/${path.slice(lastSlash + 1, index)}`; + } else { + res = path.slice(lastSlash + 1, index); + } + lastSegmentLength = index - lastSlash - 1; + } + lastSlash = index; + dots = 0; + } else if (char === "." && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} +const isAbsolute = function(p) { + return _IS_ABSOLUTE_RE.test(p); +}; +const relative = function(from, to) { + const _from = resolve(from).replace(_ROOT_FOLDER_RE, "$1").split("/"); + const _to = resolve(to).replace(_ROOT_FOLDER_RE, "$1").split("/"); + if (_to[0][1] === ":" && _from[0][1] === ":" && _from[0] !== _to[0]) { + return _to.join("/"); + } + const _fromCopy = [..._from]; + for (const segment of _fromCopy) { + if (_to[0] !== segment) { + break; + } + _from.shift(); + _to.shift(); + } + return [..._from.map(() => ".."), ..._to].join("/"); +}; +const dirname = function(p) { + const segments = normalizeWindowsPath(p).replace(/\/$/, "").split("/").slice(0, -1); + if (segments.length === 1 && _DRIVE_LETTER_RE.test(segments[0])) { + segments[0] += "/"; + } + return segments.join("/") || (isAbsolute(p) ? "/" : "."); +}; +const basename = function(p, extension) { + const segments = normalizeWindowsPath(p).split("/"); + let lastSegment = ""; + for (let i = segments.length - 1; i >= 0; i--) { + const val = segments[i]; + if (val) { + lastSegment = val; + break; + } + } + return extension && lastSegment.endsWith(extension) ? lastSegment.slice(0, -extension.length) : lastSegment; +}; + +// strip iframe locator part from the trace description e.g. +// - locator('[data-vitest="true"]').contentFrame().getByRole('button') +// ⇓ +// - getByRole('button') +function getDescribedLocator(context, selector) { + const locator = context.iframe.locator(selector); + return typeof locator.describe === "function" ? locator.describe(asLocator("javascript", selector)) : locator; +} + +const clear = async (context, selector) => { + const element = getDescribedLocator(context, selector); + await element.clear(); +}; + +const click = async (context, selector, options = {}) => { + await getDescribedLocator(context, selector).click(options); +}; +const dblClick = async (context, selector, options = {}) => { + await getDescribedLocator(context, selector).dblclick(options); +}; +const tripleClick = async (context, selector, options = {}) => { + await getDescribedLocator(context, selector).click({ + ...options, + clickCount: 3 + }); +}; + +const dragAndDrop = async (context, source, target, options_) => { + const frame = await context.frame(); + await frame.dragAndDrop(source, target, options_); +}; + +const fill = async (context, selector, text, options = {}) => { + const element = getDescribedLocator(context, selector); + await element.fill(text, options); +}; + +const hover = async (context, selector, options = {}) => { + await getDescribedLocator(context, selector).hover(options); +}; + +const keyboard = async (context, text, state) => { + const frame = await context.frame(); + await frame.evaluate(focusIframe); + const pressed = new Set(state.unreleased); + await keyboardImplementation(pressed, context.provider, context.sessionId, text, async () => { + const frame = await context.frame(); + await frame.evaluate(selectAll); + }, true); + return { unreleased: Array.from(pressed) }; +}; +const keyboardCleanup = async (context, state) => { + const { provider, sessionId } = context; + if (!state.unreleased) { + return; + } + const page = provider.getPage(sessionId); + for (const key of state.unreleased) { + await page.keyboard.up(key); + } +}; +// fallback to insertText for non US key +// https://github.com/microsoft/playwright/blob/50775698ae13642742f2a1e8983d1d686d7f192d/packages/playwright-core/src/server/input.ts#L95 +const VALID_KEYS = new Set([ + "Escape", + "F1", + "F2", + "F3", + "F4", + "F5", + "F6", + "F7", + "F8", + "F9", + "F10", + "F11", + "F12", + "Backquote", + "`", + "~", + "Digit1", + "1", + "!", + "Digit2", + "2", + "@", + "Digit3", + "3", + "#", + "Digit4", + "4", + "$", + "Digit5", + "5", + "%", + "Digit6", + "6", + "^", + "Digit7", + "7", + "&", + "Digit8", + "8", + "*", + "Digit9", + "9", + "(", + "Digit0", + "0", + ")", + "Minus", + "-", + "_", + "Equal", + "=", + "+", + "Backslash", + "\\", + "|", + "Backspace", + "Tab", + "KeyQ", + "q", + "Q", + "KeyW", + "w", + "W", + "KeyE", + "e", + "E", + "KeyR", + "r", + "R", + "KeyT", + "t", + "T", + "KeyY", + "y", + "Y", + "KeyU", + "u", + "U", + "KeyI", + "i", + "I", + "KeyO", + "o", + "O", + "KeyP", + "p", + "P", + "BracketLeft", + "[", + "{", + "BracketRight", + "]", + "}", + "CapsLock", + "KeyA", + "a", + "A", + "KeyS", + "s", + "S", + "KeyD", + "d", + "D", + "KeyF", + "f", + "F", + "KeyG", + "g", + "G", + "KeyH", + "h", + "H", + "KeyJ", + "j", + "J", + "KeyK", + "k", + "K", + "KeyL", + "l", + "L", + "Semicolon", + ";", + ":", + "Quote", + "'", + "\"", + "Enter", + "\n", + "\r", + "ShiftLeft", + "Shift", + "KeyZ", + "z", + "Z", + "KeyX", + "x", + "X", + "KeyC", + "c", + "C", + "KeyV", + "v", + "V", + "KeyB", + "b", + "B", + "KeyN", + "n", + "N", + "KeyM", + "m", + "M", + "Comma", + ",", + "<", + "Period", + ".", + ">", + "Slash", + "/", + "?", + "ShiftRight", + "ControlLeft", + "Control", + "MetaLeft", + "Meta", + "AltLeft", + "Alt", + "Space", + " ", + "AltRight", + "AltGraph", + "MetaRight", + "ContextMenu", + "ControlRight", + "PrintScreen", + "ScrollLock", + "Pause", + "PageUp", + "PageDown", + "Insert", + "Delete", + "Home", + "End", + "ArrowLeft", + "ArrowUp", + "ArrowRight", + "ArrowDown", + "NumLock", + "NumpadDivide", + "NumpadMultiply", + "NumpadSubtract", + "Numpad7", + "Numpad8", + "Numpad9", + "Numpad4", + "Numpad5", + "Numpad6", + "NumpadAdd", + "Numpad1", + "Numpad2", + "Numpad3", + "Numpad0", + "NumpadDecimal", + "NumpadEnter", + "ControlOrMeta" +]); +async function keyboardImplementation(pressed, provider, sessionId, text, selectAll, skipRelease) { + const page = provider.getPage(sessionId); + const actions = parseKeyDef(text); + for (const { releasePrevious, releaseSelf, repeat, keyDef } of actions) { + const key = keyDef.key; + // TODO: instead of calling down/up for each key, join non special + // together, and call `type` once for all non special keys, + // and then `press` for special keys + if (pressed.has(key)) { + if (VALID_KEYS.has(key)) { + await page.keyboard.up(key); + } + pressed.delete(key); + } + if (!releasePrevious) { + if (key === "selectall") { + await selectAll(); + continue; + } + for (let i = 1; i <= repeat; i++) { + if (VALID_KEYS.has(key)) { + await page.keyboard.down(key); + } else { + await page.keyboard.insertText(key); + } + } + if (releaseSelf) { + if (VALID_KEYS.has(key)) { + await page.keyboard.up(key); + } + } else { + pressed.add(key); + } + } + } + if (!skipRelease && pressed.size) { + for (const key of pressed) { + if (VALID_KEYS.has(key)) { + await page.keyboard.up(key); + } + } + } + return { pressed }; +} +function focusIframe() { + if (!document.activeElement || document.activeElement.ownerDocument !== document || document.activeElement === document.body) { + window.focus(); + } +} +function selectAll() { + const element = document.activeElement; + if (element && typeof element.select === "function") { + element.select(); + } +} + +/** +* Takes a screenshot using the provided browser context and returns a buffer and the expected screenshot path. +* +* **Note**: the returned `path` indicates where the screenshot *might* be found. +* It is not guaranteed to exist, especially if `options.save` is `false`. +* +* @throws {Error} If the function is not called within a test or if the browser provider does not support screenshots. +*/ +async function takeScreenshot(context, name, options) { + if (!context.testPath) { + throw new Error(`Cannot take a screenshot without a test path`); + } + const path = resolveScreenshotPath(context.testPath, name, context.project.config, options.path); + // playwright does not need a screenshot path if we don't intend to save it + let savePath; + if (options.save) { + savePath = normalize(path); + assertBrowserApiWrite(context.project, savePath); + assertBrowserFileAccess(context.project, savePath); + await mkdir(dirname(savePath), { recursive: true }); + } + const mask = options.mask?.map((selector) => getDescribedLocator(context, selector)); + if (options.element) { + const { element: selector, ...config } = options; + const element = getDescribedLocator(context, selector); + const buffer = await element.screenshot({ + ...config, + mask, + path: savePath + }); + return { + buffer, + path + }; + } + const buffer = await getDescribedLocator(context, "body").screenshot({ + ...options, + mask, + path: savePath + }); + return { + buffer, + path + }; +} + +const selectOptions = async (context, selector, userValues, options = {}) => { + const value = userValues; + const selectElement = getDescribedLocator(context, selector); + const values = await Promise.all(value.map(async (v) => { + if (typeof v === "string") { + return v; + } + const elementHandler = await getDescribedLocator(context, v.element).elementHandle(); + if (!elementHandler) { + throw new Error(`Element not found: ${v.element}`); + } + return elementHandler; + })); + await selectElement.selectOption(values, options); +}; + +const tab = async (context, options = {}) => { + const page = context.page; + await page.keyboard.press(options.shift === true ? "Shift+Tab" : "Tab"); +}; + +const startTracing = async ({ context, project, provider, sessionId }) => { + if (isPlaywrightProvider(provider)) { + if (provider.tracingContexts.has(sessionId)) { + return; + } + provider.tracingContexts.add(sessionId); + const options = project.config.browser.trace; + await context.tracing.start({ + screenshots: options.screenshots ?? true, + snapshots: options.snapshots ?? true, + sources: options.sources ?? true + }).catch(() => { + provider.tracingContexts.delete(sessionId); + }); + return; + } + throw new TypeError(`The ${provider.name} provider does not support tracing.`); +}; +const startChunkTrace = async (command, { name, title }) => { + const { provider, sessionId, testPath, context } = command; + if (!testPath) { + throw new Error(`stopChunkTrace cannot be called outside of the test file.`); + } + if (isPlaywrightProvider(provider)) { + if (!provider.tracingContexts.has(sessionId)) { + await startTracing(command); + } + const path = resolveTracesPath(command, name); + provider.pendingTraces.set(path, sessionId); + await context.tracing.startChunk({ + name, + title + }); + return; + } + throw new TypeError(`The ${provider.name} provider does not support tracing.`); +}; +const stopChunkTrace = async (context, { name }) => { + if (isPlaywrightProvider(context.provider)) { + const path = resolveTracesPath(context, name); + assertBrowserApiWrite(context.project, path); + assertBrowserFileAccess(context.project, path); + context.provider.pendingTraces.delete(path); + await context.context.tracing.stopChunk({ path }); + return { tracePath: path }; + } + throw new TypeError(`The ${context.provider.name} provider does not support tracing.`); +}; +const markTrace = async (context, payload) => { + if (isPlaywrightProvider(context.provider)) { + // skip if tracing is not active + // this is only safe guard and this isn't expected to happen since + // runner already checks if tracing is active before sending this command + if (!context.provider.tracingContexts.has(context.sessionId)) { + return; + } + const { name, selector, stack } = payload; + const location = parseLocation(context, stack); + // mark trace via group/groupEnd with dummy calls to force snapshot. + // https://github.com/microsoft/playwright/issues/39308 + await context.context.tracing.group(name, { location }); + try { + if (selector) { + const locator = getDescribedLocator(context, selector); + if (typeof locator._expect === "function") { + await locator._expect("to.be.attached", { + isNot: false, + timeout: 1 + }); + } else { + await context.page.evaluate(() => 0); + } + } else { + await context.page.evaluate(() => 0); + } + } catch {} + await context.context.tracing.groupEnd(); + return; + } + throw new TypeError(`The ${context.provider.name} provider does not support tracing.`); +}; +const groupTraceStart = async (context, payload) => { + if (isPlaywrightProvider(context.provider)) { + if (!context.provider.tracingContexts.has(context.sessionId)) { + return; + } + const { name, stack } = payload; + const location = parseLocation(context, stack); + await context.context.tracing.group(name, { location }); + return; + } + throw new TypeError(`The ${context.provider.name} provider does not support tracing.`); +}; +const groupTraceEnd = async (context) => { + if (isPlaywrightProvider(context.provider)) { + if (!context.provider.tracingContexts.has(context.sessionId)) { + return; + } + await context.context.tracing.groupEnd(); + return; + } + throw new TypeError(`The ${context.provider.name} provider does not support tracing.`); +}; +function parseLocation(context, stack) { + if (!stack) { + return; + } + const parsedStacks = context.project.browser.parseStacktrace(stack); + return parsedStacks[0]; +} +function resolveTracesPath({ testPath, project }, name) { + if (!testPath) { + throw new Error(`This command can only be called inside a test file.`); + } + const options = project.config.browser.trace; + const sanitizedName = `${project.name.replace(/[^a-z0-9]/gi, "-")}-${name}.trace.zip`; + if (options.tracesDir) { + return resolve(options.tracesDir, sanitizedName); + } + const dir = dirname(testPath); + const base = basename(testPath); + return resolve(dir, "__traces__", base, `${project.name.replace(/[^a-z0-9]/gi, "-")}-${name}.trace.zip`); +} +const deleteTracing = async (context, { traces }) => { + if (!context.testPath) { + throw new Error(`stopChunkTrace cannot be called outside of the test file.`); + } + if (isPlaywrightProvider(context.provider)) { + for (const trace of traces) { + assertBrowserApiWrite(context.project, trace); + assertBrowserFileAccess(context.project, trace); + } + return Promise.all(traces.map((trace) => unlink(trace).catch((err) => { + if (err.code === "ENOENT") { + // Ignore the error if the file doesn't exist + return; + } + // Re-throw other errors + throw err; + }))); + } + throw new Error(`provider ${context.provider.name} is not supported`); +}; +const annotateTraces = async ({ project }, { testId, traces }) => { + const vitest = project.vitest; + await Promise.all(traces.map((trace) => { + assertBrowserApiWrite(project, trace); + assertBrowserFileAccess(project, trace); + const entity = vitest.state.getReportedEntityById(testId); + const location = entity?.location ? { + file: entity.module.moduleId, + line: entity.location.line, + column: entity.location.column + } : undefined; + return vitest._testRun.recordArtifact(testId, { + type: "internal:annotation", + annotation: { + message: relative(project.config.root, trace), + type: "traces", + attachment: { + path: trace, + contentType: "application/octet-stream" + }, + location + }, + location + }); + })); +}; +function isPlaywrightProvider(provider) { + return provider.name === "playwright"; +} + +const type = async (context, selector, text, options = {}) => { + const { skipClick = false, skipAutoClose = false } = options; + const unreleased = new Set(Reflect.get(options, "unreleased") ?? []); + const element = getDescribedLocator(context, selector); + if (!skipClick) { + await element.focus(); + } + await keyboardImplementation(unreleased, context.provider, context.sessionId, text, () => element.selectText(), skipAutoClose); + return { unreleased: Array.from(unreleased) }; +}; + +const upload = async (context, selector, files, options) => { + const testPath = context.testPath; + if (!testPath) { + throw new Error(`Cannot upload files outside of a test`); + } + const root = context.project.config.root; + const playwrightFiles = files.map((file) => { + if (typeof file === "string") { + const filepath = resolve(root, file); + assertBrowserFileAccess(context.project, filepath); + return filepath; + } + return { + name: file.name, + mimeType: file.mimeType, + buffer: Buffer.from(file.base64, "base64") + }; + }); + await getDescribedLocator(context, selector).setInputFiles(playwrightFiles, options); +}; + +const wheel = async (context, selector, options) => { + await hover(context, selector); + const times = options.times ?? 1; + const deltaX = options.delta.x ?? 0; + const deltaY = options.delta.y ?? 0; + for (let count = 0; count < times; count += 1) { + await context.page.mouse.wheel(deltaX, deltaY); + } +}; + +var commands = { + __vitest_upload: upload, + __vitest_click: click, + __vitest_dblClick: dblClick, + __vitest_tripleClick: tripleClick, + __vitest_wheel: wheel, + __vitest_takeScreenshot: takeScreenshot, + __vitest_type: type, + __vitest_clear: clear, + __vitest_fill: fill, + __vitest_tab: tab, + __vitest_keyboard: keyboard, + __vitest_selectOptions: selectOptions, + __vitest_dragAndDrop: dragAndDrop, + __vitest_hover: hover, + __vitest_cleanup: keyboardCleanup, + __vitest_deleteTracing: deleteTracing, + __vitest_startChunkTrace: startChunkTrace, + __vitest_startTracing: startTracing, + __vitest_stopChunkTrace: stopChunkTrace, + __vitest_annotateTraces: annotateTraces, + __vitest_markTrace: markTrace, + __vitest_groupTraceStart: groupTraceStart, + __vitest_groupTraceEnd: groupTraceEnd +}; + +const pkgRoot = resolve(fileURLToPath(import.meta.url), "../.."); +const distRoot = resolve(pkgRoot, "dist"); + +const debug = createDebugger("vitest:browser:playwright"); +const playwrightBrowsers = [ + "firefox", + "webkit", + "chromium" +]; +// Enable intercepting of requests made by service workers - experimental API is only available in Chromium based browsers +// Requests from service workers are only available on context.route() https://playwright.dev/docs/service-workers-experimental +process.env.PW_EXPERIMENTAL_SERVICE_WORKER_NETWORK_EVENTS ??= "1"; +function playwright(options = {}) { + return defineBrowserProvider({ + name: "playwright", + supportedBrowser: playwrightBrowsers, + options, + providerFactory(project) { + return new PlaywrightBrowserProvider(project, options); + } + }); +} +class PlaywrightBrowserProvider { + name = "playwright"; + supportsParallelism = true; + browser = null; + persistentContext = null; + contexts = new Map(); + pages = new Map(); + mocker; + browserName; + browserPromise = null; + closing = false; + tracingContexts = new Set(); + pendingTraces = new Map(); + initScripts = [resolve(distRoot, "locators.js")]; + constructor(project, options) { + this.project = project; + this.options = options; + this.browserName = project.config.browser.name; + this.mocker = this.createMocker(); + for (const [name, command] of Object.entries(commands)) { + project.browser.registerCommand(name, command); + } + // make sure the traces are finished if the test hangs + process.on("SIGTERM", this.onSIGTERM); + } + onSIGTERM = () => { + if (!this.browser) { + return; + } + const promises = []; + for (const [trace, contextId] of this.pendingTraces.entries()) { + promises.push((() => { + const context = this.contexts.get(contextId); + return context?.tracing.stopChunk({ path: trace }); + })()); + } + return Promise.allSettled(promises); + }; + async openBrowser(openBrowserOptions) { + await this._throwIfClosing(); + if (this.browserPromise) { + debug?.("[%s] the browser is resolving, reusing the promise", this.browserName); + return this.browserPromise; + } + if (this.browser) { + debug?.("[%s] the browser is resolved, reusing it", this.browserName); + return this.browser; + } + this.browserPromise = (async () => { + const options = this.project.config.browser; + const playwright = await import('playwright'); + const launchOptions = { + ...this.options.launchOptions, + headless: options.headless + }; + if (typeof options.trace === "object" && options.trace.tracesDir) { + launchOptions.tracesDir = options.trace?.tracesDir; + } + const inspector = this.project.vitest.config.inspector; + if (inspector.enabled) { + // NodeJS equivalent defaults: https://nodejs.org/en/learn/getting-started/debugging#enable-inspector + const port = inspector.port || 9229; + const host = inspector.host || "127.0.0.1"; + launchOptions.args ||= []; + launchOptions.args.push(`--remote-debugging-port=${port}`); + if (host !== "localhost" && host !== "127.0.0.1" && host !== "::1") { + this.project.vitest.logger.warn(`Custom inspector host "${host}" will be ignored. Chromium only allows remote debugging on localhost.`); + } + this.project.vitest.logger.log(`Debugger listening on ws://127.0.0.1:${port}`); + } + // start Vitest UI maximized only on supported browsers + if (this.project.config.browser.ui && this.browserName === "chromium") { + if (!launchOptions.args) { + launchOptions.args = []; + } + if (!launchOptions.args.includes("--start-maximized") && !launchOptions.args.includes("--start-fullscreen")) { + launchOptions.args.push("--start-maximized"); + } + } + debug?.("[%s] initializing the browser with launch options: %O", this.browserName, launchOptions); + if (this.options.connectOptions) { + let { wsEndpoint, headers = {}, ...connectOptions } = this.options.connectOptions; + if ("x-playwright-launch-options" in headers) { + this.project.vitest.logger.warn(c.yellow("Detected \"x-playwright-launch-options\" in connectOptions.headers. Provider config launchOptions is ignored.")); + } else { + headers = { + ...headers, + "x-playwright-launch-options": JSON.stringify(launchOptions) + }; + } + this.browser = await playwright[this.browserName].connect(wsEndpoint, { + ...connectOptions, + headers + }); + this.browserPromise = null; + return this.browser; + } + let persistentContextOption = this.options.persistentContext; + if (persistentContextOption && openBrowserOptions.parallel) { + persistentContextOption = false; + this.project.vitest.logger.warn(c.yellow(`The persistentContext option is ignored because tests are running in parallel.`)); + } + if (persistentContextOption) { + const userDataDir = typeof this.options.persistentContext === "string" ? this.options.persistentContext : "./node_modules/.cache/vitest-playwright-user-data"; + // TODO: how to avoid default "about" page? + this.persistentContext = await playwright[this.browserName].launchPersistentContext(userDataDir, { + ...launchOptions, + ...this.getContextOptions() + }); + this.browser = this.persistentContext.browser(); + } else { + this.browser = await playwright[this.browserName].launch(launchOptions); + } + this.browserPromise = null; + return this.browser; + })(); + return this.browserPromise; + } + createMocker() { + const idPredicates = new Map(); + const sessionIds = new Map(); + function createPredicate(url) { + const moduleUrl = new URL(url, "http://localhost"); + const predicate = (url) => { + if (url.searchParams.has("_vitest_original")) { + return false; + } + // different modules, ignore request + if (url.pathname !== moduleUrl.pathname) { + return false; + } + url.searchParams.delete("t"); + url.searchParams.delete("v"); + url.searchParams.delete("import"); + // different search params, ignore request + if (url.searchParams.size !== moduleUrl.searchParams.size) { + return false; + } + // check that all search params are the same + for (const [param, value] of url.searchParams.entries()) { + if (moduleUrl.searchParams.get(param) !== value) { + return false; + } + } + return true; + }; + return { + url: moduleUrl.href, + predicate + }; + } + function predicateKey(sessionId, url) { + return `${sessionId}:${url}`; + } + return { + register: async (sessionId, module) => { + const page = this.getPage(sessionId); + const { url: moduleUrl, predicate } = createPredicate(module.url); + const key = predicateKey(sessionId, moduleUrl); + const existingPredicate = idPredicates.get(key); + if (existingPredicate) { + await page.context().unroute(existingPredicate); + } + const ids = sessionIds.get(sessionId) ?? new Set(); + ids.add(moduleUrl); + sessionIds.set(sessionId, ids); + idPredicates.set(key, predicate); + await page.context().route(predicate, async (route) => { + if (module.type === "manual") { + const exports$1 = Object.keys(await module.resolve()); + const body = createManualModuleSource(module.url, exports$1); + return route.fulfill({ + body, + headers: getHeaders(this.project.browser.vite.config) + }); + } + // webkit doesn't support redirect responses + // https://github.com/microsoft/playwright/issues/18318 + const isWebkit = this.browserName === "webkit"; + if (isWebkit) { + let url; + if (module.type === "redirect") { + const redirect = new URL(module.redirect); + url = redirect.href.slice(redirect.origin.length); + } else { + const request = new URL(route.request().url()); + request.searchParams.set("mock", module.type); + url = request.href.slice(request.origin.length); + } + const result = await this.project.browser.vite.transformRequest(url).catch(() => null); + if (!result) { + return route.continue(); + } + let content = result.code; + if (result.map && "version" in result.map && result.map.mappings) { + const type = isDirectCSSRequest(url) ? "css" : "js"; + content = getCodeWithSourcemap(type, content.toString(), result.map); + } + return route.fulfill({ + body: content, + headers: getHeaders(this.project.browser.vite.config) + }); + } + if (module.type === "redirect") { + return route.fulfill({ + status: 302, + headers: { Location: module.redirect } + }); + } else if (module.type === "automock" || module.type === "autospy") { + const url = new URL(route.request().url()); + url.searchParams.set("mock", module.type); + return route.fulfill({ + status: 302, + headers: { Location: url.href } + }); + } else ; + }); + }, + delete: async (sessionId, id) => { + const page = this.getPage(sessionId); + const key = predicateKey(sessionId, id); + const predicate = idPredicates.get(key); + if (predicate) { + await page.context().unroute(predicate).finally(() => idPredicates.delete(key)); + } + }, + clear: async (sessionId) => { + const page = this.getPage(sessionId); + const ids = sessionIds.get(sessionId) ?? new Set(); + const promises = [...ids].map((id) => { + const key = predicateKey(sessionId, id); + const predicate = idPredicates.get(key); + if (predicate) { + return page.context().unroute(predicate).finally(() => idPredicates.delete(key)); + } + return null; + }); + await Promise.all(promises).finally(() => sessionIds.delete(sessionId)); + } + }; + } + async createContext(sessionId, openBrowserOptions) { + await this._throwIfClosing(); + if (this.contexts.has(sessionId)) { + debug?.("[%s][%s] the context already exists, reusing it", sessionId, this.browserName); + return this.contexts.get(sessionId); + } + const browser = await this.openBrowser(openBrowserOptions); + await this._throwIfClosing(browser); + const actionTimeout = this.options.actionTimeout; + const options = this.getContextOptions(); + // TODO: investigate the consequences for Vitest 5 + // else { + // if UI is disabled, keep the iframe scale to 1 + // options.viewport ??= this.project.config.browser.viewport + // } + const context = this.persistentContext ?? await browser.newContext(options); + await this._throwIfClosing(context); + if (actionTimeout != null) { + context.setDefaultTimeout(actionTimeout); + } + debug?.("[%s][%s] the context is ready", sessionId, this.browserName); + this.contexts.set(sessionId, context); + return context; + } + getContextOptions() { + const contextOptions = this.options.contextOptions ?? {}; + const options = { + ...contextOptions, + ignoreHTTPSErrors: true + }; + if (this.project.config.browser.ui) { + options.viewport = null; + } + return options; + } + getPage(sessionId) { + const page = this.pages.get(sessionId); + if (!page) { + throw new Error(`Page "${sessionId}" not found in ${this.browserName} browser.`); + } + return page; + } + getCommandsContext(sessionId) { + const page = this.getPage(sessionId); + return { + page, + context: this.contexts.get(sessionId), + frame() { + return new Promise((resolve, reject) => { + const frame = page.frame("vitest-iframe"); + if (frame) { + return resolve(frame); + } + const timeout = setTimeout(() => { + const err = new Error(`Cannot find "vitest-iframe" on the page. This is a bug in Vitest, please report it.`); + reject(err); + }, 1e3).unref(); + page.on("frameattached", (frame) => { + clearTimeout(timeout); + resolve(frame); + }); + }); + }, + get iframe() { + return page.frameLocator("[data-vitest=\"true\"]"); + } + }; + } + async openBrowserPage(sessionId, options) { + await this._throwIfClosing(); + if (this.pages.has(sessionId)) { + debug?.("[%s][%s] the page already exists, closing the old one", sessionId, this.browserName); + const page = this.pages.get(sessionId); + await page.close(); + this.pages.delete(sessionId); + } + const context = await this.createContext(sessionId, options); + const page = await context.newPage(); + debug?.("[%s][%s] the page is ready", sessionId, this.browserName); + await this._throwIfClosing(page); + this.pages.set(sessionId, page); + if (process.env.VITEST_PW_DEBUG) { + page.on("requestfailed", (request) => { + console.error("[PW Error]", request.resourceType(), "request failed for", request.url(), "url:", request.failure()?.errorText); + }); + } + return page; + } + async openPage(sessionId, url, options) { + debug?.("[%s][%s] creating the browser page for %s", sessionId, this.browserName, url); + const browserPage = await this.openBrowserPage(sessionId, options); + debug?.("[%s][%s] browser page is created, opening %s", sessionId, this.browserName, url); + await browserPage.goto(url, { timeout: 0 }); + await this._throwIfClosing(browserPage); + } + async _throwIfClosing(disposable) { + if (this.closing) { + debug?.("[%s] provider was closed, cannot perform the action on %s", this.browserName, String(disposable)); + await disposable?.close(); + this.pages.clear(); + this.contexts.clear(); + this.browser = null; + this.browserPromise = null; + throw new Error(`[vitest] The provider was closed.`); + } + } + async getCDPSession(sessionid) { + const page = this.getPage(sessionid); + const cdp = await page.context().newCDPSession(page); + return { + send: cdp.send.bind(cdp), + on: cdp.on.bind(cdp), + off: cdp.off.bind(cdp), + once: cdp.once.bind(cdp) + }; + } + async close() { + process.off("SIGTERM", this.onSIGTERM); + debug?.("[%s] closing provider", this.browserName); + this.closing = true; + if (this.browserPromise) { + await this.browserPromise; + this.browserPromise = null; + } + const browser = this.browser; + this.browser = null; + await Promise.all([...this.pages.values()].map((p) => p.close())); + this.pages.clear(); + if (this.persistentContext) { + await this.persistentContext.close(); + } else { + await Promise.all([...this.contexts.values()].map((c) => c.close())); + } + this.contexts.clear(); + await browser?.close(); + debug?.("[%s] provider is closed", this.browserName); + } +} +function getHeaders(config) { + const headers = { "Content-Type": "application/javascript" }; + for (const name in config.server.headers) { + headers[name] = String(config.server.headers[name]); + } + return headers; +} +function getCodeWithSourcemap(type, code, map) { + if (type === "js") { + code += `\n//# sourceMappingURL=${genSourceMapUrl(map)}`; + } else if (type === "css") { + code += `\n/*# sourceMappingURL=${genSourceMapUrl(map)} */`; + } + return code; +} +function genSourceMapUrl(map) { + if (typeof map !== "string") { + map = JSON.stringify(map); + } + return `data:application/json;base64,${Buffer.from(map).toString("base64")}`; +} +const directRequestRE = /[?&]direct\b/; +function isDirectCSSRequest(request) { + return isCSSRequest(request) && directRequestRE.test(request); +} + +export { PlaywrightBrowserProvider, playwright }; diff --git a/tools/ui/node_modules/@vitest/browser-playwright/dist/locators.js b/tools/ui/node_modules/@vitest/browser-playwright/dist/locators.js new file mode 100644 index 0000000000000000000000000000000000000000..e879e285a9fd04f846ad29aaca69f59d5a58bb8a --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/dist/locators.js @@ -0,0 +1,114 @@ +import { selectorEngine, getByTitleSelector, getByTextSelector, getByPlaceholderSelector, getByAltTextSelector, getByTestIdSelector, getByRoleSelector, getByLabelSelector, Locator, processTimeoutOptions, getIframeScale } from '@vitest/browser/locators'; +import { page, server } from 'vitest/browser'; +import { __INTERNAL } from 'vitest/internal/browser'; + +class PlaywrightLocator extends Locator { + constructor(selector, _container) { + super(); + this.selector = selector; + this._container = _container; + } + click(options) { + return super.click(processTimeoutOptions(processClickOptions(options))); + } + dblClick(options) { + return super.dblClick(processTimeoutOptions(processClickOptions(options))); + } + tripleClick(options) { + return super.tripleClick(processTimeoutOptions(processClickOptions(options))); + } + selectOptions(value, options) { + return super.selectOptions(value, processTimeoutOptions(options)); + } + clear(options) { + return super.clear(processTimeoutOptions(options)); + } + hover(options) { + return super.hover(processTimeoutOptions(processHoverOptions(options))); + } + upload(files, options) { + return super.upload(files, processTimeoutOptions(options)); + } + fill(text, options) { + return super.fill(text, processTimeoutOptions(options)); + } + dropTo(target, options) { + return super.dropTo(target, processTimeoutOptions(processDragAndDropOptions(options))); + } + locator(selector) { + return new PlaywrightLocator(`${this.selector} >> ${selector}`, this._container); + } + elementLocator(element) { + return new PlaywrightLocator(selectorEngine.generateSelectorSimple(element), element); + } +} +page.extend({ + getByLabelText(text, options) { + return new PlaywrightLocator(getByLabelSelector(text, options)); + }, + getByRole(role, options) { + return new PlaywrightLocator(getByRoleSelector(role, options)); + }, + getByTestId(testId) { + return new PlaywrightLocator(getByTestIdSelector(server.config.browser.locators.testIdAttribute, testId)); + }, + getByAltText(text, options) { + return new PlaywrightLocator(getByAltTextSelector(text, options)); + }, + getByPlaceholder(text, options) { + return new PlaywrightLocator(getByPlaceholderSelector(text, options)); + }, + getByText(text, options) { + return new PlaywrightLocator(getByTextSelector(text, options)); + }, + getByTitle(title, options) { + return new PlaywrightLocator(getByTitleSelector(title, options)); + }, + elementLocator(element) { + return new PlaywrightLocator(selectorEngine.generateSelectorSimple(element), element); + }, + frameLocator(locator) { + return new PlaywrightLocator(`${locator.selector} >> internal:control=enter-frame`); + } +}); +__INTERNAL._createLocator = (selector) => new PlaywrightLocator(selector); +function processDragAndDropOptions(options) { + if (!options) { + return options; + } + if (options.sourcePosition) { + options.sourcePosition = processPlaywrightPosition(options.sourcePosition); + } + if (options.targetPosition) { + options.targetPosition = processPlaywrightPosition(options.targetPosition); + } + return options; +} +function processHoverOptions(options) { + if (!options) { + return options; + } + if (options.position) { + options.position = processPlaywrightPosition(options.position); + } + return options; +} +function processClickOptions(options) { + if (!options) { + return options; + } + if (options.position) { + options.position = processPlaywrightPosition(options.position); + } + return options; +} +function processPlaywrightPosition(position) { + const scale = getIframeScale(); + if (position.x != null) { + position.x *= scale; + } + if (position.y != null) { + position.y *= scale; + } + return position; +} diff --git a/tools/ui/node_modules/@vitest/browser-playwright/package.json b/tools/ui/node_modules/@vitest/browser-playwright/package.json new file mode 100644 index 0000000000000000000000000000000000000000..cd97163ff9245d162f02db3b05cd86818bd8c424 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser-playwright/package.json @@ -0,0 +1,65 @@ +{ + "name": "@vitest/browser-playwright", + "type": "module", + "version": "4.1.10", + "description": "Browser running for Vitest using playwright", + "license": "MIT", + "funding": "https://opencollective.com/vitest", + "homepage": "https://vitest.dev/config/browser/playwright", + "repository": { + "type": "git", + "url": "git+https://github.com/vitest-dev/vitest.git", + "directory": "packages/browser-playwright" + }, + "bugs": { + "url": "https://github.com/vitest-dev/vitest/issues" + }, + "keywords": [ + "browser", + "playwright", + "component", + "mocks", + "test", + "testing" + ], + "sideEffects": false, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "default": "./dist/index.js" + }, + "./context": { + "types": "./context.d.ts" + }, + "./package.json": "./package.json" + }, + "main": "./dist/index.js", + "module": "./dist/index.js", + "types": "./dist/index.d.ts", + "files": [ + "context.d.ts", + "dist" + ], + "peerDependencies": { + "playwright": "*", + "vitest": "4.1.10" + }, + "peerDependenciesMeta": { + "playwright": { + "optional": false + } + }, + "dependencies": { + "tinyrainbow": "^3.1.0", + "@vitest/browser": "4.1.10", + "@vitest/mocker": "4.1.10" + }, + "devDependencies": { + "playwright": "^1.61.0", + "vitest": "4.1.10" + }, + "scripts": { + "build": "premove dist && pnpm rollup -c", + "dev": "rollup -c --watch --watch.include 'src/**'" + } +} \ No newline at end of file diff --git a/tools/ui/node_modules/@vitest/browser/LICENSE b/tools/ui/node_modules/@vitest/browser/LICENSE new file mode 100644 index 0000000000000000000000000000000000000000..0e5771dddf4e96ebc77c349f53fc763b910e63c0 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-Present VoidZero Inc. and Vitest contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/tools/ui/node_modules/@vitest/browser/README.md b/tools/ui/node_modules/@vitest/browser/README.md new file mode 100644 index 0000000000000000000000000000000000000000..5edbbe2bd309ebe5a6720d5f15e407c569f2b088 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser/README.md @@ -0,0 +1,11 @@ +# @vitest/browser + +[![NPM version](https://img.shields.io/npm/v/@vitest/browser?color=a1b858&label=)](https://npmx.dev/package/@vitest/browser) + +This package exposes utilities to make your own browser provider. If you just need to run tests in the browser, consider installing one of these packages instead: + +- [@vitest/browser-playwright](https://npmx.dev/package/@vitest/browser-playwright) - run tests using [playwright](https://playwright.dev/) +- [@vitest/browser-webdriverio](https://npmx.dev/package/@vitest/browser-webdriverio) - run tests using [webdriverio](https://webdriver.io/) +- [@vitest/browser-preview](https://npmx.dev/package/@vitest/browser-preview) to see how your tests look like in a real browser. + +[GitHub](https://github.com/vitest-dev/vitest) | [Documentation](https://vitest.dev/guide/browser/) diff --git a/tools/ui/node_modules/@vitest/browser/aria-role.d.ts b/tools/ui/node_modules/@vitest/browser/aria-role.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..8818dd8b34b59e6d0a70440b608898a03c77f9b9 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser/aria-role.d.ts @@ -0,0 +1,96 @@ +type ARIAWidgetRole = + | "button" + | "checkbox" + | "gridcell" + | "link" + | "menuitem" + | "menuitemcheckbox" + | "menuitemradio" + | "option" + | "progressbar" + | "radio" + | "scrollbar" + | "searchbox" + | "slider" + | "spinbutton" + | "switch" + | "tab" + | "tabpanel" + | "textbox" + | "treeitem"; + +type ARIACompositeWidgetRole = + | "combobox" + | "grid" + | "listbox" + | "menu" + | "menubar" + | "radiogroup" + | "tablist" + | "tree" + | "treegrid"; + +type ARIADocumentStructureRole = + | "application" + | "article" + | "blockquote" + | "caption" + | "cell" + | "columnheader" + | "definition" + | "deletion" + | "directory" + | "document" + | "emphasis" + | "feed" + | "figure" + | "generic" + | "group" + | "heading" + | "img" + | "insertion" + | "list" + | "listitem" + | "math" + | "meter" + | "none" + | "note" + | "paragraph" + | "presentation" + | "row" + | "rowgroup" + | "rowheader" + | "separator" + | "strong" + | "subscript" + | "superscript" + | "table" + | "term" + | "time" + | "toolbar" + | "tooltip"; + +type ARIALandmarkRole = + | "banner" + | "complementary" + | "contentinfo" + | "form" + | "main" + | "navigation" + | "region" + | "search"; + +type ARIALiveRegionRole = "alert" | "log" | "marquee" | "status" | "timer"; + +type ARIAWindowRole = "alertdialog" | "dialog"; + +type ARIAUncategorizedRole = "code"; + +export type ARIARole = + | ARIAWidgetRole + | ARIACompositeWidgetRole + | ARIADocumentStructureRole + | ARIALandmarkRole + | ARIALiveRegionRole + | ARIAWindowRole + | ARIAUncategorizedRole; diff --git a/tools/ui/node_modules/@vitest/browser/context.d.ts b/tools/ui/node_modules/@vitest/browser/context.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..d9a2f8e766a7f54c8c8fc20a28442a43f10b6a34 --- /dev/null +++ b/tools/ui/node_modules/@vitest/browser/context.d.ts @@ -0,0 +1,942 @@ +import { SerializedConfig } from 'vitest' +import { StringifyOptions, CDPSession, BrowserCommands } from 'vitest/internal/browser' +import { ARIARole } from './aria-role.js' +import {} from './matchers.js' + +export type BufferEncoding = + | 'ascii' + | 'utf8' + | 'utf-8' + | 'utf16le' + | 'utf-16le' + | 'ucs2' + | 'ucs-2' + | 'base64' + | 'base64url' + | 'latin1' + | 'binary' + | 'hex' + +export { CDPSession }; + +export interface ScreenshotOptions extends SelectorOptions { + /** + * The HTML element to screenshot. + */ + element?: Element | Locator + /** + * Path relative to the current test file. + * @default `__screenshots__/${testFileName}/${testName}.png` + */ + path?: string + /** + * Will also return the base64 encoded screenshot alongside the path. + */ + base64?: boolean + /** + * Keep the screenshot on the file system. If file is not saved, + * `page.screenshot` always returns `base64` screenshot. + * @default true + */ + save?: boolean +} + +export interface MarkOptions { + /** + * Optional stack string used to resolve marker location. + * Useful for wrapper libraries that need to forward the end-user callsite. + */ + stack?: string +} + +interface StandardScreenshotComparators { + pixelmatch: { + /** + * The maximum number of pixels that are allowed to differ between the captured + * screenshot and the stored reference image. + * + * If set to `undefined`, any non-zero difference will cause the test to fail. + * + * For example, `allowedMismatchedPixels: 10` means the test will pass if 10 + * or fewer pixels differ, but fail if 11 or more differ. + * + * If both this and `allowedMismatchedPixelRatio` are set, the more restrictive + * value (i.e., fewer allowed mismatches) will be used. + * + * @default undefined + */ + allowedMismatchedPixels?: number | undefined + /** + * The maximum allowed ratio of differing pixels between the captured screenshot + * and the reference image. + * + * Must be a value between `0` and `1`. + * + * For example, `allowedMismatchedPixelRatio: 0.02` means the test will pass + * if up to 2% of pixels differ, but fail if more than 2% differ. + * + * If both this and `allowedMismatchedPixels` are set, the more restrictive + * value (i.e., fewer allowed mismatches) will be used. + * + * @default undefined + */ + allowedMismatchedPixelRatio?: number | undefined + /** + * Acceptable perceived color difference between the same pixel in two images. + * + * Value ranges from `0` (strict) to `1` (very lenient). Lower values mean + * small differences will be detected. + * + * The comparison uses the {@link https://en.wikipedia.org/wiki/YIQ | YIQ color space}. + * + * @default 0.1 + */ + threshold?: number | undefined + /** + * If `true`, disables detection and ignoring of anti-aliased pixels. + * + * @default false + */ + includeAA?: boolean | undefined + /** + * Blending level of unchanged pixels in the diff image. + * + * Ranges from `0` (white) to `1` (original brightness). + * + * @default 0.1 + */ + alpha?: number | undefined + /** + * Color used for anti-aliased pixels in the diff image. + * + * Format: `[R, G, B]` + * + * @default [255, 255, 0] + */ + aaColor?: [r: number, g: number, b: number] | undefined + /** + * Color used for differing pixels in the diff image. + * + * Format: `[R, G, B]` + * + * @default [255, 0, 0] + */ + diffColor?: [r: number, g: number, b: number] | undefined + /** + * Optional alternative color for dark-on-light differences, to help show + * what's added vs. removed. + * + * If not set, `diffColor` is used for all differences. + * + * Format: `[R, G, B]` + * + * @default undefined + */ + diffColorAlt?: [r: number, g: number, b: number] | undefined + /** + * If `true`, shows only the diff as a mask on a transparent background, + * instead of overlaying it on the original image. + * + * Anti-aliased pixels won't be shown (if detected). + * + * @default false + */ + diffMask?: boolean | undefined + } +} + +export interface ScreenshotComparatorRegistry extends StandardScreenshotComparators {} + +export type NonStandardScreenshotComparators = Omit< + ScreenshotComparatorRegistry, + keyof StandardScreenshotComparators +> + +export interface ScreenshotMatcherOptions< + ComparatorName extends keyof ScreenshotComparatorRegistry = keyof ScreenshotComparatorRegistry +> { + /** + * The name of the comparator to use for visual diffing. + * + * Must be one of the keys from {@linkcode ScreenshotComparatorRegistry}. + * + * @defaultValue `'pixelmatch'` + */ + comparatorName?: ComparatorName + comparatorOptions?: ScreenshotComparatorRegistry[ComparatorName] + screenshotOptions?: Omit< + ScreenshotOptions, + 'element' | 'base64' | 'path' | 'save' | 'type' | 'strict' | 'timeout' + > + /** + * Time to wait until a stable screenshot is found. + * + * Setting this value to `0` disables the timeout, but if a stable screenshot + * can't be determined the process will not end. + * + * @default 5000 + */ + timeout?: number + /** + * Allow only a single element with the same locator. + * + * If Vitest finds multiple elements, it will throw an error immediately without retrying. + * @default true + */ + strict?: boolean +} + +export interface UserEvent { + /** + * Creates a new user event instance. This is useful if you need to keep the + * state of keyboard to press and release buttons correctly. + * + * **Note:** Unlike `@testing-library/user-event`, the default `userEvent` instance + * from `vitest/browser` is created once, not every time its methods are called! + * @see {@link https://vitest.dev/api/browser/interactivity.html#userevent-setup} + */ + setup: () => UserEvent + /** + * Cleans up the user event instance, releasing any resources or state it holds, + * such as keyboard press state. For the default `userEvent` instance, this method + * is automatically called after each test case. + */ + cleanup: () => Promise + /** + * Click on an element. Uses provider's API under the hood and supports all its options. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-click} Playwright API + * @see {@link https://webdriver.io/docs/api/element/click/} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/convenience/#click} testing-library API + */ + click: (element: Element | Locator, options?: UserEventClickOptions) => Promise + /** + * Triggers a double click event on an element. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-dblclick} Playwright API + * @see {@link https://webdriver.io/docs/api/element/doubleClick/} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/convenience/#dblClick} testing-library API + */ + dblClick: (element: Element | Locator, options?: UserEventDoubleClickOptions) => Promise + /** + * Triggers a triple click event on an element. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-click} Playwright API: using `click` with `clickCount: 3` + * @see {@link https://webdriver.io/docs/api/browser/actions/} WebdriverIO API: using actions api with `move` plus three `down + up + pause` events in a row + * @see {@link https://testing-library.com/docs/user-event/convenience/#tripleclick} testing-library API + */ + tripleClick: (element: Element | Locator, options?: UserEventTripleClickOptions) => Promise + /** + * Triggers a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event|`wheel` event} on an element. + * + * @param element - The target element to receive wheel events. + * @param options - Scroll configuration using `delta` or `direction`. + * @returns A promise that resolves when all wheel events have been dispatched. + * + * @since 4.1.0 + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-wheel} + * + * @example + * // Scroll down by 100 pixels + * await userEvent.wheel(container, { delta: { y: 100 } }) + * + * @example + * // Scroll up 5 times + * await userEvent.wheel(container, { direction: 'up', times: 5 }) + */ + wheel(element: Element | Locator, options: UserEventWheelOptions): Promise + /** + * Choose one or more values from a select element. Uses provider's API under the hood. + * If select doesn't have `multiple` attribute, only the first value will be selected. + * @example + * await userEvent.selectOptions(select, 'Option 1') + * expect(select).toHaveValue('option-1') + * + * await userEvent.selectOptions(select, 'option-1') + * expect(select).toHaveValue('option-1') + * + * await userEvent.selectOptions(select, [ + * screen.getByRole('option', { name: 'Option 1' }), + * screen.getByRole('option', { name: 'Option 2' }), + * ]) + * expect(select).toHaveValue(['option-1', 'option-2']) + * @see {@link https://playwright.dev/docs/api/class-locator#locator-select-option} Playwright API + * @see {@link https://webdriver.io/docs/api/element/doubleClick/} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/utility/#-selectoptions-deselectoptions} testing-library API + */ + selectOptions: ( + element: HTMLElement | SVGElement | Locator, + values: HTMLElement | HTMLElement[] | Locator | Locator[] | string | string[], + options?: UserEventSelectOptions, + ) => Promise + /** + * Type text on the keyboard. If any input is focused, it will receive the text, + * otherwise it will be typed on the document. Uses provider's API under the hood. + * **Supports** [user-event `keyboard` syntax](https://testing-library.com/docs/user-event/keyboard) (e.g., `{Shift}`) even with `playwright` and `webdriverio` providers. + * @example + * await userEvent.keyboard('foo') // translates to: f, o, o + * await userEvent.keyboard('{{a[[') // translates to: {, a, [ + * await userEvent.keyboard('{Shift}{f}{o}{o}') // translates to: Shift, f, o, o + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API + * @see {@link https://webdriver.io/docs/api/browser/keys} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/keyboard} testing-library API + */ + keyboard: (text: string) => Promise + /** + * Types text into an element. Uses provider's API under the hood. + * **Supports** [user-event `keyboard` syntax](https://testing-library.com/docs/user-event/keyboard) (e.g., `{Shift}`) even with `playwright` and `webdriverio` providers. + * This method can be significantly slower than `userEvent.fill`, so it should be used only when necessary. + * @example + * await userEvent.type(input, 'foo') // translates to: f, o, o + * await userEvent.type(input, '{{a[[') // translates to: {, a, [ + * await userEvent.type(input, '{Shift}{f}{o}{o}') // translates to: Shift, f, o, o + * @see {@link https://playwright.dev/docs/api/class-locator#locator-press} Playwright API + * @see {@link https://webdriver.io/docs/api/browser/action#key-input-source} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/utility/#type} testing-library API + */ + type: (element: Element | Locator, text: string, options?: UserEventTypeOptions) => Promise + /** + * Removes all text from an element. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-clear} Playwright API + * @see {@link https://webdriver.io/docs/api/element/clearValue} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/utility/#clear} testing-library API + */ + clear: (element: Element | Locator, options?: UserEventClearOptions) => Promise + /** + * Sends a `Tab` key event. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API + * @see {@link https://webdriver.io/docs/api/element/keys} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/convenience/#tab} testing-library API + */ + tab: (options?: UserEventTabOptions) => Promise + /** + * Hovers over an element. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-hover} Playwright API + * @see {@link https://webdriver.io/docs/api/element/moveTo/} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/convenience/#hover} testing-library API + */ + hover: (element: Element | Locator, options?: UserEventHoverOptions) => Promise + /** + * Moves cursor position to the body element. Uses provider's API under the hood. + * By default, the cursor position is in the center (in webdriverio) or in some visible place (in playwright) + * of the body element, so if the current element is already there, this will have no effect. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-hover} Playwright API + * @see {@link https://webdriver.io/docs/api/element/moveTo/} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/convenience/#hover} testing-library API + */ + unhover: (element: Element | Locator, options?: UserEventHoverOptions) => Promise + /** + * Change a file input element to have the specified files. Uses provider's API under the hood. + * @see {@link https://playwright.dev/docs/api/class-locator#locator-set-input-files} Playwright API + * @see {@link https://testing-library.com/docs/user-event/utility#upload} testing-library API + */ + upload: (element: Element | Locator, files: File | File[] | string | string[], options?: UserEventUploadOptions) => Promise + /** + * Copies the selected content. + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API + * @see {@link https://webdriver.io/docs/api/browser/keys//} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/clipboard#copy} testing-library API + */ + copy: () => Promise + /** + * Cuts the selected content. + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API + * @see {@link https://webdriver.io/docs/api/browser/keys//} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/clipboard#cut} testing-library API + */ + cut: () => Promise + /** + * Pastes the copied or cut content. + * @see {@link https://playwright.dev/docs/api/class-keyboard} Playwright API + * @see {@link https://webdriver.io/docs/api/browser/keys//} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/clipboard#paste} testing-library API + */ + paste: () => Promise + /** + * Fills an input element with text. This will remove any existing text in the input before typing the new text. + * Uses provider's API under the hood. + * This API is faster than using `userEvent.type` or `userEvent.keyboard`, but it **doesn't support** [user-event `keyboard` syntax](https://testing-library.com/docs/user-event/keyboard) (e.g., `{Shift}`). + * @example + * await userEvent.fill(input, 'foo') // translates to: f, o, o + * await userEvent.fill(input, '{{a[[') // translates to: {, {, a, [, [ + * await userEvent.fill(input, '{Shift}') // translates to: {, S, h, i, f, t, } + * @see {@link https://playwright.dev/docs/api/class-locator#locator-fill} Playwright API + * @see {@link https://webdriver.io/docs/api/element/setValue} WebdriverIO API + * @see {@link https://testing-library.com/docs/user-event/utility/#type} testing-library API + */ + fill: (element: Element | Locator, text: string, options?: UserEventFillOptions) => Promise + /** + * Drags a source element on top of the target element. This API is not supported by "preview" provider. + * @see {@link https://playwright.dev/docs/api/class-frame#frame-drag-and-drop} Playwright API + * @see {@link https://webdriver.io/docs/api/element/dragAndDrop/} WebdriverIO API + */ + dragAndDrop: (source: Element | Locator, target: Element | Locator, options?: UserEventDragAndDropOptions) => Promise +} + +export interface UserEventFillOptions {} +export interface UserEventHoverOptions {} +export interface UserEventSelectOptions {} +export interface UserEventClickOptions {} +export interface UserEventClearOptions {} +export interface UserEventDoubleClickOptions {} +export interface UserEventTripleClickOptions {} +export interface UserEventDragAndDropOptions {} +export interface UserEventUploadOptions {} + +/** + * Base options shared by all wheel event configurations. + * + * @since 4.1.0 + */ +export interface UserEventWheelBaseOptions { + /** + * Number of wheel events to fire. Defaults to `1`. + * + * Useful for triggering multiple scroll steps in a single call. + */ + times?: number +} + +/** + * Wheel options using pixel-based `delta` values for precise scroll control. + * + * @since 4.1.0 + */ +export interface UserEventWheelDeltaOptions extends UserEventWheelBaseOptions { + /** + * Precise scroll delta values in pixels. At least one axis must be specified. + * + * - Positive `y` scrolls down, negative `y` scrolls up. + * - Positive `x` scrolls right, negative `x` scrolls left. + */ + delta: { x: number; y?: number } | { x?: number; y: number } + direction?: undefined +} + +/** + * Wheel options using semantic `direction` values for simpler scroll control. + * + * @since 4.1.0 + */ +export interface UserEventWheelDirectionOptions extends UserEventWheelBaseOptions { + /** + * Semantic scroll direction. Use this for readable tests when exact pixel values don't matter. + */ + direction: 'up' | 'down' | 'left' | 'right' + delta?: undefined +} + +/** + * Options for triggering wheel events. + * + * Specify scrolling using either `delta` for precise pixel values, or `direction` for semantic scrolling. These are mutually exclusive. + * + * @since 4.1.0 + */ +export type UserEventWheelOptions = UserEventWheelDeltaOptions | UserEventWheelDirectionOptions + +export interface LocatorOptions { + /** + * Whether to find an exact match: case-sensitive and whole-string. Default to false. Ignored when locating by a + * regular expression. Note that exact match still trims whitespace. + */ + exact?: boolean + hasText?: string | RegExp + hasNotText?: string | RegExp + has?: Locator + hasNot?: Locator +} + +export interface LocatorByRoleOptions extends LocatorOptions { + /** + * Should checked elements (set by `aria-checked` or ``) be included or not. By default, the filter is not applied. + * + * See [`aria-checked`](https://www.w3.org/TR/wai-aria-1.2/#aria-checked) for more information + */ + checked?: boolean + /** + * Should disabled elements be included or not. By default, the filter is not applied. Note that unlike other attributes, `disable` state is inherited. + * + * See [`aria-disabled`](https://www.w3.org/TR/wai-aria-1.2/#aria-disabled) for more information + */ + disabled?: boolean + /** + * Should expanded elements be included or not. By default, the filter is not applied. + * + * See [`aria-expanded`](https://www.w3.org/TR/wai-aria-1.2/#aria-expanded) for more information + */ + expanded?: boolean + /** + * Should elements that are [normally excluded](https://www.w3.org/TR/wai-aria-1.2/#tree_exclusion) from the accessibility tree be queried. By default, only non-hidden elements are matched by role selector. + * + * Note that roles `none` and `presentation` are always included. + * @default false + */ + includeHidden?: boolean + /** + * A number attribute that is usually present for `heading`, `listitem`, `row`, `treeitem` roles with default values for `

-

` elements. By default, the filter is not applied. + * + * See [`aria-level`](https://www.w3.org/TR/wai-aria-1.2/#aria-level) for more information + */ + level?: number + /** + * Option to match the [accessible name](https://w3c.github.io/accname/#dfn-accessible-name). By default, matching is + * case-insensitive and searches for a substring, use `exact` to control this behavior. + */ + name?: string | RegExp + /** + * Should pressed elements be included or not. By default, the filter is not applied. + * + * See [`aria-pressed`](https://www.w3.org/TR/wai-aria-1.2/#aria-pressed) for more information + */ + pressed?: boolean + /** + * Should selected elements be included or not. By default, the filter is not applied. + * + * See [`aria-selected`](https://www.w3.org/TR/wai-aria-1.2/#aria-selected) for more information + */ + selected?: boolean +} + +export interface LocatorScreenshotOptions extends Omit {} + +export interface LocatorSelectors { + /** + * Creates a way to locate an element by its [ARIA role](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Roles), [ARIA attributes](https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/Attributes) and [accessible name](https://developer.mozilla.org/en-US/docs/Glossary/Accessible_name). + * @see {@link https://vitest.dev/api/browser/locators#getbyrole} + */ + getByRole: (role: ARIARole | ({} & string), options?: LocatorByRoleOptions) => Locator + /** + * @see {@link https://vitest.dev/api/browser/locators#getbylabeltext} + */ + getByLabelText: (text: string | RegExp, options?: LocatorOptions) => Locator + /** + * Creates a locator capable of finding an element with an `alt` attribute that matches the text. Unlike testing-library's implementation, Vitest will match any element that has an `alt` attribute. + * @see {@link https://vitest.dev/api/browser/locators#getbyalttext} + */ + getByAltText: (text: string | RegExp, options?: LocatorOptions) => Locator + /** + * Creates a locator capable of finding an element that has the specified placeholder text. Vitest will match any element that has a matching `placeholder` attribute, not just `input`. + * @see {@link https://vitest.dev/api/browser/locators#getbyplaceholder} + */ + getByPlaceholder: (text: string | RegExp, options?: LocatorOptions) => Locator + /** + * Creates a locator capable of finding an element that contains the specified text. The text will be matched against TextNode's [`nodeValue`](https://developer.mozilla.org/en-US/docs/Web/API/Node/nodeValue) or input's value if the type is `button` or `reset`. + * Matching by text always normalizes whitespace, even with exact match. + * For example, it turns multiple spaces into one, turns line breaks into spaces and ignores leading and trailing whitespace. + * @see {@link https://vitest.dev/api/browser/locators#getbytext} + */ + getByText: (text: string | RegExp, options?: LocatorOptions) => Locator + /** + * Creates a locator capable of finding an element that has the specified `title` attribute. Unlike testing-library's `getByTitle`, Vitest cannot find `title` elements within an SVG. + * @see {@link https://vitest.dev/api/browser/locators#getbytitle} + */ + getByTitle: (text: string | RegExp, options?: LocatorOptions) => Locator + /** + * Creates a locator capable of finding an element that matches the specified test id attribute. You can configure the attribute name with [`browser.locators.testIdAttribute`](https://vitest.dev/config/browser/locators#browser-locators-testidattribute). + * @see {@link https://vitest.dev/api/browser/locators#getbytestid} + */ + getByTestId: (text: string | RegExp) => Locator +} + +export interface FrameLocator extends LocatorSelectors {} + +export interface SelectorOptions { + /** + * How long to wait until a single element is found. By default, this has the same timeout as the test. + * + * Vitest will try to find the element in ever increasing intervals: 0, 20, 50, 100, 100, 500. + */ + timeout?: number + /** + * Allow only a single element with the same locator. + * + * If Vitest finds multiple elements, it will throw an error immediately without retrying. + * @default true + */ + strict?: boolean +} + +export interface Locator extends LocatorSelectors { + /** + * Selector string that will be used to locate the element by the browser provider. + * You can use this string in the commands API: + * ```ts + * // playwright + * function test({ selector, iframe }) { + * await iframe.locator(selector).click() + * } + * // webdriverio + * function test({ selector, browser }) { + * await browser.$(selector).click() + * } + * ``` + * @see {@link https://vitest.dev/api/browser/locators#selector} + */ + readonly selector: string + + /** + * The number of elements that this locator is matching. + * @see {@link https://vitest.dev/api/browser/locators#length} + */ + readonly length: number + + /** + * Click on an element. You can use the options to set the cursor position. + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-click} + */ + click(options?: UserEventClickOptions): Promise + /** + * Triggers a double click event on an element. You can use the options to set the cursor position. + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-dblclick} + */ + dblClick(options?: UserEventDoubleClickOptions): Promise + /** + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-tripleclick} + */ + tripleClick(options?: UserEventTripleClickOptions): Promise + /** + * Triggers a {@link https://developer.mozilla.org/en-US/docs/Web/API/Element/wheel_event|`wheel` event} on an element. + * + * @param options - Scroll configuration using `delta` or `direction`. + * @returns A promise that resolves when all wheel events have been dispatched. + * + * @since 4.1.0 + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-wheel} + * + * @example + * // Scroll down by 100 pixels + * await container.wheel({ delta: { y: 100 } }) + * + * @example + * // Scroll up 5 times + * await container.wheel({ direction: 'up', times: 5 }) + */ + wheel(options: UserEventWheelOptions): Promise + /** + * Clears the input element content + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-clear} + */ + clear(options?: UserEventClearOptions): Promise + /** + * Moves the cursor position to the selected element + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-hover} + */ + hover(options?: UserEventHoverOptions): Promise + /** + * This works the same as `locator.hover`, but moves the cursor to the `document.body` element instead. + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-unhover} + */ + unhover(options?: UserEventHoverOptions): Promise + /** + * Sets the value of the current `input`, `textarea` or `contenteditable` element. + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-fill} + */ + fill(text: string, options?: UserEventFillOptions): Promise + /** + * Drags the current element to the target location. + * @see {@link https://vitest.dev/api/browser/interactivity#userevent-dropto} + */ + dropTo(target: Locator, options?: UserEventDragAndDropOptions): Promise + /** + * Choose one or more values from a `