123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821 |
- 'use strict';
- /**
- * Licensed Materials - Property of IBM
- * IBM Cognos Products: BI Cloud (C) Copyright IBM Corp. 2019, 2020
- * US Government Users Restricted Rights - Use, duplication or disclosure restricted by GSA ADP Schedule Contract with IBM Corp.
- */
- define(['jquery', 'underscore', '../VisView', 'text!./Kpi.html', 'text!./kpiSparklineSpec.json', '../../../util/DashboardFormatter', './KpiEventTarget', './KpiViewFactory', '../VisEventHandler', '../../../DynamicFileLoader', '../../../widgets/livewidget/nls/StringResources', '../../../util/TextScrambler', '../../../features/content/dataQueryExecution/QueryResults'], function ($, _, VisView, KpiTemplate, KPISparklineSpec, Formatter, KpiEventTarget, KpiViewFactory, VisEventHandler, DynamicFileLoader, StringResources, TextScrambler, QueryResults) {
- 'use strict';
- var QUERY_RESULT_ROW_INDEX = 0;
- var BASE_DATA_ITEM_INDEX = 0;
- var TARGET_DATA_ITEM_INDEX = 1;
- var KpiView = VisView.extend({
- BASE_SLOT_ID: 'actual',
- TARGET_SLOT_ID: 'goal',
- SPARKLINE_TIME_SLOT_ID: 'sparkline.time',
- SPARKLINE_ACTUAL_SLOT_ID: 'sparkline.actual',
- className: 'dataview kpi-widget',
- templateString: KpiTemplate,
- init: function init(options) {
- KpiView.inherited('init', this, arguments);
- this._baseValueView = null;
- this._targetValueView = null;
- this._sparkLineView = null;
- this._content = options.content;
- var isNewFeature = this._isNewConditionalFormatFeature();
- var condFeatureName = isNewFeature ? 'ConditionalFormatting' : 'conditionalFormatting';
- this._conditionalFormattingFeature = this._content.getFeature(condFeatureName);
- this._colorsService = this.dashboardApi.getFeature('Colors');
- this._visualizationAPI = this._content.getFeature('Visualization.internal');
- this._kpiViewFactory = options.kpiViewFactory || new KpiViewFactory();
- // deregister here since the new component do not have access to the dashboardAPI to check whether the feature flag is turned on or off
- // Instead when the new feature gets loaded it always register itself with the 'Properties' and 'CustomColor' feature
- // Remove this code when the new feature get turn on by default
- if (!isNewFeature) {
- var newCondFeature = this._content.getFeature('ConditionalFormatting');
- if (newCondFeature) {
- this._content.getFeature('Properties').deregisterProvider(newCondFeature);
- this.dashboardApi.getFeature('CustomColor').deregisterProvider(newCondFeature);
- }
- }
- },
- summaryReveal: function summaryReveal() {
- this.visModel.renderCompleteBeforeAnimation();
- if (!this._readyToRender()) {
- return Promise.resolve();
- }
- var $label = this.$el.find('.kpi-widget-base-value .labeled-value-label');
- var $value = this.$el.find('.kpi-widget-base-value .labeled-value-value');
- if ($label.length) {
- this.labelScrambler = new TextScrambler({
- el: $label[0]
- });
- this.labelScrambler.scramble();
- }
- if ($value.length) {
- this.valueScrambler = new TextScrambler({
- ignoreSet: ['-', ',', '.'],
- el: $value[0]
- });
- this.valueScrambler.scramble();
- }
- return Promise.resolve();
- },
- remove: function remove() {
- if (this.eventHandler) {
- this.eventHandler.remove();
- this.eventHandler = null;
- }
- this._removeViews();
- KpiView.inherited('remove', this, arguments);
- },
- /**
- * Loads and creates the control. Returns a promise which is resolved when the control
- * is created and ready to render
- */
- whenVisControlReady: function whenVisControlReady() {
- var _this = this;
- if (this.visControl) {
- return Promise.resolve(this.visControl);
- } else {
- return DynamicFileLoader.load(['dashboard-analytics/visualizations/renderer/kpi/control/KpiControl']).then(function (modules) {
- var VisControl = modules[0];
- _this.visControl = new VisControl({
- domNode: _this.$el.find('.kpi-widget-content')[0]
- });
- _this.eventHandler = new VisEventHandler({
- target: new KpiEventTarget({
- $el: _this.$el,
- visControl: _this.visControl,
- visAPI: _this.visModel,
- view: _this,
- visualization: _this.visualization
- }),
- transaction: _this.transactionApi,
- ownerWidget: _this.ownerWidget,
- visAPI: _this.visModel,
- edgeSelection: true
- });
- return _this.visControl;
- });
- }
- },
- _removeViews: function _removeViews() {
- if (this._baseValueView) {
- this._baseValueView.remove();
- this._baseValueView = null;
- }
- if (this._targetValueView) {
- this._targetValueView.remove();
- this._targetValueView = null;
- }
- this._removeSparkLine();
- },
- _initializeConditionalFormatting: function _initializeConditionalFormatting() {
- // This is temporary until features have a proper way of initializing themselves
- if (this._conditionalFormattingFeature) {
- return this._conditionalFormattingFeature.initializeFeature();
- } else {
- return Promise.resolve();
- }
- },
- render: function render(renderInfo) {
- var _this2 = this,
- _arguments = arguments;
- // This is temporary until features have a proper way of initializing themselves
- return this._initializeConditionalFormatting().then(function () {
- _this2._baseValue = null;
- _this2._targetValue = null;
- var baseSlot = _this2._getBaseSlot();
- var targetSlot = _this2._getTargetSlot();
- if (!_this2._readyToRender() || !baseSlot) {
- _this2.renderIconView();
- return Promise.resolve();
- }
- _this2.removeIconView();
- $(_this2.contentNode).css('text-align', _this2._getTextAlignment() || 'center');
- if (!_this2._baseValueNode) {
- _this2._baseValueNode = _this2.$el.find('.kpi-widget-base-value');
- _this2._targetValueNode = _this2.$el.find('.kpi-widget-target-value');
- _this2._sparkLineNode = _this2._getSparklineContainer();
- }
- var queryResultData = renderInfo.data.getResult();
- _this2._baseValue = _this2._getQueryResultValue(queryResultData, QUERY_RESULT_ROW_INDEX, BASE_DATA_ITEM_INDEX);
- _this2._targetValue = _this2._getQueryResultValue(queryResultData, QUERY_RESULT_ROW_INDEX, TARGET_DATA_ITEM_INDEX);
- var baseProperties = _this2._getBaseProperties();
- var baseFormattedValue = _this2._formatValue(baseSlot, _this2._baseValue);
- var baseDataItem = _this2._getDataItem(baseSlot);
- var baseLabel = baseDataItem.getLabel();
- var targetProperties = _this2._getTargetProperties();
- _this2._targetValueNode.addClass('hidden');
- _this2._targetValueNode.empty();
- var renderPromises = [];
- var targetSlotIsMapped = _this2._isSlotMapped(targetSlot);
- if (targetSlotIsMapped || (targetProperties.manualValue || targetProperties.manualValue === 0) && !isNaN(targetProperties.manualValue)) {
- var formatSlot = void 0,
- targetLabel = void 0;
- if (targetSlotIsMapped) {
- formatSlot = targetSlot;
- var targetDataItem = _this2._getDataItem(targetSlot);
- targetLabel = targetDataItem.getLabel();
- } else {
- //Manual Value
- formatSlot = baseSlot;
- targetLabel = StringResources.get('kpiDefaultTargetLabel');
- _this2._targetValue = Number(targetProperties.manualValue);
- }
- if (targetProperties.showValue || targetProperties.showDistance) {
- _this2._targetValueNode.removeClass('hidden');
- var targetString = _this2._getTargetValueString(targetProperties, formatSlot);
- renderPromises.push(_this2._renderLabeledValue(targetString, targetLabel, targetProperties, 'targetValue'));
- }
- }
- var conditionalFormatting = _this2._conditionalFormattingFeature ? _this2._conditionalFormattingFeature.getFormatting(_this2._baseValue, _this2._targetValue, baseDataItem.getColumnId()) : null;
- renderPromises.push(_this2._renderLabeledValue(baseFormattedValue, baseLabel, baseProperties, 'baseValue', conditionalFormatting));
- var sparklineQueryResultData = renderInfo.data.getResult('sparkline');
- var showSparkline = _this2._shouldDisplaySparkline(sparklineQueryResultData);
- _this2._sparkLineNode.toggleClass('hidden', !showSparkline);
- if (showSparkline) {
- renderPromises.push(_this2._renderSparkLine(renderInfo, conditionalFormatting, baseProperties));
- } else {
- _this2._removeSparkLine();
- }
- return Promise.all(renderPromises);
- }).then(function () {
- var baseProperties = _this2._getBaseProperties();
- if (baseProperties.labelSize === 'auto') {
- _this2._scaleSections(_this2._getResizeDefinition());
- }
- return KpiView.inherited('render', _this2, _arguments);
- });
- },
- _getQueryResultValue: function _getQueryResultValue(queryResultData, rowIndex, dataItemIndex) {
- var value = null;
- var rowCount = queryResultData.getRowCount();
- if (rowIndex < rowCount) {
- var dataPointCount = queryResultData.getDataPointValueList()[rowIndex].pt.length;
- if (dataItemIndex < dataPointCount) {
- value = queryResultData.getValue(rowIndex, dataItemIndex).value;
- }
- }
- return value;
- },
- _getTargetValueString: function _getTargetValueString(targetProperties, formatSlot) {
- var targetFormattedValue = this._formatValue(formatSlot, this._targetValue);
- var targetString = '';
- if (targetProperties.showDistance) {
- var formattedTargetDistance = this._getFormattedTargetDistanceString(formatSlot, this._baseValue, this._targetValue);
- if (targetProperties.showValue) {
- targetString = StringResources.get('kpiTargetWithDistance', {
- value: targetFormattedValue,
- distance: formattedTargetDistance
- });
- } else {
- targetString = formattedTargetDistance;
- }
- } else {
- targetString = targetFormattedValue;
- }
- return targetString;
- },
- _renderLabeledValue: function _renderLabeledValue(value, label, properties, sectionName, conditionalFormatting) {
- var viewName = '_' + sectionName + 'View';
- var nodeName = '_' + sectionName + 'Node';
- var valueStyle = '';
- if (properties.labelSize && properties.labelSize !== 'auto') {
- valueStyle = 'font-size:' + properties.labelSize + 'px;';
- }
- if (conditionalFormatting && conditionalFormatting.color) {
- valueStyle += 'color:' + conditionalFormatting.color + ';';
- } else if (properties.valueColor) {
- var hexColor = this._colorsService.getHexColorFromDashboardColorSet(properties.valueColor);
- if (hexColor !== 'transparent') {
- valueStyle += 'color:' + hexColor + ';';
- }
- }
- var finalLabel = properties.label || label;
- var view = this[viewName];
- if (!view) {
- view = this[viewName] = this._kpiViewFactory.createLabeledValueView({
- el: this[nodeName][0],
- dashboardApi: this.dashboardApi,
- value: value,
- valueStyle: valueStyle,
- label: finalLabel,
- showLabel: properties.showLabel,
- conditionalFormatting: conditionalFormatting
- });
- } else {
- view.setValue(value);
- view.setValueStyle(valueStyle);
- view.setLabel(finalLabel);
- view.setShowLabel(properties.showLabel);
- view.setConditionalFormatting(conditionalFormatting);
- }
- return view.render();
- },
- _readyToRender: function _readyToRender() {
- return this.isMappingComplete() && !this.hasMissingFilters() && !this.hasUnavailableMetadataColumns();
- },
- _getResizeDefinition: function _getResizeDefinition() {
- var sizingDefinition = {
- $node: this.$el,
- reservedSpace: 16, //Remove any padding between and around elements from size calculations.
- children: []
- };
- if (this._baseValueView) {
- sizingDefinition.children.push({
- $node: this._baseValueView.getValueNode(),
- referenceHeight: 40, //Observed reference height in chrome given the rendering at the default size.
- minimumHeight: 22.8, //19 - Commented number is the desired minimum font size. Increased due to the line-height -> font-size reduction.
- text: true
- });
- if (this._baseValueView.hasShape()) {
- sizingDefinition.children[0].icon = {
- $node: this._baseValueView.getValueNode().find('svg'),
- paddingDivisor: 4
- };
- }
- if (this._baseValueView.getShowLabel()) {
- sizingDefinition.reservedSpace += 8;
- sizingDefinition.children.push({
- $node: this._baseValueView.getLabelNode(),
- referenceHeight: 14,
- minimumHeight: 9.6, //8
- maximumHeight: 29, //24 - Commented number is the desired maximum font size. Increased due to the line-height -> font-size reduction.
- text: true
- });
- }
- if (this._targetValueNode && !this._targetValueNode.hasClass('hidden') && this._targetValueView) {
- sizingDefinition.reservedSpace += 16;
- sizingDefinition.children.push({
- $node: this._targetValueView.getValueNode(),
- referenceHeight: 19,
- minimumHeight: 12, //10
- maximumHeight: 39, //32
- text: true
- });
- if (this._targetValueView.getShowLabel()) {
- sizingDefinition.reservedSpace += 8;
- sizingDefinition.children.push({
- $node: this._targetValueView.getLabelNode(),
- referenceHeight: 14,
- minimumHeight: 9.6, //8
- maximumHeight: 29, //24
- text: true
- });
- }
- }
- if (this._sparkLineNode && !this._sparkLineNode.hasClass('hidden') && this._sparkLineView) {
- sizingDefinition.reservedSpace += 16;
- sizingDefinition.children.push({
- $node: this._sparkLineNode,
- referenceHeight: 32,
- minimumHeight: 16,
- text: false
- });
- }
- }
- return sizingDefinition;
- },
- _scaleSections: function _scaleSections(sizingDefinition) {
- if (!sizingDefinition.children || !sizingDefinition.children.length) {
- return; //There are no child items, so there is nothing to size.
- }
- var LINE_HEIGHT_TO_FONT_SIZE = 1.2; //The font-size does not cover the full size needed to display that font. Reduce the font below the line-height to prevent font overflow.
- var padding = 0;
- if (sizingDefinition.reservedSpace) {
- padding += sizingDefinition.reservedSpace;
- }
- sizingDefinition.$node.css('overflow', 'hidden');
- var existingHeight = sizingDefinition.$node.height() - padding;
- var referenceHeight = 0;
- sizingDefinition.children.forEach(function (child) {
- referenceHeight += child.referenceHeight;
- });
- function setSizes(definition, size) {
- var sizeCapped = false;
- if (definition.minimumHeight) {
- size = Math.max(Math.floor(size), definition.minimumHeight);
- }
- if (definition.maximumHeight) {
- size = Math.min(size, definition.maximumHeight);
- sizeCapped = size === definition.maximumHeight;
- }
- var height = size;
- definition.$node.css('height', height + 'px');
- var fontSize = size / LINE_HEIGHT_TO_FONT_SIZE;
- if (definition.text) {
- definition.$node.css({ 'font-size': fontSize + 'px', 'line-height': size + 'px', 'flex-basis': size + 'px' });
- }
- if (definition.icon) {
- var iconSize = fontSize / 2;
- var iconCss = {
- width: iconSize + 'px',
- height: iconSize + 'px'
- };
- if (definition.icon.paddingDivisor) {
- iconCss['padding-left'] = iconSize / definition.icon.paddingDivisor + 'px';
- }
- definition.icon.$node.css(iconCss);
- }
- return sizeCapped;
- }
- var someItemsCapped = false;
- var adjustedDefinition = {
- $node: sizingDefinition.$node,
- reservedSpace: sizingDefinition.reservedSpace,
- children: []
- };
- sizingDefinition.children.forEach(function (child) {
- var percentOfFullHeight = child.referenceHeight / referenceHeight;
- var childSize = percentOfFullHeight * existingHeight;
- var childSizeCapped = setSizes(child, childSize);
- if (child.text) {
- var boundingWidth = child.$node.width();
- var actualWidth = child.$node[0].scrollWidth;
- if (actualWidth > Math.round(boundingWidth)) {
- actualWidth += 8; //scrollWidth is rounded, plus reserve a couple pixels around the text to prevent some infrequent scrollbars, some of which can be caused by the selection chrome
- if (childSizeCapped) {
- childSize = child.maximumHeight;
- }
- childSize = childSize * boundingWidth / actualWidth;
- childSizeCapped = setSizes(child, childSize);
- }
- }
- someItemsCapped = someItemsCapped || childSizeCapped;
- if (!childSizeCapped) {
- adjustedDefinition.children.push(child);
- } else {
- adjustedDefinition.reservedSpace += child.maximumHeight;
- }
- });
- sizingDefinition.$node.css('overflow', '');
- if (someItemsCapped) {
- //Some items were capped. Resize the other items.
- this._scaleSections(adjustedDefinition);
- }
- },
- /**
- * Return text formatted value for field
- *
- * @param slot, slotAPI
- * @param v The raw fact value.
- * @returns text formatted data value
- */
- _formatValue: function _formatValue(slot, v) {
- var formatSpec = this._getFormatForSlot(slot);
- v = Formatter.format(v, formatSpec);
- return v;
- },
- _getFormatForSlot: function _getFormatForSlot(slot) {
- var dataItem = this._getDataItem(slot);
- var format = dataItem && dataItem.getFormat();
- return format || {};
- },
- _getFormattedTargetDistanceString: function _getFormattedTargetDistanceString(slot, baseValue, targetValue) {
- if (targetValue === 0) {
- return StringResources.get('kpiDistanceUndefined');
- }
- var targetDistance = (baseValue - targetValue) / Math.abs(targetValue);
- var formatSpec = {
- convertPercent: true,
- maximumFractionDigits: 2,
- minimumFractionDigits: 0,
- type: 'percent',
- locale: slot.locale
- };
- var distanceString = Formatter.format(targetDistance, formatSpec);
- if (targetDistance > 0) {
- distanceString = '+' + distanceString;
- }
- return distanceString;
- },
- _getBaseProperties: function _getBaseProperties() {
- return {
- labelSize: this._content.getPropertyValue('baseValueSize'),
- showLabel: this._content.getPropertyValue('showItemLabel') === false ? false : true,
- label: this._content.getPropertyValue('baseValueLabel'),
- valueColor: this._content.getPropertyValue('elementColor')
- };
- },
- _getTargetProperties: function _getTargetProperties() {
- return {
- labelSize: this._content.getPropertyValue('targetValueSize'),
- showLabel: this._content.getPropertyValue('showTargetLabel') === false ? false : true,
- showValue: this._content.getPropertyValue('showTargetValue') === false ? false : true,
- showDistance: this._content.getPropertyValue('showTargetDistance') === false ? false : true,
- label: this._content.getPropertyValue('targetValueLabel'),
- manualValue: this._content.getPropertyValue('targetValue')
- };
- },
- _getTimeProperties: function _getTimeProperties() {
- return {
- showSparkline: this._content.getPropertyValue('showSparkline') === false ? false : true
- };
- },
- _getTextAlignment: function _getTextAlignment() {
- return this._content.getPropertyValue('textAlignment');
- },
- _getBaseSlot: function _getBaseSlot() {
- return this._visualizationAPI.getSlots().getSlot(this.BASE_SLOT_ID);
- },
- _getTargetSlot: function _getTargetSlot() {
- return this._visualizationAPI.getSlots().getSlot(this.TARGET_SLOT_ID);
- },
- _getSparklineTimeSlot: function _getSparklineTimeSlot() {
- return this._visualizationAPI.getSlots().getSlot(this.SPARKLINE_TIME_SLOT_ID);
- },
- _getSparklineActualSlot: function _getSparklineActualSlot() {
- return this._visualizationAPI.getSlots().getSlot(this.SPARKLINE_ACTUAL_SLOT_ID);
- },
- _getDataItem: function _getDataItem(slot) {
- var dataItemIndex = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 0;
- return slot.getDataItemList()[dataItemIndex];
- },
- _isSlotMapped: function _isSlotMapped(slot) {
- var dataItems = slot && slot.getDataItemList() || [];
- return dataItems.length > 0;
- },
- animate: function animate() {
- if (this.resizing) {
- this.visModel.renderCompleteBeforeAnimation(); // Rendering is complete, no animation
- } else {
- KpiView.inherited('animate', this, arguments);
- }
- },
- resize: function resize() {
- // intentionally override VisView behavior.
- if (this.isMappingComplete()) {
- //TODO: Update which sections are shown based on size.
- var baseProperties = this._getBaseProperties();
- if (baseProperties.labelSize === 'auto') {
- this._scaleSections(this._getResizeDefinition());
- }
- } else {
- KpiView.inherited('resize', this, arguments);
- }
- },
- //[livewidget-cleanup] todo: this function is moved to KpiPropertyCallbacks
- onChangeValueSizeProperty: function onChangeValueSizeProperty(propertyName, propertyValue) {
- var props = {};
- if (propertyValue === 'auto') {
- props['baseValueSize'] = 'auto';
- props['targetValueSize'] = 'auto';
- } else {
- props['baseValueSize'] = this._content.getPropertyValue('baseValueSize');
- props['targetValueSize'] = this._content.getPropertyValue('targetValueSize');
- if (props['baseValueSize'] === 'auto') {
- props['baseValueSize'] = '32';
- props['targetValueSize'] = '16';
- }
- props[propertyName] = propertyValue;
- }
- var transactionId = _.uniqueId('kpi_font_size');
- for (var property in props) {
- this.ownerWidget.onPropertyUpdate({
- 'category': property,
- 'item': props[property],
- 'transactionId': transactionId
- });
- }
- },
- getDecoratorAPI: function getDecoratorAPI() {
- var indexedView = [this._baseValueView, this._targetValueView];
- return {
- decorateItem: function decorateItem(itemIndex) {
- if (indexedView[itemIndex]) {
- indexedView[itemIndex].setShowLabelTranslationIcon(true);
- }
- },
- decoratePoint: function decoratePoint() {
- return null;
- },
- decorate: function decorate() {
- return null;
- },
- clearItemDecoration: function clearItemDecoration() {
- indexedView.forEach(function (view) {
- if (view) {
- view.setShowLabelTranslationIcon(false);
- }
- });
- },
- updateDecorations: function updateDecorations() {
- indexedView.forEach(function (view) {
- if (view) {
- view.render();
- }
- });
- }
- };
- },
- getBaseValue: function getBaseValue() {
- return this._baseValue;
- },
- getTargetValue: function getTargetValue() {
- return this._targetValue;
- },
- _removeSparkLine: function _removeSparkLine() {
- if (this._sparkLineView) {
- this._sparkLineView.destroy();
- this._sparkLineView = null;
- }
- },
- _shouldDisplaySparkline: function _shouldDisplaySparkline(sparklineQueryResultData) {
- if (!this._isSlotMapped(this._getSparklineActualSlot())) {
- return false;
- }
- if (!this._isSlotMapped(this._getSparklineTimeSlot())) {
- return false;
- }
- if (!this._getTimeProperties().showSparkline) {
- return false;
- }
- if (!this._hasEnoughDataToRenderSparkline(sparklineQueryResultData)) {
- return false;
- }
- return true;
- },
- _hasEnoughDataToRenderSparkline: function _hasEnoughDataToRenderSparkline(sparklineQueryResultData) {
- if (!sparklineQueryResultData) {
- return false;
- }
- var dataPointValueList = sparklineQueryResultData.getDataPointValueList();
- var dataPointValueListLength = dataPointValueList.length;
- // Need at least 2 data point to draw the sparkline
- if (!dataPointValueList || dataPointValueListLength < 2) {
- this._addNotRenderingSparklineInfo();
- return false;
- }
- // Make sure we have at least 2 non NULL values
- var nonNullCount = 0;
- for (var i = 0; i < dataPointValueListLength; i++) {
- if (sparklineQueryResultData.getValue(i, 0).value !== null) {
- nonNullCount++;
- }
- if (nonNullCount > 1) {
- break;
- }
- }
- if (nonNullCount < 2) {
- this._addNotRenderingSparklineInfo();
- return false;
- }
- return true;
- },
- _addNotRenderingSparklineInfo: function _addNotRenderingSparklineInfo() {
- if (this.infoIndicator) {
- this.infoIndicator.addInfo([{
- id: 'data_notifications',
- label: StringResources.get('visualizationNotifications'),
- items: [{
- id: 'sparkLineInfoLabel',
- label: StringResources.get('kpiUnableDrawSparklineLabel'),
- isSubMessage: false
- }, {
- id: 'sparkLineInfo',
- label: StringResources.get('kpiUnableDrawSparklineInfo'),
- isSubMessage: true
- }]
- }]);
- }
- },
- _renderSparkLine: function _renderSparkLine(renderInfo, conditionalFormatting, baseProperties) {
- var sparkLineColor = '';
- if (conditionalFormatting && conditionalFormatting.color) {
- sparkLineColor = conditionalFormatting.color;
- } else if (baseProperties.valueColor) {
- var hexColor = this._colorsService.getHexColorFromDashboardColorSet(baseProperties.valueColor);
- if (hexColor !== 'transparent') {
- sparkLineColor = hexColor;
- }
- }
- if (this._sparkLineView) {
- if (renderInfo.refresh && renderInfo.refresh.data) {
- // Query data, or color has changed, need to recreate the sparkline
- this._removeSparkLine();
- } else if (this.resizing) {
- this._sparkLineView.resize();
- }
- }
- var sparklineColorChanged = sparkLineColor !== this._cachedSparkLineColor;
- this._updateCachedSparkLineColor(sparkLineColor);
- if (!this._sparkLineView) {
- var sparklineQueryResults = new QueryResults();
- sparklineQueryResults.addResult(renderInfo.data.getResult('sparkline'));
- this._sparkLineView = this._createSparkLine(sparklineQueryResults.getAPI());
- this._sparkLineView.render();
- } else if (sparklineColorChanged) {
- //If we already have a sparkline and there was a color change. Update the color property of the sparkline.
- this._sparkLineView.widget.updateVisProperties(this._getSparklineColorProperty());
- }
- return Promise.resolve();
- },
- _getSparklineContainer: function _getSparklineContainer() {
- return this.$el.find('.kpi-widget-sparkline');
- },
- _addSlotDef: function _addSlotDef(spec, slotName, slot) {
- var slotDef = {
- 'name': slotName,
- 'dataItems': []
- };
- slot.getDataItemList().forEach(function (dataItem) {
- var dataItemDef = {
- id: dataItem.getId(),
- itemId: dataItem.getColumnId()
- };
- if (dataItem.getSort()) {
- dataItemDef.selection = [{
- operation: 'order',
- sort: dataItem.getSort()
- }];
- }
- spec.data.dataViews[0].dataItems.push(dataItemDef);
- slotDef.dataItems.push(dataItem.getId());
- });
- spec.slotmapping.slots.push(slotDef);
- },
- _getSparklineColorProperty: function _getSparklineColorProperty() {
- return {
- id: 'colors.series',
- value: this._cachedSparkLineColor
- };
- },
- _updateCachedSparkLineColor: function _updateCachedSparkLineColor(color) {
- this._cachedSparkLineColor = color;
- var container = this._getSparklineContainer();
- if (this._cachedSparkLineColor) {
- container.removeClass('defaultColors');
- } else {
- container.addClass('defaultColors'); //When no explicit color is set, use CSS to override the line color to match the default value color.
- }
- },
- _buildSparklineSpec: function _buildSparklineSpec() {
- var spec = JSON.parse(KPISparklineSpec);
- if (this._cachedSparkLineColor) {
- spec.properties.push(this._getSparklineColorProperty());
- }
- spec.data = {
- 'dataViews': [{
- modelRef: this._visualizationAPI.getDataSource().getId(),
- dataItems: []
- }]
- };
- spec.slotmapping.slots = [];
- this._addSlotDef(spec, 'categories', this._getSparklineTimeSlot());
- this._addSlotDef(spec, 'values', this._getSparklineActualSlot());
- var localFilters = this._visualizationAPI.getLocalFilters();
- spec.localFilters = localFilters.getFilterList();
- return spec;
- },
- _createSparkLine: function _createSparkLine(queryResults) {
- var spec = this._buildSparklineSpec();
- var container = this._getSparklineContainer();
- var options = {
- enableHover: true,
- enableClick: false,
- enablePanAndZoom: false,
- tabNavigation: false,
- runtimeEnv: {
- dashboardApi: this.dashboardApi
- },
- node: container[0],
- spec: spec,
- queryResults: queryResults,
- managesOwnQueries: true
- };
- return this._kpiViewFactory.createSparklineView(options);
- },
- _isNewConditionalFormatFeature: function _isNewConditionalFormatFeature() {
- return !this.dashboardApi.getGlassCoreSvc('.FeatureChecker').checkValue('dashboard', 'condFormat', 'disabled');
- }
- });
- return KpiView;
- });
- //# sourceMappingURL=KpiView.js.map
|