mirror of
https://github.com/nasa/openmct.git
synced 2025-06-27 11:32:13 +00:00
Compare commits
53 Commits
Author | SHA1 | Date | |
---|---|---|---|
8af947ba06 | |||
6bea39c59e | |||
a2301e67d1 | |||
44cbd3fc50 | |||
b21db2ecd5 | |||
858de567ae | |||
ad22661029 | |||
26aa49d9a8 | |||
cb55500cba | |||
340246ab26 | |||
9cb743fb48 | |||
9c52ec7233 | |||
c8723da098 | |||
933ce7aa3c | |||
8ef3869325 | |||
53f5fdabe5 | |||
d10561fc7f | |||
566469e691 | |||
6d4a324fca | |||
b8fabb7e73 | |||
1680c3cc1b | |||
61dd85c704 | |||
980777691a | |||
a50c1704e5 | |||
98080784a3 | |||
bf7b672957 | |||
5dadf6f6fc | |||
555db60bf7 | |||
1972ca9ea7 | |||
1e11bbc2ad | |||
c4a87ae5d7 | |||
4e325fb165 | |||
e59e4efdf0 | |||
f17fda53a0 | |||
f2dbe6d816 | |||
510d3bd333 | |||
a908eb1d65 | |||
c0bda64927 | |||
d0c5731287 | |||
5eaf222f88 | |||
0249ab4df5 | |||
4f8cba160d | |||
c269e089da | |||
4873f40614 | |||
10bb9173ec | |||
ea8c9c7cc8 | |||
4c9c084eec | |||
b64ee10812 | |||
ee1ecf43db | |||
4d8db8eb7c | |||
1b13965200 | |||
38db8f7fe5 | |||
4ba8f893a6 |
@ -7,30 +7,42 @@ orbs:
|
||||
node: circleci/node@4.5.1
|
||||
browser-tools: circleci/browser-tools@1.1.3
|
||||
jobs:
|
||||
npm-audit:
|
||||
executor: linux
|
||||
steps:
|
||||
- checkout
|
||||
- node/install:
|
||||
install-npm: true
|
||||
node-version: lts/fermium
|
||||
- run: npm install
|
||||
- run: npm audit --audit-level=low
|
||||
test:
|
||||
parameters:
|
||||
node-version:
|
||||
type: string
|
||||
browser:
|
||||
type: string
|
||||
always-pass:
|
||||
type: boolean
|
||||
executor: linux
|
||||
steps:
|
||||
- checkout
|
||||
- restore_cache:
|
||||
key: deps-{{ .Branch }}--<< parameters.node-version >>--{{ checksum "package.json" }}
|
||||
- node/install:
|
||||
install-npm: false
|
||||
node-version: << parameters.node-version >>
|
||||
- node/install-packages:
|
||||
override-ci-command: npm install
|
||||
- when: # Just to save time until caching saves the browser bin
|
||||
- run: npm install
|
||||
- when:
|
||||
condition:
|
||||
equal: [ "FirefoxESR", <<parameters.browser>> ]
|
||||
steps:
|
||||
- browser-tools/install-firefox:
|
||||
version: "78.11.0esr" #https://archive.mozilla.org/pub/firefox/releases/
|
||||
- when: # Just to save time until caching saves the browser bin
|
||||
version: "91.2.0esr" #https://archive.mozilla.org/pub/firefox/releases/
|
||||
- when:
|
||||
condition:
|
||||
equal: [ "FirefoxHeadless", <<parameters.browser>> ]
|
||||
steps:
|
||||
- browser-tools/install-firefox
|
||||
- when:
|
||||
condition:
|
||||
equal: [ "ChromeHeadless", <<parameters.browser>> ]
|
||||
steps:
|
||||
@ -42,7 +54,15 @@ jobs:
|
||||
- ~/.npm
|
||||
- ~/.cache
|
||||
- node_modules
|
||||
- run: npm run test:coverage -- --browsers=<<parameters.browser>> || <<parameters.always-pass>>
|
||||
- when:
|
||||
condition:
|
||||
equal: [ "", <<parameters.browser>> ] #Only run linting when browsers are not running to save time
|
||||
steps:
|
||||
- run: npm run lint
|
||||
- when:
|
||||
condition: << parameters.browser >> #Truthy evaluation to only run when browser is specified
|
||||
steps:
|
||||
- run: npm run test:coverage -- --browsers=<<parameters.browser>>
|
||||
- store_test_results:
|
||||
path: dist/reports/tests/
|
||||
- store_artifacts:
|
||||
@ -51,37 +71,37 @@ workflows:
|
||||
matrix-tests:
|
||||
jobs:
|
||||
- test:
|
||||
post-steps:
|
||||
- run:
|
||||
command:
|
||||
curl -Os https://uploader.codecov.io/latest/linux/codecov;chmod +x codecov;./codecov
|
||||
name: node10-chrome
|
||||
node-version: lts/dubnium
|
||||
browser: ChromeHeadless
|
||||
always-pass: false
|
||||
- test:
|
||||
name: node12-firefoxESR-build-only
|
||||
name: node12-build-lint
|
||||
node-version: lts/erbium
|
||||
browser: FirefoxESR
|
||||
always-pass: true
|
||||
browser: "" #Skip unit tests
|
||||
- test:
|
||||
name: node14-chrome-build-only
|
||||
name: node14-build-lint
|
||||
node-version: lts/fermium
|
||||
browser: ChromeHeadless
|
||||
always-pass: true
|
||||
browser: "" #Skip unit tests
|
||||
|
||||
nightly:
|
||||
jobs:
|
||||
- test:
|
||||
name: node10-chrome-nightly
|
||||
node-version: lts/dubnium
|
||||
browser: ChromeHeadless
|
||||
always-pass: false
|
||||
- test:
|
||||
name: node12-firefoxESR-nightly
|
||||
node-version: lts/erbium
|
||||
browser: FirefoxESR
|
||||
always-pass: false
|
||||
- test:
|
||||
name: node14-chrome-nightly
|
||||
name: node14-firefox-nightly
|
||||
node-version: lts/fermium
|
||||
browser: ChromeHeadless
|
||||
always-pass: false
|
||||
browser: FirefoxHeadless
|
||||
- npm-audit
|
||||
triggers:
|
||||
- schedule:
|
||||
cron: "0 0 * * *"
|
||||
|
2
.github/ISSUE_TEMPLATE/config.yml
vendored
2
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -2,4 +2,4 @@ blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: Discussions
|
||||
url: https://github.com/nasa/openmct/discussions
|
||||
about: Got a question?
|
||||
about: Have a question about the project?
|
||||
|
23
.github/ISSUE_TEMPLATE/feature_request.md
vendored
23
.github/ISSUE_TEMPLATE/feature_request.md
vendored
@ -1,23 +0,0 @@
|
||||
<!--- This is for filing enhancements or features. If you have a general -->
|
||||
<!--- question, please visit https://github.com/nasa/openmct/discussions -->
|
||||
|
||||
---
|
||||
name: Feature Request
|
||||
about: Suggest an idea for this project
|
||||
|
||||
---
|
||||
|
||||
<!--
|
||||
Thank you for suggesting an idea to make Open MCT better.
|
||||
|
||||
Please fill in as much of the template below as you're able.
|
||||
-->
|
||||
|
||||
**Is your feature request related to a problem? Please describe.**
|
||||
<!-- Please describe the problem you are trying to solve. -->
|
||||
|
||||
**Describe the solution you'd like**
|
||||
<!--- Please describe the desired behavior. -->
|
||||
|
||||
**Describe alternatives you've considered**
|
||||
<!--- Please describe alternative solutions or features you have considered. -->
|
11
.github/ISSUE_TEMPLATE/maintenance-type.md
vendored
Normal file
11
.github/ISSUE_TEMPLATE/maintenance-type.md
vendored
Normal file
@ -0,0 +1,11 @@
|
||||
---
|
||||
name: Maintenance
|
||||
about: Add, update or remove documentation, tests, or dependencies.
|
||||
title: ''
|
||||
labels: type:maintenance
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
#### Summary
|
||||
<!--- Generally describe the purpose of the change. -->
|
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
1
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -2,6 +2,7 @@
|
||||
|
||||
* [ ] Have you followed the guidelines in our [Contributing document](https://github.com/nasa/openmct/blob/master/CONTRIBUTING.md)?
|
||||
* [ ] Have you checked to ensure there aren't other open [Pull Requests](https://github.com/nasa/openmct/pulls) for the same update/change?
|
||||
* [ ] Is this change backwards compatible? For example, developers won't need to change how they are calling the API or how they've extended core plugins such as Tables or Plots.
|
||||
|
||||
### Author Checklist
|
||||
|
||||
|
23
.github/dependabot.yml
vendored
Normal file
23
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "npm"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
open-pull-requests-limit: 2
|
||||
labels:
|
||||
- "type:maintenance"
|
||||
- "dependencies"
|
||||
allow:
|
||||
- dependency-name: "eslint*"
|
||||
- dependency-name: "karma*"
|
||||
- dependency-name: "jasmine*"
|
||||
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: "daily"
|
||||
labels:
|
||||
- "type:maintenance"
|
||||
- "dependencies"
|
8
.github/workflows/codeql-analysis.yml
vendored
8
.github/workflows/codeql-analysis.yml
vendored
@ -4,6 +4,14 @@ name: "CodeQL"
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
paths-ignore:
|
||||
- '**/*Spec.js'
|
||||
- '**/*.md'
|
||||
- '**/*.txt'
|
||||
- '**/*.yml'
|
||||
- '**/*.yaml'
|
||||
schedule:
|
||||
- cron: '28 21 * * 3'
|
||||
|
||||
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -44,3 +44,6 @@ report.*.json
|
||||
.lighthouseci
|
||||
|
||||
package-lock.json
|
||||
|
||||
#codecov artifacts
|
||||
codecov
|
||||
|
@ -317,6 +317,7 @@ checklist).
|
||||
### Reviewer Checklist
|
||||
|
||||
* [ ] Changes appear to address issue?
|
||||
* [ ] Changes appear not to be breaking changes?
|
||||
* [ ] Appropriate unit tests included?
|
||||
* [ ] Code style and in-line documentation are appropriate?
|
||||
* [ ] Commit messages meet standards?
|
||||
|
@ -1,4 +1,4 @@
|
||||
# Open MCT [](http://www.apache.org/licenses/LICENSE-2.0) [](https://lgtm.com/projects/g/nasa/openmct/context:javascript)
|
||||
# Open MCT [](http://www.apache.org/licenses/LICENSE-2.0) [](https://lgtm.com/projects/g/nasa/openmct/context:javascript) [](https://codecov.io/gh/nasa/openmct)
|
||||
|
||||
Open MCT (Open Mission Control Technologies) is a next-generation mission control framework for visualization of data on desktop and mobile devices. It is developed at NASA's Ames Research Center, and is being used by NASA for data analysis of spacecraft missions, as well as planning and operation of experimental rover systems. As a generalizable and open source framework, Open MCT could be used as the basis for building applications for planning, operation, and analysis of any systems producing telemetry data.
|
||||
|
||||
@ -85,6 +85,8 @@ naming convention is otherwise the same.)
|
||||
When `npm test` is run, test results will be written as HTML to
|
||||
`dist/reports/tests/`. Code coverage information is written to `dist/reports/coverage`.
|
||||
|
||||
Code Coverage Reports are available from [codecov.io](https://app.codecov.io/gh/nasa/openmct/)
|
||||
|
||||
# Glossary
|
||||
|
||||
Certain terms are used throughout Open MCT with consistent meanings
|
||||
|
31
SECURITY.md
Normal file
31
SECURITY.md
Normal file
@ -0,0 +1,31 @@
|
||||
# Security Policy
|
||||
|
||||
The Open MCT team secures our code base using a combination of code review, dependency review, and periodic security reviews. Static analysis performed during automated verification additionally safeguards against common coding errors which may result in vulnerabilities.
|
||||
|
||||
### Reporting a Vulnerability
|
||||
|
||||
For general defects, please for a [Bug Report](https://github.com/nasa/openmct/issues/new/choose)
|
||||
|
||||
To report a vulnerability for Open MCT please send a detailed report to [arc-dl-openmct](mailto:arc-dl-openmct@mail.nasa.gov).
|
||||
|
||||
See our [top-level security policy](https://github.com/nasa/openmct/security/policy) for additional information.
|
||||
|
||||
### CodeQL and LGTM
|
||||
|
||||
The [CodeQL GitHub Actions workflow](https://github.com/nasa/openmct/blob/master/.github/workflows/codeql-analysis.yml) is available to the public. To review the results, fork the repository and run the CodeQL workflow.
|
||||
|
||||
CodeQL is run for every pull-request in GitHub Actions.
|
||||
|
||||
The project is also monitored by [LGTM](https://lgtm.com/projects/g/nasa/openmct/) and is available to public.
|
||||
|
||||
### ESLint
|
||||
|
||||
Static analysis is run for every push on the master branch and every pull request on all branches in Github Actions.
|
||||
|
||||
For more information about ESLint, visit https://eslint.org/.
|
||||
|
||||
### General Support
|
||||
|
||||
For additional support, please open a [Github Discussion](https://github.com/nasa/openmct/discussions).
|
||||
|
||||
If you wish to report a cybersecurity incident or concern, please contact the NASA Security Operations Center either by phone at 1-877-627-2732 or via email address soc@nasa.gov.
|
27
codecov.yml
Normal file
27
codecov.yml
Normal file
@ -0,0 +1,27 @@
|
||||
codecov:
|
||||
require_ci_to_pass: false #This setting will update the bot regardless of whether or not tests pass
|
||||
|
||||
coverage:
|
||||
status:
|
||||
project:
|
||||
default:
|
||||
informational: true
|
||||
patch:
|
||||
default:
|
||||
informational: true
|
||||
precision: 2
|
||||
round: down
|
||||
range: "66...100"
|
||||
|
||||
parsers:
|
||||
gcov:
|
||||
branch_detection:
|
||||
conditional: true
|
||||
loop: true
|
||||
method: false
|
||||
macro: false
|
||||
|
||||
comment:
|
||||
layout: "reach,diff,flags,files,footer"
|
||||
behavior: default
|
||||
require_changes: false
|
@ -118,100 +118,6 @@ define([
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
'example.spectral-generator': {
|
||||
values: [
|
||||
{
|
||||
key: "name",
|
||||
name: "Name",
|
||||
format: "string"
|
||||
},
|
||||
{
|
||||
key: "utc",
|
||||
name: "Time",
|
||||
format: "utc",
|
||||
hints: {
|
||||
domain: 1
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "wavelength",
|
||||
name: "Wavelength",
|
||||
unit: "Hz",
|
||||
formatString: '%0.2f',
|
||||
hints: {
|
||||
domain: 2,
|
||||
spectralAttribute: true
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "cos",
|
||||
name: "Cosine",
|
||||
unit: "deg",
|
||||
formatString: '%0.2f',
|
||||
hints: {
|
||||
range: 2,
|
||||
spectralAttribute: true
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
'example.spectral-aggregate-generator': {
|
||||
values: [
|
||||
{
|
||||
key: "name",
|
||||
name: "Name",
|
||||
format: "string"
|
||||
},
|
||||
{
|
||||
key: "utc",
|
||||
name: "Time",
|
||||
format: "utc",
|
||||
hints: {
|
||||
domain: 1
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "ch1",
|
||||
name: "Channel 1",
|
||||
format: "string",
|
||||
hints: {
|
||||
range: 1
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "ch2",
|
||||
name: "Channel 2",
|
||||
format: "string",
|
||||
hints: {
|
||||
range: 2
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "ch3",
|
||||
name: "Channel 3",
|
||||
format: "string",
|
||||
hints: {
|
||||
range: 3
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "ch4",
|
||||
name: "Channel 4",
|
||||
format: "string",
|
||||
hints: {
|
||||
range: 4
|
||||
}
|
||||
},
|
||||
{
|
||||
key: "ch5",
|
||||
name: "Channel 5",
|
||||
format: "string",
|
||||
hints: {
|
||||
range: 5
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
};
|
||||
|
||||
|
@ -1,86 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
|
||||
], function (
|
||||
|
||||
) {
|
||||
|
||||
function SpectralAggregateGeneratorProvider() {
|
||||
|
||||
}
|
||||
|
||||
function pointForTimestamp(timestamp, count, name) {
|
||||
return {
|
||||
name: name,
|
||||
utc: String(Math.floor(timestamp / count) * count),
|
||||
ch1: String(Math.floor(timestamp / count) % 1),
|
||||
ch2: String(Math.floor(timestamp / count) % 2),
|
||||
ch3: String(Math.floor(timestamp / count) % 3),
|
||||
ch4: String(Math.floor(timestamp / count) % 4),
|
||||
ch5: String(Math.floor(timestamp / count) % 5)
|
||||
};
|
||||
}
|
||||
|
||||
SpectralAggregateGeneratorProvider.prototype.supportsSubscribe = function (domainObject) {
|
||||
return domainObject.type === 'example.spectral-aggregate-generator';
|
||||
};
|
||||
|
||||
SpectralAggregateGeneratorProvider.prototype.subscribe = function (domainObject, callback) {
|
||||
var count = 5000;
|
||||
|
||||
var interval = setInterval(function () {
|
||||
var now = Date.now();
|
||||
var datum = pointForTimestamp(now, count, domainObject.name);
|
||||
callback(datum);
|
||||
}, count);
|
||||
|
||||
return function () {
|
||||
clearInterval(interval);
|
||||
};
|
||||
};
|
||||
|
||||
SpectralAggregateGeneratorProvider.prototype.supportsRequest = function (domainObject, options) {
|
||||
return domainObject.type === 'example.spectral-aggregate-generator';
|
||||
};
|
||||
|
||||
SpectralAggregateGeneratorProvider.prototype.request = function (domainObject, options) {
|
||||
var start = options.start;
|
||||
var end = Math.min(Date.now(), options.end); // no future values
|
||||
var count = 5000;
|
||||
if (options.strategy === 'latest' || options.size === 1) {
|
||||
start = end;
|
||||
}
|
||||
|
||||
var data = [];
|
||||
while (start <= end && data.length < 5000) {
|
||||
data.push(pointForTimestamp(start, count, domainObject.name));
|
||||
start += count;
|
||||
}
|
||||
|
||||
return Promise.resolve(data);
|
||||
};
|
||||
|
||||
return SpectralAggregateGeneratorProvider;
|
||||
|
||||
});
|
@ -1,102 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
'./WorkerInterface'
|
||||
], function (
|
||||
WorkerInterface
|
||||
) {
|
||||
|
||||
var REQUEST_DEFAULTS = {
|
||||
amplitude: 1,
|
||||
wavelength: 1,
|
||||
period: 10,
|
||||
offset: 0,
|
||||
dataRateInHz: 1,
|
||||
randomness: 0,
|
||||
phase: 0
|
||||
};
|
||||
|
||||
function SpectralGeneratorProvider() {
|
||||
this.workerInterface = new WorkerInterface();
|
||||
}
|
||||
|
||||
SpectralGeneratorProvider.prototype.canProvideTelemetry = function (domainObject) {
|
||||
return domainObject.type === 'example.spectral-generator';
|
||||
};
|
||||
|
||||
SpectralGeneratorProvider.prototype.supportsRequest =
|
||||
SpectralGeneratorProvider.prototype.supportsSubscribe =
|
||||
SpectralGeneratorProvider.prototype.canProvideTelemetry;
|
||||
|
||||
SpectralGeneratorProvider.prototype.makeWorkerRequest = function (domainObject, request = {}) {
|
||||
var props = [
|
||||
'amplitude',
|
||||
'wavelength',
|
||||
'period',
|
||||
'offset',
|
||||
'dataRateInHz',
|
||||
'phase',
|
||||
'randomness'
|
||||
];
|
||||
|
||||
var workerRequest = {};
|
||||
|
||||
props.forEach(function (prop) {
|
||||
if (domainObject.telemetry && Object.prototype.hasOwnProperty.call(domainObject.telemetry, prop)) {
|
||||
workerRequest[prop] = domainObject.telemetry[prop];
|
||||
}
|
||||
|
||||
if (request && Object.prototype.hasOwnProperty.call(request, prop)) {
|
||||
workerRequest[prop] = request[prop];
|
||||
}
|
||||
|
||||
if (!Object.prototype.hasOwnProperty.call(workerRequest, prop)) {
|
||||
workerRequest[prop] = REQUEST_DEFAULTS[prop];
|
||||
}
|
||||
|
||||
workerRequest[prop] = Number(workerRequest[prop]);
|
||||
});
|
||||
|
||||
workerRequest.name = domainObject.name;
|
||||
|
||||
return workerRequest;
|
||||
};
|
||||
|
||||
SpectralGeneratorProvider.prototype.request = function (domainObject, request) {
|
||||
var workerRequest = this.makeWorkerRequest(domainObject, request);
|
||||
workerRequest.start = request.start;
|
||||
workerRequest.end = request.end;
|
||||
workerRequest.spectra = true;
|
||||
|
||||
return this.workerInterface.request(workerRequest);
|
||||
};
|
||||
|
||||
SpectralGeneratorProvider.prototype.subscribe = function (domainObject, callback) {
|
||||
var workerRequest = this.makeWorkerRequest(domainObject, {});
|
||||
workerRequest.spectra = true;
|
||||
|
||||
return this.workerInterface.subscribe(workerRequest, callback);
|
||||
};
|
||||
|
||||
return SpectralGeneratorProvider;
|
||||
});
|
@ -24,15 +24,11 @@ define([
|
||||
"./GeneratorProvider",
|
||||
"./SinewaveLimitProvider",
|
||||
"./StateGeneratorProvider",
|
||||
"./SpectralGeneratorProvider",
|
||||
"./SpectralAggregateGeneratorProvider",
|
||||
"./GeneratorMetadataProvider"
|
||||
], function (
|
||||
GeneratorProvider,
|
||||
SinewaveLimitProvider,
|
||||
StateGeneratorProvider,
|
||||
SpectralGeneratorProvider,
|
||||
SpectralAggregateGeneratorProvider,
|
||||
GeneratorMetadataProvider
|
||||
) {
|
||||
|
||||
@ -65,37 +61,6 @@ define([
|
||||
|
||||
openmct.telemetry.addProvider(new StateGeneratorProvider());
|
||||
|
||||
openmct.types.addType("example.spectral-generator", {
|
||||
name: "Spectral Generator",
|
||||
description: "For development use. Generates example streaming telemetry data using a simple sine wave algorithm.",
|
||||
cssClass: "icon-generator-telemetry",
|
||||
creatable: true,
|
||||
initialize: function (object) {
|
||||
object.telemetry = {
|
||||
period: 10,
|
||||
amplitude: 1,
|
||||
wavelength: 1,
|
||||
frequency: 1,
|
||||
offset: 0,
|
||||
dataRateInHz: 1,
|
||||
phase: 0,
|
||||
randomness: 0
|
||||
};
|
||||
}
|
||||
});
|
||||
openmct.telemetry.addProvider(new SpectralGeneratorProvider());
|
||||
|
||||
openmct.types.addType("example.spectral-aggregate-generator", {
|
||||
name: "Spectral Aggregate Generator",
|
||||
description: "For development use. Generates example streaming telemetry data using a simple state algorithm.",
|
||||
cssClass: "icon-generator-telemetry",
|
||||
creatable: true,
|
||||
initialize: function (object) {
|
||||
object.telemetry = {};
|
||||
}
|
||||
});
|
||||
openmct.telemetry.addProvider(new SpectralAggregateGeneratorProvider());
|
||||
|
||||
openmct.types.addType("generator", {
|
||||
name: "Sine Wave Generator",
|
||||
description: "For development use. Generates example streaming telemetry data using a simple sine wave algorithm.",
|
||||
|
@ -20,14 +20,7 @@
|
||||
* at runtime from the About dialog for additional information.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
|
||||
], function (
|
||||
|
||||
) {
|
||||
function ImageryPlugin() {
|
||||
|
||||
const IMAGE_SAMPLES = [
|
||||
const DEFAULT_IMAGE_SAMPLES = [
|
||||
"https://www.hq.nasa.gov/alsj/a16/AS16-117-18731.jpg",
|
||||
"https://www.hq.nasa.gov/alsj/a16/AS16-117-18732.jpg",
|
||||
"https://www.hq.nasa.gov/alsj/a16/AS16-117-18733.jpg",
|
||||
@ -47,73 +40,14 @@ define([
|
||||
"https://www.hq.nasa.gov/alsj/a16/AS16-117-18747.jpg",
|
||||
"https://www.hq.nasa.gov/alsj/a16/AS16-117-18748.jpg"
|
||||
];
|
||||
const IMAGE_DELAY = 20000;
|
||||
const DEFAULT_IMAGE_LOAD_DELAY_IN_MILISECONDS = 20000;
|
||||
const MIN_IMAGE_LOAD_DELAY_IN_MILISECONDS = 5000;
|
||||
|
||||
function getCompassValues(min, max) {
|
||||
return min + Math.random() * (max - min);
|
||||
}
|
||||
|
||||
function pointForTimestamp(timestamp, name) {
|
||||
const url = IMAGE_SAMPLES[Math.floor(timestamp / IMAGE_DELAY) % IMAGE_SAMPLES.length];
|
||||
const urlItems = url.split('/');
|
||||
const imageDownloadName = `example.imagery.${urlItems[urlItems.length - 1]}`;
|
||||
|
||||
return {
|
||||
name,
|
||||
utc: Math.floor(timestamp / IMAGE_DELAY) * IMAGE_DELAY,
|
||||
local: Math.floor(timestamp / IMAGE_DELAY) * IMAGE_DELAY,
|
||||
url,
|
||||
sunOrientation: getCompassValues(0, 360),
|
||||
cameraPan: getCompassValues(0, 360),
|
||||
heading: getCompassValues(0, 360),
|
||||
imageDownloadName
|
||||
};
|
||||
}
|
||||
|
||||
var realtimeProvider = {
|
||||
supportsSubscribe: function (domainObject) {
|
||||
return domainObject.type === 'example.imagery';
|
||||
},
|
||||
subscribe: function (domainObject, callback) {
|
||||
var interval = setInterval(function () {
|
||||
callback(pointForTimestamp(Date.now(), domainObject.name));
|
||||
}, IMAGE_DELAY);
|
||||
|
||||
return function () {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
var historicalProvider = {
|
||||
supportsRequest: function (domainObject, options) {
|
||||
return domainObject.type === 'example.imagery'
|
||||
&& options.strategy !== 'latest';
|
||||
},
|
||||
request: function (domainObject, options) {
|
||||
var start = options.start;
|
||||
var end = Math.min(options.end, Date.now());
|
||||
var data = [];
|
||||
while (start <= end && data.length < IMAGE_DELAY) {
|
||||
data.push(pointForTimestamp(start, domainObject.name));
|
||||
start += IMAGE_DELAY;
|
||||
}
|
||||
|
||||
return Promise.resolve(data);
|
||||
}
|
||||
};
|
||||
|
||||
var ladProvider = {
|
||||
supportsRequest: function (domainObject, options) {
|
||||
return domainObject.type === 'example.imagery'
|
||||
&& options.strategy === 'latest';
|
||||
},
|
||||
request: function (domainObject, options) {
|
||||
return Promise.resolve([pointForTimestamp(Date.now(), domainObject.name)]);
|
||||
}
|
||||
};
|
||||
let openmctInstance;
|
||||
|
||||
export default function () {
|
||||
return function install(openmct) {
|
||||
openmctInstance = openmct;
|
||||
openmct.types.addType('example.imagery', {
|
||||
key: 'example.imagery',
|
||||
name: 'Example Imagery',
|
||||
@ -121,7 +55,13 @@ define([
|
||||
description: 'For development use. Creates example imagery '
|
||||
+ 'data that mimics a live imagery stream.',
|
||||
creatable: true,
|
||||
initialize: function (object) {
|
||||
initialize: (object) => {
|
||||
object.configuration = {
|
||||
imageLocation: '',
|
||||
imageLoadDelayInMilliSeconds: DEFAULT_IMAGE_LOAD_DELAY_IN_MILISECONDS,
|
||||
imageSamples: []
|
||||
};
|
||||
|
||||
object.telemetry = {
|
||||
values: [
|
||||
{
|
||||
@ -162,14 +102,137 @@ define([
|
||||
}
|
||||
]
|
||||
};
|
||||
},
|
||||
form: [
|
||||
{
|
||||
key: 'imageLocation',
|
||||
name: 'Images url list (comma separated)',
|
||||
control: 'textarea',
|
||||
cssClass: 'l-inline',
|
||||
property: [
|
||||
"configuration",
|
||||
"imageLocation"
|
||||
]
|
||||
},
|
||||
{
|
||||
key: 'imageLoadDelayInMilliSeconds',
|
||||
name: 'Image load delay (milliseconds)',
|
||||
control: 'numberfield',
|
||||
required: true,
|
||||
cssClass: 'l-inline',
|
||||
property: [
|
||||
"configuration",
|
||||
"imageLoadDelayInMilliSeconds"
|
||||
]
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
openmct.telemetry.addProvider(realtimeProvider);
|
||||
openmct.telemetry.addProvider(historicalProvider);
|
||||
openmct.telemetry.addProvider(ladProvider);
|
||||
openmct.telemetry.addProvider(getRealtimeProvider());
|
||||
openmct.telemetry.addProvider(getHistoricalProvider());
|
||||
openmct.telemetry.addProvider(getLadProvider());
|
||||
};
|
||||
}
|
||||
|
||||
return ImageryPlugin;
|
||||
});
|
||||
function getCompassValues(min, max) {
|
||||
return min + Math.random() * (max - min);
|
||||
}
|
||||
|
||||
function getImageSamples(configuration) {
|
||||
let imageSamples = DEFAULT_IMAGE_SAMPLES;
|
||||
|
||||
if (configuration.imageLocation && configuration.imageLocation.length) {
|
||||
imageSamples = getImageUrlListFromConfig(configuration);
|
||||
}
|
||||
|
||||
return imageSamples;
|
||||
}
|
||||
|
||||
function getImageUrlListFromConfig(configuration) {
|
||||
return configuration.imageLocation.split(',');
|
||||
}
|
||||
|
||||
function getImageLoadDelay(domainObject) {
|
||||
const imageLoadDelay = domainObject.configuration.imageLoadDelayInMilliSeconds;
|
||||
if (!imageLoadDelay) {
|
||||
openmctInstance.objects.mutate(domainObject, 'configuration.imageLoadDelayInMilliSeconds', DEFAULT_IMAGE_LOAD_DELAY_IN_MILISECONDS);
|
||||
|
||||
return DEFAULT_IMAGE_LOAD_DELAY_IN_MILISECONDS;
|
||||
}
|
||||
|
||||
if (imageLoadDelay < MIN_IMAGE_LOAD_DELAY_IN_MILISECONDS) {
|
||||
openmctInstance.objects.mutate(domainObject, 'configuration.imageLoadDelayInMilliSeconds', MIN_IMAGE_LOAD_DELAY_IN_MILISECONDS);
|
||||
|
||||
return MIN_IMAGE_LOAD_DELAY_IN_MILISECONDS;
|
||||
}
|
||||
|
||||
return imageLoadDelay;
|
||||
}
|
||||
|
||||
function getRealtimeProvider() {
|
||||
return {
|
||||
supportsSubscribe: domainObject => domainObject.type === 'example.imagery',
|
||||
subscribe: (domainObject, callback) => {
|
||||
const delay = getImageLoadDelay(domainObject);
|
||||
const interval = setInterval(() => {
|
||||
callback(pointForTimestamp(Date.now(), domainObject.name, getImageSamples(domainObject.configuration), delay));
|
||||
}, delay);
|
||||
|
||||
return () => {
|
||||
clearInterval(interval);
|
||||
};
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getHistoricalProvider() {
|
||||
return {
|
||||
supportsRequest: (domainObject, options) => {
|
||||
return domainObject.type === 'example.imagery'
|
||||
&& options.strategy !== 'latest';
|
||||
},
|
||||
request: (domainObject, options) => {
|
||||
const delay = getImageLoadDelay(domainObject);
|
||||
let start = options.start;
|
||||
const end = Math.min(options.end, Date.now());
|
||||
const data = [];
|
||||
while (start <= end && data.length < delay) {
|
||||
data.push(pointForTimestamp(start, domainObject.name, getImageSamples(domainObject.configuration), delay));
|
||||
start += delay;
|
||||
}
|
||||
|
||||
return Promise.resolve(data);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function getLadProvider() {
|
||||
return {
|
||||
supportsRequest: (domainObject, options) => {
|
||||
return domainObject.type === 'example.imagery'
|
||||
&& options.strategy === 'latest';
|
||||
},
|
||||
request: (domainObject, options) => {
|
||||
const delay = getImageLoadDelay(domainObject);
|
||||
|
||||
return Promise.resolve([pointForTimestamp(Date.now(), domainObject.name, delay)]);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function pointForTimestamp(timestamp, name, imageSamples, delay) {
|
||||
const url = imageSamples[Math.floor(timestamp / delay) % imageSamples.length];
|
||||
const urlItems = url.split('/');
|
||||
const imageDownloadName = `example.imagery.${urlItems[urlItems.length - 1]}`;
|
||||
|
||||
return {
|
||||
name,
|
||||
utc: Math.floor(timestamp / delay) * delay,
|
||||
local: Math.floor(timestamp / delay) * delay,
|
||||
url,
|
||||
sunOrientation: getCompassValues(0, 360),
|
||||
cameraPan: getCompassValues(0, 360),
|
||||
heading: getCompassValues(0, 360),
|
||||
imageDownloadName
|
||||
};
|
||||
}
|
||||
|
@ -82,6 +82,7 @@
|
||||
);
|
||||
|
||||
openmct.install(openmct.plugins.LocalStorage());
|
||||
|
||||
openmct.install(openmct.plugins.Espresso());
|
||||
openmct.install(openmct.plugins.MyItems());
|
||||
openmct.install(openmct.plugins.Generator());
|
||||
@ -196,6 +197,7 @@
|
||||
{indicator: true}
|
||||
));
|
||||
openmct.install(openmct.plugins.Clock({ enableClockIndicator: true }));
|
||||
openmct.install(openmct.plugins.Timer());
|
||||
openmct.start();
|
||||
</script>
|
||||
</html>
|
||||
|
@ -25,7 +25,7 @@
|
||||
const devMode = process.env.NODE_ENV !== 'production';
|
||||
const browsers = [process.env.NODE_ENV === 'debug' ? 'ChromeDebugging' : 'ChromeHeadless'];
|
||||
const coverageEnabled = process.env.COVERAGE === 'true';
|
||||
const reporters = ['progress', 'html', 'junit'];
|
||||
const reporters = ['spec', 'junit'];
|
||||
|
||||
if (coverageEnabled) {
|
||||
reporters.push('coverage-istanbul');
|
||||
@ -60,7 +60,7 @@ module.exports = (config) => {
|
||||
client: {
|
||||
jasmine: {
|
||||
random: false,
|
||||
timeoutInterval: 30000
|
||||
timeoutInterval: 5000
|
||||
}
|
||||
},
|
||||
customLaunchers: {
|
||||
@ -78,33 +78,37 @@ module.exports = (config) => {
|
||||
logLevel: config.LOG_INFO,
|
||||
autoWatch: true,
|
||||
// HTML test reporting.
|
||||
htmlReporter: {
|
||||
outputDir: "dist/reports/tests",
|
||||
preserveDescribeNesting: true,
|
||||
foldAll: false
|
||||
},
|
||||
// htmlReporter: {
|
||||
// outputDir: "dist/reports/tests",
|
||||
// preserveDescribeNesting: true,
|
||||
// foldAll: false
|
||||
// },
|
||||
junitReporter: {
|
||||
outputDir: "dist/reports/tests",
|
||||
outputFile: "test-results.xml",
|
||||
useBrowserName: false
|
||||
},
|
||||
browserConsoleLogOptions: {
|
||||
level: "error",
|
||||
format: "%b %T: %m",
|
||||
terminal: true
|
||||
},
|
||||
coverageIstanbulReporter: {
|
||||
fixWebpackSourcePaths: true,
|
||||
dir: process.env.CIRCLE_ARTIFACTS
|
||||
? process.env.CIRCLE_ARTIFACTS + '/coverage'
|
||||
: "dist/reports/coverage",
|
||||
reports: ['html', 'lcovonly', 'text-summary'],
|
||||
reports: ['lcovonly', 'text-summary'],
|
||||
thresholds: {
|
||||
global: {
|
||||
lines: 66
|
||||
}
|
||||
}
|
||||
},
|
||||
specReporter: {
|
||||
maxLogLines: 5,
|
||||
suppressErrorSummary: false,
|
||||
suppressFailed: false,
|
||||
suppressPassed: false,
|
||||
suppressSkipped: true,
|
||||
showSpecTiming: true,
|
||||
failFast: false
|
||||
},
|
||||
preprocessors: {
|
||||
'indexTest.js': ['webpack', 'sourcemap']
|
||||
},
|
||||
|
@ -1,8 +1,9 @@
|
||||
{
|
||||
"name": "openmct",
|
||||
"version": "1.7.8-SNAPSHOT",
|
||||
"version": "1.8.1",
|
||||
"description": "The Open MCT core platform",
|
||||
"devDependencies": {
|
||||
"@braintree/sanitize-url": "^5.0.2",
|
||||
"angular": ">=1.8.0",
|
||||
"angular-route": "1.4.14",
|
||||
"babel-eslint": "10.0.3",
|
||||
@ -37,10 +38,10 @@
|
||||
"karma-coverage": "2.0.3",
|
||||
"karma-coverage-istanbul-reporter": "3.0.3",
|
||||
"karma-firefox-launcher": "2.1.1",
|
||||
"karma-html-reporter": "0.2.7",
|
||||
"karma-jasmine": "4.0.1",
|
||||
"karma-junit-reporter": "2.0.1",
|
||||
"karma-sourcemap-loader": "0.3.8",
|
||||
"karma-spec-reporter": "0.0.32",
|
||||
"karma-webpack": "4.0.2",
|
||||
"location-bar": "^3.0.1",
|
||||
"lodash": "^4.17.12",
|
||||
@ -64,6 +65,7 @@
|
||||
"uuid": "^3.3.3",
|
||||
"v8-compile-cache": "^1.1.0",
|
||||
"vue": "2.5.6",
|
||||
"vue-eslint-parser": "7.11.0",
|
||||
"vue-loader": "^15.2.6",
|
||||
"vue-template-compiler": "2.5.6",
|
||||
"webpack": "^4.16.2",
|
||||
|
@ -34,9 +34,6 @@ define([
|
||||
"./src/policies/EditPersistableObjectsPolicy",
|
||||
"./src/representers/EditRepresenter",
|
||||
"./src/capabilities/EditorCapability",
|
||||
"./src/capabilities/TransactionCapabilityDecorator",
|
||||
"./src/services/TransactionManager",
|
||||
"./src/services/TransactionService",
|
||||
"./src/creation/CreateMenuController",
|
||||
"./src/creation/LocatorController",
|
||||
"./src/creation/CreationPolicy",
|
||||
@ -63,9 +60,6 @@ define([
|
||||
EditPersistableObjectsPolicy,
|
||||
EditRepresenter,
|
||||
EditorCapability,
|
||||
TransactionCapabilityDecorator,
|
||||
TransactionManager,
|
||||
TransactionService,
|
||||
CreateMenuController,
|
||||
LocatorController,
|
||||
CreationPolicy,
|
||||
@ -263,26 +257,6 @@ define([
|
||||
}
|
||||
],
|
||||
"components": [
|
||||
{
|
||||
"type": "decorator",
|
||||
"provides": "capabilityService",
|
||||
"implementation": TransactionCapabilityDecorator,
|
||||
"depends": [
|
||||
"$q",
|
||||
"transactionManager"
|
||||
],
|
||||
"priority": "fallback"
|
||||
},
|
||||
{
|
||||
"type": "provider",
|
||||
"provides": "transactionService",
|
||||
"implementation": TransactionService,
|
||||
"depends": [
|
||||
"$q",
|
||||
"$log",
|
||||
"cacheService"
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "CreateActionProvider",
|
||||
"provides": "actionService",
|
||||
@ -320,7 +294,6 @@ define([
|
||||
"description": "Provides transactional editing capabilities",
|
||||
"implementation": EditorCapability,
|
||||
"depends": [
|
||||
"transactionService",
|
||||
"openmct"
|
||||
]
|
||||
}
|
||||
@ -331,15 +304,6 @@ define([
|
||||
"template": locatorTemplate
|
||||
}
|
||||
],
|
||||
"services": [
|
||||
{
|
||||
"key": "transactionManager",
|
||||
"implementation": TransactionManager,
|
||||
"depends": [
|
||||
"transactionService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
depends: [
|
||||
|
@ -96,8 +96,7 @@ function (
|
||||
SaveAsAction.prototype.save = function () {
|
||||
var self = this,
|
||||
domainObject = this.domainObject,
|
||||
dialog = new SaveInProgressDialog(this.dialogService),
|
||||
toUndirty = [];
|
||||
dialog = new SaveInProgressDialog(this.dialogService);
|
||||
|
||||
function doWizardSave(parent) {
|
||||
var wizard = self.createWizard(parent);
|
||||
@ -132,10 +131,13 @@ function (
|
||||
return fetchObject(object.getModel().location);
|
||||
}
|
||||
|
||||
function saveObject(parent) {
|
||||
function saveObject(object) {
|
||||
//persist the object, which adds it to the transaction and then call editor.save
|
||||
return object.getCapability("persistence").persist()
|
||||
.then(() => {
|
||||
return self.openmct.editor.save().then(() => {
|
||||
// Force mutation for search indexing
|
||||
return parent;
|
||||
return object;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@ -150,17 +152,6 @@ function (
|
||||
});
|
||||
}
|
||||
|
||||
function undirty(object) {
|
||||
return object.getCapability('persistence').refresh();
|
||||
}
|
||||
|
||||
function undirtyOriginals(object) {
|
||||
return Promise.all(toUndirty.map(undirty))
|
||||
.then(() => {
|
||||
return object;
|
||||
});
|
||||
}
|
||||
|
||||
function indexForSearch(addedObject) {
|
||||
addedObject.useCapability('mutation', (model) => {
|
||||
return model;
|
||||
@ -187,10 +178,9 @@ function (
|
||||
return getParent(domainObject)
|
||||
.then(doWizardSave)
|
||||
.then(showBlockingDialog)
|
||||
.then(getParent)
|
||||
.then(saveObject)
|
||||
.then(getParent)
|
||||
.then(addSavedObjectToParent)
|
||||
.then(undirtyOriginals)
|
||||
.then((addedObject) => {
|
||||
return fetchObject(addedObject.getId());
|
||||
})
|
||||
|
@ -30,34 +30,17 @@ define(
|
||||
* Once initiated, any persist operations will be queued pending a
|
||||
* subsequent call to [.save()](@link #save) or [.finish()](@link
|
||||
* #finish).
|
||||
* @param transactionService
|
||||
* @param domainObject
|
||||
* @constructor
|
||||
*/
|
||||
function EditorCapability(
|
||||
transactionService,
|
||||
openmct,
|
||||
domainObject
|
||||
) {
|
||||
this.transactionService = transactionService;
|
||||
this.openmct = openmct;
|
||||
this.domainObject = domainObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initiate an editing session. This will start a transaction during
|
||||
* which any persist operations will be deferred until either save()
|
||||
* or finish() are called.
|
||||
*/
|
||||
EditorCapability.prototype.edit = function () {
|
||||
console.warn('DEPRECATED: cannot edit via edit capability, use openmct.editor instead.');
|
||||
|
||||
if (!this.openmct.editor.isEditing()) {
|
||||
this.openmct.editor.edit();
|
||||
this.domainObject.getCapability('status').set('editing', true);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Determines whether this object, or any of its ancestors are
|
||||
* currently being edited.
|
||||
@ -76,38 +59,6 @@ define(
|
||||
return this.openmct.editor.isEditing();
|
||||
};
|
||||
|
||||
/**
|
||||
* Save any unsaved changes from this editing session. This will
|
||||
* end the current transaction and continue with a new one.
|
||||
* @returns {*}
|
||||
*/
|
||||
EditorCapability.prototype.save = function () {
|
||||
console.warn('DEPRECATED: cannot save via edit capability, use openmct.editor instead.');
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
EditorCapability.prototype.invoke = EditorCapability.prototype.edit;
|
||||
|
||||
/**
|
||||
* Finish the current editing session. This will discard any pending
|
||||
* persist operations
|
||||
* @returns {*}
|
||||
*/
|
||||
EditorCapability.prototype.finish = function () {
|
||||
console.warn('DEPRECATED: cannot finish via edit capability, use openmct.editor instead.');
|
||||
|
||||
return Promise.resolve();
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns {boolean} true if there have been any domain model
|
||||
* modifications since the last persist, false otherwise.
|
||||
*/
|
||||
EditorCapability.prototype.dirty = function () {
|
||||
return this.transactionService.size() > 0;
|
||||
};
|
||||
|
||||
return EditorCapability;
|
||||
}
|
||||
);
|
||||
|
@ -1,75 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
['./TransactionalPersistenceCapability'],
|
||||
function (TransactionalPersistenceCapability) {
|
||||
|
||||
/**
|
||||
* Wraps the [PersistenceCapability]{@link PersistenceCapability} with
|
||||
* transactional capabilities.
|
||||
* @param $q
|
||||
* @param transactionService
|
||||
* @param capabilityService
|
||||
* @see TransactionalPersistenceCapability
|
||||
* @constructor
|
||||
*/
|
||||
function TransactionCapabilityDecorator(
|
||||
$q,
|
||||
transactionService,
|
||||
capabilityService
|
||||
) {
|
||||
this.capabilityService = capabilityService;
|
||||
this.transactionService = transactionService;
|
||||
this.$q = $q;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decorate PersistenceCapability to queue persistence calls when a
|
||||
* transaction is in progress.
|
||||
*/
|
||||
TransactionCapabilityDecorator.prototype.getCapabilities = function () {
|
||||
var self = this,
|
||||
capabilities = this.capabilityService.getCapabilities
|
||||
.apply(this.capabilityService, arguments),
|
||||
persistenceCapability = capabilities.persistence;
|
||||
|
||||
capabilities.persistence = function (domainObject) {
|
||||
var original =
|
||||
(typeof persistenceCapability === 'function')
|
||||
? persistenceCapability(domainObject)
|
||||
: persistenceCapability;
|
||||
|
||||
return new TransactionalPersistenceCapability(
|
||||
self.$q,
|
||||
self.transactionService,
|
||||
original,
|
||||
domainObject
|
||||
);
|
||||
};
|
||||
|
||||
return capabilities;
|
||||
};
|
||||
|
||||
return TransactionCapabilityDecorator;
|
||||
}
|
||||
);
|
@ -1,91 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Wraps persistence capability to enable transactions. Transactions
|
||||
* will cause persist calls not to be invoked immediately, but
|
||||
* rather queued until [EditorCapability.save()]{@link EditorCapability#save}
|
||||
* or [EditorCapability.cancel()]{@link EditorCapability#cancel} are
|
||||
* called.
|
||||
* @memberof platform/commonUI/edit/capabilities
|
||||
* @param $q
|
||||
* @param transactionManager
|
||||
* @param persistenceCapability
|
||||
* @param domainObject
|
||||
* @constructor
|
||||
*/
|
||||
function TransactionalPersistenceCapability(
|
||||
$q,
|
||||
transactionManager,
|
||||
persistenceCapability,
|
||||
domainObject
|
||||
) {
|
||||
this.transactionManager = transactionManager;
|
||||
this.persistenceCapability = persistenceCapability;
|
||||
this.domainObject = domainObject;
|
||||
this.$q = $q;
|
||||
}
|
||||
|
||||
/**
|
||||
* The wrapped persist function. If a transaction is active, persist
|
||||
* will be queued until the transaction is committed or cancelled.
|
||||
* @returns {*}
|
||||
*/
|
||||
TransactionalPersistenceCapability.prototype.persist = function () {
|
||||
var wrappedPersistence = this.persistenceCapability;
|
||||
|
||||
if (this.transactionManager.isActive()) {
|
||||
this.transactionManager.addToTransaction(
|
||||
this.domainObject.getId(),
|
||||
wrappedPersistence.persist.bind(wrappedPersistence),
|
||||
wrappedPersistence.refresh.bind(wrappedPersistence)
|
||||
);
|
||||
|
||||
//Need to return a promise from this function
|
||||
return this.$q.when(true);
|
||||
} else {
|
||||
return this.persistenceCapability.persist();
|
||||
}
|
||||
};
|
||||
|
||||
TransactionalPersistenceCapability.prototype.refresh = function () {
|
||||
this.transactionManager
|
||||
.clearTransactionsFor(this.domainObject.getId());
|
||||
|
||||
return this.persistenceCapability.refresh();
|
||||
};
|
||||
|
||||
TransactionalPersistenceCapability.prototype.getSpace = function () {
|
||||
return this.persistenceCapability.getSpace();
|
||||
};
|
||||
|
||||
TransactionalPersistenceCapability.prototype.persisted = function () {
|
||||
return this.persistenceCapability.persisted();
|
||||
};
|
||||
|
||||
return TransactionalPersistenceCapability;
|
||||
}
|
||||
);
|
@ -86,13 +86,22 @@ define(
|
||||
})
|
||||
.join('/');
|
||||
|
||||
openmct.router.navigate(url);
|
||||
function editObject() {
|
||||
const path = objectPath.slice(-1).map(obj => {
|
||||
const objNew = obj.getCapability('adapter').invoke();
|
||||
|
||||
if (isFirstViewEditable(object.useCapability('adapter'), objectPath)) {
|
||||
return objNew;
|
||||
});
|
||||
if (isFirstViewEditable(object.useCapability('adapter'), path)) {
|
||||
openmct.editor.edit();
|
||||
}
|
||||
}
|
||||
|
||||
openmct.router.once('afterNavigation', editObject);
|
||||
|
||||
openmct.router.navigate(url);
|
||||
}
|
||||
|
||||
newModel.type = this.type.getKey();
|
||||
newModel.location = this.parent.getId();
|
||||
newObject = this.parent.useCapability('instantiation', newModel);
|
||||
|
@ -1,99 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
define([], function () {
|
||||
/**
|
||||
* A Transaction represents a set of changes that are intended to
|
||||
* be kept or discarded as a unit.
|
||||
* @param $log Angular's `$log` service, for logging messages
|
||||
* @constructor
|
||||
* @memberof platform/commonUI/edit/services
|
||||
*/
|
||||
function Transaction($log) {
|
||||
this.$log = $log;
|
||||
this.callbacks = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a change to the current transaction, as expressed by functions
|
||||
* to either keep or discard the change.
|
||||
* @param {Function} commit called when the transaction is committed
|
||||
* @param {Function} cancel called when the transaction is cancelled
|
||||
* @returns {Function) a function which may be called to remove this
|
||||
* pair of callbacks from the transaction
|
||||
*/
|
||||
Transaction.prototype.add = function (commit, cancel) {
|
||||
var callback = {
|
||||
commit: commit,
|
||||
cancel: cancel
|
||||
};
|
||||
this.callbacks.push(callback);
|
||||
|
||||
return function () {
|
||||
this.callbacks = this.callbacks.filter(function (c) {
|
||||
return c !== callback;
|
||||
});
|
||||
}.bind(this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the number of changes in the current transaction.
|
||||
* @returns {number} the size of the current transaction
|
||||
*/
|
||||
Transaction.prototype.size = function () {
|
||||
return this.callbacks.length;
|
||||
};
|
||||
|
||||
/**
|
||||
* Keep all changes associated with this transaction.
|
||||
* @method {platform/commonUI/edit/services.Transaction#commit}
|
||||
* @returns {Promise} a promise which will resolve when all callbacks
|
||||
* have been handled.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Discard all changes associated with this transaction.
|
||||
* @method {platform/commonUI/edit/services.Transaction#cancel}
|
||||
* @returns {Promise} a promise which will resolve when all callbacks
|
||||
* have been handled.
|
||||
*/
|
||||
|
||||
['commit', 'cancel'].forEach(function (method) {
|
||||
Transaction.prototype[method] = function () {
|
||||
var promises = [];
|
||||
var callback;
|
||||
|
||||
while (this.callbacks.length > 0) {
|
||||
callback = this.callbacks.shift();
|
||||
try {
|
||||
promises.push(callback[method]());
|
||||
} catch (e) {
|
||||
this.$log
|
||||
.error("Error trying to " + method + " transaction.");
|
||||
}
|
||||
}
|
||||
|
||||
return Promise.all(promises);
|
||||
};
|
||||
});
|
||||
|
||||
return Transaction;
|
||||
});
|
@ -1,119 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([], function () {
|
||||
/**
|
||||
* Manages transactions to support the TransactionalPersistenceCapability.
|
||||
* This assumes that all commit/cancel callbacks for a given domain
|
||||
* object are equivalent, and only need to be added once to any active
|
||||
* transaction. Violating this assumption may cause unexpected behavior.
|
||||
* @constructor
|
||||
* @memberof platform/commonUI/edit
|
||||
*/
|
||||
function TransactionManager(transactionService) {
|
||||
this.transactionService = transactionService;
|
||||
this.clearTransactionFns = {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a transaction is currently active.
|
||||
* @returns {boolean} true if there is a transaction active
|
||||
*/
|
||||
TransactionManager.prototype.isActive = function () {
|
||||
return this.transactionService.isActive();
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if callbacks associated with this domain object have already
|
||||
* been added to the active transaction.
|
||||
* @private
|
||||
* @param {string} id the identifier of the domain object to check
|
||||
* @returns {boolean} true if callbacks have been added
|
||||
*/
|
||||
TransactionManager.prototype.isScheduled = function (id) {
|
||||
return Boolean(this.clearTransactionFns[id]);
|
||||
};
|
||||
|
||||
/**
|
||||
* Add callbacks associated with this domain object to the active
|
||||
* transaction. Both callbacks are expected to return promises that
|
||||
* resolve when their associated behavior is complete.
|
||||
*
|
||||
* If callbacks associated with this domain object have already been
|
||||
* added to the active transaction, this call will be ignored.
|
||||
*
|
||||
* @param {string} id the identifier of the associated domain object
|
||||
* @param {Function} onCommit behavior to invoke when committing transaction
|
||||
* @param {Function} onCancel behavior to invoke when cancelling transaction
|
||||
*/
|
||||
TransactionManager.prototype.addToTransaction = function (
|
||||
id,
|
||||
onCommit,
|
||||
onCancel
|
||||
) {
|
||||
var release = this.releaseClearFn.bind(this, id);
|
||||
|
||||
function chain(promiseFn, nextFn) {
|
||||
return function () {
|
||||
return promiseFn().then(nextFn);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear any existing persistence calls for object with given ID. This ensures only the most recent persistence
|
||||
* call is executed. This should prevent stale objects being persisted and overwriting fresh ones.
|
||||
*/
|
||||
if (this.isScheduled(id)) {
|
||||
this.clearTransactionsFor(id);
|
||||
}
|
||||
|
||||
this.clearTransactionFns[id] =
|
||||
this.transactionService.addToTransaction(
|
||||
chain(onCommit, release),
|
||||
chain(onCancel, release)
|
||||
);
|
||||
};
|
||||
|
||||
/**
|
||||
* Remove any callbacks associated with this domain object from the
|
||||
* active transaction.
|
||||
* @param {string} id the identifier for the domain object
|
||||
*/
|
||||
TransactionManager.prototype.clearTransactionsFor = function (id) {
|
||||
if (this.isScheduled(id)) {
|
||||
this.clearTransactionFns[id]();
|
||||
this.releaseClearFn(id);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Release the cached "remove from transaction" function that has been
|
||||
* stored in association with this domain object.
|
||||
* @param {string} id the identifier for the domain object
|
||||
* @private
|
||||
*/
|
||||
TransactionManager.prototype.releaseClearFn = function (id) {
|
||||
delete this.clearTransactionFns[id];
|
||||
};
|
||||
|
||||
return TransactionManager;
|
||||
});
|
@ -1,138 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
define(
|
||||
['./Transaction', './NestedTransaction'],
|
||||
function (Transaction, NestedTransaction) {
|
||||
/**
|
||||
* Implements an application-wide transaction state. Once a
|
||||
* transaction is started, calls to
|
||||
* [PersistenceCapability.persist()]{@link PersistenceCapability#persist}
|
||||
* will be deferred until a subsequent call to
|
||||
* [TransactionService.commit]{@link TransactionService#commit} is made.
|
||||
*
|
||||
* @memberof platform/commonUI/edit/services
|
||||
* @param $q
|
||||
* @constructor
|
||||
*/
|
||||
function TransactionService($q, $log, cacheService) {
|
||||
this.$q = $q;
|
||||
this.$log = $log;
|
||||
this.cacheService = cacheService;
|
||||
this.transactions = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts a transaction. While a transaction is active all calls to
|
||||
* [PersistenceCapability.persist](@link PersistenceCapability#persist)
|
||||
* will be queued until [commit]{@link #commit} or [cancel]{@link
|
||||
* #cancel} are called
|
||||
*/
|
||||
TransactionService.prototype.startTransaction = function () {
|
||||
var transaction = this.isActive()
|
||||
? new NestedTransaction(this.transactions[0])
|
||||
: new Transaction(this.$log);
|
||||
|
||||
this.transactions.push(transaction);
|
||||
};
|
||||
|
||||
/**
|
||||
* @returns {boolean} If true, indicates that a transaction is in progress
|
||||
*/
|
||||
TransactionService.prototype.isActive = function () {
|
||||
return this.transactions.length > 0;
|
||||
};
|
||||
|
||||
/**
|
||||
* Adds provided functions to a queue to be called on
|
||||
* [.commit()]{@link #commit} or
|
||||
* [.cancel()]{@link #commit}
|
||||
* @param onCommit A function to call on commit
|
||||
* @param onCancel A function to call on cancel
|
||||
*/
|
||||
TransactionService.prototype.addToTransaction = function (onCommit, onCancel) {
|
||||
if (this.isActive()) {
|
||||
return this.activeTransaction().add(onCommit, onCancel);
|
||||
} else {
|
||||
//Log error because this is a programming error if it occurs.
|
||||
this.$log.error("No transaction in progress");
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the transaction at the top of the stack.
|
||||
* @private
|
||||
*/
|
||||
TransactionService.prototype.activeTransaction = function () {
|
||||
return this.transactions[this.transactions.length - 1];
|
||||
};
|
||||
|
||||
/**
|
||||
* All persist calls deferred since the beginning of the transaction
|
||||
* will be committed. If this is the last transaction, clears the
|
||||
* cache.
|
||||
*
|
||||
* @returns {Promise} resolved when all persist operations have
|
||||
* completed. Will reject if any commit operations fail
|
||||
*/
|
||||
TransactionService.prototype.commit = function () {
|
||||
var transaction = this.transactions.pop();
|
||||
if (!transaction) {
|
||||
return Promise.reject();
|
||||
}
|
||||
|
||||
if (!this.isActive()) {
|
||||
return transaction.commit()
|
||||
.then(function (r) {
|
||||
this.cacheService.flush();
|
||||
|
||||
return r;
|
||||
}.bind(this));
|
||||
}
|
||||
|
||||
return transaction.commit();
|
||||
};
|
||||
|
||||
/**
|
||||
* Cancel the current transaction, replacing any dirty objects from
|
||||
* persistence. Not a true rollback, as it cannot be used to undo any
|
||||
* persist calls that were successful in the event one of a batch of
|
||||
* persists failing.
|
||||
*
|
||||
* @returns {*}
|
||||
*/
|
||||
TransactionService.prototype.cancel = function () {
|
||||
var transaction = this.transactions.pop();
|
||||
|
||||
return transaction ? transaction.cancel() : Promise.reject();
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the size (the number of commit/cancel callbacks) of
|
||||
* the active transaction.
|
||||
* @returns {number} size of the active transaction
|
||||
*/
|
||||
TransactionService.prototype.size = function () {
|
||||
return this.isActive() ? this.activeTransaction().size() : 0;
|
||||
};
|
||||
|
||||
return TransactionService;
|
||||
});
|
@ -1,192 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/capabilities/EditorCapability"],
|
||||
function (EditorCapability) {
|
||||
|
||||
xdescribe("The editor capability", function () {
|
||||
var mockDomainObject,
|
||||
capabilities,
|
||||
mockParentObject,
|
||||
mockTransactionService,
|
||||
mockStatusCapability,
|
||||
mockParentStatus,
|
||||
mockContextCapability,
|
||||
capability;
|
||||
|
||||
function fastPromise(val) {
|
||||
return {
|
||||
then: function (callback) {
|
||||
return callback(val);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
"domainObject",
|
||||
["getId", "getModel", "hasCapability", "getCapability", "useCapability"]
|
||||
);
|
||||
mockParentObject = jasmine.createSpyObj(
|
||||
"domainObject",
|
||||
["getId", "getModel", "hasCapability", "getCapability", "useCapability"]
|
||||
);
|
||||
mockTransactionService = jasmine.createSpyObj(
|
||||
"transactionService",
|
||||
[
|
||||
"startTransaction",
|
||||
"size",
|
||||
"commit",
|
||||
"cancel"
|
||||
]
|
||||
);
|
||||
mockTransactionService.commit.and.returnValue(fastPromise());
|
||||
mockTransactionService.cancel.and.returnValue(fastPromise());
|
||||
mockTransactionService.isActive = jasmine.createSpy('isActive');
|
||||
|
||||
mockStatusCapability = jasmine.createSpyObj(
|
||||
"statusCapability",
|
||||
["get", "set"]
|
||||
);
|
||||
mockParentStatus = jasmine.createSpyObj(
|
||||
"statusCapability",
|
||||
["get", "set"]
|
||||
);
|
||||
mockContextCapability = jasmine.createSpyObj(
|
||||
"contextCapability",
|
||||
["getParent"]
|
||||
);
|
||||
mockContextCapability.getParent.and.returnValue(mockParentObject);
|
||||
|
||||
capabilities = {
|
||||
context: mockContextCapability,
|
||||
status: mockStatusCapability
|
||||
};
|
||||
|
||||
mockDomainObject.hasCapability.and.callFake(function (name) {
|
||||
return capabilities[name] !== undefined;
|
||||
});
|
||||
|
||||
mockDomainObject.getCapability.and.callFake(function (name) {
|
||||
return capabilities[name];
|
||||
});
|
||||
|
||||
mockParentObject.getCapability.and.returnValue(mockParentStatus);
|
||||
mockParentObject.hasCapability.and.returnValue(false);
|
||||
|
||||
capability = new EditorCapability(
|
||||
mockTransactionService,
|
||||
mockDomainObject
|
||||
);
|
||||
});
|
||||
|
||||
it("starts a transaction when edit is invoked", function () {
|
||||
capability.edit();
|
||||
expect(mockTransactionService.startTransaction).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("sets editing status on object", function () {
|
||||
capability.edit();
|
||||
expect(mockStatusCapability.set).toHaveBeenCalledWith("editing", true);
|
||||
});
|
||||
|
||||
it("uses editing status to determine editing context root", function () {
|
||||
capability.edit();
|
||||
mockStatusCapability.get.and.returnValue(false);
|
||||
expect(capability.isEditContextRoot()).toBe(false);
|
||||
mockStatusCapability.get.and.returnValue(true);
|
||||
expect(capability.isEditContextRoot()).toBe(true);
|
||||
});
|
||||
|
||||
it("inEditingContext returns true if parent object is being"
|
||||
+ " edited", function () {
|
||||
mockStatusCapability.get.and.returnValue(false);
|
||||
mockParentStatus.get.and.returnValue(false);
|
||||
expect(capability.inEditContext()).toBe(false);
|
||||
mockParentStatus.get.and.returnValue(true);
|
||||
expect(capability.inEditContext()).toBe(true);
|
||||
});
|
||||
|
||||
describe("save", function () {
|
||||
beforeEach(function () {
|
||||
capability.edit();
|
||||
capability.save();
|
||||
});
|
||||
it("commits the transaction", function () {
|
||||
expect(mockTransactionService.commit).toHaveBeenCalled();
|
||||
});
|
||||
it("begins a new transaction", function () {
|
||||
expect(mockTransactionService.startTransaction).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("finish", function () {
|
||||
beforeEach(function () {
|
||||
mockTransactionService.isActive.and.returnValue(true);
|
||||
capability.edit();
|
||||
capability.finish();
|
||||
});
|
||||
it("cancels the transaction", function () {
|
||||
expect(mockTransactionService.cancel).toHaveBeenCalled();
|
||||
});
|
||||
it("resets the edit state", function () {
|
||||
expect(mockStatusCapability.set).toHaveBeenCalledWith('editing', false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("finish", function () {
|
||||
beforeEach(function () {
|
||||
mockTransactionService.isActive.and.returnValue(false);
|
||||
capability.edit();
|
||||
});
|
||||
|
||||
it("does not cancel transaction when transaction is not active", function () {
|
||||
capability.finish();
|
||||
expect(mockTransactionService.cancel).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("returns a promise", function () {
|
||||
expect(capability.finish() instanceof Promise).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("dirty", function () {
|
||||
var model = {};
|
||||
|
||||
beforeEach(function () {
|
||||
mockDomainObject.getModel.and.returnValue(model);
|
||||
capability.edit();
|
||||
capability.finish();
|
||||
});
|
||||
it("returns true if the object has been modified since it"
|
||||
+ " was last persisted", function () {
|
||||
mockTransactionService.size.and.returnValue(0);
|
||||
expect(capability.dirty()).toBe(false);
|
||||
mockTransactionService.size.and.returnValue(1);
|
||||
expect(capability.dirty()).toBe(true);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,54 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[
|
||||
"../../src/capabilities/TransactionalPersistenceCapability",
|
||||
"../../src/capabilities/TransactionCapabilityDecorator"
|
||||
],
|
||||
function (TransactionalPersistenceCapability, TransactionCapabilityDecorator) {
|
||||
|
||||
describe("The transaction capability decorator", function () {
|
||||
var mockQ,
|
||||
mockTransactionService,
|
||||
mockCapabilityService,
|
||||
provider;
|
||||
|
||||
beforeEach(function () {
|
||||
mockQ = {};
|
||||
mockTransactionService = {};
|
||||
mockCapabilityService = jasmine.createSpyObj("capabilityService", ["getCapabilities"]);
|
||||
mockCapabilityService.getCapabilities.and.returnValue({
|
||||
persistence: function () {}
|
||||
});
|
||||
|
||||
provider = new TransactionCapabilityDecorator(mockQ, mockTransactionService, mockCapabilityService);
|
||||
|
||||
});
|
||||
it("decorates the persistence capability", function () {
|
||||
var capabilities = provider.getCapabilities();
|
||||
expect(capabilities.persistence({}) instanceof TransactionalPersistenceCapability).toBe(true);
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
@ -1,111 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[
|
||||
"../../src/capabilities/TransactionalPersistenceCapability"
|
||||
],
|
||||
function (TransactionalPersistenceCapability) {
|
||||
|
||||
function fastPromise(val) {
|
||||
return {
|
||||
then: function (callback) {
|
||||
return callback(val);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
describe("The transactional persistence decorator", function () {
|
||||
var mockQ,
|
||||
mockTransactionManager,
|
||||
mockPersistence,
|
||||
mockDomainObject,
|
||||
testId,
|
||||
capability;
|
||||
|
||||
beforeEach(function () {
|
||||
testId = "test-id";
|
||||
|
||||
mockQ = jasmine.createSpyObj("$q", ["when"]);
|
||||
mockQ.when.and.callFake(function (val) {
|
||||
return fastPromise(val);
|
||||
});
|
||||
mockTransactionManager = jasmine.createSpyObj(
|
||||
"transactionService",
|
||||
["isActive", "addToTransaction", "clearTransactionsFor"]
|
||||
);
|
||||
mockPersistence = jasmine.createSpyObj(
|
||||
"persistenceCapability",
|
||||
["persist", "refresh", "getSpace"]
|
||||
);
|
||||
mockPersistence.persist.and.returnValue(fastPromise());
|
||||
mockPersistence.refresh.and.returnValue(fastPromise());
|
||||
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
"domainObject",
|
||||
["getModel", "getId"]
|
||||
);
|
||||
mockDomainObject.getModel.and.returnValue({persisted: 1});
|
||||
mockDomainObject.getId.and.returnValue(testId);
|
||||
|
||||
capability = new TransactionalPersistenceCapability(
|
||||
mockQ,
|
||||
mockTransactionManager,
|
||||
mockPersistence,
|
||||
mockDomainObject
|
||||
);
|
||||
});
|
||||
|
||||
it("if no transaction is active, passes through to persistence"
|
||||
+ " provider", function () {
|
||||
mockTransactionManager.isActive.and.returnValue(false);
|
||||
capability.persist();
|
||||
expect(mockPersistence.persist).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("if transaction is active, persist and cancel calls are"
|
||||
+ " queued", function () {
|
||||
mockTransactionManager.isActive.and.returnValue(true);
|
||||
capability.persist();
|
||||
expect(mockTransactionManager.addToTransaction).toHaveBeenCalled();
|
||||
mockTransactionManager.addToTransaction.calls.mostRecent().args[1]();
|
||||
expect(mockPersistence.persist).toHaveBeenCalled();
|
||||
mockTransactionManager.addToTransaction.calls.mostRecent().args[2]();
|
||||
expect(mockPersistence.refresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("wraps getSpace", function () {
|
||||
mockPersistence.getSpace.and.returnValue('foo');
|
||||
expect(capability.getSpace()).toEqual('foo');
|
||||
});
|
||||
|
||||
it("clears transactions and delegates refresh calls", function () {
|
||||
capability.refresh();
|
||||
expect(mockTransactionManager.clearTransactionsFor)
|
||||
.toHaveBeenCalledWith(testId);
|
||||
expect(mockPersistence.refresh)
|
||||
.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
@ -1,75 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(["../../src/services/NestedTransaction"], function (NestedTransaction) {
|
||||
var TRANSACTION_METHODS = ['add', 'commit', 'cancel', 'size'];
|
||||
|
||||
describe("A NestedTransaction", function () {
|
||||
var mockTransaction,
|
||||
nestedTransaction;
|
||||
|
||||
beforeEach(function () {
|
||||
mockTransaction =
|
||||
jasmine.createSpyObj('transaction', TRANSACTION_METHODS);
|
||||
nestedTransaction = new NestedTransaction(mockTransaction);
|
||||
});
|
||||
|
||||
it("exposes a Transaction's interface", function () {
|
||||
TRANSACTION_METHODS.forEach(function (method) {
|
||||
expect(nestedTransaction[method])
|
||||
.toEqual(jasmine.any(Function));
|
||||
});
|
||||
});
|
||||
|
||||
describe("when callbacks are added", function () {
|
||||
var mockCommit,
|
||||
mockCancel;
|
||||
|
||||
beforeEach(function () {
|
||||
mockCommit = jasmine.createSpy('commit');
|
||||
mockCancel = jasmine.createSpy('cancel');
|
||||
nestedTransaction.add(mockCommit, mockCancel);
|
||||
});
|
||||
|
||||
it("does not interact with its parent transaction", function () {
|
||||
TRANSACTION_METHODS.forEach(function (method) {
|
||||
expect(mockTransaction[method])
|
||||
.not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("and the transaction is committed", function () {
|
||||
beforeEach(function () {
|
||||
nestedTransaction.commit();
|
||||
});
|
||||
|
||||
it("adds to its parent transaction", function () {
|
||||
expect(mockTransaction.add).toHaveBeenCalledWith(
|
||||
jasmine.any(Function),
|
||||
jasmine.any(Function)
|
||||
);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
@ -1,141 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/services/TransactionManager"],
|
||||
function (TransactionManager) {
|
||||
describe("TransactionManager", function () {
|
||||
var mockTransactionService,
|
||||
testId,
|
||||
mockOnCommit,
|
||||
mockOnCancel,
|
||||
mockRemoves,
|
||||
mockPromise,
|
||||
manager;
|
||||
|
||||
beforeEach(function () {
|
||||
mockRemoves = [];
|
||||
mockTransactionService = jasmine.createSpyObj(
|
||||
"transactionService",
|
||||
["addToTransaction", "isActive"]
|
||||
);
|
||||
mockOnCommit = jasmine.createSpy('commit');
|
||||
mockOnCancel = jasmine.createSpy('cancel');
|
||||
testId = 'test-id';
|
||||
mockPromise = jasmine.createSpyObj('promise', ['then']);
|
||||
|
||||
mockOnCommit.and.returnValue(mockPromise);
|
||||
mockOnCancel.and.returnValue(mockPromise);
|
||||
|
||||
mockTransactionService.addToTransaction.and.callFake(function () {
|
||||
var mockRemove =
|
||||
jasmine.createSpy('remove-' + mockRemoves.length);
|
||||
mockRemoves.push(mockRemove);
|
||||
|
||||
return mockRemove;
|
||||
});
|
||||
|
||||
manager = new TransactionManager(mockTransactionService);
|
||||
});
|
||||
|
||||
it("delegates isActive calls", function () {
|
||||
[false, true].forEach(function (state) {
|
||||
mockTransactionService.isActive.and.returnValue(state);
|
||||
expect(manager.isActive()).toBe(state);
|
||||
});
|
||||
});
|
||||
|
||||
describe("when addToTransaction is called", function () {
|
||||
beforeEach(function () {
|
||||
manager.addToTransaction(
|
||||
testId,
|
||||
mockOnCommit,
|
||||
mockOnCancel
|
||||
);
|
||||
});
|
||||
|
||||
it("adds callbacks to the active transaction", function () {
|
||||
expect(mockTransactionService.addToTransaction)
|
||||
.toHaveBeenCalledWith(
|
||||
jasmine.any(Function),
|
||||
jasmine.any(Function)
|
||||
);
|
||||
});
|
||||
|
||||
it("invokes passed-in callbacks from its own callbacks", function () {
|
||||
expect(mockOnCommit).not.toHaveBeenCalled();
|
||||
mockTransactionService.addToTransaction
|
||||
.calls.mostRecent().args[0]();
|
||||
expect(mockOnCommit).toHaveBeenCalled();
|
||||
|
||||
expect(mockOnCancel).not.toHaveBeenCalled();
|
||||
mockTransactionService.addToTransaction
|
||||
.calls.mostRecent().args[1]();
|
||||
expect(mockOnCancel).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("Adds callbacks to transaction", function () {
|
||||
beforeEach(function () {
|
||||
spyOn(manager, 'clearTransactionsFor');
|
||||
manager.clearTransactionsFor.and.callThrough();
|
||||
});
|
||||
|
||||
it("and clears pending calls if same object", function () {
|
||||
manager.addToTransaction(
|
||||
testId,
|
||||
jasmine.createSpy(),
|
||||
jasmine.createSpy()
|
||||
);
|
||||
expect(manager.clearTransactionsFor).toHaveBeenCalledWith(testId);
|
||||
});
|
||||
|
||||
it("and does not clear pending calls if different object", function () {
|
||||
manager.addToTransaction(
|
||||
'other-id',
|
||||
jasmine.createSpy(),
|
||||
jasmine.createSpy()
|
||||
);
|
||||
expect(manager.clearTransactionsFor).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
afterEach(function () {
|
||||
expect(mockTransactionService.addToTransaction.calls.count()).toEqual(2);
|
||||
});
|
||||
});
|
||||
|
||||
it("does not remove callbacks from the transaction", function () {
|
||||
expect(mockRemoves[0]).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
describe("and clearTransactionsFor is subsequently called", function () {
|
||||
beforeEach(function () {
|
||||
manager.clearTransactionsFor(testId);
|
||||
});
|
||||
|
||||
it("removes callbacks from the transaction", function () {
|
||||
expect(mockRemoves[0]).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,139 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/services/TransactionService"],
|
||||
function (TransactionService) {
|
||||
|
||||
describe("The Transaction Service", function () {
|
||||
var mockQ,
|
||||
mockLog,
|
||||
mockCacheService,
|
||||
transactionService;
|
||||
|
||||
function fastPromise(val) {
|
||||
return {
|
||||
then: function (callback) {
|
||||
return fastPromise(callback(val));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockQ = jasmine.createSpyObj("$q", ["all"]);
|
||||
mockCacheService = jasmine.createSpyObj("cacheService", ["flush"]);
|
||||
mockQ.all.and.returnValue(fastPromise());
|
||||
mockLog = jasmine.createSpyObj("$log", ["error"]);
|
||||
transactionService = new TransactionService(mockQ, mockLog, mockCacheService);
|
||||
});
|
||||
|
||||
it("isActive returns true if a transaction is in progress", function () {
|
||||
expect(transactionService.isActive()).toBe(false);
|
||||
transactionService.startTransaction();
|
||||
expect(transactionService.isActive()).toBe(true);
|
||||
});
|
||||
|
||||
it("addToTransaction queues onCommit and onCancel functions", function () {
|
||||
var onCommit = jasmine.createSpy('onCommit'),
|
||||
onCancel = jasmine.createSpy('onCancel');
|
||||
|
||||
transactionService.startTransaction();
|
||||
transactionService.addToTransaction(onCommit, onCancel);
|
||||
expect(transactionService.size()).toBe(1);
|
||||
});
|
||||
|
||||
it("size function returns size of commit and cancel queues", function () {
|
||||
var onCommit = jasmine.createSpy('onCommit'),
|
||||
onCancel = jasmine.createSpy('onCancel');
|
||||
|
||||
transactionService.startTransaction();
|
||||
transactionService.addToTransaction(onCommit, onCancel);
|
||||
transactionService.addToTransaction(onCommit, onCancel);
|
||||
transactionService.addToTransaction(onCommit, onCancel);
|
||||
expect(transactionService.size()).toBe(3);
|
||||
});
|
||||
|
||||
describe("commit", function () {
|
||||
var onCommits;
|
||||
|
||||
beforeEach(function () {
|
||||
onCommits = [0, 1, 2].map(function (val) {
|
||||
return jasmine.createSpy("onCommit" + val);
|
||||
});
|
||||
|
||||
transactionService.startTransaction();
|
||||
onCommits.forEach(transactionService.addToTransaction.bind(transactionService));
|
||||
});
|
||||
|
||||
it("commit calls all queued commit functions", function () {
|
||||
expect(transactionService.size()).toBe(3);
|
||||
|
||||
return transactionService.commit().then(() => {
|
||||
onCommits.forEach(function (spy) {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
it("commit resets active state and clears queues", function () {
|
||||
return transactionService.commit().then(() => {
|
||||
expect(transactionService.isActive()).toBe(false);
|
||||
expect(transactionService.size()).toBe(0);
|
||||
expect(transactionService.size()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
describe("cancel", function () {
|
||||
var onCancels;
|
||||
|
||||
beforeEach(function () {
|
||||
onCancels = [0, 1, 2].map(function (val) {
|
||||
return jasmine.createSpy("onCancel" + val);
|
||||
});
|
||||
|
||||
transactionService.startTransaction();
|
||||
onCancels.forEach(function (onCancel) {
|
||||
transactionService.addToTransaction(undefined, onCancel);
|
||||
});
|
||||
});
|
||||
|
||||
it("cancel calls all queued cancel functions", function () {
|
||||
expect(transactionService.size()).toBe(3);
|
||||
transactionService.cancel();
|
||||
onCancels.forEach(function (spy) {
|
||||
expect(spy).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
it("cancel resets active state and clears queues", function () {
|
||||
transactionService.cancel();
|
||||
expect(transactionService.isActive()).toBe(false);
|
||||
expect(transactionService.size()).toBe(0);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
@ -1,109 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/services/Transaction"],
|
||||
function (Transaction) {
|
||||
|
||||
describe("A Transaction", function () {
|
||||
var mockLog,
|
||||
transaction;
|
||||
|
||||
beforeEach(function () {
|
||||
mockLog = jasmine.createSpyObj(
|
||||
'$log',
|
||||
['warn', 'info', 'error', 'debug']
|
||||
);
|
||||
transaction = new Transaction(mockLog);
|
||||
});
|
||||
|
||||
it("initially has a size of zero", function () {
|
||||
expect(transaction.size()).toEqual(0);
|
||||
});
|
||||
|
||||
describe("when callbacks are added", function () {
|
||||
var mockCommit,
|
||||
mockCancel,
|
||||
remove;
|
||||
|
||||
beforeEach(function () {
|
||||
mockCommit = jasmine.createSpy('commit');
|
||||
mockCancel = jasmine.createSpy('cancel');
|
||||
remove = transaction.add(mockCommit, mockCancel);
|
||||
});
|
||||
|
||||
it("reports a new size", function () {
|
||||
expect(transaction.size()).toEqual(1);
|
||||
});
|
||||
|
||||
it("returns a function to remove those callbacks", function () {
|
||||
expect(remove).toEqual(jasmine.any(Function));
|
||||
remove();
|
||||
expect(transaction.size()).toEqual(0);
|
||||
});
|
||||
|
||||
describe("and the transaction is committed", function () {
|
||||
beforeEach(function () {
|
||||
transaction.commit();
|
||||
});
|
||||
|
||||
it("triggers the commit callback", function () {
|
||||
expect(mockCommit).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not trigger the cancel callback", function () {
|
||||
expect(mockCancel).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("and the transaction is cancelled", function () {
|
||||
beforeEach(function () {
|
||||
transaction.cancel();
|
||||
});
|
||||
|
||||
it("triggers the cancel callback", function () {
|
||||
expect(mockCancel).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not trigger the commit callback", function () {
|
||||
expect(mockCommit).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("and an exception is encountered during commit", function () {
|
||||
beforeEach(function () {
|
||||
mockCommit.and.callFake(function () {
|
||||
throw new Error("test error");
|
||||
});
|
||||
transaction.commit();
|
||||
});
|
||||
|
||||
it("logs an error", function () {
|
||||
expect(mockLog.error).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
||||
|
@ -25,9 +25,8 @@ define([
|
||||
], function (
|
||||
moment
|
||||
) {
|
||||
|
||||
var DATE_FORMAT = "YYYY-MM-DD HH:mm:ss.SSS",
|
||||
DATE_FORMATS = [
|
||||
const DATE_FORMAT = "YYYY-MM-DD HH:mm:ss.SSS";
|
||||
const DATE_FORMATS = [
|
||||
DATE_FORMAT,
|
||||
DATE_FORMAT + "Z",
|
||||
"YYYY-MM-DD HH:mm:ss",
|
||||
@ -53,15 +52,27 @@ define([
|
||||
this.key = "utc";
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} formatString
|
||||
* @returns the value of formatString if the value is a string type and exists in the DATE_FORMATS array; otherwise the DATE_FORMAT value.
|
||||
*/
|
||||
function validateFormatString(formatString) {
|
||||
return typeof formatString === 'string' && DATE_FORMATS.includes(formatString) ? formatString : DATE_FORMAT;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} value The value to format.
|
||||
* @returns {string} the formatted date(s). If multiple values were requested, then an array of
|
||||
* @param {string} formatString The string format to format. Default "YYYY-MM-DD HH:mm:ss.SSS" + "Z"
|
||||
* @returns {string} the formatted date(s) according to the proper parameter of formatString or the default value of "YYYY-MM-DD HH:mm:ss.SSS" + "Z".
|
||||
* If multiple values were requested, then an array of
|
||||
* formatted values will be returned. Where a value could not be formatted, `undefined` will be returned at its position
|
||||
* in the array.
|
||||
*/
|
||||
UTCTimeFormat.prototype.format = function (value) {
|
||||
UTCTimeFormat.prototype.format = function (value, formatString) {
|
||||
if (value !== undefined) {
|
||||
return moment.utc(value).format(DATE_FORMAT) + "Z";
|
||||
const format = validateFormatString(formatString);
|
||||
|
||||
return moment.utc(value).format(format) + (formatString ? '' : 'Z');
|
||||
} else {
|
||||
return value;
|
||||
}
|
||||
|
@ -28,7 +28,6 @@ define([
|
||||
"./src/models/ModelCacheService",
|
||||
"./src/models/PersistedModelProvider",
|
||||
"./src/models/CachingModelDecorator",
|
||||
"./src/models/MissingModelDecorator",
|
||||
"./src/types/TypeProvider",
|
||||
"./src/actions/ActionProvider",
|
||||
"./src/actions/ActionAggregator",
|
||||
@ -45,7 +44,6 @@ define([
|
||||
"./src/capabilities/MutationCapability",
|
||||
"./src/capabilities/DelegationCapability",
|
||||
"./src/capabilities/InstantiationCapability",
|
||||
"./src/runs/TransactingMutationListener",
|
||||
"./src/services/Now",
|
||||
"./src/services/Throttle",
|
||||
"./src/services/Topic",
|
||||
@ -58,7 +56,6 @@ define([
|
||||
ModelCacheService,
|
||||
PersistedModelProvider,
|
||||
CachingModelDecorator,
|
||||
MissingModelDecorator,
|
||||
TypeProvider,
|
||||
ActionProvider,
|
||||
ActionAggregator,
|
||||
@ -75,7 +72,6 @@ define([
|
||||
MutationCapability,
|
||||
DelegationCapability,
|
||||
InstantiationCapability,
|
||||
TransactingMutationListener,
|
||||
Now,
|
||||
Throttle,
|
||||
Topic,
|
||||
@ -150,12 +146,6 @@ define([
|
||||
"cacheService"
|
||||
]
|
||||
},
|
||||
{
|
||||
"provides": "modelService",
|
||||
"type": "decorator",
|
||||
"priority": "fallback",
|
||||
"implementation": MissingModelDecorator
|
||||
},
|
||||
{
|
||||
"provides": "typeService",
|
||||
"type": "provider",
|
||||
@ -363,12 +353,6 @@ define([
|
||||
]
|
||||
}
|
||||
],
|
||||
"runs": [
|
||||
{
|
||||
"implementation": TransactingMutationListener,
|
||||
"depends": ["topic", "transactionService", "cacheService"]
|
||||
}
|
||||
],
|
||||
"constants": [
|
||||
{
|
||||
"key": "PERSISTENCE_SPACE",
|
||||
|
@ -1,55 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT Web, Copyright (c) 2014-2015, United States Government
|
||||
* as represented by the Administrator of the National Aeronautics and Space
|
||||
* Administration. All rights reserved.
|
||||
*
|
||||
* Open MCT Web 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 Web 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([], function () {
|
||||
|
||||
/**
|
||||
* Listens for mutation on domain objects and triggers persistence when
|
||||
* it occurs.
|
||||
* @param {Topic} topic the `topic` service; used to listen for mutation
|
||||
* @memberof platform/core
|
||||
*/
|
||||
function TransactingMutationListener(
|
||||
topic,
|
||||
transactionService,
|
||||
cacheService
|
||||
) {
|
||||
|
||||
function hasChanged(domainObject) {
|
||||
var model = domainObject.getModel();
|
||||
|
||||
return model.persisted === undefined || model.modified > model.persisted;
|
||||
}
|
||||
|
||||
var mutationTopic = topic('mutation');
|
||||
mutationTopic.listen(function (domainObject) {
|
||||
var persistence = domainObject.getCapability('persistence');
|
||||
cacheService.put(domainObject.getId(), domainObject.getModel());
|
||||
|
||||
if (hasChanged(domainObject)) {
|
||||
persistence.persist();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return TransactingMutationListener;
|
||||
});
|
@ -1,86 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/models/MissingModelDecorator"],
|
||||
function (MissingModelDecorator) {
|
||||
|
||||
describe("The missing model decorator", function () {
|
||||
var mockModelService,
|
||||
testModels,
|
||||
decorator;
|
||||
|
||||
function asPromise(value) {
|
||||
return (value || {}).then ? value : {
|
||||
then: function (callback) {
|
||||
return asPromise(callback(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockModelService = jasmine.createSpyObj(
|
||||
"modelService",
|
||||
["getModels"]
|
||||
);
|
||||
|
||||
testModels = {
|
||||
testId: { someKey: "some value" }
|
||||
};
|
||||
|
||||
mockModelService.getModels.and.returnValue(asPromise(testModels));
|
||||
|
||||
decorator = new MissingModelDecorator(mockModelService);
|
||||
});
|
||||
|
||||
it("delegates to the wrapped model service", function () {
|
||||
decorator.getModels(['a', 'b', 'c']);
|
||||
expect(mockModelService.getModels)
|
||||
.toHaveBeenCalledWith(['a', 'b', 'c']);
|
||||
});
|
||||
|
||||
it("provides models for any IDs which are missing", function () {
|
||||
var models;
|
||||
decorator.getModels(['testId', 'otherId'])
|
||||
.then(function (m) {
|
||||
models = m;
|
||||
});
|
||||
expect(models.otherId).toBeDefined();
|
||||
});
|
||||
|
||||
it("does not overwrite existing models", function () {
|
||||
var models;
|
||||
decorator.getModels(['testId', 'otherId'])
|
||||
.then(function (m) {
|
||||
models = m;
|
||||
});
|
||||
expect(models.testId).toEqual({ someKey: "some value" });
|
||||
});
|
||||
|
||||
it("does not modify the wrapped service's response", function () {
|
||||
decorator.getModels(['testId', 'otherId']);
|
||||
expect(testModels.otherId).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
}
|
||||
);
|
@ -1,112 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/runs/TransactingMutationListener"],
|
||||
function (TransactingMutationListener) {
|
||||
|
||||
describe("TransactingMutationListener", function () {
|
||||
var mockTopic,
|
||||
mockMutationTopic,
|
||||
mockCacheService,
|
||||
mockTransactionService,
|
||||
mockDomainObject,
|
||||
mockModel,
|
||||
mockPersistence;
|
||||
|
||||
beforeEach(function () {
|
||||
mockTopic = jasmine.createSpy('topic');
|
||||
mockMutationTopic =
|
||||
jasmine.createSpyObj('mutation', ['listen']);
|
||||
mockCacheService =
|
||||
jasmine.createSpyObj('cacheService', [
|
||||
'put'
|
||||
]);
|
||||
mockTransactionService =
|
||||
jasmine.createSpyObj('transactionService', [
|
||||
'isActive',
|
||||
'startTransaction',
|
||||
'commit'
|
||||
]);
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getId', 'getCapability', 'getModel']
|
||||
);
|
||||
mockPersistence = jasmine.createSpyObj(
|
||||
'persistence',
|
||||
['persist', 'refresh', 'persisted']
|
||||
);
|
||||
|
||||
mockTopic.and.callFake(function (t) {
|
||||
expect(t).toBe('mutation');
|
||||
|
||||
return mockMutationTopic;
|
||||
});
|
||||
|
||||
mockDomainObject.getId.and.returnValue('mockId');
|
||||
mockDomainObject.getCapability.and.callFake(function (c) {
|
||||
expect(c).toBe('persistence');
|
||||
|
||||
return mockPersistence;
|
||||
});
|
||||
mockModel = {};
|
||||
mockDomainObject.getModel.and.returnValue(mockModel);
|
||||
|
||||
mockPersistence.persisted.and.returnValue(true);
|
||||
|
||||
return new TransactingMutationListener(
|
||||
mockTopic,
|
||||
mockTransactionService,
|
||||
mockCacheService
|
||||
);
|
||||
});
|
||||
|
||||
it("listens for mutation", function () {
|
||||
expect(mockMutationTopic.listen)
|
||||
.toHaveBeenCalledWith(jasmine.any(Function));
|
||||
});
|
||||
|
||||
it("calls persist if the model has changed", function () {
|
||||
mockModel.persisted = Date.now();
|
||||
|
||||
//Mark the model dirty by setting the mutated date later than the last persisted date.
|
||||
mockModel.modified = mockModel.persisted + 1;
|
||||
|
||||
mockMutationTopic.listen.calls.mostRecent()
|
||||
.args[0](mockDomainObject);
|
||||
|
||||
expect(mockPersistence.persist).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("does not call persist if the model has not changed", function () {
|
||||
mockModel.persisted = Date.now();
|
||||
|
||||
mockModel.modified = mockModel.persisted;
|
||||
|
||||
mockMutationTopic.listen.calls.mostRecent()
|
||||
.args[0](mockDomainObject);
|
||||
|
||||
expect(mockPersistence.persist).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,209 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
"./src/services/TickerService",
|
||||
"./src/services/TimerService",
|
||||
"./src/controllers/TimerController",
|
||||
"./src/controllers/RefreshingController",
|
||||
"./src/actions/StartTimerAction",
|
||||
"./src/actions/RestartTimerAction",
|
||||
"./src/actions/StopTimerAction",
|
||||
"./src/actions/PauseTimerAction",
|
||||
"./res/templates/timer.html"
|
||||
], function (
|
||||
TickerService,
|
||||
TimerService,
|
||||
TimerController,
|
||||
RefreshingController,
|
||||
StartTimerAction,
|
||||
RestartTimerAction,
|
||||
StopTimerAction,
|
||||
PauseTimerAction,
|
||||
timerTemplate
|
||||
) {
|
||||
return {
|
||||
name: "platform/features/clock",
|
||||
definition: {
|
||||
"name": "Clocks/Timers",
|
||||
"descriptions": "Domain objects for displaying current & relative times.",
|
||||
"configuration": {
|
||||
"paths": {
|
||||
"moment-duration-format": "moment-duration-format"
|
||||
},
|
||||
"shim": {
|
||||
"moment-duration-format": {
|
||||
"deps": [
|
||||
"moment"
|
||||
]
|
||||
}
|
||||
}
|
||||
},
|
||||
"extensions": {
|
||||
"constants": [
|
||||
{
|
||||
"key": "CLOCK_INDICATOR_FORMAT",
|
||||
"value": "YYYY/MM/DD HH:mm:ss"
|
||||
}
|
||||
],
|
||||
"services": [
|
||||
{
|
||||
"key": "tickerService",
|
||||
"implementation": TickerService,
|
||||
"depends": [
|
||||
"$timeout",
|
||||
"now"
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "timerService",
|
||||
"implementation": TimerService,
|
||||
"depends": ["openmct"]
|
||||
}
|
||||
],
|
||||
"controllers": [
|
||||
{
|
||||
"key": "TimerController",
|
||||
"implementation": TimerController,
|
||||
"depends": [
|
||||
"$scope",
|
||||
"$window",
|
||||
"now"
|
||||
]
|
||||
},
|
||||
{
|
||||
"key": "RefreshingController",
|
||||
"implementation": RefreshingController,
|
||||
"depends": [
|
||||
"$scope",
|
||||
"tickerService"
|
||||
]
|
||||
}
|
||||
],
|
||||
"views": [
|
||||
{
|
||||
"key": "timer",
|
||||
"type": "timer",
|
||||
"editable": false,
|
||||
"template": timerTemplate
|
||||
}
|
||||
],
|
||||
"actions": [
|
||||
{
|
||||
"key": "timer.start",
|
||||
"implementation": StartTimerAction,
|
||||
"depends": [
|
||||
"now"
|
||||
],
|
||||
"category": "contextual",
|
||||
"name": "Start",
|
||||
"cssClass": "icon-play",
|
||||
"priority": "preferred"
|
||||
},
|
||||
{
|
||||
"key": "timer.pause",
|
||||
"implementation": PauseTimerAction,
|
||||
"depends": [
|
||||
"now"
|
||||
],
|
||||
"category": "contextual",
|
||||
"name": "Pause",
|
||||
"cssClass": "icon-pause",
|
||||
"priority": "preferred"
|
||||
},
|
||||
{
|
||||
"key": "timer.restart",
|
||||
"implementation": RestartTimerAction,
|
||||
"depends": [
|
||||
"now"
|
||||
],
|
||||
"category": "contextual",
|
||||
"name": "Restart at 0",
|
||||
"cssClass": "icon-refresh",
|
||||
"priority": "preferred"
|
||||
},
|
||||
{
|
||||
"key": "timer.stop",
|
||||
"implementation": StopTimerAction,
|
||||
"depends": [
|
||||
"now"
|
||||
],
|
||||
"category": "contextual",
|
||||
"name": "Stop",
|
||||
"cssClass": "icon-box-round-corners",
|
||||
"priority": "preferred"
|
||||
}
|
||||
],
|
||||
"types": [
|
||||
{
|
||||
"key": "timer",
|
||||
"name": "Timer",
|
||||
"cssClass": "icon-timer",
|
||||
"description": "A timer that counts up or down to a datetime. Timers can be started, stopped and reset whenever needed, and support a variety of display formats. Each Timer displays the same value to all users. Timers can be added to Display Layouts.",
|
||||
"priority": 100,
|
||||
"features": [
|
||||
"creation"
|
||||
],
|
||||
"properties": [
|
||||
{
|
||||
"key": "timestamp",
|
||||
"control": "datetime",
|
||||
"name": "Target"
|
||||
},
|
||||
{
|
||||
"key": "timerFormat",
|
||||
"control": "select",
|
||||
"name": "Display Format",
|
||||
"options": [
|
||||
{
|
||||
"value": "long",
|
||||
"name": "DDD hh:mm:ss"
|
||||
},
|
||||
{
|
||||
"value": "short",
|
||||
"name": "hh:mm:ss"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"model": {
|
||||
"timerFormat": "DDD hh:mm:ss"
|
||||
}
|
||||
}
|
||||
],
|
||||
"runs": [],
|
||||
"licenses": [
|
||||
{
|
||||
"name": "moment-duration-format",
|
||||
"version": "1.3.0",
|
||||
"author": "John Madhavan-Reese",
|
||||
"description": "Duration parsing/formatting",
|
||||
"website": "https://github.com/jsmreese/moment-duration-format",
|
||||
"copyright": "Copyright 2014 John Madhavan-Reese",
|
||||
"license": "license-mit",
|
||||
"link": "https://github.com/jsmreese/moment-duration-format/blob/master/LICENSE"
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
};
|
||||
});
|
@ -1,37 +0,0 @@
|
||||
<!--
|
||||
Open MCT, Copyright (c) 2009-2016, 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.
|
||||
-->
|
||||
<div class="c-timer u-style-receiver js-style-receiver is-{{timer.timerState}}" ng-controller="TimerController as timer">
|
||||
<div class="c-timer__controls">
|
||||
<button ng-click="timer.clickStopButton()"
|
||||
ng-hide="timer.timerState == 'stopped'"
|
||||
title="Reset"
|
||||
class="c-timer__ctrl-reset c-icon-button c-icon-button--major icon-reset"></button>
|
||||
<button ng-click="timer.clickButton()"
|
||||
title="{{timer.buttonText()}}"
|
||||
class="c-timer__ctrl-pause-play c-icon-button c-icon-button--major {{timer.buttonCssClass()}}"></button>
|
||||
</div>
|
||||
<div class="c-timer__direction {{timer.signClass()}}"
|
||||
ng-hide="!timer.signClass()"></div>
|
||||
<div class="c-timer__value">{{timer.text() || "--:--:--"}}
|
||||
</div>
|
||||
<span class="c-timer__ng-controller u-contents" ng-controller="RefreshingController"></span>
|
||||
</div>
|
@ -1,70 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Implements the "Pause" action for timers.
|
||||
*
|
||||
* Sets the reference pausedTime in a timer to the current
|
||||
* time, such that it stops counting up.
|
||||
*
|
||||
* @implements {Action}
|
||||
* @memberof platform/features/clock
|
||||
* @constructor
|
||||
* @param {Function} now a function which returns the current
|
||||
* time (typically wrapping `Date.now`)
|
||||
* @param {ActionContext} context the context for this action
|
||||
*/
|
||||
function PauseTimerAction(now, context) {
|
||||
this.domainObject = context.domainObject;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
PauseTimerAction.appliesTo = function (context) {
|
||||
var model =
|
||||
(context.domainObject && context.domainObject.getModel())
|
||||
|| {};
|
||||
|
||||
// We show this variant for timers which have
|
||||
// a target time, or is in a playing state.
|
||||
return model.type === 'timer'
|
||||
&& model.timerState === 'started';
|
||||
};
|
||||
|
||||
PauseTimerAction.prototype.perform = function () {
|
||||
var domainObject = this.domainObject,
|
||||
now = this.now;
|
||||
|
||||
function updateModel(model) {
|
||||
model.timerState = 'paused';
|
||||
model.pausedTime = now();
|
||||
}
|
||||
|
||||
return domainObject.useCapability('mutation', updateModel);
|
||||
};
|
||||
|
||||
return PauseTimerAction;
|
||||
}
|
||||
);
|
@ -1,70 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Implements the "Restart at 0" action.
|
||||
*
|
||||
* Behaves the same as (and delegates functionality to)
|
||||
* the "Start" action.
|
||||
*
|
||||
* @implements {Action}
|
||||
* @memberof platform/features/clock
|
||||
* @constructor
|
||||
* @param {Function} now a function which returns the current
|
||||
* time (typically wrapping `Date.now`)
|
||||
* @param {ActionContext} context the context for this action
|
||||
*/
|
||||
function RestartTimerAction(now, context) {
|
||||
this.domainObject = context.domainObject;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
RestartTimerAction.appliesTo = function (context) {
|
||||
var model =
|
||||
(context.domainObject && context.domainObject.getModel())
|
||||
|| {};
|
||||
|
||||
// We show this variant for timers which already have a target time.
|
||||
return model.type === 'timer'
|
||||
&& model.timerState !== 'stopped';
|
||||
};
|
||||
|
||||
RestartTimerAction.prototype.perform = function () {
|
||||
var domainObject = this.domainObject,
|
||||
now = this.now;
|
||||
|
||||
function updateModel(model) {
|
||||
model.timestamp = now();
|
||||
model.timerState = 'started';
|
||||
model.pausedTime = undefined;
|
||||
}
|
||||
|
||||
return domainObject.useCapability('mutation', updateModel);
|
||||
};
|
||||
|
||||
return RestartTimerAction;
|
||||
}
|
||||
);
|
@ -1,78 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Implements the "Start" action for timers.
|
||||
*
|
||||
* Sets the reference timestamp in a timer to the current
|
||||
* time, such that it begins counting up.
|
||||
*
|
||||
* @implements {Action}
|
||||
* @memberof platform/features/clock
|
||||
* @constructor
|
||||
* @param {Function} now a function which returns the current
|
||||
* time (typically wrapping `Date.now`)
|
||||
* @param {ActionContext} context the context for this action
|
||||
*/
|
||||
function StartTimerAction(now, context) {
|
||||
this.domainObject = context.domainObject;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
StartTimerAction.appliesTo = function (context) {
|
||||
var model =
|
||||
(context.domainObject && context.domainObject.getModel())
|
||||
|| {};
|
||||
|
||||
// We show this variant for timers which do not yet have
|
||||
// a target time.
|
||||
return model.type === 'timer'
|
||||
&& model.timerState !== 'started';
|
||||
};
|
||||
|
||||
StartTimerAction.prototype.perform = function () {
|
||||
var domainObject = this.domainObject,
|
||||
now = this.now;
|
||||
|
||||
function updateModel(model) {
|
||||
//if we are resuming
|
||||
if (model.pausedTime) {
|
||||
var timeShift = now() - model.pausedTime;
|
||||
model.timestamp = model.timestamp + timeShift;
|
||||
} else {
|
||||
model.timestamp = now();
|
||||
}
|
||||
|
||||
model.timerState = 'started';
|
||||
model.pausedTime = undefined;
|
||||
}
|
||||
|
||||
return domainObject.useCapability('mutation', updateModel);
|
||||
};
|
||||
|
||||
return StartTimerAction;
|
||||
}
|
||||
);
|
@ -1,70 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Implements the "Stop" action for timers.
|
||||
*
|
||||
* Sets the reference timestamp in a timer undefined,
|
||||
* such that it is reset and makes no movements.
|
||||
*
|
||||
* @implements {Action}
|
||||
* @memberof platform/features/clock
|
||||
* @constructor
|
||||
* @param {Function} now a function which returns the current
|
||||
* time (typically wrapping `Date.now`)
|
||||
* @param {ActionContext} context the context for this action
|
||||
*/
|
||||
function StopTimerAction(now, context) {
|
||||
this.domainObject = context.domainObject;
|
||||
this.now = now;
|
||||
}
|
||||
|
||||
StopTimerAction.appliesTo = function (context) {
|
||||
var model =
|
||||
(context.domainObject && context.domainObject.getModel())
|
||||
|| {};
|
||||
|
||||
// We show this variant for timers which do not yet have
|
||||
// a target time.
|
||||
return model.type === 'timer'
|
||||
&& model.timerState !== 'stopped';
|
||||
};
|
||||
|
||||
StopTimerAction.prototype.perform = function () {
|
||||
var domainObject = this.domainObject;
|
||||
|
||||
function updateModel(model) {
|
||||
model.timestamp = undefined;
|
||||
model.timerState = 'stopped';
|
||||
model.pausedTime = undefined;
|
||||
}
|
||||
|
||||
return domainObject.useCapability('mutation', updateModel);
|
||||
};
|
||||
|
||||
return StopTimerAction;
|
||||
}
|
||||
);
|
@ -1,55 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Continually refreshes the represented domain object.
|
||||
*
|
||||
* This is a short-term workaround to assure Timer views stay
|
||||
* up-to-date; should be replaced by a global auto-refresh.
|
||||
*
|
||||
* @constructor
|
||||
* @memberof platform/features/clock
|
||||
* @param {angular.Scope} $scope the Angular scope
|
||||
* @param {platform/features/clock.TickerService} tickerService
|
||||
* a service used to align behavior with clock ticks
|
||||
*/
|
||||
function RefreshingController($scope, tickerService) {
|
||||
var unlisten;
|
||||
|
||||
function triggerRefresh() {
|
||||
var persistence = $scope.domainObject
|
||||
&& $scope.domainObject.getCapability('persistence');
|
||||
|
||||
return persistence && persistence.refresh();
|
||||
}
|
||||
|
||||
unlisten = tickerService.listen(triggerRefresh);
|
||||
$scope.$on('$destroy', unlisten);
|
||||
}
|
||||
|
||||
return RefreshingController;
|
||||
}
|
||||
);
|
@ -1,239 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
['./TimerFormatter'],
|
||||
function (TimerFormatter) {
|
||||
|
||||
var FORMATTER = new TimerFormatter();
|
||||
|
||||
/**
|
||||
* Controller for views of a Timer domain object.
|
||||
*
|
||||
* @constructor
|
||||
* @memberof platform/features/clock
|
||||
* @param {angular.Scope} $scope the Angular scope
|
||||
* @param $window Angular-provided window object
|
||||
* @param {Function} now a function which returns the current
|
||||
* time (typically wrapping `Date.now`)
|
||||
*/
|
||||
function TimerController($scope, $window, now) {
|
||||
var formatter,
|
||||
active = true,
|
||||
relativeTimestamp,
|
||||
lastTimestamp,
|
||||
relativeTimerState,
|
||||
self = this;
|
||||
|
||||
function update() {
|
||||
var timeDelta = lastTimestamp - relativeTimestamp;
|
||||
|
||||
if (formatter && !isNaN(timeDelta)) {
|
||||
self.textValue = formatter(timeDelta);
|
||||
self.signValue = timeDelta < 0 ? "-"
|
||||
: timeDelta >= 1000 ? "+" : "";
|
||||
self.signCssClass = timeDelta < 0 ? "icon-minus"
|
||||
: timeDelta >= 1000 ? "icon-plus" : "";
|
||||
} else {
|
||||
self.textValue = "";
|
||||
self.signValue = "";
|
||||
self.signCssClass = "";
|
||||
}
|
||||
}
|
||||
|
||||
function updateFormat(key) {
|
||||
formatter = FORMATTER[key] || FORMATTER.long;
|
||||
}
|
||||
|
||||
function updateTimestamp(timestamp) {
|
||||
relativeTimestamp = timestamp;
|
||||
}
|
||||
|
||||
function updateTimerState(timerState) {
|
||||
self.timerState = relativeTimerState = timerState;
|
||||
}
|
||||
|
||||
function updateActions(actionCapability, actionKey) {
|
||||
self.relevantAction = actionCapability
|
||||
&& actionCapability.getActions(actionKey)[0];
|
||||
|
||||
self.stopAction = relativeTimerState !== 'stopped'
|
||||
? actionCapability && actionCapability.getActions('timer.stop')[0] : undefined;
|
||||
|
||||
}
|
||||
|
||||
function isPaused() {
|
||||
return relativeTimerState === 'paused';
|
||||
}
|
||||
|
||||
function handleLegacyTimer(model) {
|
||||
if (model.timerState === undefined) {
|
||||
model.timerState = model.timestamp === undefined
|
||||
? 'stopped' : 'started';
|
||||
}
|
||||
}
|
||||
|
||||
function updateObject(domainObject) {
|
||||
var model = domainObject.getModel();
|
||||
handleLegacyTimer(model);
|
||||
|
||||
var timestamp = model.timestamp,
|
||||
formatKey = model.timerFormat,
|
||||
timerState = model.timerState,
|
||||
actionCapability = domainObject.getCapability('action'),
|
||||
actionKey = (timerState !== 'started')
|
||||
? 'timer.start' : 'timer.pause';
|
||||
|
||||
updateFormat(formatKey);
|
||||
updateTimestamp(timestamp);
|
||||
updateTimerState(timerState);
|
||||
updateActions(actionCapability, actionKey);
|
||||
|
||||
//if paused on startup show last known position
|
||||
if (isPaused() && !lastTimestamp) {
|
||||
lastTimestamp = model.pausedTime;
|
||||
}
|
||||
|
||||
update();
|
||||
}
|
||||
|
||||
function handleObjectChange(domainObject) {
|
||||
if (domainObject) {
|
||||
updateObject(domainObject);
|
||||
}
|
||||
}
|
||||
|
||||
function handleModification() {
|
||||
handleObjectChange($scope.domainObject);
|
||||
}
|
||||
|
||||
function tick() {
|
||||
var lastSign = self.signValue,
|
||||
lastText = self.textValue;
|
||||
|
||||
if (!isPaused()) {
|
||||
lastTimestamp = now();
|
||||
update();
|
||||
}
|
||||
|
||||
if (relativeTimerState === undefined) {
|
||||
handleModification();
|
||||
}
|
||||
|
||||
// We're running in an animation frame, not in a digest cycle.
|
||||
// We need to trigger a digest cycle if our displayable data
|
||||
// changes.
|
||||
if (lastSign !== self.signValue || lastText !== self.textValue) {
|
||||
$scope.$apply();
|
||||
}
|
||||
|
||||
if (active) {
|
||||
$window.requestAnimationFrame(tick);
|
||||
}
|
||||
}
|
||||
|
||||
$window.requestAnimationFrame(tick);
|
||||
|
||||
// Pull in the timer format from the domain object model
|
||||
$scope.$watch('domainObject', handleObjectChange);
|
||||
$scope.$watch('model.modified', handleModification);
|
||||
|
||||
// When the scope is destroyed, stop requesting anim. frames
|
||||
$scope.$on('$destroy', function () {
|
||||
active = false;
|
||||
});
|
||||
|
||||
this.$scope = $scope;
|
||||
this.signValue = '';
|
||||
this.textValue = '';
|
||||
this.updateObject = updateObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the CSS class to display the right icon
|
||||
* for the start/pause button.
|
||||
* @returns {string} cssclass to display
|
||||
*/
|
||||
TimerController.prototype.buttonCssClass = function () {
|
||||
return this.relevantAction
|
||||
? this.relevantAction.getMetadata().cssClass : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the text to show for the start/pause button
|
||||
* (e.g. in a tooltip)
|
||||
* @returns {string} name of the action
|
||||
*/
|
||||
TimerController.prototype.buttonText = function () {
|
||||
return this.relevantAction
|
||||
? this.relevantAction.getMetadata().name : "";
|
||||
};
|
||||
|
||||
/**
|
||||
* Perform the action associated with the start/pause button.
|
||||
*/
|
||||
TimerController.prototype.clickButton = function () {
|
||||
if (this.relevantAction) {
|
||||
this.relevantAction.perform();
|
||||
this.updateObject(this.$scope.domainObject);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Perform the action associated with the stop button.
|
||||
*/
|
||||
TimerController.prototype.clickStopButton = function () {
|
||||
if (this.stopAction) {
|
||||
this.stopAction.perform();
|
||||
this.updateObject(this.$scope.domainObject);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the sign (+ or -) of the current timer value, as
|
||||
* displayable text.
|
||||
* @returns {string} sign of the current timer value
|
||||
*/
|
||||
TimerController.prototype.sign = function () {
|
||||
return this.signValue;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the sign (+ or -) of the current timer value, as
|
||||
* a CSS class.
|
||||
* @returns {string} sign of the current timer value
|
||||
*/
|
||||
TimerController.prototype.signClass = function () {
|
||||
return this.signCssClass;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the text to display for the current timer value.
|
||||
* @returns {string} current timer value
|
||||
*/
|
||||
TimerController.prototype.text = function () {
|
||||
return this.textValue;
|
||||
};
|
||||
|
||||
return TimerController;
|
||||
}
|
||||
);
|
@ -1,73 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
['moment', 'moment-duration-format'],
|
||||
function (moment) {
|
||||
|
||||
var SHORT_FORMAT = "HH:mm:ss",
|
||||
LONG_FORMAT = "d[D] HH:mm:ss";
|
||||
|
||||
/**
|
||||
* Provides formatting functions for Timers.
|
||||
*
|
||||
* Display formats for timers are a little different from what
|
||||
* moment.js provides, so we have custom logic here. This specifically
|
||||
* supports `TimerController`.
|
||||
*
|
||||
* @constructor
|
||||
* @memberof platform/features/clock
|
||||
*/
|
||||
function TimerFormatter() {
|
||||
}
|
||||
|
||||
// Round this timestamp down to the second boundary
|
||||
// (e.g. 1124ms goes down to 1000ms, -2400ms goes down to -3000ms)
|
||||
function toWholeSeconds(duration) {
|
||||
return Math.abs(Math.floor(duration / 1000) * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a duration for display, using the short form.
|
||||
* (e.g. 03:33:11)
|
||||
* @param {number} duration the duration, in milliseconds
|
||||
* @param {boolean} sign true if positive
|
||||
*/
|
||||
TimerFormatter.prototype.short = function (duration) {
|
||||
return moment.duration(toWholeSeconds(duration), 'ms')
|
||||
.format(SHORT_FORMAT, { trim: false });
|
||||
};
|
||||
|
||||
/**
|
||||
* Format a duration for display, using the long form.
|
||||
* (e.g. 0d 03:33:11)
|
||||
* @param {number} duration the duration, in milliseconds
|
||||
* @param {boolean} sign true if positive
|
||||
*/
|
||||
TimerFormatter.prototype.long = function (duration) {
|
||||
return moment.duration(toWholeSeconds(duration), 'ms')
|
||||
.format(LONG_FORMAT, { trim: false });
|
||||
};
|
||||
|
||||
return TimerFormatter;
|
||||
}
|
||||
);
|
@ -1,87 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
[],
|
||||
function () {
|
||||
|
||||
/**
|
||||
* Calls functions every second, as close to the actual second
|
||||
* tick as is feasible.
|
||||
* @constructor
|
||||
* @memberof platform/features/clock
|
||||
* @param $timeout Angular's $timeout
|
||||
* @param {Function} now function to provide the current time in ms
|
||||
*/
|
||||
function TickerService($timeout, now) {
|
||||
var self = this;
|
||||
|
||||
function tick() {
|
||||
var timestamp = now(),
|
||||
millis = timestamp % 1000;
|
||||
|
||||
// Only update callbacks if a second has actually passed.
|
||||
if (timestamp >= self.last + 1000) {
|
||||
self.callbacks.forEach(function (callback) {
|
||||
callback(timestamp);
|
||||
});
|
||||
self.last = timestamp - millis;
|
||||
}
|
||||
|
||||
// Try to update at exactly the next second
|
||||
$timeout(tick, 1000 - millis, true);
|
||||
}
|
||||
|
||||
tick();
|
||||
|
||||
this.callbacks = [];
|
||||
this.last = now() - 1000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for clock ticks. The provided callback will
|
||||
* be invoked with the current timestamp (in milliseconds
|
||||
* since Jan 1 1970) at regular intervals, as near to the
|
||||
* second boundary as possible.
|
||||
*
|
||||
* @param {Function} callback callback to invoke
|
||||
* @returns {Function} a function to unregister this listener
|
||||
*/
|
||||
TickerService.prototype.listen = function (callback) {
|
||||
var self = this;
|
||||
|
||||
self.callbacks.push(callback);
|
||||
|
||||
// Provide immediate feedback
|
||||
callback(this.last);
|
||||
|
||||
// Provide a deregistration function
|
||||
return function () {
|
||||
self.callbacks = self.callbacks.filter(function (cb) {
|
||||
return cb !== callback;
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
return TickerService;
|
||||
}
|
||||
);
|
@ -1,113 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(['EventEmitter'], function (EventEmitter) {
|
||||
|
||||
/**
|
||||
* Tracks the currently-followed Timer object. Used by
|
||||
* timelines et al to synchronize to a particular timer.
|
||||
*
|
||||
* The TimerService emits `change` events when the active timer
|
||||
* is changed.
|
||||
*/
|
||||
function TimerService(openmct) {
|
||||
EventEmitter.apply(this);
|
||||
this.time = openmct.time;
|
||||
this.objects = openmct.objects;
|
||||
}
|
||||
|
||||
TimerService.prototype = Object.create(EventEmitter.prototype);
|
||||
|
||||
/**
|
||||
* Set (or clear, if `timer` is undefined) the currently active timer.
|
||||
* @param {DomainObject} timer the new active timer
|
||||
* @emits change
|
||||
*/
|
||||
TimerService.prototype.setTimer = function (timer) {
|
||||
this.timer = timer;
|
||||
this.emit('change', timer);
|
||||
|
||||
if (this.stopObserving) {
|
||||
this.stopObserving();
|
||||
delete this.stopObserving;
|
||||
}
|
||||
|
||||
if (timer) {
|
||||
this.stopObserving =
|
||||
this.objects.observe(timer, '*', this.setTimer.bind(this));
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the currently active timer.
|
||||
* @return {DomainObject} the active timer
|
||||
* @emits change
|
||||
*/
|
||||
TimerService.prototype.getTimer = function () {
|
||||
return this.timer;
|
||||
};
|
||||
|
||||
/**
|
||||
* Check if there is a currently active timer.
|
||||
* @return {boolean} true if there is a timer
|
||||
*/
|
||||
TimerService.prototype.hasTimer = function () {
|
||||
return Boolean(this.timer);
|
||||
};
|
||||
|
||||
/**
|
||||
* Convert the provided timestamp to milliseconds relative to
|
||||
* the active timer.
|
||||
* @return {number} milliseconds since timer start
|
||||
*/
|
||||
TimerService.prototype.convert = function (timestamp) {
|
||||
var clock = this.time.clock();
|
||||
var canConvert = this.hasTimer()
|
||||
&& Boolean(clock)
|
||||
&& this.timer.timerState !== 'stopped';
|
||||
|
||||
if (!canConvert) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
var now = clock.currentValue();
|
||||
var delta = this.timer.timerState === 'paused'
|
||||
? now - this.timer.pausedTime : 0;
|
||||
var epoch = this.timer.timestamp;
|
||||
|
||||
return timestamp - epoch - delta;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the value of the active clock, adjusted to be relative to the active
|
||||
* timer. If there is no clock or no active timer, this will return
|
||||
* `undefined`.
|
||||
* @return {number} milliseconds since the start of the active timer
|
||||
*/
|
||||
TimerService.prototype.now = function () {
|
||||
var clock = this.time.clock();
|
||||
|
||||
return clock && this.convert(clock.currentValue());
|
||||
};
|
||||
|
||||
return TimerService;
|
||||
});
|
@ -1,106 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/actions/PauseTimerAction"],
|
||||
function (PauseTimerAction) {
|
||||
|
||||
describe("A timer's Pause action", function () {
|
||||
var mockNow,
|
||||
mockDomainObject,
|
||||
testModel,
|
||||
testContext,
|
||||
action;
|
||||
|
||||
function asPromise(value) {
|
||||
return (value || {}).then ? value : {
|
||||
then: function (callback) {
|
||||
return asPromise(callback(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function testState(type, timerState, timestamp, expected) {
|
||||
testModel.type = type;
|
||||
testModel.timerState = timerState;
|
||||
testModel.timestamp = timestamp;
|
||||
|
||||
if (expected) {
|
||||
expect(PauseTimerAction.appliesTo(testContext)).toBeTruthy();
|
||||
} else {
|
||||
expect(PauseTimerAction.appliesTo(testContext)).toBeFalsy();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockNow = jasmine.createSpy('now');
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability', 'useCapability', 'getModel']
|
||||
);
|
||||
|
||||
mockDomainObject.useCapability.and.callFake(function (c, v) {
|
||||
if (c === 'mutation') {
|
||||
testModel = v(testModel) || testModel;
|
||||
|
||||
return asPromise(true);
|
||||
}
|
||||
});
|
||||
mockDomainObject.getModel.and.callFake(function () {
|
||||
return testModel;
|
||||
});
|
||||
|
||||
testModel = {};
|
||||
testContext = {domainObject: mockDomainObject};
|
||||
|
||||
action = new PauseTimerAction(mockNow, testContext);
|
||||
});
|
||||
|
||||
it("updates the model with a timerState", function () {
|
||||
testModel.timerState = 'started';
|
||||
action.perform();
|
||||
expect(testModel.timerState).toEqual('paused');
|
||||
});
|
||||
|
||||
it("updates the model with a pausedTime", function () {
|
||||
testModel.pausedTime = undefined;
|
||||
mockNow.and.returnValue(12000);
|
||||
action.perform();
|
||||
expect(testModel.pausedTime).toEqual(12000);
|
||||
});
|
||||
|
||||
it("applies only to timers in a playing state", function () {
|
||||
//in a stopped state
|
||||
testState('timer', 'stopped', undefined, false);
|
||||
|
||||
//in a paused state
|
||||
testState('timer', 'paused', 12000, false);
|
||||
|
||||
//in a playing state
|
||||
testState('timer', 'started', 12000, true);
|
||||
|
||||
//not a timer
|
||||
testState('clock', 'started', 12000, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,112 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/actions/RestartTimerAction"],
|
||||
function (RestartTimerAction) {
|
||||
|
||||
describe("A timer's restart action", function () {
|
||||
var mockNow,
|
||||
mockDomainObject,
|
||||
testModel,
|
||||
testContext,
|
||||
action;
|
||||
|
||||
function asPromise(value) {
|
||||
return (value || {}).then ? value : {
|
||||
then: function (callback) {
|
||||
return asPromise(callback(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function testState(type, timerState, timestamp, expected) {
|
||||
testModel.type = type;
|
||||
testModel.timerState = timerState;
|
||||
testModel.timestamp = timestamp;
|
||||
|
||||
if (expected) {
|
||||
expect(RestartTimerAction.appliesTo(testContext)).toBeTruthy();
|
||||
} else {
|
||||
expect(RestartTimerAction.appliesTo(testContext)).toBeFalsy();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockNow = jasmine.createSpy('now');
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability', 'useCapability', 'getModel']
|
||||
);
|
||||
|
||||
mockDomainObject.useCapability.and.callFake(function (c, v) {
|
||||
if (c === 'mutation') {
|
||||
testModel = v(testModel) || testModel;
|
||||
|
||||
return asPromise(true);
|
||||
}
|
||||
});
|
||||
mockDomainObject.getModel.and.callFake(function () {
|
||||
return testModel;
|
||||
});
|
||||
|
||||
testModel = {};
|
||||
testContext = { domainObject: mockDomainObject };
|
||||
|
||||
action = new RestartTimerAction(mockNow, testContext);
|
||||
});
|
||||
|
||||
it("updates the model with a timestamp", function () {
|
||||
testModel.pausedTime = 12000;
|
||||
mockNow.and.returnValue(12000);
|
||||
action.perform();
|
||||
expect(testModel.timestamp).toEqual(12000);
|
||||
});
|
||||
|
||||
it("updates the model with a pausedTime", function () {
|
||||
testModel.pausedTime = 12000;
|
||||
action.perform();
|
||||
expect(testModel.pausedTime).toEqual(undefined);
|
||||
});
|
||||
|
||||
it("updates the model with a timerState", function () {
|
||||
testModel.timerState = 'stopped';
|
||||
action.perform();
|
||||
expect(testModel.timerState).toEqual('started');
|
||||
});
|
||||
|
||||
it("applies only to timers in a non-stopped state", function () {
|
||||
//in a stopped state
|
||||
testState('timer', 'stopped', undefined, false);
|
||||
|
||||
//in a paused state
|
||||
testState('timer', 'paused', 12000, true);
|
||||
|
||||
//in a playing state
|
||||
testState('timer', 'started', 12000, true);
|
||||
|
||||
//not a timer
|
||||
testState('clock', 'paused', 12000, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,111 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/actions/StartTimerAction"],
|
||||
function (StartTimerAction) {
|
||||
|
||||
describe("A timer's start action", function () {
|
||||
var mockNow,
|
||||
mockDomainObject,
|
||||
testModel,
|
||||
testContext,
|
||||
action;
|
||||
|
||||
function asPromise(value) {
|
||||
return (value || {}).then ? value : {
|
||||
then: function (callback) {
|
||||
return asPromise(callback(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function testState(type, timerState, timestamp, expected) {
|
||||
testModel.type = type;
|
||||
testModel.timerState = timerState;
|
||||
testModel.timestamp = timestamp;
|
||||
|
||||
if (expected) {
|
||||
expect(StartTimerAction.appliesTo(testContext)).toBeTruthy();
|
||||
} else {
|
||||
expect(StartTimerAction.appliesTo(testContext)).toBeFalsy();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockNow = jasmine.createSpy('now');
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability', 'useCapability', 'getModel']
|
||||
);
|
||||
|
||||
mockDomainObject.useCapability.and.callFake(function (c, v) {
|
||||
if (c === 'mutation') {
|
||||
testModel = v(testModel) || testModel;
|
||||
|
||||
return asPromise(true);
|
||||
}
|
||||
});
|
||||
mockDomainObject.getModel.and.callFake(function () {
|
||||
return testModel;
|
||||
});
|
||||
|
||||
testModel = {};
|
||||
testContext = {domainObject: mockDomainObject};
|
||||
|
||||
action = new StartTimerAction(mockNow, testContext);
|
||||
});
|
||||
|
||||
it("updates the model with a timestamp", function () {
|
||||
mockNow.and.returnValue(12000);
|
||||
action.perform();
|
||||
expect(testModel.timestamp).toEqual(12000);
|
||||
});
|
||||
|
||||
it("updates the model with a pausedTime", function () {
|
||||
testModel.pausedTime = 12000;
|
||||
action.perform();
|
||||
expect(testModel.pausedTime).toEqual(undefined);
|
||||
});
|
||||
|
||||
it("updates the model with a timerState", function () {
|
||||
testModel.timerState = undefined;
|
||||
action.perform();
|
||||
expect(testModel.timerState).toEqual('started');
|
||||
});
|
||||
|
||||
it("applies only to timers not in a playing state", function () {
|
||||
//in a stopped state
|
||||
testState('timer', 'stopped', undefined, true);
|
||||
|
||||
//in a paused state
|
||||
testState('timer', 'paused', 12000, true);
|
||||
|
||||
//in a playing state
|
||||
testState('timer', 'started', 12000, false);
|
||||
|
||||
//not a timer
|
||||
testState('clock', 'paused', 12000, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,111 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/actions/StopTimerAction"],
|
||||
function (StopTimerAction) {
|
||||
|
||||
describe("A timer's stop action", function () {
|
||||
var mockNow,
|
||||
mockDomainObject,
|
||||
testModel,
|
||||
testContext,
|
||||
action;
|
||||
|
||||
function asPromise(value) {
|
||||
return (value || {}).then ? value : {
|
||||
then: function (callback) {
|
||||
return asPromise(callback(value));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function testState(type, timerState, timestamp, expected) {
|
||||
testModel.type = type;
|
||||
testModel.timerState = timerState;
|
||||
testModel.timestamp = timestamp;
|
||||
|
||||
if (expected) {
|
||||
expect(StopTimerAction.appliesTo(testContext)).toBeTruthy();
|
||||
} else {
|
||||
expect(StopTimerAction.appliesTo(testContext)).toBeFalsy();
|
||||
}
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockNow = jasmine.createSpy('now');
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability', 'useCapability', 'getModel']
|
||||
);
|
||||
|
||||
mockDomainObject.useCapability.and.callFake(function (c, v) {
|
||||
if (c === 'mutation') {
|
||||
testModel = v(testModel) || testModel;
|
||||
|
||||
return asPromise(true);
|
||||
}
|
||||
});
|
||||
mockDomainObject.getModel.and.callFake(function () {
|
||||
return testModel;
|
||||
});
|
||||
|
||||
testModel = {};
|
||||
testContext = {domainObject: mockDomainObject};
|
||||
|
||||
action = new StopTimerAction(mockNow, testContext);
|
||||
});
|
||||
|
||||
it("updates the model with a timestamp", function () {
|
||||
mockNow.and.returnValue(12000);
|
||||
action.perform();
|
||||
expect(testModel.timestamp).toEqual(undefined);
|
||||
});
|
||||
|
||||
it("updates the model with a pausedTime", function () {
|
||||
testModel.pausedTime = 12000;
|
||||
action.perform();
|
||||
expect(testModel.pausedTime).toEqual(undefined);
|
||||
});
|
||||
|
||||
it("updates the model with a timerState", function () {
|
||||
testModel.timerState = 'started';
|
||||
action.perform();
|
||||
expect(testModel.timerState).toEqual('stopped');
|
||||
});
|
||||
|
||||
it("applies only to timers in a non-stopped state", function () {
|
||||
//in a stopped state
|
||||
testState('timer', 'stopped', undefined, false);
|
||||
|
||||
//in a paused state
|
||||
testState('timer', 'paused', 12000, true);
|
||||
|
||||
//in a playing state
|
||||
testState('timer', 'started', 12000, true);
|
||||
|
||||
//not a timer
|
||||
testState('clock', 'paused', 12000, false);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,80 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/controllers/RefreshingController"],
|
||||
function (RefreshingController) {
|
||||
|
||||
describe("The refreshing controller", function () {
|
||||
var mockScope,
|
||||
mockTicker,
|
||||
mockUnticker,
|
||||
controller;
|
||||
|
||||
beforeEach(function () {
|
||||
mockScope = jasmine.createSpyObj('$scope', ['$on']);
|
||||
mockTicker = jasmine.createSpyObj('ticker', ['listen']);
|
||||
mockUnticker = jasmine.createSpy('unticker');
|
||||
|
||||
mockTicker.listen.and.returnValue(mockUnticker);
|
||||
|
||||
controller = new RefreshingController(mockScope, mockTicker);
|
||||
});
|
||||
|
||||
it("refreshes the represented object on every tick", function () {
|
||||
var mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability']
|
||||
),
|
||||
mockPersistence = jasmine.createSpyObj(
|
||||
'persistence',
|
||||
['persist', 'refresh']
|
||||
);
|
||||
|
||||
mockDomainObject.getCapability.and.callFake(function (c) {
|
||||
return (c === 'persistence') && mockPersistence;
|
||||
});
|
||||
|
||||
mockScope.domainObject = mockDomainObject;
|
||||
|
||||
mockTicker.listen.calls.mostRecent().args[0](12321);
|
||||
expect(mockPersistence.refresh).toHaveBeenCalled();
|
||||
expect(mockPersistence.persist).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("subscribes to clock ticks", function () {
|
||||
expect(mockTicker.listen)
|
||||
.toHaveBeenCalledWith(jasmine.any(Function));
|
||||
});
|
||||
|
||||
it("unsubscribes to ticks when destroyed", function () {
|
||||
// Make sure $destroy is being listened for...
|
||||
expect(mockScope.$on.calls.mostRecent().args[0]).toEqual('$destroy');
|
||||
expect(mockUnticker).not.toHaveBeenCalled();
|
||||
|
||||
// ...and makes sure that its listener unsubscribes from ticker
|
||||
mockScope.$on.calls.mostRecent().args[1]();
|
||||
expect(mockUnticker).toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,227 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/controllers/TimerController"],
|
||||
function (TimerController) {
|
||||
|
||||
// Wed, 03 Jun 2015 17:56:14 GMT
|
||||
var TEST_TIMESTAMP = 1433354174000;
|
||||
|
||||
describe("A timer view's controller", function () {
|
||||
var mockScope,
|
||||
mockWindow,
|
||||
mockNow,
|
||||
mockDomainObject,
|
||||
mockActionCapability,
|
||||
mockStart,
|
||||
mockPause,
|
||||
mockStop,
|
||||
testModel,
|
||||
controller;
|
||||
|
||||
function invokeWatch(expr, value) {
|
||||
mockScope.$watch.calls.all().forEach(function (call) {
|
||||
if (call.args[0] === expr) {
|
||||
call.args[1](value);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
beforeEach(function () {
|
||||
mockScope = jasmine.createSpyObj(
|
||||
'$scope',
|
||||
['$watch', '$on', '$apply']
|
||||
);
|
||||
mockWindow = jasmine.createSpyObj(
|
||||
'$window',
|
||||
['requestAnimationFrame']
|
||||
);
|
||||
mockDomainObject = jasmine.createSpyObj(
|
||||
'domainObject',
|
||||
['getCapability', 'useCapability', 'getModel']
|
||||
);
|
||||
mockActionCapability = jasmine.createSpyObj(
|
||||
'action',
|
||||
['getActions']
|
||||
);
|
||||
mockStart = jasmine.createSpyObj(
|
||||
'start',
|
||||
['getMetadata', 'perform']
|
||||
);
|
||||
mockPause = jasmine.createSpyObj(
|
||||
'paused',
|
||||
['getMetadata', 'perform']
|
||||
);
|
||||
mockStop = jasmine.createSpyObj(
|
||||
'stopped',
|
||||
['getMetadata', 'perform']
|
||||
);
|
||||
mockNow = jasmine.createSpy('now');
|
||||
|
||||
mockDomainObject.getCapability.and.callFake(function (c) {
|
||||
return (c === 'action') && mockActionCapability;
|
||||
});
|
||||
mockDomainObject.getModel.and.callFake(function () {
|
||||
return testModel;
|
||||
});
|
||||
mockActionCapability.getActions.and.callFake(function (k) {
|
||||
return [{
|
||||
'timer.start': mockStart,
|
||||
'timer.pause': mockPause,
|
||||
'timer.stop': mockStop
|
||||
}[k]];
|
||||
});
|
||||
|
||||
mockStart.getMetadata.and.returnValue({
|
||||
cssClass: "icon-play",
|
||||
name: "Start"
|
||||
});
|
||||
mockPause.getMetadata.and.returnValue({
|
||||
cssClass: "icon-pause",
|
||||
name: "Pause"
|
||||
});
|
||||
mockStop.getMetadata.and.returnValue({
|
||||
cssClass: "icon-box-round-corners",
|
||||
name: "Stop"
|
||||
});
|
||||
mockScope.domainObject = mockDomainObject;
|
||||
|
||||
testModel = {};
|
||||
|
||||
controller = new TimerController(mockScope, mockWindow, mockNow);
|
||||
});
|
||||
|
||||
it("watches for the domain object in view", function () {
|
||||
expect(mockScope.$watch).toHaveBeenCalledWith(
|
||||
"domainObject",
|
||||
jasmine.any(Function)
|
||||
);
|
||||
});
|
||||
|
||||
it("watches for domain object modifications", function () {
|
||||
expect(mockScope.$watch).toHaveBeenCalledWith(
|
||||
"model.modified",
|
||||
jasmine.any(Function)
|
||||
);
|
||||
});
|
||||
|
||||
it("updates on a timer", function () {
|
||||
expect(mockWindow.requestAnimationFrame)
|
||||
.toHaveBeenCalledWith(jasmine.any(Function));
|
||||
});
|
||||
|
||||
it("displays nothing when there is no target", function () {
|
||||
// Notify that domain object is available via scope
|
||||
invokeWatch('domainObject', mockDomainObject);
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(controller.sign()).toEqual("");
|
||||
expect(controller.signClass()).toEqual("");
|
||||
expect(controller.text()).toEqual("");
|
||||
});
|
||||
|
||||
it("formats time to display relative to target", function () {
|
||||
testModel.timestamp = TEST_TIMESTAMP;
|
||||
testModel.timerFormat = 'long';
|
||||
// Notify that domain object is available via scope
|
||||
invokeWatch('domainObject', mockDomainObject);
|
||||
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP + 121000);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(controller.sign()).toEqual("+");
|
||||
expect(controller.signClass()).toEqual("icon-plus");
|
||||
expect(controller.text()).toEqual("0D 00:02:01");
|
||||
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP - 121000);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(controller.sign()).toEqual("-");
|
||||
expect(controller.signClass()).toEqual("icon-minus");
|
||||
expect(controller.text()).toEqual("0D 00:02:01");
|
||||
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(controller.sign()).toEqual("");
|
||||
expect(controller.signClass()).toEqual("");
|
||||
expect(controller.text()).toEqual("0D 00:00:00");
|
||||
});
|
||||
|
||||
it("shows cssClass & name for the applicable start/pause action", function () {
|
||||
invokeWatch('domainObject', mockDomainObject);
|
||||
expect(controller.buttonCssClass()).toEqual("icon-play");
|
||||
expect(controller.buttonText()).toEqual("Start");
|
||||
|
||||
testModel.timestamp = 12321;
|
||||
testModel.timerState = 'started';
|
||||
invokeWatch('model.modified', 1);
|
||||
expect(controller.buttonCssClass()).toEqual("icon-pause");
|
||||
expect(controller.buttonText()).toEqual("Pause");
|
||||
});
|
||||
|
||||
it("performs correct start/pause/stop action on click", function () {
|
||||
//test start
|
||||
invokeWatch('domainObject', mockDomainObject);
|
||||
expect(mockStart.perform).not.toHaveBeenCalled();
|
||||
controller.clickButton();
|
||||
expect(mockStart.perform).toHaveBeenCalled();
|
||||
|
||||
//test pause
|
||||
testModel.timestamp = 12321;
|
||||
testModel.timerState = 'started';
|
||||
invokeWatch('model.modified', 1);
|
||||
expect(mockPause.perform).not.toHaveBeenCalled();
|
||||
controller.clickButton();
|
||||
expect(mockPause.perform).toHaveBeenCalled();
|
||||
|
||||
//test stop
|
||||
expect(mockStop.perform).not.toHaveBeenCalled();
|
||||
controller.clickStopButton();
|
||||
expect(mockStop.perform).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("stops requesting animation frames when destroyed", function () {
|
||||
var initialCount = mockWindow.requestAnimationFrame.calls.count();
|
||||
|
||||
// First, check that normally new frames keep getting requested
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(mockWindow.requestAnimationFrame.calls.count())
|
||||
.toEqual(initialCount + 1);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(mockWindow.requestAnimationFrame.calls.count())
|
||||
.toEqual(initialCount + 2);
|
||||
|
||||
// Now, verify that it stops after $destroy
|
||||
expect(mockScope.$on.calls.mostRecent().args[0])
|
||||
.toEqual('$destroy');
|
||||
mockScope.$on.calls.mostRecent().args[1]();
|
||||
|
||||
// Frames should no longer get requested
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(mockWindow.requestAnimationFrame.calls.count())
|
||||
.toEqual(initialCount + 2);
|
||||
mockWindow.requestAnimationFrame.calls.mostRecent().args[0]();
|
||||
expect(mockWindow.requestAnimationFrame.calls.count())
|
||||
.toEqual(initialCount + 2);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,111 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/controllers/TimerFormatter"],
|
||||
function (TimerFormatter) {
|
||||
|
||||
var MS_IN_SEC = 1000,
|
||||
MS_IN_MIN = MS_IN_SEC * 60,
|
||||
MS_IN_HR = MS_IN_MIN * 60,
|
||||
MS_IN_DAY = MS_IN_HR * 24;
|
||||
|
||||
describe("The timer value formatter", function () {
|
||||
var formatter = new TimerFormatter();
|
||||
|
||||
function sum(a, b) {
|
||||
return a + b;
|
||||
}
|
||||
|
||||
function toDuration(days, hours, mins, secs) {
|
||||
return [
|
||||
days * MS_IN_DAY,
|
||||
hours * MS_IN_HR,
|
||||
mins * MS_IN_MIN,
|
||||
secs * MS_IN_SEC
|
||||
].reduce(sum, 0);
|
||||
}
|
||||
|
||||
it("formats short-form values (no days)", function () {
|
||||
expect(formatter.short(toDuration(0, 123, 2, 3) + 123))
|
||||
.toEqual("123:02:03");
|
||||
});
|
||||
|
||||
it("formats negative short-form values (no days)", function () {
|
||||
expect(formatter.short(-toDuration(0, 123, 2, 3) + 123))
|
||||
.toEqual("123:02:03");
|
||||
});
|
||||
|
||||
it("formats long-form values (with days)", function () {
|
||||
expect(formatter.long(toDuration(0, 123, 2, 3) + 123))
|
||||
.toEqual("5D 03:02:03");
|
||||
});
|
||||
|
||||
it("formats negative long-form values (no days)", function () {
|
||||
expect(formatter.long(-toDuration(0, 123, 2, 3) + 123))
|
||||
.toEqual("5D 03:02:03");
|
||||
});
|
||||
|
||||
it("rounds seconds down for positive durations", function () {
|
||||
expect(formatter.short(MS_IN_SEC + 600))
|
||||
.toEqual("00:00:01");
|
||||
});
|
||||
|
||||
it("rounds seconds up for negative durations", function () {
|
||||
expect(formatter.short(-MS_IN_SEC - 600))
|
||||
.toEqual("00:00:02");
|
||||
});
|
||||
|
||||
it("short-formats correctly around negative time borders", function () {
|
||||
expect(formatter.short(-1)).toEqual("00:00:01");
|
||||
expect(formatter.short(-1000)).toEqual("00:00:01");
|
||||
expect(formatter.short(-1001)).toEqual("00:00:02");
|
||||
expect(formatter.short(-2000)).toEqual("00:00:02");
|
||||
expect(formatter.short(-59001)).toEqual("00:01:00");
|
||||
expect(formatter.short(-60000)).toEqual("00:01:00");
|
||||
|
||||
expect(formatter.short(-MS_IN_HR + 999)).toEqual("01:00:00");
|
||||
expect(formatter.short(-MS_IN_HR)).toEqual("01:00:00");
|
||||
});
|
||||
|
||||
it("differentiates between values around zero", function () {
|
||||
// These are more than 1000 ms apart so should not appear
|
||||
// as the same second
|
||||
expect(formatter.short(-999))
|
||||
.not.toEqual(formatter.short(999));
|
||||
});
|
||||
|
||||
it("handles negative days", function () {
|
||||
expect(formatter.long(-10 * MS_IN_DAY))
|
||||
.toEqual("10D 00:00:00");
|
||||
expect(formatter.long(-10 * MS_IN_DAY + 100))
|
||||
.toEqual("10D 00:00:00");
|
||||
expect(formatter.long(-10 * MS_IN_DAY + 999))
|
||||
.toEqual("10D 00:00:00");
|
||||
|
||||
expect(formatter.short(-10 * MS_IN_DAY + 100))
|
||||
.toEqual("240:00:00");
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
@ -1,62 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define(
|
||||
["../../src/services/TickerService"],
|
||||
function (TickerService) {
|
||||
|
||||
var TEST_TIMESTAMP = 1433354174000;
|
||||
|
||||
describe("The ticker service", function () {
|
||||
var mockTimeout,
|
||||
mockNow,
|
||||
mockCallback,
|
||||
tickerService;
|
||||
|
||||
beforeEach(function () {
|
||||
mockTimeout = jasmine.createSpy('$timeout');
|
||||
mockNow = jasmine.createSpy('now');
|
||||
mockCallback = jasmine.createSpy('callback');
|
||||
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP);
|
||||
|
||||
tickerService = new TickerService(mockTimeout, mockNow);
|
||||
});
|
||||
|
||||
it("notifies listeners of clock ticks", function () {
|
||||
tickerService.listen(mockCallback);
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP + 12321);
|
||||
mockTimeout.calls.mostRecent().args[0]();
|
||||
expect(mockCallback)
|
||||
.toHaveBeenCalledWith(TEST_TIMESTAMP + 12321);
|
||||
});
|
||||
|
||||
it("allows listeners to unregister", function () {
|
||||
tickerService.listen(mockCallback)(); // Unregister immediately
|
||||
mockNow.and.returnValue(TEST_TIMESTAMP + 12321);
|
||||
mockTimeout.calls.mostRecent().args[0]();
|
||||
expect(mockCallback).not
|
||||
.toHaveBeenCalledWith(TEST_TIMESTAMP + 12321);
|
||||
});
|
||||
});
|
||||
}
|
||||
);
|
@ -1,77 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2009-2016, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
'../../src/services/TimerService'
|
||||
], function (TimerService) {
|
||||
describe("TimerService", function () {
|
||||
var callback;
|
||||
var mockmct;
|
||||
var timerService;
|
||||
|
||||
beforeEach(function () {
|
||||
callback = jasmine.createSpy('callback');
|
||||
mockmct = {
|
||||
time: { clock: jasmine.createSpy('clock') },
|
||||
objects: { observe: jasmine.createSpy('observe') }
|
||||
};
|
||||
timerService = new TimerService(mockmct);
|
||||
timerService.on('change', callback);
|
||||
});
|
||||
|
||||
it("initially emits no change events", function () {
|
||||
expect(callback).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports no current timer", function () {
|
||||
expect(timerService.getTimer()).toBeUndefined();
|
||||
});
|
||||
|
||||
describe("setTimer", function () {
|
||||
var testTimer;
|
||||
|
||||
beforeEach(function () {
|
||||
testTimer = { name: "I am some timer; you are nobody." };
|
||||
timerService.setTimer(testTimer);
|
||||
});
|
||||
|
||||
it("emits a change event", function () {
|
||||
expect(callback).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("reports the current timer", function () {
|
||||
expect(timerService.getTimer()).toBe(testTimer);
|
||||
});
|
||||
|
||||
it("observes changes to an object", function () {
|
||||
var newTimer = { name: "I am another timer." };
|
||||
expect(mockmct.objects.observe).toHaveBeenCalledWith(
|
||||
testTimer,
|
||||
'*',
|
||||
jasmine.any(Function)
|
||||
);
|
||||
mockmct.objects.observe.calls.mostRecent().args[2](newTimer);
|
||||
expect(timerService.getTimer()).toBe(newTimer);
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
@ -44,9 +44,11 @@ define(
|
||||
setText(result.name);
|
||||
scope.ngModel[scope.field] = result;
|
||||
control.$setValidity("file-input", true);
|
||||
scope.$digest();
|
||||
}, function () {
|
||||
setText('Select File');
|
||||
control.$setValidity("file-input", false);
|
||||
scope.$digest();
|
||||
});
|
||||
}
|
||||
|
||||
|
@ -71,13 +71,15 @@ define(['zepto', 'objectUtils'], function ($, objectUtils) {
|
||||
var rootObj = this.instantiate(rootModel, rootId);
|
||||
var newStyleParent = parent.useCapability('adapter');
|
||||
var newStyleRootObj = rootObj.useCapability('adapter');
|
||||
newStyleRootObj.location = parent.getId();
|
||||
|
||||
if (this.openmct.composition.checkPolicy(newStyleParent, newStyleRootObj)) {
|
||||
// Instantiate all objects in tree with their newly generated ids,
|
||||
// adding each to its rightful parent's composition
|
||||
rootObj.getCapability("location").setPrimaryLocation(parent.getId());
|
||||
this.deepInstantiate(rootObj, tree.openmct, []);
|
||||
parent.getCapability("composition").add(rootObj);
|
||||
this.openmct.objects.save(newStyleRootObj);
|
||||
const compositionCollection = this.openmct.composition.get(newStyleParent);
|
||||
compositionCollection.add(newStyleRootObj);
|
||||
} else {
|
||||
var dialog = this.openmct.overlays.dialog({
|
||||
iconClass: 'alert',
|
||||
@ -103,7 +105,6 @@ define(['zepto', 'objectUtils'], function ($, objectUtils) {
|
||||
var newObj;
|
||||
|
||||
seen.push(parent.getId());
|
||||
|
||||
parentModel.composition.forEach(function (childId) {
|
||||
let keystring = this.openmct.objects.makeKeyString(childId);
|
||||
|
||||
@ -115,8 +116,7 @@ define(['zepto', 'objectUtils'], function ($, objectUtils) {
|
||||
delete newModel.persisted;
|
||||
|
||||
newObj = this.instantiate(newModel, keystring);
|
||||
newObj.getCapability("location")
|
||||
.setPrimaryLocation(tree[keystring].location);
|
||||
this.openmct.objects.save(newModel);
|
||||
this.deepInstantiate(newObj, tree, seen);
|
||||
}, this);
|
||||
}
|
||||
|
@ -42,15 +42,21 @@ define(
|
||||
newObjects;
|
||||
|
||||
beforeEach(function () {
|
||||
|
||||
uniqueId = 0;
|
||||
newObjects = [];
|
||||
openmct = {
|
||||
$injector: jasmine.createSpyObj('$injector', ['get']),
|
||||
objects: {
|
||||
makeKeyString: function (identifier) {
|
||||
return identifier.key;
|
||||
}
|
||||
makeKeyString: identifier => identifier.key,
|
||||
save: o => true
|
||||
},
|
||||
composition: {
|
||||
get: (o) => {
|
||||
return {
|
||||
add: v => {}
|
||||
};
|
||||
},
|
||||
checkPolicy: (a, b) => true
|
||||
}
|
||||
};
|
||||
mockInstantiate = jasmine.createSpy('instantiate').and.callFake(
|
||||
@ -60,14 +66,6 @@ define(
|
||||
"id": id,
|
||||
"capabilities": {}
|
||||
};
|
||||
var locationCapability = {
|
||||
setPrimaryLocation: jasmine.createSpy('setPrimaryLocation')
|
||||
.and
|
||||
.callFake(function (newLocation) {
|
||||
config.model.location = newLocation;
|
||||
})
|
||||
};
|
||||
config.capabilities.location = locationCapability;
|
||||
if (model.composition) {
|
||||
var compCapability =
|
||||
jasmine.createSpy('compCapability')
|
||||
@ -79,6 +77,10 @@ define(
|
||||
config.capabilities.composition = compCapability;
|
||||
}
|
||||
|
||||
config.capabilities.adapter = {
|
||||
invoke: () => model
|
||||
};
|
||||
|
||||
newObjects.push(domainObjectFactory(config));
|
||||
|
||||
return domainObjectFactory(config);
|
||||
@ -146,14 +148,33 @@ define(
|
||||
});
|
||||
});
|
||||
|
||||
xit("can import self-containing objects", function () {
|
||||
it("can import self-containing objects", function () {
|
||||
var compDomainObject = domainObjectFactory({
|
||||
name: 'compObject',
|
||||
model: { name: 'compObject'},
|
||||
capabilities: {"composition": compositionCapability}
|
||||
capabilities: {
|
||||
"composition": compositionCapability,
|
||||
'adapter': {
|
||||
invoke: () => {
|
||||
return {
|
||||
name: 'parent',
|
||||
composition: [],
|
||||
id: "mine",
|
||||
identifier: {
|
||||
namespace: '',
|
||||
key: 'mine'
|
||||
},
|
||||
location: "ROOT",
|
||||
modified: 1637287323760,
|
||||
persisted: 1637287323760,
|
||||
type: "folder"
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
context.domainObject = compDomainObject;
|
||||
|
||||
context.domainObject = compDomainObject;
|
||||
dialogService.getUserInput.and.returnValue(Promise.resolve(
|
||||
{
|
||||
selectFile: {
|
||||
@ -161,10 +182,14 @@ define(
|
||||
"openmct": {
|
||||
"infiniteParent": {
|
||||
"composition": [{
|
||||
key: "infinteChild",
|
||||
namespace: ""
|
||||
"key": "infinteChild",
|
||||
"namespace": ""
|
||||
}],
|
||||
"name": "1",
|
||||
"identifier": {
|
||||
"key": "infiniteParent",
|
||||
"namespace": ""
|
||||
},
|
||||
"name": "parent",
|
||||
"type": "folder",
|
||||
"modified": 1503598129176,
|
||||
"location": "mine",
|
||||
@ -172,10 +197,14 @@ define(
|
||||
},
|
||||
"infinteChild": {
|
||||
"composition": [{
|
||||
key: "infinteParent",
|
||||
namespace: ""
|
||||
"key": "infiniteParent",
|
||||
"namespace": ""
|
||||
}],
|
||||
"name": "2",
|
||||
"identifier": {
|
||||
"key": "infinteChild",
|
||||
"namespace": ""
|
||||
},
|
||||
"name": "child",
|
||||
"type": "folder",
|
||||
"modified": 1503598132428,
|
||||
"location": "infiniteParent",
|
||||
@ -198,7 +227,7 @@ define(
|
||||
});
|
||||
});
|
||||
|
||||
xit("assigns new ids to each imported object", function () {
|
||||
it("assigns new ids to each imported object", function () {
|
||||
dialogService.getUserInput.and.returnValue(Promise.resolve(
|
||||
{
|
||||
selectFile: {
|
||||
@ -229,7 +258,6 @@ define(
|
||||
expect(newObjects[0].getId()).toBe('1');
|
||||
});
|
||||
});
|
||||
|
||||
});
|
||||
}
|
||||
);
|
||||
|
@ -253,6 +253,8 @@ define([
|
||||
|
||||
this.status = new api.StatusAPI(this);
|
||||
|
||||
this.priority = api.PriorityAPI;
|
||||
|
||||
this.router = new ApplicationRouter(this);
|
||||
|
||||
this.branding = BrandingAPI.default;
|
||||
@ -263,6 +265,7 @@ define([
|
||||
// Plugins that are installed by default
|
||||
|
||||
this.install(this.plugins.Plot());
|
||||
this.install(this.plugins.Chart());
|
||||
this.install(this.plugins.TelemetryTable.default());
|
||||
this.install(PreviewPlugin.default());
|
||||
this.install(LegacyIndicatorsPlugin());
|
||||
|
@ -28,8 +28,6 @@ export default function LegacyActionAdapter(openmct, legacyActions) {
|
||||
return true;
|
||||
}
|
||||
|
||||
console.warn(`DEPRECATION WARNING: Action ${action.definition.key} in bundle ${action.bundle.path} is non-contextual and should be migrated.`);
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
|
@ -25,11 +25,9 @@ define([
|
||||
'./capabilities/AdapterCapability',
|
||||
'./directives/MCTView',
|
||||
'./services/Instantiate',
|
||||
'./services/MissingModelCompatibilityDecorator',
|
||||
'./capabilities/APICapabilityDecorator',
|
||||
'./policies/AdaptedViewPolicy',
|
||||
'./runs/AlternateCompositionInitializer',
|
||||
'./runs/TypeDeprecationChecker',
|
||||
'./runs/LegacyTelemetryProvider',
|
||||
'./runs/RegisterLegacyTypes',
|
||||
'./services/LegacyObjectAPIInterceptor',
|
||||
@ -42,11 +40,9 @@ define([
|
||||
AdapterCapability,
|
||||
MCTView,
|
||||
Instantiate,
|
||||
MissingModelCompatibilityDecorator,
|
||||
APICapabilityDecorator,
|
||||
AdaptedViewPolicy,
|
||||
AlternateCompositionInitializer,
|
||||
TypeDeprecationChecker,
|
||||
LegacyTelemetryProvider,
|
||||
RegisterLegacyTypes,
|
||||
LegacyObjectAPIInterceptor,
|
||||
@ -99,12 +95,6 @@ define([
|
||||
implementation: ActionDialogDecorator,
|
||||
depends: ["openmct"]
|
||||
},
|
||||
{
|
||||
type: "decorator",
|
||||
provides: "modelService",
|
||||
implementation: MissingModelCompatibilityDecorator,
|
||||
depends: ["openmct"]
|
||||
},
|
||||
{
|
||||
provides: "objectService",
|
||||
type: "decorator",
|
||||
@ -135,10 +125,6 @@ define([
|
||||
}
|
||||
],
|
||||
runs: [
|
||||
{
|
||||
implementation: TypeDeprecationChecker,
|
||||
depends: ["types[]"]
|
||||
},
|
||||
{
|
||||
implementation: AlternateCompositionInitializer,
|
||||
depends: ["openmct"]
|
||||
|
@ -4,12 +4,6 @@ define([
|
||||
|
||||
) {
|
||||
function RegisterLegacyTypes(types, openmct) {
|
||||
types.forEach(function (legacyDefinition) {
|
||||
if (!openmct.types.get(legacyDefinition.key)) {
|
||||
console.warn(`DEPRECATION WARNING: Migrate type ${legacyDefinition.key} from ${legacyDefinition.bundle.path} to use the new Types API. Legacy type support will be removed soon.`);
|
||||
}
|
||||
});
|
||||
|
||||
openmct.types.importLegacyTypes(types);
|
||||
}
|
||||
|
||||
|
@ -1,46 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open openmct, Copyright (c) 2014-2021, United States Government
|
||||
* as represented by the Administrator of the National Aeronautics and Space
|
||||
* Administration. All rights reserved.
|
||||
*
|
||||
* Open openmct 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 openmct 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
|
||||
], function (
|
||||
|
||||
) {
|
||||
|
||||
function checkForDeprecatedFunctionality(typeDef) {
|
||||
if (Object.prototype.hasOwnProperty.call(typeDef, 'telemetry')) {
|
||||
console.warn(
|
||||
'DEPRECATION WARNING: Telemetry data on type '
|
||||
+ 'registrations will be deprecated in a future version, '
|
||||
+ 'please convert to a custom telemetry metadata provider '
|
||||
+ 'for type: ' + typeDef.key
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
function TypeDeprecationChecker(types) {
|
||||
types.forEach(checkForDeprecatedFunctionality);
|
||||
}
|
||||
|
||||
return TypeDeprecationChecker;
|
||||
|
||||
});
|
@ -133,9 +133,13 @@ define([
|
||||
|
||||
return this.objectService.getObjects([keyString])
|
||||
.then(function (results) {
|
||||
if (results[keyString]) {
|
||||
let model = results[keyString].getModel();
|
||||
|
||||
return utils.toNewFormat(model, key);
|
||||
}
|
||||
|
||||
return;
|
||||
});
|
||||
};
|
||||
|
||||
|
@ -1,97 +0,0 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
define([
|
||||
'objectUtils'
|
||||
], function (
|
||||
objectUtils
|
||||
) {
|
||||
|
||||
/**
|
||||
* Compatibility decorator for New API.
|
||||
*
|
||||
* When the model service returns no results, this attempts to load
|
||||
* the model from the new Object API and returns that instead. In order
|
||||
* to prevent infinite recursion, this only tries to fetch from the API
|
||||
* a single time.
|
||||
*
|
||||
*/
|
||||
function MissingModelCompatibilityDecorator(api, modelService) {
|
||||
this.api = api;
|
||||
this.modelService = modelService;
|
||||
this.apiFetching = {}; // to prevent loops, if we have already
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a set of ids from the public api and return a promise for their
|
||||
* models. If a model is requested twice, respond with a missing result.
|
||||
*/
|
||||
MissingModelCompatibilityDecorator.prototype.apiFetch = function (ids) {
|
||||
const results = {};
|
||||
|
||||
const promises = ids.map(function (id) {
|
||||
if (this.apiFetching[id]) {
|
||||
return Promise.resolve();
|
||||
}
|
||||
|
||||
this.apiFetching[id] = true;
|
||||
|
||||
return this.api.objects.get(objectUtils.parseKeyString(id))
|
||||
.then(function (newDO) {
|
||||
results[id] = objectUtils.toOldFormat(newDO);
|
||||
});
|
||||
}, this);
|
||||
|
||||
return Promise.all(promises).then(function () {
|
||||
return results;
|
||||
});
|
||||
};
|
||||
|
||||
/**
|
||||
* Return a promise for model results based on provided ids. Will attempt
|
||||
* to fetch any missing results from the object api.
|
||||
*/
|
||||
MissingModelCompatibilityDecorator.prototype.getModels = function (ids) {
|
||||
return this.modelService.getModels(ids)
|
||||
.then(function (models) {
|
||||
const missingIds = ids.filter(function (id) {
|
||||
return !models[id];
|
||||
});
|
||||
|
||||
if (!missingIds.length) {
|
||||
return models;
|
||||
}
|
||||
|
||||
return this.apiFetch(missingIds)
|
||||
.then(function (apiResults) {
|
||||
Object.keys(apiResults).forEach(function (k) {
|
||||
models[k] = apiResults[k];
|
||||
});
|
||||
|
||||
return models;
|
||||
});
|
||||
}.bind(this));
|
||||
};
|
||||
|
||||
return MissingModelCompatibilityDecorator;
|
||||
});
|
||||
|
@ -15,8 +15,6 @@ define([
|
||||
};
|
||||
|
||||
function LegacyViewProvider(legacyView, openmct, convertToLegacyObject) {
|
||||
console.warn(`DEPRECATION WARNING: Migrate ${legacyView.key} from ${legacyView.bundle.path} to use the new View APIs. Legacy view support will be removed soon.`);
|
||||
|
||||
return {
|
||||
key: legacyView.key,
|
||||
name: legacyView.name,
|
||||
|
@ -4,7 +4,6 @@ define([
|
||||
|
||||
) {
|
||||
function TypeInspectorViewProvider(typeDefinition, openmct, convertToLegacyObject) {
|
||||
console.warn(`DEPRECATION WARNING: Migrate ${typeDefinition.key} from ${typeDefinition.bundle.path} to use the new Inspector View APIs. Legacy Inspector view support will be removed soon.`);
|
||||
let representation = openmct.$injector.get('representations[]')
|
||||
.filter((r) => r.key === typeDefinition.inspector)[0];
|
||||
|
||||
|
@ -34,7 +34,6 @@ export default class Editor extends EventEmitter {
|
||||
* Initiate an editing session. This will start a transaction during
|
||||
* which any persist operations will be deferred until either save()
|
||||
* or finish() are called.
|
||||
* @private
|
||||
*/
|
||||
edit() {
|
||||
if (this.editing === true) {
|
||||
@ -42,8 +41,8 @@ export default class Editor extends EventEmitter {
|
||||
}
|
||||
|
||||
this.editing = true;
|
||||
this.getTransactionService().startTransaction();
|
||||
this.emit('isEditing', true);
|
||||
this.openmct.objects.startTransaction();
|
||||
}
|
||||
|
||||
/**
|
||||
@ -56,41 +55,36 @@ export default class Editor extends EventEmitter {
|
||||
/**
|
||||
* Save any unsaved changes from this editing session. This will
|
||||
* end the current transaction.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
save() {
|
||||
return this.getTransactionService().commit().then((result) => {
|
||||
const transaction = this.openmct.objects.getActiveTransaction();
|
||||
|
||||
return transaction.commit()
|
||||
.then(() => {
|
||||
this.editing = false;
|
||||
this.emit('isEditing', false);
|
||||
|
||||
return result;
|
||||
}).catch((error) => {
|
||||
}).catch(error => {
|
||||
throw error;
|
||||
}).finally(() => {
|
||||
this.openmct.objects.endTransaction();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* End the currently active transaction and discard unsaved changes.
|
||||
*
|
||||
* @private
|
||||
*/
|
||||
cancel() {
|
||||
let cancelPromise = this.getTransactionService().cancel();
|
||||
this.editing = false;
|
||||
this.emit('isEditing', false);
|
||||
|
||||
return cancelPromise;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
*/
|
||||
getTransactionService() {
|
||||
if (!this.transactionService) {
|
||||
this.transactionService = this.openmct.$injector.get('transactionService');
|
||||
}
|
||||
|
||||
return this.transactionService;
|
||||
return new Promise((resolve, reject) => {
|
||||
const transaction = this.openmct.objects.getActiveTransaction();
|
||||
transaction.cancel()
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
.finally(() => {
|
||||
this.openmct.objects.endTransaction();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
@ -110,7 +110,7 @@ class ActionsAPI extends EventEmitter {
|
||||
return actionsObject;
|
||||
}
|
||||
|
||||
_groupAndSortActions(actionsArray) {
|
||||
_groupAndSortActions(actionsArray = []) {
|
||||
if (!Array.isArray(actionsArray) && typeof actionsArray === 'object') {
|
||||
actionsArray = Object.keys(actionsArray).map(key => actionsArray[key]);
|
||||
}
|
||||
|
@ -31,7 +31,8 @@ define([
|
||||
'./Editor',
|
||||
'./menu/MenuAPI',
|
||||
'./actions/ActionsAPI',
|
||||
'./status/StatusAPI'
|
||||
'./status/StatusAPI',
|
||||
'./priority/PriorityAPI'
|
||||
], function (
|
||||
TimeAPI,
|
||||
ObjectAPI,
|
||||
@ -43,7 +44,8 @@ define([
|
||||
EditorAPI,
|
||||
MenuAPI,
|
||||
ActionsAPI,
|
||||
StatusAPI
|
||||
StatusAPI,
|
||||
PriorityAPI
|
||||
) {
|
||||
return {
|
||||
TimeAPI: TimeAPI.default,
|
||||
@ -56,6 +58,7 @@ define([
|
||||
EditorAPI: EditorAPI,
|
||||
MenuAPI: MenuAPI.default,
|
||||
ActionsAPI: ActionsAPI.default,
|
||||
StatusAPI: StatusAPI.default
|
||||
StatusAPI: StatusAPI.default,
|
||||
PriorityAPI: PriorityAPI.default
|
||||
};
|
||||
});
|
||||
|
@ -31,14 +31,22 @@ define([
|
||||
this.indicatorObjects = [];
|
||||
}
|
||||
|
||||
IndicatorAPI.prototype.getIndicatorObjectsByPriority = function () {
|
||||
const sortedIndicators = this.indicatorObjects.sort((a, b) => b.priority - a.priority);
|
||||
|
||||
return sortedIndicators;
|
||||
};
|
||||
|
||||
IndicatorAPI.prototype.simpleIndicator = function () {
|
||||
return new SimpleIndicator(this.openmct);
|
||||
};
|
||||
|
||||
/**
|
||||
* Accepts an indicator object, which is a simple object
|
||||
* with a single attribute, 'element' which has an HTMLElement
|
||||
* as its value.
|
||||
* with a two attributes: 'element' which has an HTMLElement
|
||||
* as its value, and 'priority' with an integer that specifies its order in the layout.
|
||||
* The lower the priority, the further to the right the element is placed.
|
||||
* If undefined, the priority will be assigned -1.
|
||||
*
|
||||
* We provide .simpleIndicator() as a convenience function
|
||||
* which will create a default Open MCT indicator that can
|
||||
@ -47,7 +55,7 @@ define([
|
||||
* and dynamic behavior.
|
||||
*
|
||||
* Eg.
|
||||
* var myIndicator = openmct.indicators.simpleIndicator();
|
||||
* const myIndicator = openmct.indicators.simpleIndicator();
|
||||
* openmct.indicators.add(myIndicator);
|
||||
*
|
||||
* myIndicator.text("Hello World!");
|
||||
@ -55,6 +63,10 @@ define([
|
||||
*
|
||||
*/
|
||||
IndicatorAPI.prototype.add = function (indicator) {
|
||||
if (!indicator.priority) {
|
||||
indicator.priority = this.openmct.priority.DEFAULT;
|
||||
}
|
||||
|
||||
this.indicatorObjects.push(indicator);
|
||||
};
|
||||
|
||||
|
@ -19,97 +19,64 @@
|
||||
* 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';
|
||||
import SimpleIndicator from './SimpleIndicator';
|
||||
|
||||
define(
|
||||
[
|
||||
"../../MCT",
|
||||
"../../../platform/commonUI/general/src/directives/MCTIndicators"
|
||||
],
|
||||
function (
|
||||
MCT,
|
||||
MCTIndicators
|
||||
) {
|
||||
xdescribe("The Indicator API", function () {
|
||||
describe("The Indicator API", () => {
|
||||
let openmct;
|
||||
let directive;
|
||||
let holderElement;
|
||||
|
||||
beforeEach(function () {
|
||||
openmct = new MCT();
|
||||
directive = new MCTIndicators(openmct);
|
||||
holderElement = document.createElement('div');
|
||||
beforeEach(() => {
|
||||
openmct = createOpenMct();
|
||||
});
|
||||
|
||||
describe("The simple indicator", function () {
|
||||
let simpleIndicator;
|
||||
afterEach(() => {
|
||||
return resetApplicationState(openmct);
|
||||
});
|
||||
|
||||
beforeEach(function () {
|
||||
simpleIndicator = openmct.indicators.simpleIndicator();
|
||||
function generateIndicator(className, label, priority) {
|
||||
const element = document.createElement('div');
|
||||
element.classList.add(className);
|
||||
const textNode = document.createTextNode(label);
|
||||
element.appendChild(textNode);
|
||||
const testIndicator = {
|
||||
element,
|
||||
priority
|
||||
};
|
||||
|
||||
return testIndicator;
|
||||
}
|
||||
|
||||
it("can register an indicator", () => {
|
||||
const testIndicator = generateIndicator('test-indicator', 'This is a test indicator', 2);
|
||||
openmct.indicators.add(testIndicator);
|
||||
expect(openmct.indicators.indicatorObjects).toBeDefined();
|
||||
// notifier indicator is installed by default
|
||||
expect(openmct.indicators.indicatorObjects.length).toBe(2);
|
||||
});
|
||||
|
||||
it("can order indicators based on priority", () => {
|
||||
const testIndicator1 = generateIndicator('test-indicator-1', 'This is a test indicator', openmct.priority.LOW);
|
||||
openmct.indicators.add(testIndicator1);
|
||||
|
||||
const testIndicator2 = generateIndicator('test-indicator-2', 'This is another test indicator', openmct.priority.DEFAULT);
|
||||
openmct.indicators.add(testIndicator2);
|
||||
|
||||
const testIndicator3 = generateIndicator('test-indicator-3', 'This is yet another test indicator', openmct.priority.LOW);
|
||||
openmct.indicators.add(testIndicator3);
|
||||
|
||||
const testIndicator4 = generateIndicator('test-indicator-4', 'This is yet another test indicator', openmct.priority.HIGH);
|
||||
openmct.indicators.add(testIndicator4);
|
||||
|
||||
expect(openmct.indicators.indicatorObjects.length).toBe(5);
|
||||
const indicatorObjectsByPriority = openmct.indicators.getIndicatorObjectsByPriority();
|
||||
expect(indicatorObjectsByPriority.length).toBe(5);
|
||||
expect(indicatorObjectsByPriority[2].priority).toBe(openmct.priority.DEFAULT);
|
||||
});
|
||||
|
||||
it("the simple indicator can be added", () => {
|
||||
const simpleIndicator = new SimpleIndicator(openmct);
|
||||
openmct.indicators.add(simpleIndicator);
|
||||
renderIndicators();
|
||||
});
|
||||
|
||||
it("applies the set icon class", function () {
|
||||
simpleIndicator.iconClass('testIconClass');
|
||||
|
||||
expect(getIconElement().classList.contains('testIconClass')).toBe(true);
|
||||
|
||||
simpleIndicator.iconClass('anotherIconClass');
|
||||
expect(getIconElement().classList.contains('testIconClass')).toBe(false);
|
||||
expect(getIconElement().classList.contains('anotherIconClass')).toBe(true);
|
||||
});
|
||||
|
||||
it("applies the set status class", function () {
|
||||
simpleIndicator.statusClass('testStatusClass');
|
||||
|
||||
expect(getIconElement().classList.contains('testStatusClass')).toBe(true);
|
||||
simpleIndicator.statusClass('anotherStatusClass');
|
||||
expect(getIconElement().classList.contains('testStatusClass')).toBe(false);
|
||||
expect(getIconElement().classList.contains('anotherStatusClass')).toBe(true);
|
||||
});
|
||||
|
||||
it("displays the set text", function () {
|
||||
simpleIndicator.text('some test text');
|
||||
expect(getTextElement().textContent.trim()).toEqual('some test text');
|
||||
});
|
||||
|
||||
it("sets the indicator's title", function () {
|
||||
simpleIndicator.description('a test description');
|
||||
expect(getIndicatorElement().getAttribute('title')).toEqual('a test description');
|
||||
});
|
||||
|
||||
it("Hides indicator icon if no text is set", function () {
|
||||
simpleIndicator.text('');
|
||||
expect(getIndicatorElement().classList.contains('hidden')).toBe(true);
|
||||
});
|
||||
|
||||
function getIconElement() {
|
||||
return holderElement.querySelector('.ls-indicator');
|
||||
}
|
||||
|
||||
function getIndicatorElement() {
|
||||
return holderElement.querySelector('.ls-indicator');
|
||||
}
|
||||
|
||||
function getTextElement() {
|
||||
return holderElement.querySelector('.indicator-text');
|
||||
}
|
||||
});
|
||||
|
||||
it("Supports registration of a completely custom indicator", function () {
|
||||
const customIndicator = document.createElement('div');
|
||||
customIndicator.classList.add('customIndicator');
|
||||
customIndicator.textContent = 'A custom indicator';
|
||||
|
||||
openmct.indicators.add({element: customIndicator});
|
||||
renderIndicators();
|
||||
|
||||
expect(holderElement.querySelector('.customIndicator').textContent.trim()).toEqual('A custom indicator');
|
||||
});
|
||||
|
||||
function renderIndicators() {
|
||||
directive.link({}, holderElement);
|
||||
}
|
||||
|
||||
expect(openmct.indicators.indicatorObjects.length).toBe(2);
|
||||
});
|
||||
});
|
||||
|
@ -27,6 +27,7 @@ define(['zepto', './res/indicator-template.html'],
|
||||
function SimpleIndicator(openmct) {
|
||||
this.openmct = openmct;
|
||||
this.element = $(indicatorTemplate)[0];
|
||||
this.priority = openmct.priority.DEFAULT;
|
||||
|
||||
this.textElement = this.element.querySelector('.js-indicator-text');
|
||||
|
||||
|
2
src/api/objects/ConflictError.js
Normal file
2
src/api/objects/ConflictError.js
Normal file
@ -0,0 +1,2 @@
|
||||
export default class ConflictError extends Error {
|
||||
}
|
@ -129,9 +129,7 @@ class MutableDomainObject {
|
||||
|
||||
mutable.$observe('$_synchronize_model', (updatedObject) => {
|
||||
let clone = JSON.parse(JSON.stringify(updatedObject));
|
||||
let deleted = _.difference(Object.keys(mutable), Object.keys(updatedObject));
|
||||
deleted.forEach((propertyName) => delete mutable[propertyName]);
|
||||
Object.assign(mutable, clone);
|
||||
utils.refresh(mutable, clone);
|
||||
});
|
||||
|
||||
return mutable;
|
||||
|
@ -26,6 +26,8 @@ import RootRegistry from './RootRegistry';
|
||||
import RootObjectProvider from './RootObjectProvider';
|
||||
import EventEmitter from 'EventEmitter';
|
||||
import InterceptorRegistry from './InterceptorRegistry';
|
||||
import Transaction from './Transaction';
|
||||
import ConflictError from './ConflictError';
|
||||
|
||||
/**
|
||||
* Utilities for loading, saving, and manipulating domain objects.
|
||||
@ -34,12 +36,13 @@ import InterceptorRegistry from './InterceptorRegistry';
|
||||
*/
|
||||
|
||||
function ObjectAPI(typeRegistry, openmct) {
|
||||
this.openmct = openmct;
|
||||
this.typeRegistry = typeRegistry;
|
||||
this.eventEmitter = new EventEmitter();
|
||||
this.providers = {};
|
||||
this.rootRegistry = new RootRegistry();
|
||||
this.injectIdentifierService = function () {
|
||||
this.identifierService = openmct.$injector.get("identifierService");
|
||||
this.identifierService = this.openmct.$injector.get("identifierService");
|
||||
};
|
||||
|
||||
this.rootProvider = new RootObjectProvider(this.rootRegistry);
|
||||
@ -47,6 +50,10 @@ function ObjectAPI(typeRegistry, openmct) {
|
||||
this.interceptorRegistry = new InterceptorRegistry();
|
||||
|
||||
this.SYNCHRONIZED_OBJECT_TYPES = ['notebook', 'plan'];
|
||||
|
||||
this.errors = {
|
||||
Conflict: ConflictError
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
@ -86,6 +93,14 @@ ObjectAPI.prototype.getProvider = function (identifier) {
|
||||
return this.providers[namespace] || this.fallbackProvider;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get an active transaction instance
|
||||
* @returns {Transaction} a transaction object
|
||||
*/
|
||||
ObjectAPI.prototype.getActiveTransaction = function () {
|
||||
return this.transaction;
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the root-level object.
|
||||
* @returns {Promise.<DomainObject>} a promise for the root object
|
||||
@ -169,6 +184,15 @@ ObjectAPI.prototype.get = function (identifier, abortSignal) {
|
||||
}
|
||||
|
||||
identifier = utils.parseKeyString(identifier);
|
||||
let dirtyObject;
|
||||
if (this.isTransactionActive()) {
|
||||
dirtyObject = this.transaction.getDirtyObject(keystring);
|
||||
}
|
||||
|
||||
if (dirtyObject) {
|
||||
return Promise.resolve(dirtyObject);
|
||||
}
|
||||
|
||||
const provider = this.getProvider(identifier);
|
||||
|
||||
if (!provider) {
|
||||
@ -181,7 +205,22 @@ ObjectAPI.prototype.get = function (identifier, abortSignal) {
|
||||
|
||||
let objectPromise = provider.get(identifier, abortSignal).then(result => {
|
||||
delete this.cache[keystring];
|
||||
|
||||
result = this.applyGetInterceptors(identifier, result);
|
||||
if (result.isMutable) {
|
||||
result.$refresh(result);
|
||||
} else {
|
||||
let mutableDomainObject = this._toMutable(result);
|
||||
mutableDomainObject.$refresh(result);
|
||||
}
|
||||
|
||||
return result;
|
||||
}).catch((result) => {
|
||||
console.warn(`Failed to retrieve ${keystring}:`, result);
|
||||
|
||||
delete this.cache[keystring];
|
||||
|
||||
result = this.applyGetInterceptors(identifier);
|
||||
|
||||
return result;
|
||||
});
|
||||
@ -272,6 +311,13 @@ ObjectAPI.prototype.isPersistable = function (idOrKeyString) {
|
||||
&& provider.update !== undefined;
|
||||
};
|
||||
|
||||
ObjectAPI.prototype.isMissing = function (domainObject) {
|
||||
let identifier = utils.makeKeyString(domainObject.identifier);
|
||||
let missingName = 'Missing: ' + identifier;
|
||||
|
||||
return domainObject.name === missingName;
|
||||
};
|
||||
|
||||
/**
|
||||
* Save this domain object in its current state. EXPERIMENTAL
|
||||
*
|
||||
@ -285,6 +331,7 @@ ObjectAPI.prototype.isPersistable = function (idOrKeyString) {
|
||||
ObjectAPI.prototype.save = function (domainObject) {
|
||||
let provider = this.getProvider(domainObject.identifier);
|
||||
let savedResolve;
|
||||
let savedReject;
|
||||
let result;
|
||||
|
||||
if (!this.isPersistable(domainObject.identifier)) {
|
||||
@ -294,14 +341,22 @@ ObjectAPI.prototype.save = function (domainObject) {
|
||||
} else {
|
||||
const persistedTime = Date.now();
|
||||
if (domainObject.persisted === undefined) {
|
||||
result = new Promise((resolve) => {
|
||||
result = new Promise((resolve, reject) => {
|
||||
savedResolve = resolve;
|
||||
savedReject = reject;
|
||||
});
|
||||
domainObject.persisted = persistedTime;
|
||||
provider.create(domainObject).then((response) => {
|
||||
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 {
|
||||
domainObject.persisted = persistedTime;
|
||||
this.mutate(domainObject, 'persisted', persistedTime);
|
||||
@ -312,6 +367,24 @@ ObjectAPI.prototype.save = function (domainObject) {
|
||||
return result;
|
||||
};
|
||||
|
||||
/**
|
||||
* After entering into edit mode, creates a new instance of Transaction to keep track of changes in Objects
|
||||
*/
|
||||
ObjectAPI.prototype.startTransaction = function () {
|
||||
if (this.isTransactionActive()) {
|
||||
throw new Error("Unable to start new Transaction: Previous Transaction is active");
|
||||
}
|
||||
|
||||
this.transaction = new Transaction(this);
|
||||
};
|
||||
|
||||
/**
|
||||
* Clear instance of Transaction
|
||||
*/
|
||||
ObjectAPI.prototype.endTransaction = function () {
|
||||
this.transaction = null;
|
||||
};
|
||||
|
||||
/**
|
||||
* Add a root-level object.
|
||||
* @param {module:openmct.ObjectAPI~Identifier|function} an array of
|
||||
@ -401,6 +474,29 @@ ObjectAPI.prototype.mutate = function (domainObject, path, value) {
|
||||
//Destroy temporary mutable object
|
||||
this.destroyMutable(mutableDomainObject);
|
||||
}
|
||||
|
||||
if (this.isTransactionActive()) {
|
||||
this.transaction.add(domainObject);
|
||||
} else {
|
||||
this.save(domainObject);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a domain object based on its latest persisted state. Note that this will mutate the provided object.
|
||||
* @param {module:openmct.DomainObject} domainObject an object to refresh from its persistence store
|
||||
* @returns {Promise} the provided object, updated to reflect the latest persisted state of the object.
|
||||
*/
|
||||
ObjectAPI.prototype.refresh = async function (domainObject) {
|
||||
const refreshedObject = await this.get(domainObject.identifier);
|
||||
|
||||
if (domainObject.isMutable) {
|
||||
domainObject.$refresh(refreshedObject);
|
||||
} else {
|
||||
utils.refresh(domainObject, refreshedObject);
|
||||
}
|
||||
|
||||
return domainObject;
|
||||
};
|
||||
|
||||
/**
|
||||
@ -437,6 +533,23 @@ ObjectAPI.prototype._toMutable = function (object) {
|
||||
return mutableObject;
|
||||
};
|
||||
|
||||
/**
|
||||
* Updates a domain object based on its latest persisted state. Note that this will mutate the provided object.
|
||||
* @param {module:openmct.DomainObject} domainObject an object to refresh from its persistence store
|
||||
* @returns {Promise} the provided object, updated to reflect the latest persisted state of the object.
|
||||
*/
|
||||
ObjectAPI.prototype.refresh = async function (domainObject) {
|
||||
const refreshedObject = await this.get(domainObject.identifier);
|
||||
|
||||
if (domainObject.isMutable) {
|
||||
domainObject.$refresh(refreshedObject);
|
||||
} else {
|
||||
utils.refresh(domainObject, refreshedObject);
|
||||
}
|
||||
|
||||
return domainObject;
|
||||
};
|
||||
|
||||
/**
|
||||
* @param module:openmct.ObjectAPI~Identifier identifier An object identifier
|
||||
* @returns {boolean} true if the object can be mutated, otherwise returns false
|
||||
@ -513,6 +626,10 @@ ObjectAPI.prototype.isObjectPathToALink = function (domainObject, objectPath) {
|
||||
&& domainObject.location !== this.makeKeyString(objectPath[1].identifier);
|
||||
};
|
||||
|
||||
ObjectAPI.prototype.isTransactionActive = function () {
|
||||
return Boolean(this.transaction && this.openmct.editor.isEditing());
|
||||
};
|
||||
|
||||
/**
|
||||
* Uniquely identifies a domain object.
|
||||
*
|
||||
|
@ -26,6 +26,10 @@ describe("The Object API", () => {
|
||||
|
||||
openmct.$injector.get.and.returnValue(mockIdentifierService);
|
||||
objectAPI = new ObjectAPI(typeRegistry, openmct);
|
||||
|
||||
openmct.editor = {};
|
||||
openmct.editor.isEditing = () => false;
|
||||
|
||||
mockDomainObject = {
|
||||
identifier: {
|
||||
namespace: TEST_NAMESPACE,
|
||||
@ -223,6 +227,28 @@ describe("The Object API", () => {
|
||||
expect(testObject.name).toBe(MUTATED_NAME);
|
||||
});
|
||||
|
||||
it('Provides a way of refreshing an object from the persistence store', () => {
|
||||
const modifiedTestObject = JSON.parse(JSON.stringify(testObject));
|
||||
const OTHER_ATTRIBUTE_VALUE = 'Modified value';
|
||||
const NEW_ATTRIBUTE_VALUE = 'A new attribute';
|
||||
modifiedTestObject.otherAttribute = OTHER_ATTRIBUTE_VALUE;
|
||||
modifiedTestObject.newAttribute = NEW_ATTRIBUTE_VALUE;
|
||||
delete modifiedTestObject.objectAttribute;
|
||||
|
||||
spyOn(objectAPI, 'get');
|
||||
objectAPI.get.and.returnValue(Promise.resolve(modifiedTestObject));
|
||||
|
||||
expect(objectAPI.get).not.toHaveBeenCalled();
|
||||
|
||||
return objectAPI.refresh(testObject).then(() => {
|
||||
expect(objectAPI.get).toHaveBeenCalledWith(testObject.identifier);
|
||||
|
||||
expect(testObject.otherAttribute).toEqual(OTHER_ATTRIBUTE_VALUE);
|
||||
expect(testObject.newAttribute).toEqual(NEW_ATTRIBUTE_VALUE);
|
||||
expect(testObject.objectAttribute).not.toBeDefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe ('uses a MutableDomainObject', () => {
|
||||
it('and retains properties of original object ', function () {
|
||||
expect(hasOwnProperty(mutable, 'identifier')).toBe(true);
|
||||
|
82
src/api/objects/Transaction.js
Normal file
82
src/api/objects/Transaction.js
Normal file
@ -0,0 +1,82 @@
|
||||
/*****************************************************************************
|
||||
* Open MCT, Copyright (c) 2014-2021, 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.
|
||||
*****************************************************************************/
|
||||
|
||||
export default class Transaction {
|
||||
constructor(objectAPI) {
|
||||
this.dirtyObjects = new Set();
|
||||
this.objectAPI = objectAPI;
|
||||
}
|
||||
|
||||
add(object) {
|
||||
this.dirtyObjects.add(object);
|
||||
}
|
||||
|
||||
cancel() {
|
||||
return this._clear();
|
||||
}
|
||||
|
||||
commit() {
|
||||
const promiseArray = [];
|
||||
const save = this.objectAPI.save.bind(this.objectAPI);
|
||||
this.dirtyObjects.forEach(object => {
|
||||
promiseArray.push(this.createDirtyObjectPromise(object, save));
|
||||
});
|
||||
|
||||
return Promise.all(promiseArray);
|
||||
}
|
||||
|
||||
createDirtyObjectPromise(object, action) {
|
||||
return new Promise((resolve, reject) => {
|
||||
action(object)
|
||||
.then(resolve)
|
||||
.catch(reject)
|
||||
.finally(() => {
|
||||
this.dirtyObjects.delete(object);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
getDirtyObject(keystring) {
|
||||
let dirtyObject;
|
||||
this.dirtyObjects.forEach(object => {
|
||||
if (this.objectAPI.makeKeyString(object.identifier) === keystring) {
|
||||
dirtyObject = object;
|
||||
}
|
||||
});
|
||||
|
||||
return dirtyObject;
|
||||
}
|
||||
|
||||
start() {
|
||||
this.dirtyObjects = new Set();
|
||||
}
|
||||
|
||||
_clear() {
|
||||
const promiseArray = [];
|
||||
const refresh = this.objectAPI.refresh.bind(this.objectAPI);
|
||||
this.dirtyObjects.forEach(object => {
|
||||
promiseArray.push(this.createDirtyObjectPromise(object, refresh));
|
||||
});
|
||||
|
||||
return Promise.all(promiseArray);
|
||||
}
|
||||
}
|
@ -165,12 +165,19 @@ define([
|
||||
return identifierEquals(a.identifier, b.identifier);
|
||||
}
|
||||
|
||||
function refresh(oldObject, newObject) {
|
||||
let deleted = _.difference(Object.keys(oldObject), Object.keys(newObject));
|
||||
deleted.forEach((propertyName) => delete oldObject[propertyName]);
|
||||
Object.assign(oldObject, newObject);
|
||||
}
|
||||
|
||||
return {
|
||||
toOldFormat: toOldFormat,
|
||||
toNewFormat: toNewFormat,
|
||||
makeKeyString: makeKeyString,
|
||||
parseKeyString: parseKeyString,
|
||||
equals: objectEquals,
|
||||
identifierEquals: identifierEquals
|
||||
identifierEquals: identifierEquals,
|
||||
refresh: refresh
|
||||
};
|
||||
});
|
||||
|
@ -19,31 +19,10 @@
|
||||
* this source code distribution or the Licensing information page available
|
||||
* at runtime from the About dialog for additional information.
|
||||
*****************************************************************************/
|
||||
define(['./Transaction'], function (Transaction) {
|
||||
/**
|
||||
* A nested transaction is a transaction which takes place in the context
|
||||
* of a larger parent transaction. It becomes part of the parent
|
||||
* transaction when (and only when) committed.
|
||||
* @param parent
|
||||
* @constructor
|
||||
* @extends {platform/commonUI/edit/services.Transaction}
|
||||
* @memberof platform/commonUI/edit/services
|
||||
*/
|
||||
function NestedTransaction(parent) {
|
||||
this.parent = parent;
|
||||
Transaction.call(this, parent.$log);
|
||||
}
|
||||
|
||||
NestedTransaction.prototype = Object.create(Transaction.prototype);
|
||||
|
||||
NestedTransaction.prototype.commit = function () {
|
||||
this.parent.add(
|
||||
Transaction.prototype.commit.bind(this),
|
||||
Transaction.prototype.cancel.bind(this)
|
||||
);
|
||||
|
||||
return Promise.resolve(true);
|
||||
};
|
||||
|
||||
return NestedTransaction;
|
||||
const PRIORITIES = Object.freeze({
|
||||
HIGH: 1000,
|
||||
DEFAULT: 0,
|
||||
LOW: -1000
|
||||
});
|
||||
export default PRIORITIES;
|
@ -180,12 +180,6 @@ define([
|
||||
* @memberof module:openmct.TelemetryAPI~TelemetryProvider#
|
||||
*/
|
||||
TelemetryAPI.prototype.canProvideTelemetry = function (domainObject) {
|
||||
console.warn(
|
||||
'DEPRECATION WARNING: openmct.telemetry.canProvideTelemetry '
|
||||
+ 'will not be supported in future versions of Open MCT. Please '
|
||||
+ 'use openmct.telemetry.isTelemetryObject instead.'
|
||||
);
|
||||
|
||||
return Boolean(this.findSubscriptionProvider(domainObject))
|
||||
|| Boolean(this.findRequestProvider(domainObject));
|
||||
};
|
||||
@ -483,6 +477,10 @@ define([
|
||||
* @returns {Object<String, {TelemetryValueFormatter}>}
|
||||
*/
|
||||
TelemetryAPI.prototype.getFormatMap = function (metadata) {
|
||||
if (!metadata) {
|
||||
return {};
|
||||
}
|
||||
|
||||
if (!this.formatMapCache.has(metadata)) {
|
||||
const formatMap = metadata.values().reduce(function (map, valueMetadata) {
|
||||
map[valueMetadata.key] = this.getValueFormatter(valueMetadata);
|
||||
|
@ -49,7 +49,6 @@ export class TelemetryCollection extends EventEmitter {
|
||||
this.parseTime = undefined;
|
||||
this.metadata = this.openmct.telemetry.getMetadata(domainObject);
|
||||
this.unsubscribe = undefined;
|
||||
this.historicalProvider = undefined;
|
||||
this.options = options;
|
||||
this.pageState = undefined;
|
||||
this.lastBounds = undefined;
|
||||
@ -65,13 +64,13 @@ export class TelemetryCollection extends EventEmitter {
|
||||
this._error(ERRORS.LOADED);
|
||||
}
|
||||
|
||||
this._timeSystem(this.openmct.time.timeSystem());
|
||||
this._setTimeSystem(this.openmct.time.timeSystem());
|
||||
this.lastBounds = this.openmct.time.bounds();
|
||||
|
||||
this._watchBounds();
|
||||
this._watchTimeSystem();
|
||||
|
||||
this._initiateHistoricalRequests();
|
||||
this._requestHistoricalTelemetry();
|
||||
this._initiateSubscriptionTelemetry();
|
||||
|
||||
this.loaded = true;
|
||||
@ -103,36 +102,35 @@ export class TelemetryCollection extends EventEmitter {
|
||||
return this.boundedTelemetry;
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up the telemetry collection for historical requests,
|
||||
* this uses the "standardizeRequestOptions" from Telemetry API
|
||||
* @private
|
||||
*/
|
||||
_initiateHistoricalRequests() {
|
||||
this.openmct.telemetry.standardizeRequestOptions(this.options);
|
||||
this.historicalProvider = this.openmct.telemetry.
|
||||
findRequestProvider(this.domainObject, this.options);
|
||||
|
||||
this._requestHistoricalTelemetry();
|
||||
}
|
||||
|
||||
/**
|
||||
* If a historical provider exists, then historical requests will be made
|
||||
* @private
|
||||
*/
|
||||
async _requestHistoricalTelemetry() {
|
||||
if (!this.historicalProvider) {
|
||||
let options = { ...this.options };
|
||||
let historicalProvider;
|
||||
|
||||
this.openmct.telemetry.standardizeRequestOptions(options);
|
||||
historicalProvider = this.openmct.telemetry.
|
||||
findRequestProvider(this.domainObject, options);
|
||||
|
||||
if (!historicalProvider) {
|
||||
return;
|
||||
}
|
||||
|
||||
let historicalData;
|
||||
|
||||
this.options.onPartialResponse = this._processNewTelemetry.bind(this);
|
||||
options.onPartialResponse = this._processNewTelemetry.bind(this);
|
||||
|
||||
try {
|
||||
if (this.requestAbort) {
|
||||
this.requestAbort.abort();
|
||||
}
|
||||
|
||||
this.requestAbort = new AbortController();
|
||||
this.options.signal = this.requestAbort.signal;
|
||||
historicalData = await this.historicalProvider.request(this.domainObject, this.options);
|
||||
options.signal = this.requestAbort.signal;
|
||||
this.emit('requestStarted');
|
||||
historicalData = await historicalProvider.request(this.domainObject, options);
|
||||
} catch (error) {
|
||||
if (error.name !== 'AbortError') {
|
||||
console.error('Error requesting telemetry data...');
|
||||
@ -140,6 +138,7 @@ export class TelemetryCollection extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
this.emit('requestEnded');
|
||||
this.requestAbort = undefined;
|
||||
|
||||
this._processNewTelemetry(historicalData);
|
||||
@ -173,6 +172,10 @@ export class TelemetryCollection extends EventEmitter {
|
||||
* @private
|
||||
*/
|
||||
_processNewTelemetry(telemetryData) {
|
||||
if (telemetryData === undefined) {
|
||||
return;
|
||||
}
|
||||
|
||||
let data = Array.isArray(telemetryData) ? telemetryData : [telemetryData];
|
||||
let parsedValue;
|
||||
let beforeStartOfBounds;
|
||||
@ -199,9 +202,10 @@ export class TelemetryCollection extends EventEmitter {
|
||||
|
||||
if (endIndex > startIndex) {
|
||||
let potentialDupes = this.boundedTelemetry.slice(startIndex, endIndex);
|
||||
|
||||
isDuplicate = potentialDupes.some(_.isEqual.bind(undefined, datum));
|
||||
}
|
||||
} else if (startIndex === this.boundedTelemetry.length) {
|
||||
isDuplicate = _.isEqual(datum, this.boundedTelemetry[this.boundedTelemetry.length - 1]);
|
||||
}
|
||||
|
||||
if (!isDuplicate) {
|
||||
@ -317,7 +321,7 @@ export class TelemetryCollection extends EventEmitter {
|
||||
* Time System
|
||||
* @private
|
||||
*/
|
||||
_timeSystem(timeSystem) {
|
||||
_setTimeSystem(timeSystem) {
|
||||
let domains = this.metadata.valuesForHints(['domain']);
|
||||
let domain = domains.find((d) => d.key === timeSystem.key);
|
||||
|
||||
@ -333,7 +337,10 @@ export class TelemetryCollection extends EventEmitter {
|
||||
this.parseTime = (datum) => {
|
||||
return valueFormatter.parse(datum);
|
||||
};
|
||||
}
|
||||
|
||||
_setTimeSystemAndFetchData(timeSystem) {
|
||||
this._setTimeSystem(timeSystem);
|
||||
this._reset();
|
||||
}
|
||||
|
||||
@ -370,19 +377,19 @@ export class TelemetryCollection extends EventEmitter {
|
||||
}
|
||||
|
||||
/**
|
||||
* adds the _timeSystem callback to the 'timeSystem' timeAPI listener
|
||||
* adds the _setTimeSystemAndFetchData callback to the 'timeSystem' timeAPI listener
|
||||
* @private
|
||||
*/
|
||||
_watchTimeSystem() {
|
||||
this.openmct.time.on('timeSystem', this._timeSystem, this);
|
||||
this.openmct.time.on('timeSystem', this._setTimeSystemAndFetchData, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* removes the _timeSystem callback from the 'timeSystem' timeAPI listener
|
||||
* removes the _setTimeSystemAndFetchData callback from the 'timeSystem' timeAPI listener
|
||||
* @private
|
||||
*/
|
||||
_unwatchTimeSystem() {
|
||||
this.openmct.time.off('timeSystem', this._timeSystem, this);
|
||||
this.openmct.time.off('timeSystem', this._setTimeSystemAndFetchData, this);
|
||||
}
|
||||
|
||||
/**
|
||||
|
@ -31,11 +31,6 @@ define([
|
||||
valueMetadata.hints = valueMetadata.hints || {};
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(valueMetadata.hints, 'x')) {
|
||||
console.warn(
|
||||
'DEPRECATION WARNING: `x` hints should be replaced with '
|
||||
+ '`domain` hints moving forward. '
|
||||
+ 'https://github.com/nasa/openmct/issues/1546'
|
||||
);
|
||||
if (!Object.prototype.hasOwnProperty.call(valueMetadata.hints, 'domain')) {
|
||||
valueMetadata.hints.domain = valueMetadata.hints.x;
|
||||
}
|
||||
@ -44,11 +39,6 @@ define([
|
||||
}
|
||||
|
||||
if (Object.prototype.hasOwnProperty.call(valueMetadata.hints, 'y')) {
|
||||
console.warn(
|
||||
'DEPRECATION WARNING: `y` hints should be replaced with '
|
||||
+ '`range` hints moving forward. '
|
||||
+ 'https://github.com/nasa/openmct/issues/1546'
|
||||
);
|
||||
if (!Object.prototype.hasOwnProperty.call(valueMetadata.hints, 'range')) {
|
||||
valueMetadata.hints.range = valueMetadata.hints.y;
|
||||
}
|
||||
|
@ -172,7 +172,7 @@ class TimeAPI extends GlobalTimeContext {
|
||||
* @memberof module:openmct.TimeAPI#
|
||||
* @method getContextForView
|
||||
*/
|
||||
getContextForView(objectPath) {
|
||||
getContextForView(objectPath = []) {
|
||||
let timeContext = this;
|
||||
|
||||
objectPath.forEach(item => {
|
||||
|
@ -63,12 +63,6 @@ define(['./Type'], function (Type) {
|
||||
*/
|
||||
TypeRegistry.prototype.standardizeType = function (typeDef) {
|
||||
if (Object.prototype.hasOwnProperty.call(typeDef, 'label')) {
|
||||
console.warn(
|
||||
'DEPRECATION WARNING typeDef: ' + typeDef.label + '. '
|
||||
+ '`label` is deprecated in type definitions. Please use '
|
||||
+ '`name` instead. This will cause errors in a future version '
|
||||
+ 'of Open MCT. For more information, see '
|
||||
+ 'https://github.com/nasa/openmct/issues/1568');
|
||||
if (!typeDef.name) {
|
||||
typeDef.name = typeDef.label;
|
||||
}
|
||||
|
@ -37,11 +37,9 @@ const DEFAULTS = [
|
||||
'platform/execution',
|
||||
'platform/exporters',
|
||||
'platform/telemetry',
|
||||
'platform/features/clock',
|
||||
'platform/forms',
|
||||
'platform/identity',
|
||||
'platform/persistence/aggregator',
|
||||
'platform/persistence/queue',
|
||||
'platform/policy',
|
||||
'platform/entanglement',
|
||||
'platform/search',
|
||||
@ -78,8 +76,6 @@ define([
|
||||
'../platform/entanglement/bundle',
|
||||
'../platform/execution/bundle',
|
||||
'../platform/exporters/bundle',
|
||||
'../platform/features/clock/bundle',
|
||||
'../platform/features/my-items/bundle',
|
||||
'../platform/features/static-markup/bundle',
|
||||
'../platform/forms/bundle',
|
||||
'../platform/framework/bundle',
|
||||
|
@ -32,7 +32,7 @@ describe('the plugin', function () {
|
||||
let openmct;
|
||||
let composition;
|
||||
|
||||
beforeEach((done) => {
|
||||
beforeEach(() => {
|
||||
|
||||
openmct = createOpenMct();
|
||||
|
||||
@ -47,11 +47,6 @@ describe('the plugin', function () {
|
||||
}
|
||||
}));
|
||||
|
||||
openmct.on('start', done);
|
||||
openmct.startHeadless();
|
||||
|
||||
composition = openmct.composition.get({identifier});
|
||||
|
||||
spyOn(couchPlugin.couchProvider, 'getObjectsByFilter').and.returnValue(Promise.resolve([
|
||||
{
|
||||
identifier: {
|
||||
@ -66,6 +61,19 @@ describe('the plugin', function () {
|
||||
}
|
||||
}
|
||||
]));
|
||||
|
||||
spyOn(couchPlugin.couchProvider, "get").and.callFake((id) => {
|
||||
return Promise.resolve({
|
||||
identifier: id
|
||||
});
|
||||
});
|
||||
|
||||
return new Promise((resolve) => {
|
||||
openmct.once('start', resolve);
|
||||
openmct.startHeadless();
|
||||
}).then(() => {
|
||||
composition = openmct.composition.get({identifier});
|
||||
});
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
|
@ -48,6 +48,7 @@ const CONTEXT_MENU_ACTIONS = [
|
||||
'viewHistoricalData',
|
||||
'remove'
|
||||
];
|
||||
const BLANK_VALUE = '---';
|
||||
|
||||
export default {
|
||||
inject: ['openmct', 'currentView'],
|
||||
@ -67,15 +68,43 @@ export default {
|
||||
},
|
||||
data() {
|
||||
return {
|
||||
datum: undefined,
|
||||
timestamp: undefined,
|
||||
value: '---',
|
||||
valueClass: '',
|
||||
timestampKey: undefined,
|
||||
unit: ''
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
value() {
|
||||
if (!this.datum) {
|
||||
return BLANK_VALUE;
|
||||
}
|
||||
|
||||
return this.formats[this.valueKey].format(this.datum);
|
||||
},
|
||||
valueClass() {
|
||||
if (!this.datum) {
|
||||
return '';
|
||||
}
|
||||
|
||||
const limit = this.limitEvaluator.evaluate(this.datum, this.valueMetadata);
|
||||
|
||||
return limit ? limit.cssClass : '';
|
||||
|
||||
},
|
||||
formattedTimestamp() {
|
||||
return this.timestamp !== undefined ? this.getFormattedTimestamp(this.timestamp) : '---';
|
||||
if (!this.timestamp) {
|
||||
return BLANK_VALUE;
|
||||
}
|
||||
|
||||
return this.timeSystemFormat.format(this.timestamp);
|
||||
},
|
||||
timeSystemFormat() {
|
||||
if (!this.formats[this.timestampKey]) {
|
||||
console.warn(`No formatter for ${this.timestampKey} time system for ${this.domainObject.name}.`);
|
||||
}
|
||||
|
||||
return this.formats[this.timestampKey];
|
||||
},
|
||||
objectPath() {
|
||||
return [this.domainObject, ...this.pathToTable];
|
||||
@ -96,15 +125,19 @@ export default {
|
||||
|
||||
this.timestampKey = this.openmct.time.timeSystem().key;
|
||||
|
||||
this.valueMetadata = undefined;
|
||||
|
||||
if (this.metadata) {
|
||||
this.valueMetadata = this
|
||||
.metadata
|
||||
.valuesForHints(['range'])[0];
|
||||
.valuesForHints(['range'])[0] || this.firstNonDomainAttribute(this.metadata);
|
||||
}
|
||||
|
||||
this.valueKey = this.valueMetadata.key;
|
||||
this.valueKey = this.valueMetadata ? this.valueMetadata.key : undefined;
|
||||
|
||||
this.unsubscribe = this.openmct
|
||||
.telemetry
|
||||
.subscribe(this.domainObject, this.updateValues);
|
||||
.subscribe(this.domainObject, this.setLatestValues);
|
||||
|
||||
this.requestHistory();
|
||||
|
||||
@ -118,29 +151,29 @@ export default {
|
||||
this.openmct.time.off('bounds', this.updateBounds);
|
||||
},
|
||||
methods: {
|
||||
updateValues(datum) {
|
||||
let newTimestamp = this.getParsedTimestamp(datum);
|
||||
let limit;
|
||||
updateView() {
|
||||
if (!this.updatingView) {
|
||||
this.updatingView = true;
|
||||
requestAnimationFrame(() => {
|
||||
let newTimestamp = this.getParsedTimestamp(this.latestDatum);
|
||||
|
||||
if (this.shouldUpdate(newTimestamp)) {
|
||||
this.datum = datum;
|
||||
this.timestamp = newTimestamp;
|
||||
this.value = this.formats[this.valueKey].format(datum);
|
||||
limit = this.limitEvaluator.evaluate(datum, this.valueMetadata);
|
||||
if (limit) {
|
||||
this.valueClass = limit.cssClass;
|
||||
} else {
|
||||
this.valueClass = '';
|
||||
this.datum = this.latestDatum;
|
||||
}
|
||||
|
||||
this.updatingView = false;
|
||||
});
|
||||
}
|
||||
},
|
||||
shouldUpdate(newTimestamp) {
|
||||
let newTimestampInBounds = this.inBounds(newTimestamp);
|
||||
let noExistingTimestamp = this.timestamp === undefined;
|
||||
let newTimestampIsLatest = newTimestamp > this.timestamp;
|
||||
setLatestValues(datum) {
|
||||
this.latestDatum = datum;
|
||||
|
||||
return newTimestampInBounds
|
||||
&& (noExistingTimestamp || newTimestampIsLatest);
|
||||
this.updateView();
|
||||
},
|
||||
shouldUpdate(newTimestamp) {
|
||||
return this.inBounds(newTimestamp)
|
||||
&& (this.timestamp === undefined || newTimestamp > this.timestamp);
|
||||
},
|
||||
requestHistory() {
|
||||
this.openmct
|
||||
@ -151,7 +184,10 @@ export default {
|
||||
size: 1,
|
||||
strategy: 'latest'
|
||||
})
|
||||
.then((array) => this.updateValues(array[array.length - 1]));
|
||||
.then((array) => this.setLatestValues(array[array.length - 1]))
|
||||
.catch((error) => {
|
||||
console.warn('Error fetching data', error);
|
||||
});
|
||||
},
|
||||
updateBounds(bounds, isTick) {
|
||||
this.bounds = bounds;
|
||||
@ -186,31 +222,21 @@ export default {
|
||||
}
|
||||
},
|
||||
resetValues() {
|
||||
this.value = '---';
|
||||
this.timestamp = undefined;
|
||||
this.valueClass = '';
|
||||
this.datum = undefined;
|
||||
},
|
||||
getParsedTimestamp(timestamp) {
|
||||
if (this.timeSystemFormat()) {
|
||||
return this.formats[this.timestampKey].parse(timestamp);
|
||||
}
|
||||
},
|
||||
getFormattedTimestamp(timestamp) {
|
||||
if (this.timeSystemFormat()) {
|
||||
return this.formats[this.timestampKey].format(timestamp);
|
||||
}
|
||||
},
|
||||
timeSystemFormat() {
|
||||
if (this.formats[this.timestampKey]) {
|
||||
return true;
|
||||
} else {
|
||||
console.warn(`No formatter for ${this.timestampKey} time system for ${this.domainObject.name}.`);
|
||||
|
||||
return false;
|
||||
if (this.timeSystemFormat) {
|
||||
return this.timeSystemFormat.parse(timestamp);
|
||||
}
|
||||
},
|
||||
setUnit() {
|
||||
this.unit = this.valueMetadata.unit || '';
|
||||
},
|
||||
firstNonDomainAttribute(metadata) {
|
||||
return metadata
|
||||
.values()
|
||||
.find(metadatum => metadatum.hints.domain === undefined && metadatum.key !== 'name');
|
||||
}
|
||||
}
|
||||
};
|
||||
|
@ -73,8 +73,9 @@ export default {
|
||||
hasUnits() {
|
||||
let itemsWithUnits = this.items.filter((item) => {
|
||||
let metadata = this.openmct.telemetry.getMetadata(item.domainObject);
|
||||
const valueMetadatas = metadata ? metadata.valueMetadatas : [];
|
||||
|
||||
return this.metadataHasUnits(metadata.valueMetadatas);
|
||||
return this.metadataHasUnits(valueMetadatas);
|
||||
|
||||
});
|
||||
|
||||
|
@ -26,6 +26,7 @@ import {
|
||||
getMockObjects,
|
||||
getMockTelemetry,
|
||||
getLatestTelemetry,
|
||||
spyOnBuiltins,
|
||||
resetApplicationState
|
||||
} from 'utils/testing';
|
||||
|
||||
@ -160,6 +161,11 @@ describe("The LAD Table", () => {
|
||||
anotherTelemetryObjectResolve = resolve;
|
||||
});
|
||||
|
||||
spyOnBuiltins(['requestAnimationFrame']);
|
||||
window.requestAnimationFrame.and.callFake((callBack) => {
|
||||
callBack();
|
||||
});
|
||||
|
||||
openmct.telemetry.request.and.callFake(() => {
|
||||
telemetryRequestResolve(mockTelemetry);
|
||||
|
||||
|
@ -23,30 +23,26 @@
|
||||
import { BAR_GRAPH_KEY } from './BarGraphConstants';
|
||||
|
||||
export default function BarGraphCompositionPolicy(openmct) {
|
||||
function hasAggregateDomainAndRange(metadata) {
|
||||
function hasRange(metadata) {
|
||||
const rangeValues = metadata.valuesForHints(['range']);
|
||||
|
||||
return rangeValues.length > 0;
|
||||
}
|
||||
|
||||
function hasBarGraphTelemetry(domainObject) {
|
||||
if (!Object.prototype.hasOwnProperty.call(domainObject, 'telemetry')) {
|
||||
if (!openmct.telemetry.isTelemetryObject(domainObject)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let metadata = openmct.telemetry.getMetadata(domainObject);
|
||||
|
||||
return metadata.values().length > 0 && hasAggregateDomainAndRange(metadata);
|
||||
}
|
||||
|
||||
function hasNoChildren(parentObject) {
|
||||
return parentObject.composition && parentObject.composition.length < 1;
|
||||
return metadata.values().length > 0 && hasRange(metadata);
|
||||
}
|
||||
|
||||
return {
|
||||
allow: function (parent, child) {
|
||||
if ((parent.type === BAR_GRAPH_KEY)
|
||||
&& ((child.type !== 'telemetry.plot.overlay') && (hasBarGraphTelemetry(child) === false))
|
||||
&& (hasBarGraphTelemetry(child) === false)
|
||||
) {
|
||||
return false;
|
||||
}
|
@ -1,5 +1,3 @@
|
||||
export const BAR_GRAPH_VIEW = 'bar-graph.view';
|
||||
export const BAR_GRAPH_KEY = 'telemetry.plot.bar-graph';
|
||||
export const BAR_GRAPH_INSPECTOR_KEY = 'telemetry.plot.bar-graph.inspector';
|
||||
export const SUBSCRIBE = 'subscribe';
|
||||
export const UNSUBSCRIBE = 'unsubscribe';
|
@ -12,6 +12,7 @@
|
||||
</div>
|
||||
<div ref="plot"
|
||||
class="c-bar-chart"
|
||||
@plotly_relayout="zoom"
|
||||
></div>
|
||||
<div v-if="false"
|
||||
ref="localControl"
|
||||
@ -28,8 +29,7 @@
|
||||
</div>
|
||||
</template>
|
||||
<script>
|
||||
import Plotly from 'plotly.js-basic-dist';
|
||||
import { SUBSCRIBE, UNSUBSCRIBE } from './BarGraphConstants';
|
||||
import Plotly from 'plotly-basic';
|
||||
|
||||
const MULTI_AXES_X_PADDING_PERCENT = {
|
||||
LEFT: 8,
|
||||
@ -79,8 +79,6 @@ export default {
|
||||
this.registerListeners();
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.$refs.plot.removeAllListeners();
|
||||
|
||||
if (this.plotResizeObserver) {
|
||||
this.plotResizeObserver.unobserve(this.$refs.plotWrapper);
|
||||
clearTimeout(this.resizeTimer);
|
||||
@ -139,8 +137,8 @@ export default {
|
||||
getYAxisMeta() {
|
||||
const yAxisMeta = {};
|
||||
|
||||
this.data.forEach(d => {
|
||||
const yAxisMetadata = d.yAxisMetadata;
|
||||
this.data.forEach(datum => {
|
||||
const yAxisMetadata = datum.yAxisMetadata;
|
||||
const range = '1';
|
||||
const side = 'left';
|
||||
const name = '';
|
||||
@ -203,8 +201,6 @@ export default {
|
||||
return yaxis;
|
||||
},
|
||||
registerListeners() {
|
||||
this.$refs.plot.on('plotly_relayout', this.zoom);
|
||||
|
||||
this.removeBarColorListener = this.openmct.objects.observe(
|
||||
this.domainObject,
|
||||
'configuration.barStyles',
|
||||
@ -226,17 +222,17 @@ export default {
|
||||
this.updatePlot();
|
||||
|
||||
this.isZoomed = false;
|
||||
this.$emit(SUBSCRIBE);
|
||||
this.$emit('subscribe');
|
||||
},
|
||||
barColorChanged() {
|
||||
const colors = [];
|
||||
const indices = [];
|
||||
this.data.forEach((item, index) => {
|
||||
const key = item.key;
|
||||
const color = this.domainObject.configuration.barStyles[key] && this.domainObject.configuration.barStyles[key].color;
|
||||
const colorExists = this.domainObject.configuration.barStyles.series[key] && this.domainObject.configuration.barStyles.series[key].color;
|
||||
indices.push(index);
|
||||
if (color) {
|
||||
colors.push();
|
||||
if (colorExists) {
|
||||
colors.push(this.domainObject.configuration.barStyles.series[key].color);
|
||||
} else {
|
||||
colors.push(item.marker.color);
|
||||
}
|
||||
@ -285,7 +281,7 @@ export default {
|
||||
}
|
||||
|
||||
this.isZoomed = true;
|
||||
this.$emit(UNSUBSCRIBE);
|
||||
this.$emit('unsubscribe');
|
||||
}
|
||||
}
|
||||
};
|
@ -25,33 +25,31 @@
|
||||
class="c-plot c-bar-chart-view"
|
||||
:data="trace"
|
||||
:plot-axis-title="plotAxisTitle"
|
||||
@subscribe="subscribeToAll"
|
||||
@unsubscribe="removeAllSubscriptions"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script>
|
||||
import * as SPECTRAL_AGGREGATE from './BarGraphConstants';
|
||||
import ColorPalette from '../lib/ColorPalette';
|
||||
import BarGraph from './BarGraphPlot.vue';
|
||||
import Color from "@/plugins/plot/lib/Color";
|
||||
import _ from 'lodash';
|
||||
|
||||
export default {
|
||||
components: {
|
||||
BarGraph
|
||||
},
|
||||
inject: ['openmct', 'domainObject'],
|
||||
inject: ['openmct', 'domainObject', 'path'],
|
||||
data() {
|
||||
this.telemetryObjects = {};
|
||||
this.telemetryObjectFormats = {};
|
||||
this.subscriptions = [];
|
||||
this.composition = {};
|
||||
|
||||
return {
|
||||
composition: {},
|
||||
currentDomainObject: this.domainObject,
|
||||
subscriptions: [],
|
||||
telemetryObjects: {},
|
||||
trace: []
|
||||
};
|
||||
},
|
||||
computed: {
|
||||
activeClock() {
|
||||
return this.openmct.time.activeClock;
|
||||
},
|
||||
plotAxisTitle() {
|
||||
const { xAxisMetadata = {}, yAxisMetadata = {} } = this.trace[0] || {};
|
||||
const xAxisUnit = xAxisMetadata.units ? `(${xAxisMetadata.units})` : '';
|
||||
@ -64,24 +62,14 @@ export default {
|
||||
}
|
||||
},
|
||||
mounted() {
|
||||
this.colorPalette = new ColorPalette();
|
||||
this.loadComposition();
|
||||
|
||||
this.openmct.time.on('bounds', this.refreshData);
|
||||
this.openmct.time.on('clock', this.clockChanged);
|
||||
|
||||
this.$refs.barGraph.$on(SPECTRAL_AGGREGATE.SUBSCRIBE, this.subscribeToAll);
|
||||
this.$refs.barGraph.$on(SPECTRAL_AGGREGATE.UNSUBSCRIBE, this.removeAllSubscriptions);
|
||||
|
||||
this.unobserve = this.openmct.objects.observe(this.currentDomainObject, '*', this.updateDomainObject);
|
||||
},
|
||||
beforeDestroy() {
|
||||
this.$refs.barGraph.$off();
|
||||
this.openmct.time.off('bounds', this.refreshData);
|
||||
this.openmct.time.off('clock', this.clockChanged);
|
||||
|
||||
this.removeAllSubscriptions();
|
||||
this.unobserve();
|
||||
|
||||
if (!this.composition) {
|
||||
return;
|
||||
@ -92,35 +80,34 @@ export default {
|
||||
},
|
||||
methods: {
|
||||
addTelemetryObject(telemetryObject) {
|
||||
// grab information we need from the added telmetry object
|
||||
const key = this.openmct.objects.makeKeyString(telemetryObject.identifier);
|
||||
this.telemetryObjects[key] = telemetryObject;
|
||||
const metadata = this.openmct.telemetry.getMetadata(telemetryObject);
|
||||
this.telemetryObjectFormats[key] = this.openmct.telemetry.getFormatMap(metadata);
|
||||
const telemetryObjectPath = [telemetryObject, ...this.path];
|
||||
const telemetryIsAlias = this.openmct.objects.isObjectPathToALink(telemetryObject, telemetryObjectPath);
|
||||
|
||||
if (!this.domainObject.configuration.barStyles) {
|
||||
this.domainObject.configuration.barStyles = {};
|
||||
// make an update object that's a clone of the existing styles object so we preserve existing choices
|
||||
let stylesUpdate = {};
|
||||
if (this.domainObject.configuration.barStyles.series[key]) {
|
||||
stylesUpdate = _.clone(this.domainObject.configuration.barStyles.series[key]);
|
||||
}
|
||||
|
||||
// check to see if we've set a bar color
|
||||
if (!this.domainObject.configuration.barStyles[key] || !this.domainObject.configuration.barStyles[key].color) {
|
||||
const color = this.colorPalette.getNextColor().asHexString();
|
||||
this.domainObject.configuration.barStyles[key] = {
|
||||
name: telemetryObject.name,
|
||||
color
|
||||
};
|
||||
stylesUpdate.name = telemetryObject.name;
|
||||
stylesUpdate.type = telemetryObject.type;
|
||||
stylesUpdate.isAlias = telemetryIsAlias;
|
||||
|
||||
// if something has changed, mutate and notify listeners
|
||||
if (!_.isEqual(stylesUpdate, this.domainObject.configuration.barStyles.series[key])) {
|
||||
this.openmct.objects.mutate(
|
||||
this.domainObject,
|
||||
`configuration.barStyles[${this.key}]`,
|
||||
this.domainObject.configuration.barStyles[key]
|
||||
`configuration.barStyles.series["${key}"]`,
|
||||
stylesUpdate
|
||||
);
|
||||
} else {
|
||||
let color = this.domainObject.configuration.barStyles[key].color;
|
||||
if (!(color instanceof Color)) {
|
||||
color = Color.fromHexString(color);
|
||||
}
|
||||
|
||||
this.colorPalette.remove(color);
|
||||
}
|
||||
|
||||
this.telemetryObjects[key] = telemetryObject;
|
||||
|
||||
// ask for the current telemetry data, then subcribe for changes
|
||||
this.requestDataFor(telemetryObject);
|
||||
this.subscribeToObject(telemetryObject);
|
||||
},
|
||||
@ -144,12 +131,12 @@ export default {
|
||||
|
||||
this.trace = isInTrace ? newTrace : newTrace.concat([trace]);
|
||||
},
|
||||
clockChanged() {
|
||||
this.removeAllSubscriptions();
|
||||
this.subscribeToAll();
|
||||
},
|
||||
getAxisMetadata(telemetryObject) {
|
||||
const metadata = this.openmct.telemetry.getMetadata(telemetryObject);
|
||||
if (!metadata) {
|
||||
return {};
|
||||
}
|
||||
|
||||
const yAxisMetadata = metadata.valuesForHints(['range'])[0];
|
||||
//Exclude 'name' and 'time' based metadata specifically, from the x-Axis values by using range hints only
|
||||
const xAxisMetadata = metadata.valuesForHints(['range']);
|
||||
@ -159,21 +146,19 @@ export default {
|
||||
yAxisMetadata
|
||||
};
|
||||
},
|
||||
getOptions(telemetryObject) {
|
||||
getOptions() {
|
||||
const { start, end } = this.openmct.time.bounds();
|
||||
|
||||
return {
|
||||
end,
|
||||
start,
|
||||
startTime: null,
|
||||
spectra: true
|
||||
start
|
||||
};
|
||||
},
|
||||
loadComposition() {
|
||||
this.composition = this.openmct.composition.get(this.currentDomainObject);
|
||||
this.composition = this.openmct.composition.get(this.domainObject);
|
||||
|
||||
if (!this.composition) {
|
||||
this.addTelemetryObject(this.currentDomainObject);
|
||||
this.addTelemetryObject(this.domainObject);
|
||||
|
||||
return;
|
||||
}
|
||||
@ -202,21 +187,34 @@ export default {
|
||||
removeTelemetryObject(identifier) {
|
||||
const key = this.openmct.objects.makeKeyString(identifier);
|
||||
delete this.telemetryObjects[key];
|
||||
if (this.domainObject.configuration.barStyles[key]) {
|
||||
delete this.domainObject.configuration.barStyles[key];
|
||||
if (this.telemetryObjectFormats && this.telemetryObjectFormats[key]) {
|
||||
delete this.telemetryObjectFormats[key];
|
||||
}
|
||||
|
||||
if (this.domainObject.configuration.barStyles.series[key]) {
|
||||
delete this.domainObject.configuration.barStyles.series[key];
|
||||
this.openmct.objects.mutate(
|
||||
this.domainObject,
|
||||
`configuration.barStyles.series["${key}"]`,
|
||||
undefined
|
||||
);
|
||||
}
|
||||
|
||||
this.removeSubscription(key);
|
||||
|
||||
this.trace = this.trace.filter(t => t.key !== key);
|
||||
},
|
||||
processData(telemetryObject, data, axisMetadata) {
|
||||
addDataToGraph(telemetryObject, data, axisMetadata) {
|
||||
const key = this.openmct.objects.makeKeyString(telemetryObject.identifier);
|
||||
|
||||
if (data.message) {
|
||||
this.openmct.notifications.alert(data.message);
|
||||
}
|
||||
|
||||
if (!this.isDataInTimeRange(data, key)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let xValues = [];
|
||||
let yValues = [];
|
||||
|
||||
@ -224,10 +222,10 @@ export default {
|
||||
axisMetadata.xAxisMetadata.forEach((metadata) => {
|
||||
xValues.push(metadata.name);
|
||||
if (data[metadata.key]) {
|
||||
//TODO: Format the data?
|
||||
yValues.push(data[metadata.key]);
|
||||
const formattedValue = this.format(key, metadata.key, data);
|
||||
yValues.push(formattedValue);
|
||||
} else {
|
||||
yValues.push('');
|
||||
yValues.push(null);
|
||||
}
|
||||
});
|
||||
|
||||
@ -241,20 +239,43 @@ export default {
|
||||
yAxisMetadata: axisMetadata.yAxisMetadata,
|
||||
type: 'bar',
|
||||
marker: {
|
||||
color: this.domainObject.configuration.barStyles[key].color
|
||||
color: this.domainObject.configuration.barStyles.series[key].color
|
||||
},
|
||||
hoverinfo: 'skip'
|
||||
};
|
||||
|
||||
this.addTrace(trace, key);
|
||||
},
|
||||
isDataInTimeRange(datum, key) {
|
||||
const timeSystemKey = this.openmct.time.timeSystem().key;
|
||||
let currentTimestamp = this.parse(key, timeSystemKey, datum);
|
||||
|
||||
return currentTimestamp && this.openmct.time.bounds().end >= currentTimestamp;
|
||||
},
|
||||
format(telemetryObjectKey, metadataKey, data) {
|
||||
const formats = this.telemetryObjectFormats[telemetryObjectKey];
|
||||
|
||||
return formats[metadataKey].format(data);
|
||||
},
|
||||
parse(telemetryObjectKey, metadataKey, datum) {
|
||||
if (!datum) {
|
||||
return;
|
||||
}
|
||||
|
||||
const formats = this.telemetryObjectFormats[telemetryObjectKey];
|
||||
|
||||
return formats[metadataKey].parse(datum);
|
||||
},
|
||||
requestDataFor(telemetryObject) {
|
||||
const axisMetadata = this.getAxisMetadata(telemetryObject);
|
||||
this.openmct.telemetry.request(telemetryObject, this.getOptions(telemetryObject))
|
||||
this.openmct.telemetry.request(telemetryObject)
|
||||
.then(data => {
|
||||
data.forEach((datum) => {
|
||||
this.processData(telemetryObject, datum, axisMetadata);
|
||||
this.addDataToGraph(telemetryObject, datum, axisMetadata);
|
||||
});
|
||||
})
|
||||
.catch((error) => {
|
||||
console.warn(`Error fetching data`, error);
|
||||
});
|
||||
},
|
||||
subscribeToObject(telemetryObject) {
|
||||
@ -262,10 +283,10 @@ export default {
|
||||
|
||||
this.removeSubscription(key);
|
||||
|
||||
const options = this.getOptions(telemetryObject);
|
||||
const options = this.getOptions();
|
||||
const axisMetadata = this.getAxisMetadata(telemetryObject);
|
||||
const unsubscribe = this.openmct.telemetry.subscribe(telemetryObject,
|
||||
data => this.processData(telemetryObject, data, axisMetadata)
|
||||
data => this.addDataToGraph(telemetryObject, data, axisMetadata)
|
||||
, options);
|
||||
|
||||
this.subscriptions.push({
|
||||
@ -276,9 +297,6 @@ export default {
|
||||
subscribeToAll() {
|
||||
const telemetryObjects = Object.values(this.telemetryObjects);
|
||||
telemetryObjects.forEach(this.subscribeToObject);
|
||||
},
|
||||
updateDomainObject(newDomainObject) {
|
||||
this.currentDomainObject = newDomainObject;
|
||||
}
|
||||
}
|
||||
};
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user