Visualization.js 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583
  1. 'use strict';
  2. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
  3. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  4. function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
  5. function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
  6. /**
  7. * Licensed Materials - Property of IBM
  8. * IBM Cognos Products: Dashboard
  9. * (C) Copyright IBM Corp. 2018, 2020
  10. * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
  11. */
  12. /**
  13. * @class Visualization
  14. * @hideconstructor
  15. */
  16. define(['underscore', './VisualizationAPISpec', '../../lib/@waca/dashboard-common/dist/core/APIFactory', '../deprecated/VisualizationAPI', '../internal/VisualizationAPI', '../VisualizationAPI', '../cleanup/VisualizationAPI', './LocalFilters', './Slots', './SavedPrompts', './serviceability/ServiceabilityDataInfo', '../../widgets/livewidget/modelapis/modelmanagers/VisModelManager', '../../widgets/livewidget/visapi/support/VisFilterSupport', '../../widgets/livewidget/visapi/support/VisPropertySupport', './model/DataModel', '../../widgets/livewidget/nls/StringResources'], function (_, VisualizationAPISpec, APIFactory, DeprecatedVisualizationAPI, InternalVisualizationAPI, VisualizationAPI, CleanUpVisualizationAPI, LocalFilters, Slots, SavedPrompts, ServiceabilityDataInfo, VisModelManager, VisFilterSupport, VisPropertySupport, DataModel, StringResources) {
  17. // Used to indicate which fields are supported in the "compare" api
  18. // Each field can have an exclude list to exclude certain attributes from the comparison
  19. var widgetMatchingConfig = {
  20. visId: {
  21. getValue: function getValue(visModel) {
  22. return visModel.visId;
  23. },
  24. exclude: []
  25. },
  26. localFilters: {
  27. getValue: function getValue(visModel) {
  28. var filters = visModel.localFilters;
  29. return filters ? filters.toJSON() : {};
  30. },
  31. exclude: ['binsLabel', 'id', 'readOnly', 'isMissing']
  32. }
  33. };
  34. var Visualization = function (_VisualizationAPISpec) {
  35. _inherits(Visualization, _VisualizationAPISpec);
  36. function Visualization(options) {
  37. _classCallCheck(this, Visualization);
  38. var _this = _possibleConstructorReturn(this, _VisualizationAPISpec.call(this));
  39. _this.doNotRegisterDataSourceUsage = options.doNotRegisterDataSourceUsage;
  40. _this.state = options.features['state.internal'];
  41. _this.widgetModel = options.features['Models.internal'].getWidgetModel();
  42. _this.dashboardAPI = options.features['Dashboard.API'];
  43. _this.logger = options.features['Dashboard.Logger'];
  44. _this.content = options.content;
  45. _this.colors = options.features['Dashboard.Colors'];
  46. _this.transaction = options.features['Dashboard.Transaction'];
  47. _this.dataSources = options.features['Dashboard.DataSources'];
  48. _this.boardModel = options.features['Dashboard.internal'].getBoardModel();
  49. _this.visDefinitions = options.features['Dashboard.VisDefinitions'];
  50. _this.serviceability = options.features['Serviceability'];
  51. _this.internalVisDefinitions = options.features['Dashboard.VisDefinitions.internal'];
  52. _this.notification = options.features['Dashboard.Notification'];
  53. _this._isPreview = options.spec && options.spec.isPreview;
  54. // TODO - should be its own dashboard feature
  55. _this.userProfile = _this.dashboardAPI.getGlassCoreSvc('.UserProfile');
  56. if (!_this.widgetModel.data) {
  57. _this.widgetModel.data = {};
  58. }
  59. _this.dataModel = new DataModel(_this.widgetModel.data);
  60. _this.visDefinitions.on('refresh', _this.refreshSlotsAfterChanges, _this);
  61. _this._dataSource = {};
  62. return _this;
  63. }
  64. Visualization.prototype.refreshSlotsAfterChanges = function refreshSlotsAfterChanges() {
  65. var isEmpty = this.internalVisDefinitions.getRawDefinition(this.getDefinition().getId()).empty;
  66. if (!this.getDefinition().getState().getError() && !isEmpty) {
  67. this.slotsImpl.setDefinition(this.getDefinition());
  68. this.slotsImpl._initializeDataItems();
  69. }
  70. };
  71. Visualization.prototype.destroy = function destroy() {
  72. if (this.destroyed) {
  73. // TODO livewidget_cleanup -- remove the viz from the live widget feature
  74. // so that we don't need this..
  75. // Because we temporary register this as a lvie widget feature and content feature,
  76. // the destroy will be called twice.. don't bother the second time
  77. // This code can go away once one move to the content feature
  78. return;
  79. }
  80. var dataSource = this.getDataSource();
  81. if (dataSource && !this.doNotRegisterDataSourceUsage) {
  82. dataSource.deregisterUsage(this.widgetModel.id);
  83. }
  84. this.visDefinitions.off('refresh:definition', this.refreshSlotsAfterChanges, this);
  85. this.widgetModel = null;
  86. this.dashboardAPI = null;
  87. this.logger = null;
  88. this.widget = null;
  89. this.content = null;
  90. this.colors = null;
  91. this.transaction = null;
  92. this.dataSources = null;
  93. this.boardModel = null;
  94. this.visDefinitions = null;
  95. this.internalVisDefinitions = null;
  96. this.userProfile = null;
  97. this.localFiltersImpl.destroy();
  98. this.localFiltersImpl = null;
  99. this.savedPromptsImpl.destroy();
  100. this.savedPromptsImpl = null;
  101. this.slotsImpl.destroy();
  102. this.slotsImpl = null;
  103. this.destroyed = true;
  104. };
  105. Visualization.prototype._createLegacyManagers = function _createLegacyManagers() {
  106. var visModelManager = new VisModelManager({
  107. logger: this.logger,
  108. localFilters: this.widgetModel.localFilters,
  109. searchFilters: this.widgetModel.searchFilters,
  110. visDefinitions: this.internalVisDefinitions,
  111. widgetModel: this.widgetModel,
  112. dashboardApi: this.dashboardAPI,
  113. boardModel: this.boardModel,
  114. colors: this.colors,
  115. content: this.content,
  116. visualizationFeature: this.getAPI()
  117. });
  118. var pageContextModel = this.boardModel.get('pageContext');
  119. var pageContext = pageContextModel && pageContextModel.getAPI();
  120. var visFilterSupport = new VisFilterSupport({
  121. visModelManager: visModelManager,
  122. pageContext: pageContext,
  123. logger: this.logger,
  124. dashboardApi: this.dashboardAPI,
  125. content: this.content,
  126. contentId: this.widgetModel.id,
  127. visualization: this.getAPI()
  128. });
  129. var visPropertySupport = new VisPropertySupport({
  130. properties: this.widgetModel.properties,
  131. visModelManager: visModelManager,
  132. dashboardApi: this.dashboardAPI,
  133. content: this.content
  134. });
  135. visModelManager.initialize({
  136. propertySupport: visPropertySupport,
  137. filterSupport: visFilterSupport //,
  138. });
  139. this.legacyManagers = {
  140. visModelManager: visModelManager,
  141. visFilterSupport: visFilterSupport,
  142. visPropertySupport: visPropertySupport,
  143. dataModel: this.dataModel // TODO livewidget_cleanup -- remove this.. it is here temporary for the visCOnditionSupport
  144. };
  145. };
  146. Visualization.prototype.getLegacyManagers = function getLegacyManagers() {
  147. return this.legacyManagers;
  148. };
  149. Visualization.prototype.getAPI = function getAPI(type) {
  150. if (type === 'legacy') {
  151. return {
  152. getLegacyManagers: this.getLegacyManagers.bind(this)
  153. };
  154. }
  155. if (type === 'internal') {
  156. if (!this.internal) {
  157. this.internal = APIFactory.createAPIFromSpec([{
  158. implementation: this,
  159. interface: VisualizationAPI
  160. }, {
  161. implementation: this,
  162. interface: InternalVisualizationAPI
  163. }, {
  164. implementation: this,
  165. interface: DeprecatedVisualizationAPI,
  166. options: {
  167. // Set true to enable deprecated logging
  168. isDeprecated: false
  169. }
  170. }]);
  171. }
  172. return this.internal;
  173. }
  174. if (type === 'cleanup') {
  175. if (!this.cleanup) {
  176. this.cleanup = APIFactory.createAPIFromSpec([{
  177. implementation: this,
  178. interface: CleanUpVisualizationAPI
  179. }]);
  180. }
  181. return this.cleanup;
  182. }
  183. if (!this._apiInstance) {
  184. this._apiInstance = APIFactory.createAPIFromSpec([{
  185. implementation: this,
  186. interface: VisualizationAPI
  187. }, {
  188. implementation: this,
  189. interface: DeprecatedVisualizationAPI,
  190. options: {
  191. // Set true to enable deprecated logging
  192. isDeprecated: false
  193. }
  194. }]);
  195. }
  196. return this._apiInstance;
  197. };
  198. /**
  199. * @param {object} options
  200. * @description one of the task this method will do is to set data mapping
  201. * infomation to its associated contentInfo object. We put a try...catch...
  202. * here because of we don't want to block creating a widget on a place which
  203. * is not a canvas, like a conversation panel.
  204. */
  205. Visualization.prototype.initialize = function initialize() {
  206. var _this2 = this;
  207. var dataSource = this.getDataSource();
  208. var whenMetadataLoaded = null;
  209. if (dataSource) {
  210. if (!this.doNotRegisterDataSourceUsage) {
  211. dataSource.registerUsage(this.widgetModel.id);
  212. }
  213. whenMetadataLoaded = dataSource.loadMetadata();
  214. } else {
  215. whenMetadataLoaded = Promise.resolve();
  216. }
  217. // todo livewidget_cleanup - Should we load the metadata here or have a separate feature (metadataLoader)
  218. // I should be able to create the visualization without having to load the metadata.
  219. return whenMetadataLoaded.catch(function (e) {
  220. _this2.logger.log('An error occured while loading the metadata for content with id ' + _this2.content.getId());
  221. _this2.logger.log(e);
  222. _this2.state.setError({
  223. msg: 'dwErrorMissingDataset',
  224. params: {
  225. datasetName: e.sourceInfo && e.sourceInfo.name ? e.sourceInfo.name : dataSource.getAssetId()
  226. }
  227. });
  228. }).finally(function () {
  229. _this2._createLegacyManagers();
  230. _this2._createSubAPIs();
  231. _this2._getFilterSupport().validateFilters();
  232. // We don't support two cases where the following error will be thrown:
  233. // 1. live widgets on the conversation panel and,
  234. // 2. live widgets on the starting point page of an Exploration
  235. if (_this2.serviceability) {
  236. _this2._initializeServiceability(_this2.serviceability);
  237. }
  238. _this2._initializePropsAndThemes();
  239. });
  240. };
  241. Visualization.prototype._initializePropsAndThemes = function _initializePropsAndThemes() {
  242. if (this.getType()) {
  243. var definition = this.getDefinition();
  244. var propertySupport = this._getPropertySupport();
  245. propertySupport.buildProperties(definition.getProperty('properties') || definition.getProperty('propertyList'), this.boardModel.getLanguageModelOptions());
  246. // TODO: livewidget_cleanup - the updateThemeMapping should move to the VisDefinitions feature and we can register them in the Colors feature directly
  247. // This cannot be done until the color feature is a proper feature and created after the boardModel
  248. this.colors.updateThemeMapping(definition.getProperty('themeMapping'));
  249. }
  250. };
  251. Visualization.prototype._initializeServiceability = function _initializeServiceability(serviceability) {
  252. var _this3 = this;
  253. if (serviceability !== undefined) {
  254. var s12yInfo = serviceability.getContentInfo();
  255. s12yInfo.setData('dataInfo', new ServiceabilityDataInfo(this));
  256. var generalInfo = s12yInfo.getData('generalInfo');
  257. generalInfo.getLabel = function () {
  258. return _this3.getDefinition().getLabel();
  259. };
  260. s12yInfo.setData('generalInfo', generalInfo);
  261. } else {
  262. this.logger.warn('Cannot set serviceability information for this widget');
  263. }
  264. };
  265. Visualization.prototype.selectData = function selectData(selection, options) {
  266. return this._getFilterSupport().select(selection, options);
  267. };
  268. Visualization.prototype._createSubAPIs = function _createSubAPIs() {
  269. this.localFiltersImpl = new LocalFilters({ filterSupport: this._getFilterSupport(), visualization: this.getAPI('internal'), dataModel: this.dataModel });
  270. APIFactory.setParentChildRelation(this, this.localFiltersImpl);
  271. this.savedPromptsImpl = new SavedPrompts(this.widgetModel);
  272. APIFactory.setParentChildRelation(this, this.savedPromptsImpl);
  273. this.slotsImpl = new Slots(this.widgetModel, this.dataModel, this, this.transaction, this.userProfile.preferences.contentLocale, this.legacyManagers.visFilterSupport);
  274. APIFactory.setParentChildRelation(this, this.slotsImpl);
  275. };
  276. Visualization.prototype.matches = function matches(spec) {
  277. return this._matches(spec);
  278. };
  279. /**
  280. * Return true if the widget match the content provided in the parameter
  281. * We currently only support match visId and localFilter. Anything else will cause an error.
  282. *
  283. * @param {Object} widgetContent - content to match.
  284. */
  285. Visualization.prototype._matches = function _matches(widgetContent) {
  286. var _this4 = this;
  287. var widgetContentAsString = '';
  288. var currentAsString = '';
  289. Object.keys(widgetContent).forEach(function (key) {
  290. var matchingConfig = widgetMatchingConfig[key];
  291. if (!matchingConfig) {
  292. // Not supported
  293. throw 'the matches API does not support matching the property "' + key + '"';
  294. }
  295. widgetContentAsString += _this4._getCompareString(widgetContent[key], matchingConfig.exclude);
  296. var currentValueToCompare = matchingConfig.getValue(_this4.widgetModel);
  297. currentAsString += _this4._getCompareString(currentValueToCompare, matchingConfig.exclude);
  298. });
  299. return widgetContentAsString === currentAsString;
  300. };
  301. /**
  302. * Build a unique string that represents a given object.
  303. * This string can be used to compare with another object
  304. * Certain props can be excluded from the string like ids.
  305. *
  306. */
  307. Visualization.prototype._getCompareString = function _getCompareString(object, excludeAttributes) {
  308. var _this5 = this;
  309. var compareString = '';
  310. if ((typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object') {
  311. var compareValues = [];
  312. if (Array.isArray(object)) {
  313. object.forEach(function (value) {
  314. compareValues.push(_this5._getCompareString(value, excludeAttributes));
  315. });
  316. } else {
  317. var name = void 0;
  318. for (name in object) {
  319. if (excludeAttributes.indexOf(name) === -1) {
  320. compareValues.push(name + '_' + this._getCompareString(object[name], excludeAttributes));
  321. }
  322. }
  323. }
  324. compareValues.sort();
  325. compareValues.forEach(function (value) {
  326. compareString += value;
  327. });
  328. } else {
  329. compareString += object;
  330. }
  331. return compareString;
  332. };
  333. Visualization.prototype.getType = function getType() {
  334. var type = null;
  335. var definition = this.getDefinition();
  336. if (definition) {
  337. type = definition.getType();
  338. }
  339. return type;
  340. };
  341. Visualization.prototype.setType = function setType(type) {
  342. if (type && type !== this.getType()) {
  343. var newDefinition = this.visDefinitions.getByType(type);
  344. if (newDefinition) {
  345. this.widgetModel.visId = newDefinition.getId();
  346. this.slotsImpl.setDefinition(newDefinition);
  347. this._initializePropsAndThemes();
  348. this.refreshSlotsAfterChanges();
  349. } else {
  350. throw new Error('Invalid type');
  351. }
  352. }
  353. };
  354. Visualization.prototype.isTypeLocked = function isTypeLocked() {
  355. var isLocked = this.widgetModel.get('visTypeLocked');
  356. return !!isLocked;
  357. };
  358. Visualization.prototype.lockType = function lockType() {
  359. this.widgetModel.visTypeLocked = true;
  360. };
  361. Visualization.prototype.unlockType = function unlockType() {
  362. this.widgetModel.visTypeLocked = false;
  363. };
  364. Visualization.prototype.getDefinition = function getDefinition() {
  365. var definition = this.visDefinitions.getById(this.widgetModel.visId);
  366. return definition;
  367. };
  368. Visualization.prototype.getDataSource = function getDataSource() {
  369. var dataSource = null;
  370. var dataView = this.dataModel.getDataView();
  371. if (dataView && dataView.modelRef) {
  372. if (!this._dataSource[dataView.modelRef]) {
  373. this._dataSource[dataView.modelRef] = this.dataSources.getDataSource(dataView.modelRef);
  374. }
  375. dataSource = this._dataSource[dataView.modelRef];
  376. }
  377. return dataSource;
  378. };
  379. Visualization.prototype.setDataSource = function setDataSource(sourceId) {
  380. var currentDataSource = this.getDataSource();
  381. var currentId = currentDataSource && currentDataSource.getId();
  382. var visDef = this.getDefinition();
  383. if (currentId !== sourceId) {
  384. if (currentId !== null && (this.slotsImpl.getMappedSlotList().length > 0 || this.getLocalFilters().getFilterList().length > 0)) {
  385. throw 'Cannot change dataSource while the visualiation contains dataItems or filters from another source';
  386. }
  387. var dataSource = this.dataSources.getDataSource(sourceId);
  388. if (dataSource) {
  389. if (dataSource.isOlapPackage() && visDef && visDef.getProperty('supportsOLAP') === false) {
  390. // todo livewidget_cleanup - add notification to dependencies in perspective file in the server
  391. this.dashboardAPI.getFeature('Notification').setMessage(StringResources.get('visualizationDoesNotSupportOLAP'));
  392. return false;
  393. }
  394. if (!this.doNotRegisterDataSourceUsage) {
  395. dataSource.registerUsage(this.widgetModel.id);
  396. }
  397. }
  398. if (currentDataSource && !this.doNotRegisterDataSourceUsage) {
  399. currentDataSource.deregisterUsage(this.widgetModel.id);
  400. }
  401. this.dataModel.setModelRefInAllViews(sourceId);
  402. return true;
  403. }
  404. return false;
  405. };
  406. /**
  407. * @description Get an array of MetadataColumnAPI objects which are being used in the visualization
  408. * @return {MetadataColumnAPI[]}
  409. */
  410. Visualization.prototype.getUsedMetadataColumnList = function getUsedMetadataColumnList() {};
  411. Visualization.prototype.getSlots = function getSlots() {
  412. return this.slotsImpl.getAPI();
  413. };
  414. Visualization.prototype.getSavedPrompts = function getSavedPrompts() {
  415. return this.savedPromptsImpl.getAPI();
  416. };
  417. Visualization.prototype.getLocalFilters = function getLocalFilters() {
  418. return this.localFiltersImpl.getAPI();
  419. };
  420. Visualization.prototype.getSearchFilterList = function getSearchFilterList() {
  421. return this._getVisModelManager().searchFilters.toJSON();
  422. };
  423. // /**
  424. // * @description Returns the decorator object that can be used to decorate the data in the visualization.
  425. // * If the visualizatoin support multiple datasets and no view id is provided, then the decorator for the first dataset is returned
  426. // *
  427. // * @param {String} [viewId] Data view id. If not provided, the decorator for the first data view is returned.
  428. // *
  429. // * @return {DecoratorAPI} decorator object
  430. // *
  431. // */
  432. // getDecorator(/* dataViewId */) { }
  433. // /**
  434. // * @description Return a list of decorator object that can be used to decorate the data in the visualization.
  435. // * Each dataset will have its own decorator object.
  436. // *
  437. // *
  438. // * @return {DecoratorAPI[]} decorator object
  439. // *
  440. // */
  441. // getDecoratorList() {
  442. // if (!this.decorators) {
  443. // this.decorators = [];
  444. // const oldAPIs = this.widget.getDecoratorAPIs();
  445. // if (oldAPIs) {
  446. // oldAPIs.forEach(oldAPI => {
  447. // this.decorators.push(new Decorator(oldAPI).getAPI());
  448. // });
  449. // }
  450. // }
  451. // return this.decorators;
  452. // }
  453. /**
  454. * @description Returns true if the visualization references a column that is no longer available
  455. *
  456. * @returns {Boolean}
  457. */
  458. Visualization.prototype.hasUnavailableMetadataColumns = function hasUnavailableMetadataColumns() {
  459. var slotWithUnavailableColumns = this.getSlots().getSlotList().find(function (slot) {
  460. return slot.hasUnavailableMetadataColumns();
  461. });
  462. return !!slotWithUnavailableColumns;
  463. };
  464. Visualization.prototype._convertTransactionTokenToLegacyOptions = function _convertTransactionTokenToLegacyOptions(transactionToken) {
  465. var oldOptions = {};
  466. if (transactionToken) {
  467. oldOptions.payloadData = {
  468. transactionToken: transactionToken
  469. };
  470. if (transactionToken.transactionId) {
  471. oldOptions.payloadData.undoRedoTransactionId = transactionToken.transactionId;
  472. }
  473. }
  474. return oldOptions;
  475. };
  476. Visualization.prototype.isPreview = function isPreview() {
  477. return !!this._isPreview;
  478. };
  479. Visualization.prototype._getFilterSupport = function _getFilterSupport() {
  480. return this.legacyManagers.visFilterSupport;
  481. };
  482. Visualization.prototype._getVisModelManager = function _getVisModelManager() {
  483. return this.legacyManagers.visModelManager;
  484. };
  485. Visualization.prototype._getPropertySupport = function _getPropertySupport() {
  486. return this.legacyManagers.visPropertySupport;
  487. };
  488. Visualization.prototype.refreshSlotsCache = function refreshSlotsCache() {
  489. this.slotsImpl.invalidateCache();
  490. };
  491. return Visualization;
  492. }(VisualizationAPISpec);
  493. return Visualization;
  494. });
  495. //# sourceMappingURL=Visualization.js.map