Welcome to mirror list, hosted at ThFree Co, Russian Federation.

github.com/nasa/openmct.git - Unnamed repository; edit this file 'description' to name the repository.
summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorJesse Mazzella <ozyx@users.noreply.github.com>2022-10-22 03:29:52 +0300
committerGitHub <noreply@github.com>2022-10-22 03:29:52 +0300
commit41fc502564501e4956c803b80f03680a74ecb678 (patch)
tree2276335a2e4c6e4cfd88bcb47a5d980543b4f5e6
parentb4554d2fc1fbc7a8c6ed17171e37ffac724e780b (diff)
Generate type declarations for CompositionAPI and publish with OpenMCT (#5838)
* add typescript * update tsconfig * convert to es6 class * Convert more stuff to es6 class * skip checking libs, test files * more es6 classes! * Fix some jsdocs * Rename file * Improve jsdoc types * Rename references as well * more types * types for CompositionAPI * Types for CompositionCollection * Types for CompositionProvider * type * types for api * nvm * cleanup MCT * Fix API type definition * Generate types before publish * fix openmct 👀 * rename PublicAPI -> OpenMCT and document methods * try and fix visual test ? * Make private methods private * more private methods!! * import all es6 api's so we get more types for free * convert Selection to es6 class * remove redundant docs * fix Branding types * fix openmct.start() types * Remove useless `@memberof` * Add parameter name * [docs] Add a section on Types * markdownlint * word * Add section on limitations / contibuting types * Let these methods be private * make private members private, fix a type * fix another type * Make method private * Update docs for `skipMutate` and related methods * Rename file and fix references * `DefaultCompositionProvider` extends `CompositionProvider` * Make private members private * Type for `AbortSignal` * `domainObject` must be accessible for perf tests Co-authored-by: Andrew Henry <akhenry@gmail.com>
-rw-r--r--API.md594
-rw-r--r--openmct.js45
-rw-r--r--package.json3
-rw-r--r--src/MCT.js10
-rw-r--r--src/api/Branding.js3
-rw-r--r--src/api/api.js4
-rw-r--r--src/api/composition/CompositionAPI.js105
-rw-r--r--src/api/composition/CompositionAPISpec.js538
-rw-r--r--src/api/composition/CompositionCollection.js302
-rw-r--r--src/api/composition/CompositionProvider.js262
-rw-r--r--src/api/composition/DefaultCompositionProvider.js248
-rw-r--r--src/api/objects/ObjectAPI.js22
-rw-r--r--src/selection/Selection.js425
-rw-r--r--tsconfig.json10
14 files changed, 1426 insertions, 1145 deletions
diff --git a/API.md b/API.md
index 0603e898c..8f5dc5526 100644
--- a/API.md
+++ b/API.md
@@ -1,11 +1,14 @@
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
-**Table of Contents**
+**Table of Contents**
-- [Building Applications With Open MCT](#building-applications-with-open-mct)
+- [Building Applications With Open MCT](#developing-applications-with-open-mct)
- [Scope and purpose of this document](#scope-and-purpose-of-this-document)
- [Building From Source](#building-from-source)
- [Starting an Open MCT application](#starting-an-open-mct-application)
+ - [Types](#types)
+ - [Using Types](#using-types)
+ - [Limitations](#limitations)
- [Plugins](#plugins)
- [Defining and Installing a New Plugin](#defining-and-installing-a-new-plugin)
- [Domain Objects and Identifiers](#domain-objects-and-identifiers)
@@ -61,18 +64,18 @@
## Scope and purpose of this document
-This document is intended to serve as a reference for developing an application
-based on Open MCT. It will provide details of the API functions necessary to
-extend the Open MCT platform meet common use cases such as integrating with a telemetry source.
+This document is intended to serve as a reference for developing an application
+based on Open MCT. It will provide details of the API functions necessary to
+extend the Open MCT platform meet common use cases such as integrating with a telemetry source.
-The best place to start is with the [Open MCT Tutorials](https://github.com/nasa/openmct-tutorial).
-These will walk you through the process of getting up and running with Open
+The best place to start is with the [Open MCT Tutorials](https://github.com/nasa/openmct-tutorial).
+These will walk you through the process of getting up and running with Open
MCT, as well as addressing some common developer use cases.
-## Building From Source
+## Building From Source
-The latest version of Open MCT is available from [our GitHub repository](https://github.com/nasa/openmct).
-If you have `git`, and `node` installed, you can build Open MCT with the commands
+The latest version of Open MCT is available from [our GitHub repository](https://github.com/nasa/openmct).
+If you have `git`, and `node` installed, you can build Open MCT with the commands
```bash
git clone https://github.com/nasa/openmct.git
@@ -80,28 +83,28 @@ cd openmct
npm install
```
-These commands will fetch the Open MCT source from our GitHub repository, and
-build a minified version that can be included in your application. The output
-of the build process is placed in a `dist` folder under the openmct source
-directory, which can be copied out to another location as needed. The contents
-of this folder will include a minified javascript file named `openmct.js` as
+These commands will fetch the Open MCT source from our GitHub repository, and
+build a minified version that can be included in your application. The output
+of the build process is placed in a `dist` folder under the openmct source
+directory, which can be copied out to another location as needed. The contents
+of this folder will include a minified javascript file named `openmct.js` as
well as assets such as html, css, and images necessary for the UI.
## Starting an Open MCT application
-To start a minimally functional Open MCT application, it is necessary to
-include the Open MCT distributable, enable some basic plugins, and bootstrap
-the application. The tutorials walk through the process of getting Open MCT up
-and running from scratch, but provided below is a minimal HTML template that
-includes Open MCT, installs some basic plugins, and bootstraps the application.
-It assumes that Open MCT is installed under an `openmct` subdirectory, as
-described in [Building From Source](#building-from-source).
+To start a minimally functional Open MCT application, it is necessary to
+include the Open MCT distributable, enable some basic plugins, and bootstrap
+the application. The tutorials walk through the process of getting Open MCT up
+and running from scratch, but provided below is a minimal HTML template that
+includes Open MCT, installs some basic plugins, and bootstraps the application.
+It assumes that Open MCT is installed under an `openmct` subdirectory, as
+described in [Building From Source](#building-from-source).
-This approach includes openmct using a simple script tag, resulting in a global
-variable named `openmct`. This `openmct` object is used subsequently to make
-API calls.
+This approach includes openmct using a simple script tag, resulting in a global
+variable named `openmct`. This `openmct` object is used subsequently to make
+API calls.
-Open MCT is packaged as a UMD (Universal Module Definition) module, so common
+Open MCT is packaged as a UMD (Universal Module Definition) module, so common
script loaders are also supported.
```html
@@ -122,17 +125,59 @@ script loaders are also supported.
</html>
```
-The Open MCT library included above requires certain assets such as html
-templates, images, and css. If you installed Open MCT from GitHub as described
+The Open MCT library included above requires certain assets such as html
+templates, images, and css. If you installed Open MCT from GitHub as described
in the section on [Building from Source](#building-from-source) then these
-assets will have been downloaded along with the Open MCT javascript library.
+assets will have been downloaded along with the Open MCT javascript library.
-There are some plugins bundled with the application that provide UI,
-persistence, and other default configuration which are necessary to be able to
-do anything with the application initially. Any of these plugins can, in
-principle, be replaced with a custom plugin. The included plugins are
+There are some plugins bundled with the application that provide UI,
+persistence, and other default configuration which are necessary to be able to
+do anything with the application initially. Any of these plugins can, in
+principle, be replaced with a custom plugin. The included plugins are
documented in the [Included Plugins](#included-plugins) section.
+## Types
+
+The Open MCT library includes its own TypeScript declaration files which can be
+used to provide code hints and typechecking in your own Open MCT application.
+
+Open MCT's type declarations are generated via `tsc` from JSDoc-style comment
+blocks. For more information on this, [check out TypeScript's documentation](https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html).
+
+### Using Types
+
+In order to use Open MCT's provided types in your own application, create a
+`jsconfig.js` at the root of your project with this minimal configuration:
+
+```json
+{
+ "compilerOptions": {
+ "baseUrl": "./",
+ "target": "es6",
+ "checkJs": true,
+ "moduleResolution": "node",
+ "paths": {
+ "openmct": ["node_modules/openmct/dist/openmct.d.ts"]
+ }
+ }
+}
+```
+
+Then, simply import and use `openmct` in your application:
+
+```js
+import openmct from "openmct";
+```
+
+### Limitations
+
+The effort to add types for Open MCT's public API is ongoing, and the provided
+type declarations may be incomplete.
+
+If you would like to contribute types to Open MCT, please check out
+[TypeScript's documentation](https://www.typescriptlang.org/docs/handbook/declaration-files/dts-from-js.html) on generating type declarations from JSDoc-style comment blocks.
+Then read through our [contributing guide](https://github.com/nasa/openmct/blob/f7cf3f72c2efd46da7ce5719c5e52c8806d166f0/CONTRIBUTING.md) and open a PR!
+
## Plugins
### Defining and Installing a New Plugin
@@ -145,10 +190,10 @@ openmct.install(function install(openmctAPI) {
```
New plugins are installed in Open MCT by calling `openmct.install`, and
-providing a plugin installation function. This function will be invoked on
-application startup with one parameter - the openmct API object. A common
-approach used in the Open MCT codebase is to define a plugin as a function that
-returns this installation function. This allows configuration to be specified
+providing a plugin installation function. This function will be invoked on
+application startup with one parameter - the openmct API object. A common
+approach used in the Open MCT codebase is to define a plugin as a function that
+returns this installation function. This allows configuration to be specified
when the plugin is included.
eg.
@@ -161,16 +206,16 @@ This approach can be seen in all of the [plugins provided with Open MCT](https:/
## Domain Objects and Identifiers
-_Domain Objects_ are the basic entities that represent domain knowledge in Open
-MCT. The temperature sensor on a solar panel, an overlay plot comparing the
-results of all temperature sensors, the command dictionary for a spacecraft,
-the individual commands in that dictionary, the "My Items" folder: All of these
+_Domain Objects_ are the basic entities that represent domain knowledge in Open
+MCT. The temperature sensor on a solar panel, an overlay plot comparing the
+results of all temperature sensors, the command dictionary for a spacecraft,
+the individual commands in that dictionary, the "My Items" folder: All of these
things are domain objects.
A _Domain Object_ is simply a javascript object with some standard attributes.
-An example of a _Domain Object_ is the "My Items" object which is a folder in
-which a user can persist any objects that they create. The My Items object
-looks like this:
+An example of a _Domain Object_ is the "My Items" object which is a folder in
+which a user can persist any objects that they create. The My Items object
+looks like this:
```javascript
{
@@ -189,23 +234,24 @@ looks like this:
The main attributes to note are the `identifier`, and `type` attributes.
-* `identifier`: A composite key that provides a universally unique identifier
+- `identifier`: A composite key that provides a universally unique identifier
for this object. The `namespace` and `key` are used to identify the object.
- The `key` must be unique within the namespace.
-* `type`: All objects in Open MCT have a type. Types allow you to form an
- ontology of knowledge and provide an abstraction for grouping, visualizing,
- and interpreting data. Details on how to define a new object type are
- provided below.
+ The `key` must be unique within the namespace.
+- `type`: All objects in Open MCT have a type. Types allow you to form an
+ ontology of knowledge and provide an abstraction for grouping, visualizing,
+ and interpreting data. Details on how to define a new object type are
+ provided below.
-Open MCT uses a number of builtin types. Typically you are going to want to
+Open MCT uses a number of builtin types. Typically you are going to want to
define your own when extending Open MCT.
### Domain Object Types
-Custom types may be registered via the `addType` function on the Open MCT Type
+Custom types may be registered via the `addType` function on the Open MCT Type
registry.
eg.
+
```javascript
openmct.types.addType('example.my-type', {
name: "My Type",
@@ -215,37 +261,39 @@ openmct.types.addType('example.my-type', {
```
The `addType` function accepts two arguments:
-* A `string` key identifying the type. This key is used when specifying a type
+
+- A `string` key identifying the type. This key is used when specifying a type
for an object. We recommend prefixing your types with a namespace to avoid
conflicts with other plugins.
-* An object type specification. An object type definition supports the following
-attributes
- * `name`: a `string` naming this object type
- * `description`: a `string` specifying a longer-form description of this type
- * `initialize`: a `function` which initializes the model for new domain objects
- of this type. This can be used for setting default values on an object when
+- An object type specification. An object type definition supports the following
+attributes
+ - `name`: a `string` naming this object type
+ - `description`: a `string` specifying a longer-form description of this type
+ - `initialize`: a `function` which initializes the model for new domain objects
+ of this type. This can be used for setting default values on an object when
it is instantiated.
- * `creatable`: A `boolean` indicating whether users should be allowed to create
- this type (default: `false`). This will determine whether the type appears
+ - `creatable`: A `boolean` indicating whether users should be allowed to create
+ this type (default: `false`). This will determine whether the type appears
in the `Create` menu.
- * `cssClass`: A `string` specifying a CSS class to apply to each representation
- of this object. This is used for specifying an icon to appear next to each
+ - `cssClass`: A `string` specifying a CSS class to apply to each representation
+ of this object. This is used for specifying an icon to appear next to each
object of this type.
-The [Open MCT Tutorials](https://github.com/nasa/openmct-tutorial) provide a
-step-by-step examples of writing code for Open MCT that includes a [section on
+The [Open MCT Tutorials](https://github.com/nasa/openmct-tutorial) provide a
+step-by-step examples of writing code for Open MCT that includes a [section on
defining a new object type](https://github.com/nasa/openmct-tutorial#step-3---providing-objects).
## Root Objects
-In many cases, you'd like a certain object (or a certain hierarchy of objects)
-to be accessible from the top level of the application (the tree on the left-hand
-side of Open MCT.) For example, it is typical to expose a telemetry dictionary
+In many cases, you'd like a certain object (or a certain hierarchy of objects)
+to be accessible from the top level of the application (the tree on the left-hand
+side of Open MCT.) For example, it is typical to expose a telemetry dictionary
as a hierarchy of telemetry-providing domain objects in this fashion.
To do so, use the `addRoot` method of the object API.
eg.
+
```javascript
openmct.objects.addRoot({
namespace: "example.namespace",
@@ -254,12 +302,13 @@ openmct.objects.addRoot({
openmct.priority.HIGH);
```
-The `addRoot` function takes a two arguments, the first can be an [object identifier](#domain-objects-and-identifiers) for a root level object, or an array of identifiers for root
+The `addRoot` function takes a two arguments, the first can be an [object identifier](#domain-objects-and-identifiers) for a root level object, or an array of identifiers for root
level objects, or a function that returns a promise for an identifier or an array of root level objects, the second is a [priority](#priority-api) or numeric value.
When using the `getAll` method of the object API, they will be returned in order of priority.
eg.
+
```javascript
openmct.objects.addRoot(identifier, openmct.priority.LOW); // low = -1000, will appear last in composition or tree
openmct.objects.addRoot(otherIdentifier, openmct.priority.HIGH); // high = 1000, will appear first in composition or tree
@@ -269,11 +318,11 @@ Root objects are loaded just like any other objects, i.e. via an object provider
## Object Providers
-An Object Provider is used to build _Domain Objects_, typically retrieved from
-some source such as a persistence store or telemetry dictionary. In order to
-integrate telemetry from a new source an object provider will need to be created
-that can build objects representing telemetry points exposed by the telemetry
-source. The API call to define a new object provider is fairly straightforward.
+An Object Provider is used to build _Domain Objects_, typically retrieved from
+some source such as a persistence store or telemetry dictionary. In order to
+integrate telemetry from a new source an object provider will need to be created
+that can build objects representing telemetry points exposed by the telemetry
+source. The API call to define a new object provider is fairly straightforward.
Here's a very simple example:
```javascript
@@ -287,14 +336,15 @@ openmct.objects.addProvider('example.namespace', {
}
});
```
+
The `addProvider` function takes two arguments:
-* `namespace`: A `string` representing the namespace that this object provider
+- `namespace`: A `string` representing the namespace that this object provider
will provide objects for.
-* `provider`: An `object` with a single function, `get`. This function accepts an
-[Identifier](#domain-objects-and-identifiers) for the object to be provided.
-It is expected that the `get` function will return a
-[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
+- `provider`: An `object` with a single function, `get`. This function accepts an
+[Identifier](#domain-objects-and-identifiers) for the object to be provided.
+It is expected that the `get` function will return a
+[Promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise)
that resolves with the object being requested.
In future, object providers will support other methods to enable other operations with persistence stores, such as creating, updating, and deleting objects.
@@ -309,8 +359,8 @@ may be cases where you want to provide the composition of a certain object
### Adding Composition Providers
-You may want to populate a hierarchy under a custom root-level object based on
-the contents of a telemetry dictionary. To do this, you can add a new
+You may want to populate a hierarchy under a custom root-level object based on
+the contents of a telemetry dictionary. To do this, you can add a new
Composition Provider:
```javascript
@@ -323,19 +373,20 @@ openmct.composition.addProvider({
}
});
```
-The `addProvider` function accepts a Composition Provider object as its sole
+
+The `addProvider` function accepts a Composition Provider object as its sole
argument. A Composition Provider is a javascript object exposing two functions:
-* `appliesTo`: A `function` that accepts a `domainObject` argument, and returns
-a `boolean` value indicating whether this composition provider applies to the
+- `appliesTo`: A `function` that accepts a `domainObject` argument, and returns
+a `boolean` value indicating whether this composition provider applies to the
given object.
-* `load`: A `function` that accepts a `domainObject` as an argument, and returns
+- `load`: A `function` that accepts a `domainObject` as an argument, and returns
a `Promise` that resolves with an array of [Identifier](#domain-objects-and-identifiers).
These identifiers will be used to fetch Domain Objects from an [Object Provider](#object-provider)
### Default Composition Provider
-The default composition provider applies to any domain object with a
-`composition` property. The value of `composition` should be an array of
+The default composition provider applies to any domain object with a
+`composition` property. The value of `composition` should be an array of
identifiers, e.g.:
```javascript
@@ -369,7 +420,7 @@ Open MCT are stable and documentation is included below.
There are two main tasks for integrating telemetry sources-- describing telemetry objects with relevant metadata, and then providing telemetry data for those objects. You'll use an [Object Provider](#object-providers) to provide objects with the necessary [Telemetry Metadata](#telemetry-metadata), and then register a [Telemetry Provider](#telemetry-providers) to retrieve telemetry data for those objects. Alternatively, you can register a telemetry metadata provider to provide the necessary telemetry metadata.
-For a step-by-step guide to building a telemetry adapter, please see the
+For a step-by-step guide to building a telemetry adapter, please see the
[Open MCT Tutorials](https://github.com/nasa/openmct-tutorial).
#### Telemetry Metadata
@@ -429,24 +480,22 @@ attribute | type | flags | notes
`max` | number | optional | the maximum possible value of this measurement. Will be used by plots, gauges, etc to automatically set a max value.
`enumerations` | array | optional | for objects where `format` is `"enum"`, this array tracks all possible enumerations of the value. Each entry in this array is an object, with a `value` property that is the numerical value of the enumeration, and a `string` property that is the text value of the enumeration. ex: `{"value": 0, "string": "OFF"}`. If you use an enumerations array, `min` and `max` will be set automatically for you.
-
###### Value Hints
Each telemetry value description has an object defining hints. Keys in this object represent the hint itself, and the value represents the weight of that hint. A lower weight means the hint has a higher priority. For example, multiple values could be hinted for use as the y-axis of a plot (raw, engineering), but the highest priority would be the default choice. Likewise, a table will use hints to determine the default order of columns.
Known hints:
-* `domain`: Values with a `domain` hint will be used for the x-axis of a plot, and tables will render columns for these values first.
-* `range`: Values with a `range` hint will be used as the y-axis on a plot, and tables will render columns for these values after the `domain` values.
-* `image`: Indicates that the value may be interpreted as the URL to an image file, in which case appropriate views will be made available.
-* `imageDownloadName`: Indicates that the value may be interpreted as the name of the image file.
+- `domain`: Values with a `domain` hint will be used for the x-axis of a plot, and tables will render columns for these values first.
+- `range`: Values with a `range` hint will be used as the y-axis on a plot, and tables will render columns for these values after the `domain` values.
+- `image`: Indicates that the value may be interpreted as the URL to an image file, in which case appropriate views will be made available.
+- `imageDownloadName`: Indicates that the value may be interpreted as the name of the image file.
-##### The Time Conductor and Telemetry
+##### The Time Conductor and Telemetry
Open MCT provides a number of ways to pivot through data and link data via time. The Time Conductor helps synchronize multiple views around the same time.
-In order for the time conductor to work, there will always be an active "time system". All telemetry metadata *must* have a telemetry value with a `key` that matches the `key` of the active time system. You can use the `source` attribute on the value metadata to remap this to a different field in the telemetry datum-- especially useful if you are working with disparate datasources that have different field mappings.
-
+In order for the time conductor to work, there will always be an active "time system". All telemetry metadata _must_ have a telemetry value with a `key` that matches the `key` of the active time system. You can use the `source` attribute on the value metadata to remap this to a different field in the telemetry datum-- especially useful if you are working with disparate datasources that have different field mappings.
#### Telemetry Providers
@@ -454,14 +503,14 @@ Telemetry providers are responsible for providing historical and real-time telem
A telemetry provider is a javascript object with up to four methods:
-* `supportsSubscribe(domainObject, callback, options)` optional. Must be implemented to provide realtime telemetry. Should return `true` if the provider supports subscriptions for the given domain object (and request options).
-* `subscribe(domainObject, callback, options)` required if `supportsSubscribe` is implemented. Establish a subscription for realtime data for the given domain object. Should invoke `callback` with a single telemetry datum every time data is received. Must return an unsubscribe function. Multiple views can subscribe to the same telemetry object, so it should always return a new unsubscribe function.
-* `supportsRequest(domainObject, options)` optional. Must be implemented to provide historical telemetry. Should return `true` if the provider supports historical requests for the given domain object.
-* `request(domainObject, options)` required if `supportsRequest` is implemented. Must return a promise for an array of telemetry datums that fulfills the request. The `options` argument will include a `start`, `end`, and `domain` attribute representing the query bounds. See [Telemetry Requests and Responses](#telemetry-requests-and-responses) for more info on how to respond to requests.
-* `supportsMetadata(domainObject)` optional. Implement and return `true` for objects that you want to provide dynamic metadata for.
-* `getMetadata(domainObject)` required if `supportsMetadata` is implemented. Must return a valid telemetry metadata definition that includes at least one valueMetadata definition.
-* `supportsLimits(domainObject)` optional. Implement and return `true` for domain objects that you want to provide a limit evaluator for.
-* `getLimitEvaluator(domainObject)` required if `supportsLimits` is implemented. Must return a valid LimitEvaluator for a given domain object.
+- `supportsSubscribe(domainObject, callback, options)` optional. Must be implemented to provide realtime telemetry. Should return `true` if the provider supports subscriptions for the given domain object (and request options).
+- `subscribe(domainObject, callback, options)` required if `supportsSubscribe` is implemented. Establish a subscription for realtime data for the given domain object. Should invoke `callback` with a single telemetry datum every time data is received. Must return an unsubscribe function. Multiple views can subscribe to the same telemetry object, so it should always return a new unsubscribe function.
+- `supportsRequest(domainObject, options)` optional. Must be implemented to provide historical telemetry. Should return `true` if the provider supports historical requests for the given domain object.
+- `request(domainObject, options)` required if `supportsRequest` is implemented. Must return a promise for an array of telemetry datums that fulfills the request. The `options` argument will include a `start`, `end`, and `domain` attribute representing the query bounds. See [Telemetry Requests and Responses](#telemetry-requests-and-responses) for more info on how to respond to requests.
+- `supportsMetadata(domainObject)` optional. Implement and return `true` for objects that you want to provide dynamic metadata for.
+- `getMetadata(domainObject)` required if `supportsMetadata` is implemented. Must return a valid telemetry metadata definition that includes at least one valueMetadata definition.
+- `supportsLimits(domainObject)` optional. Implement and return `true` for domain objects that you want to provide a limit evaluator for.
+- `getLimitEvaluator(domainObject)` required if `supportsLimits` is implemented. Must return a valid LimitEvaluator for a given domain object.
Telemetry providers are registered by calling `openmct.telemetry.addProvider(provider)`, e.g.
@@ -474,7 +523,7 @@ openmct.telemetry.addProvider({
Note: it is not required to implement all of the methods on every provider. Depending on the complexity of your implementation, it may be helpful to instantiate and register your realtime, historical, and metadata providers separately.
-#### Telemetry Requests and Responses.
+#### Telemetry Requests and Responses
Telemetry requests support time bounded queries. A call to a _Telemetry Provider_'s `request` function will include an `options` argument. These are simply javascript objects with attributes for the request parameters. An example of a telemetry request object with a start and end time is included below:
@@ -507,6 +556,7 @@ the number of results it desires. The `size` parameter is a hint; views
must not assume the response will have the exact number of results requested.
example:
+
```javascript
{
start: 1487981997240,
@@ -522,6 +572,7 @@ This strategy says "I want the latest data point in this time range". A provide
##### `minmax` request strategy
example:
+
```javascript
{
start: 1487981997240,
@@ -536,28 +587,28 @@ MinMax queries are issued by plots, and may be issued by other types as well. T
#### Telemetry Formats
-Telemetry format objects define how to interpret and display telemetry data.
+Telemetry format objects define how to interpret and display telemetry data.
They have a simple structure:
-* `key`: A `string` that uniquely identifies this formatter.
-* `format`: A `function` that takes a raw telemetry value, and returns a
- human-readable `string` representation of that value. It has one required
- argument, and three optional arguments that provide context and can be used
- for returning scaled representations of a value. An example of this is
- representing time values in a scale such as the time conductor scale. There
+- `key`: A `string` that uniquely identifies this formatter.
+- `format`: A `function` that takes a raw telemetry value, and returns a
+ human-readable `string` representation of that value. It has one required
+ argument, and three optional arguments that provide context and can be used
+ for returning scaled representations of a value. An example of this is
+ representing time values in a scale such as the time conductor scale. There
are multiple ways of representing a point in time, and by providing a minimum
scale value, maximum scale value, and a count, it's possible to provide more
useful representations of time given the provided limitations.
- * `value`: The raw telemetry value in its native type.
- * `minValue`: An __optional__ argument specifying the minimum displayed
+ - `value`: The raw telemetry value in its native type.
+ - `minValue`: An **optional** argument specifying the minimum displayed
value.
- * `maxValue`: An __optional__ argument specifying the maximum displayed
+ - `maxValue`: An **optional** argument specifying the maximum displayed
value.
- * `count`: An __optional__ argument specifying the number of displayed
+ - `count`: An **optional** argument specifying the number of displayed
values.
-* `parse`: A `function` that takes a `string` representation of a telemetry
+- `parse`: A `function` that takes a `string` representation of a telemetry
value, and returns the value in its native type. **Note** parse might receive an already-parsed value. This function should be idempotent.
-* `validate`: A `function` that takes a `string` representation of a telemetry
+- `validate`: A `function` that takes a `string` representation of a telemetry
value, and returns a `boolean` value indicating whether the provided string
can be parsed.
@@ -583,9 +634,9 @@ openmct.telemetry.addFormat({
#### Telemetry Data
A single telemetry point is considered a Datum, and is represented by a standard
-javascript object. Realtime subscriptions (obtained via __subscribe__) will
+javascript object. Realtime subscriptions (obtained via **subscribe**) will
invoke the supplied callback once for each telemetry datum recieved. Telemetry
-requests (obtained via __request__) will return a promise for an array of
+requests (obtained via **request**) will return a promise for an array of
telemetry datums.
##### Telemetry Datums
@@ -606,14 +657,14 @@ section.
#### Limit Evaluators **draft**
-Limit evaluators allow a telemetry integrator to define which limits exist for a
+Limit evaluators allow a telemetry integrator to define which limits exist for a
telemetry endpoint and how limits should be applied to telemetry from a given domain object.
A limit evaluator can implement the `evalute` method which is used to define how limits
-should be applied to telemetry and the `getLimits` method which is used to specify
+should be applied to telemetry and the `getLimits` method which is used to specify
what the limit values are for different limit levels.
-Limit levels can be mapped to one of 5 colors for visualization:
+Limit levels can be mapped to one of 5 colors for visualization:
`purple`, `red`, `orange`, `yellow` and `cyan`.
For an example of a limit evaluator, take a look at `examples/generator/SinewaveLimitProvider.js`.
@@ -622,30 +673,29 @@ For an example of a limit evaluator, take a look at `examples/generator/Sinewave
The APIs for requesting telemetry from Open MCT -- e.g. for use in custom views -- are currently in draft state and are being revised. If you'd like to experiment with them before they are finalized, please contact the team via the contact-us link on our website.
-
## Time API
Open MCT provides API for managing the temporal state of the application.
-Central to this is the concept of "time bounds". Views in Open MCT will
-typically show telemetry data for some prescribed date range, and the Time API
+Central to this is the concept of "time bounds". Views in Open MCT will
+typically show telemetry data for some prescribed date range, and the Time API
provides a way to centrally manage these bounds.
-The Time API exposes a number of methods for querying and setting the temporal
+The Time API exposes a number of methods for querying and setting the temporal
state of the application, and emits events to inform listeners when the state changes.
-Because the data displayed tends to be time domain data, Open MCT must always
+Because the data displayed tends to be time domain data, Open MCT must always
have at least one time system installed and activated. When you download Open
-MCT, it will be pre-configured to use the UTC time system, which is installed and activated, along with other default plugins, in `index.html`. Installing and activating a time system is simple, and is covered
-[in the next section](#defining-and-registering-time-systems).
+MCT, it will be pre-configured to use the UTC time system, which is installed and activated, along with other default plugins, in `index.html`. Installing and activating a time system is simple, and is covered
+[in the next section](#defining-and-registering-time-systems).
### Time Systems and Bounds
#### Defining and Registering Time Systems
-The time bounds of an Open MCT application are defined as numbers, and a Time
-System gives meaning and context to these numbers so that they can be correctly
-interpreted. Time Systems are JavaScript objects that provide some information
-about the current time reference frame. An example of defining and registering
+The time bounds of an Open MCT application are defined as numbers, and a Time
+System gives meaning and context to these numbers so that they can be correctly
+interpreted. Time Systems are JavaScript objects that provide some information
+about the current time reference frame. An example of defining and registering
a new time system is given below:
``` javascript
@@ -659,31 +709,31 @@ openmct.time.addTimeSystem({
});
```
-The example above defines a new utc based time system. In fact, this time system
-is configured and activated by default from `index.html` in the default
-installation of Open MCT if you download the source from GitHub. Some details of
+The example above defines a new utc based time system. In fact, this time system
+is configured and activated by default from `index.html` in the default
+installation of Open MCT if you download the source from GitHub. Some details of
each of the required properties is provided below.
-* `key`: A `string` that uniquely identifies this time system.
-* `name`: A `string` providing a brief human readable label. If the [Time Conductor](#the-time-conductor)
+- `key`: A `string` that uniquely identifies this time system.
+- `name`: A `string` providing a brief human readable label. If the [Time Conductor](#the-time-conductor)
plugin is enabled, this name will identify the time system in a dropdown menu.
-* `cssClass`: A class name `string` that will be applied to the time system when
-it appears in the UI. This will be used to represent the time system with an icon.
-There are a number of built-in icon classes [available in Open MCT](https://github.com/nasa/openmct/blob/master/platform/commonUI/general/res/sass/_glyphs.scss),
-or a custom class can be used here.
-* `timeFormat`: A `string` corresponding to the key of a registered
-[telemetry time format](#telemetry-formats). The format will be used for
-displaying discrete timestamps from telemetry streams when this time system is
-activated. If the [UTCTimeSystem](#included-plugins) is enabled, then the `utc`
+- `cssClass`: A class name `string` that will be applied to the time system when
+it appears in the UI. This will be used to represent the time system with an icon.
+There are a number of built-in icon classes [available in Open MCT](https://github.com/nasa/openmct/blob/master/platform/commonUI/general/res/sass/_glyphs.scss),
+or a custom class can be used here.
+- `timeFormat`: A `string` corresponding to the key of a registered
+[telemetry time format](#telemetry-formats). The format will be used for
+displaying discrete timestamps from telemetry streams when this time system is
+activated. If the [UTCTimeSystem](#included-plugins) is enabled, then the `utc`
format can be used if this is a utc-based time system
-* `durationFormat`: A `string` corresponding to the key of a registered
-[telemetry time format](#telemetry-formats). The format will be used for
-displaying time ranges, for example `00:15:00` might be used to represent a time
+- `durationFormat`: A `string` corresponding to the key of a registered
+[telemetry time format](#telemetry-formats). The format will be used for
+displaying time ranges, for example `00:15:00` might be used to represent a time
period of fifteen minutes. These are used by the Time Conductor plugin to specify
-relative time offsets. If the [UTCTimeSystem](#included-plugins) is enabled,
+relative time offsets. If the [UTCTimeSystem](#included-plugins) is enabled,
then the `duration` format can be used if this is a utc-based time system
-* `isUTCBased`: A `boolean` that defines whether this time system represents
-numbers in UTC terrestrial time.
+- `isUTCBased`: A `boolean` that defines whether this time system represents
+numbers in UTC terrestrial time.
#### Getting and Setting the Active Time System
@@ -696,30 +746,30 @@ timeSystem.
openmct.time.timeSystem('utc', bounds);
```
-A time system can be immediately activated after registration:
+A time system can be immediately activated after registration:
```javascript
openmct.time.addTimeSystem(utcTimeSystem);
openmct.time.timeSystem(utcTimeSystem, bounds);
```
-Setting the active time system will trigger a [`'timeSystem'`](#time-events)
+Setting the active time system will trigger a [`'timeSystem'`](#time-events)
event. If you supplied bounds, a [`'bounds'`](#time-events) event will be triggered afterwards with your newly supplied bounds.
#### Time Bounds
-The TimeAPI provides a getter/setter for querying and setting time bounds. Time
+The TimeAPI provides a getter/setter for querying and setting time bounds. Time
bounds are simply an object with a `start` and an end `end` attribute.
-* `start`: A `number` representing a moment in time in the active [Time System](#defining-and-registering-time-systems).
+- `start`: A `number` representing a moment in time in the active [Time System](#defining-and-registering-time-systems).
This will be used as the beginning of the time period displayed by time-responsive
telemetry views.
-* `end`: A `number` representing a moment in time in the active [Time System](#defining-and-registering-time-systems).
+- `end`: A `number` representing a moment in time in the active [Time System](#defining-and-registering-time-systems).
This will be used as the end of the time period displayed by time-responsive
telemetry views.
-If invoked with bounds, it will set the new time bounds system-wide. If invoked
-without any parameters, it will return the current application-wide time bounds.
+If invoked with bounds, it will set the new time bounds system-wide. If invoked
+without any parameters, it will return the current application-wide time bounds.
``` javascript
const ONE_HOUR = 60 * 60 * 1000;
@@ -734,16 +784,16 @@ event.
The Time API can be set to follow a clock source which will cause the bounds
to be updated automatically whenever the clock source "ticks". A clock is simply
-an object that supports registration of listeners and periodically invokes its
-listeners with a number. Open MCT supports registration of new clock sources that
-tick on almost anything. A tick occurs when the clock invokes callback functions
+an object that supports registration of listeners and periodically invokes its
+listeners with a number. Open MCT supports registration of new clock sources that
+tick on almost anything. A tick occurs when the clock invokes callback functions
registered by its listeners with a new time value.
-An example of a clock source is the [LocalClock](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/LocalClock.js)
-which emits the current time in UTC every 100ms. Clocks can tick on anything. For
-example, a clock could be defined to provide the timestamp of any new data
-received via a telemetry subscription. This would have the effect of advancing
-the bounds of views automatically whenever data is received. A clock could also
+An example of a clock source is the [LocalClock](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/LocalClock.js)
+which emits the current time in UTC every 100ms. Clocks can tick on anything. For
+example, a clock could be defined to provide the timestamp of any new data
+received via a telemetry subscription. This would have the effect of advancing
+the bounds of views automatically whenever data is received. A clock could also
be defined to tick on some remote timing source.
The values provided by clocks are simple `number`s, which are interpreted in the
@@ -753,32 +803,32 @@ context of the active [Time System](#defining-and-registering-time-systems).
A clock is an object that defines certain required metadata and functions:
-* `key`: A `string` uniquely identifying this clock. This can be used later to
+- `key`: A `string` uniquely identifying this clock. This can be used later to
reference the clock in places such as the [Time Conductor configuration](#time-conductor-configuration)
-* `cssClass`: A `string` identifying a CSS class to apply to this clock when it's
-displayed in the UI. This will be used to represent the time system with an icon.
-There are a number of built-in icon classes [available in Open MCT](https://github.com/nasa/openmct/blob/master/platform/commonUI/general/res/sass/_glyphs.scss),
-or a custom class can be used here.
-* `name`: A `string` providing a human-readable identifier for the clock source.
-This will be displayed in the clock selector menu in the Time Conductor UI
-component, if active.
-* `description`: An __optional__ `string` providing a longer description of the
-clock. The description will be visible in the clock selection menu in the Time
+- `cssClass`: A `string` identifying a CSS class to apply to this clock when it's
+displayed in the UI. This will be used to represent the time system with an icon.
+There are a number of built-in icon classes [available in Open MCT](https://github.com/nasa/openmct/blob/master/platform/commonUI/general/res/sass/_glyphs.scss),
+or a custom class can be used here.
+- `name`: A `string` providing a human-readable identifier for the clock source.
+This will be displayed in the clock selector menu in the Time Conductor UI
+component, if active.
+- `description`: An **optional** `string` providing a longer description of the
+clock. The description will be visible in the clock selection menu in the Time
Conductor plugin.
-* `on`: A `function` supporting registration of a new callback that will be
+- `on`: A `function` supporting registration of a new callback that will be
invoked when the clock next ticks. It will be invoked with two arguments:
- * `eventName`: A `string` specifying the event to listen on. For now, clocks
+ - `eventName`: A `string` specifying the event to listen on. For now, clocks
support one event - `tick`.
- * `callback`: A `function` that will be invoked when this clock ticks. The
+ - `callback`: A `function` that will be invoked when this clock ticks. The
function must be invoked with one parameter - a `number` representing a valid
time in the current time system.
-* `off`: A `function` that allows deregistration of a tick listener. It accepts
+- `off`: A `function` that allows deregistration of a tick listener. It accepts
the same arguments as `on`.
-* `currentValue`: A `function` that returns a `number` representing a point in
-time in the active time system. It should be the last value provided by a tick,
+- `currentValue`: A `function` that returns a `number` representing a point in
+time in the active time system. It should be the last value provided by a tick,
or some default value if no ticking has yet occurred.
-A new clock can be registered using the `addClock` function exposed by the Time
+A new clock can be registered using the `addClock` function exposed by the Time
API:
```javascript
@@ -805,26 +855,25 @@ An example clock implementation is provided in the form of the [LocalClock](http
#### Getting and setting active clock
-Once registered a clock can be activated by calling the `clock` function on the
-Time API passing in the key or instance of a registered clock. Only one clock
-may be active at once, so activating a clock will deactivate any currently
+Once registered a clock can be activated by calling the `clock` function on the
+Time API passing in the key or instance of a registered clock. Only one clock
+may be active at once, so activating a clock will deactivate any currently
active clock. [`clockOffsets`](#clock-offsets) must be specified when changing a clock.
Setting the clock triggers a [`'clock'`](#time-events) event, followed by a [`'clockOffsets'`](#time-events) event, and then a [`'bounds'`](#time-events) event as the offsets are applied to the clock's currentValue().
-
```
openmct.time.clock(someClock, clockOffsets);
```
Upon being activated, the time API will listen for tick events on the clock by calling `clock.on`.
-The currently active clock (if any) can be retrieved by calling the same
+The currently active clock (if any) can be retrieved by calling the same
function without any arguments.
#### Stopping an active clock
-The `stopClock` method can be used to stop an active clock, and to clear it. It
+The `stopClock` method can be used to stop an active clock, and to clear it. It
will stop the clock from ticking, and set the active clock to `undefined`.
``` javascript
@@ -833,22 +882,22 @@ openmct.time.stopClock();
#### Clock Offsets
-When a clock is active, the time bounds of the application will be updated
-automatically each time the clock "ticks". The bounds are calculated based on
-the current value provided by the active clock (via its `tick` event, or its
-`currentValue()` method).
+When a clock is active, the time bounds of the application will be updated
+automatically each time the clock "ticks". The bounds are calculated based on
+the current value provided by the active clock (via its `tick` event, or its
+`currentValue()` method).
Unlike bounds, which represent absolute time values, clock offsets represent
relative time spans. Offsets are defined as an object with two properties:
-* `start`: A `number` that must be < 0 and which is used to calculate the start
-bounds on each clock tick. The start offset will be calculated relative to the
+- `start`: A `number` that must be < 0 and which is used to calculate the start
+bounds on each clock tick. The start offset will be calculated relative to the
value provided by a clock's tick callback, or its `currentValue()` function.
-* `end`: A `number` that must be >= 0 and which is used to calculate the end
+- `end`: A `number` that must be >= 0 and which is used to calculate the end
bounds on each clock tick.
-The `clockOffsets` function can be used to get or set clock offsets. For example,
-to show the last fifteen minutes in a ms-based time system:
+The `clockOffsets` function can be used to get or set clock offsets. For example,
+to show the last fifteen minutes in a ms-based time system:
```javascript
var FIFTEEN_MINUTES = 15 * 60 * 1000;
@@ -859,8 +908,8 @@ openmct.time.clockOffsets({
})
```
-__Note:__ Setting the clock offsets will trigger an immediate bounds change, as
-new bounds will be calculated based on the `currentValue()` of the active clock.
+**Note:** Setting the clock offsets will trigger an immediate bounds change, as
+new bounds will be calculated based on the `currentValue()` of the active clock.
Clock offsets are only relevant when a clock source is active.
### Time Events
@@ -879,89 +928,88 @@ openmct.time.on('bounds', function callback (newBounds, tick) {
The events emitted by the Time API are:
-* `bounds`: emitted whenever the bounds change. The callback will be invoked
+- `bounds`: emitted whenever the bounds change. The callback will be invoked
with two arguments:
- * `bounds`: A [bounds](#getting-and-setting-bounds) bounds object
+ - `bounds`: A [bounds](#getting-and-setting-bounds) bounds object
representing a new time period bound by the specified start and send times.
- * `tick`: A `boolean` indicating whether or not this bounds change is due to
- a "tick" from a [clock source](#clocks). This information can be useful
- when determining a strategy for fetching telemetry data in response to a
- bounds change event. For example, if the bounds change was automatic, and
- is due to a tick then it's unlikely that you would need to perform a
- historical data query. It should be sufficient to just show any new
- telemetry received via subscription since the last tick, and optionally to
- discard any older data that now falls outside of the currently set bounds.
- If `tick` is false,then the bounds change was not due to an automatic tick,
- and a query for historical data may be necessary, depending on your data
+ - `tick`: A `boolean` indicating whether or not this bounds change is due to
+ a "tick" from a [clock source](#clocks). This information can be useful
+ when determining a strategy for fetching telemetry data in response to a
+ bounds change event. For example, if the bounds change was automatic, and
+ is due to a tick then it's unlikely that you would need to perform a
+ historical data query. It should be sufficient to just show any new
+ telemetry received via subscription since the last tick, and optionally to
+ discard any older data that now falls outside of the currently set bounds.
+ If `tick` is false,then the bounds change was not due to an automatic tick,
+ and a query for historical data may be necessary, depending on your data
caching strategy, and how significantly the start bound has changed.
-* `timeSystem`: emitted whenever the active time system changes. The callback will be invoked with a single argument:
- * `timeSystem`: The newly active [time system](#defining-and-registering-time-systems).
-* `clock`: emitted whenever the clock changes. The callback will be invoked
+- `timeSystem`: emitted whenever the active time system changes. The callback will be invoked with a single argument:
+ - `timeSystem`: The newly active [time system](#defining-and-registering-time-systems).
+- `clock`: emitted whenever the clock changes. The callback will be invoked
with a single argument:
- * `clock`: The newly active [clock](#clocks), or `undefined` if an active
+ - `clock`: The newly active [clock](#clocks), or `undefined` if an active
clock has been deactivated.
-* `clockOffsets`: emitted whenever the active clock offsets change. The
+- `clockOffsets`: emitted whenever the active clock offsets change. The
callback will be invoked with a single argument:
- * `clockOffsets`: The new [clock offsets](#clock-offsets).
-
+ - `clockOffsets`: The new [clock offsets](#clock-offsets).
### The Time Conductor
-The Time Conductor provides a user interface for managing time bounds in Open
+The Time Conductor provides a user interface for managing time bounds in Open
MCT. It allows a user to select from configured time systems and clocks, and to set bounds and clock offsets.
-If activated, the time conductor must be provided with configuration options,
+If activated, the time conductor must be provided with configuration options,
detailed below.
#### Time Conductor Configuration
-The time conductor is configured by specifying the options that will be
-available to the user from the menus in the time conductor. These will determine
-the clocks available from the conductor, the time systems available for each
-clock, and some default bounds and clock offsets for each combination of clock
-and time system. By default, the conductor always supports a `fixed` mode where
+The time conductor is configured by specifying the options that will be
+available to the user from the menus in the time conductor. These will determine
+the clocks available from the conductor, the time systems available for each
+clock, and some default bounds and clock offsets for each combination of clock
+and time system. By default, the conductor always supports a `fixed` mode where
no clock is active. To specify configuration for fixed mode, simply leave out a
`clock` attribute in the configuration entry object.
-Configuration is provided as an `array` of menu options. Each entry of the
+Configuration is provided as an `array` of menu options. Each entry of the
array is an object with some properties specifying configuration. The configuration
-options specified are slightly different depending on whether or not it is for
+options specified are slightly different depending on whether or not it is for
an active clock mode.
-__Configuration for Fixed Time Mode (no active clock)__
+**Configuration for Fixed Time Mode (no active clock)**
-* `timeSystem`: A `string`, the key for the time system that this configuration
+- `timeSystem`: A `string`, the key for the time system that this configuration
relates to.
-* `bounds`: A [`Time Bounds`](#time-bounds) object. These bounds will be applied
-when the user selects the time system specified in the previous `timeSystem`
+- `bounds`: A [`Time Bounds`](#time-bounds) object. These bounds will be applied
+when the user selects the time system specified in the previous `timeSystem`
property.
-* `zoomOutLimit`: An __optional__ `number` specifying the longest period of time
-that can be represented by the conductor when zooming. If a `zoomOutLimit` is
-provided, then a `zoomInLimit` must also be provided. If provided, the zoom
+- `zoomOutLimit`: An **optional** `number` specifying the longest period of time
+that can be represented by the conductor when zooming. If a `zoomOutLimit` is
+provided, then a `zoomInLimit` must also be provided. If provided, the zoom
slider will automatically become available in the Time Conductor UI.
-* `zoomInLimit`: An __optional__ `number` specifying the shortest period of time
-that can be represented by the conductor when zooming. If a `zoomInLimit` is
-provided, then a `zoomOutLimit` must also be provided. If provided, the zoom
+- `zoomInLimit`: An **optional** `number` specifying the shortest period of time
+that can be represented by the conductor when zooming. If a `zoomInLimit` is
+provided, then a `zoomOutLimit` must also be provided. If provided, the zoom
slider will automatically become available in the Time Conductor UI.
-__Configuration for Active Clock__
+**Configuration for Active Clock**
-* `clock`: A `string`, the `key` of the clock that this configuration applies to.
-* `timeSystem`: A `string`, the key for the time system that this configuration
-relates to. Separate configuration must be provided for each time system that you
+- `clock`: A `string`, the `key` of the clock that this configuration applies to.
+- `timeSystem`: A `string`, the key for the time system that this configuration
+relates to. Separate configuration must be provided for each time system that you
wish to be available to users when they select the specified clock.
-* `clockOffsets`: A [`clockOffsets`](#clock-offsets) object that will be
-automatically applied when the combination of clock and time system specified in
+- `clockOffsets`: A [`clockOffsets`](#clock-offsets) object that will be
+automatically applied when the combination of clock and time system specified in
this configuration is selected from the UI.
#### Example conductor configuration
-An example time conductor configuration is provided below. It sets up some
-default options for the [UTCTimeSystem](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/UTCTimeSystem.js)
-and [LocalTimeSystem](https://github.com/nasa/openmct/blob/master/src/plugins/localTimeSystem/LocalTimeSystem.js),
-in both fixed mode, and for the [LocalClock](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/LocalClock.js)
-source. In this configutation, the local clock supports both the UTCTimeSystem
-and LocalTimeSystem. Configuration for fixed bounds mode is specified by omitting
+An example time conductor configuration is provided below. It sets up some
+default options for the [UTCTimeSystem](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/UTCTimeSystem.js)
+and [LocalTimeSystem](https://github.com/nasa/openmct/blob/master/src/plugins/localTimeSystem/LocalTimeSystem.js),
+in both fixed mode, and for the [LocalClock](https://github.com/nasa/openmct/blob/master/src/plugins/utcTimeSystem/LocalClock.js)
+source. In this configutation, the local clock supports both the UTCTimeSystem
+and LocalTimeSystem. Configuration for fixed bounds mode is specified by omitting
a clock key.
``` javascript
@@ -997,26 +1045,27 @@ openmct.install(openmct.plugins.Conductor({
## Indicators
-Indicators are small widgets that reside at the bottom of the screen and are visible from
+Indicators are small widgets that reside at the bottom of the screen and are visible from
every screen in Open MCT. They can be used to convey system state using an icon and text.
-Typically an indicator will display an icon (customizable with a CSS class) that will
+Typically an indicator will display an icon (customizable with a CSS class) that will
reveal additional information when the mouse cursor is hovered over it.
### The URL Status Indicator
-A common use case for indicators is to convey the state of some external system such as a
-persistence backend or HTTP server. So long as this system is accessible via HTTP request,
-Open MCT provides a general purpose indicator to show whether the server is available and
+A common use case for indicators is to convey the state of some external system such as a
+persistence backend or HTTP server. So long as this system is accessible via HTTP request,
+Open MCT provides a general purpose indicator to show whether the server is available and
returning a 2xx status code. The URL Status Indicator is made available as a default plugin. See
-the [documentation](./src/plugins/URLIndicatorPlugin) for details on how to install and configure the
+the [documentation](./src/plugins/URLIndicatorPlugin) for details on how to install and configure the
URL Status Indicator.
### Creating a Simple Indicator
-A simple indicator with an icon and some text can be created and added with minimal code. An indicator
+A simple indicator with an icon and some text can be created and added with minimal code. An indicator
of this type exposes functions for customizing the text, icon, and style of the indicator.
eg.
+
``` javascript
var myIndicator = openmct.indicators.simpleIndicator();
myIndicator.text("Hello World!");
@@ -1025,24 +1074,24 @@ openmct.indicators.add(myIndicator);
This will create a new indicator and add it to the bottom of the screen in Open MCT.
By default, the indicator will appear as an information icon. Hovering over the icon will
-reveal the text set via the call to `.text()`. The Indicator object returned by the API
+reveal the text set via the call to `.text()`. The Indicator object returned by the API
call exposes a number of functions for customizing the content and appearance of the indicator:
-* `.text([text])`: Gets or sets the text shown when the user hovers over the indicator.
-Accepts an __optional__ `string` argument that, if provided, will be used to set the text.
-Hovering over the indicator will expand it to its full size, revealing this text alongside
+- `.text([text])`: Gets or sets the text shown when the user hovers over the indicator.
+Accepts an **optional** `string` argument that, if provided, will be used to set the text.
+Hovering over the indicator will expand it to its full size, revealing this text alongside
the icon. Returns the currently set text as a `string`.
-* `.description([description])`: Gets or sets the indicator's description. Accepts an
-__optional__ `string` argument that, if provided, will be used to set the text. The description
-allows for more detail to be provided in a tooltip when the user hovers over the indicator.
+- `.description([description])`: Gets or sets the indicator's description. Accepts an
+**optional** `string` argument that, if provided, will be used to set the text. The description
+allows for more detail to be provided in a tooltip when the user hovers over the indicator.
Returns the currently set text as a `string`.
-* `.iconClass([className])`: Gets or sets the CSS class used to define the icon. Accepts an __optional__
-`string` parameter to be used to set the class applied to the indicator. Any of
-[the built-in glyphs](https://nasa.github.io/openmct/style-guide/#/browse/styleguide:home/glyphs?view=styleguide.glyphs)
-may be used here, or a custom CSS class can be provided. Returns the currently defined CSS
+- `.iconClass([className])`: Gets or sets the CSS class used to define the icon. Accepts an **optional**
+`string` parameter to be used to set the class applied to the indicator. Any of
+[the built-in glyphs](https://nasa.github.io/openmct/style-guide/#/browse/styleguide:home/glyphs?view=styleguide.glyphs)
+may be used here, or a custom CSS class can be provided. Returns the currently defined CSS
class as a `string`.
-* `.statusClass([className])`: Gets or sets the CSS class used to determine status. Accepts an __optional __
-`string` parameter to be used to set a status class applied to the indicator. May be used to apply
+- `.statusClass([className])`: Gets or sets the CSS class used to determine status. Accepts an __optional__
+`string` parameter to be used to set a status class applied to the indicator. May be used to apply
different colors to indicate status.
### Custom Indicators
@@ -1068,6 +1117,7 @@ Open MCT provides some built-in priority values that can be used in the applicat
### Priority Types
Currently, the Open MCT Priority API provides (type: numeric value):
+
- HIGH: 1000
- Default: 0
- LOW: -1000
diff --git a/openmct.js b/openmct.js
index fe4ce8e62..e8ec87c07 100644
--- a/openmct.js
+++ b/openmct.js
@@ -30,8 +30,53 @@ if (document.currentScript) {
}
}
+/**
+ * @typedef {object} BuildInfo
+ * @property {string} version
+ * @property {string} buildDate
+ * @property {string} revision
+ * @property {string} branch
+ */
+
+/**
+ * @typedef {object} OpenMCT
+ * @property {BuildInfo} buildInfo
+ * @property {*} selection
+ * @property {import('./src/api/time/TimeAPI').default} time
+ * @property {import('./src/api/composition/CompositionAPI').default} composition
+ * @property {*} objectViews
+ * @property {*} inspectorViews
+ * @property {*} propertyEditors
+ * @property {*} toolbars
+ * @property {*} types
+ * @property {import('./src/api/objects/ObjectAPI').default} objects
+ * @property {import('./src/api/telemetry/TelemetryAPI').default} telemetry
+ * @property {import('./src/api/indicators/IndicatorAPI').default} indicators
+ * @property {import('./src/api/user/UserAPI').default} user
+ * @property {import('./src/api/notifications/NotificationAPI').default} notifications
+ * @property {import('./src/api/Editor').default} editor
+ * @property {import('./src/api/overlays/OverlayAPI')} overlays
+ * @property {import('./src/api/menu/MenuAPI').default} menus
+ * @property {import('./src/api/actions/ActionsAPI').default} actions
+ * @property {import('./src/api/status/StatusAPI').default} status
+ * @property {*} priority
+ * @property {import('./src/ui/router/ApplicationRouter')} router
+ * @property {import('./src/api/faultmanagement/FaultManagementAPI').default} faults
+ * @property {import('./src/api/forms/FormsAPI').default} forms
+ * @property {import('./src/api/Branding').default} branding
+ * @property {import('./src/api/annotation/AnnotationAPI').default} annotation
+ * @property {{(plugin: OpenMCTPlugin) => void}} install
+ * @property {{() => string}} getAssetPath
+ * @property {{(domElement: HTMLElement, isHeadlessMode: boolean) => void}} start
+ * @property {{() => void}} startHeadless
+ * @property {{() => void}} destroy
+ * @property {OpenMCTPlugin[]} plugins
+ * @property {OpenMCTComponent[]} components
+ */
+
const MCT = require('./src/MCT');
+/** @type {OpenMCT} */
const openmct = new MCT();
module.exports = openmct;
diff --git a/package.json b/package.json
index d548fdbdd..2a7419a72 100644
--- a/package.json
+++ b/package.json
@@ -57,6 +57,7 @@
"sass-loader": "13.0.2",
"sinon": "14.0.0",
"style-loader": "^3.3.1",
+ "typescript": "4.8.4",
"uuid": "9.0.0",
"vue": "2.6.14",
"vue-eslint-parser": "9.1.0",
@@ -96,7 +97,7 @@
"cov:e2e:full:publish": "codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-full",
"cov:e2e:stable:publish": "codecov --disable=gcov -f ./coverage/e2e/lcov.info -F e2e-stable",
"cov:unit:publish": "codecov --disable=gcov -f ./coverage/unit/lcov.info -F unit",
- "prepare": "npm run build:prod"
+ "prepare": "npm run build:prod && npx tsc"
},
"repository": {
"type": "git",
diff --git a/src/MCT.js b/src/MCT.js
index 595afa7b0..1609f6588 100644
--- a/src/MCT.js
+++ b/src/MCT.js
@@ -19,7 +19,7 @@
* this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information.
*****************************************************************************/
-
+/* eslint-disable no-undef */
define([
'EventEmitter',
'./api/api',
@@ -81,13 +81,11 @@ define([
/**
* The Open MCT application. This may be configured by installing plugins
* or registering extensions before the application is started.
- * @class MCT
+ * @constructor
* @memberof module:openmct
- * @augments {EventEmitter}
*/
function MCT() {
EventEmitter.call(this);
- /* eslint-disable no-undef */
this.buildInfo = {
version: __OPENMCT_VERSION__,
buildDate: __OPENMCT_BUILD_DATE__,
@@ -101,7 +99,7 @@ define([
* Tracks current selection state of the application.
* @private
*/
- ['selection', () => new Selection(this)],
+ ['selection', () => new Selection.default(this)],
/**
* MCT's time conductor, which may be used to synchronize view contents
@@ -125,7 +123,7 @@ define([
* @memberof module:openmct.MCT#
* @name composition
*/
- ['composition', () => new api.CompositionAPI(this)],
+ ['composition', () => new api.CompositionAPI.default(this)],
/**
* Registry for views of domain objects which should appear in the
diff --git a/src/api/Branding.js b/src/api/Branding.js
index c44821741..26de8f197 100644
--- a/src/api/Branding.js
+++ b/src/api/Branding.js
@@ -23,8 +23,7 @@
let brandingOptions = {};
/**
- * @typedef {Object} BrandingOptions
- * @memberOf openmct/branding
+ * @typedef {object} BrandingOptions
* @property {string} smallLogoImage URL to the image to use as the applications logo.
* This logo will appear on every screen and when clicked will launch the about dialog.
* @property {string} aboutHtml Custom content for the about screen. When defined the
diff --git a/src/api/api.js b/src/api/api.js
index 505213476..24a35ee46 100644
--- a/src/api/api.js
+++ b/src/api/api.js
@@ -37,7 +37,9 @@ define([
'./types/TypeRegistry',
'./user/UserAPI',
'./annotation/AnnotationAPI'
-], function (
+],
+
+function (
ActionsAPI,
CompositionAPI,
EditorAPI,
diff --git a/src/api/composition/CompositionAPI.js b/src/api/composition/CompositionAPI.js
index 02dfb0315..96bc1faad 100644
--- a/src/api/composition/CompositionAPI.js
+++ b/src/api/composition/CompositionAPI.js
@@ -20,34 +20,41 @@
* at runtime from the About dialog for additional information.
*****************************************************************************/
-define([
- 'lodash',
- 'EventEmitter',
- './DefaultCompositionProvider',
- './CompositionCollection'
-], function (
- _,
- EventEmitter,
- DefaultCompositionProvider,
- CompositionCollection
-) {
+import DefaultCompositionProvider from './DefaultCompositionProvider';
+import CompositionCollection from './CompositionCollection';
+
+/**
+ * @typedef {import('./CompositionProvider').default} CompositionProvider
+ */
+
+/**
+ * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject
+ */
+
+/**
+ * @typedef {import('../../../openmct').OpenMCT} OpenMCT
+ */
+
+/**
+ * An interface for interacting with the composition of domain objects.
+ * The composition of a domain object is the list of other domain objects
+ * it "contains" (for instance, that should be displayed beneath it
+ * in the tree.)
+ * @constructor
+ */
+export default class CompositionAPI {
/**
- * An interface for interacting with the composition of domain objects.
- * The composition of a domain object is the list of other domain objects
- * it "contains" (for instance, that should be displayed beneath it
- * in the tree.)
- *
- * @interface CompositionAPI
- * @returns {module:openmct.CompositionCollection}
- * @memberof module:openmct
+ * @param {OpenMCT} publicAPI
*/
- function CompositionAPI(publicAPI) {
+ constructor(publicAPI) {
+ /** @type {CompositionProvider[]} */
this.registry = [];
+ /** @type {CompositionPolicy[]} */
this.policies = [];
this.addProvider(new DefaultCompositionProvider(publicAPI, this));
+ /** @type {OpenMCT} */
this.publicAPI = publicAPI;
}
-
/**
* Add a composition provider.
*
@@ -55,21 +62,19 @@ define([
* behavior for certain domain objects.
*
* @method addProvider
- * @param {module:openmct.CompositionProvider} provider the provider to add
- * @memberof module:openmct.CompositionAPI#
+ * @param {CompositionProvider} provider the provider to add
*/
- CompositionAPI.prototype.addProvider = function (provider) {
+ addProvider(provider) {
this.registry.unshift(provider);
- };
-
+ }
/**
* Retrieve the composition (if any) of this domain object.
*
* @method get
- * @returns {module:openmct.CompositionCollection}
- * @memberof module:openmct.CompositionAPI#
+ * @param {DomainObject} domainObject
+ * @returns {CompositionCollection}
*/
- CompositionAPI.prototype.get = function (domainObject) {
+ get(domainObject) {
const provider = this.registry.find(p => {
return p.appliesTo(domainObject);
});
@@ -79,8 +84,7 @@ define([
}
return new CompositionCollection(domainObject, provider, this.publicAPI);
- };
-
+ }
/**
* A composition policy is a function which either allows or disallows
* placing one object in another's composition.
@@ -90,52 +94,51 @@ define([
* generally be written to return true in the default case.
*
* @callback CompositionPolicy
- * @memberof module:openmct.CompositionAPI~
- * @param {module:openmct.DomainObject} containingObject the object which
+ * @param {DomainObject} containingObject the object which
* would act as a container
- * @param {module:openmct.DomainObject} containedObject the object which
+ * @param {DomainObject} containedObject the object which
* would be contained
* @returns {boolean} false if this composition should be disallowed
*/
-
/**
* Add a composition policy. Composition policies may disallow domain
* objects from containing other domain objects.
*
* @method addPolicy
- * @param {module:openmct.CompositionAPI~CompositionPolicy} policy
+ * @param {CompositionPolicy} policy
* the policy to add
- * @memberof module:openmct.CompositionAPI#
*/
- CompositionAPI.prototype.addPolicy = function (policy) {
+ addPolicy(policy) {
this.policies.push(policy);
- };
-
+ }
/**
* Check whether or not a domain object is allowed to contain another
* domain object.
*
* @private
* @method checkPolicy
- * @param {module:openmct.DomainObject} containingObject the object which
+ * @param {DomainObject} container the object which
* would act as a container
- * @param {module:openmct.DomainObject} containedObject the object which
+ * @param {DomainObject} containee the object which
* would be contained
* @returns {boolean} false if this composition should be disallowed
-
- * @param {module:openmct.CompositionAPI~CompositionPolicy} policy
+ * @param {CompositionPolicy} policy
* the policy to add
- * @memberof module:openmct.CompositionAPI#
*/
- CompositionAPI.prototype.checkPolicy = function (container, containee) {
+ checkPolicy(container, containee) {
return this.policies.every(function (policy) {
return policy(container, containee);
});
- };
+ }
- CompositionAPI.prototype.supportsComposition = function (domainObject) {
+ /**
+ * Check whether or not a domainObject supports composition
+ *
+ * @param {DomainObject} domainObject
+ * @returns {boolean} true if the domainObject supports composition
+ */
+ supportsComposition(domainObject) {
return this.get(domainObject) !== undefined;
- };
+ }
+}
- return CompositionAPI;
-});
diff --git a/src/api/composition/CompositionAPISpec.js b/src/api/composition/CompositionAPISpec.js
index 822e3fd02..f8d33ed07 100644
--- a/src/api/composition/CompositionAPISpec.js
+++ b/src/api/composition/CompositionAPISpec.js
@@ -1,325 +1,319 @@
-define([
- './CompositionAPI',
- './CompositionCollection'
-], function (
- CompositionAPI,
- CompositionCollection
-) {
-
- describe('The Composition API', function () {
- let publicAPI;
- let compositionAPI;
- let topicService;
- let mutationTopic;
+import CompositionAPI from './CompositionAPI';
+import CompositionCollection from './CompositionCollection';
+
+describe('The Composition API', function () {
+ let publicAPI;
+ let compositionAPI;
+ let topicService;
+ let mutationTopic;
+
+ beforeEach(function () {
+
+ mutationTopic = jasmine.createSpyObj('mutationTopic', [
+ 'listen'
+ ]);
+ topicService = jasmine.createSpy('topicService');
+ topicService.and.returnValue(mutationTopic);
+ publicAPI = {};
+ publicAPI.objects = jasmine.createSpyObj('ObjectAPI', [
+ 'get',
+ 'mutate',
+ 'observe',
+ 'areIdsEqual'
+ ]);
+
+ publicAPI.objects.areIdsEqual.and.callFake(function (id1, id2) {
+ return id1.namespace === id2.namespace && id1.key === id2.key;
+ });
- beforeEach(function () {
+ publicAPI.composition = jasmine.createSpyObj('CompositionAPI', [
+ 'checkPolicy'
+ ]);
+ publicAPI.composition.checkPolicy.and.returnValue(true);
- mutationTopic = jasmine.createSpyObj('mutationTopic', [
- 'listen'
- ]);
- topicService = jasmine.createSpy('topicService');
- topicService.and.returnValue(mutationTopic);
- publicAPI = {};
- publicAPI.objects = jasmine.createSpyObj('ObjectAPI', [
- 'get',
- 'mutate',
- 'observe',
- 'areIdsEqual'
- ]);
+ publicAPI.objects.eventEmitter = jasmine.createSpyObj('eventemitter', [
+ 'on'
+ ]);
+ publicAPI.objects.get.and.callFake(function (identifier) {
+ return Promise.resolve({identifier: identifier});
+ });
+ publicAPI.$injector = jasmine.createSpyObj('$injector', [
+ 'get'
+ ]);
+ publicAPI.$injector.get.and.returnValue(topicService);
+ compositionAPI = new CompositionAPI(publicAPI);
+ });
- publicAPI.objects.areIdsEqual.and.callFake(function (id1, id2) {
- return id1.namespace === id2.namespace && id1.key === id2.key;
- });
+ it('returns falsy if an object does not support composition', function () {
+ expect(compositionAPI.get({})).toBeFalsy();
+ });
- publicAPI.composition = jasmine.createSpyObj('CompositionAPI', [
- 'checkPolicy'
- ]);
- publicAPI.composition.checkPolicy.and.returnValue(true);
+ describe('default composition', function () {
+ let domainObject;
+ let composition;
- publicAPI.objects.eventEmitter = jasmine.createSpyObj('eventemitter', [
- 'on'
- ]);
- publicAPI.objects.get.and.callFake(function (identifier) {
- return Promise.resolve({identifier: identifier});
- });
- publicAPI.$injector = jasmine.createSpyObj('$injector', [
- 'get'
- ]);
- publicAPI.$injector.get.and.returnValue(topicService);
- compositionAPI = new CompositionAPI(publicAPI);
+ beforeEach(function () {
+ domainObject = {
+ name: 'test folder',
+ identifier: {
+ namespace: 'test',
+ key: '1'
+ },
+ composition: [
+ {
+ namespace: 'test',
+ key: 'a'
+ },
+ {
+ namespace: 'test',
+ key: 'b'
+ },
+ {
+ namespace: 'test',
+ key: 'c'
+ }
+ ]
+ };
+ composition = compositionAPI.get(domainObject);
});
- it('returns falsy if an object does not support composition', function () {
- expect(compositionAPI.get({})).toBeFalsy();
+ it('returns composition collection', function () {
+ expect(composition).toBeDefined();
+ expect(composition).toEqual(jasmine.any(CompositionCollection));
});
- describe('default composition', function () {
- let domainObject;
- let composition;
+ it('correctly reflects composability', function () {
+ expect(compositionAPI.supportsComposition(domainObject)).toBe(true);
+ delete domainObject.composition;
+ expect(compositionAPI.supportsComposition(domainObject)).toBe(false);
+ });
- beforeEach(function () {
- domainObject = {
- name: 'test folder',
+ it('loads composition from domain object', function () {
+ const listener = jasmine.createSpy('addListener');
+ composition.on('add', listener);
+
+ return composition.load().then(function () {
+ expect(listener.calls.count()).toBe(3);
+ expect(listener).toHaveBeenCalledWith({
identifier: {
namespace: 'test',
- key: '1'
- },
- composition: [
- {
- namespace: 'test',
- key: 'a'
- },
- {
- namespace: 'test',
- key: 'b'
- },
- {
- namespace: 'test',
- key: 'c'
- }
- ]
- };
- composition = compositionAPI.get(domainObject);
+ key: 'a'
+ }
+ });
});
+ });
+ describe('supports reordering of composition', function () {
+ let listener;
+ beforeEach(function () {
+ listener = jasmine.createSpy('reorderListener');
+ composition.on('reorder', listener);
- it('returns composition collection', function () {
- expect(composition).toBeDefined();
- expect(composition).toEqual(jasmine.any(CompositionCollection));
+ return composition.load();
});
+ it('', function () {
+ composition.reorder(1, 0);
+ let newComposition =
+ publicAPI.objects.mutate.calls.mostRecent().args[2];
+ let reorderPlan = listener.calls.mostRecent().args[0][0];
- it('correctly reflects composability', function () {
- expect(compositionAPI.supportsComposition(domainObject)).toBe(true);
- delete domainObject.composition;
- expect(compositionAPI.supportsComposition(domainObject)).toBe(false);
+ expect(reorderPlan.oldIndex).toBe(1);
+ expect(reorderPlan.newIndex).toBe(0);
+ expect(newComposition[0].key).toEqual('b');
+ expect(newComposition[1].key).toEqual('a');
+ expect(newComposition[2].key).toEqual('c');
});
+ it('', function () {
+ composition.reorder(0, 2);
+ let newComposition =
+ publicAPI.objects.mutate.calls.mostRecent().args[2];
+ let reorderPlan = listener.calls.mostRecent().args[0][0];
- it('loads composition from domain object', function () {
- const listener = jasmine.createSpy('addListener');
- composition.on('add', listener);
+ expect(reorderPlan.oldIndex).toBe(0);
+ expect(reorderPlan.newIndex).toBe(2);
+ expect(newComposition[0].key).toEqual('b');
+ expect(newComposition[1].key).toEqual('c');
+ expect(newComposition[2].key).toEqual('a');
+ });
+ });
+ it('supports adding an object to composition', function () {
+ let addListener = jasmine.createSpy('addListener');
+ let mockChildObject = {
+ identifier: {
+ key: 'mock-key',
+ namespace: ''
+ }
+ };
+ composition.on('add', addListener);
+ composition.add(mockChildObject);
+
+ expect(domainObject.composition.length).toBe(4);
+ expect(domainObject.composition[3]).toEqual(mockChildObject.identifier);
+ });
+ });
- return composition.load().then(function () {
- expect(listener.calls.count()).toBe(3);
- expect(listener).toHaveBeenCalledWith({
- identifier: {
- namespace: 'test',
- key: 'a'
+ describe('static custom composition', function () {
+ let customProvider;
+ let domainObject;
+ let composition;
+
+ beforeEach(function () {
+ // A simple custom provider, returns the same composition for
+ // all objects of a given type.
+ customProvider = {
+ appliesTo: function (object) {
+ return object.type === 'custom-object-type';
+ },
+ load: function (object) {
+ return Promise.resolve([
+ {
+ namespace: 'custom',
+ key: 'thing'
}
- });
- });
- });
- describe('supports reordering of composition', function () {
- let listener;
- beforeEach(function () {
- listener = jasmine.createSpy('reorderListener');
- composition.on('reorder', listener);
+ ]);
+ },
+ add: jasmine.createSpy('add'),
+ remove: jasmine.createSpy('remove')
+ };
+ domainObject = {
+ identifier: {
+ namespace: 'test',
+ key: '1'
+ },
+ type: 'custom-object-type'
+ };
+ compositionAPI.addProvider(customProvider);
+ composition = compositionAPI.get(domainObject);
+ });
- return composition.load();
- });
- it('', function () {
- composition.reorder(1, 0);
- let newComposition =
- publicAPI.objects.mutate.calls.mostRecent().args[2];
- let reorderPlan = listener.calls.mostRecent().args[0][0];
+ it('supports listening and loading', function () {
+ const addListener = jasmine.createSpy('addListener');
+ composition.on('add', addListener);
- expect(reorderPlan.oldIndex).toBe(1);
- expect(reorderPlan.newIndex).toBe(0);
- expect(newComposition[0].key).toEqual('b');
- expect(newComposition[1].key).toEqual('a');
- expect(newComposition[2].key).toEqual('c');
- });
- it('', function () {
- composition.reorder(0, 2);
- let newComposition =
- publicAPI.objects.mutate.calls.mostRecent().args[2];
- let reorderPlan = listener.calls.mostRecent().args[0][0];
+ return composition.load().then(function (children) {
+ let listenObject;
+ const loadedObject = children[0];
+
+ expect(addListener).toHaveBeenCalled();
- expect(reorderPlan.oldIndex).toBe(0);
- expect(reorderPlan.newIndex).toBe(2);
- expect(newComposition[0].key).toEqual('b');
- expect(newComposition[1].key).toEqual('c');
- expect(newComposition[2].key).toEqual('a');
+ listenObject = addListener.calls.mostRecent().args[0];
+ expect(listenObject).toEqual(loadedObject);
+ expect(loadedObject).toEqual({
+ identifier: {
+ namespace: 'custom',
+ key: 'thing'
+ }
});
});
- it('supports adding an object to composition', function () {
- let addListener = jasmine.createSpy('addListener');
- let mockChildObject = {
+ });
+ describe('Calling add or remove', function () {
+ let mockChildObject;
+
+ beforeEach(function () {
+ mockChildObject = {
identifier: {
key: 'mock-key',
namespace: ''
}
};
- composition.on('add', addListener);
composition.add(mockChildObject);
+ });
+
+ it('calls add on the provider', function () {
+ expect(customProvider.add).toHaveBeenCalledWith(domainObject, mockChildObject.identifier);
+ });
- expect(domainObject.composition.length).toBe(4);
- expect(domainObject.composition[3]).toEqual(mockChildObject.identifier);
+ it('calls remove on the provider', function () {
+ composition.remove(mockChildObject);
+ expect(customProvider.remove).toHaveBeenCalledWith(domainObject, mockChildObject.identifier);
});
});
+ });
- describe('static custom composition', function () {
- let customProvider;
- let domainObject;
- let composition;
+ describe('dynamic custom composition', function () {
+ let customProvider;
+ let domainObject;
+ let composition;
- beforeEach(function () {
- // A simple custom provider, returns the same composition for
- // all objects of a given type.
- customProvider = {
- appliesTo: function (object) {
- return object.type === 'custom-object-type';
- },
- load: function (object) {
- return Promise.resolve([
- {
- namespace: 'custom',
- key: 'thing'
- }
- ]);
- },
- add: jasmine.createSpy('add'),
- remove: jasmine.createSpy('remove')
- };
- domainObject = {
- identifier: {
- namespace: 'test',
- key: '1'
- },
- type: 'custom-object-type'
- };
- compositionAPI.addProvider(customProvider);
- composition = compositionAPI.get(domainObject);
- });
+ beforeEach(function () {
+ // A dynamic provider, loads an empty composition and exposes
+ // listener functions.
+ customProvider = jasmine.createSpyObj('dynamicProvider', [
+ 'appliesTo',
+ 'load',
+ 'on',
+ 'off'
+ ]);
- it('supports listening and loading', function () {
- const addListener = jasmine.createSpy('addListener');
- composition.on('add', addListener);
+ customProvider.appliesTo.and.returnValue('true');
+ customProvider.load.and.returnValue(Promise.resolve([]));
+
+ domainObject = {
+ identifier: {
+ namespace: 'test',
+ key: '1'
+ },
+ type: 'custom-object-type'
+ };
+ compositionAPI.addProvider(customProvider);
+ composition = compositionAPI.get(domainObject);
+ });
- return composition.load().then(function (children) {
- let listenObject;
- const loadedObject = children[0];
+ it('supports listening and loading', function () {
+ const addListener = jasmine.createSpy('addListener');
+ const removeListener = jasmine.createSpy('removeListener');
+ const addPromise = new Promise(function (resolve) {
+ addListener.and.callFake(resolve);
+ });
+ const removePromise = new Promise(function (resolve) {
+ removeListener.and.callFake(resolve);
+ });
- expect(addListener).toHaveBeenCalled();
+ composition.on('add', addListener);
+ composition.on('remove', removeListener);
+
+ expect(customProvider.on).toHaveBeenCalledWith(
+ domainObject,
+ 'add',
+ jasmine.any(Function),
+ jasmine.any(CompositionCollection)
+ );
+ expect(customProvider.on).toHaveBeenCalledWith(
+ domainObject,
+ 'remove',
+ jasmine.any(Function),
+ jasmine.any(CompositionCollection)
+ );
+ const add = customProvider.on.calls.all()[0].args[2];
+ const remove = customProvider.on.calls.all()[1].args[2];
+
+ return composition.load()
+ .then(function () {
+ expect(addListener).not.toHaveBeenCalled();
+ expect(removeListener).not.toHaveBeenCalled();
+ add({
+ namespace: 'custom',
+ key: 'thing'
+ });
- listenObject = addListener.calls.mostRecent().args[0];
- expect(listenObject).toEqual(loadedObject);
- expect(loadedObject).toEqual({
+ return addPromise;
+ }).then(function () {
+ expect(addListener).toHaveBeenCalledWith({
identifier: {
namespace: 'custom',
key: 'thing'
}
});
- });
- });
- describe('Calling add or remove', function () {
- let mockChildObject;
+ remove(addListener.calls.mostRecent().args[0]);
- beforeEach(function () {
- mockChildObject = {
+ return removePromise;
+ }).then(function () {
+ expect(removeListener).toHaveBeenCalledWith({
identifier: {
- key: 'mock-key',
- namespace: ''
- }
- };
- composition.add(mockChildObject);
- });
-
- it('calls add on the provider', function () {
- expect(customProvider.add).toHaveBeenCalledWith(domainObject, mockChildObject.identifier);
- });
-
- it('calls remove on the provider', function () {
- composition.remove(mockChildObject);
- expect(customProvider.remove).toHaveBeenCalledWith(domainObject, mockChildObject.identifier);
- });
- });
- });
-
- describe('dynamic custom composition', function () {
- let customProvider;
- let domainObject;
- let composition;
-
- beforeEach(function () {
- // A dynamic provider, loads an empty composition and exposes
- // listener functions.
- customProvider = jasmine.createSpyObj('dynamicProvider', [
- 'appliesTo',
- 'load',
- 'on',
- 'off'
- ]);
-
- customProvider.appliesTo.and.returnValue('true');
- customProvider.load.and.returnValue(Promise.resolve([]));
-
- domainObject = {
- identifier: {
- namespace: 'test',
- key: '1'
- },
- type: 'custom-object-type'
- };
- compositionAPI.addProvider(customProvider);
- composition = compositionAPI.get(domainObject);
- });
-
- it('supports listening and loading', function () {
- const addListener = jasmine.createSpy('addListener');
- const removeListener = jasmine.createSpy('removeListener');
- const addPromise = new Promise(function (resolve) {
- addListener.and.callFake(resolve);
- });
- const removePromise = new Promise(function (resolve) {
- removeListener.and.callFake(resolve);
- });
-
- composition.on('add', addListener);
- composition.on('remove', removeListener);
-
- expect(customProvider.on).toHaveBeenCalledWith(
- domainObject,
- 'add',
- jasmine.any(Function),
- jasmine.any(CompositionCollection)
- );
- expect(customProvider.on).toHaveBeenCalledWith(
- domainObject,
- 'remove',
- jasmine.any(Function),
- jasmine.any(CompositionCollection)
- );
- const add = customProvider.on.calls.all()[0].args[2];
- const remove = customProvider.on.calls.all()[1].args[2];
-
- return composition.load()
- .then(function () {
- expect(addListener).not.toHaveBeenCalled();
- expect(removeListener).not.toHaveBeenCalled();
- add({
namespace: 'custom',
key: 'thing'
- });
-
- return addPromise;
- }).then(function () {
- expect(addListener).toHaveBeenCalledWith({
- identifier: {
- namespace: 'custom',
- key: 'thing'
- }
- });
- remove(addListener.calls.mostRecent().args[0]);
-
- return removePromise;
- }).then(function () {
- expect(removeListener).toHaveBeenCalledWith({
- identifier: {
- namespace: 'custom',
- key: 'thing'
- }
- });
+ }
});
- });
+ });
});
});
});
diff --git a/src/api/composition/CompositionCollection.js b/src/api/composition/CompositionCollection.js
index 78a0a0c8a..7d8345362 100644
--- a/src/api/composition/CompositionCollection.js
+++ b/src/api/composition/CompositionCollection.js
@@ -20,75 +20,98 @@
* at runtime from the About dialog for additional information.
*****************************************************************************/
-define([
- 'lodash'
-], function (
- _
-) {
+/**
+ * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject
+ */
+
+/**
+ * @typedef {import('./CompositionAPI').default} CompositionAPI
+ */
+
+/**
+ * @typedef {import('../../../openmct').OpenMCT} OpenMCT
+ */
+
+/**
+ * @typedef {object} ListenerMap
+ * @property {Array.<any>} add
+ * @property {Array.<any>} remove
+ * @property {Array.<any>} load
+ * @property {Array.<any>} reorder
+ */
+
+/**
+ * A CompositionCollection represents the list of domain objects contained
+ * by another domain object. It provides methods for loading this
+ * list asynchronously, modifying this list, and listening for changes to
+ * this list.
+ *
+ * Usage:
+ * ```javascript
+ * var myViewComposition = MCT.composition.get(myViewObject);
+ * myViewComposition.on('add', addObjectToView);
+ * myViewComposition.on('remove', removeObjectFromView);
+ * myViewComposition.load(); // will trigger `add` for all loaded objects.
+ * ```
+ */
+export default class CompositionCollection {
+ domainObject;
+ #provider;
+ #publicAPI;
+ #listeners;
+ #mutables;
/**
- * A CompositionCollection represents the list of domain objects contained
- * by another domain object. It provides methods for loading this
- * list asynchronously, modifying this list, and listening for changes to
- * this list.
- *
- * Usage:
- * ```javascript
- * var myViewComposition = MCT.composition.get(myViewObject);
- * myViewComposition.on('add', addObjectToView);
- * myViewComposition.on('remove', removeObjectFromView);
- * myViewComposition.load(); // will trigger `add` for all loaded objects.
- * ```
- *
- * @interface CompositionCollection
- * @param {module:openmct.DomainObject} domainObject the domain object
+ * @constructor
+ * @param {DomainObject} domainObject the domain object
* whose composition will be contained
- * @param {module:openmct.CompositionProvider} provider the provider
+ * @param {import('./CompositionProvider').default} provider the provider
* to use to retrieve other domain objects
- * @param {module:openmct.CompositionAPI} api the composition API, for
+ * @param {OpenMCT} publicAPI the composition API, for
* policy checks
- * @memberof module:openmct
*/
- function CompositionCollection(domainObject, provider, publicAPI) {
+ constructor(domainObject, provider, publicAPI) {
this.domainObject = domainObject;
- this.provider = provider;
- this.publicAPI = publicAPI;
- this.listeners = {
+ /** @type {import('./CompositionProvider').default} */
+ this.#provider = provider;
+ /** @type {OpenMCT} */
+ this.#publicAPI = publicAPI;
+ /** @type {ListenerMap} */
+ this.#listeners = {
add: [],
remove: [],
load: [],
reorder: []
};
- this.onProviderAdd = this.onProviderAdd.bind(this);
- this.onProviderRemove = this.onProviderRemove.bind(this);
- this.mutables = {};
+ this.onProviderAdd = this.#onProviderAdd.bind(this);
+ this.onProviderRemove = this.#onProviderRemove.bind(this);
+ this.#mutables = {};
if (this.domainObject.isMutable) {
this.returnMutables = true;
let unobserve = this.domainObject.$on('$_destroy', () => {
- Object.values(this.mutables).forEach(mutable => {
- this.publicAPI.objects.destroyMutable(mutable);
+ Object.values(this.#mutables).forEach(mutable => {
+ this.#publicAPI.objects.destroyMutable(mutable);
});
unobserve();
});
}
}
-
/**
* Listen for changes to this composition. Supports 'add', 'remove', and
* 'load' events.
*
- * @param event event to listen for, either 'add', 'remove' or 'load'.
- * @param callback to trigger when event occurs.
- * @param [context] context to use when invoking callback, optional.
+ * @param {string} event event to listen for, either 'add', 'remove' or 'load'.
+ * @param {(...args: any[]) => void} callback to trigger when event occurs.
+ * @param {any} [context] to use when invoking callback, optional.
*/
- CompositionCollection.prototype.on = function (event, callback, context) {
- if (!this.listeners[event]) {
+ on(event, callback, context) {
+ if (!this.#listeners[event]) {
throw new Error('Event not supported by composition: ' + event);
}
- if (this.provider.on && this.provider.off) {
+ if (this.#provider.on && this.#provider.off) {
if (event === 'add') {
- this.provider.on(
+ this.#provider.on(
this.domainObject,
'add',
this.onProviderAdd,
@@ -97,7 +120,7 @@ define([
}
if (event === 'remove') {
- this.provider.on(
+ this.#provider.on(
this.domainObject,
'remove',
this.onProviderRemove,
@@ -106,36 +129,34 @@ define([
}
if (event === 'reorder') {
- this.provider.on(
+ this.#provider.on(
this.domainObject,
'reorder',
- this.onProviderReorder,
+ this.#onProviderReorder,
this
);
}
}
- this.listeners[event].push({
+ this.#listeners[event].push({
callback: callback,
context: context
});
- };
-
+ }
/**
* Remove a listener. Must be called with same exact parameters as
* `off`.
*
- * @param event
- * @param callback
- * @param [context]
+ * @param {string} event
+ * @param {(...args: any[]) => void} callback
+ * @param {any} [context]
*/
-
- CompositionCollection.prototype.off = function (event, callback, context) {
- if (!this.listeners[event]) {
+ off(event, callback, context) {
+ if (!this.#listeners[event]) {
throw new Error('Event not supported by composition: ' + event);
}
- const index = this.listeners[event].findIndex(l => {
+ const index = this.#listeners[event].findIndex(l => {
return l.callback === callback && l.context === context;
});
@@ -143,125 +164,116 @@ define([
throw new Error('Tried to remove a listener that does not exist');
}
- this.listeners[event].splice(index, 1);
- if (this.listeners[event].length === 0) {
+ this.#listeners[event].splice(index, 1);
+ if (this.#listeners[event].length === 0) {
this._destroy();
// Remove provider listener if this is the last callback to
// be removed.
- if (this.provider.off && this.provider.on) {
+ if (this.#provider.off && this.#provider.on) {
if (event === 'add') {
- this.provider.off(
+ this.#provider.off(
this.domainObject,
'add',
this.onProviderAdd,
this
);
} else if (event === 'remove') {
- this.provider.off(
+ this.#provider.off(
this.domainObject,
'remove',
this.onProviderRemove,
this
);
} else if (event === 'reorder') {
- this.provider.off(
+ this.#provider.off(
this.domainObject,
'reorder',
- this.onProviderReorder,
+ this.#onProviderReorder,
this
);
}
}
}
- };
-
+ }
/**
* Add a domain object to this composition.
*
* A call to [load]{@link module:openmct.CompositionCollection#load}
* must have resolved before using this method.
*
- * @param {module:openmct.DomainObject} child the domain object to add
- * @param {boolean} skipMutate true if the underlying provider should
- * not be updated
- * @memberof module:openmct.CompositionCollection#
- * @name add
+ * **TODO:** Remove `skipMutate` parameter.
+ *
+ * @param {DomainObject} child the domain object to add
+ * @param {boolean} skipMutate
+ * **Intended for internal use ONLY.**
+ * true if the underlying provider should not be updated.
*/
- CompositionCollection.prototype.add = function (child, skipMutate) {
+ add(child, skipMutate) {
if (!skipMutate) {
- if (!this.publicAPI.composition.checkPolicy(this.domainObject, child)) {
+ if (!this.#publicAPI.composition.checkPolicy(this.domainObject, child)) {
throw `Object of type ${child.type} cannot be added to object of type ${this.domainObject.type}`;
}
- this.provider.add(this.domainObject, child.identifier);
+ this.#provider.add(this.domainObject, child.identifier);
} else {
- if (this.returnMutables && this.publicAPI.objects.supportsMutation(child.identifier)) {
- let keyString = this.publicAPI.objects.makeKeyString(child.identifier);
+ if (this.returnMutables && this.#publicAPI.objects.supportsMutation(child.identifier)) {
+ let keyString = this.#publicAPI.objects.makeKeyString(child.identifier);
- child = this.publicAPI.objects.toMutable(child);
- this.mutables[keyString] = child;
+ child = this.#publicAPI.objects.toMutable(child);
+ this.#mutables[keyString] = child;
}
- this.emit('add', child);
+ this.#emit('add', child);
}
- };
-
+ }
/**
* Load the domain objects in this composition.
*
- * @returns {Promise.<Array.<module:openmct.DomainObject>>} a promise for
+ * @param {AbortSignal} abortSignal
+ * @returns {Promise.<Array.<DomainObject>>} a promise for
* the domain objects in this composition
* @memberof {module:openmct.CompositionCollection#}
* @name load
*/
- CompositionCollection.prototype.load = function (abortSignal) {
- this.cleanUpMutables();
-
- return this.provider.load(this.domainObject)
- .then(function (children) {
- return Promise.all(children.map((c) => this.publicAPI.objects.get(c, abortSignal)));
- }.bind(this))
- .then(function (childObjects) {
- childObjects.forEach(c => this.add(c, true));
-
- return childObjects;
- }.bind(this))
- .then(function (children) {
- this.emit('load');
-
- return children;
- }.bind(this));
- };
-
+ async load(abortSignal) {
+ this.#cleanUpMutables();
+ const children = await this.#provider.load(this.domainObject);
+ const childObjects = await Promise.all(children.map((c) => this.#publicAPI.objects.get(c, abortSignal)));
+ childObjects.forEach(c => this.add(c, true));
+ this.#emit('load');
+
+ return childObjects;
+ }
/**
* Remove a domain object from this composition.
*
* A call to [load]{@link module:openmct.CompositionCollection#load}
* must have resolved before using this method.
*
- * @param {module:openmct.DomainObject} child the domain object to remove
- * @param {boolean} skipMutate true if the underlying provider should
- * not be updated
- * @memberof module:openmct.CompositionCollection#
+ * **TODO:** Remove `skipMutate` parameter.
+ *
+ * @param {DomainObject} child the domain object to remove
+ * @param {boolean} skipMutate
+ * **Intended for internal use ONLY.**
+ * true if the underlying provider should not be updated.
* @name remove
*/
- CompositionCollection.prototype.remove = function (child, skipMutate) {
+ remove(child, skipMutate) {
if (!skipMutate) {
- this.provider.remove(this.domainObject, child.identifier);
+ this.#provider.remove(this.domainObject, child.identifier);
} else {
if (this.returnMutables) {
- let keyString = this.publicAPI.objects.makeKeyString(child);
- if (this.mutables[keyString] !== undefined && this.mutables[keyString].isMutable) {
- this.publicAPI.objects.destroyMutable(this.mutables[keyString]);
- delete this.mutables[keyString];
+ let keyString = this.#publicAPI.objects.makeKeyString(child);
+ if (this.#mutables[keyString] !== undefined && this.#mutables[keyString].isMutable) {
+ this.#publicAPI.objects.destroyMutable(this.#mutables[keyString]);
+ delete this.#mutables[keyString];
}
}
- this.emit('remove', child);
+ this.#emit('remove', child);
}
- };
-
+ }
/**
* Reorder the domain objects in this composition.
*
@@ -270,67 +282,75 @@ define([
*
* @param {number} oldIndex
* @param {number} newIndex
- * @memberof module:openmct.CompositionCollection#
* @name remove
*/
- CompositionCollection.prototype.reorder = function (oldIndex, newIndex, skipMutate) {
- this.provider.reorder(this.domainObject, oldIndex, newIndex);
- };
-
+ reorder(oldIndex, newIndex, _skipMutate) {
+ this.#provider.reorder(this.domainObject, oldIndex, newIndex);
+ }
+ /**
+ * Destroy mutationListener
+ */
+ _destroy() {
+ if (this.mutationListener) {
+ this.mutationListener();
+ delete this.mutationListener;
+ }
+ }
/**
* Handle reorder from provider.
* @private
+ * @param {object} reorderMap
*/
- CompositionCollection.prototype.onProviderReorder = function (reorderMap) {
- this.emit('reorder', reorderMap);
- };
+ #onProviderReorder(reorderMap) {
+ this.#emit('reorder', reorderMap);
+ }
/**
* Handle adds from provider.
* @private
+ * @param {import('../objects/ObjectAPI').Identifier} childId
+ * @returns {DomainObject}
*/
- CompositionCollection.prototype.onProviderAdd = function (childId) {
- return this.publicAPI.objects.get(childId).then(function (child) {
+ #onProviderAdd(childId) {
+ return this.#publicAPI.objects.get(childId).then(function (child) {
this.add(child, true);
return child;
}.bind(this));
- };
+ }
/**
* Handle removal from provider.
- * @private
+ * @param {DomainObject} child
*/
- CompositionCollection.prototype.onProviderRemove = function (child) {
+ #onProviderRemove(child) {
this.remove(child, true);
- };
-
- CompositionCollection.prototype._destroy = function () {
- if (this.mutationListener) {
- this.mutationListener();
- delete this.mutationListener;
- }
- };
+ }
/**
* Emit events.
+ *
* @private
+ * @param {string} event
+ * @param {...args.<any>} payload
*/
- CompositionCollection.prototype.emit = function (event, ...payload) {
- this.listeners[event].forEach(function (l) {
+ #emit(event, ...payload) {
+ this.#listeners[event].forEach(function (l) {
if (l.context) {
l.callback.apply(l.context, payload);
} else {
l.callback(...payload);
}
});
- };
+ }
- CompositionCollection.prototype.cleanUpMutables = function () {
- Object.values(this.mutables).forEach(mutable => {
- this.publicAPI.objects.destroyMutable(mutable);
+ /**
+ * Destroy all mutables.
+ * @private
+ */
+ #cleanUpMutables() {
+ Object.values(this.#mutables).forEach(mutable => {
+ this.#publicAPI.objects.destroyMutable(mutable);
});
- };
-
- return CompositionCollection;
-});
+ }
+}
diff --git a/src/api/composition/CompositionProvider.js b/src/api/composition/CompositionProvider.js
new file mode 100644
index 000000000..792a3db48
--- /dev/null
+++ b/src/api/composition/CompositionProvider.js
@@ -0,0 +1,262 @@
+/*****************************************************************************
+ * Open MCT, Copyright (c) 2014-2022, United States Government
+ * as represented by the Administrator of the National Aeronautics and Space
+ * Administration. All rights reserved.
+ *
+ * Open MCT is licensed under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ * http://www.apache.org/licenses/LICENSE-2.0.
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ * Open MCT includes source code licensed under additional open source
+ * licenses. See the Open Source Licenses file (LICENSES.md) included with
+ * this source code distribution or the Licensing information page available
+ * at runtime from the About dialog for additional information.
+ *****************************************************************************/
+import _ from 'lodash';
+import objectUtils from "../objects/object-utils";
+
+/**
+ * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject
+ */
+
+/**
+ * @typedef {import('../objects/ObjectAPI').Identifier} Identifier
+ */
+
+/**
+ * @typedef {import('./CompositionAPI').default} CompositionAPI
+ */
+
+/**
+ * @typedef {import('../../../openmct').OpenMCT} OpenMCT
+ */
+
+/**
+ * A CompositionProvider provides the underlying implementation of
+ * composition-related behavior for certain types of domain object.
+ *
+ * By default, a composition provider will not support composition
+ * modification. You can add support for mutation of composition by
+ * defining `add` and/or `remove` methods.
+ *
+ * If the composition of an object can change over time-- perhaps via
+ * server updates or mutation via the add/remove methods, then one must
+ * trigger events as necessary.
+ *
+ */
+export default class CompositionProvider {
+ #publicAPI;
+ #listeningTo;
+
+ /**
+ * @param {OpenMCT} publicAPI
+ * @param {CompositionAPI} compositionAPI
+ */
+ constructor(publicAPI, compositionAPI) {
+ this.#publicAPI = publicAPI;
+ this.#listeningTo = {};
+
+ compositionAPI.addPolicy(this.#cannotContainItself.bind(this));
+ compositionAPI.addPolicy(this.#supportsComposition.bind(this));
+ }
+
+ get listeningTo() {
+ return this.#listeningTo;
+ }
+
+ get establishTopicListener() {
+ return this.#establishTopicListener.bind(this);
+ }
+
+ get publicAPI() {
+ return this.#publicAPI;
+ }
+
+ /**
+ * Check if this provider should be used to load composition for a
+ * particular domain object.
+ * @method appliesTo
+ * @param {import('../objects/ObjectAPI').DomainObject} domainObject the domain object
+ * to check
+ * @returns {boolean} true if this provider can provide composition for a given domain object
+ */
+ appliesTo(domainObject) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+ /**
+ * Load any domain objects contained in the composition of this domain
+ * object.
+ * @param {DomainObject} domainObject the domain object
+ * for which to load composition
+ * @returns {Promise<Identifier[]>} a promise for
+ * the Identifiers in this composition
+ * @method load
+ */
+ load(domainObject) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+ /**
+ * Attach listeners for changes to the composition of a given domain object.
+ * Supports `add` and `remove` events.
+ *
+ * @param {DomainObject} domainObject to listen to
+ * @param {string} event the event to bind to, either `add` or `remove`.
+ * @param {Function} callback callback to invoke when event is triggered.
+ * @param {any} [context] to use when invoking callback.
+ */
+ on(domainObject,
+ event,
+ callback,
+ context) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+ /**
+ * Remove a listener that was previously added for a given domain object.
+ * event name, callback, and context must be the same as when the listener
+ * was originally attached.
+ *
+ * @param {DomainObject} domainObject to remove listener for
+ * @param {string} event event to stop listening to: `add` or `remove`.
+ * @param {Function} callback callback to remove.
+ * @param {any} context of callback to remove.
+ */
+ off(domainObject,
+ event,
+ callback,
+ context) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+ /**
+ * Remove a domain object from another domain object's composition.
+ *
+ * This method is optional; if not present, adding to a domain object's
+ * composition using this provider will be disallowed.
+ *
+ * @param {DomainObject} domainObject the domain object
+ * which should have its composition modified
+ * @param {Identifier} childId the domain object to remove
+ * @method remove
+ */
+ remove(domainObject, childId) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+ /**
+ * Add a domain object to another domain object's composition.
+ *
+ * This method is optional; if not present, adding to a domain object's
+ * composition using this provider will be disallowed.
+ *
+ * @param {DomainObject} parent the domain object
+ * which should have its composition modified
+ * @param {Identifier} childId the domain object to add
+ * @method add
+ */
+ add(parent, childId) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+
+ /**
+ * @param {DomainObject} parent
+ * @param {Identifier} childId
+ * @returns {boolean}
+ */
+ includes(parent, childId) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+
+ /**
+ * @param {DomainObject} domainObject
+ * @param {number} oldIndex
+ * @param {number} newIndex
+ * @returns
+ */
+ reorder(domainObject, oldIndex, newIndex) {
+ throw new Error("This method must be implemented by a subclass.");
+ }
+
+ /**
+ * Listens on general mutation topic, using injector to fetch to avoid
+ * circular dependencies.
+ * @private
+ */
+ #establishTopicListener() {
+ if (this.topicListener) {
+ return;
+ }
+
+ this.#publicAPI.objects.eventEmitter.on('mutation', this.#onMutation.bind(this));
+ this.topicListener = () => {
+ this.#publicAPI.objects.eventEmitter.off('mutation', this.#onMutation.bind(this));
+ };
+ }
+
+ /**
+ * @private
+ * @param {DomainObject} parent
+ * @param {DomainObject} child
+ * @returns {boolean}
+ */
+ #cannotContainItself(parent, child) {
+ return !(parent.identifier.namespace === child.identifier.namespace
+ && parent.identifier.key === child.identifier.key);
+ }
+
+ /**
+ * @private
+ * @param {DomainObject} parent
+ * @returns {boolean}
+ */
+ #supportsComposition(parent, _child) {
+ return this.#publicAPI.composition.supportsComposition(parent);
+ }
+
+ /**
+ * Handles mutation events. If there are active listeners for the mutated
+ * object, detects changes to composition and triggers necessary events.
+ *
+ * @private
+ * @param {DomainObject} oldDomainObject
+ */
+ #onMutation(oldDomainObject) {
+ const id = objectUtils.makeKeyString(oldDomainObject.identifier);
+ const listeners = this.#listeningTo[id];
+
+ if (!listeners) {
+ return;
+ }
+
+ const oldComposition = listeners.composition.map(objectUtils.makeKeyString);
+ const newComposition = oldDomainObject.composition.map(objectUtils.makeKeyString);
+
+ const added = _.difference(newComposition, oldComposition).map(objectUtils.parseKeyString);
+ const removed = _.difference(oldComposition, newComposition).map(objectUtils.parseKeyString);
+
+ function notify(value) {
+ return function (listener) {
+ if (listener.context) {
+ listener.callback.call(listener.context, value);
+ } else {
+ listener.callback(value);
+ }
+ };
+ }
+
+ listeners.composition = newComposition.map(objectUtils.parseKeyString);
+
+ added.forEach(function (addedChild) {
+ listeners.add.forEach(notify(addedChild));
+ });
+
+ removed.forEach(function (removedChild) {
+ listeners.remove.forEach(notify(removedChild));
+ });
+ }
+}
+
diff --git a/src/api/composition/DefaultCompositionProvider.js b/src/api/composition/DefaultCompositionProvider.js
index 3a46b127f..6c242a25c 100644
--- a/src/api/composition/DefaultCompositionProvider.js
+++ b/src/api/composition/DefaultCompositionProvider.js
@@ -19,102 +19,79 @@
* this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information.
*****************************************************************************/
+import objectUtils from "../objects/object-utils";
+import CompositionProvider from './CompositionProvider';
-define([
- 'lodash',
- 'objectUtils'
-], function (
- _,
- objectUtils
-) {
- /**
- * A CompositionProvider provides the underlying implementation of
- * composition-related behavior for certain types of domain object.
- *
- * By default, a composition provider will not support composition
- * modification. You can add support for mutation of composition by
- * defining `add` and/or `remove` methods.
- *
- * If the composition of an object can change over time-- perhaps via
- * server updates or mutation via the add/remove methods, then one must
- * trigger events as necessary.
- *
- * @interface CompositionProvider
- * @memberof module:openmct
- */
+/**
+ * @typedef {import('../objects/ObjectAPI').DomainObject} DomainObject
+ */
- function DefaultCompositionProvider(publicAPI, compositionAPI) {
- this.publicAPI = publicAPI;
- this.listeningTo = {};
- this.onMutation = this.onMutation.bind(this);
+/**
+ * @typedef {import('../objects/ObjectAPI').Identifier} Identifier
+ */
- this.cannotContainItself = this.cannotContainItself.bind(this);
- this.supportsComposition = this.supportsComposition.bind(this);
+/**
+ * @typedef {import('./CompositionAPI').default} CompositionAPI
+ */
- compositionAPI.addPolicy(this.cannotContainItself);
- compositionAPI.addPolicy(this.supportsComposition);
- }
-
- /**
- * @private
- */
- DefaultCompositionProvider.prototype.cannotContainItself = function (parent, child) {
- return !(parent.identifier.namespace === child.identifier.namespace
- && parent.identifier.key === child.identifier.key);
- };
-
- /**
- * @private
- */
- DefaultCompositionProvider.prototype.supportsComposition = function (parent, child) {
- return this.publicAPI.composition.supportsComposition(parent);
- };
+/**
+ * @typedef {import('../../../openmct').OpenMCT} OpenMCT
+ */
+/**
+ * A CompositionProvider provides the underlying implementation of
+ * composition-related behavior for certain types of domain object.
+ *
+ * By default, a composition provider will not support composition
+ * modification. You can add support for mutation of composition by
+ * defining `add` and/or `remove` methods.
+ *
+ * If the composition of an object can change over time-- perhaps via
+ * server updates or mutation via the add/remove methods, then one must
+ * trigger events as necessary.
+ * @extends CompositionProvider
+ */
+export default class DefaultCompositionProvider extends CompositionProvider {
/**
* Check if this provider should be used to load composition for a
* particular domain object.
- * @param {module:openmct.DomainObject} domainObject the domain object
+ * @override
+ * @param {DomainObject} domainObject the domain object
* to check
- * @returns {boolean} true if this provider can provide
- * composition for a given domain object
- * @memberof module:openmct.CompositionProvider#
- * @method appliesTo
+ * @returns {boolean} true if this provider can provide composition for a given domain object
*/
- DefaultCompositionProvider.prototype.appliesTo = function (domainObject) {
+ appliesTo(domainObject) {
return Boolean(domainObject.composition);
- };
-
+ }
/**
* Load any domain objects contained in the composition of this domain
* object.
- * @param {module:openmct.DomainObject} domainObject the domain object
+ * @override
+ * @param {DomainObject} domainObject the domain object
* for which to load composition
- * @returns {Promise.<Array.<module:openmct.Identifier>>} a promise for
+ * @returns {Promise<Identifier[]>} a promise for
* the Identifiers in this composition
- * @memberof module:openmct.CompositionProvider#
- * @method load
*/
- DefaultCompositionProvider.prototype.load = function (domainObject) {
+ load(domainObject) {
return Promise.all(domainObject.composition);
- };
-
+ }
/**
* Attach listeners for changes to the composition of a given domain object.
* Supports `add` and `remove` events.
*
- * @param {module:openmct.DomainObject} domainObject to listen to
- * @param String event the event to bind to, either `add` or `remove`.
- * @param Function callback callback to invoke when event is triggered.
- * @param [context] context to use when invoking callback.
+ * @override
+ * @param {DomainObject} domainObject to listen to
+ * @param {string} event the event to bind to, either `add` or `remove`.
+ * @param {Function} callback callback to invoke when event is triggered.
+ * @param {any} [context] to use when invoking callback.
*/
- DefaultCompositionProvider.prototype.on = function (
- domainObject,
+ on(domainObject,
event,
callback,
- context
- ) {
+ context) {
this.establishTopicListener();
+ /** @type {string} */
const keyString = objectUtils.makeKeyString(domainObject.identifier);
let objectListeners = this.listeningTo[keyString];
@@ -131,24 +108,24 @@ define([
callback: callback,
context: context
});
- };
-
+ }
/**
* Remove a listener that was previously added for a given domain object.
* event name, callback, and context must be the same as when the listener
* was originally attached.
*
- * @param {module:openmct.DomainObject} domainObject to remove listener for
- * @param String event event to stop listening to: `add` or `remove`.
- * @param Function callback callback to remove.
- * @param [context] context of callback to remove.
+ * @override
+ * @param {DomainObject} domainObject to remove listener for
+ * @param {string} event event to stop listening to: `add` or `remove`.
+ * @param {Function} callback callback to remove.
+ * @param {any} context of callback to remove.
*/
- DefaultCompositionProvider.prototype.off = function (
- domainObject,
+ off(domainObject,
event,
callback,
- context
- ) {
+ context) {
+
+ /** @type {string} */
const keyString = objectUtils.makeKeyString(domainObject.identifier);
const objectListeners = this.listeningTo[keyString];
@@ -160,57 +137,64 @@ define([
if (!objectListeners.add.length && !objectListeners.remove.length && !objectListeners.reorder.length) {
delete this.listeningTo[keyString];
}
- };
-
+ }
/**
* Remove a domain object from another domain object's composition.
*
* This method is optional; if not present, adding to a domain object's
* composition using this provider will be disallowed.
*
- * @param {module:openmct.DomainObject} domainObject the domain object
+ * @override
+ * @param {DomainObject} domainObject the domain object
* which should have its composition modified
- * @param {module:openmct.DomainObject} child the domain object to remove
- * @memberof module:openmct.CompositionProvider#
+ * @param {Identifier} childId the domain object to remove
* @method remove
*/
- DefaultCompositionProvider.prototype.remove = function (domainObject, childId) {
+ remove(domainObject, childId) {
let composition = domainObject.composition.filter(function (child) {
return !(childId.namespace === child.namespace
- && childId.key === child.key);
+ && childId.key === child.key);
});
this.publicAPI.objects.mutate(domainObject, 'composition', composition);
- };
-
+ }
/**
* Add a domain object to another domain object's composition.
*
* This method is optional; if not present, adding to a domain object's
* composition using this provider will be disallowed.
*
- * @param {module:openmct.DomainObject} domainObject the domain object
+ * @override
+ * @param {DomainObject} parent the domain object
* which should have its composition modified
- * @param {module:openmct.DomainObject} child the domain object to add
- * @memberof module:openmct.CompositionProvider#
+ * @param {Identifier} childId the domain object to add
* @method add
*/
- DefaultCompositionProvider.prototype.add = function (parent, childId) {
+ add(parent, childId) {
if (!this.includes(parent, childId)) {
parent.composition.push(childId);
this.publicAPI.objects.mutate(parent, 'composition', parent.composition);
}
- };
+ }
/**
- * @private
+ * @override
+ * @param {DomainObject} parent
+ * @param {Identifier} childId
+ * @returns {boolean}
*/
- DefaultCompositionProvider.prototype.includes = function (parent, childId) {
- return parent.composition.some(composee =>
- this.publicAPI.objects.areIdsEqual(composee, childId));
- };
+ includes(parent, childId) {
+ return parent.composition.some(composee => this.publicAPI.objects.areIdsEqual(composee, childId));
+ }
- DefaultCompositionProvider.prototype.reorder = function (domainObject, oldIndex, newIndex) {
+ /**
+ * @override
+ * @param {DomainObject} domainObject
+ * @param {number} oldIndex
+ * @param {number} newIndex
+ * @returns
+ */
+ reorder(domainObject, oldIndex, newIndex) {
let newComposition = domainObject.composition.slice();
let removeId = oldIndex > newIndex ? oldIndex + 1 : oldIndex;
let insertPosition = oldIndex < newIndex ? newIndex + 1 : newIndex;
@@ -241,6 +225,7 @@ define([
this.publicAPI.objects.mutate(domainObject, 'composition', newComposition);
+ /** @type {string} */
let id = objectUtils.makeKeyString(domainObject.identifier);
const listeners = this.listeningTo[id];
@@ -257,66 +242,5 @@ define([
listener.callback(reorderPlan);
}
}
- };
-
- /**
- * Listens on general mutation topic, using injector to fetch to avoid
- * circular dependencies.
- *
- * @private
- */
- DefaultCompositionProvider.prototype.establishTopicListener = function () {
- if (this.topicListener) {
- return;
- }
-
- this.publicAPI.objects.eventEmitter.on('mutation', this.onMutation);
- this.topicListener = () => {
- this.publicAPI.objects.eventEmitter.off('mutation', this.onMutation);
- };
- };
-
- /**
- * Handles mutation events. If there are active listeners for the mutated
- * object, detects changes to composition and triggers necessary events.
- *
- * @private
- */
- DefaultCompositionProvider.prototype.onMutation = function (oldDomainObject) {
- const id = objectUtils.makeKeyString(oldDomainObject.identifier);
- const listeners = this.listeningTo[id];
-
- if (!listeners) {
- return;
- }
-
- const oldComposition = listeners.composition.map(objectUtils.makeKeyString);
- const newComposition = oldDomainObject.composition.map(objectUtils.makeKeyString);
-
- const added = _.difference(newComposition, oldComposition).map(objectUtils.parseKeyString);
- const removed = _.difference(oldComposition, newComposition).map(objectUtils.parseKeyString);
-
- function notify(value) {
- return function (listener) {
- if (listener.context) {
- listener.callback.call(listener.context, value);
- } else {
- listener.callback(value);
- }
- };
- }
-
- listeners.composition = newComposition.map(objectUtils.parseKeyString);
-
- added.forEach(function (addedChild) {
- listeners.add.forEach(notify(addedChild));
- });
-
- removed.forEach(function (removedChild) {
- listeners.remove.forEach(notify(removedChild));
- });
-
- };
-
- return DefaultCompositionProvider;
-});
+ }
+}
diff --git a/src/api/objects/ObjectAPI.js b/src/api/objects/ObjectAPI.js
index 5c22765f9..0ebeba5da 100644
--- a/src/api/objects/ObjectAPI.js
+++ b/src/api/objects/ObjectAPI.js
@@ -33,7 +33,7 @@ import InMemorySearchProvider from './InMemorySearchProvider';
/**
* Uniquely identifies a domain object.
*
- * @typedef Identifier
+ * @typedef {object} Identifier
* @property {string} namespace the namespace to/from which this domain
* object should be loaded/stored.
* @property {string} key a unique identifier for the domain object
@@ -50,8 +50,8 @@ import InMemorySearchProvider from './InMemorySearchProvider';
* A few common properties are defined for domain objects. Beyond these,
* individual types of domain objects may add more as they see fit.
*
- * @typedef DomainObject
- * @property {module:openmct.ObjectAPI~Identifier} identifier a key/namespace pair which
+ * @typedef {object} DomainObject
+ * @property {Identifier} identifier a key/namespace pair which
* uniquely identifies this domain object
* @property {string} type the type of domain object
* @property {string} name the human-readable name for this domain object
@@ -59,19 +59,19 @@ import InMemorySearchProvider from './InMemorySearchProvider';
* object
* @property {number} [modified] the time, in milliseconds since the UNIX
* epoch, at which this domain object was last modified
- * @property {module:openmct.ObjectAPI~Identifier[]} [composition] if
+ * @property {Identifier[]} [composition] if
* present, this will be used by the default composition provider
* to load domain objects
- * @memberof module:openmct
+ * @memberof module:openmct.ObjectAPI~
*/
/**
- * @readonly
- * @enum {String} SEARCH_TYPES
- * @property {String} OBJECTS Search for objects
- * @property {String} ANNOTATIONS Search for annotations
- * @property {String} TAGS Search for tags
-*/
+ * @readonly
+ * @enum {string} SEARCH_TYPES
+ * @property {string} OBJECTS Search for objects
+ * @property {string} ANNOTATIONS Search for annotations
+ * @property {string} TAGS Search for tags
+ */
/**
* Utilities for loading, saving, and manipulating domain objects.
diff --git a/src/selection/Selection.js b/src/selection/Selection.js
index d9afa03d5..76e18aef1 100644
--- a/src/selection/Selection.js
+++ b/src/selection/Selection.js
@@ -20,250 +20,225 @@
* at runtime from the About dialog for additional information.
*****************************************************************************/
-define(
- [
- 'EventEmitter',
- 'lodash'
- ],
- function (
- EventEmitter,
- _
- ) {
- /**
- * Manages selection state for Open MCT
- * @private
- */
- function Selection(openmct) {
- EventEmitter.call(this);
-
- this.openmct = openmct;
- this.selected = [];
+import EventEmitter from 'EventEmitter';
+import _ from 'lodash';
+
+/**
+ * Manages selection state for Open MCT
+ * @private
+ */
+export default class Selection extends EventEmitter {
+ constructor(openmct) {
+ super();
+
+ this.openmct = openmct;
+ this.selected = [];
+ }
+ /**
+ * Gets the selected object.
+ * @public
+ */
+ get() {
+ return this.selected;
+ }
+ /**
+ * Selects the selectable object and emits the 'change' event.
+ *
+ * @param {object} selectable an object with element and context properties
+ * @param {Boolean} isMultiSelectEvent flag indication shift key is pressed or not
+ * @private
+ */
+ select(selectable, isMultiSelectEvent) {
+ if (!Array.isArray(selectable)) {
+ selectable = [selectable];
}
- Selection.prototype = Object.create(EventEmitter.prototype);
-
- /**
- * Gets the selected object.
- * @public
- */
- Selection.prototype.get = function () {
- return this.selected;
- };
-
- /**
- * Selects the selectable object and emits the 'change' event.
- *
- * @param {object} selectable an object with element and context properties
- * @param {Boolean} isMultiSelectEvent flag indication shift key is pressed or not
- * @private
- */
- Selection.prototype.select = function (selectable, isMultiSelectEvent) {
- if (!Array.isArray(selectable)) {
- selectable = [selectable];
- }
-
- let multiSelect = isMultiSelectEvent
- && this.parentSupportsMultiSelect(selectable)
- && this.isPeer(selectable)
- && !this.selectionContainsParent(selectable);
-
- if (multiSelect) {
- this.handleMultiSelect(selectable);
- } else {
- this.handleSingleSelect(selectable);
- }
- };
-
- /**
- * @private
- */
- Selection.prototype.handleMultiSelect = function (selectable) {
- if (this.elementSelected(selectable)) {
- this.remove(selectable);
- } else {
- this.addSelectionAttributes(selectable);
- this.selected.push(selectable);
- }
-
- this.emit('change', this.selected);
- };
-
- /**
- * @private
- */
- Selection.prototype.handleSingleSelect = function (selectable) {
- if (!_.isEqual([selectable], this.selected)) {
- this.setSelectionStyles(selectable);
- this.selected = [selectable];
-
- this.emit('change', this.selected);
- }
- };
-
- /**
- * @private
- */
- Selection.prototype.elementSelected = function (selectable) {
- return this.selected.some(selectionPath => _.isEqual(selectionPath, selectable));
- };
-
- /**
- * @private
- */
- Selection.prototype.remove = function (selectable) {
- this.selected = this.selected.filter(selectionPath => !_.isEqual(selectionPath, selectable));
-
- if (this.selected.length === 0) {
- this.removeSelectionAttributes(selectable);
- selectable[1].element.click(); // Select the parent if there is no selection.
- } else {
- this.removeSelectionAttributes(selectable, true);
- }
- };
+ let multiSelect = isMultiSelectEvent
+ && this.parentSupportsMultiSelect(selectable)
+ && this.isPeer(selectable)
+ && !this.selectionContainsParent(selectable);
- /**
- * @private
- */
- Selection.prototype.setSelectionStyles = function (selectable) {
- this.selected.forEach(selectionPath => this.removeSelectionAttributes(selectionPath));
+ if (multiSelect) {
+ this.handleMultiSelect(selectable);
+ } else {
+ this.handleSingleSelect(selectable);
+ }
+ }
+ /**
+ * @private
+ */
+ handleMultiSelect(selectable) {
+ if (this.elementSelected(selectable)) {
+ this.remove(selectable);
+ } else {
this.addSelectionAttributes(selectable);
- };
+ this.selected.push(selectable);
+ }
- Selection.prototype.removeSelectionAttributes = function (selectionPath, keepParentStyle) {
- if (selectionPath[0] && selectionPath[0].element) {
- selectionPath[0].element.removeAttribute('s-selected');
- }
+ this.emit('change', this.selected);
+ }
+ /**
+ * @private
+ */
+ handleSingleSelect(selectable) {
+ if (!_.isEqual([selectable], this.selected)) {
+ this.setSelectionStyles(selectable);
+ this.selected = [selectable];
- if (selectionPath[1] && selectionPath[1].element && !keepParentStyle) {
- selectionPath[1].element.removeAttribute('s-selected-parent');
- }
- };
+ this.emit('change', this.selected);
+ }
+ }
+ /**
+ * @private
+ */
+ elementSelected(selectable) {
+ return this.selected.some(selectionPath => _.isEqual(selectionPath, selectable));
+ }
+ /**
+ * @private
+ */
+ remove(selectable) {
+ this.selected = this.selected.filter(selectionPath => !_.isEqual(selectionPath, selectable));
+
+ if (this.selected.length === 0) {
+ this.removeSelectionAttributes(selectable);
+ selectable[1].element.click(); // Select the parent if there is no selection.
+ } else {
+ this.removeSelectionAttributes(selectable, true);
+ }
+ }
+ /**
+ * @private
+ */
+ setSelectionStyles(selectable) {
+ this.selected.forEach(selectionPath => this.removeSelectionAttributes(selectionPath));
+ this.addSelectionAttributes(selectable);
+ }
+ removeSelectionAttributes(selectionPath, keepParentStyle) {
+ if (selectionPath[0] && selectionPath[0].element) {
+ selectionPath[0].element.removeAttribute('s-selected');
+ }
- /*
- * Adds selection attributes to the selected element and its parent.
- * @private
- */
- Selection.prototype.addSelectionAttributes = function (selectable) {
- if (selectable[0] && selectable[0].element) {
- selectable[0].element.setAttribute('s-selected', "");
- }
+ if (selectionPath[1] && selectionPath[1].element && !keepParentStyle) {
+ selectionPath[1].element.removeAttribute('s-selected-parent');
+ }
+ }
+ /**
+ * Adds selection attributes to the selected element and its parent.
+ * @private
+ */
+ addSelectionAttributes(selectable) {
+ if (selectable[0] && selectable[0].element) {
+ selectable[0].element.setAttribute('s-selected', "");
+ }
- if (selectable[1] && selectable[1].element) {
- selectable[1].element.setAttribute('s-selected-parent', "");
- }
- };
+ if (selectable[1] && selectable[1].element) {
+ selectable[1].element.setAttribute('s-selected-parent', "");
+ }
+ }
+ /**
+ * @private
+ */
+ parentSupportsMultiSelect(selectable) {
+ return selectable[1] && selectable[1].context.supportsMultiSelect;
+ }
+ /**
+ * @private
+ */
+ selectionContainsParent(selectable) {
+ return this.selected.some(selectionPath => _.isEqual(selectionPath[0], selectable[1]));
+ }
+ /**
+ * @private
+ */
+ isPeer(selectable) {
+ return this.selected.some(selectionPath => _.isEqual(selectionPath[1], selectable[1]));
+ }
+ /**
+ * @private
+ */
+ isSelectable(element) {
+ if (!element) {
+ return false;
+ }
- /**
- * @private
- */
- Selection.prototype.parentSupportsMultiSelect = function (selectable) {
- return selectable[1] && selectable[1].context.supportsMultiSelect;
- };
+ return Boolean(element.closest('[data-selectable]'));
+ }
+ /**
+ * @private
+ */
+ capture(selectable) {
+ let capturingContainsSelectable = this.capturing && this.capturing.includes(selectable);
- /**
- * @private
- */
- Selection.prototype.selectionContainsParent = function (selectable) {
- return this.selected.some(selectionPath => _.isEqual(selectionPath[0], selectable[1]));
- };
+ if (!this.capturing || capturingContainsSelectable) {
+ this.capturing = [];
+ }
- /**
- * @private
- */
- Selection.prototype.isPeer = function (selectable) {
- return this.selected.some(selectionPath => _.isEqual(selectionPath[1], selectable[1]));
- };
+ this.capturing.push(selectable);
+ }
+ /**
+ * @private
+ */
+ selectCapture(selectable, event) {
+ if (!this.capturing) {
+ return;
+ }
- /**
- * @private
- */
- Selection.prototype.isSelectable = function (element) {
- if (!element) {
- return false;
- }
+ let reversedCapturing = this.capturing.reverse();
+ delete this.capturing;
+ this.select(reversedCapturing, event.shiftKey);
+ }
+ /**
+ * Attaches the click handlers to the element.
+ *
+ * @param element an html element
+ * @param context object which defines item or other arbitrary properties.
+ * e.g. {
+ * item: domainObject,
+ * elementProxy: element,
+ * controller: fixedController
+ * }
+ * @param select a flag to select the element if true
+ * @returns a function that removes the click handlers from the element
+ * @public
+ */
+ selectable(element, context, select) {
+ if (!this.isSelectable(element)) {
+ return () => { };
+ }
- return Boolean(element.closest('[data-selectable]'));
+ let selectable = {
+ context: context,
+ element: element
};
- /**
- * @private
- */
- Selection.prototype.capture = function (selectable) {
- let capturingContainsSelectable = this.capturing && this.capturing.includes(selectable);
+ const capture = this.capture.bind(this, selectable);
+ const selectCapture = this.selectCapture.bind(this, selectable);
+ let removeMutable = false;
- if (!this.capturing || capturingContainsSelectable) {
- this.capturing = [];
- }
-
- this.capturing.push(selectable);
- };
-
- /**
- * @private
- */
- Selection.prototype.selectCapture = function (selectable, event) {
- if (!this.capturing) {
- return;
- }
+ element.addEventListener('click', capture, true);
+ element.addEventListener('click', selectCapture);
- let reversedCapturing = this.capturing.reverse();
- delete this.capturing;
- this.select(reversedCapturing, event.shiftKey);
- };
+ if (context.item && context.item.isMutable !== true) {
+ removeMutable = true;
+ context.item = this.openmct.objects.toMutable(context.item);
+ }
- /**
- * Attaches the click handlers to the element.
- *
- * @param element an html element
- * @param context object which defines item or other arbitrary properties.
- * e.g. {
- * item: domainObject,
- * elementProxy: element,
- * controller: fixedController
- * }
- * @param select a flag to select the element if true
- * @returns a function that removes the click handlers from the element
- * @public
- */
- Selection.prototype.selectable = function (element, context, select) {
- if (!this.isSelectable(element)) {
- return () => {};
+ if (select) {
+ if (typeof select === 'object') {
+ element.dispatchEvent(select);
+ } else if (typeof select === 'boolean') {
+ element.click();
}
+ }
- let selectable = {
- context: context,
- element: element
- };
-
- const capture = this.capture.bind(this, selectable);
- const selectCapture = this.selectCapture.bind(this, selectable);
- let removeMutable = false;
-
- element.addEventListener('click', capture, true);
- element.addEventListener('click', selectCapture);
-
- if (context.item && context.item.isMutable !== true) {
- removeMutable = true;
- context.item = this.openmct.objects.toMutable(context.item);
- }
+ return (function () {
+ element.removeEventListener('click', capture, true);
+ element.removeEventListener('click', selectCapture);
- if (select) {
- if (typeof select === 'object') {
- element.dispatchEvent(select);
- } else if (typeof select === 'boolean') {
- element.click();
- }
+ if (context.item !== undefined && context.item.isMutable && removeMutable === true) {
+ this.openmct.objects.destroyMutable(context.item);
}
-
- return (function () {
- element.removeEventListener('click', capture, true);
- element.removeEventListener('click', selectCapture);
-
- if (context.item !== undefined && context.item.isMutable && removeMutable === true) {
- this.openmct.objects.destroyMutable(context.item);
- }
- }).bind(this);
- };
-
- return Selection;
- });
+ }).bind(this);
+ }
+}
diff --git a/tsconfig.json b/tsconfig.json
index 96eb34902..b618a6e78 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -7,19 +7,27 @@
"baseUrl": "./",
"allowJs": true,
"checkJs": false,
+ "declaration": true,
+ "emitDeclarationOnly": true,
+ "declarationMap": true,
"strict": true,
"esModuleInterop": true,
"noImplicitOverride": true,
"module": "esnext",
"moduleResolution": "node",
"outDir": "dist",
+ "skipLibCheck": true,
"paths": {
// matches the alias in webpack config, so that types for those imports are visible.
"@/*": ["src/*"]
}
},
+ "include": [
+ "src/api/**/*.js"
+ ],
"exclude": [
"node_modules",
- "dist"
+ "dist",
+ "**/*Spec.js"
]
}