UNPKG

@gitlab/ui

Version:
334 lines (299 loc) • 10 kB
import merge from 'lodash/merge'; import truncate from 'lodash/truncate'; import Chart from '../chart/chart'; import ChartTooltip from '../tooltip/tooltip'; import TooltipDefaultFormat from '../../shared_components/charts/tooltip_default_format'; import { dataZoomAdjustments, mergeSeriesToOptions, grid } from '../../../utils/charts/config'; import ToolboxMixin from '../../mixins/toolbox_mixin'; import { engineeringNotation } from '../../../utils/number_utils'; import { colorFromDefaultPalette } from '../../../utils/charts/theme'; import { debounceByAnimationFrame, hexToRgba } from '../../../utils/utils'; import { TOOLTIP_LEFT_OFFSET } from '../../../utils/charts/constants'; import __vue_normalize__ from 'vue-runtime-helpers/dist/normalize-component.js'; function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); } function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } function _iterableToArrayLimit(arr, i) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); } function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; return arr2; } function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } /** * `nameGap` in charts/config is set to 50 but it is not * used for bar charts as the axes are flipped. That is why * we're explicitly setting it here */ var DEFAULT_NAME_GAP = 50; /** * This is the magic number at which the y-axis name * and y-axis labels don't overlap * @Number */ var AXIS_LABEL_LENGTH = 7; /** * Because the axes are reversed in bar charts defaultChartOptions * xAxis and yAxis needs to be handled specifically. */ var defaultOptions = { grid: grid, xAxis: { nameLocation: 'center', axisLabel: { formatter: function formatter(num) { return engineeringNotation(num, 2); } } }, yAxis: { nameGap: DEFAULT_NAME_GAP, boundaryGap: true, nameLocation: 'center', splitLine: { show: false }, axisLabel: { interval: 0, formatter: function formatter(str) { return truncate(str, { length: AXIS_LABEL_LENGTH, separator: '...' }); } } } }; var script = { components: { Chart: Chart, ChartTooltip: ChartTooltip, TooltipDefaultFormat: TooltipDefaultFormat }, mixins: [ToolboxMixin], inheritAttrs: false, props: { data: { type: Object, required: true }, option: { type: Object, required: false, default: function _default() { return {}; } }, yAxisTitle: { type: String, required: true }, xAxisTitle: { type: String, required: true }, xAxisType: { type: String, required: false, default: 'value' } }, data: function data() { return { chart: null, showTooltip: false, tooltipTitle: '', tooltipContent: {}, tooltipPosition: { left: '0', top: '0' }, debouncedMoveShowTooltip: debounceByAnimationFrame(this.moveShowTooltip) }; }, computed: { series: function series() { var _this = this; return Object.keys(this.data).map(function (key, index) { var barColor = colorFromDefaultPalette(index); return { name: key, data: _this.data[key], type: 'bar', stack: 'chart', itemStyle: { color: hexToRgba(barColor, 0.2), barBorderColor: barColor, barBorderWidth: 1 }, emphasis: { itemStyle: { color: hexToRgba(barColor, 0.4) } }, barMaxWidth: '50%' }; }); }, options: function options() { var mergedOptions = merge({}, defaultOptions, { xAxis: { axisLine: { show: false }, name: this.xAxisTitle, type: this.xAxisType }, yAxis: { name: this.yAxisTitle, type: 'category', axisTick: { show: true }, axisPointer: { show: true, type: 'none', label: { formatter: this.onLabelChange } } }, legend: { show: false } }, this.option, dataZoomAdjustments(this.option.dataZoom), this.toolboxAdjustments); // All chart options can be merged but series // needs to be handled specially return mergeSeriesToOptions(mergedOptions, this.series); } }, beforeDestroy: function beforeDestroy() { if (this.chart) { this.chart.getDom().removeEventListener('mousemove', this.debouncedMoveShowTooltip); this.chart.getDom().removeEventListener('mouseout', this.debouncedMoveShowTooltip); } }, methods: { moveShowTooltip: function moveShowTooltip(mouseEvent) { this.tooltipPosition = { left: "".concat(mouseEvent.zrX + TOOLTIP_LEFT_OFFSET, "px"), top: "".concat(mouseEvent.zrY, "px") }; this.showTooltip = this.chart.containPixel('grid', [mouseEvent.zrX, mouseEvent.zrY]); }, onCreated: function onCreated(chart) { this.chart = chart; this.$emit('created', chart); chart.getDom().addEventListener('mousemove', this.debouncedMoveShowTooltip); chart.getDom().addEventListener('mouseout', this.debouncedMoveShowTooltip); }, onLabelChange: function onLabelChange(params) { var _this$getDefaultToolt = this.getDefaultTooltipContent(params, this.xAxisTitle), yLabels = _this$getDefaultToolt.yLabels, tooltipContent = _this$getDefaultToolt.tooltipContent; this.$set(this, 'tooltipContent', tooltipContent); this.tooltipTitle = yLabels.join(', '); }, /** * The existing getDefaultTooltipContent in utils works against the y-axis value. * However, for bar charts, the tooltip should be against x-axis values. * This method will be removed after https://gitlab.com/gitlab-org/gitlab-ui/-/issues/674 * * @param {Object} params series data * @param {String} xAxisTitle x-axis title * @returns {Object} tooltip title and content */ getDefaultTooltipContent: function getDefaultTooltipContent(params) { var xAxisTitle = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var seriesDataLength = params.seriesData.length; var _params$seriesData$re = params.seriesData.reduce(function (acc, chartItem) { var _ref = chartItem.value || [], _ref2 = _slicedToArray(_ref, 2), value = _ref2[0], title = _ref2[1]; // The x axis title is used instead of y axis var seriesName = seriesDataLength === 1 && xAxisTitle ? xAxisTitle : chartItem.seriesName; var color = seriesDataLength === 1 ? '' : chartItem.color; acc.tooltipContent[seriesName] = { value: value, color: color }; if (!acc.yLabels.includes(title)) { acc.yLabels.push(title); } return acc; }, { yLabels: [], tooltipContent: {} }), yLabels = _params$seriesData$re.yLabels, tooltipContent = _params$seriesData$re.tooltipContent; return { yLabels: yLabels, tooltipContent: tooltipContent }; } } }; /* script */ const __vue_script__ = script; /* template */ var __vue_render__ = function () {var _vm=this;var _h=_vm.$createElement;var _c=_vm._self._c||_h;return _c('div',{staticClass:"position-relative"},[_c('chart',_vm._g(_vm._b({attrs:{"options":_vm.options},on:{"created":_vm.onCreated}},'chart',_vm.$attrs,false),_vm.$listeners)),_vm._v(" "),(_vm.chart)?_c('chart-tooltip',{attrs:{"show":_vm.showTooltip,"chart":_vm.chart,"top":_vm.tooltipPosition.top,"left":_vm.tooltipPosition.left}},[_c('div',{attrs:{"slot":"title"},slot:"title"},[_vm._v(_vm._s(_vm.tooltipTitle)+" ("+_vm._s(_vm.yAxisTitle)+")")]),_vm._v(" "),_c('tooltip-default-format',{attrs:{"tooltip-content":_vm.tooltipContent}})],1):_vm._e()],1)}; var __vue_staticRenderFns__ = []; /* style */ const __vue_inject_styles__ = undefined; /* scoped */ const __vue_scope_id__ = undefined; /* module identifier */ const __vue_module_identifier__ = undefined; /* functional template */ const __vue_is_functional_template__ = false; /* style inject */ /* style inject SSR */ /* style inject shadow dom */ const __vue_component__ = __vue_normalize__( { render: __vue_render__, staticRenderFns: __vue_staticRenderFns__ }, __vue_inject_styles__, __vue_script__, __vue_scope_id__, __vue_is_functional_template__, __vue_module_identifier__, false, undefined, undefined, undefined ); export default __vue_component__;