Compare commits
	
		
			5 Commits
		
	
	
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
|   | b85f0dbb80 | ||
|   | be4450ddae | ||
|   | b434a3b9df | ||
|   | 6064a0d4fb | ||
|   | f8b9d9274b | 
| @@ -2,7 +2,7 @@ version: 2.1 | ||||
| executors: | ||||
|   pw-focal-development: | ||||
|     docker: | ||||
|       - image: mcr.microsoft.com/playwright:v1.25.2-focal | ||||
|       - image: mcr.microsoft.com/playwright:v1.25.0-focal | ||||
|     environment: | ||||
|       NODE_ENV: development # Needed to ensure 'dist' folder created and devDependencies installed | ||||
|       PERCY_POSTINSTALL_BROWSER: 'true' # Needed to store the percy browser in cache deps | ||||
|   | ||||
							
								
								
									
										4
									
								
								.github/PULL_REQUEST_TEMPLATE.md
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -21,9 +21,9 @@ Closes <!--- Insert Issue Number(s) this PR addresses. Start by typing # will op | ||||
| ### Reviewer Checklist | ||||
|  | ||||
| * [ ] Changes appear to address issue? | ||||
| * [ ] Reviewer has tested changes by following the provided instructions? | ||||
| * [ ] Changes appear not to be breaking changes? | ||||
| * [ ] Appropriate automated tests included? | ||||
| * [ ] Appropriate unit tests included? | ||||
| * [ ] Code style and in-line documentation are appropriate? | ||||
| * [ ] Commit messages meet standards? | ||||
| * [ ] Has associated issue been labelled unverified? (only applicable if this PR closes the issue) | ||||
| * [ ] Has associated issue been labelled bug? (only applicable if this PR is for a bug fix) | ||||
|   | ||||
							
								
								
									
										1
									
								
								.github/codeql/codeql-config.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -1 +0,0 @@ | ||||
| name: 'Custom CodeQL config' | ||||
							
								
								
									
										8
									
								
								.github/dependabot.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -13,12 +13,8 @@ updates: | ||||
|       - "pr:daveit" | ||||
|       - "pr:platform" | ||||
|     ignore: | ||||
|       - dependency-name: "@playwright/test" #We have to source the playwright container which is not detected by Dependabot | ||||
|       - dependency-name: "playwright-core" #We have to source the playwright container which is not detected by Dependabot | ||||
|       - dependency-name: "@babel/eslint-parser" #Lots of noise in these type patch releases. | ||||
|         update-types: ["version-update:semver-patch"]  | ||||
|       - dependency-name: "eslint-plugin-vue" #Lots of noise in these type patch releases.   | ||||
|         update-types: ["version-update:semver-patch"] | ||||
|       - dependency-name: "@playwright/test" #we source the container instead of the dependency in CI | ||||
|  | ||||
|   - package-ecosystem: "github-actions" | ||||
|     directory: "/" | ||||
|     schedule: | ||||
|   | ||||
							
								
								
									
										31
									
								
								.github/workflows/codeql-analysis.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -1,10 +1,11 @@ | ||||
| name: 'CodeQL' | ||||
|  | ||||
| name: "CodeQL" | ||||
|  | ||||
| on: | ||||
|   push: | ||||
|     branches: [master, 'release/*'] | ||||
|     branches: [ master ] | ||||
|   pull_request: | ||||
|     branches: [master, 'release/*'] | ||||
|     branches: [ master ] | ||||
|     paths-ignore: | ||||
|       - '**/*Spec.js' | ||||
|       - '**/*.md' | ||||
| @@ -26,19 +27,17 @@ jobs: | ||||
|       security-events: write | ||||
|  | ||||
|     steps: | ||||
|       - name: Checkout repository | ||||
|         uses: actions/checkout@v3 | ||||
|     - name: Checkout repository | ||||
|       uses: actions/checkout@v3 | ||||
|  | ||||
|       # Initializes the CodeQL tools for scanning. | ||||
|       - name: Initialize CodeQL | ||||
|         uses: github/codeql-action/init@v2 | ||||
|         with: | ||||
|           config-file: ./.github/codeql/codeql-config.yml | ||||
|           languages: javascript | ||||
|           queries: security-and-quality | ||||
|     # Initializes the CodeQL tools for scanning. | ||||
|     - name: Initialize CodeQL | ||||
|       uses: github/codeql-action/init@v2 | ||||
|       with: | ||||
|         languages: javascript | ||||
|  | ||||
|       - name: Autobuild | ||||
|         uses: github/codeql-action/autobuild@v2 | ||||
|     - name: Autobuild | ||||
|       uses: github/codeql-action/autobuild@v2 | ||||
|  | ||||
|       - name: Perform CodeQL Analysis | ||||
|         uses: github/codeql-action/analyze@v2 | ||||
|     - name: Perform CodeQL Analysis | ||||
|       uses: github/codeql-action/analyze@v2 | ||||
|   | ||||
							
								
								
									
										2
									
								
								.github/workflows/e2e-couchdb.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -23,7 +23,7 @@ jobs: | ||||
|       - uses: actions/setup-node@v3 | ||||
|         with: | ||||
|           node-version: '16' | ||||
|       - run: npx playwright@1.25.2 install | ||||
|       - run: npx playwright@1.25.0 install | ||||
|       - run: npm install | ||||
|       - run: sh src/plugins/persistence/couch/replace-localstorage-with-couchdb-indexhtml.sh | ||||
|       - run: npm run test:e2e:couchdb | ||||
|   | ||||
							
								
								
									
										2
									
								
								.github/workflows/e2e-pr.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -30,7 +30,7 @@ jobs: | ||||
|       - uses: actions/setup-node@v3 | ||||
|         with: | ||||
|           node-version: '16' | ||||
|       - run: npx playwright@1.25.2 install | ||||
|       - run: npx playwright@1.25.0 install | ||||
|       - run: npx playwright install chrome-beta | ||||
|       - run: npm install | ||||
|       - run: npm run test:e2e:full | ||||
|   | ||||
							
								
								
									
										98
									
								
								.github/workflows/lighthouse.yml
									
									
									
									
										vendored
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,98 @@ | ||||
| name: lighthouse | ||||
| on: | ||||
|   workflow_dispatch: | ||||
|     inputs:  | ||||
|       version: | ||||
|         description: 'Which branch do you want to test?' # Limited to branch for now | ||||
|         required: false | ||||
|         default: 'master' | ||||
|   pull_request: | ||||
|     types:  | ||||
|       - labeled | ||||
| jobs: | ||||
|   lighthouse-pr: | ||||
|     if: ${{ github.event.label.name == 'pr:lighthouse' }} | ||||
|     runs-on: ubuntu-latest | ||||
|     steps: | ||||
|       - name: Checkout Master for Baseline | ||||
|         uses: actions/checkout@v3 | ||||
|         with: | ||||
|           ref: master #explicitly checkout master for baseline | ||||
|       - name: Install Node 16 | ||||
|         uses: actions/setup-node@v3 | ||||
|         with: | ||||
|           node-version: '16' | ||||
|       - name: Cache node modules | ||||
|         uses: actions/cache@v2 | ||||
|         env: | ||||
|           cache-name: cache-node-modules | ||||
|         with: | ||||
|           path: ~/.npm | ||||
|           key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|           restore-keys: | | ||||
|             ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|       - name: npm install with lighthouse cli  | ||||
|         run: npm install && npm install -g @lhci/cli | ||||
|       - name: Run lhci against master to generate baseline and ignore exit codes | ||||
|         run: lhci autorun || true | ||||
|       - name: Perform clean checkout of PR | ||||
|         uses: actions/checkout@v3 | ||||
|         with: | ||||
|           clean: true | ||||
|       - name: Install Node version which is compatible with PR | ||||
|         uses: actions/setup-node@v3 | ||||
|       - name: npm install with lighthouse cli  | ||||
|         run: npm install && npm install -g @lhci/cli | ||||
|       - name: Run lhci with PR | ||||
|         run: lhci autorun | ||||
|         env: | ||||
|           LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} | ||||
|   lighthouse-nightly: | ||||
|     if: ${{ github.event.schedule }} | ||||
|     runs-on: ubuntu-latest | ||||
|     steps: | ||||
|       - uses: actions/checkout@v3 | ||||
|       - name: Install Node 16 | ||||
|         uses: actions/setup-node@v3 | ||||
|         with: | ||||
|           node-version: '16' | ||||
|       - name: Cache node modules | ||||
|         uses: actions/cache@v2 | ||||
|         env: | ||||
|           cache-name: cache-node-modules | ||||
|         with: | ||||
|           path: ~/.npm | ||||
|           key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|           restore-keys: | | ||||
|             ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|       - name: npm install with lighthouse cli  | ||||
|         run: npm install && npm install -g @lhci/cli | ||||
|       - name: Run lhci against master to generate baseline | ||||
|         run: lhci autorun | ||||
|         env: | ||||
|           LHCI_GITHUB_APP_TOKEN: ${{ secrets.LHCI_GITHUB_APP_TOKEN }} | ||||
|   lighthouse-dispatch: | ||||
|     if: ${{ github.event.workflow_dispatch }} | ||||
|     runs-on: ubuntu-latest | ||||
|     steps: | ||||
|       - uses: actions/checkout@v3 | ||||
|         with: | ||||
|           ref: ${{ github.event.inputs.version }} | ||||
|       - name: Install Node 14 | ||||
|         uses: actions/setup-node@v3 | ||||
|         with: | ||||
|           node-version: '16' | ||||
|       - name: Cache node modules | ||||
|         uses: actions/cache@v3 | ||||
|         env: | ||||
|           cache-name: cache-node-modules | ||||
|         with: | ||||
|           path: ~/.npm | ||||
|           key: ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|           restore-keys: | | ||||
|             ${{ runner.os }}-build-${{ env.cache-name }}-${{ hashFiles('**/package.json') }} | ||||
|       - name: npm install with lighthouse cli  | ||||
|         run: npm install && npm install -g @lhci/cli | ||||
|       - name: Run lhci against master to generate baseline | ||||
|         run: lhci autorun | ||||
|          | ||||
							
								
								
									
										2
									
								
								.github/workflows/npm-prerelease.yml
									
									
									
									
										vendored
									
									
								
							
							
						
						| @@ -28,6 +28,6 @@ jobs: | ||||
|           node-version: 16 | ||||
|           registry-url: https://registry.npmjs.org/ | ||||
|       - run: npm install | ||||
|       - run: npm publish --access=public --tag unstable | ||||
|       - run: npm publish --access public --tag unstable | ||||
|         env: | ||||
|           NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} | ||||
|   | ||||
							
								
								
									
										11
									
								
								.npmignore
									
									
									
									
									
								
							
							
						
						| @@ -10,6 +10,9 @@ | ||||
| # https://github.com/nasa/openmct/issues/4992 | ||||
| !/example/**/* | ||||
|  | ||||
| # We will remove this in https://github.com/nasa/openmct/issues/4922 | ||||
| !/app.js | ||||
|  | ||||
| # ...except for these files in the above folders. | ||||
| /src/**/*Spec.js | ||||
| /src/**/test/ | ||||
| @@ -21,10 +24,4 @@ | ||||
| !copyright-notice.html | ||||
| !index.html | ||||
| !openmct.js | ||||
| !SECURITY.md | ||||
|  | ||||
| # Add e2e tests to npm package | ||||
| !/e2e/**/* | ||||
|  | ||||
| # ... except our test-data folder files. | ||||
| /e2e/test-data/*.json | ||||
| !SECURITY.md | ||||
| @@ -173,7 +173,7 @@ The following guidelines are provided for anyone contributing source code to the | ||||
| 1. Avoid deep nesting (especially of functions), except where necessary | ||||
|    (e.g. due to closure scope). | ||||
| 1. End with a single new-line character. | ||||
| 1. Always use ES6 `Class`es and inheritance rather than the pre-ES6 prototypal  | ||||
| 1. Always use ES6 `Class`es and inheritence rather than the pre-ES6 prototypal  | ||||
|    pattern. | ||||
| 1. Within a given function's scope, do not mix declarations and imperative | ||||
|    code, and  present these in the following order: | ||||
| @@ -328,4 +328,4 @@ checklist). | ||||
| Write out a small list of tests performed with just enough detail for another developer on the team  | ||||
| to execute.  | ||||
|  | ||||
| i.e. ```When Clicking on Add button, new `object` appears in dropdown.``` | ||||
| i.e. ```When Clicking on Add button, new `object` appears in dropdown.``` | ||||
							
								
								
									
										12
									
								
								README.md
									
									
									
									
									
								
							
							
						
						| @@ -30,8 +30,6 @@ Building and running Open MCT in your local dev environment is very easy. Be sur | ||||
|  | ||||
| Open MCT is now running, and can be accessed by pointing a web browser at [http://localhost:8080/](http://localhost:8080/) | ||||
|  | ||||
| Open MCT is built using [`npm`](http://npmjs.com/) and [`webpack`](https://webpack.js.org/). | ||||
|  | ||||
| ## Documentation | ||||
|  | ||||
| Documentation is available on the [Open MCT website](https://nasa.github.io/openmct/documentation/). | ||||
| @@ -45,9 +43,11 @@ our documentation. | ||||
| We want Open MCT to be as easy to use, install, run, and develop for as | ||||
| possible, and your feedback will help us get there! Feedback can be provided via [GitHub issues](https://github.com/nasa/openmct/issues/new/choose), [Starting a GitHub Discussion](https://github.com/nasa/openmct/discussions), or by emailing us at [arc-dl-openmct@mail.nasa.gov](mailto:arc-dl-openmct@mail.nasa.gov). | ||||
|  | ||||
| ## Developing Applications With Open MCT | ||||
| ## Building Applications With Open MCT | ||||
|  | ||||
| For more on developing with Open MCT, see our documentation for a guide on [Developing Applications with Open MCT](./API.md#starting-an-open-mct-application). | ||||
| Open MCT is built using [`npm`](http://npmjs.com/) and [`webpack`](https://webpack.js.org/). | ||||
|  | ||||
| See our documentation for a guide on [building Applications with Open MCT](https://github.com/nasa/openmct/blob/master/API.md#starting-an-open-mct-application). | ||||
|  | ||||
| ## Compatibility | ||||
|  | ||||
| @@ -64,7 +64,7 @@ that is intended to be added or removed as a single unit. | ||||
| As well as providing an extension mechanism, most of the core Open MCT codebase is also  | ||||
| written as plugins. | ||||
|  | ||||
| For information on writing plugins, please see [our API documentation](./API.md#plugins). | ||||
| For information on writing plugins, please see [our API documentation](https://github.com/nasa/openmct/blob/master/API.md#plugins). | ||||
|  | ||||
| ## Tests | ||||
|  | ||||
| @@ -100,7 +100,7 @@ To run the performance tests: | ||||
| The test suite is configured to all tests localed in `e2e/tests/` ending in `*.e2e.spec.js`. For more about the e2e test suite, please see the [README](./e2e/README.md) | ||||
|  | ||||
| ### Security Tests | ||||
| Each commit is analyzed for known security vulnerabilities using [CodeQL](https://codeql.github.com/docs/codeql-language-guides/codeql-library-for-javascript/) and our overall security report is available on [LGTM](https://lgtm.com/projects/g/nasa/openmct/). The list of CWE coverage items is avaiable in the [CodeQL docs](https://codeql.github.com/codeql-query-help/javascript-cwe/). The CodeQL workflow is specified in the [CodeQL analysis file](./.github/workflows/codeql-analysis.yml) and the custom [CodeQL config](./.github/codeql/codeql-config.yml). | ||||
| Each commit is analyzed for known security vulnerabilities using [CodeQL](https://codeql.github.com/docs/codeql-language-guides/codeql-library-for-javascript/) and our overall security report is available on [LGTM](https://lgtm.com/projects/g/nasa/openmct/) | ||||
|  | ||||
| ### Test Reporting and Code Coverage | ||||
|  | ||||
|   | ||||
							
								
								
									
										92
									
								
								app.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,92 @@ | ||||
| /*global process*/ | ||||
|  | ||||
| /** | ||||
|  * Usage: | ||||
|  * | ||||
|  * npm install minimist express | ||||
|  * node app.js [options] | ||||
|  */ | ||||
|  | ||||
| const options = require('minimist')(process.argv.slice(2)); | ||||
| const express = require('express'); | ||||
| const app = express(); | ||||
| const fs = require('fs'); | ||||
| const request = require('request'); | ||||
| const __DEV__ = !process.env.NODE_ENV || process.env.NODE_ENV === 'development'; | ||||
|  | ||||
| // Defaults | ||||
| options.port = options.port || options.p || 8080; | ||||
| options.host = options.host || 'localhost'; | ||||
| options.directory = options.directory || options.D || '.'; | ||||
|  | ||||
| // Show command line options | ||||
| if (options.help || options.h) { | ||||
|     console.log("\nUsage: node app.js [options]\n"); | ||||
|     console.log("Options:"); | ||||
|     console.log("  --help, -h               Show this message."); | ||||
|     console.log("  --port, -p <number>      Specify port."); | ||||
|     console.log("  --directory, -D <bundle>   Serve files from specified directory."); | ||||
|     console.log(""); | ||||
|     process.exit(0); | ||||
| } | ||||
|  | ||||
| app.disable('x-powered-by'); | ||||
|  | ||||
| app.use('/proxyUrl', function proxyRequest(req, res, next) { | ||||
|     console.log('Proxying request to: ', req.query.url); | ||||
|     req.pipe(request({ | ||||
|         url: req.query.url, | ||||
|         strictSSL: false | ||||
|     }).on('error', next)).pipe(res); | ||||
| }); | ||||
|  | ||||
| class WatchRunPlugin { | ||||
|     apply(compiler) { | ||||
|         compiler.hooks.emit.tapAsync('WatchRunPlugin', (compilation, callback) => { | ||||
|             console.log('Begin compile at ' + new Date()); | ||||
|             callback(); | ||||
|         }); | ||||
|     } | ||||
| } | ||||
|  | ||||
| const webpack = require('webpack'); | ||||
| let webpackConfig; | ||||
| if (__DEV__) { | ||||
|     webpackConfig = require('./webpack.dev'); | ||||
|     webpackConfig.plugins.push(new webpack.HotModuleReplacementPlugin()); | ||||
|     webpackConfig.entry.openmct = [ | ||||
|         'webpack-hot-middleware/client?reload=true', | ||||
|         webpackConfig.entry.openmct | ||||
|     ]; | ||||
|     webpackConfig.plugins.push(new WatchRunPlugin()); | ||||
| } else { | ||||
|     webpackConfig = require('./webpack.coverage'); | ||||
| } | ||||
|  | ||||
| const compiler = webpack(webpackConfig); | ||||
|  | ||||
| app.use(require('webpack-dev-middleware')( | ||||
|     compiler, | ||||
|     { | ||||
|         publicPath: '/dist', | ||||
|         stats: 'errors-warnings' | ||||
|     } | ||||
| )); | ||||
|  | ||||
| if (__DEV__) { | ||||
|     app.use(require('webpack-hot-middleware')( | ||||
|         compiler, | ||||
|         {} | ||||
|     )); | ||||
| } | ||||
|  | ||||
| // Expose index.html for development users. | ||||
| app.get('/', function (req, res) { | ||||
|     fs.createReadStream('index.html').pipe(res); | ||||
| }); | ||||
|  | ||||
| // Finally, open the HTTP server and log the instance to the console | ||||
| app.listen(options.port, options.host, function () { | ||||
|     console.log('Open MCT application running at %s:%s', options.host, options.port); | ||||
| }); | ||||
|  | ||||
							
								
								
									
										3
									
								
								docs/footer.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,3 @@ | ||||
|         <hr> | ||||
|     </body> | ||||
| </html> | ||||
							
								
								
									
										209
									
								
								docs/gendocs.js
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,209 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /*global require,process,__dirname,GLOBAL*/ | ||||
| /*jslint nomen: false */ | ||||
|  | ||||
|  | ||||
| // Usage: | ||||
| //   node gendocs.js --in <source directory> --out <dest directory> | ||||
|  | ||||
| var CONSTANTS = { | ||||
|         DIAGRAM_WIDTH: 800, | ||||
|         DIAGRAM_HEIGHT: 500 | ||||
|     }, | ||||
|     TOC_HEAD = "# Table of Contents"; | ||||
|  | ||||
| GLOBAL.window = GLOBAL.window ||  GLOBAL; // nomnoml expects window to be defined | ||||
| (function () { | ||||
|     "use strict"; | ||||
|  | ||||
|     var fs = require("fs"), | ||||
|         mkdirp = require("mkdirp"), | ||||
|         path = require("path"), | ||||
|         glob = require("glob"), | ||||
|         marked = require("marked"), | ||||
|         split = require("split"), | ||||
|         stream = require("stream"), | ||||
|         nomnoml = require('nomnoml'), | ||||
|         toc = require("markdown-toc"), | ||||
|         Canvas = require('canvas'), | ||||
|         header = fs.readFileSync(path.resolve(__dirname, 'header.html')), | ||||
|         footer = fs.readFileSync(path.resolve(__dirname, 'footer.html')), | ||||
|         options = require("minimist")(process.argv.slice(2)); | ||||
|  | ||||
|     // Convert from nomnoml source to a target PNG file. | ||||
|     function renderNomnoml(source, target) { | ||||
|         var canvas = | ||||
|             new Canvas(CONSTANTS.DIAGRAM_WIDTH, CONSTANTS.DIAGRAM_HEIGHT); | ||||
|         nomnoml.draw(canvas, source, 1.0); | ||||
|         canvas.pngStream().pipe(fs.createWriteStream(target)); | ||||
|     } | ||||
|  | ||||
|     // Stream transform. | ||||
|     // Pulls out nomnoml diagrams from fenced code blocks and renders them | ||||
|     // as PNG files in the output directory, prefixed with a provided name. | ||||
|     // The fenced code blocks will be replaced with Markdown in the | ||||
|     // output of this stream. | ||||
|     function nomnomlifier(outputDirectory, prefix) { | ||||
|         var transform = new stream.Transform({ objectMode: true }), | ||||
|             isBuilding = false, | ||||
|             counter = 1, | ||||
|             outputPath, | ||||
|             source = ""; | ||||
|  | ||||
|         transform._transform = function (chunk, encoding, done) { | ||||
|             if (!isBuilding) { | ||||
|                 if (chunk.trim().indexOf("```nomnoml") === 0) { | ||||
|                     var outputFilename = prefix + '-' + counter + '.png'; | ||||
|                     outputPath = path.join(outputDirectory, outputFilename); | ||||
|                     this.push([ | ||||
|                         "\n\n\n" | ||||
|                     ].join("")); | ||||
|                     isBuilding = true; | ||||
|                     source = ""; | ||||
|                     counter += 1; | ||||
|                 } else { | ||||
|                     // Otherwise, pass through | ||||
|                     this.push(chunk + '\n'); | ||||
|                 } | ||||
|             } else { | ||||
|                 if (chunk.trim() === "```") { | ||||
|                     // End nomnoml | ||||
|                     renderNomnoml(source, outputPath); | ||||
|                     isBuilding = false; | ||||
|                 } else { | ||||
|                     source += chunk + '\n'; | ||||
|                 } | ||||
|             } | ||||
|             done(); | ||||
|         }; | ||||
|  | ||||
|         return transform; | ||||
|     } | ||||
|  | ||||
|     // Convert from Github-flavored Markdown to HTML | ||||
|     function gfmifier(renderTOC) { | ||||
|         var transform = new stream.Transform({ objectMode: true }), | ||||
|             markdown = ""; | ||||
|         transform._transform = function (chunk, encoding, done) { | ||||
|             markdown += chunk; | ||||
|             done(); | ||||
|         }; | ||||
|         transform._flush = function (done) { | ||||
|             if (renderTOC){ | ||||
|                 // Prepend table of contents | ||||
|                 markdown = | ||||
|                     [ TOC_HEAD, toc(markdown).content, "", markdown ].join("\n"); | ||||
|             } | ||||
|             this.push(header); | ||||
|             this.push(marked(markdown)); | ||||
|             this.push(footer); | ||||
|             done(); | ||||
|         }; | ||||
|         return transform; | ||||
|     } | ||||
|  | ||||
|     // Custom renderer for marked; converts relative links from md to html, | ||||
|     // and makes headings linkable. | ||||
|     function CustomRenderer() { | ||||
|         var renderer = new marked.Renderer(), | ||||
|             customRenderer = Object.create(renderer); | ||||
|         customRenderer.heading = function (text, level) { | ||||
|             var escapedText = (text || "").trim().toLowerCase().replace(/\W/g, "-"), | ||||
|                 aOpen = "<a name=\"" + escapedText + "\" href=\"#" + escapedText + "\">", | ||||
|                 aClose = "</a>"; | ||||
|             return aOpen + renderer.heading.apply(renderer, arguments) + aClose; | ||||
|         }; | ||||
|         // Change links to .md files to .html | ||||
|         customRenderer.link = function (href, title, text) { | ||||
|             // ...but only if they look like relative paths | ||||
|             return (href || "").indexOf(":") === -1 && href[0] !== "/" ? | ||||
|                     renderer.link(href.replace(/\.md/, ".html"), title, text) : | ||||
|                     renderer.link.apply(renderer, arguments); | ||||
|         }; | ||||
|         return customRenderer; | ||||
|     } | ||||
|  | ||||
|     options['in'] = options['in'] || options.i; | ||||
|     options.out = options.out || options.o; | ||||
|  | ||||
|     marked.setOptions({ | ||||
|         renderer: new CustomRenderer(), | ||||
|         gfm: true, | ||||
|         tables: true, | ||||
|         breaks: false, | ||||
|         pedantic: false, | ||||
|         sanitize: true, | ||||
|         smartLists: true, | ||||
|         smartypants: false | ||||
|     }); | ||||
|  | ||||
|     // Convert all markdown files. | ||||
|     // First, pull out nomnoml diagrams. | ||||
|     // Then, convert remaining Markdown to HTML. | ||||
|     glob(options['in'] + "/**/*.md", {}, function (err, files) { | ||||
|         files.forEach(function (file) { | ||||
|             var destination = file.replace(options['in'], options.out) | ||||
|                 .replace(/md$/, "html"), | ||||
|                 destPath = path.dirname(destination), | ||||
|                 prefix = path.basename(destination).replace(/\.html$/, ""), | ||||
|                 //Determine whether TOC should be rendered for this file based | ||||
|                 //on regex provided as command line option | ||||
|                 renderTOC = file.match(options['suppress-toc'] || "") === null; | ||||
|  | ||||
|             mkdirp(destPath, function (err) { | ||||
|                 fs.createReadStream(file, { encoding: 'utf8' }) | ||||
|                     .pipe(split()) | ||||
|                     .pipe(nomnomlifier(destPath, prefix)) | ||||
|                     .pipe(gfmifier(renderTOC)) | ||||
|                     .pipe(fs.createWriteStream(destination, { | ||||
|                         encoding: 'utf8' | ||||
|                     })); | ||||
|             }); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     // Also copy over all HTML, CSS, or PNG files | ||||
|     glob(options['in'] + "/**/*.@(html|css|png)", {}, function (err, files) { | ||||
|         files.forEach(function (file) { | ||||
|             var destination = file.replace(options['in'], options.out), | ||||
|                 destPath = path.dirname(destination), | ||||
|                 streamOptions = {}; | ||||
|             if (file.match(/png$/)) { | ||||
|                 streamOptions.encoding = null; | ||||
|             } else { | ||||
|                 streamOptions.encoding = 'utf8'; | ||||
|             } | ||||
|  | ||||
|             mkdirp(destPath, function (err) { | ||||
|                 fs.createReadStream(file, streamOptions) | ||||
|                     .pipe(fs.createWriteStream(destination, streamOptions)); | ||||
|             }); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
| }()); | ||||
							
								
								
									
										9
									
								
								docs/header.html
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,9 @@ | ||||
| <html> | ||||
|     <head> | ||||
|         <link rel="stylesheet" | ||||
|               href="//nasa.github.io/openmct/static/res/css/styles.css"> | ||||
|         <link rel="stylesheet" | ||||
|               href="//nasa.github.io/openmct/static/res/css/documentation.css"> | ||||
|     </head> | ||||
|     <body> | ||||
|  | ||||
| @@ -15,8 +15,8 @@ | ||||
|  | ||||
| ## Sections | ||||
|   | ||||
|  * The [API](api/) uses inline documentation  | ||||
|  using [TypeScript](https://www.typescriptlang.org) and some legacy [JSDoc](https://jsdoc.app/). It describes the JavaScript objects and | ||||
|  * The [API](api/) document is generated from inline documentation  | ||||
|  using [JSDoc](http://usejsdoc.org/), and describes the JavaScript objects and | ||||
|  functions that make up the software platform. | ||||
|  | ||||
|  * The [Development Process](process/) document describes the | ||||
|   | ||||
| @@ -2,5 +2,4 @@ version: 2 | ||||
| snapshot: | ||||
|   widths: [1024, 2000] | ||||
|   min-height: 1440 # px | ||||
| discovery: | ||||
|   concurrency: 2 # https://github.com/percy/cli/discussions/1067 | ||||
|    | ||||
|   | ||||
							
								
								
									
										131
									
								
								e2e/README.md
									
									
									
									
									
								
							
							
						
						| @@ -70,88 +70,83 @@ The bulk of our e2e coverage lies in "functional" test coverage which verifies t | ||||
| Visual Testing is an essential part of our e2e strategy as it ensures that the application _appears_ correctly to a user while it compliments the functional e2e suite. It would be impractical to make thousands of assertions functional assertions on the look and feel of the application. Visual testing is interested in getting the DOM into a specified state and then comparing that it has not changed against a baseline. | ||||
|  | ||||
| For a better understanding of the visual issues which affect Open MCT, please see our bug tracker with the `label:visual` filter applied [here](https://github.com/nasa/openmct/issues?q=label%3Abug%3Avisual+) | ||||
| To read about how to write a good visual test, please see [How to write a great Visual Test](#how-to-write-a-great-visual-test). | ||||
| To read about how to write a good visual test, please see [How to write a great Visual Test](#how-to-write-a-great-visual-test).  | ||||
|  | ||||
| `npm run test:e2e:visual` will run all of the visual tests against a local instance of Open MCT. If no `PERCY_TOKEN` API key is found in the terminal or command line environment variables, no visual comparisons will be made. | ||||
|  | ||||
| #### Percy.io | ||||
|  | ||||
| To make this possible, we're leveraging a 3rd party service, [Percy](https://percy.io/). This service maintains a copy of all changes, users, scm-metadata, and baselines to verify that the application looks and feels the same _unless approved by a Open MCT developer_. To request a Percy API token, please reach out to the Open MCT Dev team on GitHub. For more information, please see the official [Percy documentation](https://docs.percy.io/docs/visual-testing-basics) | ||||
|  | ||||
| ### (Advanced) Snapshot Testing | ||||
|  | ||||
| Snapshot testing is very similar to visual testing but allows us to be more precise in detecting change without relying on a 3rd party service. Unfortuantely, this precision requires advanced test setup and teardown and so we're using this pattern as a last resort. | ||||
|  | ||||
| To give an example, if a _single_ visual test assertion for an Overlay plot is run through multiple DOM rendering engines at various viewports to see how the Plot looks. If that same test were run as a snapshot test, it could only be executed against a single browser, on a single platform (ubuntu docker container). | ||||
| To give an example, if a *single* visual test assertion for an Overlay plot is run through multiple DOM rendering engines at various viewports to see how the Plot looks. If that same test were run as a snapshot test, it could only be executed against a single browser, on a single platform (ubuntu docker container). | ||||
|  | ||||
| Read more about [Playwright Snapshots](https://playwright.dev/docs/test-snapshots) | ||||
|  | ||||
| #### Open MCT's implementation | ||||
| Open MCT's implementation | ||||
| -Our Snapshot tests receive a @snapshot tag. | ||||
| -Snapshots need to be executed within the official playwright container to ensure we're using the exact rendering platform in CI and locally | ||||
|  | ||||
| - Our Snapshot tests receive a `@snapshot` tag. | ||||
| - Snapshots need to be executed within the official Playwright container to ensure we're using the exact rendering platform in CI and locally. | ||||
|  | ||||
| ```sh | ||||
| ``` | ||||
| docker run --rm --network host -v $(pwd):/work/ -w /work/ -it mcr.microsoft.com/playwright:[GET THIS VERSION FROM OUR CIRCLECI CONFIG FILE]-focal /bin/bash | ||||
| npm install | ||||
| npx playwright test --config=e2e/playwright-ci.config.js --project=chrome --grep @snapshot | ||||
| ``` | ||||
|  | ||||
| ### (WIP) Updating Snapshots | ||||
|  | ||||
| When the `@snapshot` tests fail, they will need to be evaluated to see if the failure is an acceptable change or | ||||
| (WIP) Updating Snapshots | ||||
| When the @snapshot tests fail, they will need to be evaluated to see if the failure is an acceptable change or  | ||||
|  | ||||
| ## Performance Testing | ||||
|  | ||||
| The open source performance tests function mostly as a contract for the locator logic, functionality, and assumptions will work in our downstream, closed source test suites. | ||||
|  | ||||
| They're found under `./e2e/tests/performance` and are to be executed with the following npm script: | ||||
| They're found in the `/e2e/tests/performance` repo and are to be executed with the following npm script: | ||||
|  | ||||
| `npm run test:perf` | ||||
| ```npm run test:perf``` | ||||
|  | ||||
| These tests are expected to become blocking and gating with assertions as we extend the capabilities of Playwright. | ||||
| These tests are expected to become blocking and gating with assertions as we extend the capabilities of playwright. | ||||
|  | ||||
| ## Test Architecture and CI | ||||
|  | ||||
| ### Architecture (TODO) | ||||
|  | ||||
|  | ||||
|  | ||||
| ### File Structure | ||||
|  | ||||
| Our file structure follows the type of type of testing being excercised at the e2e layer and files containing test suites which matcher application behavior or our `src` and `example` layout. This area is not well refined as we figure out what works best for closed source and downstream projects. This may change altogether if we move `e2e` to it's own npm package. | ||||
|  | ||||
| - `./helper` - contains helper functions or scripts which are leveraged directly within the testsuites. i.e. non-default plugin scripts injected into DOM | ||||
| - `./test-data` - contains test data which is leveraged or generated in the functional, performance, or visual test suites. i.e. localStorage data | ||||
| - `./tests/functional` - the bulk of the tests are contained within this folder to verify the functionality of open mct | ||||
| - `./tests/functional/example/` - tests which specifically verify the example plugins | ||||
| - `./tests/functional/plugins/` - tests which loosely test each plugin. This folder is the most likely to change. Note: some @snapshot tests are still contained within this structure | ||||
| - `./tests/framework/` - tests which verify that our testframework functionality and assumptions will continue to work based on further refactoring or playwright version changes | ||||
| - `./tests/performance/` - performance tests | ||||
| - `./tests/visual/` - Visual tests | ||||
| - `./appActions.js` - Contains common fixtures which can be leveraged by testcase authors to quickly move through the application when writing new tests. | ||||
| - `./baseFixture.js` - Contains base fixtures which only extend default `@playwright/test` functionality. The goal is to remove these fixtures as native Playwright APIs improve. | ||||
|  - `./helper` - contains helper functions or scripts which are leveraged directly within the testsuites. i.e. non-default plugin scripts injected into DOM | ||||
|  - `./test-data` - contains test data which is leveraged or generated in the functional, performance, or visual test suites. i.e. localStorage data | ||||
|  - `./tests/functional` - the bulk of the tests are contained within this folder to verify the functionality of open mct | ||||
|  - `./tests/functional/example/` - tests which specifically verify the example plugins | ||||
|  - `./tests/functional/plugins/` - tests which loosely test each plugin. This folder is the most likely to change. Note: some @snapshot tests are still contained within this structure | ||||
|  - `./tests/framework/` - tests which verify that our testframework functionality and assumptions will continue to work based on further refactoring or playwright version changes | ||||
|  - `./tests/performance/` - performance tests | ||||
|  - `./tests/visual/` - Visual tests | ||||
|  - `./appActions.js` - Contains common fixtures which can be leveraged by testcase authors to quickly move through the application when writing new tests. | ||||
|  - `./baseFixture.js` - Contains base fixtures which only extend default `@playwright/test` functionality. The goal is to remove these fixtures as native Playwright APIs improve. | ||||
|  | ||||
| Our functional tests end in `*.e2e.spec.js`, visual tests in `*.visual.spec.js` and performance tests in `*.perf.spec.js`. | ||||
| Our functional tests end in `*.e2e.spec.js`, visual tests in `*.visual.spec.js` and performance tests in `*.perf.spec.js`.  | ||||
|  | ||||
| ### Configuration | ||||
|  | ||||
| Where possible, we try to run Open MCT without modification or configuration change so that the Open MCT doesn't fail exclusively in "test mode" or in "production mode". | ||||
|  | ||||
| Open MCT is leveraging the [config file](https://playwright.dev/docs/test-configuration) pattern to describe the capabilities of Open MCT e2e _where_ it's run | ||||
|  | ||||
| - `./playwright-ci.config.js` - Used when running in CI or to debug CI issues locally | ||||
| - `./playwright-local.config.js` - Used when running locally | ||||
| - `./playwright-performance.config.js` - Used when running performance tests in CI or locally | ||||
| - `./playwright-visual.config.js` - Used to run the visual tests in CI or locally | ||||
|  | ||||
| #### Test Tags | ||||
|  | ||||
| Test tags are a great way of organizing tests outside of a file structure. To learn more see the official documentation [here](https://playwright.dev/docs/test-annotations#tag-tests). | ||||
|  | ||||
| Test tags are a great way of organizing tests outside of a file structure. To learn more see the official documentation [here](https://playwright.dev/docs/test-annotations#tag-tests) | ||||
| Current list of test tags: | ||||
|  | ||||
| - `@ipad` - Test case or test suite is compatible with Playwright's iPad support and Open MCT's read-only mobile view (i.e. no Create button). | ||||
| - `@gds` - Denotes a GDS Test Case used in the VIPER Mission. | ||||
| - `@addInit` - Initializes the browser with an injected and artificial state. Useful for loading non-default plugins. Likely will not work outside of `npm start`. | ||||
| - `@addInit` - Initializes the browser with an injected and artificial state. Useful for loading non-default plugins. Likely will not work outside of app.js. | ||||
| - `@localStorage` - Captures or generates session storage to manipulate browser state. Useful for excluding in tests which require a persistent backend (i.e. CouchDB). | ||||
| - `@snapshot` - Uses Playwright's snapshot functionality to record a copy of the DOM for direct comparison. Must be run inside of the playwright container. | ||||
| - `@unstable` - A new test or test which is known to be flaky. | ||||
| @@ -159,42 +154,34 @@ Current list of test tags: | ||||
|  | ||||
| ### Continuous Integration | ||||
|  | ||||
| The cheapest time to catch a bug is pre-merge. Unfortuantely, this is the most expensive time to run all of the tests since each merge event can consist of hundreds of commits. For this reason, we're selective in _what we run_ as much as _when we run it_. | ||||
| The cheapest time to catch a bug is Pre-merge. Unfortuantely, this is the most expensive time to run all of the tests since each Merge event can consistent of hundreds of commits. For this reason, we're selective in _what_ we run as much as _when_ we run it. | ||||
|  | ||||
| We leverage CircleCI to run tests against each commit and inject the Test Reports which are generated by Playwright so that they team can keep track of flaky and [historical test trends](https://app.circleci.com/insights/github/nasa/openmct/workflows/overall-circleci-commit-status/tests?branch=master&reporting-window=last-30-days) | ||||
| We leverage CircleCI to run tests against each commit and inject the Test Reports which are generated by playwright so that they team can keep track of flaky and [historical Test Trends](https://app.circleci.com/insights/github/nasa/openmct/workflows/overall-circleci-commit-status/tests?branch=master&reporting-window=last-30-days) | ||||
|  | ||||
| We leverage Github Actions / Workflows to execute tests as it gives us the ability to run against multiple operating systems with greater control over git event triggers (i.e. Run on a PR Comment event). | ||||
|  | ||||
| Our CI environment consists of 3 main modes of operation: | ||||
|  | ||||
| #### 1. Per-Commit Testing | ||||
|  | ||||
| CircleCI | ||||
|  | ||||
| - Stable e2e tests against ubuntu and chrome | ||||
| - Performance tests against ubuntu and chrome | ||||
| - e2e tests are linted | ||||
|  | ||||
| #### 2. Per-Merge Testing | ||||
|  | ||||
| Github Actions / Workflow | ||||
|  | ||||
| - Full suite against all browsers/projects. Triggered with Github Label Event 'pr:e2e' | ||||
| - Visual Tests. Triggered with Github Label Event 'pr:visual' | ||||
|  | ||||
| #### 3. Scheduled / Batch Testing | ||||
|  | ||||
| Nightly Testing in Circle CI | ||||
|  | ||||
| - Full e2e suite against ubuntu and chrome | ||||
| - Performance tests against ubuntu and chrome | ||||
|  | ||||
| Github Actions / Workflow | ||||
|  | ||||
| - Visual Test baseline generation. | ||||
|  | ||||
| #### Parallelism and Fast Feedback | ||||
|  | ||||
| In order to provide fast feedback in the Per-Commit context, we try to keep total test feedback at 5 minutes or less. That is to say, A developer should have a pass/fail result in under 5 minutes. | ||||
|  | ||||
| Playwright has native support for semi-intelligent sharding. Read about it [here](https://playwright.dev/docs/test-parallel#shard-tests-between-multiple-machines). | ||||
| @@ -206,7 +193,6 @@ In addition to the Parallelization of Test Runners (Sharding), we're also runnin | ||||
| So for every commit, Playwright is effectively running 4 x 2 concurrent browsercontexts to keep the overall runtime to a miminum. | ||||
|  | ||||
| At the same time, we don't want to waste CI resources on parallel runs, so we've configured each shard to fail after 5 test failures. Test failure logs are recorded and stored to allow fast triage. | ||||
|  | ||||
| #### Test Promotion | ||||
|  | ||||
| In order to maintain fast and reliable feedback, tests go through a promotion process. All new test cases or test suites must be labeled with the `@unstable` annotation. The Open MCT dev team runs these unstable tests in our private repos to ensure they work downstream and are reliable. | ||||
| @@ -214,66 +200,24 @@ In order to maintain fast and reliable feedback, tests go through a promotion pr | ||||
| To run the stable tests, use the ```npm run test:e2e:stable``` command. To run the new and flaky tests, use the ```npm run test:e2e:unstable``` command. | ||||
|  | ||||
| A testcase and testsuite are to be unmarked as @unstable when: | ||||
|  | ||||
| 1. They run as part of "full" run 5 times without failure. | ||||
| 2. They've been by a Open MCT Developer 5 times in the closed source repo without failure. | ||||
|  | ||||
| ### Cross-browser and Cross-operating system | ||||
|  | ||||
| #### **What's supported:** | ||||
|  | ||||
| We are leveraging the `browserslist` project to declare our supported list of browsers. | ||||
|  | ||||
| #### **Where it's tested:** | ||||
|  | ||||
| We lint on `browserslist` to ensure that we're not implementing deprecated browser APIs and are aware of browser API improvements over time. | ||||
|  | ||||
| We also have the need to execute our e2e tests across this published list of browsers. Our browsers and browser version matrix is found inside of our `./playwright-*.config.js`, but mostly follows in order of bleeding edge to stable: | ||||
|  | ||||
| - `playwright-chromium channel:beta` | ||||
|   - A beta version of Chromium from official chromium channels. As close to the bleeding edge as we can get. | ||||
| - `playwright-chromium` | ||||
|   - A stable version of Chromium from the official chromium channels. This is always at least 1 version ahead of desktop chrome. | ||||
| - `playwright-chrome` | ||||
|   - The stable channel of Chrome from the official chrome channels. This is always 2 versions behind chromium. | ||||
|  | ||||
| #### **Mobile** | ||||
|  | ||||
| We have the Mission-need to support iPad. To run our iPad suite, please see our `playwright-*.config.js` with the 'iPad' project. | ||||
|  | ||||
| #### **Skipping or executing tests based on browser, os, and/os browser version:** | ||||
|  | ||||
| Conditionally skipping tests based on browser (**RECOMMENDED**): | ||||
|  | ||||
| ```js | ||||
| test('Can adjust image brightness/contrast by dragging the sliders', async ({ page, browserName }) => { | ||||
|   // eslint-disable-next-line playwright/no-skipped-test | ||||
|   test.skip(browserName === 'firefox', 'This test needs to be updated to work with firefox'); | ||||
|  | ||||
|   // ... | ||||
| ``` | ||||
|  | ||||
| Conditionally skipping tests based on OS: | ||||
|  | ||||
| ```js | ||||
| test('Can adjust image brightness/contrast by dragging the sliders', async ({ page }) => { | ||||
|   // eslint-disable-next-line playwright/no-skipped-test | ||||
|   test.skip(process.platform === 'darwin', 'This test needs to be updated to work with MacOS'); | ||||
|  | ||||
|   // ... | ||||
| ``` | ||||
|  | ||||
| Skipping based on browser version (Rarely used): <https://github.com/microsoft/playwright/discussions/17318> | ||||
| - Where is it tested | ||||
| - What's supported | ||||
| - Mobile | ||||
|  | ||||
| ## Test Design, Best Practices, and Tips & Tricks | ||||
|  | ||||
| ### Test Design (TODO) | ||||
|  | ||||
| - How to make tests robust to function in other contexts (VISTA, VIPER, etc.) | ||||
|   - Leverage the use of `appActions.js` methods such as `createDomainObjectWithDefaults()` | ||||
|   - Leverage the use of appActions.js like getOrCreateDomainObject | ||||
| - How to make tests faster and more resilient | ||||
|   - When possible, navigate directly by URL | ||||
|   - Leverage `await page.goto('./', { waitUntil: 'networkidle' });` | ||||
|   - Leverage ```await page.goto('/', { waitUntil: 'networkidle' });``` | ||||
|   - Avoid repeated setup to test to test a single assertion. Write longer tests with multiple soft assertions. | ||||
|  | ||||
| ### How to write a great test (TODO) | ||||
| @@ -296,7 +240,6 @@ There are instances where multiple browser pages will need to be opened to verif | ||||
| Test Reporting is done through official Playwright reporters and the CI Systems which execute them. | ||||
|  | ||||
| We leverage the following official Playwright reporters: | ||||
|  | ||||
| - HTML | ||||
| - junit | ||||
| - github annotations | ||||
| @@ -306,7 +249,6 @@ We leverage the following official Playwright reporters: | ||||
| When running the tests locally with the `npm run test:local` command, the html report will open automatically on failure. Inside this HTML report will be a complete summary of the finished tests. If the tests failed, you'll see embedded links to screenshot failure, execution logs, and the Tracefile. | ||||
|  | ||||
| When looking at the reports run in CI, you'll leverage this same HTML Report which is hosted either in CircleCI or Github Actions as a build artifact. | ||||
|  | ||||
| ### e2e Code Coverage | ||||
|  | ||||
| Code coverage is collected during test execution using our custom [baseFixture](./baseFixtures.js). The raw coverage files are stored in a `.nyc_report` directory to be converted into a lcov file with the following [nyc](https://github.com/istanbuljs/nyc) command: | ||||
| @@ -315,14 +257,13 @@ Code coverage is collected during test execution using our custom [baseFixture]( | ||||
|  | ||||
| At this point, the nyc linecov report can be published to [codecov.io](https://about.codecov.io/) with the following command: | ||||
|  | ||||
| ```npm run cov:e2e:stable:publish``` for the stable suite running in ubuntu. | ||||
| or | ||||
| ```npm run cov:e2e:stable:publish``` for the stable suite running in ubuntu.  | ||||
| or  | ||||
| ```npm run cov:e2e:full:publish``` for the full suite running against all available platforms. | ||||
|  | ||||
| Codecov.io will combine each of the above commands with [Codecov.io Flags](https://docs.codecov.com/docs/flags). Effectively, this allows us to combine multiple reports which are run at various stages of our CI Pipeline or run as part of a parallel process. | ||||
|  | ||||
| This e2e coverage is combined with our unit test report to give a comprehensive (if flawed) view of line coverage. | ||||
|  | ||||
| ## Other | ||||
|  | ||||
| ### About e2e testing | ||||
| @@ -375,6 +316,6 @@ A single e2e test in Open MCT is extended to run: | ||||
|  | ||||
| - Why is my test failing on CI and not locally? | ||||
| - How can I view the failing tests on CI? | ||||
| - Tests won't start because 'Error: <http://localhost:8080/># is already used...' | ||||
| - Tests won't start because 'Error: http://localhost:8080/# is already used...' | ||||
| This error will appear when running the tests locally. Sometimes, the webserver is left in an orphaned state and needs to be cleaned up. To clear up the orphaned webserver, execute the following from your Terminal: | ||||
| ```lsof -n -i4TCP:8080 | awk '{print$2}' | tail -1 | xargs kill -9``` | ||||
|   | ||||
| @@ -102,17 +102,6 @@ async function createDomainObjectWithDefaults(page, { type, name, parent = 'mine | ||||
|     }; | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  * @param {string} name | ||||
|  */ | ||||
| async function expandTreePaneItemByName(page, name) { | ||||
|     const treePane = page.locator('#tree-pane'); | ||||
|     const treeItem = treePane.locator(`role=treeitem[expanded=false][name=/${name}/]`); | ||||
|     const expandTriangle = treeItem.locator('.c-disclosure-triangle'); | ||||
|     await expandTriangle.click(); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Create a Plan object from JSON with the provided options. | ||||
|  * @param {import('@playwright/test').Page} page | ||||
| @@ -225,14 +214,15 @@ async function getHashUrlToDomainObject(page, uuid) { | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Utilizes the OpenMCT API to detect if the UI is in Edit mode. | ||||
|  * Utilizes the OpenMCT API to detect if the given object has an active transaction (is in Edit mode). | ||||
|  * @private | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  * @return {Promise<boolean>} true if the Open MCT is in Edit Mode | ||||
|  * @param {string | import('../src/api/objects/ObjectAPI').Identifier} identifier | ||||
|  * @return {Promise<boolean>} true if the object has an active transaction, false otherwise | ||||
|  */ | ||||
| async function _isInEditMode(page, identifier) { | ||||
|     // eslint-disable-next-line no-return-await | ||||
|     return await page.evaluate(() => window.openmct.editor.isEditing()); | ||||
|     return await page.evaluate((objectIdentifier) => window.openmct.objects.isTransactionActive(objectIdentifier), identifier); | ||||
| } | ||||
|  | ||||
| /** | ||||
| @@ -323,7 +313,6 @@ async function setEndOffset(page, offset) { | ||||
| // eslint-disable-next-line no-undef | ||||
| module.exports = { | ||||
|     createDomainObjectWithDefaults, | ||||
|     expandTreePaneItemByName, | ||||
|     createPlanFromJSON, | ||||
|     openObjectTreeContextMenu, | ||||
|     getHashUrlToDomainObject, | ||||
|   | ||||
| @@ -1,65 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| const NOTEBOOK_DROP_AREA = '.c-notebook__drag-area'; | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function enterTextEntry(page, text) { | ||||
|     // Click .c-notebook__drag-area | ||||
|     await page.locator(NOTEBOOK_DROP_AREA).click(); | ||||
|  | ||||
|     // enter text | ||||
|     await page.locator('div.c-ne__text').click(); | ||||
|     await page.locator('div.c-ne__text').fill(text); | ||||
|     await page.locator('div.c-ne__text').press('Enter'); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function dragAndDropEmbed(page, myItemsFolderName) { | ||||
|     // Click button:has-text("Create") | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     // Click li:has-text("Sine Wave Generator") | ||||
|     await page.locator('li:has-text("Sine Wave Generator")').click(); | ||||
|     // Click form[name="mctForm"] >> text=My Items | ||||
|     await page.locator(`form[name="mctForm"] >> text=${myItemsFolderName}`).click(); | ||||
|     // Click text=OK | ||||
|     await page.locator('text=OK').click(); | ||||
|     // Click text=Open MCT My Items >> span >> nth=3 | ||||
|     await page.locator(`text=Open MCT ${myItemsFolderName} >> span`).nth(3).click(); | ||||
|     // Click text=Unnamed CUSTOM_NAME | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         page.locator('text=Unnamed CUSTOM_NAME').click() | ||||
|     ]); | ||||
|  | ||||
|     await page.dragAndDrop('text=UNNAMED SINE WAVE GENERATOR', NOTEBOOK_DROP_AREA); | ||||
| } | ||||
|  | ||||
| // eslint-disable-next-line no-undef | ||||
| module.exports = { | ||||
|     enterTextEntry, | ||||
|     dragAndDropEmbed | ||||
| }; | ||||
| @@ -14,7 +14,7 @@ const config = { | ||||
|     testIgnore: '**/*.perf.spec.js', //Ignore performance tests and define in playwright-perfromance.config.js | ||||
|     timeout: 60 * 1000, | ||||
|     webServer: { | ||||
|         command: 'npm run start:coverage', | ||||
|         command: 'cross-env NODE_ENV=test npm run start', | ||||
|         url: 'http://localhost:8080/#', | ||||
|         timeout: 200 * 1000, | ||||
|         reuseExistingServer: false | ||||
|   | ||||
| @@ -12,7 +12,10 @@ const config = { | ||||
|     testIgnore: '**/*.perf.spec.js', | ||||
|     timeout: 30 * 1000, | ||||
|     webServer: { | ||||
|         command: 'npm run start:coverage', | ||||
|         env: { | ||||
|             NODE_ENV: 'test' | ||||
|         }, | ||||
|         command: 'npm run start', | ||||
|         url: 'http://localhost:8080/#', | ||||
|         timeout: 120 * 1000, | ||||
|         reuseExistingServer: true | ||||
|   | ||||
| @@ -6,12 +6,12 @@ const CI = process.env.CI === 'true'; | ||||
|  | ||||
| /** @type {import('@playwright/test').PlaywrightTestConfig} */ | ||||
| const config = { | ||||
|     retries: 1, //Only for debugging purposes for trace: 'on-first-retry' | ||||
|     retries: 1, //Only for debugging purposes because trace is enabled only on first retry | ||||
|     testDir: 'tests/performance/', | ||||
|     timeout: 60 * 1000, | ||||
|     workers: 1, //Only run in serial with 1 worker | ||||
|     webServer: { | ||||
|         command: 'npm run start', //coverage not generated | ||||
|         command: 'cross-env NODE_ENV=test npm run start', | ||||
|         url: 'http://localhost:8080/#', | ||||
|         timeout: 200 * 1000, | ||||
|         reuseExistingServer: !CI | ||||
|   | ||||
| @@ -4,13 +4,13 @@ | ||||
|  | ||||
| /** @type {import('@playwright/test').PlaywrightTestConfig<{ theme: string }>} */ | ||||
| const config = { | ||||
|     retries: 0, // Visual tests should never retry due to snapshot comparison errors. Leaving as a shim | ||||
|     retries: 0, // visual tests should never retry due to snapshot comparison errors | ||||
|     testDir: 'tests/visual', | ||||
|     testMatch: '**/*.visual.spec.js', // only run visual tests | ||||
|     timeout: 60 * 1000, | ||||
|     workers: 1, //Lower stress on Circle CI Agent for Visual tests https://github.com/percy/cli/discussions/1067 | ||||
|     timeout: 90 * 1000, | ||||
|     workers: 1, //Limit to 1 for CircleCI Agent | ||||
|     webServer: { | ||||
|         command: 'npm run start:coverage', | ||||
|         command: 'cross-env NODE_ENV=test npm run start', | ||||
|         url: 'http://localhost:8080/#', | ||||
|         timeout: 200 * 1000, | ||||
|         reuseExistingServer: !process.env.CI | ||||
| @@ -19,8 +19,8 @@ const config = { | ||||
|         baseURL: 'http://localhost:8080/', | ||||
|         headless: true, // this needs to remain headless to avoid visual changes due to GPU rendering in headed browsers | ||||
|         ignoreHTTPSErrors: true, | ||||
|         screenshot: 'only-on-failure', | ||||
|         trace: 'on-first-retry', | ||||
|         screenshot: 'on', | ||||
|         trace: 'on', | ||||
|         video: 'off' | ||||
|     }, | ||||
|     projects: [ | ||||
| @@ -31,7 +31,7 @@ const config = { | ||||
|             } | ||||
|         }, | ||||
|         { | ||||
|             name: 'chrome-snow-theme', //Runs the same visual tests but with snow-theme enabled | ||||
|             name: 'chrome-snow-theme', | ||||
|             use: { | ||||
|                 browserName: 'chromium', | ||||
|                 theme: 'snow' | ||||
|   | ||||
| @@ -23,7 +23,7 @@ | ||||
| /* | ||||
| This test suite is dedicated to testing our use of the playwright framework as it | ||||
| relates to how we've extended it (i.e. ./e2e/baseFixtures.js) and assumptions made in our dev environment | ||||
| (`npm start` and ./e2e/webpack-dev-middleware.js) | ||||
| (app.js and ./e2e/webpack-dev-middleware.js) | ||||
| */ | ||||
|  | ||||
| const { test } = require('../../baseFixtures.js'); | ||||
|   | ||||
| @@ -21,11 +21,12 @@ | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /* | ||||
| * This test suite template is to be used when creating new test suites. It will be kept up to date with the latest improvements | ||||
| * This test suite template is to be used when creating new testsuites. It will be kept up to date with the latest improvements | ||||
| * made by the Open MCT team. It will also follow our best pratices as those evolve. Please use this structure as a _reference_ and clear | ||||
| * or update any references when creating a new test suite! | ||||
| * | ||||
| * To illustrate current best practices, we've included a mocked up test suite for Renaming a Timer domain object. | ||||
| * To illustrate current best practices, we've included a mocked up test suite for Renaming a Timer domain object. In this example | ||||
| * this test suite should be cloned and renamed as /e2e/tests/plugins/timer/renameTimer.e2e.spec.js | ||||
| * | ||||
| * Demonstrated: | ||||
| * - Using appActions to leverage existing functions | ||||
| @@ -42,73 +43,55 @@ | ||||
| *    -> test2 | ||||
| *    -> test3(stub) | ||||
| * 4. Any custom functions | ||||
| * | ||||
| */ | ||||
|  | ||||
| // Structure: Some standard Imports. Please update the required pathing. | ||||
| //Structure: Some standard Imports. Please update the required pathing | ||||
| const { test, expect } = require('../../baseFixtures'); | ||||
| const { createDomainObjectWithDefaults } = require('../../appActions'); | ||||
|  | ||||
| /** | ||||
|  * Structure: | ||||
|  *  Try to keep a single describe block per logical groups of tests. | ||||
|  *  If your test runtime exceeds 5 minutes or 500 lines, it's likely that it will need to be split. | ||||
|  * | ||||
|  * Annotations: | ||||
|  *  Please use the @unstable tag at the end of the test title so that our automation can pick it up | ||||
|  *  as a part of our test promotion pipeline. | ||||
|  */ | ||||
| // Structure: Try to keep a single describe block per logical groups of tests. If your test runtime exceeds 5 minutes or 500 lines, it's likely that it will need to be split. | ||||
| // Annotations: Please use the @unstable tag so that our automation can pick it up as a part of our test promotion pipeline. | ||||
| test.describe('Renaming Timer Object', () => { | ||||
|     // Top-level declaration of the Timer object created in beforeEach(). | ||||
|     // We can then use this throughout the entire test suite. | ||||
|     let timer; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         // Open a browser, navigate to the main page, and wait until all network events to resolve | ||||
|     //Create a testcase name which will be obvious when it fails in CI | ||||
|     test('Can create a new Timer object and rename it from actions Menu', async ({ page }) => { | ||||
|         //Open a browser, navigate to the main page, and wait until all networkevents to resolve | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|         //We provide some helper functions in appActions like createDomainObjectWithDefaults. This example will create a Timer object | ||||
|         await createDomainObjectWithDefaults(page, { type: 'Timer' }); | ||||
|         //Assert the object to be created and check it's name in the title | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Timer'); | ||||
|  | ||||
|         // We provide some helper functions in appActions like `createDomainObjectWithDefaults()`. | ||||
|         // This example will create a Timer object with default properties, under the root folder: | ||||
|         timer = await createDomainObjectWithDefaults(page, { type: 'Timer' }); | ||||
|  | ||||
|         // Assert the object to be created and check its name in the title | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText(timer.name); | ||||
|     }); | ||||
|  | ||||
|     /** | ||||
|      * Make sure to use testcase names which are descriptive and easy to understand. | ||||
|      * A good testcase name concisely describes the test's goal(s) and should give | ||||
|      * some hint as to what went wrong if the test fails. | ||||
|      */ | ||||
|     test('An existing Timer object can be renamed via the 3dot actions menu', async ({ page }) => { | ||||
|         const newObjectName = "Renamed Timer"; | ||||
|         //We've created an example of a shared function which pases the page and newObjectName values | ||||
|         await renameObjectFrom3DotMenu(page, newObjectName); | ||||
|  | ||||
|         // We've created an example of a shared function which pases the page and newObjectName values | ||||
|         await renameTimerFrom3DotMenu(page, timer.url, newObjectName); | ||||
|  | ||||
|         // Assert that the name has changed in the browser bar to the value we assigned above | ||||
|         //Assert that the name has changed in the browser bar to the value we assigned above | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText(newObjectName); | ||||
|     }); | ||||
|  | ||||
|     test('An existing Timer object can be renamed twice', async ({ page }) => { | ||||
|         //Open a browser, navigate to the main page, and wait until all networkevents to resolve | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|         //We provide some helper functions in appActions like createDomainObjectWithDefaults. This example will create a Timer object | ||||
|         await createDomainObjectWithDefaults(page, { type: 'Timer' }); | ||||
|         //Expect the object to be created and check it's name in the title | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Timer'); | ||||
|  | ||||
|         const newObjectName = "Renamed Timer"; | ||||
|         const newObjectName2 = "Re-Renamed Timer"; | ||||
|         //We've created an example of a shared function which pases the page and newObjectName values | ||||
|         await renameObjectFrom3DotMenu(page, newObjectName); | ||||
|  | ||||
|         await renameTimerFrom3DotMenu(page, timer.url, newObjectName); | ||||
|  | ||||
|         // Assert that the name has changed in the browser bar to the value we assigned above | ||||
|         //Assert that the name has changed in the browser bar to the value we assigned above | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText(newObjectName); | ||||
|  | ||||
|         // Rename the Timer object again | ||||
|         await renameTimerFrom3DotMenu(page, timer.url, newObjectName2); | ||||
|         await renameObjectFrom3DotMenu(page, newObjectName2); | ||||
|  | ||||
|         // Assert that the name has changed in the browser bar to the second value | ||||
|         //Assert that the name has changed in the browser bar to the second value | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText(newObjectName2); | ||||
|     }); | ||||
|  | ||||
|     /** | ||||
|      * If you run out of time to write new tests, please stub in the missing tests | ||||
|      * in-place with a test.fixme and BDD-style test steps. | ||||
|      * Someone will carry the baton! | ||||
|      */ | ||||
|     //If you run out of time to write new tests, please stub in the missing tests in place with a test.fixme and BDD-style test steps. Someone will carry the baton! | ||||
|     test.fixme('Can Rename Timer Object from Tree', async ({ page }) => { | ||||
|         //Create a new object | ||||
|         //Copy this object | ||||
| @@ -117,30 +100,22 @@ test.describe('Renaming Timer Object', () => { | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| /** | ||||
|  * Structure: | ||||
|  * Custom functions should be declared last. | ||||
|  * We are leaning on JSDoc pretty heavily to describe functionality. It is not required, but highly recommended. | ||||
|  */ | ||||
| //Structure: custom functions should be declared last. We are leaning on JSDoc pretty heavily to describe functionality. It is not required, but heavily recommended. | ||||
|  | ||||
| /** | ||||
|  * This is an example of a function which is shared between testcases in this test suite. When refactoring, we'll be looking | ||||
|  * for common functionality which makes sense to generalize for the entire test framework. | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  * @param {string} timerUrl The URL of the timer object to be renamed | ||||
|  * @param {string} newNameForTimer New name for object | ||||
|  * @param {string} newNameForTimer New Name for object | ||||
|  */ | ||||
| async function renameTimerFrom3DotMenu(page, timerUrl, newNameForTimer) { | ||||
|     // Navigate to the timer object | ||||
|     await page.goto(timerUrl); | ||||
| async function renameObjectFrom3DotMenu(page, newNameForTimer) { | ||||
|  | ||||
|     // Click on 3 Dot Menu | ||||
|     await page.locator('button[title="More options"]').click(); | ||||
|  | ||||
|     // Click text=Edit Properties... | ||||
|     await page.locator('text=Edit Properties...').click(); | ||||
|  | ||||
|     // Rename the timer object | ||||
|     // Rename the object with newNameForTimer variable which is passed into this function | ||||
|     await page.locator('text=Properties Title Notes >> input[type="text"]').fill(newNameForTimer); | ||||
|  | ||||
|     // Click Ok button to Save | ||||
|   | ||||
| @@ -100,7 +100,7 @@ test.describe("CouchDB initialization @couchdb", () => { | ||||
|         expect(bannerMessage).toEqual('Failed to retrieve object mine'); | ||||
|  | ||||
|         // Verify that a PUT request to create "My Items" folder was made | ||||
|         await expect.poll(() => createMineFolderRequests.length, { | ||||
|         expect.poll(() => createMineFolderRequests.length, { | ||||
|             message: 'Verify that PUT request to create "mine" folder was made', | ||||
|             timeout: 1000 | ||||
|         }).toBeGreaterThanOrEqual(1); | ||||
|   | ||||
| @@ -35,24 +35,45 @@ const expectedAltText = process.platform === 'linux' ? 'Ctrl+Alt drag to pan' : | ||||
|  | ||||
| //The following block of tests verifies the basic functionality of example imagery and serves as a template for Imagery objects embedded in other objects. | ||||
| test.describe('Example Imagery Object', () => { | ||||
|  | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         //Go to baseURL | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Create a default 'Example Imagery' object | ||||
|         await createDomainObjectWithDefaults(page, { type: 'Example Imagery' }); | ||||
|         createDomainObjectWithDefaults(page, { type: 'Example Imagery' }); | ||||
|  | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation(), | ||||
|             page.locator(backgroundImageSelector).hover({trial: true}), | ||||
|             // eslint-disable-next-line playwright/missing-playwright-await | ||||
|             expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery') | ||||
|         ]); | ||||
|  | ||||
|         // Verify that the created object is focused | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     }); | ||||
|  | ||||
|     test('Can use Mouse Wheel to zoom in and out of latest image', async ({ page }) => { | ||||
|         // Zoom in x2 and assert | ||||
|         await mouseZoomOnImageAndAssert(page, 2); | ||||
|         const deltaYStep = 100; //equivalent to 1x zoom | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|         const originalImageDimensions = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         // zoom in | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|         await page.mouse.wheel(0, deltaYStep * 2); | ||||
|         // wait for zoom animation to finish | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|         const imageMouseZoomedIn = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         // zoom out | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|         await page.mouse.wheel(0, -deltaYStep); | ||||
|         // wait for zoom animation to finish | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|         const imageMouseZoomedOut = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|  | ||||
|         // Zoom out x2 and assert | ||||
|         await mouseZoomOnImageAndAssert(page, -2); | ||||
|         expect(imageMouseZoomedIn.height).toBeGreaterThan(originalImageDimensions.height); | ||||
|         expect(imageMouseZoomedIn.width).toBeGreaterThan(originalImageDimensions.width); | ||||
|         expect(imageMouseZoomedOut.height).toBeLessThan(imageMouseZoomedIn.height); | ||||
|         expect(imageMouseZoomedOut.width).toBeLessThan(imageMouseZoomedIn.width); | ||||
|     }); | ||||
|  | ||||
|     test('Can adjust image brightness/contrast by dragging the sliders', async ({ page, browserName }) => { | ||||
| @@ -130,7 +151,30 @@ test.describe('Example Imagery Object', () => { | ||||
|     }); | ||||
|  | ||||
|     test('Can use + - buttons to zoom on the image @unstable', async ({ page }) => { | ||||
|         await buttonZoomOnImageAndAssert(page); | ||||
|         // Get initial image dimensions | ||||
|         const initialBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|  | ||||
|         // Zoom in twice via button | ||||
|         await zoomIntoImageryByButton(page); | ||||
|         await zoomIntoImageryByButton(page); | ||||
|  | ||||
|         // Get and assert zoomed in image dimensions | ||||
|         const zoomedInBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         expect(zoomedInBoundingBox.height).toBeGreaterThan(initialBoundingBox.height); | ||||
|         expect(zoomedInBoundingBox.width).toBeGreaterThan(initialBoundingBox.width); | ||||
|  | ||||
|         // Zoom out once via button | ||||
|         await zoomOutOfImageryByButton(page); | ||||
|  | ||||
|         // Get and assert zoomed out image dimensions | ||||
|         const zoomedOutBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         expect(zoomedOutBoundingBox.height).toBeLessThan(zoomedInBoundingBox.height); | ||||
|         expect(zoomedOutBoundingBox.width).toBeLessThan(zoomedInBoundingBox.width); | ||||
|  | ||||
|         // Zoom out again via button, assert against the initial image dimensions | ||||
|         await zoomOutOfImageryByButton(page); | ||||
|         const finalBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         expect(finalBoundingBox).toEqual(initialBoundingBox); | ||||
|     }); | ||||
|  | ||||
|     test('Can use the reset button to reset the image @unstable', async ({ page }, testInfo) => { | ||||
| @@ -174,221 +218,44 @@ test.describe('Example Imagery Object', () => { | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Display Layout', () => { | ||||
|     let displayLayout; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         // Go to baseURL | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         displayLayout = await createDomainObjectWithDefaults(page, { type: 'Display Layout' }); | ||||
|         await page.goto(displayLayout.url); | ||||
|  | ||||
|         /* Create Sine Wave Generator with minimum Image Load Delay */ | ||||
|         // Click the Create button | ||||
|         await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click text=Example Imagery | ||||
|         await page.click('text=Example Imagery'); | ||||
|  | ||||
|         // Clear and set Image load delay to minimum value | ||||
|         await page.locator('input[type="number"]').fill(''); | ||||
|         await page.locator('input[type="number"]').fill('5000'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation({waitUntil: 'networkidle'}), | ||||
|             page.click('text=OK'), | ||||
|             //Wait for Save Banner to appear | ||||
|             page.waitForSelector('.c-message-banner__message') | ||||
|         ]); | ||||
|  | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|  | ||||
|         await page.goto(displayLayout.url); | ||||
| // The following test case will cover these scenarios | ||||
| // ('Can use Mouse Wheel to zoom in and out of previous image'); | ||||
| // ('Can use alt+drag to move around image once zoomed in'); | ||||
| // ('Clicking on the left arrow should pause the imagery and go to previous image'); | ||||
| // ('If the imagery view is in pause mode, it should not be updated when new images come in'); | ||||
| // ('If the imagery view is not in pause mode, it should be updated when new images come in'); | ||||
| test('Example Imagery in Display layout @unstable', async ({ page }) => { | ||||
|     test.info().annotations.push({ | ||||
|         type: 'issue', | ||||
|         description: 'https://github.com/nasa/openmct/issues/5265' | ||||
|     }); | ||||
|  | ||||
|     test('Imagery View operations @unstable', async ({ page }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5265' | ||||
|         }); | ||||
|     // Go to baseURL | ||||
|     await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Edit mode | ||||
|         await page.click('button[title="Edit"]'); | ||||
|     // Click the Create button | ||||
|     await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click on example imagery to expose toolbar | ||||
|         await page.locator('.c-so-view__header').click(); | ||||
|     // Click text=Example Imagery | ||||
|     await page.click('text=Example Imagery'); | ||||
|  | ||||
|         // Adjust object height | ||||
|         await page.locator('div[title="Resize object height"] > input').click(); | ||||
|         await page.locator('div[title="Resize object height"] > input').fill('50'); | ||||
|     // Clear and set Image load delay to minimum value | ||||
|     await page.locator('input[type="number"]').fill(''); | ||||
|     await page.locator('input[type="number"]').fill('5000'); | ||||
|  | ||||
|         // Adjust object width | ||||
|         await page.locator('div[title="Resize object width"] > input').click(); | ||||
|         await page.locator('div[title="Resize object width"] > input').fill('50'); | ||||
|     // Click text=OK | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation({waitUntil: 'networkidle'}), | ||||
|         page.click('text=OK'), | ||||
|         //Wait for Save Banner to appear | ||||
|         page.waitForSelector('.c-message-banner__message') | ||||
|     ]); | ||||
|  | ||||
|         await performImageryViewOperationsAndAssert(page); | ||||
|     }); | ||||
|     // Wait until Save Banner is gone | ||||
|     await page.waitForSelector('.c-message-banner__message', { state: 'detached'}); | ||||
|     await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|  | ||||
|     test('Resizing the layout changes thumbnail visibility and size', async ({ page }) => { | ||||
|         const thumbsWrapperLocator = page.locator('.c-imagery__thumbs-wrapper'); | ||||
|         // Edit mode | ||||
|         await page.click('button[title="Edit"]'); | ||||
|  | ||||
|         // Click on example imagery to expose toolbar | ||||
|         await page.locator('.c-so-view__header').click(); | ||||
|  | ||||
|         // expect thumbnails not be visible when first added | ||||
|         expect.soft(thumbsWrapperLocator.isHidden()).toBeTruthy(); | ||||
|  | ||||
|         // Resize the example imagery vertically to change the thumbnail visibility | ||||
|         /* | ||||
|         The following arbitrary values are added to observe the separate visual | ||||
|         conditions of the thumbnails (hidden, small thumbnails, regular thumbnails). | ||||
|         Specifically, height is set to 50px for small thumbs and 100px for regular | ||||
|         */ | ||||
|         await page.locator('div[title="Resize object height"] > input').click(); | ||||
|         await page.locator('div[title="Resize object height"] > input').fill('50'); | ||||
|  | ||||
|         expect(thumbsWrapperLocator.isVisible()).toBeTruthy(); | ||||
|         await expect(thumbsWrapperLocator).toHaveClass(/is-small-thumbs/); | ||||
|  | ||||
|         // Resize the example imagery vertically to change the thumbnail visibility | ||||
|         await page.locator('div[title="Resize object height"] > input').click(); | ||||
|         await page.locator('div[title="Resize object height"] > input').fill('100'); | ||||
|  | ||||
|         expect(thumbsWrapperLocator.isVisible()).toBeTruthy(); | ||||
|         await expect(thumbsWrapperLocator).not.toHaveClass(/is-small-thumbs/); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Flexible layout', () => { | ||||
|     let flexibleLayout; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         flexibleLayout = await createDomainObjectWithDefaults(page, { type: 'Flexible Layout' }); | ||||
|         await page.goto(flexibleLayout.url); | ||||
|  | ||||
|         /* Create Sine Wave Generator with minimum Image Load Delay */ | ||||
|         // Click the Create button | ||||
|         await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click text=Example Imagery | ||||
|         await page.click('text=Example Imagery'); | ||||
|  | ||||
|         // Clear and set Image load delay to minimum value | ||||
|         await page.locator('input[type="number"]').fill(''); | ||||
|         await page.locator('input[type="number"]').fill('5000'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation({waitUntil: 'networkidle'}), | ||||
|             page.click('text=OK'), | ||||
|             //Wait for Save Banner to appear | ||||
|             page.waitForSelector('.c-message-banner__message') | ||||
|         ]); | ||||
|  | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|  | ||||
|         await page.goto(flexibleLayout.url); | ||||
|     }); | ||||
|     test('Imagery View operations @unstable', async ({ page, browserName }) => { | ||||
|         test.fixme(browserName === 'firefox', 'This test needs to be updated to work with firefox'); | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5326' | ||||
|         }); | ||||
|  | ||||
|         await performImageryViewOperationsAndAssert(page); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Tabs View', () => { | ||||
|     let tabsView; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         tabsView = await createDomainObjectWithDefaults(page, { type: 'Tabs View' }); | ||||
|         await page.goto(tabsView.url); | ||||
|  | ||||
|         /* Create Sine Wave Generator with minimum Image Load Delay */ | ||||
|         // Click the Create button | ||||
|         await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click text=Example Imagery | ||||
|         await page.click('text=Example Imagery'); | ||||
|  | ||||
|         // Clear and set Image load delay to minimum value | ||||
|         await page.locator('input[type="number"]').fill(''); | ||||
|         await page.locator('input[type="number"]').fill('5000'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation({waitUntil: 'networkidle'}), | ||||
|             page.click('text=OK'), | ||||
|             //Wait for Save Banner to appear | ||||
|             page.waitForSelector('.c-message-banner__message') | ||||
|         ]); | ||||
|  | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|  | ||||
|         await page.goto(tabsView.url); | ||||
|     }); | ||||
|     test('Imagery View operations @unstable', async ({ page }) => { | ||||
|         await performImageryViewOperationsAndAssert(page); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Time Strip', () => { | ||||
|     let timeStripObject; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|         timeStripObject = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Time Strip', | ||||
|             name: 'Time Strip'.concat(' ', uuid()) | ||||
|         }); | ||||
|  | ||||
|         await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Example Imagery', | ||||
|             name: 'Example Imagery'.concat(' ', uuid()), | ||||
|             parent: timeStripObject.uuid | ||||
|         }); | ||||
|         // Navigate to timestrip | ||||
|         await page.goto(timeStripObject.url); | ||||
|     }); | ||||
|     test('Clicking a thumbnail loads the image in large view', async ({ page, browserName }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5632' | ||||
|         }); | ||||
|         await page.locator('.c-imagery-tsv-container').hover(); | ||||
|         // get url of the hovered image | ||||
|         const hoveredImg = page.locator('.c-imagery-tsv div.c-imagery-tsv__image-wrapper:hover img'); | ||||
|         const hoveredImgSrc = await hoveredImg.getAttribute('src'); | ||||
|         expect(hoveredImgSrc).toBeTruthy(); | ||||
|         await page.locator('.c-imagery-tsv-container').click(); | ||||
|         // get image of view large container | ||||
|         const viewLargeImg = page.locator('img.c-imagery__main-image__image'); | ||||
|         const viewLargeImgSrc = await viewLargeImg.getAttribute('src'); | ||||
|         expect(viewLargeImgSrc).toBeTruthy(); | ||||
|         expect(viewLargeImgSrc).toEqual(hoveredImgSrc); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| /** | ||||
|  * Perform the common actions and assertions for the Imagery View. | ||||
|  * This function verifies the following in order: | ||||
|  * 1. Can zoom in/out using the zoom buttons | ||||
|  * 2. Can zoom in/out using the mouse wheel | ||||
|  * 3. Can pan the image using the pan hotkey + mouse drag | ||||
|  * 4. Clicking on the left arrow button pauses imagery and moves to the previous image | ||||
|  * 5. Imagery is updated as new images stream in, regardless of pause status | ||||
|  * 6. Old images are discarded when new images stream in | ||||
|  * 7. Image brightness/contrast can be adjusted by dragging the sliders | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function performImageryViewOperationsAndAssert(page) { | ||||
|     // Click previous image button | ||||
|     const previousImageButton = page.locator('.c-nav--prev'); | ||||
|     await previousImageButton.click(); | ||||
| @@ -397,17 +264,27 @@ async function performImageryViewOperationsAndAssert(page) { | ||||
|     const selectedImage = page.locator('.selected'); | ||||
|     await expect(selectedImage).toBeVisible(); | ||||
|  | ||||
|     // Use the zoom buttons to zoom in and out | ||||
|     await buttonZoomOnImageAndAssert(page); | ||||
|     // Zoom in | ||||
|     const originalImageDimensions = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     const deltaYStep = 100; // equivalent to 1x zoom | ||||
|     await page.mouse.wheel(0, deltaYStep * 2); | ||||
|     const zoomedBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     const imageCenterX = zoomedBoundingBox.x + zoomedBoundingBox.width / 2; | ||||
|     const imageCenterY = zoomedBoundingBox.y + zoomedBoundingBox.height / 2; | ||||
|  | ||||
|     // Use Mouse Wheel to zoom in to previous image | ||||
|     await mouseZoomOnImageAndAssert(page, 2); | ||||
|     // Wait for zoom animation to finish | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     const imageMouseZoomedIn = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(imageMouseZoomedIn.height).toBeGreaterThan(originalImageDimensions.height); | ||||
|     expect(imageMouseZoomedIn.width).toBeGreaterThan(originalImageDimensions.width); | ||||
|  | ||||
|     // Use alt+drag to move around image once zoomed in | ||||
|     await panZoomAndAssertImageProperties(page); | ||||
|     // Center the mouse pointer | ||||
|     await page.mouse.move(imageCenterX, imageCenterY); | ||||
|  | ||||
|     // Use Mouse Wheel to zoom out of previous image | ||||
|     await mouseZoomOnImageAndAssert(page, -2); | ||||
|     // Pan Imagery Hints | ||||
|     const imageryHintsText = await page.locator('.c-imagery__hints').innerText(); | ||||
|     expect(expectedAltText).toEqual(imageryHintsText); | ||||
|  | ||||
|     // Click next image button | ||||
|     const nextImageButton = page.locator('.c-nav--next'); | ||||
| @@ -420,14 +297,21 @@ async function performImageryViewOperationsAndAssert(page) { | ||||
|     await page.locator('[data-testid=conductor-modeOption-realtime]').click(); | ||||
|  | ||||
|     // Zoom in on next image | ||||
|     await mouseZoomOnImageAndAssert(page, 2); | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     await page.mouse.wheel(0, deltaYStep * 2); | ||||
|  | ||||
|     // Clicking on the left arrow should pause the imagery and go to previous image | ||||
|     // Wait for zoom animation to finish | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     const imageNextMouseZoomedIn = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(imageNextMouseZoomedIn.height).toBeGreaterThan(originalImageDimensions.height); | ||||
|     expect(imageNextMouseZoomedIn.width).toBeGreaterThan(originalImageDimensions.width); | ||||
|  | ||||
|     // Click previous image button | ||||
|     await previousImageButton.click(); | ||||
|     await expect(page.locator('.c-button.pause-play')).toHaveClass(/is-paused/); | ||||
|  | ||||
|     // Verify previous image | ||||
|     await expect(selectedImage).toBeVisible(); | ||||
|  | ||||
|     // The imagery view should be updated when new images come in | ||||
|     const imageCount = await page.locator('.c-imagery__thumb').count(); | ||||
|     await expect.poll(async () => { | ||||
|         const newImageCount = await page.locator('.c-imagery__thumb').count(); | ||||
| @@ -435,7 +319,7 @@ async function performImageryViewOperationsAndAssert(page) { | ||||
|         return newImageCount; | ||||
|     }, { | ||||
|         message: "verify that old images are discarded", | ||||
|         timeout: 7 * 1000 | ||||
|         timeout: 6 * 1000 | ||||
|     }).toBe(imageCount); | ||||
|  | ||||
|     // Verify selected image is still displayed | ||||
| @@ -453,6 +337,283 @@ async function performImageryViewOperationsAndAssert(page) { | ||||
|     // Drag the brightness and contrast sliders around and assert filter values | ||||
|     await dragBrightnessSliderAndAssertFilterValues(page); | ||||
|     await dragContrastSliderAndAssertFilterValues(page); | ||||
| }); | ||||
|  | ||||
| test.describe('Example imagery thumbnails resize in display layouts', () => { | ||||
|     test('Resizing the layout changes thumbnail visibility and size', async ({ page }) => { | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         const thumbsWrapperLocator = page.locator('.c-imagery__thumbs-wrapper'); | ||||
|         // Click button:has-text("Create") | ||||
|         await page.locator('button:has-text("Create")').click(); | ||||
|  | ||||
|         // Click li:has-text("Display Layout") | ||||
|         await page.locator('li:has-text("Display Layout")').click(); | ||||
|         const displayLayoutTitleField = page.locator('text=Properties Title Notes Horizontal grid (px) Vertical grid (px) Horizontal size ( >> input[type="text"]'); | ||||
|         await displayLayoutTitleField.click(); | ||||
|  | ||||
|         await displayLayoutTitleField.fill('Thumbnail Display Layout'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation(), | ||||
|             page.locator('text=OK').click() | ||||
|         ]); | ||||
|  | ||||
|         // Click text=Snapshot Save and Finish Editing Save and Continue Editing >> button >> nth=1 | ||||
|         await page.locator('text=Snapshot Save and Finish Editing Save and Continue Editing >> button').nth(1).click(); | ||||
|  | ||||
|         // Click text=Save and Finish Editing | ||||
|         await page.locator('text=Save and Finish Editing').click(); | ||||
|  | ||||
|         // Click button:has-text("Create") | ||||
|         await page.locator('button:has-text("Create")').click(); | ||||
|  | ||||
|         // Click li:has-text("Example Imagery") | ||||
|         await page.locator('li:has-text("Example Imagery")').click(); | ||||
|  | ||||
|         const imageryTitleField = page.locator('text=Properties Title Notes Images url list (comma separated) Image load delay (milli >> input[type="text"]'); | ||||
|         // Click text=Properties Title Notes Images url list (comma separated) Image load delay (milli >> input[type="text"] | ||||
|         await imageryTitleField.click(); | ||||
|  | ||||
|         // Fill text=Properties Title Notes Images url list (comma separated) Image load delay (milli >> input[type="text"] | ||||
|         await imageryTitleField.fill('Thumbnail Example Imagery'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation(), | ||||
|             page.locator('text=OK').click() | ||||
|         ]); | ||||
|  | ||||
|         // Click text=Thumbnail Example Imagery Imagery Layout Snapshot >> button >> nth=0 | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation(), | ||||
|             page.locator('text=Thumbnail Example Imagery Imagery Layout Snapshot >> button').first().click() | ||||
|         ]); | ||||
|  | ||||
|         // Edit mode | ||||
|         await page.locator('text=Thumbnail Display Layout Snapshot >> button').nth(3).click(); | ||||
|  | ||||
|         // Click on example imagery to expose toolbar | ||||
|         await page.locator('text=Thumbnail Example Imagery Snapshot Large View').click(); | ||||
|  | ||||
|         // expect thumbnails not be visible when first added | ||||
|         expect.soft(thumbsWrapperLocator.isHidden()).toBeTruthy(); | ||||
|  | ||||
|         // Resize the example imagery vertically to change the thumbnail visibility | ||||
|         /* | ||||
|         The following arbitrary values are added to observe the separate visual | ||||
|         conditions of the thumbnails (hidden, small thumbnails, regular thumbnails). | ||||
|         Specifically, height is set to 50px for small thumbs and 100px for regular | ||||
|         */ | ||||
|         // Click #mct-input-id-103 | ||||
|         await page.locator('#mct-input-id-103').click(); | ||||
|  | ||||
|         // Fill #mct-input-id-103 | ||||
|         await page.locator('#mct-input-id-103').fill('50'); | ||||
|  | ||||
|         expect(thumbsWrapperLocator.isVisible()).toBeTruthy(); | ||||
|         await expect(thumbsWrapperLocator).toHaveClass(/is-small-thumbs/); | ||||
|  | ||||
|         // Resize the example imagery vertically to change the thumbnail visibility | ||||
|         // Click #mct-input-id-103 | ||||
|         await page.locator('#mct-input-id-103').click(); | ||||
|  | ||||
|         // Fill #mct-input-id-103 | ||||
|         await page.locator('#mct-input-id-103').fill('100'); | ||||
|  | ||||
|         expect(thumbsWrapperLocator.isVisible()).toBeTruthy(); | ||||
|         await expect(thumbsWrapperLocator).not.toHaveClass(/is-small-thumbs/); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Flexible layout', () => { | ||||
|     test('Example Imagery in Flexible layout @unstable', async ({ page, browserName, openmctConfig }) => { | ||||
|         const { myItemsFolderName } = openmctConfig; | ||||
|  | ||||
|         // eslint-disable-next-line playwright/no-skipped-test | ||||
|         test.skip(browserName === 'firefox', 'This test needs to be updated to work with firefox'); | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5326' | ||||
|         }); | ||||
|  | ||||
|         // Go to baseURL | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Click the Create button | ||||
|         await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click text=Example Imagery | ||||
|         await page.click('text=Example Imagery'); | ||||
|  | ||||
|         // Clear and set Image load delay (milliseconds) | ||||
|         await page.click('input[type="number"]', {clickCount: 3}); | ||||
|         await page.type('input[type="number"]', "20"); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await Promise.all([ | ||||
|             page.waitForNavigation({waitUntil: 'networkidle'}), | ||||
|             page.click('text=OK'), | ||||
|             //Wait for Save Banner to appear | ||||
|             page.waitForSelector('.c-message-banner__message') | ||||
|         ]); | ||||
|         // Wait until Save Banner is gone | ||||
|         await page.waitForSelector('.c-message-banner__message', { state: 'detached'}); | ||||
|         await expect(page.locator('.l-browse-bar__object-name')).toContainText('Unnamed Example Imagery'); | ||||
|         await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|  | ||||
|         // Click the Create button | ||||
|         await page.click('button:has-text("Create")'); | ||||
|  | ||||
|         // Click text=Flexible Layout | ||||
|         await page.click('text=Flexible Layout'); | ||||
|  | ||||
|         // Assert Flexible layout | ||||
|         await expect(page.locator('.js-form-title')).toHaveText('Create a New Flexible Layout'); | ||||
|  | ||||
|         await page.locator(`form[name="mctForm"] >> text=${myItemsFolderName}`).click(); | ||||
|  | ||||
|         // Click My Items | ||||
|         await Promise.all([ | ||||
|             page.locator('text=OK').click(), | ||||
|             page.waitForNavigation({waitUntil: 'networkidle'}) | ||||
|         ]); | ||||
|  | ||||
|         // Click My Items | ||||
|         await page.locator('.c-disclosure-triangle').click(); | ||||
|  | ||||
|         // Right click example imagery | ||||
|         await page.click(('text=Unnamed Example Imagery'), { button: 'right' }); | ||||
|  | ||||
|         // Click move | ||||
|         await page.locator('.icon-move').click(); | ||||
|  | ||||
|         // Click triangle to open sub menu | ||||
|         await page.locator('.c-form__section .c-disclosure-triangle').click(); | ||||
|  | ||||
|         // Click Flexable Layout | ||||
|         await page.click('.c-overlay__outer >> text=Unnamed Flexible Layout'); | ||||
|  | ||||
|         // Click text=OK | ||||
|         await page.locator('text=OK').click(); | ||||
|  | ||||
|         // Save template | ||||
|         await saveTemplate(page); | ||||
|  | ||||
|         // Zoom in | ||||
|         await mouseZoomIn(page); | ||||
|  | ||||
|         // Center the mouse pointer | ||||
|         const zoomedBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|         const imageCenterX = zoomedBoundingBox.x + zoomedBoundingBox.width / 2; | ||||
|         const imageCenterY = zoomedBoundingBox.y + zoomedBoundingBox.height / 2; | ||||
|         await page.mouse.move(imageCenterX, imageCenterY); | ||||
|  | ||||
|         // Pan zoom | ||||
|         await panZoomAndAssertImageProperties(page); | ||||
|  | ||||
|         // Click previous image button | ||||
|         const previousImageButton = page.locator('.c-nav--prev'); | ||||
|         await previousImageButton.click(); | ||||
|  | ||||
|         // Verify previous image | ||||
|         const selectedImage = page.locator('.selected'); | ||||
|         await expect(selectedImage).toBeVisible(); | ||||
|  | ||||
|         // Click time conductor mode button | ||||
|         await page.locator('.c-mode-button').click(); | ||||
|  | ||||
|         // Select local clock mode | ||||
|         await page.locator('[data-testid=conductor-modeOption-realtime]').nth(0).click(); | ||||
|  | ||||
|         // Zoom in on next image | ||||
|         await mouseZoomIn(page); | ||||
|  | ||||
|         // Click previous image button | ||||
|         await previousImageButton.click(); | ||||
|  | ||||
|         // Verify previous image | ||||
|         await expect(selectedImage).toBeVisible(); | ||||
|  | ||||
|         const imageCount = await page.locator('.c-imagery__thumb').count(); | ||||
|         await expect.poll(async () => { | ||||
|             const newImageCount = await page.locator('.c-imagery__thumb').count(); | ||||
|  | ||||
|             return newImageCount; | ||||
|         }, { | ||||
|             message: "verify that old images are discarded", | ||||
|             timeout: 6 * 1000 | ||||
|         }).toBe(imageCount); | ||||
|  | ||||
|         // Verify selected image is still displayed | ||||
|         await expect(selectedImage).toBeVisible(); | ||||
|  | ||||
|         // Unpause imagery | ||||
|         await page.locator('.pause-play').click(); | ||||
|  | ||||
|         //Get background-image url from background-image css prop | ||||
|         await assertBackgroundImageUrlFromBackgroundCss(page); | ||||
|  | ||||
|         // Open the image filter menu | ||||
|         await page.locator('[role=toolbar] button[title="Brightness and contrast"]').click(); | ||||
|  | ||||
|         // Drag the brightness and contrast sliders around and assert filter values | ||||
|         await dragBrightnessSliderAndAssertFilterValues(page); | ||||
|         await dragContrastSliderAndAssertFilterValues(page); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Tabs view', () => { | ||||
|     test.fixme('Can use Mouse Wheel to zoom in and out of previous image'); | ||||
|     test.fixme('Can use alt+drag to move around image once zoomed in'); | ||||
|     test.fixme('Can zoom into the latest image and the real-time/fixed-time imagery will pause'); | ||||
|     test.fixme('Can zoom into a previous image from thumbstrip in real-time or fixed-time'); | ||||
|     test.fixme('Clicking on the left arrow should pause the imagery and go to previous image'); | ||||
|     test.fixme('If the imagery view is in pause mode, it should not be updated when new images come in'); | ||||
|     test.fixme('If the imagery view is not in pause mode, it should be updated when new images come in'); | ||||
| }); | ||||
|  | ||||
| test.describe('Example Imagery in Time Strip', () => { | ||||
|     test('ensure that clicking a thumbnail loads the image in large view', async ({ page, browserName }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5632' | ||||
|         }); | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|         const timeStripObject = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Time Strip', | ||||
|             name: 'Time Strip'.concat(' ', uuid()) | ||||
|         }); | ||||
|  | ||||
|         await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Example Imagery', | ||||
|             name: 'Example Imagery'.concat(' ', uuid()), | ||||
|             parent: timeStripObject.uuid | ||||
|         }); | ||||
|         // Navigate to timestrip | ||||
|         await page.goto(timeStripObject.url); | ||||
|  | ||||
|         await page.locator('.c-imagery-tsv-container').hover(); | ||||
|         // get url of the hovered image | ||||
|         const hoveredImg = page.locator('.c-imagery-tsv div.c-imagery-tsv__image-wrapper:hover img'); | ||||
|         const hoveredImgSrc = await hoveredImg.getAttribute('src'); | ||||
|         expect(hoveredImgSrc).toBeTruthy(); | ||||
|         await page.locator('.c-imagery-tsv-container').click(); | ||||
|         // get image of view large container | ||||
|         const viewLargeImg = page.locator('img.c-imagery__main-image__image'); | ||||
|         const viewLargeImgSrc = await viewLargeImg.getAttribute('src'); | ||||
|         expect(viewLargeImgSrc).toBeTruthy(); | ||||
|         expect(viewLargeImgSrc).toEqual(hoveredImgSrc); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function saveTemplate(page) { | ||||
|     await page.locator('.c-button--menu.c-button--major.icon-save').click(); | ||||
|     await page.locator('text=Save and Finish Editing').click(); | ||||
| } | ||||
|  | ||||
| /** | ||||
| @@ -535,7 +696,7 @@ async function assertBackgroundImageUrlFromBackgroundCss(page) { | ||||
|         return backgroundImageUrl2; | ||||
|     }, { | ||||
|         message: "verify next image has updated", | ||||
|         timeout: 7 * 1000 | ||||
|         timeout: 6 * 1000 | ||||
|     }).not.toBe(backgroundImageUrl1); | ||||
|     console.log('backgroundImageUrl2 ' + backgroundImageUrl2); | ||||
| } | ||||
| @@ -589,17 +750,14 @@ async function panZoomAndAssertImageProperties(page) { | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Use the mouse wheel to zoom in or out of an image and assert that the image | ||||
|  * has successfully zoomed in or out. | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  * @param {number} [factor = 2] The zoom factor. Positive for zoom in, negative for zoom out. | ||||
| */ | ||||
| async function mouseZoomOnImageAndAssert(page, factor = 2) { | ||||
| async function mouseZoomIn(page) { | ||||
|     // Zoom in | ||||
|     const originalImageDimensions = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     const deltaYStep = 100; // equivalent to 1x zoom | ||||
|     await page.mouse.wheel(0, deltaYStep * factor); | ||||
|     await page.mouse.wheel(0, deltaYStep * 2); | ||||
|     const zoomedBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     const imageCenterX = zoomedBoundingBox.x + zoomedBoundingBox.width / 2; | ||||
|     const imageCenterY = zoomedBoundingBox.y + zoomedBoundingBox.height / 2; | ||||
| @@ -609,47 +767,9 @@ async function mouseZoomOnImageAndAssert(page, factor = 2) { | ||||
|  | ||||
|     // Wait for zoom animation to finish | ||||
|     await page.locator(backgroundImageSelector).hover({trial: true}); | ||||
|     const imageMouseZoomed = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|  | ||||
|     if (factor > 0) { | ||||
|         expect(imageMouseZoomed.height).toBeGreaterThan(originalImageDimensions.height); | ||||
|         expect(imageMouseZoomed.width).toBeGreaterThan(originalImageDimensions.width); | ||||
|     } else { | ||||
|         expect(imageMouseZoomed.height).toBeLessThan(originalImageDimensions.height); | ||||
|         expect(imageMouseZoomed.width).toBeLessThan(originalImageDimensions.width); | ||||
|     } | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * Zoom in and out of the image using the buttons, and assert that the image has | ||||
|  * been successfully zoomed in or out. | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function buttonZoomOnImageAndAssert(page) { | ||||
|     // Get initial image dimensions | ||||
|     const initialBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|  | ||||
|     // Zoom in twice via button | ||||
|     await zoomIntoImageryByButton(page); | ||||
|     await zoomIntoImageryByButton(page); | ||||
|  | ||||
|     // Get and assert zoomed in image dimensions | ||||
|     const zoomedInBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(zoomedInBoundingBox.height).toBeGreaterThan(initialBoundingBox.height); | ||||
|     expect(zoomedInBoundingBox.width).toBeGreaterThan(initialBoundingBox.width); | ||||
|  | ||||
|     // Zoom out once via button | ||||
|     await zoomOutOfImageryByButton(page); | ||||
|  | ||||
|     // Get and assert zoomed out image dimensions | ||||
|     const zoomedOutBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(zoomedOutBoundingBox.height).toBeLessThan(zoomedInBoundingBox.height); | ||||
|     expect(zoomedOutBoundingBox.width).toBeLessThan(zoomedInBoundingBox.width); | ||||
|  | ||||
|     // Zoom out again via button, assert against the initial image dimensions | ||||
|     await zoomOutOfImageryByButton(page); | ||||
|     const finalBoundingBox = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(finalBoundingBox).toEqual(initialBoundingBox); | ||||
|     const imageMouseZoomedIn = await page.locator(backgroundImageSelector).boundingBox(); | ||||
|     expect(imageMouseZoomedIn.height).toBeGreaterThan(originalImageDimensions.height); | ||||
|     expect(imageMouseZoomedIn.width).toBeGreaterThan(originalImageDimensions.width); | ||||
| } | ||||
|  | ||||
| /** | ||||
|   | ||||
| @@ -27,8 +27,7 @@ This test suite is dedicated to tests which verify the basic operations surround | ||||
| // FIXME: Remove this eslint exception once tests are implemented | ||||
| // eslint-disable-next-line no-unused-vars | ||||
| const { test, expect } = require('../../../../baseFixtures'); | ||||
| const { expandTreePaneItemByName, createDomainObjectWithDefaults } = require('../../../../appActions'); | ||||
| const nbUtils = require('../../../../helper/notebookUtils'); | ||||
| const { createDomainObjectWithDefaults } = require('../../../../appActions'); | ||||
|  | ||||
| test.describe('Notebook CRUD Operations', () => { | ||||
|     test.fixme('Can create a Notebook Object', async ({ page }) => { | ||||
| @@ -210,58 +209,13 @@ test.describe('Notebook search tests', () => { | ||||
|  | ||||
| test.describe('Notebook entry tests', () => { | ||||
|     test.fixme('When a new entry is created, it should be focused', async ({ page }) => {}); | ||||
|     test('When an object is dropped into a notebook, a new entry is created and it should be focused @unstable', async ({ page }) => { | ||||
|         await page.goto('./#/browse/mine', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Create Notebook | ||||
|         const notebook = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Notebook', | ||||
|             name: "Embed Test Notebook" | ||||
|         }); | ||||
|         // Create Overlay Plot | ||||
|         await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Overlay Plot', | ||||
|             name: "Dropped Overlay Plot" | ||||
|         }); | ||||
|  | ||||
|         await expandTreePaneItemByName(page, 'My Items'); | ||||
|  | ||||
|         await page.goto(notebook.url); | ||||
|         await page.dragAndDrop('role=treeitem[name=/Dropped Overlay Plot/]', '.c-notebook__drag-area'); | ||||
|  | ||||
|         const embed = page.locator('.c-ne__embed__link'); | ||||
|         const embedName = await embed.textContent(); | ||||
|  | ||||
|         await expect(embed).toHaveClass(/icon-plot-overlay/); | ||||
|         expect(embedName).toBe('Dropped Overlay Plot'); | ||||
|     test.fixme('When a telemetry object is dropped into a notebook, a new entry is created and it should be focused', async ({ page }) => { | ||||
|         // Drag and drop any telmetry object on 'drop object' | ||||
|         // new entry gets created with telemtry object | ||||
|     }); | ||||
|     test('When an object is dropped into a notebooks existing entry, it should be focused @unstable', async ({ page }) => { | ||||
|         await page.goto('./#/browse/mine', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Create Notebook | ||||
|         const notebook = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Notebook', | ||||
|             name: "Embed Test Notebook" | ||||
|         }); | ||||
|         // Create Overlay Plot | ||||
|         await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Overlay Plot', | ||||
|             name: "Dropped Overlay Plot" | ||||
|         }); | ||||
|  | ||||
|         await expandTreePaneItemByName(page, 'My Items'); | ||||
|  | ||||
|         await page.goto(notebook.url); | ||||
|  | ||||
|         await nbUtils.enterTextEntry(page, 'Entry to drop into'); | ||||
|         await page.dragAndDrop('role=treeitem[name=/Dropped Overlay Plot/]', 'text=Entry to drop into'); | ||||
|  | ||||
|         const existingEntry = page.locator('.c-ne__content', { has: page.locator('text="Entry to drop into"') }); | ||||
|         const embed = existingEntry.locator('.c-ne__embed__link'); | ||||
|         const embedName = await embed.textContent(); | ||||
|  | ||||
|         await expect(embed).toHaveClass(/icon-plot-overlay/); | ||||
|         expect(embedName).toBe('Dropped Overlay Plot'); | ||||
|     test.fixme('When a telemetry object is dropped into a notebooks existing entry, it should be focused', async ({ page }) => { | ||||
|         // Drag and drop any telemetry object onto existing entry | ||||
|         // Entry updated with object and snapshot | ||||
|     }); | ||||
|     test.fixme('new entries persist through navigation events without save', async ({ page }) => {}); | ||||
|     test.fixme('previous and new entries can be deleted', async ({ page }) => {}); | ||||
|   | ||||
| @@ -1,271 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /* | ||||
| This test suite is dedicated to tests which verify the basic operations surrounding Notebooks with CouchDB. | ||||
| */ | ||||
|  | ||||
| const { test, expect } = require('../../../../baseFixtures'); | ||||
| const { createDomainObjectWithDefaults } = require('../../../../appActions'); | ||||
|  | ||||
| test.describe('Notebook Tests with CouchDB @couchdb', () => { | ||||
|     let testNotebook; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         //Navigate to baseURL | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Create Notebook | ||||
|         testNotebook = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Notebook', | ||||
|             name: "TestNotebook" | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     test('Inspect Notebook Entry Network Requests', async ({ page }) => { | ||||
|         // Expand sidebar | ||||
|         await page.locator('.c-notebook__toggle-nav-button').click(); | ||||
|  | ||||
|         // Collect all request events to count and assert after notebook action | ||||
|         let addingNotebookElementsRequests = []; | ||||
|         page.on('request', (request) => addingNotebookElementsRequests.push(request)); | ||||
|  | ||||
|         let [notebookUrlRequest, allDocsRequest] = await Promise.all([ | ||||
|             // Waits for the next request with the specified url | ||||
|             page.waitForRequest(`**/openmct/${testNotebook.uuid}`), | ||||
|             page.waitForRequest('**/openmct/_all_docs?include_docs=true'), | ||||
|             // Triggers the request | ||||
|             page.click('[aria-label="Add Page"]'), | ||||
|             // Ensures that there are no other network requests | ||||
|             page.waitForLoadState('networkidle') | ||||
|         ]); | ||||
|         // Assert that only two requests are made | ||||
|         // Network Requests are: | ||||
|         // 1) The actual POST to create the page | ||||
|         // 2) The shared worker event from 👆 request | ||||
|         expect(addingNotebookElementsRequests.length).toBe(2); | ||||
|  | ||||
|         // Assert on request object | ||||
|         expect(notebookUrlRequest.postDataJSON().metadata.name).toBe('TestNotebook'); | ||||
|         expect(notebookUrlRequest.postDataJSON().model.persisted).toBeGreaterThanOrEqual(notebookUrlRequest.postDataJSON().model.modified); | ||||
|         expect(allDocsRequest.postDataJSON().keys).toContain(testNotebook.uuid); | ||||
|  | ||||
|         // Add an entry | ||||
|         // Network Requests are: | ||||
|         // 1) The actual POST to create the entry | ||||
|         // 2) The shared worker event from 👆 POST request | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').fill(`First Entry`); | ||||
|         await page.waitForLoadState('networkidle'); | ||||
|         expect(addingNotebookElementsRequests.length).toBeLessThanOrEqual(2); | ||||
|  | ||||
|         // Add some tags | ||||
|         // Network Requests are for each tag creation are: | ||||
|         // 1) Getting the original path of the parent object | ||||
|         // 2) Getting the original path of the grandparent object (recursive call) | ||||
|         // 3) Creating the annotation/tag object | ||||
|         // 4) The shared worker event from 👆 POST request | ||||
|         // 5) Mutate notebook domain object's annotationModified property | ||||
|         // 6) The shared worker event from 👆 POST request | ||||
|         // 7) Notebooks fetching new annotations due to annotationModified changed | ||||
|         // 8) The update of the notebook domain's object's modified property | ||||
|         // 9) The shared worker event from 👆 POST request | ||||
|         // 10) Entry is timestamped | ||||
|         // 11) The shared worker event from 👆 POST request | ||||
|  | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Driving').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Driving")'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(11); | ||||
|  | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Drilling').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Drilling")'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(11); | ||||
|  | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Science').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Science")'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(11); | ||||
|  | ||||
|         // Delete all the tags | ||||
|         // Network requests are: | ||||
|         // 1) Send POST to mutate _delete property to true on annotation with tag | ||||
|         // 2) The shared worker event from 👆 POST request | ||||
|         // 3) Timestamp update on entry | ||||
|         // 4) The shared worker event from 👆 POST request | ||||
|         // This happens for 3 tags so 12 requests | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.hover('[aria-label="Tag"]:has-text("Driving")'); | ||||
|         await page.locator('[aria-label="Tag"]:has-text("Driving") ~ .c-completed-tag-deletion').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Driving")', {state: 'hidden'}); | ||||
|         await page.hover('[aria-label="Tag"]:has-text("Drilling")'); | ||||
|         await page.locator('[aria-label="Tag"]:has-text("Drilling") ~ .c-completed-tag-deletion').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Drilling")', {state: 'hidden'}); | ||||
|         page.hover('[aria-label="Tag"]:has-text("Science")'); | ||||
|         await page.locator('[aria-label="Tag"]:has-text("Science") ~ .c-completed-tag-deletion').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Science")', {state: 'hidden'}); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(12); | ||||
|  | ||||
|         // Add two more pages | ||||
|         await page.click('[aria-label="Add Page"]'); | ||||
|         await page.click('[aria-label="Add Page"]'); | ||||
|  | ||||
|         // Add three entries | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').fill(`First Entry`); | ||||
|  | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=1').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=1').fill(`Second Entry`); | ||||
|  | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=2').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=2').fill(`Third Entry`); | ||||
|  | ||||
|         // Add three tags | ||||
|         await page.hover(`button:has-text("Add Tag") >> nth=2`); | ||||
|         await page.locator(`button:has-text("Add Tag") >> nth=2`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Science').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Science")'); | ||||
|  | ||||
|         await page.hover(`button:has-text("Add Tag") >> nth=2`); | ||||
|         await page.locator(`button:has-text("Add Tag") >> nth=2`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Drilling').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Drilling")'); | ||||
|  | ||||
|         await page.hover(`button:has-text("Add Tag") >> nth=2`); | ||||
|         await page.locator(`button:has-text("Add Tag") >> nth=2`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Driving').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Driving")'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|  | ||||
|         // Add a fourth entry | ||||
|         // Network requests are: | ||||
|         // 1) Send POST to add new entry | ||||
|         // 2) The shared worker event from 👆 POST request | ||||
|         // 3) Timestamp update on entry | ||||
|         // 4) The shared worker event from 👆 POST request | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=3').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=3').fill(`Fourth Entry`); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=3').press('Enter'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|  | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(4); | ||||
|  | ||||
|         // Add a fifth entry | ||||
|         // Network requests are: | ||||
|         // 1) Send POST to add new entry | ||||
|         // 2) The shared worker event from 👆 POST request | ||||
|         // 3) Timestamp update on entry | ||||
|         // 4) The shared worker event from 👆 POST request | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=4').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=4').fill(`Fifth Entry`); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=4').press('Enter'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|  | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(4); | ||||
|  | ||||
|         // Add a sixth entry | ||||
|         // 1) Send POST to add new entry | ||||
|         // 2) The shared worker event from 👆 POST request | ||||
|         // 3) Timestamp update on entry | ||||
|         // 4) The shared worker event from 👆 POST request | ||||
|         addingNotebookElementsRequests = []; | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=5').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=5').fill(`Sixth Entry`); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=5').press('Enter'); | ||||
|         page.waitForLoadState('networkidle'); | ||||
|  | ||||
|         expect(filterNonFetchRequests(addingNotebookElementsRequests).length).toBeLessThanOrEqual(4); | ||||
|     }); | ||||
|  | ||||
|     test('Search tests', async ({ page }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/akhenry/openmct-yamcs/issues/69' | ||||
|         }); | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').click(); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').fill(`First Entry`); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"]').press('Enter'); | ||||
|  | ||||
|         // Add three tags | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Science').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Science")'); | ||||
|  | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Drilling').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Drilling")'); | ||||
|  | ||||
|         await page.hover(`button:has-text("Add Tag")`); | ||||
|         await page.locator(`button:has-text("Add Tag")`).click(); | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|         await page.locator('[aria-label="Autocomplete Options"] >> text=Driving').click(); | ||||
|         await page.waitForSelector('[aria-label="Tag"]:has-text("Driving")'); | ||||
|  | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').click(); | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('Sc'); | ||||
|         await expect(page.locator('[aria-label="Search Result"]').first()).toContainText("Science"); | ||||
|         await expect(page.locator('[aria-label="Search Result"]').first()).not.toContainText("Driving"); | ||||
|  | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').click(); | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('Xq'); | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| // Try to reduce indeterminism of browser requests by only returning fetch requests. | ||||
| // Filter out preflight CORS, fetching stylesheets, page icons, etc. that can occur during tests | ||||
| function filterNonFetchRequests(requests) { | ||||
|     return requests.filter(request => { | ||||
|         return (request.resourceType() === 'fetch'); | ||||
|     }); | ||||
| } | ||||
| @@ -23,11 +23,11 @@ | ||||
| const { test, expect } = require('../../../../pluginFixtures'); | ||||
| const { openObjectTreeContextMenu, createDomainObjectWithDefaults } = require('../../../../appActions'); | ||||
| const path = require('path'); | ||||
| const nbUtils = require('../../../../helper/notebookUtils'); | ||||
|  | ||||
| const TEST_TEXT = 'Testing text for entries.'; | ||||
| const TEST_TEXT_NAME = 'Test Page'; | ||||
| const CUSTOM_NAME = 'CUSTOM_NAME'; | ||||
| const NOTEBOOK_DROP_AREA = '.c-notebook__drag-area'; | ||||
|  | ||||
| test.describe('Restricted Notebook', () => { | ||||
|     let notebook; | ||||
| @@ -66,7 +66,7 @@ test.describe('Restricted Notebook', () => { | ||||
|  | ||||
|     test('Can be locked if at least one page has one entry @addInit', async ({ page }) => { | ||||
|  | ||||
|         await nbUtils.enterTextEntry(page, TEST_TEXT); | ||||
|         await enterTextEntry(page); | ||||
|  | ||||
|         const commitButton = page.locator('button:has-text("Commit Entries")'); | ||||
|         expect(await commitButton.count()).toEqual(1); | ||||
| @@ -78,7 +78,7 @@ test.describe('Restricted Notebook with at least one entry and with the page loc | ||||
|     let notebook; | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         notebook = await startAndAddRestrictedNotebookObject(page); | ||||
|         await nbUtils.enterTextEntry(page, TEST_TEXT); | ||||
|         await enterTextEntry(page); | ||||
|         await lockPage(page); | ||||
|  | ||||
|         // open sidebar | ||||
| @@ -121,7 +121,7 @@ test.describe('Restricted Notebook with at least one entry and with the page loc | ||||
|         expect.soft(newPageCount).toEqual(1); | ||||
|  | ||||
|         // enter test text | ||||
|         await nbUtils.enterTextEntry(page, TEST_TEXT); | ||||
|         await enterTextEntry(page); | ||||
|  | ||||
|         // expect new page to be lockable | ||||
|         const commitButton = page.locator('BUTTON:HAS-TEXT("COMMIT ENTRIES")'); | ||||
| @@ -148,7 +148,7 @@ test.describe('Restricted Notebook with a page locked and with an embed @addInit | ||||
|     test.beforeEach(async ({ page, openmctConfig }) => { | ||||
|         const { myItemsFolderName } = openmctConfig; | ||||
|         await startAndAddRestrictedNotebookObject(page); | ||||
|         await nbUtils.dragAndDropEmbed(page, myItemsFolderName); | ||||
|         await dragAndDropEmbed(page, myItemsFolderName); | ||||
|     }); | ||||
|  | ||||
|     test('Allows embeds to be deleted if page unlocked @addInit', async ({ page }) => { | ||||
| @@ -181,6 +181,42 @@ async function startAndAddRestrictedNotebookObject(page) { | ||||
|     return createDomainObjectWithDefaults(page, { type: CUSTOM_NAME }); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function enterTextEntry(page) { | ||||
|     // Click .c-notebook__drag-area | ||||
|     await page.locator(NOTEBOOK_DROP_AREA).click(); | ||||
|  | ||||
|     // enter text | ||||
|     await page.locator('div.c-ne__text').click(); | ||||
|     await page.locator('div.c-ne__text').fill(TEST_TEXT); | ||||
|     await page.locator('div.c-ne__text').press('Enter'); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
| async function dragAndDropEmbed(page, myItemsFolderName) { | ||||
|     // Click button:has-text("Create") | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     // Click li:has-text("Sine Wave Generator") | ||||
|     await page.locator('li:has-text("Sine Wave Generator")').click(); | ||||
|     // Click form[name="mctForm"] >> text=My Items | ||||
|     await page.locator(`form[name="mctForm"] >> text=${myItemsFolderName}`).click(); | ||||
|     // Click text=OK | ||||
|     await page.locator('text=OK').click(); | ||||
|     // Click text=Open MCT My Items >> span >> nth=3 | ||||
|     await page.locator(`text=Open MCT ${myItemsFolderName} >> span`).nth(3).click(); | ||||
|     // Click text=Unnamed CUSTOM_NAME | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         page.locator('text=Unnamed CUSTOM_NAME').click() | ||||
|     ]); | ||||
|  | ||||
|     await page.dragAndDrop('text=UNNAMED SINE WAVE GENERATOR', NOTEBOOK_DROP_AREA); | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @param {import('@playwright/test').Page} page | ||||
|  */ | ||||
|   | ||||
| @@ -39,7 +39,7 @@ async function createNotebookAndEntry(page, iterations = 1) { | ||||
|     createDomainObjectWithDefaults(page, { type: 'Notebook' }); | ||||
|  | ||||
|     for (let iteration = 0; iteration < iterations; iteration++) { | ||||
|         // Create an entry | ||||
|         // Click text=To start a new entry, click here or drag and drop any object | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         const entryLocator = `[aria-label="Notebook Entry Input"] >> nth = ${iteration}`; | ||||
|         await page.locator(entryLocator).click(); | ||||
| @@ -81,8 +81,10 @@ test.describe('Tagging in Notebooks @addInit', () => { | ||||
|     test('Can load tags', async ({ page }) => { | ||||
|  | ||||
|         await createNotebookAndEntry(page); | ||||
|         // Click text=To start a new entry, click here or drag and drop any object | ||||
|         await page.locator('button:has-text("Add Tag")').click(); | ||||
|  | ||||
|         // Click [placeholder="Type to select tag"] | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|  | ||||
|         await expect(page.locator('[aria-label="Autocomplete Options"]')).toContainText("Science"); | ||||
| @@ -95,7 +97,9 @@ test.describe('Tagging in Notebooks @addInit', () => { | ||||
|         await expect(page.locator('[aria-label="Notebook Entry"]')).toContainText("Science"); | ||||
|         await expect(page.locator('[aria-label="Notebook Entry"]')).toContainText("Driving"); | ||||
|  | ||||
|         // Click button:has-text("Add Tag") | ||||
|         await page.locator('button:has-text("Add Tag")').click(); | ||||
|         // Click [placeholder="Type to select tag"] | ||||
|         await page.locator('[placeholder="Type to select tag"]').click(); | ||||
|  | ||||
|         await expect(page.locator('[aria-label="Autocomplete Options"]')).not.toContainText("Science"); | ||||
| @@ -104,56 +108,43 @@ test.describe('Tagging in Notebooks @addInit', () => { | ||||
|     }); | ||||
|     test('Can search for tags', async ({ page }) => { | ||||
|         await createNotebookEntryAndTags(page); | ||||
|         // Click [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').click(); | ||||
|         // Fill [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('sc'); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toContainText("Science"); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).not.toContainText("Driving"); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toContainText("Driving"); | ||||
|  | ||||
|         // Click [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').click(); | ||||
|         // Fill [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('Sc'); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toContainText("Science"); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).not.toContainText("Driving"); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toContainText("Driving"); | ||||
|  | ||||
|         // Click [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').click(); | ||||
|         // Fill [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('Xq'); | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toBeHidden(); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).toBeHidden(); | ||||
|     }); | ||||
|  | ||||
|     test('Can delete tags', async ({ page }) => { | ||||
|         await createNotebookEntryAndTags(page); | ||||
|         await page.locator('[aria-label="Notebook Entries"]').click(); | ||||
|         // Delete Driving | ||||
|         await page.hover('[aria-label="Tag"]:has-text("Driving")'); | ||||
|         await page.locator('[aria-label="Tag"]:has-text("Driving") ~ .c-completed-tag-deletion').click(); | ||||
|         await page.hover('.c-tag__label:has-text("Driving")'); | ||||
|         await page.locator('.c-tag__label:has-text("Driving") ~ .c-completed-tag-deletion').click(); | ||||
|  | ||||
|         await expect(page.locator('[aria-label="Notebook Entry"]')).toContainText("Science"); | ||||
|         await expect(page.locator('[aria-label="Notebook Entry"]')).not.toContainText("Driving"); | ||||
|  | ||||
|         // Fill [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('sc'); | ||||
|         await expect(page.locator('[aria-label="Search Result"]')).not.toContainText("Driving"); | ||||
|     }); | ||||
|  | ||||
|     test('Can delete entries without tags', async ({ page }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/5823' | ||||
|         }); | ||||
|  | ||||
|         await createNotebookEntryAndTags(page); | ||||
|  | ||||
|         await page.locator('text=To start a new entry, click here or drag and drop any object').click(); | ||||
|         const entryLocator = `[aria-label="Notebook Entry Input"] >> nth = 1`; | ||||
|         await page.locator(entryLocator).click(); | ||||
|         await page.locator(entryLocator).fill(`An entry without tags`); | ||||
|         await page.locator('[aria-label="Notebook Entry Input"] >> nth=1').press('Enter'); | ||||
|  | ||||
|         await page.hover('[aria-label="Notebook Entry Input"] >> nth=1'); | ||||
|         await page.locator('button[title="Delete this entry"]').last().click(); | ||||
|         await expect(page.locator('text=This action will permanently delete this entry. Do you wish to continue?')).toBeVisible(); | ||||
|         await page.locator('button:has-text("Ok")').click(); | ||||
|         await expect(page.locator('text=This action will permanently delete this entry. Do you wish to continue?')).toBeHidden(); | ||||
|     }); | ||||
|  | ||||
|     test('Can delete objects with tags and neither return in search', async ({ page }) => { | ||||
|         await createNotebookEntryAndTags(page); | ||||
|         // Delete Notebook | ||||
| @@ -162,12 +153,13 @@ test.describe('Tagging in Notebooks @addInit', () => { | ||||
|         await page.locator('button:has-text("OK")').click(); | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Fill [aria-label="OpenMCT Search"] input[type="search"] | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('Unnamed'); | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|         await expect(page.locator('text=No matching results.')).toBeVisible(); | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('sci'); | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|         await expect(page.locator('text=No matching results.')).toBeVisible(); | ||||
|         await page.locator('[aria-label="OpenMCT Search"] input[type="search"]').fill('dri'); | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|         await expect(page.locator('text=No matching results.')).toBeVisible(); | ||||
|     }); | ||||
|     test('Tags persist across reload', async ({ page }) => { | ||||
|         //Go to baseURL | ||||
|   | ||||
| @@ -56,7 +56,7 @@ test.describe('ExportAsJSON', () => { | ||||
|  | ||||
|         await canvas.hover({trial: true}); | ||||
|  | ||||
|         expect(await canvas.screenshot()).toMatchSnapshot('autoscale-canvas-prepan.png', { animations: 'disabled' }); | ||||
|         expect(await canvas.screenshot()).toMatchSnapshot('autoscale-canvas-prepan'); | ||||
|  | ||||
|         //Alt Drag Start | ||||
|         await page.keyboard.down('Alt'); | ||||
| @@ -80,7 +80,7 @@ test.describe('ExportAsJSON', () => { | ||||
|  | ||||
|         await canvas.hover({trial: true}); | ||||
|  | ||||
|         expect(await canvas.screenshot()).toMatchSnapshot('autoscale-canvas-panned.png', { animations: 'disabled' }); | ||||
|         expect(await canvas.screenshot()).toMatchSnapshot('autoscale-canvas-panned'); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
|   | ||||
| Before Width: | Height: | Size: 16 KiB After Width: | Height: | Size: 16 KiB | 
| After Width: | Height: | Size: 15 KiB | 
| Before Width: | Height: | Size: 15 KiB | 
| Before Width: | Height: | Size: 18 KiB After Width: | Height: | Size: 18 KiB | 
| After Width: | Height: | Size: 18 KiB | 
| Before Width: | Height: | Size: 18 KiB | 
| @@ -1,110 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /* | ||||
| Tests to verify log plot functionality. Note this test suite if very much under active development and should not | ||||
| necessarily be used for reference when writing new tests in this area. | ||||
| */ | ||||
|  | ||||
| const { test, expect } = require('../../../../pluginFixtures'); | ||||
|  | ||||
| test.describe('Legend color in sync with plot color', () => { | ||||
|     test('Testing', async ({ page }) => { | ||||
|         await makeOverlayPlot(page); | ||||
|  | ||||
|         // navigate to plot series color palette | ||||
|         await page.click('.l-browse-bar__actions__edit'); | ||||
|         await page.locator('li.c-tree__item.menus-to-left .c-disclosure-triangle').click(); | ||||
|         await page.locator('.c-click-swatch--menu').click(); | ||||
|         await page.locator('.c-palette__item[style="background: rgb(255, 166, 61);"]').click(); | ||||
|  | ||||
|         // gets color for swatch located in legend | ||||
|         const element = await page.waitForSelector('.plot-series-color-swatch'); | ||||
|         const color = await element.evaluate((el) => { | ||||
|             return window.getComputedStyle(el).getPropertyValue('background-color'); | ||||
|         }); | ||||
|  | ||||
|         expect(color).toBe('rgb(255, 166, 61)'); | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| async function saveOverlayPlot(page) { | ||||
|     // save overlay plot | ||||
|     await page.locator('text=Snapshot Save and Finish Editing Save and Continue Editing >> button').nth(1).click(); | ||||
|  | ||||
|     await Promise.all([ | ||||
|         page.locator('text=Save and Finish Editing').click(), | ||||
|         //Wait for Save Banner to appear | ||||
|         page.waitForSelector('.c-message-banner__message') | ||||
|     ]); | ||||
|     //Wait until Save Banner is gone | ||||
|     await page.locator('.c-message-banner__close-button').click(); | ||||
|     await page.waitForSelector('.c-message-banner__message', { state: 'detached' }); | ||||
| } | ||||
|  | ||||
| async function makeOverlayPlot(page) { | ||||
|     // fresh page with time range from 2022-03-29 22:00:00.000Z to 2022-03-29 22:00:30.000Z | ||||
|     await page.goto('/', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|     // create overlay plot | ||||
|  | ||||
|     await page.locator('button.c-create-button').click(); | ||||
|     await page.locator('li:has-text("Overlay Plot")').click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation({ waitUntil: 'networkidle'}), | ||||
|         page.locator('text=OK').click(), | ||||
|         //Wait for Save Banner to appear | ||||
|         page.waitForSelector('.c-message-banner__message') | ||||
|     ]); | ||||
|     //Wait until Save Banner is gone | ||||
|     await page.locator('.c-message-banner__close-button').click(); | ||||
|     await page.waitForSelector('.c-message-banner__message', { state: 'detached'}); | ||||
|  | ||||
|     // save the overlay plot | ||||
|  | ||||
|     await saveOverlayPlot(page); | ||||
|  | ||||
|     // create a sinewave generator | ||||
|  | ||||
|     await page.locator('button.c-create-button').click(); | ||||
|     await page.locator('li:has-text("Sine Wave Generator")').click(); | ||||
|  | ||||
|     // Click OK to make generator | ||||
|  | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation({ waitUntil: 'networkidle'}), | ||||
|         page.locator('text=OK').click(), | ||||
|         //Wait for Save Banner to appear | ||||
|         page.waitForSelector('.c-message-banner__message') | ||||
|     ]); | ||||
|     //Wait until Save Banner is gone | ||||
|     await page.locator('.c-message-banner__close-button').click(); | ||||
|     await page.waitForSelector('.c-message-banner__message', { state: 'detached'}); | ||||
|  | ||||
|     // click on overlay plot | ||||
|  | ||||
|     await page.locator('text=Open MCT My Items >> span').nth(3).click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         page.locator('text=Unnamed Overlay Plot').first().click() | ||||
|     ]); | ||||
| } | ||||
| @@ -1,54 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /* | ||||
| * This test suite is dedicated to testing the rendering and interaction of plots. | ||||
| * | ||||
| */ | ||||
|  | ||||
| const { test, expect } = require('../../../../baseFixtures'); | ||||
| const { createDomainObjectWithDefaults } = require('../../../../appActions'); | ||||
|  | ||||
| test.describe('Plot Integrity Testing @unstable', () => { | ||||
|     let sineWaveGeneratorObject; | ||||
|  | ||||
|     test.beforeEach(async ({ page }) => { | ||||
|         //Open a browser, navigate to the main page, and wait until all networkevents to resolve | ||||
|         await page.goto('./', { waitUntil: 'networkidle' }); | ||||
|         sineWaveGeneratorObject = await createDomainObjectWithDefaults(page, { type: 'Sine Wave Generator' }); | ||||
|     }); | ||||
|  | ||||
|     test('Plots do not re-request data when a plot is clicked', async ({ page }) => { | ||||
|         //Navigate to Sine Wave Generator | ||||
|         await page.goto(sineWaveGeneratorObject.url); | ||||
|         //Capture the number of plots points and store as const name numberOfPlotPoints | ||||
|         //Click on the plot canvas | ||||
|         await page.locator('canvas').nth(1).click(); | ||||
|         //No request was made to get historical data | ||||
|         const createMineFolderRequests = []; | ||||
|         page.on('request', req => { | ||||
|             // eslint-disable-next-line playwright/no-conditional-in-test | ||||
|             createMineFolderRequests.push(req); | ||||
|         }); | ||||
|         expect(createMineFolderRequests.length).toEqual(0); | ||||
|     }); | ||||
| }); | ||||
| @@ -168,23 +168,3 @@ test.describe('Time conductor input fields real-time mode', () => { | ||||
|         // select an option and verify the offsets are updated correctly | ||||
|     }); | ||||
| }); | ||||
|  | ||||
| test.describe('Time Conductor History', () => { | ||||
|     test("shows milliseconds on hover @unstable", async ({ page }) => { | ||||
|         test.info().annotations.push({ | ||||
|             type: 'issue', | ||||
|             description: 'https://github.com/nasa/openmct/issues/4386' | ||||
|         }); | ||||
|         // Navigate to Open MCT in Fixed Time Mode, UTC Time System | ||||
|         // with startBound at 2022-01-01 00:00:00.000Z | ||||
|         // and endBound at 2022-01-01 00:00:00.200Z | ||||
|         await page.goto('./#/browse/mine?view=grid&tc.mode=fixed&tc.startBound=1640995200000&tc.endBound=1640995200200&tc.timeSystem=utc&hideInspector=true', { waitUntil: 'networkidle' }); | ||||
|         await page.locator("[aria-label='Time Conductor History']").hover({ trial: true}); | ||||
|         await page.locator("[aria-label='Time Conductor History']").click(); | ||||
|  | ||||
|         // Validate history item format | ||||
|         const historyItem = page.locator('text="2022-01-01 00:00:00 + 200ms"'); | ||||
|         await expect(historyItem).toBeEnabled(); | ||||
|         await expect(historyItem).toHaveAttribute('title', '2022-01-01 00:00:00.000 - 2022-01-01 00:00:00.200'); | ||||
|     }); | ||||
| }); | ||||
|   | ||||
| @@ -111,7 +111,7 @@ test.describe("Search Tests @unstable", () => { | ||||
|         expect(await searchResults.count()).toBe(0); | ||||
|  | ||||
|         // Verify proper message appears | ||||
|         await expect(page.locator('text=No results found')).toBeVisible(); | ||||
|         await expect(page.locator('text=No matching results.')).toBeVisible(); | ||||
|     }); | ||||
|  | ||||
|     test('Validate single object in search result @couchdb', async ({ page }) => { | ||||
| @@ -220,7 +220,7 @@ async function createObjectsForSearch(page, myItemsFolderName) { | ||||
|     ]); | ||||
|  | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     await page.locator('li[title="A digital clock that uses system time and supports a variety of display formats and timezones."]').click(); | ||||
|     await page.locator('li[title="A UTC-based clock that supports a variety of display formats. Clocks can be added to Display Layouts."]').click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         await page.locator('text=Properties Title Notes >> input[type="text"] >> nth=0').fill('Clock A'), | ||||
| @@ -229,7 +229,7 @@ async function createObjectsForSearch(page, myItemsFolderName) { | ||||
|     ]); | ||||
|  | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     await page.locator('li[title="A digital clock that uses system time and supports a variety of display formats and timezones."]').click(); | ||||
|     await page.locator('li[title="A UTC-based clock that supports a variety of display formats. Clocks can be added to Display Layouts."]').click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         await page.locator('text=Properties Title Notes >> input[type="text"] >> nth=0').fill('Clock B'), | ||||
| @@ -238,7 +238,7 @@ async function createObjectsForSearch(page, myItemsFolderName) { | ||||
|     ]); | ||||
|  | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     await page.locator('li[title="A digital clock that uses system time and supports a variety of display formats and timezones."]').click(); | ||||
|     await page.locator('li[title="A UTC-based clock that supports a variety of display formats. Clocks can be added to Display Layouts."]').click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         await page.locator('text=Properties Title Notes >> input[type="text"] >> nth=0').fill('Clock C'), | ||||
| @@ -247,7 +247,7 @@ async function createObjectsForSearch(page, myItemsFolderName) { | ||||
|     ]); | ||||
|  | ||||
|     await page.locator('button:has-text("Create")').click(); | ||||
|     await page.locator('li[title="A digital clock that uses system time and supports a variety of display formats and timezones."]').click(); | ||||
|     await page.locator('li[title="A UTC-based clock that supports a variety of display formats. Clocks can be added to Display Layouts."]').click(); | ||||
|     await Promise.all([ | ||||
|         page.waitForNavigation(), | ||||
|         await page.locator('text=Properties Title Notes >> input[type="text"] >> nth=0').fill('Clock D'), | ||||
|   | ||||
| @@ -22,7 +22,7 @@ | ||||
|  | ||||
| /* | ||||
| Collection of Visual Tests set to run in a default context. The tests within this suite | ||||
| are only meant to run against openmct started by `npm start` within the | ||||
| are only meant to run against openmct's app.js started by `npm run start` within the | ||||
| `./e2e/playwright-visual.config.js` file. | ||||
|  | ||||
| */ | ||||
|   | ||||
| @@ -22,7 +22,7 @@ | ||||
|  | ||||
| /* | ||||
| Collection of Visual Tests set to run in a default context. The tests within this suite | ||||
| are only meant to run against openmct started by `npm start` within the | ||||
| are only meant to run against openmct's app.js started by `npm run start` within the | ||||
| `./e2e/playwright-visual.config.js` file. | ||||
|  | ||||
| These should only use functional expect statements to verify assumptions about the state | ||||
|   | ||||
| @@ -1,51 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| const { test } = require('../../pluginFixtures'); | ||||
| const percySnapshot = require('@percy/playwright'); | ||||
| const { expandTreePaneItemByName, createDomainObjectWithDefaults } = require('../../appActions'); | ||||
|  | ||||
| test.describe('Visual - Notebook', () => { | ||||
|     test('Accepts dropped objects as embeds @unstable', async ({ page, theme, openmctConfig }) => { | ||||
|         const { myItemsFolderName } = openmctConfig; | ||||
|         await page.goto('./#/browse/mine', { waitUntil: 'networkidle' }); | ||||
|  | ||||
|         // Create Notebook | ||||
|         const notebook = await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Notebook', | ||||
|             name: "Embed Test Notebook" | ||||
|         }); | ||||
|         // Create Overlay Plot | ||||
|         await createDomainObjectWithDefaults(page, { | ||||
|             type: 'Overlay Plot', | ||||
|             name: "Dropped Overlay Plot" | ||||
|         }); | ||||
|  | ||||
|         await expandTreePaneItemByName(page, myItemsFolderName); | ||||
|  | ||||
|         await page.goto(notebook.url); | ||||
|         await page.dragAndDrop('role=treeitem[name=/Dropped Overlay Plot/]', '.c-notebook__drag-area'); | ||||
|  | ||||
|         await percySnapshot(page, `Notebook w/ dropped embed (theme: ${theme})`); | ||||
|  | ||||
|     }); | ||||
| }); | ||||
| @@ -36,7 +36,7 @@ define([ | ||||
|  | ||||
|         openmct.types.addType("example.state-generator", { | ||||
|             name: "State Generator", | ||||
|             description: "For development use. Generates example enumerated telemetry by cycling through a given set of states.", | ||||
|             description: "For development use.  Generates test enumerated telemetry by cycling through a given set of states", | ||||
|             cssClass: "icon-generator-telemetry", | ||||
|             creatable: true, | ||||
|             form: [ | ||||
|   | ||||
							
								
								
									
										12
									
								
								jsdoc.json
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,12 @@ | ||||
| { | ||||
|     "source": { | ||||
|         "include": [ | ||||
|             "src/" | ||||
|         ], | ||||
|         "includePattern": "src/.+\\.js$", | ||||
|         "excludePattern": ".+\\Spec\\.js$|lib/.+" | ||||
|     }, | ||||
|     "plugins": [ | ||||
|         "plugins/markdown" | ||||
|     ] | ||||
| } | ||||
| @@ -23,32 +23,14 @@ | ||||
| /*global module,process*/ | ||||
|  | ||||
| module.exports = (config) => { | ||||
|     let webpackConfig; | ||||
|     let browsers; | ||||
|     let singleRun; | ||||
|  | ||||
|     if (process.env.KARMA_DEBUG) { | ||||
|         webpackConfig = require('./webpack.dev.js'); | ||||
|         browsers = ['ChromeDebugging']; | ||||
|         singleRun = false; | ||||
|     } else { | ||||
|         webpackConfig = require('./webpack.coverage.js'); | ||||
|         browsers = ['ChromeHeadless']; | ||||
|         singleRun = true; | ||||
|     } | ||||
|  | ||||
|     const webpackConfig = require('./webpack.coverage.js'); | ||||
|     delete webpackConfig.output; | ||||
|     // karma doesn't support webpack entry | ||||
|     delete webpackConfig.entry; | ||||
|  | ||||
|     config.set({ | ||||
|         basePath: '', | ||||
|         frameworks: ['jasmine', 'webpack'], | ||||
|         frameworks: ['jasmine'], | ||||
|         files: [ | ||||
|             'indexTest.js', | ||||
|             // included means: should the files be included in the browser using <script> tag? | ||||
|             // We don't want them as a <script> because the shared worker source | ||||
|             // needs loaded remotely by the shared worker process. | ||||
|             { | ||||
|                 pattern: 'dist/couchDBChangesFeed.js*', | ||||
|                 included: false | ||||
| @@ -64,7 +46,7 @@ module.exports = (config) => { | ||||
|         ], | ||||
|         port: 9876, | ||||
|         reporters: ['spec', 'junit', 'coverage-istanbul'], | ||||
|         browsers, | ||||
|         browsers: [process.env.NODE_ENV === 'debug' ? 'ChromeDebugging' : 'ChromeHeadless'], | ||||
|         client: { | ||||
|             jasmine: { | ||||
|                 random: false, | ||||
| @@ -88,7 +70,6 @@ module.exports = (config) => { | ||||
|         }, | ||||
|         coverageIstanbulReporter: { | ||||
|             fixWebpackSourcePaths: true, | ||||
|             skipFilesWithNoCoverage: true, | ||||
|             dir: "coverage/unit", //Sets coverage file to be consumed by codecov.io | ||||
|             reports: ['lcovonly'] | ||||
|         }, | ||||
| @@ -109,7 +90,7 @@ module.exports = (config) => { | ||||
|             stats: 'errors-warnings' | ||||
|         }, | ||||
|         concurrency: 1, | ||||
|         singleRun, | ||||
|         singleRun: true, | ||||
|         browserNoActivityTimeout: 400000 | ||||
|     }); | ||||
| }; | ||||
|   | ||||
							
								
								
									
										96
									
								
								lighthouserc.yml
									
									
									
									
									
										Normal file
									
								
							
							
						
						| @@ -0,0 +1,96 @@ | ||||
| --- | ||||
| ci: | ||||
|   collect: | ||||
|     urls: | ||||
|     - http://localhost/ | ||||
|     numberOfRuns: 5 | ||||
|     settings: | ||||
|       onlyCategories: | ||||
|       - performance | ||||
|       - best-practices | ||||
|   upload: | ||||
|     target: temporary-public-storage | ||||
|   assert: | ||||
|     preset: lighthouse:recommended | ||||
|     assertions: | ||||
|       ### Applicable assertions | ||||
|       bootup-time: | ||||
|       - warn | ||||
|       - minScore: 0.88 #Original value was calculated at 0.88 | ||||
|       dom-size:  | ||||
|       - error | ||||
|       - maxNumericValue: 200 #Original value was calculated at 188 | ||||
|       first-contentful-paint: | ||||
|       - error | ||||
|       - minScore: 0.07 #Original value was calculated at 0.08 | ||||
|       mainthread-work-breakdown: | ||||
|       - warn | ||||
|       - minScore: 0.8 #Original value was calculated at 0.8 | ||||
|       unused-javascript: | ||||
|       - warn | ||||
|       - maxLength: 1 | ||||
|       - error | ||||
|       - maxNumericValue: 2000 #Original value was calculated at 1855 | ||||
|       unused-css-rules: warn | ||||
|       installable-manifest: warn | ||||
|       service-worker: warn | ||||
|       ### Disabled seo, accessibility, and pwa assertions, below | ||||
|       categories:seo: 'off' | ||||
|       categories:accessibility: 'off' | ||||
|       categories:pwa: 'off' | ||||
|       accesskeys: 'off' | ||||
|       apple-touch-icon: 'off' | ||||
|       aria-allowed-attr: 'off' | ||||
|       aria-command-name: 'off' | ||||
|       aria-hidden-body: 'off' | ||||
|       aria-hidden-focus: 'off' | ||||
|       aria-input-field-name: 'off' | ||||
|       aria-meter-name: 'off' | ||||
|       aria-progressbar-name: 'off' | ||||
|       aria-required-attr: 'off' | ||||
|       aria-required-children: 'off' | ||||
|       aria-required-parent: 'off' | ||||
|       aria-roles: 'off' | ||||
|       aria-toggle-field-name: 'off' | ||||
|       aria-tooltip-name: 'off' | ||||
|       aria-treeitem-name: 'off' | ||||
|       aria-valid-attr: 'off' | ||||
|       aria-valid-attr-value: 'off' | ||||
|       button-name: 'off' | ||||
|       bypass: 'off' | ||||
|       canonical: 'off' | ||||
|       color-contrast: 'off' | ||||
|       content-width: 'off' | ||||
|       crawlable-anchors: 'off' | ||||
|       csp-xss: 'off' | ||||
|       font-display: 'off' | ||||
|       font-size: 'off' | ||||
|       maskable-icon: 'off' | ||||
|       heading-order: 'off' | ||||
|       hreflang: 'off' | ||||
|       html-has-lang: 'off' | ||||
|       html-lang-valid: 'off' | ||||
|       http-status-code: 'off' | ||||
|       image-alt: 'off' | ||||
|       input-image-alt: 'off' | ||||
|       is-crawlable: 'off' | ||||
|       label: 'off' | ||||
|       link-name: 'off' | ||||
|       link-text: 'off' | ||||
|       list: 'off' | ||||
|       listitem: 'off' | ||||
|       meta-description: 'off' | ||||
|       meta-refresh: 'off' | ||||
|       meta-viewport: 'off' | ||||
|       object-alt: 'off' | ||||
|       plugins: 'off' | ||||
|       robots-txt: 'off' | ||||
|       splash-screen: 'off' | ||||
|       tabindex: 'off' | ||||
|       tap-targets: 'off' | ||||
|       td-headers-attr: 'off' | ||||
|       th-has-data-cells: 'off' | ||||
|       themed-omnibox: 'off' | ||||
|       valid-lang: 'off' | ||||
|       video-caption: 'off' | ||||
|       viewport: 'off' | ||||
							
								
								
									
										45
									
								
								openmct.js
									
									
									
									
									
								
							
							
						
						| @@ -30,53 +30,8 @@ if (document.currentScript) { | ||||
|     } | ||||
| } | ||||
|  | ||||
| /** | ||||
|  * @typedef {object} BuildInfo | ||||
|  * @property {string} version | ||||
|  * @property {string} buildDate | ||||
|  * @property {string} revision | ||||
|  * @property {string} branch | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {object} OpenMCT | ||||
|  * @property {BuildInfo} buildInfo | ||||
|  * @property {*} selection | ||||
|  * @property {import('./src/api/time/TimeAPI').default} time | ||||
|  * @property {import('./src/api/composition/CompositionAPI').default} composition | ||||
|  * @property {*} objectViews | ||||
|  * @property {*} inspectorViews | ||||
|  * @property {*} propertyEditors | ||||
|  * @property {*} toolbars | ||||
|  * @property {*} types | ||||
|  * @property {import('./src/api/objects/ObjectAPI').default} objects | ||||
|  * @property {import('./src/api/telemetry/TelemetryAPI').default} telemetry | ||||
|  * @property {import('./src/api/indicators/IndicatorAPI').default} indicators | ||||
|  * @property {import('./src/api/user/UserAPI').default} user | ||||
|  * @property {import('./src/api/notifications/NotificationAPI').default} notifications | ||||
|  * @property {import('./src/api/Editor').default} editor | ||||
|  * @property {import('./src/api/overlays/OverlayAPI')} overlays | ||||
|  * @property {import('./src/api/menu/MenuAPI').default} menus | ||||
|  * @property {import('./src/api/actions/ActionsAPI').default} actions | ||||
|  * @property {import('./src/api/status/StatusAPI').default} status | ||||
|  * @property {*} priority | ||||
|  * @property {import('./src/ui/router/ApplicationRouter')} router | ||||
|  * @property {import('./src/api/faultmanagement/FaultManagementAPI').default} faults | ||||
|  * @property {import('./src/api/forms/FormsAPI').default} forms | ||||
|  * @property {import('./src/api/Branding').default} branding | ||||
|  * @property {import('./src/api/annotation/AnnotationAPI').default} annotation | ||||
|  * @property {{(plugin: OpenMCTPlugin) => void}} install | ||||
|  * @property {{() => string}} getAssetPath | ||||
|  * @property {{(domElement: HTMLElement, isHeadlessMode: boolean) => void}} start | ||||
|  * @property {{() => void}} startHeadless | ||||
|  * @property {{() => void}} destroy | ||||
|  * @property {OpenMCTPlugin[]} plugins | ||||
|  * @property {OpenMCTComponent[]} components | ||||
|  */ | ||||
|  | ||||
| const MCT = require('./src/MCT'); | ||||
|  | ||||
| /** @type {OpenMCT} */ | ||||
| const openmct = new MCT(); | ||||
|  | ||||
| module.exports = openmct; | ||||
|   | ||||
							
								
								
									
										62
									
								
								package.json
									
									
									
									
									
								
							
							
						
						| @@ -1,30 +1,35 @@ | ||||
| { | ||||
|   "name": "openmct", | ||||
|   "version": "2.1.2", | ||||
|   "version": "2.1.0", | ||||
|   "description": "The Open MCT core platform", | ||||
|   "devDependencies": { | ||||
|     "@babel/eslint-parser": "7.18.9", | ||||
|     "@braintree/sanitize-url": "6.0.0", | ||||
|     "@percy/cli": "1.11.0", | ||||
|     "@percy/cli": "1.7.2", | ||||
|     "@percy/playwright": "1.0.4", | ||||
|     "@playwright/test": "1.25.2", | ||||
|     "@types/jasmine": "4.3.0", | ||||
|     "@types/lodash": "4.14.186", | ||||
|     "@playwright/test": "1.25.0", | ||||
|     "@types/eventemitter3": "^1.0.0", | ||||
|     "@types/jasmine": "^4.0.1", | ||||
|     "@types/karma": "^6.3.2", | ||||
|     "@types/lodash": "^4.14.178", | ||||
|     "@types/mocha": "^9.1.0", | ||||
|     "babel-loader": "8.2.5", | ||||
|     "babel-plugin-istanbul": "6.1.1", | ||||
|     "codecov": "3.8.3", | ||||
|     "comma-separated-values": "3.6.4", | ||||
|     "codecov":"3.8.3", | ||||
|     "copy-webpack-plugin": "11.0.0", | ||||
|     "cross-env": "7.0.3", | ||||
|     "css-loader": "6.7.1", | ||||
|     "d3-axis": "3.0.0", | ||||
|     "d3-scale": "3.3.0", | ||||
|     "d3-selection": "3.0.0", | ||||
|     "eslint": "8.25.0", | ||||
|     "eslint": "8.23.0", | ||||
|     "eslint-plugin-compat": "4.0.2", | ||||
|     "eslint-plugin-playwright": "0.11.2", | ||||
|     "eslint-plugin-vue": "9.6.0", | ||||
|     "eslint-plugin-playwright": "0.11.1", | ||||
|     "eslint-plugin-vue": "9.3.0", | ||||
|     "eslint-plugin-you-dont-need-lodash-underscore": "6.12.0", | ||||
|     "eventemitter3": "1.2.0", | ||||
|     "express": "4.13.1", | ||||
|     "file-saver": "2.0.5", | ||||
|     "git-rev-sync": "3.0.2", | ||||
|     "html2canvas": "1.4.1", | ||||
| @@ -46,42 +51,41 @@ | ||||
|     "moment": "2.29.4", | ||||
|     "moment-duration-format": "2.3.2", | ||||
|     "moment-timezone": "0.5.37", | ||||
|     "nyc": "15.1.0", | ||||
|     "nyc":"15.1.0", | ||||
|     "painterro": "1.2.78", | ||||
|     "playwright-core": "1.25.2", | ||||
|     "plotly.js-basic-dist": "2.14.0", | ||||
|     "plotly.js-gl2d-dist": "2.14.0", | ||||
|     "printj": "1.3.1", | ||||
|     "request": "2.88.2", | ||||
|     "resolve-url-loader": "5.0.0", | ||||
|     "sass": "1.55.0", | ||||
|     "sass": "1.54.4", | ||||
|     "sass-loader": "13.0.2", | ||||
|     "sinon": "14.0.0", | ||||
|     "style-loader": "^3.3.1", | ||||
|     "typescript": "4.8.4", | ||||
|     "style-loader": "^1.0.1", | ||||
|     "uuid": "9.0.0", | ||||
|     "vue": "2.6.14", | ||||
|     "vue-eslint-parser": "9.1.0", | ||||
|     "vue-eslint-parser": "9.0.2", | ||||
|     "vue-loader": "15.9.8", | ||||
|     "vue-template-compiler": "2.6.14", | ||||
|     "webpack": "5.74.0", | ||||
|     "webpack": "5.68.0", | ||||
|     "webpack-cli": "4.10.0", | ||||
|     "webpack-dev-server": "4.11.1", | ||||
|     "webpack-dev-middleware": "5.3.3", | ||||
|     "webpack-hot-middleware": "2.25.1", | ||||
|     "webpack-merge": "5.8.0" | ||||
|   }, | ||||
|   "scripts": { | ||||
|     "clean": "rm -rf ./dist ./node_modules ./package-lock.json", | ||||
|     "clean-test-lint": "npm run clean; npm install; npm run test; npm run lint", | ||||
|     "start": "npx webpack serve --config ./webpack.dev.js", | ||||
|     "start:coverage": "npx webpack serve --config ./webpack.coverage.js", | ||||
|     "start": "node app.js", | ||||
|     "lint": "eslint example src e2e --ext .js,.vue openmct.js --max-warnings=0", | ||||
|     "lint:fix": "eslint example src e2e --ext .js,.vue openmct.js --fix", | ||||
|     "build:prod": "webpack --config webpack.prod.js", | ||||
|     "build:prod": "cross-env webpack --config webpack.prod.js", | ||||
|     "build:dev": "webpack --config webpack.dev.js", | ||||
|     "build:coverage": "webpack --config webpack.coverage.js", | ||||
|     "build:watch": "webpack --config webpack.dev.js --watch", | ||||
|     "info": "npx envinfo --system --browsers --npmPackages --binaries --languages --markdown", | ||||
|     "test": "karma start", | ||||
|     "test:debug": "KARMA_DEBUG=true karma start", | ||||
|     "test": "cross-env NODE_ENV=test NODE_OPTIONS=\"--max_old_space_size=4096\" karma start --single-run", | ||||
|     "test:debug": "cross-env NODE_ENV=debug karma start --no-single-run", | ||||
|     "test:e2e": "npx playwright test", | ||||
|     "test:e2e:couchdb": "npx playwright test --config=e2e/playwright-ci.config.js --project=chrome --grep @couchdb", | ||||
|     "test:e2e:stable": "npx playwright test --config=e2e/playwright-ci.config.js --project=chrome --grep-invert \"@unstable|@couchdb\"", | ||||
| @@ -91,13 +95,14 @@ | ||||
|     "test:e2e:visual": "percy exec --config ./e2e/.percy.yml -- npx playwright test --config=e2e/playwright-visual.config.js --grep-invert @unstable", | ||||
|     "test:e2e:full": "npx playwright test --config=e2e/playwright-ci.config.js --grep-invert @couchdb", | ||||
|     "test:perf": "npx playwright test --config=e2e/playwright-performance.config.js", | ||||
|     "test:watch": "cross-env NODE_ENV=test NODE_OPTIONS=\"--max_old_space_size=4096\" karma start --no-single-run", | ||||
|     "update-about-dialog-copyright": "perl -pi -e 's/20\\d\\d\\-202\\d/2014\\-2022/gm' ./src/ui/layout/AboutDialog.vue", | ||||
|     "update-copyright-date": "npm run update-about-dialog-copyright && grep -lr --null --include=*.{js,scss,vue,ts,sh,html,md,frag} 'Copyright (c) 20' . | xargs -r0 perl -pi -e 's/Copyright\\s\\(c\\)\\s20\\d\\d\\-20\\d\\d/Copyright \\(c\\)\\ 2014\\-2022/gm'", | ||||
|     "cov:e2e:report": "nyc report --reporter=lcovonly --report-dir=./coverage/e2e", | ||||
|     "cov:e2e:full:publish": "codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-full", | ||||
|     "cov:e2e:stable:publish": "codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-stable", | ||||
|     "cov:unit:publish": "codecov --disable=gcov -f ./coverage/unit/lcov.info -F unit", | ||||
|     "prepare": "npm run build:prod && npx tsc" | ||||
|     "cov:e2e:report":"nyc report --reporter=lcovonly --report-dir=./coverage/e2e", | ||||
|     "cov:e2e:full:publish":"codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-full", | ||||
|     "cov:e2e:stable:publish":"codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-stable", | ||||
|     "cov:unit:publish":"codecov --disable=gcov -f ./coverage/unit/lcov.info -F unit", | ||||
|     "prepare": "npm run build:prod" | ||||
|   }, | ||||
|   "repository": { | ||||
|     "type": "git", | ||||
| @@ -106,6 +111,9 @@ | ||||
|   "engines": { | ||||
|     "node": ">=14.19.1" | ||||
|   }, | ||||
|   "overrides": { | ||||
|     "core-js": "3.21.1" | ||||
|   }, | ||||
|   "browserslist": [ | ||||
|     "Firefox ESR", | ||||
|     "not IE 11", | ||||
|   | ||||
							
								
								
									
										10
									
								
								src/MCT.js
									
									
									
									
									
								
							
							
						
						| @@ -19,7 +19,7 @@ | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
| /* eslint-disable no-undef */ | ||||
|  | ||||
| define([ | ||||
|     'EventEmitter', | ||||
|     './api/api', | ||||
| @@ -81,11 +81,13 @@ define([ | ||||
|     /** | ||||
|      * The Open MCT application. This may be configured by installing plugins | ||||
|      * or registering extensions before the application is started. | ||||
|      * @constructor | ||||
|      * @class MCT | ||||
|      * @memberof module:openmct | ||||
|      * @augments {EventEmitter} | ||||
|      */ | ||||
|     function MCT() { | ||||
|         EventEmitter.call(this); | ||||
|         /* eslint-disable no-undef */ | ||||
|         this.buildInfo = { | ||||
|             version: __OPENMCT_VERSION__, | ||||
|             buildDate: __OPENMCT_BUILD_DATE__, | ||||
| @@ -99,7 +101,7 @@ define([ | ||||
|             * Tracks current selection state of the application. | ||||
|             * @private | ||||
|             */ | ||||
|             ['selection', () => new Selection.default(this)], | ||||
|             ['selection', () => new Selection(this)], | ||||
|  | ||||
|             /** | ||||
|              * MCT's time conductor, which may be used to synchronize view contents | ||||
| @@ -123,7 +125,7 @@ define([ | ||||
|              * @memberof module:openmct.MCT# | ||||
|              * @name composition | ||||
|              */ | ||||
|             ['composition', () => new api.CompositionAPI.default(this)], | ||||
|             ['composition', () => new api.CompositionAPI(this)], | ||||
|  | ||||
|             /** | ||||
|              * Registry for views of domain objects which should appear in the | ||||
|   | ||||
| @@ -23,7 +23,8 @@ | ||||
| let brandingOptions = {}; | ||||
|  | ||||
| /** | ||||
|  * @typedef {object} BrandingOptions | ||||
|  * @typedef {Object} BrandingOptions | ||||
|  * @memberOf openmct/branding | ||||
|  * @property {string} smallLogoImage URL to the image to use as the applications logo. | ||||
|  * This logo will appear on every screen and when clicked will launch the about dialog. | ||||
|  * @property {string} aboutHtml Custom content for the about screen. When defined the | ||||
|   | ||||
| @@ -63,9 +63,10 @@ export default class Editor extends EventEmitter { | ||||
|             .then(() => { | ||||
|                 this.editing = false; | ||||
|                 this.emit('isEditing', false); | ||||
|                 this.openmct.objects.endTransaction(); | ||||
|             }).catch(error => { | ||||
|                 throw error; | ||||
|             }).finally(() => { | ||||
|                 this.openmct.objects.endTransaction(); | ||||
|             }); | ||||
|     } | ||||
|  | ||||
|   | ||||
| @@ -1,80 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| import { | ||||
|     createOpenMct, resetApplicationState | ||||
| } from '../utils/testing'; | ||||
|  | ||||
| describe('The Editor API', () => { | ||||
|     let openmct; | ||||
|  | ||||
|     beforeEach((done) => { | ||||
|         openmct = createOpenMct(); | ||||
|         openmct.on('start', done); | ||||
|  | ||||
|         spyOn(openmct.objects, 'endTransaction'); | ||||
|  | ||||
|         openmct.startHeadless(); | ||||
|     }); | ||||
|  | ||||
|     afterEach(() => { | ||||
|         return resetApplicationState(openmct); | ||||
|     }); | ||||
|  | ||||
|     it('opens a transaction on edit', () => { | ||||
|         expect( | ||||
|             openmct.objects.isTransactionActive() | ||||
|         ).toBeFalse(); | ||||
|         openmct.editor.edit(); | ||||
|         expect( | ||||
|             openmct.objects.isTransactionActive() | ||||
|         ).toBeTrue(); | ||||
|     }); | ||||
|  | ||||
|     it('closes an open transaction on successful save', async () => { | ||||
|         spyOn(openmct.objects, 'getActiveTransaction') | ||||
|             .and.returnValue({ | ||||
|                 commit: () => Promise.resolve(true) | ||||
|             }); | ||||
|  | ||||
|         openmct.editor.edit(); | ||||
|         await openmct.editor.save(); | ||||
|  | ||||
|         expect( | ||||
|             openmct.objects.endTransaction | ||||
|         ).toHaveBeenCalled(); | ||||
|     }); | ||||
|  | ||||
|     it('does not close an open transaction on failed save', async () => { | ||||
|         spyOn(openmct.objects, 'getActiveTransaction') | ||||
|             .and.returnValue({ | ||||
|                 commit: () => Promise.reject() | ||||
|             }); | ||||
|  | ||||
|         openmct.editor.edit(); | ||||
|         await openmct.editor.save().catch(() => {}); | ||||
|  | ||||
|         expect( | ||||
|             openmct.objects.endTransaction | ||||
|         ).not.toHaveBeenCalled(); | ||||
|     }); | ||||
| }); | ||||
| @@ -22,7 +22,6 @@ | ||||
|  | ||||
| import { v4 as uuid } from 'uuid'; | ||||
| import EventEmitter from 'EventEmitter'; | ||||
| import _ from 'lodash'; | ||||
|  | ||||
| /** | ||||
|  * @readonly | ||||
| @@ -43,28 +42,19 @@ const ANNOTATION_TYPES = Object.freeze({ | ||||
|  | ||||
| const ANNOTATION_TYPE = 'annotation'; | ||||
|  | ||||
| const ANNOTATION_LAST_CREATED = 'annotationLastCreated'; | ||||
|  | ||||
| /** | ||||
|  * @typedef {Object} Tag | ||||
|  * @property {String} key a unique identifier for the tag | ||||
|  * @property {String} backgroundColor eg. "#cc0000" | ||||
|  * @property {String} foregroundColor eg. "#ffffff" | ||||
|  */ | ||||
|  | ||||
| export default class AnnotationAPI extends EventEmitter { | ||||
|  | ||||
|     /** | ||||
|      * @param {OpenMCT} openmct | ||||
|      */ | ||||
|     constructor(openmct) { | ||||
|         super(); | ||||
|         this.openmct = openmct; | ||||
|         this.availableTags = {}; | ||||
|  | ||||
|         this.ANNOTATION_TYPES = ANNOTATION_TYPES; | ||||
|         this.ANNOTATION_TYPE = ANNOTATION_TYPE; | ||||
|         this.ANNOTATION_LAST_CREATED = ANNOTATION_LAST_CREATED; | ||||
|  | ||||
|         this.openmct.types.addType(ANNOTATION_TYPE, { | ||||
|             name: 'Annotation', | ||||
| @@ -73,7 +63,6 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|             cssClass: 'icon-notebook', | ||||
|             initialize: function (domainObject) { | ||||
|                 domainObject.targets = domainObject.targets || {}; | ||||
|                 domainObject._deleted = domainObject._deleted || false; | ||||
|                 domainObject.originalContextPath = domainObject.originalContextPath || ''; | ||||
|                 domainObject.tags = domainObject.tags || []; | ||||
|                 domainObject.contentText = domainObject.contentText || ''; | ||||
| @@ -123,7 +112,6 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|                 namespace | ||||
|             }, | ||||
|             tags, | ||||
|             _deleted: false, | ||||
|             annotationType, | ||||
|             contentText, | ||||
|             originalContextPath | ||||
| @@ -139,7 +127,6 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|         const success = await this.openmct.objects.save(createdObject); | ||||
|         if (success) { | ||||
|             this.emit('annotationCreated', createdObject); | ||||
|             this.#updateAnnotationModified(domainObject); | ||||
|  | ||||
|             return createdObject; | ||||
|         } else { | ||||
| @@ -147,32 +134,14 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     #updateAnnotationModified(domainObject) { | ||||
|         this.openmct.objects.mutate(domainObject, this.ANNOTATION_LAST_CREATED, Date.now()); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method defineTag | ||||
|     * @param {String} key a unique identifier for the tag | ||||
|     * @param {Tag} tagsDefinition the definition of the tag to add | ||||
|     */ | ||||
|     defineTag(tagKey, tagsDefinition) { | ||||
|         this.availableTags[tagKey] = tagsDefinition; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method isAnnotation | ||||
|     * @param {import('../objects/ObjectAPI').DomainObject} domainObject domainObject the domainObject in question | ||||
|     * @returns {Boolean} Returns true if the domain object is an annotation | ||||
|     */ | ||||
|     isAnnotation(domainObject) { | ||||
|         return domainObject && (domainObject.type === ANNOTATION_TYPE); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method getAvailableTags | ||||
|     * @returns {Tag[]} Returns an array of the available tags that have been loaded | ||||
|     */ | ||||
|     getAvailableTags() { | ||||
|         if (this.availableTags) { | ||||
|             const rearrangedToArray = Object.keys(this.availableTags).map(tagKey => { | ||||
| @@ -188,26 +157,18 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method getAnnotations | ||||
|     * @param {String} query - The keystring of the domain object to search for annotations for | ||||
|     * @returns {import('../objects/ObjectAPI').DomainObject[]} Returns an array of domain objects that match the search query | ||||
|     */ | ||||
|     async getAnnotations(query) { | ||||
|         const searchResults = (await Promise.all(this.openmct.objects.search(query, null, this.openmct.objects.SEARCH_TYPES.ANNOTATIONS))).flat(); | ||||
|     async getAnnotation(query, searchType) { | ||||
|         let foundAnnotation = null; | ||||
|  | ||||
|         return searchResults; | ||||
|         const searchResults = (await Promise.all(this.openmct.objects.search(query, null, searchType))).flat(); | ||||
|         if (searchResults) { | ||||
|             foundAnnotation = searchResults[0]; | ||||
|         } | ||||
|  | ||||
|         return foundAnnotation; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method addSingleAnnotationTag | ||||
|     * @param {import('../objects/ObjectAPI').DomainObject=} existingAnnotation - An optional annotation to add the tag to. If not specified, we will create an annotation. | ||||
|     * @param {import('../objects/ObjectAPI').DomainObject} targetDomainObject - The domain object the annotation will point to. | ||||
|     * @param {Object=} targetSpecificDetails - Optional object to add to the target object. E.g., for notebooks this would be an entryID | ||||
|     * @param {AnnotationType} annotationType - The type of annotation this is for. | ||||
|     * @returns {import('../objects/ObjectAPI').DomainObject[]} Returns the annotation that was either created or passed as an existingAnnotation | ||||
|     */ | ||||
|     async addSingleAnnotationTag(existingAnnotation, targetDomainObject, targetSpecificDetails, annotationType, tag) { | ||||
|     async addAnnotationTag(existingAnnotation, targetDomainObject, targetSpecificDetails, annotationType, tag) { | ||||
|         if (!existingAnnotation) { | ||||
|             const targets = {}; | ||||
|             const targetKeyString = this.openmct.objects.makeKeyString(targetDomainObject.identifier); | ||||
| @@ -225,44 +186,27 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|  | ||||
|             return newAnnotation; | ||||
|         } else { | ||||
|             if (!existingAnnotation.tags.includes(tag)) { | ||||
|                 throw new Error(`Existing annotation did not contain tag ${tag}`); | ||||
|             } | ||||
|  | ||||
|             if (existingAnnotation._deleted) { | ||||
|                 this.unDeleteAnnotation(existingAnnotation); | ||||
|             } | ||||
|             const tagArray = [tag, ...existingAnnotation.tags]; | ||||
|             this.openmct.objects.mutate(existingAnnotation, 'tags', tagArray); | ||||
|  | ||||
|             return existingAnnotation; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method deleteAnnotations | ||||
|     * @param {import('../objects/ObjectAPI').DomainObject[]} existingAnnotation - An array of annotations to delete (set _deleted to true) | ||||
|     */ | ||||
|     deleteAnnotations(annotations) { | ||||
|         if (!annotations) { | ||||
|             throw new Error('Asked to delete null annotations! 🙅♂️'); | ||||
|     removeAnnotationTag(existingAnnotation, tagToRemove) { | ||||
|         if (existingAnnotation && existingAnnotation.tags.includes(tagToRemove)) { | ||||
|             const cleanedArray = existingAnnotation.tags.filter(extantTag => extantTag !== tagToRemove); | ||||
|             this.openmct.objects.mutate(existingAnnotation, 'tags', cleanedArray); | ||||
|         } else { | ||||
|             throw new Error(`Asked to remove tag (${tagToRemove}) that doesn't exist`, existingAnnotation); | ||||
|         } | ||||
|  | ||||
|         annotations.forEach(annotation => { | ||||
|             if (!annotation._deleted) { | ||||
|                 this.openmct.objects.mutate(annotation, '_deleted', true); | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method deleteAnnotations | ||||
|     * @param {import('../objects/ObjectAPI').DomainObject} existingAnnotation - An annotations to undelete (set _deleted to false) | ||||
|     */ | ||||
|     unDeleteAnnotation(annotation) { | ||||
|         if (!annotation) { | ||||
|             throw new Error('Asked to undelete null annotation! 🙅♂️'); | ||||
|     removeAnnotationTags(existingAnnotation) { | ||||
|         // just removes tags on the annotation as we can't really delete objects | ||||
|         if (existingAnnotation && existingAnnotation.tags) { | ||||
|             this.openmct.objects.mutate(existingAnnotation, 'tags', []); | ||||
|         } | ||||
|  | ||||
|         this.openmct.objects.mutate(annotation, '_deleted', false); | ||||
|     } | ||||
|  | ||||
|     #getMatchingTags(query) { | ||||
| @@ -322,40 +266,16 @@ export default class AnnotationAPI extends EventEmitter { | ||||
|         return modelAddedToResults; | ||||
|     } | ||||
|  | ||||
|     #combineSameTargets(results) { | ||||
|         const combinedResults = []; | ||||
|         results.forEach(currentAnnotation => { | ||||
|             const existingAnnotation = combinedResults.find((annotationToFind) => { | ||||
|                 return _.isEqual(currentAnnotation.targets, annotationToFind.targets); | ||||
|             }); | ||||
|             if (!existingAnnotation) { | ||||
|                 combinedResults.push(currentAnnotation); | ||||
|             } else { | ||||
|                 existingAnnotation.tags.push(...currentAnnotation.tags); | ||||
|             } | ||||
|         }); | ||||
|  | ||||
|         return combinedResults; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|     * @method searchForTags | ||||
|     * @param {String} query A query to match against tags. E.g., "dr" will match the tags "drilling" and "driving" | ||||
|     * @param {Object} [abortController] An optional abort method to stop the query | ||||
|     * @param {Object} abortController An optional abort method to stop the query | ||||
|     * @returns {Promise} returns a model of matching tags with their target domain objects attached | ||||
|     */ | ||||
|     async searchForTags(query, abortController) { | ||||
|         const matchingTagKeys = this.#getMatchingTags(query); | ||||
|         if (!matchingTagKeys.length) { | ||||
|             return []; | ||||
|         } | ||||
|  | ||||
|         const searchResults = (await Promise.all(this.openmct.objects.search(matchingTagKeys, abortController, this.openmct.objects.SEARCH_TYPES.TAGS))).flat(); | ||||
|         const filteredDeletedResults = searchResults.filter((result) => { | ||||
|             return !(result._deleted); | ||||
|         }); | ||||
|         const combinedSameTargets = this.#combineSameTargets(filteredDeletedResults); | ||||
|         const appliedTagSearchResults = this.#addTagMetaInformationToResults(combinedSameTargets, matchingTagKeys); | ||||
|         const appliedTagSearchResults = this.#addTagMetaInformationToResults(searchResults, matchingTagKeys); | ||||
|         const appliedTargetsModels = await this.#addTargetModelsToResults(appliedTagSearchResults); | ||||
|         const resultsWithValidPath = appliedTargetsModels.filter(result => { | ||||
|             return this.openmct.objects.isReachable(result.targetModels?.[0]?.originalPath); | ||||
|   | ||||
| @@ -94,6 +94,7 @@ describe("The Annotation API", () => { | ||||
|         openmct.startHeadless(); | ||||
|     }); | ||||
|     afterEach(async () => { | ||||
|         openmct.objects.providers = {}; | ||||
|         await resetApplicationState(openmct); | ||||
|     }); | ||||
|     it("is defined", () => { | ||||
| @@ -125,44 +126,34 @@ describe("The Annotation API", () => { | ||||
|  | ||||
|     describe("Tagging", () => { | ||||
|         it("can create a tag", async () => { | ||||
|             const annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             const annotationObject = await openmct.annotation.addAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             expect(annotationObject.type).toEqual('annotation'); | ||||
|             expect(annotationObject.tags).toContain('aWonderfulTag'); | ||||
|         }); | ||||
|         it("can delete a tag", async () => { | ||||
|             const annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             const originalAnnotationObject = await openmct.annotation.addAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             const annotationObject = await openmct.annotation.addAnnotationTag(originalAnnotationObject, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'anotherTagToRemove'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             openmct.annotation.deleteAnnotations([annotationObject]); | ||||
|             expect(annotationObject._deleted).toBeTrue(); | ||||
|             openmct.annotation.removeAnnotationTag(annotationObject, 'anotherTagToRemove'); | ||||
|             expect(annotationObject.tags).toEqual(['aWonderfulTag']); | ||||
|             openmct.annotation.removeAnnotationTag(annotationObject, 'aWonderfulTag'); | ||||
|             expect(annotationObject.tags).toEqual([]); | ||||
|         }); | ||||
|         it("throws an error if deleting non-existent tag", async () => { | ||||
|             const annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             const annotationObject = await openmct.annotation.addAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             expect(() => { | ||||
|                 openmct.annotation.removeAnnotationTag(annotationObject, 'ThisTagShouldNotExist'); | ||||
|             }).toThrow(); | ||||
|         }); | ||||
|         it("can remove all tags", async () => { | ||||
|             const annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             const annotationObject = await openmct.annotation.addAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             expect(() => { | ||||
|                 openmct.annotation.deleteAnnotations([annotationObject]); | ||||
|                 openmct.annotation.removeAnnotationTags(annotationObject); | ||||
|             }).not.toThrow(); | ||||
|             expect(annotationObject._deleted).toBeTrue(); | ||||
|         }); | ||||
|         it("can add/delete/add a tag", async () => { | ||||
|             let annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             expect(annotationObject.type).toEqual('annotation'); | ||||
|             expect(annotationObject.tags).toContain('aWonderfulTag'); | ||||
|             openmct.annotation.deleteAnnotations([annotationObject]); | ||||
|             expect(annotationObject._deleted).toBeTrue(); | ||||
|             annotationObject = await openmct.annotation.addSingleAnnotationTag(null, mockDomainObject, {entryId: 'foo'}, openmct.annotation.ANNOTATION_TYPES.NOTEBOOK, 'aWonderfulTag'); | ||||
|             expect(annotationObject).toBeDefined(); | ||||
|             expect(annotationObject.type).toEqual('annotation'); | ||||
|             expect(annotationObject.tags).toContain('aWonderfulTag'); | ||||
|             expect(annotationObject._deleted).toBeFalse(); | ||||
|             expect(annotationObject.tags).toEqual([]); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
| @@ -184,10 +175,16 @@ describe("The Annotation API", () => { | ||||
|             expect(results).toBeDefined(); | ||||
|             expect(results.length).toEqual(1); | ||||
|         }); | ||||
|         it("returns no tags for empty search", async () => { | ||||
|             const results = await openmct.annotation.searchForTags('q'); | ||||
|         it("can get notebook annotations", async () => { | ||||
|             const targetKeyString = openmct.objects.makeKeyString(mockDomainObject.identifier); | ||||
|             const query = { | ||||
|                 targetKeyString, | ||||
|                 entryId: 'fooBarEntry' | ||||
|             }; | ||||
|  | ||||
|             const results = await openmct.annotation.getAnnotation(query, openmct.objects.SEARCH_TYPES.NOTEBOOK_ANNOTATIONS); | ||||
|             expect(results).toBeDefined(); | ||||
|             expect(results.length).toEqual(0); | ||||
|             expect(results.tags.length).toEqual(2); | ||||
|         }); | ||||
|     }); | ||||
| }); | ||||
|   | ||||
| @@ -37,9 +37,7 @@ define([ | ||||
|     './types/TypeRegistry', | ||||
|     './user/UserAPI', | ||||
|     './annotation/AnnotationAPI' | ||||
| ], | ||||
|  | ||||
| function ( | ||||
| ], function ( | ||||
|     ActionsAPI, | ||||
|     CompositionAPI, | ||||
|     EditorAPI, | ||||
|   | ||||
| @@ -20,41 +20,34 @@ | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| import DefaultCompositionProvider from './DefaultCompositionProvider'; | ||||
| import CompositionCollection from './CompositionCollection'; | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('./CompositionProvider').default} CompositionProvider | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../../../openmct').OpenMCT} OpenMCT | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * An interface for interacting with the composition of domain objects. | ||||
|  * The composition of a domain object is the list of other domain objects | ||||
|  * it "contains" (for instance, that should be displayed beneath it | ||||
|  * in the tree.) | ||||
|  * @constructor | ||||
|  */ | ||||
| export default class CompositionAPI { | ||||
| define([ | ||||
|     'lodash', | ||||
|     'EventEmitter', | ||||
|     './DefaultCompositionProvider', | ||||
|     './CompositionCollection' | ||||
| ], function ( | ||||
|     _, | ||||
|     EventEmitter, | ||||
|     DefaultCompositionProvider, | ||||
|     CompositionCollection | ||||
| ) { | ||||
|     /** | ||||
|      * @param {OpenMCT} publicAPI | ||||
|      * An interface for interacting with the composition of domain objects. | ||||
|      * The composition of a domain object is the list of other domain objects | ||||
|      * it "contains" (for instance, that should be displayed beneath it | ||||
|      * in the tree.) | ||||
|      * | ||||
|      * @interface CompositionAPI | ||||
|      * @returns {module:openmct.CompositionCollection} | ||||
|      * @memberof module:openmct | ||||
|      */ | ||||
|     constructor(publicAPI) { | ||||
|         /** @type {CompositionProvider[]} */ | ||||
|     function CompositionAPI(publicAPI) { | ||||
|         this.registry = []; | ||||
|         /** @type {CompositionPolicy[]} */ | ||||
|         this.policies = []; | ||||
|         this.addProvider(new DefaultCompositionProvider(publicAPI, this)); | ||||
|         /** @type {OpenMCT} */ | ||||
|         this.publicAPI = publicAPI; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Add a composition provider. | ||||
|      * | ||||
| @@ -62,19 +55,21 @@ export default class CompositionAPI { | ||||
|      * behavior for certain domain objects. | ||||
|      * | ||||
|      * @method addProvider | ||||
|      * @param {CompositionProvider} provider the provider to add | ||||
|      * @param {module:openmct.CompositionProvider} provider the provider to add | ||||
|      * @memberof module:openmct.CompositionAPI# | ||||
|      */ | ||||
|     addProvider(provider) { | ||||
|     CompositionAPI.prototype.addProvider = function (provider) { | ||||
|         this.registry.unshift(provider); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Retrieve the composition (if any) of this domain object. | ||||
|      * | ||||
|      * @method get | ||||
|      * @param {DomainObject} domainObject | ||||
|      * @returns {CompositionCollection} | ||||
|      * @returns {module:openmct.CompositionCollection} | ||||
|      * @memberof module:openmct.CompositionAPI# | ||||
|      */ | ||||
|     get(domainObject) { | ||||
|     CompositionAPI.prototype.get = function (domainObject) { | ||||
|         const provider = this.registry.find(p => { | ||||
|             return p.appliesTo(domainObject); | ||||
|         }); | ||||
| @@ -84,7 +79,8 @@ export default class CompositionAPI { | ||||
|         } | ||||
|  | ||||
|         return new CompositionCollection(domainObject, provider, this.publicAPI); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * A composition policy is a function which either allows or disallows | ||||
|      * placing one object in another's composition. | ||||
| @@ -94,51 +90,52 @@ export default class CompositionAPI { | ||||
|      * generally be written to return true in the default case. | ||||
|      * | ||||
|      * @callback CompositionPolicy | ||||
|      * @param {DomainObject} containingObject the object which | ||||
|      * @memberof module:openmct.CompositionAPI~ | ||||
|      * @param {module:openmct.DomainObject} containingObject the object which | ||||
|      *        would act as a container | ||||
|      * @param {DomainObject} containedObject the object which | ||||
|      * @param {module:openmct.DomainObject} containedObject the object which | ||||
|      *        would be contained | ||||
|      * @returns {boolean} false if this composition should be disallowed | ||||
|      */ | ||||
|  | ||||
|     /** | ||||
|      * Add a composition policy. Composition policies may disallow domain | ||||
|      * objects from containing other domain objects. | ||||
|      * | ||||
|      * @method addPolicy | ||||
|      * @param {CompositionPolicy} policy | ||||
|      * @param {module:openmct.CompositionAPI~CompositionPolicy} policy | ||||
|      *        the policy to add | ||||
|      * @memberof module:openmct.CompositionAPI# | ||||
|      */ | ||||
|     addPolicy(policy) { | ||||
|     CompositionAPI.prototype.addPolicy = function (policy) { | ||||
|         this.policies.push(policy); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Check whether or not a domain object is allowed to contain another | ||||
|      * domain object. | ||||
|      * | ||||
|      * @private | ||||
|      * @method checkPolicy | ||||
|      * @param {DomainObject} container the object which | ||||
|      * @param {module:openmct.DomainObject} containingObject the object which | ||||
|      *        would act as a container | ||||
|      * @param {DomainObject} containee the object which | ||||
|      * @param {module:openmct.DomainObject} containedObject the object which | ||||
|      *        would be contained | ||||
|      * @returns {boolean} false if this composition should be disallowed | ||||
|      * @param {CompositionPolicy} policy | ||||
|  | ||||
|      * @param {module:openmct.CompositionAPI~CompositionPolicy} policy | ||||
|      *        the policy to add | ||||
|      * @memberof module:openmct.CompositionAPI# | ||||
|      */ | ||||
|     checkPolicy(container, containee) { | ||||
|     CompositionAPI.prototype.checkPolicy = function (container, containee) { | ||||
|         return this.policies.every(function (policy) { | ||||
|             return policy(container, containee); | ||||
|         }); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Check whether or not a domainObject supports composition | ||||
|      * | ||||
|      * @param {DomainObject} domainObject | ||||
|      * @returns {boolean} true if the domainObject supports composition | ||||
|      */ | ||||
|     supportsComposition(domainObject) { | ||||
|     CompositionAPI.prototype.supportsComposition = function (domainObject) { | ||||
|         return this.get(domainObject) !== undefined; | ||||
|     } | ||||
| } | ||||
|     }; | ||||
|  | ||||
|     return CompositionAPI; | ||||
| }); | ||||
|   | ||||
| @@ -1,319 +1,325 @@ | ||||
| import CompositionAPI from './CompositionAPI'; | ||||
| import CompositionCollection from './CompositionCollection'; | ||||
| define([ | ||||
|     './CompositionAPI', | ||||
|     './CompositionCollection' | ||||
| ], function ( | ||||
|     CompositionAPI, | ||||
|     CompositionCollection | ||||
| ) { | ||||
|  | ||||
| describe('The Composition API', function () { | ||||
|     let publicAPI; | ||||
|     let compositionAPI; | ||||
|     let topicService; | ||||
|     let mutationTopic; | ||||
|  | ||||
|     beforeEach(function () { | ||||
|  | ||||
|         mutationTopic = jasmine.createSpyObj('mutationTopic', [ | ||||
|             'listen' | ||||
|         ]); | ||||
|         topicService = jasmine.createSpy('topicService'); | ||||
|         topicService.and.returnValue(mutationTopic); | ||||
|         publicAPI = {}; | ||||
|         publicAPI.objects = jasmine.createSpyObj('ObjectAPI', [ | ||||
|             'get', | ||||
|             'mutate', | ||||
|             'observe', | ||||
|             'areIdsEqual' | ||||
|         ]); | ||||
|  | ||||
|         publicAPI.objects.areIdsEqual.and.callFake(function (id1, id2) { | ||||
|             return id1.namespace === id2.namespace && id1.key === id2.key; | ||||
|         }); | ||||
|  | ||||
|         publicAPI.composition = jasmine.createSpyObj('CompositionAPI', [ | ||||
|             'checkPolicy' | ||||
|         ]); | ||||
|         publicAPI.composition.checkPolicy.and.returnValue(true); | ||||
|  | ||||
|         publicAPI.objects.eventEmitter = jasmine.createSpyObj('eventemitter', [ | ||||
|             'on' | ||||
|         ]); | ||||
|         publicAPI.objects.get.and.callFake(function (identifier) { | ||||
|             return Promise.resolve({identifier: identifier}); | ||||
|         }); | ||||
|         publicAPI.$injector = jasmine.createSpyObj('$injector', [ | ||||
|             'get' | ||||
|         ]); | ||||
|         publicAPI.$injector.get.and.returnValue(topicService); | ||||
|         compositionAPI = new CompositionAPI(publicAPI); | ||||
|     }); | ||||
|  | ||||
|     it('returns falsy if an object does not support composition', function () { | ||||
|         expect(compositionAPI.get({})).toBeFalsy(); | ||||
|     }); | ||||
|  | ||||
|     describe('default composition', function () { | ||||
|         let domainObject; | ||||
|         let composition; | ||||
|     describe('The Composition API', function () { | ||||
|         let publicAPI; | ||||
|         let compositionAPI; | ||||
|         let topicService; | ||||
|         let mutationTopic; | ||||
|  | ||||
|         beforeEach(function () { | ||||
|             domainObject = { | ||||
|                 name: 'test folder', | ||||
|                 identifier: { | ||||
|                     namespace: 'test', | ||||
|                     key: '1' | ||||
|                 }, | ||||
|                 composition: [ | ||||
|                     { | ||||
|                         namespace: 'test', | ||||
|                         key: 'a' | ||||
|                     }, | ||||
|                     { | ||||
|                         namespace: 'test', | ||||
|                         key: 'b' | ||||
|                     }, | ||||
|                     { | ||||
|                         namespace: 'test', | ||||
|                         key: 'c' | ||||
|                     } | ||||
|                 ] | ||||
|             }; | ||||
|             composition = compositionAPI.get(domainObject); | ||||
|  | ||||
|             mutationTopic = jasmine.createSpyObj('mutationTopic', [ | ||||
|                 'listen' | ||||
|             ]); | ||||
|             topicService = jasmine.createSpy('topicService'); | ||||
|             topicService.and.returnValue(mutationTopic); | ||||
|             publicAPI = {}; | ||||
|             publicAPI.objects = jasmine.createSpyObj('ObjectAPI', [ | ||||
|                 'get', | ||||
|                 'mutate', | ||||
|                 'observe', | ||||
|                 'areIdsEqual' | ||||
|             ]); | ||||
|  | ||||
|             publicAPI.objects.areIdsEqual.and.callFake(function (id1, id2) { | ||||
|                 return id1.namespace === id2.namespace && id1.key === id2.key; | ||||
|             }); | ||||
|  | ||||
|             publicAPI.composition = jasmine.createSpyObj('CompositionAPI', [ | ||||
|                 'checkPolicy' | ||||
|             ]); | ||||
|             publicAPI.composition.checkPolicy.and.returnValue(true); | ||||
|  | ||||
|             publicAPI.objects.eventEmitter = jasmine.createSpyObj('eventemitter', [ | ||||
|                 'on' | ||||
|             ]); | ||||
|             publicAPI.objects.get.and.callFake(function (identifier) { | ||||
|                 return Promise.resolve({identifier: identifier}); | ||||
|             }); | ||||
|             publicAPI.$injector = jasmine.createSpyObj('$injector', [ | ||||
|                 'get' | ||||
|             ]); | ||||
|             publicAPI.$injector.get.and.returnValue(topicService); | ||||
|             compositionAPI = new CompositionAPI(publicAPI); | ||||
|         }); | ||||
|  | ||||
|         it('returns composition collection', function () { | ||||
|             expect(composition).toBeDefined(); | ||||
|             expect(composition).toEqual(jasmine.any(CompositionCollection)); | ||||
|         it('returns falsy if an object does not support composition', function () { | ||||
|             expect(compositionAPI.get({})).toBeFalsy(); | ||||
|         }); | ||||
|  | ||||
|         it('correctly reflects composability', function () { | ||||
|             expect(compositionAPI.supportsComposition(domainObject)).toBe(true); | ||||
|             delete domainObject.composition; | ||||
|             expect(compositionAPI.supportsComposition(domainObject)).toBe(false); | ||||
|         }); | ||||
|         describe('default composition', function () { | ||||
|             let domainObject; | ||||
|             let composition; | ||||
|  | ||||
|         it('loads composition from domain object', function () { | ||||
|             const listener = jasmine.createSpy('addListener'); | ||||
|             composition.on('add', listener); | ||||
|  | ||||
|             return composition.load().then(function () { | ||||
|                 expect(listener.calls.count()).toBe(3); | ||||
|                 expect(listener).toHaveBeenCalledWith({ | ||||
|             beforeEach(function () { | ||||
|                 domainObject = { | ||||
|                     name: 'test folder', | ||||
|                     identifier: { | ||||
|                         namespace: 'test', | ||||
|                         key: 'a' | ||||
|                     } | ||||
|                 }); | ||||
|             }); | ||||
|         }); | ||||
|         describe('supports reordering of composition', function () { | ||||
|             let listener; | ||||
|             beforeEach(function () { | ||||
|                 listener = jasmine.createSpy('reorderListener'); | ||||
|                 composition.on('reorder', listener); | ||||
|  | ||||
|                 return composition.load(); | ||||
|             }); | ||||
|             it('', function () { | ||||
|                 composition.reorder(1, 0); | ||||
|                 let newComposition = | ||||
|                         publicAPI.objects.mutate.calls.mostRecent().args[2]; | ||||
|                 let reorderPlan = listener.calls.mostRecent().args[0][0]; | ||||
|  | ||||
|                 expect(reorderPlan.oldIndex).toBe(1); | ||||
|                 expect(reorderPlan.newIndex).toBe(0); | ||||
|                 expect(newComposition[0].key).toEqual('b'); | ||||
|                 expect(newComposition[1].key).toEqual('a'); | ||||
|                 expect(newComposition[2].key).toEqual('c'); | ||||
|             }); | ||||
|             it('', function () { | ||||
|                 composition.reorder(0, 2); | ||||
|                 let newComposition = | ||||
|                         publicAPI.objects.mutate.calls.mostRecent().args[2]; | ||||
|                 let reorderPlan = listener.calls.mostRecent().args[0][0]; | ||||
|  | ||||
|                 expect(reorderPlan.oldIndex).toBe(0); | ||||
|                 expect(reorderPlan.newIndex).toBe(2); | ||||
|                 expect(newComposition[0].key).toEqual('b'); | ||||
|                 expect(newComposition[1].key).toEqual('c'); | ||||
|                 expect(newComposition[2].key).toEqual('a'); | ||||
|             }); | ||||
|         }); | ||||
|         it('supports adding an object to composition', function () { | ||||
|             let addListener = jasmine.createSpy('addListener'); | ||||
|             let mockChildObject = { | ||||
|                 identifier: { | ||||
|                     key: 'mock-key', | ||||
|                     namespace: '' | ||||
|                 } | ||||
|             }; | ||||
|             composition.on('add', addListener); | ||||
|             composition.add(mockChildObject); | ||||
|  | ||||
|             expect(domainObject.composition.length).toBe(4); | ||||
|             expect(domainObject.composition[3]).toEqual(mockChildObject.identifier); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     describe('static custom composition', function () { | ||||
|         let customProvider; | ||||
|         let domainObject; | ||||
|         let composition; | ||||
|  | ||||
|         beforeEach(function () { | ||||
|             // A simple custom provider, returns the same composition for | ||||
|             // all objects of a given type. | ||||
|             customProvider = { | ||||
|                 appliesTo: function (object) { | ||||
|                     return object.type === 'custom-object-type'; | ||||
|                 }, | ||||
|                 load: function (object) { | ||||
|                     return Promise.resolve([ | ||||
|                         key: '1' | ||||
|                     }, | ||||
|                     composition: [ | ||||
|                         { | ||||
|                             namespace: 'custom', | ||||
|                             key: 'thing' | ||||
|                             namespace: 'test', | ||||
|                             key: 'a' | ||||
|                         }, | ||||
|                         { | ||||
|                             namespace: 'test', | ||||
|                             key: 'b' | ||||
|                         }, | ||||
|                         { | ||||
|                             namespace: 'test', | ||||
|                             key: 'c' | ||||
|                         } | ||||
|                     ]); | ||||
|                 }, | ||||
|                 add: jasmine.createSpy('add'), | ||||
|                 remove: jasmine.createSpy('remove') | ||||
|             }; | ||||
|             domainObject = { | ||||
|                 identifier: { | ||||
|                     namespace: 'test', | ||||
|                     key: '1' | ||||
|                 }, | ||||
|                 type: 'custom-object-type' | ||||
|             }; | ||||
|             compositionAPI.addProvider(customProvider); | ||||
|             composition = compositionAPI.get(domainObject); | ||||
|         }); | ||||
|                     ] | ||||
|                 }; | ||||
|                 composition = compositionAPI.get(domainObject); | ||||
|             }); | ||||
|  | ||||
|         it('supports listening and loading', function () { | ||||
|             const addListener = jasmine.createSpy('addListener'); | ||||
|             composition.on('add', addListener); | ||||
|             it('returns composition collection', function () { | ||||
|                 expect(composition).toBeDefined(); | ||||
|                 expect(composition).toEqual(jasmine.any(CompositionCollection)); | ||||
|             }); | ||||
|  | ||||
|             return composition.load().then(function (children) { | ||||
|                 let listenObject; | ||||
|                 const loadedObject = children[0]; | ||||
|             it('correctly reflects composability', function () { | ||||
|                 expect(compositionAPI.supportsComposition(domainObject)).toBe(true); | ||||
|                 delete domainObject.composition; | ||||
|                 expect(compositionAPI.supportsComposition(domainObject)).toBe(false); | ||||
|             }); | ||||
|  | ||||
|                 expect(addListener).toHaveBeenCalled(); | ||||
|             it('loads composition from domain object', function () { | ||||
|                 const listener = jasmine.createSpy('addListener'); | ||||
|                 composition.on('add', listener); | ||||
|  | ||||
|                 listenObject = addListener.calls.mostRecent().args[0]; | ||||
|                 expect(listenObject).toEqual(loadedObject); | ||||
|                 expect(loadedObject).toEqual({ | ||||
|                     identifier: { | ||||
|                         namespace: 'custom', | ||||
|                         key: 'thing' | ||||
|                     } | ||||
|                 return composition.load().then(function () { | ||||
|                     expect(listener.calls.count()).toBe(3); | ||||
|                     expect(listener).toHaveBeenCalledWith({ | ||||
|                         identifier: { | ||||
|                             namespace: 'test', | ||||
|                             key: 'a' | ||||
|                         } | ||||
|                     }); | ||||
|                 }); | ||||
|             }); | ||||
|         }); | ||||
|         describe('Calling add or remove', function () { | ||||
|             let mockChildObject; | ||||
|             describe('supports reordering of composition', function () { | ||||
|                 let listener; | ||||
|                 beforeEach(function () { | ||||
|                     listener = jasmine.createSpy('reorderListener'); | ||||
|                     composition.on('reorder', listener); | ||||
|  | ||||
|             beforeEach(function () { | ||||
|                 mockChildObject = { | ||||
|                     return composition.load(); | ||||
|                 }); | ||||
|                 it('', function () { | ||||
|                     composition.reorder(1, 0); | ||||
|                     let newComposition = | ||||
|                         publicAPI.objects.mutate.calls.mostRecent().args[2]; | ||||
|                     let reorderPlan = listener.calls.mostRecent().args[0][0]; | ||||
|  | ||||
|                     expect(reorderPlan.oldIndex).toBe(1); | ||||
|                     expect(reorderPlan.newIndex).toBe(0); | ||||
|                     expect(newComposition[0].key).toEqual('b'); | ||||
|                     expect(newComposition[1].key).toEqual('a'); | ||||
|                     expect(newComposition[2].key).toEqual('c'); | ||||
|                 }); | ||||
|                 it('', function () { | ||||
|                     composition.reorder(0, 2); | ||||
|                     let newComposition = | ||||
|                         publicAPI.objects.mutate.calls.mostRecent().args[2]; | ||||
|                     let reorderPlan = listener.calls.mostRecent().args[0][0]; | ||||
|  | ||||
|                     expect(reorderPlan.oldIndex).toBe(0); | ||||
|                     expect(reorderPlan.newIndex).toBe(2); | ||||
|                     expect(newComposition[0].key).toEqual('b'); | ||||
|                     expect(newComposition[1].key).toEqual('c'); | ||||
|                     expect(newComposition[2].key).toEqual('a'); | ||||
|                 }); | ||||
|             }); | ||||
|             it('supports adding an object to composition', function () { | ||||
|                 let addListener = jasmine.createSpy('addListener'); | ||||
|                 let mockChildObject = { | ||||
|                     identifier: { | ||||
|                         key: 'mock-key', | ||||
|                         namespace: '' | ||||
|                     } | ||||
|                 }; | ||||
|                 composition.on('add', addListener); | ||||
|                 composition.add(mockChildObject); | ||||
|             }); | ||||
|  | ||||
|             it('calls add on the provider', function () { | ||||
|                 expect(customProvider.add).toHaveBeenCalledWith(domainObject, mockChildObject.identifier); | ||||
|             }); | ||||
|  | ||||
|             it('calls remove on the provider', function () { | ||||
|                 composition.remove(mockChildObject); | ||||
|                 expect(customProvider.remove).toHaveBeenCalledWith(domainObject, mockChildObject.identifier); | ||||
|                 expect(domainObject.composition.length).toBe(4); | ||||
|                 expect(domainObject.composition[3]).toEqual(mockChildObject.identifier); | ||||
|             }); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     describe('dynamic custom composition', function () { | ||||
|         let customProvider; | ||||
|         let domainObject; | ||||
|         let composition; | ||||
|         describe('static custom composition', function () { | ||||
|             let customProvider; | ||||
|             let domainObject; | ||||
|             let composition; | ||||
|  | ||||
|         beforeEach(function () { | ||||
|             // A dynamic provider, loads an empty composition and exposes | ||||
|             // listener functions. | ||||
|             customProvider = jasmine.createSpyObj('dynamicProvider', [ | ||||
|                 'appliesTo', | ||||
|                 'load', | ||||
|                 'on', | ||||
|                 'off' | ||||
|             ]); | ||||
|  | ||||
|             customProvider.appliesTo.and.returnValue('true'); | ||||
|             customProvider.load.and.returnValue(Promise.resolve([])); | ||||
|  | ||||
|             domainObject = { | ||||
|                 identifier: { | ||||
|                     namespace: 'test', | ||||
|                     key: '1' | ||||
|                 }, | ||||
|                 type: 'custom-object-type' | ||||
|             }; | ||||
|             compositionAPI.addProvider(customProvider); | ||||
|             composition = compositionAPI.get(domainObject); | ||||
|         }); | ||||
|  | ||||
|         it('supports listening and loading', function () { | ||||
|             const addListener = jasmine.createSpy('addListener'); | ||||
|             const removeListener = jasmine.createSpy('removeListener'); | ||||
|             const addPromise = new Promise(function (resolve) { | ||||
|                 addListener.and.callFake(resolve); | ||||
|             }); | ||||
|             const removePromise = new Promise(function (resolve) { | ||||
|                 removeListener.and.callFake(resolve); | ||||
|             beforeEach(function () { | ||||
|                 // A simple custom provider, returns the same composition for | ||||
|                 // all objects of a given type. | ||||
|                 customProvider = { | ||||
|                     appliesTo: function (object) { | ||||
|                         return object.type === 'custom-object-type'; | ||||
|                     }, | ||||
|                     load: function (object) { | ||||
|                         return Promise.resolve([ | ||||
|                             { | ||||
|                                 namespace: 'custom', | ||||
|                                 key: 'thing' | ||||
|                             } | ||||
|                         ]); | ||||
|                     }, | ||||
|                     add: jasmine.createSpy('add'), | ||||
|                     remove: jasmine.createSpy('remove') | ||||
|                 }; | ||||
|                 domainObject = { | ||||
|                     identifier: { | ||||
|                         namespace: 'test', | ||||
|                         key: '1' | ||||
|                     }, | ||||
|                     type: 'custom-object-type' | ||||
|                 }; | ||||
|                 compositionAPI.addProvider(customProvider); | ||||
|                 composition = compositionAPI.get(domainObject); | ||||
|             }); | ||||
|  | ||||
|             composition.on('add', addListener); | ||||
|             composition.on('remove', removeListener); | ||||
|             it('supports listening and loading', function () { | ||||
|                 const addListener = jasmine.createSpy('addListener'); | ||||
|                 composition.on('add', addListener); | ||||
|  | ||||
|             expect(customProvider.on).toHaveBeenCalledWith( | ||||
|                 domainObject, | ||||
|                 'add', | ||||
|                 jasmine.any(Function), | ||||
|                 jasmine.any(CompositionCollection) | ||||
|             ); | ||||
|             expect(customProvider.on).toHaveBeenCalledWith( | ||||
|                 domainObject, | ||||
|                 'remove', | ||||
|                 jasmine.any(Function), | ||||
|                 jasmine.any(CompositionCollection) | ||||
|             ); | ||||
|             const add = customProvider.on.calls.all()[0].args[2]; | ||||
|             const remove = customProvider.on.calls.all()[1].args[2]; | ||||
|                 return composition.load().then(function (children) { | ||||
|                     let listenObject; | ||||
|                     const loadedObject = children[0]; | ||||
|  | ||||
|             return composition.load() | ||||
|                 .then(function () { | ||||
|                     expect(addListener).not.toHaveBeenCalled(); | ||||
|                     expect(removeListener).not.toHaveBeenCalled(); | ||||
|                     add({ | ||||
|                         namespace: 'custom', | ||||
|                         key: 'thing' | ||||
|                     }); | ||||
|                     expect(addListener).toHaveBeenCalled(); | ||||
|  | ||||
|                     return addPromise; | ||||
|                 }).then(function () { | ||||
|                     expect(addListener).toHaveBeenCalledWith({ | ||||
|                         identifier: { | ||||
|                             namespace: 'custom', | ||||
|                             key: 'thing' | ||||
|                         } | ||||
|                     }); | ||||
|                     remove(addListener.calls.mostRecent().args[0]); | ||||
|  | ||||
|                     return removePromise; | ||||
|                 }).then(function () { | ||||
|                     expect(removeListener).toHaveBeenCalledWith({ | ||||
|                     listenObject = addListener.calls.mostRecent().args[0]; | ||||
|                     expect(listenObject).toEqual(loadedObject); | ||||
|                     expect(loadedObject).toEqual({ | ||||
|                         identifier: { | ||||
|                             namespace: 'custom', | ||||
|                             key: 'thing' | ||||
|                         } | ||||
|                     }); | ||||
|                 }); | ||||
|             }); | ||||
|             describe('Calling add or remove', function () { | ||||
|                 let mockChildObject; | ||||
|  | ||||
|                 beforeEach(function () { | ||||
|                     mockChildObject = { | ||||
|                         identifier: { | ||||
|                             key: 'mock-key', | ||||
|                             namespace: '' | ||||
|                         } | ||||
|                     }; | ||||
|                     composition.add(mockChildObject); | ||||
|                 }); | ||||
|  | ||||
|                 it('calls add on the provider', function () { | ||||
|                     expect(customProvider.add).toHaveBeenCalledWith(domainObject, mockChildObject.identifier); | ||||
|                 }); | ||||
|  | ||||
|                 it('calls remove on the provider', function () { | ||||
|                     composition.remove(mockChildObject); | ||||
|                     expect(customProvider.remove).toHaveBeenCalledWith(domainObject, mockChildObject.identifier); | ||||
|                 }); | ||||
|             }); | ||||
|         }); | ||||
|  | ||||
|         describe('dynamic custom composition', function () { | ||||
|             let customProvider; | ||||
|             let domainObject; | ||||
|             let composition; | ||||
|  | ||||
|             beforeEach(function () { | ||||
|                 // A dynamic provider, loads an empty composition and exposes | ||||
|                 // listener functions. | ||||
|                 customProvider = jasmine.createSpyObj('dynamicProvider', [ | ||||
|                     'appliesTo', | ||||
|                     'load', | ||||
|                     'on', | ||||
|                     'off' | ||||
|                 ]); | ||||
|  | ||||
|                 customProvider.appliesTo.and.returnValue('true'); | ||||
|                 customProvider.load.and.returnValue(Promise.resolve([])); | ||||
|  | ||||
|                 domainObject = { | ||||
|                     identifier: { | ||||
|                         namespace: 'test', | ||||
|                         key: '1' | ||||
|                     }, | ||||
|                     type: 'custom-object-type' | ||||
|                 }; | ||||
|                 compositionAPI.addProvider(customProvider); | ||||
|                 composition = compositionAPI.get(domainObject); | ||||
|             }); | ||||
|  | ||||
|             it('supports listening and loading', function () { | ||||
|                 const addListener = jasmine.createSpy('addListener'); | ||||
|                 const removeListener = jasmine.createSpy('removeListener'); | ||||
|                 const addPromise = new Promise(function (resolve) { | ||||
|                     addListener.and.callFake(resolve); | ||||
|                 }); | ||||
|                 const removePromise = new Promise(function (resolve) { | ||||
|                     removeListener.and.callFake(resolve); | ||||
|                 }); | ||||
|  | ||||
|                 composition.on('add', addListener); | ||||
|                 composition.on('remove', removeListener); | ||||
|  | ||||
|                 expect(customProvider.on).toHaveBeenCalledWith( | ||||
|                     domainObject, | ||||
|                     'add', | ||||
|                     jasmine.any(Function), | ||||
|                     jasmine.any(CompositionCollection) | ||||
|                 ); | ||||
|                 expect(customProvider.on).toHaveBeenCalledWith( | ||||
|                     domainObject, | ||||
|                     'remove', | ||||
|                     jasmine.any(Function), | ||||
|                     jasmine.any(CompositionCollection) | ||||
|                 ); | ||||
|                 const add = customProvider.on.calls.all()[0].args[2]; | ||||
|                 const remove = customProvider.on.calls.all()[1].args[2]; | ||||
|  | ||||
|                 return composition.load() | ||||
|                     .then(function () { | ||||
|                         expect(addListener).not.toHaveBeenCalled(); | ||||
|                         expect(removeListener).not.toHaveBeenCalled(); | ||||
|                         add({ | ||||
|                             namespace: 'custom', | ||||
|                             key: 'thing' | ||||
|                         }); | ||||
|  | ||||
|                         return addPromise; | ||||
|                     }).then(function () { | ||||
|                         expect(addListener).toHaveBeenCalledWith({ | ||||
|                             identifier: { | ||||
|                                 namespace: 'custom', | ||||
|                                 key: 'thing' | ||||
|                             } | ||||
|                         }); | ||||
|                         remove(addListener.calls.mostRecent().args[0]); | ||||
|  | ||||
|                         return removePromise; | ||||
|                     }).then(function () { | ||||
|                         expect(removeListener).toHaveBeenCalledWith({ | ||||
|                             identifier: { | ||||
|                                 namespace: 'custom', | ||||
|                                 key: 'thing' | ||||
|                             } | ||||
|                         }); | ||||
|                     }); | ||||
|             }); | ||||
|         }); | ||||
|     }); | ||||
| }); | ||||
|   | ||||
| @@ -20,98 +20,75 @@ | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('./CompositionAPI').default} CompositionAPI | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../../../openmct').OpenMCT} OpenMCT | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {object} ListenerMap | ||||
|  * @property {Array.<any>} add | ||||
|  * @property {Array.<any>} remove | ||||
|  * @property {Array.<any>} load | ||||
|  * @property {Array.<any>} reorder | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|  * A CompositionCollection represents the list of domain objects contained | ||||
|  * by another domain object. It provides methods for loading this | ||||
|  * list asynchronously, modifying this list, and listening for changes to | ||||
|  * this list. | ||||
|  * | ||||
|  * Usage: | ||||
|  * ```javascript | ||||
|  *  var myViewComposition = MCT.composition.get(myViewObject); | ||||
|  *  myViewComposition.on('add', addObjectToView); | ||||
|  *  myViewComposition.on('remove', removeObjectFromView); | ||||
|  *  myViewComposition.load(); // will trigger `add` for all loaded objects. | ||||
|  *  ``` | ||||
|  */ | ||||
| export default class CompositionCollection { | ||||
|     domainObject; | ||||
|     #provider; | ||||
|     #publicAPI; | ||||
|     #listeners; | ||||
|     #mutables; | ||||
| define([ | ||||
|     'lodash' | ||||
| ], function ( | ||||
|     _ | ||||
| ) { | ||||
|     /** | ||||
|      * @constructor | ||||
|      * @param {DomainObject} domainObject the domain object | ||||
|      * A CompositionCollection represents the list of domain objects contained | ||||
|      * by another domain object. It provides methods for loading this | ||||
|      * list asynchronously, modifying this list, and listening for changes to | ||||
|      * this list. | ||||
|      * | ||||
|      * Usage: | ||||
|      * ```javascript | ||||
|      *  var myViewComposition = MCT.composition.get(myViewObject); | ||||
|      *  myViewComposition.on('add', addObjectToView); | ||||
|      *  myViewComposition.on('remove', removeObjectFromView); | ||||
|      *  myViewComposition.load(); // will trigger `add` for all loaded objects. | ||||
|      *  ``` | ||||
|      * | ||||
|      * @interface CompositionCollection | ||||
|      * @param {module:openmct.DomainObject} domainObject the domain object | ||||
|      *        whose composition will be contained | ||||
|      * @param {import('./CompositionProvider').default} provider the provider | ||||
|      * @param {module:openmct.CompositionProvider} provider the provider | ||||
|      *        to use to retrieve other domain objects | ||||
|      * @param {OpenMCT} publicAPI the composition API, for | ||||
|      * @param {module:openmct.CompositionAPI} api the composition API, for | ||||
|      *        policy checks | ||||
|      * @memberof module:openmct | ||||
|      */ | ||||
|     constructor(domainObject, provider, publicAPI) { | ||||
|     function CompositionCollection(domainObject, provider, publicAPI) { | ||||
|         this.domainObject = domainObject; | ||||
|         /** @type {import('./CompositionProvider').default} */ | ||||
|         this.#provider = provider; | ||||
|         /** @type {OpenMCT} */ | ||||
|         this.#publicAPI = publicAPI; | ||||
|         /** @type {ListenerMap} */ | ||||
|         this.#listeners = { | ||||
|         this.provider = provider; | ||||
|         this.publicAPI = publicAPI; | ||||
|         this.listeners = { | ||||
|             add: [], | ||||
|             remove: [], | ||||
|             load: [], | ||||
|             reorder: [] | ||||
|         }; | ||||
|         this.onProviderAdd = this.#onProviderAdd.bind(this); | ||||
|         this.onProviderRemove = this.#onProviderRemove.bind(this); | ||||
|         this.#mutables = {}; | ||||
|         this.onProviderAdd = this.onProviderAdd.bind(this); | ||||
|         this.onProviderRemove = this.onProviderRemove.bind(this); | ||||
|         this.mutables = {}; | ||||
|  | ||||
|         if (this.domainObject.isMutable) { | ||||
|             this.returnMutables = true; | ||||
|             let unobserve = this.domainObject.$on('$_destroy', () => { | ||||
|                 Object.values(this.#mutables).forEach(mutable => { | ||||
|                     this.#publicAPI.objects.destroyMutable(mutable); | ||||
|                 Object.values(this.mutables).forEach(mutable => { | ||||
|                     this.publicAPI.objects.destroyMutable(mutable); | ||||
|                 }); | ||||
|                 unobserve(); | ||||
|             }); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Listen for changes to this composition.  Supports 'add', 'remove', and | ||||
|      * 'load' events. | ||||
|      * | ||||
|      * @param {string} event event to listen for, either 'add', 'remove' or 'load'. | ||||
|      * @param {(...args: any[]) => void} callback to trigger when event occurs. | ||||
|      * @param {any} [context] to use when invoking callback, optional. | ||||
|      * @param event event to listen for, either 'add', 'remove' or 'load'. | ||||
|      * @param callback to trigger when event occurs. | ||||
|      * @param [context] context to use when invoking callback, optional. | ||||
|      */ | ||||
|     on(event, callback, context) { | ||||
|         if (!this.#listeners[event]) { | ||||
|     CompositionCollection.prototype.on = function (event, callback, context) { | ||||
|         if (!this.listeners[event]) { | ||||
|             throw new Error('Event not supported by composition: ' + event); | ||||
|         } | ||||
|  | ||||
|         if (this.#provider.on && this.#provider.off) { | ||||
|         if (this.provider.on && this.provider.off) { | ||||
|             if (event === 'add') { | ||||
|                 this.#provider.on( | ||||
|                 this.provider.on( | ||||
|                     this.domainObject, | ||||
|                     'add', | ||||
|                     this.onProviderAdd, | ||||
| @@ -120,7 +97,7 @@ export default class CompositionCollection { | ||||
|             } | ||||
|  | ||||
|             if (event === 'remove') { | ||||
|                 this.#provider.on( | ||||
|                 this.provider.on( | ||||
|                     this.domainObject, | ||||
|                     'remove', | ||||
|                     this.onProviderRemove, | ||||
| @@ -129,34 +106,36 @@ export default class CompositionCollection { | ||||
|             } | ||||
|  | ||||
|             if (event === 'reorder') { | ||||
|                 this.#provider.on( | ||||
|                 this.provider.on( | ||||
|                     this.domainObject, | ||||
|                     'reorder', | ||||
|                     this.#onProviderReorder, | ||||
|                     this.onProviderReorder, | ||||
|                     this | ||||
|                 ); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         this.#listeners[event].push({ | ||||
|         this.listeners[event].push({ | ||||
|             callback: callback, | ||||
|             context: context | ||||
|         }); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Remove a listener.  Must be called with same exact parameters as | ||||
|      * `off`. | ||||
|      * | ||||
|      * @param {string} event | ||||
|      * @param {(...args: any[]) => void} callback | ||||
|      * @param {any} [context] | ||||
|      * @param event | ||||
|      * @param callback | ||||
|      * @param [context] | ||||
|      */ | ||||
|     off(event, callback, context) { | ||||
|         if (!this.#listeners[event]) { | ||||
|  | ||||
|     CompositionCollection.prototype.off = function (event, callback, context) { | ||||
|         if (!this.listeners[event]) { | ||||
|             throw new Error('Event not supported by composition: ' + event); | ||||
|         } | ||||
|  | ||||
|         const index = this.#listeners[event].findIndex(l => { | ||||
|         const index = this.listeners[event].findIndex(l => { | ||||
|             return l.callback === callback && l.context === context; | ||||
|         }); | ||||
|  | ||||
| @@ -164,116 +143,125 @@ export default class CompositionCollection { | ||||
|             throw new Error('Tried to remove a listener that does not exist'); | ||||
|         } | ||||
|  | ||||
|         this.#listeners[event].splice(index, 1); | ||||
|         if (this.#listeners[event].length === 0) { | ||||
|         this.listeners[event].splice(index, 1); | ||||
|         if (this.listeners[event].length === 0) { | ||||
|             this._destroy(); | ||||
|  | ||||
|             // Remove provider listener if this is the last callback to | ||||
|             // be removed. | ||||
|             if (this.#provider.off && this.#provider.on) { | ||||
|             if (this.provider.off && this.provider.on) { | ||||
|                 if (event === 'add') { | ||||
|                     this.#provider.off( | ||||
|                     this.provider.off( | ||||
|                         this.domainObject, | ||||
|                         'add', | ||||
|                         this.onProviderAdd, | ||||
|                         this | ||||
|                     ); | ||||
|                 } else if (event === 'remove') { | ||||
|                     this.#provider.off( | ||||
|                     this.provider.off( | ||||
|                         this.domainObject, | ||||
|                         'remove', | ||||
|                         this.onProviderRemove, | ||||
|                         this | ||||
|                     ); | ||||
|                 } else if (event === 'reorder') { | ||||
|                     this.#provider.off( | ||||
|                     this.provider.off( | ||||
|                         this.domainObject, | ||||
|                         'reorder', | ||||
|                         this.#onProviderReorder, | ||||
|                         this.onProviderReorder, | ||||
|                         this | ||||
|                     ); | ||||
|                 } | ||||
|             } | ||||
|         } | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Add a domain object to this composition. | ||||
|      * | ||||
|      * A call to [load]{@link module:openmct.CompositionCollection#load} | ||||
|      * must have resolved before using this method. | ||||
|      * | ||||
|      * **TODO:** Remove `skipMutate` parameter. | ||||
|      * | ||||
|      * @param {DomainObject} child the domain object to add | ||||
|      * @param {boolean} skipMutate | ||||
|      * **Intended for internal use ONLY.** | ||||
|      * true if the underlying provider should not be updated. | ||||
|      * @param {module:openmct.DomainObject} child the domain object to add | ||||
|      * @param {boolean} skipMutate true if the underlying provider should | ||||
|      *        not be updated | ||||
|      * @memberof module:openmct.CompositionCollection# | ||||
|      * @name add | ||||
|      */ | ||||
|     add(child, skipMutate) { | ||||
|     CompositionCollection.prototype.add = function (child, skipMutate) { | ||||
|         if (!skipMutate) { | ||||
|             if (!this.#publicAPI.composition.checkPolicy(this.domainObject, child)) { | ||||
|             if (!this.publicAPI.composition.checkPolicy(this.domainObject, child)) { | ||||
|                 throw `Object of type ${child.type} cannot be added to object of type ${this.domainObject.type}`; | ||||
|             } | ||||
|  | ||||
|             this.#provider.add(this.domainObject, child.identifier); | ||||
|             this.provider.add(this.domainObject, child.identifier); | ||||
|         } else { | ||||
|             if (this.returnMutables && this.#publicAPI.objects.supportsMutation(child.identifier)) { | ||||
|                 let keyString = this.#publicAPI.objects.makeKeyString(child.identifier); | ||||
|             if (this.returnMutables && this.publicAPI.objects.supportsMutation(child.identifier)) { | ||||
|                 let keyString = this.publicAPI.objects.makeKeyString(child.identifier); | ||||
|  | ||||
|                 child = this.#publicAPI.objects.toMutable(child); | ||||
|                 this.#mutables[keyString] = child; | ||||
|                 child = this.publicAPI.objects._toMutable(child); | ||||
|                 this.mutables[keyString] = child; | ||||
|             } | ||||
|  | ||||
|             this.#emit('add', child); | ||||
|             this.emit('add', child); | ||||
|         } | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Load the domain objects in this composition. | ||||
|      * | ||||
|      * @param {AbortSignal} abortSignal | ||||
|      * @returns {Promise.<Array.<DomainObject>>} a promise for | ||||
|      * @returns {Promise.<Array.<module:openmct.DomainObject>>} a promise for | ||||
|      *          the domain objects in this composition | ||||
|      * @memberof {module:openmct.CompositionCollection#} | ||||
|      * @name load | ||||
|      */ | ||||
|     async load(abortSignal) { | ||||
|         this.#cleanUpMutables(); | ||||
|         const children = await this.#provider.load(this.domainObject); | ||||
|         const childObjects = await Promise.all(children.map((c) => this.#publicAPI.objects.get(c, abortSignal))); | ||||
|         childObjects.forEach(c => this.add(c, true)); | ||||
|         this.#emit('load'); | ||||
|     CompositionCollection.prototype.load = function (abortSignal) { | ||||
|         this.cleanUpMutables(); | ||||
|  | ||||
|         return this.provider.load(this.domainObject) | ||||
|             .then(function (children) { | ||||
|                 return Promise.all(children.map((c) => this.publicAPI.objects.get(c, abortSignal))); | ||||
|             }.bind(this)) | ||||
|             .then(function (childObjects) { | ||||
|                 childObjects.forEach(c => this.add(c, true)); | ||||
|  | ||||
|                 return childObjects; | ||||
|             }.bind(this)) | ||||
|             .then(function (children) { | ||||
|                 this.emit('load'); | ||||
|  | ||||
|                 return children; | ||||
|             }.bind(this)); | ||||
|     }; | ||||
|  | ||||
|         return childObjects; | ||||
|     } | ||||
|     /** | ||||
|      * Remove a domain object from this composition. | ||||
|      * | ||||
|      * A call to [load]{@link module:openmct.CompositionCollection#load} | ||||
|      * must have resolved before using this method. | ||||
|      * | ||||
|      * **TODO:** Remove `skipMutate` parameter. | ||||
|      * | ||||
|      * @param {DomainObject} child the domain object to remove | ||||
|      * @param {boolean} skipMutate | ||||
|      * **Intended for internal use ONLY.** | ||||
|      * true if the underlying provider should not be updated. | ||||
|      * @param {module:openmct.DomainObject} child the domain object to remove | ||||
|      * @param {boolean} skipMutate true if the underlying provider should | ||||
|      *        not be updated | ||||
|      * @memberof module:openmct.CompositionCollection# | ||||
|      * @name remove | ||||
|      */ | ||||
|     remove(child, skipMutate) { | ||||
|     CompositionCollection.prototype.remove = function (child, skipMutate) { | ||||
|         if (!skipMutate) { | ||||
|             this.#provider.remove(this.domainObject, child.identifier); | ||||
|             this.provider.remove(this.domainObject, child.identifier); | ||||
|         } else { | ||||
|             if (this.returnMutables) { | ||||
|                 let keyString = this.#publicAPI.objects.makeKeyString(child); | ||||
|                 if (this.#mutables[keyString] !== undefined && this.#mutables[keyString].isMutable) { | ||||
|                     this.#publicAPI.objects.destroyMutable(this.#mutables[keyString]); | ||||
|                     delete this.#mutables[keyString]; | ||||
|                 let keyString = this.publicAPI.objects.makeKeyString(child); | ||||
|                 if (this.mutables[keyString] !== undefined && this.mutables[keyString].isMutable) { | ||||
|                     this.publicAPI.objects.destroyMutable(this.mutables[keyString]); | ||||
|                     delete this.mutables[keyString]; | ||||
|                 } | ||||
|             } | ||||
|  | ||||
|             this.#emit('remove', child); | ||||
|             this.emit('remove', child); | ||||
|         } | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Reorder the domain objects in this composition. | ||||
|      * | ||||
| @@ -282,75 +270,67 @@ export default class CompositionCollection { | ||||
|      * | ||||
|      * @param {number} oldIndex | ||||
|      * @param {number} newIndex | ||||
|      * @memberof module:openmct.CompositionCollection# | ||||
|      * @name remove | ||||
|      */ | ||||
|     reorder(oldIndex, newIndex, _skipMutate) { | ||||
|         this.#provider.reorder(this.domainObject, oldIndex, newIndex); | ||||
|     } | ||||
|     /** | ||||
|      * Destroy mutationListener | ||||
|      */ | ||||
|     _destroy() { | ||||
|         if (this.mutationListener) { | ||||
|             this.mutationListener(); | ||||
|             delete this.mutationListener; | ||||
|         } | ||||
|     } | ||||
|     CompositionCollection.prototype.reorder = function (oldIndex, newIndex, skipMutate) { | ||||
|         this.provider.reorder(this.domainObject, oldIndex, newIndex); | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Handle reorder from provider. | ||||
|      * @private | ||||
|      * @param {object} reorderMap | ||||
|      */ | ||||
|     #onProviderReorder(reorderMap) { | ||||
|         this.#emit('reorder', reorderMap); | ||||
|     } | ||||
|     CompositionCollection.prototype.onProviderReorder = function (reorderMap) { | ||||
|         this.emit('reorder', reorderMap); | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Handle adds from provider. | ||||
|      * @private | ||||
|      * @param {import('../objects/ObjectAPI').Identifier} childId | ||||
|      * @returns {DomainObject} | ||||
|      */ | ||||
|     #onProviderAdd(childId) { | ||||
|         return this.#publicAPI.objects.get(childId).then(function (child) { | ||||
|     CompositionCollection.prototype.onProviderAdd = function (childId) { | ||||
|         return this.publicAPI.objects.get(childId).then(function (child) { | ||||
|             this.add(child, true); | ||||
|  | ||||
|             return child; | ||||
|         }.bind(this)); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Handle removal from provider. | ||||
|      * @param {DomainObject} child | ||||
|      * @private | ||||
|      */ | ||||
|     #onProviderRemove(child) { | ||||
|     CompositionCollection.prototype.onProviderRemove = function (child) { | ||||
|         this.remove(child, true); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     CompositionCollection.prototype._destroy = function () { | ||||
|         if (this.mutationListener) { | ||||
|             this.mutationListener(); | ||||
|             delete this.mutationListener; | ||||
|         } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Emit events. | ||||
|      * | ||||
|      * @private | ||||
|      * @param {string} event | ||||
|      * @param {...args.<any>} payload | ||||
|      */ | ||||
|     #emit(event, ...payload) { | ||||
|         this.#listeners[event].forEach(function (l) { | ||||
|     CompositionCollection.prototype.emit = function (event, ...payload) { | ||||
|         this.listeners[event].forEach(function (l) { | ||||
|             if (l.context) { | ||||
|                 l.callback.apply(l.context, payload); | ||||
|             } else { | ||||
|                 l.callback(...payload); | ||||
|             } | ||||
|         }); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Destroy all mutables. | ||||
|      * @private | ||||
|      */ | ||||
|     #cleanUpMutables() { | ||||
|         Object.values(this.#mutables).forEach(mutable => { | ||||
|             this.#publicAPI.objects.destroyMutable(mutable); | ||||
|     CompositionCollection.prototype.cleanUpMutables = function () { | ||||
|         Object.values(this.mutables).forEach(mutable => { | ||||
|             this.publicAPI.objects.destroyMutable(mutable); | ||||
|         }); | ||||
|     } | ||||
| } | ||||
|     }; | ||||
|  | ||||
|     return CompositionCollection; | ||||
| }); | ||||
|   | ||||
| @@ -1,262 +0,0 @@ | ||||
| /***************************************************************************** | ||||
|  * Open MCT, Copyright (c) 2014-2022, United States Government | ||||
|  * as represented by the Administrator of the National Aeronautics and Space | ||||
|  * Administration. All rights reserved. | ||||
|  * | ||||
|  * Open MCT is 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. | ||||
|  * | ||||
|  * Open MCT includes source code licensed under additional open source | ||||
|  * licenses. See the Open Source Licenses file (LICENSES.md) included with | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
| import _ from 'lodash'; | ||||
| import objectUtils from "../objects/object-utils"; | ||||
|  | ||||
| /** | ||||
|   * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject | ||||
|   */ | ||||
|  | ||||
| /** | ||||
|   * @typedef {import('../objects/ObjectAPI').Identifier} Identifier | ||||
|   */ | ||||
|  | ||||
| /** | ||||
|   * @typedef {import('./CompositionAPI').default} CompositionAPI | ||||
|   */ | ||||
|  | ||||
| /** | ||||
|   * @typedef {import('../../../openmct').OpenMCT} OpenMCT | ||||
|   */ | ||||
|  | ||||
| /** | ||||
|   * A CompositionProvider provides the underlying implementation of | ||||
|   * composition-related behavior for certain types of domain object. | ||||
|   * | ||||
|   * By default, a composition provider will not support composition | ||||
|   * modification.  You can add support for mutation of composition by | ||||
|   * defining `add` and/or `remove` methods. | ||||
|   * | ||||
|   * If the composition of an object can change over time-- perhaps via | ||||
|   * server updates or mutation via the add/remove methods, then one must | ||||
|   * trigger events as necessary. | ||||
|   * | ||||
|   */ | ||||
| export default class CompositionProvider { | ||||
|     #publicAPI; | ||||
|     #listeningTo; | ||||
|  | ||||
|     /** | ||||
|       * @param {OpenMCT} publicAPI | ||||
|       * @param {CompositionAPI} compositionAPI | ||||
|       */ | ||||
|     constructor(publicAPI, compositionAPI) { | ||||
|         this.#publicAPI = publicAPI; | ||||
|         this.#listeningTo = {}; | ||||
|  | ||||
|         compositionAPI.addPolicy(this.#cannotContainItself.bind(this)); | ||||
|         compositionAPI.addPolicy(this.#supportsComposition.bind(this)); | ||||
|     } | ||||
|  | ||||
|     get listeningTo() { | ||||
|         return this.#listeningTo; | ||||
|     } | ||||
|  | ||||
|     get establishTopicListener() { | ||||
|         return this.#establishTopicListener.bind(this); | ||||
|     } | ||||
|  | ||||
|     get publicAPI() { | ||||
|         return this.#publicAPI; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * Check if this provider should be used to load composition for a | ||||
|       * particular domain object. | ||||
|       * @method appliesTo | ||||
|       * @param {import('../objects/ObjectAPI').DomainObject} domainObject the domain object | ||||
|       *        to check | ||||
|       * @returns {boolean} true if this provider can provide composition for a given domain object | ||||
|       */ | ||||
|     appliesTo(domainObject) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|     /** | ||||
|       * Load any domain objects contained in the composition of this domain | ||||
|       * object. | ||||
|       * @param {DomainObject} domainObject the domain object | ||||
|       *        for which to load composition | ||||
|       * @returns {Promise<Identifier[]>} a promise for | ||||
|       *          the Identifiers in this composition | ||||
|       * @method load | ||||
|       */ | ||||
|     load(domainObject) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|     /** | ||||
|       * Attach listeners for changes to the composition of a given domain object. | ||||
|       * Supports `add` and `remove` events. | ||||
|       * | ||||
|       * @param {DomainObject} domainObject to listen to | ||||
|       * @param {string} event the event to bind to, either `add` or `remove`. | ||||
|       * @param {Function} callback callback to invoke when event is triggered. | ||||
|       * @param {any} [context] to use when invoking callback. | ||||
|       */ | ||||
|     on(domainObject, | ||||
|         event, | ||||
|         callback, | ||||
|         context) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|     /** | ||||
|       * Remove a listener that was previously added for a given domain object. | ||||
|       * event name, callback, and context must be the same as when the listener | ||||
|       * was originally attached. | ||||
|       * | ||||
|       * @param {DomainObject} domainObject to remove listener for | ||||
|       * @param {string} event event to stop listening to: `add` or `remove`. | ||||
|       * @param {Function} callback callback to remove. | ||||
|       * @param {any} context of callback to remove. | ||||
|       */ | ||||
|     off(domainObject, | ||||
|         event, | ||||
|         callback, | ||||
|         context) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|     /** | ||||
|       * Remove a domain object from another domain object's composition. | ||||
|       * | ||||
|       * This method is optional; if not present, adding to a domain object's | ||||
|       * composition using this provider will be disallowed. | ||||
|       * | ||||
|       * @param {DomainObject} domainObject the domain object | ||||
|       *        which should have its composition modified | ||||
|       * @param {Identifier} childId the domain object to remove | ||||
|       * @method remove | ||||
|       */ | ||||
|     remove(domainObject, childId) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|     /** | ||||
|       * Add a domain object to another domain object's composition. | ||||
|       * | ||||
|       * This method is optional; if not present, adding to a domain object's | ||||
|       * composition using this provider will be disallowed. | ||||
|       * | ||||
|       * @param {DomainObject} parent the domain object | ||||
|       *        which should have its composition modified | ||||
|       * @param {Identifier} childId the domain object to add | ||||
|       * @method add | ||||
|       */ | ||||
|     add(parent, childId) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * @param {DomainObject} parent | ||||
|       * @param {Identifier} childId | ||||
|       * @returns {boolean} | ||||
|       */ | ||||
|     includes(parent, childId) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * @param {DomainObject} domainObject | ||||
|       * @param {number} oldIndex | ||||
|       * @param {number} newIndex | ||||
|       * @returns | ||||
|       */ | ||||
|     reorder(domainObject, oldIndex, newIndex) { | ||||
|         throw new Error("This method must be implemented by a subclass."); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * Listens on general mutation topic, using injector to fetch to avoid | ||||
|       * circular dependencies. | ||||
|       * @private | ||||
|       */ | ||||
|     #establishTopicListener() { | ||||
|         if (this.topicListener) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         this.#publicAPI.objects.eventEmitter.on('mutation', this.#onMutation.bind(this)); | ||||
|         this.topicListener = () => { | ||||
|             this.#publicAPI.objects.eventEmitter.off('mutation', this.#onMutation.bind(this)); | ||||
|         }; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * @private | ||||
|       * @param {DomainObject} parent | ||||
|       * @param {DomainObject} child | ||||
|       * @returns {boolean} | ||||
|       */ | ||||
|     #cannotContainItself(parent, child) { | ||||
|         return !(parent.identifier.namespace === child.identifier.namespace | ||||
|                && parent.identifier.key === child.identifier.key); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * @private | ||||
|       * @param {DomainObject} parent | ||||
|       * @returns {boolean} | ||||
|       */ | ||||
|     #supportsComposition(parent, _child) { | ||||
|         return this.#publicAPI.composition.supportsComposition(parent); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|       * Handles mutation events.  If there are active listeners for the mutated | ||||
|       * object, detects changes to composition and triggers necessary events. | ||||
|       * | ||||
|       * @private | ||||
|       * @param {DomainObject} oldDomainObject | ||||
|       */ | ||||
|     #onMutation(oldDomainObject) { | ||||
|         const id = objectUtils.makeKeyString(oldDomainObject.identifier); | ||||
|         const listeners = this.#listeningTo[id]; | ||||
|  | ||||
|         if (!listeners) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         const oldComposition = listeners.composition.map(objectUtils.makeKeyString); | ||||
|         const newComposition = oldDomainObject.composition.map(objectUtils.makeKeyString); | ||||
|  | ||||
|         const added = _.difference(newComposition, oldComposition).map(objectUtils.parseKeyString); | ||||
|         const removed = _.difference(oldComposition, newComposition).map(objectUtils.parseKeyString); | ||||
|  | ||||
|         function notify(value) { | ||||
|             return function (listener) { | ||||
|                 if (listener.context) { | ||||
|                     listener.callback.call(listener.context, value); | ||||
|                 } else { | ||||
|                     listener.callback(value); | ||||
|                 } | ||||
|             }; | ||||
|         } | ||||
|  | ||||
|         listeners.composition = newComposition.map(objectUtils.parseKeyString); | ||||
|  | ||||
|         added.forEach(function (addedChild) { | ||||
|             listeners.add.forEach(notify(addedChild)); | ||||
|         }); | ||||
|  | ||||
|         removed.forEach(function (removedChild) { | ||||
|             listeners.remove.forEach(notify(removedChild)); | ||||
|         }); | ||||
|     } | ||||
| } | ||||
|  | ||||
| @@ -19,79 +19,102 @@ | ||||
|  * this source code distribution or the Licensing information page available | ||||
|  * at runtime from the About dialog for additional information. | ||||
|  *****************************************************************************/ | ||||
| import objectUtils from "../objects/object-utils"; | ||||
| import CompositionProvider from './CompositionProvider'; | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject | ||||
|  */ | ||||
| define([ | ||||
|     'lodash', | ||||
|     'objectUtils' | ||||
| ], function ( | ||||
|     _, | ||||
|     objectUtils | ||||
| ) { | ||||
|     /** | ||||
|      * A CompositionProvider provides the underlying implementation of | ||||
|      * composition-related behavior for certain types of domain object. | ||||
|      * | ||||
|      * By default, a composition provider will not support composition | ||||
|      * modification.  You can add support for mutation of composition by | ||||
|      * defining `add` and/or `remove` methods. | ||||
|      * | ||||
|      * If the composition of an object can change over time-- perhaps via | ||||
|      * server updates or mutation via the add/remove methods, then one must | ||||
|      * trigger events as necessary. | ||||
|      * | ||||
|      * @interface CompositionProvider | ||||
|      * @memberof module:openmct | ||||
|      */ | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../objects/ObjectAPI').Identifier} Identifier | ||||
|  */ | ||||
|     function DefaultCompositionProvider(publicAPI, compositionAPI) { | ||||
|         this.publicAPI = publicAPI; | ||||
|         this.listeningTo = {}; | ||||
|         this.onMutation = this.onMutation.bind(this); | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('./CompositionAPI').default} CompositionAPI | ||||
|  */ | ||||
|         this.cannotContainItself = this.cannotContainItself.bind(this); | ||||
|         this.supportsComposition = this.supportsComposition.bind(this); | ||||
|  | ||||
| /** | ||||
|  * @typedef {import('../../../openmct').OpenMCT} OpenMCT | ||||
|  */ | ||||
|         compositionAPI.addPolicy(this.cannotContainItself); | ||||
|         compositionAPI.addPolicy(this.supportsComposition); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     DefaultCompositionProvider.prototype.cannotContainItself = function (parent, child) { | ||||
|         return !(parent.identifier.namespace === child.identifier.namespace | ||||
|             && parent.identifier.key === child.identifier.key); | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     DefaultCompositionProvider.prototype.supportsComposition = function (parent, child) { | ||||
|         return this.publicAPI.composition.supportsComposition(parent); | ||||
|     }; | ||||
|  | ||||
| /** | ||||
|  * A CompositionProvider provides the underlying implementation of | ||||
|  * composition-related behavior for certain types of domain object. | ||||
|  * | ||||
|  * By default, a composition provider will not support composition | ||||
|  * modification.  You can add support for mutation of composition by | ||||
|  * defining `add` and/or `remove` methods. | ||||
|  * | ||||
|  * If the composition of an object can change over time-- perhaps via | ||||
|  * server updates or mutation via the add/remove methods, then one must | ||||
|  * trigger events as necessary. | ||||
|  * @extends CompositionProvider | ||||
|  */ | ||||
| export default class DefaultCompositionProvider extends CompositionProvider { | ||||
|     /** | ||||
|      * Check if this provider should be used to load composition for a | ||||
|      * particular domain object. | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject the domain object | ||||
|      * @param {module:openmct.DomainObject} domainObject the domain object | ||||
|      *        to check | ||||
|      * @returns {boolean} true if this provider can provide composition for a given domain object | ||||
|      * @returns {boolean} true if this provider can provide | ||||
|      *          composition for a given domain object | ||||
|      * @memberof module:openmct.CompositionProvider# | ||||
|      * @method appliesTo | ||||
|      */ | ||||
|     appliesTo(domainObject) { | ||||
|     DefaultCompositionProvider.prototype.appliesTo = function (domainObject) { | ||||
|         return Boolean(domainObject.composition); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Load any domain objects contained in the composition of this domain | ||||
|      * object. | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject the domain object | ||||
|      * @param {module:openmct.DomainObject} domainObject the domain object | ||||
|      *        for which to load composition | ||||
|      * @returns {Promise<Identifier[]>} a promise for | ||||
|      * @returns {Promise.<Array.<module:openmct.Identifier>>} a promise for | ||||
|      *          the Identifiers in this composition | ||||
|      * @memberof module:openmct.CompositionProvider# | ||||
|      * @method load | ||||
|      */ | ||||
|     load(domainObject) { | ||||
|     DefaultCompositionProvider.prototype.load = function (domainObject) { | ||||
|         return Promise.all(domainObject.composition); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Attach listeners for changes to the composition of a given domain object. | ||||
|      * Supports `add` and `remove` events. | ||||
|      * | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject to listen to | ||||
|      * @param {string} event the event to bind to, either `add` or `remove`. | ||||
|      * @param {Function} callback callback to invoke when event is triggered. | ||||
|      * @param {any} [context] to use when invoking callback. | ||||
|      * @param {module:openmct.DomainObject} domainObject to listen to | ||||
|      * @param String event the event to bind to, either `add` or `remove`. | ||||
|      * @param Function callback callback to invoke when event is triggered. | ||||
|      * @param [context] context to use when invoking callback. | ||||
|      */ | ||||
|     on(domainObject, | ||||
|     DefaultCompositionProvider.prototype.on = function ( | ||||
|         domainObject, | ||||
|         event, | ||||
|         callback, | ||||
|         context) { | ||||
|         context | ||||
|     ) { | ||||
|         this.establishTopicListener(); | ||||
|  | ||||
|         /** @type {string} */ | ||||
|         const keyString = objectUtils.makeKeyString(domainObject.identifier); | ||||
|         let objectListeners = this.listeningTo[keyString]; | ||||
|  | ||||
| @@ -108,24 +131,24 @@ export default class DefaultCompositionProvider extends CompositionProvider { | ||||
|             callback: callback, | ||||
|             context: context | ||||
|         }); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Remove a listener that was previously added for a given domain object. | ||||
|      * event name, callback, and context must be the same as when the listener | ||||
|      * was originally attached. | ||||
|      * | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject to remove listener for | ||||
|      * @param {string} event event to stop listening to: `add` or `remove`. | ||||
|      * @param {Function} callback callback to remove. | ||||
|      * @param {any} context of callback to remove. | ||||
|      * @param {module:openmct.DomainObject} domainObject to remove listener for | ||||
|      * @param String event event to stop listening to: `add` or `remove`. | ||||
|      * @param Function callback callback to remove. | ||||
|      * @param [context] context of callback to remove. | ||||
|      */ | ||||
|     off(domainObject, | ||||
|     DefaultCompositionProvider.prototype.off = function ( | ||||
|         domainObject, | ||||
|         event, | ||||
|         callback, | ||||
|         context) { | ||||
|  | ||||
|         /** @type {string} */ | ||||
|         context | ||||
|     ) { | ||||
|         const keyString = objectUtils.makeKeyString(domainObject.identifier); | ||||
|         const objectListeners = this.listeningTo[keyString]; | ||||
|  | ||||
| @@ -137,64 +160,57 @@ export default class DefaultCompositionProvider extends CompositionProvider { | ||||
|         if (!objectListeners.add.length && !objectListeners.remove.length && !objectListeners.reorder.length) { | ||||
|             delete this.listeningTo[keyString]; | ||||
|         } | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Remove a domain object from another domain object's composition. | ||||
|      * | ||||
|      * This method is optional; if not present, adding to a domain object's | ||||
|      * composition using this provider will be disallowed. | ||||
|      * | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject the domain object | ||||
|      * @param {module:openmct.DomainObject} domainObject the domain object | ||||
|      *        which should have its composition modified | ||||
|      * @param {Identifier} childId the domain object to remove | ||||
|      * @param {module:openmct.DomainObject} child the domain object to remove | ||||
|      * @memberof module:openmct.CompositionProvider# | ||||
|      * @method remove | ||||
|      */ | ||||
|     remove(domainObject, childId) { | ||||
|     DefaultCompositionProvider.prototype.remove = function (domainObject, childId) { | ||||
|         let composition = domainObject.composition.filter(function (child) { | ||||
|             return !(childId.namespace === child.namespace | ||||
|                       && childId.key === child.key); | ||||
|                 && childId.key === child.key); | ||||
|         }); | ||||
|  | ||||
|         this.publicAPI.objects.mutate(domainObject, 'composition', composition); | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Add a domain object to another domain object's composition. | ||||
|      * | ||||
|      * This method is optional; if not present, adding to a domain object's | ||||
|      * composition using this provider will be disallowed. | ||||
|      * | ||||
|      * @override | ||||
|      * @param {DomainObject} parent the domain object | ||||
|      * @param {module:openmct.DomainObject} domainObject the domain object | ||||
|      *        which should have its composition modified | ||||
|      * @param {Identifier} childId the domain object to add | ||||
|      * @param {module:openmct.DomainObject} child the domain object to add | ||||
|      * @memberof module:openmct.CompositionProvider# | ||||
|      * @method add | ||||
|      */ | ||||
|     add(parent, childId) { | ||||
|     DefaultCompositionProvider.prototype.add = function (parent, childId) { | ||||
|         if (!this.includes(parent, childId)) { | ||||
|             parent.composition.push(childId); | ||||
|             this.publicAPI.objects.mutate(parent, 'composition', parent.composition); | ||||
|         } | ||||
|     } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * @override | ||||
|      * @param {DomainObject} parent | ||||
|      * @param {Identifier} childId | ||||
|      * @returns {boolean} | ||||
|      * @private | ||||
|      */ | ||||
|     includes(parent, childId) { | ||||
|         return parent.composition.some(composee => this.publicAPI.objects.areIdsEqual(composee, childId)); | ||||
|     } | ||||
|     DefaultCompositionProvider.prototype.includes = function (parent, childId) { | ||||
|         return parent.composition.some(composee => | ||||
|             this.publicAPI.objects.areIdsEqual(composee, childId)); | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * @override | ||||
|      * @param {DomainObject} domainObject | ||||
|      * @param {number} oldIndex | ||||
|      * @param {number} newIndex | ||||
|      * @returns | ||||
|      */ | ||||
|     reorder(domainObject, oldIndex, newIndex) { | ||||
|     DefaultCompositionProvider.prototype.reorder = function (domainObject, oldIndex, newIndex) { | ||||
|         let newComposition = domainObject.composition.slice(); | ||||
|         let removeId = oldIndex > newIndex ? oldIndex + 1 : oldIndex; | ||||
|         let insertPosition = oldIndex < newIndex ? newIndex + 1 : newIndex; | ||||
| @@ -225,7 +241,6 @@ export default class DefaultCompositionProvider extends CompositionProvider { | ||||
|  | ||||
|         this.publicAPI.objects.mutate(domainObject, 'composition', newComposition); | ||||
|  | ||||
|         /** @type {string} */ | ||||
|         let id = objectUtils.makeKeyString(domainObject.identifier); | ||||
|         const listeners = this.listeningTo[id]; | ||||
|  | ||||
| @@ -242,5 +257,66 @@ export default class DefaultCompositionProvider extends CompositionProvider { | ||||
|                 listener.callback(reorderPlan); | ||||
|             } | ||||
|         } | ||||
|     } | ||||
| } | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Listens on general mutation topic, using injector to fetch to avoid | ||||
|      * circular dependencies. | ||||
|      * | ||||
|      * @private | ||||
|      */ | ||||
|     DefaultCompositionProvider.prototype.establishTopicListener = function () { | ||||
|         if (this.topicListener) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         this.publicAPI.objects.eventEmitter.on('mutation', this.onMutation); | ||||
|         this.topicListener = () => { | ||||
|             this.publicAPI.objects.eventEmitter.off('mutation', this.onMutation); | ||||
|         }; | ||||
|     }; | ||||
|  | ||||
|     /** | ||||
|      * Handles mutation events.  If there are active listeners for the mutated | ||||
|      * object, detects changes to composition and triggers necessary events. | ||||
|      * | ||||
|      * @private | ||||
|      */ | ||||
|     DefaultCompositionProvider.prototype.onMutation = function (oldDomainObject) { | ||||
|         const id = objectUtils.makeKeyString(oldDomainObject.identifier); | ||||
|         const listeners = this.listeningTo[id]; | ||||
|  | ||||
|         if (!listeners) { | ||||
|             return; | ||||
|         } | ||||
|  | ||||
|         const oldComposition = listeners.composition.map(objectUtils.makeKeyString); | ||||
|         const newComposition = oldDomainObject.composition.map(objectUtils.makeKeyString); | ||||
|  | ||||
|         const added = _.difference(newComposition, oldComposition).map(objectUtils.parseKeyString); | ||||
|         const removed = _.difference(oldComposition, newComposition).map(objectUtils.parseKeyString); | ||||
|  | ||||
|         function notify(value) { | ||||
|             return function (listener) { | ||||
|                 if (listener.context) { | ||||
|                     listener.callback.call(listener.context, value); | ||||
|                 } else { | ||||
|                     listener.callback(value); | ||||
|                 } | ||||
|             }; | ||||
|         } | ||||
|  | ||||
|         listeners.composition = newComposition.map(objectUtils.parseKeyString); | ||||
|  | ||||
|         added.forEach(function (addedChild) { | ||||
|             listeners.add.forEach(notify(addedChild)); | ||||
|         }); | ||||
|  | ||||
|         removed.forEach(function (removedChild) { | ||||
|             listeners.remove.forEach(notify(removedChild)); | ||||
|         }); | ||||
|  | ||||
|     }; | ||||
|  | ||||
|     return DefaultCompositionProvider; | ||||
| }); | ||||
|   | ||||
| @@ -23,11 +23,13 @@ | ||||
| import FormController from './FormController'; | ||||
| import FormProperties from './components/FormProperties.vue'; | ||||
|  | ||||
| import EventEmitter from 'EventEmitter'; | ||||
| import Vue from 'vue'; | ||||
| import _ from 'lodash'; | ||||
|  | ||||
| export default class FormsAPI { | ||||
| export default class FormsAPI extends EventEmitter { | ||||
|     constructor(openmct) { | ||||
|         super(); | ||||
|  | ||||
|         this.openmct = openmct; | ||||
|         this.formController = new FormController(openmct); | ||||
|     } | ||||
| @@ -90,75 +92,29 @@ export default class FormsAPI { | ||||
|  | ||||
|     /** | ||||
|      * Show form inside an Overlay dialog with given form structure | ||||
|      * @public | ||||
|      * @param {Array<Section>} formStructure a form structure, array of section | ||||
|      * @param {Object} options | ||||
|      *      @property {function} onChange a callback function when any changes detected | ||||
|      */ | ||||
|     showForm(formStructure, { | ||||
|         onChange | ||||
|     } = {}) { | ||||
|         let overlay; | ||||
|  | ||||
|         const self = this; | ||||
|  | ||||
|         const overlayEl = document.createElement('div'); | ||||
|         overlayEl.classList.add('u-contents'); | ||||
|  | ||||
|         overlay = self.openmct.overlays.overlay({ | ||||
|             element: overlayEl, | ||||
|             size: 'dialog' | ||||
|         }); | ||||
|  | ||||
|         let formSave; | ||||
|         let formCancel; | ||||
|         const promise = new Promise((resolve, reject) => { | ||||
|             formSave = resolve; | ||||
|             formCancel = reject; | ||||
|         }); | ||||
|  | ||||
|         this.showCustomForm(formStructure, { | ||||
|             element: overlayEl, | ||||
|             onChange | ||||
|         }) | ||||
|             .then((response) => { | ||||
|                 overlay.dismiss(); | ||||
|                 formSave(response); | ||||
|             }) | ||||
|             .catch((response) => { | ||||
|                 overlay.dismiss(); | ||||
|                 formCancel(response); | ||||
|             }); | ||||
|  | ||||
|         return promise; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Show form as a child of the element provided with given form structure | ||||
|      * | ||||
|      * @public | ||||
|      * @param {Array<Section>} formStructure a form structure, array of section | ||||
|      * @param {Object} options | ||||
|      *      @property {HTMLElement} element Parent Element to render a Form | ||||
|      *      @property {function} onChange a callback function when any changes detected | ||||
|      *      @property {function} onSave a callback function when form is submitted | ||||
|      *      @property {function} onDismiss a callback function when form is dismissed | ||||
|      */ | ||||
|     showCustomForm(formStructure, { | ||||
|     showForm(formStructure, { | ||||
|         element, | ||||
|         onChange | ||||
|     } = {}) { | ||||
|         if (element === undefined) { | ||||
|             throw Error('Required element parameter not provided'); | ||||
|         } | ||||
|         const changes = {}; | ||||
|         let overlay; | ||||
|         let onDismiss; | ||||
|         let onSave; | ||||
|  | ||||
|         const self = this; | ||||
|  | ||||
|         const changes = {}; | ||||
|         let formSave; | ||||
|         let formCancel; | ||||
|  | ||||
|         const promise = new Promise((resolve, reject) => { | ||||
|             formSave = onFormAction(resolve); | ||||
|             formCancel = onFormAction(reject); | ||||
|             onSave = onFormAction(resolve); | ||||
|             onDismiss = onFormAction(reject); | ||||
|         }); | ||||
|  | ||||
|         const vm = new Vue({ | ||||
| @@ -170,17 +126,26 @@ export default class FormsAPI { | ||||
|                 return { | ||||
|                     formStructure, | ||||
|                     onChange: onFormPropertyChange, | ||||
|                     onCancel: formCancel, | ||||
|                     onSave: formSave | ||||
|                     onDismiss, | ||||
|                     onSave | ||||
|                 }; | ||||
|             }, | ||||
|             template: '<FormProperties :model="formStructure" @onChange="onChange" @onCancel="onCancel" @onSave="onSave"></FormProperties>' | ||||
|             template: '<FormProperties :model="formStructure" @onChange="onChange" @onDismiss="onDismiss" @onSave="onSave"></FormProperties>' | ||||
|         }).$mount(); | ||||
|  | ||||
|         const formElement = vm.$el; | ||||
|         element.append(formElement); | ||||
|         if (element) { | ||||
|             element.append(formElement); | ||||
|         } else { | ||||
|             overlay = self.openmct.overlays.overlay({ | ||||
|                 element: vm.$el, | ||||
|                 size: 'small', | ||||
|                 onDestroy: () => vm.$destroy() | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         function onFormPropertyChange(data) { | ||||
|             self.emit('onFormPropertyChange', data); | ||||
|             if (onChange) { | ||||
|                 onChange(data); | ||||
|             } | ||||
| @@ -193,14 +158,17 @@ export default class FormsAPI { | ||||
|                     key = property.join('.'); | ||||
|                 } | ||||
|  | ||||
|                 _.set(changes, key, data.value); | ||||
|                 changes[key] = data.value; | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         function onFormAction(callback) { | ||||
|             return () => { | ||||
|                 formElement.remove(); | ||||
|                 vm.$destroy(); | ||||
|                 if (element) { | ||||
|                     formElement.remove(); | ||||
|                 } else { | ||||
|                     overlay.dismiss(); | ||||
|                 } | ||||
|  | ||||
|                 if (callback) { | ||||
|                     callback(changes); | ||||
|   | ||||
| @@ -133,7 +133,7 @@ describe('The Forms API', () => { | ||||
|         }); | ||||
|  | ||||
|         it('when container element is provided', (done) => { | ||||
|             openmct.forms.showCustomForm(formStructure, { element }).catch(() => { | ||||
|             openmct.forms.showForm(formStructure, { element }).catch(() => { | ||||
|                 done(); | ||||
|             }); | ||||
|             const titleElement = element.querySelector('.c-overlay__dialog-title'); | ||||
|   | ||||
| @@ -73,7 +73,7 @@ | ||||
|             tabindex="0" | ||||
|             class="c-button js-cancel-button" | ||||
|             aria-label="Cancel" | ||||
|             @click="onCancel" | ||||
|             @click="onDismiss" | ||||
|         > | ||||
|             {{ cancelLabel }} | ||||
|         </button> | ||||
| @@ -164,8 +164,8 @@ export default { | ||||
|  | ||||
|             this.$emit('onChange', data); | ||||
|         }, | ||||
|         onCancel() { | ||||
|             this.$emit('onCancel'); | ||||
|         onDismiss() { | ||||
|             this.$emit('onDismiss'); | ||||
|         }, | ||||
|         onSave() { | ||||
|             this.$emit('onSave'); | ||||
|   | ||||
| @@ -32,49 +32,53 @@ | ||||
|         prevent | ||||
|         class="u-contents" | ||||
|     > | ||||
|         <input | ||||
|             v-model="date" | ||||
|             class="field control date" | ||||
|             :pattern="/\d{4}-\d{2}-\d{2}/" | ||||
|             :placeholder="format" | ||||
|             type="date" | ||||
|             name="date" | ||||
|             @change="onChange" | ||||
|         > | ||||
|         <input | ||||
|             v-model="hour" | ||||
|             class="field control hour c-input--sm" | ||||
|             :pattern="/\d+/" | ||||
|             type="number" | ||||
|             name="hour" | ||||
|             maxlength="10" | ||||
|             min="0" | ||||
|             max="23" | ||||
|             @change="onChange" | ||||
|         > | ||||
|         <input | ||||
|             v-model="min" | ||||
|             class="field control min c-input--sm" | ||||
|             :pattern="/\d+/" | ||||
|             type="number" | ||||
|             name="min" | ||||
|             maxlength="2" | ||||
|             min="0" | ||||
|             max="59" | ||||
|             @change="onChange" | ||||
|         > | ||||
|         <input | ||||
|             v-model="sec" | ||||
|             class="field control sec c-input--sm" | ||||
|             :pattern="/\d+/" | ||||
|             type="number" | ||||
|             name="sec" | ||||
|             maxlength="2" | ||||
|             min="0" | ||||
|             max="59" | ||||
|             @change="onChange" | ||||
|         > | ||||
|         <div class="field control hint timezone"> | ||||
|         <div class="field control date"> | ||||
|             <input | ||||
|                 v-model="date" | ||||
|                 :pattern="/\d{4}-\d{2}-\d{2}/" | ||||
|                 :placeholder="format" | ||||
|                 type="date" | ||||
|                 name="date" | ||||
|                 @change="onChange" | ||||
|             > | ||||
|         </div> | ||||
|         <div class="field control hour sm"> | ||||
|             <input | ||||
|                 v-model="hour" | ||||
|                 :pattern="/\d+/" | ||||
|                 type="number" | ||||
|                 name="hour" | ||||
|                 maxlength="10" | ||||
|                 min="0" | ||||
|                 max="23" | ||||
|                 @change="onChange" | ||||
|             > | ||||
|         </div> | ||||
|         <div class="field control min sm"> | ||||
|             <input | ||||
|                 v-model="min" | ||||
|                 :pattern="/\d+/" | ||||
|                 type="number" | ||||
|                 name="min" | ||||
|                 maxlength="2" | ||||
|                 min="0" | ||||
|                 max="59" | ||||
|                 @change="onChange" | ||||
|             > | ||||
|         </div> | ||||
|         <div class="field control sec sm"> | ||||
|             <input | ||||
|                 v-model="sec" | ||||
|                 :pattern="/\d+/" | ||||
|                 type="number" | ||||
|                 name="sec" | ||||
|                 maxlength="2" | ||||
|                 min="0" | ||||
|                 max="59" | ||||
|                 @change="onChange" | ||||
|             > | ||||
|         </div> | ||||
|         <div class="field control timezone"> | ||||
|             UTC | ||||
|         </div> | ||||
|     </form> | ||||
|   | ||||
| @@ -42,6 +42,7 @@ class InMemorySearchProvider { | ||||
|         this.openmct = openmct; | ||||
|         this.indexedIds = {}; | ||||
|         this.indexedCompositions = {}; | ||||
|         this.indexedTags = {}; | ||||
|         this.idsToIndex = []; | ||||
|         this.pendingIndex = {}; | ||||
|         this.pendingRequests = 0; | ||||
| @@ -60,6 +61,7 @@ class InMemorySearchProvider { | ||||
|         this.localSearchForObjects = this.localSearchForObjects.bind(this); | ||||
|         this.localSearchForAnnotations = this.localSearchForAnnotations.bind(this); | ||||
|         this.localSearchForTags = this.localSearchForTags.bind(this); | ||||
|         this.localSearchForNotebookAnnotations = this.localSearchForNotebookAnnotations.bind(this); | ||||
|         this.onAnnotationCreation = this.onAnnotationCreation.bind(this); | ||||
|         this.onCompositionAdded = this.onCompositionAdded.bind(this); | ||||
|         this.onCompositionRemoved = this.onCompositionRemoved.bind(this); | ||||
| @@ -91,7 +93,7 @@ class InMemorySearchProvider { | ||||
|  | ||||
|         this.searchTypes = this.openmct.objects.SEARCH_TYPES; | ||||
|  | ||||
|         this.supportedSearchTypes = [this.searchTypes.OBJECTS, this.searchTypes.ANNOTATIONS, this.searchTypes.TAGS]; | ||||
|         this.supportedSearchTypes = [this.searchTypes.OBJECTS, this.searchTypes.ANNOTATIONS, this.searchTypes.NOTEBOOK_ANNOTATIONS, this.searchTypes.TAGS]; | ||||
|  | ||||
|         this.scheduleForIndexing(rootObject.identifier); | ||||
|  | ||||
| @@ -161,6 +163,8 @@ class InMemorySearchProvider { | ||||
|             return this.localSearchForObjects(queryId, query, maxResults); | ||||
|         } else if (searchType === this.searchTypes.ANNOTATIONS) { | ||||
|             return this.localSearchForAnnotations(queryId, query, maxResults); | ||||
|         } else if (searchType === this.searchTypes.NOTEBOOK_ANNOTATIONS) { | ||||
|             return this.localSearchForNotebookAnnotations(queryId, query, maxResults); | ||||
|         } else if (searchType === this.searchTypes.TAGS) { | ||||
|             return this.localSearchForTags(queryId, query, maxResults); | ||||
|         } else { | ||||
| @@ -277,6 +281,13 @@ class InMemorySearchProvider { | ||||
|         provider.index(domainObject); | ||||
|     } | ||||
|  | ||||
|     onTagMutation(domainObject, newTags) { | ||||
|         domainObject.tags = newTags; | ||||
|         const provider = this; | ||||
|  | ||||
|         provider.index(domainObject); | ||||
|     } | ||||
|  | ||||
|     onCompositionAdded(newDomainObjectToIndex) { | ||||
|         const provider = this; | ||||
|         // The object comes in as a mutable domain object, which has functions, | ||||
| @@ -331,6 +342,14 @@ class InMemorySearchProvider { | ||||
|                 composition.on('remove', this.onCompositionRemoved); | ||||
|                 this.indexedCompositions[keyString] = composition; | ||||
|             } | ||||
|  | ||||
|             if (domainObject.type === 'annotation') { | ||||
|                 this.indexedTags[keyString] = this.openmct.objects.observe( | ||||
|                     domainObject, | ||||
|                     'tags', | ||||
|                     this.onTagMutation.bind(this, domainObject) | ||||
|                 ); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         if ((keyString !== 'ROOT')) { | ||||
| @@ -562,6 +581,43 @@ class InMemorySearchProvider { | ||||
|         this.onWorkerMessage(eventToReturn); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * A local version of the same SharedWorker function | ||||
|      * if we don't have SharedWorkers available (e.g., iOS) | ||||
|      */ | ||||
|     localSearchForNotebookAnnotations(queryId, {entryId, targetKeyString}, maxResults) { | ||||
|         // This results dictionary will have domain object ID keys which | ||||
|         // point to the value the domain object's score. | ||||
|         let results = []; | ||||
|         const message = { | ||||
|             request: 'searchForNotebookAnnotations', | ||||
|             results: [], | ||||
|             total: 0, | ||||
|             queryId | ||||
|         }; | ||||
|  | ||||
|         const matchingAnnotations = this.localIndexedAnnotationsByDomainObject[targetKeyString]; | ||||
|         if (matchingAnnotations) { | ||||
|             results = matchingAnnotations.filter(matchingAnnotation => { | ||||
|                 if (!matchingAnnotation.targets) { | ||||
|                     return false; | ||||
|                 } | ||||
|  | ||||
|                 const target = matchingAnnotation.targets[targetKeyString]; | ||||
|  | ||||
|                 return (target && target.entryId && (target.entryId === entryId)); | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         message.total = results.length; | ||||
|         message.results = results | ||||
|             .slice(0, maxResults); | ||||
|         const eventToReturn = { | ||||
|             data: message | ||||
|         }; | ||||
|         this.onWorkerMessage(eventToReturn); | ||||
|     } | ||||
|  | ||||
|     destroyObservers(observers) { | ||||
|         Object.entries(observers).forEach(([keyString, unobserve]) => { | ||||
|             if (typeof unobserve === 'function') { | ||||
|   | ||||
| @@ -43,6 +43,8 @@ | ||||
|                 port.postMessage(searchForAnnotations(event.data)); | ||||
|             } else if (requestType === 'TAGS') { | ||||
|                 port.postMessage(searchForTags(event.data)); | ||||
|             } else if (requestType === 'NOTEBOOK_ANNOTATIONS') { | ||||
|                 port.postMessage(searchForNotebookAnnotations(event.data)); | ||||
|             } else { | ||||
|                 throw new Error(`Unknown request ${event.data.request}`); | ||||
|             } | ||||
| @@ -202,4 +204,33 @@ | ||||
|  | ||||
|         return message; | ||||
|     } | ||||
|  | ||||
|     function searchForNotebookAnnotations(data) { | ||||
|         let results = []; | ||||
|         const message = { | ||||
|             request: 'searchForNotebookAnnotations', | ||||
|             results: {}, | ||||
|             total: 0, | ||||
|             queryId: data.queryId | ||||
|         }; | ||||
|  | ||||
|         const matchingAnnotations = indexedAnnotationsByDomainObject[data.input.targetKeyString]; | ||||
|         if (matchingAnnotations) { | ||||
|             results = matchingAnnotations.filter(matchingAnnotation => { | ||||
|                 if (!matchingAnnotation.targets) { | ||||
|                     return false; | ||||
|                 } | ||||
|  | ||||
|                 const target = matchingAnnotation.targets[data.input.targetKeyString]; | ||||
|  | ||||
|                 return (target && target.entryId && (target.entryId === data.input.entryId)); | ||||
|             }); | ||||
|         } | ||||
|  | ||||
|         message.total = results.length; | ||||
|         message.results = results | ||||
|             .slice(0, data.maxResults); | ||||
|  | ||||
|         return message; | ||||
|     } | ||||
| }()); | ||||
|   | ||||
| @@ -75,7 +75,11 @@ class MutableDomainObject { | ||||
|         return eventOff; | ||||
|     } | ||||
|     $set(path, value) { | ||||
|         MutableDomainObject.mutateObject(this, path, value); | ||||
|         _.set(this, path, value); | ||||
|  | ||||
|         if (path !== 'persisted' && path !== 'modified') { | ||||
|             _.set(this, 'modified', Date.now()); | ||||
|         } | ||||
|  | ||||
|         //Emit secret synchronization event first, so that all objects are in sync before subsequent events fired. | ||||
|         this._globalEventEmitter.emit(qualifiedEventName(this, '$_synchronize_model'), this); | ||||
| @@ -132,11 +136,8 @@ class MutableDomainObject { | ||||
|     } | ||||
|  | ||||
|     static mutateObject(object, path, value) { | ||||
|         if (path !== 'persisted') { | ||||
|             _.set(object, 'modified', Date.now()); | ||||
|         } | ||||
|  | ||||
|         _.set(object, path, value); | ||||
|         _.set(object, 'modified', Date.now()); | ||||
|     } | ||||
| } | ||||
|  | ||||
|   | ||||
| @@ -33,7 +33,7 @@ import InMemorySearchProvider from './InMemorySearchProvider'; | ||||
| /** | ||||
|  * Uniquely identifies a domain object. | ||||
|  * | ||||
|  * @typedef {object} Identifier | ||||
|  * @typedef Identifier | ||||
|  * @property {string} namespace the namespace to/from which this domain | ||||
|  *           object should be loaded/stored. | ||||
|  * @property {string} key a unique identifier for the domain object | ||||
| @@ -50,8 +50,8 @@ import InMemorySearchProvider from './InMemorySearchProvider'; | ||||
|  * A few common properties are defined for domain objects. Beyond these, | ||||
|  * individual types of domain objects may add more as they see fit. | ||||
|  * | ||||
|  * @typedef {object} DomainObject | ||||
|  * @property {Identifier} identifier a key/namespace pair which | ||||
|  * @typedef DomainObject | ||||
|  * @property {module:openmct.ObjectAPI~Identifier} identifier a key/namespace pair which | ||||
|  *           uniquely identifies this domain object | ||||
|  * @property {string} type the type of domain object | ||||
|  * @property {string} name the human-readable name for this domain object | ||||
| @@ -59,20 +59,11 @@ import InMemorySearchProvider from './InMemorySearchProvider'; | ||||
|  *           object | ||||
|  * @property {number} [modified] the time, in milliseconds since the UNIX | ||||
|  *           epoch, at which this domain object was last modified | ||||
|  * @property {Identifier[]} [composition] if | ||||
|  * @property {module:openmct.ObjectAPI~Identifier[]} [composition] if | ||||
|  *           present, this will be used by the default composition provider | ||||
|  *           to load domain objects | ||||
|  * @memberof module:openmct.ObjectAPI~ | ||||
|  * @memberof module:openmct | ||||
|  */ | ||||
|  | ||||
| /** | ||||
|   * @readonly | ||||
|   * @enum {string} SEARCH_TYPES | ||||
|   * @property {string} OBJECTS Search for objects | ||||
|   * @property {string} ANNOTATIONS Search for annotations | ||||
|   * @property {string} TAGS Search for tags | ||||
|   */ | ||||
|  | ||||
| /** | ||||
|  * Utilities for loading, saving, and manipulating domain objects. | ||||
|  * @interface ObjectAPI | ||||
| @@ -85,6 +76,7 @@ export default class ObjectAPI { | ||||
|         this.SEARCH_TYPES = Object.freeze({ | ||||
|             OBJECTS: 'OBJECTS', | ||||
|             ANNOTATIONS: 'ANNOTATIONS', | ||||
|             NOTEBOOK_ANNOTATIONS: 'NOTEBOOK_ANNOTATIONS', | ||||
|             TAGS: 'TAGS' | ||||
|         }); | ||||
|         this.eventEmitter = new EventEmitter(); | ||||
| @@ -96,7 +88,7 @@ export default class ObjectAPI { | ||||
|         this.cache = {}; | ||||
|         this.interceptorRegistry = new InterceptorRegistry(); | ||||
|  | ||||
|         this.SYNCHRONIZED_OBJECT_TYPES = ['notebook', 'restricted-notebook', 'plan', 'annotation']; | ||||
|         this.SYNCHRONIZED_OBJECT_TYPES = ['notebook', 'plan', 'annotation']; | ||||
|  | ||||
|         this.errors = { | ||||
|             Conflict: ConflictError | ||||
| @@ -196,6 +188,7 @@ export default class ObjectAPI { | ||||
|      * @returns {Promise} a promise which will resolve when the domain object | ||||
|      *          has been saved, or be rejected if it cannot be saved | ||||
|      */ | ||||
|  | ||||
|     get(identifier, abortSignal) { | ||||
|         let keystring = this.makeKeyString(identifier); | ||||
|  | ||||
| @@ -204,13 +197,13 @@ export default class ObjectAPI { | ||||
|         } | ||||
|  | ||||
|         identifier = utils.parseKeyString(identifier); | ||||
|  | ||||
|         let dirtyObject; | ||||
|         if (this.isTransactionActive()) { | ||||
|             let dirtyObject = this.transaction.getDirtyObject(identifier); | ||||
|             dirtyObject = this.transaction.getDirtyObject(identifier); | ||||
|         } | ||||
|  | ||||
|             if (dirtyObject) { | ||||
|                 return Promise.resolve(dirtyObject); | ||||
|             } | ||||
|         if (dirtyObject) { | ||||
|             return Promise.resolve(dirtyObject); | ||||
|         } | ||||
|  | ||||
|         const provider = this.getProvider(identifier); | ||||
| @@ -230,7 +223,7 @@ export default class ObjectAPI { | ||||
|             if (result.isMutable) { | ||||
|                 result.$refresh(result); | ||||
|             } else { | ||||
|                 let mutableDomainObject = this.toMutable(result); | ||||
|                 let mutableDomainObject = this._toMutable(result); | ||||
|                 mutableDomainObject.$refresh(result); | ||||
|             } | ||||
|  | ||||
| @@ -307,7 +300,7 @@ export default class ObjectAPI { | ||||
|         } | ||||
|  | ||||
|         return this.get(identifier).then((object) => { | ||||
|             return this.toMutable(object); | ||||
|             return this._toMutable(object); | ||||
|         }); | ||||
|     } | ||||
|  | ||||
| @@ -354,8 +347,10 @@ export default class ObjectAPI { | ||||
|      * @returns {Promise} a promise which will resolve when the domain object | ||||
|      *          has been saved, or be rejected if it cannot be saved | ||||
|      */ | ||||
|     async save(domainObject) { | ||||
|         const provider = this.getProvider(domainObject.identifier); | ||||
|     save(domainObject) { | ||||
|         let provider = this.getProvider(domainObject.identifier); | ||||
|         let savedResolve; | ||||
|         let savedReject; | ||||
|         let result; | ||||
|  | ||||
|         if (!this.isPersistable(domainObject.identifier)) { | ||||
| @@ -363,42 +358,28 @@ export default class ObjectAPI { | ||||
|         } else if (this.#hasAlreadyBeenPersisted(domainObject)) { | ||||
|             result = Promise.resolve(true); | ||||
|         } else { | ||||
|             const username = await this.#getCurrentUsername(); | ||||
|             const isNewObject = domainObject.persisted === undefined; | ||||
|             let savedResolve; | ||||
|             let savedReject; | ||||
|             let savedObjectPromise; | ||||
|  | ||||
|             result = new Promise((resolve, reject) => { | ||||
|                 savedResolve = resolve; | ||||
|                 savedReject = reject; | ||||
|             }); | ||||
|  | ||||
|             this.#mutate(domainObject, 'modifiedBy', username); | ||||
|  | ||||
|             if (isNewObject) { | ||||
|                 const persistedTime = Date.now(); | ||||
|  | ||||
|                 this.#mutate(domainObject, 'persisted', persistedTime); | ||||
|                 this.#mutate(domainObject, 'created', persistedTime); | ||||
|                 this.#mutate(domainObject, 'createdBy', username); | ||||
|  | ||||
|                 savedObjectPromise = provider.create(domainObject); | ||||
|             } else { | ||||
|                 const persistedTime = Date.now(); | ||||
|                 this.#mutate(domainObject, 'persisted', persistedTime); | ||||
|  | ||||
|                 savedObjectPromise = provider.update(domainObject); | ||||
|             } | ||||
|  | ||||
|             if (savedObjectPromise) { | ||||
|                 savedObjectPromise.then(response => { | ||||
|                     savedResolve(response); | ||||
|                 }).catch((error) => { | ||||
|                     savedReject(error); | ||||
|             const persistedTime = Date.now(); | ||||
|             if (domainObject.persisted === undefined) { | ||||
|                 result = new Promise((resolve, reject) => { | ||||
|                     savedResolve = resolve; | ||||
|                     savedReject = reject; | ||||
|                 }); | ||||
|                 domainObject.persisted = persistedTime; | ||||
|                 const newObjectPromise = provider.create(domainObject); | ||||
|                 if (newObjectPromise) { | ||||
|                     newObjectPromise.then(response => { | ||||
|                         this.mutate(domainObject, 'persisted', persistedTime); | ||||
|                         savedResolve(response); | ||||
|                     }).catch((error) => { | ||||
|                         savedReject(error); | ||||
|                     }); | ||||
|                 } else { | ||||
|                     result = Promise.reject(`[ObjectAPI][save] Object provider returned ${newObjectPromise} when creating new object.`); | ||||
|                 } | ||||
|             } else { | ||||
|                 result = Promise.reject(`[ObjectAPI][save] Object provider returned ${savedObjectPromise} when ${isNewObject ? 'creating new' : 'updating'} object.`); | ||||
|                 domainObject.persisted = persistedTime; | ||||
|                 this.mutate(domainObject, 'persisted', persistedTime); | ||||
|                 result = provider.update(domainObject); | ||||
|             } | ||||
|         } | ||||
|  | ||||
| @@ -411,21 +392,8 @@ export default class ObjectAPI { | ||||
|         }); | ||||
|     } | ||||
|  | ||||
|     async #getCurrentUsername() { | ||||
|         const user = await this.openmct.user.getCurrentUser(); | ||||
|         let username; | ||||
|  | ||||
|         if (user !== undefined) { | ||||
|             username = user.getName(); | ||||
|         } | ||||
|  | ||||
|         return username; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * After entering into edit mode, creates a new instance of Transaction to keep track of changes in Objects | ||||
|      * | ||||
|      * @returns {Transaction} a new Transaction that was just created | ||||
|      */ | ||||
|     startTransaction() { | ||||
|         if (this.isTransactionActive()) { | ||||
| @@ -433,8 +401,6 @@ export default class ObjectAPI { | ||||
|         } | ||||
|  | ||||
|         this.transaction = new Transaction(this); | ||||
|  | ||||
|         return this.transaction; | ||||
|     } | ||||
|  | ||||
|     /** | ||||
| @@ -507,16 +473,14 @@ export default class ObjectAPI { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Modify a domain object. Internal to ObjectAPI, won't call save after. | ||||
|      * @private | ||||
|      * | ||||
|      * Modify a domain object. | ||||
|      * @param {module:openmct.DomainObject} object the object to mutate | ||||
|      * @param {string} path the property to modify | ||||
|      * @param {*} value the new value for this property | ||||
|      * @method mutate | ||||
|      * @memberof module:openmct.ObjectAPI# | ||||
|      */ | ||||
|     #mutate(domainObject, path, value) { | ||||
|     mutate(domainObject, path, value) { | ||||
|         if (!this.supportsMutation(domainObject.identifier)) { | ||||
|             throw `Error: Attempted to mutate immutable object ${domainObject.name}`; | ||||
|         } | ||||
| @@ -526,7 +490,7 @@ export default class ObjectAPI { | ||||
|         } else { | ||||
|             //Creating a temporary mutable domain object allows other mutable instances of the | ||||
|             //object to be kept in sync. | ||||
|             let mutableDomainObject = this.toMutable(domainObject); | ||||
|             let mutableDomainObject = this._toMutable(domainObject); | ||||
|  | ||||
|             //Mutate original object | ||||
|             MutableDomainObject.mutateObject(domainObject, path, value); | ||||
| @@ -537,18 +501,6 @@ export default class ObjectAPI { | ||||
|             //Destroy temporary mutable object | ||||
|             this.destroyMutable(mutableDomainObject); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Modify a domain object and save. | ||||
|      * @param {module:openmct.DomainObject} object the object to mutate | ||||
|      * @param {string} path the property to modify | ||||
|      * @param {*} value the new value for this property | ||||
|      * @method mutate | ||||
|      * @memberof module:openmct.ObjectAPI# | ||||
|      */ | ||||
|     mutate(domainObject, path, value) { | ||||
|         this.#mutate(domainObject, path, value); | ||||
|  | ||||
|         if (this.isTransactionActive()) { | ||||
|             this.transaction.add(domainObject); | ||||
| @@ -558,19 +510,15 @@ export default class ObjectAPI { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Create a mutable domain object from an existing domain object | ||||
|      * @param {module:openmct.DomainObject} domainObject the object to make mutable | ||||
|      * @returns {MutableDomainObject} a mutable domain object that will automatically sync | ||||
|      * @method toMutable | ||||
|      * @memberof module:openmct.ObjectAPI# | ||||
|      * @private | ||||
|      */ | ||||
|     toMutable(domainObject) { | ||||
|     _toMutable(object) { | ||||
|         let mutableObject; | ||||
|  | ||||
|         if (domainObject.isMutable) { | ||||
|             mutableObject = domainObject; | ||||
|         if (object.isMutable) { | ||||
|             mutableObject = object; | ||||
|         } else { | ||||
|             mutableObject = MutableDomainObject.createMutable(domainObject, this.eventEmitter); | ||||
|             mutableObject = MutableDomainObject.createMutable(object, this.eventEmitter); | ||||
|  | ||||
|             // Check if provider supports realtime updates | ||||
|             let identifier = utils.parseKeyString(mutableObject.identifier); | ||||
| @@ -578,11 +526,9 @@ export default class ObjectAPI { | ||||
|  | ||||
|             if (provider !== undefined | ||||
|                 && provider.observe !== undefined | ||||
|                 && this.SYNCHRONIZED_OBJECT_TYPES.includes(domainObject.type)) { | ||||
|                 && this.SYNCHRONIZED_OBJECT_TYPES.includes(object.type)) { | ||||
|                 let unobserve = provider.observe(identifier, (updatedModel) => { | ||||
|                     // modified can sometimes be undefined, so make it 0 in this case | ||||
|                     const mutableObjectModification = mutableObject.modified ?? Number.MIN_SAFE_INTEGER; | ||||
|                     if (updatedModel.persisted > mutableObjectModification) { | ||||
|                     if (updatedModel.persisted > mutableObject.modified) { | ||||
|                         //Don't replace with a stale model. This can happen on slow connections when multiple mutations happen | ||||
|                         //in rapid succession and intermediate persistence states are returned by the observe function. | ||||
|                         updatedModel = this.applyGetInterceptors(identifier, updatedModel); | ||||
| @@ -636,7 +582,7 @@ export default class ObjectAPI { | ||||
|         if (domainObject.isMutable) { | ||||
|             return domainObject.$observe(path, callback); | ||||
|         } else { | ||||
|             let mutable = this.toMutable(domainObject); | ||||
|             let mutable = this._toMutable(domainObject); | ||||
|             mutable.$observe(path, callback); | ||||
|  | ||||
|             return () => mutable.$destroy(); | ||||
| @@ -725,14 +671,12 @@ export default class ObjectAPI { | ||||
|     } | ||||
|  | ||||
|     isTransactionActive() { | ||||
|         return this.transaction !== undefined && this.transaction !== null; | ||||
|         return Boolean(this.transaction && this.openmct.editor.isEditing()); | ||||
|     } | ||||
|  | ||||
|     #hasAlreadyBeenPersisted(domainObject) { | ||||
|         // modified can sometimes be undefined, so make it 0 in this case | ||||
|         const modified = domainObject.modified ?? Number.MIN_SAFE_INTEGER; | ||||
|         const result = domainObject.persisted !== undefined | ||||
|             && domainObject.persisted >= modified; | ||||
|             && domainObject.persisted >= domainObject.modified; | ||||
|  | ||||
|         return result; | ||||
|     } | ||||
|   | ||||
| @@ -8,27 +8,13 @@ describe("The Object API", () => { | ||||
|     let mockDomainObject; | ||||
|     const TEST_NAMESPACE = "test-namespace"; | ||||
|     const TEST_KEY = "test-key"; | ||||
|     const USERNAME = 'Joan Q Public'; | ||||
|     const FIFTEEN_MINUTES = 15 * 60 * 1000; | ||||
|  | ||||
|     beforeEach((done) => { | ||||
|         typeRegistry = jasmine.createSpyObj('typeRegistry', [ | ||||
|             'get' | ||||
|         ]); | ||||
|         const userProvider = { | ||||
|             isLoggedIn() { | ||||
|                 return true; | ||||
|             }, | ||||
|             getCurrentUser() { | ||||
|                 return Promise.resolve({ | ||||
|                     getName() { | ||||
|                         return USERNAME; | ||||
|                     } | ||||
|                 }); | ||||
|             } | ||||
|         }; | ||||
|         openmct = createOpenMct(); | ||||
|         openmct.user.setProvider(userProvider); | ||||
|         objectAPI = openmct.objects; | ||||
|  | ||||
|         openmct.editor = {}; | ||||
| @@ -77,63 +63,19 @@ describe("The Object API", () => { | ||||
|                 mockProvider.update.and.returnValue(Promise.resolve(true)); | ||||
|                 objectAPI.addProvider(TEST_NAMESPACE, mockProvider); | ||||
|             }); | ||||
|             it("Adds a 'created' timestamp to new objects", async () => { | ||||
|                 await objectAPI.save(mockDomainObject); | ||||
|                 expect(mockDomainObject.created).not.toBeUndefined(); | ||||
|             }); | ||||
|             it("Calls 'create' on provider if object is new", async () => { | ||||
|                 await objectAPI.save(mockDomainObject); | ||||
|             it("Calls 'create' on provider if object is new", () => { | ||||
|                 objectAPI.save(mockDomainObject); | ||||
|                 expect(mockProvider.create).toHaveBeenCalled(); | ||||
|                 expect(mockProvider.update).not.toHaveBeenCalled(); | ||||
|             }); | ||||
|             it("Calls 'update' on provider if object is not new", async () => { | ||||
|             it("Calls 'update' on provider if object is not new", () => { | ||||
|                 mockDomainObject.persisted = Date.now() - FIFTEEN_MINUTES; | ||||
|                 mockDomainObject.modified = Date.now(); | ||||
|  | ||||
|                 await objectAPI.save(mockDomainObject); | ||||
|                 objectAPI.save(mockDomainObject); | ||||
|                 expect(mockProvider.create).not.toHaveBeenCalled(); | ||||
|                 expect(mockProvider.update).toHaveBeenCalled(); | ||||
|             }); | ||||
|             describe("the persisted timestamp for existing objects", () => { | ||||
|                 let persistedTimestamp; | ||||
|                 beforeEach(() => { | ||||
|                     persistedTimestamp = Date.now() - FIFTEEN_MINUTES; | ||||
|                     mockDomainObject.persisted = persistedTimestamp; | ||||
|                     mockDomainObject.modified = Date.now(); | ||||
|                 }); | ||||
|  | ||||
|                 it("is updated", async () => { | ||||
|                     await objectAPI.save(mockDomainObject); | ||||
|                     expect(mockDomainObject.persisted).toBeDefined(); | ||||
|                     expect(mockDomainObject.persisted > persistedTimestamp).toBe(true); | ||||
|                 }); | ||||
|                 it("is >= modified timestamp", async () => { | ||||
|                     await objectAPI.save(mockDomainObject); | ||||
|                     expect(mockDomainObject.persisted >= mockDomainObject.modified).toBe(true); | ||||
|                 }); | ||||
|             }); | ||||
|             describe("the persisted timestamp for new objects", () => { | ||||
|                 it("is updated", async () => { | ||||
|                     await objectAPI.save(mockDomainObject); | ||||
|                     expect(mockDomainObject.persisted).toBeDefined(); | ||||
|                 }); | ||||
|                 it("is >= modified timestamp", async () => { | ||||
|                     await objectAPI.save(mockDomainObject); | ||||
|                     expect(mockDomainObject.persisted >= mockDomainObject.modified).toBe(true); | ||||
|                 }); | ||||
|             }); | ||||
|  | ||||
|             it("Sets the current user for 'createdBy' on new objects", async () => { | ||||
|                 await objectAPI.save(mockDomainObject); | ||||
|                 expect(mockDomainObject.createdBy).toBe(USERNAME); | ||||
|             }); | ||||
|             it("Sets the current user for 'modifedBy' on existing objects", async () => { | ||||
|                 mockDomainObject.persisted = Date.now() - FIFTEEN_MINUTES; | ||||
|                 mockDomainObject.modified = Date.now(); | ||||
|  | ||||
|                 await objectAPI.save(mockDomainObject); | ||||
|                 expect(mockDomainObject.modifiedBy).toBe(USERNAME); | ||||
|             }); | ||||
|  | ||||
|             it("Does not persist if the object is unchanged", () => { | ||||
|                 mockDomainObject.persisted = | ||||
| @@ -378,7 +320,7 @@ describe("The Object API", () => { | ||||
|             beforeEach(function () { | ||||
|                 // Duplicate object to guarantee we are not sharing object instance, which would invalidate test | ||||
|                 testObjectDuplicate = JSON.parse(JSON.stringify(testObject)); | ||||
|                 mutableSecondInstance = objectAPI.toMutable(testObjectDuplicate); | ||||
|                 mutableSecondInstance = objectAPI._toMutable(testObjectDuplicate); | ||||
|             }); | ||||
|  | ||||
|             afterEach(() => { | ||||
|   | ||||
| @@ -6,8 +6,7 @@ const cssClasses = { | ||||
|     large: 'l-overlay-large', | ||||
|     small: 'l-overlay-small', | ||||
|     fit: 'l-overlay-fit', | ||||
|     fullscreen: 'l-overlay-fullscreen', | ||||
|     dialog: 'l-overlay-dialog' | ||||
|     fullscreen: 'l-overlay-fullscreen' | ||||
| }; | ||||
|  | ||||
| class Overlay extends EventEmitter { | ||||
| @@ -17,7 +16,6 @@ class Overlay extends EventEmitter { | ||||
|         dismissable = true, | ||||
|         element, | ||||
|         onDestroy, | ||||
|         onDismiss, | ||||
|         size | ||||
|     } = {}) { | ||||
|         super(); | ||||
| @@ -33,7 +31,7 @@ class Overlay extends EventEmitter { | ||||
|                 OverlayComponent: OverlayComponent | ||||
|             }, | ||||
|             provide: { | ||||
|                 dismiss: this.notifyAndDismiss.bind(this), | ||||
|                 dismiss: this.dismiss.bind(this), | ||||
|                 element, | ||||
|                 buttons, | ||||
|                 dismissable: this.dismissable | ||||
| @@ -44,10 +42,6 @@ class Overlay extends EventEmitter { | ||||
|         if (onDestroy) { | ||||
|             this.once('destroy', onDestroy); | ||||
|         } | ||||
|  | ||||
|         if (onDismiss) { | ||||
|             this.once('dismiss', onDismiss); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     dismiss() { | ||||
| @@ -56,12 +50,6 @@ class Overlay extends EventEmitter { | ||||
|         this.component.$destroy(); | ||||
|     } | ||||
|  | ||||
|     //Ensures that any callers are notified that the overlay is dismissed | ||||
|     notifyAndDismiss() { | ||||
|         this.emit('dismiss'); | ||||
|         this.dismiss(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @private | ||||
|      **/ | ||||
|   | ||||
| @@ -55,7 +55,7 @@ class OverlayAPI { | ||||
|     dismissLastOverlay() { | ||||
|         let lastOverlay = this.activeOverlays[this.activeOverlays.length - 1]; | ||||
|         if (lastOverlay && lastOverlay.dismissable) { | ||||
|             lastOverlay.notifyAndDismiss(); | ||||
|             lastOverlay.dismiss(); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|   | ||||
| @@ -1,4 +1,4 @@ | ||||
| @mixin overlaySizing($marginTB: auto, $marginLR: auto, $width: auto, $height: auto) { | ||||
| @mixin overlaySizing($marginTB: 5%, $marginLR: $marginTB, $width: auto, $height: auto) { | ||||
|     position: absolute; | ||||
|     top: $marginTB; right: $marginLR; bottom: $marginTB; left: $marginLR; | ||||
|     width: $width; | ||||
| @@ -98,7 +98,6 @@ body.desktop { | ||||
|     // Overlay types, styling for desktop. Appended to .l-overlay-wrapper element. | ||||
|     .l-overlay-large, | ||||
|     .l-overlay-small, | ||||
|     .l-overlay-dialog, | ||||
|     .l-overlay-fit { | ||||
|         .c-overlay__outer { | ||||
|             border-radius: $overlayCr; | ||||
| @@ -109,7 +108,7 @@ body.desktop { | ||||
|     .l-overlay-fullscreen { | ||||
|         // Used by About > Licenses display | ||||
|         .c-overlay__outer { | ||||
|             @include overlaySizing(nth($overlayOuterMarginFullscreen, 1), nth($overlayOuterMarginFullscreen, 2)); | ||||
|             @include overlaySizing($overlayOuterMarginFullscreen); | ||||
|         } | ||||
|     } | ||||
|  | ||||
| @@ -120,7 +119,7 @@ body.desktop { | ||||
|         $lrPad: $pad; | ||||
|         .c-overlay { | ||||
|             &__outer { | ||||
|                 @include overlaySizing(nth($overlayOuterMarginLarge, 1), nth($overlayOuterMarginLarge, 2)); | ||||
|                 @include overlaySizing($overlayOuterMarginLarge); | ||||
|                 padding: $tbPad $lrPad; | ||||
|             } | ||||
|  | ||||
| @@ -138,20 +137,14 @@ body.desktop { | ||||
|  | ||||
|     .l-overlay-small { | ||||
|         .c-overlay__outer { | ||||
|             @include overlaySizing(nth($overlayOuterMarginSmall, 1), nth($overlayOuterMarginSmall, 2)); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     .l-overlay-dialog { | ||||
|         .c-overlay__outer { | ||||
|             @include overlaySizing(nth($overlayOuterMarginDialog, 1), nth($overlayOuterMarginDialog, 2)); | ||||
|             @include overlaySizing($overlayOuterMarginDialog); | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     .t-dialog-sm .l-overlay-small, // Legacy dialog support | ||||
|     .l-overlay-fit { | ||||
|         .c-overlay__outer { | ||||
|             @include overlaySizing(auto, auto); | ||||
|             @include overlaySizing(auto); | ||||
|             top: 50%; | ||||
|             left: 50%; | ||||
|             transform: translate(-50%, -50%); | ||||
|   | ||||
| @@ -27,6 +27,7 @@ import TelemetryMetadataManager from './TelemetryMetadataManager'; | ||||
| import TelemetryValueFormatter from './TelemetryValueFormatter'; | ||||
| import DefaultMetadataProvider from './DefaultMetadataProvider'; | ||||
| import objectUtils from 'objectUtils'; | ||||
| import _ from 'lodash'; | ||||
|  | ||||
| export default class TelemetryAPI { | ||||
|  | ||||
| @@ -72,7 +73,7 @@ export default class TelemetryAPI { | ||||
|      * @returns {boolean} true if the object is a telemetry object. | ||||
|      */ | ||||
|     isTelemetryObject(domainObject) { | ||||
|         return Boolean(this.#findMetadataProvider(domainObject)); | ||||
|         return Boolean(this.findMetadataProvider(domainObject)); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
| @@ -86,7 +87,7 @@ export default class TelemetryAPI { | ||||
|      * @memberof module:openmct.TelemetryAPI~TelemetryProvider# | ||||
|      */ | ||||
|     canProvideTelemetry(domainObject) { | ||||
|         return Boolean(this.#findSubscriptionProvider(domainObject)) | ||||
|         return Boolean(this.findSubscriptionProvider(domainObject)) | ||||
|                 || Boolean(this.findRequestProvider(domainObject)); | ||||
|     } | ||||
|  | ||||
| @@ -119,7 +120,7 @@ export default class TelemetryAPI { | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     #findSubscriptionProvider() { | ||||
|     findSubscriptionProvider() { | ||||
|         const args = Array.prototype.slice.apply(arguments); | ||||
|         function supportsDomainObject(provider) { | ||||
|             return provider.supportsSubscribe.apply(provider, args); | ||||
| @@ -129,10 +130,9 @@ export default class TelemetryAPI { | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Returns a telemetry request provider that supports | ||||
|      * a given domain object and options. | ||||
|      * @private | ||||
|      */ | ||||
|     findRequestProvider() { | ||||
|     findRequestProvider(domainObject) { | ||||
|         const args = Array.prototype.slice.apply(arguments); | ||||
|         function supportsDomainObject(provider) { | ||||
|             return provider.supportsRequest.apply(provider, args); | ||||
| @@ -144,7 +144,7 @@ export default class TelemetryAPI { | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     #findMetadataProvider(domainObject) { | ||||
|     findMetadataProvider(domainObject) { | ||||
|         return this.metadataProviders.filter(function (p) { | ||||
|             return p.supportsMetadata(domainObject); | ||||
|         })[0]; | ||||
| @@ -153,7 +153,7 @@ export default class TelemetryAPI { | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     #findLimitEvaluator(domainObject) { | ||||
|     findLimitEvaluator(domainObject) { | ||||
|         return this.limitProviders.filter(function (p) { | ||||
|             return p.supportsLimits(domainObject); | ||||
|         })[0]; | ||||
| @@ -161,7 +161,6 @@ export default class TelemetryAPI { | ||||
|  | ||||
|     /** | ||||
|      * @private | ||||
|      * Though used in TelemetryCollection as well | ||||
|      */ | ||||
|     standardizeRequestOptions(options) { | ||||
|         if (!Object.prototype.hasOwnProperty.call(options, 'start')) { | ||||
| @@ -175,10 +174,6 @@ export default class TelemetryAPI { | ||||
|         if (!Object.prototype.hasOwnProperty.call(options, 'domain')) { | ||||
|             options.domain = this.openmct.time.timeSystem().key; | ||||
|         } | ||||
|  | ||||
|         if (!Object.prototype.hasOwnProperty.call(options, 'timeContext')) { | ||||
|             options.timeContext = this.openmct.time; | ||||
|         } | ||||
|     } | ||||
|  | ||||
|     /** | ||||
| @@ -246,7 +241,7 @@ export default class TelemetryAPI { | ||||
|     /** | ||||
|      * Request historical telemetry for a domain object. | ||||
|      * The `options` argument allows you to specify filters | ||||
|      * (start, end, etc.), sort order, time context, and strategies for retrieving | ||||
|      * (start, end, etc.), sort order, and strategies for retrieving | ||||
|      * telemetry (aggregation, latest available, etc.). | ||||
|      * | ||||
|      * @method request | ||||
| @@ -260,7 +255,7 @@ export default class TelemetryAPI { | ||||
|      */ | ||||
|     async request(domainObject) { | ||||
|         if (this.noRequestProviderForAllObjects) { | ||||
|             return []; | ||||
|             return Promise.resolve([]); | ||||
|         } | ||||
|  | ||||
|         if (arguments.length === 1) { | ||||
| @@ -278,24 +273,22 @@ export default class TelemetryAPI { | ||||
|         if (!provider) { | ||||
|             this.requestAbortControllers.delete(abortController); | ||||
|  | ||||
|             return this.#handleMissingRequestProvider(domainObject); | ||||
|             return this.handleMissingRequestProvider(domainObject); | ||||
|         } | ||||
|  | ||||
|         arguments[1] = await this.applyRequestInterceptors(domainObject, arguments[1]); | ||||
|         try { | ||||
|             const telemetry = await provider.request(...arguments); | ||||
|  | ||||
|             return telemetry; | ||||
|         } catch (error) { | ||||
|             if (error.name !== 'AbortError') { | ||||
|                 this.openmct.notifications.error('Error requesting telemetry data, see console for details'); | ||||
|                 console.error(error); | ||||
|             } | ||||
|         return provider.request.apply(provider, arguments) | ||||
|             .catch((rejected) => { | ||||
|                 if (rejected.name !== 'AbortError') { | ||||
|                     this.openmct.notifications.error('Error requesting telemetry data, see console for details'); | ||||
|                     console.error(rejected); | ||||
|                 } | ||||
|  | ||||
|             throw new Error(error); | ||||
|         } finally { | ||||
|             this.requestAbortControllers.delete(abortController); | ||||
|         } | ||||
|                 return Promise.reject(rejected); | ||||
|             }).finally(() => { | ||||
|                 this.requestAbortControllers.delete(abortController); | ||||
|             }); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
| @@ -313,7 +306,7 @@ export default class TelemetryAPI { | ||||
|      *          the subscription | ||||
|      */ | ||||
|     subscribe(domainObject, callback, options) { | ||||
|         const provider = this.#findSubscriptionProvider(domainObject); | ||||
|         const provider = this.findSubscriptionProvider(domainObject); | ||||
|  | ||||
|         if (!this.subscribeCache) { | ||||
|             this.subscribeCache = {}; | ||||
| @@ -360,7 +353,7 @@ export default class TelemetryAPI { | ||||
|      */ | ||||
|     getMetadata(domainObject) { | ||||
|         if (!this.metadataCache.has(domainObject)) { | ||||
|             const metadataProvider = this.#findMetadataProvider(domainObject); | ||||
|             const metadataProvider = this.findMetadataProvider(domainObject); | ||||
|             if (!metadataProvider) { | ||||
|                 return; | ||||
|             } | ||||
| @@ -376,6 +369,33 @@ export default class TelemetryAPI { | ||||
|         return this.metadataCache.get(domainObject); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Return an array of valueMetadatas that are common to all supplied | ||||
|      * telemetry objects and match the requested hints. | ||||
|      * | ||||
|      */ | ||||
|     commonValuesForHints(metadatas, hints) { | ||||
|         const options = metadatas.map(function (metadata) { | ||||
|             const values = metadata.valuesForHints(hints); | ||||
|  | ||||
|             return _.keyBy(values, 'key'); | ||||
|         }).reduce(function (a, b) { | ||||
|             const results = {}; | ||||
|             Object.keys(a).forEach(function (key) { | ||||
|                 if (Object.prototype.hasOwnProperty.call(b, key)) { | ||||
|                     results[key] = a[key]; | ||||
|                 } | ||||
|             }); | ||||
|  | ||||
|             return results; | ||||
|         }); | ||||
|         const sortKeys = hints.map(function (h) { | ||||
|             return 'hints.' + h; | ||||
|         }); | ||||
|  | ||||
|         return _.sortBy(options, sortKeys); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Get a value formatter for a given valueMetadata. | ||||
|      * | ||||
| @@ -430,7 +450,7 @@ export default class TelemetryAPI { | ||||
|      * | ||||
|      * @returns Promise | ||||
|      */ | ||||
|     #handleMissingRequestProvider(domainObject) { | ||||
|     handleMissingRequestProvider(domainObject) { | ||||
|         this.noRequestProviderForAllObjects = this.requestProviders.every(requestProvider => { | ||||
|             const supportsRequest = requestProvider.supportsRequest.apply(requestProvider, arguments); | ||||
|             const hasRequestProvider = Object.prototype.hasOwnProperty.call(requestProvider, 'request') && typeof requestProvider.request === 'function'; | ||||
| @@ -520,7 +540,7 @@ export default class TelemetryAPI { | ||||
|      * @memberof module:openmct.TelemetryAPI~TelemetryProvider# | ||||
|      */ | ||||
|     getLimitEvaluator(domainObject) { | ||||
|         const provider = this.#findLimitEvaluator(domainObject); | ||||
|         const provider = this.findLimitEvaluator(domainObject); | ||||
|         if (!provider) { | ||||
|             return { | ||||
|                 evaluate: function () {} | ||||
| @@ -558,7 +578,7 @@ export default class TelemetryAPI { | ||||
|      * @memberof module:openmct.TelemetryAPI~TelemetryProvider# | ||||
|      */ | ||||
|     getLimits(domainObject) { | ||||
|         const provider = this.#findLimitEvaluator(domainObject); | ||||
|         const provider = this.findLimitEvaluator(domainObject); | ||||
|         if (!provider || !provider.getLimits) { | ||||
|             return { | ||||
|                 limits: function () { | ||||
|   | ||||
| @@ -23,11 +23,11 @@ import { createOpenMct, resetApplicationState } from 'utils/testing'; | ||||
| import TelemetryAPI from './TelemetryAPI'; | ||||
| import TelemetryCollection from './TelemetryCollection'; | ||||
|  | ||||
| describe('Telemetry API', () => { | ||||
| describe('Telemetry API', function () { | ||||
|     let openmct; | ||||
|     let telemetryAPI; | ||||
|  | ||||
|     beforeEach(() => { | ||||
|     beforeEach(function () { | ||||
|         openmct = { | ||||
|             time: jasmine.createSpyObj('timeAPI', [ | ||||
|                 'timeSystem', | ||||
| @@ -47,11 +47,11 @@ describe('Telemetry API', () => { | ||||
|  | ||||
|     }); | ||||
|  | ||||
|     describe('telemetry providers', () => { | ||||
|     describe('telemetry providers', function () { | ||||
|         let telemetryProvider; | ||||
|         let domainObject; | ||||
|  | ||||
|         beforeEach(() => { | ||||
|         beforeEach(function () { | ||||
|             telemetryProvider = jasmine.createSpyObj('telemetryProvider', [ | ||||
|                 'supportsSubscribe', | ||||
|                 'subscribe', | ||||
| @@ -73,16 +73,19 @@ describe('Telemetry API', () => { | ||||
|             }; | ||||
|         }); | ||||
|  | ||||
|         it('provides consistent results without providers', async () => { | ||||
|         it('provides consistent results without providers', function (done) { | ||||
|             const unsubscribe = telemetryAPI.subscribe(domainObject); | ||||
|  | ||||
|             expect(unsubscribe).toEqual(jasmine.any(Function)); | ||||
|  | ||||
|             const data = await telemetryAPI.request(domainObject); | ||||
|             expect(data).toEqual([]); | ||||
|             telemetryAPI.request(domainObject) | ||||
|                 .then((data) => { | ||||
|                     expect(data).toEqual([]); | ||||
|                 }) | ||||
|                 .finally(done); | ||||
|         }); | ||||
|  | ||||
|         it('skips providers that do not match', async () => { | ||||
|         it('skips providers that do not match', function (done) { | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(false); | ||||
|             telemetryProvider.supportsRequest.and.returnValue(false); | ||||
|             telemetryProvider.request.and.returnValue(Promise.resolve([])); | ||||
| @@ -95,13 +98,14 @@ describe('Telemetry API', () => { | ||||
|             expect(telemetryProvider.subscribe).not.toHaveBeenCalled(); | ||||
|             expect(unsubscribe).toEqual(jasmine.any(Function)); | ||||
|  | ||||
|             await telemetryAPI.request(domainObject); | ||||
|             expect(telemetryProvider.supportsRequest) | ||||
|                 .toHaveBeenCalledWith(domainObject, jasmine.any(Object)); | ||||
|             expect(telemetryProvider.request).not.toHaveBeenCalled(); | ||||
|             telemetryAPI.request(domainObject).then((response) => { | ||||
|                 expect(telemetryProvider.supportsRequest) | ||||
|                     .toHaveBeenCalledWith(domainObject, jasmine.any(Object)); | ||||
|                 expect(telemetryProvider.request).not.toHaveBeenCalled(); | ||||
|             }).finally(done); | ||||
|         }); | ||||
|  | ||||
|         it('sends subscribe calls to matching providers', () => { | ||||
|         it('sends subscribe calls to matching providers', function () { | ||||
|             const unsubFunc = jasmine.createSpy('unsubscribe'); | ||||
|             telemetryProvider.subscribe.and.returnValue(unsubFunc); | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(true); | ||||
| @@ -129,7 +133,7 @@ describe('Telemetry API', () => { | ||||
|             expect(callback).not.toHaveBeenCalledWith('otherValue'); | ||||
|         }); | ||||
|  | ||||
|         it('subscribes once per object', () => { | ||||
|         it('subscribes once per object', function () { | ||||
|             const unsubFunc = jasmine.createSpy('unsubscribe'); | ||||
|             telemetryProvider.subscribe.and.returnValue(unsubFunc); | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(true); | ||||
| @@ -160,7 +164,7 @@ describe('Telemetry API', () => { | ||||
|             expect(callbacktwo).not.toHaveBeenCalledWith('anotherValue'); | ||||
|         }); | ||||
|  | ||||
|         it('only deletes subscription cache when there are no more subscribers', () => { | ||||
|         it('only deletes subscription cache when there are no more subscribers', function () { | ||||
|             const unsubFunc = jasmine.createSpy('unsubscribe'); | ||||
|             telemetryProvider.subscribe.and.returnValue(unsubFunc); | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(true); | ||||
| @@ -183,7 +187,7 @@ describe('Telemetry API', () => { | ||||
|             unsubscribeThree(); | ||||
|         }); | ||||
|  | ||||
|         it('does subscribe/unsubscribe', () => { | ||||
|         it('does subscribe/unsubscribe', function () { | ||||
|             const unsubFunc = jasmine.createSpy('unsubscribe'); | ||||
|             telemetryProvider.subscribe.and.returnValue(unsubFunc); | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(true); | ||||
| @@ -199,7 +203,7 @@ describe('Telemetry API', () => { | ||||
|             unsubscribe(); | ||||
|         }); | ||||
|  | ||||
|         it('subscribes for different object', () => { | ||||
|         it('subscribes for different object', function () { | ||||
|             const unsubFuncs = []; | ||||
|             const notifiers = []; | ||||
|             telemetryProvider.supportsSubscribe.and.returnValue(true); | ||||
| @@ -239,120 +243,120 @@ describe('Telemetry API', () => { | ||||
|             expect(unsubFuncs[1]).toHaveBeenCalled(); | ||||
|         }); | ||||
|  | ||||
|         it('sends requests to matching providers', async () => { | ||||
|         it('sends requests to matching providers', function (done) { | ||||
|             const telemPromise = Promise.resolve([]); | ||||
|             telemetryProvider.supportsRequest.and.returnValue(true); | ||||
|             telemetryProvider.request.and.returnValue(telemPromise); | ||||
|             telemetryAPI.addProvider(telemetryProvider); | ||||
|  | ||||
|             await telemetryAPI.request(domainObject); | ||||
|             expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                 domainObject, | ||||
|                 jasmine.any(Object) | ||||
|             ); | ||||
|             expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                 domainObject, | ||||
|                 jasmine.any(Object) | ||||
|             ); | ||||
|             telemetryAPI.request(domainObject).then(() => { | ||||
|                 expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                     domainObject, | ||||
|                     jasmine.any(Object) | ||||
|                 ); | ||||
|                 expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                     domainObject, | ||||
|                     jasmine.any(Object) | ||||
|                 ); | ||||
|             }).finally(done); | ||||
|         }); | ||||
|  | ||||
|         it('generates default request options', async () => { | ||||
|         it('generates default request options', function (done) { | ||||
|             telemetryProvider.supportsRequest.and.returnValue(true); | ||||
|             telemetryProvider.request.and.returnValue(Promise.resolve([])); | ||||
|             telemetryAPI.addProvider(telemetryProvider); | ||||
|  | ||||
|             await telemetryAPI.request(domainObject); | ||||
|             const { signal } = new AbortController(); | ||||
|             expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     signal, | ||||
|                     start: 0, | ||||
|                     end: 1, | ||||
|                     domain: 'system', | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|             telemetryAPI.request(domainObject).then(() => { | ||||
|                 const { signal } = new AbortController(); | ||||
|                 expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                     jasmine.any(Object), | ||||
|                     { | ||||
|                         signal, | ||||
|                         start: 0, | ||||
|                         end: 1, | ||||
|                         domain: 'system' | ||||
|                     } | ||||
|                 ); | ||||
|  | ||||
|             expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     signal, | ||||
|                     start: 0, | ||||
|                     end: 1, | ||||
|                     domain: 'system', | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|                 expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                     jasmine.any(Object), | ||||
|                     { | ||||
|                         signal, | ||||
|                         start: 0, | ||||
|                         end: 1, | ||||
|                         domain: 'system' | ||||
|                     } | ||||
|                 ); | ||||
|  | ||||
|             telemetryProvider.supportsRequest.calls.reset(); | ||||
|             telemetryProvider.request.calls.reset(); | ||||
|                 telemetryProvider.supportsRequest.calls.reset(); | ||||
|                 telemetryProvider.request.calls.reset(); | ||||
|  | ||||
|             await telemetryAPI.request(domainObject, {}); | ||||
|             expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     signal, | ||||
|                     start: 0, | ||||
|                     end: 1, | ||||
|                     domain: 'system', | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|                 telemetryAPI.request(domainObject, {}).then(() => { | ||||
|                     expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                         jasmine.any(Object), | ||||
|                         { | ||||
|                             signal, | ||||
|                             start: 0, | ||||
|                             end: 1, | ||||
|                             domain: 'system' | ||||
|                         } | ||||
|                     ); | ||||
|  | ||||
|                     expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                         jasmine.any(Object), | ||||
|                         { | ||||
|                             signal, | ||||
|                             start: 0, | ||||
|                             end: 1, | ||||
|                             domain: 'system' | ||||
|                         } | ||||
|                     ); | ||||
|                 }); | ||||
|             }).finally(done); | ||||
|  | ||||
|             expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     signal, | ||||
|                     start: 0, | ||||
|                     end: 1, | ||||
|                     domain: 'system', | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|         }); | ||||
|  | ||||
|         it('do not overwrite existing request options', async () => { | ||||
|         it('do not overwrite existing request options', function (done) { | ||||
|             telemetryProvider.supportsRequest.and.returnValue(true); | ||||
|             telemetryProvider.request.and.returnValue(Promise.resolve([])); | ||||
|             telemetryAPI.addProvider(telemetryProvider); | ||||
|  | ||||
|             await telemetryAPI.request(domainObject, { | ||||
|             telemetryAPI.request(domainObject, { | ||||
|                 start: 20, | ||||
|                 end: 30, | ||||
|                 domain: 'someDomain' | ||||
|             }); | ||||
|             const { signal } = new AbortController(); | ||||
|             expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     start: 20, | ||||
|                     end: 30, | ||||
|                     domain: 'someDomain', | ||||
|                     signal, | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|             }).then(() => { | ||||
|                 const { signal } = new AbortController(); | ||||
|                 expect(telemetryProvider.supportsRequest).toHaveBeenCalledWith( | ||||
|                     jasmine.any(Object), | ||||
|                     { | ||||
|                         start: 20, | ||||
|                         end: 30, | ||||
|                         domain: 'someDomain', | ||||
|                         signal | ||||
|                     } | ||||
|                 ); | ||||
|  | ||||
|             expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                 jasmine.any(Object), | ||||
|                 { | ||||
|                     start: 20, | ||||
|                     end: 30, | ||||
|                     domain: 'someDomain', | ||||
|                     signal, | ||||
|                     timeContext: jasmine.any(Object) | ||||
|                 } | ||||
|             ); | ||||
|                 expect(telemetryProvider.request).toHaveBeenCalledWith( | ||||
|                     jasmine.any(Object), | ||||
|                     { | ||||
|                         start: 20, | ||||
|                         end: 30, | ||||
|                         domain: 'someDomain', | ||||
|                         signal | ||||
|                     } | ||||
|                 ); | ||||
|  | ||||
|             }).finally(done); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     describe('metadata', () => { | ||||
|     describe('metadata', function () { | ||||
|         let mockMetadata = {}; | ||||
|         let mockObjectType = { | ||||
|             definition: {} | ||||
|         }; | ||||
|         beforeEach(() => { | ||||
|         beforeEach(function () { | ||||
|             telemetryAPI.addProvider({ | ||||
|                 key: 'mockMetadataProvider', | ||||
|                 supportsMetadata() { | ||||
| @@ -365,7 +369,7 @@ describe('Telemetry API', () => { | ||||
|             openmct.types.get.and.returnValue(mockObjectType); | ||||
|         }); | ||||
|  | ||||
|         it('respects explicit priority', () => { | ||||
|         it('respects explicit priority', function () { | ||||
|             mockMetadata.values = [ | ||||
|                 { | ||||
|                     key: "name", | ||||
| @@ -404,7 +408,7 @@ describe('Telemetry API', () => { | ||||
|                 expect(value.hints.priority).toBe(index + 1); | ||||
|             }); | ||||
|         }); | ||||
|         it('if no explicit priority, defaults to order defined', () => { | ||||
|         it('if no explicit priority, defaults to order defined', function () { | ||||
|             mockMetadata.values = [ | ||||
|                 { | ||||
|                     key: "name", | ||||
| @@ -431,7 +435,7 @@ describe('Telemetry API', () => { | ||||
|                 expect(value.key).toBe(mockMetadata.values[index].key); | ||||
|             }); | ||||
|         }); | ||||
|         it('respects domain priority', () => { | ||||
|         it('respects domain priority', function () { | ||||
|             mockMetadata.values = [ | ||||
|                 { | ||||
|                     key: "name", | ||||
| @@ -473,7 +477,7 @@ describe('Telemetry API', () => { | ||||
|             expect(values[0].key).toBe('timestamp-local'); | ||||
|             expect(values[1].key).toBe('timestamp-utc'); | ||||
|         }); | ||||
|         it('respects range priority', () => { | ||||
|         it('respects range priority', function () { | ||||
|             mockMetadata.values = [ | ||||
|                 { | ||||
|                     key: "name", | ||||
| @@ -515,7 +519,7 @@ describe('Telemetry API', () => { | ||||
|             expect(values[0].key).toBe('cos'); | ||||
|             expect(values[1].key).toBe('sin'); | ||||
|         }); | ||||
|         it('respects priority and domain ordering', () => { | ||||
|         it('respects priority and domain ordering', function () { | ||||
|             mockMetadata.values = [ | ||||
|                 { | ||||
|                     key: "id", | ||||
| @@ -584,7 +588,7 @@ describe('Telemetry API', () => { | ||||
|             definition: {} | ||||
|         }; | ||||
|  | ||||
|         beforeEach(() => { | ||||
|         beforeEach(function () { | ||||
|             openmct.telemetry = telemetryAPI; | ||||
|             telemetryAPI.addProvider({ | ||||
|                 key: 'mockMetadataProvider', | ||||
| @@ -640,14 +644,16 @@ describe('Telemetery', () => { | ||||
|         return resetApplicationState(openmct); | ||||
|     }); | ||||
|  | ||||
|     it('should not abort request without navigation', async () => { | ||||
|     it('should not abort request without navigation', function (done) { | ||||
|         telemetryAPI.addProvider(telemetryProvider); | ||||
|  | ||||
|         await telemetryAPI.request({}); | ||||
|         expect(watchedSignal.aborted).toBe(false); | ||||
|         telemetryAPI.request({}).finally(() => { | ||||
|             expect(watchedSignal.aborted).toBe(false); | ||||
|             done(); | ||||
|         }); | ||||
|     }); | ||||
|  | ||||
|     it('should abort request on navigation', (done) => { | ||||
|     it('should abort request on navigation', function (done) { | ||||
|         telemetryAPI.addProvider(telemetryProvider); | ||||
|  | ||||
|         telemetryAPI.request({}).finally(() => { | ||||
|   | ||||
| @@ -229,25 +229,6 @@ describe("The Time API", function () { | ||||
|             expect(api.clock()).toBeUndefined(); | ||||
|         }); | ||||
|  | ||||
|         it('Provides a default time context', () => { | ||||
|             const timeContext = api.getContextForView([]); | ||||
|             expect(timeContext).not.toBe(null); | ||||
|         }); | ||||
|  | ||||
|         it("Without a clock, is in fixed time mode", () => { | ||||
|             const timeContext = api.getContextForView([]); | ||||
|             expect(timeContext.isRealTime()).toBe(false); | ||||
|         }); | ||||
|  | ||||
|         it("Provided a clock, is in real-time mode", () => { | ||||
|             const timeContext = api.getContextForView([]); | ||||
|             timeContext.clock('mts', { | ||||
|                 start: 0, | ||||
|                 end: 1 | ||||
|             }); | ||||
|             expect(timeContext.isRealTime()).toBe(true); | ||||
|         }); | ||||
|  | ||||
|     }); | ||||
|  | ||||
|     it("on tick, observes offsets, and indicates tick in bounds callback", function () { | ||||
|   | ||||
| @@ -362,18 +362,6 @@ class TimeContext extends EventEmitter { | ||||
|         this.boundsVal = newBounds; | ||||
|         this.emit('bounds', this.boundsVal, true); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * Checks if this time context is in real-time mode or not. | ||||
|      * @returns {boolean} true if this context is in real-time mode, false if not | ||||
|     */ | ||||
|     isRealTime() { | ||||
|         if (this.clock()) { | ||||
|             return true; | ||||
|         } | ||||
|  | ||||
|         return false; | ||||
|     } | ||||
| } | ||||
|  | ||||
| export default TimeContext; | ||||
|   | ||||
| @@ -114,8 +114,6 @@ export default { | ||||
|         this.formats = this.openmct.telemetry.getFormatMap(this.metadata); | ||||
|         this.keyString = this.openmct.objects.makeKeyString(this.domainObject.identifier); | ||||
|  | ||||
|         this.timeContext = this.openmct.time.getContextForView(this.objectPath); | ||||
|  | ||||
|         this.limitEvaluator = this.openmct | ||||
|             .telemetry | ||||
|             .limitEvaluator(this.domainObject); | ||||
| @@ -136,8 +134,7 @@ export default { | ||||
|  | ||||
|         this.telemetryCollection = this.openmct.telemetry.requestCollection(this.domainObject, { | ||||
|             size: 1, | ||||
|             strategy: 'latest', | ||||
|             timeContext: this.timeContext | ||||
|             strategy: 'latest' | ||||
|         }); | ||||
|         this.telemetryCollection.on('add', this.setLatestValues); | ||||
|         this.telemetryCollection.on('clear', this.resetValues); | ||||
|   | ||||
| @@ -32,7 +32,7 @@ export default function plugin() { | ||||
|         openmct.types.addType('LadTable', { | ||||
|             name: "LAD Table", | ||||
|             creatable: true, | ||||
|             description: "Display the current value for one or more telemetry end points in a fixed table. Each row is a telemetry end point.", | ||||
|             description: "A Latest Available Data tabular view in which each row displays the values for one or more contained telemetry objects.", | ||||
|             cssClass: 'icon-tabular-lad', | ||||
|             initialize(domainObject) { | ||||
|                 domainObject.composition = []; | ||||
| @@ -42,7 +42,7 @@ export default function plugin() { | ||||
|         openmct.types.addType('LadTableSet', { | ||||
|             name: "LAD Table Set", | ||||
|             creatable: true, | ||||
|             description: "Group LAD Tables together into a single view with sub-headers.", | ||||
|             description: "A Latest Available Data tabular view in which each row displays the values for one or more contained telemetry objects.", | ||||
|             cssClass: 'icon-tabular-lad-set', | ||||
|             initialize(domainObject) { | ||||
|                 domainObject.composition = []; | ||||
|   | ||||
| @@ -32,7 +32,7 @@ export default function ClockPlugin(options) { | ||||
|         const CLOCK_INDICATOR_FORMAT = 'YYYY/MM/DD HH:mm:ss'; | ||||
|         openmct.types.addType('clock', { | ||||
|             name: 'Clock', | ||||
|             description: 'A digital clock that uses system time and supports a variety of display formats and timezones.', | ||||
|             description: 'A UTC-based clock that supports a variety of display formats. Clocks can be added to Display Layouts.', | ||||
|             creatable: true, | ||||
|             cssClass: 'icon-clock', | ||||
|             initialize: function (domainObject) { | ||||
|   | ||||
| @@ -30,12 +30,6 @@ | ||||
|     padding: $interiorMarginLg $interiorMarginLg * 2; | ||||
| } | ||||
|  | ||||
| .c-condition-widget__label { | ||||
|     padding: $interiorMargin; | ||||
|     text-align: center; | ||||
|     white-space: normal; | ||||
| } | ||||
|  | ||||
| a.c-condition-widget { | ||||
|     // Widget is conditionally made into a <a> when URL property has been defined | ||||
|     cursor: pointer !important; | ||||
|   | ||||
| @@ -93,7 +93,7 @@ define(['lodash'], function (_) { | ||||
|                     'table': { | ||||
|                         value: 'table', | ||||
|                         name: 'Table', | ||||
|                         class: 'icon-tabular-scrolling' | ||||
|                         class: 'icon-tabular-realtime' | ||||
|                     } | ||||
|                 }; | ||||
|                 const APPLICABLE_VIEWS = { | ||||
|   | ||||
| @@ -1,34 +0,0 @@ | ||||
| const displayLayoutDrawingObjectTypes = { | ||||
|     'box-view': { | ||||
|         name: "Box", | ||||
|         creatable: false, | ||||
|         description: 'A rectangle shape.', | ||||
|         cssClass: 'icon-box-round-corners' | ||||
|     }, | ||||
|     'ellipse-view': { | ||||
|         name: "Ellipse", | ||||
|         creatable: false, | ||||
|         description: 'A ellipse shape.', | ||||
|         cssClass: 'icon-circle' | ||||
|     }, | ||||
|     'line-view': { | ||||
|         name: "Line", | ||||
|         creatable: false, | ||||
|         description: 'A line.', | ||||
|         cssClass: 'icon-line-horz' | ||||
|     }, | ||||
|     'text-view': { | ||||
|         name: "Text", | ||||
|         creatable: false, | ||||
|         description: 'An editable text box.', | ||||
|         cssClass: 'icon-font' | ||||
|     }, | ||||
|     'image-view': { | ||||
|         name: "Image", | ||||
|         creatable: false, | ||||
|         description: 'An image.', | ||||
|         cssClass: 'icon-image' | ||||
|     } | ||||
| }; | ||||
|  | ||||
| export default displayLayoutDrawingObjectTypes; | ||||
| @@ -282,15 +282,12 @@ export default { | ||||
|             this.limitEvaluator = this.openmct.telemetry.limitEvaluator(this.domainObject); | ||||
|             this.formats = this.openmct.telemetry.getFormatMap(this.metadata); | ||||
|  | ||||
|             this.timeContext = this.openmct.time.getContextForView(this.objectPath); | ||||
|  | ||||
|             const valueMetadata = this.metadata ? this.metadata.value(this.item.value) : {}; | ||||
|             this.customStringformatter = this.openmct.telemetry.customStringFormatter(valueMetadata, this.item.format); | ||||
|  | ||||
|             this.telemetryCollection = this.openmct.telemetry.requestCollection(this.domainObject, { | ||||
|                 size: 1, | ||||
|                 strategy: 'latest', | ||||
|                 timeContext: this.timeContext | ||||
|                 strategy: 'latest' | ||||
|             }); | ||||
|             this.telemetryCollection.on('add', this.setLatestValues); | ||||
|             this.telemetryCollection.on('clear', this.refreshData); | ||||
|   | ||||
| @@ -74,15 +74,14 @@ | ||||
|                         transition-delay: $moveBarOutDelay; | ||||
|                         @include userSelectNone(); | ||||
|                         background: $editFrameMovebarColorBg; | ||||
|                         box-shadow: rgba(black, 0.3) 0 2px; | ||||
|                         box-shadow: rgba(black, 0.2) 0 1px; | ||||
|                         bottom: auto; | ||||
|                         display: block; | ||||
|                         height: 0; // Height is set on hover below | ||||
|                         opacity: 0.9; | ||||
|                         opacity: 0.8; | ||||
|                         max-height: 100%; | ||||
|                         overflow: hidden; | ||||
|                         text-align: center; | ||||
|                         z-index: 10; | ||||
|  | ||||
|                         &:before { | ||||
|                             // Grippy | ||||
| @@ -105,6 +104,7 @@ | ||||
|                     > .c-so-view.has-complex-content { | ||||
|                         transition: $transIn; | ||||
|                         transition-delay: 0s; | ||||
|                         padding-top: $editFrameMovebarH + $interiorMarginSm; | ||||
|  | ||||
|                         > .c-so-view__local-controls { | ||||
|                             transform: translateY($editFrameMovebarH); | ||||
|   | ||||
| @@ -4,7 +4,7 @@ | ||||
|  | ||||
|     > * { | ||||
|         // Label and value holders | ||||
|         flex: 1 1 50%; | ||||
|         flex: 1 1 auto; | ||||
|         display: flex; | ||||
|         flex-direction: row; | ||||
|         align-items: center; | ||||
|   | ||||
| @@ -25,7 +25,6 @@ import CopyToClipboardAction from './actions/CopyToClipboardAction'; | ||||
| import DisplayLayout from './components/DisplayLayout.vue'; | ||||
| import DisplayLayoutToolbar from './DisplayLayoutToolbar.js'; | ||||
| import DisplayLayoutType from './DisplayLayoutType.js'; | ||||
| import DisplayLayoutDrawingObjectTypes from './DrawingObjectTypes.js'; | ||||
|  | ||||
| import objectUtils from 'objectUtils'; | ||||
|  | ||||
| @@ -126,11 +125,6 @@ export default function DisplayLayoutPlugin(options) { | ||||
|                 return true; | ||||
|             } | ||||
|         }); | ||||
|  | ||||
|         for (const [type, definition] of Object.entries(DisplayLayoutDrawingObjectTypes)) { | ||||
|             openmct.types.addType(type, definition); | ||||
|         } | ||||
|  | ||||
|         DisplayLayoutPlugin._installed = true; | ||||
|     }; | ||||
| } | ||||
|   | ||||
| @@ -159,7 +159,7 @@ function ToolbarProvider(openmct) { | ||||
|  | ||||
|                         let prompt = openmct.overlays.dialog({ | ||||
|                             iconClass: 'alert', | ||||
|                             message: 'This action will permanently delete this container from this Flexible Layout. Do you want to continue?', | ||||
|                             message: 'This action will permanently delete this container from this Flexible Layout', | ||||
|                             buttons: [ | ||||
|                                 { | ||||
|                                     label: 'OK', | ||||
|   | ||||
| @@ -24,7 +24,6 @@ import PropertiesAction from './PropertiesAction'; | ||||
| import CreateWizard from './CreateWizard'; | ||||
|  | ||||
| import { v4 as uuid } from 'uuid'; | ||||
| import _ from 'lodash'; | ||||
|  | ||||
| export default class CreateAction extends PropertiesAction { | ||||
|     constructor(openmct, type, parentDomainObject) { | ||||
| @@ -51,15 +50,19 @@ export default class CreateAction extends PropertiesAction { | ||||
|                 return; | ||||
|             } | ||||
|  | ||||
|             const existingValue = this.domainObject[key]; | ||||
|             if (!(existingValue instanceof Array) && (typeof existingValue === 'object')) { | ||||
|                 value = { | ||||
|                     ...existingValue, | ||||
|                     ...value | ||||
|                 }; | ||||
|             } | ||||
|             const properties = key.split('.'); | ||||
|             let object = this.domainObject; | ||||
|             const propertiesLength = properties.length; | ||||
|             properties.forEach((property, index) => { | ||||
|                 const isComplexProperty = propertiesLength > 1 && index !== propertiesLength - 1; | ||||
|                 if (isComplexProperty && object[property] !== null) { | ||||
|                     object = object[property]; | ||||
|                 } else { | ||||
|                     object[property] = value; | ||||
|                 } | ||||
|             }); | ||||
|  | ||||
|             _.set(this.domainObject, key, value); | ||||
|             object = value; | ||||
|         }); | ||||
|  | ||||
|         const parentDomainObject = parentDomainObjectPath[0]; | ||||
| @@ -91,12 +94,6 @@ export default class CreateAction extends PropertiesAction { | ||||
|         dialog.dismiss(); | ||||
|     } | ||||
|  | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
|     _onCancel() { | ||||
|         //do Nothing | ||||
|     } | ||||
|     /** | ||||
|      * @private | ||||
|      */ | ||||
| @@ -110,7 +107,7 @@ export default class CreateAction extends PropertiesAction { | ||||
|         } | ||||
|  | ||||
|         const url = '#/browse/' + objectPath | ||||
|             .map(object => object && this.openmct.objects.makeKeyString(object.identifier)) | ||||
|             .map(object => object && this.openmct.objects.makeKeyString(object.identifier.key)) | ||||
|             .reverse() | ||||
|             .join('/'); | ||||
|  | ||||
| @@ -154,7 +151,6 @@ export default class CreateAction extends PropertiesAction { | ||||
|         formStructure.title = 'Create a New ' + definition.name; | ||||
|  | ||||
|         this.openmct.forms.showForm(formStructure) | ||||
|             .then(this._onSave.bind(this)) | ||||
|             .catch(this._onCancel.bind(this)); | ||||
|             .then(this._onSave.bind(this)); | ||||
|     } | ||||
| } | ||||
|   | ||||
| @@ -22,7 +22,6 @@ | ||||
|  | ||||
| import PropertiesAction from './PropertiesAction'; | ||||
| import CreateWizard from './CreateWizard'; | ||||
|  | ||||
| export default class EditPropertiesAction extends PropertiesAction { | ||||
|     constructor(openmct) { | ||||
|         super(openmct); | ||||
| @@ -53,31 +52,24 @@ export default class EditPropertiesAction extends PropertiesAction { | ||||
|      * @private | ||||
|      */ | ||||
|     _onSave(changes) { | ||||
|         if (!this.openmct.objects.isTransactionActive()) { | ||||
|             this.openmct.objects.startTransaction(); | ||||
|         } | ||||
|  | ||||
|         try { | ||||
|             Object.entries(changes).forEach(([key, value]) => { | ||||
|                 const existingValue = this.domainObject[key]; | ||||
|                 if (!(Array.isArray(existingValue)) && (typeof existingValue === 'object')) { | ||||
|                     value = { | ||||
|                         ...existingValue, | ||||
|                         ...value | ||||
|                     }; | ||||
|                 } | ||||
|  | ||||
|                 this.openmct.objects.mutate(this.domainObject, key, value); | ||||
|             }); | ||||
|             const transaction = this.openmct.objects.getActiveTransaction(); | ||||
|  | ||||
|             return transaction.commit() | ||||
|                 .catch(error => { | ||||
|                     throw error; | ||||
|                 }).finally(() => { | ||||
|                     this.openmct.objects.endTransaction(); | ||||
|                 const properties = key.split('.'); | ||||
|                 let object = this.domainObject; | ||||
|                 const propertiesLength = properties.length; | ||||
|                 properties.forEach((property, index) => { | ||||
|                     const isComplexProperty = propertiesLength > 1 && index !== propertiesLength - 1; | ||||
|                     if (isComplexProperty && object[property] !== null) { | ||||
|                         object = object[property]; | ||||
|                     } else { | ||||
|                         object[property] = value; | ||||
|                     } | ||||
|                 }); | ||||
|  | ||||
|                 object = value; | ||||
|                 this.openmct.objects.mutate(this.domainObject, key, value); | ||||
|                 this.openmct.notifications.info('Save successful'); | ||||
|             }); | ||||
|         } catch (error) { | ||||
|             this.openmct.notifications.error('Error saving objects'); | ||||
|             console.error(error); | ||||
|   | ||||
| @@ -24,7 +24,6 @@ import { | ||||
|     createOpenMct, | ||||
|     resetApplicationState | ||||
| } from 'utils/testing'; | ||||
| import Vue from 'vue'; | ||||
|  | ||||
| import { debounce } from 'lodash'; | ||||
|  | ||||
| @@ -102,15 +101,10 @@ describe('EditPropertiesAction plugin', () => { | ||||
|             composition: [] | ||||
|         }; | ||||
|  | ||||
|         editPropertiesAction.invoke([domainObject]) | ||||
|             .then(() => { | ||||
|                 done(); | ||||
|             }) | ||||
|             .catch(() => { | ||||
|                 done(); | ||||
|             }); | ||||
|         const deBouncedFormChange = debounce(handleFormPropertyChange, 500); | ||||
|         openmct.forms.on('onFormPropertyChange', deBouncedFormChange); | ||||
|  | ||||
|         Vue.nextTick(() => { | ||||
|         function handleFormPropertyChange(data) { | ||||
|             const form = document.querySelector('.js-form'); | ||||
|             const title = form.querySelector('input'); | ||||
|             expect(title.value).toEqual(domainObject.name); | ||||
| @@ -124,7 +118,17 @@ describe('EditPropertiesAction plugin', () => { | ||||
|  | ||||
|             const clickEvent = createMouseEvent('click'); | ||||
|             buttons[1].dispatchEvent(clickEvent); | ||||
|         }); | ||||
|  | ||||
|             openmct.forms.off('onFormPropertyChange', deBouncedFormChange); | ||||
|         } | ||||
|  | ||||
|         editPropertiesAction.invoke([domainObject]) | ||||
|             .then(() => { | ||||
|                 done(); | ||||
|             }) | ||||
|             .catch(() => { | ||||
|                 done(); | ||||
|             }); | ||||
|     }); | ||||
|  | ||||
|     it('edit properties action saves changes', (done) => { | ||||
| @@ -155,9 +159,11 @@ describe('EditPropertiesAction plugin', () => { | ||||
|         const deBouncedCallback = debounce(callback, 300); | ||||
|         unObserve = openmct.objects.observe(domainObject, '*', deBouncedCallback); | ||||
|  | ||||
|         editPropertiesAction.invoke([domainObject]); | ||||
|         let changed = false; | ||||
|         const deBouncedFormChange = debounce(handleFormPropertyChange, 500); | ||||
|         openmct.forms.on('onFormPropertyChange', deBouncedFormChange); | ||||
|  | ||||
|         Vue.nextTick(() => { | ||||
|         function handleFormPropertyChange(data) { | ||||
|             const form = document.querySelector('.js-form'); | ||||
|             const title = form.querySelector('input'); | ||||
|             const notes = form.querySelector('textArea'); | ||||
| @@ -166,18 +172,27 @@ describe('EditPropertiesAction plugin', () => { | ||||
|             expect(buttons[0].textContent.trim()).toEqual('OK'); | ||||
|             expect(buttons[1].textContent.trim()).toEqual('Cancel'); | ||||
|  | ||||
|             expect(title.value).toEqual(domainObject.name); | ||||
|             expect(notes.value).toEqual(domainObject.notes); | ||||
|             if (!changed) { | ||||
|                 expect(title.value).toEqual(domainObject.name); | ||||
|                 expect(notes.value).toEqual(domainObject.notes); | ||||
|  | ||||
|             // change input field value and dispatch event for it | ||||
|             title.focus(); | ||||
|             title.value = newName; | ||||
|             title.dispatchEvent(new Event('input')); | ||||
|             title.blur(); | ||||
|                 // change input field value and dispatch event for it | ||||
|                 title.focus(); | ||||
|                 title.value = newName; | ||||
|                 title.dispatchEvent(new Event('input')); | ||||
|                 title.blur(); | ||||
|  | ||||
|             const clickEvent = createMouseEvent('click'); | ||||
|             buttons[0].dispatchEvent(clickEvent); | ||||
|         }); | ||||
|                 changed = true; | ||||
|             } else { | ||||
|                 // click ok to save form changes | ||||
|                 const clickEvent = createMouseEvent('click'); | ||||
|                 buttons[0].dispatchEvent(clickEvent); | ||||
|  | ||||
|                 openmct.forms.off('onFormPropertyChange', deBouncedFormChange); | ||||
|             } | ||||
|         } | ||||
|  | ||||
|         editPropertiesAction.invoke([domainObject]); | ||||
|     }); | ||||
|  | ||||
|     it('edit properties action discards changes', (done) => { | ||||
| @@ -202,6 +217,7 @@ describe('EditPropertiesAction plugin', () => { | ||||
|             }) | ||||
|             .catch(() => { | ||||
|                 expect(domainObject.name).toEqual(name); | ||||
|  | ||||
|                 done(); | ||||
|             }); | ||||
|  | ||||
|   | ||||
| @@ -100,7 +100,6 @@ export default { | ||||
|     components: { | ||||
|         ToggleSwitch | ||||
|     }, | ||||
|     inject: ["openmct"], | ||||
|     props: { | ||||
|         model: { | ||||
|             type: Object, | ||||
| @@ -108,10 +107,11 @@ export default { | ||||
|         } | ||||
|     }, | ||||
|     data() { | ||||
|         this.changes = {}; | ||||
|  | ||||
|         return { | ||||
|             isUseTelemetryLimits: this.model.value.isUseTelemetryLimits, | ||||
|             isDisplayMinMax: this.model.value.isDisplayMinMax, | ||||
|             isDisplayCurVal: this.model.value.isDisplayCurVal, | ||||
|             isDisplayUnits: this.model.value.isDisplayUnits, | ||||
|             limitHigh: this.model.value.limitHigh, | ||||
|             limitLow: this.model.value.limitLow, | ||||
|             max: this.model.value.max, | ||||
| @@ -120,15 +120,24 @@ export default { | ||||
|     }, | ||||
|     methods: { | ||||
|         onChange(event) { | ||||
|             let data = { | ||||
|                 model: {} | ||||
|             const data = { | ||||
|                 model: this.model, | ||||
|                 value: { | ||||
|                     gaugeType: this.model.value.gaugeType, | ||||
|                     isDisplayMinMax: this.isDisplayMinMax, | ||||
|                     isDisplayCurVal: this.isDisplayCurVal, | ||||
|                     isDisplayUnits: this.isDisplayUnits, | ||||
|                     isUseTelemetryLimits: this.isUseTelemetryLimits, | ||||
|                     limitLow: this.limitLow, | ||||
|                     limitHigh: this.limitHigh, | ||||
|                     max: this.max, | ||||
|                     min: this.min, | ||||
|                     precision: this.model.value.precision | ||||
|                 } | ||||
|             }; | ||||
|  | ||||
|             if (event) { | ||||
|                 const target = event.target; | ||||
|                 const property = target.dataset.fieldName; | ||||
|                 data.model.property = Array.from(this.model.property).concat([property]); | ||||
|                 data.value = this[property]; | ||||
|                 const targetIndicator = target.parentElement.querySelector('.req-indicator'); | ||||
|                 if (targetIndicator.classList.contains('req')) { | ||||
|                     targetIndicator.classList.add('visited'); | ||||
| @@ -151,13 +160,13 @@ export default { | ||||
|         }, | ||||
|         toggleUseTelemetryLimits() { | ||||
|             this.isUseTelemetryLimits = !this.isUseTelemetryLimits; | ||||
|             const data = { | ||||
|                 model: { | ||||
|                     property: Array.from(this.model.property).concat(['isUseTelemetryLimits']) | ||||
|                 }, | ||||
|                 value: this.isUseTelemetryLimits | ||||
|             }; | ||||
|             this.$emit('onChange', data); | ||||
|  | ||||
|             this.onChange(); | ||||
|         }, | ||||
|         toggleMinMax() { | ||||
|             this.isDisplayMinMax = !this.isDisplayMinMax; | ||||
|  | ||||
|             this.onChange(); | ||||
|         } | ||||
|     } | ||||
| }; | ||||
|   | ||||
| @@ -52,8 +52,6 @@ $meterNeedleBorderRadius: 5px; | ||||
| .c-dial { | ||||
|   max-height: 100%; | ||||
|   max-width: 100%; | ||||
|   display: block; | ||||
|   margin: auto; // Centers SVG in container while allowing scaling | ||||
|  | ||||
|   &__bg { | ||||
|     fill: $colorGaugeBg; | ||||
|   | ||||