feat: AMD -> ES6 (#7029)

* feat: full amd -> es6 conversion

* fix: move MCT to ES6 class

* fix: default drop, correct imports

* fix: correct all imports

* fix: property typo

* fix: avoid anonymous functions

* fix: correct typo

scarily small - can see why this e2e coverage issue is high priority

* fix: use proper uuid format

* style: fmt

* fix: import vue correctly, get correct layout

* fix: createApp without JSON

fixes template issues

* fix: don't use default on InspectorDataVisualization

* fix: remove more .default calls

* Update src/api/api.js

Co-authored-by: Jesse Mazzella <ozyx@users.noreply.github.com>

* Update src/plugins/plugins.js

Co-authored-by: Jesse Mazzella <ozyx@users.noreply.github.com>

* Update src/plugins/plugins.js

Co-authored-by: Jesse Mazzella <ozyx@users.noreply.github.com>

* fix: suggestions

* fix: drop unnecessary this.annotation initialization

* fix: move all initialization calls to constructor

* refactor: move vue dist import to webpack alias

---------

Co-authored-by: Jesse Mazzella <ozyx@users.noreply.github.com>
This commit is contained in:
Tristan F 2023-12-27 15:15:51 -05:00 committed by GitHub
parent 715a44864e
commit 2e03bc394c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
102 changed files with 11730 additions and 12016 deletions

View File

@ -76,7 +76,8 @@ const config = {
MCT: path.join(projectRootDir, 'src/MCT'), MCT: path.join(projectRootDir, 'src/MCT'),
testUtils: path.join(projectRootDir, 'src/utils/testUtils.js'), testUtils: path.join(projectRootDir, 'src/utils/testUtils.js'),
objectUtils: path.join(projectRootDir, 'src/api/objects/object-utils.js'), objectUtils: path.join(projectRootDir, 'src/api/objects/object-utils.js'),
utils: path.join(projectRootDir, 'src/utils') utils: path.join(projectRootDir, 'src/utils'),
vue: 'vue/dist/vue.esm-bundler'
} }
}, },
plugins: [ plugins: [

View File

@ -1,5 +1,4 @@
define(['lodash'], function (_) { const METADATA_BY_TYPE = {
var METADATA_BY_TYPE = {
generator: { generator: {
values: [ values: [
{ {
@ -122,17 +121,14 @@ define(['lodash'], function (_) {
} }
] ]
} }
}; };
function GeneratorMetadataProvider() {} export default function GeneratorMetadataProvider() {}
GeneratorMetadataProvider.prototype.supportsMetadata = function (domainObject) { GeneratorMetadataProvider.prototype.supportsMetadata = function (domainObject) {
return Object.prototype.hasOwnProperty.call(METADATA_BY_TYPE, domainObject.type); return Object.prototype.hasOwnProperty.call(METADATA_BY_TYPE, domainObject.type);
}; };
GeneratorMetadataProvider.prototype.getMetadata = function (domainObject) { GeneratorMetadataProvider.prototype.getMetadata = function (domainObject) {
return Object.assign({}, domainObject.telemetry, METADATA_BY_TYPE[domainObject.type]); return Object.assign({}, domainObject.telemetry, METADATA_BY_TYPE[domainObject.type]);
}; };
return GeneratorMetadataProvider;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./WorkerInterface'], function (WorkerInterface) { import WorkerInterface from './WorkerInterface';
var REQUEST_DEFAULTS = {
const REQUEST_DEFAULTS = {
amplitude: 1, amplitude: 1,
period: 10, period: 10,
offset: 0, offset: 0,
@ -31,21 +32,21 @@ define(['./WorkerInterface'], function (WorkerInterface) {
loadDelay: 0, loadDelay: 0,
infinityValues: false, infinityValues: false,
exceedFloat32: false exceedFloat32: false
}; };
function GeneratorProvider(openmct, StalenessProvider) { export default function GeneratorProvider(openmct, StalenessProvider) {
this.openmct = openmct; this.openmct = openmct;
this.workerInterface = new WorkerInterface(openmct, StalenessProvider); this.workerInterface = new WorkerInterface(openmct, StalenessProvider);
} }
GeneratorProvider.prototype.canProvideTelemetry = function (domainObject) { GeneratorProvider.prototype.canProvideTelemetry = function (domainObject) {
return domainObject.type === 'generator'; return domainObject.type === 'generator';
}; };
GeneratorProvider.prototype.supportsRequest = GeneratorProvider.prototype.supportsSubscribe = GeneratorProvider.prototype.supportsRequest = GeneratorProvider.prototype.supportsSubscribe =
GeneratorProvider.prototype.canProvideTelemetry; GeneratorProvider.prototype.canProvideTelemetry;
GeneratorProvider.prototype.makeWorkerRequest = function (domainObject, request) { GeneratorProvider.prototype.makeWorkerRequest = function (domainObject, request) {
var props = [ var props = [
'amplitude', 'amplitude',
'period', 'period',
@ -85,21 +86,18 @@ define(['./WorkerInterface'], function (WorkerInterface) {
workerRequest.name = domainObject.name; workerRequest.name = domainObject.name;
return workerRequest; return workerRequest;
}; };
GeneratorProvider.prototype.request = function (domainObject, request) { GeneratorProvider.prototype.request = function (domainObject, request) {
var workerRequest = this.makeWorkerRequest(domainObject, request); var workerRequest = this.makeWorkerRequest(domainObject, request);
workerRequest.start = request.start; workerRequest.start = request.start;
workerRequest.end = request.end; workerRequest.end = request.end;
return this.workerInterface.request(workerRequest); return this.workerInterface.request(workerRequest);
}; };
GeneratorProvider.prototype.subscribe = function (domainObject, callback) { GeneratorProvider.prototype.subscribe = function (domainObject, callback) {
var workerRequest = this.makeWorkerRequest(domainObject, {}); var workerRequest = this.makeWorkerRequest(domainObject, {});
return this.workerInterface.subscribe(workerRequest, callback); return this.workerInterface.subscribe(workerRequest, callback);
}; };
return GeneratorProvider;
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { var PURPLE = {
var PURPLE = {
sin: 2.2, sin: 2.2,
cos: 2.2 cos: 2.2
}, },
@ -68,13 +67,13 @@ define([], function () {
} }
}; };
function SinewaveLimitProvider() {} export default function SinewaveLimitProvider() {}
SinewaveLimitProvider.prototype.supportsLimits = function (domainObject) { SinewaveLimitProvider.prototype.supportsLimits = function (domainObject) {
return domainObject.type === 'generator'; return domainObject.type === 'generator';
}; };
SinewaveLimitProvider.prototype.getLimitEvaluator = function (domainObject) { SinewaveLimitProvider.prototype.getLimitEvaluator = function (domainObject) {
return { return {
evaluate: function (datum, valueMetadata) { evaluate: function (datum, valueMetadata) {
var range = valueMetadata && valueMetadata.key; var range = valueMetadata && valueMetadata.key;
@ -96,9 +95,9 @@ define([], function () {
} }
} }
}; };
}; };
SinewaveLimitProvider.prototype.getLimits = function (domainObject) { SinewaveLimitProvider.prototype.getLimits = function (domainObject) {
return { return {
limits: function () { limits: function () {
return Promise.resolve({ return Promise.resolve({
@ -160,7 +159,4 @@ define([], function () {
}); });
} }
}; };
}; };
return SinewaveLimitProvider;
});

View File

@ -20,22 +20,21 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function StateGeneratorProvider() {}
function StateGeneratorProvider() {}
function pointForTimestamp(timestamp, duration, name) { function pointForTimestamp(timestamp, duration, name) {
return { return {
name: name, name: name,
utc: Math.floor(timestamp / duration) * duration, utc: Math.floor(timestamp / duration) * duration,
value: Math.floor(timestamp / duration) % 2 value: Math.floor(timestamp / duration) % 2
}; };
} }
StateGeneratorProvider.prototype.supportsSubscribe = function (domainObject) { StateGeneratorProvider.prototype.supportsSubscribe = function (domainObject) {
return domainObject.type === 'example.state-generator'; return domainObject.type === 'example.state-generator';
}; };
StateGeneratorProvider.prototype.subscribe = function (domainObject, callback) { StateGeneratorProvider.prototype.subscribe = function (domainObject, callback) {
var duration = domainObject.telemetry.duration * 1000; var duration = domainObject.telemetry.duration * 1000;
var interval = setInterval(function () { var interval = setInterval(function () {
@ -48,13 +47,13 @@ define([], function () {
return function () { return function () {
clearInterval(interval); clearInterval(interval);
}; };
}; };
StateGeneratorProvider.prototype.supportsRequest = function (domainObject, options) { StateGeneratorProvider.prototype.supportsRequest = function (domainObject, options) {
return domainObject.type === 'example.state-generator'; return domainObject.type === 'example.state-generator';
}; };
StateGeneratorProvider.prototype.request = function (domainObject, options) { StateGeneratorProvider.prototype.request = function (domainObject, options) {
var start = options.start; var start = options.start;
var end = Math.min(Date.now(), options.end); // no future values var end = Math.min(Date.now(), options.end); // no future values
var duration = domainObject.telemetry.duration * 1000; var duration = domainObject.telemetry.duration * 1000;
@ -69,7 +68,4 @@ define([], function () {
} }
return Promise.resolve(data); return Promise.resolve(data);
}; };
return StateGeneratorProvider;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['uuid'], function ({ v4: uuid }) { import { v4 as uuid } from 'uuid';
function WorkerInterface(openmct, StalenessProvider) {
export default function WorkerInterface(openmct, StalenessProvider) {
// eslint-disable-next-line no-undef // eslint-disable-next-line no-undef
const workerUrl = `${openmct.getAssetPath()}${__OPENMCT_ROOT_RELATIVE__}generatorWorker.js`; const workerUrl = `${openmct.getAssetPath()}${__OPENMCT_ROOT_RELATIVE__}generatorWorker.js`;
this.StalenessProvider = StalenessProvider; this.StalenessProvider = StalenessProvider;
@ -31,23 +32,23 @@ define(['uuid'], function ({ v4: uuid }) {
this.staleTelemetryIds = {}; this.staleTelemetryIds = {};
this.watchStaleness(); this.watchStaleness();
} }
WorkerInterface.prototype.watchStaleness = function () { WorkerInterface.prototype.watchStaleness = function () {
this.StalenessProvider.on('stalenessEvent', ({ id, isStale }) => { this.StalenessProvider.on('stalenessEvent', ({ id, isStale }) => {
this.staleTelemetryIds[id] = isStale; this.staleTelemetryIds[id] = isStale;
}); });
}; };
WorkerInterface.prototype.onMessage = function (message) { WorkerInterface.prototype.onMessage = function (message) {
message = message.data; message = message.data;
var callback = this.callbacks[message.id]; var callback = this.callbacks[message.id];
if (callback) { if (callback) {
callback(message); callback(message);
} }
}; };
WorkerInterface.prototype.dispatch = function (request, data, callback) { WorkerInterface.prototype.dispatch = function (request, data, callback) {
var message = { var message = {
request: request, request: request,
data: data, data: data,
@ -61,9 +62,9 @@ define(['uuid'], function ({ v4: uuid }) {
this.worker.postMessage(message); this.worker.postMessage(message);
return message.id; return message.id;
}; };
WorkerInterface.prototype.request = function (request) { WorkerInterface.prototype.request = function (request) {
var deferred = {}; var deferred = {};
var promise = new Promise(function (resolve, reject) { var promise = new Promise(function (resolve, reject) {
deferred.resolve = resolve; deferred.resolve = resolve;
@ -85,9 +86,9 @@ define(['uuid'], function ({ v4: uuid }) {
messageId = this.dispatch('request', request, callback.bind(this)); messageId = this.dispatch('request', request, callback.bind(this));
return promise; return promise;
}; };
WorkerInterface.prototype.subscribe = function (request, cb) { WorkerInterface.prototype.subscribe = function (request, cb) {
const { id, loadDelay } = request; const { id, loadDelay } = request;
const messageId = this.dispatch('subscribe', request, (message) => { const messageId = this.dispatch('subscribe', request, (message) => {
if (!this.staleTelemetryIds[id]) { if (!this.staleTelemetryIds[id]) {
@ -101,7 +102,4 @@ define(['uuid'], function ({ v4: uuid }) {
}); });
delete this.callbacks[messageId]; delete this.callbacks[messageId];
}.bind(this); }.bind(this);
}; };
return WorkerInterface;
});

View File

@ -75,7 +75,7 @@ if (document.currentScript) {
* @property {OpenMCTComponent[]} components * @property {OpenMCTComponent[]} components
*/ */
const MCT = require('./src/MCT'); const { MCT } = require('./src/MCT');
/** @type {OpenMCT} */ /** @type {OpenMCT} */
const openmct = new MCT(); const openmct = new MCT();

View File

@ -20,56 +20,47 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
/* eslint-disable no-undef */ /* eslint-disable no-undef */
define([ import EventEmitter from 'EventEmitter';
'EventEmitter', import { createApp, markRaw } from 'vue';
'./api/api',
'./api/overlays/OverlayAPI', import ActionsAPI from './api/actions/ActionsAPI';
'./api/tooltips/ToolTipAPI', import AnnotationAPI from './api/annotation/AnnotationAPI';
'./selection/Selection', import BrandingAPI from './api/Branding';
'./plugins/plugins', import CompositionAPI from './api/composition/CompositionAPI';
'./ui/registries/ViewRegistry', import EditorAPI from './api/Editor';
'./plugins/imagery/plugin', import FaultManagementAPI from './api/faultmanagement/FaultManagementAPI';
'./ui/registries/InspectorViewRegistry', import FormsAPI from './api/forms/FormsAPI';
'./ui/registries/ToolbarRegistry', import IndicatorAPI from './api/indicators/IndicatorAPI';
'./ui/router/ApplicationRouter', import MenuAPI from './api/menu/MenuAPI';
'./ui/router/Browse', import NotificationAPI from './api/notifications/NotificationAPI';
'./ui/layout/AppLayout.vue', import ObjectAPI from './api/objects/ObjectAPI';
'./ui/preview/plugin', import OverlayAPI from './api/overlays/OverlayAPI';
'./api/Branding', import PriorityAPI from './api/priority/PriorityAPI';
'./plugins/licenses/plugin', import StatusAPI from './api/status/StatusAPI';
'./plugins/remove/plugin', import TelemetryAPI from './api/telemetry/TelemetryAPI';
'./plugins/move/plugin', import TimeAPI from './api/time/TimeAPI';
'./plugins/linkAction/plugin', import ToolTipAPI from './api/tooltips/ToolTipAPI';
'./plugins/duplicate/plugin', import TypeRegistry from './api/types/TypeRegistry';
'./plugins/importFromJSONAction/plugin', import UserAPI from './api/user/UserAPI';
'./plugins/exportAsJSONAction/plugin', import DuplicateActionPlugin from './plugins/duplicate/plugin';
'vue' import ExportAsJSONAction from './plugins/exportAsJSONAction/plugin';
], function ( import ImageryPlugin from './plugins/imagery/plugin';
EventEmitter, import ImportFromJSONAction from './plugins/importFromJSONAction/plugin';
api, import LicensesPlugin from './plugins/licenses/plugin';
OverlayAPI, import LinkActionPlugin from './plugins/linkAction/plugin';
ToolTipAPI, import MoveActionPlugin from './plugins/move/plugin';
Selection, import plugins from './plugins/plugins';
plugins, import RemoveActionPlugin from './plugins/remove/plugin';
ViewRegistry, import Selection from './selection/Selection';
ImageryPlugin, import Layout from './ui/layout/AppLayout.vue';
InspectorViewRegistry, import PreviewPlugin from './ui/preview/plugin';
ToolbarRegistry, import InspectorViewRegistry from './ui/registries/InspectorViewRegistry';
ApplicationRouter, import ToolbarRegistry from './ui/registries/ToolbarRegistry';
Browse, import ViewRegistry from './ui/registries/ViewRegistry';
Layout, import ApplicationRouter from './ui/router/ApplicationRouter';
PreviewPlugin, import Browse from './ui/router/Browse';
BrandingAPI,
LicensesPlugin, /**
RemoveActionPlugin,
MoveActionPlugin,
LinkActionPlugin,
DuplicateActionPlugin,
ImportFromJSONAction,
ExportAsJSONAction,
Vue
) {
/**
* Open MCT is an extensible web application for building mission * Open MCT is an extensible web application for building mission
* control user interfaces. This module is itself an instance of * control user interfaces. This module is itself an instance of
* [MCT]{@link module:openmct.MCT}, which provides an interface for * [MCT]{@link module:openmct.MCT}, which provides an interface for
@ -78,14 +69,17 @@ define([
* @exports openmct * @exports openmct
*/ */
/** /**
* The Open MCT application. This may be configured by installing plugins * The Open MCT application. This may be configured by installing plugins
* or registering extensions before the application is started. * or registering extensions before the application is started.
* @constructor * @constructor
* @memberof module:openmct * @memberof module:openmct
*/ */
function MCT() { export class MCT extends EventEmitter {
constructor() {
super();
EventEmitter.call(this); EventEmitter.call(this);
this.buildInfo = { this.buildInfo = {
version: __OPENMCT_VERSION__, version: __OPENMCT_VERSION__,
buildDate: __OPENMCT_BUILD_DATE__, buildDate: __OPENMCT_BUILD_DATE__,
@ -95,12 +89,14 @@ define([
this.destroy = this.destroy.bind(this); this.destroy = this.destroy.bind(this);
this.defaultClock = 'local'; this.defaultClock = 'local';
[
this.plugins = plugins;
/** /**
* Tracks current selection state of the application. * Tracks current selection state of the application.
* @private * @private
*/ */
['selection', () => new Selection.default(this)], this.selection = new Selection(this);
/** /**
* MCT's time conductor, which may be used to synchronize view contents * MCT's time conductor, which may be used to synchronize view contents
@ -109,7 +105,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name conductor * @name conductor
*/ */
['time', () => new api.TimeAPI(this)], this.time = new TimeAPI(this);
/** /**
* An interface for interacting with the composition of domain objects. * An interface for interacting with the composition of domain objects.
@ -124,7 +120,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name composition * @name composition
*/ */
['composition', () => new api.CompositionAPI.default(this)], this.composition = new CompositionAPI(this);
/** /**
* Registry for views of domain objects which should appear in the * Registry for views of domain objects which should appear in the
@ -134,7 +130,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name objectViews * @name objectViews
*/ */
['objectViews', () => new ViewRegistry()], this.objectViews = new ViewRegistry();
/** /**
* Registry for views which should appear in the Inspector area. * Registry for views which should appear in the Inspector area.
@ -144,7 +140,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name inspectorViews * @name inspectorViews
*/ */
['inspectorViews', () => new InspectorViewRegistry.default()], this.inspectorViews = new InspectorViewRegistry();
/** /**
* Registry for views which should appear in Edit Properties * Registry for views which should appear in Edit Properties
@ -155,7 +151,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name propertyEditors * @name propertyEditors
*/ */
['propertyEditors', () => new ViewRegistry()], this.propertyEditors = new ViewRegistry();
/** /**
* Registry for views which should appear in the toolbar area while * Registry for views which should appear in the toolbar area while
@ -165,7 +161,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name toolbars * @name toolbars
*/ */
['toolbars', () => new ToolbarRegistry()], this.toolbars = new ToolbarRegistry();
/** /**
* Registry for domain object types which may exist within this * Registry for domain object types which may exist within this
@ -175,7 +171,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name types * @name types
*/ */
['types', () => new api.TypeRegistry()], this.types = new TypeRegistry();
/** /**
* An interface for interacting with domain objects and the domain * An interface for interacting with domain objects and the domain
@ -185,7 +181,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name objects * @name objects
*/ */
['objects', () => new api.ObjectAPI.default(this.types, this)], this.objects = new ObjectAPI(this.types, this);
/** /**
* An interface for retrieving and interpreting telemetry data associated * An interface for retrieving and interpreting telemetry data associated
@ -195,7 +191,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name telemetry * @name telemetry
*/ */
['telemetry', () => new api.TelemetryAPI.default(this)], this.telemetry = new TelemetryAPI(this);
/** /**
* An interface for creating new indicators and changing them dynamically. * An interface for creating new indicators and changing them dynamically.
@ -204,7 +200,7 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name indicators * @name indicators
*/ */
['indicators', () => new api.IndicatorAPI(this)], this.indicators = new IndicatorAPI(this);
/** /**
* MCT's user awareness management, to enable user and * MCT's user awareness management, to enable user and
@ -213,31 +209,20 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name user * @name user
*/ */
['user', () => new api.UserAPI(this)], this.user = new UserAPI(this);
['notifications', () => new api.NotificationAPI()], this.notifications = new NotificationAPI();
this.editor = new EditorAPI(this);
['editor', () => new api.EditorAPI.default(this)], this.overlays = new OverlayAPI();
this.tooltips = new ToolTipAPI();
['overlays', () => new OverlayAPI.default()], this.menus = new MenuAPI(this);
this.actions = new ActionsAPI(this);
['tooltips', () => new ToolTipAPI.default()], this.status = new StatusAPI(this);
this.priority = PriorityAPI;
['menus', () => new api.MenuAPI(this)], this.router = new ApplicationRouter(this);
this.faults = new FaultManagementAPI(this);
['actions', () => new api.ActionsAPI(this)], this.forms = new FormsAPI(this);
this.branding = BrandingAPI;
['status', () => new api.StatusAPI(this)],
['priority', () => api.PriorityAPI],
['router', () => new ApplicationRouter(this)],
['faults', () => new api.FaultManagementAPI.default(this)],
['forms', () => new api.FormsAPI.default(this)],
['branding', () => BrandingAPI.default],
/** /**
* MCT's annotation API that enables * MCT's annotation API that enables
@ -246,43 +231,23 @@ define([
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @name annotation * @name annotation
*/ */
['annotation', () => new api.AnnotationAPI(this)] this.annotation = new AnnotationAPI(this);
].forEach((apiEntry) => {
const apiName = apiEntry[0];
const apiObject = apiEntry[1]();
Object.defineProperty(this, apiName, {
value: apiObject,
enumerable: false,
configurable: false,
writable: true
});
});
/**
* MCT's annotation API that enables
* human-created comments and categorization linked to data products
* @type {module:openmct.AnnotationAPI}
* @memberof module:openmct.MCT#
* @name annotation
*/
this.annotation = new api.AnnotationAPI(this);
// Plugins that are installed by default // Plugins that are installed by default
this.install(this.plugins.Plot()); this.install(this.plugins.Plot());
this.install(this.plugins.TelemetryTable.default()); this.install(this.plugins.TelemetryTable());
this.install(PreviewPlugin.default()); this.install(PreviewPlugin());
this.install(LicensesPlugin.default()); this.install(LicensesPlugin());
this.install(RemoveActionPlugin.default()); this.install(RemoveActionPlugin());
this.install(MoveActionPlugin.default()); this.install(MoveActionPlugin());
this.install(LinkActionPlugin.default()); this.install(LinkActionPlugin());
this.install(DuplicateActionPlugin.default()); this.install(DuplicateActionPlugin());
this.install(ExportAsJSONAction.default()); this.install(ExportAsJSONAction());
this.install(ImportFromJSONAction.default()); this.install(ImportFromJSONAction());
this.install(this.plugins.FormActions.default()); this.install(this.plugins.FormActions());
this.install(this.plugins.FolderView()); this.install(this.plugins.FolderView());
this.install(this.plugins.Tabs()); this.install(this.plugins.Tabs());
this.install(ImageryPlugin.default()); this.install(ImageryPlugin());
this.install(this.plugins.FlexibleLayout()); this.install(this.plugins.FlexibleLayout());
this.install(this.plugins.GoToOriginalAction()); this.install(this.plugins.GoToOriginalAction());
this.install(this.plugins.OpenInNewTabAction()); this.install(this.plugins.OpenInNewTabAction());
@ -300,26 +265,20 @@ define([
this.install(this.plugins.Gauge()); this.install(this.plugins.Gauge());
this.install(this.plugins.InspectorViews()); this.install(this.plugins.InspectorViews());
} }
MCT.prototype = Object.create(EventEmitter.prototype);
MCT.prototype.MCT = MCT;
/** /**
* Set path to where assets are hosted. This should be the path to main.js. * Set path to where assets are hosted. This should be the path to main.js.
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @method setAssetPath * @method setAssetPath
*/ */
MCT.prototype.setAssetPath = function (assetPath) { setAssetPath(assetPath) {
this._assetPath = assetPath; this._assetPath = assetPath;
}; }
/** /**
* Get path to where assets are hosted. * Get path to where assets are hosted.
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
* @method getAssetPath * @method getAssetPath
*/ */
MCT.prototype.getAssetPath = function () { getAssetPath() {
const assetPathLength = this._assetPath && this._assetPath.length; const assetPathLength = this._assetPath && this._assetPath.length;
if (!assetPathLength) { if (!assetPathLength) {
return '/'; return '/';
@ -330,8 +289,7 @@ define([
} }
return this._assetPath; return this._assetPath;
}; }
/** /**
* Start running Open MCT. This should be called only after any plugins * Start running Open MCT. This should be called only after any plugins
* have been installed. * have been installed.
@ -341,10 +299,7 @@ define([
* @param {HTMLElement} [domElement] the DOM element in which to run * @param {HTMLElement} [domElement] the DOM element in which to run
* MCT; if undefined, MCT will be run in the body of the document * MCT; if undefined, MCT will be run in the body of the document
*/ */
MCT.prototype.start = function ( start(domElement = document.body.firstElementChild, isHeadlessMode = false) {
domElement = document.body.firstElementChild,
isHeadlessMode = false
) {
// Create element to mount Layout if it doesn't exist // Create element to mount Layout if it doesn't exist
if (domElement === null) { if (domElement === null) {
domElement = document.createElement('div'); domElement = document.createElement('div');
@ -376,20 +331,12 @@ define([
* @event start * @event start
* @memberof module:openmct.MCT~ * @memberof module:openmct.MCT~
*/ */
if (!isHeadlessMode) { if (!isHeadlessMode) {
const appLayout = Vue.createApp({ const appLayout = createApp(Layout);
components: { appLayout.provide('openmct', markRaw(this));
Layout: Layout.default
},
provide: {
openmct: Vue.markRaw(this)
},
template: '<Layout ref="layout"></Layout>'
});
const component = appLayout.mount(domElement); const component = appLayout.mount(domElement);
component.$nextTick(() => { component.$nextTick(() => {
this.layout = component.$refs.layout; this.layout = component;
this.app = appLayout; this.app = appLayout;
Browse(this); Browse(this);
window.addEventListener('beforeunload', this.destroy); window.addEventListener('beforeunload', this.destroy);
@ -402,14 +349,12 @@ define([
this.router.start(); this.router.start();
this.emit('start'); this.emit('start');
} }
}; }
startHeadless() {
MCT.prototype.startHeadless = function () {
let unreachableNode = document.createElement('div'); let unreachableNode = document.createElement('div');
return this.start(unreachableNode, true); return this.start(unreachableNode, true);
}; }
/** /**
* Install a plugin in MCT. * Install a plugin in MCT.
* *
@ -417,17 +362,13 @@ define([
* invoked with the mct instance. * invoked with the mct instance.
* @memberof module:openmct.MCT# * @memberof module:openmct.MCT#
*/ */
MCT.prototype.install = function (plugin) { install(plugin) {
plugin(this); plugin(this);
}; }
MCT.prototype.destroy = function () { destroy() {
window.removeEventListener('beforeunload', this.destroy); window.removeEventListener('beforeunload', this.destroy);
this.emit('destroy'); this.emit('destroy');
this.router.destroy(); this.router.destroy();
}; }
}
MCT.prototype.plugins = plugins;
return MCT;
});

View File

@ -20,8 +20,11 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./plugins/plugins', 'utils/testing'], function (plugins, testUtils) { import * as testUtils from 'utils/testing';
describe('MCT', function () {
import plugins from './plugins/plugins';
describe('MCT', function () {
let openmct; let openmct;
let mockPlugin; let mockPlugin;
let mockPlugin2; let mockPlugin2;
@ -111,5 +114,4 @@ define(['./plugins/plugins', 'utils/testing'], function (plugins, testUtils) {
expect(openmct.getAssetPath()).toBe(testAssetPath + '/'); expect(openmct.getAssetPath()).toBe(testAssetPath + '/');
}); });
}); });
});
}); });

View File

@ -20,24 +20,24 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([ import ActionsAPI from './actions/ActionsAPI';
'./actions/ActionsAPI', import AnnotationAPI from './annotation/AnnotationAPI';
'./composition/CompositionAPI', import CompositionAPI from './composition/CompositionAPI';
'./Editor', import EditorAPI from './Editor';
'./faultmanagement/FaultManagementAPI', import FaultManagementAPI from './faultmanagement/FaultManagementAPI';
'./forms/FormsAPI', import FormsAPI from './forms/FormsAPI';
'./indicators/IndicatorAPI', import IndicatorAPI from './indicators/IndicatorAPI';
'./menu/MenuAPI', import MenuAPI from './menu/MenuAPI';
'./notifications/NotificationAPI', import NotificationAPI from './notifications/NotificationAPI';
'./objects/ObjectAPI', import ObjectAPI from './objects/ObjectAPI';
'./priority/PriorityAPI', import PriorityAPI from './priority/PriorityAPI';
'./status/StatusAPI', import StatusAPI from './status/StatusAPI';
'./telemetry/TelemetryAPI', import TelemetryAPI from './telemetry/TelemetryAPI';
'./time/TimeAPI', import TimeAPI from './time/TimeAPI';
'./types/TypeRegistry', import TypeRegistry from './types/TypeRegistry';
'./user/UserAPI', import UserAPI from './user/UserAPI';
'./annotation/AnnotationAPI'
], function ( export default {
ActionsAPI, ActionsAPI,
CompositionAPI, CompositionAPI,
EditorAPI, EditorAPI,
@ -54,23 +54,4 @@ define([
TypeRegistry, TypeRegistry,
UserAPI, UserAPI,
AnnotationAPI AnnotationAPI
) { };
return {
ActionsAPI: ActionsAPI.default,
CompositionAPI: CompositionAPI,
EditorAPI: EditorAPI,
FaultManagementAPI: FaultManagementAPI,
FormsAPI: FormsAPI,
IndicatorAPI: IndicatorAPI.default,
MenuAPI: MenuAPI.default,
NotificationAPI: NotificationAPI.default,
ObjectAPI: ObjectAPI,
PriorityAPI: PriorityAPI.default,
StatusAPI: StatusAPI.default,
TelemetryAPI: TelemetryAPI,
TimeAPI: TimeAPI.default,
TypeRegistry: TypeRegistry.default,
UserAPI: UserAPI.default,
AnnotationAPI: AnnotationAPI.default
};
});

View File

@ -20,28 +20,27 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* Utility for checking if a thing is an Open MCT Identifier. * Utility for checking if a thing is an Open MCT Identifier.
* @private * @private
*/ */
function isIdentifier(thing) { function isIdentifier(thing) {
return ( return (
typeof thing === 'object' && typeof thing === 'object' &&
Object.prototype.hasOwnProperty.call(thing, 'key') && Object.prototype.hasOwnProperty.call(thing, 'key') &&
Object.prototype.hasOwnProperty.call(thing, 'namespace') Object.prototype.hasOwnProperty.call(thing, 'namespace')
); );
} }
/** /**
* Utility for checking if a thing is a key string. Not perfect. * Utility for checking if a thing is a key string. Not perfect.
* @private * @private
*/ */
function isKeyString(thing) { function isKeyString(thing) {
return typeof thing === 'string'; return typeof thing === 'string';
} }
/** /**
* Convert a keyString into an Open MCT Identifier, ex: * Convert a keyString into an Open MCT Identifier, ex:
* 'scratch:root' ==> {namespace: 'scratch', key: 'root'} * 'scratch:root' ==> {namespace: 'scratch', key: 'root'}
* *
@ -50,7 +49,7 @@ define([], function () {
* @param keyString * @param keyString
* @returns identifier * @returns identifier
*/ */
function parseKeyString(keyString) { function parseKeyString(keyString) {
if (isIdentifier(keyString)) { if (isIdentifier(keyString)) {
return keyString; return keyString;
} }
@ -76,9 +75,9 @@ define([], function () {
namespace: namespace, namespace: namespace,
key: key key: key
}; };
} }
/** /**
* Convert an Open MCT Identifier into a keyString, ex: * Convert an Open MCT Identifier into a keyString, ex:
* {namespace: 'scratch', key: 'root'} ==> 'scratch:root' * {namespace: 'scratch', key: 'root'} ==> 'scratch:root'
* *
@ -87,7 +86,7 @@ define([], function () {
* @param identifier * @param identifier
* @returns keyString * @returns keyString
*/ */
function makeKeyString(identifier) { function makeKeyString(identifier) {
if (!identifier) { if (!identifier) {
throw new Error('Cannot make key string from null identifier'); throw new Error('Cannot make key string from null identifier');
} }
@ -101,9 +100,9 @@ define([], function () {
} }
return [identifier.namespace.replace(/:/g, '\\:'), identifier.key].join(':'); return [identifier.namespace.replace(/:/g, '\\:'), identifier.key].join(':');
} }
/** /**
* Convert a new domain object into an old format model, removing the * Convert a new domain object into an old format model, removing the
* identifier and converting the composition array from Open MCT Identifiers * identifier and converting the composition array from Open MCT Identifiers
* to old format keyStrings. * to old format keyStrings.
@ -111,7 +110,7 @@ define([], function () {
* @param domainObject * @param domainObject
* @returns oldFormatModel * @returns oldFormatModel
*/ */
function toOldFormat(model) { function toOldFormat(model) {
model = JSON.parse(JSON.stringify(model)); model = JSON.parse(JSON.stringify(model));
delete model.identifier; delete model.identifier;
if (model.composition) { if (model.composition) {
@ -119,9 +118,9 @@ define([], function () {
} }
return model; return model;
} }
/** /**
* Convert an old format domain object model into a new format domain * Convert an old format domain object model into a new format domain
* object. Adds an identifier using the provided keyString, and converts * object. Adds an identifier using the provided keyString, and converts
* the composition array to utilize Open MCT Identifiers. * the composition array to utilize Open MCT Identifiers.
@ -130,7 +129,7 @@ define([], function () {
* @param keyString * @param keyString
* @returns domainObject * @returns domainObject
*/ */
function toNewFormat(model, keyString) { function toNewFormat(model, keyString) {
model = JSON.parse(JSON.stringify(model)); model = JSON.parse(JSON.stringify(model));
model.identifier = parseKeyString(keyString); model.identifier = parseKeyString(keyString);
if (model.composition) { if (model.composition) {
@ -138,20 +137,20 @@ define([], function () {
} }
return model; return model;
} }
/** /**
* Compare two Open MCT Identifiers, returning true if they are equal. * Compare two Open MCT Identifiers, returning true if they are equal.
* *
* @param identifier * @param identifier
* @param otherIdentifier * @param otherIdentifier
* @returns Boolean true if identifiers are equal. * @returns Boolean true if identifiers are equal.
*/ */
function identifierEquals(a, b) { function identifierEquals(a, b) {
return a.key === b.key && a.namespace === b.namespace; return a.key === b.key && a.namespace === b.namespace;
} }
/** /**
* Compare two domain objects, return true if they're the same object. * Compare two domain objects, return true if they're the same object.
* Equality is determined by identifier. * Equality is determined by identifier.
* *
@ -159,17 +158,17 @@ define([], function () {
* @param otherDomainOBject * @param otherDomainOBject
* @returns Boolean true if objects are equal. * @returns Boolean true if objects are equal.
*/ */
function objectEquals(a, b) { function objectEquals(a, b) {
return identifierEquals(a.identifier, b.identifier); return identifierEquals(a.identifier, b.identifier);
} }
function refresh(oldObject, newObject) { function refresh(oldObject, newObject) {
let deleted = _.difference(Object.keys(oldObject), Object.keys(newObject)); let deleted = _.difference(Object.keys(oldObject), Object.keys(newObject));
deleted.forEach((propertyName) => delete oldObject[propertyName]); deleted.forEach((propertyName) => delete oldObject[propertyName]);
Object.assign(oldObject, newObject); Object.assign(oldObject, newObject);
} }
return { export default {
isIdentifier: isIdentifier, isIdentifier: isIdentifier,
toOldFormat: toOldFormat, toOldFormat: toOldFormat,
toNewFormat: toNewFormat, toNewFormat: toNewFormat,
@ -178,5 +177,4 @@ define([], function () {
equals: objectEquals, equals: objectEquals,
identifierEquals: identifierEquals, identifierEquals: identifierEquals,
refresh: refresh refresh: refresh
}; };
});

View File

@ -1,5 +1,6 @@
define(['objectUtils'], function (objectUtils) { import objectUtils from 'objectUtils';
describe('objectUtils', function () {
describe('objectUtils', function () {
describe('keyString util', function () { describe('keyString util', function () {
const EXPECTATIONS = { const EXPECTATIONS = {
ROOT: { ROOT: {
@ -143,5 +144,4 @@ define(['objectUtils'], function (objectUtils) {
}); });
}); });
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['lodash'], function (_) { import _ from 'lodash';
/**
/**
* This is the default metadata provider; for any object with a "telemetry" * This is the default metadata provider; for any object with a "telemetry"
* property, this provider will return the value of that property as the * property, this provider will return the value of that property as the
* telemetry metadata. * telemetry metadata.
@ -30,7 +31,8 @@ define(['lodash'], function (_) {
* defined on the type. Telemetry metadata definitions on type will be * defined on the type. Telemetry metadata definitions on type will be
* depreciated in the future. * depreciated in the future.
*/ */
function DefaultMetadataProvider(openmct) { export default class DefaultMetadataProvider {
constructor(openmct) {
this.openmct = openmct; this.openmct = openmct;
} }
@ -38,15 +40,43 @@ define(['lodash'], function (_) {
* Applies to any domain object with a telemetry property, or whose type * Applies to any domain object with a telemetry property, or whose type
* definition has a telemetry property. * definition has a telemetry property.
*/ */
DefaultMetadataProvider.prototype.supportsMetadata = function (domainObject) { supportsMetadata(domainObject) {
return Boolean(domainObject.telemetry) || Boolean(this.typeHasTelemetry(domainObject)); return Boolean(domainObject.telemetry) || Boolean(this.typeHasTelemetry(domainObject));
}; }
/** /**
* Returns telemetry metadata for a given domain object.
*/
getMetadata(domainObject) {
const metadata = domainObject.telemetry || {};
if (this.typeHasTelemetry(domainObject)) {
const typeMetadata = this.openmct.types.get(domainObject.type).definition.telemetry;
Object.assign(metadata, typeMetadata);
if (!metadata.values) {
metadata.values = valueMetadatasFromOldFormat(metadata);
}
}
return metadata;
}
/**
* @private
*/
typeHasTelemetry(domainObject) {
const type = this.openmct.types.get(domainObject.type);
return Boolean(type.definition.telemetry);
}
}
/**
* Retrieves valueMetadata from legacy metadata. * Retrieves valueMetadata from legacy metadata.
* @private * @private
*/ */
function valueMetadatasFromOldFormat(metadata) { function valueMetadatasFromOldFormat(metadata) {
const valueMetadatas = []; const valueMetadatas = [];
valueMetadatas.push({ valueMetadatas.push({
@ -91,34 +121,4 @@ define(['lodash'], function (_) {
}); });
return valueMetadatas; return valueMetadatas;
} }
/**
* Returns telemetry metadata for a given domain object.
*/
DefaultMetadataProvider.prototype.getMetadata = function (domainObject) {
const metadata = domainObject.telemetry || {};
if (this.typeHasTelemetry(domainObject)) {
const typeMetadata = this.openmct.types.get(domainObject.type).definition.telemetry;
Object.assign(metadata, typeMetadata);
if (!metadata.values) {
metadata.values = valueMetadatasFromOldFormat(metadata);
}
}
return metadata;
};
/**
* @private
*/
DefaultMetadataProvider.prototype.typeHasTelemetry = function (domainObject) {
const type = this.openmct.types.get(domainObject.type);
return Boolean(type.definition.telemetry);
};
return DefaultMetadataProvider;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['lodash'], function (_) { import _ from 'lodash';
function applyReasonableDefaults(valueMetadata, index) {
function applyReasonableDefaults(valueMetadata, index) {
valueMetadata.source = valueMetadata.source || valueMetadata.key; valueMetadata.source = valueMetadata.source || valueMetadata.key;
valueMetadata.hints = valueMetadata.hints || {}; valueMetadata.hints = valueMetadata.hints || {};
@ -60,43 +61,43 @@ define(['lodash'], function (_) {
} }
return valueMetadata; return valueMetadata;
} }
/** /**
* Utility class for handling and inspecting telemetry metadata. Applies * Utility class for handling and inspecting telemetry metadata. Applies
* reasonable defaults to simplify the task of providing metadata, while * reasonable defaults to simplify the task of providing metadata, while
* also providing methods for interrogating telemetry metadata. * also providing methods for interrogating telemetry metadata.
*/ */
function TelemetryMetadataManager(metadata) { export default function TelemetryMetadataManager(metadata) {
this.metadata = metadata; this.metadata = metadata;
this.valueMetadatas = this.metadata.values this.valueMetadatas = this.metadata.values
? this.metadata.values.map(applyReasonableDefaults) ? this.metadata.values.map(applyReasonableDefaults)
: []; : [];
} }
/** /**
* Get value metadata for a single key. * Get value metadata for a single key.
*/ */
TelemetryMetadataManager.prototype.value = function (key) { TelemetryMetadataManager.prototype.value = function (key) {
return this.valueMetadatas.filter(function (metadata) { return this.valueMetadatas.filter(function (metadata) {
return metadata.key === key; return metadata.key === key;
})[0]; })[0];
}; };
/** /**
* Returns all value metadatas, sorted by priority. * Returns all value metadatas, sorted by priority.
*/ */
TelemetryMetadataManager.prototype.values = function () { TelemetryMetadataManager.prototype.values = function () {
return this.valuesForHints(['priority']); return this.valuesForHints(['priority']);
}; };
/** /**
* Get an array of valueMetadatas that possess all hints requested. * Get an array of valueMetadatas that possess all hints requested.
* Array is sorted based on hint priority. * Array is sorted based on hint priority.
* *
*/ */
TelemetryMetadataManager.prototype.valuesForHints = function (hints) { TelemetryMetadataManager.prototype.valuesForHints = function (hints) {
function hasHint(hint) { function hasHint(hint) {
// eslint-disable-next-line no-invalid-this // eslint-disable-next-line no-invalid-this
return Object.prototype.hasOwnProperty.call(this.hints, hint); return Object.prototype.hasOwnProperty.call(this.hints, hint);
@ -114,35 +115,35 @@ define(['lodash'], function (_) {
}); });
return _.sortBy(matchingMetadata, ...iteratees); return _.sortBy(matchingMetadata, ...iteratees);
}; };
/** /**
* check out of a given metadata has array values * check out of a given metadata has array values
*/ */
TelemetryMetadataManager.prototype.isArrayValue = function (metadata) { TelemetryMetadataManager.prototype.isArrayValue = function (metadata) {
const regex = /\[\]$/g; const regex = /\[\]$/g;
if (!metadata.format && !metadata.formatString) { if (!metadata.format && !metadata.formatString) {
return false; return false;
} }
return (metadata.format || metadata.formatString).match(regex) !== null; return (metadata.format || metadata.formatString).match(regex) !== null;
}; };
TelemetryMetadataManager.prototype.getFilterableValues = function () { TelemetryMetadataManager.prototype.getFilterableValues = function () {
return this.valueMetadatas.filter( return this.valueMetadatas.filter(
(metadatum) => metadatum.filters && metadatum.filters.length > 0 (metadatum) => metadatum.filters && metadatum.filters.length > 0
); );
}; };
TelemetryMetadataManager.prototype.getUseToUpdateInPlaceValue = function () { TelemetryMetadataManager.prototype.getUseToUpdateInPlaceValue = function () {
return this.valueMetadatas.find(this.isInPlaceUpdateValue); return this.valueMetadatas.find(this.isInPlaceUpdateValue);
}; };
TelemetryMetadataManager.prototype.isInPlaceUpdateValue = function (metadatum) { TelemetryMetadataManager.prototype.isInPlaceUpdateValue = function (metadatum) {
return metadatum.useToUpdateInPlace === true; return metadatum.useToUpdateInPlace === true;
}; };
TelemetryMetadataManager.prototype.getDefaultDisplayValue = function () { TelemetryMetadataManager.prototype.getDefaultDisplayValue = function () {
let valueMetadata = this.valuesForHints(['range'])[0]; let valueMetadata = this.valuesForHints(['range'])[0];
if (valueMetadata === undefined) { if (valueMetadata === undefined) {
@ -156,7 +157,4 @@ define(['lodash'], function (_) {
} }
return valueMetadata; return valueMetadata;
}; };
return TelemetryMetadataManager;
});

View File

@ -20,22 +20,21 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { // Set of connection states; changing among these states will be
// Set of connection states; changing among these states will be // reflected in the indicator's appearance.
// reflected in the indicator's appearance. // CONNECTED: Everything nominal, expect to be able to read/write.
// CONNECTED: Everything nominal, expect to be able to read/write. // DISCONNECTED: HTTP failed; maybe misconfigured, disconnected.
// DISCONNECTED: HTTP failed; maybe misconfigured, disconnected. // PENDING: Still trying to connect, and haven't failed yet.
// PENDING: Still trying to connect, and haven't failed yet. const CONNECTED = {
const CONNECTED = {
statusClass: 's-status-on' statusClass: 's-status-on'
}; };
const PENDING = { const PENDING = {
statusClass: 's-status-warning-lo' statusClass: 's-status-warning-lo'
}; };
const DISCONNECTED = { const DISCONNECTED = {
statusClass: 's-status-warning-hi' statusClass: 's-status-warning-hi'
}; };
function URLIndicator(options, simpleIndicator) { export default function URLIndicator(options, simpleIndicator) {
this.bindMethods(); this.bindMethods();
this.count = 0; this.count = 0;
@ -45,9 +44,9 @@ define([], function () {
this.fetchUrl(); this.fetchUrl();
setInterval(this.fetchUrl, this.interval); setInterval(this.fetchUrl, this.interval);
} }
URLIndicator.prototype.setIndicatorToState = function (state) { URLIndicator.prototype.setIndicatorToState = function (state) {
switch (state) { switch (state) {
case CONNECTED: { case CONNECTED: {
this.indicator.text(this.label + ' is connected'); this.indicator.text(this.label + ' is connected');
@ -73,9 +72,9 @@ define([], function () {
} }
this.indicator.statusClass(state.statusClass); this.indicator.statusClass(state.statusClass);
}; };
URLIndicator.prototype.fetchUrl = function () { URLIndicator.prototype.fetchUrl = function () {
fetch(this.URLpath) fetch(this.URLpath)
.then((response) => { .then((response) => {
if (response.ok) { if (response.ok) {
@ -87,29 +86,26 @@ define([], function () {
.catch((error) => { .catch((error) => {
this.handleError(); this.handleError();
}); });
}; };
URLIndicator.prototype.handleError = function (e) { URLIndicator.prototype.handleError = function (e) {
this.setIndicatorToState(DISCONNECTED); this.setIndicatorToState(DISCONNECTED);
}; };
URLIndicator.prototype.handleSuccess = function () { URLIndicator.prototype.handleSuccess = function () {
this.setIndicatorToState(CONNECTED); this.setIndicatorToState(CONNECTED);
}; };
URLIndicator.prototype.setDefaultsFromOptions = function (options) { URLIndicator.prototype.setDefaultsFromOptions = function (options) {
this.URLpath = options.url; this.URLpath = options.url;
this.label = options.label || options.url; this.label = options.label || options.url;
this.interval = options.interval || 10000; this.interval = options.interval || 10000;
this.indicator.iconClass(options.iconClass || 'icon-chain-links'); this.indicator.iconClass(options.iconClass || 'icon-chain-links');
}; };
URLIndicator.prototype.bindMethods = function () { URLIndicator.prototype.bindMethods = function () {
this.fetchUrl = this.fetchUrl.bind(this); this.fetchUrl = this.fetchUrl.bind(this);
this.handleSuccess = this.handleSuccess.bind(this); this.handleSuccess = this.handleSuccess.bind(this);
this.handleError = this.handleError.bind(this); this.handleError = this.handleError.bind(this);
this.setIndicatorToState = this.setIndicatorToState.bind(this); this.setIndicatorToState = this.setIndicatorToState.bind(this);
}; };
return URLIndicator;
});

View File

@ -19,8 +19,9 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./URLIndicator'], function URLIndicatorPlugin(URLIndicator) { import URLIndicator from './URLIndicator';
return function (opts) {
export default function URLIndicatorPlugin(opts) {
return function install(openmct) { return function install(openmct) {
const simpleIndicator = openmct.indicators.simpleIndicator(); const simpleIndicator = openmct.indicators.simpleIndicator();
const urlIndicator = new URLIndicator(opts, simpleIndicator); const urlIndicator = new URLIndicator(opts, simpleIndicator);
@ -29,5 +30,4 @@ define(['./URLIndicator'], function URLIndicatorPlugin(URLIndicator) {
return urlIndicator; return urlIndicator;
}; };
}; }
});

View File

@ -20,13 +20,11 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['utils/testing', './URLIndicator', './URLIndicatorPlugin', '../../MCT'], function ( import * as testingUtils from 'utils/testing';
testingUtils,
URLIndicator, import URLIndicatorPlugin from './URLIndicatorPlugin';
URLIndicatorPlugin,
MCT describe('The URLIndicator', function () {
) {
describe('The URLIndicator', function () {
let openmct; let openmct;
let indicatorElement; let indicatorElement;
let pluginOptions; let pluginOptions;
@ -133,5 +131,4 @@ define(['utils/testing', './URLIndicator', './URLIndicatorPlugin', '../../MCT'],
expect(indicatorElement.classList.contains('s-status-warning-hi')).toBe(true); expect(indicatorElement.classList.contains('s-status-warning-hi')).toBe(true);
}); });
}); });
});
}); });

View File

@ -20,15 +20,13 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* Constant values used by the Autoflow Tabular View. * Constant values used by the Autoflow Tabular View.
*/ */
return { export default {
ROW_HEIGHT: 16, ROW_HEIGHT: 16,
SLIDER_HEIGHT: 10, SLIDER_HEIGHT: 10,
INITIAL_COLUMN_WIDTH: 225, INITIAL_COLUMN_WIDTH: 225,
MAX_COLUMN_WIDTH: 525, MAX_COLUMN_WIDTH: 525,
COLUMN_WIDTH_STEP: 25 COLUMN_WIDTH_STEP: 25
}; };
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./AutoflowTabularRowController'], function (AutoflowTabularRowController) { import AutoflowTabularRowController from './AutoflowTabularRowController';
/**
/**
* Controller for an Autoflow Tabular View. Subscribes to telemetry * Controller for an Autoflow Tabular View. Subscribes to telemetry
* associated with children of the domain object and passes that * associated with children of the domain object and passes that
* information on to the view. * information on to the view.
@ -30,7 +31,7 @@ define(['./AutoflowTabularRowController'], function (AutoflowTabularRowControlle
* @param {*} data the view data * @param {*} data the view data
* @param openmct a reference to the openmct application * @param openmct a reference to the openmct application
*/ */
function AutoflowTabularController(domainObject, data, openmct) { export default function AutoflowTabularController(domainObject, data, openmct) {
this.composition = openmct.composition.get(domainObject); this.composition = openmct.composition.get(domainObject);
this.data = data; this.data = data;
this.openmct = openmct; this.openmct = openmct;
@ -40,22 +41,22 @@ define(['./AutoflowTabularRowController'], function (AutoflowTabularRowControlle
this.addRow = this.addRow.bind(this); this.addRow = this.addRow.bind(this);
this.removeRow = this.removeRow.bind(this); this.removeRow = this.removeRow.bind(this);
} }
/** /**
* Set the "Last Updated" value to be displayed. * Set the "Last Updated" value to be displayed.
* @param {String} value the value to display * @param {String} value the value to display
* @private * @private
*/ */
AutoflowTabularController.prototype.trackLastUpdated = function (value) { AutoflowTabularController.prototype.trackLastUpdated = function (value) {
this.data.updated = value; this.data.updated = value;
}; };
/** /**
* Respond to an `add` event from composition by adding a new row. * Respond to an `add` event from composition by adding a new row.
* @private * @private
*/ */
AutoflowTabularController.prototype.addRow = function (childObject) { AutoflowTabularController.prototype.addRow = function (childObject) {
const identifier = childObject.identifier; const identifier = childObject.identifier;
const id = [identifier.namespace, identifier.key].join(':'); const id = [identifier.namespace, identifier.key].join(':');
@ -74,14 +75,14 @@ define(['./AutoflowTabularRowController'], function (AutoflowTabularRowControlle
this.controllers[id].activate(); this.controllers[id].activate();
this.data.items.push(this.rows[id]); this.data.items.push(this.rows[id]);
} }
}; };
/** /**
* Respond to an `remove` event from composition by removing any * Respond to an `remove` event from composition by removing any
* related row. * related row.
* @private * @private
*/ */
AutoflowTabularController.prototype.removeRow = function (identifier) { AutoflowTabularController.prototype.removeRow = function (identifier) {
const id = [identifier.namespace, identifier.key].join(':'); const id = [identifier.namespace, identifier.key].join(':');
if (this.rows[id]) { if (this.rows[id]) {
@ -94,21 +95,21 @@ define(['./AutoflowTabularRowController'], function (AutoflowTabularRowControlle
delete this.controllers[id]; delete this.controllers[id];
delete this.rows[id]; delete this.rows[id];
} }
}; };
/** /**
* Activate this controller; begin listening for changes. * Activate this controller; begin listening for changes.
*/ */
AutoflowTabularController.prototype.activate = function () { AutoflowTabularController.prototype.activate = function () {
this.composition.on('add', this.addRow); this.composition.on('add', this.addRow);
this.composition.on('remove', this.removeRow); this.composition.on('remove', this.removeRow);
this.composition.load(); this.composition.load();
}; };
/** /**
* Destroy this controller; detach any associated resources. * Destroy this controller; detach any associated resources.
*/ */
AutoflowTabularController.prototype.destroy = function () { AutoflowTabularController.prototype.destroy = function () {
Object.keys(this.controllers).forEach( Object.keys(this.controllers).forEach(
function (id) { function (id) {
this.controllers[id].destroy(); this.controllers[id].destroy();
@ -117,7 +118,4 @@ define(['./AutoflowTabularRowController'], function (AutoflowTabularRowControlle
this.controllers = {}; this.controllers = {};
this.composition.off('add', this.addRow); this.composition.off('add', this.addRow);
this.composition.off('remove', this.removeRow); this.composition.off('remove', this.removeRow);
}; };
return AutoflowTabularController;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./AutoflowTabularView'], function (AutoflowTabularView) { import AutoflowTabularView from './AutoflowTabularView';
return function (options) {
export default function (options) {
return function (openmct) { return function (openmct) {
const views = openmct.mainViews || openmct.objectViews; const views = openmct.mainViews || openmct.objectViews;
@ -38,5 +39,4 @@ define(['./AutoflowTabularView'], function (AutoflowTabularView) {
} }
}); });
}; };
}; }
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* Controller for individual rows of an Autoflow Tabular View. * Controller for individual rows of an Autoflow Tabular View.
* Subscribes to telemetry and updates row data. * Subscribes to telemetry and updates row data.
* *
@ -30,7 +29,7 @@ define([], function () {
* @param openmct a reference to the openmct application * @param openmct a reference to the openmct application
* @param {Function} callback a callback to invoke with "last updated" timestamps * @param {Function} callback a callback to invoke with "last updated" timestamps
*/ */
function AutoflowTabularRowController(domainObject, data, openmct, callback) { export default function AutoflowTabularRowController(domainObject, data, openmct, callback) {
this.domainObject = domainObject; this.domainObject = domainObject;
this.data = data; this.data = data;
this.openmct = openmct; this.openmct = openmct;
@ -44,25 +43,25 @@ define([], function () {
this.evaluator = this.openmct.telemetry.limitEvaluator(this.domainObject); this.evaluator = this.openmct.telemetry.limitEvaluator(this.domainObject);
this.initialized = false; this.initialized = false;
} }
/** /**
* Update row to reflect incoming telemetry data. * Update row to reflect incoming telemetry data.
* @private * @private
*/ */
AutoflowTabularRowController.prototype.updateRowData = function (datum) { AutoflowTabularRowController.prototype.updateRowData = function (datum) {
const violations = this.evaluator.evaluate(datum, this.ranges[0]); const violations = this.evaluator.evaluate(datum, this.ranges[0]);
this.initialized = true; this.initialized = true;
this.data.classes = violations ? violations.cssClass : ''; this.data.classes = violations ? violations.cssClass : '';
this.data.value = this.rangeFormatter.format(datum); this.data.value = this.rangeFormatter.format(datum);
this.callback(this.domainFormatter.format(datum)); this.callback(this.domainFormatter.format(datum));
}; };
/** /**
* Activate this controller; begin listening for changes. * Activate this controller; begin listening for changes.
*/ */
AutoflowTabularRowController.prototype.activate = function () { AutoflowTabularRowController.prototype.activate = function () {
this.unsubscribe = this.openmct.telemetry.subscribe( this.unsubscribe = this.openmct.telemetry.subscribe(
this.domainObject, this.domainObject,
this.updateRowData.bind(this) this.updateRowData.bind(this)
@ -80,16 +79,13 @@ define([], function () {
} }
}.bind(this) }.bind(this)
); );
}; };
/** /**
* Destroy this controller; detach any associated resources. * Destroy this controller; detach any associated resources.
*/ */
AutoflowTabularRowController.prototype.destroy = function () { AutoflowTabularRowController.prototype.destroy = function () {
if (this.unsubscribe) { if (this.unsubscribe) {
this.unsubscribe(); this.unsubscribe();
} }
}; };
return AutoflowTabularRowController;
});

View File

@ -20,22 +20,21 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([ import autoflowTemplate from './autoflow-tabular.html';
'./AutoflowTabularController', import AutoflowTabularConstants from './AutoflowTabularConstants';
'./AutoflowTabularConstants', import AutoflowTabularController from './AutoflowTabularController';
'./VueView', import VueView from './VueView';
'./autoflow-tabular.html'
], function (AutoflowTabularController, AutoflowTabularConstants, VueView, autoflowTemplate) {
const ROW_HEIGHT = AutoflowTabularConstants.ROW_HEIGHT;
const SLIDER_HEIGHT = AutoflowTabularConstants.SLIDER_HEIGHT;
const INITIAL_COLUMN_WIDTH = AutoflowTabularConstants.INITIAL_COLUMN_WIDTH;
const MAX_COLUMN_WIDTH = AutoflowTabularConstants.MAX_COLUMN_WIDTH;
const COLUMN_WIDTH_STEP = AutoflowTabularConstants.COLUMN_WIDTH_STEP;
/** const ROW_HEIGHT = AutoflowTabularConstants.ROW_HEIGHT;
const SLIDER_HEIGHT = AutoflowTabularConstants.SLIDER_HEIGHT;
const INITIAL_COLUMN_WIDTH = AutoflowTabularConstants.INITIAL_COLUMN_WIDTH;
const MAX_COLUMN_WIDTH = AutoflowTabularConstants.MAX_COLUMN_WIDTH;
const COLUMN_WIDTH_STEP = AutoflowTabularConstants.COLUMN_WIDTH_STEP;
/**
* Implements the Autoflow Tabular view of a domain object. * Implements the Autoflow Tabular view of a domain object.
*/ */
function AutoflowTabularView(domainObject, openmct) { export default function AutoflowTabularView(domainObject, openmct) {
const data = { const data = {
items: [], items: [],
columns: [], columns: [],
@ -107,9 +106,6 @@ define([
this.$nextTick(updateRowHeight); this.$nextTick(updateRowHeight);
} }
}); });
} }
AutoflowTabularView.prototype = Object.create(VueView.default.prototype); AutoflowTabularView.prototype = Object.create(VueView.prototype);
return AutoflowTabularView;
});

View File

@ -22,13 +22,15 @@
import mount from 'utils/mount'; import mount from 'utils/mount';
export default function () { export default function () {
return function VueView(options) { class VueView {
constructor(options) {
const { vNode, destroy } = mount(options); const { vNode, destroy } = mount(options);
this.show = function (container) { this.show = function (container) {
container.appendChild(vNode.el); container.appendChild(vNode.el);
}; };
this.destroy = destroy; this.destroy = destroy;
}; }
}
return VueView;
} }

View File

@ -20,13 +20,12 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function DOMObserver(element) {
function DOMObserver(element) {
this.element = element; this.element = element;
this.observers = []; this.observers = [];
} }
DOMObserver.prototype.when = function (latchFunction) { DOMObserver.prototype.when = function (latchFunction) {
return new Promise( return new Promise(
function (resolve, reject) { function (resolve, reject) {
//Test latch function at least once //Test latch function at least once
@ -49,15 +48,12 @@ define([], function () {
} }
}.bind(this) }.bind(this)
); );
}; };
DOMObserver.prototype.destroy = function () { DOMObserver.prototype.destroy = function () {
this.observers.forEach( this.observers.forEach(
function (observer) { function (observer) {
observer.disconnect(); observer.disconnect();
}.bind(this) }.bind(this)
); );
}; };
return DOMObserver;
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(function () { export default function DisplayLayoutType() {
function DisplayLayoutType() {
return { return {
name: 'Display Layout', name: 'Display Layout',
creatable: true, creatable: true,
@ -66,7 +65,4 @@ define(function () {
} }
] ]
}; };
} }
return DisplayLayoutType;
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* Handles drag interactions on frames in layouts. This will * Handles drag interactions on frames in layouts. This will
* provides new positions/dimensions for frames based on * provides new positions/dimensions for frames based on
* relative pixel positions provided; these will take into account * relative pixel positions provided; these will take into account
@ -48,65 +47,62 @@ define([], function () {
* @constructor * @constructor
* @memberof platform/features/layout * @memberof platform/features/layout
*/ */
function LayoutDrag(rawPosition, posFactor, dimFactor, gridSize) { export default function LayoutDrag(rawPosition, posFactor, dimFactor, gridSize) {
this.rawPosition = rawPosition; this.rawPosition = rawPosition;
this.posFactor = posFactor; this.posFactor = posFactor;
this.dimFactor = dimFactor; this.dimFactor = dimFactor;
this.gridSize = gridSize; this.gridSize = gridSize;
} }
// Convert a delta from pixel coordinates to grid coordinates, // Convert a delta from pixel coordinates to grid coordinates,
// rounding to whole-number grid coordinates. // rounding to whole-number grid coordinates.
function toGridDelta(gridSize, pixelDelta) { function toGridDelta(gridSize, pixelDelta) {
return pixelDelta.map(function (v, i) { return pixelDelta.map(function (v, i) {
return Math.round(v / gridSize[i]); return Math.round(v / gridSize[i]);
}); });
} }
// Utility function to perform element-by-element multiplication // Utility function to perform element-by-element multiplication
function multiply(array, factors) { function multiply(array, factors) {
return array.map(function (v, i) { return array.map(function (v, i) {
return v * factors[i]; return v * factors[i];
}); });
} }
// Utility function to perform element-by-element addition // Utility function to perform element-by-element addition
function add(array, other) { function add(array, other) {
return array.map(function (v, i) { return array.map(function (v, i) {
return v + other[i]; return v + other[i];
}); });
} }
// Utility function to perform element-by-element max-choosing // Utility function to perform element-by-element max-choosing
function max(array, other) { function max(array, other) {
return array.map(function (v, i) { return array.map(function (v, i) {
return Math.max(v, other[i]); return Math.max(v, other[i]);
}); });
} }
/** /**
* Get a new position object in grid coordinates, with * Get a new position object in grid coordinates, with
* position and dimensions both offset appropriately * position and dimensions both offset appropriately
* according to the factors supplied in the constructor. * according to the factors supplied in the constructor.
* @param {number[]} pixelDelta the offset from the * @param {number[]} pixelDelta the offset from the
* original position, in pixels * original position, in pixels
*/ */
LayoutDrag.prototype.getAdjustedPositionAndDimensions = function (pixelDelta) { LayoutDrag.prototype.getAdjustedPositionAndDimensions = function (pixelDelta) {
const gridDelta = toGridDelta(this.gridSize, pixelDelta); const gridDelta = toGridDelta(this.gridSize, pixelDelta);
return { return {
position: max(add(this.rawPosition.position, multiply(gridDelta, this.posFactor)), [0, 0]), position: max(add(this.rawPosition.position, multiply(gridDelta, this.posFactor)), [0, 0]),
dimensions: max(add(this.rawPosition.dimensions, multiply(gridDelta, this.dimFactor)), [1, 1]) dimensions: max(add(this.rawPosition.dimensions, multiply(gridDelta, this.dimFactor)), [1, 1])
}; };
}; };
LayoutDrag.prototype.getAdjustedPosition = function (pixelDelta) { LayoutDrag.prototype.getAdjustedPosition = function (pixelDelta) {
const gridDelta = toGridDelta(this.gridSize, pixelDelta); const gridDelta = toGridDelta(this.gridSize, pixelDelta);
return { return {
position: max(add(this.rawPosition.position, multiply(gridDelta, this.posFactor)), [0, 0]) position: max(add(this.rawPosition.position, multiply(gridDelta, this.posFactor)), [0, 0])
}; };
}; };
return LayoutDrag;
});

View File

@ -20,12 +20,12 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./FiltersInspectorViewProvider'], function (FiltersInspectorViewProvider) { import FiltersInspectorViewProvider from './FiltersInspectorViewProvider';
return function plugin(supportedObjectTypesArray) {
export default function plugin(supportedObjectTypesArray) {
return function install(openmct) { return function install(openmct) {
openmct.inspectorViews.addProvider( openmct.inspectorViews.addProvider(
new FiltersInspectorViewProvider.default(openmct, supportedObjectTypesArray) new FiltersInspectorViewProvider(openmct, supportedObjectTypesArray)
); );
}; };
}; }
});

View File

@ -20,14 +20,13 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./flexibleLayoutViewProvider', './utils/container', './toolbarProvider'], function ( import FlexibleLayoutViewProvider from './flexibleLayoutViewProvider';
FlexibleLayoutViewProvider, import ToolBarProvider from './toolbarProvider';
Container, import Container from './utils/container';
ToolBarProvider
) { export default function plugin() {
return function plugin() {
return function install(openmct) { return function install(openmct) {
openmct.objectViews.addProvider(new FlexibleLayoutViewProvider.default(openmct)); openmct.objectViews.addProvider(new FlexibleLayoutViewProvider(openmct));
openmct.types.addType('flexible-layout', { openmct.types.addType('flexible-layout', {
name: 'Flexible Layout', name: 'Flexible Layout',
@ -37,16 +36,15 @@ define(['./flexibleLayoutViewProvider', './utils/container', './toolbarProvider'
cssClass: 'icon-flexible-layout', cssClass: 'icon-flexible-layout',
initialize: function (domainObject) { initialize: function (domainObject) {
domainObject.configuration = { domainObject.configuration = {
containers: [new Container.default(50), new Container.default(50)], containers: [new Container(50), new Container(50)],
rowsLayout: false rowsLayout: false
}; };
domainObject.composition = []; domainObject.composition = [];
} }
}); });
let toolbar = ToolBarProvider.default(openmct); let toolbar = ToolBarProvider(openmct);
openmct.toolbars.addProvider(toolbar); openmct.toolbars.addProvider(toolbar);
}; };
}; }
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { const helperFunctions = {
const helperFunctions = {
listenTo: function (object, event, callback, context) { listenTo: function (object, event, callback, context) {
if (!this._listeningTo) { if (!this._listeningTo) {
this._listeningTo = []; this._listeningTo = [];
@ -93,7 +92,6 @@ define([], function () {
object.listenTo = helperFunctions.listenTo; object.listenTo = helperFunctions.listenTo;
object.stopListening = helperFunctions.stopListening; object.stopListening = helperFunctions.stopListening;
} }
}; };
return helperFunctions; export default helperFunctions;
});

View File

@ -20,24 +20,24 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['../../../src/plugins/utcTimeSystem/LocalClock'], function (LocalClock) { import LocalClock from '../../../src/plugins/utcTimeSystem/LocalClock';
class LADClock extends LocalClock {
/** /**
* A {@link Clock} that mocks a "latest available data" type tick source. * A {@link Clock} that mocks a "latest available data" type tick source.
* This is for testing purposes only, and behaves identically to a local clock. * This is for testing purposes only, and behaves identically to a local clock.
* It DOES NOT tick on receipt of data. * It DOES NOT tick on receipt of data.
* @constructor * @constructor
*/ */
function LADClock(period) { constructor(period) {
LocalClock.call(this, period); super(period);
this.key = 'test-lad'; this.key = 'test-lad';
this.mode = 'lad'; this.mode = 'lad';
this.cssClass = 'icon-suitcase'; this.cssClass = 'icon-suitcase';
this.name = 'Latest available data'; this.name = 'Latest available data';
this.description = 'Updates when when new data is available'; this.description = 'Updates when new data is available';
} }
}
LADClock.prototype = Object.create(LocalClock.prototype); export default LADClock;
return LADClock;
});

View File

@ -20,10 +20,10 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./LADClock'], function (LADClock) { import LADClock from './LADClock';
return function () {
export default function () {
return function (openmct) { return function (openmct) {
openmct.time.addClock(new LADClock()); openmct.time.addClock(new LADClock());
}; };
}; }
});

View File

@ -20,18 +20,19 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['moment'], function (moment) { import moment from 'moment';
const DATE_FORMAT = 'YYYY-MM-DD h:mm:ss.SSS a';
const DATE_FORMATS = [DATE_FORMAT, 'YYYY-MM-DD h:mm:ss a', 'YYYY-MM-DD h:mm a', 'YYYY-MM-DD']; const DATE_FORMAT = 'YYYY-MM-DD h:mm:ss.SSS a';
/** const DATE_FORMATS = [DATE_FORMAT, 'YYYY-MM-DD h:mm:ss a', 'YYYY-MM-DD h:mm a', 'YYYY-MM-DD'];
/**
* @typedef Scale * @typedef Scale
* @property {number} min the minimum scale value, in ms * @property {number} min the minimum scale value, in ms
* @property {number} max the maximum scale value, in ms * @property {number} max the maximum scale value, in ms
*/ */
/** /**
* Formatter for UTC timestamps. Interprets numeric values as * Formatter for UTC timestamps. Interprets numeric values as
* milliseconds since the start of 1970. * milliseconds since the start of 1970.
* *
@ -39,30 +40,27 @@ define(['moment'], function (moment) {
* @constructor * @constructor
* @memberof platform/commonUI/formats * @memberof platform/commonUI/formats
*/ */
function LocalTimeFormat() { export default function LocalTimeFormat() {
this.key = 'local-format'; this.key = 'local-format';
} }
/** /**
* *
* @param value * @param value
* @returns {string} the formatted date * @returns {string} the formatted date
*/ */
LocalTimeFormat.prototype.format = function (value, scale) { LocalTimeFormat.prototype.format = function (value, scale) {
return moment(value).format(DATE_FORMAT); return moment(value).format(DATE_FORMAT);
}; };
LocalTimeFormat.prototype.parse = function (text) { LocalTimeFormat.prototype.parse = function (text) {
if (typeof text === 'number') { if (typeof text === 'number') {
return text; return text;
} }
return moment(text, DATE_FORMATS).valueOf(); return moment(text, DATE_FORMATS).valueOf();
}; };
LocalTimeFormat.prototype.validate = function (text) { LocalTimeFormat.prototype.validate = function (text) {
return moment(text, DATE_FORMATS).isValid(); return moment(text, DATE_FORMATS).isValid();
}; };
return LocalTimeFormat;
});

View File

@ -20,13 +20,13 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* This time system supports UTC dates and provides a ticking clock source. * This time system supports UTC dates and provides a ticking clock source.
* @implements TimeSystem * @implements TimeSystem
* @constructor * @constructor
*/ */
function LocalTimeSystem() { export default class LocalTimeSystem {
constructor() {
/** /**
* Some metadata, which will be used to identify the time system in * Some metadata, which will be used to identify the time system in
* the UI * the UI
@ -41,6 +41,4 @@ define([], function () {
this.isUTCBased = true; this.isUTCBased = true;
} }
}
return LocalTimeSystem;
});

View File

@ -20,11 +20,12 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./LocalTimeSystem', './LocalTimeFormat'], function (LocalTimeSystem, LocalTimeFormat) { import LocalTimeFormat from './LocalTimeFormat';
return function () { import LocalTimeSystem from './LocalTimeSystem';
export default function () {
return function (openmct) { return function (openmct) {
openmct.time.addTimeSystem(new LocalTimeSystem()); openmct.time.addTimeSystem(new LocalTimeSystem());
openmct.telemetry.addFormat(new LocalTimeFormat()); openmct.telemetry.addFormat(new LocalTimeFormat());
}; };
}; }
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['uuid'], function ({ v4: uuid }) { import { v4 as uuid } from 'uuid';
return function Migrations(openmct) {
export default function Migrations(openmct) {
function getColumnNameKeyMap(domainObject) { function getColumnNameKeyMap(domainObject) {
let composition = openmct.composition.get(domainObject); let composition = openmct.composition.get(domainObject);
if (composition) { if (composition) {
@ -275,5 +276,4 @@ define(['uuid'], function ({ v4: uuid }) {
} }
} }
]; ];
}; }
});

View File

@ -20,160 +20,91 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([ import ExampleDataVisualizationSourcePlugin from '../../example/dataVisualization/plugin';
'lodash', import EventGeneratorPlugin from '../../example/eventGenerator/plugin';
'./utcTimeSystem/plugin', import ExampleTags from '../../example/exampleTags/plugin';
'./remoteClock/plugin', import ExampleUser from '../../example/exampleUser/plugin';
'./localTimeSystem/plugin', import ExampleFaultSource from '../../example/faultManagement/exampleFaultSource';
'./ISOTimeFormat/plugin', import GeneratorPlugin from '../../example/generator/plugin';
'./myItems/plugin', import ExampleImagery from '../../example/imagery/plugin';
'../../example/generator/plugin', import AutoflowPlugin from './autoflow/AutoflowTabularPlugin';
'../../example/eventGenerator/plugin', import BarChartPlugin from './charts/bar/plugin';
'../../example/dataVisualization/plugin', import ScatterPlotPlugin from './charts/scatter/plugin';
'./autoflow/AutoflowTabularPlugin', import ClearData from './clearData/plugin';
'./timeConductor/plugin', import Clock from './clock/plugin';
'../../example/imagery/plugin', import ConditionPlugin from './condition/plugin';
'../../example/faultManagement/exampleFaultSource', import ConditionWidgetPlugin from './conditionWidget/plugin';
'./imagery/plugin', import CouchDBSearchFolder from './CouchDBSearchFolder/plugin';
'./summaryWidget/plugin', import DefaultRootName from './defaultRootName/plugin';
'./URLIndicatorPlugin/URLIndicatorPlugin', import DeviceClassifier from './DeviceClassifier/plugin';
'./telemetryMean/plugin', import DisplayLayoutPlugin from './displayLayout/plugin';
'./plot/plugin', import FaultManagementPlugin from './faultManagement/FaultManagementPlugin';
'./charts/bar/plugin', import Filters from './filters/plugin';
'./charts/scatter/plugin', import FlexibleLayout from './flexibleLayout/plugin';
'./telemetryTable/plugin', import FolderView from './folderView/plugin';
'./staticRootPlugin/plugin', import FormActions from './formActions/plugin';
'./notebook/plugin', import GaugePlugin from './gauge/GaugePlugin';
'./displayLayout/plugin', import GoToOriginalAction from './goToOriginalAction/plugin';
'./formActions/plugin', import Hyperlink from './hyperlink/plugin';
'./folderView/plugin', import ImageryPlugin from './imagery/plugin';
'./flexibleLayout/plugin', import InspectorDataVisualization from './inspectorDataVisualization/plugin';
'./tabs/plugin', import InspectorViews from './inspectorViews/plugin';
'./LADTable/plugin', import ObjectInterceptors from './interceptors/plugin';
'./filters/plugin', import ISOTimeFormat from './ISOTimeFormat/plugin';
'./objectMigration/plugin', import LADTable from './LADTable/plugin';
'./goToOriginalAction/plugin', import LocalStorage from './localStorage/plugin';
'./openInNewTabAction/plugin', import LocalTimeSystem from './localTimeSystem/plugin';
'./clearData/plugin', import MyItems from './myItems/plugin';
'./webPage/plugin', import NewFolderAction from './newFolderAction/plugin';
'./condition/plugin', import { NotebookPlugin, RestrictedNotebookPlugin } from './notebook/plugin';
'./conditionWidget/plugin', import NotificationIndicator from './notificationIndicator/plugin';
'./themes/espresso', import ObjectMigration from './objectMigration/plugin';
'./themes/snow', import OpenInNewTabAction from './openInNewTabAction/plugin';
'./URLTimeSettingsSynchronizer/plugin', import OperatorStatus from './operatorStatus/plugin';
'./notificationIndicator/plugin', import PerformanceIndicator from './performanceIndicator/plugin';
'./newFolderAction/plugin', import CouchDBPlugin from './persistence/couch/plugin';
'./persistence/couch/plugin', import PlanLayout from './plan/plugin';
'./defaultRootName/plugin', import PlotPlugin from './plot/plugin';
'./plan/plugin', import RemoteClock from './remoteClock/plugin';
'./viewDatumAction/plugin', import StaticRootPlugin from './staticRootPlugin/plugin';
'./viewLargeAction/plugin', import SummaryWidget from './summaryWidget/plugin';
'./interceptors/plugin', import Tabs from './tabs/plugin';
'./performanceIndicator/plugin', import TelemetryMean from './telemetryMean/plugin';
'./CouchDBSearchFolder/plugin', import TelemetryTablePlugin from './telemetryTable/plugin';
'./timeline/plugin', import Espresso from './themes/espresso';
'./hyperlink/plugin', import Snow from './themes/snow';
'./clock/plugin', import TimeConductorPlugin from './timeConductor/plugin';
'./DeviceClassifier/plugin', import Timeline from './timeline/plugin';
'./timer/plugin', import TimeList from './timelist/plugin';
'./userIndicator/plugin', import Timer from './timer/plugin';
'../../example/exampleUser/plugin', import URLIndicatorPlugin from './URLIndicatorPlugin/URLIndicatorPlugin';
'./localStorage/plugin', import URLTimeSettingsSynchronizer from './URLTimeSettingsSynchronizer/plugin';
'./operatorStatus/plugin', import UserIndicator from './userIndicator/plugin';
'./gauge/GaugePlugin', import UTCTimeSystem from './utcTimeSystem/plugin';
'./timelist/plugin', import ViewDatumAction from './viewDatumAction/plugin';
'./faultManagement/FaultManagementPlugin', import ViewLargeAction from './viewLargeAction/plugin';
'../../example/exampleTags/plugin', import WebPagePlugin from './webPage/plugin';
'./inspectorViews/plugin',
'./inspectorDataVisualization/plugin'
], function (
_,
UTCTimeSystem,
RemoteClock,
LocalTimeSystem,
ISOTimeFormat,
MyItems,
GeneratorPlugin,
EventGeneratorPlugin,
ExampleDataVisualizationSourcePlugin,
AutoflowPlugin,
TimeConductorPlugin,
ExampleImagery,
ExampleFaultSource,
ImageryPlugin,
SummaryWidget,
URLIndicatorPlugin,
TelemetryMean,
PlotPlugin,
BarChartPlugin,
ScatterPlotPlugin,
TelemetryTablePlugin,
StaticRootPlugin,
Notebook,
DisplayLayoutPlugin,
FormActions,
FolderView,
FlexibleLayout,
Tabs,
LADTable,
Filters,
ObjectMigration,
GoToOriginalAction,
OpenInNewTabAction,
ClearData,
WebPagePlugin,
ConditionPlugin,
ConditionWidgetPlugin,
Espresso,
Snow,
URLTimeSettingsSynchronizer,
NotificationIndicator,
NewFolderAction,
CouchDBPlugin,
DefaultRootName,
PlanLayout,
ViewDatumAction,
ViewLargeAction,
ObjectInterceptors,
PerformanceIndicator,
CouchDBSearchFolder,
Timeline,
Hyperlink,
Clock,
DeviceClassifier,
Timer,
UserIndicator,
ExampleUser,
LocalStorage,
OperatorStatus,
GaugePlugin,
TimeList,
FaultManagementPlugin,
ExampleTags,
InspectorViews,
InspectorDataVisualization
) {
const plugins = {};
plugins.example = {}; const plugins = {};
plugins.example.ExampleUser = ExampleUser.default;
plugins.example.ExampleImagery = ExampleImagery.default;
plugins.example.ExampleFaultSource = ExampleFaultSource.default;
plugins.example.EventGeneratorPlugin = EventGeneratorPlugin.default;
plugins.example.ExampleDataVisualizationSourcePlugin =
ExampleDataVisualizationSourcePlugin.default;
plugins.example.ExampleTags = ExampleTags.default;
plugins.example.Generator = () => GeneratorPlugin.default;
plugins.UTCTimeSystem = UTCTimeSystem.default; plugins.example = {};
plugins.LocalTimeSystem = LocalTimeSystem; plugins.example.ExampleUser = ExampleUser;
plugins.RemoteClock = RemoteClock.default; plugins.example.ExampleImagery = ExampleImagery;
plugins.example.ExampleFaultSource = ExampleFaultSource;
plugins.example.EventGeneratorPlugin = EventGeneratorPlugin;
plugins.example.ExampleDataVisualizationSourcePlugin = ExampleDataVisualizationSourcePlugin;
plugins.example.ExampleTags = ExampleTags;
plugins.example.Generator = () => GeneratorPlugin;
plugins.MyItems = MyItems.default; plugins.UTCTimeSystem = UTCTimeSystem;
plugins.LocalTimeSystem = LocalTimeSystem;
plugins.RemoteClock = RemoteClock;
plugins.StaticRootPlugin = StaticRootPlugin.default; plugins.MyItems = MyItems;
/** plugins.StaticRootPlugin = StaticRootPlugin;
/**
* A tabular view showing the latest values of multiple telemetry points at * A tabular view showing the latest values of multiple telemetry points at
* once. Formatted so that labels and values are aligned. * once. Formatted so that labels and values are aligned.
* *
@ -182,63 +113,62 @@ define([
* @param {string} [options.type] The key of an object type to apply this view * @param {string} [options.type] The key of an object type to apply this view
* to exclusively. * to exclusively.
*/ */
plugins.AutoflowView = AutoflowPlugin; plugins.AutoflowView = AutoflowPlugin;
plugins.Conductor = TimeConductorPlugin.default; plugins.Conductor = TimeConductorPlugin;
plugins.CouchDB = CouchDBPlugin.default; plugins.CouchDB = CouchDBPlugin;
plugins.ImageryPlugin = ImageryPlugin; plugins.ImageryPlugin = ImageryPlugin;
plugins.Plot = PlotPlugin.default; plugins.Plot = PlotPlugin;
plugins.BarChart = BarChartPlugin.default; plugins.BarChart = BarChartPlugin;
plugins.ScatterPlot = ScatterPlotPlugin.default; plugins.ScatterPlot = ScatterPlotPlugin;
plugins.TelemetryTable = TelemetryTablePlugin; plugins.TelemetryTable = TelemetryTablePlugin;
plugins.SummaryWidget = SummaryWidget; plugins.SummaryWidget = SummaryWidget;
plugins.TelemetryMean = TelemetryMean; plugins.TelemetryMean = TelemetryMean;
plugins.URLIndicator = URLIndicatorPlugin; plugins.URLIndicator = URLIndicatorPlugin;
plugins.Notebook = Notebook.NotebookPlugin; plugins.Notebook = NotebookPlugin;
plugins.RestrictedNotebook = Notebook.RestrictedNotebookPlugin; plugins.RestrictedNotebook = RestrictedNotebookPlugin;
plugins.DisplayLayout = DisplayLayoutPlugin.default; plugins.DisplayLayout = DisplayLayoutPlugin;
plugins.FaultManagement = FaultManagementPlugin.default; plugins.FaultManagement = FaultManagementPlugin;
plugins.FormActions = FormActions; plugins.FormActions = FormActions;
plugins.FolderView = FolderView.default; plugins.FolderView = FolderView;
plugins.Tabs = Tabs; plugins.Tabs = Tabs;
plugins.FlexibleLayout = FlexibleLayout; plugins.FlexibleLayout = FlexibleLayout;
plugins.LADTable = LADTable.default; plugins.LADTable = LADTable;
plugins.Filters = Filters; plugins.Filters = Filters;
plugins.ObjectMigration = ObjectMigration.default; plugins.ObjectMigration = ObjectMigration;
plugins.GoToOriginalAction = GoToOriginalAction.default; plugins.GoToOriginalAction = GoToOriginalAction;
plugins.OpenInNewTabAction = OpenInNewTabAction.default; plugins.OpenInNewTabAction = OpenInNewTabAction;
plugins.ClearData = ClearData.default; plugins.ClearData = ClearData;
plugins.WebPage = WebPagePlugin.default; plugins.WebPage = WebPagePlugin;
plugins.Espresso = Espresso.default; plugins.Espresso = Espresso;
plugins.Snow = Snow.default; plugins.Snow = Snow;
plugins.Condition = ConditionPlugin.default; plugins.Condition = ConditionPlugin;
plugins.ConditionWidget = ConditionWidgetPlugin.default; plugins.ConditionWidget = ConditionWidgetPlugin;
plugins.URLTimeSettingsSynchronizer = URLTimeSettingsSynchronizer.default; plugins.URLTimeSettingsSynchronizer = URLTimeSettingsSynchronizer;
plugins.NotificationIndicator = NotificationIndicator.default; plugins.NotificationIndicator = NotificationIndicator;
plugins.NewFolderAction = NewFolderAction.default; plugins.NewFolderAction = NewFolderAction;
plugins.ISOTimeFormat = ISOTimeFormat.default; plugins.ISOTimeFormat = ISOTimeFormat;
plugins.DefaultRootName = DefaultRootName.default; plugins.DefaultRootName = DefaultRootName;
plugins.PlanLayout = PlanLayout.default; plugins.PlanLayout = PlanLayout;
plugins.ViewDatumAction = ViewDatumAction.default; plugins.ViewDatumAction = ViewDatumAction;
plugins.ViewLargeAction = ViewLargeAction.default; plugins.ViewLargeAction = ViewLargeAction;
plugins.ObjectInterceptors = ObjectInterceptors.default; plugins.ObjectInterceptors = ObjectInterceptors;
plugins.PerformanceIndicator = PerformanceIndicator.default; plugins.PerformanceIndicator = PerformanceIndicator;
plugins.CouchDBSearchFolder = CouchDBSearchFolder.default; plugins.CouchDBSearchFolder = CouchDBSearchFolder;
plugins.Timeline = Timeline.default; plugins.Timeline = Timeline;
plugins.Hyperlink = Hyperlink.default; plugins.Hyperlink = Hyperlink;
plugins.Clock = Clock.default; plugins.Clock = Clock;
plugins.Timer = Timer.default; plugins.Timer = Timer;
plugins.DeviceClassifier = DeviceClassifier.default; plugins.DeviceClassifier = DeviceClassifier;
plugins.UserIndicator = UserIndicator.default; plugins.UserIndicator = UserIndicator;
plugins.LocalStorage = LocalStorage.default; plugins.LocalStorage = LocalStorage;
plugins.OperatorStatus = OperatorStatus.default; plugins.OperatorStatus = OperatorStatus;
plugins.Gauge = GaugePlugin.default; plugins.Gauge = GaugePlugin;
plugins.Timelist = TimeList.default; plugins.Timelist = TimeList;
plugins.InspectorViews = InspectorViews.default; plugins.InspectorViews = InspectorViews;
plugins.InspectorDataVisualization = InspectorDataVisualization.default; plugins.InspectorDataVisualization = InspectorDataVisualization;
return plugins; export default plugins;
});

View File

@ -20,20 +20,16 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* Policy determining which views can apply to summary widget. Disables * Policy determining which views can apply to summary widget. Disables
* any view other than normal summary widget view. * any view other than normal summary widget view.
*/ */
function SummaryWidgetViewPolicy() {} export default function SummaryWidgetViewPolicy() {}
SummaryWidgetViewPolicy.prototype.allow = function (view, domainObject) { SummaryWidgetViewPolicy.prototype.allow = function (view, domainObject) {
if (domainObject.getModel().type === 'summary-widget') { if (domainObject.getModel().type === 'summary-widget') {
return view.key === 'summary-widget-viewer'; return view.key === 'summary-widget-viewer';
} }
return true; return true;
}; };
return SummaryWidgetViewPolicy;
});

View File

@ -20,12 +20,11 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function SummaryWidgetsCompositionPolicy(openmct) {
function SummaryWidgetsCompositionPolicy(openmct) {
this.openmct = openmct; this.openmct = openmct;
} }
SummaryWidgetsCompositionPolicy.prototype.allow = function (parent, child) { SummaryWidgetsCompositionPolicy.prototype.allow = function (parent, child) {
const parentType = parent.type; const parentType = parent.type;
if (parentType === 'summary-widget' && !this.openmct.telemetry.isTelemetryObject(child)) { if (parentType === 'summary-widget' && !this.openmct.telemetry.isTelemetryObject(child)) {
@ -33,7 +32,4 @@ define([], function () {
} }
return true; return true;
}; };
return SummaryWidgetsCompositionPolicy;
});

View File

@ -1,17 +1,9 @@
define([ import SummaryWidgetMetadataProvider from './src/telemetry/SummaryWidgetMetadataProvider';
'./SummaryWidgetsCompositionPolicy', import SummaryWidgetTelemetryProvider from './src/telemetry/SummaryWidgetTelemetryProvider';
'./src/telemetry/SummaryWidgetMetadataProvider', import SummaryWidgetViewProvider from './src/views/SummaryWidgetViewProvider';
'./src/telemetry/SummaryWidgetTelemetryProvider', import SummaryWidgetsCompositionPolicy from './SummaryWidgetsCompositionPolicy';
'./src/views/SummaryWidgetViewProvider',
'./SummaryWidgetViewPolicy' export default function plugin() {
], function (
SummaryWidgetsCompositionPolicy,
SummaryWidgetMetadataProvider,
SummaryWidgetTelemetryProvider,
SummaryWidgetViewProvider,
SummaryWidgetViewPolicy
) {
function plugin() {
const widgetType = { const widgetType = {
name: 'Summary Widget', name: 'Summary Widget',
description: 'A compact status update for collections of telemetry-producing items', description: 'A compact status update for collections of telemetry-producing items',
@ -92,7 +84,4 @@ define([
openmct.telemetry.addProvider(new SummaryWidgetTelemetryProvider(openmct)); openmct.telemetry.addProvider(new SummaryWidgetTelemetryProvider(openmct));
openmct.objectViews.addProvider(new SummaryWidgetViewProvider(openmct)); openmct.objectViews.addProvider(new SummaryWidgetViewProvider(openmct));
}; };
} }
return plugin;
});

View File

@ -19,24 +19,17 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([
'../res/conditionTemplate.html', import EventEmitter from 'EventEmitter';
'./input/ObjectSelect',
'./input/KeySelect', import * as templateHelpers from '../../../utils/template/templateHelpers';
'./input/OperationSelect', import conditionTemplate from '../res/conditionTemplate.html';
'./eventHelpers', import eventHelpers from './eventHelpers';
'../../../utils/template/templateHelpers', import KeySelect from './input/KeySelect';
'EventEmitter' import ObjectSelect from './input/ObjectSelect';
], function ( import OperationSelect from './input/OperationSelect';
conditionTemplate,
ObjectSelect, /**
KeySelect,
OperationSelect,
eventHelpers,
templateHelpers,
EventEmitter
) {
/**
* Represents an individual condition for a summary widget rule. Manages the * Represents an individual condition for a summary widget rule. Manages the
* associated inputs and view. * associated inputs and view.
* @param {Object} conditionConfig The configuration for this condition, consisting * @param {Object} conditionConfig The configuration for this condition, consisting
@ -46,7 +39,7 @@ define([
* @param {ConditionManager} conditionManager A ConditionManager instance for populating * @param {ConditionManager} conditionManager A ConditionManager instance for populating
* selects with configuration data * selects with configuration data
*/ */
function Condition(conditionConfig, index, conditionManager) { export default function Condition(conditionConfig, index, conditionManager) {
eventHelpers.extend(this); eventHelpers.extend(this);
this.config = conditionConfig; this.config = conditionConfig;
this.index = index; this.index = index;
@ -128,13 +121,13 @@ define([
}); });
this.listenTo(this.domElement.querySelector('.t-value-inputs'), 'input', onValueInput); this.listenTo(this.domElement.querySelector('.t-value-inputs'), 'input', onValueInput);
} }
Condition.prototype.getDOM = function (container) { Condition.prototype.getDOM = function (container) {
return this.domElement; return this.domElement;
}; };
/** /**
* Register a callback with this condition: supported callbacks are remove, change, * Register a callback with this condition: supported callbacks are remove, change,
* duplicate * duplicate
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
@ -142,57 +135,57 @@ define([
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
Condition.prototype.on = function (event, callback, context) { Condition.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} }
}; };
/** /**
* Hide the appropriate inputs when this is the only condition * Hide the appropriate inputs when this is the only condition
*/ */
Condition.prototype.hideButtons = function () { Condition.prototype.hideButtons = function () {
this.deleteButton.style.display = 'none'; this.deleteButton.style.display = 'none';
}; };
/** /**
* Remove this condition from the configuration. Invokes any registered * Remove this condition from the configuration. Invokes any registered
* remove callbacks * remove callbacks
*/ */
Condition.prototype.remove = function () { Condition.prototype.remove = function () {
this.selects.object.off('change', this.handleObjectChange); this.selects.object.off('change', this.handleObjectChange);
this.selects.key.off('change', this.handleKeyChange); this.selects.key.off('change', this.handleKeyChange);
this.eventEmitter.emit('remove', this.index); this.eventEmitter.emit('remove', this.index);
this.destroy(); this.destroy();
}; };
Condition.prototype.destroy = function () { Condition.prototype.destroy = function () {
this.stopListening(); this.stopListening();
Object.values(this.selects).forEach(function (select) { Object.values(this.selects).forEach(function (select) {
select.destroy(); select.destroy();
}); });
}; };
/** /**
* Make a deep clone of this condition's configuration and invoke any duplicate * Make a deep clone of this condition's configuration and invoke any duplicate
* callbacks with the cloned configuration and this rule's index * callbacks with the cloned configuration and this rule's index
*/ */
Condition.prototype.duplicate = function () { Condition.prototype.duplicate = function () {
const sourceCondition = JSON.parse(JSON.stringify(this.config)); const sourceCondition = JSON.parse(JSON.stringify(this.config));
this.eventEmitter.emit('duplicate', { this.eventEmitter.emit('duplicate', {
sourceCondition: sourceCondition, sourceCondition: sourceCondition,
index: this.index index: this.index
}); });
}; };
/** /**
* When an operation is selected, create the appropriate value inputs * When an operation is selected, create the appropriate value inputs
* and add them to the view. If an operation is of type enum, create * and add them to the view. If an operation is of type enum, create
* a drop-down menu instead. * a drop-down menu instead.
* *
* @param {string} operation The key of currently selected operation * @param {string} operation The key of currently selected operation
*/ */
Condition.prototype.generateValueInputs = function (operation) { Condition.prototype.generateValueInputs = function (operation) {
const evaluator = this.conditionManager.getEvaluator(); const evaluator = this.conditionManager.getEvaluator();
const inputArea = this.domElement.querySelector('.t-value-inputs'); const inputArea = this.domElement.querySelector('.t-value-inputs');
let inputCount; let inputCount;
@ -240,9 +233,9 @@ define([
}); });
} }
} }
}; };
Condition.prototype.generateSelectOptions = function () { Condition.prototype.generateSelectOptions = function () {
let telemetryMetadata = this.conditionManager.getTelemetryMetadata(this.config.object); let telemetryMetadata = this.conditionManager.getTelemetryMetadata(this.config.object);
let fragment = document.createDocumentFragment(); let fragment = document.createDocumentFragment();
@ -254,7 +247,4 @@ define([
}); });
return fragment; return fragment;
}; };
return Condition;
});

View File

@ -1,5 +1,4 @@
define([], function () { /**
/**
* Responsible for maintaining the possible operations for conditions * Responsible for maintaining the possible operations for conditions
* in this widget, and evaluating the boolean value of conditions passed as * in this widget, and evaluating the boolean value of conditions passed as
* input. * input.
@ -10,7 +9,7 @@ define([], function () {
* @param {Object} compositionObjs The current set of composition objects to * @param {Object} compositionObjs The current set of composition objects to
* evaluate for 'any' and 'all' conditions * evaluate for 'any' and 'all' conditions
*/ */
function ConditionEvaluator(subscriptionCache, compositionObjs) { export default function ConditionEvaluator(subscriptionCache, compositionObjs) {
this.subscriptionCache = subscriptionCache; this.subscriptionCache = subscriptionCache;
this.compositionObjs = compositionObjs; this.compositionObjs = compositionObjs;
@ -242,9 +241,9 @@ define([], function () {
} }
} }
}; };
} }
/** /**
* Evaluate the conditions passed in as an argument, and return the boolean * Evaluate the conditions passed in as an argument, and return the boolean
* value of these conditions. Available evaluation modes are 'any', which will * value of these conditions. Available evaluation modes are 'any', which will
* return true if any of the conditions evaluates to true (i.e. logical OR); 'all', * return true if any of the conditions evaluates to true (i.e. logical OR); 'all',
@ -256,7 +255,7 @@ define([], function () {
* @param {string} mode The key of the mode to use when evaluating the conditions. * @param {string} mode The key of the mode to use when evaluating the conditions.
* @return {boolean} The boolean value of the conditions * @return {boolean} The boolean value of the conditions
*/ */
ConditionEvaluator.prototype.execute = function (conditions, mode) { ConditionEvaluator.prototype.execute = function (conditions, mode) {
let active = false; let active = false;
let conditionValue; let conditionValue;
let conditionDefined = false; let conditionDefined = false;
@ -320,9 +319,9 @@ define([], function () {
} }
return active; return active;
}; };
/** /**
* Execute a condition defined as an object. * Execute a condition defined as an object.
* @param {string} object The identifier of the telemetry object to retrieve data from * @param {string} object The identifier of the telemetry object to retrieve data from
* @param {string} key The property of the telemetry object * @param {string} key The property of the telemetry object
@ -330,7 +329,7 @@ define([], function () {
* @param {string} values An array of comparison values to invoke the operation with * @param {string} values An array of comparison values to invoke the operation with
* @return {boolean} The value of this condition * @return {boolean} The value of this condition
*/ */
ConditionEvaluator.prototype.executeCondition = function (object, key, operation, values) { ConditionEvaluator.prototype.executeCondition = function (object, key, operation, values) {
const cache = this.useTestCache ? this.testCache : this.subscriptionCache; const cache = this.useTestCache ? this.testCache : this.subscriptionCache;
let telemetryValue; let telemetryValue;
let op; let op;
@ -355,95 +354,95 @@ define([], function () {
} else { } else {
throw new Error('Malformed condition'); throw new Error('Malformed condition');
} }
}; };
/** /**
* A function that returns true only if each value in its input argument is * A function that returns true only if each value in its input argument is
* of a numerical type * of a numerical type
* @param {[]} input An array of values * @param {[]} input An array of values
* @returns {boolean} * @returns {boolean}
*/ */
ConditionEvaluator.prototype.validateNumberInput = function (input) { ConditionEvaluator.prototype.validateNumberInput = function (input) {
let valid = true; let valid = true;
input.forEach(function (value) { input.forEach(function (value) {
valid = valid && typeof value === 'number'; valid = valid && typeof value === 'number';
}); });
return valid; return valid;
}; };
/** /**
* A function that returns true only if each value in its input argument is * A function that returns true only if each value in its input argument is
* a string * a string
* @param {[]} input An array of values * @param {[]} input An array of values
* @returns {boolean} * @returns {boolean}
*/ */
ConditionEvaluator.prototype.validateStringInput = function (input) { ConditionEvaluator.prototype.validateStringInput = function (input) {
let valid = true; let valid = true;
input.forEach(function (value) { input.forEach(function (value) {
valid = valid && typeof value === 'string'; valid = valid && typeof value === 'string';
}); });
return valid; return valid;
}; };
/** /**
* Get the keys of operations supported by this evaluator * Get the keys of operations supported by this evaluator
* @return {string[]} An array of the keys of supported operations * @return {string[]} An array of the keys of supported operations
*/ */
ConditionEvaluator.prototype.getOperationKeys = function () { ConditionEvaluator.prototype.getOperationKeys = function () {
return Object.keys(this.operations); return Object.keys(this.operations);
}; };
/** /**
* Get the human-readable text corresponding to a given operation * Get the human-readable text corresponding to a given operation
* @param {string} key The key of the operation * @param {string} key The key of the operation
* @return {string} The text description of the operation * @return {string} The text description of the operation
*/ */
ConditionEvaluator.prototype.getOperationText = function (key) { ConditionEvaluator.prototype.getOperationText = function (key) {
return this.operations[key].text; return this.operations[key].text;
}; };
/** /**
* Returns true only if the given operation applies to a given type * Returns true only if the given operation applies to a given type
* @param {string} key The key of the operation * @param {string} key The key of the operation
* @param {string} type The value type to query * @param {string} type The value type to query
* @returns {boolean} True if the condition applies, false otherwise * @returns {boolean} True if the condition applies, false otherwise
*/ */
ConditionEvaluator.prototype.operationAppliesTo = function (key, type) { ConditionEvaluator.prototype.operationAppliesTo = function (key, type) {
return this.operations[key].appliesTo.includes(type); return this.operations[key].appliesTo.includes(type);
}; };
/** /**
* Return the number of value inputs required by an operation * Return the number of value inputs required by an operation
* @param {string} key The key of the operation to query * @param {string} key The key of the operation to query
* @return {number} * @return {number}
*/ */
ConditionEvaluator.prototype.getInputCount = function (key) { ConditionEvaluator.prototype.getInputCount = function (key) {
if (this.operations[key]) { if (this.operations[key]) {
return this.operations[key].inputCount; return this.operations[key].inputCount;
} }
}; };
/** /**
* Return the human-readable shorthand description of the operation for a rule header * Return the human-readable shorthand description of the operation for a rule header
* @param {string} key The key of the operation to query * @param {string} key The key of the operation to query
* @param {} values An array of values with which to invoke the getDescription function * @param {} values An array of values with which to invoke the getDescription function
* of the operation * of the operation
* @return {string} A text description of this operation * @return {string} A text description of this operation
*/ */
ConditionEvaluator.prototype.getOperationDescription = function (key, values) { ConditionEvaluator.prototype.getOperationDescription = function (key, values) {
if (this.operations[key]) { if (this.operations[key]) {
return this.operations[key].getDescription(values); return this.operations[key].getDescription(values);
} }
}; };
/** /**
* Return the HTML input type associated with a given operation * Return the HTML input type associated with a given operation
* @param {string} key The key of the operation to query * @param {string} key The key of the operation to query
* @return {string} The key for an HTML5 input type * @return {string} The key for an HTML5 input type
*/ */
ConditionEvaluator.prototype.getInputType = function (key) { ConditionEvaluator.prototype.getInputType = function (key) {
let type; let type;
if (this.operations[key]) { if (this.operations[key]) {
type = this.operations[key].appliesTo[0]; type = this.operations[key].appliesTo[0];
@ -452,35 +451,32 @@ define([], function () {
if (this.inputTypes[type]) { if (this.inputTypes[type]) {
return this.inputTypes[type]; return this.inputTypes[type];
} }
}; };
/** /**
* Returns the HTML input type associated with a value type * Returns the HTML input type associated with a value type
* @param {string} dataType The JavaScript value type * @param {string} dataType The JavaScript value type
* @return {string} The key for an HTML5 input type * @return {string} The key for an HTML5 input type
*/ */
ConditionEvaluator.prototype.getInputTypeById = function (dataType) { ConditionEvaluator.prototype.getInputTypeById = function (dataType) {
return this.inputTypes[dataType]; return this.inputTypes[dataType];
}; };
/** /**
* Set the test data cache used by this rule evaluator * Set the test data cache used by this rule evaluator
* @param {object} testCache A mock cache following the format of the real * @param {object} testCache A mock cache following the format of the real
* subscription cache * subscription cache
*/ */
ConditionEvaluator.prototype.setTestDataCache = function (testCache) { ConditionEvaluator.prototype.setTestDataCache = function (testCache) {
this.testCache = testCache; this.testCache = testCache;
}; };
/** /**
* Have this RuleEvaluator pull data values from the provided test cache * Have this RuleEvaluator pull data values from the provided test cache
* instead of its actual subscription cache when evaluating. If invoked with true, * instead of its actual subscription cache when evaluating. If invoked with true,
* will use the test cache; otherwise, will use the subscription cache * will use the test cache; otherwise, will use the subscription cache
* @param {boolean} useTestData Boolean flag * @param {boolean} useTestData Boolean flag
*/ */
ConditionEvaluator.prototype.useTestData = function (useTestCache) { ConditionEvaluator.prototype.useTestData = function (useTestCache) {
this.useTestCache = useTestCache; this.useTestCache = useTestCache;
}; };
return ConditionEvaluator;
});

View File

@ -1,10 +1,10 @@
define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], function ( import EventEmitter from 'EventEmitter';
ConditionEvaluator, import _ from 'lodash';
objectUtils, import objectUtils from 'objectUtils';
EventEmitter,
_ import ConditionEvaluator from './ConditionEvaluator';
) {
/** /**
* Provides a centralized content manager for conditions in the summary widget. * Provides a centralized content manager for conditions in the summary widget.
* Loads and caches composition and telemetry subscriptions, and maintains a * Loads and caches composition and telemetry subscriptions, and maintains a
* {ConditionEvaluator} instance to handle evaluation * {ConditionEvaluator} instance to handle evaluation
@ -12,7 +12,7 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
* @param {Object} domainObject the Summary Widget domain object * @param {Object} domainObject the Summary Widget domain object
* @param {MCT} openmct an MCT instance * @param {MCT} openmct an MCT instance
*/ */
function ConditionManager(domainObject, openmct) { export default function ConditionManager(domainObject, openmct) {
this.domainObject = domainObject; this.domainObject = domainObject;
this.openmct = openmct; this.openmct = openmct;
@ -47,9 +47,9 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
this.composition.on('load', this.onCompositionLoad, this); this.composition.on('load', this.onCompositionLoad, this);
this.composition.load(); this.composition.load();
} }
/** /**
* Register a callback with this ConditionManager: supported callbacks are add * Register a callback with this ConditionManager: supported callbacks are add
* remove, load, metadata, and receiveTelemetry * remove, load, metadata, and receiveTelemetry
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
@ -57,7 +57,7 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
ConditionManager.prototype.on = function (event, callback, context) { ConditionManager.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} else { } else {
@ -65,9 +65,9 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
event + ' is not a supported callback. Supported callbacks are ' + this.supportedCallbacks event + ' is not a supported callback. Supported callbacks are ' + this.supportedCallbacks
); );
} }
}; };
/** /**
* Given a set of rules, execute the conditions associated with each rule * Given a set of rules, execute the conditions associated with each rule
* and return the id of the last rule whose conditions evaluate to true * and return the id of the last rule whose conditions evaluate to true
* @param {string[]} ruleOrder An array of rule IDs indicating what order They * @param {string[]} ruleOrder An array of rule IDs indicating what order They
@ -75,7 +75,7 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
* @param {Object} rules An object mapping rule IDs to rule configurations * @param {Object} rules An object mapping rule IDs to rule configurations
* @return {string} The ID of the rule to display on the widget * @return {string} The ID of the rule to display on the widget
*/ */
ConditionManager.prototype.executeRules = function (ruleOrder, rules) { ConditionManager.prototype.executeRules = function (ruleOrder, rules) {
const self = this; const self = this;
let activeId = ruleOrder[0]; let activeId = ruleOrder[0];
let rule; let rule;
@ -90,35 +90,35 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
}); });
return activeId; return activeId;
}; };
/** /**
* Adds a field to the list of all available metadata fields in the widget * Adds a field to the list of all available metadata fields in the widget
* @param {Object} metadatum An object representing a set of telemetry metadata * @param {Object} metadatum An object representing a set of telemetry metadata
*/ */
ConditionManager.prototype.addGlobalMetadata = function (metadatum) { ConditionManager.prototype.addGlobalMetadata = function (metadatum) {
this.telemetryMetadataById.any[metadatum.key] = metadatum; this.telemetryMetadataById.any[metadatum.key] = metadatum;
this.telemetryMetadataById.all[metadatum.key] = metadatum; this.telemetryMetadataById.all[metadatum.key] = metadatum;
}; };
/** /**
* Adds a field to the list of properties for globally available metadata * Adds a field to the list of properties for globally available metadata
* @param {string} key The key for the property this type applies to * @param {string} key The key for the property this type applies to
* @param {string} type The type that should be associated with this property * @param {string} type The type that should be associated with this property
*/ */
ConditionManager.prototype.addGlobalPropertyType = function (key, type) { ConditionManager.prototype.addGlobalPropertyType = function (key, type) {
this.telemetryTypesById.any[key] = type; this.telemetryTypesById.any[key] = type;
this.telemetryTypesById.all[key] = type; this.telemetryTypesById.all[key] = type;
}; };
/** /**
* Given a telemetry-producing domain object, associate each of it's telemetry * Given a telemetry-producing domain object, associate each of it's telemetry
* fields with a type, parsing from historical data. * fields with a type, parsing from historical data.
* @param {Object} object a domain object that can produce telemetry * @param {Object} object a domain object that can produce telemetry
* @return {Promise} A promise that resolves when a telemetry request * @return {Promise} A promise that resolves when a telemetry request
* has completed and types have been parsed * has completed and types have been parsed
*/ */
ConditionManager.prototype.parsePropertyTypes = function (object) { ConditionManager.prototype.parsePropertyTypes = function (object) {
const objectId = objectUtils.makeKeyString(object.identifier); const objectId = objectUtils.makeKeyString(object.identifier);
this.telemetryTypesById[objectId] = {}; this.telemetryTypesById[objectId] = {};
@ -139,47 +139,47 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
this.telemetryTypesById[objectId][valueMetadata.key] = type; this.telemetryTypesById[objectId][valueMetadata.key] = type;
this.addGlobalPropertyType(valueMetadata.key, type); this.addGlobalPropertyType(valueMetadata.key, type);
}, this); }, this);
}; };
/** /**
* Parse types of telemetry fields from all composition objects; used internally * Parse types of telemetry fields from all composition objects; used internally
* to perform a block types load once initial composition load has completed * to perform a block types load once initial composition load has completed
* @return {Promise} A promise that resolves when all metadata has been loaded * @return {Promise} A promise that resolves when all metadata has been loaded
* and property types parsed * and property types parsed
*/ */
ConditionManager.prototype.parseAllPropertyTypes = function () { ConditionManager.prototype.parseAllPropertyTypes = function () {
Object.values(this.compositionObjs).forEach(this.parsePropertyTypes, this); Object.values(this.compositionObjs).forEach(this.parsePropertyTypes, this);
this.metadataLoadComplete = true; this.metadataLoadComplete = true;
this.eventEmitter.emit('metadata'); this.eventEmitter.emit('metadata');
}; };
/** /**
* Invoked when a telemetry subscription yields new data. Updates the LAD * Invoked when a telemetry subscription yields new data. Updates the LAD
* cache and invokes any registered receiveTelemetry callbacks * cache and invokes any registered receiveTelemetry callbacks
* @param {string} objId The key associated with the telemetry source * @param {string} objId The key associated with the telemetry source
* @param {datum} datum The new data from the telemetry source * @param {datum} datum The new data from the telemetry source
* @private * @private
*/ */
ConditionManager.prototype.handleSubscriptionCallback = function (objId, telemetryDatum) { ConditionManager.prototype.handleSubscriptionCallback = function (objId, telemetryDatum) {
this.subscriptionCache[objId] = this.createNormalizedDatum(objId, telemetryDatum); this.subscriptionCache[objId] = this.createNormalizedDatum(objId, telemetryDatum);
this.eventEmitter.emit('receiveTelemetry'); this.eventEmitter.emit('receiveTelemetry');
}; };
ConditionManager.prototype.createNormalizedDatum = function (objId, telemetryDatum) { ConditionManager.prototype.createNormalizedDatum = function (objId, telemetryDatum) {
return Object.values(this.telemetryMetadataById[objId]).reduce((normalizedDatum, metadatum) => { return Object.values(this.telemetryMetadataById[objId]).reduce((normalizedDatum, metadatum) => {
normalizedDatum[metadatum.key] = telemetryDatum[metadatum.source]; normalizedDatum[metadatum.key] = telemetryDatum[metadatum.source];
return normalizedDatum; return normalizedDatum;
}, {}); }, {});
}; };
/** /**
* Event handler for an add event in this Summary Widget's composition. * Event handler for an add event in this Summary Widget's composition.
* Sets up subscription handlers and parses its property types. * Sets up subscription handlers and parses its property types.
* @param {Object} obj The newly added domain object * @param {Object} obj The newly added domain object
* @private * @private
*/ */
ConditionManager.prototype.onCompositionAdd = function (obj) { ConditionManager.prototype.onCompositionAdd = function (obj) {
let compositionKeys; let compositionKeys;
const telemetryAPI = this.openmct.telemetry; const telemetryAPI = this.openmct.telemetry;
const objId = objectUtils.makeKeyString(obj.identifier); const objId = objectUtils.makeKeyString(obj.identifier);
@ -236,15 +236,15 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
summaryWidget.classList.remove('s-status-no-data'); summaryWidget.classList.remove('s-status-no-data');
} }
} }
}; };
/** /**
* Invoked on a remove event in this Summary Widget's composition. Removes * Invoked on a remove event in this Summary Widget's composition. Removes
* the object from the local composition, and untracks it * the object from the local composition, and untracks it
* @param {object} identifier The identifier of the object to be removed * @param {object} identifier The identifier of the object to be removed
* @private * @private
*/ */
ConditionManager.prototype.onCompositionRemove = function (identifier) { ConditionManager.prototype.onCompositionRemove = function (identifier) {
const objectId = objectUtils.makeKeyString(identifier); const objectId = objectUtils.makeKeyString(identifier);
// FIXME: this should just update by listener. // FIXME: this should just update by listener.
_.remove(this.domainObject.composition, function (id) { _.remove(this.domainObject.composition, function (id) {
@ -262,34 +262,34 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
summaryWidget.classList.add('s-status-no-data'); summaryWidget.classList.add('s-status-no-data');
} }
} }
}; };
/** /**
* Invoked when the Summary Widget's composition finishes its initial load. * Invoked when the Summary Widget's composition finishes its initial load.
* Invokes any registered load callbacks, does a block load of all metadata, * Invokes any registered load callbacks, does a block load of all metadata,
* and then invokes any registered metadata load callbacks. * and then invokes any registered metadata load callbacks.
* @private * @private
*/ */
ConditionManager.prototype.onCompositionLoad = function () { ConditionManager.prototype.onCompositionLoad = function () {
this.loadComplete = true; this.loadComplete = true;
this.eventEmitter.emit('load'); this.eventEmitter.emit('load');
this.parseAllPropertyTypes(); this.parseAllPropertyTypes();
}; };
/** /**
* Returns the currently tracked telemetry sources * Returns the currently tracked telemetry sources
* @return {Object} An object mapping object keys to domain objects * @return {Object} An object mapping object keys to domain objects
*/ */
ConditionManager.prototype.getComposition = function () { ConditionManager.prototype.getComposition = function () {
return this.compositionObjs; return this.compositionObjs;
}; };
/** /**
* Get the human-readable name of a domain object from its key * Get the human-readable name of a domain object from its key
* @param {string} id The key of the domain object * @param {string} id The key of the domain object
* @return {string} The human-readable name of the domain object * @return {string} The human-readable name of the domain object
*/ */
ConditionManager.prototype.getObjectName = function (id) { ConditionManager.prototype.getObjectName = function (id) {
let name; let name;
if (this.keywordLabels[id]) { if (this.keywordLabels[id]) {
@ -299,88 +299,85 @@ define(['./ConditionEvaluator', 'objectUtils', 'EventEmitter', 'lodash'], functi
} }
return name; return name;
}; };
/** /**
* Returns the property metadata associated with a given telemetry source * Returns the property metadata associated with a given telemetry source
* @param {string} id The key associated with the domain object * @param {string} id The key associated with the domain object
* @return {Object} Returns an object with fields representing each telemetry field * @return {Object} Returns an object with fields representing each telemetry field
*/ */
ConditionManager.prototype.getTelemetryMetadata = function (id) { ConditionManager.prototype.getTelemetryMetadata = function (id) {
return this.telemetryMetadataById[id]; return this.telemetryMetadataById[id];
}; };
/** /**
* Returns the type associated with a telemetry data field of a particular domain * Returns the type associated with a telemetry data field of a particular domain
* object * object
* @param {string} id The key associated with the domain object * @param {string} id The key associated with the domain object
* @param {string} property The telemetry field key to retrieve the type of * @param {string} property The telemetry field key to retrieve the type of
* @return {string} The type name * @return {string} The type name
*/ */
ConditionManager.prototype.getTelemetryPropertyType = function (id, property) { ConditionManager.prototype.getTelemetryPropertyType = function (id, property) {
if (this.telemetryTypesById[id]) { if (this.telemetryTypesById[id]) {
return this.telemetryTypesById[id][property]; return this.telemetryTypesById[id][property];
} }
}; };
/** /**
* Returns the human-readable name of a telemetry data field of a particular domain * Returns the human-readable name of a telemetry data field of a particular domain
* object * object
* @param {string} id The key associated with the domain object * @param {string} id The key associated with the domain object
* @param {string} property The telemetry field key to retrieve the type of * @param {string} property The telemetry field key to retrieve the type of
* @return {string} The telemetry field name * @return {string} The telemetry field name
*/ */
ConditionManager.prototype.getTelemetryPropertyName = function (id, property) { ConditionManager.prototype.getTelemetryPropertyName = function (id, property) {
if (this.telemetryMetadataById[id] && this.telemetryMetadataById[id][property]) { if (this.telemetryMetadataById[id] && this.telemetryMetadataById[id][property]) {
return this.telemetryMetadataById[id][property].name; return this.telemetryMetadataById[id][property].name;
} }
}; };
/** /**
* Returns the {ConditionEvaluator} instance associated with this condition * Returns the {ConditionEvaluator} instance associated with this condition
* manager * manager
* @return {ConditionEvaluator} * @return {ConditionEvaluator}
*/ */
ConditionManager.prototype.getEvaluator = function () { ConditionManager.prototype.getEvaluator = function () {
return this.evaluator; return this.evaluator;
}; };
/** /**
* Returns true if the initial composition load has completed * Returns true if the initial composition load has completed
* @return {boolean} * @return {boolean}
*/ */
ConditionManager.prototype.loadCompleted = function () { ConditionManager.prototype.loadCompleted = function () {
return this.loadComplete; return this.loadComplete;
}; };
/** /**
* Returns true if the initial block metadata load has completed * Returns true if the initial block metadata load has completed
*/ */
ConditionManager.prototype.metadataLoadCompleted = function () { ConditionManager.prototype.metadataLoadCompleted = function () {
return this.metadataLoadComplete; return this.metadataLoadComplete;
}; };
/** /**
* Triggers the telemetryReceive callbacks registered to this ConditionManager, * Triggers the telemetryReceive callbacks registered to this ConditionManager,
* used by the {TestDataManager} to force a rule evaluation when test data is * used by the {TestDataManager} to force a rule evaluation when test data is
* enabled * enabled
*/ */
ConditionManager.prototype.triggerTelemetryCallback = function () { ConditionManager.prototype.triggerTelemetryCallback = function () {
this.eventEmitter.emit('receiveTelemetry'); this.eventEmitter.emit('receiveTelemetry');
}; };
/** /**
* Unsubscribe from all registered telemetry sources and unregister all event * Unsubscribe from all registered telemetry sources and unregister all event
* listeners registered with the Open MCT APIs * listeners registered with the Open MCT APIs
*/ */
ConditionManager.prototype.destroy = function () { ConditionManager.prototype.destroy = function () {
Object.values(this.subscriptions).forEach(function (unsubscribeFunction) { Object.values(this.subscriptions).forEach(function (unsubscribeFunction) {
unsubscribeFunction(); unsubscribeFunction();
}); });
this.composition.off('add', this.onCompositionAdd, this); this.composition.off('add', this.onCompositionAdd, this);
this.composition.off('remove', this.onCompositionRemove, this); this.composition.off('remove', this.onCompositionRemove, this);
this.composition.off('load', this.onCompositionLoad, this); this.composition.off('load', this.onCompositionLoad, this);
}; };
return ConditionManager;
});

View File

@ -1,23 +1,14 @@
define([ import EventEmitter from 'EventEmitter';
'../res/ruleTemplate.html', import _ from 'lodash';
'./Condition',
'./input/ColorPalette', import * as templateHelpers from '../../../utils/template/templateHelpers';
'./input/IconPalette', import ruleTemplate from '../res/ruleTemplate.html';
'./eventHelpers', import Condition from './Condition';
'../../../utils/template/templateHelpers', import eventHelpers from './eventHelpers';
'EventEmitter', import ColorPalette from './input/ColorPalette';
'lodash' import IconPalette from './input/IconPalette';
], function (
ruleTemplate, /**
Condition,
ColorPalette,
IconPalette,
eventHelpers,
templateHelpers,
EventEmitter,
_
) {
/**
* An object representing a summary widget rule. Maintains a set of text * An object representing a summary widget rule. Maintains a set of text
* and css properties for output, and a set of conditions for configuring * and css properties for output, and a set of conditions for configuring
* when the rule will be applied to the summary widget. * when the rule will be applied to the summary widget.
@ -29,7 +20,14 @@ define([
* @param {WidgetDnD} widgetDnD A WidgetDnD instance to handle dragging and dropping rules * @param {WidgetDnD} widgetDnD A WidgetDnD instance to handle dragging and dropping rules
* @param {element} container The DOM element which contains this summary widget * @param {element} container The DOM element which contains this summary widget
*/ */
function Rule(ruleConfig, domainObject, openmct, conditionManager, widgetDnD, container) { export default function Rule(
ruleConfig,
domainObject,
openmct,
conditionManager,
widgetDnD,
container
) {
eventHelpers.extend(this); eventHelpers.extend(this);
const self = this; const self = this;
const THUMB_ICON_CLASS = 'c-sw__icon js-sw__icon'; const THUMB_ICON_CLASS = 'c-sw__icon js-sw__icon';
@ -164,9 +162,7 @@ define([
function onDragStart(event) { function onDragStart(event) {
document.querySelectorAll('.t-drag-indicator').forEach((indicator) => { document.querySelectorAll('.t-drag-indicator').forEach((indicator) => {
// eslint-disable-next-line no-invalid-this // eslint-disable-next-line no-invalid-this
const ruleHeader = self.domElement const ruleHeader = self.domElement.querySelectorAll('.widget-rule-header')[0].cloneNode(true);
.querySelectorAll('.widget-rule-header')[0]
.cloneNode(true);
indicator.textContent = ''; indicator.textContent = '';
indicator.appendChild(ruleHeader); indicator.appendChild(ruleHeader);
}); });
@ -276,20 +272,20 @@ define([
this.domElement.querySelector('.t-widget-rule-config').style.display = 'none'; this.domElement.querySelector('.t-widget-rule-config').style.display = 'none';
this.domElement.querySelector('.t-grippy').style.display = 'none'; this.domElement.querySelector('.t-grippy').style.display = 'none';
} }
} }
/** /**
* Return the DOM element representing this rule * Return the DOM element representing this rule
* @return {Element} A DOM element * @return {Element} A DOM element
*/ */
Rule.prototype.getDOM = function () { Rule.prototype.getDOM = function () {
return this.domElement; return this.domElement;
}; };
/** /**
* Unregister any event handlers registered with external sources * Unregister any event handlers registered with external sources
*/ */
Rule.prototype.destroy = function () { Rule.prototype.destroy = function () {
Object.values(this.colorInputs).forEach(function (palette) { Object.values(this.colorInputs).forEach(function (palette) {
palette.destroy(); palette.destroy();
}); });
@ -298,9 +294,9 @@ define([
this.conditions.forEach(function (condition) { this.conditions.forEach(function (condition) {
condition.destroy(); condition.destroy();
}); });
}; };
/** /**
* Register a callback with this rule: supported callbacks are remove, change, * Register a callback with this rule: supported callbacks are remove, change,
* conditionChange, and duplicate * conditionChange, and duplicate
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
@ -308,58 +304,58 @@ define([
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
Rule.prototype.on = function (event, callback, context) { Rule.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} }
}; };
/** /**
* An event handler for when a condition's configuration is modified * An event handler for when a condition's configuration is modified
* @param {} value * @param {} value
* @param {string} property The path in the configuration to updateDomainObject * @param {string} property The path in the configuration to updateDomainObject
* @param {number} index The index of the condition that initiated this change * @param {number} index The index of the condition that initiated this change
*/ */
Rule.prototype.onConditionChange = function (event) { Rule.prototype.onConditionChange = function (event) {
_.set(this.config.conditions[event.index], event.property, event.value); _.set(this.config.conditions[event.index], event.property, event.value);
this.generateDescription(); this.generateDescription();
this.updateDomainObject(); this.updateDomainObject();
this.eventEmitter.emit('conditionChange'); this.eventEmitter.emit('conditionChange');
}; };
/** /**
* During a rule drag event, show the placeholder element after this rule * During a rule drag event, show the placeholder element after this rule
*/ */
Rule.prototype.showDragIndicator = function () { Rule.prototype.showDragIndicator = function () {
document.querySelector('.t-drag-indicator').style.display = 'none'; document.querySelector('.t-drag-indicator').style.display = 'none';
this.domElement.querySelector('.t-drag-indicator').style.display = ''; this.domElement.querySelector('.t-drag-indicator').style.display = '';
}; };
/** /**
* Mutate the domain object with this rule's local configuration * Mutate the domain object with this rule's local configuration
*/ */
Rule.prototype.updateDomainObject = function () { Rule.prototype.updateDomainObject = function () {
this.openmct.objects.mutate( this.openmct.objects.mutate(
this.domainObject, this.domainObject,
'configuration.ruleConfigById.' + this.config.id, 'configuration.ruleConfigById.' + this.config.id,
this.config this.config
); );
}; };
/** /**
* Get a property of this rule by key * Get a property of this rule by key
* @param {string} prop They property key of this rule to get * @param {string} prop They property key of this rule to get
* @return {} The queried property * @return {} The queried property
*/ */
Rule.prototype.getProperty = function (prop) { Rule.prototype.getProperty = function (prop) {
return this.config[prop]; return this.config[prop];
}; };
/** /**
* Remove this rule from the domain object's configuration and invoke any * Remove this rule from the domain object's configuration and invoke any
* registered remove callbacks * registered remove callbacks
*/ */
Rule.prototype.remove = function () { Rule.prototype.remove = function () {
const ruleOrder = this.domainObject.configuration.ruleOrder; const ruleOrder = this.domainObject.configuration.ruleOrder;
const ruleConfigById = this.domainObject.configuration.ruleConfigById; const ruleConfigById = this.domainObject.configuration.ruleConfigById;
const self = this; const self = this;
@ -373,19 +369,19 @@ define([
this.openmct.objects.mutate(this.domainObject, 'configuration.ruleOrder', ruleOrder); this.openmct.objects.mutate(this.domainObject, 'configuration.ruleOrder', ruleOrder);
this.destroy(); this.destroy();
this.eventEmitter.emit('remove'); this.eventEmitter.emit('remove');
}; };
/** /**
* Makes a deep clone of this rule's configuration, and calls the duplicate event * Makes a deep clone of this rule's configuration, and calls the duplicate event
* callback with the cloned configuration as an argument if one has been registered * callback with the cloned configuration as an argument if one has been registered
*/ */
Rule.prototype.duplicate = function () { Rule.prototype.duplicate = function () {
const sourceRule = JSON.parse(JSON.stringify(this.config)); const sourceRule = JSON.parse(JSON.stringify(this.config));
sourceRule.expanded = true; sourceRule.expanded = true;
this.eventEmitter.emit('duplicate', sourceRule); this.eventEmitter.emit('duplicate', sourceRule);
}; };
/** /**
* Initialize a new condition. If called with the sourceConfig and sourceIndex arguments, * Initialize a new condition. If called with the sourceConfig and sourceIndex arguments,
* will insert a new condition with the provided configuration after the sourceIndex * will insert a new condition with the provided configuration after the sourceIndex
* index. Otherwise, initializes a new blank rule and inserts it at the end * index. Otherwise, initializes a new blank rule and inserts it at the end
@ -393,7 +389,7 @@ define([
* @param {Object} [config] The configuration to initialize this rule from, * @param {Object} [config] The configuration to initialize this rule from,
* consisting of sourceCondition and index fields * consisting of sourceCondition and index fields
*/ */
Rule.prototype.initCondition = function (config) { Rule.prototype.initCondition = function (config) {
const ruleConfigById = this.domainObject.configuration.ruleConfigById; const ruleConfigById = this.domainObject.configuration.ruleConfigById;
let newConfig; let newConfig;
const sourceIndex = config && config.index; const sourceIndex = config && config.index;
@ -415,12 +411,12 @@ define([
this.updateDomainObject(); this.updateDomainObject();
this.refreshConditions(); this.refreshConditions();
this.generateDescription(); this.generateDescription();
}; };
/** /**
* Build {Condition} objects from configuration and rebuild associated view * Build {Condition} objects from configuration and rebuild associated view
*/ */
Rule.prototype.refreshConditions = function () { Rule.prototype.refreshConditions = function () {
const self = this; const self = this;
let $condition = null; let $condition = null;
let loopCnt = 0; let loopCnt = 0;
@ -467,13 +463,13 @@ define([
if (self.conditions.length === 1) { if (self.conditions.length === 1) {
self.conditions[0].hideButtons(); self.conditions[0].hideButtons();
} }
}; };
/** /**
* Remove a condition from this rule's configuration at the given index * Remove a condition from this rule's configuration at the given index
* @param {number} removeIndex The index of the condition to remove * @param {number} removeIndex The index of the condition to remove
*/ */
Rule.prototype.removeCondition = function (removeIndex) { Rule.prototype.removeCondition = function (removeIndex) {
const ruleConfigById = this.domainObject.configuration.ruleConfigById; const ruleConfigById = this.domainObject.configuration.ruleConfigById;
const conditions = ruleConfigById[this.config.id].conditions; const conditions = ruleConfigById[this.config.id].conditions;
@ -486,12 +482,12 @@ define([
this.refreshConditions(); this.refreshConditions();
this.generateDescription(); this.generateDescription();
this.eventEmitter.emit('conditionChange'); this.eventEmitter.emit('conditionChange');
}; };
/** /**
* Build a human-readable description from this rule's conditions * Build a human-readable description from this rule's conditions
*/ */
Rule.prototype.generateDescription = function () { Rule.prototype.generateDescription = function () {
let description = ''; let description = '';
const manager = this.conditionManager; const manager = this.conditionManager;
const evaluator = manager.getEvaluator(); const evaluator = manager.getEvaluator();
@ -531,7 +527,4 @@ define([
description = description === '' ? this.config.description : description; description = description === '' ? this.config.description : description;
this.description.innerText = self.config.description; this.description.innerText = self.config.description;
this.config.description = description; this.config.description = description;
}; };
return Rule;
});

View File

@ -1,34 +1,21 @@
define([ import * as urlSanitizeLib from '@braintree/sanitize-url';
'../res/widgetTemplate.html',
'./Rule', import * as templateHelpers from '../../../utils/template/templateHelpers';
'./ConditionManager', import widgetTemplate from '../res/widgetTemplate.html';
'./TestDataManager', import ConditionManager from './ConditionManager';
'./WidgetDnD', import eventHelpers from './eventHelpers';
'./eventHelpers', import Rule from './Rule';
'../../../utils/template/templateHelpers', import TestDataManager from './TestDataManager';
'objectUtils', import WidgetDnD from './WidgetDnD';
'lodash',
'@braintree/sanitize-url' //default css configuration for new rules
], function ( const DEFAULT_PROPS = {
widgetTemplate,
Rule,
ConditionManager,
TestDataManager,
WidgetDnD,
eventHelpers,
templateHelpers,
objectUtils,
_,
urlSanitizeLib
) {
//default css configuration for new rules
const DEFAULT_PROPS = {
color: '#cccccc', color: '#cccccc',
'background-color': '#666666', 'background-color': '#666666',
'border-color': 'rgba(0,0,0,0)' 'border-color': 'rgba(0,0,0,0)'
}; };
/** /**
* A Summary Widget object, which allows a user to configure rules based * A Summary Widget object, which allows a user to configure rules based
* on telemetry producing domain objects, and update a compact display * on telemetry producing domain objects, and update a compact display
* accordingly. * accordingly.
@ -36,7 +23,7 @@ define([
* @param {Object} domainObject The domain Object represented by this Widget * @param {Object} domainObject The domain Object represented by this Widget
* @param {MCT} openmct An MCT instance * @param {MCT} openmct An MCT instance
*/ */
function SummaryWidget(domainObject, openmct) { export default function SummaryWidget(domainObject, openmct) {
eventHelpers.extend(this); eventHelpers.extend(this);
this.domainObject = domainObject; this.domainObject = domainObject;
@ -123,14 +110,14 @@ define([
} }
this.listenTo(this.toggleRulesControl, 'click', toggleRules); this.listenTo(this.toggleRulesControl, 'click', toggleRules);
} }
/** /**
* adds or removes href to widget button and adds or removes openInNewTab * adds or removes href to widget button and adds or removes openInNewTab
* @param {string} url String that denotes the url to be opened * @param {string} url String that denotes the url to be opened
* @param {string} openNewTab String that denotes wether to open link in new tab or not * @param {string} openNewTab String that denotes wether to open link in new tab or not
*/ */
SummaryWidget.prototype.addHyperlink = function (url, openNewTab) { SummaryWidget.prototype.addHyperlink = function (url, openNewTab) {
if (url) { if (url) {
this.widgetButton.href = urlSanitizeLib.sanitizeUrl(url); this.widgetButton.href = urlSanitizeLib.sanitizeUrl(url);
} else { } else {
@ -142,15 +129,15 @@ define([
} else { } else {
this.widgetButton.removeAttribute('target'); this.widgetButton.removeAttribute('target');
} }
}; };
/** /**
* adds a listener to the object to watch for any changes made by user * adds a listener to the object to watch for any changes made by user
* only executes if changes are observed * only executes if changes are observed
* @param {openmct} Object Instance of OpenMCT * @param {openmct} Object Instance of OpenMCT
* @param {domainObject} Object instance of this object * @param {domainObject} Object instance of this object
*/ */
SummaryWidget.prototype.watchForChanges = function (openmct, domainObject) { SummaryWidget.prototype.watchForChanges = function (openmct, domainObject) {
this.watchForChangesUnsubscribe = openmct.objects.observe( this.watchForChangesUnsubscribe = openmct.objects.observe(
domainObject, domainObject,
'*', '*',
@ -163,15 +150,15 @@ define([
} }
}.bind(this) }.bind(this)
); );
}; };
/** /**
* Builds the Summary Widget's DOM, performs other necessary setup, and attaches * Builds the Summary Widget's DOM, performs other necessary setup, and attaches
* this Summary Widget's view to the supplied container. * this Summary Widget's view to the supplied container.
* @param {element} container The DOM element that will contain this Summary * @param {element} container The DOM element that will contain this Summary
* Widget's view. * Widget's view.
*/ */
SummaryWidget.prototype.show = function (container) { SummaryWidget.prototype.show = function (container) {
const self = this; const self = this;
this.container = container; this.container = container;
this.container.append(this.domElement); this.container.append(this.domElement);
@ -193,13 +180,13 @@ define([
this.listenTo(this.addRuleButton, 'click', this.addRule); this.listenTo(this.addRuleButton, 'click', this.addRule);
this.conditionManager.on('receiveTelemetry', this.executeRules, this); this.conditionManager.on('receiveTelemetry', this.executeRules, this);
this.widgetDnD.on('drop', this.reorder, this); this.widgetDnD.on('drop', this.reorder, this);
}; };
/** /**
* Unregister event listeners with the Open MCT APIs, unsubscribe from telemetry, * Unregister event listeners with the Open MCT APIs, unsubscribe from telemetry,
* and clean up event handlers * and clean up event handlers
*/ */
SummaryWidget.prototype.destroy = function (container) { SummaryWidget.prototype.destroy = function (container) {
this.editListenerUnsubscribe(); this.editListenerUnsubscribe();
this.conditionManager.destroy(); this.conditionManager.destroy();
this.testDataManager.destroy(); this.testDataManager.destroy();
@ -210,12 +197,12 @@ define([
}); });
this.stopListening(); this.stopListening();
}; };
/** /**
* Update the view from the current rule configuration and order * Update the view from the current rule configuration and order
*/ */
SummaryWidget.prototype.refreshRules = function () { SummaryWidget.prototype.refreshRules = function () {
const self = this; const self = this;
const ruleOrder = self.domainObject.configuration.ruleOrder; const ruleOrder = self.domainObject.configuration.ruleOrder;
const rules = self.rulesById; const rules = self.rulesById;
@ -226,9 +213,9 @@ define([
this.executeRules(); this.executeRules();
this.addOrRemoveDragIndicator(); this.addOrRemoveDragIndicator();
}; };
SummaryWidget.prototype.addOrRemoveDragIndicator = function () { SummaryWidget.prototype.addOrRemoveDragIndicator = function () {
const rules = this.domainObject.configuration.ruleOrder; const rules = this.domainObject.configuration.ruleOrder;
const rulesById = this.rulesById; const rulesById = this.rulesById;
@ -239,12 +226,12 @@ define([
rulesById[ruleKey].domElement.querySelector('.t-grippy').style.display = 'none'; rulesById[ruleKey].domElement.querySelector('.t-grippy').style.display = 'none';
} }
}); });
}; };
/** /**
* Update the widget's appearance from the configuration of the active rule * Update the widget's appearance from the configuration of the active rule
*/ */
SummaryWidget.prototype.updateWidget = function () { SummaryWidget.prototype.updateWidget = function () {
const WIDGET_ICON_CLASS = 'c-sw__icon js-sw__icon'; const WIDGET_ICON_CLASS = 'c-sw__icon js-sw__icon';
const activeRule = this.rulesById[this.activeId]; const activeRule = this.rulesById[this.activeId];
@ -253,23 +240,23 @@ define([
this.domElement.querySelector('#widgetLabel').textContent = activeRule.getProperty('label'); this.domElement.querySelector('#widgetLabel').textContent = activeRule.getProperty('label');
this.domElement.querySelector('#widgetIcon').classList = this.domElement.querySelector('#widgetIcon').classList =
WIDGET_ICON_CLASS + ' ' + activeRule.getProperty('icon'); WIDGET_ICON_CLASS + ' ' + activeRule.getProperty('icon');
}; };
/** /**
* Get the active rule and update the Widget's appearance. * Get the active rule and update the Widget's appearance.
*/ */
SummaryWidget.prototype.executeRules = function () { SummaryWidget.prototype.executeRules = function () {
this.activeId = this.conditionManager.executeRules( this.activeId = this.conditionManager.executeRules(
this.domainObject.configuration.ruleOrder, this.domainObject.configuration.ruleOrder,
this.rulesById this.rulesById
); );
this.updateWidget(); this.updateWidget();
}; };
/** /**
* Add a new rule to this widget * Add a new rule to this widget
*/ */
SummaryWidget.prototype.addRule = function () { SummaryWidget.prototype.addRule = function () {
let ruleCount = 0; let ruleCount = 0;
let ruleId; let ruleId;
const ruleOrder = this.domainObject.configuration.ruleOrder; const ruleOrder = this.domainObject.configuration.ruleOrder;
@ -285,15 +272,15 @@ define([
this.initRule(ruleId, 'Rule'); this.initRule(ruleId, 'Rule');
this.updateDomainObject(); this.updateDomainObject();
this.refreshRules(); this.refreshRules();
}; };
/** /**
* Duplicate an existing widget rule from its configuration and splice it in * Duplicate an existing widget rule from its configuration and splice it in
* after the rule it duplicates * after the rule it duplicates
* @param {Object} sourceConfig The configuration properties of the rule to be * @param {Object} sourceConfig The configuration properties of the rule to be
* instantiated * instantiated
*/ */
SummaryWidget.prototype.duplicateRule = function (sourceConfig) { SummaryWidget.prototype.duplicateRule = function (sourceConfig) {
let ruleCount = 0; let ruleCount = 0;
let ruleId; let ruleId;
const sourceRuleId = sourceConfig.id; const sourceRuleId = sourceConfig.id;
@ -313,16 +300,16 @@ define([
this.initRule(ruleId, sourceConfig.name); this.initRule(ruleId, sourceConfig.name);
this.updateDomainObject(); this.updateDomainObject();
this.refreshRules(); this.refreshRules();
}; };
/** /**
* Initialize a new rule from a default configuration, or build a {Rule} object * Initialize a new rule from a default configuration, or build a {Rule} object
* from it if already exists * from it if already exists
* @param {string} ruleId An key to be used to identify this ruleId, or the key * @param {string} ruleId An key to be used to identify this ruleId, or the key
of the rule to be instantiated of the rule to be instantiated
* @param {string} ruleName The initial human-readable name of this rule * @param {string} ruleName The initial human-readable name of this rule
*/ */
SummaryWidget.prototype.initRule = function (ruleId, ruleName) { SummaryWidget.prototype.initRule = function (ruleId, ruleName) {
let ruleConfig; let ruleConfig;
const styleObj = {}; const styleObj = {};
@ -363,15 +350,15 @@ define([
this.rulesById[ruleId].on('duplicate', this.duplicateRule, this); this.rulesById[ruleId].on('duplicate', this.duplicateRule, this);
this.rulesById[ruleId].on('change', this.updateWidget, this); this.rulesById[ruleId].on('change', this.updateWidget, this);
this.rulesById[ruleId].on('conditionChange', this.executeRules, this); this.rulesById[ruleId].on('conditionChange', this.executeRules, this);
}; };
/** /**
* Given two ruleIds, move the source rule after the target rule and update * Given two ruleIds, move the source rule after the target rule and update
* the view. * the view.
* @param {Object} event An event object representing this drop with draggingId * @param {Object} event An event object representing this drop with draggingId
* and dropTarget fields * and dropTarget fields
*/ */
SummaryWidget.prototype.reorder = function (event) { SummaryWidget.prototype.reorder = function (event) {
const ruleOrder = this.domainObject.configuration.ruleOrder; const ruleOrder = this.domainObject.configuration.ruleOrder;
const sourceIndex = ruleOrder.indexOf(event.draggingId); const sourceIndex = ruleOrder.indexOf(event.draggingId);
let targetIndex; let targetIndex;
@ -385,29 +372,22 @@ define([
} }
this.refreshRules(); this.refreshRules();
}; };
/** /**
* Apply a list of css properties to an element * Apply a list of css properties to an element
* @param {element} elem The DOM element to which the rules will be applied * @param {element} elem The DOM element to which the rules will be applied
* @param {object} style an object representing the style * @param {object} style an object representing the style
*/ */
SummaryWidget.prototype.applyStyle = function (elem, style) { SummaryWidget.prototype.applyStyle = function (elem, style) {
Object.keys(style).forEach(function (propId) { Object.keys(style).forEach(function (propId) {
elem.style[propId] = style[propId]; elem.style[propId] = style[propId];
}); });
}; };
/** /**
* Mutate this domain object's configuration with the current local configuration * Mutate this domain object's configuration with the current local configuration
*/ */
SummaryWidget.prototype.updateDomainObject = function () { SummaryWidget.prototype.updateDomainObject = function () {
this.openmct.objects.mutate( this.openmct.objects.mutate(this.domainObject, 'configuration', this.domainObject.configuration);
this.domainObject, };
'configuration',
this.domainObject.configuration
);
};
return SummaryWidget;
});

View File

@ -1,12 +1,12 @@
define([ import EventEmitter from 'EventEmitter';
'../res/testDataItemTemplate.html',
'./input/ObjectSelect', import * as templateHelpers from '../../../utils/template/templateHelpers';
'./input/KeySelect', import itemTemplate from '../res/testDataItemTemplate.html';
'./eventHelpers', import eventHelpers from './eventHelpers';
'../../../utils/template/templateHelpers', import KeySelect from './input/KeySelect';
'EventEmitter' import ObjectSelect from './input/ObjectSelect';
], function (itemTemplate, ObjectSelect, KeySelect, eventHelpers, templateHelpers, EventEmitter) {
/** /**
* An object representing a single mock telemetry value * An object representing a single mock telemetry value
* @param {object} itemConfig the configuration for this item, consisting of * @param {object} itemConfig the configuration for this item, consisting of
* object, key, and value fields * object, key, and value fields
@ -17,7 +17,7 @@ define([
* for populating selects with configuration data * for populating selects with configuration data
* @constructor * @constructor
*/ */
function TestDataItem(itemConfig, index, conditionManager) { export default function TestDataItem(itemConfig, index, conditionManager) {
eventHelpers.extend(this); eventHelpers.extend(this);
this.config = itemConfig; this.config = itemConfig;
this.index = index; this.index = index;
@ -97,17 +97,17 @@ define([
self.domElement.querySelector('.t-configuration').append(select.getDOM()); self.domElement.querySelector('.t-configuration').append(select.getDOM());
}); });
this.listenTo(this.domElement, 'input', onValueInput); this.listenTo(this.domElement, 'input', onValueInput);
} }
/** /**
* Gets the DOM associated with this element's view * Gets the DOM associated with this element's view
* @return {Element} * @return {Element}
*/ */
TestDataItem.prototype.getDOM = function (container) { TestDataItem.prototype.getDOM = function (container) {
return this.domElement; return this.domElement;
}; };
/** /**
* Register a callback with this item: supported callbacks are remove, change, * Register a callback with this item: supported callbacks are remove, change,
* and duplicate * and duplicate
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
@ -115,31 +115,31 @@ define([
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
TestDataItem.prototype.on = function (event, callback, context) { TestDataItem.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} }
}; };
/** /**
* Implement "off" to complete event emitter interface. * Implement "off" to complete event emitter interface.
*/ */
TestDataItem.prototype.off = function (event, callback, context) { TestDataItem.prototype.off = function (event, callback, context) {
this.eventEmitter.off(event, callback, context); this.eventEmitter.off(event, callback, context);
}; };
/** /**
* Hide the appropriate inputs when this is the only item * Hide the appropriate inputs when this is the only item
*/ */
TestDataItem.prototype.hideButtons = function () { TestDataItem.prototype.hideButtons = function () {
this.deleteButton.style.display = 'none'; this.deleteButton.style.display = 'none';
}; };
/** /**
* Remove this item from the configuration. Invokes any registered * Remove this item from the configuration. Invokes any registered
* remove callbacks * remove callbacks
*/ */
TestDataItem.prototype.remove = function () { TestDataItem.prototype.remove = function () {
const self = this; const self = this;
this.eventEmitter.emit('remove', self.index); this.eventEmitter.emit('remove', self.index);
this.stopListening(); this.stopListening();
@ -147,13 +147,13 @@ define([
Object.values(this.selects).forEach(function (select) { Object.values(this.selects).forEach(function (select) {
select.destroy(); select.destroy();
}); });
}; };
/** /**
* Makes a deep clone of this item's configuration, and invokes any registered * Makes a deep clone of this item's configuration, and invokes any registered
* duplicate callbacks with the cloned configuration as an argument * duplicate callbacks with the cloned configuration as an argument
*/ */
TestDataItem.prototype.duplicate = function () { TestDataItem.prototype.duplicate = function () {
const sourceItem = JSON.parse(JSON.stringify(this.config)); const sourceItem = JSON.parse(JSON.stringify(this.config));
const self = this; const self = this;
@ -161,14 +161,14 @@ define([
sourceItem: sourceItem, sourceItem: sourceItem,
index: self.index index: self.index
}); });
}; };
/** /**
* When a telemetry property key is selected, create the appropriate value input * When a telemetry property key is selected, create the appropriate value input
* and add it to the view * and add it to the view
* @param {string} key The key of currently selected telemetry property * @param {string} key The key of currently selected telemetry property
*/ */
TestDataItem.prototype.generateValueInput = function (key) { TestDataItem.prototype.generateValueInput = function (key) {
const evaluator = this.conditionManager.getEvaluator(); const evaluator = this.conditionManager.getEvaluator();
const inputArea = this.domElement.querySelector('.t-value-inputs'); const inputArea = this.domElement.querySelector('.t-value-inputs');
const dataType = this.conditionManager.getTelemetryPropertyType(this.config.object, key); const dataType = this.conditionManager.getTelemetryPropertyType(this.config.object, key);
@ -187,7 +187,4 @@ define([
this.valueInput = newInput; this.valueInput = newInput;
inputArea.append(this.valueInput); inputArea.append(this.valueInput);
} }
}; };
return TestDataItem;
});

View File

@ -1,18 +1,18 @@
define([ import _ from 'lodash';
'./eventHelpers',
'../res/testDataTemplate.html', import * as templateHelpers from '../../../utils/template/templateHelpers';
'./TestDataItem', import testDataTemplate from '../res/testDataTemplate.html';
'../../../utils/template/templateHelpers', import eventHelpers from './eventHelpers';
'lodash' import TestDataItem from './TestDataItem';
], function (eventHelpers, testDataTemplate, TestDataItem, templateHelpers, _) {
/** /**
* Controls the input and usage of test data in the summary widget. * Controls the input and usage of test data in the summary widget.
* @constructor * @constructor
* @param {Object} domainObject The summary widget domain object * @param {Object} domainObject The summary widget domain object
* @param {ConditionManager} conditionManager A conditionManager instance * @param {ConditionManager} conditionManager A conditionManager instance
* @param {MCT} openmct and MCT instance * @param {MCT} openmct and MCT instance
*/ */
function TestDataManager(domainObject, conditionManager, openmct) { export default function TestDataManager(domainObject, conditionManager, openmct) {
eventHelpers.extend(this); eventHelpers.extend(this);
const self = this; const self = this;
@ -50,22 +50,22 @@ define([
this.evaluator.useTestData(false); this.evaluator.useTestData(false);
this.refreshItems(); this.refreshItems();
} }
/** /**
* Get the DOM element representing this test data manager in the view * Get the DOM element representing this test data manager in the view
*/ */
TestDataManager.prototype.getDOM = function () { TestDataManager.prototype.getDOM = function () {
return this.domElement; return this.domElement;
}; };
/** /**
* Initialize a new test data item, either from a source configuration, or with * Initialize a new test data item, either from a source configuration, or with
* the default empty configuration * the default empty configuration
* @param {Object} [config] An object with sourceItem and index fields to instantiate * @param {Object} [config] An object with sourceItem and index fields to instantiate
* this rule from, optional * this rule from, optional
*/ */
TestDataManager.prototype.initItem = function (config) { TestDataManager.prototype.initItem = function (config) {
const sourceIndex = config && config.index; const sourceIndex = config && config.index;
const defaultItem = { const defaultItem = {
object: '', object: '',
@ -83,47 +83,47 @@ define([
this.updateDomainObject(); this.updateDomainObject();
this.refreshItems(); this.refreshItems();
}; };
/** /**
* Remove an item from this TestDataManager at the given index * Remove an item from this TestDataManager at the given index
* @param {number} removeIndex The index of the item to remove * @param {number} removeIndex The index of the item to remove
*/ */
TestDataManager.prototype.removeItem = function (removeIndex) { TestDataManager.prototype.removeItem = function (removeIndex) {
_.remove(this.config, function (item, index) { _.remove(this.config, function (item, index) {
return index === removeIndex; return index === removeIndex;
}); });
this.updateDomainObject(); this.updateDomainObject();
this.refreshItems(); this.refreshItems();
}; };
/** /**
* Change event handler for the test data items which compose this * Change event handler for the test data items which compose this
* test data generator * test data generator
* @param {Object} event An object representing this event, with value, property, * @param {Object} event An object representing this event, with value, property,
* and index fields * and index fields
*/ */
TestDataManager.prototype.onItemChange = function (event) { TestDataManager.prototype.onItemChange = function (event) {
this.config[event.index][event.property] = event.value; this.config[event.index][event.property] = event.value;
this.updateDomainObject(); this.updateDomainObject();
this.updateTestCache(); this.updateTestCache();
}; };
/** /**
* Builds the test cache from the current item configuration, and passes * Builds the test cache from the current item configuration, and passes
* the new test cache to the associated {ConditionEvaluator} instance * the new test cache to the associated {ConditionEvaluator} instance
*/ */
TestDataManager.prototype.updateTestCache = function () { TestDataManager.prototype.updateTestCache = function () {
this.generateTestCache(); this.generateTestCache();
this.evaluator.setTestDataCache(this.testCache); this.evaluator.setTestDataCache(this.testCache);
this.manager.triggerTelemetryCallback(); this.manager.triggerTelemetryCallback();
}; };
/** /**
* Instantiate {TestDataItem} objects from the current configuration, and * Instantiate {TestDataItem} objects from the current configuration, and
* update the view accordingly * update the view accordingly
*/ */
TestDataManager.prototype.refreshItems = function () { TestDataManager.prototype.refreshItems = function () {
const self = this; const self = this;
if (this.items) { if (this.items) {
this.items.forEach(function (item) { this.items.forEach(function (item) {
@ -154,13 +154,13 @@ define([
} }
this.updateTestCache(); this.updateTestCache();
}; };
/** /**
* Builds a test data cache in the format of a telemetry subscription cache * Builds a test data cache in the format of a telemetry subscription cache
* as expected by a {ConditionEvaluator} * as expected by a {ConditionEvaluator}
*/ */
TestDataManager.prototype.generateTestCache = function () { TestDataManager.prototype.generateTestCache = function () {
let testCache = this.testCache; let testCache = this.testCache;
const manager = this.manager; const manager = this.manager;
const compositionObjs = manager.getComposition(); const compositionObjs = manager.getComposition();
@ -181,21 +181,18 @@ define([
}); });
this.testCache = testCache; this.testCache = testCache;
}; };
/** /**
* Update the domain object configuration associated with this test data manager * Update the domain object configuration associated with this test data manager
*/ */
TestDataManager.prototype.updateDomainObject = function () { TestDataManager.prototype.updateDomainObject = function () {
this.openmct.objects.mutate(this.domainObject, 'configuration.testDataConfig', this.config); this.openmct.objects.mutate(this.domainObject, 'configuration.testDataConfig', this.config);
}; };
TestDataManager.prototype.destroy = function () { TestDataManager.prototype.destroy = function () {
this.stopListening(); this.stopListening();
this.items.forEach(function (item) { this.items.forEach(function (item) {
item.remove(); item.remove();
}); });
}; };
return TestDataManager;
});

View File

@ -1,15 +1,15 @@
define([ import EventEmitter from 'EventEmitter';
'../res/ruleImageTemplate.html',
'EventEmitter', import * as templateHelpers from '../../../utils/template/templateHelpers';
'../../../utils/template/templateHelpers' import ruleImageTemplate from '../res/ruleImageTemplate.html';
], function (ruleImageTemplate, EventEmitter, templateHelpers) {
/** /**
* Manages the Sortable List interface for reordering rules by drag and drop * Manages the Sortable List interface for reordering rules by drag and drop
* @param {Element} container The DOM element that contains this Summary Widget's view * @param {Element} container The DOM element that contains this Summary Widget's view
* @param {string[]} ruleOrder An array of rule IDs representing the current rule order * @param {string[]} ruleOrder An array of rule IDs representing the current rule order
* @param {Object} rulesById An object mapping rule IDs to rule configurations * @param {Object} rulesById An object mapping rule IDs to rule configurations
*/ */
function WidgetDnD(container, ruleOrder, rulesById) { export default function WidgetDnD(container, ruleOrder, rulesById) {
this.container = container; this.container = container;
this.ruleOrder = ruleOrder; this.ruleOrder = ruleOrder;
this.rulesById = rulesById; this.rulesById = rulesById;
@ -28,44 +28,44 @@ define([
document.addEventListener('mouseup', this.drop); document.addEventListener('mouseup', this.drop);
this.container.parentNode.insertBefore(this.imageContainer, this.container); this.container.parentNode.insertBefore(this.imageContainer, this.container);
this.imageContainer.style.display = 'none'; this.imageContainer.style.display = 'none';
} }
/** /**
* Remove event listeners registered to elements external to the widget * Remove event listeners registered to elements external to the widget
*/ */
WidgetDnD.prototype.destroy = function () { WidgetDnD.prototype.destroy = function () {
this.container.removeEventListener('mousemove', this.drag); this.container.removeEventListener('mousemove', this.drag);
document.removeEventListener('mouseup', this.drop); document.removeEventListener('mouseup', this.drop);
}; };
/** /**
* Register a callback with this WidgetDnD: supported callback is drop * Register a callback with this WidgetDnD: supported callback is drop
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
* @param {function} callback The function that this rule will invoke on this event * @param {function} callback The function that this rule will invoke on this event
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
WidgetDnD.prototype.on = function (event, callback, context) { WidgetDnD.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} }
}; };
/** /**
* Sets the image for the dragged element to the given DOM element * Sets the image for the dragged element to the given DOM element
* @param {Element} image The HTML element to set as the drap image * @param {Element} image The HTML element to set as the drap image
*/ */
WidgetDnD.prototype.setDragImage = function (image) { WidgetDnD.prototype.setDragImage = function (image) {
this.image.html(image); this.image.html(image);
}; };
/** /**
* Calculate where this rule has been dragged relative to the other rules * Calculate where this rule has been dragged relative to the other rules
* @param {Event} event The mousemove or mouseup event that triggered this * @param {Event} event The mousemove or mouseup event that triggered this
event handler event handler
* @return {string} The ID of the rule whose drag indicator should be displayed * @return {string} The ID of the rule whose drag indicator should be displayed
*/ */
WidgetDnD.prototype.getDropLocation = function (event) { WidgetDnD.prototype.getDropLocation = function (event) {
const ruleOrder = this.ruleOrder; const ruleOrder = this.ruleOrder;
const rulesById = this.rulesById; const rulesById = this.rulesById;
const draggingId = this.draggingId; const draggingId = this.draggingId;
@ -96,13 +96,13 @@ define([
}); });
return target; return target;
}; };
/** /**
* Called by a {Rule} instance that initiates a drag gesture * Called by a {Rule} instance that initiates a drag gesture
* @param {string} ruleId The identifier of the rule which is being dragged * @param {string} ruleId The identifier of the rule which is being dragged
*/ */
WidgetDnD.prototype.dragStart = function (ruleId) { WidgetDnD.prototype.dragStart = function (ruleId) {
const ruleOrder = this.ruleOrder; const ruleOrder = this.ruleOrder;
this.draggingId = ruleId; this.draggingId = ruleId;
this.draggingRulePrevious = ruleOrder[ruleOrder.indexOf(ruleId) - 1]; this.draggingRulePrevious = ruleOrder[ruleOrder.indexOf(ruleId) - 1];
@ -112,13 +112,13 @@ define([
top: event.pageY - this.image.height() / 2, top: event.pageY - this.image.height() / 2,
left: event.pageX - this.image.querySelector('.t-grippy').style.width left: event.pageX - this.image.querySelector('.t-grippy').style.width
}); });
}; };
/** /**
* An event handler for a mousemove event, once a rule has begun a drag gesture * An event handler for a mousemove event, once a rule has begun a drag gesture
* @param {Event} event The mousemove event that triggered this callback * @param {Event} event The mousemove event that triggered this callback
*/ */
WidgetDnD.prototype.drag = function (event) { WidgetDnD.prototype.drag = function (event) {
let dragTarget; let dragTarget;
if (this.draggingId && this.draggingId !== '') { if (this.draggingId && this.draggingId !== '') {
event.preventDefault(); event.preventDefault();
@ -133,16 +133,16 @@ define([
this.rulesById[this.draggingRulePrevious].showDragIndicator(); this.rulesById[this.draggingRulePrevious].showDragIndicator();
} }
} }
}; };
/** /**
* Handles the mouseup event that corresponds to the user dropping the rule * Handles the mouseup event that corresponds to the user dropping the rule
* in its final location. Invokes any registered drop callbacks with the dragged * in its final location. Invokes any registered drop callbacks with the dragged
* rule's ID and the ID of the target rule that the dragged rule should be * rule's ID and the ID of the target rule that the dragged rule should be
* inserted after * inserted after
* @param {Event} event The mouseup event that triggered this callback * @param {Event} event The mouseup event that triggered this callback
*/ */
WidgetDnD.prototype.drop = function (event) { WidgetDnD.prototype.drop = function (event) {
let dropTarget = this.getDropLocation(event); let dropTarget = this.getDropLocation(event);
const draggingId = this.draggingId; const draggingId = this.draggingId;
@ -159,7 +159,4 @@ define([
this.draggingRulePrevious = ''; this.draggingRulePrevious = '';
this.imageContainer.hide(); this.imageContainer.hide();
} }
}; };
return WidgetDnD;
});

View File

@ -20,9 +20,8 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { const helperFunctions = {
const helperFunctions = { listenTo(object, event, callback, context) {
listenTo: function (object, event, callback, context) {
if (!this._listeningTo) { if (!this._listeningTo) {
this._listeningTo = []; this._listeningTo = [];
} }
@ -48,7 +47,7 @@ define([], function () {
this._listeningTo.push(listener); this._listeningTo.push(listener);
}, },
stopListening: function (object, event, callback, context) { stopListening(object, event, callback, context) {
if (!this._listeningTo) { if (!this._listeningTo) {
this._listeningTo = []; this._listeningTo = [];
} }
@ -93,7 +92,6 @@ define([], function () {
object.listenTo = helperFunctions.listenTo; object.listenTo = helperFunctions.listenTo;
object.stopListening = helperFunctions.stopListening; object.stopListening = helperFunctions.stopListening;
} }
}; };
return helperFunctions; export default helperFunctions;
});

View File

@ -1,6 +1,7 @@
define(['./Palette'], function (Palette) { import Palette from './Palette';
//The colors that will be used to instantiate this palette if none are provided
const DEFAULT_COLORS = [ // The colors that will be used to instantiate this palette if none are provided
const DEFAULT_COLORS = [
'#000000', '#000000',
'#434343', '#434343',
'#666666', '#666666',
@ -81,9 +82,9 @@ define(['./Palette'], function (Palette) {
'#073763', '#073763',
'#20124d', '#20124d',
'#4c1130' '#4c1130'
]; ];
/** /**
* Instantiates a new Open MCT Color Palette input * Instantiates a new Open MCT Color Palette input
* @constructor * @constructor
* @param {string} cssClass The class name of the icon which should be applied * @param {string} cssClass The class name of the icon which should be applied
@ -91,7 +92,7 @@ define(['./Palette'], function (Palette) {
* @param {Element} container The view that contains this palette * @param {Element} container The view that contains this palette
* @param {string[]} colors (optional) A list of colors that should be used to instantiate this palette * @param {string[]} colors (optional) A list of colors that should be used to instantiate this palette
*/ */
function ColorPalette(cssClass, container, colors) { export default function ColorPalette(cssClass, container, colors) {
this.colors = colors || DEFAULT_COLORS; this.colors = colors || DEFAULT_COLORS;
this.palette = new Palette(cssClass, container, this.colors); this.palette = new Palette(cssClass, container, this.colors);
@ -122,7 +123,4 @@ define(['./Palette'], function (Palette) {
this.palette.on('change', updateSwatch); this.palette.on('change', updateSwatch);
return this.palette; return this.palette;
} }
return ColorPalette;
});

View File

@ -1,6 +1,7 @@
define(['./Palette'], function (Palette) { import Palette from './Palette';
//The icons that will be used to instantiate this palette if none are provided
const DEFAULT_ICONS = [ //The icons that will be used to instantiate this palette if none are provided
const DEFAULT_ICONS = [
'icon-alert-rect', 'icon-alert-rect',
'icon-alert-triangle', 'icon-alert-triangle',
'icon-arrow-down', 'icon-arrow-down',
@ -25,9 +26,9 @@ define(['./Palette'], function (Palette) {
'icon-plus', 'icon-plus',
'icon-trash', 'icon-trash',
'icon-x' 'icon-x'
]; ];
/** /**
* Instantiates a new Open MCT Icon Palette input * Instantiates a new Open MCT Icon Palette input
* @constructor * @constructor
* @param {string} cssClass The class name of the icon which should be applied * @param {string} cssClass The class name of the icon which should be applied
@ -35,7 +36,7 @@ define(['./Palette'], function (Palette) {
* @param {Element} container The view that contains this palette * @param {Element} container The view that contains this palette
* @param {string[]} icons (optional) A list of icons that should be used to instantiate this palette * @param {string[]} icons (optional) A list of icons that should be used to instantiate this palette
*/ */
function IconPalette(cssClass, container, icons) { export default function IconPalette(cssClass, container, icons) {
this.icons = icons || DEFAULT_ICONS; this.icons = icons || DEFAULT_ICONS;
this.palette = new Palette(cssClass, container, this.icons); this.palette = new Palette(cssClass, container, this.icons);
@ -71,7 +72,4 @@ define(['./Palette'], function (Palette) {
this.palette.on('change', updateSwatch); this.palette.on('change', updateSwatch);
return this.palette; return this.palette;
} }
return IconPalette;
});

View File

@ -1,5 +1,6 @@
define(['./Select'], function (Select) { import Select from './Select';
/**
/**
* Create a {Select} element whose composition is dynamically updated with * Create a {Select} element whose composition is dynamically updated with
* the telemetry fields of a particular domain object * the telemetry fields of a particular domain object
* @constructor * @constructor
@ -13,9 +14,9 @@ define(['./Select'], function (Select) {
* @param {function} changeCallback A change event callback to register with this * @param {function} changeCallback A change event callback to register with this
* select on initialization * select on initialization
*/ */
const NULLVALUE = '- Select Field -'; const NULLVALUE = '- Select Field -';
function KeySelect(config, objectSelect, manager, changeCallback) { export default function KeySelect(config, objectSelect, manager, changeCallback) {
const self = this; const self = this;
this.config = config; this.config = config;
@ -68,12 +69,12 @@ define(['./Select'], function (Select) {
this.manager.on('metadata', onMetadataLoad); this.manager.on('metadata', onMetadataLoad);
return this.select; return this.select;
} }
/** /**
* Populate this select with options based on its current composition * Populate this select with options based on its current composition
*/ */
KeySelect.prototype.generateOptions = function () { KeySelect.prototype.generateOptions = function () {
const items = Object.entries(this.telemetryMetadata).map(function (metaDatum) { const items = Object.entries(this.telemetryMetadata).map(function (metaDatum) {
return [metaDatum[0], metaDatum[1].name]; return [metaDatum[0], metaDatum[1].name];
}); });
@ -85,11 +86,8 @@ define(['./Select'], function (Select) {
} else if (this.select.options.length > 1) { } else if (this.select.options.length > 1) {
this.select.show(); this.select.show();
} }
}; };
KeySelect.prototype.destroy = function () { KeySelect.prototype.destroy = function () {
this.objectSelect.destroy(); this.objectSelect.destroy();
}; };
return KeySelect;
});

View File

@ -1,5 +1,8 @@
define(['./Select', 'objectUtils'], function (Select, objectUtils) { import objectUtils from 'objectUtils';
/**
import Select from './Select';
/**
* Create a {Select} element whose composition is dynamically updated with * Create a {Select} element whose composition is dynamically updated with
* the current composition of the Summary Widget * the current composition of the Summary Widget
* @constructor * @constructor
@ -10,7 +13,7 @@ define(['./Select', 'objectUtils'], function (Select, objectUtils) {
* @param {string[][]} baseOptions A set of [value, label] keyword pairs to * @param {string[][]} baseOptions A set of [value, label] keyword pairs to
* display regardless of the composition state * display regardless of the composition state
*/ */
function ObjectSelect(config, manager, baseOptions) { export default function ObjectSelect(config, manager, baseOptions) {
const self = this; const self = this;
this.config = config; this.config = config;
@ -67,12 +70,12 @@ define(['./Select', 'objectUtils'], function (Select, objectUtils) {
} }
return this.select; return this.select;
} }
/** /**
* Populate this select with options based on its current composition * Populate this select with options based on its current composition
*/ */
ObjectSelect.prototype.generateOptions = function () { ObjectSelect.prototype.generateOptions = function () {
const items = Object.values(this.compositionObjs).map(function (obj) { const items = Object.values(this.compositionObjs).map(function (obj) {
return [objectUtils.makeKeyString(obj.identifier), obj.name]; return [objectUtils.makeKeyString(obj.identifier), obj.name];
}); });
@ -80,7 +83,4 @@ define(['./Select', 'objectUtils'], function (Select, objectUtils) {
items.splice(index, 0, option); items.splice(index, 0, option);
}); });
this.select.setOptions(items); this.select.setOptions(items);
}; };
return ObjectSelect;
});

View File

@ -1,5 +1,7 @@
define(['./Select', '../eventHelpers'], function (Select, eventHelpers) { import eventHelpers from '../eventHelpers';
/** import Select from './Select';
/**
* Create a {Select} element whose composition is dynamically updated with * Create a {Select} element whose composition is dynamically updated with
* the operations applying to a particular telemetry property * the operations applying to a particular telemetry property
* @constructor * @constructor
@ -13,9 +15,9 @@ define(['./Select', '../eventHelpers'], function (Select, eventHelpers) {
* @param {function} changeCallback A change event callback to register with this * @param {function} changeCallback A change event callback to register with this
* select on initialization * select on initialization
*/ */
const NULLVALUE = '- Select Comparison -'; const NULLVALUE = '- Select Comparison -';
function OperationSelect(config, keySelect, manager, changeCallback) { export default function OperationSelect(config, keySelect, manager, changeCallback) {
eventHelpers.extend(this); eventHelpers.extend(this);
const self = this; const self = this;
@ -73,12 +75,12 @@ define(['./Select', '../eventHelpers'], function (Select, eventHelpers) {
} }
return this.select; return this.select;
} }
/** /**
* Populate this select with options based on its current composition * Populate this select with options based on its current composition
*/ */
OperationSelect.prototype.generateOptions = function () { OperationSelect.prototype.generateOptions = function () {
const self = this; const self = this;
const items = this.operationKeys.map(function (operation) { const items = this.operationKeys.map(function (operation) {
return [operation, self.evaluator.getOperationText(operation)]; return [operation, self.evaluator.getOperationText(operation)];
@ -91,14 +93,14 @@ define(['./Select', '../eventHelpers'], function (Select, eventHelpers) {
} else { } else {
this.select.show(); this.select.show();
} }
}; };
/** /**
* Retrieve the data type associated with a given telemetry property and * Retrieve the data type associated with a given telemetry property and
* the applicable operations from the {ConditionEvaluator} * the applicable operations from the {ConditionEvaluator}
* @param {string} key The telemetry property to load operations for * @param {string} key The telemetry property to load operations for
*/ */
OperationSelect.prototype.loadOptions = function (key) { OperationSelect.prototype.loadOptions = function (key) {
const self = this; const self = this;
const operations = self.evaluator.getOperationKeys(); const operations = self.evaluator.getOperationKeys();
let type; let type;
@ -110,11 +112,8 @@ define(['./Select', '../eventHelpers'], function (Select, eventHelpers) {
return self.evaluator.operationAppliesTo(operation, type); return self.evaluator.operationAppliesTo(operation, type);
}); });
} }
}; };
OperationSelect.prototype.destroy = function () { OperationSelect.prototype.destroy = function () {
this.stopListening(); this.stopListening();
}; };
return OperationSelect;
});

View File

@ -1,10 +1,10 @@
define([ import EventEmitter from 'EventEmitter';
'../eventHelpers',
'../../res/input/paletteTemplate.html', import * as templateHelpers from '../../../../utils/template/templateHelpers';
'../../../../utils/template/templateHelpers', import paletteTemplate from '../../res/input/paletteTemplate.html';
'EventEmitter' import eventHelpers from '../eventHelpers';
], function (eventHelpers, paletteTemplate, templateHelpers, EventEmitter) {
/** /**
* Instantiates a new Open MCT Color Palette input * Instantiates a new Open MCT Color Palette input
* @constructor * @constructor
* @param {string} cssClass The class name of the icon which should be applied * @param {string} cssClass The class name of the icon which should be applied
@ -14,7 +14,7 @@ define([
* palette item in the view; how this data is represented is * palette item in the view; how this data is represented is
* up to the descendent class * up to the descendent class
*/ */
function Palette(cssClass, container, items) { export default function Palette(cssClass, container, items) {
eventHelpers.extend(this); eventHelpers.extend(this);
const self = this; const self = this;
@ -77,56 +77,56 @@ define([
self.domElement.querySelectorAll('.c-palette__item').forEach((item) => { self.domElement.querySelectorAll('.c-palette__item').forEach((item) => {
this.listenTo(item, 'click', handleItemClick); this.listenTo(item, 'click', handleItemClick);
}); });
} }
/** /**
* Get the DOM element representing this palette in the view * Get the DOM element representing this palette in the view
*/ */
Palette.prototype.getDOM = function () { Palette.prototype.getDOM = function () {
return this.domElement; return this.domElement;
}; };
/** /**
* Clean up any event listeners registered to DOM elements external to the widget * Clean up any event listeners registered to DOM elements external to the widget
*/ */
Palette.prototype.destroy = function () { Palette.prototype.destroy = function () {
this.stopListening(); this.stopListening();
}; };
Palette.prototype.hideMenu = function () { Palette.prototype.hideMenu = function () {
this.domElement.querySelector('.c-menu').style.display = 'none'; this.domElement.querySelector('.c-menu').style.display = 'none';
}; };
/** /**
* Register a callback with this palette: supported callback is change * Register a callback with this palette: supported callback is change
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
* @param {function} callback The function that this rule will invoke on this event * @param {function} callback The function that this rule will invoke on this event
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
Palette.prototype.on = function (event, callback, context) { Palette.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} else { } else {
throw new Error('Unsupported event type: ' + event); throw new Error('Unsupported event type: ' + event);
} }
}; };
/** /**
* Get the currently selected value of this palette * Get the currently selected value of this palette
* @return {string} The selected value * @return {string} The selected value
*/ */
Palette.prototype.getCurrent = function () { Palette.prototype.getCurrent = function () {
return this.value; return this.value;
}; };
/** /**
* Set the selected value of this palette; if the item doesn't exist in the * Set the selected value of this palette; if the item doesn't exist in the
* palette's data model, the selected value will not change. Invokes any * palette's data model, the selected value will not change. Invokes any
* change callbacks associated with this palette. * change callbacks associated with this palette.
* @param {string} item The key of the item to set as selected * @param {string} item The key of the item to set as selected
*/ */
Palette.prototype.set = function (item) { Palette.prototype.set = function (item) {
const self = this; const self = this;
if (this.items.includes(item) || item === this.nullOption) { if (this.items.includes(item) || item === this.nullOption) {
this.value = item; this.value = item;
@ -138,12 +138,12 @@ define([
} }
this.eventEmitter.emit('change', self.value); this.eventEmitter.emit('change', self.value);
}; };
/** /**
* Update the view associated with the currently selected item * Update the view associated with the currently selected item
*/ */
Palette.prototype.updateSelected = function (item) { Palette.prototype.updateSelected = function (item) {
this.domElement.querySelectorAll('.c-palette__item').forEach((paletteItem) => { this.domElement.querySelectorAll('.c-palette__item').forEach((paletteItem) => {
if (paletteItem.classList.contains('is-selected')) { if (paletteItem.classList.contains('is-selected')) {
paletteItem.classList.remove('is-selected'); paletteItem.classList.remove('is-selected');
@ -155,22 +155,22 @@ define([
} else { } else {
this.domElement.querySelector('.t-swatch').classList.remove('no-selection'); this.domElement.querySelector('.t-swatch').classList.remove('no-selection');
} }
}; };
/** /**
* set the property to be used for the 'no selection' item. If not set, this * set the property to be used for the 'no selection' item. If not set, this
* defaults to a single space * defaults to a single space
* @param {string} item The key to use as the 'no selection' item * @param {string} item The key to use as the 'no selection' item
*/ */
Palette.prototype.setNullOption = function (item) { Palette.prototype.setNullOption = function (item) {
this.nullOption = item; this.nullOption = item;
this.itemElements.nullOption.data = { item: item }; this.itemElements.nullOption.data = { item: item };
}; };
/** /**
* Hides the 'no selection' option to be hidden in the view if it doesn't apply * Hides the 'no selection' option to be hidden in the view if it doesn't apply
*/ */
Palette.prototype.toggleNullOption = function () { Palette.prototype.toggleNullOption = function () {
const elem = this.domElement.querySelector('.c-palette__item-none'); const elem = this.domElement.querySelector('.c-palette__item-none');
if (elem.style.display === 'none') { if (elem.style.display === 'none') {
@ -178,7 +178,4 @@ define([
} else { } else {
this.domElement.querySelector('.c-palette__item-none').style.display = 'none'; this.domElement.querySelector('.c-palette__item-none').style.display = 'none';
} }
}; };
return Palette;
});

View File

@ -1,15 +1,15 @@
define([ import EventEmitter from 'EventEmitter';
'../eventHelpers',
'../../res/input/selectTemplate.html', import * as templateHelpers from '../../../../utils/template/templateHelpers';
'../../../../utils/template/templateHelpers', import selectTemplate from '../../res/input/selectTemplate.html';
'EventEmitter' import eventHelpers from '../eventHelpers';
], function (eventHelpers, selectTemplate, templateHelpers, EventEmitter) {
/** /**
* Wraps an HTML select element, and provides methods for dynamically altering * Wraps an HTML select element, and provides methods for dynamically altering
* its composition from the data model * its composition from the data model
* @constructor * @constructor
*/ */
function Select() { export default function Select() {
eventHelpers.extend(this); eventHelpers.extend(this);
const self = this; const self = this;
@ -36,50 +36,50 @@ define([
} }
this.listenTo(this.domElement.querySelector('select'), 'change', onChange, this); this.listenTo(this.domElement.querySelector('select'), 'change', onChange, this);
} }
/** /**
* Get the DOM element representing this Select in the view * Get the DOM element representing this Select in the view
* @return {Element} * @return {Element}
*/ */
Select.prototype.getDOM = function () { Select.prototype.getDOM = function () {
return this.domElement; return this.domElement;
}; };
/** /**
* Register a callback with this select: supported callback is change * Register a callback with this select: supported callback is change
* @param {string} event The key for the event to listen to * @param {string} event The key for the event to listen to
* @param {function} callback The function that this rule will invoke on this event * @param {function} callback The function that this rule will invoke on this event
* @param {Object} context A reference to a scope to use as the context for * @param {Object} context A reference to a scope to use as the context for
* context for the callback function * context for the callback function
*/ */
Select.prototype.on = function (event, callback, context) { Select.prototype.on = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.on(event, callback, context || this); this.eventEmitter.on(event, callback, context || this);
} else { } else {
throw new Error('Unsupported event type' + event); throw new Error('Unsupported event type' + event);
} }
}; };
/** /**
* Unregister a callback from this select. * Unregister a callback from this select.
* @param {string} event The key for the event to stop listening to * @param {string} event The key for the event to stop listening to
* @param {function} callback The function to unregister * @param {function} callback The function to unregister
* @param {Object} context A reference to a scope to use as the context for the callback function * @param {Object} context A reference to a scope to use as the context for the callback function
*/ */
Select.prototype.off = function (event, callback, context) { Select.prototype.off = function (event, callback, context) {
if (this.supportedCallbacks.includes(event)) { if (this.supportedCallbacks.includes(event)) {
this.eventEmitter.off(event, callback, context || this); this.eventEmitter.off(event, callback, context || this);
} else { } else {
throw new Error('Unsupported event type: ' + event); throw new Error('Unsupported event type: ' + event);
} }
}; };
/** /**
* Update the select element in the view from the current state of the data * Update the select element in the view from the current state of the data
* model * model
*/ */
Select.prototype.populate = function () { Select.prototype.populate = function () {
const self = this; const self = this;
let selectedIndex = 0; let selectedIndex = 0;
@ -96,34 +96,34 @@ define([
}); });
this.domElement.querySelector('select').selectedIndex = selectedIndex; this.domElement.querySelector('select').selectedIndex = selectedIndex;
}; };
/** /**
* Add a single option to this select * Add a single option to this select
* @param {string} value The value for the new option * @param {string} value The value for the new option
* @param {string} label The human-readable text for the new option * @param {string} label The human-readable text for the new option
*/ */
Select.prototype.addOption = function (value, label) { Select.prototype.addOption = function (value, label) {
this.options.push([value, label]); this.options.push([value, label]);
this.populate(); this.populate();
}; };
/** /**
* Set the available options for this select. Replaces any existing options * Set the available options for this select. Replaces any existing options
* @param {string[][]} options An array of [value, label] pairs to display * @param {string[][]} options An array of [value, label] pairs to display
*/ */
Select.prototype.setOptions = function (options) { Select.prototype.setOptions = function (options) {
this.options = options; this.options = options;
this.populate(); this.populate();
}; };
/** /**
* Sets the currently selected element an invokes any registered change * Sets the currently selected element an invokes any registered change
* callbacks with the new value. If the value doesn't exist in this select's * callbacks with the new value. If the value doesn't exist in this select's
* model, its state will not change. * model, its state will not change.
* @param {string} value The value to set as the selected option * @param {string} value The value to set as the selected option
*/ */
Select.prototype.setSelected = function (value) { Select.prototype.setSelected = function (value) {
let selectedIndex = 0; let selectedIndex = 0;
let selectedOption; let selectedOption;
@ -136,33 +136,30 @@ define([
selectedOption = this.options[selectedIndex]; selectedOption = this.options[selectedIndex];
this.eventEmitter.emit('change', selectedOption[0]); this.eventEmitter.emit('change', selectedOption[0]);
}; };
/** /**
* Get the value of the currently selected item * Get the value of the currently selected item
* @return {string} * @return {string}
*/ */
Select.prototype.getSelected = function () { Select.prototype.getSelected = function () {
return this.domElement.querySelector('select').value; return this.domElement.querySelector('select').value;
}; };
Select.prototype.hide = function () { Select.prototype.hide = function () {
this.domElement.classList.add('hidden'); this.domElement.classList.add('hidden');
if (this.domElement.querySelector('.equal-to')) { if (this.domElement.querySelector('.equal-to')) {
this.domElement.querySelector('.equal-to').classList.add('hidden'); this.domElement.querySelector('.equal-to').classList.add('hidden');
} }
}; };
Select.prototype.show = function () { Select.prototype.show = function () {
this.domElement.classList.remove('hidden'); this.domElement.classList.remove('hidden');
if (this.domElement.querySelector('.equal-to')) { if (this.domElement.querySelector('.equal-to')) {
this.domElement.querySelector('.equal-to').classList.remove('hidden'); this.domElement.querySelector('.equal-to').classList.remove('hidden');
} }
}; };
Select.prototype.destroy = function () { Select.prototype.destroy = function () {
this.stopListening(); this.stopListening();
}; };
return Select;
});

View File

@ -20,14 +20,17 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetEvaluator', 'objectUtils'], function (SummaryWidgetEvaluator, objectUtils) { import objectUtils from 'objectUtils';
function EvaluatorPool(openmct) {
import SummaryWidgetEvaluator from './SummaryWidgetEvaluator';
export default function EvaluatorPool(openmct) {
this.openmct = openmct; this.openmct = openmct;
this.byObjectId = {}; this.byObjectId = {};
this.byEvaluator = new WeakMap(); this.byEvaluator = new WeakMap();
} }
EvaluatorPool.prototype.get = function (domainObject) { EvaluatorPool.prototype.get = function (domainObject) {
const objectId = objectUtils.makeKeyString(domainObject.identifier); const objectId = objectUtils.makeKeyString(domainObject.identifier);
let poolEntry = this.byObjectId[objectId]; let poolEntry = this.byObjectId[objectId];
if (!poolEntry) { if (!poolEntry) {
@ -43,9 +46,9 @@ define(['./SummaryWidgetEvaluator', 'objectUtils'], function (SummaryWidgetEvalu
poolEntry.leases += 1; poolEntry.leases += 1;
return poolEntry.evaluator; return poolEntry.evaluator;
}; };
EvaluatorPool.prototype.release = function (evaluator) { EvaluatorPool.prototype.release = function (evaluator) {
const poolEntry = this.byEvaluator.get(evaluator); const poolEntry = this.byEvaluator.get(evaluator);
poolEntry.leases -= 1; poolEntry.leases -= 1;
if (poolEntry.leases === 0) { if (poolEntry.leases === 0) {
@ -53,7 +56,4 @@ define(['./SummaryWidgetEvaluator', 'objectUtils'], function (SummaryWidgetEvalu
this.byEvaluator.delete(evaluator); this.byEvaluator.delete(evaluator);
delete this.byObjectId[poolEntry.objectId]; delete this.byObjectId[poolEntry.objectId];
} }
}; };
return EvaluatorPool;
});

View File

@ -20,11 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./EvaluatorPool', './SummaryWidgetEvaluator'], function ( import EvaluatorPool from './EvaluatorPool';
EvaluatorPool,
SummaryWidgetEvaluator describe('EvaluatorPool', function () {
) {
describe('EvaluatorPool', function () {
let pool; let pool;
let openmct; let openmct;
let objectA; let objectA;
@ -93,5 +91,4 @@ define(['./EvaluatorPool', './SummaryWidgetEvaluator'], function (
const evaluatorC = pool.get(objectA); const evaluatorC = pool.get(objectA);
expect(evaluatorA).not.toBe(evaluatorC); expect(evaluatorA).not.toBe(evaluatorC);
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./operations'], function (OPERATIONS) { import OPERATIONS from './operations';
function SummaryWidgetCondition(definition) {
export default function SummaryWidgetCondition(definition) {
this.object = definition.object; this.object = definition.object;
this.key = definition.key; this.key = definition.key;
this.values = definition.values; this.values = definition.values;
@ -33,9 +34,9 @@ define(['./operations'], function (OPERATIONS) {
} else { } else {
this.comparator = OPERATIONS[definition.operation].operation; this.comparator = OPERATIONS[definition.operation].operation;
} }
} }
SummaryWidgetCondition.prototype.evaluate = function (telemetryState) { SummaryWidgetCondition.prototype.evaluate = function (telemetryState) {
const stateKeys = Object.keys(telemetryState); const stateKeys = Object.keys(telemetryState);
let state; let state;
let result; let result;
@ -64,13 +65,10 @@ define(['./operations'], function (OPERATIONS) {
} else { } else {
return this.evaluateState(telemetryState[this.object]); return this.evaluateState(telemetryState[this.object]);
} }
}; };
SummaryWidgetCondition.prototype.evaluateState = function (state) { SummaryWidgetCondition.prototype.evaluateState = function (state) {
const testValues = [state.formats[this.key].parse(state.lastDatum)].concat(this.values); const testValues = [state.formats[this.key].parse(state.lastDatum)].concat(this.values);
return this.comparator(testValues); return this.comparator(testValues);
}; };
return SummaryWidgetCondition;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetCondition'], function (SummaryWidgetCondition) { import SummaryWidgetCondition from './SummaryWidgetCondition';
describe('SummaryWidgetCondition', function () {
describe('SummaryWidgetCondition', function () {
let condition; let condition;
let telemetryState; let telemetryState;
@ -121,5 +122,4 @@ define(['./SummaryWidgetCondition'], function (SummaryWidgetCondition) {
telemetryState.otherObjectId.lastDatum.value = 15; telemetryState.otherObjectId.lastDatum.value = 15;
expect(condition.evaluate(telemetryState)).toBe(true); expect(condition.evaluate(telemetryState)).toBe(true);
}); });
});
}); });

View File

@ -20,18 +20,18 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], function ( import _ from 'lodash';
SummaryWidgetRule, import objectUtils from 'objectUtils';
eventHelpers,
objectUtils, import eventHelpers from '../eventHelpers';
_ import SummaryWidgetRule from './SummaryWidgetRule';
) {
/** /**
* evaluates rules defined in a summary widget against either lad or * evaluates rules defined in a summary widget against either lad or
* realtime state. * realtime state.
* *
*/ */
function SummaryWidgetEvaluator(domainObject, openmct) { export default function SummaryWidgetEvaluator(domainObject, openmct) {
this.openmct = openmct; this.openmct = openmct;
this.baseState = {}; this.baseState = {};
@ -44,14 +44,14 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
this.listenTo(composition, 'remove', this.removeChild, this); this.listenTo(composition, 'remove', this.removeChild, this);
this.loadPromise = composition.load(); this.loadPromise = composition.load();
} }
eventHelpers.extend(SummaryWidgetEvaluator.prototype); eventHelpers.extend(SummaryWidgetEvaluator.prototype);
/** /**
* Subscribes to realtime telemetry for the given summary widget. * Subscribes to realtime telemetry for the given summary widget.
*/ */
SummaryWidgetEvaluator.prototype.subscribe = function (callback) { SummaryWidgetEvaluator.prototype.subscribe = function (callback) {
let active = true; let active = true;
let unsubscribes = []; let unsubscribes = [];
@ -69,10 +69,7 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
}.bind(this); }.bind(this);
/* eslint-disable you-dont-need-lodash-underscore/map */ /* eslint-disable you-dont-need-lodash-underscore/map */
unsubscribes = _.map( unsubscribes = _.map(realtimeStates, this.subscribeToObjectState.bind(this, updateCallback));
realtimeStates,
this.subscribeToObjectState.bind(this, updateCallback)
);
/* eslint-enable you-dont-need-lodash-underscore/map */ /* eslint-enable you-dont-need-lodash-underscore/map */
}.bind(this) }.bind(this)
); );
@ -83,13 +80,13 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
unsubscribe(); unsubscribe();
}); });
}; };
}; };
/** /**
* Returns a promise for a telemetry datum obtained by evaluating the * Returns a promise for a telemetry datum obtained by evaluating the
* current lad data. * current lad data.
*/ */
SummaryWidgetEvaluator.prototype.requestLatest = function (options) { SummaryWidgetEvaluator.prototype.requestLatest = function (options) {
return this.getBaseStateClone() return this.getBaseStateClone()
.then( .then(
function (ladState) { function (ladState) {
@ -107,15 +104,15 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
return this.evaluateState(ladStates, options.domain); return this.evaluateState(ladStates, options.domain);
}.bind(this) }.bind(this)
); );
}; };
SummaryWidgetEvaluator.prototype.updateRules = function (domainObject) { SummaryWidgetEvaluator.prototype.updateRules = function (domainObject) {
this.rules = domainObject.configuration.ruleOrder.map(function (ruleId) { this.rules = domainObject.configuration.ruleOrder.map(function (ruleId) {
return new SummaryWidgetRule(domainObject.configuration.ruleConfigById[ruleId]); return new SummaryWidgetRule(domainObject.configuration.ruleConfigById[ruleId]);
}); });
}; };
SummaryWidgetEvaluator.prototype.addChild = function (childObject) { SummaryWidgetEvaluator.prototype.addChild = function (childObject) {
const childId = objectUtils.makeKeyString(childObject.identifier); const childId = objectUtils.makeKeyString(childObject.identifier);
const metadata = this.openmct.telemetry.getMetadata(childObject); const metadata = this.openmct.telemetry.getMetadata(childObject);
const formats = this.openmct.telemetry.getFormatMap(metadata); const formats = this.openmct.telemetry.getFormatMap(metadata);
@ -126,24 +123,24 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
metadata: metadata, metadata: metadata,
formats: formats formats: formats
}; };
}; };
SummaryWidgetEvaluator.prototype.removeChild = function (childObject) { SummaryWidgetEvaluator.prototype.removeChild = function (childObject) {
const childId = objectUtils.makeKeyString(childObject.identifier); const childId = objectUtils.makeKeyString(childObject.identifier);
delete this.baseState[childId]; delete this.baseState[childId];
}; };
SummaryWidgetEvaluator.prototype.load = function () { SummaryWidgetEvaluator.prototype.load = function () {
return this.loadPromise; return this.loadPromise;
}; };
/** /**
* Return a promise for a 2-deep clone of the base state object: object * Return a promise for a 2-deep clone of the base state object: object
* states are shallow cloned, and then assembled and returned as a new base * states are shallow cloned, and then assembled and returned as a new base
* state. Allows object states to be mutated while sharing telemetry * state. Allows object states to be mutated while sharing telemetry
* metadata and formats. * metadata and formats.
*/ */
SummaryWidgetEvaluator.prototype.getBaseStateClone = function () { SummaryWidgetEvaluator.prototype.getBaseStateClone = function () {
return this.load().then( return this.load().then(
function () { function () {
/* eslint-disable you-dont-need-lodash-underscore/values */ /* eslint-disable you-dont-need-lodash-underscore/values */
@ -151,15 +148,15 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
/* eslint-enable you-dont-need-lodash-underscore/values */ /* eslint-enable you-dont-need-lodash-underscore/values */
}.bind(this) }.bind(this)
); );
}; };
/** /**
* Subscribes to realtime updates for a given objectState, and invokes * Subscribes to realtime updates for a given objectState, and invokes
* the supplied callback when objectState has been updated. Returns * the supplied callback when objectState has been updated. Returns
* a function to unsubscribe. * a function to unsubscribe.
* @private. * @private.
*/ */
SummaryWidgetEvaluator.prototype.subscribeToObjectState = function (callback, objectState) { SummaryWidgetEvaluator.prototype.subscribeToObjectState = function (callback, objectState) {
return this.openmct.telemetry.subscribe( return this.openmct.telemetry.subscribe(
objectState.domainObject, objectState.domainObject,
function (datum) { function (datum) {
@ -168,14 +165,14 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
callback(); callback();
}.bind(this) }.bind(this)
); );
}; };
/** /**
* Given an object state, will return a promise that is resolved when the * Given an object state, will return a promise that is resolved when the
* object state has been updated from the LAD. * object state has been updated from the LAD.
* @private. * @private.
*/ */
SummaryWidgetEvaluator.prototype.updateObjectStateFromLAD = function (options, objectState) { SummaryWidgetEvaluator.prototype.updateObjectStateFromLAD = function (options, objectState) {
options = Object.assign({}, options, { options = Object.assign({}, options, {
strategy: 'latest', strategy: 'latest',
size: 1 size: 1
@ -187,28 +184,27 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
objectState.timestamps = this.getTimestamps(objectState.id, objectState.lastDatum); objectState.timestamps = this.getTimestamps(objectState.id, objectState.lastDatum);
}.bind(this) }.bind(this)
); );
}; };
/** /**
* Returns an object containing all domain values in a datum. * Returns an object containing all domain values in a datum.
* @private. * @private.
*/ */
SummaryWidgetEvaluator.prototype.getTimestamps = function (childId, datum) { SummaryWidgetEvaluator.prototype.getTimestamps = function (childId, datum) {
const timestampedDatum = {}; const timestampedDatum = {};
this.openmct.time.getAllTimeSystems().forEach(function (timeSystem) { this.openmct.time.getAllTimeSystems().forEach(function (timeSystem) {
timestampedDatum[timeSystem.key] = timestampedDatum[timeSystem.key] = this.baseState[childId].formats[timeSystem.key].parse(datum);
this.baseState[childId].formats[timeSystem.key].parse(datum);
}, this); }, this);
return timestampedDatum; return timestampedDatum;
}; };
/** /**
* Given a base datum(containing timestamps) and rule index, adds values * Given a base datum(containing timestamps) and rule index, adds values
* from the matching rule. * from the matching rule.
* @private * @private
*/ */
SummaryWidgetEvaluator.prototype.makeDatumFromRule = function (ruleIndex, baseDatum) { SummaryWidgetEvaluator.prototype.makeDatumFromRule = function (ruleIndex, baseDatum) {
const rule = this.rules[ruleIndex]; const rule = this.rules[ruleIndex];
baseDatum.ruleLabel = rule.label; baseDatum.ruleLabel = rule.label;
@ -221,16 +217,16 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
baseDatum.icon = rule.icon; baseDatum.icon = rule.icon;
return baseDatum; return baseDatum;
}; };
/** /**
* Evaluate a `state` object and return a summary widget telemetry datum. * Evaluate a `state` object and return a summary widget telemetry datum.
* Datum timestamps will be taken from the "latest" datum in the `state` * Datum timestamps will be taken from the "latest" datum in the `state`
* where "latest" is the datum with the largest value for the given * where "latest" is the datum with the largest value for the given
* `timestampKey`. * `timestampKey`.
* @private. * @private.
*/ */
SummaryWidgetEvaluator.prototype.evaluateState = function (state, timestampKey) { SummaryWidgetEvaluator.prototype.evaluateState = function (state, timestampKey) {
const hasRequiredData = Object.keys(state).reduce(function (itDoes, k) { const hasRequiredData = Object.keys(state).reduce(function (itDoes, k) {
return itDoes && state[k].lastDatum; return itDoes && state[k].lastDatum;
}, true); }, true);
@ -256,15 +252,12 @@ define(['./SummaryWidgetRule', '../eventHelpers', 'objectUtils', 'lodash'], func
const baseDatum = _.clone(latestTimestamp); const baseDatum = _.clone(latestTimestamp);
return this.makeDatumFromRule(i, baseDatum); return this.makeDatumFromRule(i, baseDatum);
}; };
/** /**
* remove all listeners and clean up any resources. * remove all listeners and clean up any resources.
*/ */
SummaryWidgetEvaluator.prototype.destroy = function () { SummaryWidgetEvaluator.prototype.destroy = function () {
this.stopListening(); this.stopListening();
this.removeObserver(); this.removeObserver();
}; };
return SummaryWidgetEvaluator;
});

View File

@ -20,16 +20,15 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function SummaryWidgetMetadataProvider(openmct) {
function SummaryWidgetMetadataProvider(openmct) {
this.openmct = openmct; this.openmct = openmct;
} }
SummaryWidgetMetadataProvider.prototype.supportsMetadata = function (domainObject) { SummaryWidgetMetadataProvider.prototype.supportsMetadata = function (domainObject) {
return domainObject.type === 'summary-widget'; return domainObject.type === 'summary-widget';
}; };
SummaryWidgetMetadataProvider.prototype.getDomains = function (domainObject) { SummaryWidgetMetadataProvider.prototype.getDomains = function (domainObject) {
return this.openmct.time.getAllTimeSystems().map(function (ts, i) { return this.openmct.time.getAllTimeSystems().map(function (ts, i) {
return { return {
key: ts.key, key: ts.key,
@ -40,9 +39,9 @@ define([], function () {
} }
}; };
}); });
}; };
SummaryWidgetMetadataProvider.prototype.getMetadata = function (domainObject) { SummaryWidgetMetadataProvider.prototype.getMetadata = function (domainObject) {
const ruleOrder = domainObject.configuration.ruleOrder || []; const ruleOrder = domainObject.configuration.ruleOrder || [];
const enumerations = ruleOrder const enumerations = ruleOrder
.filter(function (ruleId) { .filter(function (ruleId) {
@ -107,7 +106,4 @@ define([], function () {
}; };
return metadata; return metadata;
}; };
return SummaryWidgetMetadataProvider;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetCondition'], function (SummaryWidgetCondition) { import SummaryWidgetCondition from './SummaryWidgetCondition';
function SummaryWidgetRule(definition) {
export default function SummaryWidgetRule(definition) {
this.name = definition.name; this.name = definition.name;
this.label = definition.label; this.label = definition.label;
this.id = definition.id; this.id = definition.id;
@ -33,13 +34,13 @@ define(['./SummaryWidgetCondition'], function (SummaryWidgetCondition) {
return new SummaryWidgetCondition(cDefinition); return new SummaryWidgetCondition(cDefinition);
}); });
this.trigger = definition.trigger; this.trigger = definition.trigger;
} }
/** /**
* Evaluate the given rule against a telemetryState and return true if it * Evaluate the given rule against a telemetryState and return true if it
* matches. * matches.
*/ */
SummaryWidgetRule.prototype.evaluate = function (telemetryState) { SummaryWidgetRule.prototype.evaluate = function (telemetryState) {
let i; let i;
let result; let result;
@ -64,7 +65,4 @@ define(['./SummaryWidgetCondition'], function (SummaryWidgetCondition) {
} else { } else {
throw new Error('Invalid rule trigger: ' + this.trigger); throw new Error('Invalid rule trigger: ' + this.trigger);
} }
}; };
return SummaryWidgetRule;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetRule'], function (SummaryWidgetRule) { import SummaryWidgetRule from './SummaryWidgetRule';
describe('SummaryWidgetRule', function () {
describe('SummaryWidgetRule', function () {
let rule; let rule;
let telemetryState; let telemetryState;
@ -149,5 +150,4 @@ define(['./SummaryWidgetRule'], function (SummaryWidgetRule) {
telemetryState.otherObjectId.lastDatum.value = 25; telemetryState.otherObjectId.lastDatum.value = 25;
expect(rule.evaluate(telemetryState)).toBe(true); expect(rule.evaluate(telemetryState)).toBe(true);
}); });
});
}); });

View File

@ -20,16 +20,17 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./EvaluatorPool'], function (EvaluatorPool) { import EvaluatorPool from './EvaluatorPool';
function SummaryWidgetTelemetryProvider(openmct) {
export default function SummaryWidgetTelemetryProvider(openmct) {
this.pool = new EvaluatorPool(openmct); this.pool = new EvaluatorPool(openmct);
} }
SummaryWidgetTelemetryProvider.prototype.supportsRequest = function (domainObject, options) { SummaryWidgetTelemetryProvider.prototype.supportsRequest = function (domainObject, options) {
return domainObject.type === 'summary-widget'; return domainObject.type === 'summary-widget';
}; };
SummaryWidgetTelemetryProvider.prototype.request = function (domainObject, options) { SummaryWidgetTelemetryProvider.prototype.request = function (domainObject, options) {
if (options.strategy !== 'latest' && options.size !== 1) { if (options.strategy !== 'latest' && options.size !== 1) {
return Promise.resolve([]); return Promise.resolve([]);
} }
@ -43,13 +44,13 @@ define(['./EvaluatorPool'], function (EvaluatorPool) {
return latestDatum ? [latestDatum] : []; return latestDatum ? [latestDatum] : [];
}.bind(this) }.bind(this)
); );
}; };
SummaryWidgetTelemetryProvider.prototype.supportsSubscribe = function (domainObject) { SummaryWidgetTelemetryProvider.prototype.supportsSubscribe = function (domainObject) {
return domainObject.type === 'summary-widget'; return domainObject.type === 'summary-widget';
}; };
SummaryWidgetTelemetryProvider.prototype.subscribe = function (domainObject, callback) { SummaryWidgetTelemetryProvider.prototype.subscribe = function (domainObject, callback) {
const evaluator = this.pool.get(domainObject); const evaluator = this.pool.get(domainObject);
const unsubscribe = evaluator.subscribe(callback); const unsubscribe = evaluator.subscribe(callback);
@ -57,7 +58,4 @@ define(['./EvaluatorPool'], function (EvaluatorPool) {
this.pool.release(evaluator); this.pool.release(evaluator);
unsubscribe(); unsubscribe();
}.bind(this); }.bind(this);
}; };
return SummaryWidgetTelemetryProvider;
});

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./SummaryWidgetTelemetryProvider'], function (SummaryWidgetTelemetryProvider) { import SummaryWidgetTelemetryProvider from './SummaryWidgetTelemetryProvider';
xdescribe('SummaryWidgetTelemetryProvider', function () {
xdescribe('SummaryWidgetTelemetryProvider', function () {
let telemObjectA; let telemObjectA;
let telemObjectB; let telemObjectB;
let summaryWidgetObject; let summaryWidgetObject;
@ -459,5 +460,4 @@ define(['./SummaryWidgetTelemetryProvider'], function (SummaryWidgetTelemetryPro
]); ]);
}); });
}); });
});
}); });

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { const OPERATIONS = {
const OPERATIONS = {
equalTo: { equalTo: {
operation: function (input) { operation: function (input) {
return input[0] === input[1]; return input[0] === input[1];
@ -209,7 +208,6 @@ define([], function () {
return ' != ' + values[0]; return ' != ' + values[0];
} }
} }
}; };
return OPERATIONS; export default OPERATIONS;
});

View File

@ -1,13 +1,30 @@
define(['../SummaryWidget', './SummaryWidgetView', 'objectUtils'], function ( /*****************************************************************************
SummaryWidgetEditView, * Open MCT, Copyright (c) 2014-2023, United States Government
SummaryWidgetView, * as represented by the Administrator of the National Aeronautics and Space
objectUtils * Administration. All rights reserved.
) {
const DEFAULT_VIEW_PRIORITY = 100;
/**
* *
*/ * Open MCT is licensed under the Apache License, Version 2.0 (the
function SummaryWidgetViewProvider(openmct) { * "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 SummaryWidgetEditView from '../SummaryWidget';
import SummaryWidgetView from './SummaryWidgetView';
const DEFAULT_VIEW_PRIORITY = 100;
export default function SummaryWidgetViewProvider(openmct) {
return { return {
key: 'summary-widget-viewer', key: 'summary-widget-viewer',
name: 'Summary View', name: 'Summary View',
@ -32,7 +49,4 @@ define(['../SummaryWidget', './SummaryWidgetView', 'objectUtils'], function (
} }
} }
}; };
} }
return SummaryWidgetViewProvider;
});

View File

@ -1,5 +1,6 @@
define(['../src/ConditionEvaluator'], function (ConditionEvaluator) { import ConditionEvaluator from '../src/ConditionEvaluator';
describe('A Summary Widget Rule Evaluator', function () {
describe('A Summary Widget Rule Evaluator', function () {
let evaluator; let evaluator;
let testEvaluator; let testEvaluator;
let testOperation; let testOperation;
@ -359,5 +360,4 @@ define(['../src/ConditionEvaluator'], function (ConditionEvaluator) {
expect(testEvaluator.getOperationDescription(key, [])).toBeDefined(); expect(testEvaluator.getOperationDescription(key, [])).toBeDefined();
}); });
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['../src/ConditionManager'], function (ConditionManager) { import ConditionManager from '../src/ConditionManager';
describe('A Summary Widget Condition Manager', function () {
describe('A Summary Widget Condition Manager', function () {
let conditionManager; let conditionManager;
let mockDomainObject; let mockDomainObject;
let mockCompObject1; let mockCompObject1;
@ -180,12 +181,7 @@ define(['../src/ConditionManager'], function (ConditionManager) {
} }
}; };
mockComposition = jasmine.createSpyObj('composition', [ mockComposition = jasmine.createSpyObj('composition', ['on', 'off', 'load', 'triggerCallback']);
'on',
'off',
'load',
'triggerCallback'
]);
mockComposition.on.and.callFake(function (event, callback, context) { mockComposition.on.and.callFake(function (event, callback, context) {
mockEventCallbacks[event] = callback.bind(context); mockEventCallbacks[event] = callback.bind(context);
}); });
@ -439,5 +435,4 @@ define(['../src/ConditionManager'], function (ConditionManager) {
conditionManager.triggerTelemetryCallback(); conditionManager.triggerTelemetryCallback();
expect(telemetryCallbackSpy).toHaveBeenCalled(); expect(telemetryCallbackSpy).toHaveBeenCalled();
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['../src/Condition'], function (Condition) { import Condition from '../src/Condition';
describe('A summary widget condition', function () {
describe('A summary widget condition', function () {
let testCondition; let testCondition;
let mockConfig; let mockConfig;
let mockConditionManager; let mockConditionManager;
@ -201,5 +202,4 @@ define(['../src/Condition'], function (Condition) {
index: 54 index: 54
}); });
}); });
});
}); });

View File

@ -1,5 +1,28 @@
define(['../src/Rule'], function (Rule) { /*****************************************************************************
describe('A Summary Widget Rule', function () { * Open MCT, Copyright (c) 2014-2023, 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 Rule from '../src/Rule';
describe('A Summary Widget Rule', function () {
let mockRuleConfig; let mockRuleConfig;
let mockDomainObject; let mockDomainObject;
let mockOpenMCT; let mockOpenMCT;
@ -289,5 +312,4 @@ define(['../src/Rule'], function (Rule) {
} }
]); ]);
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['../src/SummaryWidget'], function (SummaryWidget) { import SummaryWidget from '../src/SummaryWidget';
describe('The Summary Widget', function () {
describe('The Summary Widget', function () {
let summaryWidget; let summaryWidget;
let mockDomainObject; let mockDomainObject;
let mockOldDomainObject; let mockOldDomainObject;
@ -188,5 +189,4 @@ define(['../src/SummaryWidget'], function (SummaryWidget) {
expect(widgetButton.href).toEqual('https://www.nasa.gov/'); expect(widgetButton.href).toEqual('https://www.nasa.gov/');
expect(widgetButton.target).toEqual('_blank'); expect(widgetButton.target).toEqual('_blank');
}); });
});
}); });

View File

@ -20,8 +20,9 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['../SummaryWidgetViewPolicy'], function (SummaryWidgetViewPolicy) { import SummaryWidgetViewPolicy from '../SummaryWidgetViewPolicy';
describe('SummaryWidgetViewPolicy', function () {
describe('SummaryWidgetViewPolicy', function () {
let policy; let policy;
let domainObject; let domainObject;
let view; let view;
@ -54,5 +55,4 @@ define(['../SummaryWidgetViewPolicy'], function (SummaryWidgetViewPolicy) {
view.key = 'other view'; view.key = 'other view';
expect(policy.allow(view, domainObject)).toBe(false); expect(policy.allow(view, domainObject)).toBe(false);
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../src/TestDataItem'], function (TestDataItem) { import TestDataItem from '../src/TestDataItem';
describe('A summary widget test data item', function () {
describe('A summary widget test data item', function () {
let testDataItem; let testDataItem;
let mockConfig; let mockConfig;
let mockConditionManager; let mockConditionManager;
@ -163,5 +164,4 @@ define(['../src/TestDataItem'], function (TestDataItem) {
index: 54 index: 54
}); });
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../src/TestDataManager'], function (TestDataManager) { import TestDataManager from '../src/TestDataManager';
describe('A Summary Widget Rule', function () {
describe('A Summary Widget Rule', function () {
let mockDomainObject; let mockDomainObject;
let mockOpenMCT; let mockOpenMCT;
let mockConditionManager; let mockConditionManager;
@ -118,9 +119,7 @@ define(['../src/TestDataManager'], function (TestDataManager) {
it('exposes a DOM element to represent itself in the view', function () { it('exposes a DOM element to represent itself in the view', function () {
mockContainer.append(testDataManager.getDOM()); mockContainer.append(testDataManager.getDOM());
expect(mockContainer.querySelectorAll('.t-widget-test-data-content').length).toBeGreaterThan( expect(mockContainer.querySelectorAll('.t-widget-test-data-content').length).toBeGreaterThan(0);
0
);
}); });
it('generates a test cache in the format expected by a condition evaluator', function () { it('generates a test cache in the format expected by a condition evaluator', function () {
@ -137,10 +136,7 @@ define(['../src/TestDataManager'], function (TestDataManager) {
}); });
}); });
it( it('updates its configuration on a item change and provides an updated cache to the evaluator', function () {
'updates its configuration on a item change and provides an updated' +
'cache to the evaluator',
function () {
testDataManager.onItemChange({ testDataManager.onItemChange({
value: 26, value: 26,
property: 'value', property: 'value',
@ -157,8 +153,7 @@ define(['../src/TestDataManager'], function (TestDataManager) {
property4: 'Text It Is' property4: 'Text It Is'
} }
}); });
} });
);
it('allows initializing a new item with a default configuration', function () { it('allows initializing a new item with a default configuration', function () {
testDataManager.initItem(); testDataManager.initItem();
@ -246,5 +241,4 @@ define(['../src/TestDataManager'], function (TestDataManager) {
}); });
it('exposes a UI element to toggle test data on and off', function () {}); it('exposes a UI element to toggle test data on and off', function () {});
});
}); });

View File

@ -1,5 +1,6 @@
define(['../../src/input/ColorPalette'], function (ColorPalette) { import ColorPalette from '../../src/input/ColorPalette';
describe('An Open MCT color palette', function () {
describe('An Open MCT color palette', function () {
let colorPalette; let colorPalette;
let changeCallback; let changeCallback;
@ -20,5 +21,4 @@ define(['../../src/input/ColorPalette'], function (ColorPalette) {
colorPalette = new ColorPalette('someClass', 'someContainer'); colorPalette = new ColorPalette('someClass', 'someContainer');
expect(colorPalette.getCurrent()).toBeDefined(); expect(colorPalette.getCurrent()).toBeDefined();
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../../src/input/IconPalette'], function (IconPalette) { import IconPalette from '../../src/input/IconPalette';
describe('An Open MCT icon palette', function () {
describe('An Open MCT icon palette', function () {
let iconPalette; let iconPalette;
let changeCallback; let changeCallback;
@ -20,5 +21,4 @@ define(['../../src/input/IconPalette'], function (IconPalette) {
iconPalette = new IconPalette('someClass', 'someContainer'); iconPalette = new IconPalette('someClass', 'someContainer');
expect(iconPalette.getCurrent()).toBeDefined(); expect(iconPalette.getCurrent()).toBeDefined();
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../../src/input/KeySelect'], function (KeySelect) { import KeySelect from '../../src/input/KeySelect';
describe('A select for choosing composition object properties', function () {
describe('A select for choosing composition object properties', function () {
let mockConfig; let mockConfig;
let mockBadConfig; let mockBadConfig;
let mockManager; let mockManager;
@ -119,5 +120,4 @@ define(['../../src/input/KeySelect'], function (KeySelect) {
mockObjectSelect.triggerCallback('change', 'object3'); mockObjectSelect.triggerCallback('change', 'object3');
expect(keySelect.getSelected()).toEqual('a'); expect(keySelect.getSelected()).toEqual('a');
}); });
});
}); });

View File

@ -1,5 +1,28 @@
define(['../../src/input/ObjectSelect'], function (ObjectSelect) { /*****************************************************************************
describe('A select for choosing composition objects', function () { * Open MCT, Copyright (c) 2014-2023, 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 ObjectSelect from '../../src/input/ObjectSelect';
describe('A select for choosing composition objects', function () {
let mockConfig; let mockConfig;
let mockBadConfig; let mockBadConfig;
let mockManager; let mockManager;
@ -108,5 +131,4 @@ define(['../../src/input/ObjectSelect'], function (ObjectSelect) {
mockManager.triggerCallback('remove'); mockManager.triggerCallback('remove');
expect(objectSelect.getSelected()).not.toEqual('key1'); expect(objectSelect.getSelected()).not.toEqual('key1');
}); });
});
}); });

View File

@ -1,5 +1,28 @@
define(['../../src/input/OperationSelect'], function (OperationSelect) { /*****************************************************************************
describe('A select for choosing composition object properties', function () { * Open MCT, Copyright (c) 2014-2023, 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 OperationSelect from '../../src/input/OperationSelect';
describe('A select for choosing composition object properties', function () {
let mockConfig; let mockConfig;
let mockBadConfig; let mockBadConfig;
let mockManager; let mockManager;
@ -139,5 +162,4 @@ define(['../../src/input/OperationSelect'], function (OperationSelect) {
mockKeySelect.triggerCallback('change', 'c'); mockKeySelect.triggerCallback('change', 'c');
expect(operationSelect.getSelected()).toEqual('operation1'); expect(operationSelect.getSelected()).toEqual('operation1');
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../../src/input/Palette'], function (Palette) { import Palette from '../../src/input/Palette';
describe('A generic Open MCT palette input', function () {
describe('A generic Open MCT palette input', function () {
let palette; let palette;
let callbackSpy1; let callbackSpy1;
let callbackSpy2; let callbackSpy2;
@ -40,5 +41,4 @@ define(['../../src/input/Palette'], function (Palette) {
palette.set('foobar'); palette.set('foobar');
expect(palette.getCurrent()).not.toEqual('foobar'); expect(palette.getCurrent()).not.toEqual('foobar');
}); });
});
}); });

View File

@ -1,5 +1,6 @@
define(['../../src/input/Select'], function (Select) { import Select from '../../src/input/Select';
describe('A select wrapper', function () {
describe('A select wrapper', function () {
let select; let select;
let testOptions; let testOptions;
let callbackSpy1; let callbackSpy1;
@ -57,5 +58,4 @@ define(['../../src/input/Select'], function (Select) {
select.setSelected('foobar'); select.setSelected('foobar');
expect(select.getSelected()).not.toEqual('foobar'); expect(select.getSelected()).not.toEqual('foobar');
}); });
});
}); });

View File

@ -19,11 +19,11 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
import Tabs from './tabs';
define(['./tabs'], function (Tabs) { export default function plugin() {
return function plugin() {
return function install(openmct) { return function install(openmct) {
openmct.objectViews.addProvider(new Tabs.default(openmct)); openmct.objectViews.addProvider(new Tabs(openmct));
openmct.types.addType('tabs', { openmct.types.addType('tabs', {
name: 'Tabs View', name: 'Tabs View',
@ -55,5 +55,4 @@ define(['./tabs'], function (Tabs) {
] ]
}); });
}; };
}; }
});

View File

@ -47,7 +47,7 @@ export default class Tabs {
let component = null; let component = null;
return { return {
show: function (element, editMode) { show(element, editMode) {
const { vNode, destroy } = mount( const { vNode, destroy } = mount(
{ {
el: element, el: element,

View File

@ -20,10 +20,11 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./src/MeanTelemetryProvider'], function (MeanTelemetryProvider) { import MeanTelemetryProvider from './src/MeanTelemetryProvider';
const DEFAULT_SAMPLES = 10;
function plugin() { const DEFAULT_SAMPLES = 10;
export default function plugin() {
return function install(openmct) { return function install(openmct) {
openmct.types.addType('telemetry-mean', { openmct.types.addType('telemetry-mean', {
name: 'Telemetry Filter', name: 'Telemetry Filter',
@ -72,7 +73,4 @@ define(['./src/MeanTelemetryProvider'], function (MeanTelemetryProvider) {
}); });
openmct.telemetry.addProvider(new MeanTelemetryProvider(openmct)); openmct.telemetry.addProvider(new MeanTelemetryProvider(openmct));
}; };
} }
return plugin;
});

View File

@ -20,24 +20,27 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['objectUtils', './TelemetryAverager'], function (objectUtils, TelemetryAverager) { import objectUtils from 'objectUtils';
function MeanTelemetryProvider(openmct) {
import TelemetryAverager from './TelemetryAverager';
export default function MeanTelemetryProvider(openmct) {
this.openmct = openmct; this.openmct = openmct;
this.telemetryAPI = openmct.telemetry; this.telemetryAPI = openmct.telemetry;
this.timeAPI = openmct.time; this.timeAPI = openmct.time;
this.objectAPI = openmct.objects; this.objectAPI = openmct.objects;
this.perObjectProviders = {}; this.perObjectProviders = {};
} }
MeanTelemetryProvider.prototype.canProvideTelemetry = function (domainObject) { MeanTelemetryProvider.prototype.canProvideTelemetry = function (domainObject) {
return domainObject.type === 'telemetry-mean'; return domainObject.type === 'telemetry-mean';
}; };
MeanTelemetryProvider.prototype.supportsRequest = MeanTelemetryProvider.prototype.supportsRequest =
MeanTelemetryProvider.prototype.supportsSubscribe = MeanTelemetryProvider.prototype.supportsSubscribe =
MeanTelemetryProvider.prototype.canProvideTelemetry; MeanTelemetryProvider.prototype.canProvideTelemetry;
MeanTelemetryProvider.prototype.subscribe = function (domainObject, callback) { MeanTelemetryProvider.prototype.subscribe = function (domainObject, callback) {
let wrappedUnsubscribe; let wrappedUnsubscribe;
let unsubscribeCalled = false; let unsubscribeCalled = false;
const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint); const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint);
@ -60,9 +63,9 @@ define(['objectUtils', './TelemetryAverager'], function (objectUtils, TelemetryA
wrappedUnsubscribe(); wrappedUnsubscribe();
} }
}; };
}; };
MeanTelemetryProvider.prototype.subscribeToAverage = function (domainObject, samples, callback) { MeanTelemetryProvider.prototype.subscribeToAverage = function (domainObject, samples, callback) {
const telemetryAverager = new TelemetryAverager( const telemetryAverager = new TelemetryAverager(
this.telemetryAPI, this.telemetryAPI,
this.timeAPI, this.timeAPI,
@ -73,9 +76,9 @@ define(['objectUtils', './TelemetryAverager'], function (objectUtils, TelemetryA
const createAverageDatum = telemetryAverager.createAverageDatum.bind(telemetryAverager); const createAverageDatum = telemetryAverager.createAverageDatum.bind(telemetryAverager);
return this.telemetryAPI.subscribe(domainObject, createAverageDatum); return this.telemetryAPI.subscribe(domainObject, createAverageDatum);
}; };
MeanTelemetryProvider.prototype.request = function (domainObject, request) { MeanTelemetryProvider.prototype.request = function (domainObject, request) {
const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint); const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint);
const samples = domainObject.samples; const samples = domainObject.samples;
@ -84,16 +87,16 @@ define(['objectUtils', './TelemetryAverager'], function (objectUtils, TelemetryA
return this.requestAverageTelemetry(linkedDomainObject, request, samples); return this.requestAverageTelemetry(linkedDomainObject, request, samples);
}.bind(this) }.bind(this)
); );
}; };
/** /**
* @private * @private
*/ */
MeanTelemetryProvider.prototype.requestAverageTelemetry = function ( MeanTelemetryProvider.prototype.requestAverageTelemetry = function (
domainObject, domainObject,
request, request,
samples samples
) { ) {
const averageData = []; const averageData = [];
const addToAverageData = averageData.push.bind(averageData); const addToAverageData = averageData.push.bind(averageData);
const telemetryAverager = new TelemetryAverager( const telemetryAverager = new TelemetryAverager(
@ -110,24 +113,21 @@ define(['objectUtils', './TelemetryAverager'], function (objectUtils, TelemetryA
return averageData; return averageData;
}); });
}; };
/** /**
* @private * @private
*/ */
MeanTelemetryProvider.prototype.getLinkedObject = function (domainObject) { MeanTelemetryProvider.prototype.getLinkedObject = function (domainObject) {
const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint); const objectId = objectUtils.parseKeyString(domainObject.telemetryPoint);
return this.objectAPI.get(objectId); return this.objectAPI.get(objectId);
}; };
function logError(error) { function logError(error) {
if (error.stack) { if (error.stack) {
console.error(error.stack); console.error(error.stack);
} else { } else {
console.error(error); console.error(error);
} }
} }
return MeanTelemetryProvider;
});

View File

@ -20,13 +20,13 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
/* eslint-disable no-invalid-this */ /* eslint-disable no-invalid-this */
define(['./MeanTelemetryProvider', './MockTelemetryApi'], function (
MeanTelemetryProvider,
MockTelemetryApi
) {
const RANGE_KEY = 'value';
describe('The Mean Telemetry Provider', function () { import MeanTelemetryProvider from './MeanTelemetryProvider';
import MockTelemetryApi from './MockTelemetryApi';
const RANGE_KEY = 'value';
describe('The Mean Telemetry Provider', function () {
let mockApi; let mockApi;
let meanTelemetryProvider; let meanTelemetryProvider;
let mockDomainObject; let mockDomainObject;
@ -619,5 +619,4 @@ define(['./MeanTelemetryProvider', './MockTelemetryApi'], function (
key: timeSystemKey key: timeSystemKey
}); });
} }
});
}); });

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function MockTelemetryApi() {
function MockTelemetryApi() {
this.createSpy('subscribe'); this.createSpy('subscribe');
this.createSpy('getMetadata'); this.createSpy('getMetadata');
@ -29,19 +28,19 @@ define([], function () {
this.setDefaultRangeTo('defaultRange'); this.setDefaultRangeTo('defaultRange');
this.unsubscribe = jasmine.createSpy('unsubscribe'); this.unsubscribe = jasmine.createSpy('unsubscribe');
this.mockReceiveTelemetry = this.mockReceiveTelemetry.bind(this); this.mockReceiveTelemetry = this.mockReceiveTelemetry.bind(this);
} }
MockTelemetryApi.prototype.subscribe = function () { MockTelemetryApi.prototype.subscribe = function () {
return this.unsubscribe; return this.unsubscribe;
}; };
MockTelemetryApi.prototype.getMetadata = function (object) { MockTelemetryApi.prototype.getMetadata = function (object) {
return this.metadata; return this.metadata;
}; };
MockTelemetryApi.prototype.request = jasmine.createSpy('request'); MockTelemetryApi.prototype.request = jasmine.createSpy('request');
MockTelemetryApi.prototype.getValueFormatter = function (valueMetadata) { MockTelemetryApi.prototype.getValueFormatter = function (valueMetadata) {
const mockValueFormatter = jasmine.createSpyObj('valueFormatter', ['parse']); const mockValueFormatter = jasmine.createSpyObj('valueFormatter', ['parse']);
mockValueFormatter.parse.and.callFake(function (value) { mockValueFormatter.parse.and.callFake(function (value) {
@ -49,34 +48,34 @@ define([], function () {
}); });
return mockValueFormatter; return mockValueFormatter;
}; };
MockTelemetryApi.prototype.mockReceiveTelemetry = function (newTelemetryDatum) { MockTelemetryApi.prototype.mockReceiveTelemetry = function (newTelemetryDatum) {
const subscriptionCallback = this.subscribe.calls.mostRecent().args[1]; const subscriptionCallback = this.subscribe.calls.mostRecent().args[1];
subscriptionCallback(newTelemetryDatum); subscriptionCallback(newTelemetryDatum);
}; };
/** /**
* @private * @private
*/ */
MockTelemetryApi.prototype.onRequestReturn = function (telemetryData) { MockTelemetryApi.prototype.onRequestReturn = function (telemetryData) {
this.requestTelemetry = telemetryData; this.requestTelemetry = telemetryData;
}; };
/** /**
* @private * @private
*/ */
MockTelemetryApi.prototype.setDefaultRangeTo = function (rangeKey) { MockTelemetryApi.prototype.setDefaultRangeTo = function (rangeKey) {
const mockMetadataValue = { const mockMetadataValue = {
key: rangeKey key: rangeKey
}; };
this.metadata.valuesForHints.and.returnValue([mockMetadataValue]); this.metadata.valuesForHints.and.returnValue([mockMetadataValue]);
}; };
/** /**
* @private * @private
*/ */
MockTelemetryApi.prototype.createMockMetadata = function () { MockTelemetryApi.prototype.createMockMetadata = function () {
const mockMetadata = jasmine.createSpyObj('metadata', ['value', 'valuesForHints']); const mockMetadata = jasmine.createSpyObj('metadata', ['value', 'valuesForHints']);
mockMetadata.value.and.callFake(function (key) { mockMetadata.value.and.callFake(function (key) {
@ -86,16 +85,13 @@ define([], function () {
}); });
return mockMetadata; return mockMetadata;
}; };
/** /**
* @private * @private
*/ */
MockTelemetryApi.prototype.createSpy = function (functionName) { MockTelemetryApi.prototype.createSpy = function (functionName) {
this[functionName] = this[functionName].bind(this); this[functionName] = this[functionName].bind(this);
spyOn(this, functionName); spyOn(this, functionName);
this[functionName].and.callThrough(); this[functionName].and.callThrough();
}; };
return MockTelemetryApi;
});

View File

@ -20,8 +20,13 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default function TelemetryAverager(
function TelemetryAverager(telemetryAPI, timeAPI, domainObject, samples, averageDatumCallback) { telemetryAPI,
timeAPI,
domainObject,
samples,
averageDatumCallback
) {
this.telemetryAPI = telemetryAPI; this.telemetryAPI = telemetryAPI;
this.timeAPI = timeAPI; this.timeAPI = timeAPI;
@ -38,9 +43,9 @@ define([], function () {
this.domainFormatter = undefined; this.domainFormatter = undefined;
this.averageDatumCallback = averageDatumCallback; this.averageDatumCallback = averageDatumCallback;
} }
TelemetryAverager.prototype.createAverageDatum = function (telemetryDatum) { TelemetryAverager.prototype.createAverageDatum = function (telemetryDatum) {
this.setDomainKeyAndFormatter(); this.setDomainKeyAndFormatter();
const timeValue = this.domainFormatter.parse(telemetryDatum); const timeValue = this.domainFormatter.parse(telemetryDatum);
@ -63,12 +68,12 @@ define([], function () {
meanDatum.value = averageValue; meanDatum.value = averageValue;
this.averageDatumCallback(meanDatum); this.averageDatumCallback(meanDatum);
}; };
/** /**
* @private * @private
*/ */
TelemetryAverager.prototype.calculateMean = function () { TelemetryAverager.prototype.calculateMean = function () {
let sum = 0; let sum = 0;
let i = 0; let i = 0;
@ -77,43 +82,40 @@ define([], function () {
} }
return sum / this.averagingWindow.length; return sum / this.averagingWindow.length;
}; };
/** /**
* The mean telemetry filter produces domain values in whatever time * The mean telemetry filter produces domain values in whatever time
* system is currently selected from the conductor. Because this can * system is currently selected from the conductor. Because this can
* change dynamically, the averager needs to be updated regularly with * change dynamically, the averager needs to be updated regularly with
* the current domain. * the current domain.
* @private * @private
*/ */
TelemetryAverager.prototype.setDomainKeyAndFormatter = function () { TelemetryAverager.prototype.setDomainKeyAndFormatter = function () {
const domainKey = this.timeAPI.timeSystem().key; const domainKey = this.timeAPI.timeSystem().key;
if (domainKey !== this.domainKey) { if (domainKey !== this.domainKey) {
this.domainKey = domainKey; this.domainKey = domainKey;
this.domainFormatter = this.getFormatter(domainKey); this.domainFormatter = this.getFormatter(domainKey);
} }
}; };
/** /**
* @private * @private
*/ */
TelemetryAverager.prototype.setRangeKeyAndFormatter = function () { TelemetryAverager.prototype.setRangeKeyAndFormatter = function () {
const metadatas = this.telemetryAPI.getMetadata(this.domainObject); const metadatas = this.telemetryAPI.getMetadata(this.domainObject);
const rangeValues = metadatas.valuesForHints(['range']); const rangeValues = metadatas.valuesForHints(['range']);
this.rangeKey = rangeValues[0].key; this.rangeKey = rangeValues[0].key;
this.rangeFormatter = this.getFormatter(this.rangeKey); this.rangeFormatter = this.getFormatter(this.rangeKey);
}; };
/** /**
* @private * @private
*/ */
TelemetryAverager.prototype.getFormatter = function (key) { TelemetryAverager.prototype.getFormatter = function (key) {
const objectMetadata = this.telemetryAPI.getMetadata(this.domainObject); const objectMetadata = this.telemetryAPI.getMetadata(this.domainObject);
const valueMetadata = objectMetadata.value(key); const valueMetadata = objectMetadata.value(key);
return this.telemetryAPI.getValueFormatter(valueMetadata); return this.telemetryAPI.getValueFormatter(valueMetadata);
}; };
return TelemetryAverager;
});

View File

@ -20,28 +20,18 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([ import EventEmitter from 'EventEmitter';
'EventEmitter', import _ from 'lodash';
'lodash',
'./collections/TableRowCollection', import StalenessUtils from '../../utils/staleness';
'./TelemetryTableRow', import TableRowCollection from './collections/TableRowCollection';
'./TelemetryTableNameColumn', import TelemetryTableColumn from './TelemetryTableColumn';
'./TelemetryTableColumn', import TelemetryTableConfiguration from './TelemetryTableConfiguration';
'./TelemetryTableUnitColumn', import TelemetryTableNameColumn from './TelemetryTableNameColumn';
'./TelemetryTableConfiguration', import TelemetryTableRow from './TelemetryTableRow';
'../../utils/staleness' import TelemetryTableUnitColumn from './TelemetryTableUnitColumn';
], function (
EventEmitter, export default class TelemetryTable extends EventEmitter {
_,
TableRowCollection,
TelemetryTableRow,
TelemetryTableNameColumn,
TelemetryTableColumn,
TelemetryTableUnitColumn,
TelemetryTableConfiguration,
StalenessUtils
) {
class TelemetryTable extends EventEmitter {
constructor(domainObject, openmct) { constructor(domainObject, openmct) {
super(); super();
@ -195,7 +185,7 @@ define([
} }
this.stalenessSubscription[keyString] = {}; this.stalenessSubscription[keyString] = {};
this.stalenessSubscription[keyString].stalenessUtils = new StalenessUtils.default( this.stalenessSubscription[keyString].stalenessUtils = new StalenessUtils(
this.openmct, this.openmct,
domainObject domainObject
); );
@ -470,7 +460,4 @@ define([
this.tableComposition.off('remove', this.removeTelemetryObject); this.tableComposition.off('remove', this.removeTelemetryObject);
} }
} }
} }
return TelemetryTable;
});

View File

@ -19,8 +19,7 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(function () { export default class TelemetryTableColumn {
class TelemetryTableColumn {
constructor(openmct, metadatum, options = { selectable: false }) { constructor(openmct, metadatum, options = { selectable: false }) {
this.metadatum = metadatum; this.metadatum = metadatum;
this.formatter = openmct.telemetry.getValueFormatter(metadatum); this.formatter = openmct.telemetry.getValueFormatter(metadatum);
@ -60,7 +59,4 @@ define(function () {
getParsedValue(telemetryDatum) { getParsedValue(telemetryDatum) {
return this.formatter.parse(telemetryDatum); return this.formatter.parse(telemetryDatum);
} }
} }
return TelemetryTableColumn;
});

View File

@ -20,8 +20,10 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['lodash', 'EventEmitter'], function (_, EventEmitter) { import EventEmitter from 'EventEmitter';
class TelemetryTableConfiguration extends EventEmitter { import _ from 'lodash';
export default class TelemetryTableConfiguration extends EventEmitter {
constructor(domainObject, openmct) { constructor(domainObject, openmct) {
super(); super();
@ -162,7 +164,4 @@ define(['lodash', 'EventEmitter'], function (_, EventEmitter) {
destroy() { destroy() {
this.unlistenFromMutation(); this.unlistenFromMutation();
} }
} }
return TelemetryTableConfiguration;
});

View File

@ -19,8 +19,10 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./TelemetryTableColumn.js'], function (TelemetryTableColumn) {
class TelemetryTableNameColumn extends TelemetryTableColumn { import TelemetryTableColumn from './TelemetryTableColumn';
export default class TelemetryTableNameColumn extends TelemetryTableColumn {
constructor(openmct, telemetryObject, metadatum) { constructor(openmct, telemetryObject, metadatum) {
super(openmct, metadatum); super(openmct, metadatum);
@ -34,7 +36,4 @@ define(['./TelemetryTableColumn.js'], function (TelemetryTableColumn) {
getFormattedValue() { getFormattedValue() {
return this.telemetryObject.name; return this.telemetryObject.name;
} }
} }
return TelemetryTableNameColumn;
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { export default class TelemetryTableRow {
class TelemetryTableRow {
constructor(datum, columns, objectKeyString, limitEvaluator, inPlaceUpdateKey) { constructor(datum, columns, objectKeyString, limitEvaluator, inPlaceUpdateKey) {
this.columns = columns; this.columns = columns;
@ -101,16 +100,16 @@ define([], function () {
...updatesToDatum ...updatesToDatum
}; };
} }
} }
/** /**
* Normalize the structure of datums to assist sorting and merging of columns. * Normalize the structure of datums to assist sorting and merging of columns.
* Maps all sources to keys. * Maps all sources to keys.
* @private * @private
* @param {*} telemetryDatum * @param {*} telemetryDatum
* @param {*} metadataValues * @param {*} metadataValues
*/ */
function createNormalizedDatum(datum, columns) { function createNormalizedDatum(datum, columns) {
const normalizedDatum = JSON.parse(JSON.stringify(datum)); const normalizedDatum = JSON.parse(JSON.stringify(datum));
Object.values(columns).forEach((column) => { Object.values(columns).forEach((column) => {
@ -121,7 +120,4 @@ define([], function () {
}); });
return normalizedDatum; return normalizedDatum;
} }
return TelemetryTableRow;
});

View File

@ -20,8 +20,7 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(function () { export default {
return {
name: 'Telemetry Table', name: 'Telemetry Table',
description: description:
'Display values for one or more telemetry end points in a scrolling table. Each row is a time-stamped value.', 'Display values for one or more telemetry end points in a scrolling table. Each row is a time-stamped value.',
@ -34,5 +33,4 @@ define(function () {
hiddenColumns: {} hiddenColumns: {}
}; };
} }
}; };
});

View File

@ -19,8 +19,9 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['./TelemetryTableColumn.js'], function (TelemetryTableColumn) { import TelemetryTableColumn from './TelemetryTableColumn.js';
class TelemetryTableUnitColumn extends TelemetryTableColumn {
class TelemetryTableUnitColumn extends TelemetryTableColumn {
constructor(openmct, metadatum) { constructor(openmct, metadatum) {
super(openmct, metadatum); super(openmct, metadatum);
this.isUnit = true; this.isUnit = true;
@ -50,7 +51,6 @@ define(['./TelemetryTableColumn.js'], function (TelemetryTableColumn) {
getFormattedValue(telemetryDatum) { getFormattedValue(telemetryDatum) {
return this.formatter.format(telemetryDatum); return this.formatter.format(telemetryDatum);
} }
} }
return TelemetryTableUnitColumn; export default TelemetryTableUnitColumn;
});

View File

@ -19,12 +19,13 @@
* this source code distribution or the Licensing information page available * this source code distribution or the Licensing information page available
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
import EventEmitter from 'EventEmitter';
import _ from 'lodash';
define(['lodash', 'EventEmitter'], function (_, EventEmitter) { /**
/**
* @constructor * @constructor
*/ */
class TableRowCollection extends EventEmitter { export default class TableRowCollection extends EventEmitter {
constructor() { constructor() {
super(); super();
@ -383,7 +384,4 @@ define(['lodash', 'EventEmitter'], function (_, EventEmitter) {
destroy() { destroy() {
this.removeAllListeners(); this.removeAllListeners();
} }
} }
return TableRowCollection;
});

View File

@ -20,17 +20,17 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* This time system supports UTC dates. * This time system supports UTC dates.
* @implements TimeSystem * @implements TimeSystem
* @constructor * @constructor
*/ */
function UTCTimeSystem() { class UTCTimeSystem {
/** /**
* Metadata used to identify the time system in * Metadata used to identify the time system in
* the UI * the UI
*/ */
constructor() {
this.key = 'utc'; this.key = 'utc';
this.name = 'UTC'; this.name = 'UTC';
this.cssClass = 'icon-clock'; this.cssClass = 'icon-clock';
@ -38,6 +38,6 @@ define([], function () {
this.durationFormat = 'duration'; this.durationFormat = 'duration';
this.isUTCBased = true; this.isUTCBased = true;
} }
}
return UTCTimeSystem; export default UTCTimeSystem;
});

View File

@ -20,25 +20,24 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define([], function () { /**
/**
* A ToolbarRegistry maintains the definitions for toolbars. * A ToolbarRegistry maintains the definitions for toolbars.
* *
* @interface ToolbarRegistry * @interface ToolbarRegistry
* @memberof module:openmct * @memberof module:openmct
*/ */
function ToolbarRegistry() { export default function ToolbarRegistry() {
this.providers = {}; this.providers = {};
} }
/** /**
* Gets toolbar controls from providers which can provide a toolbar for this selection. * Gets toolbar controls from providers which can provide a toolbar for this selection.
* *
* @param {object} selection the selection object * @param {object} selection the selection object
* @returns {Object[]} an array of objects defining controls for the toolbar * @returns {Object[]} an array of objects defining controls for the toolbar
* @private for platform-internal use * @private for platform-internal use
*/ */
ToolbarRegistry.prototype.get = function (selection) { ToolbarRegistry.prototype.get = function (selection) {
const providers = this.getAllProviders().filter(function (provider) { const providers = this.getAllProviders().filter(function (provider) {
return provider.forSelection(selection); return provider.forSelection(selection);
}); });
@ -50,30 +49,30 @@ define([], function () {
}); });
return structure; return structure;
}; };
/** /**
* @private * @private
*/ */
ToolbarRegistry.prototype.getAllProviders = function () { ToolbarRegistry.prototype.getAllProviders = function () {
return Object.values(this.providers); return Object.values(this.providers);
}; };
/** /**
* @private * @private
*/ */
ToolbarRegistry.prototype.getByProviderKey = function (key) { ToolbarRegistry.prototype.getByProviderKey = function (key) {
return this.providers[key]; return this.providers[key];
}; };
/** /**
* Registers a new type of toolbar. * Registers a new type of toolbar.
* *
* @param {module:openmct.ToolbarRegistry} provider the provider for this toolbar * @param {module:openmct.ToolbarRegistry} provider the provider for this toolbar
* @method addProvider * @method addProvider
* @memberof module:openmct.ToolbarRegistry# * @memberof module:openmct.ToolbarRegistry#
*/ */
ToolbarRegistry.prototype.addProvider = function (provider) { ToolbarRegistry.prototype.addProvider = function (provider) {
const key = provider.key; const key = provider.key;
if (key === undefined) { if (key === undefined) {
@ -85,9 +84,9 @@ define([], function () {
} }
this.providers[key] = provider; this.providers[key] = provider;
}; };
/** /**
* Exposes types of toolbars in Open MCT. * Exposes types of toolbars in Open MCT.
* *
* @interface ToolbarProvider * @interface ToolbarProvider
@ -98,7 +97,7 @@ define([], function () {
* @memberof module:openmct * @memberof module:openmct
*/ */
/** /**
* Checks if this provider can supply toolbar for a selection. * Checks if this provider can supply toolbar for a selection.
* *
* @method forSelection * @method forSelection
@ -108,7 +107,7 @@ define([], function () {
* otherwise 'false'. * otherwise 'false'.
*/ */
/** /**
* Provides controls that comprise a toolbar. * Provides controls that comprise a toolbar.
* *
* @method toolbar * @method toolbar
@ -116,6 +115,3 @@ define([], function () {
* @param {object} selection the selection object * @param {object} selection the selection object
* @returns {Object[]} an array of objects defining controls for the toolbar. * @returns {Object[]} an array of objects defining controls for the toolbar.
*/ */
return ToolbarRegistry;
});

View File

@ -20,23 +20,24 @@
* at runtime from the About dialog for additional information. * at runtime from the About dialog for additional information.
*****************************************************************************/ *****************************************************************************/
define(['EventEmitter'], function (EventEmitter) { import EventEmitter from 'EventEmitter';
const DEFAULT_VIEW_PRIORITY = 100;
/** const DEFAULT_VIEW_PRIORITY = 100;
/**
* A ViewRegistry maintains the definitions for different kinds of views * A ViewRegistry maintains the definitions for different kinds of views
* that may occur in different places in the user interface. * that may occur in different places in the user interface.
* @interface ViewRegistry * @interface ViewRegistry
* @memberof module:openmct * @memberof module:openmct
*/ */
function ViewRegistry() { export default function ViewRegistry() {
EventEmitter.apply(this); EventEmitter.apply(this);
this.providers = {}; this.providers = {};
} }
ViewRegistry.prototype = Object.create(EventEmitter.prototype); ViewRegistry.prototype = Object.create(EventEmitter.prototype);
/** /**
* @private for platform-internal use * @private for platform-internal use
* @param {*} item the object to be viewed * @param {*} item the object to be viewed
* @param {array} objectPath - The current contextual object path of the view object * @param {array} objectPath - The current contextual object path of the view object
@ -44,7 +45,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @returns {module:openmct.ViewProvider[]} any providers * @returns {module:openmct.ViewProvider[]} any providers
* which can provide views of this object * which can provide views of this object
*/ */
ViewRegistry.prototype.get = function (item, objectPath) { ViewRegistry.prototype.get = function (item, objectPath) {
if (objectPath === undefined) { if (objectPath === undefined) {
throw 'objectPath must be provided to get applicable views for an object'; throw 'objectPath must be provided to get applicable views for an object';
} }
@ -61,23 +62,23 @@ define(['EventEmitter'], function (EventEmitter) {
return provider.canView(item, objectPath); return provider.canView(item, objectPath);
}) })
.sort(byPriority); .sort(byPriority);
}; };
/** /**
* @private * @private
*/ */
ViewRegistry.prototype.getAllProviders = function () { ViewRegistry.prototype.getAllProviders = function () {
return Object.values(this.providers); return Object.values(this.providers);
}; };
/** /**
* Register a new type of view. * Register a new type of view.
* *
* @param {module:openmct.ViewProvider} provider the provider for this view * @param {module:openmct.ViewProvider} provider the provider for this view
* @method addProvider * @method addProvider
* @memberof module:openmct.ViewRegistry# * @memberof module:openmct.ViewRegistry#
*/ */
ViewRegistry.prototype.addProvider = function (provider) { ViewRegistry.prototype.addProvider = function (provider) {
const key = provider.key; const key = provider.key;
if (key === undefined) { if (key === undefined) {
throw "View providers must have a unique 'key' property defined"; throw "View providers must have a unique 'key' property defined";
@ -101,27 +102,27 @@ define(['EventEmitter'], function (EventEmitter) {
}; };
this.providers[key] = provider; this.providers[key] = provider;
}; };
/** /**
* @private * @private
*/ */
ViewRegistry.prototype.getByProviderKey = function (key) { ViewRegistry.prototype.getByProviderKey = function (key) {
return this.providers[key]; return this.providers[key];
}; };
/** /**
* Used internally to support seamless usage of new views with old * Used internally to support seamless usage of new views with old
* views. * views.
* @private * @private
*/ */
ViewRegistry.prototype.getByVPID = function (vpid) { ViewRegistry.prototype.getByVPID = function (vpid) {
return this.providers.filter(function (p) { return this.providers.filter(function (p) {
return p.vpid === vpid; return p.vpid === vpid;
})[0]; })[0];
}; };
/** /**
* A View is used to provide displayable content, and to react to * A View is used to provide displayable content, and to react to
* associated life cycle events. * associated life cycle events.
* *
@ -130,7 +131,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct * @memberof module:openmct
*/ */
/** /**
* Populate the supplied DOM element with the contents of this view. * Populate the supplied DOM element with the contents of this view.
* *
* View implementations should use this method to attach any * View implementations should use this method to attach any
@ -142,7 +143,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct.View# * @memberof module:openmct.View#
*/ */
/** /**
* Indicates whether or not the application is in edit mode. This supports * Indicates whether or not the application is in edit mode. This supports
* views that have distinct visual and behavioral elements when the * views that have distinct visual and behavioral elements when the
* navigated object is being edited. * navigated object is being edited.
@ -155,7 +156,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct.View# * @memberof module:openmct.View#
*/ */
/** /**
* Release any resources associated with this view. * Release any resources associated with this view.
* *
* View implementations should use this method to detach any * View implementations should use this method to detach any
@ -166,7 +167,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct.View# * @memberof module:openmct.View#
*/ */
/** /**
* Returns the selection context. * Returns the selection context.
* *
* View implementations should use this method to customize * View implementations should use this method to customize
@ -176,7 +177,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct.View# * @memberof module:openmct.View#
*/ */
/** /**
* Exposes types of views in Open MCT. * Exposes types of views in Open MCT.
* *
* @interface ViewProvider * @interface ViewProvider
@ -189,7 +190,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @memberof module:openmct * @memberof module:openmct
*/ */
/** /**
* Check if this provider can supply views for a domain object. * Check if this provider can supply views for a domain object.
* *
* When called by Open MCT, this may include additional arguments * When called by Open MCT, this may include additional arguments
@ -207,7 +208,7 @@ define(['EventEmitter'], function (EventEmitter) {
* otherwise 'false'. * otherwise 'false'.
*/ */
/** /**
* An optional function that defines whether or not this view can be used to edit a given object. * An optional function that defines whether or not this view can be used to edit a given object.
* If not provided, will default to `false` and the view will not support editing. To support editing, * If not provided, will default to `false` and the view will not support editing. To support editing,
* return true from this function and then - * return true from this function and then -
@ -229,7 +230,7 @@ define(['EventEmitter'], function (EventEmitter) {
* otherwise 'false'. * otherwise 'false'.
*/ */
/** /**
* Optional method determining the priority of a given view. If this * Optional method determining the priority of a given view. If this
* function is not defined on a view provider, then a default priority * function is not defined on a view provider, then a default priority
* of 100 will be applicable for all objects supported by this view. * of 100 will be applicable for all objects supported by this view.
@ -243,7 +244,7 @@ define(['EventEmitter'], function (EventEmitter) {
* the default view. * the default view.
*/ */
/** /**
* Provide a view of this object. * Provide a view of this object.
* *
* When called by Open MCT, the following arguments will be passed to it: * When called by Open MCT, the following arguments will be passed to it:
@ -257,7 +258,7 @@ define(['EventEmitter'], function (EventEmitter) {
* @returns {module:openmct.View} a view of this domain object * @returns {module:openmct.View} a view of this domain object
*/ */
/** /**
* Provide an edit-mode specific view of this object. * Provide an edit-mode specific view of this object.
* *
* If optionally specified, this function will be called when the application * If optionally specified, this function will be called when the application
@ -269,6 +270,3 @@ define(['EventEmitter'], function (EventEmitter) {
* @param {*} object the object to be edit * @param {*} object the object to be edit
* @returns {module:openmct.View} an editable view of this domain object * @returns {module:openmct.View} an editable view of this domain object
*/ */
return ViewRegistry;
});

Some files were not shown because too many files have changed in this diff Show More